UNPKG

114 kBTypeScriptView Raw
1import IndexHints = require('./index-hints');
2import { Association, BelongsTo, BelongsToMany, BelongsToManyOptions, BelongsToOptions, HasMany, HasManyOptions, HasOne, HasOneOptions } from './associations/index';
3import { DataType } from './data-types';
4import { Deferrable } from './deferrable';
5import { HookReturn, Hooks, ModelHooks } from './hooks';
6import { ValidationOptions } from './instance-validator';
7import { IndexesOptions, QueryOptions, TableName } from './dialects/abstract/query-interface';
8import { Sequelize, SyncOptions } from './sequelize';
9import { Col, Fn, Literal, Where, MakeNullishOptional, AnyFunction, Cast, Json } from './utils';
10import { LOCK, Transaction, Op, Optional } from './index';
11import { SetRequired } from './utils/set-required';
12
13// Backport of https://github.com/sequelize/sequelize/blob/a68b439fb3ea748d3f3d37356d9fe610f86184f6/src/utils/index.ts#L85
14export type AllowReadonlyArray<T> = T | readonly T[];
15
16export interface Logging {
17 /**
18 * A function that gets executed while running the query to log the sql.
19 */
20 logging?: boolean | ((sql: string, timing?: number) => void);
21
22 /**
23 * Pass query execution time in milliseconds as second argument to logging function (options.logging).
24 */
25 benchmark?: boolean;
26}
27
28export interface Poolable {
29 /**
30 * Force the query to use the write pool, regardless of the query type.
31 *
32 * @default false
33 */
34 useMaster?: boolean;
35}
36
37export interface Transactionable {
38 /**
39 * Transaction to run query under
40 */
41 transaction?: Transaction | null;
42}
43
44export interface SearchPathable {
45 /**
46 * An optional parameter to specify the schema search_path (Postgres only)
47 */
48 searchPath?: string;
49}
50
51export interface Filterable<TAttributes = any> {
52 /**
53 * Attribute has to be matched for rows to be selected for the given action.
54 */
55 where?: WhereOptions<TAttributes>;
56}
57
58export interface Projectable {
59 /**
60 * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with
61 * two elements - the first is the name of the attribute in the DB (or some kind of expression such as
62 * `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to
63 * have in the returned instance
64 */
65 attributes?: FindAttributeOptions;
66}
67
68export interface Paranoid {
69 /**
70 * If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
71 * be returned. Only applies if `options.paranoid` is true for the model.
72 */
73 paranoid?: boolean;
74}
75
76export type GroupOption = string | Fn | Col | (string | Fn | Col)[];
77
78/**
79 * Options to pass to Model on drop
80 */
81export interface DropOptions extends Logging {
82 /**
83 * Also drop all objects depending on this table, such as views. Only works in postgres
84 */
85 cascade?: boolean;
86}
87
88/**
89 * Schema Options provided for applying a schema to a model
90 */
91export interface SchemaOptions extends Logging {
92 /**
93 * The character(s) that separates the schema name from the table name
94 */
95 schemaDelimiter?: string;
96}
97
98/**
99 * Scope Options for Model.scope
100 */
101export interface ScopeOptions {
102 /**
103 * The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments.
104 * To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function,
105 * pass an object, with a `method` property. The value can either be a string, if the method does not take
106 * any arguments, or an array, where the first element is the name of the method, and consecutive elements
107 * are arguments to that method. Pass null to remove all scopes, including the default.
108 */
109 method: string | readonly [string, ...unknown[]];
110}
111
112type InvalidInSqlArray = ColumnReference | Fn | Cast | null | Literal;
113
114/**
115 * This type allows using `Op.or`, `Op.and`, and `Op.not` recursively around another type.
116 * It also supports using a plain Array as an alias for `Op.and`. (unlike {@link AllowNotOrAndRecursive}).
117 *
118 * Example of plain-array treated as `Op.and`:
119 * User.findAll({ where: [{ id: 1 }, { id: 2 }] });
120 *
121 * Meant to be used by {@link WhereOptions}.
122 */
123type AllowNotOrAndWithImplicitAndArrayRecursive<T> = AllowArray<
124 // this is the equivalent of Op.and
125 | T
126 | { [Op.or]: AllowArray<AllowNotOrAndWithImplicitAndArrayRecursive<T>> }
127 | { [Op.and]: AllowArray<AllowNotOrAndWithImplicitAndArrayRecursive<T>> }
128 | { [Op.not]: AllowNotOrAndWithImplicitAndArrayRecursive<T> }
129>;
130
131/**
132 * This type allows using `Op.or`, `Op.and`, and `Op.not` recursively around another type.
133 * Unlike {@link AllowNotOrAndWithImplicitAndArrayRecursive}, it does not allow the 'implicit AND Array'.
134 *
135 * Example of plain-array NOT treated as Op.and:
136 * User.findAll({ where: { id: [1, 2] } });
137 *
138 * Meant to be used by {@link WhereAttributeHashValue}.
139 */
140type AllowNotOrAndRecursive<T> =
141 | T
142 | { [Op.or]: AllowArray<AllowNotOrAndRecursive<T>> }
143 | { [Op.and]: AllowArray<AllowNotOrAndRecursive<T>> }
144 | { [Op.not]: AllowNotOrAndRecursive<T> };
145
146type AllowArray<T> = T | T[];
147type AllowAnyAll<T> =
148 | T
149 // Op.all: [x, z] results in ALL (ARRAY[x, z])
150 // Some things cannot go in ARRAY. Op.values must be used to support them.
151 | { [Op.all]: Exclude<T, InvalidInSqlArray>[] | Literal | { [Op.values]: Array<T | DynamicValues<T>> } }
152 | { [Op.any]: Exclude<T, InvalidInSqlArray>[] | Literal | { [Op.values]: Array<T | DynamicValues<T>> } };
153
154/**
155 * The type accepted by every `where` option
156 */
157export type WhereOptions<TAttributes = any> = AllowNotOrAndWithImplicitAndArrayRecursive<
158 | WhereAttributeHash<TAttributes>
159 | Literal
160 | Fn
161 | Where
162 | Json
163>;
164
165/**
166 * @deprecated unused
167 */
168export interface AnyOperator {
169 [Op.any]: readonly (string | number | Date | Literal)[] | Literal;
170}
171
172/** @deprecated unused */
173export interface AllOperator {
174 [Op.all]: readonly (string | number | Date | Literal)[] | Literal;
175}
176
177// number is always allowed because -Infinity & +Infinity are valid
178export type Rangable<T> = readonly [
179 lower: T | RangePart<T | number> | number | null,
180 higher: T | RangePart<T | number> | number | null
181] | EmptyRange;
182
183/**
184 * This type represents the output of the {@link RANGE} data type.
185 */
186// number is always allowed because -Infinity & +Infinity are valid
187export type Range<T> = readonly [lower: RangePart<T | number>, higher: RangePart<T | number>] | EmptyRange;
188
189type EmptyRange = [];
190
191type RangePart<T> = { value: T, inclusive: boolean };
192
193/**
194 * Internal type - prone to changes. Do not export.
195 * @private
196 */
197export type ColumnReference = Col | { [Op.col]: string };
198
199/**
200 * Internal type - prone to changes. Do not export.
201 * @private
202 */
203type WhereSerializableValue = boolean | string | number | Buffer | Date;
204
205/**
206 * Internal type - prone to changes. Do not export.
207 * @private
208 */
209type OperatorValues<AcceptableValues> =
210 | StaticValues<AcceptableValues>
211 | DynamicValues<AcceptableValues>;
212
213/**
214 * Represents acceptable Dynamic values.
215 *
216 * Dynamic values, as opposed to {@link StaticValues}. i.e. column references, functions, etc...
217 */
218type DynamicValues<AcceptableValues> =
219 | Literal
220 | ColumnReference
221 | Fn
222 | Cast
223 // where() can only be used on boolean attributes
224 | (AcceptableValues extends boolean ? Where : never)
225
226/**
227 * Represents acceptable Static values.
228 *
229 * Static values, as opposed to {@link DynamicValues}. i.e. booleans, strings, etc...
230 */
231type StaticValues<Type> =
232 Type extends Range<infer RangeType> ? [lower: RangeType | RangePart<RangeType>, higher: RangeType | RangePart<RangeType>]
233 : Type extends any[] ? { readonly [Key in keyof Type]: StaticValues<Type[Key]>}
234 : Type extends null ? Type | WhereSerializableValue | null
235 : Type | WhereSerializableValue;
236
237/**
238 * Operators that can be used in {@link WhereOptions}
239 *
240 * @typeParam AttributeType - The JS type of the attribute the operator is operating on.
241 *
242 * See https://sequelize.org/master/en/v3/docs/querying/#operators
243 */
244// TODO: default to something more strict than `any` which lists serializable values
245export interface WhereOperators<AttributeType = any> {
246 /**
247 * @example: `[Op.eq]: 6,` becomes `= 6`
248 * @example: `[Op.eq]: [6, 7]` becomes `= ARRAY[6, 7]`
249 * @example: `[Op.eq]: null` becomes `IS NULL`
250 * @example: `[Op.eq]: true` becomes `= true`
251 * @example: `[Op.eq]: literal('raw sql')` becomes `= raw sql`
252 * @example: `[Op.eq]: col('column')` becomes `= "column"`
253 * @example: `[Op.eq]: fn('NOW')` becomes `= NOW()`
254 */
255 [Op.eq]?: AllowAnyAll<OperatorValues<AttributeType>>;
256
257 /**
258 * @example: `[Op.ne]: 20,` becomes `!= 20`
259 * @example: `[Op.ne]: [20, 21]` becomes `!= ARRAY[20, 21]`
260 * @example: `[Op.ne]: null` becomes `IS NOT NULL`
261 * @example: `[Op.ne]: true` becomes `!= true`
262 * @example: `[Op.ne]: literal('raw sql')` becomes `!= raw sql`
263 * @example: `[Op.ne]: col('column')` becomes `!= "column"`
264 * @example: `[Op.ne]: fn('NOW')` becomes `!= NOW()`
265 */
266 [Op.ne]?: WhereOperators<AttributeType>[typeof Op.eq]; // accepts the same types as Op.eq
267
268 /**
269 * @example: `[Op.is]: null` becomes `IS NULL`
270 * @example: `[Op.is]: true` becomes `IS TRUE`
271 * @example: `[Op.is]: literal('value')` becomes `IS value`
272 */
273 [Op.is]?: Extract<AttributeType, null | boolean> | Literal;
274
275 /**
276 * @example: `[Op.not]: true` becomes `IS NOT TRUE`
277 * @example: `{ col: { [Op.not]: { [Op.gt]: 5 } } }` becomes `NOT (col > 5)`
278 */
279 [Op.not]?: WhereOperators<AttributeType>[typeof Op.eq]; // accepts the same types as Op.eq ('Op.not' is not strictly the opposite of 'Op.is' due to legacy reasons)
280
281 /** @example: `[Op.gte]: 6` becomes `>= 6` */
282 [Op.gte]?: AllowAnyAll<OperatorValues<NonNullable<AttributeType>>>;
283
284 /** @example: `[Op.lte]: 10` becomes `<= 10` */
285 [Op.lte]?: WhereOperators<AttributeType>[typeof Op.gte]; // accepts the same types as Op.gte
286
287 /** @example: `[Op.lt]: 10` becomes `< 10` */
288 [Op.lt]?: WhereOperators<AttributeType>[typeof Op.gte]; // accepts the same types as Op.gte
289
290 /** @example: `[Op.gt]: 6` becomes `> 6` */
291 [Op.gt]?: WhereOperators<AttributeType>[typeof Op.gte]; // accepts the same types as Op.gte
292
293 /**
294 * @example: `[Op.between]: [6, 10],` becomes `BETWEEN 6 AND 10`
295 */
296 [Op.between]?:
297 | [
298 lowerInclusive: OperatorValues<NonNullable<AttributeType>>,
299 higherInclusive: OperatorValues<NonNullable<AttributeType>>,
300 ]
301 | Literal;
302
303 /** @example: `[Op.notBetween]: [11, 15],` becomes `NOT BETWEEN 11 AND 15` */
304 [Op.notBetween]?: WhereOperators<AttributeType>[typeof Op.between];
305
306 /** @example: `[Op.in]: [1, 2],` becomes `IN (1, 2)` */
307 [Op.in]?: ReadonlyArray<OperatorValues<NonNullable<AttributeType>>> | Literal;
308
309 /** @example: `[Op.notIn]: [1, 2],` becomes `NOT IN (1, 2)` */
310 [Op.notIn]?: WhereOperators<AttributeType>[typeof Op.in];
311
312 /**
313 * @example: `[Op.like]: '%hat',` becomes `LIKE '%hat'`
314 * @example: `[Op.like]: { [Op.any]: ['cat', 'hat'] }` becomes `LIKE ANY ARRAY['cat', 'hat']`
315 */
316 [Op.like]?: AllowAnyAll<OperatorValues<Extract<AttributeType, string>>>;
317
318 /**
319 * @example: `[Op.notLike]: '%hat'` becomes `NOT LIKE '%hat'`
320 * @example: `[Op.notLike]: { [Op.any]: ['cat', 'hat']}` becomes `NOT LIKE ANY ARRAY['cat', 'hat']`
321 */
322 [Op.notLike]?: WhereOperators<AttributeType>[typeof Op.like];
323
324 /**
325 * case insensitive PG only
326 *
327 * @example: `[Op.iLike]: '%hat'` becomes `ILIKE '%hat'`
328 * @example: `[Op.iLike]: { [Op.any]: ['cat', 'hat']}` becomes `ILIKE ANY ARRAY['cat', 'hat']`
329 */
330 [Op.iLike]?: WhereOperators<AttributeType>[typeof Op.like];
331
332 /**
333 * PG only
334 *
335 * @example: `[Op.notILike]: '%hat'` becomes `NOT ILIKE '%hat'`
336 * @example: `[Op.notLike]: ['cat', 'hat']` becomes `LIKE ANY ARRAY['cat', 'hat']`
337 */
338 [Op.notILike]?: WhereOperators<AttributeType>[typeof Op.like];
339
340 /**
341 * PG array & range 'overlaps' operator
342 *
343 * @example: `[Op.overlap]: [1, 2]` becomes `&& [1, 2]`
344 */
345 // https://www.postgresql.org/docs/14/functions-range.html range && range
346 // https://www.postgresql.org/docs/14/functions-array.html array && array
347 [Op.overlap]?: AllowAnyAll<
348 | (
349 // RANGE && RANGE
350 AttributeType extends Range<infer RangeType> ? Rangable<RangeType>
351 // ARRAY && ARRAY
352 : AttributeType extends any[] ? StaticValues<NonNullable<AttributeType>>
353 : never
354 )
355 | DynamicValues<AttributeType>
356 >;
357
358 /**
359 * PG array & range 'contains' operator
360 *
361 * @example: `[Op.contains]: [1, 2]` becomes `@> [1, 2]`
362 */
363 // https://www.postgresql.org/docs/14/functions-json.html jsonb @> jsonb
364 // https://www.postgresql.org/docs/14/functions-range.html range @> range ; range @> element
365 // https://www.postgresql.org/docs/14/functions-array.html array @> array
366 [Op.contains]?:
367 // RANGE @> ELEMENT
368 | AttributeType extends Range<infer RangeType> ? OperatorValues<OperatorValues<NonNullable<RangeType>>> : never
369 // ARRAY @> ARRAY ; RANGE @> RANGE
370 | WhereOperators<AttributeType>[typeof Op.overlap];
371
372 /**
373 * PG array & range 'contained by' operator
374 *
375 * @example: `[Op.contained]: [1, 2]` becomes `<@ [1, 2]`
376 */
377 [Op.contained]?:
378 AttributeType extends any[]
379 // ARRAY <@ ARRAY ; RANGE <@ RANGE
380 ? WhereOperators<AttributeType>[typeof Op.overlap]
381 // ELEMENT <@ RANGE
382 : AllowAnyAll<OperatorValues<Rangable<AttributeType>>>;
383
384 /**
385 * Strings starts with value.
386 */
387 [Op.startsWith]?: OperatorValues<Extract<AttributeType, string>>;
388
389 /**
390 * String ends with value.
391 */
392 [Op.endsWith]?: WhereOperators<AttributeType>[typeof Op.startsWith];
393 /**
394 * String contains value.
395 */
396 [Op.substring]?: WhereOperators<AttributeType>[typeof Op.startsWith];
397
398 /**
399 * MySQL/PG only
400 *
401 * Matches regular expression, case sensitive
402 *
403 * @example: `[Op.regexp]: '^[h|a|t]'` becomes `REGEXP/~ '^[h|a|t]'`
404 */
405 [Op.regexp]?: AllowAnyAll<OperatorValues<Extract<AttributeType, string>>>;
406
407 /**
408 * MySQL/PG only
409 *
410 * Does not match regular expression, case sensitive
411 *
412 * @example: `[Op.notRegexp]: '^[h|a|t]'` becomes `NOT REGEXP/!~ '^[h|a|t]'`
413 */
414 [Op.notRegexp]?: WhereOperators<AttributeType>[typeof Op.regexp];
415
416 /**
417 * PG only
418 *
419 * Matches regular expression, case insensitive
420 *
421 * @example: `[Op.iRegexp]: '^[h|a|t]'` becomes `~* '^[h|a|t]'`
422 */
423 [Op.iRegexp]?: WhereOperators<AttributeType>[typeof Op.regexp];
424
425 /**
426 * PG only
427 *
428 * Does not match regular expression, case insensitive
429 *
430 * @example: `[Op.notIRegexp]: '^[h|a|t]'` becomes `!~* '^[h|a|t]'`
431 */
432 [Op.notIRegexp]?: WhereOperators<AttributeType>[typeof Op.regexp];
433
434 /** @example: `[Op.match]: Sequelize.fn('to_tsquery', 'fat & rat')` becomes `@@ to_tsquery('fat & rat')` */
435 [Op.match]?: AllowAnyAll<DynamicValues<AttributeType>>;
436
437 /**
438 * PG only
439 *
440 * Whether the range is strictly left of the other range.
441 *
442 * @example:
443 * ```typescript
444 * { rangeAttribute: { [Op.strictLeft]: [1, 2] } }
445 * // results in
446 * // "rangeAttribute" << [1, 2)
447 * ```
448 *
449 * https://www.postgresql.org/docs/14/functions-range.html
450 */
451 [Op.strictLeft]?:
452 | AttributeType extends Range<infer RangeType> ? Rangable<RangeType> : never
453 | DynamicValues<AttributeType>;
454
455 /**
456 * PG only
457 *
458 * Whether the range is strictly right of the other range.
459 *
460 * @example:
461 * ```typescript
462 * { rangeAttribute: { [Op.strictRight]: [1, 2] } }
463 * // results in
464 * // "rangeAttribute" >> [1, 2)
465 * ```
466 *
467 * https://www.postgresql.org/docs/14/functions-range.html
468 */
469 [Op.strictRight]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
470
471 /**
472 * PG only
473 *
474 * Whether the range extends to the left of the other range.
475 *
476 * @example:
477 * ```typescript
478 * { rangeAttribute: { [Op.noExtendLeft]: [1, 2] } }
479 * // results in
480 * // "rangeAttribute" &> [1, 2)
481 * ```
482 *
483 * https://www.postgresql.org/docs/14/functions-range.html
484 */
485 [Op.noExtendLeft]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
486
487 /**
488 * PG only
489 *
490 * Whether the range extends to the right of the other range.
491 *
492 * @example:
493 * ```typescript
494 * { rangeAttribute: { [Op.noExtendRight]: [1, 2] } }
495 * // results in
496 * // "rangeAttribute" &< [1, 2)
497 * ```
498 *
499 * https://www.postgresql.org/docs/14/functions-range.html
500 */
501 [Op.noExtendRight]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
502
503 /**
504 * PG only
505 *
506 * Whether the two ranges are adjacent.
507 *
508 * @example:
509 * ```typescript
510 * { rangeAttribute: { [Op.adjacent]: [1, 2] } }
511 * // results in
512 * // "rangeAttribute" -|- [1, 2)
513 * ```
514 *
515 * https://www.postgresql.org/docs/14/functions-range.html
516 */
517 [Op.adjacent]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
518}
519
520/**
521 * Example: `[Op.or]: [{a: 5}, {a: 6}]` becomes `(a = 5 OR a = 6)`
522 *
523 * @deprecated do not use me!
524 */
525// TODO [>6]: Remove me
526export interface OrOperator<TAttributes = any> {
527 [Op.or]: WhereOptions<TAttributes> | readonly WhereOptions<TAttributes>[] | WhereValue<TAttributes> | readonly WhereValue<TAttributes>[];
528}
529
530/**
531 * Example: `[Op.and]: {a: 5}` becomes `AND (a = 5)`
532 *
533 * @deprecated do not use me!
534 */
535// TODO [>6]: Remove me
536export interface AndOperator<TAttributes = any> {
537 [Op.and]: WhereOptions<TAttributes> | readonly WhereOptions<TAttributes>[] | WhereValue<TAttributes> | readonly WhereValue<TAttributes>[];
538}
539
540/**
541 * Where Geometry Options
542 */
543export interface WhereGeometryOptions {
544 type: string;
545 coordinates: readonly (number[] | number)[];
546}
547
548/**
549 * Used for the right hand side of WhereAttributeHash.
550 * WhereAttributeHash is in there for JSON columns.
551 *
552 * @deprecated do not use me
553 */
554// TODO [>6]: remove this
555export type WhereValue<TAttributes = any> =
556 | string
557 | number
558 | bigint
559 | boolean
560 | Date
561 | Buffer
562 | null
563 | WhereAttributeHash<any> // for JSON columns
564 | Col // reference another column
565 | Fn
566 | WhereGeometryOptions
567
568/**
569 * A hash of attributes to describe your search.
570 *
571 * Possible key values:
572 *
573 * - An attribute name: `{ id: 1 }`
574 * - A nested attribute: `{ '$projects.id$': 1 }`
575 * - A JSON key: `{ 'object.key': 1 }`
576 * - A cast: `{ 'id::integer': 1 }`
577 *
578 * - A combination of the above: `{ '$join.attribute$.json.path::integer': 1 }`
579 */
580export type WhereAttributeHash<TAttributes = any> = {
581 // support 'attribute' & '$attribute$'
582 [AttributeName in keyof TAttributes as AttributeName extends string ? AttributeName | `$${AttributeName}$` : never]?: WhereAttributeHashValue<TAttributes[AttributeName]>;
583} & {
584 [AttributeName in keyof TAttributes as AttributeName extends string ?
585 // support 'json.path', '$json$.path'
586 | `${AttributeName}.${string}` | `$${AttributeName}$.${string}`
587 // support 'attribute::cast', '$attribute$::cast', 'json.path::cast' & '$json$.path::cast'
588 | `${AttributeName | `$${AttributeName}$` | `${AttributeName}.${string}` | `$${AttributeName}$.${string}`}::${string}`
589 : never]?: WhereAttributeHashValue<any>;
590} & {
591 // support '$nested.attribute$', '$nested.attribute$::cast', '$nested.attribute$.json.path', & '$nested.attribute$.json.path::cast'
592 // TODO [2022-05-26]: Remove this ts-ignore once we drop support for TS < 4.4
593 // TypeScript < 4.4 does not support using a Template Literal Type as a key.
594 // note: this *must* be a ts-ignore, as it works in ts >= 4.4
595 // @ts-ignore
596 [attribute: `$${string}.${string}$` | `$${string}.${string}$::${string}` | `$${string}.${string}$.${string}` | `$${string}.${string}$.${string}::${string}`]: WhereAttributeHashValue<any>;
597}
598
599/**
600 * Types that can be compared to an attribute in a WHERE context.
601 */
602export type WhereAttributeHashValue<AttributeType> =
603 | AllowNotOrAndRecursive<
604 // if the right-hand side is an array, it will be equal to Op.in
605 // otherwise it will be equal to Op.eq
606 // Exception: array attribtues always use Op.eq, never Op.in.
607 | AttributeType extends any[]
608 ? WhereOperators<AttributeType>[typeof Op.eq] | WhereOperators<AttributeType>
609 : (
610 | WhereOperators<AttributeType>[typeof Op.in]
611 | WhereOperators<AttributeType>[typeof Op.eq]
612 | WhereOperators<AttributeType>
613 )
614 >
615 // TODO: this needs a simplified version just for JSON columns
616 | WhereAttributeHash<any> // for JSON columns
617
618/**
619 * Through options for Include Options
620 */
621export interface IncludeThroughOptions extends Filterable<any>, Projectable {
622 /**
623 * The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` /
624 * `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
625 */
626 as?: string;
627
628 /**
629 * If true, only non-deleted records will be returned from the join table.
630 * If false, both deleted and non-deleted records will be returned.
631 * Only applies if through model is paranoid.
632 */
633 paranoid?: boolean;
634}
635
636/**
637 * Options for eager-loading associated models, also allowing for all associations to be loaded at once
638 */
639export type Includeable = ModelType | Association | IncludeOptions | { all: true, nested?: true } | string;
640
641/**
642 * Complex include options
643 */
644export interface IncludeOptions extends Filterable<any>, Projectable, Paranoid {
645 /**
646 * Mark the include as duplicating, will prevent a subquery from being used.
647 */
648 duplicating?: boolean;
649 /**
650 * The model you want to eagerly load
651 */
652 model?: ModelType;
653
654 /**
655 * The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` /
656 * `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
657 */
658 as?: string;
659
660 /**
661 * The association you want to eagerly load. (This can be used instead of providing a model/as pair)
662 */
663 association?: Association | string;
664
665 /**
666 * Custom `on` clause, overrides default.
667 */
668 on?: WhereOptions<any>;
669
670 /**
671 * Note that this converts the eager load to an inner join,
672 * unless you explicitly set `required: false`
673 */
674 where?: WhereOptions<any>;
675
676 /**
677 * If true, converts to an inner join, which means that the parent model will only be loaded if it has any
678 * matching children. True if `include.where` is set, false otherwise.
679 */
680 required?: boolean;
681
682 /**
683 * If true, converts to a right join if dialect support it. Ignored if `include.required` is true.
684 */
685 right?: boolean;
686
687 /**
688 * Limit include. Only available when setting `separate` to true.
689 */
690 limit?: number;
691
692 /**
693 * Run include in separate queries.
694 */
695 separate?: boolean;
696
697 /**
698 * Through Options
699 */
700 through?: IncludeThroughOptions;
701
702 /**
703 * Load further nested related models
704 */
705 include?: Includeable[];
706
707 /**
708 * Order include. Only available when setting `separate` to true.
709 */
710 order?: Order;
711
712 /**
713 * Use sub queries. This should only be used if you know for sure the query does not result in a cartesian product.
714 */
715 subQuery?: boolean;
716}
717
718type OrderItemAssociation = Association | ModelStatic<Model> | { model: ModelStatic<Model>; as: string } | string
719type OrderItemColumn = string | Col | Fn | Literal
720export type OrderItem =
721 | string
722 | Fn
723 | Col
724 | Literal
725 | [OrderItemColumn, string]
726 | [OrderItemAssociation, OrderItemColumn]
727 | [OrderItemAssociation, OrderItemColumn, string]
728 | [OrderItemAssociation, OrderItemAssociation, OrderItemColumn]
729 | [OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string]
730 | [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn]
731 | [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string]
732 | [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn]
733 | [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string]
734export type Order = Fn | Col | Literal | OrderItem[];
735
736/**
737 * Please note if this is used the aliased property will not be available on the model instance
738 * as a property but only via `instance.get('alias')`.
739 */
740export type ProjectionAlias = readonly [string | Literal | Fn | Col, string];
741
742export type FindAttributeOptions =
743 | (string | ProjectionAlias)[]
744 | {
745 exclude: string[];
746 include?: (string | ProjectionAlias)[];
747 }
748 | {
749 exclude?: string[];
750 include: (string | ProjectionAlias)[];
751 };
752
753export interface IndexHint {
754 type: IndexHints;
755 values: string[];
756}
757
758export interface IndexHintable {
759 /**
760 * MySQL only.
761 */
762 indexHints?: IndexHint[];
763}
764
765/**
766 * Options that are passed to any model creating a SELECT query
767 *
768 * A hash of options to describe the scope of the search
769 */
770export interface FindOptions<TAttributes = any>
771 extends QueryOptions, Filterable<TAttributes>, Projectable, Paranoid, IndexHintable
772{
773 /**
774 * A list of associations to eagerly load using a left join (a single association is also supported). Supported is either
775 * `{ include: Model1 }`, `{ include: [ Model1, Model2, ...]}`, `{ include: [{ model: Model1, as: 'Alias' }]}` or
776 * `{ include: [{ all: true }]}`.
777 * If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z' }`, you need to specify Z in
778 * the as attribute when eager loading Y).
779 */
780 include?: Includeable | Includeable[];
781
782 /**
783 * Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide
784 * several columns / functions to order by. Each element can be further wrapped in a two-element array. The
785 * first element is the column / function to order by, the second is the direction. For example:
786 * `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
787 */
788 order?: Order;
789
790 /**
791 * GROUP BY in sql
792 */
793 group?: GroupOption;
794
795 /**
796 * Limits how many items will be retrieved by the operation.
797 *
798 * If `limit` and `include` are used together, Sequelize will turn the `subQuery` option on by default.
799 * This is done to ensure that `limit` only impacts the Model on the same level as the `limit` option.
800 *
801 * You can disable this behavior by explicitly setting `subQuery: false`, however `limit` will then
802 * affect the total count of returned values, including eager-loaded associations, instead of just one table.
803 *
804 * @example
805 * // in the following query, `limit` only affects the "User" model.
806 * // This will return 2 users, each including all of their projects.
807 * User.findAll({
808 * limit: 2,
809 * include: [User.associations.projects],
810 * });
811 *
812 * @example
813 * // in the following query, `limit` affects the total number of returned values, eager-loaded associations included.
814 * // This may return 2 users, each with one project,
815 * // or 1 user with 2 projects.
816 * User.findAll({
817 * limit: 2,
818 * include: [User.associations.projects],
819 * subQuery: false,
820 * });
821 */
822 limit?: number;
823
824 // TODO: document this - this is an undocumented property but it exists and there are tests for it.
825 groupedLimit?: unknown;
826
827 /**
828 * Skip the results;
829 */
830 offset?: number;
831
832 /**
833 * Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE.
834 * Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model
835 * locks with joins. See [transaction.LOCK for an example](transaction#lock)
836 */
837 lock?:
838 | LOCK
839 | { level: LOCK; of: ModelStatic<Model> }
840 | boolean;
841 /**
842 * Skip locked rows. Only supported in Postgres.
843 */
844 skipLocked?: boolean;
845
846 /**
847 * Return raw result. See sequelize.query for more information.
848 */
849 raw?: boolean;
850
851 /**
852 * Select group rows after groups and aggregates are computed.
853 */
854 having?: WhereOptions<any>;
855
856 /**
857 * Use sub queries (internal).
858 *
859 * If unspecified, this will `true` by default if `limit` is specified, and `false` otherwise.
860 * See {@link FindOptions#limit} for more information.
861 */
862 subQuery?: boolean;
863}
864
865export interface NonNullFindOptions<TAttributes = any> extends FindOptions<TAttributes> {
866 /**
867 * Throw if nothing was found.
868 */
869 rejectOnEmpty: boolean | Error;
870}
871
872/**
873 * Options for Model.count method
874 */
875export interface CountOptions<TAttributes = any>
876 extends Logging, Transactionable, Filterable<TAttributes>, Projectable, Paranoid, Poolable
877{
878 /**
879 * Include options. See `find` for details
880 */
881 include?: Includeable | Includeable[];
882
883 /**
884 * Apply COUNT(DISTINCT(col))
885 */
886 distinct?: boolean;
887
888 /**
889 * GROUP BY in sql
890 * Used in conjunction with `attributes`.
891 *
892 * @see Projectable
893 */
894 group?: GroupOption;
895
896 /**
897 * The column to aggregate on.
898 */
899 col?: string;
900}
901
902/**
903 * Options for Model.count when GROUP BY is used
904 */
905export type CountWithOptions<TAttributes = any> = SetRequired<CountOptions<TAttributes>, 'group'>
906
907export interface FindAndCountOptions<TAttributes = any> extends CountOptions<TAttributes>, FindOptions<TAttributes> { }
908
909export interface GroupedCountResultItem {
910 [key: string]: unknown // projected attributes
911 count: number // the count for each group
912}
913
914/**
915 * Options for Model.build method
916 */
917export interface BuildOptions {
918 /**
919 * If set to true, values will ignore field and virtual setters.
920 */
921 raw?: boolean;
922
923 /**
924 * Is this record new
925 */
926 isNewRecord?: boolean;
927
928 /**
929 * An array of include options. A single option is also supported - Used to build prefetched/included model instances. See `set`
930 *
931 * TODO: See set
932 */
933 include?: Includeable | Includeable[];
934}
935
936export interface Silent {
937 /**
938 * If true, the updatedAt timestamp will not be updated.
939 *
940 * @default false
941 */
942 silent?: boolean;
943}
944
945/**
946 * Options for Model.create method
947 */
948export interface CreateOptions<TAttributes = any> extends BuildOptions, Logging, Silent, Transactionable, Hookable {
949 /**
950 * If set, only columns matching those in fields will be saved
951 */
952 fields?: (keyof TAttributes)[];
953
954 /**
955 * dialect specific ON CONFLICT DO NOTHING / INSERT IGNORE
956 */
957 ignoreDuplicates?: boolean;
958
959 /**
960 * Return the affected rows (only for postgres)
961 */
962 returning?: boolean | (keyof TAttributes)[];
963
964 /**
965 * If false, validations won't be run.
966 *
967 * @default true
968 */
969 validate?: boolean;
970
971}
972
973export interface Hookable {
974
975 /**
976 * If `false` the applicable hooks will not be called.
977 * The default value depends on the context.
978 */
979 hooks?: boolean
980
981}
982
983/**
984 * Options for Model.findOrCreate method
985 */
986export interface FindOrCreateOptions<TAttributes = any, TCreationAttributes = TAttributes>
987 extends FindOptions<TAttributes>, CreateOptions<TAttributes>
988{
989 /**
990 * Default values to use if building a new instance
991 */
992 defaults?: TCreationAttributes;
993}
994
995/**
996 * Options for Model.findOrBuild method
997 */
998export interface FindOrBuildOptions<TAttributes = any, TCreationAttributes = TAttributes>
999 extends FindOptions<TAttributes>, BuildOptions
1000{
1001 /**
1002 * Default values to use if building a new instance
1003 */
1004 defaults?: TCreationAttributes;
1005}
1006
1007/**
1008 * Options for Model.upsert method
1009 */
1010export interface UpsertOptions<TAttributes = any> extends Logging, Transactionable, SearchPathable, Hookable {
1011 /**
1012 * The fields to insert / update. Defaults to all fields
1013 */
1014 fields?: (keyof TAttributes)[];
1015
1016 /**
1017 * Return the affected rows (only for postgres)
1018 */
1019 returning?: boolean | (keyof TAttributes)[];
1020
1021 /**
1022 * Run validations before the row is inserted
1023 */
1024 validate?: boolean;
1025 /**
1026 * An optional parameter that specifies a where clause for the `ON CONFLICT` part of the query
1027 * (in particular: for applying to partial unique indexes).
1028 * Only supported in Postgres >= 9.5 and SQLite >= 3.24.0
1029 */
1030 conflictWhere?: WhereOptions<TAttributes>;
1031 /**
1032 * Optional override for the conflict fields in the ON CONFLICT part of the query.
1033 * Only supported in Postgres >= 9.5 and SQLite >= 3.24.0
1034 */
1035 conflictFields?: (keyof TAttributes)[];
1036}
1037
1038/**
1039 * Options for Model.bulkCreate method
1040 */
1041export interface BulkCreateOptions<TAttributes = any> extends Logging, Transactionable, Hookable, SearchPathable {
1042 /**
1043 * Fields to insert (defaults to all fields)
1044 */
1045 fields?: (keyof TAttributes)[];
1046
1047 /**
1048 * Should each row be subject to validation before it is inserted. The whole insert will fail if one row
1049 * fails validation
1050 */
1051 validate?: boolean;
1052
1053 /**
1054 * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if
1055 * options.hooks is true.
1056 */
1057 individualHooks?: boolean;
1058
1059 /**
1060 * Ignore duplicate values for primary keys?
1061 *
1062 * @default false
1063 */
1064 ignoreDuplicates?: boolean;
1065
1066 /**
1067 * Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL,
1068 * MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5).
1069 */
1070 updateOnDuplicate?: (keyof TAttributes)[];
1071
1072 /**
1073 * Include options. See `find` for details
1074 */
1075 include?: Includeable | Includeable[];
1076
1077 /**
1078 * Return all columns or only the specified columns for the affected rows (only for postgres)
1079 */
1080 returning?: boolean | (keyof TAttributes)[];
1081 /**
1082 * An optional parameter to specify a where clause for partial unique indexes
1083 * (note: `ON CONFLICT WHERE` not `ON CONFLICT DO UPDATE WHERE`).
1084 * Only supported in Postgres >= 9.5 and sqlite >= 9.5
1085 */
1086 conflictWhere?: WhereOptions<TAttributes>;
1087 /**
1088 * Optional override for the conflict fields in the ON CONFLICT part of the query.
1089 * Only supported in Postgres >= 9.5 and SQLite >= 3.24.0
1090 */
1091 conflictAttributes?: Array<keyof TAttributes>;
1092}
1093
1094/**
1095 * The options passed to Model.destroy in addition to truncate
1096 */
1097export interface TruncateOptions<TAttributes = any> extends Logging, Transactionable, Filterable<TAttributes>, Hookable {
1098 /**
1099 * Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the
1100 * named table, or to any tables added to the group due to CASCADE.
1101 *
1102 * @default false;
1103 */
1104 cascade?: boolean;
1105
1106 /**
1107 * If set to true, destroy will SELECT all records matching the where parameter and will execute before /
1108 * after destroy hooks on each row
1109 */
1110 individualHooks?: boolean;
1111
1112 /**
1113 * How many rows to delete
1114 */
1115 limit?: number;
1116
1117 /**
1118 * Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
1119 */
1120 force?: boolean;
1121
1122 /**
1123 * Only used in conjunction with `truncate`.
1124 * Automatically restart sequences owned by columns of the truncated table
1125 */
1126 restartIdentity?: boolean;
1127}
1128
1129/**
1130 * Options used for Model.destroy
1131 */
1132export interface DestroyOptions<TAttributes = any> extends TruncateOptions<TAttributes> {
1133 /**
1134 * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is
1135 * truncated the where and limit options are ignored
1136 */
1137 truncate?: boolean;
1138}
1139
1140/**
1141 * Options for Model.restore
1142 */
1143export interface RestoreOptions<TAttributes = any> extends Logging, Transactionable, Filterable<TAttributes>, Hookable {
1144
1145 /**
1146 * If set to true, restore will find all records within the where parameter and will execute before / after
1147 * bulkRestore hooks on each row
1148 */
1149 individualHooks?: boolean;
1150
1151 /**
1152 * How many rows to undelete
1153 */
1154 limit?: number;
1155}
1156
1157/**
1158 * Options used for Model.update
1159 */
1160export interface UpdateOptions<TAttributes = any> extends Logging, Transactionable, Paranoid, Hookable {
1161 /**
1162 * Options to describe the scope of the search.
1163 */
1164 where: WhereOptions<TAttributes>;
1165
1166 /**
1167 * Fields to update (defaults to all fields)
1168 */
1169 fields?: (keyof TAttributes)[];
1170
1171 /**
1172 * Should each row be subject to validation before it is inserted. The whole insert will fail if one row
1173 * fails validation.
1174 *
1175 * @default true
1176 */
1177 validate?: boolean;
1178
1179 /**
1180 * Whether or not to update the side effects of any virtual setters.
1181 *
1182 * @default true
1183 */
1184 sideEffects?: boolean;
1185
1186 /**
1187 * Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs.
1188 * A select is needed, because the row data needs to be passed to the hooks
1189 *
1190 * @default false
1191 */
1192 individualHooks?: boolean;
1193
1194 /**
1195 * Return the affected rows (only for postgres)
1196 */
1197 returning?: boolean | (keyof TAttributes)[];
1198
1199 /**
1200 * How many rows to update (only for mysql and mariadb)
1201 */
1202 limit?: number;
1203
1204 /**
1205 * If true, the updatedAt timestamp will not be updated.
1206 */
1207 silent?: boolean;
1208}
1209
1210/**
1211 * Options used for Model.aggregate
1212 */
1213export interface AggregateOptions<T extends DataType | unknown, TAttributes = any>
1214 extends QueryOptions, Filterable<TAttributes>, Paranoid
1215{
1216 /**
1217 * The type of the result. If `field` is a field in this Model, the default will be the type of that field,
1218 * otherwise defaults to float.
1219 */
1220 dataType?: string | T;
1221
1222 /**
1223 * Applies DISTINCT to the field being aggregated over
1224 */
1225 distinct?: boolean;
1226}
1227
1228// instance
1229
1230/**
1231 * Options used for Instance.increment method
1232 */
1233export interface IncrementDecrementOptions<TAttributes = any>
1234 extends Logging, Transactionable, Silent, SearchPathable, Filterable<TAttributes> { }
1235
1236/**
1237 * Options used for Instance.increment method
1238 */
1239export interface IncrementDecrementOptionsWithBy<TAttributes = any> extends IncrementDecrementOptions<TAttributes> {
1240 /**
1241 * The number to increment by
1242 *
1243 * @default 1
1244 */
1245 by?: number;
1246}
1247
1248/**
1249 * Options used for Instance.restore method
1250 */
1251export interface InstanceRestoreOptions extends Logging, Transactionable { }
1252
1253/**
1254 * Options used for Instance.destroy method
1255 */
1256export interface InstanceDestroyOptions extends Logging, Transactionable, Hookable {
1257 /**
1258 * If set to true, paranoid models will actually be deleted
1259 */
1260 force?: boolean;
1261}
1262
1263/**
1264 * Options used for Instance.update method
1265 */
1266export interface InstanceUpdateOptions<TAttributes = any> extends
1267 SaveOptions<TAttributes>, SetOptions, Filterable<TAttributes> { }
1268
1269/**
1270 * Options used for Instance.set method
1271 */
1272export interface SetOptions {
1273 /**
1274 * If set to true, field and virtual setters will be ignored
1275 */
1276 raw?: boolean;
1277
1278 /**
1279 * Clear all previously set data values
1280 */
1281 reset?: boolean;
1282}
1283
1284/**
1285 * Options used for Instance.save method
1286 */
1287export interface SaveOptions<TAttributes = any> extends Logging, Transactionable, Silent, Hookable {
1288 /**
1289 * An optional array of strings, representing database columns. If fields is provided, only those columns
1290 * will be validated and saved.
1291 */
1292 fields?: (keyof TAttributes)[];
1293
1294 /**
1295 * If false, validations won't be run.
1296 *
1297 * @default true
1298 */
1299 validate?: boolean;
1300
1301 /**
1302 * A flag that defines if null values should be passed as values or not.
1303 *
1304 * @default false
1305 */
1306 omitNull?: boolean;
1307
1308 /**
1309 * Return the affected rows (only for postgres)
1310 */
1311 returning?: boolean | Array<keyof TAttributes>;
1312}
1313
1314/**
1315 * Model validations, allow you to specify format/content/inheritance validations for each attribute of the
1316 * model.
1317 *
1318 * Validations are automatically run on create, update and save. You can also call validate() to manually
1319 * validate an instance.
1320 *
1321 * The validations are implemented by validator.js.
1322 */
1323export interface ModelValidateOptions {
1324 /**
1325 * - `{ is: ['^[a-z]+$','i'] }` will only allow letters
1326 * - `{ is: /^[a-z]+$/i }` also only allows letters
1327 */
1328 is?: string | readonly (string | RegExp)[] | RegExp | { msg: string; args: string | readonly (string | RegExp)[] | RegExp };
1329
1330 /**
1331 * - `{ not: ['[a-z]','i'] }` will not allow letters
1332 */
1333 not?: string | readonly (string | RegExp)[] | RegExp | { msg: string; args: string | readonly (string | RegExp)[] | RegExp };
1334
1335 /**
1336 * checks for email format (foo@bar.com)
1337 */
1338 isEmail?: boolean | { msg: string };
1339
1340 /**
1341 * checks for url format (http://foo.com)
1342 */
1343 isUrl?: boolean | { msg: string };
1344
1345 /**
1346 * checks for IPv4 (129.89.23.1) or IPv6 format
1347 */
1348 isIP?: boolean | { msg: string };
1349
1350 /**
1351 * checks for IPv4 (129.89.23.1)
1352 */
1353 isIPv4?: boolean | { msg: string };
1354
1355 /**
1356 * checks for IPv6 format
1357 */
1358 isIPv6?: boolean | { msg: string };
1359
1360 /**
1361 * will only allow letters
1362 */
1363 isAlpha?: boolean | { msg: string };
1364
1365 /**
1366 * will only allow alphanumeric characters, so "_abc" will fail
1367 */
1368 isAlphanumeric?: boolean | { msg: string };
1369
1370 /**
1371 * will only allow numbers
1372 */
1373 isNumeric?: boolean | { msg: string };
1374
1375 /**
1376 * checks for valid integers
1377 */
1378 isInt?: boolean | { msg: string };
1379
1380 /**
1381 * checks for valid floating point numbers
1382 */
1383 isFloat?: boolean | { msg: string };
1384
1385 /**
1386 * checks for any numbers
1387 */
1388 isDecimal?: boolean | { msg: string };
1389
1390 /**
1391 * checks for lowercase
1392 */
1393 isLowercase?: boolean | { msg: string };
1394
1395 /**
1396 * checks for uppercase
1397 */
1398 isUppercase?: boolean | { msg: string };
1399
1400 /**
1401 * won't allow null
1402 */
1403 notNull?: boolean | { msg: string };
1404
1405 /**
1406 * only allows null
1407 */
1408 isNull?: boolean | { msg: string };
1409
1410 /**
1411 * don't allow empty strings
1412 */
1413 notEmpty?: boolean | { msg: string };
1414
1415 /**
1416 * only allow a specific value
1417 */
1418 equals?: string | { msg: string };
1419
1420 /**
1421 * force specific substrings
1422 */
1423 contains?: string | { msg: string };
1424
1425 /**
1426 * check the value is not one of these
1427 */
1428 notIn?: ReadonlyArray<readonly any[]> | { msg: string; args: ReadonlyArray<readonly any[]> };
1429
1430 /**
1431 * check the value is one of these
1432 */
1433 isIn?: ReadonlyArray<readonly any[]> | { msg: string; args: ReadonlyArray<readonly any[]> };
1434
1435 /**
1436 * don't allow specific substrings
1437 */
1438 notContains?: readonly string[] | string | { msg: string; args: readonly string[] | string };
1439
1440 /**
1441 * only allow values with length between 2 and 10
1442 */
1443 len?: readonly [number, number] | { msg: string; args: readonly [number, number] };
1444
1445 /**
1446 * only allow uuids
1447 */
1448 isUUID?: number | { msg: string; args: number };
1449
1450 /**
1451 * only allow date strings
1452 */
1453 isDate?: boolean | { msg: string; args: boolean };
1454
1455 /**
1456 * only allow date strings after a specific date
1457 */
1458 isAfter?: string | { msg: string; args: string };
1459
1460 /**
1461 * only allow date strings before a specific date
1462 */
1463 isBefore?: string | { msg: string; args: string };
1464
1465 /**
1466 * only allow values
1467 */
1468 max?: number | { msg: string; args: readonly [number] };
1469
1470 /**
1471 * only allow values >= 23
1472 */
1473 min?: number | { msg: string; args: readonly [number] };
1474
1475 /**
1476 * only allow arrays
1477 */
1478 isArray?: boolean | { msg: string; args: boolean };
1479
1480 /**
1481 * check for valid credit card numbers
1482 */
1483 isCreditCard?: boolean | { msg: string; args: boolean };
1484
1485 // TODO: Enforce 'rest' indexes to have type `(value: unknown) => boolean`
1486 // Blocked by: https://github.com/microsoft/TypeScript/issues/7765
1487 /**
1488 * Custom validations are also possible
1489 */
1490 [name: string]: unknown;
1491}
1492
1493/**
1494 * Interface for indexes property in InitOptions
1495 */
1496export type ModelIndexesOptions = IndexesOptions
1497
1498/**
1499 * Interface for name property in InitOptions
1500 */
1501export interface ModelNameOptions {
1502 /**
1503 * Singular model name
1504 */
1505 singular?: string;
1506
1507 /**
1508 * Plural model name
1509 */
1510 plural?: string;
1511}
1512
1513/**
1514 * Interface for getterMethods in InitOptions
1515 */
1516export interface ModelGetterOptions<M extends Model = Model> {
1517 [name: string]: (this: M) => unknown;
1518}
1519
1520/**
1521 * Interface for setterMethods in InitOptions
1522 */
1523export interface ModelSetterOptions<M extends Model = Model> {
1524 [name: string]: (this: M, val: any) => void;
1525}
1526
1527/**
1528 * Interface for Define Scope Options
1529 */
1530export interface ModelScopeOptions<TAttributes = any> {
1531 /**
1532 * Name of the scope and it's query
1533 */
1534 [scopeName: string]: FindOptions<TAttributes> | ((...args: readonly any[]) => FindOptions<TAttributes>);
1535}
1536
1537/**
1538 * General column options
1539 */
1540export interface ColumnOptions {
1541 /**
1542 * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an
1543 * instance is saved.
1544 *
1545 * @default true
1546 */
1547 allowNull?: boolean;
1548
1549 /**
1550 * If set, sequelize will map the attribute name to a different name in the database
1551 */
1552 field?: string;
1553
1554 /**
1555 * A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
1556 */
1557 defaultValue?: unknown;
1558}
1559
1560/**
1561 * References options for the column's attributes
1562 */
1563export interface ModelAttributeColumnReferencesOptions {
1564 /**
1565 * If this column references another table, provide it here as a Model, or a string
1566 */
1567 model?: TableName | ModelType;
1568
1569 /**
1570 * The column of the foreign table that this column references
1571 */
1572 key?: string;
1573
1574 /**
1575 * When to check for the foreign key constraing
1576 *
1577 * PostgreSQL only
1578 */
1579 deferrable?: Deferrable;
1580}
1581
1582/**
1583 * Column options for the model schema attributes
1584 */
1585export interface ModelAttributeColumnOptions<M extends Model = Model> extends ColumnOptions {
1586 /**
1587 * A string or a data type
1588 */
1589 type: DataType;
1590
1591 /**
1592 * If true, the column will get a unique constraint. If a string is provided, the column will be part of a
1593 * composite unique index. If multiple columns have the same string, they will be part of the same unique
1594 * index
1595 */
1596 unique?: boolean | string | { name: string; msg: string };
1597
1598 /**
1599 * Primary key flag
1600 */
1601 primaryKey?: boolean;
1602
1603 /**
1604 * Is this field an auto increment field
1605 */
1606 autoIncrement?: boolean;
1607
1608 /**
1609 * If this field is a Postgres auto increment field, use Postgres `GENERATED BY DEFAULT AS IDENTITY` instead of `SERIAL`. Postgres 10+ only.
1610 */
1611 autoIncrementIdentity?: boolean;
1612
1613 /**
1614 * Comment for the database
1615 */
1616 comment?: string;
1617
1618 /**
1619 * An object with reference configurations or the column name as string
1620 */
1621 references?: string | ModelAttributeColumnReferencesOptions;
1622
1623 /**
1624 * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
1625 * NO ACTION
1626 */
1627 onUpdate?: string;
1628
1629 /**
1630 * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
1631 * NO ACTION
1632 */
1633 onDelete?: string;
1634
1635
1636 /**
1637 * An object of validations to execute for this column every time the model is saved. Can be either the
1638 * name of a validation provided by validator.js, a validation function provided by extending validator.js
1639 * (see the
1640 * `DAOValidator` property for more details), or a custom validation function. Custom validation functions
1641 * are called with the value of the field, and can possibly take a second callback argument, to signal that
1642 * they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it
1643 * it is async, the callback should be called with the error text.
1644 */
1645 validate?: ModelValidateOptions;
1646
1647 /**
1648 * Usage in object notation
1649 *
1650 * ```js
1651 * class MyModel extends Model {}
1652 * MyModel.init({
1653 * states: {
1654 * type: Sequelize.ENUM,
1655 * values: ['active', 'pending', 'deleted']
1656 * }
1657 * }, { sequelize })
1658 * ```
1659 */
1660 values?: readonly string[];
1661
1662 /**
1663 * Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying
1664 * values.
1665 */
1666 get?(this: M): unknown;
1667
1668 /**
1669 * Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the
1670 * underlying values.
1671 */
1672 set?(this: M, val: unknown): void;
1673}
1674
1675/**
1676 * Interface for Attributes provided for all columns in a model
1677 */
1678export type ModelAttributes<M extends Model = Model, TAttributes = any> = {
1679 /**
1680 * The description of a database column
1681 */
1682 [name in keyof TAttributes]: DataType | ModelAttributeColumnOptions<M>;
1683}
1684
1685/**
1686 * Possible types for primary keys
1687 */
1688export type Identifier = number | bigint | string | Buffer;
1689
1690/**
1691 * Options for model definition
1692 */
1693export interface ModelOptions<M extends Model = Model> {
1694 /**
1695 * Define the default search scope to use for this model. Scopes have the same form as the options passed to
1696 * find / findAll.
1697 */
1698 defaultScope?: FindOptions<Attributes<M>>;
1699
1700 /**
1701 * More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about
1702 * how scopes are defined, and what you can do with them
1703 */
1704 scopes?: ModelScopeOptions<Attributes<M>>;
1705
1706 /**
1707 * Don't persits null values. This means that all columns with null values will not be saved.
1708 */
1709 omitNull?: boolean;
1710
1711 /**
1712 * Adds createdAt and updatedAt timestamps to the model. Default true.
1713 */
1714 timestamps?: boolean;
1715
1716 /**
1717 * Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs
1718 * timestamps=true to work. Default false.
1719 */
1720 paranoid?: boolean;
1721
1722 /**
1723 * Converts all camelCased columns to underscored if true. Default false.
1724 */
1725 underscored?: boolean;
1726
1727 /**
1728 * Indicates if the model's table has a trigger associated with it. Default false.
1729 */
1730 hasTrigger?: boolean;
1731
1732 /**
1733 * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name.
1734 * Otherwise, the dao name will be pluralized. Default false.
1735 */
1736 freezeTableName?: boolean;
1737
1738 /**
1739 * An object with two attributes, `singular` and `plural`, which are used when this model is associated to
1740 * others.
1741 */
1742 name?: ModelNameOptions;
1743
1744 /**
1745 * Set name of the model. By default its same as Class name.
1746 */
1747 modelName?: string;
1748
1749 /**
1750 * Indexes for the provided database table
1751 */
1752 indexes?: readonly ModelIndexesOptions[];
1753
1754 /**
1755 * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps
1756 * must be true. Not affected by underscored setting.
1757 */
1758 createdAt?: string | boolean;
1759
1760 /**
1761 * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps
1762 * must be true. Not affected by underscored setting.
1763 */
1764 deletedAt?: string | boolean;
1765
1766 /**
1767 * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps
1768 * must be true. Not affected by underscored setting.
1769 */
1770 updatedAt?: string | boolean;
1771
1772 /**
1773 * @default pluralized model name, unless freezeTableName is true, in which case it uses model name
1774 * verbatim
1775 */
1776 tableName?: string;
1777
1778 schema?: string;
1779
1780 /**
1781 * You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
1782 */
1783 engine?: string;
1784
1785 charset?: string;
1786
1787 /**
1788 * Finaly you can specify a comment for the table in MySQL and PG
1789 */
1790 comment?: string;
1791
1792 collate?: string;
1793
1794 /**
1795 * Set the initial AUTO_INCREMENT value for the table in MySQL.
1796 */
1797 initialAutoIncrement?: string;
1798
1799 /**
1800 * An object of hook function that are called before and after certain lifecycle events.
1801 * See Hooks for more information about hook
1802 * functions and their signatures. Each property can either be a function, or an array of functions.
1803 */
1804 hooks?: Partial<ModelHooks<M, Attributes<M>>>;
1805
1806 /**
1807 * An object of model wide validations. Validations have access to all model values via `this`. If the
1808 * validator function takes an argument, it is asumed to be async, and is called with a callback that
1809 * accepts an optional error.
1810 */
1811 validate?: ModelValidateOptions;
1812
1813 /**
1814 * Allows defining additional setters that will be available on model instances.
1815 */
1816 setterMethods?: ModelSetterOptions<M>;
1817
1818 /**
1819 * Allows defining additional getters that will be available on model instances.
1820 */
1821 getterMethods?: ModelGetterOptions<M>;
1822
1823 /**
1824 * Enable optimistic locking.
1825 * When enabled, sequelize will add a version count attribute to the model and throw an
1826 * OptimisticLockingError error when stale instances are saved.
1827 * - If string: Uses the named attribute.
1828 * - If boolean: Uses `version`.
1829 *
1830 * @default false
1831 */
1832 version?: boolean | string;
1833
1834 /**
1835 * Specify the scopes merging strategy (default 'overwrite'). Valid values are 'and' and 'overwrite'.
1836 * When the 'and' strategy is set, scopes will be grouped using the Op.and operator.
1837 * For instance merging scopes containing `{ where: { myField: 1 }}` and `{ where: { myField: 2 }}` will result in
1838 * `{ where: { [Op.and]: [{ myField: 1 }, { myField: 2 }] } }`.
1839 * When the 'overwrite' strategy is set, scopes containing the same attribute in a where clause will be overwritten by the lastly defined one.
1840 * For instance merging scopes containing `{ where: { myField: 1 }}` and `{ where: { myField: 2 }}` will result in
1841 * `{ where: { myField: 2 } }`.
1842 *
1843 * @default false
1844 */
1845 whereMergeStrategy?: 'and' | 'overwrite';
1846}
1847
1848/**
1849 * Options passed to [[Model.init]]
1850 */
1851export interface InitOptions<M extends Model = Model> extends ModelOptions<M> {
1852 /**
1853 * The sequelize connection. Required ATM.
1854 */
1855 sequelize: Sequelize;
1856}
1857
1858/**
1859 * AddScope Options for Model.addScope
1860 */
1861export interface AddScopeOptions {
1862 /**
1863 * If a scope of the same name already exists, should it be overwritten?
1864 */
1865 override: boolean;
1866}
1867
1868export abstract class Model<TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes>
1869 extends Hooks<Model<TModelAttributes, TCreationAttributes>, TModelAttributes, TCreationAttributes>
1870{
1871 /**
1872 * A dummy variable that doesn't exist on the real object. This exists so
1873 * Typescript can infer the type of the attributes in static functions. Don't
1874 * try to access this!
1875 *
1876 * Before using these, I'd tried typing out the functions without them, but
1877 * Typescript fails to infer `TAttributes` in signatures like the below.
1878 *
1879 * ```ts
1880 * public static findOne<M extends Model<TAttributes>, TAttributes>(
1881 * this: { new(): M },
1882 * options: NonNullFindOptions<TAttributes>
1883 * ): Promise<M>;
1884 * ```
1885 *
1886 * @deprecated This property will become a Symbol in v7 to prevent collisions.
1887 * Use Attributes<Model> instead of this property to be forward-compatible.
1888 */
1889 _attributes: TModelAttributes; // TODO [>6]: make this a non-exported symbol (same as the one in hooks.d.ts)
1890
1891 /**
1892 * Object that contains underlying model data
1893 */
1894 dataValues: TModelAttributes;
1895
1896 /**
1897 * A similar dummy variable that doesn't exist on the real object. Do not
1898 * try to access this in real code.
1899 *
1900 * @deprecated This property will become a Symbol in v7 to prevent collisions.
1901 * Use CreationAttributes<Model> instead of this property to be forward-compatible.
1902 */
1903 _creationAttributes: TCreationAttributes; // TODO [>6]: make this a non-exported symbol (same as the one in hooks.d.ts)
1904
1905 /** The name of the database table */
1906 public static readonly tableName: string;
1907
1908 /**
1909 * The name of the primary key attribute
1910 */
1911 public static readonly primaryKeyAttribute: string;
1912
1913 /**
1914 * The name of the primary key attributes
1915 */
1916 public static readonly primaryKeyAttributes: readonly string[];
1917
1918 /**
1919 * An object hash from alias to association object
1920 */
1921 public static readonly associations: {
1922 [key: string]: Association;
1923 };
1924
1925 /**
1926 * The options that the model was initialized with
1927 */
1928 public static readonly options: InitOptions;
1929
1930 // TODO [>7]: Remove `rawAttributes` in v8
1931 /**
1932 * The attributes of the model.
1933 *
1934 * @deprecated use {@link Model.getAttributes} for better typings.
1935 */
1936 public static readonly rawAttributes: { [attribute: string]: ModelAttributeColumnOptions };
1937
1938 /**
1939 * Returns the attributes of the model
1940 */
1941 public static getAttributes<M extends Model>(this: ModelStatic<M>): {
1942 readonly [Key in keyof Attributes<M>]: ModelAttributeColumnOptions
1943 };
1944
1945 /**
1946 * Reference to the sequelize instance the model was initialized with
1947 */
1948 public static readonly sequelize?: Sequelize;
1949
1950 /**
1951 * Initialize a model, representing a table in the DB, with attributes and options.
1952 *
1953 * 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:
1954 *
1955 * ```js
1956 * Project.init({
1957 * columnA: {
1958 * type: Sequelize.BOOLEAN,
1959 * validate: {
1960 * is: ['[a-z]','i'], // will only allow letters
1961 * max: 23, // only allow values <= 23
1962 * isIn: {
1963 * args: [['en', 'zh']],
1964 * msg: "Must be English or Chinese"
1965 * }
1966 * },
1967 * field: 'column_a'
1968 * // Other attributes here
1969 * },
1970 * columnB: Sequelize.STRING,
1971 * columnC: 'MY VERY OWN COLUMN TYPE'
1972 * }, {sequelize})
1973 *
1974 * sequelize.models.modelName // The model will now be available in models under the class name
1975 * ```
1976 *
1977 * 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.
1978 *
1979 * For a list of possible data types, see https://sequelize.org/master/en/latest/docs/models-definition/#data-types
1980 *
1981 * For more about getters and setters, see https://sequelize.org/master/en/latest/docs/models-definition/#getters-setters
1982 *
1983 * For more about instance and class methods, see https://sequelize.org/master/en/latest/docs/models-definition/#expansion-of-models
1984 *
1985 * For more about validation, see https://sequelize.org/master/en/latest/docs/models-definition/#validations
1986 *
1987 * @param attributes
1988 * An object, where each attribute is a column of the table. Each column can be either a DataType, a
1989 * string or a type-description object, with the properties described below:
1990 * @param options These options are merged with the default define options provided to the Sequelize constructor
1991 * @returns Return the initialized model
1992 */
1993 public static init<MS extends ModelStatic<Model>, M extends InstanceType<MS>>(
1994 this: MS,
1995 attributes: ModelAttributes<
1996 M,
1997 // 'foreign keys' are optional in Model.init as they are added by association declaration methods
1998 Optional<Attributes<M>, BrandedKeysOf<Attributes<M>, typeof ForeignKeyBrand>>
1999 >,
2000 options: InitOptions<M>
2001 ): MS;
2002
2003 /**
2004 * Remove attribute from model definition
2005 *
2006 * @param attribute
2007 */
2008 public static removeAttribute(attribute: string): void;
2009
2010 /**
2011 * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the
2012 * model instance (this)
2013 */
2014 public static sync<M extends Model>(options?: SyncOptions): Promise<M>;
2015
2016 /**
2017 * Drop the table represented by this Model
2018 *
2019 * @param options
2020 */
2021 public static drop(options?: DropOptions): Promise<void>;
2022
2023 /**
2024 * Apply a schema to this model. For postgres, this will actually place the schema in front of the table
2025 * name
2026 * - `"schema"."tableName"`, while the schema will be prepended to the table name for mysql and
2027 * sqlite - `'schema.tablename'`.
2028 *
2029 * @param schema The name of the schema
2030 * @param options
2031 */
2032 public static schema<M extends Model>(
2033 this: ModelStatic<M>,
2034 schema: string,
2035 options?: SchemaOptions
2036 ): ModelCtor<M>;
2037
2038 /**
2039 * Get the tablename of the model, taking schema into account. The method will return The name as a string
2040 * if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties.
2041 *
2042 * @param options The hash of options from any query. You can use one model to access tables with matching
2043 * schemas by overriding `getTableName` and using custom key/values to alter the name of the table.
2044 * (eg.
2045 * subscribers_1, subscribers_2)
2046 */
2047 public static getTableName(): string | {
2048 tableName: string;
2049 schema: string;
2050 delimiter: string;
2051 };
2052
2053 /**
2054 * Apply a scope created in `define` to the model. First let's look at how to create scopes:
2055 * ```js
2056 * class MyModel extends Model {}
2057 * MyModel.init(attributes, {
2058 * defaultScope: {
2059 * where: {
2060 * username: 'dan'
2061 * },
2062 * limit: 12
2063 * },
2064 * scopes: {
2065 * isALie: {
2066 * where: {
2067 * stuff: 'cake'
2068 * }
2069 * },
2070 * complexFunction(email, accessLevel) {
2071 * return {
2072 * where: {
2073 * email: {
2074 * [Op.like]: email
2075 * },
2076 * accesss_level {
2077 * [Op.gte]: accessLevel
2078 * }
2079 * }
2080 * }
2081 * }
2082 * },
2083 * sequelize,
2084 * })
2085 * ```
2086 * Now, since you defined a default scope, every time you do Model.find, the default scope is appended to
2087 * your query. Here's a couple of examples:
2088 * ```js
2089 * Model.findAll() // WHERE username = 'dan'
2090 * Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
2091 * ```
2092 *
2093 * To invoke scope functions you can do:
2094 * ```js
2095 * Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
2096 * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
2097 * ```
2098 *
2099 * @returns Model A reference to the model, with the scope(s) applied. Calling scope again on the returned
2100 * model will clear the previous scope.
2101 */
2102 public static scope<M extends Model>(
2103 this: ModelStatic<M>,
2104 options?: string | ScopeOptions | readonly (string | ScopeOptions)[] | WhereAttributeHash<M>
2105 ): ModelCtor<M>;
2106
2107 /**
2108 * Add a new scope to the model
2109 *
2110 * This is especially useful for adding scopes with includes, when the model you want to
2111 * include is not available at the time this model is defined. By default this will throw an
2112 * error if a scope with that name already exists. Pass `override: true` in the options
2113 * object to silence this error.
2114 */
2115 public static addScope<M extends Model>(
2116 this: ModelStatic<M>,
2117 name: string,
2118 scope: FindOptions<Attributes<M>>,
2119 options?: AddScopeOptions
2120 ): void;
2121 public static addScope<M extends Model>(
2122 this: ModelStatic<M>,
2123 name: string,
2124 scope: (...args: readonly any[]) => FindOptions<Attributes<M>>,
2125 options?: AddScopeOptions
2126 ): void;
2127
2128 /**
2129 * Search for multiple instances.
2130 *
2131 * __Simple search using AND and =__
2132 * ```js
2133 * Model.findAll({
2134 * where: {
2135 * attr1: 42,
2136 * attr2: 'cake'
2137 * }
2138 * })
2139 * ```
2140 * ```sql
2141 * WHERE attr1 = 42 AND attr2 = 'cake'
2142 * ```
2143 *
2144 * __Using greater than, less than etc.__
2145 * ```js
2146 *
2147 * Model.findAll({
2148 * where: {
2149 * attr1: {
2150 * gt: 50
2151 * },
2152 * attr2: {
2153 * lte: 45
2154 * },
2155 * attr3: {
2156 * in: [1,2,3]
2157 * },
2158 * attr4: {
2159 * ne: 5
2160 * }
2161 * }
2162 * })
2163 * ```
2164 * ```sql
2165 * WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
2166 * ```
2167 * 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],
2168 * [Op.notILike], '..'/[Op.between], '!..'/[Op.notBetween], '&&'/[Op.overlap], '@>'/[Op.contains], '<@'/[Op.contained]`
2169 *
2170 * __Queries using OR__
2171 * ```js
2172 * Model.findAll({
2173 * where: Sequelize.and(
2174 * { name: 'a project' },
2175 * Sequelize.or(
2176 * { id: [1,2,3] },
2177 * { id: { gt: 10 } }
2178 * )
2179 * )
2180 * })
2181 * ```
2182 * ```sql
2183 * WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
2184 * ```
2185 *
2186 * The success listener is called with an array of instances if the query succeeds.
2187 *
2188 * @see {Sequelize#query}
2189 */
2190 public static findAll<M extends Model>(
2191 this: ModelStatic<M>,
2192 options?: FindOptions<Attributes<M>>): Promise<M[]>;
2193
2194 /**
2195 * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will
2196 * always be called with a single instance.
2197 */
2198 public static findByPk<M extends Model>(
2199 this: ModelStatic<M>,
2200 identifier: Identifier,
2201 options: Omit<NonNullFindOptions<Attributes<M>>, 'where'>
2202 ): Promise<M>;
2203 public static findByPk<M extends Model>(
2204 this: ModelStatic<M>,
2205 identifier?: Identifier,
2206 options?: Omit<FindOptions<Attributes<M>>, 'where'>
2207 ): Promise<M | null>;
2208
2209 /**
2210 * Search for a single instance. Returns the first instance found, or null if none can be found.
2211 */
2212 public static findOne<M extends Model>(
2213 this: ModelStatic<M>,
2214 options: NonNullFindOptions<Attributes<M>>
2215 ): Promise<M>;
2216 public static findOne<M extends Model>(
2217 this: ModelStatic<M>,
2218 options?: FindOptions<Attributes<M>>
2219 ): Promise<M | null>;
2220
2221 /**
2222 * Run an aggregation method on the specified field
2223 *
2224 * @param field The field to aggregate over. Can be a field name or *
2225 * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc.
2226 * @param options Query options. See sequelize.query for full options
2227 * @returns Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in
2228 * which case the complete data result is returned.
2229 */
2230 public static aggregate<T, M extends Model>(
2231 this: ModelStatic<M>,
2232 field: keyof Attributes<M> | '*',
2233 aggregateFunction: string,
2234 options?: AggregateOptions<T, Attributes<M>>
2235 ): Promise<T>;
2236
2237 /**
2238 * Count number of records if group by is used
2239 *
2240 * @returns Returns count for each group and the projected attributes.
2241 */
2242 public static count<M extends Model>(
2243 this: ModelStatic<M>,
2244 options: CountWithOptions<Attributes<M>>
2245 ): Promise<GroupedCountResultItem[]>;
2246
2247 /**
2248 * Count the number of records matching the provided where clause.
2249 *
2250 * If you provide an `include` option, the number of matching associations will be counted instead.
2251 *
2252 * @returns Returns count for each group and the projected attributes.
2253 */
2254 public static count<M extends Model>(
2255 this: ModelStatic<M>,
2256 options?: Omit<CountOptions<Attributes<M>>, 'group'>
2257 ): Promise<number>;
2258
2259 /**
2260 * Find all the rows matching your query, within a specified offset / limit, and get the total number of
2261 * rows matching your query. This is very useful for paging
2262 *
2263 * ```js
2264 * Model.findAndCountAll({
2265 * where: ...,
2266 * limit: 12,
2267 * offset: 12
2268 * }).then(result => {
2269 * ...
2270 * })
2271 * ```
2272 * In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return
2273 * the
2274 * total number of rows that matched your query.
2275 *
2276 * When you add includes, only those which are required (either because they have a where clause, or
2277 * because
2278 * `required` is explicitly set to true on the include) will be added to the count part.
2279 *
2280 * Suppose you want to find all users who have a profile attached:
2281 * ```js
2282 * User.findAndCountAll({
2283 * include: [
2284 * { model: Profile, required: true}
2285 * ],
2286 * limit: 3
2287 * });
2288 * ```
2289 * Because the include for `Profile` has `required` set it will result in an inner join, and only the users
2290 * who have a profile will be counted. If we remove `required` from the include, both users with and
2291 * without
2292 * profiles will be counted
2293 *
2294 * This function also support grouping, when `group` is provided, the count will be an array of objects
2295 * containing the count for each group and the projected attributes.
2296 * ```js
2297 * User.findAndCountAll({
2298 * group: 'type'
2299 * });
2300 * ```
2301 */
2302 public static findAndCountAll<M extends Model>(
2303 this: ModelStatic<M>,
2304 options?: Omit<FindAndCountOptions<Attributes<M>>, 'group'>
2305 ): Promise<{ rows: M[]; count: number }>;
2306 public static findAndCountAll<M extends Model>(
2307 this: ModelStatic<M>,
2308 options: SetRequired<FindAndCountOptions<Attributes<M>>, 'group'>
2309 ): Promise<{ rows: M[]; count: GroupedCountResultItem[] }>;
2310
2311 /**
2312 * Find the maximum value of field
2313 */
2314 public static max<T extends DataType | unknown, M extends Model>(
2315 this: ModelStatic<M>,
2316 field: keyof Attributes<M>,
2317 options?: AggregateOptions<T, Attributes<M>>
2318 ): Promise<T>;
2319
2320 /**
2321 * Find the minimum value of field
2322 */
2323 public static min<T extends DataType | unknown, M extends Model>(
2324 this: ModelStatic<M>,
2325 field: keyof Attributes<M>,
2326 options?: AggregateOptions<T, Attributes<M>>
2327 ): Promise<T>;
2328
2329 /**
2330 * Find the sum of field
2331 */
2332 public static sum<T extends DataType | unknown, M extends Model>(
2333 this: ModelStatic<M>,
2334 field: keyof Attributes<M>,
2335 options?: AggregateOptions<T, Attributes<M>>
2336 ): Promise<number>;
2337
2338 /**
2339 * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
2340 */
2341 public static build<M extends Model>(
2342 this: ModelStatic<M>,
2343 record?: CreationAttributes<M>,
2344 options?: BuildOptions
2345 ): M;
2346
2347 /**
2348 * Undocumented bulkBuild
2349 */
2350 public static bulkBuild<M extends Model>(
2351 this: ModelStatic<M>,
2352 records: ReadonlyArray<CreationAttributes<M>>,
2353 options?: BuildOptions
2354 ): M[];
2355
2356 /**
2357 * Builds a new model instance and calls save on it.
2358 */
2359 public static create<
2360 M extends Model,
2361 O extends CreateOptions<Attributes<M>> = CreateOptions<Attributes<M>>
2362 >(
2363 this: ModelStatic<M>,
2364 values?: CreationAttributes<M>,
2365 options?: O
2366 ): Promise<O extends { returning: false } | { ignoreDuplicates: true } ? void : M>;
2367
2368 /**
2369 * Find a row that matches the query, or build (but don't save) the row if none is found.
2370 * The successful result of the promise will be (instance, initialized) - Make sure to use `.then(([...]))`
2371 */
2372 public static findOrBuild<M extends Model>(
2373 this: ModelStatic<M>,
2374 options: FindOrBuildOptions<
2375 Attributes<M>,
2376 CreationAttributes<M>
2377 >
2378 ): Promise<[M, boolean]>;
2379
2380 /**
2381 * Find a row that matches the query, or build and save the row if none is found
2382 * The successful result of the promise will be (instance, created) - Make sure to use `.then(([...]))`
2383 *
2384 * If no transaction is passed in the `options` object, a new transaction will be created internally, to
2385 * prevent the race condition where a matching row is created by another connection after the find but
2386 * before the insert call. However, it is not always possible to handle this case in SQLite, specifically
2387 * if one transaction inserts and another tries to select before the first one has comitted. In this case,
2388 * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint
2389 * will be created instead, and any unique constraint violation will be handled internally.
2390 */
2391 public static findOrCreate<M extends Model>(
2392 this: ModelStatic<M>,
2393 options: FindOrCreateOptions<Attributes<M>, CreationAttributes<M>>
2394 ): Promise<[M, boolean]>;
2395
2396 /**
2397 * A more performant findOrCreate that will not work under a transaction (at least not in postgres)
2398 * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
2399 */
2400 public static findCreateFind<M extends Model>(
2401 this: ModelStatic<M>,
2402 options: FindOrCreateOptions<Attributes<M>, CreationAttributes<M>>
2403 ): Promise<[M, boolean]>;
2404
2405 /**
2406 * Insert or update a single row. An update will be executed if a row which matches the supplied values on
2407 * either the primary key or a unique key is found. Note that the unique index must be defined in your
2408 * sequelize model and not just in the table. Otherwise you may experience a unique constraint violation,
2409 * because sequelize fails to identify the row that should be updated.
2410 *
2411 * **Implementation details:**
2412 *
2413 * * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values`
2414 * * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN
2415 * unique_constraint UPDATE
2416 * * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed
2417 * regardless
2418 * of whether the row already existed or not
2419 *
2420 * **Note** that SQLite returns null for created, no matter if the row was created or updated. This is
2421 * because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know
2422 * whether the row was inserted or not.
2423 */
2424 public static upsert<M extends Model>(
2425 this: ModelStatic<M>,
2426 values: CreationAttributes<M>,
2427 options?: UpsertOptions<Attributes<M>>
2428 ): Promise<[M, boolean | null]>;
2429
2430 /**
2431 * Create and insert multiple instances in bulk.
2432 *
2433 * The success handler is passed an array of instances, but please notice that these may not completely
2434 * represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to
2435 * obtain
2436 * back automatically generated IDs and other default values in a way that can be mapped to multiple
2437 * records. To obtain Instances for the newly created values, you will need to query for them again.
2438 *
2439 * @param records List of objects (key/value pairs) to create instances from
2440 */
2441 public static bulkCreate<M extends Model>(
2442 this: ModelStatic<M>,
2443 records: ReadonlyArray<CreationAttributes<M>>,
2444 options?: BulkCreateOptions<Attributes<M>>
2445 ): Promise<M[]>;
2446
2447 /**
2448 * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
2449 */
2450 public static truncate<M extends Model>(
2451 this: ModelStatic<M>,
2452 options?: TruncateOptions<Attributes<M>>
2453 ): Promise<void>;
2454
2455 /**
2456 * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
2457 *
2458 * @returns Promise<number> The number of destroyed rows
2459 */
2460 public static destroy<M extends Model>(
2461 this: ModelStatic<M>,
2462 options?: DestroyOptions<Attributes<M>>
2463 ): Promise<number>;
2464
2465 /**
2466 * Restore multiple instances if `paranoid` is enabled.
2467 */
2468 public static restore<M extends Model>(
2469 this: ModelStatic<M>,
2470 options?: RestoreOptions<Attributes<M>>
2471 ): Promise<void>;
2472
2473 /**
2474 * Update multiple instances that match the where options. The promise returns an array with one or two
2475 * elements. The first element is always the number of affected rows, while the second element is the actual
2476 * affected rows (only supported in postgres and mssql with `options.returning` true.)
2477 */
2478 public static update<M extends Model>(
2479 this: ModelStatic<M>,
2480 values: {
2481 [key in keyof Attributes<M>]?: Attributes<M>[key] | Fn | Col | Literal;
2482 },
2483 options: Omit<UpdateOptions<Attributes<M>>, 'returning'>
2484 & { returning: Exclude<UpdateOptions<Attributes<M>>['returning'], undefined | false> }
2485 ): Promise<[affectedCount: number, affectedRows: M[]]>;
2486
2487 /**
2488 * Update multiple instances that match the where options. The promise returns an array with one or two
2489 * elements. The first element is always the number of affected rows, while the second element is the actual
2490 * affected rows (only supported in postgres and mssql with `options.returning` true.)
2491 */
2492 public static update<M extends Model>(
2493 this: ModelStatic<M>,
2494 values: {
2495 [key in keyof Attributes<M>]?: Attributes<M>[key] | Fn | Col | Literal;
2496 },
2497 options: UpdateOptions<Attributes<M>>
2498 ): Promise<[affectedCount: number]>;
2499
2500 /**
2501 * Increments the value of one or more attributes.
2502 *
2503 * The increment is done using a `SET column = column + X WHERE foo = 'bar'` query.
2504 *
2505 * @example <caption>increment number by 1</caption>
2506 * ```javascript
2507 * Model.increment('number', { where: { foo: 'bar' });
2508 * ```
2509 *
2510 * @example <caption>increment number and count by 2</caption>
2511 * ```javascript
2512 * Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
2513 * ```
2514 *
2515 * @example <caption>increment answer by 42, and decrement tries by 1</caption>
2516 * ```javascript
2517 * // `by` cannot be used, as each attribute specifies its own value
2518 * Model.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } });
2519 * ```
2520 *
2521 * @param fields If a string is provided, that column is incremented by the
2522 * value of `by` given in options. If an array is provided, the same is true for each column.
2523 * If an object is provided, each key is incremented by the corresponding value, `by` is ignored.
2524 *
2525 * @returns an array of affected rows or with affected count if `options.returning` is true, whenever supported by dialect
2526 */
2527 static increment<M extends Model>(
2528 this: ModelStatic<M>,
2529 fields: AllowReadonlyArray<keyof Attributes<M>>,
2530 options: IncrementDecrementOptionsWithBy<Attributes<M>>
2531 ): Promise<[affectedRows: M[], affectedCount?: number]>;
2532 static increment<M extends Model>(
2533 this: ModelStatic<M>,
2534 fields: { [key in keyof Attributes<M>]?: number },
2535 options: IncrementDecrementOptions<Attributes<M>>
2536 ): Promise<[affectedRows: M[], affectedCount?: number]>;
2537
2538 /**
2539 * Decrements the value of one or more attributes.
2540 *
2541 * Works like {@link Model.increment}
2542 *
2543 * @param fields If a string is provided, that column is incremented by the
2544 * value of `by` given in options. If an array is provided, the same is true for each column.
2545 * If an object is provided, each key is incremented by the corresponding value, `by` is ignored.
2546 *
2547 * @returns an array of affected rows or with affected count if `options.returning` is true, whenever supported by dialect
2548 *
2549 * @since 4.36.0
2550 */
2551 static decrement<M extends Model>(
2552 this: ModelStatic<M>,
2553 fields: AllowReadonlyArray<keyof Attributes<M>>,
2554 options: IncrementDecrementOptionsWithBy<Attributes<M>>
2555 ): Promise<[affectedRows: M[], affectedCount?: number]>;
2556 static decrement<M extends Model>(
2557 this: ModelStatic<M>,
2558 fields: { [key in keyof Attributes<M>]?: number },
2559 options: IncrementDecrementOptions<Attributes<M>>
2560 ): Promise<[affectedRows: M[], affectedCount?: number]>;
2561
2562 /**
2563 * Run a describe query on the table. The result will be return to the listener as a hash of attributes and
2564 * their types.
2565 */
2566 public static describe(): Promise<object>;
2567
2568 /**
2569 * Unscope the model
2570 */
2571 public static unscoped<M extends ModelType>(this: M): M;
2572
2573 /**
2574 * A hook that is run before validation
2575 *
2576 * @param name
2577 * @param fn A callback function that is called with instance, options
2578 */
2579 public static beforeValidate<M extends Model>(
2580 this: ModelStatic<M>,
2581 name: string,
2582 fn: (instance: M, options: ValidationOptions) => HookReturn
2583 ): void;
2584 public static beforeValidate<M extends Model>(
2585 this: ModelStatic<M>,
2586 fn: (instance: M, options: ValidationOptions) => HookReturn
2587 ): void;
2588
2589 /**
2590 * A hook that is run after validation
2591 *
2592 * @param name
2593 * @param fn A callback function that is called with instance, options
2594 */
2595 public static afterValidate<M extends Model>(
2596 this: ModelStatic<M>,
2597 name: string,
2598 fn: (instance: M, options: ValidationOptions) => HookReturn
2599 ): void;
2600 public static afterValidate<M extends Model>(
2601 this: ModelStatic<M>,
2602 fn: (instance: M, options: ValidationOptions) => HookReturn
2603 ): void;
2604
2605 /**
2606 * A hook that is run before creating a single instance
2607 *
2608 * @param name
2609 * @param fn A callback function that is called with attributes, options
2610 */
2611 public static beforeCreate<M extends Model>(
2612 this: ModelStatic<M>,
2613 name: string,
2614 fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn
2615 ): void;
2616 public static beforeCreate<M extends Model>(
2617 this: ModelStatic<M>,
2618 fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn
2619 ): void;
2620
2621 /**
2622 * A hook that is run after creating a single instance
2623 *
2624 * @param name
2625 * @param fn A callback function that is called with attributes, options
2626 */
2627 public static afterCreate<M extends Model>(
2628 this: ModelStatic<M>,
2629 name: string,
2630 fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn
2631 ): void;
2632 public static afterCreate<M extends Model>(
2633 this: ModelStatic<M>,
2634 fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn
2635 ): void;
2636
2637 /**
2638 * A hook that is run before destroying a single instance
2639 *
2640 * @param name
2641 * @param fn A callback function that is called with instance, options
2642 */
2643 public static beforeDestroy<M extends Model>(
2644 this: ModelStatic<M>,
2645 name: string,
2646 fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
2647 ): void;
2648 public static beforeDestroy<M extends Model>(
2649 this: ModelStatic<M>,
2650 fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
2651 ): void;
2652
2653 /**
2654 * A hook that is run after destroying a single instance
2655 *
2656 * @param name
2657 * @param fn A callback function that is called with instance, options
2658 */
2659 public static afterDestroy<M extends Model>(
2660 this: ModelStatic<M>,
2661 name: string,
2662 fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
2663 ): void;
2664 public static afterDestroy<M extends Model>(
2665 this: ModelStatic<M>,
2666 fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
2667 ): void;
2668
2669 /**
2670 * A hook that is run before updating a single instance
2671 *
2672 * @param name
2673 * @param fn A callback function that is called with instance, options
2674 */
2675 public static beforeUpdate<M extends Model>(
2676 this: ModelStatic<M>,
2677 name: string,
2678 fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn
2679 ): void;
2680 public static beforeUpdate<M extends Model>(
2681 this: ModelStatic<M>,
2682 fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn
2683 ): void;
2684
2685 /**
2686 * A hook that is run after updating a single instance
2687 *
2688 * @param name
2689 * @param fn A callback function that is called with instance, options
2690 */
2691 public static afterUpdate<M extends Model>(
2692 this: ModelStatic<M>,
2693 name: string,
2694 fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn
2695 ): void;
2696 public static afterUpdate<M extends Model>(
2697 this: ModelStatic<M>,
2698 fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn
2699 ): void;
2700
2701 /**
2702 * A hook that is run before creating or updating a single instance, It proxies `beforeCreate` and `beforeUpdate`
2703 *
2704 * @param name
2705 * @param fn A callback function that is called with instance, options
2706 */
2707 public static beforeSave<M extends Model>(
2708 this: ModelStatic<M>,
2709 name: string,
2710 fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn
2711 ): void;
2712 public static beforeSave<M extends Model>(
2713 this: ModelStatic<M>,
2714 fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn
2715 ): void;
2716
2717 /**
2718 * A hook that is run after creating or updating a single instance, It proxies `afterCreate` and `afterUpdate`
2719 *
2720 * @param name
2721 * @param fn A callback function that is called with instance, options
2722 */
2723 public static afterSave<M extends Model>(
2724 this: ModelStatic<M>,
2725 name: string,
2726 fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn
2727 ): void;
2728 public static afterSave<M extends Model>(
2729 this: ModelStatic<M>,
2730 fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn
2731 ): void;
2732
2733 /**
2734 * A hook that is run before creating instances in bulk
2735 *
2736 * @param name
2737 * @param fn A callback function that is called with instances, options
2738 */
2739 public static beforeBulkCreate<M extends Model>(
2740 this: ModelStatic<M>,
2741 name: string,
2742 fn: (instances: M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn
2743 ): void;
2744 public static beforeBulkCreate<M extends Model>(
2745 this: ModelStatic<M>,
2746 fn: (instances: M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn
2747 ): void;
2748
2749 /**
2750 * A hook that is run after creating instances in bulk
2751 *
2752 * @param name
2753 * @param fn A callback function that is called with instances, options
2754 */
2755 public static afterBulkCreate<M extends Model>(
2756 this: ModelStatic<M>,
2757 name: string,
2758 fn: (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn
2759 ): void;
2760 public static afterBulkCreate<M extends Model>(
2761 this: ModelStatic<M>,
2762 fn: (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn
2763 ): void;
2764
2765 /**
2766 * A hook that is run before destroying instances in bulk
2767 *
2768 * @param name
2769 * @param fn A callback function that is called with options
2770 */
2771 public static beforeBulkDestroy<M extends Model>(
2772 this: ModelStatic<M>,
2773 name: string, fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn): void;
2774 public static beforeBulkDestroy<M extends Model>(
2775 this: ModelStatic<M>,
2776 fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn
2777 ): void;
2778
2779 /**
2780 * A hook that is run after destroying instances in bulk
2781 *
2782 * @param name
2783 * @param fn A callback function that is called with options
2784 */
2785 public static afterBulkDestroy<M extends Model>(
2786 this: ModelStatic<M>,
2787 name: string, fn: (options: DestroyOptions<Attributes<M>>) => HookReturn
2788 ): void;
2789 public static afterBulkDestroy<M extends Model>(
2790 this: ModelStatic<M>,
2791 fn: (options: DestroyOptions<Attributes<M>>) => HookReturn
2792 ): void;
2793
2794 /**
2795 * A hook that is run after updating instances in bulk
2796 *
2797 * @param name
2798 * @param fn A callback function that is called with options
2799 */
2800 public static beforeBulkUpdate<M extends Model>(
2801 this: ModelStatic<M>,
2802 name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn
2803 ): void;
2804 public static beforeBulkUpdate<M extends Model>(
2805 this: ModelStatic<M>,
2806 fn: (options: UpdateOptions<Attributes<M>>) => HookReturn
2807 ): void;
2808
2809 /**
2810 * A hook that is run after updating instances in bulk
2811 *
2812 * @param name
2813 * @param fn A callback function that is called with options
2814 */
2815 public static afterBulkUpdate<M extends Model>(
2816 this: ModelStatic<M>,
2817 name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn
2818 ): void;
2819 public static afterBulkUpdate<M extends Model>(
2820 this: ModelStatic<M>,
2821 fn: (options: UpdateOptions<Attributes<M>>) => HookReturn
2822 ): void;
2823
2824 /**
2825 * A hook that is run before a find (select) query
2826 *
2827 * @param name
2828 * @param fn A callback function that is called with options
2829 */
2830 public static beforeFind<M extends Model>(
2831 this: ModelStatic<M>,
2832 name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn
2833 ): void;
2834 public static beforeFind<M extends Model>(
2835 this: ModelStatic<M>,
2836 fn: (options: FindOptions<Attributes<M>>) => HookReturn
2837 ): void;
2838
2839 /**
2840 * A hook that is run before a count query
2841 *
2842 * @param name
2843 * @param fn A callback function that is called with options
2844 */
2845 public static beforeCount<M extends Model>(
2846 this: ModelStatic<M>,
2847 name: string, fn: (options: CountOptions<Attributes<M>>) => HookReturn
2848 ): void;
2849 public static beforeCount<M extends Model>(
2850 this: ModelStatic<M>,
2851 fn: (options: CountOptions<Attributes<M>>) => HookReturn
2852 ): void;
2853
2854 /**
2855 * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
2856 *
2857 * @param name
2858 * @param fn A callback function that is called with options
2859 */
2860 public static beforeFindAfterExpandIncludeAll<M extends Model>(
2861 this: ModelStatic<M>,
2862 name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn
2863 ): void;
2864 public static beforeFindAfterExpandIncludeAll<M extends Model>(
2865 this: ModelStatic<M>,
2866 fn: (options: FindOptions<Attributes<M>>) => HookReturn
2867 ): void;
2868
2869 /**
2870 * A hook that is run before a find (select) query, after all option parsing is complete
2871 *
2872 * @param name
2873 * @param fn A callback function that is called with options
2874 */
2875 public static beforeFindAfterOptions<M extends Model>(
2876 this: ModelStatic<M>,
2877 name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn
2878 ): void;
2879 public static beforeFindAfterOptions<M extends Model>(
2880 this: ModelStatic<M>,
2881 fn: (options: FindOptions<Attributes<M>>) => void
2882 ): HookReturn;
2883
2884 /**
2885 * A hook that is run after a find (select) query
2886 *
2887 * @param name
2888 * @param fn A callback function that is called with instance(s), options
2889 */
2890 public static afterFind<M extends Model>(
2891 this: ModelStatic<M>,
2892 name: string,
2893 fn: (instancesOrInstance: readonly M[] | M | null, options: FindOptions<Attributes<M>>) => HookReturn
2894 ): void;
2895 public static afterFind<M extends Model>(
2896 this: ModelStatic<M>,
2897 fn: (instancesOrInstance: readonly M[] | M | null, options: FindOptions<Attributes<M>>) => HookReturn
2898 ): void;
2899
2900 /**
2901 * A hook that is run before sequelize.sync call
2902 *
2903 * @param fn A callback function that is called with options passed to sequelize.sync
2904 */
2905 public static beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2906 public static beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void;
2907
2908 /**
2909 * A hook that is run after sequelize.sync call
2910 *
2911 * @param fn A callback function that is called with options passed to sequelize.sync
2912 */
2913 public static afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2914 public static afterBulkSync(fn: (options: SyncOptions) => HookReturn): void;
2915
2916 /**
2917 * A hook that is run before Model.sync call
2918 *
2919 * @param fn A callback function that is called with options passed to Model.sync
2920 */
2921 public static beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2922 public static beforeSync(fn: (options: SyncOptions) => HookReturn): void;
2923
2924 /**
2925 * A hook that is run after Model.sync call
2926 *
2927 * @param fn A callback function that is called with options passed to Model.sync
2928 */
2929 public static afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
2930 public static afterSync(fn: (options: SyncOptions) => HookReturn): void;
2931
2932 /**
2933 * Creates an association between this (the source) and the provided target. The foreign key is added
2934 * on the target.
2935 *
2936 * Example: `User.hasOne(Profile)`. This will add userId to the profile table.
2937 *
2938 * @param target The model that will be associated with hasOne relationship
2939 * @param options Options for the association
2940 */
2941 public static hasOne<M extends Model, T extends Model>(
2942 this: ModelStatic<M>, target: ModelStatic<T>, options?: HasOneOptions
2943 ): HasOne<M, T>;
2944
2945 /**
2946 * Creates an association between this (the source) and the provided target. The foreign key is added on the
2947 * source.
2948 *
2949 * Example: `Profile.belongsTo(User)`. This will add userId to the profile table.
2950 *
2951 * @param target The model that will be associated with hasOne relationship
2952 * @param options Options for the association
2953 */
2954 public static belongsTo<M extends Model, T extends Model>(
2955 this: ModelStatic<M>, target: ModelStatic<T>, options?: BelongsToOptions
2956 ): BelongsTo<M, T>;
2957
2958 /**
2959 * Create an association that is either 1:m or n:m.
2960 *
2961 * ```js
2962 * // Create a 1:m association between user and project
2963 * User.hasMany(Project)
2964 * ```
2965 * ```js
2966 * // Create a n:m association between user and project
2967 * User.hasMany(Project)
2968 * Project.hasMany(User)
2969 * ```
2970 * By default, the name of the join table will be source+target, so in this case projectsusers. This can be
2971 * overridden by providing either a string or a Model as `through` in the options. If you use a through
2972 * model with custom attributes, these attributes can be set when adding / setting new associations in two
2973 * ways. Consider users and projects from before with a join table that stores whether the project has been
2974 * started yet:
2975 * ```js
2976 * class UserProjects extends Model {}
2977 * UserProjects.init({
2978 * started: Sequelize.BOOLEAN
2979 * }, { sequelize })
2980 * User.hasMany(Project, { through: UserProjects })
2981 * Project.hasMany(User, { through: UserProjects })
2982 * ```
2983 * ```js
2984 * jan.addProject(homework, { started: false }) // The homework project is not started yet
2985 * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been
2986 * started
2987 * ```
2988 *
2989 * If you want to set several target instances, but with different attributes you have to set the
2990 * attributes on the instance, using a property with the name of the through model:
2991 *
2992 * ```js
2993 * p1.userprojects {
2994 * started: true
2995 * }
2996 * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
2997 * ```
2998 *
2999 * Similarily, when fetching through a join table with custom attributes, these attributes will be
3000 * available as an object with the name of the through model.
3001 * ```js
3002 * user.getProjects().then(projects => {
3003 * const p1 = projects[0]
3004 * p1.userprojects.started // Is this project started yet?
3005 * })
3006 * ```
3007 *
3008 * @param target The model that will be associated with hasOne relationship
3009 * @param options Options for the association
3010 */
3011 public static hasMany<M extends Model, T extends Model>(
3012 this: ModelStatic<M>, target: ModelStatic<T>, options?: HasManyOptions
3013 ): HasMany<M, T>;
3014
3015 /**
3016 * Create an N:M association with a join table
3017 *
3018 * ```js
3019 * User.belongsToMany(Project)
3020 * Project.belongsToMany(User)
3021 * ```
3022 * By default, the name of the join table will be source+target, so in this case projectsusers. This can be
3023 * overridden by providing either a string or a Model as `through` in the options.
3024 *
3025 * If you use a through model with custom attributes, these attributes can be set when adding / setting new
3026 * associations in two ways. Consider users and projects from before with a join table that stores whether
3027 * the project has been started yet:
3028 * ```js
3029 * class UserProjects extends Model {}
3030 * UserProjects.init({
3031 * started: Sequelize.BOOLEAN
3032 * }, { sequelize });
3033 * User.belongsToMany(Project, { through: UserProjects })
3034 * Project.belongsToMany(User, { through: UserProjects })
3035 * ```
3036 * ```js
3037 * jan.addProject(homework, { started: false }) // The homework project is not started yet
3038 * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started
3039 * ```
3040 *
3041 * If you want to set several target instances, but with different attributes you have to set the
3042 * attributes on the instance, using a property with the name of the through model:
3043 *
3044 * ```js
3045 * p1.userprojects {
3046 * started: true
3047 * }
3048 * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
3049 * ```
3050 *
3051 * Similarily, when fetching through a join table with custom attributes, these attributes will be
3052 * available as an object with the name of the through model.
3053 * ```js
3054 * user.getProjects().then(projects => {
3055 * const p1 = projects[0]
3056 * p1.userprojects.started // Is this project started yet?
3057 * })
3058 * ```
3059 *
3060 * @param target The model that will be associated with hasOne relationship
3061 * @param options Options for the association
3062 *
3063 */
3064 public static belongsToMany<M extends Model, T extends Model>(
3065 this: ModelStatic<M>, target: ModelStatic<T>, options: BelongsToManyOptions
3066 ): BelongsToMany<M, T>;
3067
3068 /**
3069 * Returns true if this instance has not yet been persisted to the database
3070 */
3071 public isNewRecord: boolean;
3072
3073 /**
3074 * A reference to the sequelize instance
3075 */
3076 public sequelize: Sequelize;
3077
3078 /**
3079 * Builds a new model instance.
3080 *
3081 * @param values an object of key value pairs
3082 */
3083 constructor(values?: MakeNullishOptional<TCreationAttributes>, options?: BuildOptions);
3084
3085 /**
3086 * Get an object representing the query for this instance, use with `options.where`
3087 */
3088 public where(): object;
3089
3090 /**
3091 * Get the value of the underlying data value
3092 */
3093 public getDataValue<K extends keyof TModelAttributes>(key: K): TModelAttributes[K];
3094
3095 /**
3096 * Update the underlying data value
3097 */
3098 public setDataValue<K extends keyof TModelAttributes>(key: K, value: TModelAttributes[K]): void;
3099
3100 /**
3101 * If no key is given, returns all values of the instance, also invoking virtual getters.
3102 *
3103 * If key is given and a field or virtual getter is present for the key it will call that getter - else it
3104 * will return the value for key.
3105 *
3106 * @param options.plain If set to true, included instances will be returned as plain objects
3107 */
3108 public get(options?: { plain?: boolean; clone?: boolean }): TModelAttributes;
3109 public get<K extends keyof this>(key: K, options?: { plain?: boolean; clone?: boolean }): this[K];
3110 public get(key: string, options?: { plain?: boolean; clone?: boolean }): unknown;
3111
3112 /**
3113 * Set is used to update values on the instance (the sequelize representation of the instance that is,
3114 * remember that nothing will be persisted before you actually call `save`). In its most basic form `set`
3115 * will update a value stored in the underlying `dataValues` object. However, if a custom setter function
3116 * is defined for the key, that function will be called instead. To bypass the setter, you can pass `raw:
3117 * true` in the options object.
3118 *
3119 * If set is called with an object, it will loop over the object, and call set recursively for each key,
3120 * value pair. If you set raw to true, the underlying dataValues will either be set directly to the object
3121 * passed, or used to extend dataValues, if dataValues already contain values.
3122 *
3123 * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
3124 *
3125 * Set can also be used to build instances for associations, if you have values for those.
3126 * When using set with associations you need to make sure the property key matches the alias of the
3127 * association while also making sure that the proper include options have been set (from .build() or
3128 * .findOne())
3129 *
3130 * If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the
3131 * entire object as changed.
3132 *
3133 * @param options.raw If set to true, field and virtual setters will be ignored
3134 * @param options.reset Clear all previously set data values
3135 */
3136 public set<K extends keyof TModelAttributes>(key: K, value: TModelAttributes[K], options?: SetOptions): this;
3137 public set(keys: Partial<TModelAttributes>, options?: SetOptions): this;
3138 public setAttributes<K extends keyof TModelAttributes>(key: K, value: TModelAttributes[K], options?: SetOptions): this;
3139 public setAttributes(keys: Partial<TModelAttributes>, options?: SetOptions): this;
3140
3141 /**
3142 * If changed is called with a string it will return a boolean indicating whether the value of that key in
3143 * `dataValues` is different from the value in `_previousDataValues`.
3144 *
3145 * If changed is called without an argument, it will return an array of keys that have changed.
3146 *
3147 * If changed is called with two arguments, it will set the property to `dirty`.
3148 *
3149 * If changed is called without an argument and no keys have changed, it will return `false`.
3150 */
3151 public changed<K extends keyof this>(key: K): boolean;
3152 public changed<K extends keyof this>(key: K, dirty: boolean): void;
3153 public changed(): false | string[];
3154
3155 /**
3156 * Returns the previous value for key from `_previousDataValues`.
3157 */
3158 public previous(): Partial<TModelAttributes>;
3159 public previous<K extends keyof TModelAttributes>(key: K): TModelAttributes[K] | undefined;
3160
3161 /**
3162 * Validates this instance, and if the validation passes, persists it to the database.
3163 *
3164 * Returns a Promise that resolves to the saved instance (or rejects with a `Sequelize.ValidationError`, which will have a property for each of the fields for which the validation failed, with the error message for that field).
3165 *
3166 * This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed.
3167 *
3168 * This method is not aware of eager loaded associations. In other words, if some other model instance (child) was eager loaded with this instance (parent), and you change something in the child, calling `save()` will simply ignore the change that happened on the child.
3169 */
3170 public save(options?: SaveOptions<TModelAttributes>): Promise<this>;
3171
3172 /**
3173 * Refresh the current instance in-place, i.e. update the object with current data from the DB and return
3174 * the same object. This is different from doing a `find(Instance.id)`, because that would create and
3175 * return a new instance. With this method, all references to the Instance are updated with the new data
3176 * and no new objects are created.
3177 */
3178 public reload(options?: FindOptions<TModelAttributes>): Promise<this>;
3179
3180 /**
3181 * Validate the attribute of this instance according to validation rules set in the model definition.
3182 *
3183 * Emits null if and only if validation successful; otherwise an Error instance containing
3184 * { field name : [error msgs] } entries.
3185 *
3186 * @param options.skip An array of strings. All properties that are in this array will not be validated
3187 */
3188 public validate(options?: ValidationOptions): Promise<void>;
3189
3190 /**
3191 * This is the same as calling `set` and then calling `save`.
3192 */
3193 public update<K extends keyof TModelAttributes>(key: K, value: TModelAttributes[K] | Col | Fn | Literal, options?: InstanceUpdateOptions<TModelAttributes>): Promise<this>;
3194 public update(
3195 keys: {
3196 [key in keyof TModelAttributes]?: TModelAttributes[key] | Fn | Col | Literal;
3197 },
3198 options?: InstanceUpdateOptions<TModelAttributes>
3199 ): Promise<this>;
3200
3201 /**
3202 * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will
3203 * either be completely deleted, or have its deletedAt timestamp set to the current time.
3204 */
3205 public destroy(options?: InstanceDestroyOptions): Promise<void>;
3206
3207 /**
3208 * Restore the row corresponding to this instance. Only available for paranoid models.
3209 */
3210 public restore(options?: InstanceRestoreOptions): Promise<void>;
3211
3212 /**
3213 * Increment the value of one or more columns. This is done in the database, which means it does not use
3214 * the values currently stored on the Instance. The increment is done using a
3215 * ```sql
3216 * SET column = column + X
3217 * ```
3218 * query. To get the correct value after an increment into the Instance you should do a reload.
3219 *
3220 * ```js
3221 * instance.increment('number') // increment number by 1
3222 * instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
3223 * instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
3224 * // `by` is ignored, since each column has its own
3225 * // value
3226 * ```
3227 *
3228 * @param fields If a string is provided, that column is incremented by the value of `by` given in options.
3229 * If an array is provided, the same is true for each column.
3230 * If and object is provided, each column is incremented by the value given.
3231 */
3232 public increment<K extends keyof TModelAttributes>(
3233 fields: K | readonly K[] | Partial<TModelAttributes>,
3234 options?: IncrementDecrementOptionsWithBy<TModelAttributes>
3235 ): Promise<this>;
3236
3237 /**
3238 * Decrement the value of one or more columns. This is done in the database, which means it does not use
3239 * the values currently stored on the Instance. The decrement is done using a
3240 * ```sql
3241 * SET column = column - X
3242 * ```
3243 * query. To get the correct value after an decrement into the Instance you should do a reload.
3244 *
3245 * ```js
3246 * instance.decrement('number') // decrement number by 1
3247 * instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
3248 * instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
3249 * // `by` is ignored, since each column has its own
3250 * // value
3251 * ```
3252 *
3253 * @param fields If a string is provided, that column is decremented by the value of `by` given in options.
3254 * If an array is provided, the same is true for each column.
3255 * If and object is provided, each column is decremented by the value given
3256 */
3257 public decrement<K extends keyof TModelAttributes>(
3258 fields: K | readonly K[] | Partial<TModelAttributes>,
3259 options?: IncrementDecrementOptionsWithBy<TModelAttributes>
3260 ): Promise<this>;
3261
3262 /**
3263 * Check whether all values of this and `other` Instance are the same
3264 */
3265 public equals(other: this): boolean;
3266
3267 /**
3268 * Check if this is equal to one of `others` by calling equals
3269 */
3270 public equalsOneOf(others: readonly this[]): boolean;
3271
3272 /**
3273 * Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all
3274 * values gotten from the DB, and apply all custom getters.
3275 */
3276 public toJSON<T extends TModelAttributes>(): T;
3277 public toJSON(): object;
3278
3279 /**
3280 * Helper method to determine if a instance is "soft deleted". This is
3281 * particularly useful if the implementer renamed the deletedAt attribute to
3282 * something different. This method requires paranoid to be enabled.
3283 *
3284 * Throws an error if paranoid is not enabled.
3285 */
3286 public isSoftDeleted(): boolean;
3287}
3288
3289/** @deprecated use ModelStatic */
3290export type ModelType<TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes> = new () => Model<TModelAttributes, TCreationAttributes>;
3291
3292type NonConstructorKeys<T> = ({[P in keyof T]: T[P] extends new () => any ? never : P })[keyof T];
3293type NonConstructor<T> = Pick<T, NonConstructorKeys<T>>;
3294
3295/** @deprecated use ModelStatic */
3296export type ModelCtor<M extends Model> = ModelStatic<M>;
3297
3298export type ModelDefined<S extends {}, T extends {}> = ModelStatic<Model<S, T>>;
3299
3300// remove the existing constructor that tries to return `Model<{},{}>` which would be incompatible with models that have typing defined & replace with proper constructor.
3301export type ModelStatic<M extends Model> = NonConstructor<typeof Model> & { new(): M };
3302
3303export default Model;
3304
3305/**
3306 * Type will be true is T is branded with Brand, false otherwise
3307 */
3308// How this works:
3309// - `A extends B` will be true if A has *at least* all the properties of B
3310// - If we do `A extends Omit<A, Checked>` - the result will only be true if A did not have Checked to begin with
3311// - So if we want to check if T is branded, we remove the brand, and check if they list of keys is still the same.
3312// we exclude Null & Undefined so "field: Brand<value> | null" is still detected as branded
3313// this is important because "Brand<value | null>" are transformed into "Brand<value> | null" to not break null & undefined
3314type IsBranded<T, Brand extends symbol> = keyof NonNullable<T> extends keyof Omit<NonNullable<T>, Brand>
3315 ? false
3316 : true;
3317
3318type BrandedKeysOf<T, Brand extends symbol> = {
3319 [P in keyof T]-?: IsBranded<T[P], Brand> extends true ? P : never
3320}[keyof T];
3321
3322/**
3323 * Dummy Symbol used as branding by {@link NonAttribute}.
3324 *
3325 * Do not export, Do not use.
3326 */
3327declare const NonAttributeBrand: unique symbol;
3328
3329/**
3330 * This is a Branded Type.
3331 * You can use it to tag fields from your class that are NOT attributes.
3332 * They will be ignored by {@link InferAttributes} and {@link InferCreationAttributes}
3333 */
3334export type NonAttribute<T> =
3335 // we don't brand null & undefined as they can't have properties.
3336 // This means `NonAttribute<null>` will not work, but who makes an attribute that only accepts null?
3337 // Note that `NonAttribute<string | null>` does work!
3338 T extends null | undefined ? T
3339 : (T & { [NonAttributeBrand]?: true });
3340
3341/**
3342 * Dummy Symbol used as branding by {@link ForeignKey}.
3343 *
3344 * Do not export, Do not use.
3345 */
3346declare const ForeignKeyBrand: unique symbol;
3347
3348/**
3349 * This is a Branded Type.
3350 * You can use it to tag fields from your class that are foreign keys.
3351 * They will become optional in {@link Model.init} (as foreign keys are added by association methods, like {@link Model.hasMany}.
3352 */
3353export type ForeignKey<T> =
3354 // we don't brand null & undefined as they can't have properties.
3355 // This means `ForeignKey<null>` will not work, but who makes an attribute that only accepts null?
3356 // Note that `ForeignKey<string | null>` does work!
3357 T extends null | undefined ? T
3358 : (T & { [ForeignKeyBrand]?: true });
3359
3360/**
3361 * Option bag for {@link InferAttributes}.
3362 *
3363 * - omit: properties to not treat as Attributes.
3364 */
3365type InferAttributesOptions<Excluded, > = { omit?: Excluded };
3366
3367/**
3368 * Utility type to extract Attributes of a given Model class.
3369 *
3370 * It returns all instance properties defined in the Model, except:
3371 * - those inherited from Model (intermediate inheritance works),
3372 * - the ones whose type is a function,
3373 * - the ones manually excluded using the second parameter.
3374 * - the ones branded using {@link NonAttribute}
3375 *
3376 * It cannot detect whether something is a getter or not, you should use the `Excluded`
3377 * parameter to exclude getter & setters from the attribute list.
3378 *
3379 * @example
3380 * // listed attributes will be 'id' & 'firstName'.
3381 * class User extends Model<InferAttributes<User>> {
3382 * id: number;
3383 * firstName: string;
3384 * }
3385 *
3386 * @example
3387 * // listed attributes will be 'id' & 'firstName'.
3388 * // we're excluding the `name` getter & `projects` attribute using the `omit` option.
3389 * class User extends Model<InferAttributes<User, { omit: 'name' | 'projects' }>> {
3390 * id: number;
3391 * firstName: string;
3392 *
3393 * // this is a getter, not an attribute. It should not be listed in attributes.
3394 * get name(): string { return this.firstName; }
3395 * // this is an association, it should not be listed in attributes
3396 * projects?: Project[];
3397 * }
3398 *
3399 * @example
3400 * // listed attributes will be 'id' & 'firstName'.
3401 * // we're excluding the `name` getter & `test` attribute using the `NonAttribute` branded type.
3402 * class User extends Model<InferAttributes<User>> {
3403 * id: number;
3404 * firstName: string;
3405 *
3406 * // this is a getter, not an attribute. It should not be listed in attributes.
3407 * get name(): NonAttribute<string> { return this.firstName; }
3408 * // this is an association, it should not be listed in attributes
3409 * projects?: NonAttribute<Project[]>;
3410 * }
3411 */
3412export type InferAttributes<
3413 M extends Model,
3414 Options extends InferAttributesOptions<keyof M | never | ''> = { omit: never }
3415 > = {
3416 [Key in keyof M as InternalInferAttributeKeysFromFields<M, Key, Options>]: M[Key]
3417};
3418
3419/**
3420 * Dummy Symbol used as branding by {@link CreationOptional}.
3421 *
3422 * Do not export, Do not use.
3423 */
3424declare const CreationAttributeBrand: unique symbol;
3425
3426/**
3427 * This is a Branded Type.
3428 * You can use it to tag attributes that can be ommited during Model Creation.
3429 *
3430 * For use with {@link InferCreationAttributes}.
3431 */
3432export type CreationOptional<T> =
3433 // we don't brand null & undefined as they can't have properties.
3434 // This means `CreationOptional<null>` will not work, but who makes an attribute that only accepts null?
3435 // Note that `CreationOptional<string | null>` does work!
3436 T extends null | undefined ? T
3437 : (T & { [CreationAttributeBrand]?: true });
3438
3439/**
3440 * Utility type to extract Creation Attributes of a given Model class.
3441 *
3442 * Works like {@link InferAttributes}, but fields that are tagged using
3443 * {@link CreationOptional} will be optional.
3444 *
3445 * @example
3446 * class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
3447 * // this attribute is optional in Model#create
3448 * declare id: CreationOptional<number>;
3449 *
3450 * // this attribute is mandatory in Model#create
3451 * declare name: string;
3452 * }
3453 */
3454export type InferCreationAttributes<
3455 M extends Model,
3456 Options extends InferAttributesOptions<keyof M | never | ''> = { omit: never }
3457 > = {
3458 [Key in keyof M as InternalInferAttributeKeysFromFields<M, Key, Options>]: IsBranded<M[Key], typeof CreationAttributeBrand> extends true
3459 ? (M[Key] | undefined)
3460 : M[Key]
3461};
3462
3463/**
3464 * @private
3465 *
3466 * Internal type used by {@link InferCreationAttributes} and {@link InferAttributes} to exclude
3467 * attributes that are:
3468 * - functions
3469 * - branded using {@link NonAttribute}
3470 * - inherited from {@link Model}
3471 * - Excluded manually using {@link InferAttributesOptions#omit}
3472 */
3473type InternalInferAttributeKeysFromFields<M extends Model, Key extends keyof M, Options extends InferAttributesOptions<keyof M | never | ''>> =
3474 // fields inherited from Model are all excluded
3475 Key extends keyof Model ? never
3476 // functions are always excluded
3477 : M[Key] extends AnyFunction ? never
3478 // fields branded with NonAttribute are excluded
3479 : IsBranded<M[Key], typeof NonAttributeBrand> extends true ? never
3480 // check 'omit' option is provided & exclude those listed in it
3481 : Options['omit'] extends string ? (Key extends Options['omit'] ? never : Key)
3482 : Key;
3483
3484// in v7, we should be able to drop InferCreationAttributes and InferAttributes,
3485// resolving this confusion.
3486/**
3487 * Returns the creation attributes of a given Model.
3488 *
3489 * This returns the Creation Attributes of a Model, it does not build them.
3490 * If you need to build them, use {@link InferCreationAttributes}.
3491 *
3492 * @example
3493 * function buildModel<M extends Model>(modelClass: ModelStatic<M>, attributes: CreationAttributes<M>) {}
3494 */
3495export type CreationAttributes<M extends Model | Hooks> = MakeNullishOptional<M['_creationAttributes']>;
3496
3497/**
3498 * Returns the creation attributes of a given Model.
3499 *
3500 * This returns the Attributes of a Model that have already been defined, it does not build them.
3501 * If you need to build them, use {@link InferAttributes}.
3502 *
3503 * @example
3504 * function getValue<M extends Model>(modelClass: ModelStatic<M>, attribute: keyof Attributes<M>) {}
3505 */
3506export type Attributes<M extends Model | Hooks> = M['_attributes'];
3507
\No newline at end of file