model.js 191 KB

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