UNPKG

81.6 kBTypeScriptView Raw
1import {
2 Association,
3 BelongsTo,
4 BelongsToMany,
5 BelongsToManyOptions,
6 BelongsToOptions,
7 HasMany,
8 HasManyOptions,
9 HasOne,
10 HasOneOptions,
11} from './associations/index';
12import { DataType } from './data-types';
13import { Deferrable } from './deferrable';
14import { HookReturn, Hooks, ModelHooks } from './hooks';
15import { ValidationOptions } from './instance-validator';
16import { ModelManager } from './model-manager';
17import Op = require('./operators');
18import { Promise } from './promise';
19import { QueryOptions, IndexesOptions } from './query-interface';
20import { Config, Options, Sequelize, SyncOptions } from './sequelize';
21import { Transaction } from './transaction';
22import { Col, Fn, Literal, Where } from './utils';
23import { IndexHints } from '..';
24
25export interface Logging {
26 /**
27 * A function that gets executed while running the query to log the sql.
28 */
29 logging?: boolean | ((sql: string, timing?: number) => void);
30
31 /**
32 * Pass query execution time in milliseconds as second argument to logging function (options.logging).
33 */
34 benchmark?: boolean;
35}
36
37export interface Poolable {
38 /**
39 * Force the query to use the write pool, regardless of the query type.
40 *
41 * @default false
42 */
43 useMaster?: boolean;
44}
45
46export interface Transactionable {
47 /**
48 * Transaction to run query under
49 */
50 transaction?: Transaction;
51}
52
53export interface SearchPathable {
54 /**
55 * An optional parameter to specify the schema search_path (Postgres only)
56 */
57 searchPath?: string;
58}
59
60export interface Filterable {
61 /**
62 * Attribute has to be matched for rows to be selected for the given action.
63 */
64 where?: WhereOptions;
65}
66
67export interface Projectable {
68 /**
69 * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with
70 * two elements - the first is the name of the attribute in the DB (or some kind of expression such as
71 * `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to
72 * have in the returned instance
73 */
74 attributes?: FindAttributeOptions;
75}
76
77export interface Paranoid {
78 /**
79 * If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
80 * be returned. Only applies if `options.paranoid` is true for the model.
81 */
82 paranoid?: boolean;
83}
84
85export type GroupOption = string | Fn | Col | (string | Fn | Col)[];
86
87/**
88 * Options to pass to Model on drop
89 */
90export interface DropOptions extends Logging {
91 /**
92 * Also drop all objects depending on this table, such as views. Only works in postgres
93 */
94 cascade?: boolean;
95}
96
97/**
98 * Schema Options provided for applying a schema to a model
99 */
100export interface SchemaOptions extends Logging {
101 /**
102 * The character(s) that separates the schema name from the table name
103 */
104 schemaDelimiter?: string;
105}
106
107/**
108 * Scope Options for Model.scope
109 */
110export interface ScopeOptions {
111 /**
112 * The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments.
113 * To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function,
114 * pass an object, with a `method` property. The value can either be a string, if the method does not take
115 * any arguments, or an array, where the first element is the name of the method, and consecutive elements
116 * are arguments to that method. Pass null to remove all scopes, including the default.
117 */
118 method: string | [string, ...unknown[]];
119}
120
121/**
122 * The type accepted by every `where` option
123 */
124export type WhereOptions = WhereAttributeHash | AndOperator | OrOperator | Literal | Where;
125
126/**
127 * Example: `[Op.any]: [2,3]` becomes `ANY ARRAY[2, 3]::INTEGER`
128 *
129 * _PG only_
130 */
131export interface AnyOperator {
132 [Op.any]: (string | number)[];
133}
134
135/** Undocumented? */
136export interface AllOperator {
137 [Op.all]: (string | number | Date | Literal)[];
138}
139
140export type Rangable = [number, number] | [Date, Date] | Literal;
141
142/**
143 * Operators that can be used in WhereOptions
144 *
145 * See https://sequelize.org/master/en/v3/docs/querying/#operators
146 */
147export interface WhereOperators {
148 /**
149 * Example: `[Op.any]: [2,3]` becomes `ANY ARRAY[2, 3]::INTEGER`
150 *
151 * _PG only_
152 */
153 [Op.any]?: (string | number | Literal)[] | Literal;
154
155 /** Example: `[Op.gte]: 6,` becomes `>= 6` */
156 [Op.gte]?: number | string | Date | Literal;
157
158 /** Example: `[Op.lt]: 10,` becomes `< 10` */
159 [Op.lt]?: number | string | Date | Literal;
160
161 /** Example: `[Op.lte]: 10,` becomes `<= 10` */
162 [Op.lte]?: number | string | Date | Literal;
163
164 /** Example: `[Op.ne]: 20,` becomes `!= 20` */
165 [Op.ne]?: string | number | Literal | WhereOperators;
166
167 /** Example: `[Op.not]: true,` becomes `IS NOT TRUE` */
168 [Op.not]?: boolean | string | number | Literal | WhereOperators;
169
170 /** Example: `[Op.between]: [6, 10],` becomes `BETWEEN 6 AND 10` */
171 [Op.between]?: [number, number];
172
173 /** Example: `[Op.in]: [1, 2],` becomes `IN [1, 2]` */
174 [Op.in]?: (string | number | Literal)[] | Literal;
175
176 /** Example: `[Op.notIn]: [1, 2],` becomes `NOT IN [1, 2]` */
177 [Op.notIn]?: (string | number | Literal)[] | Literal;
178
179 /**
180 * Examples:
181 * - `[Op.like]: '%hat',` becomes `LIKE '%hat'`
182 * - `[Op.like]: { [Op.any]: ['cat', 'hat']}` becomes `LIKE ANY ARRAY['cat', 'hat']`
183 */
184 [Op.like]?: string | Literal | AnyOperator | AllOperator;
185
186 /**
187 * Examples:
188 * - `[Op.notLike]: '%hat'` becomes `NOT LIKE '%hat'`
189 * - `[Op.notLike]: { [Op.any]: ['cat', 'hat']}` becomes `NOT LIKE ANY ARRAY['cat', 'hat']`
190 */
191 [Op.notLike]?: string | Literal | AnyOperator | AllOperator;
192
193 /**
194 * case insensitive PG only
195 *
196 * Examples:
197 * - `[Op.iLike]: '%hat'` becomes `ILIKE '%hat'`
198 * - `[Op.iLike]: { [Op.any]: ['cat', 'hat']}` becomes `ILIKE ANY ARRAY['cat', 'hat']`
199 */
200 [Op.iLike]?: string | Literal | AnyOperator | AllOperator;
201
202 /**
203 * PG array overlap operator
204 *
205 * Example: `[Op.overlap]: [1, 2]` becomes `&& [1, 2]`
206 */
207 [Op.overlap]?: Rangable;
208
209 /**
210 * PG array contains operator
211 *
212 * Example: `[Op.contains]: [1, 2]` becomes `@> [1, 2]`
213 */
214 [Op.contains]?: (string | number)[] | Rangable;
215
216 /**
217 * PG array contained by operator
218 *
219 * Example: `[Op.contained]: [1, 2]` becomes `<@ [1, 2]`
220 */
221 [Op.contained]?: (string | number)[] | Rangable;
222
223 /** Example: `[Op.gt]: 6,` becomes `> 6` */
224 [Op.gt]?: number | string | Date | Literal;
225
226 /**
227 * PG only
228 *
229 * Examples:
230 * - `[Op.notILike]: '%hat'` becomes `NOT ILIKE '%hat'`
231 * - `[Op.notLike]: ['cat', 'hat']` becomes `LIKE ANY ARRAY['cat', 'hat']`
232 */
233 [Op.notILike]?: string | Literal | AnyOperator | AllOperator;
234
235 /** Example: `[Op.notBetween]: [11, 15],` becomes `NOT BETWEEN 11 AND 15` */
236 [Op.notBetween]?: [number, number];
237
238 /**
239 * Strings starts with value.
240 */
241 [Op.startsWith]?: string;
242
243 /**
244 * String ends with value.
245 */
246 [Op.endsWith]?: string;
247 /**
248 * String contains value.
249 */
250 [Op.substring]?: string;
251
252 /**
253 * MySQL/PG only
254 *
255 * Matches regular expression, case sensitive
256 *
257 * Example: `[Op.regexp]: '^[h|a|t]'` becomes `REGEXP/~ '^[h|a|t]'`
258 */
259 [Op.regexp]?: string;
260
261 /**
262 * MySQL/PG only
263 *
264 * Does not match regular expression, case sensitive
265 *
266 * Example: `[Op.notRegexp]: '^[h|a|t]'` becomes `NOT REGEXP/!~ '^[h|a|t]'`
267 */
268 [Op.notRegexp]?: string;
269
270 /**
271 * PG only
272 *
273 * Matches regular expression, case insensitive
274 *
275 * Example: `[Op.iRegexp]: '^[h|a|t]'` becomes `~* '^[h|a|t]'`
276 */
277 [Op.iRegexp]?: string;
278
279 /**
280 * PG only
281 *
282 * Does not match regular expression, case insensitive
283 *
284 * Example: `[Op.notIRegexp]: '^[h|a|t]'` becomes `!~* '^[h|a|t]'`
285 */
286 [Op.notIRegexp]?: string;
287
288 /**
289 * PG only
290 *
291 * Forces the operator to be strictly left eg. `<< [a, b)`
292 */
293 [Op.strictLeft]?: Rangable;
294
295 /**
296 * PG only
297 *
298 * Forces the operator to be strictly right eg. `>> [a, b)`
299 */
300 [Op.strictRight]?: Rangable;
301
302 /**
303 * PG only
304 *
305 * Forces the operator to not extend the left eg. `&> [1, 2)`
306 */
307 [Op.noExtendLeft]?: Rangable;
308
309 /**
310 * PG only
311 *
312 * Forces the operator to not extend the left eg. `&< [1, 2)`
313 */
314 [Op.noExtendRight]?: Rangable;
315
316}
317
318/** Example: `[Op.or]: [{a: 5}, {a: 6}]` becomes `(a = 5 OR a = 6)` */
319export interface OrOperator {
320 [Op.or]: WhereOptions | WhereOptions[] | WhereValue | WhereValue[];
321}
322
323/** Example: `[Op.and]: {a: 5}` becomes `AND (a = 5)` */
324export interface AndOperator {
325 [Op.and]: WhereOptions | WhereOptions[] | WhereValue | WhereValue[];
326}
327
328/**
329 * Where Geometry Options
330 */
331export interface WhereGeometryOptions {
332 type: string;
333 coordinates: (number[] | number)[];
334}
335
336/**
337 * Used for the right hand side of WhereAttributeHash.
338 * WhereAttributeHash is in there for JSON columns.
339 */
340export type WhereValue =
341 | string // literal value
342 | number // literal value
343 | boolean // literal value
344 | Buffer // literal value
345 | null
346 | WhereOperators
347 | WhereAttributeHash // for JSON columns
348 | Col // reference another column
349 | Fn
350 | OrOperator
351 | AndOperator
352 | WhereGeometryOptions
353 | (string | number | Buffer | WhereAttributeHash)[]; // implicit [Op.or]
354
355/**
356 * A hash of attributes to describe your search.
357 */
358export interface WhereAttributeHash {
359 /**
360 * Possible key values:
361 * - A simple attribute name
362 * - A nested key for JSON columns
363 *
364 * {
365 * "meta.audio.length": {
366 * [Op.gt]: 20
367 * }
368 * }
369 */
370 [field: string]: WhereValue | WhereOptions;
371}
372/**
373 * Through options for Include Options
374 */
375export interface IncludeThroughOptions extends Filterable, Projectable {}
376
377/**
378 * Options for eager-loading associated models, also allowing for all associations to be loaded at once
379 */
380export type Includeable = typeof Model | Association | IncludeOptions | { all: true } | string;
381
382/**
383 * Complex include options
384 */
385export interface IncludeOptions extends Filterable, Projectable, Paranoid {
386 /**
387 * Mark the include as duplicating, will prevent a subquery from being used.
388 */
389 duplicating?: boolean;
390 /**
391 * The model you want to eagerly load
392 */
393 model?: typeof Model;
394
395 /**
396 * The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` /
397 * `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
398 */
399 as?: string;
400
401 /**
402 * The association you want to eagerly load. (This can be used instead of providing a model/as pair)
403 */
404 association?: Association | string;
405
406 /**
407 * Custom `on` clause, overrides default.
408 */
409 on?: WhereOptions;
410
411 /**
412 * Note that this converts the eager load to an inner join,
413 * unless you explicitly set `required: false`
414 */
415 where?: WhereOptions;
416
417 /**
418 * If true, converts to an inner join, which means that the parent model will only be loaded if it has any
419 * matching children. True if `include.where` is set, false otherwise.
420 */
421 required?: boolean;
422
423 /**
424 * If true, converts to a right join if dialect support it. Ignored if `include.required` is true.
425 */
426 right?: boolean;
427
428 /**
429 * Limit include. Only available when setting `separate` to true.
430 */
431 limit?: number;
432
433 /**
434 * Run include in separate queries.
435 */
436 separate?: boolean;
437
438 /**
439 * Through Options
440 */
441 through?: IncludeThroughOptions;
442
443 /**
444 * Load further nested related models
445 */
446 include?: Includeable[];
447
448 /**
449 * Order include. Only available when setting `separate` to true.
450 */
451 order?: Order;
452
453 /**
454 * Use sub queries. This should only be used if you know for sure the query does not result in a cartesian product.
455 */
456 subQuery?: boolean;
457}
458
459type OrderItemModel = typeof Model | { model: typeof Model; as: string } | string
460type OrderItemColumn = string | Col | Fn | Literal
461export type OrderItem =
462 | string
463 | Fn
464 | Col
465 | Literal
466 | [OrderItemColumn, string]
467 | [OrderItemModel, OrderItemColumn]
468 | [OrderItemModel, OrderItemColumn, string]
469 | [OrderItemModel, OrderItemModel, OrderItemColumn]
470 | [OrderItemModel, OrderItemModel, OrderItemColumn, string]
471 | [OrderItemModel, OrderItemModel, OrderItemModel, OrderItemColumn]
472 | [OrderItemModel, OrderItemModel, OrderItemModel, OrderItemColumn, string]
473 | [OrderItemModel, OrderItemModel, OrderItemModel, OrderItemModel, OrderItemColumn]
474 | [OrderItemModel, OrderItemModel, OrderItemModel, OrderItemModel, OrderItemColumn, string]
475export type Order = string | Fn | Col | Literal | OrderItem[];
476
477/**
478 * Please note if this is used the aliased property will not be available on the model instance
479 * as a property but only via `instance.get('alias')`.
480 */
481export type ProjectionAlias = [string | Literal | Fn, string];
482
483export type FindAttributeOptions =
484 | (string | ProjectionAlias)[]
485 | {
486 exclude: string[];
487 include?: (string | ProjectionAlias)[];
488 }
489 | {
490 exclude?: string[];
491 include: (string | ProjectionAlias)[];
492 };
493
494export interface IndexHint {
495 type: IndexHints;
496 values: string[];
497}
498
499export interface IndexHintable {
500 /**
501 * MySQL only.
502 */
503 indexHints?: IndexHint[];
504}
505
506type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
507
508/**
509 * Options that are passed to any model creating a SELECT query
510 *
511 * A hash of options to describe the scope of the search
512 */
513export interface FindOptions extends QueryOptions, Filterable, Projectable, Paranoid, IndexHintable {
514 /**
515 * A list of associations to eagerly load using a left join. Supported is either
516 * `{ include: [ Model1, Model2, ...]}`, `{ include: [{ model: Model1, as: 'Alias' }]}` or
517 * `{ include: [{ all: true }]}`.
518 * If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in
519 * the as attribute when eager loading Y).
520 */
521 include?: Includeable[];
522
523 /**
524 * Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide
525 * several columns / functions to order by. Each element can be further wrapped in a two-element array. The
526 * first element is the column / function to order by, the second is the direction. For example:
527 * `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
528 */
529 order?: Order;
530
531 /**
532 * GROUP BY in sql
533 */
534 group?: GroupOption;
535
536 /**
537 * Limit the results
538 */
539 limit?: number;
540
541 /**
542 * Skip the results;
543 */
544 offset?: number;
545
546 /**
547 * Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE.
548 * Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model
549 * locks with joins. See [transaction.LOCK for an example](transaction#lock)
550 */
551 lock?: Transaction.LOCK | { level: Transaction.LOCK; of: typeof Model };
552
553 /**
554 * Skip locked rows. Only supported in Postgres.
555 */
556 skipLocked?: boolean;
557
558 /**
559 * Return raw result. See sequelize.query for more information.
560 */
561 raw?: boolean;
562
563 /**
564 * Select group rows after groups and aggregates are computed.
565 */
566 having?: WhereOptions;
567
568 /**
569 * Use sub queries (internal)
570 */
571 subQuery?: boolean;
572}
573
574export interface NonNullFindOptions extends FindOptions {
575 /**
576 * Throw if nothing was found.
577 */
578 rejectOnEmpty: boolean | Error;
579}
580
581/**
582 * Options for Model.count method
583 */
584export interface CountOptions extends Logging, Transactionable, Filterable, Projectable, Paranoid, Poolable {
585 /**
586 * Include options. See `find` for details
587 */
588 include?: Includeable[];
589
590 /**
591 * Apply COUNT(DISTINCT(col))
592 */
593 distinct?: boolean;
594
595 /**
596 * GROUP BY in sql
597 * Used in conjunction with `attributes`.
598 * @see Projectable
599 */
600 group?: GroupOption;
601
602 /**
603 * The column to aggregate on.
604 */
605 col?: string;
606}
607
608/**
609 * Options for Model.count when GROUP BY is used
610 */
611export interface CountWithOptions extends CountOptions {
612 /**
613 * GROUP BY in sql
614 * Used in conjunction with `attributes`.
615 * @see Projectable
616 */
617 group: GroupOption;
618}
619
620export interface FindAndCountOptions extends CountOptions, FindOptions {}
621
622/**
623 * Options for Model.build method
624 */
625export interface BuildOptions {
626 /**
627 * If set to true, values will ignore field and virtual setters.
628 */
629 raw?: boolean;
630
631 /**
632 * Is this record new
633 */
634 isNewRecord?: boolean;
635
636 /**
637 * an array of include options - Used to build prefetched/included model instances. See `set`
638 *
639 * TODO: See set
640 */
641 include?: Includeable[];
642}
643
644export interface Silent {
645 /**
646 * If true, the updatedAt timestamp will not be updated.
647 *
648 * @default false
649 */
650 silent?: boolean;
651}
652
653/**
654 * Options for Model.create method
655 */
656export interface CreateOptions extends BuildOptions, Logging, Silent, Transactionable {
657 /**
658 * If set, only columns matching those in fields will be saved
659 */
660 fields?: string[];
661
662 /**
663 * On Duplicate
664 */
665 onDuplicate?: string;
666
667 /**
668 * If false, validations won't be run.
669 *
670 * @default true
671 */
672 validate?: boolean;
673}
674
675/**
676 * Options for Model.findOrCreate method
677 */
678export interface FindOrCreateOptions extends Logging, Transactionable {
679 /**
680 * A hash of search attributes.
681 */
682 where: WhereOptions;
683
684 /**
685 * Default values to use if building a new instance
686 */
687 defaults?: object;
688}
689
690/**
691 * Options for Model.upsert method
692 */
693export interface UpsertOptions extends Logging, Transactionable, SearchPathable {
694 /**
695 * The fields to insert / update. Defaults to all fields
696 */
697 fields?: string[];
698
699 /**
700 * Run before / after bulk create hooks?
701 */
702 hooks?: boolean;
703
704 /**
705 * Return the affected rows (only for postgres)
706 */
707 returning?: boolean;
708
709 /**
710 * Run validations before the row is inserted
711 */
712 validate?: boolean;
713}
714
715/**
716 * Options for Model.bulkCreate method
717 */
718export interface BulkCreateOptions extends Logging, Transactionable {
719 /**
720 * Fields to insert (defaults to all fields)
721 */
722 fields?: string[];
723
724 /**
725 * Should each row be subject to validation before it is inserted. The whole insert will fail if one row
726 * fails validation
727 */
728 validate?: boolean;
729
730 /**
731 * Run before / after bulk create hooks?
732 */
733 hooks?: boolean;
734
735 /**
736 * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if
737 * options.hooks is true.
738 */
739 individualHooks?: boolean;
740
741 /**
742 * Ignore duplicate values for primary keys? (not supported by postgres)
743 *
744 * @default false
745 */
746 ignoreDuplicates?: boolean;
747
748 /**
749 * Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL,
750 * MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5). By default, all fields are updated.
751 */
752 updateOnDuplicate?: string[];
753
754 /**
755 * Include options. See `find` for details
756 */
757 include?: Includeable[];
758
759 /**
760 * Return all columns or only the specified columns for the affected rows (only for postgres)
761 */
762 returning?: boolean | string[];
763}
764
765/**
766 * The options passed to Model.destroy in addition to truncate
767 */
768export interface TruncateOptions extends Logging, Transactionable, Filterable {
769 /**
770 * Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the
771 * named table, or to any tables added to the group due to CASCADE.
772 *
773 * @default false;
774 */
775 cascade?: boolean;
776
777 /**
778 * Run before / after bulk destroy hooks?
779 */
780 hooks?: boolean;
781
782 /**
783 * If set to true, destroy will SELECT all records matching the where parameter and will execute before /
784 * after destroy hooks on each row
785 */
786 individualHooks?: boolean;
787
788 /**
789 * How many rows to delete
790 */
791 limit?: number;
792
793 /**
794 * Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
795 */
796 force?: boolean;
797
798 /**
799 * Only used in conjunction with `truncate`.
800 * Automatically restart sequences owned by columns of the truncated table
801 */
802 restartIdentity?: boolean;
803}
804
805/**
806 * Options used for Model.destroy
807 */
808export interface DestroyOptions extends TruncateOptions {
809 /**
810 * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is
811 * truncated the where and limit options are ignored
812 */
813 truncate?: boolean;
814}
815
816/**
817 * Options for Model.restore
818 */
819export interface RestoreOptions extends Logging, Transactionable, Filterable {
820 /**
821 * Run before / after bulk restore hooks?
822 */
823 hooks?: boolean;
824
825 /**
826 * If set to true, restore will find all records within the where parameter and will execute before / after
827 * bulkRestore hooks on each row
828 */
829 individualHooks?: boolean;
830
831 /**
832 * How many rows to undelete
833 */
834 limit?: number;
835}
836
837/**
838 * Options used for Model.update
839 */
840export interface UpdateOptions extends Logging, Transactionable {
841 /**
842 * Options to describe the scope of the search.
843 */
844 where: WhereOptions;
845
846 /**
847 * Fields to update (defaults to all fields)
848 */
849 fields?: string[];
850
851 /**
852 * Should each row be subject to validation before it is inserted. The whole insert will fail if one row
853 * fails validation.
854 *
855 * @default true
856 */
857 validate?: boolean;
858
859 /**
860 * Run before / after bulk update hooks?
861 *
862 * @default true
863 */
864 hooks?: boolean;
865
866 /**
867 * Whether or not to update the side effects of any virtual setters.
868 *
869 * @default true
870 */
871 sideEffects?: boolean;
872
873 /**
874 * Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs.
875 * A select is needed, because the row data needs to be passed to the hooks
876 *
877 * @default false
878 */
879 individualHooks?: boolean;
880
881 /**
882 * Return the affected rows (only for postgres)
883 */
884 returning?: boolean;
885
886 /**
887 * How many rows to update (only for mysql and mariadb)
888 */
889 limit?: number;
890
891 /**
892 * If true, the updatedAt timestamp will not be updated.
893 */
894 silent?: boolean;
895}
896
897/**
898 * Options used for Model.aggregate
899 */
900export interface AggregateOptions<T extends DataType | unknown> extends QueryOptions, Filterable, Paranoid {
901 /**
902 * The type of the result. If `field` is a field in this Model, the default will be the type of that field,
903 * otherwise defaults to float.
904 */
905 dataType?: string | T;
906
907 /**
908 * Applies DISTINCT to the field being aggregated over
909 */
910 distinct?: boolean;
911}
912
913// instance
914
915/**
916 * Options used for Instance.increment method
917 */
918export interface IncrementDecrementOptions extends Logging, Transactionable, Silent, SearchPathable, Filterable {}
919
920/**
921 * Options used for Instance.increment method
922 */
923export interface IncrementDecrementOptionsWithBy extends IncrementDecrementOptions {
924 /**
925 * The number to increment by
926 *
927 * @default 1
928 */
929 by?: number;
930}
931
932/**
933 * Options used for Instance.restore method
934 */
935export interface InstanceRestoreOptions extends Logging, Transactionable {}
936
937/**
938 * Options used for Instance.destroy method
939 */
940export interface InstanceDestroyOptions extends Logging, Transactionable {
941 /**
942 * If set to true, paranoid models will actually be deleted
943 */
944 force?: boolean;
945}
946
947/**
948 * Options used for Instance.update method
949 */
950export interface InstanceUpdateOptions extends SaveOptions, SetOptions, Filterable {}
951
952/**
953 * Options used for Instance.set method
954 */
955export interface SetOptions {
956 /**
957 * If set to true, field and virtual setters will be ignored
958 */
959 raw?: boolean;
960
961 /**
962 * Clear all previously set data values
963 */
964 reset?: boolean;
965}
966
967/**
968 * Options used for Instance.save method
969 */
970export interface SaveOptions extends Logging, Transactionable, Silent {
971 /**
972 * An optional array of strings, representing database columns. If fields is provided, only those columns
973 * will be validated and saved.
974 */
975 fields?: string[];
976
977 /**
978 * If false, validations won't be run.
979 *
980 * @default true
981 */
982 validate?: boolean;
983}
984
985/**
986 * Model validations, allow you to specify format/content/inheritance validations for each attribute of the
987 * model.
988 *
989 * Validations are automatically run on create, update and save. You can also call validate() to manually
990 * validate an instance.
991 *
992 * The validations are implemented by validator.js.
993 */
994export interface ModelValidateOptions {
995 /**
996 * is: ["^[a-z]+$",'i'] // will only allow letters
997 * is: /^[a-z]+[Op./i] // same as the previous example using real RegExp
998 */
999 is?: string | (string | RegExp)[] | RegExp | { msg: string; args: string | (string | RegExp)[] | RegExp };
1000
1001 /**
1002 * not: ["[a-z]",'i'] // will not allow letters
1003 */
1004 not?: string | (string | RegExp)[] | RegExp | { msg: string; args: string | (string | RegExp)[] | RegExp };
1005
1006 /**
1007 * checks for email format (foo@bar.com)
1008 */
1009 isEmail?: boolean | { msg: string };
1010
1011 /**
1012 * checks for url format (http://foo.com)
1013 */
1014 isUrl?: boolean | { msg: string };
1015
1016 /**
1017 * checks for IPv4 (129.89.23.1) or IPv6 format
1018 */
1019 isIP?: boolean | { msg: string };
1020
1021 /**
1022 * checks for IPv4 (129.89.23.1)
1023 */
1024 isIPv4?: boolean | { msg: string };
1025
1026 /**
1027 * checks for IPv6 format
1028 */
1029 isIPv6?: boolean | { msg: string };
1030
1031 /**
1032 * will only allow letters
1033 */
1034 isAlpha?: boolean | { msg: string };
1035
1036 /**
1037 * will only allow alphanumeric characters, so "_abc" will fail
1038 */
1039 isAlphanumeric?: boolean | { msg: string };
1040
1041 /**
1042 * will only allow numbers
1043 */
1044 isNumeric?: boolean | { msg: string };
1045
1046 /**
1047 * checks for valid integers
1048 */
1049 isInt?: boolean | { msg: string };
1050
1051 /**
1052 * checks for valid floating point numbers
1053 */
1054 isFloat?: boolean | { msg: string };
1055
1056 /**
1057 * checks for any numbers
1058 */
1059 isDecimal?: boolean | { msg: string };
1060
1061 /**
1062 * checks for lowercase
1063 */
1064 isLowercase?: boolean | { msg: string };
1065
1066 /**
1067 * checks for uppercase
1068 */
1069 isUppercase?: boolean | { msg: string };
1070
1071 /**
1072 * won't allow null
1073 */
1074 notNull?: boolean | { msg: string };
1075
1076 /**
1077 * only allows null
1078 */
1079 isNull?: boolean | { msg: string };
1080
1081 /**
1082 * don't allow empty strings
1083 */
1084 notEmpty?: boolean | { msg: string };
1085
1086 /**
1087 * only allow a specific value
1088 */
1089 equals?: string | { msg: string };
1090
1091 /**
1092 * force specific substrings
1093 */
1094 contains?: string | { msg: string };
1095
1096 /**
1097 * check the value is not one of these
1098 */
1099 notIn?: string[][] | { msg: string; args: string[][] };
1100
1101 /**
1102 * check the value is one of these
1103 */
1104 isIn?: string[][] | { msg: string; args: string[][] };
1105
1106 /**
1107 * don't allow specific substrings
1108 */
1109 notContains?: string[] | string | { msg: string; args: string[] | string };
1110
1111 /**
1112 * only allow values with length between 2 and 10
1113 */
1114 len?: [number, number] | { msg: string; args: [number, number] };
1115
1116 /**
1117 * only allow uuids
1118 */
1119 isUUID?: number | { msg: string; args: number };
1120
1121 /**
1122 * only allow date strings
1123 */
1124 isDate?: boolean | { msg: string; args: boolean };
1125
1126 /**
1127 * only allow date strings after a specific date
1128 */
1129 isAfter?: string | { msg: string; args: string };
1130
1131 /**
1132 * only allow date strings before a specific date
1133 */
1134 isBefore?: string | { msg: string; args: string };
1135
1136 /**
1137 * only allow values
1138 */
1139 max?: number | { msg: string; args: [number] };
1140
1141 /**
1142 * only allow values >= 23
1143 */
1144 min?: number | { msg: string; args: [number] };
1145
1146 /**
1147 * only allow arrays
1148 */
1149 isArray?: boolean | { msg: string; args: boolean };
1150
1151 /**
1152 * check for valid credit card numbers
1153 */
1154 isCreditCard?: boolean | { msg: string; args: boolean };
1155
1156 /**
1157 * custom validations are also possible
1158 *
1159 * Implementation notes :
1160 *
1161 * We can't enforce any other method to be a function, so :
1162 *
1163 * ```typescript
1164 * [name: string] : ( value : unknown ) => boolean;
1165 * ```
1166 *
1167 * doesn't work in combination with the properties above
1168 *
1169 * @see https://github.com/Microsoft/TypeScript/issues/1889
1170 */
1171 [name: string]: unknown;
1172}
1173
1174/**
1175 * Interface for indexes property in InitOptions
1176 */
1177export type ModelIndexesOptions = IndexesOptions
1178
1179/**
1180 * Interface for name property in InitOptions
1181 */
1182export interface ModelNameOptions {
1183 /**
1184 * Singular model name
1185 */
1186 singular?: string;
1187
1188 /**
1189 * Plural model name
1190 */
1191 plural?: string;
1192}
1193
1194/**
1195 * Interface for getterMethods in InitOptions
1196 */
1197export interface ModelGetterOptions<M extends Model = Model> {
1198 [name: string]: (this: M) => unknown;
1199}
1200
1201/**
1202 * Interface for setterMethods in InitOptions
1203 */
1204export interface ModelSetterOptions<M extends Model = Model> {
1205 [name: string]: (this: M, val: any) => void;
1206}
1207
1208/**
1209 * Interface for Define Scope Options
1210 */
1211export interface ModelScopeOptions {
1212 /**
1213 * Name of the scope and it's query
1214 */
1215 [scopeName: string]: FindOptions | ((...args: any[]) => FindOptions);
1216}
1217
1218/**
1219 * General column options
1220 */
1221export interface ColumnOptions {
1222 /**
1223 * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an
1224 * instance is saved.
1225 * @default true
1226 */
1227 allowNull?: boolean;
1228
1229 /**
1230 * If set, sequelize will map the attribute name to a different name in the database
1231 */
1232 field?: string;
1233
1234 /**
1235 * A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
1236 */
1237 defaultValue?: unknown;
1238}
1239
1240/**
1241 * References options for the column's attributes
1242 */
1243export interface ModelAttributeColumnReferencesOptions {
1244 /**
1245 * If this column references another table, provide it here as a Model, or a string
1246 */
1247 model?: string | typeof Model;
1248
1249 /**
1250 * The column of the foreign table that this column references
1251 */
1252 key?: string;
1253
1254 /**
1255 * When to check for the foreign key constraing
1256 *
1257 * PostgreSQL only
1258 */
1259 deferrable?: Deferrable;
1260}
1261
1262/**
1263 * Column options for the model schema attributes
1264 */
1265export interface ModelAttributeColumnOptions extends ColumnOptions {
1266 /**
1267 * A string or a data type
1268 */
1269 type: DataType;
1270
1271 /**
1272 * If true, the column will get a unique constraint. If a string is provided, the column will be part of a
1273 * composite unique index. If multiple columns have the same string, they will be part of the same unique
1274 * index
1275 */
1276 unique?: boolean | string | { name: string; msg: string };
1277
1278 /**
1279 * Primary key flag
1280 */
1281 primaryKey?: boolean;
1282
1283 /**
1284 * Is this field an auto increment field
1285 */
1286 autoIncrement?: boolean;
1287
1288 /**
1289 * If this field is a Postgres auto increment field, use Postgres `GENERATED BY DEFAULT AS IDENTITY` instead of `SERIAL`. Postgres 10+ only.
1290 */
1291 autoIncrementIdentity?: boolean;
1292
1293 /**
1294 * Comment for the database
1295 */
1296 comment?: string;
1297
1298 /**
1299 * An object with reference configurations
1300 */
1301 references?: ModelAttributeColumnReferencesOptions;
1302
1303 /**
1304 * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
1305 * NO ACTION
1306 */
1307 onUpdate?: string;
1308
1309 /**
1310 * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
1311 * NO ACTION
1312 */
1313 onDelete?: string;
1314
1315
1316 /**
1317 * An object of validations to execute for this column every time the model is saved. Can be either the
1318 * name of a validation provided by validator.js, a validation function provided by extending validator.js
1319 * (see the
1320 * `DAOValidator` property for more details), or a custom validation function. Custom validation functions
1321 * are called with the value of the field, and can possibly take a second callback argument, to signal that
1322 * they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it
1323 * it is async, the callback should be called with the error text.
1324 */
1325 validate?: ModelValidateOptions;
1326
1327 /**
1328 * Usage in object notation
1329 *
1330 * ```js
1331 * class MyModel extends Model {}
1332 * MyModel.init({
1333 * states: {
1334 * type: Sequelize.ENUM,
1335 * values: ['active', 'pending', 'deleted']
1336 * }
1337 * }, { sequelize })
1338 * ```
1339 */
1340 values?: string[];
1341
1342 /**
1343 * Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying
1344 * values.
1345 */
1346 get?(): unknown;
1347
1348 /**
1349 * Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the
1350 * underlying values.
1351 */
1352 set?(val: unknown): void;
1353}
1354
1355/**
1356 * Interface for Attributes provided for a column
1357 */
1358export interface ModelAttributes {
1359 /**
1360 * The description of a database column
1361 */
1362 [name: string]: DataType | ModelAttributeColumnOptions;
1363}
1364
1365/**
1366 * Possible types for primary keys
1367 */
1368export type Identifier = number | string | Buffer;
1369
1370/**
1371 * Options for model definition
1372 */
1373export interface ModelOptions<M extends Model = Model> {
1374 /**
1375 * Define the default search scope to use for this model. Scopes have the same form as the options passed to
1376 * find / findAll.
1377 */
1378 defaultScope?: FindOptions;
1379
1380 /**
1381 * More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about
1382 * how scopes are defined, and what you can do with them
1383 */
1384 scopes?: ModelScopeOptions;
1385
1386 /**
1387 * Don't persits null values. This means that all columns with null values will not be saved.
1388 */
1389 omitNull?: boolean;
1390
1391 /**
1392 * Adds createdAt and updatedAt timestamps to the model. Default true.
1393 */
1394 timestamps?: boolean;
1395
1396 /**
1397 * Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs
1398 * timestamps=true to work. Default false.
1399 */
1400 paranoid?: boolean;
1401
1402 /**
1403 * Converts all camelCased columns to underscored if true. Default false.
1404 */
1405 underscored?: boolean;
1406
1407 /**
1408 * Indicates if the model's table has a trigger associated with it. Default false.
1409 */
1410 hasTrigger?: boolean;
1411
1412 /**
1413 * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name.
1414 * Otherwise, the dao name will be pluralized. Default false.
1415 */
1416 freezeTableName?: boolean;
1417
1418 /**
1419 * An object with two attributes, `singular` and `plural`, which are used when this model is associated to
1420 * others.
1421 */
1422 name?: ModelNameOptions;
1423
1424 /**
1425 * Set name of the model. By default its same as Class name.
1426 */
1427 modelName?: string;
1428
1429 /**
1430 * Indexes for the provided database table
1431 */
1432 indexes?: ModelIndexesOptions[];
1433
1434 /**
1435 * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps
1436 * must be true. Not affected by underscored setting.
1437 */
1438 createdAt?: string | boolean;
1439
1440 /**
1441 * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps
1442 * must be true. Not affected by underscored setting.
1443 */
1444 deletedAt?: string | boolean;
1445
1446 /**
1447 * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps
1448 * must be true. Not affected by underscored setting.
1449 */
1450 updatedAt?: string | boolean;
1451
1452 /**
1453 * @default pluralized model name, unless freezeTableName is true, in which case it uses model name
1454 * verbatim
1455 */
1456 tableName?: string;
1457
1458 schema?: string;
1459
1460 /**
1461 * You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
1462 */
1463 engine?: string;
1464
1465 charset?: string;
1466
1467 /**
1468 * Finaly you can specify a comment for the table in MySQL and PG
1469 */
1470 comment?: string;
1471
1472 collate?: string;
1473
1474 /**
1475 * Set the initial AUTO_INCREMENT value for the table in MySQL.
1476 */
1477 initialAutoIncrement?: string;
1478
1479 /**
1480 * An object of hook function that are called before and after certain lifecycle events.
1481 * See Hooks for more information about hook
1482 * functions and their signatures. Each property can either be a function, or an array of functions.
1483 */
1484 hooks?: Partial<ModelHooks<M>>;
1485
1486 /**
1487 * An object of model wide validations. Validations have access to all model values via `this`. If the
1488 * validator function takes an argument, it is asumed to be async, and is called with a callback that
1489 * accepts an optional error.
1490 */
1491 validate?: ModelValidateOptions;
1492
1493 /**
1494 * Allows defining additional setters that will be available on model instances.
1495 */
1496 setterMethods?: ModelSetterOptions<M>;
1497
1498 /**
1499 * Allows defining additional getters that will be available on model instances.
1500 */
1501 getterMethods?: ModelGetterOptions<M>;
1502
1503 /**
1504 * Enable optimistic locking.
1505 * When enabled, sequelize will add a version count attribute to the model and throw an
1506 * OptimisticLockingError error when stale instances are saved.
1507 * - If string: Uses the named attribute.
1508 * - If boolean: Uses `version`.
1509 * @default false
1510 */
1511 version?: boolean | string;
1512}
1513
1514/**
1515 * Options passed to [[Model.init]]
1516 */
1517export interface InitOptions<M extends Model = Model> extends ModelOptions<M> {
1518 /**
1519 * The sequelize connection. Required ATM.
1520 */
1521 sequelize: Sequelize;
1522}
1523
1524/**
1525 * AddScope Options for Model.addScope
1526 */
1527export interface AddScopeOptions {
1528 /**
1529 * If a scope of the same name already exists, should it be overwritten?
1530 */
1531 override: boolean;
1532}
1533
1534export abstract class Model<T = any, T2 = any> extends Hooks {
1535 /** The name of the database table */
1536 public static readonly tableName: string;
1537
1538 /**
1539 * The name of the primary key attribute
1540 */
1541 public static readonly primaryKeyAttribute: string;
1542
1543 /**
1544 * The name of the primary key attributes
1545 */
1546 public static readonly primaryKeyAttributes: string[];
1547
1548 /**
1549 * An object hash from alias to association object
1550 */
1551 public static readonly associations: {
1552 [key: string]: Association;
1553 };
1554
1555 /**
1556 * The options that the model was initialized with
1557 */
1558 public static readonly options: InitOptions;
1559
1560 /**
1561 * The attributes of the model
1562 */
1563 public static readonly rawAttributes: { [attribute: string]: ModelAttributeColumnOptions };
1564
1565 /**
1566 * Reference to the sequelize instance the model was initialized with
1567 */
1568 public static readonly sequelize?: Sequelize;
1569
1570 /**
1571 * Initialize a model, representing a table in the DB, with attributes and options.
1572 *
1573 * The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
1574 *
1575 * ```js
1576 * Project.init({
1577 * columnA: {
1578 * type: Sequelize.BOOLEAN,
1579 * validate: {
1580 * is: ['[a-z]','i'], // will only allow letters
1581 * max: 23, // only allow values <= 23
1582 * isIn: {
1583 * args: [['en', 'zh']],
1584 * msg: "Must be English or Chinese"
1585 * }
1586 * },
1587 * field: 'column_a'
1588 * // Other attributes here
1589 * },
1590 * columnB: Sequelize.STRING,
1591 * columnC: 'MY VERY OWN COLUMN TYPE'
1592 * }, {sequelize})
1593 *
1594 * sequelize.models.modelName // The model will now be available in models under the class name
1595 * ```
1596 *
1597 * As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
1598 *
1599 * For a list of possible data types, see https://sequelize.org/master/en/latest/docs/models-definition/#data-types
1600 *
1601 * For more about getters and setters, see https://sequelize.org/master/en/latest/docs/models-definition/#getters-setters
1602 *
1603 * For more about instance and class methods, see https://sequelize.org/master/en/latest/docs/models-definition/#expansion-of-models
1604 *
1605 * For more about validation, see https://sequelize.org/master/en/latest/docs/models-definition/#validations
1606 *
1607 * @param attributes
1608 * An object, where each attribute is a column of the table. Each column can be either a DataType, a
1609 * string or a type-description object, with the properties described below:
1610 * @param options These options are merged with the default define options provided to the Sequelize constructor
1611 */
1612 public static init<M extends Model = Model>(this: ModelCtor<M>, attributes: ModelAttributes, options: InitOptions<M>): void;
1613
1614 /**
1615 * Remove attribute from model definition
1616 *
1617 * @param attribute
1618 */
1619 public static removeAttribute(attribute: string): void;
1620
1621 /**
1622 * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the
1623 * model instance (this)
1624 */
1625 public static sync(options?: SyncOptions): Promise<Model>;
1626
1627 /**
1628 * Drop the table represented by this Model
1629 *
1630 * @param options
1631 */
1632 public static drop(options?: DropOptions): Promise<void>;
1633
1634 /**
1635 * Apply a schema to this model. For postgres, this will actually place the schema in front of the table
1636 * name
1637 * - `"schema"."tableName"`, while the schema will be prepended to the table name for mysql and
1638 * sqlite - `'schema.tablename'`.
1639 *
1640 * @param schema The name of the schema
1641 * @param options
1642 */
1643 public static schema<M extends Model>(
1644 this: { new (): M } & typeof Model,
1645 schema: string,
1646 options?: SchemaOptions
1647 ): { new (): M } & typeof Model;
1648
1649 /**
1650 * Get the tablename of the model, taking schema into account. The method will return The name as a string
1651 * if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties.
1652 *
1653 * @param options The hash of options from any query. You can use one model to access tables with matching
1654 * schemas by overriding `getTableName` and using custom key/values to alter the name of the table.
1655 * (eg.
1656 * subscribers_1, subscribers_2)
1657 */
1658 public static getTableName(): string | {
1659 tableName: string;
1660 schema: string;
1661 delimiter: string;
1662 };
1663
1664 /**
1665 * Apply a scope created in `define` to the model. First let's look at how to create scopes:
1666 * ```js
1667 * class MyModel extends Model {}
1668 * MyModel.init(attributes, {
1669 * defaultScope: {
1670 * where: {
1671 * username: 'dan'
1672 * },
1673 * limit: 12
1674 * },
1675 * scopes: {
1676 * isALie: {
1677 * where: {
1678 * stuff: 'cake'
1679 * }
1680 * },
1681 * complexFunction(email, accessLevel) {
1682 * return {
1683 * where: {
1684 * email: {
1685 * [Op.like]: email
1686 * },
1687 * accesss_level {
1688 * [Op.gte]: accessLevel
1689 * }
1690 * }
1691 * }
1692 * }
1693 * },
1694 * sequelize,
1695 * })
1696 * ```
1697 * Now, since you defined a default scope, every time you do Model.find, the default scope is appended to
1698 * your query. Here's a couple of examples:
1699 * ```js
1700 * Model.findAll() // WHERE username = 'dan'
1701 * Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
1702 * ```
1703 *
1704 * To invoke scope functions you can do:
1705 * ```js
1706 * Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
1707 * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
1708 * ```
1709 *
1710 * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned
1711 * model will clear the previous scope.
1712 */
1713 public static scope<M extends { new (): Model }>(
1714 this: M,
1715 options?: string | ScopeOptions | (string | ScopeOptions)[] | WhereAttributeHash
1716 ): M;
1717
1718 /**
1719 * Add a new scope to the model
1720 *
1721 * This is especially useful for adding scopes with includes, when the model you want to
1722 * include is not available at the time this model is defined. By default this will throw an
1723 * error if a scope with that name already exists. Pass `override: true` in the options
1724 * object to silence this error.
1725 */
1726 public static addScope(name: string, scope: FindOptions, options?: AddScopeOptions): void;
1727 public static addScope(name: string, scope: (...args: any[]) => FindOptions, options?: AddScopeOptions): void;
1728
1729 /**
1730 * Search for multiple instances.
1731 *
1732 * __Simple search using AND and =__
1733 * ```js
1734 * Model.findAll({
1735 * where: {
1736 * attr1: 42,
1737 * attr2: 'cake'
1738 * }
1739 * })
1740 * ```
1741 * ```sql
1742 * WHERE attr1 = 42 AND attr2 = 'cake'
1743 * ```
1744 *
1745 * __Using greater than, less than etc.__
1746 * ```js
1747 *
1748 * Model.findAll({
1749 * where: {
1750 * attr1: {
1751 * gt: 50
1752 * },
1753 * attr2: {
1754 * lte: 45
1755 * },
1756 * attr3: {
1757 * in: [1,2,3]
1758 * },
1759 * attr4: {
1760 * ne: 5
1761 * }
1762 * }
1763 * })
1764 * ```
1765 * ```sql
1766 * WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
1767 * ```
1768 * Possible options are: `[Op.ne], [Op.in], [Op.not], [Op.notIn], [Op.gte], [Op.gt], [Op.lte], [Op.lt], [Op.like], [Op.ilike]/[Op.iLike], [Op.notLike],
1769 * [Op.notILike], '..'/[Op.between], '!..'/[Op.notBetween], '&&'/[Op.overlap], '@>'/[Op.contains], '<@'/[Op.contained]`
1770 *
1771 * __Queries using OR__
1772 * ```js
1773 * Model.findAll({
1774 * where: Sequelize.and(
1775 * { name: 'a project' },
1776 * Sequelize.or(
1777 * { id: [1,2,3] },
1778 * { id: { gt: 10 } }
1779 * )
1780 * )
1781 * })
1782 * ```
1783 * ```sql
1784 * WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
1785 * ```
1786 *
1787 * The success listener is called with an array of instances if the query succeeds.
1788 *
1789 * @see {Sequelize#query}
1790 */
1791 public static findAll<M extends Model>(this: { new (): M } & typeof Model, options?: FindOptions): Promise<M[]>;
1792
1793 /**
1794 * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will
1795 * always be called with a single instance.
1796 */
1797 public static findByPk<M extends Model>(
1798 this: { new (): M } & typeof Model,
1799 identifier?: Identifier,
1800 options?: Omit<FindOptions, 'where'>
1801 ): Promise<M | null>;
1802 public static findByPk<M extends Model>(
1803 this: { new (): M } & typeof Model,
1804 identifier: Identifier,
1805 options: Omit<NonNullFindOptions, 'where'>
1806 ): Promise<M>;
1807
1808 /**
1809 * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single
1810 * instance.
1811 */
1812 public static findOne<M extends Model>(
1813 this: { new (): M } & typeof Model,
1814 options?: FindOptions
1815 ): Promise<M | null>;
1816 public static findOne<M extends Model>(this: { new (): M } & typeof Model, options: NonNullFindOptions): Promise<M>;
1817
1818 /**
1819 * Run an aggregation method on the specified field
1820 *
1821 * @param field The field to aggregate over. Can be a field name or *
1822 * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc.
1823 * @param options Query options. See sequelize.query for full options
1824 * @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in
1825 * which case the complete data result is returned.
1826 */
1827 public static aggregate<M extends Model, T extends DataType | unknown>(
1828 this: { new (): M } & typeof Model,
1829 field: keyof M,
1830 aggregateFunction: string,
1831 options?: AggregateOptions<T>
1832 ): Promise<T>;
1833
1834 /**
1835 * Count number of records if group by is used
1836 */
1837 public static count(options: CountWithOptions): Promise<{ [key: string]: number }>;
1838
1839 /**
1840 * Count the number of records matching the provided where clause.
1841 *
1842 * If you provide an `include` option, the number of matching associations will be counted instead.
1843 */
1844 public static count(options?: CountOptions): Promise<number>;
1845
1846 /**
1847 * Find all the rows matching your query, within a specified offset / limit, and get the total number of
1848 * rows matching your query. This is very usefull for paging
1849 *
1850 * ```js
1851 * Model.findAndCountAll({
1852 * where: ...,
1853 * limit: 12,
1854 * offset: 12
1855 * }).then(result => {
1856 * ...
1857 * })
1858 * ```
1859 * In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return
1860 * the
1861 * total number of rows that matched your query.
1862 *
1863 * When you add includes, only those which are required (either because they have a where clause, or
1864 * because
1865 * `required` is explicitly set to true on the include) will be added to the count part.
1866 *
1867 * Suppose you want to find all users who have a profile attached:
1868 * ```js
1869 * User.findAndCountAll({
1870 * include: [
1871 * { model: Profile, required: true}
1872 * ],
1873 * limit 3
1874 * });
1875 * ```
1876 * Because the include for `Profile` has `required` set it will result in an inner join, and only the users
1877 * who have a profile will be counted. If we remove `required` from the include, both users with and
1878 * without
1879 * profiles will be counted
1880 */
1881 public static findAndCountAll<M extends Model>(
1882 this: { new (): M } & typeof Model,
1883 options?: FindAndCountOptions
1884 ): Promise<{ rows: M[]; count: number }>;
1885
1886 /**
1887 * Find the maximum value of field
1888 */
1889 public static max<M extends Model, T extends DataType | unknown>(
1890 this: { new (): M } & typeof Model,
1891 field: keyof M,
1892 options?: AggregateOptions<T>
1893 ): Promise<T>;
1894
1895 /**
1896 * Find the minimum value of field
1897 */
1898 public static min<M extends Model, T extends DataType | unknown>(
1899 this: { new (): M } & typeof Model,
1900 field: keyof M,
1901 options?: AggregateOptions<T>
1902 ): Promise<T>;
1903
1904 /**
1905 * Find the sum of field
1906 */
1907 public static sum<M extends Model, T extends DataType | unknown>(
1908 this: { new (): M } & typeof Model,
1909 field: keyof M,
1910 options?: AggregateOptions<T>
1911 ): Promise<number>;
1912
1913 /**
1914 * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
1915 */
1916 public static build<M extends Model>(
1917 this: { new (): M } & typeof Model,
1918 record?: object,
1919 options?: BuildOptions
1920 ): M;
1921
1922 /**
1923 * Undocumented bulkBuild
1924 */
1925 public static bulkBuild<M extends Model>(
1926 this: { new (): M } & typeof Model,
1927 records: object[],
1928 options?: BuildOptions
1929 ): M[];
1930
1931 /**
1932 * Builds a new model instance and calls save on it.
1933 */
1934 public static create<M extends Model>(
1935 this: { new (): M } & typeof Model,
1936 values?: object,
1937 options?: CreateOptions
1938 ): Promise<M>;
1939 public static create(values: object, options: CreateOptions & { returning: false }): Promise<void>;
1940
1941 /**
1942 * Find a row that matches the query, or build (but don't save) the row if none is found.
1943 * The successfull result of the promise will be (instance, initialized) - Make sure to use `.then(([...]))`
1944 */
1945 public static findOrBuild<M extends Model>(
1946 this: { new (): M } & typeof Model,
1947 options: FindOrCreateOptions
1948 ): Promise<[M, boolean]>;
1949
1950 /**
1951 * Find a row that matches the query, or build and save the row if none is found
1952 * The successful result of the promise will be (instance, created) - Make sure to use `.then(([...]))`
1953 *
1954 * If no transaction is passed in the `options` object, a new transaction will be created internally, to
1955 * prevent the race condition where a matching row is created by another connection after the find but
1956 * before the insert call. However, it is not always possible to handle this case in SQLite, specifically
1957 * if one transaction inserts and another tries to select before the first one has comitted. In this case,
1958 * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint
1959 * will be created instead, and any unique constraint violation will be handled internally.
1960 */
1961 public static findOrCreate<M extends Model>(
1962 this: { new (): M } & typeof Model,
1963 options: FindOrCreateOptions
1964 ): Promise<[M, boolean]>;
1965
1966 /**
1967 * A more performant findOrCreate that will not work under a transaction (at least not in postgres)
1968 * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
1969 */
1970 public static findCreateFind<M extends Model>(
1971 this: { new (): M } & typeof Model,
1972 options: FindOrCreateOptions
1973 ): Promise<[M, boolean]>;
1974
1975 /**
1976 * Insert or update a single row. An update will be executed if a row which matches the supplied values on
1977 * either the primary key or a unique key is found. Note that the unique index must be defined in your
1978 * sequelize model and not just in the table. Otherwise you may experience a unique constraint violation,
1979 * because sequelize fails to identify the row that should be updated.
1980 *
1981 * **Implementation details:**
1982 *
1983 * * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values`
1984 * * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN
1985 * unique_constraint UPDATE
1986 * * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed
1987 * regardless
1988 * of whether the row already existed or not
1989 *
1990 * **Note** that SQLite returns undefined for created, no matter if the row was created or updated. This is
1991 * because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know
1992 * whether the row was inserted or not.
1993 */
1994 public static upsert<M extends Model>(
1995 this: { new (): M } & typeof Model,
1996 values: object,
1997 options?: UpsertOptions & { returning?: false | undefined }
1998 ): Promise<boolean>;
1999
2000 public static upsert<M extends Model> (
2001 this: { new (): M } & typeof Model,
2002 values: object,
2003 options?: UpsertOptions & { returning: true }
2004 ): Promise<[ M, boolean ]>;
2005
2006 /**
2007 * Create and insert multiple instances in bulk.
2008 *
2009 * The success handler is passed an array of instances, but please notice that these may not completely
2010 * represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to
2011 * obtain
2012 * back automatically generated IDs and other default values in a way that can be mapped to multiple
2013 * records. To obtain Instances for the newly created values, you will need to query for them again.
2014 *
2015 * @param records List of objects (key/value pairs) to create instances from
2016 */
2017 public static bulkCreate<M extends Model>(
2018 this: { new (): M } & typeof Model,
2019 records: object[],
2020 options?: BulkCreateOptions
2021 ): Promise<M[]>;
2022
2023 /**
2024 * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
2025 */
2026 public static truncate(options?: TruncateOptions): Promise<void>;
2027
2028 /**
2029 * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
2030 *
2031 * @return Promise<number> The number of destroyed rows
2032 */
2033 public static destroy(options?: DestroyOptions): Promise<number>;
2034
2035 /**
2036 * Restore multiple instances if `paranoid` is enabled.
2037 */
2038 public static restore(options?: RestoreOptions): Promise<void>;
2039
2040 /**
2041 * Update multiple instances that match the where options. The promise returns an array with one or two
2042 * elements. The first element is always the number of affected rows, while the second element is the actual
2043 * affected rows (only supported in postgres with `options.returning` true.)
2044 */
2045 public static update<M extends Model>(
2046 this: { new (): M } & typeof Model,
2047 values: object,
2048 options: UpdateOptions
2049 ): Promise<[number, M[]]>;
2050
2051 /**
2052 * Increments a single field.
2053 */
2054 public static increment<M extends Model, K extends keyof M>(
2055 this: { new (): M },
2056 field: K,
2057 options: IncrementDecrementOptionsWithBy
2058 ): Promise<M>;
2059
2060 /**
2061 * Increments multiple fields by the same value.
2062 */
2063 public static increment<M extends Model, K extends keyof M>(
2064 this: { new (): M },
2065 fields: K[],
2066 options: IncrementDecrementOptionsWithBy
2067 ): Promise<M>;
2068
2069 /**
2070 * Increments multiple fields by different values.
2071 */
2072 public static increment<M extends Model, K extends keyof M>(
2073 this: { new (): M },
2074 fields: { [key in K]?: number },
2075 options: IncrementDecrementOptions
2076 ): Promise<M>;
2077
2078 /**
2079 * Run a describe query on the table. The result will be return to the listener as a hash of attributes and
2080 * their types.
2081 */
2082 public static describe(): Promise<object>;
2083
2084 /**
2085 * Unscope the model
2086 */
2087 public static unscoped<M extends typeof Model>(this: M): M;
2088
2089 /**
2090 * A hook that is run before validation
2091 *
2092 * @param name
2093 * @param fn A callback function that is called with instance, options
2094 */
2095 public static beforeValidate<M extends Model>(
2096 this: { new (): M } & typeof Model,
2097 name: string,
2098 fn: (instance: M, options: ValidationOptions) => HookReturn
2099 ): void;
2100 public static beforeValidate<M extends Model>(
2101 this: { new (): M } & typeof Model,
2102 fn: (instance: M, options: ValidationOptions) => HookReturn
2103 ): void;
2104
2105 /**
2106 * A hook that is run after validation
2107 *
2108 * @param name
2109 * @param fn A callback function that is called with instance, options
2110 */
2111 public static afterValidate<M extends Model>(
2112 this: { new (): M } & typeof Model,
2113 name: string,
2114 fn: (instance: M, options: ValidationOptions) => HookReturn
2115 ): void;
2116 public static afterValidate<M extends Model>(
2117 this: { new (): M } & typeof Model,
2118 fn: (instance: M, options: ValidationOptions) => HookReturn
2119 ): void;
2120
2121 /**
2122 * A hook that is run before creating a single instance
2123 *
2124 * @param name
2125 * @param fn A callback function that is called with attributes, options
2126 */
2127 public static beforeCreate<M extends Model>(
2128 this: { new (): M } & typeof Model,
2129 name: string,
2130 fn: (attributes: M, options: CreateOptions) => HookReturn
2131 ): void;
2132 public static beforeCreate<M extends Model>(
2133 this: { new (): M } & typeof Model,
2134 fn: (attributes: M, options: CreateOptions) => HookReturn
2135 ): void;
2136
2137 /**
2138 * A hook that is run after creating a single instance
2139 *
2140 * @param name
2141 * @param fn A callback function that is called with attributes, options
2142 */
2143 public static afterCreate<M extends Model>(
2144 this: { new (): M } & typeof Model,
2145 name: string,
2146 fn: (attributes: M, options: CreateOptions) => HookReturn
2147 ): void;
2148 public static afterCreate<M extends Model>(
2149 this: { new (): M } & typeof Model,
2150 fn: (attributes: M, options: CreateOptions) => HookReturn
2151 ): void;
2152
2153 /**
2154 * A hook that is run before destroying a single instance
2155 *
2156 * @param name
2157 * @param fn A callback function that is called with instance, options
2158 */
2159 public static beforeDestroy<M extends Model>(
2160 this: { new (): M } & typeof Model,
2161 name: string,
2162 fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
2163 ): void;
2164 public static beforeDestroy<M extends Model>(
2165 this: { new (): M } & typeof Model,
2166 fn: (instance: Model, options: InstanceDestroyOptions) => HookReturn
2167 ): void;
2168
2169 /**
2170 * A hook that is run after destroying a single instance
2171 *
2172 * @param name
2173 * @param fn A callback function that is called with instance, options
2174 */
2175 public static afterDestroy<M extends Model>(
2176 this: { new (): M } & typeof Model,
2177 name: string,
2178 fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
2179 ): void;
2180 public static afterDestroy<M extends Model>(
2181 this: { new (): M } & typeof Model,
2182 fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
2183 ): void;
2184
2185 /**
2186 * A hook that is run before updating a single instance
2187 *
2188 * @param name
2189 * @param fn A callback function that is called with instance, options
2190 */
2191 public static beforeUpdate<M extends Model>(
2192 this: { new (): M } & typeof Model,
2193 name: string,
2194 fn: (instance: M, options: UpdateOptions) => HookReturn
2195 ): void;
2196 public static beforeUpdate<M extends Model>(
2197 this: { new (): M } & typeof Model,
2198 fn: (instance: M, options: UpdateOptions) => HookReturn
2199 ): void;
2200
2201 /**
2202 * A hook that is run after updating a single instance
2203 *
2204 * @param name
2205 * @param fn A callback function that is called with instance, options
2206 */
2207 public static afterUpdate<M extends Model>(
2208 this: { new (): M } & typeof Model,
2209 name: string,
2210 fn: (instance: M, options: UpdateOptions) => HookReturn
2211 ): void;
2212 public static afterUpdate<M extends Model>(
2213 this: { new (): M } & typeof Model,
2214 fn: (instance: M, options: UpdateOptions) => HookReturn
2215 ): void;
2216
2217 /**
2218 * A hook that is run before creating or updating a single instance, It proxies `beforeCreate` and `beforeUpdate`
2219 *
2220 * @param name
2221 * @param fn A callback function that is called with instance, options
2222 */
2223 public static beforeSave<M extends Model>(
2224 this: { new (): M } & typeof Model,
2225 name: string,
2226 fn: (instance: M, options: UpdateOptions | SaveOptions) => HookReturn
2227 ): void;
2228 public static beforeSave<M extends Model>(
2229 this: { new (): M } & typeof Model,
2230 fn: (instance: M, options: UpdateOptions | SaveOptions) => HookReturn
2231 ): void;
2232
2233 /**
2234 * A hook that is run after creating or updating a single instance, It proxies `afterCreate` and `afterUpdate`
2235 *
2236 * @param name
2237 * @param fn A callback function that is called with instance, options
2238 */
2239 public static afterSave<M extends Model>(
2240 this: { new (): M } & typeof Model,
2241 name: string,
2242 fn: (instance: M, options: UpdateOptions | SaveOptions) => HookReturn
2243 ): void;
2244 public static afterSave<M extends Model>(
2245 this: { new (): M } & typeof Model,
2246 fn: (instance: M, options: UpdateOptions | SaveOptions) => HookReturn
2247 ): void;
2248
2249 /**
2250 * A hook that is run before creating instances in bulk
2251 *
2252 * @param name
2253 * @param fn A callback function that is called with instances, options
2254 */
2255 public static beforeBulkCreate<M extends Model>(
2256 this: { new (): M } & typeof Model,
2257 name: string,
2258 fn: (instances: M[], options: BulkCreateOptions) => HookReturn
2259 ): void;
2260 public static beforeBulkCreate<M extends Model>(
2261 this: { new (): M } & typeof Model,
2262 fn: (instances: M[], options: BulkCreateOptions) => HookReturn
2263 ): void;
2264
2265 /**
2266 * A hook that is run after creating instances in bulk
2267 *
2268 * @param name
2269 * @param fn A callback function that is called with instances, options
2270 */
2271 public static afterBulkCreate<M extends Model>(
2272 this: { new (): M } & typeof Model,
2273 name: string,
2274 fn: (instances: M[], options: BulkCreateOptions) => HookReturn
2275 ): void;
2276 public static afterBulkCreate<M extends Model>(
2277 this: { new (): M } & typeof Model,
2278 fn: (instances: M[], options: BulkCreateOptions) => HookReturn
2279 ): void;
2280
2281 /**
2282 * A hook that is run before destroying instances in bulk
2283 *
2284 * @param name
2285 * @param fn A callback function that is called with options
2286 */
2287 public static beforeBulkDestroy(name: string, fn: (options: BulkCreateOptions) => HookReturn): void;
2288 public static beforeBulkDestroy(fn: (options: BulkCreateOptions) => HookReturn): void;
2289
2290 /**
2291 * A hook that is run after destroying instances in bulk
2292 *
2293 * @param name
2294 * @param fn A callback function that is called with options
2295 */
2296 public static afterBulkDestroy(name: string, fn: (options: DestroyOptions) => HookReturn): void;
2297 public static afterBulkDestroy(fn: (options: DestroyOptions) => HookReturn): void;
2298
2299 /**
2300 * A hook that is run after updating instances in bulk
2301 *
2302 * @param name
2303 * @param fn A callback function that is called with options
2304 */
2305 public static beforeBulkUpdate(name: string, fn: (options: UpdateOptions) => HookReturn): void;
2306 public static beforeBulkUpdate(fn: (options: UpdateOptions) => HookReturn): void;
2307
2308 /**
2309 * A hook that is run after updating instances in bulk
2310 *
2311 * @param name
2312 * @param fn A callback function that is called with options
2313 */
2314 public static afterBulkUpdate(name: string, fn: (options: UpdateOptions) => HookReturn): void;
2315 public static afterBulkUpdate(fn: (options: UpdateOptions) => HookReturn): void;
2316
2317 /**
2318 * A hook that is run before a find (select) query
2319 *
2320 * @param name
2321 * @param fn A callback function that is called with options
2322 */
2323 public static beforeFind(name: string, fn: (options: FindOptions) => HookReturn): void;
2324 public static beforeFind(fn: (options: FindOptions) => HookReturn): void;
2325
2326 /**
2327 * A hook that is run before a count query
2328 *
2329 * @param name
2330 * @param fn A callback function that is called with options
2331 */
2332 public static beforeCount(name: string, fn: (options: CountOptions) => HookReturn): void;
2333 public static beforeCount(fn: (options: CountOptions) => HookReturn): void;
2334
2335 /**
2336 * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
2337 *
2338 * @param name
2339 * @param fn A callback function that is called with options
2340 */
2341 public static beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions) => HookReturn): void;
2342 public static beforeFindAfterExpandIncludeAll(fn: (options: FindOptions) => HookReturn): void;
2343
2344 /**
2345 * A hook that is run before a find (select) query, after all option parsing is complete
2346 *
2347 * @param name
2348 * @param fn A callback function that is called with options
2349 */
2350 public static beforeFindAfterOptions(name: string, fn: (options: FindOptions) => HookReturn): void;
2351 public static beforeFindAfterOptions(fn: (options: FindOptions) => void): HookReturn;
2352
2353 /**
2354 * A hook that is run after a find (select) query
2355 *
2356 * @param name
2357 * @param fn A callback function that is called with instance(s), options
2358 */
2359 public static afterFind<M extends Model>(
2360 this: { new (): M } & typeof Model,
2361 name: string,
2362 fn: (instancesOrInstance: M[] | M | null, options: FindOptions) => HookReturn
2363 ): void;
2364 public static afterFind<M extends Model>(
2365 this: { new (): M } & typeof Model,
2366 fn: (instancesOrInstance: M[] | M | null, options: FindOptions) => HookReturn
2367 ): void;
2368
2369 /**
2370 * A hook that is run before sequelize.sync call
2371 * @param fn A callback function that is called with options passed to sequelize.sync
2372 */
2373 public static beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2374 public static beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void;
2375
2376 /**
2377 * A hook that is run after sequelize.sync call
2378 * @param fn A callback function that is called with options passed to sequelize.sync
2379 */
2380 public static afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2381 public static afterBulkSync(fn: (options: SyncOptions) => HookReturn): void;
2382
2383 /**
2384 * A hook that is run before Model.sync call
2385 * @param fn A callback function that is called with options passed to Model.sync
2386 */
2387 public static beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2388 public static beforeSync(fn: (options: SyncOptions) => HookReturn): void;
2389
2390 /**
2391 * A hook that is run after Model.sync call
2392 * @param fn A callback function that is called with options passed to Model.sync
2393 */
2394 public static afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2395 public static afterSync(fn: (options: SyncOptions) => HookReturn): void;
2396
2397 /**
2398 * Creates an association between this (the source) and the provided target. The foreign key is added
2399 * on the target.
2400 *
2401 * Example: `User.hasOne(Profile)`. This will add userId to the profile table.
2402 *
2403 * @param target The model that will be associated with hasOne relationship
2404 * @param options Options for the association
2405 */
2406 public static hasOne<M extends Model, T extends Model>(
2407 this: ModelCtor<M>, target: ModelCtor<T>, options?: HasOneOptions
2408 ): HasOne<M, T>;
2409
2410 /**
2411 * Creates an association between this (the source) and the provided target. The foreign key is added on the
2412 * source.
2413 *
2414 * Example: `Profile.belongsTo(User)`. This will add userId to the profile table.
2415 *
2416 * @param target The model that will be associated with hasOne relationship
2417 * @param options Options for the association
2418 */
2419 public static belongsTo<M extends Model, T extends Model>(
2420 this: ModelCtor<M>, target: ModelCtor<T>, options?: BelongsToOptions
2421 ): BelongsTo<M, T>;
2422
2423 /**
2424 * Create an association that is either 1:m or n:m.
2425 *
2426 * ```js
2427 * // Create a 1:m association between user and project
2428 * User.hasMany(Project)
2429 * ```
2430 * ```js
2431 * // Create a n:m association between user and project
2432 * User.hasMany(Project)
2433 * Project.hasMany(User)
2434 * ```
2435 * By default, the name of the join table will be source+target, so in this case projectsusers. This can be
2436 * overridden by providing either a string or a Model as `through` in the options. If you use a through
2437 * model with custom attributes, these attributes can be set when adding / setting new associations in two
2438 * ways. Consider users and projects from before with a join table that stores whether the project has been
2439 * started yet:
2440 * ```js
2441 * class UserProjects extends Model {}
2442 * UserProjects.init({
2443 * started: Sequelize.BOOLEAN
2444 * }, { sequelize })
2445 * User.hasMany(Project, { through: UserProjects })
2446 * Project.hasMany(User, { through: UserProjects })
2447 * ```
2448 * ```js
2449 * jan.addProject(homework, { started: false }) // The homework project is not started yet
2450 * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been
2451 * started
2452 * ```
2453 *
2454 * If you want to set several target instances, but with different attributes you have to set the
2455 * attributes on the instance, using a property with the name of the through model:
2456 *
2457 * ```js
2458 * p1.userprojects {
2459 * started: true
2460 * }
2461 * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
2462 * ```
2463 *
2464 * Similarily, when fetching through a join table with custom attributes, these attributes will be
2465 * available as an object with the name of the through model.
2466 * ```js
2467 * user.getProjects().then(projects => {
2468 * const p1 = projects[0]
2469 * p1.userprojects.started // Is this project started yet?
2470 * })
2471 * ```
2472 *
2473 * @param target The model that will be associated with hasOne relationship
2474 * @param options Options for the association
2475 */
2476 public static hasMany<M extends Model, T extends Model>(
2477 this: ModelCtor<M>, target: ModelCtor<T>, options?: HasManyOptions
2478 ): HasMany<M, T>;
2479
2480 /**
2481 * Create an N:M association with a join table
2482 *
2483 * ```js
2484 * User.belongsToMany(Project)
2485 * Project.belongsToMany(User)
2486 * ```
2487 * By default, the name of the join table will be source+target, so in this case projectsusers. This can be
2488 * overridden by providing either a string or a Model as `through` in the options.
2489 *
2490 * If you use a through model with custom attributes, these attributes can be set when adding / setting new
2491 * associations in two ways. Consider users and projects from before with a join table that stores whether
2492 * the project has been started yet:
2493 * ```js
2494 * class UserProjects extends Model {}
2495 * UserProjects.init({
2496 * started: Sequelize.BOOLEAN
2497 * }, { sequelize });
2498 * User.belongsToMany(Project, { through: UserProjects })
2499 * Project.belongsToMany(User, { through: UserProjects })
2500 * ```
2501 * ```js
2502 * jan.addProject(homework, { started: false }) // The homework project is not started yet
2503 * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started
2504 * ```
2505 *
2506 * If you want to set several target instances, but with different attributes you have to set the
2507 * attributes on the instance, using a property with the name of the through model:
2508 *
2509 * ```js
2510 * p1.userprojects {
2511 * started: true
2512 * }
2513 * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
2514 * ```
2515 *
2516 * Similarily, when fetching through a join table with custom attributes, these attributes will be
2517 * available as an object with the name of the through model.
2518 * ```js
2519 * user.getProjects().then(projects => {
2520 * const p1 = projects[0]
2521 * p1.userprojects.started // Is this project started yet?
2522 * })
2523 * ```
2524 *
2525 * @param target The model that will be associated with hasOne relationship
2526 * @param options Options for the association
2527 *
2528 */
2529 public static belongsToMany<M extends Model, T extends Model>(
2530 this: ModelCtor<M>, target: ModelCtor<T>, options: BelongsToManyOptions
2531 ): BelongsToMany<M, T>;
2532
2533 /**
2534 * Returns true if this instance has not yet been persisted to the database
2535 */
2536 public isNewRecord: boolean;
2537
2538 /**
2539 * A reference to the sequelize instance
2540 */
2541 public sequelize: Sequelize;
2542
2543 /**
2544 * Builds a new model instance.
2545 * @param values an object of key value pairs
2546 */
2547 constructor(values?: object, options?: BuildOptions);
2548
2549 /**
2550 * Get an object representing the query for this instance, use with `options.where`
2551 */
2552 public where(): object;
2553
2554 /**
2555 * Get the value of the underlying data value
2556 */
2557 public getDataValue<K extends keyof this>(key: K): this[K];
2558
2559 /**
2560 * Update the underlying data value
2561 */
2562 public setDataValue<K extends keyof this>(key: K, value: this[K]): void;
2563
2564 /**
2565 * If no key is given, returns all values of the instance, also invoking virtual getters.
2566 *
2567 * If key is given and a field or virtual getter is present for the key it will call that getter - else it
2568 * will return the value for key.
2569 *
2570 * @param options.plain If set to true, included instances will be returned as plain objects
2571 */
2572 public get(options?: { plain?: boolean; clone?: boolean }): object;
2573 public get<K extends keyof this>(key: K, options?: { plain?: boolean; clone?: boolean }): this[K];
2574 public get(key: string, options?: { plain?: boolean; clone?: boolean }): unknown;
2575
2576 /**
2577 * Set is used to update values on the instance (the sequelize representation of the instance that is,
2578 * remember that nothing will be persisted before you actually call `save`). In its most basic form `set`
2579 * will update a value stored in the underlying `dataValues` object. However, if a custom setter function
2580 * is defined for the key, that function will be called instead. To bypass the setter, you can pass `raw:
2581 * true` in the options object.
2582 *
2583 * If set is called with an object, it will loop over the object, and call set recursively for each key,
2584 * value pair. If you set raw to true, the underlying dataValues will either be set directly to the object
2585 * passed, or used to extend dataValues, if dataValues already contain values.
2586 *
2587 * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
2588 *
2589 * Set can also be used to build instances for associations, if you have values for those.
2590 * When using set with associations you need to make sure the property key matches the alias of the
2591 * association while also making sure that the proper include options have been set (from .build() or
2592 * .findOne())
2593 *
2594 * If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the
2595 * entire object as changed.
2596 *
2597 * @param options.raw If set to true, field and virtual setters will be ignored
2598 * @param options.reset Clear all previously set data values
2599 */
2600 public set<K extends keyof this>(key: K, value: this[K], options?: SetOptions): this;
2601 public set(keys: Partial<this>, options?: SetOptions): this;
2602 public setAttributes<K extends keyof this>(key: K, value: this[K], options?: SetOptions): this;
2603 public setAttributes(keys: object, options?: SetOptions): this;
2604
2605 /**
2606 * If changed is called with a string it will return a boolean indicating whether the value of that key in
2607 * `dataValues` is different from the value in `_previousDataValues`.
2608 *
2609 * If changed is called without an argument, it will return an array of keys that have changed.
2610 *
2611 * If changed is called with two arguments, it will set the property to `dirty`.
2612 *
2613 * If changed is called without an argument and no keys have changed, it will return `false`.
2614 */
2615 public changed<K extends keyof this>(key: K): boolean;
2616 public changed<K extends keyof this>(key: K, dirty: boolean): void;
2617 public changed(): false | string[];
2618
2619 /**
2620 * Returns the previous value for key from `_previousDataValues`.
2621 */
2622 public previous<K extends keyof this>(key: K): this[K];
2623
2624 /**
2625 * Validate this instance, and if the validation passes, persist it to the database.
2626 *
2627 * On success, the callback will be called with this instance. On validation error, the callback will be
2628 * called with an instance of `Sequelize.ValidationError`. This error will have a property for each of the
2629 * fields for which validation failed, with the error message for that field.
2630 */
2631 public save(options?: SaveOptions): Promise<this>;
2632
2633 /**
2634 * Refresh the current instance in-place, i.e. update the object with current data from the DB and return
2635 * the same object. This is different from doing a `find(Instance.id)`, because that would create and
2636 * return a new instance. With this method, all references to the Instance are updated with the new data
2637 * and no new objects are created.
2638 */
2639 public reload(options?: FindOptions): Promise<this>;
2640
2641 /**
2642 * Validate the attribute of this instance according to validation rules set in the model definition.
2643 *
2644 * Emits null if and only if validation successful; otherwise an Error instance containing
2645 * { field name : [error msgs] } entries.
2646 *
2647 * @param options.skip An array of strings. All properties that are in this array will not be validated
2648 */
2649 public validate(options?: ValidationOptions): Promise<void>;
2650
2651 /**
2652 * This is the same as calling `set` and then calling `save`.
2653 */
2654 public update<K extends keyof this>(key: K, value: this[K], options?: InstanceUpdateOptions): Promise<this>;
2655 public update(keys: object, options?: InstanceUpdateOptions): Promise<this>;
2656
2657 /**
2658 * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will
2659 * either be completely deleted, or have its deletedAt timestamp set to the current time.
2660 */
2661 public destroy(options?: InstanceDestroyOptions): Promise<void>;
2662
2663 /**
2664 * Restore the row corresponding to this instance. Only available for paranoid models.
2665 */
2666 public restore(options?: InstanceRestoreOptions): Promise<void>;
2667
2668 /**
2669 * Increment the value of one or more columns. This is done in the database, which means it does not use
2670 * the values currently stored on the Instance. The increment is done using a
2671 * ```sql
2672 * SET column = column + X
2673 * ```
2674 * query. To get the correct value after an increment into the Instance you should do a reload.
2675 *
2676 * ```js
2677 * instance.increment('number') // increment number by 1
2678 * instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
2679 * instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
2680 * // `by` is ignored, since each column has its own
2681 * // value
2682 * ```
2683 *
2684 * @param fields If a string is provided, that column is incremented by the value of `by` given in options.
2685 * If an array is provided, the same is true for each column.
2686 * If and object is provided, each column is incremented by the value given.
2687 */
2688 public increment<K extends keyof this>(
2689 fields: K | K[] | Partial<this>,
2690 options?: IncrementDecrementOptionsWithBy
2691 ): Promise<this>;
2692
2693 /**
2694 * Decrement the value of one or more columns. This is done in the database, which means it does not use
2695 * the values currently stored on the Instance. The decrement is done using a
2696 * ```sql
2697 * SET column = column - X
2698 * ```
2699 * query. To get the correct value after an decrement into the Instance you should do a reload.
2700 *
2701 * ```js
2702 * instance.decrement('number') // decrement number by 1
2703 * instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
2704 * instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
2705 * // `by` is ignored, since each column has its own
2706 * // value
2707 * ```
2708 *
2709 * @param fields If a string is provided, that column is decremented by the value of `by` given in options.
2710 * If an array is provided, the same is true for each column.
2711 * If and object is provided, each column is decremented by the value given
2712 */
2713 public decrement<K extends keyof this>(
2714 fields: K | K[] | Partial<this>,
2715 options?: IncrementDecrementOptionsWithBy
2716 ): Promise<this>;
2717
2718 /**
2719 * Check whether all values of this and `other` Instance are the same
2720 */
2721 public equals(other: this): boolean;
2722
2723 /**
2724 * Check if this is eqaul to one of `others` by calling equals
2725 */
2726 public equalsOneOf(others: this[]): boolean;
2727
2728 /**
2729 * Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all
2730 * values gotten from the DB, and apply all custom getters.
2731 */
2732 public toJSON(): object;
2733}
2734
2735export type ModelType = typeof Model;
2736
2737export type ModelCtor<M extends Model> = { new (): M } & ModelType;
2738
2739export default Model;
2740
\No newline at end of file