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