UNPKG

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