model.js 189 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476
  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. for (const key of ['createdAt', 'updatedAt', 'deletedAt']) {
  864. if (!['undefined', 'string', 'boolean'].includes(typeof this.options[key])) {
  865. throw new Error(`Value for "${key}" option must be a string or a boolean, got ${typeof this.options[key]}`);
  866. }
  867. if (this.options[key] === '') {
  868. throw new Error(`Value for "${key}" option cannot be an empty string`);
  869. }
  870. }
  871. if (this.options.createdAt !== false) {
  872. this._timestampAttributes.createdAt =
  873. typeof this.options.createdAt === 'string' ? this.options.createdAt : 'createdAt';
  874. this._readOnlyAttributes.add(this._timestampAttributes.createdAt);
  875. }
  876. if (this.options.updatedAt !== false) {
  877. this._timestampAttributes.updatedAt =
  878. typeof this.options.updatedAt === 'string' ? this.options.updatedAt : 'updatedAt';
  879. this._readOnlyAttributes.add(this._timestampAttributes.updatedAt);
  880. }
  881. if (this.options.paranoid && this.options.deletedAt !== false) {
  882. this._timestampAttributes.deletedAt =
  883. typeof this.options.deletedAt === 'string' ? this.options.deletedAt : 'deletedAt';
  884. this._readOnlyAttributes.add(this._timestampAttributes.deletedAt);
  885. }
  886. }
  887. // setup name for version attribute
  888. if (this.options.version) {
  889. this._versionAttribute = typeof this.options.version === 'string' ? this.options.version : 'version';
  890. this._readOnlyAttributes.add(this._versionAttribute);
  891. }
  892. this._hasReadOnlyAttributes = this._readOnlyAttributes.size > 0;
  893. // Add head and tail default attributes (id, timestamps)
  894. this._addDefaultAttributes();
  895. this.refreshAttributes();
  896. this._findAutoIncrementAttribute();
  897. this._scope = this.options.defaultScope;
  898. this._scopeNames = ['defaultScope'];
  899. this.sequelize.modelManager.addModel(this);
  900. this.sequelize.runHooks('afterDefine', this);
  901. return this;
  902. }
  903. static refreshAttributes() {
  904. const attributeManipulation = {};
  905. this.prototype._customGetters = {};
  906. this.prototype._customSetters = {};
  907. ['get', 'set'].forEach(type => {
  908. const opt = `${type}terMethods`;
  909. const funcs = { ...this.options[opt] };
  910. const _custom = type === 'get' ? this.prototype._customGetters : this.prototype._customSetters;
  911. _.each(funcs, (method, attribute) => {
  912. _custom[attribute] = method;
  913. if (type === 'get') {
  914. funcs[attribute] = function() {
  915. return this.get(attribute);
  916. };
  917. }
  918. if (type === 'set') {
  919. funcs[attribute] = function(value) {
  920. return this.set(attribute, value);
  921. };
  922. }
  923. });
  924. _.each(this.rawAttributes, (options, attribute) => {
  925. if (Object.prototype.hasOwnProperty.call(options, type)) {
  926. _custom[attribute] = options[type];
  927. }
  928. if (type === 'get') {
  929. funcs[attribute] = function() {
  930. return this.get(attribute);
  931. };
  932. }
  933. if (type === 'set') {
  934. funcs[attribute] = function(value) {
  935. return this.set(attribute, value);
  936. };
  937. }
  938. });
  939. _.each(funcs, (fct, name) => {
  940. if (!attributeManipulation[name]) {
  941. attributeManipulation[name] = {
  942. configurable: true
  943. };
  944. }
  945. attributeManipulation[name][type] = fct;
  946. });
  947. });
  948. this._dataTypeChanges = {};
  949. this._dataTypeSanitizers = {};
  950. this._hasBooleanAttributes = false;
  951. this._hasDateAttributes = false;
  952. this._jsonAttributes = new Set();
  953. this._virtualAttributes = new Set();
  954. this._defaultValues = {};
  955. this.prototype.validators = {};
  956. this.fieldRawAttributesMap = {};
  957. this.primaryKeys = {};
  958. this.uniqueKeys = {};
  959. _.each(this.rawAttributes, (definition, name) => {
  960. definition.type = this.sequelize.normalizeDataType(definition.type);
  961. definition.Model = this;
  962. definition.fieldName = name;
  963. definition._modelAttribute = true;
  964. if (definition.field === undefined) {
  965. definition.field = Utils.underscoredIf(name, this.underscored);
  966. }
  967. if (definition.primaryKey === true) {
  968. this.primaryKeys[name] = definition;
  969. }
  970. this.fieldRawAttributesMap[definition.field] = definition;
  971. if (definition.type._sanitize) {
  972. this._dataTypeSanitizers[name] = definition.type._sanitize;
  973. }
  974. if (definition.type._isChanged) {
  975. this._dataTypeChanges[name] = definition.type._isChanged;
  976. }
  977. if (definition.type instanceof DataTypes.BOOLEAN) {
  978. this._hasBooleanAttributes = true;
  979. } else if (definition.type instanceof DataTypes.DATE || definition.type instanceof DataTypes.DATEONLY) {
  980. this._hasDateAttributes = true;
  981. } else if (definition.type instanceof DataTypes.JSON) {
  982. this._jsonAttributes.add(name);
  983. } else if (definition.type instanceof DataTypes.VIRTUAL) {
  984. this._virtualAttributes.add(name);
  985. }
  986. if (Object.prototype.hasOwnProperty.call(definition, 'defaultValue')) {
  987. this._defaultValues[name] = () => Utils.toDefaultValue(definition.defaultValue, this.sequelize.options.dialect);
  988. }
  989. if (Object.prototype.hasOwnProperty.call(definition, 'unique') && definition.unique) {
  990. let idxName;
  991. if (
  992. typeof definition.unique === 'object' &&
  993. Object.prototype.hasOwnProperty.call(definition.unique, 'name')
  994. ) {
  995. idxName = definition.unique.name;
  996. } else if (typeof definition.unique === 'string') {
  997. idxName = definition.unique;
  998. } else {
  999. idxName = `${this.tableName}_${name}_unique`;
  1000. }
  1001. const idx = this.uniqueKeys[idxName] || { fields: [] };
  1002. idx.fields.push(definition.field);
  1003. idx.msg = idx.msg || definition.unique.msg || null;
  1004. idx.name = idxName || false;
  1005. idx.column = name;
  1006. idx.customIndex = definition.unique !== true;
  1007. this.uniqueKeys[idxName] = idx;
  1008. }
  1009. if (Object.prototype.hasOwnProperty.call(definition, 'validate')) {
  1010. this.prototype.validators[name] = definition.validate;
  1011. }
  1012. if (definition.index === true && definition.type instanceof DataTypes.JSONB) {
  1013. this._indexes.push(
  1014. Utils.nameIndex(
  1015. this._conformIndex({
  1016. fields: [definition.field || name],
  1017. using: 'gin'
  1018. }),
  1019. this.getTableName()
  1020. )
  1021. );
  1022. delete definition.index;
  1023. }
  1024. });
  1025. // Create a map of field to attribute names
  1026. this.fieldAttributeMap = _.reduce(this.fieldRawAttributesMap, (map, value, key) => {
  1027. if (key !== value.fieldName) {
  1028. map[key] = value.fieldName;
  1029. }
  1030. return map;
  1031. }, {});
  1032. this._hasJsonAttributes = !!this._jsonAttributes.size;
  1033. this._hasVirtualAttributes = !!this._virtualAttributes.size;
  1034. this._hasDefaultValues = !_.isEmpty(this._defaultValues);
  1035. this.tableAttributes = _.omitBy(this.rawAttributes, (_a, key) => this._virtualAttributes.has(key));
  1036. this.prototype._hasCustomGetters = Object.keys(this.prototype._customGetters).length;
  1037. this.prototype._hasCustomSetters = Object.keys(this.prototype._customSetters).length;
  1038. for (const key of Object.keys(attributeManipulation)) {
  1039. if (Object.prototype.hasOwnProperty.call(Model.prototype, key)) {
  1040. this.sequelize.log(`Not overriding built-in method from model attribute: ${key}`);
  1041. continue;
  1042. }
  1043. Object.defineProperty(this.prototype, key, attributeManipulation[key]);
  1044. }
  1045. this.prototype.rawAttributes = this.rawAttributes;
  1046. this.prototype._isAttribute = key => Object.prototype.hasOwnProperty.call(this.prototype.rawAttributes, key);
  1047. // Primary key convenience constiables
  1048. this.primaryKeyAttributes = Object.keys(this.primaryKeys);
  1049. this.primaryKeyAttribute = this.primaryKeyAttributes[0];
  1050. if (this.primaryKeyAttribute) {
  1051. this.primaryKeyField = this.rawAttributes[this.primaryKeyAttribute].field || this.primaryKeyAttribute;
  1052. }
  1053. this._hasPrimaryKeys = this.primaryKeyAttributes.length > 0;
  1054. this._isPrimaryKey = key => this.primaryKeyAttributes.includes(key);
  1055. }
  1056. /**
  1057. * Remove attribute from model definition
  1058. *
  1059. * @param {string} attribute name of attribute to remove
  1060. */
  1061. static removeAttribute(attribute) {
  1062. delete this.rawAttributes[attribute];
  1063. this.refreshAttributes();
  1064. }
  1065. /**
  1066. * Sync this Model to the DB, that is create the table.
  1067. *
  1068. * @param {object} [options] sync options
  1069. *
  1070. * @see
  1071. * {@link Sequelize#sync} for options
  1072. *
  1073. * @returns {Promise<Model>}
  1074. */
  1075. static async sync(options) {
  1076. options = { ...this.options, ...options };
  1077. options.hooks = options.hooks === undefined ? true : !!options.hooks;
  1078. const attributes = this.tableAttributes;
  1079. const rawAttributes = this.fieldRawAttributesMap;
  1080. if (options.hooks) {
  1081. await this.runHooks('beforeSync', options);
  1082. }
  1083. if (options.force) {
  1084. await this.drop(options);
  1085. }
  1086. const tableName = this.getTableName(options);
  1087. await this.queryInterface.createTable(tableName, attributes, options, this);
  1088. if (options.alter) {
  1089. const tableInfos = await Promise.all([
  1090. this.queryInterface.describeTable(tableName, options),
  1091. this.queryInterface.getForeignKeyReferencesForTable(tableName, options)
  1092. ]);
  1093. const columns = tableInfos[0];
  1094. // Use for alter foreign keys
  1095. const foreignKeyReferences = tableInfos[1];
  1096. const removedConstraints = {};
  1097. for (const columnName in attributes) {
  1098. if (!Object.prototype.hasOwnProperty.call(attributes, columnName)) continue;
  1099. if (!columns[columnName] && !columns[attributes[columnName].field]) {
  1100. await this.queryInterface.addColumn(tableName, attributes[columnName].field || columnName, attributes[columnName], options);
  1101. }
  1102. }
  1103. if (options.alter === true || typeof options.alter === 'object' && options.alter.drop !== false) {
  1104. for (const columnName in columns) {
  1105. if (!Object.prototype.hasOwnProperty.call(columns, columnName)) continue;
  1106. const currentAttribute = rawAttributes[columnName];
  1107. if (!currentAttribute) {
  1108. await this.queryInterface.removeColumn(tableName, columnName, options);
  1109. continue;
  1110. }
  1111. if (currentAttribute.primaryKey) continue;
  1112. // Check foreign keys. If it's a foreign key, it should remove constraint first.
  1113. const references = currentAttribute.references;
  1114. if (currentAttribute.references) {
  1115. const database = this.sequelize.config.database;
  1116. const schema = this.sequelize.config.schema;
  1117. // Find existed foreign keys
  1118. for (const foreignKeyReference of foreignKeyReferences) {
  1119. const constraintName = foreignKeyReference.constraintName;
  1120. if (!!constraintName
  1121. && foreignKeyReference.tableCatalog === database
  1122. && (schema ? foreignKeyReference.tableSchema === schema : true)
  1123. && foreignKeyReference.referencedTableName === references.model
  1124. && foreignKeyReference.referencedColumnName === references.key
  1125. && (schema ? foreignKeyReference.referencedTableSchema === schema : true)
  1126. && !removedConstraints[constraintName]) {
  1127. // Remove constraint on foreign keys.
  1128. await this.queryInterface.removeConstraint(tableName, constraintName, options);
  1129. removedConstraints[constraintName] = true;
  1130. }
  1131. }
  1132. }
  1133. await this.queryInterface.changeColumn(tableName, columnName, currentAttribute, options);
  1134. }
  1135. }
  1136. }
  1137. let indexes = await this.queryInterface.showIndex(tableName, options);
  1138. indexes = this._indexes.filter(item1 =>
  1139. !indexes.some(item2 => item1.name === item2.name)
  1140. ).sort((index1, index2) => {
  1141. if (this.sequelize.options.dialect === 'postgres') {
  1142. // move concurrent indexes to the bottom to avoid weird deadlocks
  1143. if (index1.concurrently === true) return 1;
  1144. if (index2.concurrently === true) return -1;
  1145. }
  1146. return 0;
  1147. });
  1148. for (const index of indexes) {
  1149. await this.queryInterface.addIndex(tableName, { ...options, ...index });
  1150. }
  1151. if (options.hooks) {
  1152. await this.runHooks('afterSync', options);
  1153. }
  1154. return this;
  1155. }
  1156. /**
  1157. * Drop the table represented by this Model
  1158. *
  1159. * @param {object} [options] drop options
  1160. * @param {boolean} [options.cascade=false] Also drop all objects depending on this table, such as views. Only works in postgres
  1161. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1162. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1163. *
  1164. * @returns {Promise}
  1165. */
  1166. static async drop(options) {
  1167. return await this.queryInterface.dropTable(this.getTableName(options), options);
  1168. }
  1169. static async dropSchema(schema) {
  1170. return await this.queryInterface.dropSchema(schema);
  1171. }
  1172. /**
  1173. * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - `"schema"."tableName"`,
  1174. * while the schema will be prepended to the table name for mysql and sqlite - `'schema.tablename'`.
  1175. *
  1176. * This method is intended for use cases where the same model is needed in multiple schemas. In such a use case it is important
  1177. * to call `model.schema(schema, [options]).sync()` for each model to ensure the models are created in the correct schema.
  1178. *
  1179. * If a single default schema per model is needed, set the `options.schema='schema'` parameter during the `define()` call
  1180. * for the model.
  1181. *
  1182. * @param {string} schema The name of the schema
  1183. * @param {object} [options] schema options
  1184. * @param {string} [options.schemaDelimiter='.'] The character(s) that separates the schema name from the table name
  1185. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1186. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1187. *
  1188. * @see
  1189. * {@link Sequelize#define} for more information about setting a default schema.
  1190. *
  1191. * @returns {Model}
  1192. */
  1193. static schema(schema, options) {
  1194. const clone = class extends this {};
  1195. Object.defineProperty(clone, 'name', { value: this.name });
  1196. clone._schema = schema;
  1197. if (options) {
  1198. if (typeof options === 'string') {
  1199. clone._schemaDelimiter = options;
  1200. } else if (options.schemaDelimiter) {
  1201. clone._schemaDelimiter = options.schemaDelimiter;
  1202. }
  1203. }
  1204. return clone;
  1205. }
  1206. /**
  1207. * 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,
  1208. * or an object with `tableName`, `schema` and `delimiter` properties.
  1209. *
  1210. * @returns {string|object}
  1211. */
  1212. static getTableName() {
  1213. return this.queryGenerator.addSchema(this);
  1214. }
  1215. /**
  1216. * Get un-scoped model
  1217. *
  1218. * @returns {Model}
  1219. */
  1220. static unscoped() {
  1221. return this.scope();
  1222. }
  1223. /**
  1224. * 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.
  1225. *
  1226. * 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.
  1227. *
  1228. * @param {string} name The name of the scope. Use `defaultScope` to override the default scope
  1229. * @param {object|Function} scope scope or options
  1230. * @param {object} [options] scope options
  1231. * @param {boolean} [options.override=false] override old scope if already defined
  1232. */
  1233. static addScope(name, scope, options) {
  1234. options = { override: false, ...options };
  1235. if ((name === 'defaultScope' && Object.keys(this.options.defaultScope).length > 0 || name in this.options.scopes) && options.override === false) {
  1236. throw new Error(`The scope ${name} already exists. Pass { override: true } as options to silence this error`);
  1237. }
  1238. if (name === 'defaultScope') {
  1239. this.options.defaultScope = this._scope = scope;
  1240. } else {
  1241. this.options.scopes[name] = scope;
  1242. }
  1243. }
  1244. /**
  1245. * Apply a scope created in `define` to the model.
  1246. *
  1247. * @example <caption>how to create scopes</caption>
  1248. * const Model = sequelize.define('model', attributes, {
  1249. * defaultScope: {
  1250. * where: {
  1251. * username: 'dan'
  1252. * },
  1253. * limit: 12
  1254. * },
  1255. * scopes: {
  1256. * isALie: {
  1257. * where: {
  1258. * stuff: 'cake'
  1259. * }
  1260. * },
  1261. * complexFunction: function(email, accessLevel) {
  1262. * return {
  1263. * where: {
  1264. * email: {
  1265. * [Op.like]: email
  1266. * },
  1267. * access_level {
  1268. * [Op.gte]: accessLevel
  1269. * }
  1270. * }
  1271. * }
  1272. * }
  1273. * }
  1274. * })
  1275. *
  1276. * # 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:
  1277. *
  1278. * Model.findAll() // WHERE username = 'dan'
  1279. * Model.findAll({ where: { age: { [Op.gt]: 12 } } }) // WHERE age > 12 AND username = 'dan'
  1280. *
  1281. * @example <caption>To invoke scope functions you can do</caption>
  1282. * Model.scope({ method: ['complexFunction', 'dan@sequelize.com', 42]}).findAll()
  1283. * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
  1284. *
  1285. * @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.
  1286. *
  1287. * @returns {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
  1288. */
  1289. static scope(option) {
  1290. const self = class extends this {};
  1291. let scope;
  1292. let scopeName;
  1293. Object.defineProperty(self, 'name', { value: this.name });
  1294. self._scope = {};
  1295. self._scopeNames = [];
  1296. self.scoped = true;
  1297. if (!option) {
  1298. return self;
  1299. }
  1300. const options = _.flatten(arguments);
  1301. for (const option of options) {
  1302. scope = null;
  1303. scopeName = null;
  1304. if (_.isPlainObject(option)) {
  1305. if (option.method) {
  1306. if (Array.isArray(option.method) && !!self.options.scopes[option.method[0]]) {
  1307. scopeName = option.method[0];
  1308. scope = self.options.scopes[scopeName].apply(self, option.method.slice(1));
  1309. }
  1310. else if (self.options.scopes[option.method]) {
  1311. scopeName = option.method;
  1312. scope = self.options.scopes[scopeName].apply(self);
  1313. }
  1314. } else {
  1315. scope = option;
  1316. }
  1317. } else if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) {
  1318. scope = self.options.defaultScope;
  1319. } else {
  1320. scopeName = option;
  1321. scope = self.options.scopes[scopeName];
  1322. if (typeof scope === 'function') {
  1323. scope = scope();
  1324. }
  1325. }
  1326. if (scope) {
  1327. this._conformIncludes(scope, this);
  1328. // clone scope so it doesn't get modified
  1329. this._assignOptions(self._scope, Utils.cloneDeep(scope));
  1330. self._scopeNames.push(scopeName ? scopeName : 'defaultScope');
  1331. } else {
  1332. throw new sequelizeErrors.SequelizeScopeError(`Invalid scope ${scopeName} called.`);
  1333. }
  1334. }
  1335. return self;
  1336. }
  1337. /**
  1338. * Search for multiple instances.
  1339. *
  1340. * @example <caption>Simple search using AND and =</caption>
  1341. * Model.findAll({
  1342. * where: {
  1343. * attr1: 42,
  1344. * attr2: 'cake'
  1345. * }
  1346. * })
  1347. *
  1348. * # WHERE attr1 = 42 AND attr2 = 'cake'
  1349. *
  1350. * @example <caption>Using greater than, less than etc.</caption>
  1351. * const {gt, lte, ne, in: opIn} = Sequelize.Op;
  1352. *
  1353. * Model.findAll({
  1354. * where: {
  1355. * attr1: {
  1356. * [gt]: 50
  1357. * },
  1358. * attr2: {
  1359. * [lte]: 45
  1360. * },
  1361. * attr3: {
  1362. * [opIn]: [1,2,3]
  1363. * },
  1364. * attr4: {
  1365. * [ne]: 5
  1366. * }
  1367. * }
  1368. * })
  1369. *
  1370. * # WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
  1371. *
  1372. * @example <caption>Queries using OR</caption>
  1373. * const {or, and, gt, lt} = Sequelize.Op;
  1374. *
  1375. * Model.findAll({
  1376. * where: {
  1377. * name: 'a project',
  1378. * [or]: [
  1379. * {id: [1, 2, 3]},
  1380. * {
  1381. * [and]: [
  1382. * {id: {[gt]: 10}},
  1383. * {id: {[lt]: 100}}
  1384. * ]
  1385. * }
  1386. * ]
  1387. * }
  1388. * });
  1389. *
  1390. * # WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));
  1391. *
  1392. * @see
  1393. * {@link Operators} for possible operators
  1394. * __Alias__: _all_
  1395. *
  1396. * The promise is resolved with an array of Model instances if the query succeeds._
  1397. *
  1398. * @param {object} [options] A hash of options to describe the scope of the search
  1399. * @param {object} [options.where] A hash of attributes to describe your search. See above for examples.
  1400. * @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
  1401. * @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']] }`
  1402. * @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'] } }`
  1403. * @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.
  1404. * @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).
  1405. * @param {Model} [options.include[].model] The model you want to eagerly load
  1406. * @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
  1407. * @param {Association} [options.include[].association] The association you want to eagerly load. (This can be used instead of providing a model/as pair)
  1408. * @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`
  1409. * @param {boolean} [options.include[].or=false] Whether to bind the ON and WHERE clause together by OR instead of AND.
  1410. * @param {object} [options.include[].on] Supply your own ON condition for the join.
  1411. * @param {Array<string>} [options.include[].attributes] A list of attributes to select from the child model
  1412. * @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.
  1413. * @param {boolean} [options.include[].right] If true, converts to a right join if dialect support it. Ignored if `include.required` is true.
  1414. * @param {boolean} [options.include[].separate] If true, runs a separate query to fetch the associated instances, only supported for hasMany associations
  1415. * @param {number} [options.include[].limit] Limit the joined rows, only supported with include.separate=true
  1416. * @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.
  1417. * @param {object} [options.include[].through.where] Filter on the join model for belongsToMany relations
  1418. * @param {Array} [options.include[].through.attributes] A list of attributes to select from the join model for belongsToMany relations
  1419. * @param {Array<object|Model|string>} [options.include[].include] Load further nested related models
  1420. * @param {boolean} [options.include[].duplicating] Mark the include as duplicating, will prevent a subquery from being used.
  1421. * @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.
  1422. * @param {number} [options.limit] Limit for result
  1423. * @param {number} [options.offset] Offset for result
  1424. * @param {Transaction} [options.transaction] Transaction to run query under
  1425. * @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.
  1426. * @param {boolean} [options.skipLocked] Skip locked rows. Only supported in Postgres.
  1427. * @param {boolean} [options.raw] Return raw result. See sequelize.query for more information.
  1428. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1429. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1430. * @param {object} [options.having] Having options
  1431. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1432. * @param {boolean|Error} [options.rejectOnEmpty=false] Throws an error when no records found
  1433. *
  1434. * @see
  1435. * {@link Sequelize#query}
  1436. *
  1437. * @returns {Promise<Array<Model>>}
  1438. */
  1439. static async findAll(options) {
  1440. if (options !== undefined && !_.isPlainObject(options)) {
  1441. 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');
  1442. }
  1443. if (options !== undefined && options.attributes) {
  1444. if (!Array.isArray(options.attributes) && !_.isPlainObject(options.attributes)) {
  1445. throw new sequelizeErrors.QueryError('The attributes option must be an array of column names or an object');
  1446. }
  1447. }
  1448. this.warnOnInvalidOptions(options, Object.keys(this.rawAttributes));
  1449. const tableNames = {};
  1450. tableNames[this.getTableName(options)] = true;
  1451. options = Utils.cloneDeep(options);
  1452. _.defaults(options, { hooks: true });
  1453. // set rejectOnEmpty option, defaults to model options
  1454. options.rejectOnEmpty = Object.prototype.hasOwnProperty.call(options, 'rejectOnEmpty')
  1455. ? options.rejectOnEmpty
  1456. : this.options.rejectOnEmpty;
  1457. this._injectScope(options);
  1458. if (options.hooks) {
  1459. await this.runHooks('beforeFind', options);
  1460. }
  1461. this._conformIncludes(options, this);
  1462. this._expandAttributes(options);
  1463. this._expandIncludeAll(options);
  1464. if (options.hooks) {
  1465. await this.runHooks('beforeFindAfterExpandIncludeAll', options);
  1466. }
  1467. options.originalAttributes = this._injectDependentVirtualAttributes(options.attributes);
  1468. if (options.include) {
  1469. options.hasJoin = true;
  1470. this._validateIncludedElements(options, tableNames);
  1471. // If we're not raw, we have to make sure we include the primary key for de-duplication
  1472. if (
  1473. options.attributes
  1474. && !options.raw
  1475. && this.primaryKeyAttribute
  1476. && !options.attributes.includes(this.primaryKeyAttribute)
  1477. && (!options.group || !options.hasSingleAssociation || options.hasMultiAssociation)
  1478. ) {
  1479. options.attributes = [this.primaryKeyAttribute].concat(options.attributes);
  1480. }
  1481. }
  1482. if (!options.attributes) {
  1483. options.attributes = Object.keys(this.rawAttributes);
  1484. options.originalAttributes = this._injectDependentVirtualAttributes(options.attributes);
  1485. }
  1486. // whereCollection is used for non-primary key updates
  1487. this.options.whereCollection = options.where || null;
  1488. Utils.mapFinderOptions(options, this);
  1489. options = this._paranoidClause(this, options);
  1490. if (options.hooks) {
  1491. await this.runHooks('beforeFindAfterOptions', options);
  1492. }
  1493. const selectOptions = { ...options, tableNames: Object.keys(tableNames) };
  1494. const results = await this.queryInterface.select(this, this.getTableName(selectOptions), selectOptions);
  1495. if (options.hooks) {
  1496. await this.runHooks('afterFind', results, options);
  1497. }
  1498. //rejectOnEmpty mode
  1499. if (_.isEmpty(results) && options.rejectOnEmpty) {
  1500. if (typeof options.rejectOnEmpty === 'function') {
  1501. throw new options.rejectOnEmpty();
  1502. }
  1503. if (typeof options.rejectOnEmpty === 'object') {
  1504. throw options.rejectOnEmpty;
  1505. }
  1506. throw new sequelizeErrors.EmptyResultError();
  1507. }
  1508. return await Model._findSeparate(results, options);
  1509. }
  1510. static warnOnInvalidOptions(options, validColumnNames) {
  1511. if (!_.isPlainObject(options)) {
  1512. return;
  1513. }
  1514. const unrecognizedOptions = Object.keys(options).filter(k => !validQueryKeywords.has(k));
  1515. const unexpectedModelAttributes = _.intersection(unrecognizedOptions, validColumnNames);
  1516. if (!options.where && unexpectedModelAttributes.length > 0) {
  1517. 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?`);
  1518. }
  1519. }
  1520. static _injectDependentVirtualAttributes(attributes) {
  1521. if (!this._hasVirtualAttributes) return attributes;
  1522. if (!attributes || !Array.isArray(attributes)) return attributes;
  1523. for (const attribute of attributes) {
  1524. if (
  1525. this._virtualAttributes.has(attribute)
  1526. && this.rawAttributes[attribute].type.fields
  1527. ) {
  1528. attributes = attributes.concat(this.rawAttributes[attribute].type.fields);
  1529. }
  1530. }
  1531. attributes = _.uniq(attributes);
  1532. return attributes;
  1533. }
  1534. static async _findSeparate(results, options) {
  1535. if (!options.include || options.raw || !results) return results;
  1536. const original = results;
  1537. if (options.plain) results = [results];
  1538. if (!results.length) return original;
  1539. await Promise.all(options.include.map(async include => {
  1540. if (!include.separate) {
  1541. return await Model._findSeparate(
  1542. results.reduce((memo, result) => {
  1543. let associations = result.get(include.association.as);
  1544. // Might be an empty belongsTo relation
  1545. if (!associations) return memo;
  1546. // Force array so we can concat no matter if it's 1:1 or :M
  1547. if (!Array.isArray(associations)) associations = [associations];
  1548. for (let i = 0, len = associations.length; i !== len; ++i) {
  1549. memo.push(associations[i]);
  1550. }
  1551. return memo;
  1552. }, []),
  1553. {
  1554. ..._.omit(options, 'include', 'attributes', 'order', 'where', 'limit', 'offset', 'plain', 'scope'),
  1555. include: include.include || []
  1556. }
  1557. );
  1558. }
  1559. const map = await include.association.get(results, {
  1560. ..._.omit(options, nonCascadingOptions),
  1561. ..._.omit(include, ['parent', 'association', 'as', 'originalAttributes'])
  1562. });
  1563. for (const result of results) {
  1564. result.set(
  1565. include.association.as,
  1566. map[result.get(include.association.sourceKey)],
  1567. { raw: true }
  1568. );
  1569. }
  1570. }));
  1571. return original;
  1572. }
  1573. /**
  1574. * Search for a single instance by its primary key._
  1575. *
  1576. * @param {number|string|Buffer} param The value of the desired instance's primary key.
  1577. * @param {object} [options] find options
  1578. * @param {Transaction} [options.transaction] Transaction to run query under
  1579. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1580. *
  1581. * @see
  1582. * {@link Model.findAll} for a full explanation of options, Note that options.where is not supported.
  1583. *
  1584. * @returns {Promise<Model>}
  1585. */
  1586. static async findByPk(param, options) {
  1587. // return Promise resolved with null if no arguments are passed
  1588. if ([null, undefined].includes(param)) {
  1589. return null;
  1590. }
  1591. options = Utils.cloneDeep(options) || {};
  1592. if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) {
  1593. options.where = {
  1594. [this.primaryKeyAttribute]: param
  1595. };
  1596. } else {
  1597. throw new Error(`Argument passed to findByPk is invalid: ${param}`);
  1598. }
  1599. // Bypass a possible overloaded findOne
  1600. return await this.findOne(options);
  1601. }
  1602. /**
  1603. * Search for a single instance. Returns the first instance found, or null if none can be found.
  1604. *
  1605. * @param {object} [options] A hash of options to describe the scope of the search
  1606. * @param {Transaction} [options.transaction] Transaction to run query under
  1607. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1608. *
  1609. * @see
  1610. * {@link Model.findAll} for an explanation of options
  1611. *
  1612. * @returns {Promise<Model|null>}
  1613. */
  1614. static async findOne(options) {
  1615. if (options !== undefined && !_.isPlainObject(options)) {
  1616. 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');
  1617. }
  1618. options = Utils.cloneDeep(options);
  1619. if (options.limit === undefined) {
  1620. const uniqueSingleColumns = _.chain(this.uniqueKeys).values().filter(c => c.fields.length === 1).map('column').value();
  1621. // Don't add limit if querying directly on the pk or a unique column
  1622. if (!options.where || !_.some(options.where, (value, key) =>
  1623. (key === this.primaryKeyAttribute || uniqueSingleColumns.includes(key)) &&
  1624. (Utils.isPrimitive(value) || Buffer.isBuffer(value))
  1625. )) {
  1626. options.limit = 1;
  1627. }
  1628. }
  1629. // Bypass a possible overloaded findAll.
  1630. return await this.findAll(_.defaults(options, {
  1631. plain: true
  1632. }));
  1633. }
  1634. /**
  1635. * Run an aggregation method on the specified field
  1636. *
  1637. * @param {string} attribute The attribute to aggregate over. Can be a field name or *
  1638. * @param {string} aggregateFunction The function to use for aggregation, e.g. sum, max etc.
  1639. * @param {object} [options] Query options. See sequelize.query for full options
  1640. * @param {object} [options.where] A hash of search attributes.
  1641. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1642. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1643. * @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.
  1644. * @param {boolean} [options.distinct] Applies DISTINCT to the field being aggregated over
  1645. * @param {Transaction} [options.transaction] Transaction to run query under
  1646. * @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`
  1647. *
  1648. * @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.
  1649. */
  1650. static async aggregate(attribute, aggregateFunction, options) {
  1651. options = Utils.cloneDeep(options);
  1652. // We need to preserve attributes here as the `injectScope` call would inject non aggregate columns.
  1653. const prevAttributes = options.attributes;
  1654. this._injectScope(options);
  1655. options.attributes = prevAttributes;
  1656. this._conformIncludes(options, this);
  1657. if (options.include) {
  1658. this._expandIncludeAll(options);
  1659. this._validateIncludedElements(options);
  1660. }
  1661. const attrOptions = this.rawAttributes[attribute];
  1662. const field = attrOptions && attrOptions.field || attribute;
  1663. let aggregateColumn = this.sequelize.col(field);
  1664. if (options.distinct) {
  1665. aggregateColumn = this.sequelize.fn('DISTINCT', aggregateColumn);
  1666. }
  1667. let { group } = options;
  1668. if (Array.isArray(group) && Array.isArray(group[0])) {
  1669. noDoubleNestedGroup();
  1670. group = _.flatten(group);
  1671. }
  1672. options.attributes = _.unionBy(
  1673. options.attributes,
  1674. group,
  1675. [[this.sequelize.fn(aggregateFunction, aggregateColumn), aggregateFunction]],
  1676. a => Array.isArray(a) ? a[1] : a
  1677. );
  1678. if (!options.dataType) {
  1679. if (attrOptions) {
  1680. options.dataType = attrOptions.type;
  1681. } else {
  1682. // Use FLOAT as fallback
  1683. options.dataType = new DataTypes.FLOAT();
  1684. }
  1685. } else {
  1686. options.dataType = this.sequelize.normalizeDataType(options.dataType);
  1687. }
  1688. Utils.mapOptionFieldNames(options, this);
  1689. options = this._paranoidClause(this, options);
  1690. const value = await this.queryInterface.rawSelect(this.getTableName(options), options, aggregateFunction, this);
  1691. if (value === null) {
  1692. return 0;
  1693. }
  1694. return value;
  1695. }
  1696. /**
  1697. * Count the number of records matching the provided where clause.
  1698. *
  1699. * If you provide an `include` option, the number of matching associations will be counted instead.
  1700. *
  1701. * @param {object} [options] options
  1702. * @param {object} [options.where] A hash of search attributes.
  1703. * @param {object} [options.include] Include options. See `find` for details
  1704. * @param {boolean} [options.paranoid=true] Set `true` to count only non-deleted records. Can be used on models with `paranoid` enabled
  1705. * @param {boolean} [options.distinct] Apply COUNT(DISTINCT(col)) on primary key or on options.col.
  1706. * @param {string} [options.col] Column on which COUNT() should be applied
  1707. * @param {Array} [options.attributes] Used in conjunction with `group`
  1708. * @param {Array} [options.group] For creating complex counts. Will return multiple rows as needed.
  1709. * @param {Transaction} [options.transaction] Transaction to run query under
  1710. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1711. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1712. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1713. *
  1714. * @returns {Promise<number>}
  1715. */
  1716. static async count(options) {
  1717. options = Utils.cloneDeep(options);
  1718. options = _.defaults(options, { hooks: true });
  1719. options.raw = true;
  1720. if (options.hooks) {
  1721. await this.runHooks('beforeCount', options);
  1722. }
  1723. let col = options.col || '*';
  1724. if (options.include) {
  1725. col = `${this.name}.${options.col || this.primaryKeyField}`;
  1726. }
  1727. if (options.distinct && col === '*') {
  1728. col = this.primaryKeyField;
  1729. }
  1730. options.plain = !options.group;
  1731. options.dataType = new DataTypes.INTEGER();
  1732. options.includeIgnoreAttributes = false;
  1733. // No limit, offset or order for the options max be given to count()
  1734. // Set them to null to prevent scopes setting those values
  1735. options.limit = null;
  1736. options.offset = null;
  1737. options.order = null;
  1738. return await this.aggregate(col, 'count', options);
  1739. }
  1740. /**
  1741. * 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
  1742. *
  1743. * @example
  1744. * const result = await Model.findAndCountAll({
  1745. * where: ...,
  1746. * limit: 12,
  1747. * offset: 12
  1748. * });
  1749. *
  1750. * # 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.
  1751. *
  1752. * # 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.
  1753. *
  1754. * # Suppose you want to find all users who have a profile attached:
  1755. *
  1756. * User.findAndCountAll({
  1757. * include: [
  1758. * { model: Profile, required: true}
  1759. * ],
  1760. * limit: 3
  1761. * });
  1762. *
  1763. * # 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
  1764. *
  1765. * @param {object} [options] See findAll options
  1766. *
  1767. * @see
  1768. * {@link Model.findAll} for a specification of find and query options
  1769. * @see
  1770. * {@link Model.count} for a specification of count options
  1771. *
  1772. * @returns {Promise<{count: number, rows: Model[]}>}
  1773. */
  1774. static async findAndCountAll(options) {
  1775. if (options !== undefined && !_.isPlainObject(options)) {
  1776. 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');
  1777. }
  1778. const countOptions = Utils.cloneDeep(options);
  1779. if (countOptions.attributes) {
  1780. countOptions.attributes = undefined;
  1781. }
  1782. const [count, rows] = await Promise.all([
  1783. this.count(countOptions),
  1784. this.findAll(options)
  1785. ]);
  1786. return {
  1787. count,
  1788. rows: count === 0 ? [] : rows
  1789. };
  1790. }
  1791. /**
  1792. * Find the maximum value of field
  1793. *
  1794. * @param {string} field attribute / field name
  1795. * @param {object} [options] See aggregate
  1796. *
  1797. * @see
  1798. * {@link Model.aggregate} for options
  1799. *
  1800. * @returns {Promise<*>}
  1801. */
  1802. static async max(field, options) {
  1803. return await this.aggregate(field, 'max', options);
  1804. }
  1805. /**
  1806. * Find the minimum value of field
  1807. *
  1808. * @param {string} field attribute / field name
  1809. * @param {object} [options] See aggregate
  1810. *
  1811. * @see
  1812. * {@link Model.aggregate} for options
  1813. *
  1814. * @returns {Promise<*>}
  1815. */
  1816. static async min(field, options) {
  1817. return await this.aggregate(field, 'min', options);
  1818. }
  1819. /**
  1820. * Find the sum of field
  1821. *
  1822. * @param {string} field attribute / field name
  1823. * @param {object} [options] See aggregate
  1824. *
  1825. * @see
  1826. * {@link Model.aggregate} for options
  1827. *
  1828. * @returns {Promise<number>}
  1829. */
  1830. static async sum(field, options) {
  1831. return await this.aggregate(field, 'sum', options);
  1832. }
  1833. /**
  1834. * Builds a new model instance.
  1835. *
  1836. * @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.
  1837. * @param {object} [options] Instance build options
  1838. * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
  1839. * @param {boolean} [options.isNewRecord=true] Is this new record
  1840. * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
  1841. *
  1842. * @returns {Model|Array<Model>}
  1843. */
  1844. static build(values, options) {
  1845. if (Array.isArray(values)) {
  1846. return this.bulkBuild(values, options);
  1847. }
  1848. return new this(values, options);
  1849. }
  1850. static bulkBuild(valueSets, options) {
  1851. options = { isNewRecord: true, ...options };
  1852. if (!options.includeValidated) {
  1853. this._conformIncludes(options, this);
  1854. if (options.include) {
  1855. this._expandIncludeAll(options);
  1856. this._validateIncludedElements(options);
  1857. }
  1858. }
  1859. if (options.attributes) {
  1860. options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute);
  1861. }
  1862. return valueSets.map(values => this.build(values, options));
  1863. }
  1864. /**
  1865. * Builds a new model instance and calls save on it.
  1866. *
  1867. * @see
  1868. * {@link Model.build}
  1869. * @see
  1870. * {@link Model.save}
  1871. *
  1872. * @param {object} values Hash of data values to create new record with
  1873. * @param {object} [options] Build and query options
  1874. * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
  1875. * @param {boolean} [options.isNewRecord=true] Is this new record
  1876. * @param {Array} [options.include] An array of include options - Used to build prefetched/included model instances. See `set`
  1877. * @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
  1878. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  1879. * @param {boolean} [options.validate=true] If false, validations won't be run.
  1880. * @param {boolean} [options.hooks=true] Run before and after create / update + validate hooks
  1881. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  1882. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  1883. * @param {Transaction} [options.transaction] Transaction to run query under
  1884. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  1885. * @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)
  1886. *
  1887. * @returns {Promise<Model>}
  1888. *
  1889. */
  1890. static async create(values, options) {
  1891. options = Utils.cloneDeep(options || {});
  1892. return await this.build(values, {
  1893. isNewRecord: true,
  1894. attributes: options.fields,
  1895. include: options.include,
  1896. raw: options.raw,
  1897. silent: options.silent
  1898. }).save(options);
  1899. }
  1900. /**
  1901. * Find a row that matches the query, or build (but don't save) the row if none is found.
  1902. * The successful result of the promise will be (instance, built)
  1903. *
  1904. * @param {object} options find options
  1905. * @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.
  1906. * @param {object} [options.defaults] Default values to use if building a new instance
  1907. * @param {object} [options.transaction] Transaction to run query under
  1908. *
  1909. * @returns {Promise<Model,boolean>}
  1910. */
  1911. static async findOrBuild(options) {
  1912. if (!options || !options.where || arguments.length > 1) {
  1913. throw new Error(
  1914. 'Missing where attribute in the options parameter passed to findOrBuild. ' +
  1915. 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)'
  1916. );
  1917. }
  1918. let values;
  1919. let instance = await this.findOne(options);
  1920. if (instance === null) {
  1921. values = { ...options.defaults };
  1922. if (_.isPlainObject(options.where)) {
  1923. values = Utils.defaults(values, options.where);
  1924. }
  1925. instance = this.build(values, options);
  1926. return [instance, true];
  1927. }
  1928. return [instance, false];
  1929. }
  1930. /**
  1931. * Find a row that matches the query, or build and save the row if none is found
  1932. * The successful result of the promise will be (instance, created)
  1933. *
  1934. * 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.
  1935. * 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.
  1936. * If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.
  1937. *
  1938. * @see
  1939. * {@link Model.findAll} for a full specification of find and options
  1940. *
  1941. * @param {object} options find and create options
  1942. * @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.
  1943. * @param {object} [options.defaults] Default values to use if creating a new instance
  1944. * @param {Transaction} [options.transaction] Transaction to run query under
  1945. *
  1946. * @returns {Promise<Model,boolean>}
  1947. */
  1948. static async findOrCreate(options) {
  1949. if (!options || !options.where || arguments.length > 1) {
  1950. throw new Error(
  1951. 'Missing where attribute in the options parameter passed to findOrCreate. ' +
  1952. 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)'
  1953. );
  1954. }
  1955. options = { ...options };
  1956. if (options.defaults) {
  1957. const defaults = Object.keys(options.defaults);
  1958. const unknownDefaults = defaults.filter(name => !this.rawAttributes[name]);
  1959. if (unknownDefaults.length) {
  1960. logger.warn(`Unknown attributes (${unknownDefaults}) passed to defaults option of findOrCreate`);
  1961. }
  1962. }
  1963. if (options.transaction === undefined && this.sequelize.constructor._cls) {
  1964. const t = this.sequelize.constructor._cls.get('transaction');
  1965. if (t) {
  1966. options.transaction = t;
  1967. }
  1968. }
  1969. const internalTransaction = !options.transaction;
  1970. let values;
  1971. let transaction;
  1972. try {
  1973. const t = await this.sequelize.transaction(options);
  1974. transaction = t;
  1975. options.transaction = t;
  1976. const found = await this.findOne(Utils.defaults({ transaction }, options));
  1977. if (found !== null) {
  1978. return [found, false];
  1979. }
  1980. values = { ...options.defaults };
  1981. if (_.isPlainObject(options.where)) {
  1982. values = Utils.defaults(values, options.where);
  1983. }
  1984. options.exception = true;
  1985. options.returning = true;
  1986. try {
  1987. const created = await this.create(values, options);
  1988. if (created.get(this.primaryKeyAttribute, { raw: true }) === null) {
  1989. // If the query returned an empty result for the primary key, we know that this was actually a unique constraint violation
  1990. throw new sequelizeErrors.UniqueConstraintError();
  1991. }
  1992. return [created, true];
  1993. } catch (err) {
  1994. if (!(err instanceof sequelizeErrors.UniqueConstraintError)) throw err;
  1995. const flattenedWhere = Utils.flattenObjectDeep(options.where);
  1996. const flattenedWhereKeys = Object.keys(flattenedWhere).map(name => _.last(name.split('.')));
  1997. const whereFields = flattenedWhereKeys.map(name => _.get(this.rawAttributes, `${name}.field`, name));
  1998. const defaultFields = options.defaults && Object.keys(options.defaults)
  1999. .filter(name => this.rawAttributes[name])
  2000. .map(name => this.rawAttributes[name].field || name);
  2001. const errFieldKeys = Object.keys(err.fields);
  2002. const errFieldsWhereIntersects = Utils.intersects(errFieldKeys, whereFields);
  2003. if (defaultFields && !errFieldsWhereIntersects && Utils.intersects(errFieldKeys, defaultFields)) {
  2004. throw err;
  2005. }
  2006. if (errFieldsWhereIntersects) {
  2007. _.each(err.fields, (value, key) => {
  2008. const name = this.fieldRawAttributesMap[key].fieldName;
  2009. if (value.toString() !== options.where[name].toString()) {
  2010. 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}'`);
  2011. }
  2012. });
  2013. }
  2014. // Someone must have created a matching instance inside the same transaction since we last did a find. Let's find it!
  2015. const otherCreated = await this.findOne(Utils.defaults({
  2016. transaction: internalTransaction ? null : transaction
  2017. }, options));
  2018. // Sanity check, ideally we caught this at the defaultFeilds/err.fields check
  2019. // But if we didn't and instance is null, we will throw
  2020. if (otherCreated === null) throw err;
  2021. return [otherCreated, false];
  2022. }
  2023. } finally {
  2024. if (internalTransaction && transaction) {
  2025. await transaction.commit();
  2026. }
  2027. }
  2028. }
  2029. /**
  2030. * A more performant findOrCreate that will not work under a transaction (at least not in postgres)
  2031. * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
  2032. *
  2033. * @see
  2034. * {@link Model.findAll} for a full specification of find and options
  2035. *
  2036. * @param {object} options find options
  2037. * @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.
  2038. * @param {object} [options.defaults] Default values to use if creating a new instance
  2039. *
  2040. * @returns {Promise<Model,boolean>}
  2041. */
  2042. static async findCreateFind(options) {
  2043. if (!options || !options.where) {
  2044. throw new Error(
  2045. 'Missing where attribute in the options parameter passed to findCreateFind.'
  2046. );
  2047. }
  2048. let values = { ...options.defaults };
  2049. if (_.isPlainObject(options.where)) {
  2050. values = Utils.defaults(values, options.where);
  2051. }
  2052. const found = await this.findOne(options);
  2053. if (found) return [found, false];
  2054. try {
  2055. const created = await this.create(values, options);
  2056. return [created, true];
  2057. } catch (err) {
  2058. if (!(err instanceof sequelizeErrors.UniqueConstraintError)) throw err;
  2059. const foundAgain = await this.findOne(options);
  2060. return [foundAgain, false];
  2061. }
  2062. }
  2063. /**
  2064. * 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.
  2065. *
  2066. * **Implementation details:**
  2067. *
  2068. * * MySQL - Implemented with ON DUPLICATE KEY UPDATE`
  2069. * * 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.
  2070. * * SQLite - Implemented with ON CONFLICT DO UPDATE
  2071. * * MSSQL - Implemented as a single query using `MERGE` and `WHEN (NOT) MATCHED THEN`
  2072. *
  2073. * **Note** that Postgres/SQLite returns null for created, no matter if the row was created or updated
  2074. *
  2075. * @param {object} values hash of values to upsert
  2076. * @param {object} [options] upsert options
  2077. * @param {boolean} [options.validate=true] Run validations before the row is inserted
  2078. * @param {Array} [options.fields=Object.keys(this.attributes)] The fields to insert / update. Defaults to all changed fields
  2079. * @param {boolean} [options.hooks=true] Run before / after upsert hooks?
  2080. * @param {boolean} [options.returning=true] If true, fetches back auto generated values
  2081. * @param {Transaction} [options.transaction] Transaction to run query under
  2082. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2083. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2084. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2085. *
  2086. * @returns {Promise<[Model, boolean | null]>} returns an array with two elements, the first being the new record and the second being `true` if it was just created or `false` if it already existed (except on Postgres and SQLite, which can't detect this and will always return `null` instead of a boolean).
  2087. */
  2088. static async upsert(values, options) {
  2089. options = {
  2090. hooks: true,
  2091. returning: true,
  2092. validate: true,
  2093. ...Utils.cloneDeep(options)
  2094. };
  2095. const createdAtAttr = this._timestampAttributes.createdAt;
  2096. const updatedAtAttr = this._timestampAttributes.updatedAt;
  2097. const hasPrimary = this.primaryKeyField in values || this.primaryKeyAttribute in values;
  2098. const instance = this.build(values);
  2099. options.model = this;
  2100. options.instance = instance;
  2101. const changed = Array.from(instance._changed);
  2102. if (!options.fields) {
  2103. options.fields = changed;
  2104. }
  2105. if (options.validate) {
  2106. await instance.validate(options);
  2107. }
  2108. // Map field names
  2109. const updatedDataValues = _.pick(instance.dataValues, changed);
  2110. const insertValues = Utils.mapValueFieldNames(instance.dataValues, Object.keys(instance.rawAttributes), this);
  2111. const updateValues = Utils.mapValueFieldNames(updatedDataValues, options.fields, this);
  2112. const now = Utils.now(this.sequelize.options.dialect);
  2113. // Attach createdAt
  2114. if (createdAtAttr && !updateValues[createdAtAttr]) {
  2115. const field = this.rawAttributes[createdAtAttr].field || createdAtAttr;
  2116. insertValues[field] = this._getDefaultTimestamp(createdAtAttr) || now;
  2117. }
  2118. if (updatedAtAttr && !insertValues[updatedAtAttr]) {
  2119. const field = this.rawAttributes[updatedAtAttr].field || updatedAtAttr;
  2120. insertValues[field] = updateValues[field] = this._getDefaultTimestamp(updatedAtAttr) || now;
  2121. }
  2122. // Build adds a null value for the primary key, if none was given by the user.
  2123. // We need to remove that because of some Postgres technicalities.
  2124. if (!hasPrimary && this.primaryKeyAttribute && !this.rawAttributes[this.primaryKeyAttribute].defaultValue) {
  2125. delete insertValues[this.primaryKeyField];
  2126. delete updateValues[this.primaryKeyField];
  2127. }
  2128. if (options.hooks) {
  2129. await this.runHooks('beforeUpsert', values, options);
  2130. }
  2131. const result = await this.queryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), options);
  2132. const [record] = result;
  2133. record.isNewRecord = false;
  2134. if (options.hooks) {
  2135. await this.runHooks('afterUpsert', result, options);
  2136. return result;
  2137. }
  2138. return result;
  2139. }
  2140. /**
  2141. * Create and insert multiple instances in bulk.
  2142. *
  2143. * 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
  2144. * 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.
  2145. * To obtain Instances for the newly created values, you will need to query for them again.
  2146. *
  2147. * If validation fails, the promise is rejected with an array-like AggregateError
  2148. *
  2149. * @param {Array} records List of objects (key/value pairs) to create instances from
  2150. * @param {object} [options] Bulk create options
  2151. * @param {Array} [options.fields] Fields to insert (defaults to all fields)
  2152. * @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
  2153. * @param {boolean} [options.hooks=true] Run before / after bulk create hooks?
  2154. * @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.
  2155. * @param {boolean} [options.ignoreDuplicates=false] Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5)
  2156. * @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.
  2157. * @param {Transaction} [options.transaction] Transaction to run query under
  2158. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2159. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2160. * @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)
  2161. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2162. *
  2163. * @returns {Promise<Array<Model>>}
  2164. */
  2165. static async bulkCreate(records, options = {}) {
  2166. if (!records.length) {
  2167. return [];
  2168. }
  2169. const dialect = this.sequelize.options.dialect;
  2170. const now = Utils.now(this.sequelize.options.dialect);
  2171. options.model = this;
  2172. if (!options.includeValidated) {
  2173. this._conformIncludes(options, this);
  2174. if (options.include) {
  2175. this._expandIncludeAll(options);
  2176. this._validateIncludedElements(options);
  2177. }
  2178. }
  2179. const instances = records.map(values => this.build(values, { isNewRecord: true, include: options.include }));
  2180. const recursiveBulkCreate = async (instances, options) => {
  2181. options = {
  2182. validate: false,
  2183. hooks: true,
  2184. individualHooks: false,
  2185. ignoreDuplicates: false,
  2186. ...options
  2187. };
  2188. if (options.returning === undefined) {
  2189. if (options.association) {
  2190. options.returning = false;
  2191. } else {
  2192. options.returning = true;
  2193. }
  2194. }
  2195. if (options.ignoreDuplicates && ['mssql'].includes(dialect)) {
  2196. throw new Error(`${dialect} does not support the ignoreDuplicates option.`);
  2197. }
  2198. if (options.updateOnDuplicate && (dialect !== 'mysql' && dialect !== 'mariadb' && dialect !== 'sqlite' && dialect !== 'postgres')) {
  2199. throw new Error(`${dialect} does not support the updateOnDuplicate option.`);
  2200. }
  2201. const model = options.model;
  2202. options.fields = options.fields || Object.keys(model.rawAttributes);
  2203. const createdAtAttr = model._timestampAttributes.createdAt;
  2204. const updatedAtAttr = model._timestampAttributes.updatedAt;
  2205. if (options.updateOnDuplicate !== undefined) {
  2206. if (Array.isArray(options.updateOnDuplicate) && options.updateOnDuplicate.length) {
  2207. options.updateOnDuplicate = _.intersection(
  2208. _.without(Object.keys(model.tableAttributes), createdAtAttr),
  2209. options.updateOnDuplicate
  2210. );
  2211. } else {
  2212. throw new Error('updateOnDuplicate option only supports non-empty array.');
  2213. }
  2214. }
  2215. // Run before hook
  2216. if (options.hooks) {
  2217. await model.runHooks('beforeBulkCreate', instances, options);
  2218. }
  2219. // Validate
  2220. if (options.validate) {
  2221. const errors = [];
  2222. const validateOptions = { ...options };
  2223. validateOptions.hooks = options.individualHooks;
  2224. await Promise.all(instances.map(async instance => {
  2225. try {
  2226. await instance.validate(validateOptions);
  2227. } catch (err) {
  2228. errors.push(new sequelizeErrors.BulkRecordError(err, instance));
  2229. }
  2230. }));
  2231. delete options.skip;
  2232. if (errors.length) {
  2233. throw new sequelizeErrors.AggregateError(errors);
  2234. }
  2235. }
  2236. if (options.individualHooks) {
  2237. await Promise.all(instances.map(async instance => {
  2238. const individualOptions = {
  2239. ...options,
  2240. validate: false,
  2241. hooks: true
  2242. };
  2243. delete individualOptions.fields;
  2244. delete individualOptions.individualHooks;
  2245. delete individualOptions.ignoreDuplicates;
  2246. await instance.save(individualOptions);
  2247. }));
  2248. } else {
  2249. if (options.include && options.include.length) {
  2250. await Promise.all(options.include.filter(include => include.association instanceof BelongsTo).map(async include => {
  2251. const associationInstances = [];
  2252. const associationInstanceIndexToInstanceMap = [];
  2253. for (const instance of instances) {
  2254. const associationInstance = instance.get(include.as);
  2255. if (associationInstance) {
  2256. associationInstances.push(associationInstance);
  2257. associationInstanceIndexToInstanceMap.push(instance);
  2258. }
  2259. }
  2260. if (!associationInstances.length) {
  2261. return;
  2262. }
  2263. const includeOptions = _(Utils.cloneDeep(include))
  2264. .omit(['association'])
  2265. .defaults({
  2266. transaction: options.transaction,
  2267. logging: options.logging
  2268. }).value();
  2269. const createdAssociationInstances = await recursiveBulkCreate(associationInstances, includeOptions);
  2270. for (const idx in createdAssociationInstances) {
  2271. const associationInstance = createdAssociationInstances[idx];
  2272. const instance = associationInstanceIndexToInstanceMap[idx];
  2273. await include.association.set(instance, associationInstance, { save: false, logging: options.logging });
  2274. }
  2275. }));
  2276. }
  2277. // Create all in one query
  2278. // Recreate records from instances to represent any changes made in hooks or validation
  2279. records = instances.map(instance => {
  2280. const values = instance.dataValues;
  2281. // set createdAt/updatedAt attributes
  2282. if (createdAtAttr && !values[createdAtAttr]) {
  2283. values[createdAtAttr] = now;
  2284. if (!options.fields.includes(createdAtAttr)) {
  2285. options.fields.push(createdAtAttr);
  2286. }
  2287. }
  2288. if (updatedAtAttr && !values[updatedAtAttr]) {
  2289. values[updatedAtAttr] = now;
  2290. if (!options.fields.includes(updatedAtAttr)) {
  2291. options.fields.push(updatedAtAttr);
  2292. }
  2293. }
  2294. const out = Utils.mapValueFieldNames(values, options.fields, model);
  2295. for (const key of model._virtualAttributes) {
  2296. delete out[key];
  2297. }
  2298. return out;
  2299. });
  2300. // Map attributes to fields for serial identification
  2301. const fieldMappedAttributes = {};
  2302. for (const attr in model.tableAttributes) {
  2303. fieldMappedAttributes[model.rawAttributes[attr].field || attr] = model.rawAttributes[attr];
  2304. }
  2305. // Map updateOnDuplicate attributes to fields
  2306. if (options.updateOnDuplicate) {
  2307. options.updateOnDuplicate = options.updateOnDuplicate.map(attr => model.rawAttributes[attr].field || attr);
  2308. // Get primary keys for postgres to enable updateOnDuplicate
  2309. options.upsertKeys = _.chain(model.primaryKeys).values().map('field').value();
  2310. if (Object.keys(model.uniqueKeys).length > 0) {
  2311. options.upsertKeys = _.chain(model.uniqueKeys).values().filter(c => c.fields.length >= 1).map(c => c.fields).reduce(c => c[0]).value();
  2312. }
  2313. }
  2314. // Map returning attributes to fields
  2315. if (options.returning && Array.isArray(options.returning)) {
  2316. options.returning = options.returning.map(attr => _.get(model.rawAttributes[attr], 'field', attr));
  2317. }
  2318. const results = await model.queryInterface.bulkInsert(model.getTableName(options), records, options, fieldMappedAttributes);
  2319. if (Array.isArray(results)) {
  2320. results.forEach((result, i) => {
  2321. const instance = instances[i];
  2322. for (const key in result) {
  2323. if (!instance || key === model.primaryKeyAttribute &&
  2324. instance.get(model.primaryKeyAttribute) &&
  2325. ['mysql', 'mariadb', 'sqlite'].includes(dialect)) {
  2326. // The query.js for these DBs is blind, it autoincrements the
  2327. // primarykey value, even if it was set manually. Also, it can
  2328. // return more results than instances, bug?.
  2329. continue;
  2330. }
  2331. if (Object.prototype.hasOwnProperty.call(result, key)) {
  2332. const record = result[key];
  2333. const attr = _.find(model.rawAttributes, attribute => attribute.fieldName === key || attribute.field === key);
  2334. instance.dataValues[attr && attr.fieldName || key] = record;
  2335. }
  2336. }
  2337. });
  2338. }
  2339. }
  2340. if (options.include && options.include.length) {
  2341. await Promise.all(options.include.filter(include => !(include.association instanceof BelongsTo ||
  2342. include.parent && include.parent.association instanceof BelongsToMany)).map(async include => {
  2343. const associationInstances = [];
  2344. const associationInstanceIndexToInstanceMap = [];
  2345. for (const instance of instances) {
  2346. let associated = instance.get(include.as);
  2347. if (!Array.isArray(associated)) associated = [associated];
  2348. for (const associationInstance of associated) {
  2349. if (associationInstance) {
  2350. if (!(include.association instanceof BelongsToMany)) {
  2351. associationInstance.set(include.association.foreignKey, instance.get(include.association.sourceKey || instance.constructor.primaryKeyAttribute, { raw: true }), { raw: true });
  2352. Object.assign(associationInstance, include.association.scope);
  2353. }
  2354. associationInstances.push(associationInstance);
  2355. associationInstanceIndexToInstanceMap.push(instance);
  2356. }
  2357. }
  2358. }
  2359. if (!associationInstances.length) {
  2360. return;
  2361. }
  2362. const includeOptions = _(Utils.cloneDeep(include))
  2363. .omit(['association'])
  2364. .defaults({
  2365. transaction: options.transaction,
  2366. logging: options.logging
  2367. }).value();
  2368. const createdAssociationInstances = await recursiveBulkCreate(associationInstances, includeOptions);
  2369. if (include.association instanceof BelongsToMany) {
  2370. const valueSets = [];
  2371. for (const idx in createdAssociationInstances) {
  2372. const associationInstance = createdAssociationInstances[idx];
  2373. const instance = associationInstanceIndexToInstanceMap[idx];
  2374. const values = {
  2375. [include.association.foreignKey]: instance.get(instance.constructor.primaryKeyAttribute, { raw: true }),
  2376. [include.association.otherKey]: associationInstance.get(associationInstance.constructor.primaryKeyAttribute, { raw: true }),
  2377. // Include values defined in the association
  2378. ...include.association.through.scope
  2379. };
  2380. if (associationInstance[include.association.through.model.name]) {
  2381. for (const attr of Object.keys(include.association.through.model.rawAttributes)) {
  2382. if (include.association.through.model.rawAttributes[attr]._autoGenerated ||
  2383. attr === include.association.foreignKey ||
  2384. attr === include.association.otherKey ||
  2385. typeof associationInstance[include.association.through.model.name][attr] === undefined) {
  2386. continue;
  2387. }
  2388. values[attr] = associationInstance[include.association.through.model.name][attr];
  2389. }
  2390. }
  2391. valueSets.push(values);
  2392. }
  2393. const throughOptions = _(Utils.cloneDeep(include))
  2394. .omit(['association', 'attributes'])
  2395. .defaults({
  2396. transaction: options.transaction,
  2397. logging: options.logging
  2398. }).value();
  2399. throughOptions.model = include.association.throughModel;
  2400. const throughInstances = include.association.throughModel.bulkBuild(valueSets, throughOptions);
  2401. await recursiveBulkCreate(throughInstances, throughOptions);
  2402. }
  2403. }));
  2404. }
  2405. // map fields back to attributes
  2406. instances.forEach(instance => {
  2407. for (const attr in model.rawAttributes) {
  2408. if (model.rawAttributes[attr].field &&
  2409. instance.dataValues[model.rawAttributes[attr].field] !== undefined &&
  2410. model.rawAttributes[attr].field !== attr
  2411. ) {
  2412. instance.dataValues[attr] = instance.dataValues[model.rawAttributes[attr].field];
  2413. delete instance.dataValues[model.rawAttributes[attr].field];
  2414. }
  2415. instance._previousDataValues[attr] = instance.dataValues[attr];
  2416. instance.changed(attr, false);
  2417. }
  2418. instance.isNewRecord = false;
  2419. });
  2420. // Run after hook
  2421. if (options.hooks) {
  2422. await model.runHooks('afterBulkCreate', instances, options);
  2423. }
  2424. return instances;
  2425. };
  2426. return await recursiveBulkCreate(instances, options);
  2427. }
  2428. /**
  2429. * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
  2430. *
  2431. * @param {object} [options] The options passed to Model.destroy in addition to truncate
  2432. * @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.
  2433. * @param {boolean} [options.restartIdentity=false] Automatically restart sequences owned by columns of the truncated table.
  2434. * @param {Transaction} [options.transaction] Transaction to run query under
  2435. * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
  2436. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2437. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2438. *
  2439. * @returns {Promise}
  2440. *
  2441. * @see
  2442. * {@link Model.destroy} for more information
  2443. */
  2444. static async truncate(options) {
  2445. options = Utils.cloneDeep(options) || {};
  2446. options.truncate = true;
  2447. return await this.destroy(options);
  2448. }
  2449. /**
  2450. * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
  2451. *
  2452. * @param {object} options destroy options
  2453. * @param {object} [options.where] Filter the destroy
  2454. * @param {boolean} [options.hooks=true] Run before / after bulk destroy hooks?
  2455. * @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
  2456. * @param {number} [options.limit] How many rows to delete
  2457. * @param {boolean} [options.force=false] Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
  2458. * @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
  2459. * @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.
  2460. * @param {boolean} [options.restartIdentity=false] Only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table.
  2461. * @param {Transaction} [options.transaction] Transaction to run query under
  2462. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2463. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2464. *
  2465. * @returns {Promise<number>} The number of destroyed rows
  2466. */
  2467. static async destroy(options) {
  2468. options = Utils.cloneDeep(options);
  2469. this._injectScope(options);
  2470. if (!options || !(options.where || options.truncate)) {
  2471. throw new Error('Missing where or truncate attribute in the options parameter of model.destroy.');
  2472. }
  2473. if (!options.truncate && !_.isPlainObject(options.where) && !Array.isArray(options.where) && !(options.where instanceof Utils.SequelizeMethod)) {
  2474. throw new Error('Expected plain object, array or sequelize method in the options.where parameter of model.destroy.');
  2475. }
  2476. options = _.defaults(options, {
  2477. hooks: true,
  2478. individualHooks: false,
  2479. force: false,
  2480. cascade: false,
  2481. restartIdentity: false
  2482. });
  2483. options.type = QueryTypes.BULKDELETE;
  2484. Utils.mapOptionFieldNames(options, this);
  2485. options.model = this;
  2486. // Run before hook
  2487. if (options.hooks) {
  2488. await this.runHooks('beforeBulkDestroy', options);
  2489. }
  2490. let instances;
  2491. // Get daos and run beforeDestroy hook on each record individually
  2492. if (options.individualHooks) {
  2493. instances = await this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark });
  2494. await Promise.all(instances.map(instance => this.runHooks('beforeDestroy', instance, options)));
  2495. }
  2496. let result;
  2497. // Run delete query (or update if paranoid)
  2498. if (this._timestampAttributes.deletedAt && !options.force) {
  2499. // Set query type appropriately when running soft delete
  2500. options.type = QueryTypes.BULKUPDATE;
  2501. const attrValueHash = {};
  2502. const deletedAtAttribute = this.rawAttributes[this._timestampAttributes.deletedAt];
  2503. const field = this.rawAttributes[this._timestampAttributes.deletedAt].field;
  2504. const where = {
  2505. [field]: Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null
  2506. };
  2507. attrValueHash[field] = Utils.now(this.sequelize.options.dialect);
  2508. result = await this.queryInterface.bulkUpdate(this.getTableName(options), attrValueHash, Object.assign(where, options.where), options, this.rawAttributes);
  2509. } else {
  2510. result = await this.queryInterface.bulkDelete(this.getTableName(options), options.where, options, this);
  2511. }
  2512. // Run afterDestroy hook on each record individually
  2513. if (options.individualHooks) {
  2514. await Promise.all(
  2515. instances.map(instance => this.runHooks('afterDestroy', instance, options))
  2516. );
  2517. }
  2518. // Run after hook
  2519. if (options.hooks) {
  2520. await this.runHooks('afterBulkDestroy', options);
  2521. }
  2522. return result;
  2523. }
  2524. /**
  2525. * Restore multiple instances if `paranoid` is enabled.
  2526. *
  2527. * @param {object} options restore options
  2528. * @param {object} [options.where] Filter the restore
  2529. * @param {boolean} [options.hooks=true] Run before / after bulk restore hooks?
  2530. * @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
  2531. * @param {number} [options.limit] How many rows to undelete (only for mysql)
  2532. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2533. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2534. * @param {Transaction} [options.transaction] Transaction to run query under
  2535. *
  2536. * @returns {Promise}
  2537. */
  2538. static async restore(options) {
  2539. if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
  2540. options = {
  2541. hooks: true,
  2542. individualHooks: false,
  2543. ...options
  2544. };
  2545. options.type = QueryTypes.RAW;
  2546. options.model = this;
  2547. Utils.mapOptionFieldNames(options, this);
  2548. // Run before hook
  2549. if (options.hooks) {
  2550. await this.runHooks('beforeBulkRestore', options);
  2551. }
  2552. let instances;
  2553. // Get daos and run beforeRestore hook on each record individually
  2554. if (options.individualHooks) {
  2555. instances = await this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark, paranoid: false });
  2556. await Promise.all(instances.map(instance => this.runHooks('beforeRestore', instance, options)));
  2557. }
  2558. // Run undelete query
  2559. const attrValueHash = {};
  2560. const deletedAtCol = this._timestampAttributes.deletedAt;
  2561. const deletedAtAttribute = this.rawAttributes[deletedAtCol];
  2562. const deletedAtDefaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null;
  2563. attrValueHash[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
  2564. options.omitNull = false;
  2565. const result = await this.queryInterface.bulkUpdate(this.getTableName(options), attrValueHash, options.where, options, this.rawAttributes);
  2566. // Run afterDestroy hook on each record individually
  2567. if (options.individualHooks) {
  2568. await Promise.all(
  2569. instances.map(instance => this.runHooks('afterRestore', instance, options))
  2570. );
  2571. }
  2572. // Run after hook
  2573. if (options.hooks) {
  2574. await this.runHooks('afterBulkRestore', options);
  2575. }
  2576. return result;
  2577. }
  2578. /**
  2579. * Update multiple instances that match the where options.
  2580. *
  2581. * @param {object} values hash of values to update
  2582. * @param {object} options update options
  2583. * @param {object} options.where Options to describe the scope of the search.
  2584. * @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.
  2585. * @param {Array} [options.fields] Fields to update (defaults to all fields)
  2586. * @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
  2587. * @param {boolean} [options.hooks=true] Run before / after bulk update hooks?
  2588. * @param {boolean} [options.sideEffects=true] Whether or not to update the side effects of any virtual setters.
  2589. * @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
  2590. * @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)
  2591. * @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)
  2592. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2593. * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
  2594. * @param {Transaction} [options.transaction] Transaction to run query under
  2595. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  2596. *
  2597. * @returns {Promise<Array<number,number>>} The promise returns an array with one or two elements. The first element is always the number
  2598. * of affected rows, while the second element is the actual affected rows (only supported in postgres with `options.returning` true).
  2599. *
  2600. */
  2601. static async update(values, options) {
  2602. options = Utils.cloneDeep(options);
  2603. this._injectScope(options);
  2604. this._optionsMustContainWhere(options);
  2605. options = this._paranoidClause(this, _.defaults(options, {
  2606. validate: true,
  2607. hooks: true,
  2608. individualHooks: false,
  2609. returning: false,
  2610. force: false,
  2611. sideEffects: true
  2612. }));
  2613. options.type = QueryTypes.BULKUPDATE;
  2614. // Clone values so it doesn't get modified for caller scope and ignore undefined values
  2615. values = _.omitBy(values, value => value === undefined);
  2616. // Remove values that are not in the options.fields
  2617. if (options.fields && options.fields instanceof Array) {
  2618. for (const key of Object.keys(values)) {
  2619. if (!options.fields.includes(key)) {
  2620. delete values[key];
  2621. }
  2622. }
  2623. } else {
  2624. const updatedAtAttr = this._timestampAttributes.updatedAt;
  2625. options.fields = _.intersection(Object.keys(values), Object.keys(this.tableAttributes));
  2626. if (updatedAtAttr && !options.fields.includes(updatedAtAttr)) {
  2627. options.fields.push(updatedAtAttr);
  2628. }
  2629. }
  2630. if (this._timestampAttributes.updatedAt && !options.silent) {
  2631. values[this._timestampAttributes.updatedAt] = this._getDefaultTimestamp(this._timestampAttributes.updatedAt) || Utils.now(this.sequelize.options.dialect);
  2632. }
  2633. options.model = this;
  2634. let valuesUse;
  2635. // Validate
  2636. if (options.validate) {
  2637. const build = this.build(values);
  2638. build.set(this._timestampAttributes.updatedAt, values[this._timestampAttributes.updatedAt], { raw: true });
  2639. if (options.sideEffects) {
  2640. Object.assign(values, _.pick(build.get(), build.changed()));
  2641. options.fields = _.union(options.fields, Object.keys(values));
  2642. }
  2643. // We want to skip validations for all other fields
  2644. options.skip = _.difference(Object.keys(this.rawAttributes), Object.keys(values));
  2645. const attributes = await build.validate(options);
  2646. options.skip = undefined;
  2647. if (attributes && attributes.dataValues) {
  2648. values = _.pick(attributes.dataValues, Object.keys(values));
  2649. }
  2650. }
  2651. // Run before hook
  2652. if (options.hooks) {
  2653. options.attributes = values;
  2654. await this.runHooks('beforeBulkUpdate', options);
  2655. values = options.attributes;
  2656. delete options.attributes;
  2657. }
  2658. valuesUse = values;
  2659. // Get instances and run beforeUpdate hook on each record individually
  2660. let instances;
  2661. let updateDoneRowByRow = false;
  2662. if (options.individualHooks) {
  2663. instances = await this.findAll({
  2664. where: options.where,
  2665. transaction: options.transaction,
  2666. logging: options.logging,
  2667. benchmark: options.benchmark,
  2668. paranoid: options.paranoid
  2669. });
  2670. if (instances.length) {
  2671. // Run beforeUpdate hooks on each record and check whether beforeUpdate hook changes values uniformly
  2672. // i.e. whether they change values for each record in the same way
  2673. let changedValues;
  2674. let different = false;
  2675. instances = await Promise.all(instances.map(async instance => {
  2676. // Record updates in instances dataValues
  2677. Object.assign(instance.dataValues, values);
  2678. // Set the changed fields on the instance
  2679. _.forIn(valuesUse, (newValue, attr) => {
  2680. if (newValue !== instance._previousDataValues[attr]) {
  2681. instance.setDataValue(attr, newValue);
  2682. }
  2683. });
  2684. // Run beforeUpdate hook
  2685. await this.runHooks('beforeUpdate', instance, options);
  2686. if (!different) {
  2687. const thisChangedValues = {};
  2688. _.forIn(instance.dataValues, (newValue, attr) => {
  2689. if (newValue !== instance._previousDataValues[attr]) {
  2690. thisChangedValues[attr] = newValue;
  2691. }
  2692. });
  2693. if (!changedValues) {
  2694. changedValues = thisChangedValues;
  2695. } else {
  2696. different = !_.isEqual(changedValues, thisChangedValues);
  2697. }
  2698. }
  2699. return instance;
  2700. }));
  2701. if (!different) {
  2702. const keys = Object.keys(changedValues);
  2703. // Hooks do not change values or change them uniformly
  2704. if (keys.length) {
  2705. // Hooks change values - record changes in valuesUse so they are executed
  2706. valuesUse = changedValues;
  2707. options.fields = _.union(options.fields, keys);
  2708. }
  2709. } else {
  2710. instances = await Promise.all(instances.map(async instance => {
  2711. const individualOptions = {
  2712. ...options,
  2713. hooks: false,
  2714. validate: false
  2715. };
  2716. delete individualOptions.individualHooks;
  2717. return instance.save(individualOptions);
  2718. }));
  2719. updateDoneRowByRow = true;
  2720. }
  2721. }
  2722. }
  2723. let result;
  2724. if (updateDoneRowByRow) {
  2725. result = [instances.length, instances];
  2726. } else if (_.isEmpty(valuesUse)
  2727. || Object.keys(valuesUse).length === 1 && valuesUse[this._timestampAttributes.updatedAt]) {
  2728. // only updatedAt is being passed, then skip update
  2729. result = [0];
  2730. } else {
  2731. valuesUse = Utils.mapValueFieldNames(valuesUse, options.fields, this);
  2732. options = Utils.mapOptionFieldNames(options, this);
  2733. options.hasTrigger = this.options ? this.options.hasTrigger : false;
  2734. const affectedRows = await this.queryInterface.bulkUpdate(this.getTableName(options), valuesUse, options.where, options, this.tableAttributes);
  2735. if (options.returning) {
  2736. result = [affectedRows.length, affectedRows];
  2737. instances = affectedRows;
  2738. } else {
  2739. result = [affectedRows];
  2740. }
  2741. }
  2742. if (options.individualHooks) {
  2743. await Promise.all(instances.map(instance => this.runHooks('afterUpdate', instance, options)));
  2744. result[1] = instances;
  2745. }
  2746. // Run after hook
  2747. if (options.hooks) {
  2748. options.attributes = values;
  2749. await this.runHooks('afterBulkUpdate', options);
  2750. delete options.attributes;
  2751. }
  2752. return result;
  2753. }
  2754. /**
  2755. * Run a describe query on the table.
  2756. *
  2757. * @param {string} [schema] schema name to search table in
  2758. * @param {object} [options] query options
  2759. *
  2760. * @returns {Promise} hash of attributes and their types
  2761. */
  2762. static async describe(schema, options) {
  2763. return await this.queryInterface.describeTable(this.tableName, { schema: schema || this._schema || undefined, ...options });
  2764. }
  2765. static _getDefaultTimestamp(attr) {
  2766. if (!!this.rawAttributes[attr] && !!this.rawAttributes[attr].defaultValue) {
  2767. return Utils.toDefaultValue(this.rawAttributes[attr].defaultValue, this.sequelize.options.dialect);
  2768. }
  2769. return undefined;
  2770. }
  2771. static _expandAttributes(options) {
  2772. if (!_.isPlainObject(options.attributes)) {
  2773. return;
  2774. }
  2775. let attributes = Object.keys(this.rawAttributes);
  2776. if (options.attributes.exclude) {
  2777. attributes = attributes.filter(elem => !options.attributes.exclude.includes(elem));
  2778. }
  2779. if (options.attributes.include) {
  2780. attributes = attributes.concat(options.attributes.include);
  2781. }
  2782. options.attributes = attributes;
  2783. }
  2784. // Inject _scope into options.
  2785. static _injectScope(options) {
  2786. const scope = Utils.cloneDeep(this._scope);
  2787. this._defaultsOptions(options, scope);
  2788. }
  2789. static [Symbol.for('nodejs.util.inspect.custom')]() {
  2790. return this.name;
  2791. }
  2792. static hasAlias(alias) {
  2793. return Object.prototype.hasOwnProperty.call(this.associations, alias);
  2794. }
  2795. /**
  2796. * 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
  2797. * ``` SET column = column + X WHERE foo = 'bar' ``` query. To get the correct value after an increment into the Instance you should do a reload.
  2798. *
  2799. * @example <caption>increment number by 1</caption>
  2800. * Model.increment('number', { where: { foo: 'bar' });
  2801. *
  2802. * @example <caption>increment number and count by 2</caption>
  2803. * Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
  2804. *
  2805. * @example <caption>increment answer by 42, and decrement tries by 1</caption>
  2806. * // `by` is ignored, as each column has its own value
  2807. * Model.increment({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
  2808. *
  2809. * @see
  2810. * {@link Model#reload}
  2811. *
  2812. * @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.
  2813. * @param {object} options increment options
  2814. * @param {object} options.where conditions hash
  2815. * @param {number} [options.by=1] The number to increment by
  2816. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  2817. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  2818. * @param {Transaction} [options.transaction] Transaction to run query under
  2819. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  2820. *
  2821. * @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect
  2822. */
  2823. static async increment(fields, options) {
  2824. options = options || {};
  2825. if (typeof fields === 'string') fields = [fields];
  2826. if (Array.isArray(fields)) {
  2827. fields = fields.map(f => {
  2828. if (this.rawAttributes[f] && this.rawAttributes[f].field && this.rawAttributes[f].field !== f) {
  2829. return this.rawAttributes[f].field;
  2830. }
  2831. return f;
  2832. });
  2833. }
  2834. this._injectScope(options);
  2835. this._optionsMustContainWhere(options);
  2836. options = Utils.defaults({}, options, {
  2837. by: 1,
  2838. where: {},
  2839. increment: true
  2840. });
  2841. const isSubtraction = !options.increment;
  2842. Utils.mapOptionFieldNames(options, this);
  2843. const where = { ...options.where };
  2844. // A plain object whose keys are the fields to be incremented and whose values are
  2845. // the amounts to be incremented by.
  2846. let incrementAmountsByField = {};
  2847. if (Array.isArray(fields)) {
  2848. incrementAmountsByField = {};
  2849. for (const field of fields) {
  2850. incrementAmountsByField[field] = options.by;
  2851. }
  2852. } else {
  2853. // If the `fields` argument is not an array, then we assume it already has the
  2854. // form necessary to be placed directly in the `incrementAmountsByField` variable.
  2855. incrementAmountsByField = fields;
  2856. }
  2857. // If optimistic locking is enabled, we can take advantage that this is an
  2858. // increment/decrement operation and send it here as well. We put `-1` for
  2859. // decrementing because it will be subtracted, getting `-(-1)` which is `+1`
  2860. if (this._versionAttribute) {
  2861. incrementAmountsByField[this._versionAttribute] = isSubtraction ? -1 : 1;
  2862. }
  2863. const extraAttributesToBeUpdated = {};
  2864. const updatedAtAttr = this._timestampAttributes.updatedAt;
  2865. if (!options.silent && updatedAtAttr && !incrementAmountsByField[updatedAtAttr]) {
  2866. const attrName = this.rawAttributes[updatedAtAttr].field || updatedAtAttr;
  2867. extraAttributesToBeUpdated[attrName] = this._getDefaultTimestamp(updatedAtAttr) || Utils.now(this.sequelize.options.dialect);
  2868. }
  2869. const tableName = this.getTableName(options);
  2870. let affectedRows;
  2871. if (isSubtraction) {
  2872. affectedRows = await this.queryInterface.decrement(
  2873. this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options
  2874. );
  2875. } else {
  2876. affectedRows = await this.queryInterface.increment(
  2877. this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options
  2878. );
  2879. }
  2880. if (options.returning) {
  2881. return [affectedRows, affectedRows.length];
  2882. }
  2883. return [affectedRows];
  2884. }
  2885. /**
  2886. * 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
  2887. * ```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.
  2888. *
  2889. * @example <caption>decrement number by 1</caption>
  2890. * Model.decrement('number', { where: { foo: 'bar' });
  2891. *
  2892. * @example <caption>decrement number and count by 2</caption>
  2893. * Model.decrement(['number', 'count'], { by: 2, where: { foo: 'bar' } });
  2894. *
  2895. * @example <caption>decrement answer by 42, and decrement tries by -1</caption>
  2896. * // `by` is ignored, since each column has its own value
  2897. * Model.decrement({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
  2898. *
  2899. * @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.
  2900. * @param {object} options decrement options, similar to increment
  2901. *
  2902. * @see
  2903. * {@link Model.increment}
  2904. * @see
  2905. * {@link Model#reload}
  2906. * @since 4.36.0
  2907. *
  2908. * @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect
  2909. */
  2910. static async decrement(fields, options) {
  2911. return this.increment(fields, {
  2912. by: 1,
  2913. ...options,
  2914. increment: false
  2915. });
  2916. }
  2917. static _optionsMustContainWhere(options) {
  2918. assert(options && options.where, 'Missing where attribute in the options parameter');
  2919. assert(_.isPlainObject(options.where) || Array.isArray(options.where) || options.where instanceof Utils.SequelizeMethod,
  2920. 'Expected plain object, array or sequelize method in the options.where parameter');
  2921. }
  2922. /**
  2923. * Get an object representing the query for this instance, use with `options.where`
  2924. *
  2925. * @param {boolean} [checkVersion=false] include version attribute in where hash
  2926. *
  2927. * @returns {object}
  2928. */
  2929. where(checkVersion) {
  2930. const where = this.constructor.primaryKeyAttributes.reduce((result, attribute) => {
  2931. result[attribute] = this.get(attribute, { raw: true });
  2932. return result;
  2933. }, {});
  2934. if (_.size(where) === 0) {
  2935. return this.constructor.options.whereCollection;
  2936. }
  2937. const versionAttr = this.constructor._versionAttribute;
  2938. if (checkVersion && versionAttr) {
  2939. where[versionAttr] = this.get(versionAttr, { raw: true });
  2940. }
  2941. return Utils.mapWhereFieldNames(where, this.constructor);
  2942. }
  2943. toString() {
  2944. return `[object SequelizeInstance:${this.constructor.name}]`;
  2945. }
  2946. /**
  2947. * Get the value of the underlying data value
  2948. *
  2949. * @param {string} key key to look in instance data store
  2950. *
  2951. * @returns {any}
  2952. */
  2953. getDataValue(key) {
  2954. return this.dataValues[key];
  2955. }
  2956. /**
  2957. * Update the underlying data value
  2958. *
  2959. * @param {string} key key to set in instance data store
  2960. * @param {any} value new value for given key
  2961. *
  2962. */
  2963. setDataValue(key, value) {
  2964. const originalValue = this._previousDataValues[key];
  2965. if (!_.isEqual(value, originalValue)) {
  2966. this.changed(key, true);
  2967. }
  2968. this.dataValues[key] = value;
  2969. }
  2970. /**
  2971. * If no key is given, returns all values of the instance, also invoking virtual getters.
  2972. *
  2973. * 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.
  2974. *
  2975. * @param {string} [key] key to get value of
  2976. * @param {object} [options] get options
  2977. * @param {boolean} [options.plain=false] If set to true, included instances will be returned as plain objects
  2978. * @param {boolean} [options.raw=false] If set to true, field and virtual setters will be ignored
  2979. *
  2980. * @returns {object|any}
  2981. */
  2982. get(key, options) {
  2983. if (options === undefined && typeof key === 'object') {
  2984. options = key;
  2985. key = undefined;
  2986. }
  2987. options = options || {};
  2988. if (key) {
  2989. if (Object.prototype.hasOwnProperty.call(this._customGetters, key) && !options.raw) {
  2990. return this._customGetters[key].call(this, key, options);
  2991. }
  2992. if (options.plain && this._options.include && this._options.includeNames.includes(key)) {
  2993. if (Array.isArray(this.dataValues[key])) {
  2994. return this.dataValues[key].map(instance => instance.get(options));
  2995. }
  2996. if (this.dataValues[key] instanceof Model) {
  2997. return this.dataValues[key].get(options);
  2998. }
  2999. return this.dataValues[key];
  3000. }
  3001. return this.dataValues[key];
  3002. }
  3003. if (
  3004. this._hasCustomGetters
  3005. || options.plain && this._options.include
  3006. || options.clone
  3007. ) {
  3008. const values = {};
  3009. let _key;
  3010. if (this._hasCustomGetters) {
  3011. for (_key in this._customGetters) {
  3012. if (
  3013. this._options.attributes
  3014. && !this._options.attributes.includes(_key)
  3015. ) {
  3016. continue;
  3017. }
  3018. if (Object.prototype.hasOwnProperty.call(this._customGetters, _key)) {
  3019. values[_key] = this.get(_key, options);
  3020. }
  3021. }
  3022. }
  3023. for (_key in this.dataValues) {
  3024. if (
  3025. !Object.prototype.hasOwnProperty.call(values, _key)
  3026. && Object.prototype.hasOwnProperty.call(this.dataValues, _key)
  3027. ) {
  3028. values[_key] = this.get(_key, options);
  3029. }
  3030. }
  3031. return values;
  3032. }
  3033. return this.dataValues;
  3034. }
  3035. /**
  3036. * 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`).
  3037. * 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
  3038. * will be called instead. To bypass the setter, you can pass `raw: true` in the options object.
  3039. *
  3040. * 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
  3041. * set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
  3042. *
  3043. * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
  3044. *
  3045. * Set can also be used to build instances for associations, if you have values for those.
  3046. * When using set with associations you need to make sure the property key matches the alias of the association
  3047. * while also making sure that the proper include options have been set (from .build() or .findOne())
  3048. *
  3049. * 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.
  3050. *
  3051. * @see
  3052. * {@link Model.findAll} for more information about includes
  3053. *
  3054. * @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.
  3055. * @param {any} value value to set
  3056. * @param {object} [options] set options
  3057. * @param {boolean} [options.raw=false] If set to true, field and virtual setters will be ignored
  3058. * @param {boolean} [options.reset=false] Clear all previously set data values
  3059. *
  3060. * @returns {Model}
  3061. */
  3062. set(key, value, options) {
  3063. let values;
  3064. let originalValue;
  3065. if (typeof key === 'object' && key !== null) {
  3066. values = key;
  3067. options = value || {};
  3068. if (options.reset) {
  3069. this.dataValues = {};
  3070. for (const key in values) {
  3071. this.changed(key, false);
  3072. }
  3073. }
  3074. // If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object
  3075. if (options.raw && !(this._options && this._options.include) && !(options && options.attributes) && !this.constructor._hasDateAttributes && !this.constructor._hasBooleanAttributes) {
  3076. if (Object.keys(this.dataValues).length) {
  3077. Object.assign(this.dataValues, values);
  3078. } else {
  3079. this.dataValues = values;
  3080. }
  3081. // If raw, .changed() shouldn't be true
  3082. this._previousDataValues = { ...this.dataValues };
  3083. } else {
  3084. // Loop and call set
  3085. if (options.attributes) {
  3086. const setKeys = data => {
  3087. for (const k of data) {
  3088. if (values[k] === undefined) {
  3089. continue;
  3090. }
  3091. this.set(k, values[k], options);
  3092. }
  3093. };
  3094. setKeys(options.attributes);
  3095. if (this.constructor._hasVirtualAttributes) {
  3096. setKeys(this.constructor._virtualAttributes);
  3097. }
  3098. if (this._options.includeNames) {
  3099. setKeys(this._options.includeNames);
  3100. }
  3101. } else {
  3102. for (const key in values) {
  3103. this.set(key, values[key], options);
  3104. }
  3105. }
  3106. if (options.raw) {
  3107. // If raw, .changed() shouldn't be true
  3108. this._previousDataValues = { ...this.dataValues };
  3109. }
  3110. }
  3111. return this;
  3112. }
  3113. if (!options)
  3114. options = {};
  3115. if (!options.raw) {
  3116. originalValue = this.dataValues[key];
  3117. }
  3118. // If not raw, and there's a custom setter
  3119. if (!options.raw && this._customSetters[key]) {
  3120. this._customSetters[key].call(this, value, key);
  3121. // custom setter should have changed value, get that changed value
  3122. // TODO: v5 make setters return new value instead of changing internal store
  3123. const newValue = this.dataValues[key];
  3124. if (!_.isEqual(newValue, originalValue)) {
  3125. this._previousDataValues[key] = originalValue;
  3126. this.changed(key, true);
  3127. }
  3128. } else {
  3129. // Check if we have included models, and if this key matches the include model names/aliases
  3130. if (this._options && this._options.include && this._options.includeNames.includes(key)) {
  3131. // Pass it on to the include handler
  3132. this._setInclude(key, value, options);
  3133. return this;
  3134. }
  3135. // Bunch of stuff we won't do when it's raw
  3136. if (!options.raw) {
  3137. // If attribute is not in model definition, return
  3138. if (!this._isAttribute(key)) {
  3139. if (key.includes('.') && this.constructor._jsonAttributes.has(key.split('.')[0])) {
  3140. const previousNestedValue = Dottie.get(this.dataValues, key);
  3141. if (!_.isEqual(previousNestedValue, value)) {
  3142. Dottie.set(this.dataValues, key, value);
  3143. this.changed(key.split('.')[0], true);
  3144. }
  3145. }
  3146. return this;
  3147. }
  3148. // If attempting to set primary key and primary key is already defined, return
  3149. if (this.constructor._hasPrimaryKeys && originalValue && this.constructor._isPrimaryKey(key)) {
  3150. return this;
  3151. }
  3152. // If attempting to set read only attributes, return
  3153. if (!this.isNewRecord && this.constructor._hasReadOnlyAttributes && this.constructor._readOnlyAttributes.has(key)) {
  3154. return this;
  3155. }
  3156. }
  3157. // If there's a data type sanitizer
  3158. if (
  3159. !(value instanceof Utils.SequelizeMethod)
  3160. && Object.prototype.hasOwnProperty.call(this.constructor._dataTypeSanitizers, key)
  3161. ) {
  3162. value = this.constructor._dataTypeSanitizers[key].call(this, value, options);
  3163. }
  3164. // Set when the value has changed and not raw
  3165. if (
  3166. !options.raw &&
  3167. (
  3168. // True when sequelize method
  3169. (value instanceof Utils.SequelizeMethod ||
  3170. // Check for data type type comparators
  3171. !(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) || // Check default
  3172. !this.constructor._dataTypeChanges[key] && !_.isEqual(value, originalValue))
  3173. )
  3174. ) {
  3175. this._previousDataValues[key] = originalValue;
  3176. this.changed(key, true);
  3177. }
  3178. // set data value
  3179. this.dataValues[key] = value;
  3180. }
  3181. return this;
  3182. }
  3183. setAttributes(updates) {
  3184. return this.set(updates);
  3185. }
  3186. /**
  3187. * 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`.
  3188. *
  3189. * If changed is called without an argument, it will return an array of keys that have changed.
  3190. *
  3191. * If changed is called without an argument and no keys have changed, it will return `false`.
  3192. *
  3193. * Please note that this function will return `false` when a property from a nested (for example JSON) property
  3194. * was edited manually, you must call `changed('key', true)` manually in these cases.
  3195. * Writing an entirely new object (eg. deep cloned) will be detected.
  3196. *
  3197. * @example
  3198. * ```
  3199. * const mdl = await MyModel.findOne();
  3200. * mdl.myJsonField.a = 1;
  3201. * console.log(mdl.changed()) => false
  3202. * mdl.save(); // this will not save anything
  3203. * mdl.changed('myJsonField', true);
  3204. * console.log(mdl.changed()) => ['myJsonField']
  3205. * mdl.save(); // will save
  3206. * ```
  3207. *
  3208. * @param {string} [key] key to check or change status of
  3209. * @param {any} [value] value to set
  3210. *
  3211. * @returns {boolean|Array}
  3212. */
  3213. changed(key, value) {
  3214. if (key === undefined) {
  3215. if (this._changed.size > 0) {
  3216. return Array.from(this._changed);
  3217. }
  3218. return false;
  3219. }
  3220. if (value === true) {
  3221. this._changed.add(key);
  3222. return this;
  3223. }
  3224. if (value === false) {
  3225. this._changed.delete(key);
  3226. return this;
  3227. }
  3228. return this._changed.has(key);
  3229. }
  3230. /**
  3231. * Returns the previous value for key from `_previousDataValues`.
  3232. *
  3233. * If called without a key, returns the previous values for all values which have changed
  3234. *
  3235. * @param {string} [key] key to get previous value of
  3236. *
  3237. * @returns {any|Array<any>}
  3238. */
  3239. previous(key) {
  3240. if (key) {
  3241. return this._previousDataValues[key];
  3242. }
  3243. return _.pickBy(this._previousDataValues, (value, key) => this.changed(key));
  3244. }
  3245. _setInclude(key, value, options) {
  3246. if (!Array.isArray(value)) value = [value];
  3247. if (value[0] instanceof Model) {
  3248. value = value.map(instance => instance.dataValues);
  3249. }
  3250. const include = this._options.includeMap[key];
  3251. const association = include.association;
  3252. const accessor = key;
  3253. const primaryKeyAttribute = include.model.primaryKeyAttribute;
  3254. const childOptions = {
  3255. isNewRecord: this.isNewRecord,
  3256. include: include.include,
  3257. includeNames: include.includeNames,
  3258. includeMap: include.includeMap,
  3259. includeValidated: true,
  3260. raw: options.raw,
  3261. attributes: include.originalAttributes
  3262. };
  3263. let isEmpty;
  3264. if (include.originalAttributes === undefined || include.originalAttributes.length) {
  3265. if (association.isSingleAssociation) {
  3266. if (Array.isArray(value)) {
  3267. value = value[0];
  3268. }
  3269. isEmpty = value && value[primaryKeyAttribute] === null || value === null;
  3270. this[accessor] = this.dataValues[accessor] = isEmpty ? null : include.model.build(value, childOptions);
  3271. } else {
  3272. isEmpty = value[0] && value[0][primaryKeyAttribute] === null;
  3273. this[accessor] = this.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
  3274. }
  3275. }
  3276. }
  3277. /**
  3278. * Validates this instance, and if the validation passes, persists it to the database.
  3279. *
  3280. * 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).
  3281. *
  3282. * This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed.
  3283. *
  3284. * 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.
  3285. *
  3286. * @param {object} [options] save options
  3287. * @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
  3288. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  3289. * @param {boolean} [options.validate=true] If false, validations won't be run.
  3290. * @param {boolean} [options.hooks=true] Run before and after create / update + validate hooks
  3291. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3292. * @param {Transaction} [options.transaction] Transaction to run query under
  3293. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3294. * @param {boolean} [options.returning] Append RETURNING * to get back auto generated values (Postgres only)
  3295. *
  3296. * @returns {Promise<Model>}
  3297. */
  3298. async save(options) {
  3299. if (arguments.length > 1) {
  3300. throw new Error('The second argument was removed in favor of the options object.');
  3301. }
  3302. options = Utils.cloneDeep(options);
  3303. options = _.defaults(options, {
  3304. hooks: true,
  3305. validate: true
  3306. });
  3307. if (!options.fields) {
  3308. if (this.isNewRecord) {
  3309. options.fields = Object.keys(this.constructor.rawAttributes);
  3310. } else {
  3311. options.fields = _.intersection(this.changed(), Object.keys(this.constructor.rawAttributes));
  3312. }
  3313. options.defaultFields = options.fields;
  3314. }
  3315. if (options.returning === undefined) {
  3316. if (options.association) {
  3317. options.returning = false;
  3318. } else if (this.isNewRecord) {
  3319. options.returning = true;
  3320. }
  3321. }
  3322. const primaryKeyName = this.constructor.primaryKeyAttribute;
  3323. const primaryKeyAttribute = primaryKeyName && this.constructor.rawAttributes[primaryKeyName];
  3324. const createdAtAttr = this.constructor._timestampAttributes.createdAt;
  3325. const versionAttr = this.constructor._versionAttribute;
  3326. const hook = this.isNewRecord ? 'Create' : 'Update';
  3327. const wasNewRecord = this.isNewRecord;
  3328. const now = Utils.now(this.sequelize.options.dialect);
  3329. let updatedAtAttr = this.constructor._timestampAttributes.updatedAt;
  3330. if (updatedAtAttr && options.fields.length >= 1 && !options.fields.includes(updatedAtAttr)) {
  3331. options.fields.push(updatedAtAttr);
  3332. }
  3333. if (versionAttr && options.fields.length >= 1 && !options.fields.includes(versionAttr)) {
  3334. options.fields.push(versionAttr);
  3335. }
  3336. if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, { raw: true }))) {
  3337. // UpdateAtAttr might have been added as a result of Object.keys(Model.rawAttributes). In that case we have to remove it again
  3338. _.remove(options.fields, val => val === updatedAtAttr);
  3339. updatedAtAttr = false;
  3340. }
  3341. if (this.isNewRecord === true) {
  3342. if (createdAtAttr && !options.fields.includes(createdAtAttr)) {
  3343. options.fields.push(createdAtAttr);
  3344. }
  3345. if (primaryKeyAttribute && primaryKeyAttribute.defaultValue && !options.fields.includes(primaryKeyName)) {
  3346. options.fields.unshift(primaryKeyName);
  3347. }
  3348. }
  3349. if (this.isNewRecord === false) {
  3350. if (primaryKeyName && this.get(primaryKeyName, { raw: true }) === undefined) {
  3351. 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');
  3352. }
  3353. }
  3354. if (updatedAtAttr && !options.silent && options.fields.includes(updatedAtAttr)) {
  3355. this.dataValues[updatedAtAttr] = this.constructor._getDefaultTimestamp(updatedAtAttr) || now;
  3356. }
  3357. if (this.isNewRecord && createdAtAttr && !this.dataValues[createdAtAttr]) {
  3358. this.dataValues[createdAtAttr] = this.constructor._getDefaultTimestamp(createdAtAttr) || now;
  3359. }
  3360. // Validate
  3361. if (options.validate) {
  3362. await this.validate(options);
  3363. }
  3364. // Run before hook
  3365. if (options.hooks) {
  3366. const beforeHookValues = _.pick(this.dataValues, options.fields);
  3367. 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
  3368. let hookChanged;
  3369. let afterHookValues;
  3370. if (updatedAtAttr && options.fields.includes(updatedAtAttr)) {
  3371. ignoreChanged = _.without(ignoreChanged, updatedAtAttr);
  3372. }
  3373. await this.constructor.runHooks(`before${hook}`, this, options);
  3374. if (options.defaultFields && !this.isNewRecord) {
  3375. afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));
  3376. hookChanged = [];
  3377. for (const key of Object.keys(afterHookValues)) {
  3378. if (afterHookValues[key] !== beforeHookValues[key]) {
  3379. hookChanged.push(key);
  3380. }
  3381. }
  3382. options.fields = _.uniq(options.fields.concat(hookChanged));
  3383. }
  3384. if (hookChanged) {
  3385. if (options.validate) {
  3386. // Validate again
  3387. options.skip = _.difference(Object.keys(this.constructor.rawAttributes), hookChanged);
  3388. await this.validate(options);
  3389. delete options.skip;
  3390. }
  3391. }
  3392. }
  3393. if (options.fields.length && this.isNewRecord && this._options.include && this._options.include.length) {
  3394. await Promise.all(this._options.include.filter(include => include.association instanceof BelongsTo).map(async include => {
  3395. const instance = this.get(include.as);
  3396. if (!instance) return;
  3397. const includeOptions = _(Utils.cloneDeep(include))
  3398. .omit(['association'])
  3399. .defaults({
  3400. transaction: options.transaction,
  3401. logging: options.logging,
  3402. parentRecord: this
  3403. }).value();
  3404. await instance.save(includeOptions);
  3405. await this[include.association.accessors.set](instance, { save: false, logging: options.logging });
  3406. }));
  3407. }
  3408. const realFields = options.fields.filter(field => !this.constructor._virtualAttributes.has(field));
  3409. if (!realFields.length) return this;
  3410. if (!this.changed() && !this.isNewRecord) return this;
  3411. const versionFieldName = _.get(this.constructor.rawAttributes[versionAttr], 'field') || versionAttr;
  3412. const values = Utils.mapValueFieldNames(this.dataValues, options.fields, this.constructor);
  3413. let query = null;
  3414. let args = [];
  3415. let where;
  3416. if (this.isNewRecord) {
  3417. query = 'insert';
  3418. args = [this, this.constructor.getTableName(options), values, options];
  3419. } else {
  3420. where = this.where(true);
  3421. if (versionAttr) {
  3422. values[versionFieldName] = parseInt(values[versionFieldName], 10) + 1;
  3423. }
  3424. query = 'update';
  3425. args = [this, this.constructor.getTableName(options), values, where, options];
  3426. }
  3427. const [result, rowsUpdated] = await this.constructor.queryInterface[query](...args);
  3428. if (versionAttr) {
  3429. // Check to see that a row was updated, otherwise it's an optimistic locking error.
  3430. if (rowsUpdated < 1) {
  3431. throw new sequelizeErrors.OptimisticLockError({
  3432. modelName: this.constructor.name,
  3433. values,
  3434. where
  3435. });
  3436. } else {
  3437. result.dataValues[versionAttr] = values[versionFieldName];
  3438. }
  3439. }
  3440. // Transfer database generated values (defaults, autoincrement, etc)
  3441. for (const attr of Object.keys(this.constructor.rawAttributes)) {
  3442. if (this.constructor.rawAttributes[attr].field &&
  3443. values[this.constructor.rawAttributes[attr].field] !== undefined &&
  3444. this.constructor.rawAttributes[attr].field !== attr
  3445. ) {
  3446. values[attr] = values[this.constructor.rawAttributes[attr].field];
  3447. delete values[this.constructor.rawAttributes[attr].field];
  3448. }
  3449. }
  3450. Object.assign(values, result.dataValues);
  3451. Object.assign(result.dataValues, values);
  3452. if (wasNewRecord && this._options.include && this._options.include.length) {
  3453. await Promise.all(
  3454. this._options.include.filter(include => !(include.association instanceof BelongsTo ||
  3455. include.parent && include.parent.association instanceof BelongsToMany)).map(async include => {
  3456. let instances = this.get(include.as);
  3457. if (!instances) return;
  3458. if (!Array.isArray(instances)) instances = [instances];
  3459. const includeOptions = _(Utils.cloneDeep(include))
  3460. .omit(['association'])
  3461. .defaults({
  3462. transaction: options.transaction,
  3463. logging: options.logging,
  3464. parentRecord: this
  3465. }).value();
  3466. // Instances will be updated in place so we can safely treat HasOne like a HasMany
  3467. await Promise.all(instances.map(async instance => {
  3468. if (include.association instanceof BelongsToMany) {
  3469. await instance.save(includeOptions);
  3470. const values0 = {
  3471. [include.association.foreignKey]: this.get(this.constructor.primaryKeyAttribute, { raw: true }),
  3472. [include.association.otherKey]: instance.get(instance.constructor.primaryKeyAttribute, { raw: true }),
  3473. // Include values defined in the association
  3474. ...include.association.through.scope
  3475. };
  3476. if (instance[include.association.through.model.name]) {
  3477. for (const attr of Object.keys(include.association.through.model.rawAttributes)) {
  3478. if (include.association.through.model.rawAttributes[attr]._autoGenerated ||
  3479. attr === include.association.foreignKey ||
  3480. attr === include.association.otherKey ||
  3481. typeof instance[include.association.through.model.name][attr] === undefined) {
  3482. continue;
  3483. }
  3484. values0[attr] = instance[include.association.through.model.name][attr];
  3485. }
  3486. }
  3487. await include.association.throughModel.create(values0, includeOptions);
  3488. } else {
  3489. instance.set(include.association.foreignKey, this.get(include.association.sourceKey || this.constructor.primaryKeyAttribute, { raw: true }), { raw: true });
  3490. Object.assign(instance, include.association.scope);
  3491. await instance.save(includeOptions);
  3492. }
  3493. }));
  3494. })
  3495. );
  3496. }
  3497. // Run after hook
  3498. if (options.hooks) {
  3499. await this.constructor.runHooks(`after${hook}`, result, options);
  3500. }
  3501. for (const field of options.fields) {
  3502. result._previousDataValues[field] = result.dataValues[field];
  3503. this.changed(field, false);
  3504. }
  3505. this.isNewRecord = false;
  3506. return result;
  3507. }
  3508. /**
  3509. * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
  3510. * This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
  3511. * all references to the Instance are updated with the new data and no new objects are created.
  3512. *
  3513. * @see
  3514. * {@link Model.findAll}
  3515. *
  3516. * @param {object} [options] Options that are passed on to `Model.find`
  3517. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3518. *
  3519. * @returns {Promise<Model>}
  3520. */
  3521. async reload(options) {
  3522. options = Utils.defaults({
  3523. where: this.where()
  3524. }, options, {
  3525. include: this._options.include || undefined
  3526. });
  3527. const reloaded = await this.constructor.findOne(options);
  3528. if (!reloaded) {
  3529. throw new sequelizeErrors.InstanceError(
  3530. 'Instance could not be reloaded because it does not exist anymore (find call returned null)'
  3531. );
  3532. }
  3533. // update the internal options of the instance
  3534. this._options = reloaded._options;
  3535. // re-set instance values
  3536. this.set(reloaded.dataValues, {
  3537. raw: true,
  3538. reset: true && !options.attributes
  3539. });
  3540. return this;
  3541. }
  3542. /**
  3543. * Validate the attributes of this instance according to validation rules set in the model definition.
  3544. *
  3545. * The promise fulfills if and only if validation successful; otherwise it rejects an Error instance containing { field name : [error msgs] } entries.
  3546. *
  3547. * @param {object} [options] Options that are passed to the validator
  3548. * @param {Array} [options.skip] An array of strings. All properties that are in this array will not be validated
  3549. * @param {Array} [options.fields] An array of strings. Only the properties that are in this array will be validated
  3550. * @param {boolean} [options.hooks=true] Run before and after validate hooks
  3551. *
  3552. * @returns {Promise}
  3553. */
  3554. async validate(options) {
  3555. return new InstanceValidator(this, options).validate();
  3556. }
  3557. /**
  3558. * This is the same as calling `set` and then calling `save` but it only saves the
  3559. * exact values passed to it, making it more atomic and safer.
  3560. *
  3561. * @see
  3562. * {@link Model#set}
  3563. * @see
  3564. * {@link Model#save}
  3565. *
  3566. * @param {object} values See `set`
  3567. * @param {object} options See `save`
  3568. *
  3569. * @returns {Promise<Model>}
  3570. */
  3571. async update(values, options) {
  3572. // Clone values so it doesn't get modified for caller scope and ignore undefined values
  3573. values = _.omitBy(values, value => value === undefined);
  3574. const changedBefore = this.changed() || [];
  3575. options = options || {};
  3576. if (Array.isArray(options)) options = { fields: options };
  3577. options = Utils.cloneDeep(options);
  3578. const setOptions = Utils.cloneDeep(options);
  3579. setOptions.attributes = options.fields;
  3580. this.set(values, setOptions);
  3581. // Now we need to figure out which fields were actually affected by the setter.
  3582. const sideEffects = _.without(this.changed(), ...changedBefore);
  3583. const fields = _.union(Object.keys(values), sideEffects);
  3584. if (!options.fields) {
  3585. options.fields = _.intersection(fields, this.changed());
  3586. options.defaultFields = options.fields;
  3587. }
  3588. return await this.save(options);
  3589. }
  3590. /**
  3591. * 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.
  3592. *
  3593. * @param {object} [options={}] destroy options
  3594. * @param {boolean} [options.force=false] If set to true, paranoid models will actually be deleted
  3595. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3596. * @param {Transaction} [options.transaction] Transaction to run query under
  3597. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3598. *
  3599. * @returns {Promise}
  3600. */
  3601. async destroy(options) {
  3602. options = {
  3603. hooks: true,
  3604. force: false,
  3605. ...options
  3606. };
  3607. // Run before hook
  3608. if (options.hooks) {
  3609. await this.constructor.runHooks('beforeDestroy', this, options);
  3610. }
  3611. const where = this.where(true);
  3612. let result;
  3613. if (this.constructor._timestampAttributes.deletedAt && options.force === false) {
  3614. const attributeName = this.constructor._timestampAttributes.deletedAt;
  3615. const attribute = this.constructor.rawAttributes[attributeName];
  3616. const defaultValue = Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')
  3617. ? attribute.defaultValue
  3618. : null;
  3619. const currentValue = this.getDataValue(attributeName);
  3620. const undefinedOrNull = currentValue == null && defaultValue == null;
  3621. if (undefinedOrNull || _.isEqual(currentValue, defaultValue)) {
  3622. // only update timestamp if it wasn't already set
  3623. this.setDataValue(attributeName, new Date());
  3624. }
  3625. result = await this.save({ ...options, hooks: false });
  3626. } else {
  3627. result = await this.constructor.queryInterface.delete(this, this.constructor.getTableName(options), where, { type: QueryTypes.DELETE, limit: null, ...options });
  3628. }
  3629. // Run after hook
  3630. if (options.hooks) {
  3631. await this.constructor.runHooks('afterDestroy', this, options);
  3632. }
  3633. return result;
  3634. }
  3635. /**
  3636. * Helper method to determine if a instance is "soft deleted". This is
  3637. * particularly useful if the implementer renamed the `deletedAt` attribute
  3638. * to something different. This method requires `paranoid` to be enabled.
  3639. *
  3640. * @returns {boolean}
  3641. */
  3642. isSoftDeleted() {
  3643. if (!this.constructor._timestampAttributes.deletedAt) {
  3644. throw new Error('Model is not paranoid');
  3645. }
  3646. const deletedAtAttribute = this.constructor.rawAttributes[this.constructor._timestampAttributes.deletedAt];
  3647. const defaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null;
  3648. const deletedAt = this.get(this.constructor._timestampAttributes.deletedAt) || null;
  3649. const isSet = deletedAt !== defaultValue;
  3650. return isSet;
  3651. }
  3652. /**
  3653. * Restore the row corresponding to this instance. Only available for paranoid models.
  3654. *
  3655. * @param {object} [options={}] restore options
  3656. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3657. * @param {Transaction} [options.transaction] Transaction to run query under
  3658. *
  3659. * @returns {Promise}
  3660. */
  3661. async restore(options) {
  3662. if (!this.constructor._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
  3663. options = {
  3664. hooks: true,
  3665. force: false,
  3666. ...options
  3667. };
  3668. // Run before hook
  3669. if (options.hooks) {
  3670. await this.constructor.runHooks('beforeRestore', this, options);
  3671. }
  3672. const deletedAtCol = this.constructor._timestampAttributes.deletedAt;
  3673. const deletedAtAttribute = this.constructor.rawAttributes[deletedAtCol];
  3674. const deletedAtDefaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null;
  3675. this.setDataValue(deletedAtCol, deletedAtDefaultValue);
  3676. const result = await this.save({ ...options, hooks: false, omitNull: false });
  3677. // Run after hook
  3678. if (options.hooks) {
  3679. await this.constructor.runHooks('afterRestore', this, options);
  3680. return result;
  3681. }
  3682. return result;
  3683. }
  3684. /**
  3685. * 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
  3686. * ```sql
  3687. * SET column = column + X
  3688. * ```
  3689. * 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.
  3690. *
  3691. * @example
  3692. * instance.increment('number') // increment number by 1
  3693. *
  3694. * instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
  3695. *
  3696. * // increment answer by 42, and tries by 1.
  3697. * // `by` is ignored, since each column has its own value
  3698. * instance.increment({ answer: 42, tries: 1}, { by: 2 })
  3699. *
  3700. * @see
  3701. * {@link Model#reload}
  3702. *
  3703. * @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.
  3704. * @param {object} [options] options
  3705. * @param {number} [options.by=1] The number to increment by
  3706. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  3707. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3708. * @param {Transaction} [options.transaction] Transaction to run query under
  3709. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3710. * @param {boolean} [options.returning=true] Append RETURNING * to get back auto generated values (Postgres only)
  3711. *
  3712. * @returns {Promise<Model>}
  3713. * @since 4.0.0
  3714. */
  3715. async increment(fields, options) {
  3716. const identifier = this.where();
  3717. options = Utils.cloneDeep(options);
  3718. options.where = { ...options.where, ...identifier };
  3719. options.instance = this;
  3720. await this.constructor.increment(fields, options);
  3721. return this;
  3722. }
  3723. /**
  3724. * 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
  3725. * ```sql
  3726. * SET column = column - X
  3727. * ```
  3728. * 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.
  3729. *
  3730. * @example
  3731. * instance.decrement('number') // decrement number by 1
  3732. *
  3733. * instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
  3734. *
  3735. * // decrement answer by 42, and tries by 1.
  3736. * // `by` is ignored, since each column has its own value
  3737. * instance.decrement({ answer: 42, tries: 1}, { by: 2 })
  3738. *
  3739. * @see
  3740. * {@link Model#reload}
  3741. * @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
  3742. * @param {object} [options] decrement options
  3743. * @param {number} [options.by=1] The number to decrement by
  3744. * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
  3745. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
  3746. * @param {Transaction} [options.transaction] Transaction to run query under
  3747. * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
  3748. * @param {boolean} [options.returning=true] Append RETURNING * to get back auto generated values (Postgres only)
  3749. *
  3750. * @returns {Promise}
  3751. */
  3752. async decrement(fields, options) {
  3753. return this.increment(fields, {
  3754. by: 1,
  3755. ...options,
  3756. increment: false
  3757. });
  3758. }
  3759. /**
  3760. * Check whether this and `other` Instance refer to the same row
  3761. *
  3762. * @param {Model} other Other instance to compare against
  3763. *
  3764. * @returns {boolean}
  3765. */
  3766. equals(other) {
  3767. if (!other || !other.constructor) {
  3768. return false;
  3769. }
  3770. if (!(other instanceof this.constructor)) {
  3771. return false;
  3772. }
  3773. return this.constructor.primaryKeyAttributes.every(attribute => this.get(attribute, { raw: true }) === other.get(attribute, { raw: true }));
  3774. }
  3775. /**
  3776. * Check if this is equal to one of `others` by calling equals
  3777. *
  3778. * @param {Array<Model>} others An array of instances to check against
  3779. *
  3780. * @returns {boolean}
  3781. */
  3782. equalsOneOf(others) {
  3783. return others.some(other => this.equals(other));
  3784. }
  3785. setValidators(attribute, validators) {
  3786. this.validators[attribute] = validators;
  3787. }
  3788. /**
  3789. * Convert the instance to a JSON representation.
  3790. * Proxies to calling `get` with no keys.
  3791. * This means get all values gotten from the DB, and apply all custom getters.
  3792. *
  3793. * @see
  3794. * {@link Model#get}
  3795. *
  3796. * @returns {object}
  3797. */
  3798. toJSON() {
  3799. return _.cloneDeep(
  3800. this.get({
  3801. plain: true
  3802. })
  3803. );
  3804. }
  3805. /**
  3806. * Creates a 1:m association between this (the source) and the provided target.
  3807. * The foreign key is added on the target.
  3808. *
  3809. * @param {Model} target Target model
  3810. * @param {object} [options] hasMany association options
  3811. * @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
  3812. * @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
  3813. * @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
  3814. * @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
  3815. * @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)
  3816. * @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
  3817. * @param {string} [options.onUpdate='CASCADE'] Set `ON UPDATE`
  3818. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3819. *
  3820. * @returns {HasMany}
  3821. *
  3822. * @example
  3823. * User.hasMany(Profile) // This will add userId to the profile table
  3824. */
  3825. static hasMany(target, options) {} // eslint-disable-line
  3826. /**
  3827. * Create an N:M association with a join table. Defining `through` is required.
  3828. *
  3829. * @param {Model} target Target model
  3830. * @param {object} options belongsToMany association options
  3831. * @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
  3832. * @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.
  3833. * @param {Model} [options.through.model] The model used to join both sides of the N:M association.
  3834. * @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)
  3835. * @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)
  3836. * @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
  3837. * @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
  3838. * @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
  3839. * @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)
  3840. * @param {boolean} [options.timestamps=sequelize.options.timestamps] Should the join model have timestamps
  3841. * @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m
  3842. * @param {string} [options.onUpdate='CASCADE'] Sets `ON UPDATE`
  3843. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3844. *
  3845. * @returns {BelongsToMany}
  3846. *
  3847. * @example
  3848. * // Automagically generated join model
  3849. * User.belongsToMany(Project, { through: 'UserProjects' })
  3850. * Project.belongsToMany(User, { through: 'UserProjects' })
  3851. *
  3852. * // Join model with additional attributes
  3853. * const UserProjects = sequelize.define('UserProjects', {
  3854. * started: Sequelize.BOOLEAN
  3855. * })
  3856. * User.belongsToMany(Project, { through: UserProjects })
  3857. * Project.belongsToMany(User, { through: UserProjects })
  3858. */
  3859. static belongsToMany(target, options) {} // eslint-disable-line
  3860. /**
  3861. * Creates an association between this (the source) and the provided target. The foreign key is added on the target.
  3862. *
  3863. * @param {Model} target Target model
  3864. * @param {object} [options] hasOne association options
  3865. * @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
  3866. * @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
  3867. * @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
  3868. * @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
  3869. * @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise
  3870. * @param {string} [options.onUpdate='CASCADE'] Sets 'ON UPDATE'
  3871. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3872. * @param {string} [options.uniqueKey] The custom name for unique constraint.
  3873. *
  3874. * @returns {HasOne}
  3875. *
  3876. * @example
  3877. * User.hasOne(Profile) // This will add userId to the profile table
  3878. */
  3879. static hasOne(target, options) {} // eslint-disable-line
  3880. /**
  3881. * Creates an association between this (the source) and the provided target. The foreign key is added on the source.
  3882. *
  3883. * @param {Model} target The target model
  3884. * @param {object} [options] belongsTo association options
  3885. * @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
  3886. * @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
  3887. * @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
  3888. * @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
  3889. * @param {string} [options.onDelete='SET&nbsp;NULL|NO&nbsp;ACTION'] SET NULL if foreignKey allows nulls, NO ACTION if otherwise
  3890. * @param {string} [options.onUpdate='CASCADE'] Sets 'ON UPDATE'
  3891. * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
  3892. *
  3893. * @returns {BelongsTo}
  3894. *
  3895. * @example
  3896. * Profile.belongsTo(User) // This will add userId to the profile table
  3897. */
  3898. static belongsTo(target, options) {} // eslint-disable-line
  3899. }
  3900. Object.assign(Model, associationsMixin);
  3901. Hooks.applyTo(Model, true);
  3902. module.exports = Model;