UNPKG

233 kBTypeScriptView Raw
1// Type definitions for Sequelize 4.28.0
2// Project: http://sequelizejs.com, https://github.com/sequelize/sequelize
3// Definitions by: samuelneff <https://github.com/samuelneff>
4// Peter Harris <https://github.com/codeanimal>
5// Ivan Drinchev <https://github.com/drinchev>
6// Brendan Abolivier <https://github.com/babolivier>
7// Patsakol Tangjitcharoenchai <https://github.com/kukoo1>
8// Sebastien Bramille <https://github.com/oktapodia>
9// Nick Mueller <https://github.com/morpheusxaut>
10// Philippe D'Alva <https://github.com/TitaneBoy>
11// Carven Zhang <https://github.com/zjy01>
12// Nikola Vidic <https://github.com/nidzov>
13// Florian Oellerich <https://github.com/Raigen>
14// Todd Bealmear <https://github.com/todd>
15// Nick Schultz <https://github.com/nrschultz>
16// Thomas Breleur <https://github.com/thomas-b>
17// Antoine Boisadam <https://github.com/Antoine38660>
18// Dima Smirnov <https://github.com/smff>
19// Duy Truong <https://github.com/truongkhanhduy95>
20// Emmanuel Gautier <https://github.com/emmanuelgautier>
21// Dan Rumney <https://github.com/dancrumb>
22// Kan Yueh Chen <https://github.com/lalayueh>
23// Rohit Sud <https://github.com/rohitsud>
24// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
25// TypeScript Version: 3.2
26
27// ***************************** IMPORTANT NOTE *****************************
28// These types are for the 4.x branch of Sequelize. As of Sequelize 5.0,
29// types are packaged directly within Sequelize itself. Please target the
30// Sequelize-provided types for any changes related to versions >= 5.0.
31
32// Based on original work by: samuelneff <https://github.com/samuelneff/sequelize-auto-ts/blob/master/lib/sequelize.d.ts>
33
34import * as _ from "lodash";
35import Promise = require("bluebird");
36import * as cls from "continuation-local-storage"
37
38import ValidatorJS from 'validator'
39
40type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
41
42declare namespace sequelize {
43
44 //
45 // Associations
46 // ~~~~~~~~~~~~~~
47 //
48 // https://github.com/sequelize/sequelize/tree/v3.4.1/lib/associations
49 //
50
51
52 /**
53 * The options for the getAssociation mixin of the belongsTo association.
54 * @see BelongsToGetAssociationMixin
55 */
56 interface BelongsToGetAssociationMixinOptions {
57 /**
58 * Apply a scope on the related model, or remove its default scope by passing false.
59 */
60 scope?: string | boolean;
61 }
62
63 /**
64 * The getAssociation mixin applied to models with belongsTo.
65 * An example of usage is as follows:
66 *
67 * ```js
68 *
69 * User.belongsTo(Role);
70 *
71 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttrib>, UserAttrib {
72 * getRole: Sequelize.BelongsToGetAssociationMixin<RoleInstance>;
73 * // setRole...
74 * // createRole...
75 * }
76 * ```
77 *
78 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/
79 * @see Instance
80 */
81 interface BelongsToGetAssociationMixin<TInstance> {
82 /**
83 * Get the associated instance.
84 * @param options The options to use when getting the association.
85 */
86 (options?: BelongsToGetAssociationMixinOptions): Promise<TInstance | null>;
87 }
88
89 /**
90 * The options for the setAssociation mixin of the belongsTo association.
91 * @see BelongsToSetAssociationMixin
92 */
93 interface BelongsToSetAssociationMixinOptions {
94 /**
95 * Skip saving this after setting the foreign key if false.
96 */
97 save?: boolean;
98 }
99
100 /**
101 * The setAssociation mixin applied to models with belongsTo.
102 * An example of usage is as follows:
103 *
104 * ```js
105 *
106 * User.belongsTo(Role);
107 *
108 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
109 * // getRole...
110 * setRole: Sequelize.BelongsToSetAssociationMixin<RoleInstance, RoleId>;
111 * // createRole...
112 * }
113 * ```
114 *
115 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/
116 * @see Instance
117 */
118 interface BelongsToSetAssociationMixin<TInstance, TInstancePrimaryKey> {
119 /**
120 * Set the associated instance.
121 * @param newAssociation An instance or the primary key of an instance to associate with this. Pass null or undefined to remove the association.
122 * @param options the options passed to `this.save`.
123 */
124 (
125 newAssociation?: TInstance | TInstancePrimaryKey,
126 options?: BelongsToSetAssociationMixinOptions | InstanceSaveOptions
127 ): Promise<void>;
128 }
129
130 /**
131 * The options for the createAssociation mixin of the belongsTo association.
132 * @see BelongsToCreateAssociationMixin
133 */
134 interface BelongsToCreateAssociationMixinOptions { }
135
136 /**
137 * The createAssociation mixin applied to models with belongsTo.
138 * An example of usage is as follows:
139 *
140 * ```js
141 *
142 * User.belongsTo(Role);
143 *
144 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
145 * // getRole...
146 * // setRole...
147 * createRole: Sequelize.BelongsToCreateAssociationMixin<RoleAttributes>;
148 * }
149 * ```
150 *
151 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/
152 * @see Instance
153 */
154 interface BelongsToCreateAssociationMixin<TAttributes, TInstance> {
155 /**
156 * Create a new instance of the associated model and associate it with this.
157 * @param values The values used to create the association.
158 * @param options The options passed to `target.create` and `setAssociation`.
159 */
160 (
161 values?: TAttributes,
162 options?: BelongsToCreateAssociationMixinOptions | CreateOptions | BelongsToSetAssociationMixinOptions
163 ): Promise<TInstance>;
164 }
165
166 /**
167 * The options for the getAssociation mixin of the hasOne association.
168 * @see HasOneGetAssociationMixin
169 */
170 interface HasOneGetAssociationMixinOptions {
171 /**
172 * Apply a scope on the related model, or remove its default scope by passing false.
173 */
174 scope?: string | boolean;
175 }
176
177 /**
178 * The getAssociation mixin applied to models with hasOne.
179 * An example of usage is as follows:
180 *
181 * ```js
182 *
183 * User.hasOne(Role);
184 *
185 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttrib>, UserAttrib {
186 * getRole: Sequelize.HasOneGetAssociationMixin<RoleInstance>;
187 * // setRole...
188 * // createRole...
189 * }
190 * ```
191 *
192 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/
193 * @see Instance
194 */
195 interface HasOneGetAssociationMixin<TInstance> {
196 /**
197 * Get the associated instance.
198 * @param options The options to use when getting the association.
199 */
200 (options?: HasOneGetAssociationMixinOptions): Promise<TInstance | null>;
201 }
202
203 /**
204 * The options for the setAssociation mixin of the hasOne association.
205 * @see HasOneSetAssociationMixin
206 */
207 interface HasOneSetAssociationMixinOptions {
208 /**
209 * Skip saving this after setting the foreign key if false.
210 */
211 save?: boolean;
212 }
213
214 /**
215 * The setAssociation mixin applied to models with hasOne.
216 * An example of usage is as follows:
217 *
218 * ```js
219 *
220 * User.hasOne(Role);
221 *
222 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
223 * // getRole...
224 * setRole: Sequelize.HasOneSetAssociationMixin<RoleInstance, RoleId>;
225 * // createRole...
226 * }
227 * ```
228 *
229 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/
230 * @see Instance
231 */
232 interface HasOneSetAssociationMixin<TInstance, TInstancePrimaryKey> {
233 /**
234 * Set the associated instance.
235 * @param newAssociation An instance or the primary key of an instance to associate with this. Pass null or undefined to remove the association.
236 * @param options The options passed to `getAssocation` and `target.save`.
237 */
238 (
239 newAssociation?: TInstance | TInstancePrimaryKey,
240 options?: HasOneSetAssociationMixinOptions | HasOneGetAssociationMixinOptions | InstanceSaveOptions
241 ): Promise<void>;
242 }
243
244 /**
245 * The options for the createAssociation mixin of the hasOne association.
246 * @see HasOneCreateAssociationMixin
247 */
248 interface HasOneCreateAssociationMixinOptions { }
249
250 /**
251 * The createAssociation mixin applied to models with hasOne.
252 * An example of usage is as follows:
253 *
254 * ```js
255 *
256 * User.hasOne(Role);
257 *
258 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
259 * // getRole...
260 * // setRole...
261 * createRole: Sequelize.HasOneCreateAssociationMixin<RoleAttributes>;
262 * }
263 * ```
264 *
265 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-one/
266 * @see Instance
267 */
268 interface HasOneCreateAssociationMixin<TAttributes> {
269 /**
270 * Create a new instance of the associated model and associate it with this.
271 * @param values The values used to create the association.
272 * @param options The options passed to `target.create` and `setAssociation`.
273 */
274 (
275 values?: TAttributes,
276 options?: HasOneCreateAssociationMixinOptions | HasOneSetAssociationMixinOptions | CreateOptions
277 ): Promise<void>;
278 }
279
280 /**
281 * The options for the getAssociations mixin of the hasMany association.
282 * @see HasManyGetAssociationsMixin
283 */
284 interface HasManyGetAssociationsMixinOptions {
285
286 /**
287 * An optional where clause to limit the associated models.
288 */
289 where?: AnyWhereOptions;
290
291 /**
292 * Apply a scope on the related model, or remove its default scope by passing false.
293 */
294 scope?: string | boolean;
295
296 /**
297 * Load further nested related models
298 */
299 include?: IncludeOptions;
300 }
301
302 /**
303 * The getAssociations mixin applied to models with hasMany.
304 * An example of usage is as follows:
305 *
306 * ```js
307 *
308 * User.hasMany(Role);
309 *
310 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
311 * getRoles: Sequelize.HasManyGetAssociationsMixin<RoleInstance>;
312 * // setRoles...
313 * // addRoles...
314 * // addRole...
315 * // createRole...
316 * // removeRole...
317 * // removeRoles...
318 * // hasRole...
319 * // hasRoles...
320 * // countRoles...
321 * }
322 * ```
323 *
324 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
325 * @see Instance
326 */
327 interface HasManyGetAssociationsMixin<TInstance> {
328 /**
329 * Get everything currently associated with this, using an optional where clause.
330 * @param options The options to use when getting the associations.
331 */
332 (options?: HasManyGetAssociationsMixinOptions): Promise<TInstance[]>;
333 }
334
335 /**
336 * The options for the setAssociations mixin of the hasMany association.
337 * @see HasManySetAssociationsMixin
338 */
339 interface HasManySetAssociationsMixinOptions {
340
341 /**
342 * Run validation for the join model.
343 */
344 validate?: boolean;
345 }
346
347 /**
348 * The setAssociations mixin applied to models with hasMany.
349 * An example of usage is as follows:
350 *
351 * ```js
352 *
353 * User.hasMany(Role);
354 *
355 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
356 * // getRoles...
357 * setRoles: Sequelize.HasManySetAssociationsMixin<RoleInstance, RoleId>;
358 * // addRoles...
359 * // addRole...
360 * // createRole...
361 * // removeRole...
362 * // removeRoles...
363 * // hasRole...
364 * // hasRoles...
365 * // countRoles...
366 * }
367 * ```
368 *
369 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
370 * @see Instance
371 */
372 interface HasManySetAssociationsMixin<TInstance, TInstancePrimaryKey> {
373 /**
374 * Set the associated models by passing an array of instances or their primary keys.
375 * Everything that it not in the passed array will be un-associated.
376 * @param newAssociations An array of instances or primary key of instances to associate with this. Pass null or undefined to remove all associations.
377 * @param options The options passed to `target.findAll` and `update`.
378 */
379 (
380 newAssociations?: Array<TInstance | TInstancePrimaryKey>,
381 options?: HasManySetAssociationsMixinOptions | AnyFindOptions | InstanceUpdateOptions
382 ): Promise<void>;
383 }
384
385 /**
386 * The options for the addAssociations mixin of the hasMany association.
387 * @see HasManyAddAssociationsMixin
388 */
389 interface HasManyAddAssociationsMixinOptions {
390
391 /**
392 * Run validation for the join model.
393 */
394 validate?: boolean;
395 }
396
397 /**
398 * The addAssociations mixin applied to models with hasMany.
399 * An example of usage is as follows:
400 *
401 * ```js
402 *
403 * User.hasMany(Role);
404 *
405 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
406 * // getRoles...
407 * // setRoles...
408 * addRoles: Sequelize.HasManyAddAssociationsMixin<RoleInstance, RoleId>;
409 * // addRole...
410 * // createRole...
411 * // removeRole...
412 * // removeRoles...
413 * // hasRole...
414 * // hasRoles...
415 * // countRoles...
416 * }
417 * ```
418 *
419 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
420 * @see Instance
421 */
422 interface HasManyAddAssociationsMixin<TInstance, TInstancePrimaryKey> {
423 /**
424 * Associate several instances with this.
425 * @param newAssociations An array of instances or primary key of instances to associate with this.
426 * @param options The options passed to `target.update`.
427 */
428 (
429 newAssociations?: Array<TInstance | TInstancePrimaryKey>,
430 options?: HasManyAddAssociationsMixinOptions | InstanceUpdateOptions
431 ): Promise<void>;
432 }
433
434 /**
435 * The options for the addAssociation mixin of the hasMany association.
436 * @see HasManyAddAssociationMixin
437 */
438 interface HasManyAddAssociationMixinOptions {
439
440 /**
441 * Run validation for the join model.
442 */
443 validate?: boolean;
444 }
445
446 /**
447 * The addAssociation mixin applied to models with hasMany.
448 * An example of usage is as follows:
449 *
450 * ```js
451 *
452 * User.hasMany(Role);
453 *
454 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
455 * // getRoles...
456 * // setRoles...
457 * // addRoles...
458 * addRole: Sequelize.HasManyAddAssociationMixin<RoleInstance, RoleId>;
459 * // createRole...
460 * // removeRole...
461 * // removeRoles...
462 * // hasRole...
463 * // hasRoles...
464 * // countRoles...
465 * }
466 * ```
467 *
468 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
469 * @see Instance
470 */
471 interface HasManyAddAssociationMixin<TInstance, TInstancePrimaryKey> {
472 /**
473 * Associate an instance with this.
474 * @param newAssociation An instance or the primary key of an instance to associate with this.
475 * @param options The options passed to `target.update`.
476 */
477 (
478 newAssociation?: TInstance | TInstancePrimaryKey,
479 options?: HasManyAddAssociationMixinOptions | InstanceUpdateOptions
480 ): Promise<void>;
481 }
482
483 /**
484 * The options for the createAssociation mixin of the hasMany association.
485 * @see HasManyCreateAssociationMixin
486 */
487 interface HasManyCreateAssociationMixinOptions { }
488
489 /**
490 * The createAssociation mixin applied to models with hasMany.
491 * An example of usage is as follows:
492 *
493 * ```js
494 *
495 * User.hasMany(Role);
496 *
497 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
498 * // getRoles...
499 * // setRoles...
500 * // addRoles...
501 * // addRole...
502 * createRole: Sequelize.HasManyCreateAssociationMixin<RoleAttributes>;
503 * // removeRole...
504 * // removeRoles...
505 * // hasRole...
506 * // hasRoles...
507 * // countRoles...
508 * }
509 * ```
510 *
511 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
512 * @see Instance
513 */
514 interface HasManyCreateAssociationMixin<TAttributes, TInstance> {
515 /**
516 * Create a new instance of the associated model and associate it with this.
517 * @param values The values used to create the association.
518 * @param options The options to use when creating the association.
519 */
520 (
521 values?: TAttributes,
522 options?: HasManyCreateAssociationMixinOptions | CreateOptions
523 ): Promise<TInstance>;
524 }
525
526 /**
527 * The options for the removeAssociation mixin of the hasMany association.
528 * @see HasManyRemoveAssociationMixin
529 */
530 interface HasManyRemoveAssociationMixinOptions { }
531
532 /**
533 * The removeAssociation mixin applied to models with hasMany.
534 * An example of usage is as follows:
535 *
536 * ```js
537 *
538 * User.hasMany(Role);
539 *
540 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
541 * // getRoles...
542 * // setRoles...
543 * // addRoles...
544 * // addRole...
545 * // createRole...
546 * removeRole: Sequelize.HasManyRemoveAssociationMixin<RoleInstance, RoleId>;
547 * // removeRoles...
548 * // hasRole...
549 * // hasRoles...
550 * // countRoles...
551 * }
552 * ```
553 *
554 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
555 * @see Instance
556 */
557 interface HasManyRemoveAssociationMixin<TInstance, TInstancePrimaryKey> {
558 /**
559 * Un-associate the instance.
560 * @param oldAssociated The instance or the primary key of the instance to un-associate.
561 * @param options The options passed to `target.update`.
562 */
563 (
564 oldAssociated?: TInstance | TInstancePrimaryKey,
565 options?: HasManyRemoveAssociationMixinOptions | InstanceUpdateOptions
566 ): Promise<void>;
567 }
568
569 /**
570 * The options for the removeAssociations mixin of the hasMany association.
571 * @see HasManyRemoveAssociationsMixin
572 */
573 interface HasManyRemoveAssociationsMixinOptions { }
574
575 /**
576 * The removeAssociations mixin applied to models with hasMany.
577 * An example of usage is as follows:
578 *
579 * ```js
580 *
581 * User.hasMany(Role);
582 *
583 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
584 * // getRoles...
585 * // setRoles...
586 * // addRoles...
587 * // addRole...
588 * // createRole...
589 * // removeRole...
590 * removeRoles: Sequelize.HasManyRemoveAssociationsMixin<RoleInstance, RoleId>;
591 * // hasRole...
592 * // hasRoles...
593 * // countRoles...
594 * }
595 * ```
596 *
597 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
598 * @see Instance
599 */
600 interface HasManyRemoveAssociationsMixin<TInstance, TInstancePrimaryKey> {
601 /**
602 * Un-associate several instances.
603 * @param oldAssociated An array of instances or primary key of instances to un-associate.
604 * @param options The options passed to `target.update`.
605 */
606 (
607 oldAssociateds?: Array<TInstance | TInstancePrimaryKey>,
608 options?: HasManyRemoveAssociationsMixinOptions | InstanceUpdateOptions
609 ): Promise<void>;
610 }
611
612 /**
613 * The options for the hasAssociation mixin of the hasMany association.
614 * @see HasManyHasAssociationMixin
615 */
616 interface HasManyHasAssociationMixinOptions { }
617
618 /**
619 * The hasAssociation mixin applied to models with hasMany.
620 * An example of usage is as follows:
621 *
622 * ```js
623 *
624 * User.hasMany(Role);
625 *
626 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
627 * // getRoles...
628 * // setRoles...
629 * // addRoles...
630 * // addRole...
631 * // createRole...
632 * // removeRole...
633 * // removeRoles...
634 * hasRole: Sequelize.HasManyHasAssociationMixin<RoleInstance, RoleId>;
635 * // hasRoles...
636 * // countRoles...
637 * }
638 * ```
639 *
640 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
641 * @see Instance
642 */
643 interface HasManyHasAssociationMixin<TInstance, TInstancePrimaryKey> {
644 /**
645 * Check if an instance is associated with this.
646 * @param target The instance or the primary key of the instance to check.
647 * @param options The options passed to `getAssociations`.
648 */
649 (
650 target: TInstance | TInstancePrimaryKey,
651 options?: HasManyHasAssociationMixinOptions | HasManyGetAssociationsMixinOptions
652 ): Promise<boolean>;
653 }
654
655 /**
656 * The options for the hasAssociations mixin of the hasMany association.
657 * @see HasManyHasAssociationsMixin
658 */
659 interface HasManyHasAssociationsMixinOptions { }
660
661 /**
662 * The removeAssociations mixin applied to models with hasMany.
663 * An example of usage is as follows:
664 *
665 * ```js
666 *
667 * User.hasMany(Role);
668 *
669 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
670 * // getRoles...
671 * // setRoles...
672 * // addRoles...
673 * // addRole...
674 * // createRole...
675 * // removeRole...
676 * // removeRoles
677 * // hasRole...
678 * hasRoles: Sequelize.HasManyHasAssociationsMixin<RoleInstance, RoleId>;
679 * // countRoles...
680 * }
681 * ```
682 *
683 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
684 * @see Instance
685 */
686 interface HasManyHasAssociationsMixin<TInstance, TInstancePrimaryKey> {
687 /**
688 * Check if all instances are associated with this.
689 * @param targets An array of instances or primary key of instances to check.
690 * @param options The options passed to `getAssociations`.
691 */
692 (
693 targets: Array<TInstance | TInstancePrimaryKey>,
694 options?: HasManyHasAssociationsMixinOptions | HasManyGetAssociationsMixinOptions
695 ): Promise<boolean>;
696 }
697
698 /**
699 * The options for the countAssociations mixin of the hasMany association.
700 * @see HasManyCountAssociationsMixin
701 */
702 interface HasManyCountAssociationsMixinOptions {
703
704 /**
705 * An optional where clause to limit the associated models.
706 */
707 where?: AnyWhereOptions;
708
709 /**
710 * Apply a scope on the related model, or remove its default scope by passing false.
711 */
712 scope?: string | boolean;
713 }
714
715 /**
716 * The countAssociations mixin applied to models with hasMany.
717 * An example of usage is as follows:
718 *
719 * ```js
720 *
721 * User.hasMany(Role);
722 *
723 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
724 * // getRoles...
725 * // setRoles...
726 * // addRoles...
727 * // addRole...
728 * // createRole...
729 * // removeRole...
730 * // removeRoles...
731 * // hasRole...
732 * // hasRoles...
733 * countRoles: Sequelize.HasManyCountAssociationsMixin;
734 * }
735 * ```
736 *
737 * @see http://docs.sequelizejs.com/en/latest/api/associations/has-many/
738 * @see Instance
739 */
740 interface HasManyCountAssociationsMixin {
741 /**
742 * Count everything currently associated with this, using an optional where clause.
743 * @param options The options to use when counting the associations.
744 */
745 (options?: HasManyCountAssociationsMixinOptions): Promise<number>;
746 }
747
748 /**
749 * The options for the getAssociations mixin of the belongsToMany association.
750 * @see BelongsToManyGetAssociationsMixin
751 */
752 interface BelongsToManyGetAssociationsMixinOptions {
753
754 /**
755 * An optional where clause to limit the associated models.
756 */
757 where?: AnyWhereOptions;
758
759 /**
760 * Apply a scope on the related model, or remove its default scope by passing false.
761 */
762 scope?: string | boolean;
763 }
764
765 /**
766 * The getAssociations mixin applied to models with belongsToMany.
767 * An example of usage is as follows:
768 *
769 * ```js
770 *
771 * User.belongsToMany(Role, { through: UserRole });
772 *
773 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
774 * getRoles: Sequelize.BelongsToManyGetAssociationsMixin<RoleInstance>;
775 * // setRoles...
776 * // addRoles...
777 * // addRole...
778 * // createRole...
779 * // removeRole...
780 * // removeRoles...
781 * // hasRole...
782 * // hasRoles...
783 * // countRoles...
784 * }
785 * ```
786 *
787 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
788 * @see Instance
789 */
790 interface BelongsToManyGetAssociationsMixin<TInstance> {
791 /**
792 * Get everything currently associated with this, using an optional where clause.
793 * @param options The options to use when getting the associations.
794 */
795 (options?: BelongsToManyGetAssociationsMixinOptions): Promise<TInstance[]>;
796 }
797
798 /**
799 * The options for the setAssociations mixin of the belongsToMany association.
800 * @see BelongsToManySetAssociationsMixin
801 */
802 interface BelongsToManySetAssociationsMixinOptions {
803
804 /**
805 * Run validation for the join model.
806 */
807 validate?: boolean;
808 }
809
810 /**
811 * The setAssociations mixin applied to models with belongsToMany.
812 * An example of usage is as follows:
813 *
814 * ```js
815 *
816 * User.belongsToMany(Role, { through: UserRole });
817 *
818 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
819 * // getRoles...
820 * setRoles: Sequelize.BelongsToManySetAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
821 * // addRoles...
822 * // addRole...
823 * // createRole...
824 * // removeRole...
825 * // removeRoles...
826 * // hasRole...
827 * // hasRoles...
828 * // countRoles...
829 * }
830 * ```
831 *
832 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
833 * @see Instance
834 */
835 interface BelongsToManySetAssociationsMixin<TInstance, TInstancePrimaryKey, TJoinTableAttributes> {
836 /**
837 * Set the associated models by passing an array of instances or their primary keys.
838 * Everything that it not in the passed array will be un-associated.
839 * @param newAssociations An array of instances or primary key of instances to associate with this. Pass null or undefined to remove all associations.
840 * @param options The options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`. Can also hold additional attributes for the join table.
841 */
842 (
843 newAssociations?: Array<TInstance | TInstancePrimaryKey>,
844 options?: BelongsToManySetAssociationsMixinOptions | AnyFindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes }
845 ): Promise<void>;
846 }
847
848 /**
849 * The options for the addAssociations mixin of the belongsToMany association.
850 * @see BelongsToManyAddAssociationsMixin
851 */
852 interface BelongsToManyAddAssociationsMixinOptions {
853
854 /**
855 * Run validation for the join model.
856 */
857 validate?: boolean;
858 }
859
860 /**
861 * The addAssociations mixin applied to models with belongsToMany.
862 * An example of usage is as follows:
863 *
864 * ```js
865 *
866 * User.belongsToMany(Role, { through: UserRole });
867 *
868 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
869 * // getRoles...
870 * // setRoles...
871 * addRoles: Sequelize.BelongsToManyAddAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;
872 * // addRole...
873 * // createRole...
874 * // removeRole...
875 * // removeRoles...
876 * // hasRole...
877 * // hasRoles...
878 * // countRoles...
879 * }
880 * ```
881 *
882 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
883 * @see Instance
884 */
885 interface BelongsToManyAddAssociationsMixin<TInstance, TInstancePrimaryKey, TJoinTableAttributes> {
886 /**
887 * Associate several instances with this.
888 * @param newAssociations An array of instances or primary key of instances to associate with this.
889 * @param options The options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`. Can also hold additional attributes for the join table.
890 */
891 (
892 newAssociations?: Array<TInstance | TInstancePrimaryKey>,
893 options?: BelongsToManyAddAssociationsMixinOptions | AnyFindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes }
894 ): Promise<void>;
895 }
896
897 /**
898 * The options for the addAssociation mixin of the belongsToMany association.
899 * @see BelongsToManyAddAssociationMixin
900 */
901 interface BelongsToManyAddAssociationMixinOptions {
902
903 /**
904 * Run validation for the join model.
905 */
906 validate?: boolean;
907 }
908
909 /**
910 * The addAssociation mixin applied to models with belongsToMany.
911 * An example of usage is as follows:
912 *
913 * ```js
914 *
915 * User.belongsToMany(Role, { through: UserRole });
916 *
917 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
918 * // getRoles...
919 * // setRoles...
920 * // addRoles...
921 * addRole: Sequelize.BelongsToManyAddAssociationMixin<RoleInstance, RoleId, UserRoleAttributes>;
922 * // createRole...
923 * // removeRole...
924 * // removeRoles...
925 * // hasRole...
926 * // hasRoles...
927 * // countRoles...
928 * }
929 * ```
930 *
931 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
932 * @see Instance
933 */
934 interface BelongsToManyAddAssociationMixin<TInstance, TInstancePrimaryKey, TJoinTableAttributes> {
935 /**
936 * Associate an instance with this.
937 * @param newAssociation An instance or the primary key of an instance to associate with this.
938 * @param options The options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`. Can also hold additional attributes for the join table.
939 */
940 (
941 newAssociation?: TInstance | TInstancePrimaryKey,
942 options?: BelongsToManyAddAssociationMixinOptions | AnyFindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes }
943 ): Promise<void>;
944 }
945
946 /**
947 * The options for the createAssociation mixin of the belongsToMany association.
948 * @see BelongsToManyCreateAssociationMixin
949 */
950 interface BelongsToManyCreateAssociationMixinOptions { }
951
952 /**
953 * The createAssociation mixin applied to models with belongsToMany.
954 * An example of usage is as follows:
955 *
956 * ```js
957 *
958 * User.belongsToMany(Role, { through: UserRole });
959 *
960 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
961 * // getRoles...
962 * // setRoles...
963 * // addRoles...
964 * // addRole...
965 * createRole: Sequelize.BelongsToManyCreateAssociationMixin<RoleAttributes, UserRoleAttributes>;
966 * // removeRole...
967 * // removeRoles...
968 * // hasRole...
969 * // hasRoles...
970 * // countRoles...
971 * }
972 * ```
973 *
974 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
975 * @see Instance
976 */
977 interface BelongsToManyCreateAssociationMixin<TAttributes, TInstance, TJoinTableAttributes> {
978 /**
979 * Create a new instance of the associated model and associate it with this.
980 * @param values The values used to create the association.
981 * @param options Options passed to `create` and `add`. Can also hold additional attributes for the join table.
982 */
983 (
984 values?: TAttributes,
985 options?: BelongsToManyCreateAssociationMixinOptions | CreateOptions | { through: TJoinTableAttributes }
986 ): Promise<TInstance>;
987 }
988
989 /**
990 * The options for the removeAssociation mixin of the belongsToMany association.
991 * @see BelongsToManyRemoveAssociationMixin
992 */
993 interface BelongsToManyRemoveAssociationMixinOptions { }
994
995 /**
996 * The removeAssociation mixin applied to models with belongsToMany.
997 * An example of usage is as follows:
998 *
999 * ```js
1000 *
1001 * User.belongsToMany(Role, { through: UserRole });
1002 *
1003 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
1004 * // getRoles...
1005 * // setRoles...
1006 * // addRoles...
1007 * // addRole...
1008 * // createRole...
1009 * removeRole: Sequelize.BelongsToManyRemoveAssociationMixin<RoleInstance, RoleId>;
1010 * // removeRoles...
1011 * // hasRole...
1012 * // hasRoles...
1013 * // countRoles...
1014 * }
1015 * ```
1016 *
1017 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
1018 * @see Instance
1019 */
1020 interface BelongsToManyRemoveAssociationMixin<TInstance, TInstancePrimaryKey> {
1021 /**
1022 * Un-associate the instance.
1023 * @param oldAssociated The instance or the primary key of the instance to un-associate.
1024 * @param options The options passed to `through.destroy`.
1025 */
1026 (
1027 oldAssociated?: TInstance | TInstancePrimaryKey,
1028 options?: BelongsToManyRemoveAssociationMixinOptions | InstanceDestroyOptions
1029 ): Promise<void>;
1030 }
1031
1032 /**
1033 * The options for the removeAssociations mixin of the belongsToMany association.
1034 * @see BelongsToManyRemoveAssociationsMixin
1035 */
1036 interface BelongsToManyRemoveAssociationsMixinOptions { }
1037
1038 /**
1039 * The removeAssociations mixin applied to models with belongsToMany.
1040 * An example of usage is as follows:
1041 *
1042 * ```js
1043 *
1044 * User.belongsToMany(Role, { through: UserRole });
1045 *
1046 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
1047 * // getRoles...
1048 * // setRoles...
1049 * // addRoles...
1050 * // addRole...
1051 * // createRole...
1052 * // removeRole...
1053 * removeRoles: Sequelize.BelongsToManyRemoveAssociationsMixin<RoleInstance, RoleId>;
1054 * // hasRole...
1055 * // hasRoles...
1056 * // countRoles...
1057 * }
1058 * ```
1059 *
1060 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
1061 * @see Instance
1062 */
1063 interface BelongsToManyRemoveAssociationsMixin<TInstance, TInstancePrimaryKey> {
1064 /**
1065 * Un-associate several instances.
1066 * @param oldAssociated An array of instances or primary key of instances to un-associate.
1067 * @param options The options passed to `through.destroy`.
1068 */
1069 (
1070 oldAssociateds?: Array<TInstance | TInstancePrimaryKey>,
1071 options?: BelongsToManyRemoveAssociationsMixinOptions | InstanceDestroyOptions
1072 ): Promise<void>;
1073 }
1074
1075 /**
1076 * The options for the hasAssociation mixin of the belongsToMany association.
1077 * @see BelongsToManyHasAssociationMixin
1078 */
1079 interface BelongsToManyHasAssociationMixinOptions { }
1080
1081 /**
1082 * The hasAssociation mixin applied to models with belongsToMany.
1083 * An example of usage is as follows:
1084 *
1085 * ```js
1086 *
1087 * User.belongsToMany(Role, { through: UserRole });
1088 *
1089 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
1090 * // getRoles...
1091 * // setRoles...
1092 * // addRoles...
1093 * // addRole...
1094 * // createRole...
1095 * // removeRole...
1096 * // removeRoles...
1097 * hasRole: Sequelize.BelongsToManyHasAssociationMixin<RoleInstance, RoleId>;
1098 * // hasRoles...
1099 * // countRoles...
1100 * }
1101 * ```
1102 *
1103 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
1104 * @see Instance
1105 */
1106 interface BelongsToManyHasAssociationMixin<TInstance, TInstancePrimaryKey> {
1107 /**
1108 * Check if an instance is associated with this.
1109 * @param target The instance or the primary key of the instance to check.
1110 * @param options The options passed to `getAssociations`.
1111 */
1112 (
1113 target: TInstance | TInstancePrimaryKey,
1114 options?: BelongsToManyHasAssociationMixinOptions | BelongsToManyGetAssociationsMixinOptions
1115 ): Promise<boolean>;
1116 }
1117
1118 /**
1119 * The options for the hasAssociations mixin of the belongsToMany association.
1120 * @see BelongsToManyHasAssociationsMixin
1121 */
1122 interface BelongsToManyHasAssociationsMixinOptions { }
1123
1124 /**
1125 * The removeAssociations mixin applied to models with belongsToMany.
1126 * An example of usage is as follows:
1127 *
1128 * ```js
1129 *
1130 * User.belongsToMany(Role, { through: UserRole });
1131 *
1132 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
1133 * // getRoles...
1134 * // setRoles...
1135 * // addRoles...
1136 * // addRole...
1137 * // createRole...
1138 * // removeRole...
1139 * // removeRoles
1140 * // hasRole...
1141 * hasRoles: Sequelize.BelongsToManyHasAssociationsMixin<RoleInstance, RoleId>;
1142 * // countRoles...
1143 * }
1144 * ```
1145 *
1146 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
1147 * @see Instance
1148 */
1149 interface BelongsToManyHasAssociationsMixin<TInstance, TInstancePrimaryKey> {
1150 /**
1151 * Check if all instances are associated with this.
1152 * @param targets An array of instances or primary key of instances to check.
1153 * @param options The options passed to `getAssociations`.
1154 */
1155 (
1156 targets: Array<TInstance | TInstancePrimaryKey>,
1157 options?: BelongsToManyHasAssociationsMixinOptions | BelongsToManyGetAssociationsMixinOptions
1158 ): Promise<boolean>;
1159 }
1160
1161 /**
1162 * The options for the countAssociations mixin of the belongsToMany association.
1163 * @see BelongsToManyCountAssociationsMixin
1164 */
1165 interface BelongsToManyCountAssociationsMixinOptions {
1166
1167 /**
1168 * An optional where clause to limit the associated models.
1169 */
1170 where?: AnyWhereOptions;
1171
1172 /**
1173 * Apply a scope on the related model, or remove its default scope by passing false.
1174 */
1175 scope?: string | boolean;
1176 }
1177
1178 /**
1179 * The countAssociations mixin applied to models with belongsToMany.
1180 * An example of usage is as follows:
1181 *
1182 * ```js
1183 *
1184 * User.belongsToMany(Role, { through: UserRole });
1185 *
1186 * interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
1187 * // getRoles...
1188 * // setRoles...
1189 * // addRoles...
1190 * // addRole...
1191 * // createRole...
1192 * // removeRole...
1193 * // removeRoles...
1194 * // hasRole...
1195 * // hasRoles...
1196 * countRoles: Sequelize.BelongsToManyCountAssociationsMixin;
1197 * }
1198 * ```
1199 *
1200 * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
1201 * @see Instance
1202 */
1203 interface BelongsToManyCountAssociationsMixin {
1204 /**
1205 * Count everything currently associated with this, using an optional where clause.
1206 * @param options The options to use when counting the associations.
1207 */
1208 (options?: BelongsToManyCountAssociationsMixinOptions): Promise<number>;
1209 }
1210
1211 /**
1212 * Foreign Key Options
1213 *
1214 * @see AssociationOptions
1215 */
1216 interface AssociationForeignKeyOptions extends ColumnOptions {
1217
1218 /**
1219 * Attribute name for the relation
1220 */
1221 name?: string;
1222 unique?: boolean | string;
1223 }
1224
1225 /**
1226 * Options provided when associating models
1227 *
1228 * @see Association class
1229 */
1230 interface AssociationOptions {
1231
1232 /**
1233 * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade.
1234 * For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks
1235 * for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking
1236 * any hooks.
1237 *
1238 * Defaults to false
1239 */
1240 hooks?: boolean;
1241
1242 /**
1243 * The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If
1244 * you create multiple associations between the same tables, you should provide an alias to be able to
1245 * distinguish between them. If you provide an alias when creating the assocition, you should provide the
1246 * same alias when eager loading and when getting assocated models. Defaults to the singularized name of
1247 * target
1248 */
1249 as?: string | { singular: string, plural: string };
1250
1251 /**
1252 * The name of the foreign key in the target table or an object representing the type definition for the
1253 * foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property
1254 * to set the name of the column. Defaults to the name of source + primary key of source
1255 */
1256 foreignKey?: string | AssociationForeignKeyOptions;
1257
1258 /**
1259 * What happens when delete occurs.
1260 *
1261 * Cascade if this is a n:m, and set null if it is a 1:m
1262 *
1263 * Defaults to 'SET NULL' or 'CASCADE'
1264 */
1265 onDelete?: string;
1266
1267 /**
1268 * What happens when update occurs
1269 *
1270 * Defaults to 'CASCADE'
1271 */
1272 onUpdate?: string;
1273
1274 /**
1275 * Should on update and on delete constraints be enabled on the foreign key.
1276 */
1277 constraints?: boolean;
1278 foreignKeyConstraint?: boolean;
1279
1280 scope?: AssociationScope;
1281 }
1282
1283 /**
1284 * Options for Association Scope
1285 *
1286 * @see AssociationOptionsManyToMany
1287 */
1288 interface AssociationScope {
1289
1290 /**
1291 * The name of the column that will be used for the associated scope and it's value
1292 */
1293 [scopeName: string]: any;
1294
1295 }
1296
1297 /**
1298 * Options provided for many-to-many relationships
1299 *
1300 * @see AssociationOptionsHasMany
1301 * @see AssociationOptionsBelongsToMany
1302 */
1303 interface AssociationOptionsManyToMany extends AssociationOptions {
1304
1305 /**
1306 * A key/value set that will be used for association create and find defaults on the target.
1307 * (sqlite not supported for N:M)
1308 */
1309 scope?: AssociationScope;
1310
1311 }
1312
1313 /**
1314 * Options provided when associating models with hasOne relationship
1315 *
1316 * @see Association class hasOne method
1317 */
1318 interface AssociationOptionsHasOne extends AssociationOptions {
1319
1320 /**
1321 * A string or a data type to represent the identifier in the table
1322 */
1323 keyType?: DataTypeAbstract;
1324
1325 }
1326
1327 /**
1328 * Options provided when associating models with belongsTo relationship
1329 *
1330 * @see Association class belongsTo method
1331 */
1332 interface AssociationOptionsBelongsTo extends AssociationOptions {
1333
1334 /**
1335 * The name of the field to use as the key for the association in the target table. Defaults to the primary
1336 * key of the target table
1337 */
1338 targetKey?: string;
1339
1340 /**
1341 * A string or a data type to represent the identifier in the table
1342 */
1343 keyType?: DataTypeAbstract;
1344
1345 }
1346
1347 /**
1348 * Options provided when associating models with hasMany relationship
1349 *
1350 * @see Association class hasMany method
1351 */
1352 interface AssociationOptionsHasMany extends AssociationOptionsManyToMany {
1353
1354 /**
1355 * A string or a data type to represent the identifier in the table
1356 */
1357 keyType?: DataTypeAbstract;
1358 /**
1359 * A string to represent the name of the field to use as the key for an 1 to many association in the source table.
1360 *
1361 * @see http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-hasMany
1362 * @see https://github.com/sequelize/sequelize/blob/b4fd46426db9cdbb97074bea121203d565e4195d/lib/associations/has-many.js#L81
1363 */
1364 sourceKey?: string;
1365 }
1366
1367 /**
1368 * Options provided when associating models with belongsToMany relationship
1369 *
1370 * @see Association class belongsToMany method
1371 */
1372 interface AssociationOptionsBelongsToMany extends AssociationOptionsManyToMany {
1373
1374 /**
1375 * The name of the table that is used to join source and target in n:m associations. Can also be a
1376 * sequelize
1377 * model if you want to define the junction table yourself and add extra attributes to it.
1378 *
1379 * In 3.4.1 version of Sequelize, hasMany's use of through gives an error, and on the other hand through
1380 * option for belongsToMany has been made required.
1381 *
1382 * @see https://github.com/sequelize/sequelize/blob/v3.4.1/lib/associations/has-many.js
1383 * @see https://github.com/sequelize/sequelize/blob/v3.4.1/lib/associations/belongs-to-many.js
1384 */
1385 through: Model<any, any> | string | ThroughOptions;
1386
1387 /**
1388 * The name of the foreign key in the join table (representing the target model) or an object representing
1389 * the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you
1390 * can add a `name` property to set the name of the colum. Defaults to the name of target + primary key of
1391 * target
1392 */
1393 otherKey?: string | AssociationForeignKeyOptions;
1394
1395 /**
1396 * Should the join model have timestamps
1397 */
1398 timestamps?: boolean;
1399
1400 /**
1401 * Belongs-To-Many creates a unique key when primary key is not present on through model. This unique key name can be overridden using uniqueKey option.
1402 */
1403 uniqueKey?: string;
1404 }
1405
1406 /**
1407 * Used for a association table in n:m associations.
1408 *
1409 * @see AssociationOptionsBelongsToMany
1410 */
1411 interface ThroughOptions {
1412
1413 /**
1414 * The model used to join both sides of the N:M association.
1415 */
1416 model: Model<any, any>;
1417
1418 /**
1419 * A key/value set that will be used for association create and find defaults on the through model.
1420 * (Remember to add the attributes to the through model)
1421 */
1422 scope?: AssociationScope;
1423
1424 /**
1425 * If true a unique key will be generated from the foreign keys used (might want to turn this off and create
1426 * specific unique keys when using scopes)
1427 *
1428 * Defaults to true
1429 */
1430 unique?: boolean;
1431
1432 }
1433
1434 /**
1435 * Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany functions on a
1436 * model (the source), and providing another model as the first argument to the function (the target).
1437 *
1438 * * hasOne - adds a foreign key to target
1439 * * belongsTo - add a foreign key to source
1440 * * hasMany - adds a foreign key to target, unless you also specify that target hasMany source, in which case
1441 * a
1442 * junction table is created with sourceId and targetId
1443 *
1444 * Creating an association will add a foreign key constraint to the attributes. All associations use `CASCADE`
1445 * on update and `SET NULL` on delete, except for n:m, which also uses `CASCADE` on delete.
1446 *
1447 * When creating associations, you can provide an alias, via the `as` option. This is useful if the same model
1448 * is associated twice, or you want your association to be called something other than the name of the target
1449 * model.
1450 *
1451 * As an example, consider the case where users have many pictures, one of which is their profile picture. All
1452 * pictures have a `userId`, but in addition the user model also has a `profilePictureId`, to be able to easily
1453 * load the user's profile picture.
1454 *
1455 * ```js
1456 * User.hasMany(Picture)
1457 * User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false })
1458 *
1459 * user.getPictures() // gets you all pictures
1460 * user.getProfilePicture() // gets you only the profile picture
1461 *
1462 * User.findAll({
1463 * where: ...,
1464 * include: [
1465 * { model: Picture }, // load all pictures
1466 * { model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be
1467 * the exact same as the one in the association
1468 * ]
1469 * })
1470 * ```
1471 * To get full control over the foreign key column added by sequelize, you can use the `foreignKey` option. It
1472 * can either be a string, that specifies the name, or and object type definition,
1473 * equivalent to those passed to `sequelize.define`.
1474 *
1475 * ```js
1476 * User.hasMany(Picture, { foreignKey: 'uid' })
1477 * ```
1478 *
1479 * The foreign key column in Picture will now be called `uid` instead of the default `userId`.
1480 *
1481 * ```js
1482 * User.hasMany(Picture, {
1483 * foreignKey: {
1484 * name: 'uid',
1485 * allowNull: false
1486 * }
1487 * })
1488 * ```
1489 *
1490 * This specifies that the `uid` column can not be null. In most cases this will already be covered by the
1491 * foreign key costraints, which sequelize creates automatically, but can be useful in case where the foreign
1492 * keys are disabled, e.g. due to circular references (see `constraints: false` below).
1493 *
1494 * When fetching associated models, you can limit your query to only load some models. These queries are
1495 * written
1496 * in the same way as queries to `find`/`findAll`. To only get pictures in JPG, you can do:
1497 *
1498 * ```js
1499 * user.getPictures({
1500 * where: {
1501 * format: 'jpg'
1502 * }
1503 * })
1504 * ```
1505 *
1506 * There are several ways to update and add new assoications. Continuing with our example of users and
1507 * pictures:
1508 * ```js
1509 * user.addPicture(p) // Add a single picture
1510 * user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be
1511 * deleted user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current
1512 * associations
1513 * ```
1514 *
1515 * You don't have to pass in a complete object to the association functions, if your associated model has a
1516 * single primary key:
1517 *
1518 * ```js
1519 * user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture
1520 * ```
1521 *
1522 * In the example above we have specified that a user belongs to their profile picture. Conceptually, this might
1523 * not make sense, but since we want to add the foreign key to the user model this is the way to do it.
1524 *
1525 * Note how we also specified `constraints: false` for profile picture. This is because we add a foreign key
1526 * from user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys
1527 * to both, it would create a cyclic dependency, and sequelize would not know which table to create first,
1528 * since user depends on picture, and picture depends on user. These kinds of problems are detected by
1529 * sequelize before the models are synced to the database, and you will get an error along the lines of `Error:
1530 * Cyclic dependency found. 'users' is dependent of itself`. If you encounter this, you should either disable
1531 * some constraints, or rethink your associations completely.
1532 *
1533 * @see Sequelize.Model
1534 */
1535 interface Associations {
1536
1537 /**
1538 * Creates an association between this (the source) and the provided target. The foreign key is added
1539 * on the target.
1540 *
1541 * Example: `User.hasOne(Profile)`. This will add userId to the profile table.
1542 *
1543 * @param target The model that will be associated with hasOne relationship
1544 * @param options Options for the association
1545 * @return return type of association
1546 */
1547 hasOne(target: Model<any, any>, options?: AssociationOptionsHasOne): IncludeAssociation;
1548
1549 /**
1550 * Creates an association between this (the source) and the provided target. The foreign key is added on the
1551 * source.
1552 *
1553 * Example: `Profile.belongsTo(User)`. This will add userId to the profile table.
1554 *
1555 * @param target The model that will be associated with hasOne relationship
1556 * @param options Options for the association
1557 * @return return type of association
1558 */
1559 belongsTo(target: Model<any, any>, options?: AssociationOptionsBelongsTo): IncludeAssociation;
1560
1561 /**
1562 * Create an association that is either 1:m or n:m.
1563 *
1564 * ```js
1565 * // Create a 1:m association between user and project
1566 * User.hasMany(Project)
1567 * ```
1568 * ```js
1569 * // Create a n:m association between user and project
1570 * User.hasMany(Project)
1571 * Project.hasMany(User)
1572 * ```
1573 * By default, the name of the join table will be source+target, so in this case projectsusers. This can be
1574 * overridden by providing either a string or a Model as `through` in the options. If you use a through
1575 * model with custom attributes, these attributes can be set when adding / setting new associations in two
1576 * ways. Consider users and projects from before with a join table that stores whether the project has been
1577 * started yet:
1578 * ```js
1579 * var UserProjects = sequelize.define('userprojects', {
1580 * started: Sequelize.BOOLEAN
1581 * })
1582 * User.hasMany(Project, { through: UserProjects })
1583 * Project.hasMany(User, { through: UserProjects })
1584 * ```
1585 * ```js
1586 * jan.addProject(homework, { started: false }) // The homework project is not started yet
1587 * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been
1588 * started
1589 * ```
1590 *
1591 * If you want to set several target instances, but with different attributes you have to set the
1592 * attributes on the instance, using a property with the name of the through model:
1593 *
1594 * ```js
1595 * p1.userprojects {
1596 * started: true
1597 * }
1598 * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
1599 * ```
1600 *
1601 * Similarily, when fetching through a join table with custom attributes, these attributes will be
1602 * available as an object with the name of the through model.
1603 * ```js
1604 * user.getProjects().then(function (projects) {
1605 * var p1 = projects[0]
1606 * p1.userprojects.started // Is this project started yet?
1607 * })
1608 * ```
1609 *
1610 * @param target The model that will be associated with hasOne relationship
1611 * @param options Options for the association
1612 * @return return type of association
1613 */
1614 hasMany(target: Model<any, any>, options?: AssociationOptionsHasMany): IncludeAssociation;
1615
1616 /**
1617 * Create an N:M association with a join table
1618 *
1619 * ```js
1620 * User.belongsToMany(Project)
1621 * Project.belongsToMany(User)
1622 * ```
1623 * By default, the name of the join table will be source+target, so in this case projectsusers. This can be
1624 * overridden by providing either a string or a Model as `through` in the options.
1625 *
1626 * If you use a through model with custom attributes, these attributes can be set when adding / setting new
1627 * associations in two ways. Consider users and projects from before with a join table that stores whether
1628 * the project has been started yet:
1629 * ```js
1630 * var UserProjects = sequelize.define('userprojects', {
1631 * started: Sequelize.BOOLEAN
1632 * })
1633 * User.belongsToMany(Project, { through: UserProjects })
1634 * Project.belongsToMany(User, { through: UserProjects })
1635 * ```
1636 * ```js
1637 * jan.addProject(homework, { started: false }) // The homework project is not started yet
1638 * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started
1639 * ```
1640 *
1641 * If you want to set several target instances, but with different attributes you have to set the
1642 * attributes on the instance, using a property with the name of the through model:
1643 *
1644 * ```js
1645 * p1.userprojects {
1646 * started: true
1647 * }
1648 * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
1649 * ```
1650 *
1651 * Similarily, when fetching through a join table with custom attributes, these attributes will be
1652 * available as an object with the name of the through model.
1653 * ```js
1654 * user.getProjects().then(function (projects) {
1655 * var p1 = projects[0]
1656 * p1.userprojects.started // Is this project started yet?
1657 * })
1658 * ```
1659 *
1660 * @param target The model that will be associated with hasOne relationship
1661 * @param options Options for the association
1662 * @return return type of association
1663 *
1664 */
1665 belongsToMany(target: Model<any, any>, options: AssociationOptionsBelongsToMany): IncludeAssociation;
1666
1667 }
1668
1669 //
1670 // DataTypes
1671 // ~~~~~~~~~~~
1672 //
1673 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/data-types.js
1674 //
1675
1676 /**
1677 * Abstract DataType interface. Use this if you want to create an interface that has a value any of the
1678 * DataTypes that Sequelize supports.
1679 */
1680 interface DataTypeAbstract {
1681
1682 /**
1683 * Although this is not needed for the definitions itself, we want to make sure that DataTypeAbstract is not
1684 * something than can be evaluated to an empty object.
1685 */
1686 dialectTypes: string;
1687
1688 }
1689
1690 interface DataTypeAbstractString<T> extends DataTypeAbstract {
1691
1692 /**
1693 * A variable length string. Default length 255
1694 */
1695 (options?: { length: number }): T;
1696 (length: number): T;
1697
1698 /**
1699 * Property BINARY for the type
1700 */
1701 BINARY: T;
1702
1703 }
1704
1705 interface DataTypeString extends DataTypeAbstractString<DataTypeString> { }
1706
1707 interface DataTypeChar extends DataTypeAbstractString<DataTypeChar> { }
1708
1709 interface DataTypeText extends DataTypeAbstract {
1710
1711 /**
1712 * Length of the text field.
1713 *
1714 * Available lengths: `tiny`, `medium`, `long`
1715 */
1716 (options?: { length: string }): DataTypeText;
1717 (length: string): DataTypeText;
1718
1719 }
1720
1721 interface DataTypeAbstractNumber<T> extends DataTypeAbstract {
1722 UNSIGNED: T;
1723 ZEROFILL: T;
1724 }
1725
1726 interface DataTypeNumber extends DataTypeAbstractNumber<DataTypeNumber> { }
1727
1728 interface DataTypeInteger extends DataTypeAbstractNumber<DataTypeInteger> {
1729
1730 /**
1731 * Length of the number field.
1732 */
1733 (options?: { length: number }): DataTypeInteger;
1734 (length: number): DataTypeInteger;
1735
1736 }
1737
1738 interface DataTypeTinyInt extends DataTypeAbstractNumber<DataTypeTinyInt> {
1739
1740 /**
1741 * Length of the number field.
1742 */
1743 (options?: { length: number }): DataTypeTinyInt;
1744 (length: number): DataTypeTinyInt;
1745
1746 }
1747 interface DataTypeSmallInt extends DataTypeAbstractNumber<DataTypeSmallInt> {
1748
1749 /**
1750 * Length of the number field.
1751 */
1752 (options?: { length: number }): DataTypeSmallInt;
1753 (length: number): DataTypeSmallInt;
1754
1755 }
1756 interface DataTypeMediumInt extends DataTypeAbstractNumber<DataTypeMediumInt> {
1757
1758 /**
1759 * Length of the number field.
1760 */
1761 (options?: { length: number }): DataTypeMediumInt;
1762 (length: number): DataTypeMediumInt;
1763
1764 }
1765
1766 interface DataTypeBigInt extends DataTypeAbstractNumber<DataTypeBigInt> {
1767
1768 /**
1769 * Length of the number field.
1770 */
1771 (options?: { length: number }): DataTypeBigInt;
1772 (length: number): DataTypeBigInt;
1773
1774 }
1775
1776 interface DataTypeFloat extends DataTypeAbstractNumber<DataTypeFloat> {
1777
1778 /**
1779 * Length of the number field and decimals of the float
1780 */
1781 (options?: { length: number, decimals?: number }): DataTypeFloat;
1782 (length: number, decimals?: number): DataTypeFloat;
1783
1784 }
1785
1786 interface DataTypeReal extends DataTypeAbstractNumber<DataTypeReal> {
1787
1788 /**
1789 * Length of the number field and decimals of the real
1790 */
1791 (options?: { length: number, decimals?: number }): DataTypeReal;
1792 (length: number, decimals?: number): DataTypeReal;
1793
1794 }
1795
1796 interface DataTypeDouble extends DataTypeAbstractNumber<DataTypeDouble> {
1797
1798 /**
1799 * Length of the number field and decimals of the real
1800 */
1801 (options?: { length: number, decimals?: number }): DataTypeDouble;
1802 (length: number, decimals?: number): DataTypeDouble;
1803
1804 }
1805
1806 interface DataTypeDecimal extends DataTypeAbstractNumber<DataTypeDecimal> {
1807
1808 /**
1809 * Precision and scale for the decimal number
1810 */
1811 (options?: { precision: number, scale?: number }): DataTypeDecimal;
1812 (precision: number, scale?: number): DataTypeDecimal;
1813
1814 }
1815
1816 interface DataTypeBoolean extends DataTypeAbstract { }
1817
1818 interface DataTypeTime extends DataTypeAbstract { }
1819
1820 interface DataTypeDate extends DataTypeAbstract {
1821
1822 /**
1823 * Length of decimal places of time
1824 */
1825 (options?: { length?: number }): DataTypeDate;
1826 (length?: number): DataTypeDate;
1827
1828 }
1829
1830 interface DataTypeDateOnly extends DataTypeAbstract { }
1831
1832 interface DataTypeHStore extends DataTypeAbstract { }
1833
1834 interface DataTypeJSONType extends DataTypeAbstract { }
1835
1836 interface DataTypeJSONB extends DataTypeAbstract { }
1837
1838 interface DataTypeNow extends DataTypeAbstract { }
1839
1840 interface DataTypeBlob extends DataTypeAbstract {
1841
1842 /**
1843 * Length of the blob field.
1844 *
1845 * Available lengths: `tiny`, `medium`, `long`
1846 */
1847 (options?: { length: string }): DataTypeBlob;
1848 (length: string): DataTypeBlob;
1849
1850 }
1851
1852 interface DataTypeRange extends DataTypeAbstract {
1853
1854 /**
1855 * Range field for Postgre
1856 *
1857 * Accepts subtype any of the ranges
1858 */
1859 (options?: { subtype: DataTypeAbstract }): DataTypeRange;
1860 (subtype: DataTypeAbstract): DataTypeRange;
1861
1862 }
1863
1864 interface DataTypeAbstractUUID<T> extends DataTypeAbstract {
1865 (): T;
1866 }
1867
1868 interface DataTypeUUID extends DataTypeAbstractUUID<DataTypeUUID> { }
1869
1870 interface DataTypeUUIDv1 extends DataTypeAbstractUUID<DataTypeUUIDv1> { }
1871
1872 interface DataTypeUUIDv4 extends DataTypeAbstractUUID<DataTypeUUIDv4> { }
1873
1874 interface DataTypeVirtual extends DataTypeAbstract {
1875
1876 /**
1877 * Virtual field
1878 *
1879 * Accepts subtype any of the DataTypes
1880 * Array of required attributes that are available on the model
1881 */
1882 new (subtype: DataTypeAbstract, requireAttributes?: Array<string>): DataTypeVirtual;
1883 }
1884
1885 interface DataTypeEnum extends DataTypeAbstract {
1886
1887 /**
1888 * Enum field
1889 *
1890 * Accepts values
1891 */
1892 (options?: { values: string | string[] }): DataTypeEnum;
1893 (values: string | string[]): DataTypeEnum;
1894 (...args: string[]): DataTypeEnum;
1895
1896 }
1897
1898 interface DataTypeArray extends DataTypeAbstract {
1899
1900 /**
1901 * Array field for Postgre
1902 *
1903 * Accepts type any of the DataTypes
1904 */
1905 (options: { type: DataTypeAbstract }): DataTypeArray;
1906 (type: DataTypeAbstract): DataTypeArray;
1907
1908 }
1909
1910 interface DataTypeGeometry extends DataTypeAbstract {
1911
1912 /**
1913 * Geometry field for Postgres
1914 */
1915 (type: string, srid?: number): DataTypeGeometry;
1916
1917 }
1918
1919 /**
1920 * A convenience class holding commonly used data types. The datatypes are used when definining a new model
1921 * using
1922 * `Sequelize.define`, like this:
1923 *
1924 * ```js
1925 * sequelize.define('model', {
1926 * column: DataTypes.INTEGER
1927 * })
1928 * ```
1929 * When defining a model you can just as easily pass a string as type, but often using the types defined here
1930 * is
1931 * beneficial. For example, using `DataTypes.BLOB`, mean that that column will be returned as an instance of
1932 * `Buffer` when being fetched by sequelize.
1933 *
1934 * Some data types have special properties that can be accessed in order to change the data type.
1935 * For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`.
1936 * The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as
1937 * well. The available properties are listed under each data type.
1938 *
1939 * To provide a length for the data type, you can invoke it like a function: `INTEGER(2)`
1940 *
1941 * Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not
1942 * be used to define types. Instead they are used as shorthands for defining default values. For example, to
1943 * get a uuid field with a default value generated following v1 of the UUID standard:
1944 *
1945 * ```js
1946 * sequelize.define('model', {
1947 * uuid: {
1948 * type: DataTypes.UUID,
1949 * defaultValue: DataTypes.UUIDV1,
1950 * primaryKey: true
1951 * }
1952 * })
1953 * ```
1954 */
1955 interface DataTypes {
1956 ABSTRACT: DataTypeAbstract;
1957 STRING: DataTypeString;
1958 CHAR: DataTypeChar;
1959 TEXT: DataTypeText;
1960 NUMBER: DataTypeNumber;
1961 TINYINT: DataTypeTinyInt;
1962 SMALLINT: DataTypeSmallInt;
1963 MEDIUMINT: DataTypeMediumInt;
1964 INTEGER: DataTypeInteger;
1965 BIGINT: DataTypeBigInt;
1966 FLOAT: DataTypeFloat;
1967 TIME: DataTypeTime;
1968 DATE: DataTypeDate;
1969 DATEONLY: DataTypeDateOnly;
1970 BOOLEAN: DataTypeBoolean;
1971 NOW: DataTypeNow;
1972 BLOB: DataTypeBlob;
1973 DECIMAL: DataTypeDecimal;
1974 NUMERIC: DataTypeDecimal;
1975 UUID: DataTypeUUID;
1976 UUIDV1: DataTypeUUIDv1;
1977 UUIDV4: DataTypeUUIDv4;
1978 HSTORE: DataTypeHStore;
1979 JSON: DataTypeJSONType;
1980 JSONB: DataTypeJSONB;
1981 VIRTUAL: DataTypeVirtual;
1982 ARRAY: DataTypeArray;
1983 NONE: DataTypeVirtual;
1984 ENUM: DataTypeEnum;
1985 RANGE: DataTypeRange;
1986 REAL: DataTypeReal;
1987 DOUBLE: DataTypeDouble;
1988 "DOUBLE PRECISION": DataTypeDouble;
1989 GEOMETRY: DataTypeGeometry;
1990 }
1991
1992 //
1993 // Deferrable
1994 // ~~~~~~~~~~~~
1995 //
1996 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/deferrable.js
1997 //
1998
1999 /**
2000 * Abstract Deferrable interface. Use this if you want to create an interface that has a value any of the
2001 * Deferrables that Sequelize supports.
2002 */
2003 interface DeferrableAbstract {
2004
2005 /**
2006 * Although this is not needed for the definitions itself, we want to make sure that DeferrableAbstract is
2007 * not something than can be evaluated to an empty object.
2008 */
2009 toString(): string;
2010 toSql(): string;
2011
2012 }
2013
2014 interface DeferrableInitiallyDeferred extends DeferrableAbstract {
2015
2016 /**
2017 * A property that will defer constraints checks to the end of transactions.
2018 */
2019 (): DeferrableInitiallyDeferred;
2020
2021 }
2022
2023 interface DeferrableInitiallyImmediate extends DeferrableAbstract {
2024
2025 /**
2026 * A property that will trigger the constraint checks immediately
2027 */
2028 (): DeferrableInitiallyImmediate;
2029
2030 }
2031
2032 interface DeferrableNot extends DeferrableAbstract {
2033
2034 /**
2035 * A property that will set the constraints to not deferred. This is the default in PostgreSQL and it make
2036 * it impossible to dynamically defer the constraints within a transaction.
2037 */
2038 (): DeferrableNot;
2039
2040 }
2041
2042 interface DeferrableSetDeferred extends DeferrableAbstract {
2043
2044 /**
2045 * A property that will trigger an additional query at the beginning of a
2046 * transaction which sets the constraints to deferred.
2047 *
2048 * @param constraints An array of constraint names. Will defer all constraints by default.
2049 */
2050 (constraints: string[]): DeferrableSetDeferred;
2051
2052 }
2053
2054 interface DeferrableSetImmediate extends DeferrableAbstract {
2055
2056 /**
2057 * A property that will trigger an additional query at the beginning of a
2058 * transaction which sets the constraints to immediately.
2059 *
2060 * @param constraints An array of constraint names. Will defer all constraints by default.
2061 */
2062 (constraints: string[]): DeferrableSetImmediate;
2063
2064 }
2065
2066 /**
2067 * A collection of properties related to deferrable constraints. It can be used to
2068 * make foreign key constraints deferrable and to set the constaints within a
2069 * transaction. This is only supported in PostgreSQL.
2070 *
2071 * The foreign keys can be configured like this. It will create a foreign key
2072 * that will check the constraints immediately when the data was inserted.
2073 *
2074 * ```js
2075 * sequelize.define('Model', {
2076 * foreign_id: {
2077 * type: Sequelize.INTEGER,
2078 * references: {
2079 * model: OtherModel,
2080 * key: 'id',
2081 * deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
2082 * }
2083 * }
2084 * });
2085 * ```
2086 *
2087 * The constraints can be configured in a transaction like this. It will
2088 * trigger a query once the transaction has been started and set the constraints
2089 * to be checked at the very end of the transaction.
2090 *
2091 * ```js
2092 * sequelize.transaction({
2093 * deferrable: Sequelize.Deferrable.SET_DEFERRED
2094 * });
2095 * ```
2096 */
2097 interface Deferrable {
2098 INITIALLY_DEFERRED: DeferrableInitiallyDeferred;
2099 INITIALLY_IMMEDIATE: DeferrableInitiallyImmediate;
2100 NOT: DeferrableNot;
2101 SET_DEFERRED: DeferrableSetDeferred;
2102 SET_IMMEDIATE: DeferrableSetImmediate;
2103 }
2104
2105 //
2106 // Errors
2107 // ~~~~~~~~
2108 //
2109 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/errors.js
2110 //
2111
2112 /**
2113 * The Base Error all Sequelize Errors inherit from.
2114 */
2115 interface BaseError extends Error, ErrorConstructor { }
2116
2117 interface ValidationError extends BaseError {
2118
2119 /**
2120 * Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors`
2121 * property, which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
2122 *
2123 * @param message Error message
2124 * @param errors Array of ValidationErrorItem objects describing the validation errors
2125 */
2126 new (message: string, errors?: ValidationErrorItem[]): ValidationError;
2127
2128 /**
2129 * Gets all validation error items for the path / field specified.
2130 *
2131 * @param path The path to be checked for error items
2132 */
2133 get(path: string): ValidationErrorItem[];
2134
2135 /** Array of ValidationErrorItem objects describing the validation errors */
2136 errors: ValidationErrorItem[];
2137
2138 }
2139
2140 interface ValidationErrorItem extends BaseError {
2141
2142 /**
2143 * Validation Error Item
2144 * Instances of this class are included in the `ValidationError.errors` property.
2145 *
2146 * @param message An error message
2147 * @param type The type of the validation error
2148 * @param path The field that triggered the validation error
2149 * @param value The value that generated the error
2150 */
2151 new (message: string, type: string, path: string, value: string): ValidationErrorItem;
2152
2153 /** An error message */
2154 message: string;
2155
2156 /** The type of the validation error */
2157 type: string;
2158
2159 /** The field that triggered the validation error */
2160 path: string;
2161
2162 /** The value that generated the error */
2163 value: string;
2164
2165 }
2166
2167 interface DatabaseError extends BaseError {
2168
2169 /**
2170 * A base class for all database related errors.
2171 */
2172 new (parent: Error): DatabaseError;
2173
2174 }
2175
2176 interface TimeoutError extends DatabaseError {
2177
2178 /**
2179 * Thrown when a database query times out because of a deadlock
2180 */
2181 new (parent: Error): TimeoutError;
2182
2183 }
2184
2185 interface UniqueConstraintError extends ValidationError {
2186
2187 /**
2188 * Thrown when a unique constraint is violated in the database
2189 */
2190 new (options: { parent?: Error, message?: string, errors?: Object }): UniqueConstraintError;
2191
2192 }
2193
2194 interface ForeignKeyConstraintError extends DatabaseError {
2195
2196 /**
2197 * Thrown when a foreign key constraint is violated in the database
2198 */
2199 new (options: { parent?: Error, message?: string, index?: string, fields?: string[], table?: string }): ForeignKeyConstraintError;
2200
2201 }
2202
2203 interface ExclusionConstraintError extends DatabaseError {
2204
2205 /**
2206 * Thrown when an exclusion constraint is violated in the database
2207 */
2208 new (options: { parent?: Error, message?: string, constraint?: string, fields?: string[], table?: string }): ExclusionConstraintError;
2209
2210 }
2211
2212 interface ConnectionError extends BaseError {
2213
2214 /**
2215 * A base class for all connection related errors.
2216 */
2217 new (parent: Error): ConnectionError;
2218
2219 }
2220
2221 interface ConnectionRefusedError extends ConnectionError {
2222
2223 /**
2224 * Thrown when a connection to a database is refused
2225 */
2226 new (parent: Error): ConnectionRefusedError;
2227
2228 }
2229
2230 interface AccessDeniedError extends ConnectionError {
2231
2232 /**
2233 * Thrown when a connection to a database is refused due to insufficient privileges
2234 */
2235 new (parent: Error): AccessDeniedError;
2236
2237 }
2238
2239 interface HostNotFoundError extends ConnectionError {
2240
2241 /**
2242 * Thrown when a connection to a database has a hostname that was not found
2243 */
2244 new (parent: Error): HostNotFoundError;
2245
2246 }
2247
2248 interface HostNotReachableError extends ConnectionError {
2249
2250 /**
2251 * Thrown when a connection to a database has a hostname that was not reachable
2252 */
2253 new (parent: Error): HostNotReachableError;
2254
2255 }
2256
2257 interface InvalidConnectionError extends ConnectionError {
2258
2259 /**
2260 * Thrown when a connection to a database has invalid values for any of the connection parameters
2261 */
2262 new (parent: Error): InvalidConnectionError;
2263
2264 }
2265
2266 interface ConnectionTimedOutError extends ConnectionError {
2267
2268 /**
2269 * Thrown when a connection to a database times out
2270 */
2271 new (parent: Error): ConnectionTimedOutError;
2272
2273 }
2274
2275 interface EmptyResultError extends BaseError {
2276
2277 /**
2278 * Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
2279 */
2280 new (parent: Error): EmptyResultError;
2281
2282 }
2283
2284 /**
2285 * Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors
2286 * are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the
2287 * base JS error object.
2288 */
2289 interface Errors {
2290 Error: BaseError;
2291 ValidationError: ValidationError;
2292 ValidationErrorItem: ValidationErrorItem;
2293 DatabaseError: DatabaseError;
2294 TimeoutError: TimeoutError;
2295 UniqueConstraintError: UniqueConstraintError;
2296 ExclusionConstraintError: ExclusionConstraintError;
2297 ForeignKeyConstraintError: ForeignKeyConstraintError;
2298 ConnectionError: ConnectionError;
2299 ConnectionRefusedError: ConnectionRefusedError;
2300 AccessDeniedError: AccessDeniedError;
2301 HostNotFoundError: HostNotFoundError;
2302 HostNotReachableError: HostNotReachableError;
2303 InvalidConnectionError: InvalidConnectionError;
2304 ConnectionTimedOutError: ConnectionTimedOutError;
2305 EmptyResultError: EmptyResultError;
2306 }
2307
2308 //
2309 // Hooks
2310 // ~~~~~~~
2311 //
2312 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/hooks.js
2313 //
2314
2315 /**
2316 * Options for Sequelize.define. We mostly duplicate the Hooks here, since there is no way to combine the two
2317 * interfaces.
2318 *
2319 * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate,
2320 * beforeDestroy, beforeSave, beforeUpdate, afterCreate, afterDestroy, afterSave, afterUpdate, afterBulkCreate,
2321 * afterBulkDestroy and afterBulkUpdate.
2322 */
2323 interface HooksDefineOptions<TInstance> {
2324
2325 beforeValidate?: (instance: TInstance, options: Object, fn?: Function) => any;
2326 afterValidate?: (instance: TInstance, options: Object, fn?: Function) => any;
2327 beforeCreate?: (attributes: TInstance, options: Object, fn?: Function) => any;
2328 afterCreate?: (attributes: TInstance, options: Object, fn?: Function) => any;
2329 beforeDestroy?: (instance: TInstance, options: Object, fn?: Function) => any;
2330 beforeDelete?: (instance: TInstance, options: Object, fn?: Function) => any;
2331 afterDestroy?: (instance: TInstance, options: Object, fn?: Function) => any;
2332 afterDelete?: (instance: TInstance, options: Object, fn?: Function) => any;
2333 beforeUpdate?: (instance: TInstance, options: Object, fn?: Function) => any;
2334 afterUpdate?: (instance: TInstance, options: Object, fn?: Function) => any;
2335 beforeSave?: (instance: TInstance, options: Object, fn?: Function) => any;
2336 afterSave?: (instance: TInstance, options: Object, fn?: Function) => any;
2337 beforeBulkCreate?: (instances: TInstance[], options: Object, fn?: Function) => any;
2338 afterBulkCreate?: (instances: TInstance[], options: Object, fn?: Function) => any;
2339 beforeBulkDestroy?: (options: Object, fn?: Function) => any;
2340 beforeBulkDelete?: (options: Object, fn?: Function) => any;
2341 afterBulkDestroy?: (options: Object, fn?: Function) => any;
2342 afterBulkDelete?: (options: Object, fn?: Function) => any;
2343 beforeBulkUpdate?: (options: Object, fn?: Function) => any;
2344 afterBulkUpdate?: (options: Object, fn?: Function) => any;
2345 beforeFind?: (options: Object, fn?: Function) => any;
2346 beforeFindAfterExpandIncludeAll?: (options: Object, fn?: Function) => any;
2347 beforeFindAfterOptions?: (options: Object, fn?: Function) => any;
2348 afterFind?: (instancesOrInstance: TInstance[] | TInstance, options: Object,
2349 fn?: Function) => any;
2350
2351 }
2352
2353 /**
2354 * Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation.
2355 * Hooks can be added to you models in three ways:
2356 *
2357 * 1. By specifying them as options in `sequelize.define`
2358 * 2. By calling `hook()` with a string and your hook handler function
2359 * 3. By calling the function with the same name as the hook you want
2360 *
2361 * ```js
2362 * // Method 1
2363 * sequelize.define(name, { attributes }, {
2364 * hooks: {
2365 * beforeBulkCreate: function () {
2366 * // can be a single function
2367 * },
2368 * beforeValidate: [
2369 * function () {},
2370 * function() {} // Or an array of several
2371 * ]
2372 * }
2373 * })
2374 *
2375 * // Method 2
2376 * Model.hook('afterDestroy', function () {})
2377 *
2378 * // Method 3
2379 * Model.afterBulkUpdate(function () {})
2380 * ```
2381 *
2382 * @see Sequelize.define
2383 */
2384 interface Hooks<TInstance> {
2385
2386 /**
2387 * Add a hook to the model
2388 *
2389 * @param hookType
2390 * @param name Provide a name for the hook function. It can be used to remove the hook later or to order
2391 * hooks based on some sort of priority system in the future.
2392 * @param fn The hook function
2393 *
2394 * @alias hook
2395 */
2396 addHook(hookType: string, name: string, fn: Function): Hooks<TInstance>;
2397 addHook(hookType: string, fn: Function): Hooks<TInstance>;
2398 hook(hookType: string, name: string, fn: Function): Hooks<TInstance>;
2399 hook(hookType: string, fn: Function): Hooks<TInstance>;
2400
2401 /**
2402 * Remove hook from the model
2403 *
2404 * @param hookType
2405 * @param name
2406 */
2407 removeHook(hookType: string, name: string): Hooks<TInstance>;
2408
2409 /**
2410 * Check whether the mode has any hooks of this type
2411 *
2412 * @param hookType
2413 *
2414 * @alias hasHooks
2415 */
2416 hasHook(hookType: string): boolean;
2417 hasHooks(hookType: string): boolean;
2418
2419 /**
2420 * A hook that is run before validation
2421 *
2422 * @param name
2423 * @param fn A callback function that is called with instance, options
2424 */
2425 beforeValidate(name: string,
2426 fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2427 beforeValidate(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2428
2429 /**
2430 * A hook that is run after validation
2431 *
2432 * @param name
2433 * @param fn A callback function that is called with instance, options
2434 */
2435 afterValidate(name: string,
2436 fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2437 afterValidate(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2438
2439 /**
2440 * A hook that is run before creating a single instance
2441 *
2442 * @param name
2443 * @param fn A callback function that is called with attributes, options
2444 */
2445 beforeCreate(name: string,
2446 fn: (attributes: TInstance, options: Object, fn?: Function) => void): void;
2447 beforeCreate(fn: (attributes: TInstance, options: Object, fn?: Function) => void): void;
2448
2449 /**
2450 * A hook that is run after creating a single instance
2451 *
2452 * @param name
2453 * @param fn A callback function that is called with attributes, options
2454 */
2455 afterCreate(name: string,
2456 fn: (attributes: TInstance, options: Object, fn?: Function) => void): void;
2457 afterCreate(fn: (attributes: TInstance, options: Object, fn?: Function) => void): void;
2458
2459 /**
2460 * A hook that is run before destroying a single instance
2461 *
2462 * @param name
2463 * @param fn A callback function that is called with instance, options
2464 * @alias beforeDelete
2465 */
2466 beforeDestroy(name: string,
2467 fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2468 beforeDestroy(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2469 beforeDelete(name: string,
2470 fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2471 beforeDelete(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2472
2473 /**
2474 * A hook that is run after destroying a single instance
2475 *
2476 * @param name
2477 * @param fn A callback function that is called with instance, options
2478 * @alias afterDelete
2479 */
2480 afterDestroy(name: string,
2481 fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2482 afterDestroy(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2483 afterDelete(name: string, fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2484 afterDelete(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2485
2486 /**
2487 * A hook that is run before updating a single instance
2488 *
2489 * @param name
2490 * @param fn A callback function that is called with instance, options
2491 */
2492 beforeUpdate(name: string,
2493 fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2494 beforeUpdate(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2495
2496 /**
2497 * A hook that is run after updating a single instance
2498 *
2499 * @param name
2500 * @param fn A callback function that is called with instance, options
2501 */
2502 afterUpdate(name: string, fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2503 afterUpdate(fn: (instance: TInstance, options: Object, fn?: Function) => void): void;
2504
2505 /**
2506 * A hook that is run before creating instances in bulk
2507 *
2508 * @param name
2509 * @param fn A callback function that is called with instances, options
2510 */
2511 beforeBulkCreate(name: string,
2512 fn: (instances: TInstance[], options: Object, fn?: Function) => void): void;
2513 beforeBulkCreate(fn: (instances: TInstance[], options: Object, fn?: Function) => void): void;
2514
2515 /**
2516 * A hook that is run after creating instances in bulk
2517 *
2518 * @param name
2519 * @param fn A callback function that is called with instances, options
2520 * @name afterBulkCreate
2521 */
2522 afterBulkCreate(name: string,
2523 fn: (instances: TInstance[], options: Object, fn?: Function) => void): void;
2524 afterBulkCreate(fn: (instances: TInstance[], options: Object, fn?: Function) => void): void;
2525
2526 /**
2527 * A hook that is run before destroying instances in bulk
2528 *
2529 * @param name
2530 * @param fn A callback function that is called with options
2531 *
2532 * @alias beforeBulkDelete
2533 */
2534 beforeBulkDestroy(name: string, fn: (options: Object, fn?: Function) => void): void;
2535 beforeBulkDestroy(fn: (options: Object, fn?: Function) => void): void;
2536 beforeBulkDelete(name: string, fn: (options: Object, fn?: Function) => void): void;
2537 beforeBulkDelete(fn: (options: Object, fn?: Function) => void): void;
2538
2539 /**
2540 * A hook that is run after destroying instances in bulk
2541 *
2542 * @param name
2543 * @param fn A callback function that is called with options
2544 *
2545 * @alias afterBulkDelete
2546 */
2547 afterBulkDestroy(name: string, fn: (options: Object, fn?: Function) => void): void;
2548 afterBulkDestroy(fn: (options: Object, fn?: Function) => void): void;
2549 afterBulkDelete(name: string, fn: (options: Object, fn?: Function) => void): void;
2550 afterBulkDelete(fn: (options: Object, fn?: Function) => void): void;
2551
2552 /**
2553 * A hook that is run after updating instances in bulk
2554 *
2555 * @param name
2556 * @param fn A callback function that is called with options
2557 */
2558 beforeBulkUpdate(name: string, fn: (options: Object, fn?: Function) => void): void;
2559 beforeBulkUpdate(fn: (options: Object, fn?: Function) => void): void;
2560
2561 /**
2562 * A hook that is run after updating instances in bulk
2563 *
2564 * @param name
2565 * @param fn A callback function that is called with options
2566 */
2567 afterBulkUpdate(name: string, fn: (options: Object, fn?: Function) => void): void;
2568 afterBulkUpdate(fn: (options: Object, fn?: Function) => void): void;
2569
2570 /**
2571 * A hook that is run before a find (select) query
2572 *
2573 * @param name
2574 * @param fn A callback function that is called with options
2575 */
2576 beforeFind(name: string, fn: (options: Object, fn?: Function) => void): void;
2577 beforeFind(fn: (options: Object, fn?: Function) => void): void;
2578
2579 /**
2580 * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
2581 *
2582 * @param name
2583 * @param fn A callback function that is called with options
2584 */
2585 beforeFindAfterExpandIncludeAll(name: string,
2586 fn: (options: Object, fn?: Function) => void): void;
2587 beforeFindAfterExpandIncludeAll(fn: (options: Object, fn?: Function) => void): void;
2588
2589 /**
2590 * A hook that is run before a find (select) query, after all option parsing is complete
2591 *
2592 * @param name
2593 * @param fn A callback function that is called with options
2594 */
2595 beforeFindAfterOptions(name: string, fn: (options: Object, fn?: Function) => void): void;
2596 beforeFindAfterOptions(fn: (options: Object, fn?: Function) => void): void;
2597
2598 /**
2599 * A hook that is run after a find (select) query
2600 *
2601 * @param name
2602 * @param fn A callback function that is called with instance(s), options
2603 */
2604 afterFind(name: string,
2605 fn: (instancesOrInstance: TInstance[] | TInstance, options: Object,
2606 fn?: Function) => void): void;
2607 afterFind(fn: (instancesOrInstance: TInstance[] | TInstance, options: Object,
2608 fn?: Function) => void): void;
2609
2610 /**
2611 * A hook that is run before a define call
2612 *
2613 * @param name
2614 * @param fn A callback function that is called with attributes, options
2615 */
2616 beforeDefine(name: string, fn: (attributes: DefineAttributes, options: Object) => void): void;
2617 beforeDefine(fn: (attributes: DefineAttributes, options: Object) => void): void;
2618
2619 /**
2620 * A hook that is run after a define call
2621 *
2622 * @param name
2623 * @param fn A callback function that is called with factory
2624 */
2625 afterDefine(name: string, fn: (model: Model<TInstance, any>) => void): void;
2626 afterDefine(fn: (model: Model<TInstance, any>) => void): void;
2627
2628 /**
2629 * A hook that is run before Sequelize() call
2630 *
2631 * @param name
2632 * @param fn A callback function that is called with config, options
2633 */
2634 beforeInit(name: string, fn: (config: Object, options: Object) => void): void;
2635 beforeInit(fn: (config: Object, options: Object) => void): void;
2636
2637 /**
2638 * A hook that is run after Sequelize() call
2639 *
2640 * @param name
2641 * @param fn A callback function that is called with sequelize
2642 */
2643 afterInit(name: string, fn: (sequelize: Sequelize) => void): void;
2644 afterInit(fn: (sequelize: Sequelize) => void): void;
2645
2646 /**
2647 * A hook that is run before Model.sync call
2648 *
2649 * @param name
2650 * @param fn A callback function that is called with options passed to Model.sync
2651 */
2652 beforeSync(name: string, fn: (options: SyncOptions) => void): void;
2653 beforeSync(fn: (options: SyncOptions) => void): void;
2654
2655 /**
2656 * A hook that is run after Model.sync call
2657 *
2658 * @param name
2659 * @param fn A callback function that is called with options passed to Model.sync
2660 */
2661 afterSync(name: string, fn: (options: SyncOptions) => void): void;
2662 afterSync(fn: (options: SyncOptions) => void): void;
2663
2664 /**
2665 * A hook that is run before sequelize.sync call
2666 *
2667 * @param name
2668 * @param fn A callback function that is called with options passed to sequelize.sync
2669 */
2670 beforeBulkSync(name: string, fn: (options: SyncOptions) => void): void;
2671 beforeBulkSync(fn: (options: SyncOptions) => void): void;
2672
2673 /**
2674 * A hook that is run after sequelize.sync call
2675 *
2676 * @param name
2677 * @param fn A callback function that is called with options passed to sequelize.sync
2678 */
2679 afterBulkSync(name: string, fn: (options: SyncOptions) => void): void;
2680 afterBulkSync(fn: (options: SyncOptions) => void): void;
2681 }
2682
2683 //
2684 // Instance
2685 // ~~~~~~~~~~
2686 //
2687 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/instance.js
2688 //
2689
2690 /**
2691 * Options used for Instance.increment method
2692 */
2693 interface InstanceIncrementDecrementOptions {
2694
2695 /**
2696 * The number to increment by
2697 *
2698 * Defaults to 1
2699 */
2700 by?: number;
2701
2702 /**
2703 * A function that gets executed while running the query to log the sql.
2704 */
2705 logging?: boolean | Function;
2706
2707 /**
2708 * Transaction to run query under
2709 */
2710 transaction?: Transaction;
2711
2712 /**
2713 * A hash of attributes to describe your search. See above for examples.
2714 */
2715 where?: AnyWhereOptions | Array<col | and | or | string>;
2716
2717 }
2718
2719 /**
2720 * Options used for Instance.restore method
2721 */
2722 interface InstanceRestoreOptions {
2723
2724 /**
2725 * A function that gets executed while running the query to log the sql.
2726 */
2727 logging?: boolean | Function;
2728
2729 /**
2730 * Transaction to run query under
2731 */
2732 transaction?: Transaction;
2733 }
2734
2735 /**
2736 * Options used for Instance.destroy method
2737 */
2738 interface InstanceDestroyOptions {
2739
2740 /**
2741 * If set to true, paranoid models will actually be deleted
2742 */
2743 force?: boolean;
2744
2745 /**
2746 * A function that gets executed while running the query to log the sql.
2747 */
2748 logging?: boolean | Function;
2749
2750 /**
2751 * Transaction to run the query in
2752 */
2753 transaction?: Transaction;
2754
2755 }
2756
2757 /**
2758 * Options used for Instance.update method
2759 */
2760 interface InstanceUpdateOptions extends InstanceSaveOptions, InstanceSetOptions {
2761
2762 /**
2763 * A hash of attributes to describe your search. See above for examples.
2764 */
2765 where?: AnyWhereOptions | Array<col | and | or | string>;
2766
2767 }
2768
2769 /**
2770 * Options used for Instance.set method
2771 */
2772 interface InstanceSetOptions {
2773
2774 /**
2775 * If set to true, field and virtual setters will be ignored
2776 */
2777 raw?: boolean;
2778
2779 /**
2780 * Clear all previously set data values
2781 */
2782 reset?: boolean;
2783
2784 }
2785
2786 /**
2787 * Options used for Instance.save method
2788 */
2789 interface InstanceSaveOptions extends FieldsOptions, LoggingOptions, ReturningOptions, SearchPathOptions {
2790
2791 /**
2792 * If true, the updatedAt timestamp will not be updated.
2793 *
2794 * Defaults to false
2795 */
2796 silent?: boolean;
2797 hooks?: boolean;
2798
2799 }
2800
2801 /**
2802 * This class represents an single instance, a database row. You might see it referred to as both Instance and
2803 * instance. You should not instantiate the Instance class directly, instead you access it using the finder and
2804 * creation methods on the model.
2805 *
2806 * Instance instances operate with the concept of a `dataValues` property, which stores the actual values
2807 * represented by the instance. By default, the values from dataValues can also be accessed directly from the
2808 * Instance, that is:
2809 * ```js
2810 * instance.field
2811 * // is the same as
2812 * instance.get('field')
2813 * // is the same as
2814 * instance.getDataValue('field')
2815 * ```
2816 * However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the
2817 * value from `dataValues`. Accessing properties directly or using `get` is preferred for regular use,
2818 * `getDataValue` should only be used for custom getters.
2819 *
2820 * @see Sequelize.define for more information about getters and setters
2821 */
2822 interface Instance<TAttributes> {
2823
2824 /**
2825 * Returns true if this instance has not yet been persisted to the database
2826 */
2827 isNewRecord: boolean;
2828
2829 /**
2830 * Returns the Model the instance was created from.
2831 *
2832 * @see Model
2833 */
2834 Model: Model<this, TAttributes>;
2835
2836 /**
2837 * A reference to the sequelize instance
2838 */
2839 sequelize: Sequelize;
2840
2841 /**
2842 * Get an object representing the query for this instance, use with `options.where`
2843 */
2844 where(): Object;
2845
2846 /**
2847 * Get the value of the underlying data value
2848 */
2849 getDataValue(key: keyof TAttributes): any;
2850
2851 /**
2852 * Update the underlying data value
2853 */
2854 setDataValue<K extends keyof TAttributes>(
2855 key: K,
2856 value: TAttributes[K]
2857 ): void;
2858
2859 /**
2860 * If no key is given, returns all values of the instance, also invoking virtual getters.
2861 *
2862 * If key is given and a field or virtual getter is present for the key it will call that getter - else it
2863 * will return the value for key.
2864 *
2865 * @param options.plain If set to true, included instances will be returned as plain objects
2866 */
2867 get(key: keyof TAttributes, options?: { plain?: boolean, clone?: boolean }): any;
2868 get(options?: { plain?: boolean, clone?: boolean }): TAttributes;
2869
2870 /**
2871 * Set is used to update values on the instance (the sequelize representation of the instance that is,
2872 * remember that nothing will be persisted before you actually call `save`). In its most basic form `set`
2873 * will update a value stored in the underlying `dataValues` object. However, if a custom setter function
2874 * is defined for the key, that function will be called instead. To bypass the setter, you can pass `raw:
2875 * true` in the options object.
2876 *
2877 * If set is called with an object, it will loop over the object, and call set recursively for each key,
2878 * value pair. If you set raw to true, the underlying dataValues will either be set directly to the object
2879 * passed, or used to extend dataValues, if dataValues already contain values.
2880 *
2881 * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
2882 *
2883 * Set can also be used to build instances for associations, if you have values for those.
2884 * When using set with associations you need to make sure the property key matches the alias of the
2885 * association while also making sure that the proper include options have been set (from .build() or
2886 * .find())
2887 *
2888 * If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the
2889 * entire object as changed.
2890 *
2891 * @param options.raw If set to true, field and virtual setters will be ignored
2892 * @param options.reset Clear all previously set data values
2893 */
2894 set<K extends keyof TAttributes>(
2895 key: K,
2896 value: TAttributes[K],
2897 options?: InstanceSetOptions
2898 ): this;
2899 set(keys: Object, options?: InstanceSetOptions): this;
2900 setAttributes<K extends keyof TAttributes>(
2901 key: K,
2902 value: TAttributes[K],
2903 options?: InstanceSetOptions
2904 ): this;
2905 setAttributes(keys: Object, options?: InstanceSetOptions): this;
2906
2907 /**
2908 * If changed is called with a string it will return a boolean indicating whether the value of that key in
2909 * `dataValues` is different from the value in `_previousDataValues`.
2910 *
2911 * If changed is called without an argument, it will return an array of keys that have changed.
2912 *
2913 * If changed is called without an argument and no keys have changed, it will return `false`.
2914 */
2915 changed(key: keyof TAttributes): boolean;
2916 changed(): boolean | string[];
2917
2918 /**
2919 * If previous is called with a string, it will return the previous value for the key from `_previousDataValues`.
2920 *
2921 * If previous is called without an argument, it will return an object containing the previous keys and values that have changed.
2922 */
2923 previous(key: keyof TAttributes): any;
2924 previous(): object;
2925
2926 /**
2927 * Validate this instance, and if the validation passes, persist it to the database.
2928 *
2929 * On success, the callback will be called with this instance. On validation error, the callback will be
2930 * called with an instance of `Sequelize.ValidationError`. This error will have a property for each of the
2931 * fields for which validation failed, with the error message for that field.
2932 */
2933 save(options?: InstanceSaveOptions): Promise<this>;
2934
2935 /**
2936 * Refresh the current instance in-place, i.e. update the object with current data from the DB and return
2937 * the same object. This is different from doing a `find(Instance.id)`, because that would create and
2938 * return a new instance. With this method, all references to the Instance are updated with the new data
2939 * and no new objects are created.
2940 */
2941 reload(options?: AnyFindOptions): Promise<this>;
2942
2943 /**
2944 * Validate the attribute of this instance according to validation rules set in the model definition.
2945 *
2946 * Emits null if and only if validation successful; otherwise an Error instance containing
2947 * { field name : [error msgs] } entries.
2948 *
2949 * @param options.skip An array of strings. All properties that are in this array will not be validated
2950 */
2951 validate(options?: { skip?: string[] }): Promise<ValidationError>;
2952
2953 /**
2954 * This is the same as calling `set` and then calling `save`.
2955 */
2956 update<K extends keyof TAttributes>(
2957 key: K,
2958 value: TAttributes[K],
2959 options?: InstanceUpdateOptions
2960 ): Promise<this>;
2961 update(keys: Object, options?: InstanceUpdateOptions): Promise<this>;
2962 updateAttributes<K extends keyof TAttributes>(
2963 key: K,
2964 value: TAttributes[K],
2965 options?: InstanceUpdateOptions
2966 ): Promise<this>;
2967 updateAttributes(keys: Object, options?: InstanceUpdateOptions): Promise<this>;
2968
2969 /**
2970 * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will
2971 * either be completely deleted, or have its deletedAt timestamp set to the current time.
2972 */
2973 destroy(options?: InstanceDestroyOptions): Promise<void>;
2974
2975 /**
2976 * Restore the row corresponding to this instance. Only available for paranoid models.
2977 */
2978 restore(options?: InstanceRestoreOptions): Promise<void>;
2979
2980 /**
2981 * Increment the value of one or more columns. This is done in the database, which means it does not use
2982 * the values currently stored on the Instance. The increment is done using a
2983 * ```sql
2984 * SET column = column + X
2985 * ```
2986 * query. To get the correct value after an increment into the Instance you should do a reload.
2987 *
2988 *```js
2989 * instance.increment('number') // increment number by 1
2990 * instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
2991 * instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
2992 * // `by` is ignored, since each column has its own
2993 * // value
2994 * ```
2995 *
2996 * @param fields If a string is provided, that column is incremented by the value of `by` given in options.
2997 * If an array is provided, the same is true for each column.
2998 * If and object is provided, each column is incremented by the value given.
2999 */
3000 increment(fields: Partial<TAttributes> | Array<keyof TAttributes> | keyof TAttributes,
3001 options?: InstanceIncrementDecrementOptions): Promise<this>;
3002
3003 /**
3004 * Decrement the value of one or more columns. This is done in the database, which means it does not use
3005 * the values currently stored on the Instance. The decrement is done using a
3006 * ```sql
3007 * SET column = column - X
3008 * ```
3009 * query. To get the correct value after an decrement into the Instance you should do a reload.
3010 *
3011 * ```js
3012 * instance.decrement('number') // decrement number by 1
3013 * instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
3014 * instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
3015 * // `by` is ignored, since each column has its own
3016 * // value
3017 * ```
3018 *
3019 * @param fields If a string is provided, that column is decremented by the value of `by` given in options.
3020 * If an array is provided, the same is true for each column.
3021 * If and object is provided, each column is decremented by the value given
3022 */
3023 decrement(fields: Partial<TAttributes> | Array<keyof TAttributes> | keyof TAttributes,
3024 options?: InstanceIncrementDecrementOptions): Promise<this>;
3025
3026 /**
3027 * Check whether all values of this and `other` Instance are the same
3028 */
3029 equals(other: Instance<any>): boolean;
3030
3031 /**
3032 * Check if this is eqaul to one of `others` by calling equals
3033 */
3034 equalsOneOf(others: Instance<any>[]): boolean;
3035
3036 /**
3037 * Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all
3038 * values gotten from the DB, and apply all custom getters.
3039 */
3040 toJSON(): TAttributes;
3041
3042 }
3043
3044 interface LoggingOptions {
3045 /**
3046 * A function that gets executed while running the query to log the sql.
3047 */
3048
3049 logging?: boolean | Function;
3050
3051 /**
3052 * Print query execution time in milliseconds when logging SQL.
3053 */
3054 benchmark?: boolean;
3055 }
3056
3057 interface SearchPathOptions {
3058 /**
3059 * Transaction to run query under
3060 */
3061 transaction?: Transaction;
3062
3063 /**
3064 * An optional parameter to specify the schema search_path (Postgres only)
3065 */
3066 searchPath?: string;
3067 }
3068
3069 interface ReturningOptions {
3070 /**
3071 * Append RETURNING * to get back auto generated values (Postgres only)
3072 */
3073 returning?: boolean;
3074 }
3075
3076 interface FieldsOptions {
3077 /**
3078 * Run validations before the row is inserted
3079 */
3080 validate?: boolean;
3081
3082 /**
3083 * The fields to insert / update. Defaults to all fields
3084 */
3085 fields?: string[];
3086 }
3087
3088 //
3089 // Model
3090 // ~~~~~~~
3091 //
3092 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/model.js
3093 //
3094
3095 /**
3096 * Options to pass to Model on drop
3097 */
3098 interface DropOptions extends LoggingOptions {
3099
3100 /**
3101 * Also drop all objects depending on this table, such as views. Only works in postgres
3102 */
3103 cascade?: boolean;
3104
3105 }
3106
3107 /**
3108 * Schema Options provided for applying a schema to a model
3109 */
3110 interface SchemaOptions extends LoggingOptions {
3111
3112 /**
3113 * The character(s) that separates the schema name from the table name
3114 */
3115 schemaDelimeter?: string;
3116
3117 }
3118 /**
3119 * GetTableName Options
3120 */
3121 interface GetTableNameOptions extends LoggingOptions {
3122 // no addition properties
3123 }
3124
3125
3126 /**
3127 * AddScope Options for Model.addScope
3128 */
3129 interface AddScopeOptions {
3130 /**
3131 * If a scope of the same name already exists, should it be overwritten?
3132 */
3133 override: boolean;
3134 }
3135
3136 /**
3137* Scope Options for Model.scope
3138*/
3139 interface ScopeOptions {
3140
3141 /**
3142 * The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments.
3143 * To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function,
3144 * pass an object, with a `method` property. The value can either be a string, if the method does not take
3145 * any arguments, or an array, where the first element is the name of the method, and consecutive elements
3146 * are arguments to that method. Pass null to remove all scopes, including the default.
3147 */
3148 method: string | any[];
3149
3150 }
3151
3152 /**
3153 * Where Complex nested query
3154 */
3155 interface WhereNested {
3156 $and: Array<AnyWhereOptions | WhereLogic>;
3157 $or: Array<AnyWhereOptions | WhereLogic>;
3158 }
3159
3160 /**
3161 * Nested where Postgre Statement
3162 */
3163 interface WherePGStatement {
3164 $any: Array<string | number>;
3165 $all: Array<string | number>;
3166 }
3167
3168 /**
3169 * Where Geometry Options
3170 */
3171 interface WhereGeometryOptions {
3172 type: string;
3173 coordinates: Array<number[] | number>;
3174 }
3175
3176 /**
3177 * Logic of where statement
3178 */
3179 type WhereLogic = Partial<{
3180 $ne: string | number | WhereLogic;
3181 $in: Array<string | number> | literal;
3182 $not: boolean | string | number | AnyWhereOptions;
3183 $notIn: Array<string | number> | literal;
3184 $gte: number | string | Date;
3185 $gt: number | string | Date;
3186 $lte: number | string | Date;
3187 $lt: number | string | Date;
3188 $like: string | WherePGStatement;
3189 $iLike: string | WherePGStatement;
3190 $ilike: string | WherePGStatement;
3191 $notLike: string | WherePGStatement;
3192 $notILike: string | WherePGStatement;
3193 $between: [number, number] | [Date, Date];
3194 "..": [number, number] | [string, string];
3195 $notBetween: [number, number];
3196 "!..": [number, number] | [string, string];
3197 $overlap: [number, number] | [string, string];
3198 "&&": [number, number];
3199 $contains: any;
3200 "@>": any;
3201 $contained: any;
3202 "<@": any;
3203 }>;
3204
3205 /**
3206 * A hash of attributes to describe your search. See above for examples.
3207 *
3208 * We did put Object in the end, because there where query might be a JSON Blob. It cripples a bit the
3209 * typesafety, but there is no way to pass the tests if we just remove it.
3210 */
3211 type Primitives = string | number | boolean | Buffer;
3212 type WhereOptions<T> = {
3213 [P in keyof T]?: Primitives | Array<Primitives> | WhereLogic | (T[P] extends Primitives ? null : WhereOptions<T[P]>) | col | and | or | WhereGeometryOptions | WhereNested | where | null;
3214 };
3215
3216 /**
3217 * A hash of attributes to describe your search, accepting any field names. See `WhereOptions` for details.
3218 */
3219 interface AnyWhereOptions {
3220 [field: string]: WhereOptions<any>[] | Object;
3221 }
3222
3223 /**
3224 * Through options for Include Options
3225 */
3226 interface IncludeThroughOptions {
3227
3228 /**
3229 * Filter on the join model for belongsToMany relations
3230 */
3231 where?: AnyWhereOptions;
3232
3233 /**
3234 * A list of attributes to select from the join model for belongsToMany relations
3235 */
3236 attributes?: string[];
3237
3238 }
3239
3240 /**
3241 * Association Object for Include Options
3242 */
3243 interface IncludeAssociation {
3244 source: Model<any, any>;
3245 target: Model<any, any>;
3246 identifier: string;
3247 }
3248
3249 /**
3250 * Complex include options
3251 */
3252 interface IncludeOptions {
3253
3254 /**
3255 * The model you want to eagerly load
3256 */
3257 model?: Model<any, any>;
3258
3259 /**
3260 * The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` /
3261 * `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
3262 */
3263 as?: string;
3264
3265 /**
3266 * The association you want to eagerly load. (This can be used instead of providing a model/as pair).
3267 * You can also use the association alias.
3268 */
3269 association?: IncludeAssociation | string;
3270
3271 /**
3272 * Where clauses to apply to the child models. Note that this converts the eager load to an inner join,
3273 * unless you explicitly set `required: false`
3274 */
3275 where?: AnyWhereOptions;
3276
3277 /**
3278 * A list of attributes to select from the child model
3279 */
3280 attributes?: FindOptionsAttributesArray | { include?: FindOptionsAttributesArray, exclude?: Array<string> };
3281
3282 /**
3283 * If true, converts to an inner join, which means that the parent model will only be loaded if it has any
3284 * matching children. True if `include.where` is set, false otherwise.
3285 */
3286 required?: boolean;
3287
3288 /**
3289 * Through Options
3290 */
3291 through?: IncludeThroughOptions;
3292
3293 /**
3294 * Load further nested related models
3295 */
3296 include?: Array<Model<any, any> | IncludeOptions>;
3297
3298 /**
3299 * If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
3300 * be returned. Only applies if `options.paranoid` is true for the model.
3301 */
3302 paranoid?: boolean;
3303
3304 all?: boolean | string;
3305
3306 /**
3307 * if true, it will also eager load the relations of the child models, recursively.
3308 */
3309 nested?: boolean;
3310
3311 /**
3312 * If true, runs a separate query to fetch the associated instances, only supported for hasMany associations
3313 */
3314 separate?: boolean;
3315 }
3316
3317 /**
3318 * Shortcut for types used in FindOptions.attributes
3319 */
3320 type FindOptionsAttributesArray = Array<string | literal | [string, string] | fn | [fn, string] | cast | [cast, string] | [literal, string]>;
3321
3322 /**
3323 * Shortcut for order type in FindOptions.attributes
3324 */
3325 type FindOptionsOrderArray = Array<string | number | Model<any, any> | { model: Model<any, any>, as?: string } | fn>;
3326
3327 /**
3328 * Options that are passed to any model creating a SELECT query
3329 *
3330 * A hash of options to describe the scope of the search
3331 */
3332 interface FindOptions<T> extends LoggingOptions, SearchPathOptions {
3333
3334 /**
3335 * A hash of attributes to describe your search. See above for examples.
3336 */
3337 where?: WhereOptions<T> | where | fn | Array<col | and | or | string>;
3338
3339 /**
3340 * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with
3341 * two elements - the first is the name of the attribute in the DB (or some kind of expression such as
3342 * `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to
3343 * have in the returned instance
3344 */
3345 attributes?: FindOptionsAttributesArray | { include?: FindOptionsAttributesArray, exclude?: Array<string> };
3346
3347 /**
3348 * If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
3349 * be returned. Only applies if `options.paranoid` is true for the model.
3350 */
3351 paranoid?: boolean;
3352
3353 /**
3354 * A list of associations to eagerly load using a left join. Supported is either
3355 * `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }]}`.
3356 * If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in
3357 * the as attribute when eager loading Y).
3358 */
3359 include?: Array<Model<any, any> | IncludeOptions>;
3360
3361 /**
3362 * Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide
3363 * several columns / functions to order by. Each element can be further wrapped in a two-element array. The
3364 * first element is the column / function to order by, the second is the direction. For example:
3365 * `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
3366 */
3367 order?: string | col | literal | FindOptionsOrderArray | fn | Array<string | col | literal | FindOptionsOrderArray | fn>;
3368
3369 /**
3370 * Limit the results
3371 */
3372 limit?: number;
3373
3374 /**
3375 * Skip the results;
3376 */
3377 offset?: number;
3378
3379 /**
3380 * Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE.
3381 * Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model
3382 * locks with joins. See [transaction.LOCK for an example](transaction#lock)
3383 */
3384 lock?: TransactionLockLevel | { level: TransactionLockLevel, of: Model<any, any> };
3385
3386 /**
3387 * Return raw result. See sequelize.query for more information.
3388 */
3389 raw?: boolean;
3390
3391 /**
3392 * having ?!?
3393 */
3394 having?: AnyWhereOptions;
3395
3396 /**
3397 * Group by. It is not mentioned in sequelize's JSDoc, but mentioned in docs.
3398 * https://github.com/sequelize/sequelize/blob/master/docs/docs/models-usage.md#user-content-manipulating-the-dataset-with-limit-offset-order-and-group
3399 */
3400 group?: string | string[] | Object;
3401
3402 /**
3403 * Apply DISTINCT(col) for FindAndCount(all)
3404 */
3405 distinct?: boolean;
3406
3407 /**
3408 * Prevents a subquery on the main table when using include
3409 */
3410 subQuery?: boolean;
3411
3412 /**
3413 * Throw EmptyResultError if a record is not found
3414 */
3415 rejectOnEmpty?: boolean;
3416
3417 /**
3418 * Force the query to use the write pool
3419 *
3420 * Defaults to false
3421 */
3422 useMaster?: boolean;
3423 }
3424
3425 type AnyFindOptions = FindOptions<any>;
3426
3427 /**
3428 * Options for Model.count method
3429 */
3430 interface CountOptions extends LoggingOptions, SearchPathOptions {
3431
3432 /**
3433 * A hash of search attributes.
3434 */
3435 where?: AnyWhereOptions | string[];
3436
3437 /**
3438 * Include options. See `find` for details
3439 */
3440 include?: Array<Model<any, any> | IncludeOptions>;
3441
3442 /**
3443 * Apply column on which COUNT() should be applied
3444 */
3445 col?: string;
3446
3447 /**
3448 * Apply COUNT(DISTINCT(col))
3449 */
3450 distinct?: boolean;
3451
3452 /**
3453 * Used in conjustion with `group`
3454 */
3455 attributes?: Array<string | [string, string]>;
3456
3457 /**
3458 * For creating complex counts. Will return multiple rows as needed.
3459 *
3460 * TODO: Check?
3461 */
3462 group?: Object;
3463 }
3464
3465 /**
3466 * Options for Model.build method
3467 */
3468 interface BuildOptions extends ReturningOptions {
3469
3470 /**
3471 * If set to true, values will ignore field and virtual setters.
3472 */
3473 raw?: boolean;
3474
3475 /**
3476 * Is this record new
3477 */
3478 isNewRecord?: boolean;
3479
3480 /**
3481 * an array of include options - Used to build prefetched/included model instances. See `set`
3482 *
3483 * TODO: See set
3484 */
3485 include?: Array<Model<any, any> | IncludeOptions>;
3486 }
3487
3488 /**
3489 * Options for Model.create method
3490 */
3491 interface CreateOptions extends BuildOptions, InstanceSaveOptions {
3492
3493 /**
3494 * On Duplicate
3495 */
3496 onDuplicate?: string;
3497 }
3498
3499 /**
3500 * Options for Model.findOrInitialize method
3501 */
3502 interface FindOrInitializeOptions<TAttributes> extends FindOptions<TAttributes> {
3503
3504 /**
3505 * Default values to use if building a new instance
3506 */
3507 defaults?: TAttributes;
3508
3509 }
3510
3511 /**
3512 * Options for Model.findOrInitialize method
3513 */
3514 interface FindCreateFindOptions<TAttributes> extends FindOptions<TAttributes> {
3515
3516 /**
3517 * Default values to use if building a new instance
3518 */
3519 defaults?: TAttributes;
3520
3521 }
3522
3523 /**
3524 * Options for Model.upsert method
3525 */
3526 interface UpsertOptions extends FieldsOptions, LoggingOptions, SearchPathOptions, ReturningOptions {
3527 }
3528
3529 /**
3530 * Options for Model.bulkCreate method
3531 */
3532
3533 interface BulkCreateOptions extends FieldsOptions, LoggingOptions, SearchPathOptions, ReturningOptions {
3534
3535 /**
3536 * Run before / after bulk create hooks?
3537 */
3538 hooks?: boolean;
3539
3540 /**
3541 * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if
3542 * options.hooks is true.
3543 */
3544 individualHooks?: boolean;
3545
3546 /**
3547 * Ignore duplicate values for primary keys? (not supported by postgres)
3548 *
3549 * Defaults to false
3550 */
3551 ignoreDuplicates?: boolean;
3552
3553 /**
3554 * Fields to update if row key already exists (on duplicate key update)? (only supported by mysql &
3555 * mariadb). By default, all fields are updated.
3556 */
3557 updateOnDuplicate?: string[];
3558 }
3559
3560 /**
3561 * The options passed to Model.destroy in addition to truncate
3562 */
3563 interface TruncateOptions extends LoggingOptions, SearchPathOptions {
3564
3565 /**
3566 * Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the
3567 * named table, or to any tables added to the group due to CASCADE.
3568 *
3569 * Defaults to false;
3570 */
3571 cascade?: boolean;
3572
3573 /**
3574 * Delete instead of setting deletedAt to current timestamp (only applicable if paranoid is enabled)
3575 *
3576 * Defaults to false;
3577 */
3578 force?: boolean;
3579
3580 }
3581
3582 /**
3583 * Options used for Model.destroy
3584 */
3585 interface DestroyOptions extends TruncateOptions {
3586
3587 /**
3588 * Filter the destroy
3589 */
3590 where?: AnyWhereOptions;
3591
3592 /**
3593 * Run before / after bulk destroy hooks?
3594 */
3595 hooks?: boolean;
3596
3597 /**
3598 * If set to true, destroy will SELECT all records matching the where parameter and will execute before /
3599 * after destroy hooks on each row
3600 */
3601 individualHooks?: boolean;
3602
3603 /**
3604 * How many rows to delete
3605 */
3606 limit?: number;
3607
3608 /**
3609 * Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
3610 */
3611 force?: boolean;
3612
3613 /**
3614 * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is
3615 * truncated the where and limit options are ignored
3616 */
3617 truncate?: boolean;
3618
3619 }
3620
3621 /**
3622 * Options for Model.restore
3623 */
3624 interface RestoreOptions extends LoggingOptions {
3625
3626 /**
3627 * Filter the restore
3628 */
3629 where?: AnyWhereOptions;
3630
3631 /**
3632 * Run before / after bulk restore hooks?
3633 */
3634 hooks?: boolean;
3635
3636 /**
3637 * If set to true, restore will find all records within the where parameter and will execute before / after
3638 * bulkRestore hooks on each row
3639 */
3640 individualHooks?: boolean;
3641
3642 /**
3643 * How many rows to undelete
3644 */
3645 limit?: number;
3646
3647 /**
3648 * Transaction to run query under
3649 */
3650 transaction?: Transaction;
3651
3652 }
3653
3654 /**
3655 * Options used for Model.update
3656 */
3657 interface UpdateOptions extends FieldsOptions, LoggingOptions, ReturningOptions {
3658
3659 /**
3660 * Options to describe the scope of the search.
3661 */
3662 where: AnyWhereOptions;
3663
3664 /**
3665 * Run before / after bulk update hooks?
3666 *
3667 * Defaults to true
3668 */
3669 hooks?: boolean;
3670
3671 /**
3672 * Whether or not to update the side effects of any virtual setters.
3673 *
3674 * Defaults to true
3675 */
3676 sideEffects?: boolean;
3677
3678 /**
3679 * Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs.
3680 * A select is needed, because the row data needs to be passed to the hooks
3681 *
3682 * Defaults to false
3683 */
3684 individualHooks?: boolean;
3685
3686 /**
3687 * How many rows to update (only for mysql and mariadb)
3688 */
3689 limit?: number;
3690
3691 /**
3692 * Transaction to run query under
3693 */
3694 transaction?: Transaction;
3695
3696 /**
3697 * If true, the updatedAt timestamp will not be updated.
3698 */
3699 silent?: boolean;
3700 }
3701
3702 /**
3703 * Options used for Model.aggregate
3704 */
3705 interface AggregateOptions extends LoggingOptions {
3706
3707 /**
3708 * A hash of search attributes.
3709 */
3710 where?: AnyWhereOptions;
3711
3712 /**
3713 * The type of the result. If `field` is a field in this Model, the default will be the type of that field,
3714 * otherwise defaults to float.
3715 */
3716 dataType?: DataTypeAbstract | string;
3717
3718 /**
3719 * Applies DISTINCT to the field being aggregated over
3720 */
3721 distinct?: boolean;
3722
3723 /**
3724 * The transaction that the query should be executed under
3725 */
3726 transaction?: Transaction;
3727
3728 /**
3729 * When `true`, the first returned value of `aggregateFunction` is cast to `dataType` and returned.
3730 * If additional attributes are specified, along with `group` clauses, set `plain` to `false` to return all values of all returned rows.
3731 * Defaults to `true`
3732 */
3733 plain?: boolean;
3734 }
3735
3736 /**
3737 * Models contains Model instances associated to their name
3738 */
3739 interface Models {
3740 [index: string]: Model<any, any>;
3741 }
3742
3743 /**
3744 * A Model represents a table in the database. Sometimes you might also see it referred to as model, or simply
3745 * as factory. This class should _not_ be instantiated directly, it is created using `sequelize.define`, and
3746 * already created models can be loaded using `sequelize.import`
3747 */
3748 interface Model<TInstance, TAttributes, TCreationAttributes = TAttributes> extends Hooks<TInstance>, Associations {
3749
3750 /**
3751 * The Instance class
3752 */
3753 Instance(): TInstance;
3754
3755 /**
3756 * The singular name of the model
3757 */
3758 name: string;
3759
3760 /**
3761 * Remove attribute from model definition
3762 *
3763 * @param attribute
3764 */
3765 removeAttribute(attribute: string): void;
3766
3767 /**
3768 * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the
3769 * model instance (this)
3770 */
3771 sync(options?: SyncOptions): Promise<this>;
3772
3773 /**
3774 * Drop the table represented by this Model
3775 *
3776 * @param options
3777 */
3778 drop(options?: DropOptions): Promise<void>;
3779
3780 /**
3781 * Apply a schema to this model. For postgres, this will actually place the schema in front of the table
3782 * name
3783 * - `"schema"."tableName"`, while the schema will be prepended to the table name for mysql and
3784 * sqlite - `'schema.tablename'`.
3785 *
3786 * @param schema The name of the schema
3787 * @param options
3788 */
3789 schema(schema: string, options?: SchemaOptions): this;
3790
3791 /**
3792 * Get the tablename of the model, taking schema into account. The method will return The name as a string
3793 * if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties.
3794 *
3795 * @param options The hash of options from any query. You can use one model to access tables with matching
3796 * schemas by overriding `getTableName` and using custom key/values to alter the name of the table.
3797 * (eg.
3798 * subscribers_1, subscribers_2)
3799 * @param options.logging=false A function that gets executed while running the query to log the sql.
3800 */
3801 getTableName(options?: GetTableNameOptions): string | Object;
3802
3803 /**
3804 * 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.
3805 *
3806 * 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.
3807 *
3808 * @param {String} name The name of the scope. Use `defaultScope` to override the default scope
3809 * @param {Object|Function} scope
3810 * @param {Object} [options]
3811 * @param {Boolean} [options.override=false]
3812 */
3813 addScope(name: string, scope: AnyFindOptions | Function, options?: AddScopeOptions): void;
3814
3815 /**
3816 * 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.
3817 *
3818 * 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.
3819 *
3820 * @param {String} name The name of the scope. Use `defaultScope` to override the default scope
3821 * @param {Object|Function} scope
3822 * @param {Object} [options]
3823 * @param {Boolean} [options.override=false]
3824 */
3825 addScope(name: string, scope: AnyFindOptions | Function, options?: AddScopeOptions): void;
3826
3827 /**
3828 * Apply a scope created in `define` to the model. First let's look at how to create scopes:
3829 * ```js
3830 * var Model = sequelize.define('model', attributes, {
3831 * defaultScope: {
3832 * where: {
3833 * username: 'dan'
3834 * },
3835 * limit: 12
3836 * },
3837 * scopes: {
3838 * isALie: {
3839 * where: {
3840 * stuff: 'cake'
3841 * }
3842 * },
3843 * complexFunction: function(email, accessLevel) {
3844 * return {
3845 * where: {
3846 * email: {
3847 * $like: email
3848 * },
3849 * accesss_level {
3850 * $gte: accessLevel
3851 * }
3852 * }
3853 * }
3854 * }
3855 * }
3856 * })
3857 * ```
3858 * Now, since you defined a default scope, every time you do Model.find, the default scope is appended to
3859 * your query. Here's a couple of examples:
3860 * ```js
3861 * Model.findAll() // WHERE username = 'dan'
3862 * Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
3863 * ```
3864 *
3865 * To invoke scope functions you can do:
3866 * ```js
3867 * Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
3868 * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
3869 * ```
3870 *
3871 * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned
3872 * model will clear the previous scope.
3873 */
3874 scope(options?: string | ScopeOptions | AnyWhereOptions | Array<string | ScopeOptions | AnyWhereOptions>): this;
3875
3876 /**
3877 * Search for multiple instances.
3878 *
3879 * __Simple search using AND and =__
3880 * ```js
3881 * Model.findAll({
3882 * where: {
3883 * attr1: 42,
3884 * attr2: 'cake'
3885 * }
3886 * })
3887 * ```
3888 * ```sql
3889 * WHERE attr1 = 42 AND attr2 = 'cake'
3890 *```
3891 *
3892 * __Using greater than, less than etc.__
3893 * ```js
3894 *
3895 * Model.findAll({
3896 * where: {
3897 * attr1: {
3898 * gt: 50
3899 * },
3900 * attr2: {
3901 * lte: 45
3902 * },
3903 * attr3: {
3904 * in: [1,2,3]
3905 * },
3906 * attr4: {
3907 * ne: 5
3908 * }
3909 * }
3910 * })
3911 * ```
3912 * ```sql
3913 * WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
3914 * ```
3915 * Possible options are: `$ne, $in, $not, $notIn, $gte, $gt, $lte, $lt, $like, $ilike/$iLike, $notLike,
3916 * $notILike, '..'/$between, '!..'/$notBetween, '&&'/$overlap, '@>'/$contains, '<@'/$contained`
3917 *
3918 * __Queries using OR__
3919 * ```js
3920 * Model.findAll({
3921 * where: Sequelize.and(
3922 * { name: 'a project' },
3923 * Sequelize.or(
3924 * { id: [1,2,3] },
3925 * { id: { gt: 10 } }
3926 * )
3927 * )
3928 * })
3929 * ```
3930 * ```sql
3931 * WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
3932 * ```
3933 *
3934 * The success listener is called with an array of instances if the query succeeds.
3935 *
3936 * @see {Sequelize#query}
3937 */
3938 findAll<TCustomAttributes>(options?: FindOptions<TAttributes & TCustomAttributes>): Promise<TInstance[]>;
3939 all<TCustomAttributes>(optionz?: FindOptions<TAttributes & TCustomAttributes>): Promise<TInstance[]>;
3940
3941 /**
3942 * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will
3943 * always be called with a single instance.
3944 */
3945 findById<TCustomAttributes>(
3946 identifier?: number | string | Buffer,
3947 options?: Omit<FindOptions<TAttributes & TCustomAttributes>, 'where'>,
3948 ): Promise<TInstance | null>;
3949 findByPrimary<TCustomAttributes>(
3950 identifier?: number | string | Buffer,
3951 options?: Omit<FindOptions<TAttributes & TCustomAttributes>, 'where'>,
3952 ): Promise<TInstance | null>;
3953 findByPk<TCustomAttributes>(
3954 identifier?: number | string | Buffer,
3955 options?: Omit<FindOptions<TAttributes & TCustomAttributes>, 'where'>,
3956 ): Promise<TInstance | null>;
3957
3958 /**
3959 * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single
3960 * instance.
3961 */
3962 findOne<TCustomAttributes>(options?: FindOptions<TAttributes & TCustomAttributes>): Promise<TInstance | null>;
3963 find<TCustomAttributes>(options?: FindOptions<TAttributes & TCustomAttributes>): Promise<TInstance | null>;
3964
3965 /**
3966 * Run an aggregation method on the specified field
3967 *
3968 * @param field The field to aggregate over. Can be a field name or *
3969 * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc.
3970 * @param options Query options. See sequelize.query for full options
3971 * @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in
3972 * which case the complete data result is returned.
3973 */
3974 aggregate(field: string, aggregateFunction: string, options?: AggregateOptions): Promise<Object>;
3975
3976 /**
3977 * Count the number of records matching the provided where clause.
3978 *
3979 * If you provide an `include` option, the number of matching associations will be counted instead.
3980 */
3981 count(options?: CountOptions): Promise<number>;
3982
3983 /**
3984 * Find all the rows matching your query, within a specified offset / limit, and get the total number of
3985 * rows matching your query. This is very usefull for paging
3986 *
3987 * ```js
3988 * Model.findAndCountAll({
3989 * where: ...,
3990 * limit: 12,
3991 * offset: 12
3992 * }).then(function (result) {
3993 * ...
3994 * })
3995 * ```
3996 * In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return
3997 * the
3998 * total number of rows that matched your query.
3999 *
4000 * When you add includes, only those which are required (either because they have a where clause, or
4001 * because
4002 * `required` is explicitly set to true on the include) will be added to the count part.
4003 *
4004 * Suppose you want to find all users who have a profile attached:
4005 * ```js
4006 * User.findAndCountAll({
4007 * include: [
4008 * { model: Profile, required: true}
4009 * ],
4010 * limit 3
4011 * });
4012 * ```
4013 * Because the include for `Profile` has `required` set it will result in an inner join, and only the users
4014 * who have a profile will be counted. If we remove `required` from the include, both users with and
4015 * without
4016 * profiles will be counted
4017 */
4018 findAndCount<TCustomAttributes>(options?: FindOptions<TAttributes & TCustomAttributes>): Promise<{ rows: TInstance[], count: number }>;
4019 findAndCountAll<TCustomAttributes>(options?: FindOptions<TAttributes & TCustomAttributes>): Promise<{ rows: TInstance[], count: number }>;
4020
4021 /**
4022 * Find the maximum value of field
4023 */
4024 max(field: string, options?: AggregateOptions): Promise<any>;
4025
4026 /**
4027 * Find the minimum value of field
4028 */
4029 min(field: string, options?: AggregateOptions): Promise<any>;
4030
4031 /**
4032 * Find the sum of field
4033 */
4034 sum(field: string, options?: AggregateOptions): Promise<number>;
4035
4036 /**
4037 * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
4038 */
4039 build(record?: TAttributes, options?: BuildOptions): TInstance;
4040
4041 /**
4042 * Undocumented bulkBuild
4043 */
4044 bulkBuild(records: TAttributes[], options?: BuildOptions): TInstance[];
4045
4046 /**
4047 * Builds a new model instance and calls save on it.
4048 */
4049 create(values?: TCreationAttributes, options?: CreateOptions): Promise<TInstance>;
4050
4051 /**
4052 * Find a row that matches the query, or build (but don't save) the row if none is found.
4053 * The successfull result of the promise will be (instance, initialized) - Make sure to use .spread()
4054 */
4055 findOrInitialize(options: FindOrInitializeOptions<TAttributes>): Promise<[TInstance, boolean]>;
4056 findOrBuild(options: FindOrInitializeOptions<TAttributes>): Promise<[TInstance, boolean]>;
4057
4058 /**
4059 * Find a row that matches the query, or build and save the row if none is found
4060 * The successful result of the promise will be (instance, created) - Make sure to use .spread()
4061 *
4062 * If no transaction is passed in the `options` object, a new transaction will be created internally, to
4063 * prevent the race condition where a matching row is created by another connection after the find but
4064 * before the insert call. However, it is not always possible to handle this case in SQLite, specifically
4065 * if one transaction inserts and another tries to select before the first one has comitted. In this case,
4066 * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint
4067 * will be created instead, and any unique constraint violation will be handled internally.
4068 */
4069 findOrCreate(options: FindOrInitializeOptions<TAttributes>): Promise<[TInstance, boolean]>;
4070
4071 /**
4072 * A more performant findOrCreate that will not work under a transaction (at least not in postgres)
4073 * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
4074 */
4075 findCreateFind<TCustomAttributes>(options: FindCreateFindOptions<TAttributes & TCustomAttributes>): Promise<[TInstance, boolean]>;
4076
4077 /**
4078 * Insert or update a single row. An update will be executed if a row which matches the supplied values on
4079 * either the primary key or a unique key is found. Note that the unique index must be defined in your
4080 * sequelize model and not just in the table. Otherwise you may experience a unique constraint violation,
4081 * because sequelize fails to identify the row that should be updated.
4082 *
4083 * **Implementation details:**
4084 *
4085 * * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values`
4086 * * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN
4087 * unique_constraint UPDATE
4088 * * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed
4089 * regardless
4090 * of whether the row already existed or not
4091 *
4092 * **Note** that SQLite returns undefined for created, no matter if the row was created or updated. This is
4093 * because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know
4094 * whether the row was inserted or not.
4095 */
4096 upsert(values: TAttributes, options?: UpsertOptions & { returning?: false | undefined }): Promise<boolean>;
4097 upsert(values: TAttributes, options?: UpsertOptions & { returning: true }): Promise<[TInstance, boolean]>;
4098 insertOrUpdate(values: TAttributes, options?: UpsertOptions & { returning: false | undefined }): Promise<boolean>;
4099 insertOrUpdate(values: TAttributes, options?: UpsertOptions & { returning: true }): Promise<[TInstance, boolean]>;
4100
4101 /**
4102 * Create and insert multiple instances in bulk.
4103 *
4104 * The success handler is passed an array of instances, but please notice that these may not completely
4105 * represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to
4106 * obtain
4107 * back automatically generated IDs and other default values in a way that can be mapped to multiple
4108 * records. To obtain Instances for the newly created values, you will need to query for them again.
4109 *
4110 * @param records List of objects (key/value pairs) to create instances from
4111 */
4112 bulkCreate(records: TCreationAttributes[], options?: BulkCreateOptions): Promise<TInstance[]>;
4113
4114 /**
4115 * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
4116 */
4117 truncate(options?: TruncateOptions): Promise<void>;
4118
4119 /**
4120 * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
4121 *
4122 * @return Promise<number> The number of destroyed rows
4123 */
4124 destroy(options?: DestroyOptions): Promise<number>;
4125
4126 /**
4127 * Restore multiple instances if `paranoid` is enabled.
4128 */
4129 restore(options?: RestoreOptions): Promise<void>;
4130
4131 /**
4132 * Update multiple instances that match the where options. The promise returns an array with one or two
4133 * elements. The first element is always the number of affected rows, while the second element is the actual
4134 * affected rows (only supported in postgres with `options.returning` true.)
4135 */
4136 update(values: Partial<TAttributes>, options?: UpdateOptions): Promise<[number, TInstance[]]>;
4137
4138 /**
4139 * Run a describe query on the table. The result will be return to the listener as a hash of attributes and
4140 * their types.
4141 */
4142 describe(): Promise<Object>;
4143
4144 /**
4145 * Unscope the model
4146 */
4147 unscoped(): this;
4148
4149 /**
4150 * Set associations with other models
4151 *
4152 * Not part of the sequelize API, used as convention to associate models after creation. e.g.:
4153 * ```js
4154 * Object.keys(models).forEach(modelName => {
4155 * if (models[modelName].associate) {
4156 * models[modelName].associate(models);
4157 * }
4158 * });
4159 * ```
4160 *
4161 * @param models
4162 */
4163 associate?(models: Models): void;
4164
4165 }
4166
4167 //
4168 // Query Interface
4169 // ~~~~~~~~~~~~~~~~~
4170 //
4171 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/query-interface.js
4172 //
4173
4174 /**
4175 * Most of the methods accept options and use only the logger property of the options. That's why the most used
4176 * interface type for options in a method is separated here as another interface.
4177 */
4178 interface QueryInterfaceOptions {
4179
4180 /**
4181 * A function that gets executed while running the query to log the sql.
4182 */
4183 logging?: boolean | Function;
4184
4185 /**
4186 * An optional transaction to perform this query in
4187 */
4188 transaction?: Transaction;
4189
4190 }
4191
4192 interface AddUniqueConstraintOptions {
4193 type: 'unique';
4194 name?: string;
4195 }
4196
4197 interface AddDefaultConstraintOptions {
4198 type: 'default';
4199 name?: string;
4200 defaultValue?: any;
4201 }
4202
4203 interface AddCheckConstraintOptions {
4204 type: 'check';
4205 name?: string;
4206 where?: AnyWhereOptions;
4207 }
4208
4209 interface AddPrimaryKeyConstraintOptions {
4210 type: 'primary key';
4211 name?: string;
4212 }
4213
4214 interface AddForeignKeyConstraintOptions {
4215 type: 'foreign key';
4216 name?: string;
4217 references?: {
4218 table: string;
4219 field: string;
4220 };
4221 onDelete: string;
4222 onUpdate: string;
4223 }
4224
4225 type AddConstraintOptions = AddUniqueConstraintOptions | AddDefaultConstraintOptions | AddCheckConstraintOptions | AddPrimaryKeyConstraintOptions | AddForeignKeyConstraintOptions;
4226
4227 /**
4228 * The interface that Sequelize uses to talk to all databases.
4229 *
4230 * This interface is available through sequelize.QueryInterface. It should not be commonly used, but it's
4231 * referenced anyway, so it can be used.
4232 */
4233 interface QueryInterface {
4234
4235 /**
4236 * Returns the dialect-specific sql generator.
4237 *
4238 * We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately.
4239 */
4240 QueryGenerator: any;
4241
4242 /**
4243 * Returns the current sequelize instance.
4244 */
4245 sequelize: Sequelize;
4246
4247 /**
4248 * Queries the schema (table list).
4249 *
4250 * @param schema The schema to query. Applies only to Postgres.
4251 */
4252 createSchema(schema?: string, options?: QueryInterfaceOptions): Promise<void>;
4253
4254 /**
4255 * Drops the specified schema (table).
4256 *
4257 * @param schema The schema to query. Applies only to Postgres.
4258 */
4259 dropSchema(schema?: string, options?: QueryInterfaceOptions): Promise<void>;
4260
4261 /**
4262 * Drops all tables.
4263 */
4264 dropAllSchemas(options?: QueryInterfaceOptions): Promise<void>;
4265
4266 /**
4267 * Queries all table names in the database.
4268 *
4269 * @param options
4270 */
4271 showAllSchemas(options?: QueryOptions): Promise<Object>;
4272
4273 /**
4274 * Return database version
4275 */
4276 databaseVersion(options?: QueryInterfaceOptions): Promise<string>;
4277
4278 /**
4279 * Creates a table with specified attributes.
4280 *
4281 * @param tableName Name of table to create
4282 * @param attributes Hash of attributes, key is attribute name, value is data type
4283 * @param options Query options.
4284 */
4285 createTable(tableName: string | { schema?: string, tableName?: string }, attributes: DefineAttributes,
4286 options?: QueryOptions): Promise<void>;
4287
4288 /**
4289 * Drops the specified table.
4290 *
4291 * @param tableName Table name.
4292 * @param options Query options, particularly "force".
4293 */
4294 dropTable(tableName: string, options?: QueryOptions): Promise<void>;
4295
4296 /**
4297 * Drops all tables.
4298 *
4299 * @param options
4300 */
4301 dropAllTables(options?: QueryOptions): Promise<void>;
4302
4303 /**
4304 * Drops all defined enums
4305 *
4306 * @param options
4307 */
4308 dropAllEnums(options?: QueryOptions): Promise<void>;
4309
4310 /**
4311 * Renames a table
4312 */
4313 renameTable(before: string, after: string, options?: QueryInterfaceOptions): Promise<void>;
4314
4315 /**
4316 * Returns all tables
4317 */
4318 showAllTables(options?: QueryOptions): Promise<string[]>;
4319
4320 /**
4321 * Describe a table
4322 */
4323 describeTable(tableName: string | { schema?: string, tableName?: string },
4324 options?: string | { schema?: string, schemaDelimeter?: string, logging?: boolean | Function }): Promise<Object>;
4325
4326 /**
4327 * Adds a new column to a table
4328 */
4329 addColumn(tableName: string | { tableName?: string, schema?: string }, key: string, attribute: DefineAttributeColumnOptions | DataTypeAbstract,
4330 options?: QueryInterfaceOptions): Promise<void>;
4331
4332 /**
4333 * Removes a column from a table
4334 */
4335 removeColumn(tableName: string | { tableName?: string, schema?: string }, attribute: string,
4336 options?: QueryInterfaceOptions): Promise<void>;
4337
4338 /**
4339 * Changes a column
4340 */
4341 changeColumn(tableName: string | { schema?: string, tableName?: string }, attributeName: string,
4342 dataTypeOrOptions?: string | DataTypeAbstract | DefineAttributeColumnOptions,
4343 options?: QueryInterfaceOptions): Promise<void>;
4344
4345 /**
4346 * Renames a column
4347 */
4348 renameColumn(tableName: string | { schema?: string, tableName?: string }, attrNameBefore: string,
4349 attrNameAfter: string,
4350 options?: QueryInterfaceOptions): Promise<void>;
4351
4352 /**
4353 * Adds a new index to a table
4354 */
4355 addIndex(tableName: string | Object, options: DefineIndexOptions & { fields: string[] }, rawTablename?: string): Promise<void>;
4356 addIndex(tableName: string | Object, attributes: string[], options?: DefineIndexOptions,
4357 rawTablename?: string): Promise<void>;
4358
4359 /**
4360 * Shows the index of a table
4361 */
4362 showIndex(tableName: string | Object, options?: QueryOptions): Promise<Object>;
4363
4364 /**
4365 * Put a name to an index
4366 */
4367 nameIndexes(indexes: string[], rawTablename: string): Promise<void>;
4368
4369 /**
4370 * Returns all foreign key constraints of each table in list
4371 */
4372 getForeignKeysForTables(tableNames: string[], options?: QueryInterfaceOptions): Promise<Object>;
4373
4374 /**
4375 * Removes an index of a table
4376 */
4377 removeIndex(tableName: string, indexNameOrAttributes: string[] | string,
4378 options?: QueryInterfaceOptions): Promise<void>;
4379
4380 /**
4381 * Adds constraints to a table
4382 */
4383 addConstraint(tableName: string, attributes: string[], options?: AddConstraintOptions | QueryInterfaceOptions): Promise<void>;
4384
4385 /**
4386 * Removes constraints from a table
4387 */
4388 removeConstraint(tableName: string, constraintName: string, options?: QueryInterfaceOptions): Promise<void>;
4389
4390 /**
4391 * Inserts a new record
4392 */
4393 insert(instance: Instance<any>, tableName: string, values: Object,
4394 options?: QueryOptions): Promise<Object>;
4395
4396 /**
4397 * Inserts or Updates a record in the database
4398 */
4399 upsert(tableName: string, values: Object, updateValues: Object, model: Model<any, any>,
4400 options?: QueryOptions): Promise<Object>;
4401
4402 /**
4403 * Inserts multiple records at once
4404 */
4405 bulkInsert(tableName: string | { tableName: string, schema: string }, records: Object[], options?: QueryOptions,
4406 attributes?: string[] | string): Promise<Object>;
4407
4408 /**
4409 * Updates a row
4410 */
4411 update(instance: Instance<any>, tableName: string, values: Object, identifier: Object,
4412 options?: QueryOptions): Promise<Object>;
4413
4414 /**
4415 * Updates multiple rows at once
4416 */
4417 bulkUpdate(tableName: string, values: Object, identifier: Object, options?: QueryOptions,
4418 attributes?: string[] | string): Promise<Object>;
4419
4420 /**
4421 * Deletes a row
4422 */
4423 "delete"(instance: Instance<any>, tableName: string, identifier: Object,
4424 options?: QueryOptions): Promise<Object>;
4425
4426 /**
4427 * Deletes multiple rows at once
4428 */
4429 bulkDelete(tableName: string, identifier: Object, options?: QueryOptions,
4430 model?: Model<any, any>): Promise<Object>;
4431
4432 /**
4433 * Returns selected rows
4434 */
4435 select(model: Model<any, any>, tableName: string, options?: QueryOptions): Promise<Object[]>;
4436
4437 /**
4438 * Increments a row value
4439 */
4440 increment(instance: Instance<any>, tableName: string, values: Object, identifier: Object,
4441 options?: QueryOptions): Promise<Object>;
4442
4443 /**
4444 * Selects raw without parsing the string into an object
4445 */
4446 rawSelect(tableName: string, options: QueryOptions, attributeSelector: string | string[],
4447 model?: Model<any, any>): Promise<string[]>;
4448
4449 /**
4450 * Postgres only. Creates a trigger on specified table to call the specified function with supplied
4451 * parameters.
4452 */
4453 createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: any[],
4454 functionName: string, functionParams: any[], optionsArray: string[],
4455 options?: QueryInterfaceOptions): Promise<void>;
4456
4457 /**
4458 * Postgres only. Drops the specified trigger.
4459 */
4460 dropTrigger(tableName: string, triggerName: string, options?: QueryInterfaceOptions): Promise<void>;
4461
4462 /**
4463 * Postgres only. Renames a trigger
4464 */
4465 renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string,
4466 options?: QueryInterfaceOptions): Promise<void>;
4467
4468 /**
4469 * Postgres only. Create a function
4470 */
4471 createFunction(functionName: string, params: any[], returnType: string, language: string,
4472 body: string, options?: QueryOptions): Promise<void>;
4473
4474 /**
4475 * Postgres only. Drops a function
4476 */
4477 dropFunction(functionName: string, params: any[],
4478 options?: QueryInterfaceOptions): Promise<void>;
4479
4480 /**
4481 * Postgres only. Rename a function
4482 */
4483 renameFunction(oldFunctionName: string, params: any[], newFunctionName: string,
4484 options?: QueryInterfaceOptions): Promise<void>;
4485
4486 /**
4487 * Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted
4488 * even if the `quoteIdentifiers` option is false.
4489 */
4490 quoteIdentifier(identifier: string, force: boolean): string;
4491
4492 /**
4493 * Escape a table name
4494 */
4495 quoteTable(identifier: string): string;
4496
4497 /**
4498 * Split an identifier into .-separated tokens and quote each part. If force is true, the identifier will be
4499 * quoted even if the `quoteIdentifiers` option is false.
4500 */
4501 quoteIdentifiers(identifiers: string, force: boolean): string;
4502
4503 /**
4504 * Escape a value (e.g. a string, number or date)
4505 */
4506 escape(value?: string | number | Date): string;
4507
4508 /**
4509 * Set option for autocommit of a transaction
4510 */
4511 setAutocommit(transaction: Transaction, value: boolean, options?: QueryOptions): Promise<void>;
4512
4513 /**
4514 * Set the isolation level of a transaction
4515 */
4516 setIsolationLevel(transaction: Transaction, value: string, options?: QueryOptions): Promise<void>;
4517
4518 /**
4519 * Begin a new transaction
4520 */
4521 startTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
4522
4523 /**
4524 * Defer constraints
4525 */
4526 deferConstraints(transaction: Transaction, options?: QueryOptions): Promise<void>;
4527
4528 /**
4529 * Commit an already started transaction
4530 */
4531 commitTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
4532
4533 /**
4534 * Rollback ( revert ) a transaction that has'nt been commited
4535 */
4536 rollbackTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
4537
4538 }
4539
4540 //
4541 // Query Types
4542 // ~~~~~~~~~~~~~
4543 //
4544 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/query-types.js
4545 //
4546
4547 interface QueryTypes {
4548 SELECT: string; // 'SELECT'
4549 INSERT: string; // 'INSERT'
4550 UPDATE: string; // 'UPDATE'
4551 BULKUPDATE: string; // 'BULKUPDATE'
4552 BULKDELETE: string; // 'BULKDELETE'
4553 DELETE: string; // 'DELETE'
4554 UPSERT: string; // 'UPSERT'
4555 VERSION: string; // 'VERSION'
4556 SHOWTABLES: string; // 'SHOWTABLES'
4557 SHOWINDEXES: string; // 'SHOWINDEXES'
4558 DESCRIBE: string; // 'DESCRIBE'
4559 RAW: string; // 'RAW'
4560 FOREIGNKEYS: string; // 'FOREIGNKEYS'
4561 }
4562
4563 //
4564 // Sequelize
4565 // ~~~~~~~~~~~
4566 //
4567 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/sequelize.js
4568 //
4569
4570 /**
4571 * General column options
4572 *
4573 * @see Define
4574 * @see AssociationForeignKeyOptions
4575 */
4576 interface ColumnOptions {
4577
4578 /**
4579 * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an
4580 * instance is saved.
4581 */
4582 allowNull?: boolean;
4583
4584 /**
4585 * If set, sequelize will map the attribute name to a different name in the database
4586 */
4587 field?: string;
4588
4589 /**
4590 * A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
4591 */
4592 defaultValue?: any;
4593
4594 }
4595
4596 /**
4597 * References options for the column's attributes
4598 *
4599 * @see AttributeColumnOptions
4600 */
4601 interface DefineAttributeColumnReferencesOptions {
4602
4603 /**
4604 * If this column references another table, provide it here as a Model, or a string
4605 */
4606 model: string | Model<any, any>;
4607
4608 /**
4609 * The column of the foreign table that this column references
4610 */
4611 key?: string;
4612
4613 /**
4614 * When to check for the foreign key constraing
4615 *
4616 * PostgreSQL only
4617 */
4618 deferrable?: DeferrableInitiallyDeferred | DeferrableInitiallyImmediate | DeferrableNot | DeferrableSetDeferred | DeferrableSetImmediate;
4619
4620 }
4621
4622 /**
4623 * Column options for the model schema attributes
4624 *
4625 * @see Attributes
4626 */
4627 interface DefineAttributeColumnOptions extends ColumnOptions {
4628
4629 /**
4630 * A string or a data type
4631 */
4632 type: string | DataTypeAbstract;
4633
4634 /**
4635 * If true, the column will get a unique constraint. If a string is provided, the column will be part of a
4636 * composite unique index. If multiple columns have the same string, they will be part of the same unique
4637 * index
4638 */
4639 unique?: boolean | string | { name: string, msg: string };
4640
4641 /**
4642 * Primary key flag
4643 */
4644 primaryKey?: boolean;
4645
4646 /**
4647 * Is this field an auto increment field
4648 */
4649 autoIncrement?: boolean;
4650
4651 /**
4652 * Comment for the database
4653 */
4654 comment?: string;
4655
4656 /**
4657 * An object with reference configurations
4658 */
4659 references?: DefineAttributeColumnReferencesOptions;
4660
4661 /**
4662 * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
4663 * NO ACTION
4664 */
4665 onUpdate?: string;
4666
4667 /**
4668 * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
4669 * NO ACTION
4670 */
4671 onDelete?: string;
4672
4673 /**
4674 * Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying
4675 * values.
4676 */
4677 get?: () => any;
4678
4679 /**
4680 * Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the
4681 * underlying values.
4682 */
4683 set?: (val: any) => void;
4684
4685 /**
4686 * An object of validations to execute for this column every time the model is saved. Can be either the
4687 * name of a validation provided by validator.js, a validation function provided by extending validator.js
4688 * (see the
4689 * `DAOValidator` property for more details), or a custom validation function. Custom validation functions
4690 * are called with the value of the field, and can possibly take a second callback argument, to signal that
4691 * they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it
4692 * it is async, the callback should be called with the error text.
4693 */
4694 validate?: DefineValidateOptions;
4695
4696 /**
4697 * Usage in object notation
4698 *
4699 * ```js
4700 * sequelize.define('model', {
4701 * states: {
4702 * type: Sequelize.ENUM,
4703 * values: ['active', 'pending', 'deleted']
4704 * }
4705 * })
4706 * ```
4707 */
4708 values?: string[];
4709
4710 }
4711
4712 /**
4713 * Interface for Attributes provided for a column
4714 *
4715 * @see Sequelize.define
4716 */
4717 interface DefineAttributes {
4718
4719 /**
4720 * The description of a database column
4721 */
4722 [name: string]: string | DataTypeAbstract | DefineAttributeColumnOptions;
4723
4724 }
4725
4726 /**
4727 * Interface for Attributes provided for a column
4728 *
4729 * @see Sequelize.define
4730 */
4731 type DefineModelAttributes<T> = {
4732
4733 /**
4734 * The description of a database column for model
4735 */
4736 [P in keyof T]: string | DataTypeAbstract | DefineAttributeColumnOptions;
4737
4738 }
4739
4740 /**
4741 * Interface for query options
4742 *
4743 * @see Options
4744 */
4745 interface QueryOptions extends SearchPathOptions, ReturningOptions {
4746
4747 /**
4748 * If true, sequelize will not try to format the results of the query, or build an instance of a model from
4749 * the result
4750 */
4751 raw?: boolean;
4752
4753
4754 /**
4755 * The type of query you are executing. The query type affects how results are formatted before they are
4756 * passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
4757 */
4758 type?: string;
4759
4760 /**
4761 * If true, transforms objects with `.` separated property names into nested objects using
4762 * [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes
4763 * { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`,
4764 * unless otherwise specified
4765 *
4766 * Defaults to false
4767 */
4768 nest?: boolean;
4769
4770 /**
4771 * Sets the query type to `SELECT` and return a single row
4772 */
4773 plain?: boolean;
4774
4775 /**
4776 * Either an object of named parameter replacements in the format `:param` or an array of unnamed
4777 * replacements to replace `?` in your SQL.
4778 */
4779 replacements?: Object | string[];
4780
4781 /**
4782 * Either an object of named bind parameter in the format `$param` or an array of unnamed
4783 * bind parameter to replace `$1`, `$2`, ... in your SQL.
4784 */
4785 bind?: Object | string[];
4786
4787 /**
4788 * Force the query to use the write pool, regardless of the query type.
4789 *
4790 * Defaults to false
4791 */
4792 useMaster?: boolean;
4793
4794 /**
4795 * A function that gets executed while running the query to log the sql.
4796 */
4797 logging?: boolean | Function;
4798
4799 /**
4800 * A sequelize instance used to build the return instance
4801 */
4802 instance?: Instance<any>;
4803
4804 /**
4805 * A sequelize model used to build the returned model instances (used to be called callee)
4806 */
4807 model?: Model<any, any>;
4808
4809 /**
4810 * Set of flags that control when a query is automatically retried.
4811 */
4812 retry?: RetryOptions;
4813
4814 /**
4815 * If false do not prepend the query with the search_path (Postgres only)
4816 */
4817 supportsSearchPath?: boolean;
4818
4819 /**
4820 * Map returned fields to model's fields if `options.model` or `options.instance` is present.
4821 * Mapping will occur before building the model instance.
4822 */
4823 mapToModel?: boolean;
4824
4825 // TODO: force, cascade
4826 fieldMap?: { [key: string]: string; }
4827 }
4828
4829 /**
4830 * Model validations, allow you to specify format/content/inheritance validations for each attribute of the
4831 * model.
4832 *
4833 * Validations are automatically run on create, update and save. You can also call validate() to manually
4834 * validate an instance.
4835 *
4836 * The validations are implemented by validator.js.
4837 */
4838 interface DefineValidateOptions {
4839
4840 /**
4841 * is: ["^[a-z]+$",'i'] // will only allow letters
4842 * is: /^[a-z]+$/i // same as the previous example using real RegExp
4843 */
4844 is?: string | Array<string | RegExp> | RegExp | { msg: string, args: string | Array<string | RegExp> | RegExp };
4845
4846 /**
4847 * not: ["[a-z]",'i'] // will not allow letters
4848 */
4849 not?: string | Array<string | RegExp> | RegExp | { msg: string, args: string | Array<string | RegExp> | RegExp };
4850
4851 /**
4852 * checks for email format (foo@bar.com)
4853 */
4854 isEmail?: boolean | { msg: string };
4855
4856 /**
4857 * checks for url format (http://foo.com)
4858 */
4859 isUrl?: boolean | { msg: string };
4860
4861 /**
4862 * checks for IPv4 (129.89.23.1) or IPv6 format
4863 */
4864 isIP?: boolean | { msg: string };
4865
4866 /**
4867 * checks for IPv4 (129.89.23.1)
4868 */
4869 isIPv4?: boolean | { msg: string };
4870
4871 /**
4872 * checks for IPv6 format
4873 */
4874 isIPv6?: boolean | { msg: string };
4875
4876 /**
4877 * will only allow letters
4878 */
4879 isAlpha?: boolean | { msg: string };
4880
4881 /**
4882 * will only allow alphanumeric characters, so "_abc" will fail
4883 */
4884 isAlphanumeric?: boolean | { msg: string };
4885
4886 /**
4887 * will only allow numbers
4888 */
4889 isNumeric?: boolean | { msg: string };
4890
4891 /**
4892 * checks for valid integers
4893 */
4894 isInt?: boolean | { msg: string };
4895
4896 /**
4897 * checks for valid floating point numbers
4898 */
4899 isFloat?: boolean | { msg: string };
4900
4901 /**
4902 * checks for any numbers
4903 */
4904 isDecimal?: boolean | { msg: string };
4905
4906 /**
4907 * checks for lowercase
4908 */
4909 isLowercase?: boolean | { msg: string };
4910
4911 /**
4912 * checks for uppercase
4913 */
4914 isUppercase?: boolean | { msg: string };
4915
4916 /**
4917 * won't allow null
4918 */
4919 notNull?: boolean | { msg: string };
4920
4921 /**
4922 * only allows null
4923 */
4924 isNull?: boolean | { msg: string };
4925
4926 /**
4927 * don't allow empty strings
4928 */
4929 notEmpty?: boolean | { msg: string };
4930
4931 /**
4932 * only allow a specific value
4933 */
4934 equals?: string | { msg: string };
4935
4936 /**
4937 * force specific substrings
4938 */
4939 contains?: string | { msg: string };
4940
4941 /**
4942 * check the value is not one of these
4943 */
4944 notIn?: string[][] | { msg: string, args: string[][] };
4945
4946 /**
4947 * check the value is one of these
4948 */
4949 isIn?: string[][] | { msg: string, args: string[][] };
4950
4951 /**
4952 * don't allow specific substrings
4953 */
4954 notContains?: string[] | string | { msg: string, args: string[] | string };
4955
4956 /**
4957 * only allow values with length between 2 and 10
4958 */
4959 len?: [number, number] | { msg: string, args: [number, number] };
4960
4961 /**
4962 * only allow uuids
4963 */
4964 isUUID?: 3|4|5|"3"|"4"|"5"|"all" | { msg: string, args: number };
4965
4966 /**
4967 * only allow date strings
4968 */
4969 isDate?: boolean | { msg: string, args: boolean };
4970
4971 /**
4972 * only allow date strings after a specific date
4973 */
4974 isAfter?: string | { msg: string, args: string };
4975
4976 /**
4977 * only allow date strings before a specific date
4978 */
4979 isBefore?: string | { msg: string, args: string };
4980
4981 /**
4982 * only allow values
4983 */
4984 max?: number | { msg: string, args: number };
4985
4986 /**
4987 * only allow values >= 23
4988 */
4989 min?: number | { msg: string, args: number };
4990
4991 /**
4992 * only allow arrays
4993 */
4994 isArray?: boolean | { msg: string, args: boolean };
4995
4996 /**
4997 * check for valid credit card numbers
4998 */
4999 isCreditCard?: boolean | { msg: string, args: boolean };
5000
5001 /**
5002 * custom validations are also possible
5003 *
5004 * Implementation notes :
5005 *
5006 * We can't enforce any other method to be a function, so :
5007 *
5008 * ```typescript
5009 * [name: string] : ( value : any ) => boolean;
5010 * ```
5011 *
5012 * doesn't work in combination with the properties above
5013 *
5014 * @see https://github.com/Microsoft/TypeScript/issues/1889
5015 */
5016 [name: string]: any;
5017
5018 }
5019
5020 type IndexType = 'UNIQUE' | 'FULLTEXT' | 'SPATIAL';
5021
5022 interface DefineIndexOptions {
5023 /**
5024 * The index type
5025 */
5026 indicesType?: IndexType;
5027
5028 /**
5029 * The index type
5030 */
5031 type?: IndexType;
5032
5033 /**
5034 * The name of the index. Default is __
5035 */
5036 indexName?: string;
5037
5038 /**
5039 * Create a unique index
5040 */
5041 unique?: boolean;
5042
5043 /**
5044 * The name of the index. Default is Default is <table>_<attr1>_<attr2>
5045 */
5046 name?: string;
5047
5048 /**
5049 * For FULLTEXT columns set your parser
5050 */
5051 parser?: string;
5052
5053 /**
5054 * Set a type for the index, e.g. BTREE. See the documentation of the used dialect
5055 */
5056 indexType?: string;
5057
5058 /**
5059 * A function that receives the sql query, e.g. console.log
5060 */
5061 logging?: Function;
5062
5063 /**
5064 * Create an unique index
5065 */
5066 using?: string;
5067
5068 /**
5069 * Index operator
5070 */
5071 operator?: string;
5072
5073 /**
5074 * A hash of attributes to limit your index(Filtered Indexes - MSSQL & PostgreSQL only)
5075 */
5076 where?: AnyWhereOptions;
5077
5078 /**
5079 * Pass CONCURRENT so other operations run while the index is created - PostgresSQL only. Default is false
5080 */
5081 concurrently?: boolean;
5082 }
5083
5084 /**
5085 * Interface for indexes property in DefineOptions
5086 *
5087 * @see DefineOptions
5088 */
5089 interface DefineIndexesOptions {
5090
5091 /**
5092 * The name of the index. Defaults to model name + _ + fields concatenated
5093 */
5094 name?: string;
5095
5096 /**
5097 * Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL`
5098 */
5099 type?: IndexType;
5100
5101 /**
5102 * The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and
5103 * postgres, and postgres additionally supports GIST and GIN.
5104 */
5105 method?: string;
5106
5107 /**
5108 * Should the index by unique? Can also be triggered by setting type to `UNIQUE`
5109 *
5110 * Defaults to false
5111 */
5112 unique?: boolean;
5113
5114 /**
5115 * PostgreSQL will build the index without taking any write locks. Postgres only
5116 *
5117 * Defaults to false
5118 */
5119 concurrently?: boolean;
5120
5121 /**
5122 * An array of the fields to index. Each field can either be a string containing the name of the field,
5123 * a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute`
5124 * (field name), `length` (create a prefix index of length chars), `order` (the direction the column
5125 * should be sorted in), `collate` (the collation (sort order) for the column)
5126 */
5127 fields?: Array<string | fn | { attribute: string, length: number, order: string, collate: string }>;
5128
5129 /**
5130 * Method the index should use, for example 'gin' index.
5131 */
5132 using?: string;
5133
5134 /**
5135 * Operator that should be used by gin index, see Built-in GIN Operator Classes
5136 */
5137 operator?: string;
5138
5139 /**
5140 * Condition for partioal index
5141 */
5142 where?: AnyWhereOptions;
5143
5144 }
5145
5146 /**
5147 * Interface for name property in DefineOptions
5148 *
5149 * @see DefineOptions
5150 */
5151 interface DefineNameOptions {
5152
5153 /**
5154 * Singular model name
5155 */
5156 singular?: string;
5157
5158 /**
5159 * Plural model name
5160 */
5161 plural?: string;
5162
5163 }
5164
5165 /**
5166 * Interface for getterMethods in DefineOptions
5167 *
5168 * @see DefineOptions
5169 */
5170 interface DefineGetterMethodsOptions {
5171 [name: string]: () => any;
5172 }
5173
5174 /**
5175 * Interface for setterMethods in DefineOptions
5176 *
5177 * @see DefineOptions
5178 */
5179 interface DefineSetterMethodsOptions {
5180 [name: string]: (val: any) => void;
5181 }
5182
5183 /**
5184 * Interface for Define Scope Options
5185 *
5186 * @see DefineOptions
5187 */
5188 interface DefineScopeOptions {
5189
5190 /**
5191 * Name of the scope and it's query
5192 */
5193 [scopeName: string]: AnyFindOptions | Function;
5194
5195 }
5196
5197 /**
5198 * Options for model definition
5199 *
5200 * @see Sequelize.define
5201 */
5202 interface DefineOptions<TInstance> {
5203
5204 /**
5205 * Define the default search scope to use for this model. Scopes have the same form as the options passed to
5206 * find / findAll.
5207 */
5208 defaultScope?: AnyFindOptions;
5209
5210 /**
5211 * More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about
5212 * how scopes are defined, and what you can do with them
5213 */
5214 scopes?: DefineScopeOptions;
5215
5216 /**
5217 * Don't persits null values. This means that all columns with null values will not be saved.
5218 */
5219 omitNull?: boolean;
5220
5221 /**
5222 * Adds createdAt and updatedAt timestamps to the model. Default true.
5223 */
5224 timestamps?: boolean;
5225
5226 /**
5227 * Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs
5228 * timestamps=true to work. Default false.
5229 */
5230 paranoid?: boolean;
5231
5232 /**
5233 * Converts all camelCased columns to underscored if true. Default false.
5234 */
5235 underscored?: boolean;
5236
5237 /**
5238 * Converts camelCased model names to underscored tablenames if true. Default false.
5239 */
5240 underscoredAll?: boolean;
5241
5242 /**
5243 * Indicates if the model's table has a trigger associated with it. Default false.
5244 */
5245 hasTrigger?: boolean;
5246
5247 /**
5248 * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name.
5249 * Otherwise, the dao name will be pluralized. Default false.
5250 */
5251 freezeTableName?: boolean;
5252
5253 /**
5254 * An object with two attributes, `singular` and `plural`, which are used when this model is associated to
5255 * others.
5256 */
5257 name?: DefineNameOptions;
5258
5259 /**
5260 * Indexes for the provided database table
5261 */
5262 indexes?: DefineIndexesOptions[];
5263
5264 /**
5265 * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps
5266 * must be true. Not affected by underscored setting.
5267 */
5268 createdAt?: string | boolean;
5269
5270 /**
5271 * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps
5272 * must be true. Not affected by underscored setting.
5273 */
5274 deletedAt?: string | boolean;
5275
5276 /**
5277 * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps
5278 * must be true. Not affected by underscored setting.
5279 */
5280 updatedAt?: string | boolean;
5281
5282 /**
5283 * Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name
5284 * verbatim
5285 */
5286 tableName?: string;
5287
5288 /**
5289 * Provide getter functions that work like those defined per column. If you provide a getter method with
5290 * the
5291 * same name as a column, it will be used to access the value of that column. If you provide a name that
5292 * does not match a column, this function will act as a virtual getter, that can fetch multiple other
5293 * values
5294 */
5295 getterMethods?: DefineGetterMethodsOptions;
5296
5297 /**
5298 * Provide setter functions that work like those defined per column. If you provide a setter method with
5299 * the
5300 * same name as a column, it will be used to update the value of that column. If you provide a name that
5301 * does not match a column, this function will act as a virtual setter, that can act on and set other
5302 * values, but will not be persisted
5303 */
5304 setterMethods?: DefineSetterMethodsOptions;
5305
5306 /**
5307 * Provide functions that are added to each instance (DAO). If you override methods provided by sequelize,
5308 * you can access the original method using `this.constructor.super_.prototype`, e.g.
5309 * `this.constructor.super_.prototype.toJSON.apply(this, arguments)`
5310 */
5311 instanceMethods?: Object;
5312
5313 /**
5314 * Provide functions that are added to the model (Model). If you override methods provided by sequelize,
5315 * you can access the original method using `this.constructor.prototype`, e.g.
5316 * `this.constructor.prototype.find.apply(this, arguments)`
5317 */
5318 classMethods?: Object;
5319
5320 /**
5321 * Change the database schema. PG only feature, but also works with other dialects.
5322 */
5323 schema?: string;
5324
5325
5326 /**
5327 * Change the database schema delimiter. Defaults to "." on PG but for other dialects can be also changed to "_".
5328 */
5329 schemaDelimiter?: string;
5330
5331 /**
5332 * You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
5333 */
5334 engine?: string;
5335
5336 charset?: string;
5337
5338 /**
5339 * Finaly you can specify a comment for the table in MySQL and PG
5340 */
5341 comment?: string;
5342
5343 collate?: string;
5344
5345 /**
5346 * Specify the ROW_FORMAT for use with the MySQL InnoDB engine.
5347 */
5348 rowFormat?: string;
5349
5350 /**
5351 * Set the initial AUTO_INCREMENT value for the table in MySQL.
5352 */
5353 initialAutoIncrement?: string;
5354
5355 /**
5356 * An object of hook function that are called before and after certain lifecycle events.
5357 * The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy,
5358 * beforeBulkUpdate, beforeCreate, beforeDestroy, beforeSave, beforeUpdate, afterCreate, afterDestroy,
5359 * afterSave, afterUpdate, afterBulkCreate, afterBulkDestory and afterBulkUpdate.
5360 * See Hooks for more information about hook functions and their signatures. Each property can either
5361 * be a function, or an array of functions.
5362 */
5363 hooks?: HooksDefineOptions<TInstance>;
5364
5365 /**
5366 * An object of model wide validations. Validations have access to all model values via `this`. If the
5367 * validator function takes an argument, it is asumed to be async, and is called with a callback that
5368 * accepts an optional error.
5369 */
5370 validate?: DefineValidateOptions;
5371
5372 /**
5373 * Enable optimistic locking. When enabled, sequelize will add a version count attribute
5374 * to the model and throw an OptimisticLockingError error when stale instances are saved.
5375 * Set to true or a string with the attribute name you want to use to enable.
5376 */
5377 version?: boolean | string;
5378
5379 /**
5380 * Throws an error when no records found
5381 */
5382 rejectOnError?: boolean | Error;
5383 }
5384
5385 /**
5386 * Sync Options
5387 *
5388 * @see Sequelize.sync
5389 */
5390 interface SyncOptions {
5391
5392 /**
5393 * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table
5394 */
5395 force?: boolean;
5396
5397 /**
5398 * Match a regex against the database name before syncing, a safety check for cases where force: true is
5399 * used in tests but not live code
5400 */
5401 match?: RegExp;
5402
5403 /**
5404 * A function that logs sql queries, or false for no logging
5405 */
5406 logging?: Function | boolean;
5407
5408 /**
5409 * The schema that the tables should be created in. This can be overriden for each table in sequelize.define
5410 */
5411 schema?: string;
5412
5413 /**
5414 * Alters tables to fit models. Not recommended for production use. Deletes data in columns
5415 * that were removed or had their type changed in the model.
5416 */
5417 alter?: boolean;
5418
5419 /**
5420 * If hooks is true then beforeSync, afterSync, beforBulkSync, afterBulkSync hooks will be called
5421 */
5422 hooks?: boolean;
5423
5424 /**
5425 * An optional parameter to specify the schema search_path (Postgres only)
5426 */
5427 searchPath?: string;
5428
5429 }
5430
5431 interface SetOptions { }
5432
5433 /**
5434 * Connection Pool options
5435 *
5436 * @see Options
5437 */
5438 interface PoolOptions {
5439
5440 /**
5441 * Maximum connections of the pool
5442 */
5443 max?: number;
5444
5445 /**
5446 * Minimum connections of the pool
5447 */
5448 min?: number;
5449
5450 /**
5451 * The maximum time, in milliseconds, that a connection can be idle before being released.
5452 */
5453 idle?: number;
5454
5455 /**
5456 * The maximum time, in milliseconds, that pool will try to get connection before throwing error
5457 */
5458 acquire?: number;
5459
5460 /**
5461 * A function that validates a connection. Called with client. The default function checks that client is an
5462 * object, and that its state is not disconnected.
5463 */
5464 validate?: (client?: any) => boolean;
5465
5466 /*
5467 * The time interval, in milliseconds, for evicting stale connections
5468 */
5469 evict?: number;
5470
5471 }
5472
5473 /**
5474 * Interface for replication Options in the sequelize constructor
5475 *
5476 * @see Options
5477 */
5478 interface ReplicationOptions {
5479
5480 read?: {
5481 host?: string;
5482 port?: string | number;
5483 username?: string;
5484 password?: string;
5485 database?: string;
5486 }[];
5487
5488 write?: {
5489 host?: string;
5490 port?: string | number;
5491 username?: string;
5492 password?: string;
5493 database?: string;
5494 };
5495
5496 }
5497
5498 /**
5499 * Interface for retry Options in the sequelize constructor and QueryOptions
5500 *
5501 * @see Options, QueryOptions
5502 */
5503 interface RetryOptions {
5504
5505 /**
5506 * Only retry a query if the error matches one of these strings.
5507 */
5508 match?: (string|RegExp|Error)[];
5509
5510 /**
5511 * How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
5512 */
5513 max?: number
5514
5515 }
5516
5517 /**
5518 * Operator symbols to be used when querying data
5519 */
5520 interface Operators {
5521 eq: symbol;
5522 ne: symbol;
5523 gte: symbol;
5524 gt: symbol;
5525 lte: symbol;
5526 lt: symbol;
5527 not: symbol;
5528 is: symbol;
5529 in: symbol;
5530 notIn: symbol;
5531 like: symbol;
5532 notLike: symbol;
5533 iLike: symbol;
5534 notILike: symbol;
5535 regexp: symbol;
5536 notRegexp: symbol;
5537 iRegexp: symbol;
5538 notIRegexp: symbol;
5539 between: symbol;
5540 notBetween: symbol;
5541 overlap: symbol;
5542 contains: symbol;
5543 contained: symbol;
5544 adjacent: symbol;
5545 strictLeft: symbol;
5546 strictRight: symbol;
5547 noExtendRight: symbol;
5548 noExtendLeft: symbol;
5549 and: symbol;
5550 or: symbol;
5551 any: symbol;
5552 all: symbol;
5553 values: symbol;
5554 col: symbol;
5555 placeholder: symbol;
5556 join: symbol;
5557 raw: symbol; //deprecated remove by v5.0
5558 }
5559
5560 type OperatorsAliases = Partial<{
5561 [key: string]: symbol;
5562 $eq: symbol;
5563 $ne: symbol;
5564 $gte: symbol;
5565 $gt: symbol;
5566 $lte: symbol;
5567 $lt: symbol;
5568 $not: symbol;
5569 $in: symbol;
5570 $notIn: symbol;
5571 $is: symbol;
5572 $like: symbol;
5573 $notLike: symbol;
5574 $iLike: symbol;
5575 $notILike: symbol;
5576 $regexp: symbol;
5577 $notRegexp: symbol;
5578 $iRegexp: symbol;
5579 $notIRegexp: symbol;
5580 $between: symbol;
5581 $notBetween: symbol;
5582 $overlap: symbol;
5583 $contains: symbol;
5584 $contained: symbol;
5585 $adjacent: symbol;
5586 $strictLeft: symbol;
5587 $strictRight: symbol;
5588 $noExtendRight: symbol;
5589 $noExtendLeft: symbol;
5590 $and: symbol;
5591 $or: symbol;
5592 $any: symbol;
5593 $all: symbol;
5594 $values: symbol;
5595 $col: symbol;
5596 $raw: symbol; //deprecated remove by v5.0
5597 }>
5598
5599 /**
5600 * Options for the constructor of Sequelize main class
5601 */
5602 interface Options {
5603
5604 /**
5605 * The dialect of the database you are connecting to. One of mysql, postgres, sqlite, mariadb and mssql.
5606 *
5607 * Defaults to 'mysql'
5608 */
5609 dialect?: string;
5610
5611 /**
5612 * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of
5613 * pg when connecting to a pg database, you should specify 'pg.js' here
5614 */
5615 dialectModulePath?: string;
5616
5617 /**
5618 * An object of additional options, which are passed directly to the connection library
5619 */
5620 dialectOptions?: Object;
5621
5622 /**
5623 * Only used by sqlite.
5624 *
5625 * Defaults to ':memory:'
5626 */
5627 storage?: string;
5628
5629 /**
5630 * The host of the relational database.
5631 *
5632 * Defaults to 'localhost'
5633 */
5634 host?: string;
5635
5636 /**
5637 * The port of the relational database.
5638 */
5639 port?: number;
5640
5641 /**
5642 * The protocol of the relational database.
5643 *
5644 * Defaults to 'tcp'
5645 */
5646 protocol?: string;
5647
5648 /**
5649 * The username which is used to authenticate against the database.
5650 */
5651 username?: string;
5652
5653 /**
5654 * The password which is used to authenticate against the database.
5655 */
5656 password?: string;
5657
5658 /**
5659 * The name of the database
5660 */
5661 database?: string;
5662
5663 /**
5664 * Default options for model definitions. See sequelize.define for options
5665 */
5666 define?: DefineOptions<any>;
5667
5668 /**
5669 * Default options for sequelize.query
5670 */
5671 query?: QueryOptions;
5672
5673 /**
5674 * Default options for sequelize.set
5675 */
5676 set?: SetOptions;
5677
5678 /**
5679 * Default options for sequelize.sync
5680 */
5681 sync?: SyncOptions;
5682
5683 /**
5684 * The timezone used when converting a date from the database into a JavaScript date. The timezone is also
5685 * used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP
5686 * and other time related functions have in the right timezone. For best cross platform performance use the
5687 * format
5688 * +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles');
5689 * this is useful to capture daylight savings time changes.
5690 *
5691 * Defaults to '+00:00'
5692 */
5693 timezone?: string;
5694
5695 /**
5696 * A function that gets executed everytime Sequelize would log something.
5697 *
5698 * Defaults to console.log
5699 */
5700 logging?: boolean | Function;
5701
5702 /**
5703 * A flag that defines if null values should be passed to SQL queries or not.
5704 *
5705 * Defaults to false
5706 */
5707 omitNull?: boolean;
5708
5709 /**
5710 * A flag that defines if native library shall be used or not. Currently only has an effect for postgres
5711 *
5712 * Defaults to false
5713 */
5714 native?: boolean;
5715
5716 /**
5717 * Use read / write replication. To enable replication, pass an object, with two properties, read and write.
5718 * Write should be an object (a single server for handling writes), and read an array of object (several
5719 * servers to handle reads). Each read/write server can have the following properties: `host`, `port`,
5720 * `username`, `password`, `database`
5721 *
5722 * Defaults to false
5723 */
5724 replication?: ReplicationOptions;
5725
5726 /**
5727 * Set of flags that control when a query is automatically retried.
5728 */
5729 retry?: RetryOptions;
5730
5731 /**
5732 * Run built in type validators on insert and update,
5733 * e.g. validate that arguments passed to integer fields are integer-like.
5734 *
5735 * Defaults to false
5736 */
5737 typeValidation?: boolean;
5738
5739 /**
5740 * Connection pool options
5741 */
5742 pool?: PoolOptions;
5743
5744 /**
5745 * Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of
5746 * them.
5747 *
5748 * Defaults to true
5749 */
5750 quoteIdentifiers?: boolean;
5751
5752 /**
5753 * The version of the database. Most times, this is automatically detected and is not needed.
5754 *
5755 * Defaults to 0
5756 */
5757 databaseVersion?: number;
5758
5759 /**
5760 * Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible
5761 * options.
5762 *
5763 * Defaults to 'REPEATABLE_READ'
5764 */
5765 isolationLevel?: TransactionIsolationLevel;
5766
5767 /**
5768 * Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible
5769 * options.
5770 *
5771 * Defaults to 'DEFERRED'
5772 */
5773 transactionType?: TransactionType;
5774
5775 /**
5776 * Print query execution time in milliseconds when logging SQL.
5777 *
5778 * Defaults to false
5779 */
5780 benchmark?: boolean;
5781
5782 /**
5783 * String based operator alias, default value is true which will enable all operators alias.
5784 * Pass object to limit set of aliased operators or false to disable completely.
5785 */
5786 operatorsAliases?: boolean | OperatorsAliases;
5787
5788 /**
5789 * Set to `true` to enable connecting over SSL.
5790 *
5791 * Defaults to undefined
5792 */
5793 ssl?: boolean;
5794 }
5795
5796 /**
5797 * Sequelize methods that are available both for the static and the instance class of Sequelize
5798 */
5799 interface SequelizeStaticAndInstance extends Errors {
5800
5801 /**
5802 * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you
5803 * might want to use `Sequelize.Utils._`, which is a reference to the lodash library, if you don't already
5804 * have it imported in your project.
5805 */
5806 Utils: Utils;
5807
5808 /**
5809 * A modified version of bluebird promises, that allows listening for sql events
5810 */
5811 Promise: typeof Promise;
5812
5813 /**
5814 * Available query types for use with `sequelize.query`
5815 */
5816 QueryTypes: QueryTypes;
5817
5818 /**
5819 * Exposes the validator.js object, so you can extend it with custom validation functions.
5820 * The validator is exposed both on the instance, and on the constructor.
5821 */
5822 Validator: Validator;
5823
5824 /**
5825 * A Model represents a table in the database. Sometimes you might also see it referred to as model, or
5826 * simply as factory. This class should not be instantiated directly, it is created using sequelize.define,
5827 * and already created models can be loaded using sequelize.import
5828 */
5829 Model: Model<any, any>;
5830
5831 /**
5832 * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a
5833 * transaction
5834 */
5835 Transaction: TransactionStatic;
5836
5837 /**
5838 * A reference to the deferrable collection. Use this to access the different deferrable options.
5839 */
5840 Deferrable: Deferrable;
5841
5842 /**
5843 * A reference to the sequelize instance class.
5844 */
5845 Instance: Instance<any>;
5846
5847 Op: Operators;
5848
5849 /**
5850 * Creates a object representing a database function. This can be used in search queries, both in where and
5851 * order parts, and as default values in column definitions. If you want to refer to columns in your
5852 * function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and
5853 * not a strings.
5854 *
5855 * Convert a user's username to upper case
5856 * ```js
5857 * instance.updateAttributes({
5858 * username: self.sequelize.fn('upper', self.sequelize.col('username'))
5859 * })
5860 * ```
5861 * @param fn The function you want to call
5862 * @param args All further arguments will be passed as arguments to the function
5863 */
5864 fn(fn: string, ...args: any[]): fn;
5865
5866 /**
5867 * Creates a object representing a column in the DB. This is often useful in conjunction with
5868 * `sequelize.fn`, since raw string arguments to fn will be escaped.
5869 *
5870 * @param col The name of the column
5871 */
5872 col(col: string): col;
5873
5874 /**
5875 * Creates a object representing a call to the cast function.
5876 *
5877 * @param val The value to cast
5878 * @param type The type to cast it to
5879 */
5880 cast(val: any, type: string): cast;
5881
5882 /**
5883 * Creates a object representing a literal, i.e. something that will not be escaped.
5884 *
5885 * @param val
5886 */
5887 literal(val: any): literal;
5888 asIs(val: any): literal;
5889
5890 /**
5891 * An AND query
5892 *
5893 * @param args Each argument will be joined by AND
5894 */
5895 and(...args: Array<string | Object>): and;
5896
5897 /**
5898 * An OR query
5899 *
5900 * @param args Each argument will be joined by OR
5901 */
5902 or(...args: Array<string | Object>): or;
5903
5904 /**
5905 * Creates an object representing nested where conditions for postgres's json data-type.
5906 *
5907 * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot
5908 * notation or a string using postgres json syntax.
5909 * @param value An optional value to compare against. Produces a string of the form "<json path> =
5910 * '<value>'".
5911 */
5912 json(conditionsOrPath: string | Object, value?: string | number | boolean): json;
5913
5914 /**
5915 * A way of specifying attr = condition.
5916 *
5917 * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id`
5918 * or
5919 * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can
5920 * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.)
5921 *
5922 * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your
5923 * string to be escaped, use `sequelize.literal`.
5924 *
5925 * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a
5926 * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the
5927 * POJO syntax
5928 * @param comparator Comparator
5929 * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal`
5930 * etc.)
5931 */
5932 where(attr: Object, comparator: string, logic: string | Object): where;
5933 where(attr: Object, logic: string | Object): where;
5934 condition(attr: Object, logic: string | Object): where;
5935
5936 }
5937
5938 /**
5939 * Sequelize methods available only for the static class ( basically this is the constructor and some extends )
5940 */
5941 interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes {
5942
5943 /**
5944 * Instantiate sequelize with name of database, username and password
5945 *
5946 * #### Example usage
5947 *
5948 * ```javascript
5949 * // without password and options
5950 * var sequelize = new Sequelize('database', 'username')
5951 *
5952 * // without options
5953 * var sequelize = new Sequelize('database', 'username', 'password')
5954 *
5955 * // without password / with blank password
5956 * var sequelize = new Sequelize('database', 'username', null, {})
5957 *
5958 * // with password and options
5959 * var sequelize = new Sequelize('my_database', 'john', 'doe', {})
5960 *
5961 * // with uri (see below)
5962 * var sequelize = new Sequelize('mysql://localhost:3306/database', {})
5963 * ```
5964 *
5965 * @param database The name of the database
5966 * @param username The username which is used to authenticate against the
5967 * database.
5968 * @param password The password which is used to authenticate against the
5969 * database.
5970 * @param options An object with options.
5971 */
5972 new (database: string, username: string, password: string, options?: Options): Sequelize;
5973 new (database: string, username: string, options?: Options): Sequelize;
5974
5975 /**
5976 * Instantiate sequelize with an URI
5977 * @name Sequelize
5978 * @constructor
5979 *
5980 * @param uri A full database URI
5981 * @param options See above for possible options
5982 */
5983 new (uri: string, options?: Options): Sequelize;
5984
5985 /**
5986 * Instantiate sequelize with an options object which containing username, password, database
5987 * @name Sequelize
5988 * @constructor
5989 *
5990 * @param options An object with options. See above for possible options
5991 */
5992 new (options: Options): Sequelize;
5993
5994 /**
5995 * Provide access to continuation-local-storage (http://docs.sequelizejs.com/en/latest/api/sequelize/#transactionoptions-promise)
5996 */
5997 cls: any;
5998 useCLS(namespace:cls.Namespace): Sequelize;
5999
6000 /**
6001 * Default export for `import Sequelize from 'sequelize';` kind of imports
6002 */
6003 default: SequelizeStatic;
6004
6005 /**
6006 * Export sequelize static on the instance for `import Sequelize from 'sequelize';` kind of imports
6007 */
6008 Sequelize: SequelizeStatic;
6009 }
6010
6011 interface QueryOptionsTransactionRequired { }
6012 interface ModelsHashInterface {
6013 [name: string]: Model<any, any>;
6014 }
6015
6016 /**
6017 * This is the main class, the entry point to sequelize. To use it, you just need to
6018 * import sequelize:
6019 *
6020 * ```js
6021 * var Sequelize = require('sequelize');
6022 * ```
6023 *
6024 * In addition to sequelize, the connection library for the dialect you want to use
6025 * should also be installed in your project. You don't need to import it however, as
6026 * sequelize will take care of that.
6027 */
6028 interface Sequelize extends SequelizeStaticAndInstance, Hooks<any> {
6029
6030 /**
6031 * A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
6032 */
6033 Sequelize: SequelizeStatic;
6034
6035 /**
6036 * Defined models.
6037 */
6038 models: ModelsHashInterface;
6039
6040 /**
6041 * Defined options.
6042 */
6043 options: Options;
6044
6045 /**
6046 * Returns the specified dialect.
6047 */
6048 getDialect(): string;
6049
6050 /**
6051 * Returns an instance of QueryInterface.
6052 */
6053 getQueryInterface(): QueryInterface;
6054
6055 /**
6056 * Define a new model, representing a table in the DB.
6057 *
6058 * The table columns are define by the hash that is given as the second argument. Each attribute of the
6059 * hash
6060 * represents a column. A short table definition might look like this:
6061 *
6062 * ```js
6063 * sequelize.define('modelName', {
6064 * columnA: {
6065 * type: Sequelize.BOOLEAN,
6066 * validate: {
6067 * is: ["[a-z]",'i'], // will only allow letters
6068 * max: 23, // only allow values <= 23
6069 * isIn: {
6070 * args: [['en', 'zh']],
6071 * msg: "Must be English or Chinese"
6072 * }
6073 * },
6074 * field: 'column_a'
6075 * // Other attributes here
6076 * },
6077 * columnB: Sequelize.STRING,
6078 * columnC: 'MY VERY OWN COLUMN TYPE'
6079 * })
6080 *
6081 * sequelize.models.modelName // The model will now be available in models under the name given to define
6082 * ```
6083 *
6084 * As shown above, column definitions can be either strings, a reference to one of the datatypes that are
6085 * predefined on the Sequelize constructor, or an object that allows you to specify both the type of the
6086 * column, and other attributes such as default values, foreign key constraints and custom setters and
6087 * getters.
6088 *
6089 * For a list of possible data types, see
6090 * http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types
6091 *
6092 * For more about getters and setters, see
6093 * http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters
6094 *
6095 * For more about instance and class methods, see
6096 * http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models
6097 *
6098 * For more about validation, see
6099 * http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations
6100 *
6101 * @param modelName The name of the model. The model will be stored in `sequelize.models` under this name
6102 * @param attributes An object, where each attribute is a column of the table. Each column can be either a
6103 * DataType, a string or a type-description object, with the properties described below:
6104 * @param options These options are merged with the default define options provided to the Sequelize
6105 * constructor
6106 */
6107 define<TInstance, TAttributes, TCreationAttributes = TAttributes>(modelName: string, attributes: DefineModelAttributes<TCreationAttributes>,
6108 options?: DefineOptions<TInstance>): Model<TInstance, TAttributes, TCreationAttributes>;
6109
6110 /**
6111 * Fetch a Model which is already defined
6112 *
6113 * @param modelName The name of a model defined with Sequelize.define
6114 */
6115 model<TInstance, TAttributes>(modelName: string): Model<TInstance, TAttributes>;
6116
6117 /**
6118 * Checks whether a model with the given name is defined
6119 *
6120 * @param modelName The name of a model defined with Sequelize.define
6121 */
6122 isDefined(modelName: string): boolean;
6123
6124 /**
6125 * Imports a model defined in another file
6126 *
6127 * Imported models are cached, so multiple calls to import with the same path will not load the file
6128 * multiple times
6129 *
6130 * See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a
6131 * short example of how to define your models in separate files so that they can be imported by
6132 * sequelize.import
6133 *
6134 * @param path The path to the file that holds the model you want to import. If the part is relative, it
6135 * will be resolved relatively to the calling file
6136 *
6137 * @param defineFunction An optional function that provides model definitions. Useful if you do not
6138 * want to use the module root as the define function
6139 */
6140 import<TInstance, TAttributes>(path: string, defineFunction?: (sequelize: Sequelize, dataTypes: DataTypes) => Model<TInstance, TAttributes>): Model<TInstance, TAttributes>;
6141
6142 /**
6143 * Execute a query on the DB, with the posibility to bypass all the sequelize goodness.
6144 *
6145 * By default, the function will return two arguments: an array of results, and a metadata object,
6146 * containing number of affected rows etc. Use `.spread` to access the results.
6147 *
6148 * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you
6149 * can pass in a query type to make sequelize format the results:
6150 *
6151 * ```js
6152 * sequelize.query('SELECT...').spread(function (results, metadata) {
6153 * // Raw query - use spread
6154 * });
6155 *
6156 * sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(function (results) {
6157 * // SELECT query - use then
6158 * })
6159 * ```
6160 *
6161 * @param sql
6162 * @param options Query options
6163 */
6164 query(sql: string | { query: string, values: any[] }, options?: QueryOptions): Promise<any>;
6165
6166 /**
6167 * Execute a query which would set an environment or user variable. The variables are set per connection,
6168 * so this function needs a transaction.
6169 *
6170 * Only works for MySQL.
6171 *
6172 * @param variables Object with multiple variables.
6173 * @param options Query options.
6174 */
6175 set(variables: Object, options: QueryOptionsTransactionRequired): Promise<any>;
6176
6177 /**
6178 * Escape value.
6179 *
6180 * @param value Value that needs to be escaped
6181 */
6182 escape(value: string): string;
6183
6184 /**
6185 * Create a new database schema.
6186 *
6187 * Note,that this is a schema in the
6188 * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
6189 * not a database table. In mysql and sqlite, this command will do nothing.
6190 *
6191 * @param schema Name of the schema
6192 * @param options Options supplied
6193 * @param options.logging A function that logs sql queries, or false for no logging
6194 */
6195 createSchema(schema: string, options: { logging?: boolean | Function }): Promise<any>;
6196
6197 /**
6198 * Show all defined schemas
6199 *
6200 * Note,that this is a schema in the
6201 * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
6202 * not a database table. In mysql and sqlite, this will show all tables.
6203 *
6204 * @param options Options supplied
6205 * @param options.logging A function that logs sql queries, or false for no logging
6206 */
6207 showAllSchemas(options: { logging?: boolean | Function }): Promise<any>;
6208
6209 /**
6210 * Drop a single schema
6211 *
6212 * Note,that this is a schema in the
6213 * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
6214 * not a database table. In mysql and sqlite, this drop a table matching the schema name
6215 *
6216 * @param schema Name of the schema
6217 * @param options Options supplied
6218 * @param options.logging A function that logs sql queries, or false for no logging
6219 */
6220 dropSchema(schema: string, options: { logging?: boolean | Function }): Promise<any>;
6221
6222 /**
6223 * Drop all schemas
6224 *
6225 * Note,that this is a schema in the
6226 * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
6227 * not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
6228 *
6229 * @param options Options supplied
6230 * @param options.logging A function that logs sql queries, or false for no logging
6231 */
6232 dropAllSchemas(options: { logging?: boolean | Function }): Promise<any>;
6233
6234 /**
6235 * Sync all defined models to the DB.
6236 *
6237 * @param options Sync Options
6238 */
6239 sync(options?: SyncOptions): Promise<any>;
6240
6241 /**
6242 * Truncate all tables defined through the sequelize models. This is done
6243 * by calling Model.truncate() on each model.
6244 *
6245 * @param {object} [options] The options passed to Model.destroy in addition to truncate
6246 * @param {Boolean|function} [options.transaction]
6247 * @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
6248 */
6249 truncate(options?: DestroyOptions): Promise<any>;
6250
6251 /**
6252 * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
6253 * @see {Model#drop} for options
6254 *
6255 * @param options The options passed to each call to Model.drop
6256 */
6257 drop(options?: DropOptions): Promise<any>;
6258
6259 /**
6260 * Test the connection by trying to authenticate
6261 *
6262 * @param options Query Options for authentication
6263 */
6264 authenticate(options?: QueryOptions): Promise<void>;
6265 validate(options?: QueryOptions): Promise<ValidationError>;
6266
6267 /**
6268 * Start a transaction. When using transactions, you should pass the transaction in the options argument
6269 * in order for the query to happen under that transaction
6270 *
6271 * ```js
6272 * sequelize.transaction().then(function (t) {
6273 * return User.find(..., { transaction: t}).then(function (user) {
6274 * return user.updateAttributes(..., { transaction: t});
6275 * })
6276 * .then(t.commit.bind(t))
6277 * .catch(t.rollback.bind(t));
6278 * })
6279 * ```
6280 *
6281 * A syntax for automatically committing or rolling back based on the promise chain resolution is also
6282 * supported:
6283 *
6284 * ```js
6285 * sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then()
6286 * return User.find(..., { transaction: t}).then(function (user) {
6287 * return user.updateAttributes(..., { transaction: t});
6288 * });
6289 * }).then(function () {
6290 * // Commited
6291 * }).catch(function (err) {
6292 * // Rolled back
6293 * console.error(err);
6294 * });
6295 * ```
6296 *
6297 * If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction
6298 * will automatically be passed to any query that runs witin the callback. To enable CLS, add it do your
6299 * project, create a namespace and set it on the sequelize constructor:
6300 *
6301 * ```js
6302 * var cls = require('continuation-local-storage'),
6303 * ns = cls.createNamespace('....');
6304 * var Sequelize = require('sequelize');
6305 * Sequelize.cls = ns;
6306 * ```
6307 * Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
6308 *
6309 * @param options Transaction Options
6310 * @param autoCallback Callback for the transaction
6311 */
6312 transaction<T>(options: TransactionOptions,
6313 autoCallback: (t: Transaction) => PromiseLike<T>): Promise<T>;
6314 transaction<T>(autoCallback: (t: Transaction) => PromiseLike<T>): Promise<T>;
6315 transaction(options?: TransactionOptions): Promise<Transaction>;
6316
6317 /**
6318 * Close all connections used by this sequelize instance, and free all references so the instance can be
6319 * garbage collected.
6320 *
6321 * Normally this is done on process exit, so you only need to call this method if you are creating multiple
6322 * instances, and want to garbage collect some of them.
6323 */
6324 close(): Promise<void>;
6325
6326 /**
6327 * Returns the database version
6328 */
6329 databaseVersion(): Promise<string>;
6330
6331 /**
6332 * Get the fn for random based on the dialect
6333 */
6334 random(): fn;
6335 }
6336
6337 //
6338 // Validator
6339 // ~~~~~~~~~~~
6340
6341 type ValidatorJSType = typeof ValidatorJS
6342
6343 /**
6344 * Validator Interface
6345 */
6346 interface Validator extends ValidatorJSType {
6347
6348 notEmpty(str: string): boolean;
6349 len(str: string, min: number, max: number): boolean;
6350 isUrl(str: string): boolean;
6351 isIPv6(str: string): boolean;
6352 isIPv4(str: string): boolean;
6353 notIn(str: string, values: string[]): boolean;
6354 regex(str: string, pattern: string, modifiers: string): boolean;
6355 notRegex(str: string, pattern: string, modifiers: string): boolean;
6356 isDecimal(str: string): boolean;
6357 min(str: string, val: number): boolean;
6358 max(str: string, val: number): boolean;
6359 not(str: string, pattern: string, modifiers: string): boolean;
6360 contains(str: string, element: string[]): boolean;
6361 notContains(str: string, element: string[]): boolean;
6362 is(str: string, pattern: string, modifiers: string): boolean;
6363
6364 }
6365
6366 //
6367 // Transaction
6368 // ~~~~~~~~~~~~~
6369 //
6370 // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/transaction.js
6371 //
6372
6373 /**
6374 * The transaction object is used to identify a running transaction. It is created by calling
6375 * `Sequelize.transaction()`.
6376 *
6377 * To run a query under a transaction, you should pass the transaction in the options object.
6378 */
6379 interface Transaction {
6380
6381 /**
6382 * Possible options for row locking. Used in conjuction with `find` calls:
6383 *
6384 * @see TransactionStatic
6385 */
6386 LOCK: TransactionLock;
6387
6388 /**
6389 * Commit the transaction
6390 */
6391 commit(): Promise<void>;
6392
6393 /**
6394 * Rollback (abort) the transaction
6395 */
6396 rollback(): Promise<void>;
6397
6398 }
6399
6400 /**
6401 * The transaction static object
6402 *
6403 * @see Transaction
6404 */
6405 interface TransactionStatic {
6406
6407 /**
6408 * Isolations levels can be set per-transaction by passing `options.isolationLevel` to
6409 * `sequelize.transaction`. Default to `REPEATABLE_READ` but you can override the default isolation level
6410 * by passing
6411 * `options.isolationLevel` in `new Sequelize`.
6412 *
6413 * The possible isolations levels to use when starting a transaction:
6414 *
6415 * ```js
6416 * {
6417 * READ_UNCOMMITTED: "READ UNCOMMITTED",
6418 * READ_COMMITTED: "READ COMMITTED",
6419 * REPEATABLE_READ: "REPEATABLE READ",
6420 * SERIALIZABLE: "SERIALIZABLE"
6421 * }
6422 * ```
6423 *
6424 * Pass in the desired level as the first argument:
6425 *
6426 * ```js
6427 * return sequelize.transaction({
6428 * isolationLevel: Sequelize.Transaction.SERIALIZABLE
6429 * }, function (t) {
6430 *
6431 * // your transactions
6432 *
6433 * }).then(function(result) {
6434 * // transaction has been committed. Do something after the commit if required.
6435 * }).catch(function(err) {
6436 * // do something with the err.
6437 * });
6438 * ```
6439 *
6440 * @see ISOLATION_LEVELS
6441 */
6442 ISOLATION_LEVELS: TransactionIsolationLevels;
6443
6444 /**
6445 * Transaction type can be set per-transaction by passing `options.type` to
6446 * `sequelize.transaction`. Default to `DEFERRED` but you can override the default isolation level
6447 * by passing `options.transactionType` in `new Sequelize`.
6448 *
6449 * The transaction types to use when starting a transaction:
6450 *
6451 * ```js
6452 * {
6453 * DEFERRED: "DEFERRED",
6454 * IMMEDIATE: "IMMEDIATE",
6455 * EXCLUSIVE: "EXCLUSIVE"
6456 * }
6457 * ```
6458 *
6459 * Pass in the transaction type the first argument:
6460 *
6461 * ```js
6462 * return sequelize.transaction({
6463 * type: Sequelize.Transaction.EXCLUSIVE
6464 * }, function (t) {
6465 *
6466 * // your transactions
6467 *
6468 * }).then(function(result) {
6469 * // transaction has been committed. Do something after the commit if required.
6470 * }).catch(function(err) {
6471 * // do something with the err.
6472 * });
6473 * ```
6474 *
6475 * @see Sequelize.Transaction.TYPES
6476 */
6477 TYPES: TransactionTypes;
6478
6479 /**
6480 * Possible options for row locking. Used in conjuction with `find` calls:
6481 *
6482 * ```js
6483 * t1 // is a transaction
6484 * t1.LOCK.UPDATE,
6485 * t1.LOCK.SHARE,
6486 * t1.LOCK.KEY_SHARE, // Postgres 9.3+ only
6487 * t1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ only
6488 * ```
6489 *
6490 * Usage:
6491 * ```js
6492 * t1 // is a transaction
6493 * Model.findAll({
6494 * where: ...,
6495 * transaction: t1,
6496 * lock: t1.LOCK...
6497 * });
6498 * ```
6499 *
6500 * Postgres also supports specific locks while eager loading by using OF:
6501 * ```js
6502 * UserModel.findAll({
6503 * where: ...,
6504 * include: [TaskModel, ...],
6505 * transaction: t1,
6506 * lock: {
6507 * level: t1.LOCK...,
6508 * of: UserModel
6509 * }
6510 * });
6511 * ```
6512 * UserModel will be locked but TaskModel won't!
6513 */
6514 LOCK: TransactionLock;
6515
6516 }
6517
6518 type TransactionIsolationLevelReadUncommitted = 'READ UNCOMMITTED';
6519 type TransactionIsolationLevelReadCommitted = 'READ COMMITTED';
6520 type TransactionIsolationLevelRepeatableRead = 'REPEATABLE READ';
6521 type TransactionIsolationLevelSerializable = 'SERIALIZABLE';
6522 type TransactionIsolationLevel = TransactionIsolationLevelReadUncommitted | TransactionIsolationLevelReadCommitted | TransactionIsolationLevelRepeatableRead | TransactionIsolationLevelSerializable;
6523
6524 /**
6525 * Isolations levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
6526 * Default to `REPEATABLE_READ` but you can override the default isolation level by passing
6527 * `options.isolationLevel` in `new Sequelize`.
6528 */
6529 interface TransactionIsolationLevels {
6530 READ_UNCOMMITTED: TransactionIsolationLevelReadUncommitted; // 'READ UNCOMMITTED'
6531 READ_COMMITTED: TransactionIsolationLevelReadCommitted; // 'READ COMMITTED'
6532 REPEATABLE_READ: TransactionIsolationLevelRepeatableRead; // 'REPEATABLE READ'
6533 SERIALIZABLE: TransactionIsolationLevelSerializable; // 'SERIALIZABLE'
6534 }
6535
6536 type TransactionTypeDeferred = 'DEFERRED';
6537 type TransactionTypeImmediate = 'IMMEDIATE';
6538 type TransactionTypeExclusive = 'EXCLUSIVE';
6539 type TransactionType = TransactionTypeDeferred | TransactionTypeImmediate | TransactionTypeExclusive;
6540
6541 /**
6542 * Transaction type can be set per-transaction by passing `options.type` to `sequelize.transaction`.
6543 * Default to `DEFERRED` but you can override the default isolation level by passing
6544 * `options.transactionType` in `new Sequelize`.
6545 */
6546 interface TransactionTypes {
6547 DEFERRED: TransactionTypeDeferred; // 'DEFERRED'
6548 IMMEDIATE: TransactionTypeImmediate; // 'IMMEDIATE'
6549 EXCLUSIVE: TransactionTypeExclusive; // 'EXCLUSIVE'
6550 }
6551
6552 type TransactionLockLevelUpdate = 'UPDATE';
6553 type TransactionLockLevelShare = 'SHARE';
6554 type TransactionLockLevelKeyShare = 'KEY SHARE';
6555 type TransactionLockLevelNoKeyUpdate = 'NO KEY UPDATE';
6556 type TransactionLockLevel = TransactionLockLevelUpdate | TransactionLockLevelShare | TransactionLockLevelKeyShare | TransactionLockLevelNoKeyUpdate;
6557
6558 /**
6559 * Possible options for row locking. Used in conjuction with `find` calls:
6560 */
6561 interface TransactionLock {
6562 UPDATE: TransactionLockLevelUpdate; // 'UPDATE'
6563 SHARE: TransactionLockLevelShare; // 'SHARE'
6564 KEY_SHARE: TransactionLockLevelKeyShare; // 'KEY SHARE'
6565 NO_KEY_UPDATE: TransactionLockLevelNoKeyUpdate; // 'NO KEY UPDATE'
6566 }
6567
6568 /**
6569 * Options provided when the transaction is created
6570 *
6571 * @see sequelize.transaction()
6572 */
6573 interface TransactionOptions {
6574
6575 autocommit?: boolean;
6576
6577 /**
6578 * See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
6579 */
6580 isolationLevel?: TransactionIsolationLevel;
6581
6582 /**
6583 * See `Sequelize.Transaction.TYPES` for possible options
6584 */
6585 type?: TransactionType;
6586
6587 /**
6588 * A function that gets executed while running the query to log the sql.
6589 */
6590 logging?: Function;
6591
6592 /**
6593 * Specify the parent transaction so that this transaction is nested or a save point within the parent
6594 */
6595 transaction?: Transaction;
6596
6597 /**
6598 * Sets the constraints to be deferred or immediately checked.
6599 */
6600 deferrable?: Deferrable[keyof Deferrable];
6601
6602 }
6603
6604 //
6605 // Utils
6606 // ~~~~~~~
6607
6608 interface fn {
6609 clone: fnStatic;
6610 }
6611
6612 interface fnStatic {
6613 /**
6614 * @param fn The function you want to call
6615 * @param args All further arguments will be passed as arguments to the function
6616 */
6617 new (fn: string, ...args: any[]): fn;
6618 }
6619
6620 interface col {
6621 col: string;
6622 }
6623
6624 interface colStatic {
6625 /**
6626 * Creates a object representing a column in the DB. This is often useful in conjunction with
6627 * `sequelize.fn`, since raw string arguments to fn will be escaped.
6628 * @see {Sequelize#fn}
6629 *
6630 * @param col The name of the column
6631 */
6632 new (col: string): col;
6633 }
6634
6635 interface cast {
6636 val: any;
6637 type: string;
6638 }
6639
6640 interface castStatic {
6641 /**
6642 * Creates a object representing a call to the cast function.
6643 *
6644 * @param val The value to cast
6645 * @param type The type to cast it to
6646 */
6647 new (val: any, type: string): cast;
6648 }
6649
6650 interface literal {
6651 val: any;
6652 }
6653
6654 interface literalStatic {
6655 /**
6656 * Creates a object representing a literal, i.e. something that will not be escaped.
6657 *
6658 * @param val
6659 */
6660 new (val: any): literal;
6661 }
6662
6663 interface and {
6664 args: any[];
6665 }
6666
6667 interface andStatic {
6668 /**
6669 * An AND query
6670 *
6671 * @param args Each argument will be joined by AND
6672 */
6673 new (...args: Array<string | Object>): and;
6674 }
6675
6676 interface or {
6677 args: any[];
6678 }
6679
6680 interface orStatic {
6681 /**
6682 * An OR query
6683 * @see {Model#find}
6684 *
6685 * @param args Each argument will be joined by OR
6686 */
6687 new (...args: Array<string | Object>): or;
6688 }
6689
6690 interface json {
6691 conditions?: Object;
6692 path?: string;
6693 value?: string | number | boolean;
6694 }
6695
6696 interface jsonStatic {
6697 /**
6698 * Creates an object representing nested where conditions for postgres's json data-type.
6699 * @see {Model#find}
6700 *
6701 * @method json
6702 * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot
6703 * notation or a string using postgres json syntax.
6704 * @param value An optional value to compare against. Produces a string of the form "<json path> =
6705 * '<value>'".
6706 */
6707 new (conditionsOrPath: string | Object, value?: string | number | boolean): json;
6708 }
6709
6710 interface where {
6711 attribute: Object;
6712 comparator?: string;
6713 logic: string | Object;
6714 }
6715
6716 interface whereStatic {
6717 /**
6718 * A way of specifying attr = condition.
6719 *
6720 * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id`
6721 * or
6722 * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can
6723 * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.)
6724 *
6725 * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your
6726 * string to be escaped, use `sequelize.literal`.
6727 *
6728 * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a
6729 * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the
6730 * POJO syntax
6731 * @param comparator Comparator
6732 * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal`
6733 * etc.)
6734 */
6735 new (attr: Object, comparator: string, logic: string | Object): where;
6736 new (attr: Object, logic: string | Object): where;
6737 }
6738
6739 interface SequelizeLoDash extends _.LoDashStatic {
6740
6741 camelizeIf(str: string, condition: boolean): string;
6742 underscoredIf(str: string, condition: boolean): string;
6743 /**
6744 * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered
6745 * falsey.
6746 *
6747 * @param arr Array to compact.
6748 */
6749 compactLite<T>(arr: T[]): T[];
6750 matchesDots(dots: string | string[], value: Object): (item: Object) => boolean;
6751
6752 }
6753
6754 interface Utils {
6755
6756 _: SequelizeLoDash;
6757
6758 /**
6759 * Same concept as _.merge, but don't overwrite properties that have already been assigned
6760 */
6761 mergeDefaults: typeof _.merge;
6762
6763 lowercaseFirst(str: string): string;
6764 uppercaseFirst(str: string): string;
6765 spliceStr(str: string, index: number, count: number, add: string): string;
6766 camelize(str: string): string;
6767 format(arr: any[], dialect?: string): string;
6768 formatNamedParameters(sql: string, parameters: any, dialect?: string): string;
6769 cloneDeep<T extends Object>(obj: T, fn?: (value: T) => any): T;
6770 mapOptionFieldNames<T extends Object>(options: T, Model: Model<any, any>): T;
6771 mapValueFieldNames(dataValues: Object, fields: string[], Model: Model<any, any>): Object;
6772 argsArePrimaryKeys(args: any[], primaryKeys: Object): boolean;
6773 canTreatArrayAsAnd(arr: any[]): boolean;
6774 combineTableNames(tableName1: string, tableName2: string): string;
6775 singularize(s: string): string;
6776 pluralize(s: string): string;
6777 removeCommentsFromFunctionString(s: string): string;
6778 toDefaultValue(value: DataTypeAbstract): any;
6779 toDefaultValue(value: () => DataTypeAbstract): any;
6780
6781 /**
6782 * Determine if the default value provided exists and can be described
6783 * in a db schema using the DEFAULT directive.
6784 */
6785 defaultValueSchemable(value: any): boolean;
6786
6787 removeNullValuesFromHash(hash: Object, omitNull?: boolean, options?: Object): any;
6788 inherit(subClass: Object, superClass: Object): Object;
6789 stack(): string;
6790 sliceArgs(args: any[], begin?: number): any[];
6791 now(dialect: string): Date;
6792 tick(f: Function): void;
6793 addTicks(s: string, tickChar?: string): string;
6794 removeTicks(s: string, tickChar?: string): string;
6795
6796 fn: fnStatic;
6797 col: colStatic;
6798 cast: castStatic;
6799 literal: literalStatic;
6800 and: andStatic;
6801 or: orStatic;
6802 json: jsonStatic;
6803 where: whereStatic;
6804
6805 validateParameter(value: Object, expectation: Object, options?: Object): boolean;
6806 formatReferences(obj: Object): Object;
6807 Promise: typeof Promise;
6808
6809 }
6810
6811}
6812
6813declare var sequelize: sequelize.SequelizeStatic;
6814
6815export = sequelize;
6816
\No newline at end of file