model.js 188 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const Dottie = require('dottie');
  5. const Utils = require('./utils');
  6. const { logger } = require('./utils/logger');
  7. const BelongsTo = require('./associations/belongs-to');
  8. const BelongsToMany = require('./associations/belongs-to-many');
  9. const InstanceValidator = require('./instance-validator');
  10. const QueryTypes = require('./query-types');
  11. const sequelizeErrors = require('./errors');
  12. const Association = require('./associations/base');
  13. const HasMany = require('./associations/has-many');
  14. const DataTypes = require('./data-types');
  15. const Hooks = require('./hooks');
  16. const associationsMixin = require('./associations/mixin');
  17. const Op = require('./operators');
  18. const { noDoubleNestedGroup } = require('./utils/deprecations');
  19. // This list will quickly become dated, but failing to maintain this list just means
  20. // we won't throw a warning when we should. At least most common cases will forever be covered
  21. // so we stop throwing erroneous warnings when we shouldn't.
  22. const validQueryKeywords = new Set(['where', 'attributes', 'paranoid', 'include', 'order', 'limit', 'offset',
  23. 'transaction', 'lock', 'raw', 'logging', 'benchmark', 'having', 'searchPath', 'rejectOnEmpty', 'plain',
  24. 'scope', 'group', 'through', 'defaults', 'distinct', 'primary', 'exception', 'type', 'hooks', 'force',
  25. 'name']);
  26. // List of attributes that should not be implicitly passed into subqueries/includes.
  27. const nonCascadingOptions = ['include', 'attributes', 'originalAttributes', 'order', 'where', 'limit', 'offset', 'plain', 'group', 'having'];
  28. /**
  29. * A Model represents a table in the database. Instances of this class represent a database row.
  30. *
  31. * Model instances operate with the concept of a `dataValues` property, which stores the actual values represented by the instance.
  32. * By default, the values from dataValues can also be accessed directly from the Instance, that is:
  33. * ```js
  34. * instance.field
  35. * // is the same as
  36. * instance.get('field')
  37. * // is the same as
  38. * instance.getDataValue('field')
  39. * ```
  40. * However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the value from `dataValues`.
  41. * Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters.
  42. *
  43. * @see
  44. * {@link Sequelize#define} for more information about getters and setters
  45. * @mixes Hooks
  46. */
  47. class Model {
  48. static get queryInterface() {
  49. return this.sequelize.getQueryInterface();
  50. }
  51. static get queryGenerator() {
  52. return this.queryInterface.queryGenerator;
  53. }
  54. /**
  55. * A reference to the sequelize instance
  56. *
  57. * @see
  58. * {@link Sequelize}
  59. *
  60. * @property sequelize
  61. *
  62. * @returns {Sequelize}
  63. */
  64. get sequelize() {
  65. return this.constructor.sequelize;
  66. }
  67. /**
  68. * Builds a new model instance.
  69. *
  70. * @param {object} [values={}] an object of key value pairs
  71. * @param {object} [options] instance construction options
  72. * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
  73. * @param {boolean} [options.isNewRecord=true] Is this a new record
  74. * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
  75. */
  76. constructor(values = {}, options = {}) {
  77. options = {
  78. isNewRecord: true,
  79. _schema: this.constructor._schema,
  80. _schemaDelimiter: this.constructor._schemaDelimiter,
  81. ...options
  82. };
  83. if (options.attributes) {
  84. options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute);
  85. }
  86. if (!options.includeValidated) {
  87. this.constructor._conformIncludes(options, this.constructor);
  88. if (options.include) {
  89. this.constructor._expandIncludeAll(options);
  90. this.constructor._validateIncludedElements(options);
  91. }
  92. }
  93. this.dataValues = {};
  94. this._previousDataValues = {};
  95. this._changed = new Set();
  96. this._options = options || {};
  97. /**
  98. * Returns true if this instance has not yet been persisted to the database
  99. *
  100. * @property isNewRecord
  101. * @returns {boolean}
  102. */
  103. this.isNewRecord = options.isNewRecord;
  104. this._initValues(values, options);
  105. }
  106. _initValues(values, options) {
  107. let defaults;
  108. let key;
  109. values = { ...values };
  110. if (options.isNewRecord) {
  111. defaults = {};
  112. if (this.constructor._hasDefaultValues) {
  113. defaults = _.mapValues(this.constructor._defaultValues, valueFn => {
  114. const value = valueFn();
  115. return value && value instanceof Utils.SequelizeMethod ? value : _.cloneDeep(value);
  116. });
  117. }
  118. // set id to null if not passed as value, a newly created dao has no id
  119. // removing this breaks bulkCreate
  120. // do after default values since it might have UUID as a default value
  121. if (this.constructor.primaryKeyAttributes.length) {
  122. this.constructor.primaryKeyAttributes.forEach(primaryKeyAttribute => {
  123. if (!Object.prototype.hasOwnProperty.call(defaults, primaryKeyAttribute)) {
  124. defaults[primaryKeyAttribute] = null;
  125. }
  126. });
  127. }
  128. if (this.constructor._timestampAttributes.createdAt && defaults[this.constructor._timestampAttributes.createdAt]) {
  129. this.dataValues[this.constructor._timestampAttributes.createdAt] = Utils.toDefaultValue(defaults[this.constructor._timestampAttributes.createdAt], this.sequelize.options.dialect);
  130. delete defaults[this.constructor._timestampAttributes.createdAt];
  131. }
  132. if (this.constructor._timestampAttributes.updatedAt && defaults[this.constructor._timestampAttributes.updatedAt]) {
  133. this.dataValues[this.constructor._timestampAttributes.updatedAt] = Utils.toDefaultValue(defaults[this.constructor._timestampAttributes.updatedAt], this.sequelize.options.dialect);
  134. delete defaults[this.constructor._timestampAttributes.updatedAt];
  135. }
  136. if (this.constructor._timestampAttributes.deletedAt && defaults[this.constructor._timestampAttributes.deletedAt]) {
  137. this.dataValues[this.constructor._timestampAttributes.deletedAt] = Utils.toDefaultValue(defaults[this.constructor._timestampAttributes.deletedAt], this.sequelize.options.dialect);
  138. delete defaults[this.constructor._timestampAttributes.deletedAt];
  139. }
  140. for (key in defaults) {
  141. if (values[key] === undefined) {
  142. this.set(key, Utils.toDefaultValue(defaults[key], this.sequelize.options.dialect), { raw: true });
  143. delete values[key];
  144. }
  145. }
  146. }
  147. this.set(values, options);
  148. }
  149. // validateIncludedElements should have been called before this method
  150. static _paranoidClause(model, options = {}) {
  151. // Apply on each include
  152. // This should be handled before handling where conditions because of logic with returns
  153. // otherwise this code will never run on includes of a already conditionable where
  154. if (options.include) {
  155. for (const include of options.include) {
  156. this._paranoidClause(include.model, include);
  157. }
  158. }
  159. // apply paranoid when groupedLimit is used
  160. if (_.get(options, 'groupedLimit.on.options.paranoid')) {
  161. const throughModel = _.get(options, 'groupedLimit.on.through.model');
  162. if (throughModel) {
  163. options.groupedLimit.through = this._paranoidClause(throughModel, options.groupedLimit.through);
  164. }
  165. }
  166. if (!model.options.timestamps || !model.options.paranoid || options.paranoid === false) {
  167. // This model is not paranoid, nothing to do here;
  168. return options;
  169. }
  170. const deletedAtCol = model._timestampAttributes.deletedAt;
  171. const deletedAtAttribute = model.rawAttributes[deletedAtCol];
  172. const deletedAtObject = {};
  173. let deletedAtDefaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null;
  174. deletedAtDefaultValue = deletedAtDefaultValue || {
  175. [Op.eq]: null
  176. };
  177. deletedAtObject[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
  178. if (Utils.isWhereEmpty(options.where)) {
  179. options.where = deletedAtObject;
  180. } else {
  181. options.where = { [Op.and]: [deletedAtObject, options.where] };
  182. }
  183. return options;
  184. }
  185. static _addDefaultAttributes() {
  186. const tail = {};
  187. let head = {};
  188. // Add id if no primary key was manually added to definition
  189. // Can't use this.primaryKeys here, since this function is called before PKs are identified
  190. if (!_.some(this.rawAttributes, 'primaryKey')) {
  191. if ('id' in this.rawAttributes) {
  192. // Something is fishy here!
  193. throw new Error(`A column called 'id' was added to the attributes of '${this.tableName}' but not marked with 'primaryKey: true'`);
  194. }
  195. head = {
  196. id: {
  197. type: new DataTypes.INTEGER(),
  198. allowNull: false,
  199. primaryKey: true,
  200. autoIncrement: true,
  201. _autoGenerated: true
  202. }
  203. };
  204. }
  205. if (this._timestampAttributes.createdAt) {
  206. tail[this._timestampAttributes.createdAt] = {
  207. type: DataTypes.DATE,
  208. allowNull: false,
  209. _autoGenerated: true
  210. };
  211. }
  212. if (this._timestampAttributes.updatedAt) {
  213. tail[this._timestampAttributes.updatedAt] = {
  214. type: DataTypes.DATE,
  215. allowNull: false,
  216. _autoGenerated: true
  217. };
  218. }
  219. if (this._timestampAttributes.deletedAt) {
  220. tail[this._timestampAttributes.deletedAt] = {
  221. type: DataTypes.DATE,
  222. _autoGenerated: true
  223. };
  224. }
  225. if (this._versionAttribute) {
  226. tail[this._versionAttribute] = {
  227. type: DataTypes.INTEGER,
  228. allowNull: false,
  229. defaultValue: 0,
  230. _autoGenerated: true
  231. };
  232. }
  233. const newRawAttributes = {
  234. ...head,
  235. ...this.rawAttributes
  236. };
  237. _.each(tail, (value, attr) => {
  238. if (newRawAttributes[attr] === undefined) {
  239. newRawAttributes[attr] = value;
  240. }
  241. });
  242. this.rawAttributes = newRawAttributes;
  243. if (!Object.keys(this.primaryKeys).length) {
  244. this.primaryKeys.id = this.rawAttributes.id;
  245. }
  246. }
  247. static _findAutoIncrementAttribute() {
  248. this.autoIncrementAttribute = null;
  249. for (const name in this.rawAttributes) {
  250. if (Object.prototype.hasOwnProperty.call(this.rawAttributes, name)) {
  251. const definition = this.rawAttributes[name];
  252. if (definition && definition.autoIncrement) {
  253. if (this.autoIncrementAttribute) {
  254. throw new Error('Invalid Instance definition. Only one autoincrement field allowed.');
  255. }
  256. this.autoIncrementAttribute = name;
  257. }
  258. }
  259. }
  260. }
  261. static _conformIncludes(options, self) {
  262. if (!options.include) return;
  263. // if include is not an array, wrap in an array
  264. if (!Array.isArray(options.include)) {
  265. options.include = [options.include];
  266. } else if (!options.include.length) {
  267. delete options.include;
  268. return;
  269. }
  270. // convert all included elements to { model: Model } form
  271. options.include = options.include.map(include => this._conformInclude(include, self));
  272. }
  273. static _transformStringAssociation(include, self) {
  274. if (self && typeof include === 'string') {
  275. if (!Object.prototype.hasOwnProperty.call(self.associations, include)) {
  276. throw new Error(`Association with alias "${include}" does not exist on ${self.name}`);
  277. }
  278. return self.associations[include];
  279. }
  280. return include;
  281. }
  282. static _conformInclude(include, self) {
  283. if (include) {
  284. let model;
  285. if (include._pseudo) return include;
  286. include = this._transformStringAssociation(include, self);
  287. if (include instanceof Association) {
  288. if (self && include.target.name === self.name) {
  289. model = include.source;
  290. } else {
  291. model = include.target;
  292. }
  293. return { model, association: include, as: include.as };
  294. }
  295. if (include.prototype && include.prototype instanceof Model) {
  296. return { model: include };
  297. }
  298. if (_.isPlainObject(include)) {
  299. if (include.association) {
  300. include.association = this._transformStringAssociation(include.association, self);
  301. if (self && include.association.target.name === self.name) {
  302. model = include.association.source;
  303. } else {
  304. model = include.association.target;
  305. }
  306. if (!include.model) include.model = model;
  307. if (!include.as) include.as = include.association.as;
  308. this._conformIncludes(include, model);
  309. return include;
  310. }
  311. if (include.model) {
  312. this._conformIncludes(include, include.model);
  313. return include;
  314. }
  315. if (include.all) {
  316. this._conformIncludes(include);
  317. return include;
  318. }
  319. }
  320. }
  321. throw new Error('Include unexpected. Element has to be either a Model, an Association or an object.');
  322. }
  323. static _expandIncludeAllElement(includes, include) {
  324. // check 'all' attribute provided is valid
  325. let all = include.all;
  326. delete include.all;
  327. if (all !== true) {
  328. if (!Array.isArray(all)) {
  329. all = [all];
  330. }
  331. const validTypes = {
  332. BelongsTo: true,
  333. HasOne: true,
  334. HasMany: true,
  335. One: ['BelongsTo', 'HasOne'],
  336. Has: ['HasOne', 'HasMany'],
  337. Many: ['HasMany']
  338. };
  339. for (let i = 0; i < all.length; i++) {
  340. const type = all[i];
  341. if (type === 'All') {
  342. all = true;
  343. break;
  344. }
  345. const types = validTypes[type];
  346. if (!types) {
  347. throw new sequelizeErrors.EagerLoadingError(`include all '${type}' is not valid - must be BelongsTo, HasOne, HasMany, One, Has, Many or All`);
  348. }
  349. if (types !== true) {
  350. // replace type placeholder e.g. 'One' with its constituent types e.g. 'HasOne', 'BelongsTo'
  351. all.splice(i, 1);
  352. i--;
  353. for (let j = 0; j < types.length; j++) {
  354. if (!all.includes(types[j])) {
  355. all.unshift(types[j]);
  356. i++;
  357. }
  358. }
  359. }
  360. }
  361. }
  362. // add all associations of types specified to includes
  363. const nested = include.nested;
  364. if (nested) {
  365. delete include.nested;
  366. if (!include.include) {
  367. include.include = [];
  368. } else if (!Array.isArray(include.include)) {
  369. include.include = [include.include];
  370. }
  371. }
  372. const used = [];
  373. (function addAllIncludes(parent, includes) {
  374. _.forEach(parent.associations, association => {
  375. if (all !== true && !all.includes(association.associationType)) {
  376. return;
  377. }
  378. // check if model already included, and skip if so
  379. const model = association.target;
  380. const as = association.options.as;
  381. const predicate = { model };
  382. if (as) {
  383. // We only add 'as' to the predicate if it actually exists
  384. predicate.as = as;
  385. }
  386. if (_.some(includes, predicate)) {
  387. return;
  388. }
  389. // skip if recursing over a model already nested
  390. if (nested && used.includes(model)) {
  391. return;
  392. }
  393. used.push(parent);
  394. // include this model
  395. const thisInclude = Utils.cloneDeep(include);
  396. thisInclude.model = model;
  397. if (as) {
  398. thisInclude.as = as;
  399. }
  400. includes.push(thisInclude);
  401. // run recursively if nested
  402. if (nested) {
  403. addAllIncludes(model, thisInclude.include);
  404. if (thisInclude.include.length === 0) delete thisInclude.include;
  405. }
  406. });
  407. used.pop();
  408. })(this, includes);
  409. }
  410. static _validateIncludedElements(options, tableNames) {
  411. if (!options.model) options.model = this;
  412. tableNames = tableNames || {};
  413. options.includeNames = [];
  414. options.includeMap = {};
  415. /* Legacy */
  416. options.hasSingleAssociation = false;
  417. options.hasMultiAssociation = false;
  418. if (!options.parent) {
  419. options.topModel = options.model;
  420. options.topLimit = options.limit;
  421. }
  422. options.include = options.include.map(include => {
  423. include = this._conformInclude(include);
  424. include.parent = options;
  425. include.topLimit = options.topLimit;
  426. this._validateIncludedElement.call(options.model, include, tableNames, options);
  427. if (include.duplicating === undefined) {
  428. include.duplicating = include.association.isMultiAssociation;
  429. }
  430. include.hasDuplicating = include.hasDuplicating || include.duplicating;
  431. include.hasRequired = include.hasRequired || include.required;
  432. options.hasDuplicating = options.hasDuplicating || include.hasDuplicating;
  433. options.hasRequired = options.hasRequired || include.required;
  434. options.hasWhere = options.hasWhere || include.hasWhere || !!include.where;
  435. return include;
  436. });
  437. for (const include of options.include) {
  438. include.hasParentWhere = options.hasParentWhere || !!options.where;
  439. include.hasParentRequired = options.hasParentRequired || !!options.required;
  440. if (include.subQuery !== false && options.hasDuplicating && options.topLimit) {
  441. if (include.duplicating) {
  442. include.subQuery = false;
  443. include.subQueryFilter = include.hasRequired;
  444. } else {
  445. include.subQuery = include.hasRequired;
  446. include.subQueryFilter = false;
  447. }
  448. } else {
  449. include.subQuery = include.subQuery || false;
  450. if (include.duplicating) {
  451. include.subQueryFilter = include.subQuery;
  452. include.subQuery = false;
  453. } else {
  454. include.subQueryFilter = false;
  455. include.subQuery = include.subQuery || include.hasParentRequired && include.hasRequired && !include.separate;
  456. }
  457. }
  458. options.includeMap[include.as] = include;
  459. options.includeNames.push(include.as);
  460. // Set top level options
  461. if (options.topModel === options.model && options.subQuery === undefined && options.topLimit) {
  462. if (include.subQuery) {
  463. options.subQuery = include.subQuery;
  464. } else if (include.hasDuplicating) {
  465. options.subQuery = true;
  466. }
  467. }
  468. /* Legacy */
  469. options.hasIncludeWhere = options.hasIncludeWhere || include.hasIncludeWhere || !!include.where;
  470. options.hasIncludeRequired = options.hasIncludeRequired || include.hasIncludeRequired || !!include.required;
  471. if (include.association.isMultiAssociation || include.hasMultiAssociation) {
  472. options.hasMultiAssociation = true;
  473. }
  474. if (include.association.isSingleAssociation || include.hasSingleAssociation) {
  475. options.hasSingleAssociation = true;
  476. }
  477. }
  478. if (options.topModel === options.model && options.subQuery === undefined) {
  479. options.subQuery = false;
  480. }
  481. return options;
  482. }
  483. static _validateIncludedElement(include, tableNames, options) {
  484. tableNames[include.model.getTableName()] = true;
  485. if (include.attributes && !options.raw) {
  486. include.model._expandAttributes(include);
  487. include.originalAttributes = include.model._injectDependentVirtualAttributes(include.attributes);
  488. include = Utils.mapFinderOptions(include, include.model);
  489. if (include.attributes.length) {
  490. _.each(include.model.primaryKeys, (attr, key) => {
  491. // Include the primary key if it's not already included - take into account that the pk might be aliased (due to a .field prop)
  492. if (!include.attributes.some(includeAttr => {
  493. if (attr.field !== key) {
  494. return Array.isArray(includeAttr) && includeAttr[0] === attr.field && includeAttr[1] === key;
  495. }
  496. return includeAttr === key;
  497. })) {
  498. include.attributes.unshift(key);
  499. }
  500. });
  501. }
  502. } else {
  503. include = Utils.mapFinderOptions(include, include.model);
  504. }
  505. // pseudo include just needed the attribute logic, return
  506. if (include._pseudo) {
  507. if (!include.attributes) {
  508. include.attributes = Object.keys(include.model.tableAttributes);
  509. }
  510. return Utils.mapFinderOptions(include, include.model);
  511. }
  512. // check if the current Model is actually associated with the passed Model - or it's a pseudo include
  513. const association = include.association || this._getIncludedAssociation(include.model, include.as);
  514. include.association = association;
  515. include.as = association.as;
  516. // If through, we create a pseudo child include, to ease our parsing later on
  517. if (include.association.through && Object(include.association.through.model) === include.association.through.model) {
  518. if (!include.include) include.include = [];
  519. const through = include.association.through;
  520. include.through = _.defaults(include.through || {}, {
  521. model: through.model,
  522. as: through.model.name,
  523. association: {
  524. isSingleAssociation: true
  525. },
  526. _pseudo: true,
  527. parent: include
  528. });
  529. if (through.scope) {
  530. include.through.where = include.through.where ? { [Op.and]: [include.through.where, through.scope] } : through.scope;
  531. }
  532. include.include.push(include.through);
  533. tableNames[through.tableName] = true;
  534. }
  535. // include.model may be the main model, while the association target may be scoped - thus we need to look at association.target/source
  536. let model;
  537. if (include.model.scoped === true) {
  538. // If the passed model is already scoped, keep that
  539. model = include.model;
  540. } else {
  541. // Otherwise use the model that was originally passed to the association
  542. model = include.association.target.name === include.model.name ? include.association.target : include.association.source;
  543. }
  544. model._injectScope(include);
  545. // This check should happen after injecting the scope, since the scope may contain a .attributes
  546. if (!include.attributes) {
  547. include.attributes = Object.keys(include.model.tableAttributes);
  548. }
  549. include = Utils.mapFinderOptions(include, include.model);
  550. if (include.required === undefined) {
  551. include.required = !!include.where;
  552. }
  553. if (include.association.scope) {
  554. include.where = include.where ? { [Op.and]: [include.where, include.association.scope] } : include.association.scope;
  555. }
  556. if (include.limit && include.separate === undefined) {
  557. include.separate = true;
  558. }
  559. if (include.separate === true) {
  560. if (!(include.association instanceof HasMany)) {
  561. throw new Error('Only HasMany associations support include.separate');
  562. }
  563. include.duplicating = false;
  564. if (
  565. options.attributes
  566. && options.attributes.length
  567. && !_.flattenDepth(options.attributes, 2).includes(association.sourceKey)
  568. ) {
  569. options.attributes.push(association.sourceKey);
  570. }
  571. if (
  572. include.attributes
  573. && include.attributes.length
  574. && !_.flattenDepth(include.attributes, 2).includes(association.foreignKey)
  575. ) {
  576. include.attributes.push(association.foreignKey);
  577. }
  578. }
  579. // Validate child includes
  580. if (Object.prototype.hasOwnProperty.call(include, 'include')) {
  581. this._validateIncludedElements.call(include.model, include, tableNames);
  582. }
  583. return include;
  584. }
  585. static _getIncludedAssociation(targetModel, targetAlias) {
  586. const associations = this.getAssociations(targetModel);
  587. let association = null;
  588. if (associations.length === 0) {
  589. throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is not associated to ${this.name}!`);
  590. }
  591. if (associations.length === 1) {
  592. association = this.getAssociationForAlias(targetModel, targetAlias);
  593. if (association) {
  594. return association;
  595. }
  596. if (targetAlias) {
  597. const existingAliases = this.getAssociations(targetModel).map(association => association.as);
  598. throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
  599. `You've included an alias (${targetAlias}), but it does not match the alias(es) defined in your association (${existingAliases.join(', ')}).`);
  600. }
  601. throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
  602. 'You must use the \'as\' keyword to specify the alias within your include statement.');
  603. }
  604. association = this.getAssociationForAlias(targetModel, targetAlias);
  605. if (!association) {
  606. throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} multiple times. ` +
  607. 'To identify the correct association, you must use the \'as\' keyword to specify the alias of the association you want to include.');
  608. }
  609. return association;
  610. }
  611. static _expandIncludeAll(options) {
  612. const includes = options.include;
  613. if (!includes) {
  614. return;
  615. }
  616. for (let index = 0; index < includes.length; index++) {
  617. const include = includes[index];
  618. if (include.all) {
  619. includes.splice(index, 1);
  620. index--;
  621. this._expandIncludeAllElement(includes, include);
  622. }
  623. }
  624. includes.forEach(include => {
  625. this._expandIncludeAll.call(include.model, include);
  626. });
  627. }
  628. static _conformIndex(index) {
  629. if (!index.fields) {
  630. throw new Error('Missing "fields" property for index definition');
  631. }
  632. index = _.defaults(index, {
  633. type: '',
  634. parser: null
  635. });
  636. if (index.type && index.type.toLowerCase() === 'unique') {
  637. index.unique = true;
  638. delete index.type;
  639. }
  640. return index;
  641. }
  642. static _uniqIncludes(options) {
  643. if (!options.include) return;
  644. options.include = _(options.include)
  645. .groupBy(include => `${include.model && include.model.name}-${include.as}`)
  646. .map(includes => this._assignOptions(...includes))
  647. .value();
  648. }
  649. static _baseMerge(...args) {
  650. _.assignWith(...args);
  651. this._conformIncludes(args[0], this);
  652. this._uniqIncludes(args[0]);
  653. return args[0];
  654. }
  655. static _mergeFunction(objValue, srcValue, key) {
  656. if (Array.isArray(objValue) && Array.isArray(srcValue)) {
  657. return _.union(objValue, srcValue);
  658. }
  659. if (key === 'where' || key === 'having') {
  660. if (srcValue instanceof Utils.SequelizeMethod) {
  661. srcValue = { [Op.and]: srcValue };
  662. }
  663. if (_.isPlainObject(objValue) && _.isPlainObject(srcValue)) {
  664. return Object.assign(objValue, srcValue);
  665. }
  666. } else if (key === 'attributes' && _.isPlainObject(objValue) && _.isPlainObject(srcValue)) {
  667. return _.assignWith(objValue, srcValue, (objValue, srcValue) => {
  668. if (Array.isArray(objValue) && Array.isArray(srcValue)) {
  669. return _.union(objValue, srcValue);
  670. }
  671. });
  672. }
  673. // If we have a possible object/array to clone, we try it.
  674. // Otherwise, we return the original value when it's not undefined,
  675. // or the resulting object in that case.
  676. if (srcValue) {
  677. return Utils.cloneDeep(srcValue, true);
  678. }
  679. return srcValue === undefined ? objValue : srcValue;
  680. }
  681. static _assignOptions(...args) {
  682. return this._baseMerge(...args, this._mergeFunction);
  683. }
  684. static _defaultsOptions(target, opts) {
  685. return this._baseMerge(target, opts, (srcValue, objValue, key) => {
  686. return this._mergeFunction(objValue, srcValue, key);
  687. });
  688. }
  689. /**
  690. * Initialize a model, representing a table in the DB, with attributes and options.
  691. *
  692. * The table columns are defined by the hash that is given as the first argument.
  693. * Each attribute of the hash represents a column.
  694. *
  695. * @example
  696. * Project.init({
  697. * columnA: {
  698. * type: Sequelize.BOOLEAN,
  699. * validate: {
  700. * is: ['[a-z]','i'], // will only allow letters
  701. * max: 23, // only allow values <= 23
  702. * isIn: {
  703. * args: [['en', 'zh']],
  704. * msg: "Must be English or Chinese"
  705. * }
  706. * },
  707. * field: 'column_a'
  708. * // Other attributes here
  709. * },
  710. * columnB: Sequelize.STRING,
  711. * columnC: 'MY VERY OWN COLUMN TYPE'
  712. * }, {sequelize})
  713. *
  714. * sequelize.models.modelName // The model will now be available in models under the class name
  715. *
  716. * @see
  717. * <a href="/master/manual/model-basics.html">Model Basics</a> guide
  718. *
  719. * @see
  720. * <a href="/master/manual/model-basics.html">Hooks</a> guide
  721. *
  722. * @see
  723. * <a href="/master/manual/validations-and-constraints.html"/>Validations & Constraints</a> guide
  724. *
  725. * @param {object} attributes An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below:
  726. * @param {string|DataTypes|object} attributes.column The description of a database column
  727. * @param {string|DataTypes} attributes.column.type A string or a data type
  728. * @param {boolean} [attributes.column.allowNull=true] If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved.
  729. * @param {any} [attributes.column.defaultValue=null] A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
  730. * @param {string|boolean} [attributes.column.unique=false] If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index
  731. * @param {boolean} [attributes.column.primaryKey=false] If true, this attribute will be marked as primary key
  732. * @param {string} [attributes.column.field=null] If set, sequelize will map the attribute name to a different name in the database
  733. * @param {boolean} [attributes.column.autoIncrement=false] If true, this column will be set to auto increment
  734. * @param {boolean} [attributes.column.autoIncrementIdentity=false] If true, combined with autoIncrement=true, will use Postgres `GENERATED BY DEFAULT AS IDENTITY` instead of `SERIAL`. Postgres 10+ only.
  735. * @param {string} [attributes.column.comment=null] Comment for this column
  736. * @param {string|Model} [attributes.column.references=null] An object with reference configurations
  737. * @param {string|Model} [attributes.column.references.model] If this column references another table, provide it here as a Model, or a string
  738. * @param {string} [attributes.column.references.key='id'] The column of the foreign table that this column references
  739. * @param {string} [attributes.column.onUpdate] What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
  740. * @param {string} [attributes.column.onDelete] What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
  741. * @param {Function} [attributes.column.get] Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying values.
  742. * @param {Function} [attributes.column.set] Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the underlying values.
  743. * @param {object} [attributes.column.validate] An object of validations to execute for this column every time the model is saved. Can be either the name of a validation provided by validator.js, a validation function provided by extending validator.js (see the `DAOValidator` property for more details), or a custom validation function. Custom validation functions are called with the value of the field and the instance itself as the `this` binding, and can possibly take a second callback argument, to signal that they are asynchronous. If the validator is sync, it should throw in the case of a failed validation; if it is async, the callback should be called with the error text.
  744. * @param {object} options These options are merged with the default define options provided to the Sequelize constructor
  745. * @param {object} options.sequelize Define the sequelize instance to attach to the new Model. Throw error if none is provided.
  746. * @param {string} [options.modelName] Set name of the model. By default its same as Class name.
  747. * @param {object} [options.defaultScope={}] Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll
  748. * @param {object} [options.scopes] More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about how scopes are defined, and what you can do with them
  749. * @param {boolean} [options.omitNull] Don't persist null values. This means that all columns with null values will not be saved
  750. * @param {boolean} [options.timestamps=true] Adds createdAt and updatedAt timestamps to the model.
  751. * @param {boolean} [options.paranoid=false] Calling `destroy` will not delete the model, but instead set a `deletedAt` timestamp if this is true. Needs `timestamps=true` to work
  752. * @param {boolean} [options.underscored=false] Add underscored field to all attributes, this covers user defined attributes, timestamps and foreign keys. Will not affect attributes with explicitly set `field` option
  753. * @param {boolean} [options.freezeTableName=false] If freezeTableName is true, sequelize will not try to alter the model name to get the table name. Otherwise, the model name will be pluralized
  754. * @param {object} [options.name] An object with two attributes, `singular` and `plural`, which are used when this model is associated to others.
  755. * @param {string} [options.name.singular=Utils.singularize(modelName)] Singular name for model
  756. * @param {string} [options.name.plural=Utils.pluralize(modelName)] Plural name for model
  757. * @param {Array<object>} [options.indexes] indexes definitions
  758. * @param {string} [options.indexes[].name] The name of the index. Defaults to model name + _ + fields concatenated
  759. * @param {string} [options.indexes[].type] Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL`
  760. * @param {string} [options.indexes[].using] The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and postgres, and postgres additionally supports GIST and GIN.
  761. * @param {string} [options.indexes[].operator] Specify index operator.
  762. * @param {boolean} [options.indexes[].unique=false] Should the index by unique? Can also be triggered by setting type to `UNIQUE`
  763. * @param {boolean} [options.indexes[].concurrently=false] PostgresSQL will build the index without taking any write locks. Postgres only
  764. * @param {Array<string|object>} [options.indexes[].fields] An array of the fields to index. Each field can either be a string containing the name of the field, a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute` (field name), `length` (create a prefix index of length chars), `order` (the direction the column should be sorted in), `collate` (the collation (sort order) for the column)
  765. * @param {string|boolean} [options.createdAt] Override the name of the createdAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.
  766. * @param {string|boolean} [options.updatedAt] Override the name of the updatedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.
  767. * @param {string|boolean} [options.deletedAt] Override the name of the deletedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.
  768. * @param {string} [options.tableName] Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim
  769. * @param {string} [options.schema='public'] schema
  770. * @param {string} [options.engine] Specify engine for model's table
  771. * @param {string} [options.charset] Specify charset for model's table
  772. * @param {string} [options.comment] Specify comment for model's table
  773. * @param {string} [options.collate] Specify collation for model's table
  774. * @param {string} [options.initialAutoIncrement] Set the initial AUTO_INCREMENT value for the table in MySQL.
  775. * @param {object} [options.hooks] An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, validationFailed, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, beforeSave, afterDestroy, afterUpdate, afterBulkCreate, afterSave, afterBulkDestroy and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions.
  776. * @param {object} [options.validate] An object of model wide validations. Validations have access to all model values via `this`. If the validator function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional error.
  777. *
  778. * @returns {Model}
  779. */
  780. static init(attributes, options = {}) {
  781. if (!options.sequelize) {
  782. throw new Error('No Sequelize instance passed');
  783. }
  784. this.sequelize = options.sequelize;
  785. const globalOptions = this.sequelize.options;
  786. options = Utils.merge(_.cloneDeep(globalOptions.define), options);
  787. if (!options.modelName) {
  788. options.modelName = this.name;
  789. }
  790. options = Utils.merge({
  791. name: {
  792. plural: Utils.pluralize(options.modelName),
  793. singular: Utils.singularize(options.modelName)
  794. },
  795. indexes: [],
  796. omitNull: globalOptions.omitNull,
  797. schema: globalOptions.schema
  798. }, options);
  799. this.sequelize.runHooks('beforeDefine', attributes, options);
  800. if (options.modelName !== this.name) {
  801. Object.defineProperty(this, 'name', { value: options.modelName });
  802. }
  803. delete options.modelName;
  804. this.options = {
  805. timestamps: true,
  806. validate: {},
  807. freezeTableName: false,
  808. underscored: false,
  809. paranoid: false,
  810. rejectOnEmpty: false,
  811. whereCollection: null,
  812. schema: null,
  813. schemaDelimiter: '',
  814. defaultScope: {},
  815. scopes: {},
  816. indexes: [],
  817. ...options
  818. };
  819. // if you call "define" multiple times for the same modelName, do not clutter the factory
  820. if (this.sequelize.isDefined(this.name)) {
  821. this.sequelize.modelManager.removeModel(this.sequelize.modelManager.getModel(this.name));
  822. }
  823. this.associations = {};
  824. this._setupHooks(options.hooks);
  825. this.underscored = this.options.underscored;
  826. if (!this.options.tableName) {
  827. this.tableName = this.options.freezeTableName ? this.name : Utils.underscoredIf(Utils.pluralize(this.name), this.underscored);
  828. } else {
  829. this.tableName = this.options.tableName;
  830. }
  831. this._schema = this.options.schema;
  832. this._schemaDelimiter = this.options.schemaDelimiter;
  833. // error check options
  834. _.each(options.validate, (validator, validatorType) => {
  835. if (Object.prototype.hasOwnProperty.call(attributes, validatorType)) {
  836. throw new Error(`A model validator function must not have the same name as a field. Model: ${this.name}, field/validation name: ${validatorType}`);
  837. }
  838. if (typeof validator !== 'function') {
  839. throw new Error(`Members of the validate option must be functions. Model: ${this.name}, error with validate member ${validatorType}`);
  840. }
  841. });
  842. this.rawAttributes = _.mapValues(attributes, (attribute, name) => {
  843. attribute = this.sequelize.normalizeAttribute(attribute);
  844. if (attribute.type === undefined) {
  845. throw new Error(`Unrecognized datatype for attribute "${this.name}.${name}"`);
  846. }
  847. if (attribute.allowNull !== false && _.get(attribute, 'validate.notNull')) {
  848. throw new Error(`Invalid definition for "${this.name}.${name}", "notNull" validator is only allowed with "allowNull:false"`);
  849. }
  850. if (_.get(attribute, 'references.model.prototype') instanceof Model) {
  851. attribute.references.model = attribute.references.model.getTableName();
  852. }
  853. return attribute;
  854. });
  855. const tableName = this.getTableName();
  856. this._indexes = this.options.indexes
  857. .map(index => Utils.nameIndex(this._conformIndex(index), tableName));
  858. this.primaryKeys = {};
  859. this._readOnlyAttributes = new Set();
  860. this._timestampAttributes = {};
  861. // setup names of timestamp attributes
  862. if (this.options.timestamps) {
  863. if (this.options.createdAt !== false) {
  864. this._timestampAttributes.createdAt = this.options.createdAt || 'createdAt';
  865. this._readOnlyAttributes.add(this._timestampAttributes.createdAt);
  866. }
  867. if (this.options.updatedAt !== false) {
  868. this._timestampAttributes.updatedAt = this.options.updatedAt || 'updatedAt';
  869. this._readOnlyAttributes.add(this._timestampAttributes.updatedAt);
  870. }
  871. if (this.options.paranoid && this.options.deletedAt !== false) {
  872. this._timestampAttributes.deletedAt = this.options.deletedAt || 'deletedAt';
  873. this._readOnlyAttributes.add(this._timestampAttributes.deletedAt);
  874. }
  875. }
  876. // setup name for version attribute
  877. if (this.options.version) {
  878. this._versionAttribute = typeof this.options.version === 'string' ? this.options.version : 'version';
  879. this._readOnlyAttributes.add(this._versionAttribute);
  880. }
  881. this._hasReadOnlyAttributes = this._readOnlyAttributes.size > 0;
  882. // Add head and tail default attributes (id, timestamps)
  883. this._addDefaultAttributes();
  884. this.refreshAttributes();
  885. this._findAutoIncrementAttribute();
  886. this._scope = this.options.defaultScope;
  887. this._scopeNames = ['defaultScope'];
  888. this.sequelize.modelManager.addModel(this);
  889. this.sequelize.runHooks('afterDefine', this);
  890. return this;
  891. }
  892. static refreshAttributes() {
  893. const attributeManipulation = {};
  894. this.prototype._customGetters = {};
  895. this.prototype._customSetters = {};
  896. ['get', 'set'].forEach(type => {
  897. const opt = `${type}terMethods`;
  898. const funcs = { ...this.options[opt] };
  899. const _custom = type === 'get' ? this.prototype._customGetters : this.prototype._customSetters;
  900. _.each(funcs, (method, attribute) => {
  901. _custom[attribute] = method;
  902. if (type === 'get') {
  903. funcs[attribute] = function() {
  904. return this.get(attribute);
  905. };
  906. }
  907. if (type === 'set') {
  908. funcs[attribute] = function(value) {
  909. return this.set(attribute, value);
  910. };
  911. }
  912. });
  913. _.each(this.rawAttributes, (options, attribute) => {
  914. if (Object.prototype.hasOwnProperty.call(options, type)) {
  915. _custom[attribute] = options[type];
  916. }
  917. if (type === 'get') {
  918. funcs[attribute] = function() {
  919. return this.get(attribute);
  920. };
  921. }
  922. if (type === 'set') {
  923. funcs[attribute] = function(value) {
  924. return this.set(attribute, value);
  925. };
  926. }
  927. });
  928. _.each(funcs, (fct, name) => {
  929. if (!attributeManipulation[name]) {
  930. attributeManipulation[name] = {
  931. configurable: true
  932. };
  933. }
  934. attributeManipulation[name][type] = fct;
  935. });
  936. });
  937. this._dataTypeChanges = {};
  938. this._dataTypeSanitizers = {};
  939. this._hasBooleanAttributes = false;
  940. this._hasDateAttributes = false;
  941. this._jsonAttributes = new Set();
  942. this._virtualAttributes = new Set();
  943. this._defaultValues = {};
  944. this.prototype.validators = {};
  945. this.fieldRawAttributesMap = {};
  946. this.primaryKeys = {};
  947. this.uniqueKeys = {};
  948. _.each(this.rawAttributes, (definition, name) => {
  949. definition.type = this.sequelize.normalizeDataType(definition.type);
  950. definition.Model = this;
  951. definition.fieldName = name;
  952. definition._modelAttribute = true;
  953. if (definition.field === undefined) {
  954. definition.field = Utils.underscoredIf(name, this.underscored);
  955. }
  956. if (definition.primaryKey === true) {
  957. this.primaryKeys[name] = definition;
  958. }
  959. this.fieldRawAttributesMap[definition.field] = definition;
  960. if (definition.type._sanitize) {
  961. this._dataTypeSanitizers[name] = definition.type._sanitize;
  962. }
  963. if (definition.type._isChanged) {
  964. this._dataTypeChanges[name] = definition.type._isChanged;
  965. }
  966. if (definition.type instanceof DataTypes.BOOLEAN) {
  967. this._hasBooleanAttributes = true;
  968. } else if (definition.type instanceof DataTypes.DATE || definition.type instanceof DataTypes.DATEONLY) {
  969. this._hasDateAttributes = true;
  970. } else if (definition.type instanceof DataTypes.JSON) {
  971. this._jsonAttributes.add(name);
  972. } else if (definition.type instanceof DataTypes.VIRTUAL) {
  973. this._virtualAttributes.add(name);
  974. }
  975. if (Object.prototype.hasOwnProperty.call(definition, 'defaultValue')) {
  976. this._defaultValues[name] = () => Utils.toDefaultValue(definition.defaultValue, this.sequelize.options.dialect);
  977. }
  978. if (Object.prototype.hasOwnProperty.call(definition, 'unique') && definition.unique) {
  979. let idxName;
  980. if (
  981. typeof definition.unique === 'object' &&
  982. Object.prototype.hasOwnProperty.call(definition.unique, 'name')
  983. ) {
  984. idxName = definition.unique.name;
  985. } else if (typeof definition.unique === 'string') {
  986. idxName = definition.unique;
  987. } else {
  988. idxName = `${this.tableName}_${name}_unique`;
  989. }
  990. const idx = this.uniqueKeys[idxName] || { fields: [] };
  991. idx.fields.push(definition.field);
  992. idx.msg = idx.msg || definition.unique.msg || null;
  993. idx.name = idxName || false;
  994. idx.column = name;
  995. idx.customIndex = definition.unique !== true;
  996. this.uniqueKeys[idxName] = idx;
  997. }
  998. if (Object.prototype.hasOwnProperty.call(definition, 'validate')) {
  999. this.prototype.validators[name] = definition.validate;
  1000. }
  1001. if (definition.index === true && definition.type instanceof DataTypes.JSONB) {
  1002. this._indexes.push(
  1003. Utils.nameIndex(
  1004. this._conformIndex({
  1005. fields: [definition.field || name],
  1006. using: 'gin'
  1007. }),
  1008. this.getTableName()
  1009. )
  1010. );
  1011. delete definition.index;
  1012. }
  1013. });
  1014. // Create a map of field to attribute names
  1015. this.fieldAttributeMap = _.reduce(this.fieldRawAttributesMap, (map, value, key) => {
  1016. if (key !== value.fieldName) {
  1017. map[key] = value.fieldName;
  1018. }
  1019. return map;
  1020. }, {});
  1021. this._hasJsonAttributes = !!this._jsonAttributes.size;
  1022. this._hasVirtualAttributes = !!this._virtualAttributes.size;
  1023. this._hasDefaultValues = !_.isEmpty(this._defaultValues);
  1024. this.tableAttributes = _.omitBy(this.rawAttributes, (_a, key) => this._virtualAttributes.has(key));
  1025. this.prototype._hasCustomGetters = Object.keys(this.prototype._customGetters).length;
  1026. this.prototype._hasCustomSetters = Object.keys(this.prototype._customSetters).length;
  1027. for (const key of Object.keys(attributeManipulation)) {
  1028. if (Object.prototype.hasOwnProperty.call(Model.prototype, key)) {
  1029. this.sequelize.log(`Not overriding built-in method from model attribute: ${key}`);
  1030. continue;
  1031. }
  1032. Object.defineProperty(this.prototype, key, attributeManipulation[key]);
  1033. }
  1034. this.prototype.rawAttributes = this.rawAttributes;
  1035. this.prototype._isAttribute = key => Object.prototype.hasOwnProperty.call(this.prototype.rawAttributes, key);
  1036. // Primary key convenience constiables
  1037. this.primaryKeyAttributes = Object.keys(this.primaryKeys);
  1038. this.primaryKeyAttribute = this.primaryKeyAttributes[0];
  1039. if (this.primaryKeyAttribute) {
  1040. this.primaryKeyField = this.rawAttributes[this.primaryKeyAttribute].field || this.primaryKeyAttribute;
  1041. }
  1042. this._hasPrimaryKeys = this.primaryKeyAttributes.length > 0;
  1043. this._isPrimaryKey = key => this.primaryKeyAttributes.includes(key);
  1044. }
  1045. /**
  1046. * Remove attribute from model definition
  1047. *
  1048. * @param {string} attribute name of attribute to remove
  1049. */
  1050. static removeAttribute(attribute) {
  1051. delete this.rawAttributes[attribute];
  1052. this.refreshAttributes();
  1053. }
  1054. /**
  1055. * Sync this Model to the DB, that is create the table.
  1056. *
  1057. * @param {object} [options] sync options
  1058. *
  1059. * @see
  1060. * {@link Sequelize#sync} for options
  1061. *
  1062. * @returns {Promise<Model>}
  1063. */
  1064. static async sync(options) {
  1065. options = { ...this.options, ...options };
  1066. options.hooks = options.hooks === undefined ? true : !!options.hooks;
  1067. const attributes = this.tableAttributes;
  1068. const rawAttributes = this.fieldRawAttributesMap;
  1069. if (options.hooks) {
  1070. await this.runHooks('beforeSync', options);
  1071. }
  1072. if (options.force) {
  1073. await this.drop(options);
  1074. }
  1075. const tableName = this.getTableName(options);
  1076. await this.queryInterface.createTable(tableName, attributes, options, this);
  1077. if (options.alter) {
  1078. const tableInfos = await Promise.all([
  1079. this.queryInterface.describeTable(tableName, options),
  1080. this.queryInterface.getForeignKeyReferencesForTable(tableName, options)
  1081. ]);
  1082. const columns = tableInfos[0];
  1083. // Use for alter foreign keys
  1084. const foreignKeyReferences = tableInfos[1];
  1085. const removedConstraints = {};
  1086. for (const columnName in attributes) {
  1087. if (!Object.prototype.hasOwnProperty.call(attributes, columnName)) continue;
  1088. if (!columns[columnName] && !columns[attributes[columnName].field]) {
  1089. await this.queryInterface.addColumn(tableName, attributes[columnName].field || columnName, attributes[columnName], options);
  1090. }
  1091. }
  1092. if (options.alter === true || typeof options.alter === 'object' && options.alter.drop !== false) {
  1093. for (const columnName in columns) {
  1094. if (!Object.prototype.hasOwnProperty.call(columns, columnName)) continue;
  1095. const currentAttribute = rawAttributes[columnName];
  1096. if (!currentAttribute) {
  1097. await this.queryInterface.removeColumn(tableName, columnName, options);
  1098. continue;
  1099. }
  1100. if (currentAttribute.primaryKey) continue;
  1101. // Check foreign keys. If it's a foreign key, it should remove constraint first.
  1102. const references = currentAttribute.references;
  1103. if (currentAttribute.references) {
  1104. const database = this.sequelize.config.database;
  1105. const schema = this.sequelize.config.schema;
  1106. // Find existed foreign keys
  1107. for (const foreignKeyReference of foreignKeyReferences) {
  1108. const constraintName = foreignKeyReference.constraintName;
  1109. if (!!constraintName
  1110. && foreignKeyReference.tableCatalog === database
  1111. && (schema ? foreignKeyReference.tableSchema === schema : true)
  1112. && foreignKeyReference.referencedTableName === references.model
  1113. && foreignKeyReference.referencedColumnName === references.key
  1114. && (schema ? foreignKeyReference.referencedTableSchema === schema : true)
  1115. && !removedConstraints[constraintName]) {
  1116. // Remove constraint on foreign keys.
  1117. await this.queryInterface.removeConstraint(tableName, constraintName, options);
  1118. removedConstraints[constraintName] = true;
  1119. }
  1120. }
  1121. }
  1122. await this.queryInterface.changeColumn(tableName, columnName, currentAttribute, options);
  1123. }
  1124. }
  1125. }
  1126. let indexes = await this.queryInterface.showIndex(tableName, options);
  1127. indexes = this._indexes.filter(item1 =>
  1128. !indexes.some(item2 => item1.name === item2.name)
  1129. ).sort((index1, index2) => {
  1130. if (this.sequelize.options.dialect === 'postgres') {
  1131. // move concurrent indexes to the bottom to avoid weird deadlocks
  1132. if (index1.concurrently === true) return 1;
  1133. if (index2.concurrently === true) return -1;
  1134. }
  1135. return 0;
  1136. });
  1137. for (const index of indexes) {
  1138. await this.queryInterface.addIndex(tableName, { ...options, ...index });
  1139. }
  1140. if (options.hooks) {
  1141. await this.runHooks('afterSync', options);
  1142. }
  1143. return this;
  1144. }
  1145. /**
  1146. * Drop the table represented by this Model
  1147. *
  1148. * @param {object} [options] drop options
  1149. * @param {boolean} [options.cascade=false] Also drop all objects depending on this table, such as views. Only works in postgres
  1150. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1151. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1152. *
  1153. * @returns {Promise}
  1154. */
  1155. static async drop(options) {
  1156. return await this.queryInterface.dropTable(this.getTableName(options), options);
  1157. }
  1158. static async dropSchema(schema) {
  1159. return await this.queryInterface.dropSchema(schema);
  1160. }
  1161. /**
  1162. * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - `"schema"."tableName"`,
  1163. * while the schema will be prepended to the table name for mysql and sqlite - `'schema.tablename'`.
  1164. *
  1165. * This method is intended for use cases where the same model is needed in multiple schemas. In such a use case it is important
  1166. * to call `model.schema(schema, [options]).sync()` for each model to ensure the models are created in the correct schema.
  1167. *
  1168. * If a single default schema per model is needed, set the `options.schema='schema'` parameter during the `define()` call
  1169. * for the model.
  1170. *
  1171. * @param {string} schema The name of the schema
  1172. * @param {object} [options] schema options
  1173. * @param {string} [options.schemaDelimiter='.'] The character(s) that separates the schema name from the table name
  1174. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1175. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1176. *
  1177. * @see
  1178. * {@link Sequelize#define} for more information about setting a default schema.
  1179. *
  1180. * @returns {Model}
  1181. */
  1182. static schema(schema, options) {
  1183. const clone = class extends this {};
  1184. Object.defineProperty(clone, 'name', { value: this.name });
  1185. clone._schema = schema;
  1186. if (options) {
  1187. if (typeof options === 'string') {
  1188. clone._schemaDelimiter = options;
  1189. } else if (options.schemaDelimiter) {
  1190. clone._schemaDelimiter = options.schemaDelimiter;
  1191. }
  1192. }
  1193. return clone;
  1194. }
  1195. /**
  1196. * Get the table name of the model, taking schema into account. The method will return The name as a string if the model has no schema,
  1197. * or an object with `tableName`, `schema` and `delimiter` properties.
  1198. *
  1199. * @returns {string|object}
  1200. */
  1201. static getTableName() {
  1202. return this.queryGenerator.addSchema(this);
  1203. }
  1204. /**
  1205. * Get un-scoped model
  1206. *
  1207. * @returns {Model}
  1208. */
  1209. static unscoped() {
  1210. return this.scope();
  1211. }
  1212. /**
  1213. * Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined.
  1214. *
  1215. * By default this will throw an error if a scope with that name already exists. Pass `override: true` in the options object to silence this error.
  1216. *
  1217. * @param {string} name The name of the scope. Use `defaultScope` to override the default scope
  1218. * @param {object|Function} scope scope or options
  1219. * @param {object} [options] scope options
  1220. * @param {boolean} [options.override=false] override old scope if already defined
  1221. */
  1222. static addScope(name, scope, options) {
  1223. options = { override: false, ...options };
  1224. if ((name === 'defaultScope' && Object.keys(this.options.defaultScope).length > 0 || name in this.options.scopes) && options.override === false) {
  1225. throw new Error(`The scope ${name} already exists. Pass { override: true } as options to silence this error`);
  1226. }
  1227. if (name === 'defaultScope') {
  1228. this.options.defaultScope = this._scope = scope;
  1229. } else {
  1230. this.options.scopes[name] = scope;
  1231. }
  1232. }
  1233. /**
  1234. * Apply a scope created in `define` to the model.
  1235. *
  1236. * @example <caption>how to create scopes</caption>
  1237. * const Model = sequelize.define('model', attributes, {
  1238. * defaultScope: {
  1239. * where: {
  1240. * username: 'dan'
  1241. * },
  1242. * limit: 12
  1243. * },
  1244. * scopes: {
  1245. * isALie: {
  1246. * where: {
  1247. * stuff: 'cake'
  1248. * }
  1249. * },
  1250. * complexFunction: function(email, accessLevel) {
  1251. * return {
  1252. * where: {
  1253. * email: {
  1254. * [Op.like]: email
  1255. * },
  1256. * access_level {
  1257. * [Op.gte]: accessLevel
  1258. * }
  1259. * }
  1260. * }
  1261. * }
  1262. * }
  1263. * })
  1264. *
  1265. * # As you have defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples:
  1266. *
  1267. * Model.findAll() // WHERE username = 'dan'
  1268. * Model.findAll({ where: { age: { [Op.gt]: 12 } } }) // WHERE age > 12 AND username = 'dan'
  1269. *
  1270. * @example <caption>To invoke scope functions you can do</caption>
  1271. * Model.scope({ method: ['complexFunction', 'dan@sequelize.com', 42]}).findAll()
  1272. * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
  1273. *
  1274. * @param {?Array|object|string} [option] The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
  1275. *
  1276. * @returns {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
  1277. */
  1278. static scope(option) {
  1279. const self = class extends this {};
  1280. let scope;
  1281. let scopeName;
  1282. Object.defineProperty(self, 'name', { value: this.name });
  1283. self._scope = {};
  1284. self._scopeNames = [];
  1285. self.scoped = true;
  1286. if (!option) {
  1287. return self;
  1288. }
  1289. const options = _.flatten(arguments);
  1290. for (const option of options) {
  1291. scope = null;
  1292. scopeName = null;
  1293. if (_.isPlainObject(option)) {
  1294. if (option.method) {
  1295. if (Array.isArray(option.method) && !!self.options.scopes[option.method[0]]) {
  1296. scopeName = option.method[0];
  1297. scope = self.options.scopes[scopeName].apply(self, option.method.slice(1));
  1298. }
  1299. else if (self.options.scopes[option.method]) {
  1300. scopeName = option.method;
  1301. scope = self.options.scopes[scopeName].apply(self);
  1302. }
  1303. } else {
  1304. scope = option;
  1305. }
  1306. } else if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) {
  1307. scope = self.options.defaultScope;
  1308. } else {
  1309. scopeName = option;
  1310. scope = self.options.scopes[scopeName];
  1311. if (typeof scope === 'function') {
  1312. scope = scope();
  1313. }
  1314. }
  1315. if (scope) {
  1316. this._conformIncludes(scope, this);
  1317. // clone scope so it doesn't get modified
  1318. this._assignOptions(self._scope, Utils.cloneDeep(scope));
  1319. self._scopeNames.push(scopeName ? scopeName : 'defaultScope');
  1320. } else {
  1321. throw new sequelizeErrors.SequelizeScopeError(`Invalid scope ${scopeName} called.`);
  1322. }
  1323. }
  1324. return self;
  1325. }
  1326. /**
  1327. * Search for multiple instances.
  1328. *
  1329. * @example <caption>Simple search using AND and =</caption>
  1330. * Model.findAll({
  1331. * where: {
  1332. * attr1: 42,
  1333. * attr2: 'cake'
  1334. * }
  1335. * })
  1336. *
  1337. * # WHERE attr1 = 42 AND attr2 = 'cake'
  1338. *
  1339. * @example <caption>Using greater than, less than etc.</caption>
  1340. * const {gt, lte, ne, in: opIn} = Sequelize.Op;
  1341. *
  1342. * Model.findAll({
  1343. * where: {
  1344. * attr1: {
  1345. * [gt]: 50
  1346. * },
  1347. * attr2: {
  1348. * [lte]: 45
  1349. * },
  1350. * attr3: {
  1351. * [opIn]: [1,2,3]
  1352. * },
  1353. * attr4: {
  1354. * [ne]: 5
  1355. * }
  1356. * }
  1357. * })
  1358. *
  1359. * # WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
  1360. *
  1361. * @example <caption>Queries using OR</caption>
  1362. * const {or, and, gt, lt} = Sequelize.Op;
  1363. *
  1364. * Model.findAll({
  1365. * where: {
  1366. * name: 'a project',
  1367. * [or]: [
  1368. * {id: [1, 2, 3]},
  1369. * {
  1370. * [and]: [
  1371. * {id: {[gt]: 10}},
  1372. * {id: {[lt]: 100}}
  1373. * ]
  1374. * }
  1375. * ]
  1376. * }
  1377. * });
  1378. *
  1379. * # WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));
  1380. *
  1381. * @see
  1382. * {@link Operators} for possible operators
  1383. * __Alias__: _all_
  1384. *
  1385. * The promise is resolved with an array of Model instances if the query succeeds._
  1386. *
  1387. * @param {object} [options] A hash of options to describe the scope of the search
  1388. * @param {object} [options.where] A hash of attributes to describe your search. See above for examples.
  1389. * @param {Array<string>|object} [options.attributes] A list of the attributes that you want to select, or an object with `include` and `exclude` keys. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to have in the returned instance
  1390. * @param {Array<string>} [options.attributes.include] Select all the attributes of the model, plus some additional ones. Useful for aggregations, e.g. `{ attributes: { include: [[sequelize.fn('COUNT', sequelize.col('id')), 'total']] }`
  1391. * @param {Array<string>} [options.attributes.exclude] Select all the attributes of the model, except some few. Useful for security purposes e.g. `{ attributes: { exclude: ['password'] } }`
  1392. * @param {boolean} [options.paranoid=true] If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned. Only applies if `options.paranoid` is true for the model.
  1393. * @param {Array<object|Model|string>} [options.include] A list of associations to eagerly load using a left join. Supported is either `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }]}` or `{ include: ['Alias']}`. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y).
  1394. * @param {Model} [options.include[].model] The model you want to eagerly load
  1395. * @param {string} [options.include[].as] The alias of the relation, in case the model you want to eagerly load is aliased. For `hasOne` / `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
  1396. * @param {Association} [options.include[].association] The association you want to eagerly load. (This can be used instead of providing a model/as pair)
  1397. * @param {object} [options.include[].where] Where clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set `required: false`
  1398. * @param {boolean} [options.include[].or=false] Whether to bind the ON and WHERE clause together by OR instead of AND.
  1399. * @param {object} [options.include[].on] Supply your own ON condition for the join.
  1400. * @param {Array<string>} [options.include[].attributes] A list of attributes to select from the child model
  1401. * @param {boolean} [options.include[].required] If true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if `include.where` is set, false otherwise.
  1402. * @param {boolean} [options.include[].right] If true, converts to a right join if dialect support it. Ignored if `include.required` is true.
  1403. * @param {boolean} [options.include[].separate] If true, runs a separate query to fetch the associated instances, only supported for hasMany associations
  1404. * @param {number} [options.include[].limit] Limit the joined rows, only supported with include.separate=true
  1405. * @param {string} [options.include[].through.as] The alias for the join model, in case you want to give it a different name than the default one.
  1406. * @param {object} [options.include[].through.where] Filter on the join model for belongsToMany relations
  1407. * @param {Array} [options.include[].through.attributes] A list of attributes to select from the join model for belongsToMany relations
  1408. * @param {Array<object|Model|string>} [options.include[].include] Load further nested related models
  1409. * @param {boolean} [options.include[].duplicating] Mark the include as duplicating, will prevent a subquery from being used.
  1410. * @param {Array|Sequelize.fn|Sequelize.col|Sequelize.literal} [options.order] Specifies an ordering. Using an array, you can provide several columns / functions to order by. Each element can be further wrapped in a two-element array. The first element is the column / function to order by, the second is the direction. For example: `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
  1411. * @param {number} [options.limit] Limit for result
  1412. * @param {number} [options.offset] Offset for result
  1413. * @param {Transaction} [options.transaction] Transaction to run query under
  1414. * @param {string|object} [options.lock] Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins.
  1415. * @param {boolean} [options.skipLocked] Skip locked rows. Only supported in Postgres.
  1416. * @param {boolean} [options.raw] Return raw result. See sequelize.query for more information.
  1417. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1418. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1419. * @param {object} [options.having] Having options
  1420. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1421. * @param {boolean|Error} [options.rejectOnEmpty=false] Throws an error when no records found
  1422. *
  1423. * @see
  1424. * {@link Sequelize#query}
  1425. *
  1426. * @returns {Promise<Array<Model>>}
  1427. */
  1428. static async findAll(options) {
  1429. if (options !== undefined && !_.isPlainObject(options)) {
  1430. throw new sequelizeErrors.QueryError('The argument passed to findAll must be an options object, use findByPk if you wish to pass a single primary key value');
  1431. }
  1432. if (options !== undefined && options.attributes) {
  1433. if (!Array.isArray(options.attributes) && !_.isPlainObject(options.attributes)) {
  1434. throw new sequelizeErrors.QueryError('The attributes option must be an array of column names or an object');
  1435. }
  1436. }
  1437. this.warnOnInvalidOptions(options, Object.keys(this.rawAttributes));
  1438. const tableNames = {};
  1439. tableNames[this.getTableName(options)] = true;
  1440. options = Utils.cloneDeep(options);
  1441. _.defaults(options, { hooks: true });
  1442. // set rejectOnEmpty option, defaults to model options
  1443. options.rejectOnEmpty = Object.prototype.hasOwnProperty.call(options, 'rejectOnEmpty')
  1444. ? options.rejectOnEmpty
  1445. : this.options.rejectOnEmpty;
  1446. this._injectScope(options);
  1447. if (options.hooks) {
  1448. await this.runHooks('beforeFind', options);
  1449. }
  1450. this._conformIncludes(options, this);
  1451. this._expandAttributes(options);
  1452. this._expandIncludeAll(options);
  1453. if (options.hooks) {
  1454. await this.runHooks('beforeFindAfterExpandIncludeAll', options);
  1455. }
  1456. options.originalAttributes = this._injectDependentVirtualAttributes(options.attributes);
  1457. if (options.include) {
  1458. options.hasJoin = true;
  1459. this._validateIncludedElements(options, tableNames);
  1460. // If we're not raw, we have to make sure we include the primary key for de-duplication
  1461. if (
  1462. options.attributes
  1463. && !options.raw
  1464. && this.primaryKeyAttribute
  1465. && !options.attributes.includes(this.primaryKeyAttribute)
  1466. && (!options.group || !options.hasSingleAssociation || options.hasMultiAssociation)
  1467. ) {
  1468. options.attributes = [this.primaryKeyAttribute].concat(options.attributes);
  1469. }
  1470. }
  1471. if (!options.attributes) {
  1472. options.attributes = Object.keys(this.rawAttributes);
  1473. options.originalAttributes = this._injectDependentVirtualAttributes(options.attributes);
  1474. }
  1475. // whereCollection is used for non-primary key updates
  1476. this.options.whereCollection = options.where || null;
  1477. Utils.mapFinderOptions(options, this);
  1478. options = this._paranoidClause(this, options);
  1479. if (options.hooks) {
  1480. await this.runHooks('beforeFindAfterOptions', options);
  1481. }
  1482. const selectOptions = { ...options, tableNames: Object.keys(tableNames) };
  1483. const results = await this.queryInterface.select(this, this.getTableName(selectOptions), selectOptions);
  1484. if (options.hooks) {
  1485. await this.runHooks('afterFind', results, options);
  1486. }
  1487. //rejectOnEmpty mode
  1488. if (_.isEmpty(results) && options.rejectOnEmpty) {
  1489. if (typeof options.rejectOnEmpty === 'function') {
  1490. throw new options.rejectOnEmpty();
  1491. }
  1492. if (typeof options.rejectOnEmpty === 'object') {
  1493. throw options.rejectOnEmpty;
  1494. }
  1495. throw new sequelizeErrors.EmptyResultError();
  1496. }
  1497. return await Model._findSeparate(results, options);
  1498. }
  1499. static warnOnInvalidOptions(options, validColumnNames) {
  1500. if (!_.isPlainObject(options)) {
  1501. return;
  1502. }
  1503. const unrecognizedOptions = Object.keys(options).filter(k => !validQueryKeywords.has(k));
  1504. const unexpectedModelAttributes = _.intersection(unrecognizedOptions, validColumnNames);
  1505. if (!options.where && unexpectedModelAttributes.length > 0) {
  1506. logger.warn(`Model attributes (${unexpectedModelAttributes.join(', ')}) passed into finder method options of model ${this.name}, but the options.where object is empty. Did you forget to use options.where?`);
  1507. }
  1508. }
  1509. static _injectDependentVirtualAttributes(attributes) {
  1510. if (!this._hasVirtualAttributes) return attributes;
  1511. if (!attributes || !Array.isArray(attributes)) return attributes;
  1512. for (const attribute of attributes) {
  1513. if (
  1514. this._virtualAttributes.has(attribute)
  1515. && this.rawAttributes[attribute].type.fields
  1516. ) {
  1517. attributes = attributes.concat(this.rawAttributes[attribute].type.fields);
  1518. }
  1519. }
  1520. attributes = _.uniq(attributes);
  1521. return attributes;
  1522. }
  1523. static async _findSeparate(results, options) {
  1524. if (!options.include || options.raw || !results) return results;
  1525. const original = results;
  1526. if (options.plain) results = [results];
  1527. if (!results.length) return original;
  1528. await Promise.all(options.include.map(async include => {
  1529. if (!include.separate) {
  1530. return await Model._findSeparate(
  1531. results.reduce((memo, result) => {
  1532. let associations = result.get(include.association.as);
  1533. // Might be an empty belongsTo relation
  1534. if (!associations) return memo;
  1535. // Force array so we can concat no matter if it's 1:1 or :M
  1536. if (!Array.isArray(associations)) associations = [associations];
  1537. for (let i = 0, len = associations.length; i !== len; ++i) {
  1538. memo.push(associations[i]);
  1539. }
  1540. return memo;
  1541. }, []),
  1542. {
  1543. ..._.omit(options, 'include', 'attributes', 'order', 'where', 'limit', 'offset', 'plain', 'scope'),
  1544. include: include.include || []
  1545. }
  1546. );
  1547. }
  1548. const map = await include.association.get(results, {
  1549. ..._.omit(options, nonCascadingOptions),
  1550. ..._.omit(include, ['parent', 'association', 'as', 'originalAttributes'])
  1551. });
  1552. for (const result of results) {
  1553. result.set(
  1554. include.association.as,
  1555. map[result.get(include.association.sourceKey)],
  1556. { raw: true }
  1557. );
  1558. }
  1559. }));
  1560. return original;
  1561. }
  1562. /**
  1563. * Search for a single instance by its primary key._
  1564. *
  1565. * @param {number|string|Buffer} param The value of the desired instance's primary key.
  1566. * @param {object} [options] find options
  1567. * @param {Transaction} [options.transaction] Transaction to run query under
  1568. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1569. *
  1570. * @see
  1571. * {@link Model.findAll} for a full explanation of options, Note that options.where is not supported.
  1572. *
  1573. * @returns {Promise<Model>}
  1574. */
  1575. static async findByPk(param, options) {
  1576. // return Promise resolved with null if no arguments are passed
  1577. if ([null, undefined].includes(param)) {
  1578. return null;
  1579. }
  1580. options = Utils.cloneDeep(options) || {};
  1581. if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) {
  1582. options.where = {
  1583. [this.primaryKeyAttribute]: param
  1584. };
  1585. } else {
  1586. throw new Error(`Argument passed to findByPk is invalid: ${param}`);
  1587. }
  1588. // Bypass a possible overloaded findOne
  1589. return await this.findOne(options);
  1590. }
  1591. /**
  1592. * Search for a single instance. Returns the first instance found, or null if none can be found.
  1593. *
  1594. * @param {object} [options] A hash of options to describe the scope of the search
  1595. * @param {Transaction} [options.transaction] Transaction to run query under
  1596. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1597. *
  1598. * @see
  1599. * {@link Model.findAll} for an explanation of options
  1600. *
  1601. * @returns {Promise<Model|null>}
  1602. */
  1603. static async findOne(options) {
  1604. if (options !== undefined && !_.isPlainObject(options)) {
  1605. throw new Error('The argument passed to findOne must be an options object, use findByPk if you wish to pass a single primary key value');
  1606. }
  1607. options = Utils.cloneDeep(options);
  1608. if (options.limit === undefined) {
  1609. const uniqueSingleColumns = _.chain(this.uniqueKeys).values().filter(c => c.fields.length === 1).map('column').value();
  1610. // Don't add limit if querying directly on the pk or a unique column
  1611. if (!options.where || !_.some(options.where, (value, key) =>
  1612. (key === this.primaryKeyAttribute || uniqueSingleColumns.includes(key)) &&
  1613. (Utils.isPrimitive(value) || Buffer.isBuffer(value))
  1614. )) {
  1615. options.limit = 1;
  1616. }
  1617. }
  1618. // Bypass a possible overloaded findAll.
  1619. return await this.findAll(_.defaults(options, {
  1620. plain: true
  1621. }));
  1622. }
  1623. /**
  1624. * Run an aggregation method on the specified field
  1625. *
  1626. * @param {string} attribute The attribute to aggregate over. Can be a field name or *
  1627. * @param {string} aggregateFunction The function to use for aggregation, e.g. sum, max etc.
  1628. * @param {object} [options] Query options. See sequelize.query for full options
  1629. * @param {object} [options.where] A hash of search attributes.
  1630. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1631. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1632. * @param {DataTypes|string} [options.dataType] The type of the result. If `field` is a field in this Model, the default will be the type of that field, otherwise defaults to float.
  1633. * @param {boolean} [options.distinct] Applies DISTINCT to the field being aggregated over
  1634. * @param {Transaction} [options.transaction] Transaction to run query under
  1635. * @param {boolean} [options.plain] When `true`, the first returned value of `aggregateFunction` is cast to `dataType` and returned. If additional attributes are specified, along with `group` clauses, set `plain` to `false` to return all values of all returned rows. Defaults to `true`
  1636. *
  1637. * @returns {Promise<DataTypes|object>} Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in which case the complete data result is returned.
  1638. */
  1639. static async aggregate(attribute, aggregateFunction, options) {
  1640. options = Utils.cloneDeep(options);
  1641. // We need to preserve attributes here as the `injectScope` call would inject non aggregate columns.
  1642. const prevAttributes = options.attributes;
  1643. this._injectScope(options);
  1644. options.attributes = prevAttributes;
  1645. this._conformIncludes(options, this);
  1646. if (options.include) {
  1647. this._expandIncludeAll(options);
  1648. this._validateIncludedElements(options);
  1649. }
  1650. const attrOptions = this.rawAttributes[attribute];
  1651. const field = attrOptions && attrOptions.field || attribute;
  1652. let aggregateColumn = this.sequelize.col(field);
  1653. if (options.distinct) {
  1654. aggregateColumn = this.sequelize.fn('DISTINCT', aggregateColumn);
  1655. }
  1656. let { group } = options;
  1657. if (Array.isArray(group) && Array.isArray(group[0])) {
  1658. noDoubleNestedGroup();
  1659. group = _.flatten(group);
  1660. }
  1661. options.attributes = _.unionBy(
  1662. options.attributes,
  1663. group,
  1664. [[this.sequelize.fn(aggregateFunction, aggregateColumn), aggregateFunction]],
  1665. a => Array.isArray(a) ? a[1] : a
  1666. );
  1667. if (!options.dataType) {
  1668. if (attrOptions) {
  1669. options.dataType = attrOptions.type;
  1670. } else {
  1671. // Use FLOAT as fallback
  1672. options.dataType = new DataTypes.FLOAT();
  1673. }
  1674. } else {
  1675. options.dataType = this.sequelize.normalizeDataType(options.dataType);
  1676. }
  1677. Utils.mapOptionFieldNames(options, this);
  1678. options = this._paranoidClause(this, options);
  1679. const value = await this.queryInterface.rawSelect(this.getTableName(options), options, aggregateFunction, this);
  1680. if (value === null) {
  1681. return 0;
  1682. }
  1683. return value;
  1684. }
  1685. /**
  1686. * Count the number of records matching the provided where clause.
  1687. *
  1688. * If you provide an `include` option, the number of matching associations will be counted instead.
  1689. *
  1690. * @param {object} [options] options
  1691. * @param {object} [options.where] A hash of search attributes.
  1692. * @param {object} [options.include] Include options. See `find` for details
  1693. * @param {boolean} [options.paranoid=true] Set `true` to count only non-deleted records. Can be used on models with `paranoid` enabled
  1694. * @param {boolean} [options.distinct] Apply COUNT(DISTINCT(col)) on primary key or on options.col.
  1695. * @param {string} [options.col] Column on which COUNT() should be applied
  1696. * @param {Array} [options.attributes] Used in conjunction with `group`
  1697. * @param {Array} [options.group] For creating complex counts. Will return multiple rows as needed.
  1698. * @param {Transaction} [options.transaction] Transaction to run query under
  1699. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1700. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1701. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1702. *
  1703. * @returns {Promise<number>}
  1704. */
  1705. static async count(options) {
  1706. options = Utils.cloneDeep(options);
  1707. options = _.defaults(options, { hooks: true });
  1708. options.raw = true;
  1709. if (options.hooks) {
  1710. await this.runHooks('beforeCount', options);
  1711. }
  1712. let col = options.col || '*';
  1713. if (options.include) {
  1714. col = `${this.name}.${options.col || this.primaryKeyField}`;
  1715. }
  1716. if (options.distinct && col === '*') {
  1717. col = this.primaryKeyField;
  1718. }
  1719. options.plain = !options.group;
  1720. options.dataType = new DataTypes.INTEGER();
  1721. options.includeIgnoreAttributes = false;
  1722. // No limit, offset or order for the options max be given to count()
  1723. // Set them to null to prevent scopes setting those values
  1724. options.limit = null;
  1725. options.offset = null;
  1726. options.order = null;
  1727. return await this.aggregate(col, 'count', options);
  1728. }
  1729. /**
  1730. * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for paging
  1731. *
  1732. * @example
  1733. * const result = await Model.findAndCountAll({
  1734. * where: ...,
  1735. * limit: 12,
  1736. * offset: 12
  1737. * });
  1738. *
  1739. * # In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return the total number of rows that matched your query.
  1740. *
  1741. * # When you add includes, only those which are required (either because they have a where clause, or because `required` is explicitly set to true on the include) will be added to the count part.
  1742. *
  1743. * # Suppose you want to find all users who have a profile attached:
  1744. *
  1745. * User.findAndCountAll({
  1746. * include: [
  1747. * { model: Profile, required: true}
  1748. * ],
  1749. * limit: 3
  1750. * });
  1751. *
  1752. * # Because the include for `Profile` has `required` set it will result in an inner join, and only the users who have a profile will be counted. If we remove `required` from the include, both users with and without profiles will be counted
  1753. *
  1754. * @param {object} [options] See findAll options
  1755. *
  1756. * @see
  1757. * {@link Model.findAll} for a specification of find and query options
  1758. * @see
  1759. * {@link Model.count} for a specification of count options
  1760. *
  1761. * @returns {Promise<{count: number, rows: Model[]}>}
  1762. */
  1763. static async findAndCountAll(options) {
  1764. if (options !== undefined && !_.isPlainObject(options)) {
  1765. throw new Error('The argument passed to findAndCountAll must be an options object, use findByPk if you wish to pass a single primary key value');
  1766. }
  1767. const countOptions = Utils.cloneDeep(options);
  1768. if (countOptions.attributes) {
  1769. countOptions.attributes = undefined;
  1770. }
  1771. const [count, rows] = await Promise.all([
  1772. this.count(countOptions),
  1773. this.findAll(options)
  1774. ]);
  1775. return {
  1776. count,
  1777. rows: count === 0 ? [] : rows
  1778. };
  1779. }
  1780. /**
  1781. * Find the maximum value of field
  1782. *
  1783. * @param {string} field attribute / field name
  1784. * @param {object} [options] See aggregate
  1785. *
  1786. * @see
  1787. * {@link Model.aggregate} for options
  1788. *
  1789. * @returns {Promise<*>}
  1790. */
  1791. static async max(field, options) {
  1792. return await this.aggregate(field, 'max', options);
  1793. }
  1794. /**
  1795. * Find the minimum value of field
  1796. *
  1797. * @param {string} field attribute / field name
  1798. * @param {object} [options] See aggregate
  1799. *
  1800. * @see
  1801. * {@link Model.aggregate} for options
  1802. *
  1803. * @returns {Promise<*>}
  1804. */
  1805. static async min(field, options) {
  1806. return await this.aggregate(field, 'min', options);
  1807. }
  1808. /**
  1809. * Find the sum of field
  1810. *
  1811. * @param {string} field attribute / field name
  1812. * @param {object} [options] See aggregate
  1813. *
  1814. * @see
  1815. * {@link Model.aggregate} for options
  1816. *
  1817. * @returns {Promise<number>}
  1818. */
  1819. static async sum(field, options) {
  1820. return await this.aggregate(field, 'sum', options);
  1821. }
  1822. /**
  1823. * Builds a new model instance.
  1824. *
  1825. * @param {object|Array} values An object of key value pairs or an array of such. If an array, the function will return an array of instances.
  1826. * @param {object} [options] Instance build options
  1827. * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
  1828. * @param {boolean} [options.isNewRecord=true] Is this new record
  1829. * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
  1830. *
  1831. * @returns {Model|Array<Model>}
  1832. */
  1833. static build(values, options) {
  1834. if (Array.isArray(values)) {
  1835. return this.bulkBuild(values, options);
  1836. }
  1837. return new this(values, options);
  1838. }
  1839. static bulkBuild(valueSets, options) {
  1840. options = { isNewRecord: true, ...options };
  1841. if (!options.includeValidated) {
  1842. this._conformIncludes(options, this);
  1843. if (options.include) {
  1844. this._expandIncludeAll(options);
  1845. this._validateIncludedElements(options);
  1846. }
  1847. }
  1848. if (options.attributes) {
  1849. options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute);
  1850. }
  1851. return valueSets.map(values => this.build(values, options));
  1852. }
  1853. /**
  1854. * Builds a new model instance and calls save on it.
  1855. *
  1856. * @see
  1857. * {@link Model.build}
  1858. * @see
  1859. * {@link Model.save}
  1860. *
  1861. * @param {object} values Hash of data values to create new record with
  1862. * @param {object} [options] Build and query options
  1863. * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
  1864. * @param {boolean} [options.isNewRecord=true] Is this new record
  1865. * @param {Array} [options.include] An array of include options - Used to build prefetched/included model instances. See `set`
  1866. * @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
  1867. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  1868. * @param {boolean} [options.validate=true] If false, validations won't be run.
  1869. * @param {boolean} [options.hooks=true] Run before and after create / update + validate hooks
  1870. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1871. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1872. * @param {Transaction} [options.transaction] Transaction to run query under
  1873. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1874. * @param {boolean|Array} [options.returning=true] Appends RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only)
  1875. *
  1876. * @returns {Promise<Model>}
  1877. *
  1878. */
  1879. static async create(values, options) {
  1880. options = Utils.cloneDeep(options || {});
  1881. return await this.build(values, {
  1882. isNewRecord: true,
  1883. attributes: options.fields,
  1884. include: options.include,
  1885. raw: options.raw,
  1886. silent: options.silent
  1887. }).save(options);
  1888. }
  1889. /**
  1890. * Find a row that matches the query, or build (but don't save) the row if none is found.
  1891. * The successful result of the promise will be (instance, built)
  1892. *
  1893. * @param {object} options find options
  1894. * @param {object} options.where A hash of search attributes. If `where` is a plain object it will be appended with defaults to build a new instance.
  1895. * @param {object} [options.defaults] Default values to use if building a new instance
  1896. * @param {object} [options.transaction] Transaction to run query under
  1897. *
  1898. * @returns {Promise<Model,boolean>}
  1899. */
  1900. static async findOrBuild(options) {
  1901. if (!options || !options.where || arguments.length > 1) {
  1902. throw new Error(
  1903. 'Missing where attribute in the options parameter passed to findOrBuild. ' +
  1904. 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)'
  1905. );
  1906. }
  1907. let values;
  1908. let instance = await this.findOne(options);
  1909. if (instance === null) {
  1910. values = { ...options.defaults };
  1911. if (_.isPlainObject(options.where)) {
  1912. values = Utils.defaults(values, options.where);
  1913. }
  1914. instance = this.build(values, options);
  1915. return [instance, true];
  1916. }
  1917. return [instance, false];
  1918. }
  1919. /**
  1920. * Find a row that matches the query, or build and save the row if none is found
  1921. * The successful result of the promise will be (instance, created)
  1922. *
  1923. * If no transaction is passed in the `options` object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call.
  1924. * However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has committed. In this case, an instance of sequelize. TimeoutError will be thrown instead.
  1925. * If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.
  1926. *
  1927. * @see
  1928. * {@link Model.findAll} for a full specification of find and options
  1929. *
  1930. * @param {object} options find and create options
  1931. * @param {object} options.where where A hash of search attributes. If `where` is a plain object it will be appended with defaults to build a new instance.
  1932. * @param {object} [options.defaults] Default values to use if creating a new instance
  1933. * @param {Transaction} [options.transaction] Transaction to run query under
  1934. *
  1935. * @returns {Promise<Model,boolean>}
  1936. */
  1937. static async findOrCreate(options) {
  1938. if (!options || !options.where || arguments.length > 1) {
  1939. throw new Error(
  1940. 'Missing where attribute in the options parameter passed to findOrCreate. ' +
  1941. 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)'
  1942. );
  1943. }
  1944. options = { ...options };
  1945. if (options.defaults) {
  1946. const defaults = Object.keys(options.defaults);
  1947. const unknownDefaults = defaults.filter(name => !this.rawAttributes[name]);
  1948. if (unknownDefaults.length) {
  1949. logger.warn(`Unknown attributes (${unknownDefaults}) passed to defaults option of findOrCreate`);
  1950. }
  1951. }
  1952. if (options.transaction === undefined && this.sequelize.constructor._cls) {
  1953. const t = this.sequelize.constructor._cls.get('transaction');
  1954. if (t) {
  1955. options.transaction = t;
  1956. }
  1957. }
  1958. const internalTransaction = !options.transaction;
  1959. let values;
  1960. let transaction;
  1961. try {
  1962. const t = await this.sequelize.transaction(options);
  1963. transaction = t;
  1964. options.transaction = t;
  1965. const found = await this.findOne(Utils.defaults({ transaction }, options));
  1966. if (found !== null) {
  1967. return [found, false];
  1968. }
  1969. values = { ...options.defaults };
  1970. if (_.isPlainObject(options.where)) {
  1971. values = Utils.defaults(values, options.where);
  1972. }
  1973. options.exception = true;
  1974. options.returning = true;
  1975. try {
  1976. const created = await this.create(values, options);
  1977. if (created.get(this.primaryKeyAttribute, { raw: true }) === null) {
  1978. // If the query returned an empty result for the primary key, we know that this was actually a unique constraint violation
  1979. throw new sequelizeErrors.UniqueConstraintError();
  1980. }
  1981. return [created, true];
  1982. } catch (err) {
  1983. if (!(err instanceof sequelizeErrors.UniqueConstraintError)) throw err;
  1984. const flattenedWhere = Utils.flattenObjectDeep(options.where);
  1985. const flattenedWhereKeys = Object.keys(flattenedWhere).map(name => _.last(name.split('.')));
  1986. const whereFields = flattenedWhereKeys.map(name => _.get(this.rawAttributes, `${name}.field`, name));
  1987. const defaultFields = options.defaults && Object.keys(options.defaults)
  1988. .filter(name => this.rawAttributes[name])
  1989. .map(name => this.rawAttributes[name].field || name);
  1990. const errFieldKeys = Object.keys(err.fields);
  1991. const errFieldsWhereIntersects = Utils.intersects(errFieldKeys, whereFields);
  1992. if (defaultFields && !errFieldsWhereIntersects && Utils.intersects(errFieldKeys, defaultFields)) {
  1993. throw err;
  1994. }
  1995. if (errFieldsWhereIntersects) {
  1996. _.each(err.fields, (value, key) => {
  1997. const name = this.fieldRawAttributesMap[key].fieldName;
  1998. if (value.toString() !== options.where[name].toString()) {
  1999. throw new Error(`${this.name}#findOrCreate: value used for ${name} was not equal for both the find and the create calls, '${options.where[name]}' vs '${value}'`);
  2000. }
  2001. });
  2002. }
  2003. // Someone must have created a matching instance inside the same transaction since we last did a find. Let's find it!
  2004. const otherCreated = await this.findOne(Utils.defaults({
  2005. transaction: internalTransaction ? null : transaction
  2006. }, options));
  2007. // Sanity check, ideally we caught this at the defaultFeilds/err.fields check
  2008. // But if we didn't and instance is null, we will throw
  2009. if (otherCreated === null) throw err;
  2010. return [otherCreated, false];
  2011. }
  2012. } finally {
  2013. if (internalTransaction && transaction) {
  2014. await transaction.commit();
  2015. }
  2016. }
  2017. }
  2018. /**
  2019. * A more performant findOrCreate that will not work under a transaction (at least not in postgres)
  2020. * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
  2021. *
  2022. * @see
  2023. * {@link Model.findAll} for a full specification of find and options
  2024. *
  2025. * @param {object} options find options
  2026. * @param {object} options.where A hash of search attributes. If `where` is a plain object it will be appended with defaults to build a new instance.
  2027. * @param {object} [options.defaults] Default values to use if creating a new instance
  2028. *
  2029. * @returns {Promise<Model,boolean>}
  2030. */
  2031. static async findCreateFind(options) {
  2032. if (!options || !options.where) {
  2033. throw new Error(
  2034. 'Missing where attribute in the options parameter passed to findCreateFind.'
  2035. );
  2036. }
  2037. let values = { ...options.defaults };
  2038. if (_.isPlainObject(options.where)) {
  2039. values = Utils.defaults(values, options.where);
  2040. }
  2041. const found = await this.findOne(options);
  2042. if (found) return [found, false];
  2043. try {
  2044. const created = await this.create(values, options);
  2045. return [created, true];
  2046. } catch (err) {
  2047. if (!(err instanceof sequelizeErrors.UniqueConstraintError)) throw err;
  2048. const foundAgain = await this.findOne(options);
  2049. return [foundAgain, false];
  2050. }
  2051. }
  2052. /**
  2053. * Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
  2054. *
  2055. * **Implementation details:**
  2056. *
  2057. * * MySQL - Implemented with ON DUPLICATE KEY UPDATE`
  2058. * * PostgreSQL - Implemented with ON CONFLICT DO UPDATE. If update data contains PK field, then PK is selected as the default conflict key. Otherwise first unique constraint/index will be selected, which can satisfy conflict key requirements.
  2059. * * SQLite - Implemented with ON CONFLICT DO UPDATE
  2060. * * MSSQL - Implemented as a single query using `MERGE` and `WHEN (NOT) MATCHED THEN`
  2061. *
  2062. * **Note** that Postgres/SQLite returns null for created, no matter if the row was created or updated
  2063. *
  2064. * @param {object} values hash of values to upsert
  2065. * @param {object} [options] upsert options
  2066. * @param {boolean} [options.validate=true] Run validations before the row is inserted
  2067. * @param {Array} [options.fields=Object.keys(this.attributes)] The fields to insert / update. Defaults to all changed fields
  2068. * @param {boolean} [options.hooks=true] Run before / after upsert hooks?
  2069. * @param {boolean} [options.returning=true] If true, fetches back auto generated values
  2070. * @param {Transaction} [options.transaction] Transaction to run query under
  2071. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2072. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2073. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2074. *
  2075. * @returns {Promise<Model,boolean | null>} returns record and whether row was created or updated as boolean. For Postgres/SQLite dialects boolean value is always null`.
  2076. */
  2077. static async upsert(values, options) {
  2078. options = {
  2079. hooks: true,
  2080. returning: true,
  2081. validate: true,
  2082. ...Utils.cloneDeep(options)
  2083. };
  2084. const createdAtAttr = this._timestampAttributes.createdAt;
  2085. const updatedAtAttr = this._timestampAttributes.updatedAt;
  2086. const hasPrimary = this.primaryKeyField in values || this.primaryKeyAttribute in values;
  2087. const instance = this.build(values);
  2088. options.model = this;
  2089. options.instance = instance;
  2090. const changed = Array.from(instance._changed);
  2091. if (!options.fields) {
  2092. options.fields = changed;
  2093. }
  2094. if (options.validate) {
  2095. await instance.validate(options);
  2096. }
  2097. // Map field names
  2098. const updatedDataValues = _.pick(instance.dataValues, changed);
  2099. const insertValues = Utils.mapValueFieldNames(instance.dataValues, Object.keys(instance.rawAttributes), this);
  2100. const updateValues = Utils.mapValueFieldNames(updatedDataValues, options.fields, this);
  2101. const now = Utils.now(this.sequelize.options.dialect);
  2102. // Attach createdAt
  2103. if (createdAtAttr && !updateValues[createdAtAttr]) {
  2104. const field = this.rawAttributes[createdAtAttr].field || createdAtAttr;
  2105. insertValues[field] = this._getDefaultTimestamp(createdAtAttr) || now;
  2106. }
  2107. if (updatedAtAttr && !insertValues[updatedAtAttr]) {
  2108. const field = this.rawAttributes[updatedAtAttr].field || updatedAtAttr;
  2109. insertValues[field] = updateValues[field] = this._getDefaultTimestamp(updatedAtAttr) || now;
  2110. }
  2111. // Build adds a null value for the primary key, if none was given by the user.
  2112. // We need to remove that because of some Postgres technicalities.
  2113. if (!hasPrimary && this.primaryKeyAttribute && !this.rawAttributes[this.primaryKeyAttribute].defaultValue) {
  2114. delete insertValues[this.primaryKeyField];
  2115. delete updateValues[this.primaryKeyField];
  2116. }
  2117. if (options.hooks) {
  2118. await this.runHooks('beforeUpsert', values, options);
  2119. }
  2120. const result = await this.queryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), options);
  2121. if (options.hooks) {
  2122. await this.runHooks('afterUpsert', result, options);
  2123. return result;
  2124. }
  2125. return result;
  2126. }
  2127. /**
  2128. * Create and insert multiple instances in bulk.
  2129. *
  2130. * The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. This is because MySQL
  2131. * and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records.
  2132. * To obtain Instances for the newly created values, you will need to query for them again.
  2133. *
  2134. * If validation fails, the promise is rejected with an array-like AggregateError
  2135. *
  2136. * @param {Array} records List of objects (key/value pairs) to create instances from
  2137. * @param {object} [options] Bulk create options
  2138. * @param {Array} [options.fields] Fields to insert (defaults to all fields)
  2139. * @param {boolean} [options.validate=false] Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
  2140. * @param {boolean} [options.hooks=true] Run before / after bulk create hooks?
  2141. * @param {boolean} [options.individualHooks=false] Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.
  2142. * @param {boolean} [options.ignoreDuplicates=false] Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5)
  2143. * @param {Array} [options.updateOnDuplicate] Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5). By default, all fields are updated.
  2144. * @param {Transaction} [options.transaction] Transaction to run query under
  2145. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2146. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2147. * @param {boolean|Array} [options.returning=false] If true, append RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only)
  2148. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2149. *
  2150. * @returns {Promise<Array<Model>>}
  2151. */
  2152. static async bulkCreate(records, options = {}) {
  2153. if (!records.length) {
  2154. return [];
  2155. }
  2156. const dialect = this.sequelize.options.dialect;
  2157. const now = Utils.now(this.sequelize.options.dialect);
  2158. options.model = this;
  2159. if (!options.includeValidated) {
  2160. this._conformIncludes(options, this);
  2161. if (options.include) {
  2162. this._expandIncludeAll(options);
  2163. this._validateIncludedElements(options);
  2164. }
  2165. }
  2166. const instances = records.map(values => this.build(values, { isNewRecord: true, include: options.include }));
  2167. const recursiveBulkCreate = async (instances, options) => {
  2168. options = {
  2169. validate: false,
  2170. hooks: true,
  2171. individualHooks: false,
  2172. ignoreDuplicates: false,
  2173. ...options
  2174. };
  2175. if (options.returning === undefined) {
  2176. if (options.association) {
  2177. options.returning = false;
  2178. } else {
  2179. options.returning = true;
  2180. }
  2181. }
  2182. if (options.ignoreDuplicates && ['mssql'].includes(dialect)) {
  2183. throw new Error(`${dialect} does not support the ignoreDuplicates option.`);
  2184. }
  2185. if (options.updateOnDuplicate && (dialect !== 'mysql' && dialect !== 'mariadb' && dialect !== 'sqlite' && dialect !== 'postgres')) {
  2186. throw new Error(`${dialect} does not support the updateOnDuplicate option.`);
  2187. }
  2188. const model = options.model;
  2189. options.fields = options.fields || Object.keys(model.rawAttributes);
  2190. const createdAtAttr = model._timestampAttributes.createdAt;
  2191. const updatedAtAttr = model._timestampAttributes.updatedAt;
  2192. if (options.updateOnDuplicate !== undefined) {
  2193. if (Array.isArray(options.updateOnDuplicate) && options.updateOnDuplicate.length) {
  2194. options.updateOnDuplicate = _.intersection(
  2195. _.without(Object.keys(model.tableAttributes), createdAtAttr),
  2196. options.updateOnDuplicate
  2197. );
  2198. } else {
  2199. throw new Error('updateOnDuplicate option only supports non-empty array.');
  2200. }
  2201. }
  2202. // Run before hook
  2203. if (options.hooks) {
  2204. await model.runHooks('beforeBulkCreate', instances, options);
  2205. }
  2206. // Validate
  2207. if (options.validate) {
  2208. const errors = [];
  2209. const validateOptions = { ...options };
  2210. validateOptions.hooks = options.individualHooks;
  2211. await Promise.all(instances.map(async instance => {
  2212. try {
  2213. await instance.validate(validateOptions);
  2214. } catch (err) {
  2215. errors.push(new sequelizeErrors.BulkRecordError(err, instance));
  2216. }
  2217. }));
  2218. delete options.skip;
  2219. if (errors.length) {
  2220. throw new sequelizeErrors.AggregateError(errors);
  2221. }
  2222. }
  2223. if (options.individualHooks) {
  2224. await Promise.all(instances.map(async instance => {
  2225. const individualOptions = {
  2226. ...options,
  2227. validate: false,
  2228. hooks: true
  2229. };
  2230. delete individualOptions.fields;
  2231. delete individualOptions.individualHooks;
  2232. delete individualOptions.ignoreDuplicates;
  2233. await instance.save(individualOptions);
  2234. }));
  2235. } else {
  2236. if (options.include && options.include.length) {
  2237. await Promise.all(options.include.filter(include => include.association instanceof BelongsTo).map(async include => {
  2238. const associationInstances = [];
  2239. const associationInstanceIndexToInstanceMap = [];
  2240. for (const instance of instances) {
  2241. const associationInstance = instance.get(include.as);
  2242. if (associationInstance) {
  2243. associationInstances.push(associationInstance);
  2244. associationInstanceIndexToInstanceMap.push(instance);
  2245. }
  2246. }
  2247. if (!associationInstances.length) {
  2248. return;
  2249. }
  2250. const includeOptions = _(Utils.cloneDeep(include))
  2251. .omit(['association'])
  2252. .defaults({
  2253. transaction: options.transaction,
  2254. logging: options.logging
  2255. }).value();
  2256. const createdAssociationInstances = await recursiveBulkCreate(associationInstances, includeOptions);
  2257. for (const idx in createdAssociationInstances) {
  2258. const associationInstance = createdAssociationInstances[idx];
  2259. const instance = associationInstanceIndexToInstanceMap[idx];
  2260. await include.association.set(instance, associationInstance, { save: false, logging: options.logging });
  2261. }
  2262. }));
  2263. }
  2264. // Create all in one query
  2265. // Recreate records from instances to represent any changes made in hooks or validation
  2266. records = instances.map(instance => {
  2267. const values = instance.dataValues;
  2268. // set createdAt/updatedAt attributes
  2269. if (createdAtAttr && !values[createdAtAttr]) {
  2270. values[createdAtAttr] = now;
  2271. if (!options.fields.includes(createdAtAttr)) {
  2272. options.fields.push(createdAtAttr);
  2273. }
  2274. }
  2275. if (updatedAtAttr && !values[updatedAtAttr]) {
  2276. values[updatedAtAttr] = now;
  2277. if (!options.fields.includes(updatedAtAttr)) {
  2278. options.fields.push(updatedAtAttr);
  2279. }
  2280. }
  2281. const out = Utils.mapValueFieldNames(values, options.fields, model);
  2282. for (const key of model._virtualAttributes) {
  2283. delete out[key];
  2284. }
  2285. return out;
  2286. });
  2287. // Map attributes to fields for serial identification
  2288. const fieldMappedAttributes = {};
  2289. for (const attr in model.tableAttributes) {
  2290. fieldMappedAttributes[model.rawAttributes[attr].field || attr] = model.rawAttributes[attr];
  2291. }
  2292. // Map updateOnDuplicate attributes to fields
  2293. if (options.updateOnDuplicate) {
  2294. options.updateOnDuplicate = options.updateOnDuplicate.map(attr => model.rawAttributes[attr].field || attr);
  2295. // Get primary keys for postgres to enable updateOnDuplicate
  2296. options.upsertKeys = _.chain(model.primaryKeys).values().map('field').value();
  2297. if (Object.keys(model.uniqueKeys).length > 0) {
  2298. options.upsertKeys = _.chain(model.uniqueKeys).values().filter(c => c.fields.length >= 1).map(c => c.fields).reduce(c => c[0]).value();
  2299. }
  2300. }
  2301. // Map returning attributes to fields
  2302. if (options.returning && Array.isArray(options.returning)) {
  2303. options.returning = options.returning.map(attr => _.get(model.rawAttributes[attr], 'field', attr));
  2304. }
  2305. const results = await model.queryInterface.bulkInsert(model.getTableName(options), records, options, fieldMappedAttributes);
  2306. if (Array.isArray(results)) {
  2307. results.forEach((result, i) => {
  2308. const instance = instances[i];
  2309. for (const key in result) {
  2310. if (!instance || key === model.primaryKeyAttribute &&
  2311. instance.get(model.primaryKeyAttribute) &&
  2312. ['mysql', 'mariadb', 'sqlite'].includes(dialect)) {
  2313. // The query.js for these DBs is blind, it autoincrements the
  2314. // primarykey value, even if it was set manually. Also, it can
  2315. // return more results than instances, bug?.
  2316. continue;
  2317. }
  2318. if (Object.prototype.hasOwnProperty.call(result, key)) {
  2319. const record = result[key];
  2320. const attr = _.find(model.rawAttributes, attribute => attribute.fieldName === key || attribute.field === key);
  2321. instance.dataValues[attr && attr.fieldName || key] = record;
  2322. }
  2323. }
  2324. });
  2325. }
  2326. }
  2327. if (options.include && options.include.length) {
  2328. await Promise.all(options.include.filter(include => !(include.association instanceof BelongsTo ||
  2329. include.parent && include.parent.association instanceof BelongsToMany)).map(async include => {
  2330. const associationInstances = [];
  2331. const associationInstanceIndexToInstanceMap = [];
  2332. for (const instance of instances) {
  2333. let associated = instance.get(include.as);
  2334. if (!Array.isArray(associated)) associated = [associated];
  2335. for (const associationInstance of associated) {
  2336. if (associationInstance) {
  2337. if (!(include.association instanceof BelongsToMany)) {
  2338. associationInstance.set(include.association.foreignKey, instance.get(include.association.sourceKey || instance.constructor.primaryKeyAttribute, { raw: true }), { raw: true });
  2339. Object.assign(associationInstance, include.association.scope);
  2340. }
  2341. associationInstances.push(associationInstance);
  2342. associationInstanceIndexToInstanceMap.push(instance);
  2343. }
  2344. }
  2345. }
  2346. if (!associationInstances.length) {
  2347. return;
  2348. }
  2349. const includeOptions = _(Utils.cloneDeep(include))
  2350. .omit(['association'])
  2351. .defaults({
  2352. transaction: options.transaction,
  2353. logging: options.logging
  2354. }).value();
  2355. const createdAssociationInstances = await recursiveBulkCreate(associationInstances, includeOptions);
  2356. if (include.association instanceof BelongsToMany) {
  2357. const valueSets = [];
  2358. for (const idx in createdAssociationInstances) {
  2359. const associationInstance = createdAssociationInstances[idx];
  2360. const instance = associationInstanceIndexToInstanceMap[idx];
  2361. const values = {
  2362. [include.association.foreignKey]: instance.get(instance.constructor.primaryKeyAttribute, { raw: true }),
  2363. [include.association.otherKey]: associationInstance.get(associationInstance.constructor.primaryKeyAttribute, { raw: true }),
  2364. // Include values defined in the association
  2365. ...include.association.through.scope
  2366. };
  2367. if (associationInstance[include.association.through.model.name]) {
  2368. for (const attr of Object.keys(include.association.through.model.rawAttributes)) {
  2369. if (include.association.through.model.rawAttributes[attr]._autoGenerated ||
  2370. attr === include.association.foreignKey ||
  2371. attr === include.association.otherKey ||
  2372. typeof associationInstance[include.association.through.model.name][attr] === undefined) {
  2373. continue;
  2374. }
  2375. values[attr] = associationInstance[include.association.through.model.name][attr];
  2376. }
  2377. }
  2378. valueSets.push(values);
  2379. }
  2380. const throughOptions = _(Utils.cloneDeep(include))
  2381. .omit(['association', 'attributes'])
  2382. .defaults({
  2383. transaction: options.transaction,
  2384. logging: options.logging
  2385. }).value();
  2386. throughOptions.model = include.association.throughModel;
  2387. const throughInstances = include.association.throughModel.bulkBuild(valueSets, throughOptions);
  2388. await recursiveBulkCreate(throughInstances, throughOptions);
  2389. }
  2390. }));
  2391. }
  2392. // map fields back to attributes
  2393. instances.forEach(instance => {
  2394. for (const attr in model.rawAttributes) {
  2395. if (model.rawAttributes[attr].field &&
  2396. instance.dataValues[model.rawAttributes[attr].field] !== undefined &&
  2397. model.rawAttributes[attr].field !== attr
  2398. ) {
  2399. instance.dataValues[attr] = instance.dataValues[model.rawAttributes[attr].field];
  2400. delete instance.dataValues[model.rawAttributes[attr].field];
  2401. }
  2402. instance._previousDataValues[attr] = instance.dataValues[attr];
  2403. instance.changed(attr, false);
  2404. }
  2405. instance.isNewRecord = false;
  2406. });
  2407. // Run after hook
  2408. if (options.hooks) {
  2409. await model.runHooks('afterBulkCreate', instances, options);
  2410. }
  2411. return instances;
  2412. };
  2413. return await recursiveBulkCreate(instances, options);
  2414. }
  2415. /**
  2416. * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
  2417. *
  2418. * @param {object} [options] The options passed to Model.destroy in addition to truncate
  2419. * @param {boolean|Function} [options.cascade = false] Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.
  2420. * @param {boolean} [options.restartIdentity=false] Automatically restart sequences owned by columns of the truncated table.
  2421. * @param {Transaction} [options.transaction] Transaction to run query under
  2422. * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
  2423. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2424. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2425. *
  2426. * @returns {Promise}
  2427. *
  2428. * @see
  2429. * {@link Model.destroy} for more information
  2430. */
  2431. static async truncate(options) {
  2432. options = Utils.cloneDeep(options) || {};
  2433. options.truncate = true;
  2434. return await this.destroy(options);
  2435. }
  2436. /**
  2437. * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
  2438. *
  2439. * @param {object} options destroy options
  2440. * @param {object} [options.where] Filter the destroy
  2441. * @param {boolean} [options.hooks=true] Run before / after bulk destroy hooks?
  2442. * @param {boolean} [options.individualHooks=false] If set to true, destroy will SELECT all records matching the where parameter and will execute before / after destroy hooks on each row
  2443. * @param {number} [options.limit] How many rows to delete
  2444. * @param {boolean} [options.force=false] Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
  2445. * @param {boolean} [options.truncate=false] If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored
  2446. * @param {boolean} [options.cascade=false] Only used in conjunction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.
  2447. * @param {boolean} [options.restartIdentity=false] Only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table.
  2448. * @param {Transaction} [options.transaction] Transaction to run query under
  2449. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2450. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2451. *
  2452. * @returns {Promise<number>} The number of destroyed rows
  2453. */
  2454. static async destroy(options) {
  2455. options = Utils.cloneDeep(options);
  2456. this._injectScope(options);
  2457. if (!options || !(options.where || options.truncate)) {
  2458. throw new Error('Missing where or truncate attribute in the options parameter of model.destroy.');
  2459. }
  2460. if (!options.truncate && !_.isPlainObject(options.where) && !Array.isArray(options.where) && !(options.where instanceof Utils.SequelizeMethod)) {
  2461. throw new Error('Expected plain object, array or sequelize method in the options.where parameter of model.destroy.');
  2462. }
  2463. options = _.defaults(options, {
  2464. hooks: true,
  2465. individualHooks: false,
  2466. force: false,
  2467. cascade: false,
  2468. restartIdentity: false
  2469. });
  2470. options.type = QueryTypes.BULKDELETE;
  2471. Utils.mapOptionFieldNames(options, this);
  2472. options.model = this;
  2473. // Run before hook
  2474. if (options.hooks) {
  2475. await this.runHooks('beforeBulkDestroy', options);
  2476. }
  2477. let instances;
  2478. // Get daos and run beforeDestroy hook on each record individually
  2479. if (options.individualHooks) {
  2480. instances = await this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark });
  2481. await Promise.all(instances.map(instance => this.runHooks('beforeDestroy', instance, options)));
  2482. }
  2483. let result;
  2484. // Run delete query (or update if paranoid)
  2485. if (this._timestampAttributes.deletedAt && !options.force) {
  2486. // Set query type appropriately when running soft delete
  2487. options.type = QueryTypes.BULKUPDATE;
  2488. const attrValueHash = {};
  2489. const deletedAtAttribute = this.rawAttributes[this._timestampAttributes.deletedAt];
  2490. const field = this.rawAttributes[this._timestampAttributes.deletedAt].field;
  2491. const where = {
  2492. [field]: Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null
  2493. };
  2494. attrValueHash[field] = Utils.now(this.sequelize.options.dialect);
  2495. result = await this.queryInterface.bulkUpdate(this.getTableName(options), attrValueHash, Object.assign(where, options.where), options, this.rawAttributes);
  2496. } else {
  2497. result = await this.queryInterface.bulkDelete(this.getTableName(options), options.where, options, this);
  2498. }
  2499. // Run afterDestroy hook on each record individually
  2500. if (options.individualHooks) {
  2501. await Promise.all(
  2502. instances.map(instance => this.runHooks('afterDestroy', instance, options))
  2503. );
  2504. }
  2505. // Run after hook
  2506. if (options.hooks) {
  2507. await this.runHooks('afterBulkDestroy', options);
  2508. }
  2509. return result;
  2510. }
  2511. /**
  2512. * Restore multiple instances if `paranoid` is enabled.
  2513. *
  2514. * @param {object} options restore options
  2515. * @param {object} [options.where] Filter the restore
  2516. * @param {boolean} [options.hooks=true] Run before / after bulk restore hooks?
  2517. * @param {boolean} [options.individualHooks=false] If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row
  2518. * @param {number} [options.limit] How many rows to undelete (only for mysql)
  2519. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2520. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2521. * @param {Transaction} [options.transaction] Transaction to run query under
  2522. *
  2523. * @returns {Promise}
  2524. */
  2525. static async restore(options) {
  2526. if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
  2527. options = {
  2528. hooks: true,
  2529. individualHooks: false,
  2530. ...options
  2531. };
  2532. options.type = QueryTypes.RAW;
  2533. options.model = this;
  2534. Utils.mapOptionFieldNames(options, this);
  2535. // Run before hook
  2536. if (options.hooks) {
  2537. await this.runHooks('beforeBulkRestore', options);
  2538. }
  2539. let instances;
  2540. // Get daos and run beforeRestore hook on each record individually
  2541. if (options.individualHooks) {
  2542. instances = await this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark, paranoid: false });
  2543. await Promise.all(instances.map(instance => this.runHooks('beforeRestore', instance, options)));
  2544. }
  2545. // Run undelete query
  2546. const attrValueHash = {};
  2547. const deletedAtCol = this._timestampAttributes.deletedAt;
  2548. const deletedAtAttribute = this.rawAttributes[deletedAtCol];
  2549. const deletedAtDefaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null;
  2550. attrValueHash[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
  2551. options.omitNull = false;
  2552. const result = await this.queryInterface.bulkUpdate(this.getTableName(options), attrValueHash, options.where, options, this.rawAttributes);
  2553. // Run afterDestroy hook on each record individually
  2554. if (options.individualHooks) {
  2555. await Promise.all(
  2556. instances.map(instance => this.runHooks('afterRestore', instance, options))
  2557. );
  2558. }
  2559. // Run after hook
  2560. if (options.hooks) {
  2561. await this.runHooks('afterBulkRestore', options);
  2562. }
  2563. return result;
  2564. }
  2565. /**
  2566. * Update multiple instances that match the where options.
  2567. *
  2568. * @param {object} values hash of values to update
  2569. * @param {object} options update options
  2570. * @param {object} options.where Options to describe the scope of the search.
  2571. * @param {boolean} [options.paranoid=true] If true, only non-deleted records will be updated. If false, both deleted and non-deleted records will be updated. Only applies if `options.paranoid` is true for the model.
  2572. * @param {Array} [options.fields] Fields to update (defaults to all fields)
  2573. * @param {boolean} [options.validate=true] Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
  2574. * @param {boolean} [options.hooks=true] Run before / after bulk update hooks?
  2575. * @param {boolean} [options.sideEffects=true] Whether or not to update the side effects of any virtual setters.
  2576. * @param {boolean} [options.individualHooks=false] Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs. A select is needed, because the row data needs to be passed to the hooks
  2577. * @param {boolean|Array} [options.returning=false] If true, append RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only)
  2578. * @param {number} [options.limit] How many rows to update (only for mysql and mariadb, implemented as TOP(n) for MSSQL; for sqlite it is supported only when rowid is present)
  2579. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2580. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2581. * @param {Transaction} [options.transaction] Transaction to run query under
  2582. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  2583. *
  2584. * @returns {Promise<Array<number,number>>} The promise returns an array with one or two elements. The first element is always the number
  2585. * of affected rows, while the second element is the actual affected rows (only supported in postgres with `options.returning` true).
  2586. *
  2587. */
  2588. static async update(values, options) {
  2589. options = Utils.cloneDeep(options);
  2590. this._injectScope(options);
  2591. this._optionsMustContainWhere(options);
  2592. options = this._paranoidClause(this, _.defaults(options, {
  2593. validate: true,
  2594. hooks: true,
  2595. individualHooks: false,
  2596. returning: false,
  2597. force: false,
  2598. sideEffects: true
  2599. }));
  2600. options.type = QueryTypes.BULKUPDATE;
  2601. // Clone values so it doesn't get modified for caller scope and ignore undefined values
  2602. values = _.omitBy(values, value => value === undefined);
  2603. // Remove values that are not in the options.fields
  2604. if (options.fields && options.fields instanceof Array) {
  2605. for (const key of Object.keys(values)) {
  2606. if (!options.fields.includes(key)) {
  2607. delete values[key];
  2608. }
  2609. }
  2610. } else {
  2611. const updatedAtAttr = this._timestampAttributes.updatedAt;
  2612. options.fields = _.intersection(Object.keys(values), Object.keys(this.tableAttributes));
  2613. if (updatedAtAttr && !options.fields.includes(updatedAtAttr)) {
  2614. options.fields.push(updatedAtAttr);
  2615. }
  2616. }
  2617. if (this._timestampAttributes.updatedAt && !options.silent) {
  2618. values[this._timestampAttributes.updatedAt] = this._getDefaultTimestamp(this._timestampAttributes.updatedAt) || Utils.now(this.sequelize.options.dialect);
  2619. }
  2620. options.model = this;
  2621. let valuesUse;
  2622. // Validate
  2623. if (options.validate) {
  2624. const build = this.build(values);
  2625. build.set(this._timestampAttributes.updatedAt, values[this._timestampAttributes.updatedAt], { raw: true });
  2626. if (options.sideEffects) {
  2627. Object.assign(values, _.pick(build.get(), build.changed()));
  2628. options.fields = _.union(options.fields, Object.keys(values));
  2629. }
  2630. // We want to skip validations for all other fields
  2631. options.skip = _.difference(Object.keys(this.rawAttributes), Object.keys(values));
  2632. const attributes = await build.validate(options);
  2633. options.skip = undefined;
  2634. if (attributes && attributes.dataValues) {
  2635. values = _.pick(attributes.dataValues, Object.keys(values));
  2636. }
  2637. }
  2638. // Run before hook
  2639. if (options.hooks) {
  2640. options.attributes = values;
  2641. await this.runHooks('beforeBulkUpdate', options);
  2642. values = options.attributes;
  2643. delete options.attributes;
  2644. }
  2645. valuesUse = values;
  2646. // Get instances and run beforeUpdate hook on each record individually
  2647. let instances;
  2648. let updateDoneRowByRow = false;
  2649. if (options.individualHooks) {
  2650. instances = await this.findAll({
  2651. where: options.where,
  2652. transaction: options.transaction,
  2653. logging: options.logging,
  2654. benchmark: options.benchmark,
  2655. paranoid: options.paranoid
  2656. });
  2657. if (instances.length) {
  2658. // Run beforeUpdate hooks on each record and check whether beforeUpdate hook changes values uniformly
  2659. // i.e. whether they change values for each record in the same way
  2660. let changedValues;
  2661. let different = false;
  2662. instances = await Promise.all(instances.map(async instance => {
  2663. // Record updates in instances dataValues
  2664. Object.assign(instance.dataValues, values);
  2665. // Set the changed fields on the instance
  2666. _.forIn(valuesUse, (newValue, attr) => {
  2667. if (newValue !== instance._previousDataValues[attr]) {
  2668. instance.setDataValue(attr, newValue);
  2669. }
  2670. });
  2671. // Run beforeUpdate hook
  2672. await this.runHooks('beforeUpdate', instance, options);
  2673. if (!different) {
  2674. const thisChangedValues = {};
  2675. _.forIn(instance.dataValues, (newValue, attr) => {
  2676. if (newValue !== instance._previousDataValues[attr]) {
  2677. thisChangedValues[attr] = newValue;
  2678. }
  2679. });
  2680. if (!changedValues) {
  2681. changedValues = thisChangedValues;
  2682. } else {
  2683. different = !_.isEqual(changedValues, thisChangedValues);
  2684. }
  2685. }
  2686. return instance;
  2687. }));
  2688. if (!different) {
  2689. const keys = Object.keys(changedValues);
  2690. // Hooks do not change values or change them uniformly
  2691. if (keys.length) {
  2692. // Hooks change values - record changes in valuesUse so they are executed
  2693. valuesUse = changedValues;
  2694. options.fields = _.union(options.fields, keys);
  2695. }
  2696. } else {
  2697. instances = await Promise.all(instances.map(async instance => {
  2698. const individualOptions = {
  2699. ...options,
  2700. hooks: false,
  2701. validate: false
  2702. };
  2703. delete individualOptions.individualHooks;
  2704. return instance.save(individualOptions);
  2705. }));
  2706. updateDoneRowByRow = true;
  2707. }
  2708. }
  2709. }
  2710. let result;
  2711. if (updateDoneRowByRow) {
  2712. result = [instances.length, instances];
  2713. } else if (_.isEmpty(valuesUse)
  2714. || Object.keys(valuesUse).length === 1 && valuesUse[this._timestampAttributes.updatedAt]) {
  2715. // only updatedAt is being passed, then skip update
  2716. result = [0];
  2717. } else {
  2718. valuesUse = Utils.mapValueFieldNames(valuesUse, options.fields, this);
  2719. options = Utils.mapOptionFieldNames(options, this);
  2720. options.hasTrigger = this.options ? this.options.hasTrigger : false;
  2721. const affectedRows = await this.queryInterface.bulkUpdate(this.getTableName(options), valuesUse, options.where, options, this.tableAttributes);
  2722. if (options.returning) {
  2723. result = [affectedRows.length, affectedRows];
  2724. instances = affectedRows;
  2725. } else {
  2726. result = [affectedRows];
  2727. }
  2728. }
  2729. if (options.individualHooks) {
  2730. await Promise.all(instances.map(instance => this.runHooks('afterUpdate', instance, options)));
  2731. result[1] = instances;
  2732. }
  2733. // Run after hook
  2734. if (options.hooks) {
  2735. options.attributes = values;
  2736. await this.runHooks('afterBulkUpdate', options);
  2737. delete options.attributes;
  2738. }
  2739. return result;
  2740. }
  2741. /**
  2742. * Run a describe query on the table.
  2743. *
  2744. * @param {string} [schema] schema name to search table in
  2745. * @param {object} [options] query options
  2746. *
  2747. * @returns {Promise} hash of attributes and their types
  2748. */
  2749. static async describe(schema, options) {
  2750. return await this.queryInterface.describeTable(this.tableName, { schema: schema || this._schema || undefined, ...options });
  2751. }
  2752. static _getDefaultTimestamp(attr) {
  2753. if (!!this.rawAttributes[attr] && !!this.rawAttributes[attr].defaultValue) {
  2754. return Utils.toDefaultValue(this.rawAttributes[attr].defaultValue, this.sequelize.options.dialect);
  2755. }
  2756. return undefined;
  2757. }
  2758. static _expandAttributes(options) {
  2759. if (!_.isPlainObject(options.attributes)) {
  2760. return;
  2761. }
  2762. let attributes = Object.keys(this.rawAttributes);
  2763. if (options.attributes.exclude) {
  2764. attributes = attributes.filter(elem => !options.attributes.exclude.includes(elem));
  2765. }
  2766. if (options.attributes.include) {
  2767. attributes = attributes.concat(options.attributes.include);
  2768. }
  2769. options.attributes = attributes;
  2770. }
  2771. // Inject _scope into options.
  2772. static _injectScope(options) {
  2773. const scope = Utils.cloneDeep(this._scope);
  2774. this._defaultsOptions(options, scope);
  2775. }
  2776. static [Symbol.for('nodejs.util.inspect.custom')]() {
  2777. return this.name;
  2778. }
  2779. static hasAlias(alias) {
  2780. return Object.prototype.hasOwnProperty.call(this.associations, alias);
  2781. }
  2782. /**
  2783. * Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
  2784. * ``` SET column = column + X WHERE foo = 'bar' ``` query. To get the correct value after an increment into the Instance you should do a reload.
  2785. *
  2786. * @example <caption>increment number by 1</caption>
  2787. * Model.increment('number', { where: { foo: 'bar' });
  2788. *
  2789. * @example <caption>increment number and count by 2</caption>
  2790. * Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
  2791. *
  2792. * @example <caption>increment answer by 42, and decrement tries by 1</caption>
  2793. * // `by` is ignored, as each column has its own value
  2794. * Model.increment({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
  2795. *
  2796. * @see
  2797. * {@link Model#reload}
  2798. *
  2799. * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
  2800. * @param {object} options increment options
  2801. * @param {object} options.where conditions hash
  2802. * @param {number} [options.by=1] The number to increment by
  2803. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  2804. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2805. * @param {Transaction} [options.transaction] Transaction to run query under
  2806. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2807. *
  2808. * @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect
  2809. */
  2810. static async increment(fields, options) {
  2811. options = options || {};
  2812. if (typeof fields === 'string') fields = [fields];
  2813. if (Array.isArray(fields)) {
  2814. fields = fields.map(f => {
  2815. if (this.rawAttributes[f] && this.rawAttributes[f].field && this.rawAttributes[f].field !== f) {
  2816. return this.rawAttributes[f].field;
  2817. }
  2818. return f;
  2819. });
  2820. }
  2821. this._injectScope(options);
  2822. this._optionsMustContainWhere(options);
  2823. options = Utils.defaults({}, options, {
  2824. by: 1,
  2825. where: {},
  2826. increment: true
  2827. });
  2828. const isSubtraction = !options.increment;
  2829. Utils.mapOptionFieldNames(options, this);
  2830. const where = { ...options.where };
  2831. // A plain object whose keys are the fields to be incremented and whose values are
  2832. // the amounts to be incremented by.
  2833. let incrementAmountsByField = {};
  2834. if (Array.isArray(fields)) {
  2835. incrementAmountsByField = {};
  2836. for (const field of fields) {
  2837. incrementAmountsByField[field] = options.by;
  2838. }
  2839. } else {
  2840. // If the `fields` argument is not an array, then we assume it already has the
  2841. // form necessary to be placed directly in the `incrementAmountsByField` variable.
  2842. incrementAmountsByField = fields;
  2843. }
  2844. // If optimistic locking is enabled, we can take advantage that this is an
  2845. // increment/decrement operation and send it here as well. We put `-1` for
  2846. // decrementing because it will be subtracted, getting `-(-1)` which is `+1`
  2847. if (this._versionAttribute) {
  2848. incrementAmountsByField[this._versionAttribute] = isSubtraction ? -1 : 1;
  2849. }
  2850. const extraAttributesToBeUpdated = {};
  2851. const updatedAtAttr = this._timestampAttributes.updatedAt;
  2852. if (!options.silent && updatedAtAttr && !incrementAmountsByField[updatedAtAttr]) {
  2853. const attrName = this.rawAttributes[updatedAtAttr].field || updatedAtAttr;
  2854. extraAttributesToBeUpdated[attrName] = this._getDefaultTimestamp(updatedAtAttr) || Utils.now(this.sequelize.options.dialect);
  2855. }
  2856. const tableName = this.getTableName(options);
  2857. let affectedRows;
  2858. if (isSubtraction) {
  2859. affectedRows = await this.queryInterface.decrement(
  2860. this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options
  2861. );
  2862. } else {
  2863. affectedRows = await this.queryInterface.increment(
  2864. this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options
  2865. );
  2866. }
  2867. if (options.returning) {
  2868. return [affectedRows, affectedRows.length];
  2869. }
  2870. return [affectedRows];
  2871. }
  2872. /**
  2873. * Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
  2874. * ```sql SET column = column - X WHERE foo = 'bar'``` query. To get the correct value after a decrement into the Instance you should do a reload.
  2875. *
  2876. * @example <caption>decrement number by 1</caption>
  2877. * Model.decrement('number', { where: { foo: 'bar' });
  2878. *
  2879. * @example <caption>decrement number and count by 2</caption>
  2880. * Model.decrement(['number', 'count'], { by: 2, where: { foo: 'bar' } });
  2881. *
  2882. * @example <caption>decrement answer by 42, and decrement tries by -1</caption>
  2883. * // `by` is ignored, since each column has its own value
  2884. * Model.decrement({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
  2885. *
  2886. * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
  2887. * @param {object} options decrement options, similar to increment
  2888. *
  2889. * @see
  2890. * {@link Model.increment}
  2891. * @see
  2892. * {@link Model#reload}
  2893. * @since 4.36.0
  2894. *
  2895. * @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect
  2896. */
  2897. static async decrement(fields, options) {
  2898. return this.increment(fields, {
  2899. by: 1,
  2900. ...options,
  2901. increment: false
  2902. });
  2903. }
  2904. static _optionsMustContainWhere(options) {
  2905. assert(options && options.where, 'Missing where attribute in the options parameter');
  2906. assert(_.isPlainObject(options.where) || Array.isArray(options.where) || options.where instanceof Utils.SequelizeMethod,
  2907. 'Expected plain object, array or sequelize method in the options.where parameter');
  2908. }
  2909. /**
  2910. * Get an object representing the query for this instance, use with `options.where`
  2911. *
  2912. * @param {boolean} [checkVersion=false] include version attribute in where hash
  2913. *
  2914. * @returns {object}
  2915. */
  2916. where(checkVersion) {
  2917. const where = this.constructor.primaryKeyAttributes.reduce((result, attribute) => {
  2918. result[attribute] = this.get(attribute, { raw: true });
  2919. return result;
  2920. }, {});
  2921. if (_.size(where) === 0) {
  2922. return this.constructor.options.whereCollection;
  2923. }
  2924. const versionAttr = this.constructor._versionAttribute;
  2925. if (checkVersion && versionAttr) {
  2926. where[versionAttr] = this.get(versionAttr, { raw: true });
  2927. }
  2928. return Utils.mapWhereFieldNames(where, this.constructor);
  2929. }
  2930. toString() {
  2931. return `[object SequelizeInstance:${this.constructor.name}]`;
  2932. }
  2933. /**
  2934. * Get the value of the underlying data value
  2935. *
  2936. * @param {string} key key to look in instance data store
  2937. *
  2938. * @returns {any}
  2939. */
  2940. getDataValue(key) {
  2941. return this.dataValues[key];
  2942. }
  2943. /**
  2944. * Update the underlying data value
  2945. *
  2946. * @param {string} key key to set in instance data store
  2947. * @param {any} value new value for given key
  2948. *
  2949. */
  2950. setDataValue(key, value) {
  2951. const originalValue = this._previousDataValues[key];
  2952. if (!_.isEqual(value, originalValue)) {
  2953. this.changed(key, true);
  2954. }
  2955. this.dataValues[key] = value;
  2956. }
  2957. /**
  2958. * If no key is given, returns all values of the instance, also invoking virtual getters.
  2959. *
  2960. * If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
  2961. *
  2962. * @param {string} [key] key to get value of
  2963. * @param {object} [options] get options
  2964. * @param {boolean} [options.plain=false] If set to true, included instances will be returned as plain objects
  2965. * @param {boolean} [options.raw=false] If set to true, field and virtual setters will be ignored
  2966. *
  2967. * @returns {object|any}
  2968. */
  2969. get(key, options) {
  2970. if (options === undefined && typeof key === 'object') {
  2971. options = key;
  2972. key = undefined;
  2973. }
  2974. options = options || {};
  2975. if (key) {
  2976. if (Object.prototype.hasOwnProperty.call(this._customGetters, key) && !options.raw) {
  2977. return this._customGetters[key].call(this, key, options);
  2978. }
  2979. if (options.plain && this._options.include && this._options.includeNames.includes(key)) {
  2980. if (Array.isArray(this.dataValues[key])) {
  2981. return this.dataValues[key].map(instance => instance.get(options));
  2982. }
  2983. if (this.dataValues[key] instanceof Model) {
  2984. return this.dataValues[key].get(options);
  2985. }
  2986. return this.dataValues[key];
  2987. }
  2988. return this.dataValues[key];
  2989. }
  2990. if (
  2991. this._hasCustomGetters
  2992. || options.plain && this._options.include
  2993. || options.clone
  2994. ) {
  2995. const values = {};
  2996. let _key;
  2997. if (this._hasCustomGetters) {
  2998. for (_key in this._customGetters) {
  2999. if (
  3000. this._options.attributes
  3001. && !this._options.attributes.includes(_key)
  3002. ) {
  3003. continue;
  3004. }
  3005. if (Object.prototype.hasOwnProperty.call(this._customGetters, _key)) {
  3006. values[_key] = this.get(_key, options);
  3007. }
  3008. }
  3009. }
  3010. for (_key in this.dataValues) {
  3011. if (
  3012. !Object.prototype.hasOwnProperty.call(values, _key)
  3013. && Object.prototype.hasOwnProperty.call(this.dataValues, _key)
  3014. ) {
  3015. values[_key] = this.get(_key, options);
  3016. }
  3017. }
  3018. return values;
  3019. }
  3020. return this.dataValues;
  3021. }
  3022. /**
  3023. * Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`).
  3024. * In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function
  3025. * will be called instead. To bypass the setter, you can pass `raw: true` in the options object.
  3026. *
  3027. * If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be
  3028. * set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
  3029. *
  3030. * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
  3031. *
  3032. * Set can also be used to build instances for associations, if you have values for those.
  3033. * When using set with associations you need to make sure the property key matches the alias of the association
  3034. * while also making sure that the proper include options have been set (from .build() or .findOne())
  3035. *
  3036. * If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
  3037. *
  3038. * @see
  3039. * {@link Model.findAll} for more information about includes
  3040. *
  3041. * @param {string|object} key key to set, it can be string or object. When string it will set that key, for object it will loop over all object properties nd set them.
  3042. * @param {any} value value to set
  3043. * @param {object} [options] set options
  3044. * @param {boolean} [options.raw=false] If set to true, field and virtual setters will be ignored
  3045. * @param {boolean} [options.reset=false] Clear all previously set data values
  3046. *
  3047. * @returns {Model}
  3048. */
  3049. set(key, value, options) {
  3050. let values;
  3051. let originalValue;
  3052. if (typeof key === 'object' && key !== null) {
  3053. values = key;
  3054. options = value || {};
  3055. if (options.reset) {
  3056. this.dataValues = {};
  3057. for (const key in values) {
  3058. this.changed(key, false);
  3059. }
  3060. }
  3061. // If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object
  3062. if (options.raw && !(this._options && this._options.include) && !(options && options.attributes) && !this.constructor._hasDateAttributes && !this.constructor._hasBooleanAttributes) {
  3063. if (Object.keys(this.dataValues).length) {
  3064. Object.assign(this.dataValues, values);
  3065. } else {
  3066. this.dataValues = values;
  3067. }
  3068. // If raw, .changed() shouldn't be true
  3069. this._previousDataValues = { ...this.dataValues };
  3070. } else {
  3071. // Loop and call set
  3072. if (options.attributes) {
  3073. const setKeys = data => {
  3074. for (const k of data) {
  3075. if (values[k] === undefined) {
  3076. continue;
  3077. }
  3078. this.set(k, values[k], options);
  3079. }
  3080. };
  3081. setKeys(options.attributes);
  3082. if (this.constructor._hasVirtualAttributes) {
  3083. setKeys(this.constructor._virtualAttributes);
  3084. }
  3085. if (this._options.includeNames) {
  3086. setKeys(this._options.includeNames);
  3087. }
  3088. } else {
  3089. for (const key in values) {
  3090. this.set(key, values[key], options);
  3091. }
  3092. }
  3093. if (options.raw) {
  3094. // If raw, .changed() shouldn't be true
  3095. this._previousDataValues = { ...this.dataValues };
  3096. }
  3097. }
  3098. return this;
  3099. }
  3100. if (!options)
  3101. options = {};
  3102. if (!options.raw) {
  3103. originalValue = this.dataValues[key];
  3104. }
  3105. // If not raw, and there's a custom setter
  3106. if (!options.raw && this._customSetters[key]) {
  3107. this._customSetters[key].call(this, value, key);
  3108. // custom setter should have changed value, get that changed value
  3109. // TODO: v5 make setters return new value instead of changing internal store
  3110. const newValue = this.dataValues[key];
  3111. if (!_.isEqual(newValue, originalValue)) {
  3112. this._previousDataValues[key] = originalValue;
  3113. this.changed(key, true);
  3114. }
  3115. } else {
  3116. // Check if we have included models, and if this key matches the include model names/aliases
  3117. if (this._options && this._options.include && this._options.includeNames.includes(key)) {
  3118. // Pass it on to the include handler
  3119. this._setInclude(key, value, options);
  3120. return this;
  3121. }
  3122. // Bunch of stuff we won't do when it's raw
  3123. if (!options.raw) {
  3124. // If attribute is not in model definition, return
  3125. if (!this._isAttribute(key)) {
  3126. if (key.includes('.') && this.constructor._jsonAttributes.has(key.split('.')[0])) {
  3127. const previousNestedValue = Dottie.get(this.dataValues, key);
  3128. if (!_.isEqual(previousNestedValue, value)) {
  3129. Dottie.set(this.dataValues, key, value);
  3130. this.changed(key.split('.')[0], true);
  3131. }
  3132. }
  3133. return this;
  3134. }
  3135. // If attempting to set primary key and primary key is already defined, return
  3136. if (this.constructor._hasPrimaryKeys && originalValue && this.constructor._isPrimaryKey(key)) {
  3137. return this;
  3138. }
  3139. // If attempting to set read only attributes, return
  3140. if (!this.isNewRecord && this.constructor._hasReadOnlyAttributes && this.constructor._readOnlyAttributes.has(key)) {
  3141. return this;
  3142. }
  3143. }
  3144. // If there's a data type sanitizer
  3145. if (
  3146. !(value instanceof Utils.SequelizeMethod)
  3147. && Object.prototype.hasOwnProperty.call(this.constructor._dataTypeSanitizers, key)
  3148. ) {
  3149. value = this.constructor._dataTypeSanitizers[key].call(this, value, options);
  3150. }
  3151. // Set when the value has changed and not raw
  3152. if (
  3153. !options.raw &&
  3154. (
  3155. // True when sequelize method
  3156. (value instanceof Utils.SequelizeMethod ||
  3157. // Check for data type type comparators
  3158. !(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) || // Check default
  3159. !this.constructor._dataTypeChanges[key] && !_.isEqual(value, originalValue))
  3160. )
  3161. ) {
  3162. this._previousDataValues[key] = originalValue;
  3163. this.changed(key, true);
  3164. }
  3165. // set data value
  3166. this.dataValues[key] = value;
  3167. }
  3168. return this;
  3169. }
  3170. setAttributes(updates) {
  3171. return this.set(updates);
  3172. }
  3173. /**
  3174. * If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`.
  3175. *
  3176. * If changed is called without an argument, it will return an array of keys that have changed.
  3177. *
  3178. * If changed is called without an argument and no keys have changed, it will return `false`.
  3179. *
  3180. * Please note that this function will return `false` when a property from a nested (for example JSON) property
  3181. * was edited manually, you must call `changed('key', true)` manually in these cases.
  3182. * Writing an entirely new object (eg. deep cloned) will be detected.
  3183. *
  3184. * @example
  3185. * ```
  3186. * const mdl = await MyModel.findOne();
  3187. * mdl.myJsonField.a = 1;
  3188. * console.log(mdl.changed()) => false
  3189. * mdl.save(); // this will not save anything
  3190. * mdl.changed('myJsonField', true);
  3191. * console.log(mdl.changed()) => ['myJsonField']
  3192. * mdl.save(); // will save
  3193. * ```
  3194. *
  3195. * @param {string} [key] key to check or change status of
  3196. * @param {any} [value] value to set
  3197. *
  3198. * @returns {boolean|Array}
  3199. */
  3200. changed(key, value) {
  3201. if (key === undefined) {
  3202. if (this._changed.size > 0) {
  3203. return Array.from(this._changed);
  3204. }
  3205. return false;
  3206. }
  3207. if (value === true) {
  3208. this._changed.add(key);
  3209. return this;
  3210. }
  3211. if (value === false) {
  3212. this._changed.delete(key);
  3213. return this;
  3214. }
  3215. return this._changed.has(key);
  3216. }
  3217. /**
  3218. * Returns the previous value for key from `_previousDataValues`.
  3219. *
  3220. * If called without a key, returns the previous values for all values which have changed
  3221. *
  3222. * @param {string} [key] key to get previous value of
  3223. *
  3224. * @returns {any|Array<any>}
  3225. */
  3226. previous(key) {
  3227. if (key) {
  3228. return this._previousDataValues[key];
  3229. }
  3230. return _.pickBy(this._previousDataValues, (value, key) => this.changed(key));
  3231. }
  3232. _setInclude(key, value, options) {
  3233. if (!Array.isArray(value)) value = [value];
  3234. if (value[0] instanceof Model) {
  3235. value = value.map(instance => instance.dataValues);
  3236. }
  3237. const include = this._options.includeMap[key];
  3238. const association = include.association;
  3239. const accessor = key;
  3240. const primaryKeyAttribute = include.model.primaryKeyAttribute;
  3241. const childOptions = {
  3242. isNewRecord: this.isNewRecord,
  3243. include: include.include,
  3244. includeNames: include.includeNames,
  3245. includeMap: include.includeMap,
  3246. includeValidated: true,
  3247. raw: options.raw,
  3248. attributes: include.originalAttributes
  3249. };
  3250. let isEmpty;
  3251. if (include.originalAttributes === undefined || include.originalAttributes.length) {
  3252. if (association.isSingleAssociation) {
  3253. if (Array.isArray(value)) {
  3254. value = value[0];
  3255. }
  3256. isEmpty = value && value[primaryKeyAttribute] === null || value === null;
  3257. this[accessor] = this.dataValues[accessor] = isEmpty ? null : include.model.build(value, childOptions);
  3258. } else {
  3259. isEmpty = value[0] && value[0][primaryKeyAttribute] === null;
  3260. this[accessor] = this.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
  3261. }
  3262. }
  3263. }
  3264. /**
  3265. * Validates this instance, and if the validation passes, persists it to the database.
  3266. *
  3267. * Returns a Promise that resolves to the saved instance (or rejects with a `Sequelize.ValidationError`, which will have a property for each of the fields for which the validation failed, with the error message for that field).
  3268. *
  3269. * This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed.
  3270. *
  3271. * This method is not aware of eager loaded associations. In other words, if some other model instance (child) was eager loaded with this instance (parent), and you change something in the child, calling `save()` will simply ignore the change that happened on the child.
  3272. *
  3273. * @param {object} [options] save options
  3274. * @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
  3275. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  3276. * @param {boolean} [options.validate=true] If false, validations won't be run.
  3277. * @param {boolean} [options.hooks=true] Run before and after create / update + validate hooks
  3278. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3279. * @param {Transaction} [options.transaction] Transaction to run query under
  3280. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3281. * @param {boolean} [options.returning] Append RETURNING * to get back auto generated values (Postgres only)
  3282. *
  3283. * @returns {Promise<Model>}
  3284. */
  3285. async save(options) {
  3286. if (arguments.length > 1) {
  3287. throw new Error('The second argument was removed in favor of the options object.');
  3288. }
  3289. options = Utils.cloneDeep(options);
  3290. options = _.defaults(options, {
  3291. hooks: true,
  3292. validate: true
  3293. });
  3294. if (!options.fields) {
  3295. if (this.isNewRecord) {
  3296. options.fields = Object.keys(this.constructor.rawAttributes);
  3297. } else {
  3298. options.fields = _.intersection(this.changed(), Object.keys(this.constructor.rawAttributes));
  3299. }
  3300. options.defaultFields = options.fields;
  3301. }
  3302. if (options.returning === undefined) {
  3303. if (options.association) {
  3304. options.returning = false;
  3305. } else if (this.isNewRecord) {
  3306. options.returning = true;
  3307. }
  3308. }
  3309. const primaryKeyName = this.constructor.primaryKeyAttribute;
  3310. const primaryKeyAttribute = primaryKeyName && this.constructor.rawAttributes[primaryKeyName];
  3311. const createdAtAttr = this.constructor._timestampAttributes.createdAt;
  3312. const versionAttr = this.constructor._versionAttribute;
  3313. const hook = this.isNewRecord ? 'Create' : 'Update';
  3314. const wasNewRecord = this.isNewRecord;
  3315. const now = Utils.now(this.sequelize.options.dialect);
  3316. let updatedAtAttr = this.constructor._timestampAttributes.updatedAt;
  3317. if (updatedAtAttr && options.fields.length >= 1 && !options.fields.includes(updatedAtAttr)) {
  3318. options.fields.push(updatedAtAttr);
  3319. }
  3320. if (versionAttr && options.fields.length >= 1 && !options.fields.includes(versionAttr)) {
  3321. options.fields.push(versionAttr);
  3322. }
  3323. if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, { raw: true }))) {
  3324. // UpdateAtAttr might have been added as a result of Object.keys(Model.rawAttributes). In that case we have to remove it again
  3325. _.remove(options.fields, val => val === updatedAtAttr);
  3326. updatedAtAttr = false;
  3327. }
  3328. if (this.isNewRecord === true) {
  3329. if (createdAtAttr && !options.fields.includes(createdAtAttr)) {
  3330. options.fields.push(createdAtAttr);
  3331. }
  3332. if (primaryKeyAttribute && primaryKeyAttribute.defaultValue && !options.fields.includes(primaryKeyName)) {
  3333. options.fields.unshift(primaryKeyName);
  3334. }
  3335. }
  3336. if (this.isNewRecord === false) {
  3337. if (primaryKeyName && this.get(primaryKeyName, { raw: true }) === undefined) {
  3338. throw new Error('You attempted to save an instance with no primary key, this is not allowed since it would result in a global update');
  3339. }
  3340. }
  3341. if (updatedAtAttr && !options.silent && options.fields.includes(updatedAtAttr)) {
  3342. this.dataValues[updatedAtAttr] = this.constructor._getDefaultTimestamp(updatedAtAttr) || now;
  3343. }
  3344. if (this.isNewRecord && createdAtAttr && !this.dataValues[createdAtAttr]) {
  3345. this.dataValues[createdAtAttr] = this.constructor._getDefaultTimestamp(createdAtAttr) || now;
  3346. }
  3347. // Validate
  3348. if (options.validate) {
  3349. await this.validate(options);
  3350. }
  3351. // Run before hook
  3352. if (options.hooks) {
  3353. const beforeHookValues = _.pick(this.dataValues, options.fields);
  3354. let ignoreChanged = _.difference(this.changed(), options.fields); // In case of update where it's only supposed to update the passed values and the hook values
  3355. let hookChanged;
  3356. let afterHookValues;
  3357. if (updatedAtAttr && options.fields.includes(updatedAtAttr)) {
  3358. ignoreChanged = _.without(ignoreChanged, updatedAtAttr);
  3359. }
  3360. await this.constructor.runHooks(`before${hook}`, this, options);
  3361. if (options.defaultFields && !this.isNewRecord) {
  3362. afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));
  3363. hookChanged = [];
  3364. for (const key of Object.keys(afterHookValues)) {
  3365. if (afterHookValues[key] !== beforeHookValues[key]) {
  3366. hookChanged.push(key);
  3367. }
  3368. }
  3369. options.fields = _.uniq(options.fields.concat(hookChanged));
  3370. }
  3371. if (hookChanged) {
  3372. if (options.validate) {
  3373. // Validate again
  3374. options.skip = _.difference(Object.keys(this.constructor.rawAttributes), hookChanged);
  3375. await this.validate(options);
  3376. delete options.skip;
  3377. }
  3378. }
  3379. }
  3380. if (options.fields.length && this.isNewRecord && this._options.include && this._options.include.length) {
  3381. await Promise.all(this._options.include.filter(include => include.association instanceof BelongsTo).map(async include => {
  3382. const instance = this.get(include.as);
  3383. if (!instance) return;
  3384. const includeOptions = _(Utils.cloneDeep(include))
  3385. .omit(['association'])
  3386. .defaults({
  3387. transaction: options.transaction,
  3388. logging: options.logging,
  3389. parentRecord: this
  3390. }).value();
  3391. await instance.save(includeOptions);
  3392. await this[include.association.accessors.set](instance, { save: false, logging: options.logging });
  3393. }));
  3394. }
  3395. const realFields = options.fields.filter(field => !this.constructor._virtualAttributes.has(field));
  3396. if (!realFields.length) return this;
  3397. if (!this.changed() && !this.isNewRecord) return this;
  3398. const versionFieldName = _.get(this.constructor.rawAttributes[versionAttr], 'field') || versionAttr;
  3399. const values = Utils.mapValueFieldNames(this.dataValues, options.fields, this.constructor);
  3400. let query = null;
  3401. let args = [];
  3402. let where;
  3403. if (this.isNewRecord) {
  3404. query = 'insert';
  3405. args = [this, this.constructor.getTableName(options), values, options];
  3406. } else {
  3407. where = this.where(true);
  3408. if (versionAttr) {
  3409. values[versionFieldName] = parseInt(values[versionFieldName], 10) + 1;
  3410. }
  3411. query = 'update';
  3412. args = [this, this.constructor.getTableName(options), values, where, options];
  3413. }
  3414. const [result, rowsUpdated] = await this.constructor.queryInterface[query](...args);
  3415. if (versionAttr) {
  3416. // Check to see that a row was updated, otherwise it's an optimistic locking error.
  3417. if (rowsUpdated < 1) {
  3418. throw new sequelizeErrors.OptimisticLockError({
  3419. modelName: this.constructor.name,
  3420. values,
  3421. where
  3422. });
  3423. } else {
  3424. result.dataValues[versionAttr] = values[versionFieldName];
  3425. }
  3426. }
  3427. // Transfer database generated values (defaults, autoincrement, etc)
  3428. for (const attr of Object.keys(this.constructor.rawAttributes)) {
  3429. if (this.constructor.rawAttributes[attr].field &&
  3430. values[this.constructor.rawAttributes[attr].field] !== undefined &&
  3431. this.constructor.rawAttributes[attr].field !== attr
  3432. ) {
  3433. values[attr] = values[this.constructor.rawAttributes[attr].field];
  3434. delete values[this.constructor.rawAttributes[attr].field];
  3435. }
  3436. }
  3437. Object.assign(values, result.dataValues);
  3438. Object.assign(result.dataValues, values);
  3439. if (wasNewRecord && this._options.include && this._options.include.length) {
  3440. await Promise.all(
  3441. this._options.include.filter(include => !(include.association instanceof BelongsTo ||
  3442. include.parent && include.parent.association instanceof BelongsToMany)).map(async include => {
  3443. let instances = this.get(include.as);
  3444. if (!instances) return;
  3445. if (!Array.isArray(instances)) instances = [instances];
  3446. const includeOptions = _(Utils.cloneDeep(include))
  3447. .omit(['association'])
  3448. .defaults({
  3449. transaction: options.transaction,
  3450. logging: options.logging,
  3451. parentRecord: this
  3452. }).value();
  3453. // Instances will be updated in place so we can safely treat HasOne like a HasMany
  3454. await Promise.all(instances.map(async instance => {
  3455. if (include.association instanceof BelongsToMany) {
  3456. await instance.save(includeOptions);
  3457. const values0 = {
  3458. [include.association.foreignKey]: this.get(this.constructor.primaryKeyAttribute, { raw: true }),
  3459. [include.association.otherKey]: instance.get(instance.constructor.primaryKeyAttribute, { raw: true }),
  3460. // Include values defined in the association
  3461. ...include.association.through.scope
  3462. };
  3463. if (instance[include.association.through.model.name]) {
  3464. for (const attr of Object.keys(include.association.through.model.rawAttributes)) {
  3465. if (include.association.through.model.rawAttributes[attr]._autoGenerated ||
  3466. attr === include.association.foreignKey ||
  3467. attr === include.association.otherKey ||
  3468. typeof instance[include.association.through.model.name][attr] === undefined) {
  3469. continue;
  3470. }
  3471. values0[attr] = instance[include.association.through.model.name][attr];
  3472. }
  3473. }
  3474. await include.association.throughModel.create(values0, includeOptions);
  3475. } else {
  3476. instance.set(include.association.foreignKey, this.get(include.association.sourceKey || this.constructor.primaryKeyAttribute, { raw: true }), { raw: true });
  3477. Object.assign(instance, include.association.scope);
  3478. await instance.save(includeOptions);
  3479. }
  3480. }));
  3481. })
  3482. );
  3483. }
  3484. // Run after hook
  3485. if (options.hooks) {
  3486. await this.constructor.runHooks(`after${hook}`, result, options);
  3487. }
  3488. for (const field of options.fields) {
  3489. result._previousDataValues[field] = result.dataValues[field];
  3490. this.changed(field, false);
  3491. }
  3492. this.isNewRecord = false;
  3493. return result;
  3494. }
  3495. /**
  3496. * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
  3497. * This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
  3498. * all references to the Instance are updated with the new data and no new objects are created.
  3499. *
  3500. * @see
  3501. * {@link Model.findAll}
  3502. *
  3503. * @param {object} [options] Options that are passed on to `Model.find`
  3504. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3505. *
  3506. * @returns {Promise<Model>}
  3507. */
  3508. async reload(options) {
  3509. options = Utils.defaults({
  3510. where: this.where()
  3511. }, options, {
  3512. include: this._options.include || undefined
  3513. });
  3514. const reloaded = await this.constructor.findOne(options);
  3515. if (!reloaded) {
  3516. throw new sequelizeErrors.InstanceError(
  3517. 'Instance could not be reloaded because it does not exist anymore (find call returned null)'
  3518. );
  3519. }
  3520. // update the internal options of the instance
  3521. this._options = reloaded._options;
  3522. // re-set instance values
  3523. this.set(reloaded.dataValues, {
  3524. raw: true,
  3525. reset: true && !options.attributes
  3526. });
  3527. return this;
  3528. }
  3529. /**
  3530. * Validate the attributes of this instance according to validation rules set in the model definition.
  3531. *
  3532. * The promise fulfills if and only if validation successful; otherwise it rejects an Error instance containing { field name : [error msgs] } entries.
  3533. *
  3534. * @param {object} [options] Options that are passed to the validator
  3535. * @param {Array} [options.skip] An array of strings. All properties that are in this array will not be validated
  3536. * @param {Array} [options.fields] An array of strings. Only the properties that are in this array will be validated
  3537. * @param {boolean} [options.hooks=true] Run before and after validate hooks
  3538. *
  3539. * @returns {Promise}
  3540. */
  3541. async validate(options) {
  3542. return new InstanceValidator(this, options).validate();
  3543. }
  3544. /**
  3545. * This is the same as calling `set` and then calling `save` but it only saves the
  3546. * exact values passed to it, making it more atomic and safer.
  3547. *
  3548. * @see
  3549. * {@link Model#set}
  3550. * @see
  3551. * {@link Model#save}
  3552. *
  3553. * @param {object} values See `set`
  3554. * @param {object} options See `save`
  3555. *
  3556. * @returns {Promise<Model>}
  3557. */
  3558. async update(values, options) {
  3559. // Clone values so it doesn't get modified for caller scope and ignore undefined values
  3560. values = _.omitBy(values, value => value === undefined);
  3561. const changedBefore = this.changed() || [];
  3562. options = options || {};
  3563. if (Array.isArray(options)) options = { fields: options };
  3564. options = Utils.cloneDeep(options);
  3565. const setOptions = Utils.cloneDeep(options);
  3566. setOptions.attributes = options.fields;
  3567. this.set(values, setOptions);
  3568. // Now we need to figure out which fields were actually affected by the setter.
  3569. const sideEffects = _.without(this.changed(), ...changedBefore);
  3570. const fields = _.union(Object.keys(values), sideEffects);
  3571. if (!options.fields) {
  3572. options.fields = _.intersection(fields, this.changed());
  3573. options.defaultFields = options.fields;
  3574. }
  3575. return await this.save(options);
  3576. }
  3577. /**
  3578. * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.
  3579. *
  3580. * @param {object} [options={}] destroy options
  3581. * @param {boolean} [options.force=false] If set to true, paranoid models will actually be deleted
  3582. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3583. * @param {Transaction} [options.transaction] Transaction to run query under
  3584. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3585. *
  3586. * @returns {Promise}
  3587. */
  3588. async destroy(options) {
  3589. options = {
  3590. hooks: true,
  3591. force: false,
  3592. ...options
  3593. };
  3594. // Run before hook
  3595. if (options.hooks) {
  3596. await this.constructor.runHooks('beforeDestroy', this, options);
  3597. }
  3598. const where = this.where(true);
  3599. let result;
  3600. if (this.constructor._timestampAttributes.deletedAt && options.force === false) {
  3601. const attributeName = this.constructor._timestampAttributes.deletedAt;
  3602. const attribute = this.constructor.rawAttributes[attributeName];
  3603. const defaultValue = Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')
  3604. ? attribute.defaultValue
  3605. : null;
  3606. const currentValue = this.getDataValue(attributeName);
  3607. const undefinedOrNull = currentValue == null && defaultValue == null;
  3608. if (undefinedOrNull || _.isEqual(currentValue, defaultValue)) {
  3609. // only update timestamp if it wasn't already set
  3610. this.setDataValue(attributeName, new Date());
  3611. }
  3612. result = await this.save({ ...options, hooks: false });
  3613. } else {
  3614. result = await this.constructor.queryInterface.delete(this, this.constructor.getTableName(options), where, { type: QueryTypes.DELETE, limit: null, ...options });
  3615. }
  3616. // Run after hook
  3617. if (options.hooks) {
  3618. await this.constructor.runHooks('afterDestroy', this, options);
  3619. }
  3620. return result;
  3621. }
  3622. /**
  3623. * Helper method to determine if a instance is "soft deleted". This is
  3624. * particularly useful if the implementer renamed the `deletedAt` attribute
  3625. * to something different. This method requires `paranoid` to be enabled.
  3626. *
  3627. * @returns {boolean}
  3628. */
  3629. isSoftDeleted() {
  3630. if (!this.constructor._timestampAttributes.deletedAt) {
  3631. throw new Error('Model is not paranoid');
  3632. }
  3633. const deletedAtAttribute = this.constructor.rawAttributes[this.constructor._timestampAttributes.deletedAt];
  3634. const defaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null;
  3635. const deletedAt = this.get(this.constructor._timestampAttributes.deletedAt) || null;
  3636. const isSet = deletedAt !== defaultValue;
  3637. return isSet;
  3638. }
  3639. /**
  3640. * Restore the row corresponding to this instance. Only available for paranoid models.
  3641. *
  3642. * @param {object} [options={}] restore options
  3643. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3644. * @param {Transaction} [options.transaction] Transaction to run query under
  3645. *
  3646. * @returns {Promise}
  3647. */
  3648. async restore(options) {
  3649. if (!this.constructor._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
  3650. options = {
  3651. hooks: true,
  3652. force: false,
  3653. ...options
  3654. };
  3655. // Run before hook
  3656. if (options.hooks) {
  3657. await this.constructor.runHooks('beforeRestore', this, options);
  3658. }
  3659. const deletedAtCol = this.constructor._timestampAttributes.deletedAt;
  3660. const deletedAtAttribute = this.constructor.rawAttributes[deletedAtCol];
  3661. const deletedAtDefaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null;
  3662. this.setDataValue(deletedAtCol, deletedAtDefaultValue);
  3663. const result = await this.save({ ...options, hooks: false, omitNull: false });
  3664. // Run after hook
  3665. if (options.hooks) {
  3666. await this.constructor.runHooks('afterRestore', this, options);
  3667. return result;
  3668. }
  3669. return result;
  3670. }
  3671. /**
  3672. * Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
  3673. * ```sql
  3674. * SET column = column + X
  3675. * ```
  3676. * query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values.
  3677. *
  3678. * @example
  3679. * instance.increment('number') // increment number by 1
  3680. *
  3681. * instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
  3682. *
  3683. * // increment answer by 42, and tries by 1.
  3684. * // `by` is ignored, since each column has its own value
  3685. * instance.increment({ answer: 42, tries: 1}, { by: 2 })
  3686. *
  3687. * @see
  3688. * {@link Model#reload}
  3689. *
  3690. * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
  3691. * @param {object} [options] options
  3692. * @param {number} [options.by=1] The number to increment by
  3693. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  3694. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3695. * @param {Transaction} [options.transaction] Transaction to run query under
  3696. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3697. * @param {boolean} [options.returning=true] Append RETURNING * to get back auto generated values (Postgres only)
  3698. *
  3699. * @returns {Promise<Model>}
  3700. * @since 4.0.0
  3701. */
  3702. async increment(fields, options) {
  3703. const identifier = this.where();
  3704. options = Utils.cloneDeep(options);
  3705. options.where = { ...options.where, ...identifier };
  3706. options.instance = this;
  3707. await this.constructor.increment(fields, options);
  3708. return this;
  3709. }
  3710. /**
  3711. * Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
  3712. * ```sql
  3713. * SET column = column - X
  3714. * ```
  3715. * query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values.
  3716. *
  3717. * @example
  3718. * instance.decrement('number') // decrement number by 1
  3719. *
  3720. * instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
  3721. *
  3722. * // decrement answer by 42, and tries by 1.
  3723. * // `by` is ignored, since each column has its own value
  3724. * instance.decrement({ answer: 42, tries: 1}, { by: 2 })
  3725. *
  3726. * @see
  3727. * {@link Model#reload}
  3728. * @param {string|Array|object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given
  3729. * @param {object} [options] decrement options
  3730. * @param {number} [options.by=1] The number to decrement by
  3731. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  3732. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3733. * @param {Transaction} [options.transaction] Transaction to run query under
  3734. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3735. * @param {boolean} [options.returning=true] Append RETURNING * to get back auto generated values (Postgres only)
  3736. *
  3737. * @returns {Promise}
  3738. */
  3739. async decrement(fields, options) {
  3740. return this.increment(fields, {
  3741. by: 1,
  3742. ...options,
  3743. increment: false
  3744. });
  3745. }
  3746. /**
  3747. * Check whether this and `other` Instance refer to the same row
  3748. *
  3749. * @param {Model} other Other instance to compare against
  3750. *
  3751. * @returns {boolean}
  3752. */
  3753. equals(other) {
  3754. if (!other || !other.constructor) {
  3755. return false;
  3756. }
  3757. if (!(other instanceof this.constructor)) {
  3758. return false;
  3759. }
  3760. return this.constructor.primaryKeyAttributes.every(attribute => this.get(attribute, { raw: true }) === other.get(attribute, { raw: true }));
  3761. }
  3762. /**
  3763. * Check if this is equal to one of `others` by calling equals
  3764. *
  3765. * @param {Array<Model>} others An array of instances to check against
  3766. *
  3767. * @returns {boolean}
  3768. */
  3769. equalsOneOf(others) {
  3770. return others.some(other => this.equals(other));
  3771. }
  3772. setValidators(attribute, validators) {
  3773. this.validators[attribute] = validators;
  3774. }
  3775. /**
  3776. * Convert the instance to a JSON representation.
  3777. * Proxies to calling `get` with no keys.
  3778. * This means get all values gotten from the DB, and apply all custom getters.
  3779. *
  3780. * @see
  3781. * {@link Model#get}
  3782. *
  3783. * @returns {object}
  3784. */
  3785. toJSON() {
  3786. return _.cloneDeep(
  3787. this.get({
  3788. plain: true
  3789. })
  3790. );
  3791. }
  3792. /**
  3793. * Creates a 1:m association between this (the source) and the provided target.
  3794. * The foreign key is added on the target.
  3795. *
  3796. * @param {Model} target Target model
  3797. * @param {object} [options] hasMany association options
  3798. * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
  3799. * @param {string|object} [options.as] The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target
  3800. * @param {string|object} [options.foreignKey] The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
  3801. * @param {string} [options.sourceKey] The name of the field to use as the key for the association in the source table. Defaults to the primary key of the source table
  3802. * @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
  3803. * @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
  3804. * @param {string} [options.onUpdate='CASCADE'] Set `ON UPDATE`
  3805. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3806. *
  3807. * @returns {HasMany}
  3808. *
  3809. * @example
  3810. * User.hasMany(Profile) // This will add userId to the profile table
  3811. */
  3812. static hasMany(target, options) {} // eslint-disable-line
  3813. /**
  3814. * Create an N:M association with a join table. Defining `through` is required.
  3815. *
  3816. * @param {Model} target Target model
  3817. * @param {object} options belongsToMany association options
  3818. * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
  3819. * @param {Model|string|object} options.through The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.
  3820. * @param {Model} [options.through.model] The model used to join both sides of the N:M association.
  3821. * @param {object} [options.through.scope] A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model)
  3822. * @param {boolean} [options.through.unique=true] If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes)
  3823. * @param {string|object} [options.as] The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target
  3824. * @param {string|object} [options.foreignKey] The name of the foreign key in the join table (representing the source model) or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
  3825. * @param {string|object} [options.otherKey] The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target
  3826. * @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
  3827. * @param {boolean} [options.timestamps=sequelize.options.timestamps] Should the join model have timestamps
  3828. * @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m
  3829. * @param {string} [options.onUpdate='CASCADE'] Sets `ON UPDATE`
  3830. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3831. *
  3832. * @returns {BelongsToMany}
  3833. *
  3834. * @example
  3835. * // Automagically generated join model
  3836. * User.belongsToMany(Project, { through: 'UserProjects' })
  3837. * Project.belongsToMany(User, { through: 'UserProjects' })
  3838. *
  3839. * // Join model with additional attributes
  3840. * const UserProjects = sequelize.define('UserProjects', {
  3841. * started: Sequelize.BOOLEAN
  3842. * })
  3843. * User.belongsToMany(Project, { through: UserProjects })
  3844. * Project.belongsToMany(User, { through: UserProjects })
  3845. */
  3846. static belongsToMany(target, options) {} // eslint-disable-line
  3847. /**
  3848. * Creates an association between this (the source) and the provided target. The foreign key is added on the target.
  3849. *
  3850. * @param {Model} target Target model
  3851. * @param {object} [options] hasOne association options
  3852. * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
  3853. * @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target
  3854. * @param {string|object} [options.foreignKey] The name of the foreign key attribute in the target model or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source
  3855. * @param {string} [options.sourceKey] The name of the attribute to use as the key for the association in the source table. Defaults to the primary key of the source table
  3856. * @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
  3857. * @param {string} [options.onUpdate='CASCADE'] Sets 'ON UPDATE'
  3858. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3859. * @param {string} [options.uniqueKey] The custom name for unique constraint.
  3860. *
  3861. * @returns {HasOne}
  3862. *
  3863. * @example
  3864. * User.hasOne(Profile) // This will add userId to the profile table
  3865. */
  3866. static hasOne(target, options) {} // eslint-disable-line
  3867. /**
  3868. * Creates an association between this (the source) and the provided target. The foreign key is added on the source.
  3869. *
  3870. * @param {Model} target The target model
  3871. * @param {object} [options] belongsTo association options
  3872. * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
  3873. * @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target
  3874. * @param {string|object} [options.foreignKey] The name of the foreign key attribute in the source table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target
  3875. * @param {string} [options.targetKey] The name of the attribute to use as the key for the association in the target table. Defaults to the primary key of the target table
  3876. * @param {string} [options.onDelete='SET&nbsp;NULL|NO&nbsp;ACTION'] SET NULL if foreignKey allows nulls, NO ACTION if otherwise
  3877. * @param {string} [options.onUpdate='CASCADE'] Sets 'ON UPDATE'
  3878. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3879. *
  3880. * @returns {BelongsTo}
  3881. *
  3882. * @example
  3883. * Profile.belongsTo(User) // This will add userId to the profile table
  3884. */
  3885. static belongsTo(target, options) {} // eslint-disable-line
  3886. }
  3887. Object.assign(Model, associationsMixin);
  3888. Hooks.applyTo(Model, true);
  3889. module.exports = Model;