UNPKG

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