UNPKG

18.5 kBTypeScriptView Raw
1import { DataType } from '../../data-types';
2import {
3 Logging,
4 Model,
5 ModelAttributeColumnOptions,
6 ModelAttributes,
7 Transactionable,
8 WhereOptions,
9 Filterable,
10 Poolable,
11 ModelCtor,
12 ModelStatic,
13 ModelType,
14 CreationAttributes,
15 Attributes
16} from '../../model';
17import QueryTypes = require('../../query-types');
18import { Sequelize, RetryOptions } from '../../sequelize';
19import { Transaction } from '../../transaction';
20import { SetRequired } from '../../utils/set-required';
21import { Fn, Literal } from '../../utils';
22import { Deferrable } from '../../deferrable';
23
24type BindOrReplacements = { [key: string]: unknown } | unknown[];
25type FieldMap = { [key: string]: string };
26
27/**
28 * Interface for query options
29 */
30export interface QueryOptions extends Logging, Transactionable, Poolable {
31 /**
32 * If true, sequelize will not try to format the results of the query, or build an instance of a model from
33 * the result
34 */
35 raw?: boolean;
36
37 /**
38 * The type of query you are executing. The query type affects how results are formatted before they are
39 * passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
40 */
41 type?: string;
42
43 /**
44 * If true, transforms objects with `.` separated property names into nested objects using
45 * [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes
46 * { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`,
47 * unless otherwise specified
48 *
49 * @default false
50 */
51 nest?: boolean;
52
53 /**
54 * Sets the query type to `SELECT` and return a single row
55 */
56 plain?: boolean;
57
58 /**
59 * Either an object of named parameter replacements in the format `:param` or an array of unnamed
60 * replacements to replace `?` in your SQL.
61 */
62 replacements?: BindOrReplacements;
63
64 /**
65 * Either an object of named parameter bindings in the format `$param` or an array of unnamed
66 * values to bind to `$1`, `$2`, etc in your SQL.
67 */
68 bind?: BindOrReplacements;
69
70 /**
71 * A sequelize instance used to build the return instance
72 */
73 instance?: Model;
74
75 /**
76 * Map returned fields to model's fields if `options.model` or `options.instance` is present.
77 * Mapping will occur before building the model instance.
78 */
79 mapToModel?: boolean;
80
81 retry?: RetryOptions;
82
83 /**
84 * Map returned fields to arbitrary names for SELECT query type if `options.fieldMaps` is present.
85 */
86 fieldMap?: FieldMap;
87}
88
89export interface QueryOptionsWithWhere extends QueryOptions, Filterable<any> {
90
91}
92
93export interface QueryOptionsWithModel<M extends Model> extends QueryOptions {
94 /**
95 * A sequelize model used to build the returned model instances (used to be called callee)
96 */
97 model: ModelStatic<M>;
98}
99
100export interface QueryOptionsWithType<T extends QueryTypes> extends QueryOptions {
101 /**
102 * The type of query you are executing. The query type affects how results are formatted before they are
103 * passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
104 */
105 type: T;
106}
107
108export interface QueryOptionsWithForce extends QueryOptions {
109 force?: boolean;
110}
111
112/**
113* Most of the methods accept options and use only the logger property of the options. That's why the most used
114* interface type for options in a method is separated here as another interface.
115*/
116export interface QueryInterfaceOptions extends Logging, Transactionable {}
117
118export interface CollateCharsetOptions {
119 collate?: string;
120 charset?: string;
121}
122
123export interface QueryInterfaceCreateTableOptions extends QueryInterfaceOptions, CollateCharsetOptions {
124 engine?: string;
125 /**
126 * Used for compound unique keys.
127 */
128 uniqueKeys?: {
129 [keyName: string]: {
130 fields: string[];
131 customIndex?: boolean;
132 };
133 };
134}
135
136export interface QueryInterfaceDropTableOptions extends QueryInterfaceOptions {
137 cascade?: boolean;
138 force?: boolean;
139}
140
141export interface QueryInterfaceDropAllTablesOptions extends QueryInterfaceOptions {
142 skip?: string[];
143}
144
145export interface TableNameWithSchema {
146 tableName: string;
147 schema?: string;
148 delimiter?: string;
149 as?: string;
150 name?: string;
151}
152export type TableName = string | TableNameWithSchema;
153
154export type IndexType = 'UNIQUE' | 'FULLTEXT' | 'SPATIAL';
155export type IndexMethod = 'BTREE' | 'HASH' | 'GIST' | 'SPGIST' | 'GIN' | 'BRIN' | string;
156
157export interface IndexesOptions {
158 /**
159 * The name of the index. Defaults to model name + _ + fields concatenated
160 */
161 name?: string;
162
163 /** For FULLTEXT columns set your parser */
164 parser?: string | null;
165
166 /**
167 * Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL`
168 */
169 type?: IndexType;
170
171 /**
172 * Should the index by unique? Can also be triggered by setting type to `UNIQUE`
173 *
174 * @default false
175 */
176 unique?: boolean;
177
178 /**
179 * PostgreSQL will build the index without taking any write locks. Postgres only
180 *
181 * @default false
182 */
183 concurrently?: boolean;
184
185 /**
186 * An array of the fields to index. Each field can either be a string containing the name of the field,
187 * a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `name`
188 * (field name), `length` (create a prefix index of length chars), `order` (the direction the column
189 * should be sorted in), `collate` (the collation (sort order) for the column), `operator` (likes IndexesOptions['operator'])
190 */
191 fields?: (string | { name: string; length?: number; order?: 'ASC' | 'DESC'; collate?: string; operator?: string } | Fn | Literal)[];
192
193 /**
194 * The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and
195 * postgres, and postgres additionally supports GIST, SPGIST, BRIN and GIN.
196 */
197 using?: IndexMethod;
198
199 /**
200 * Index operator type. Postgres only
201 */
202 operator?: string;
203
204 /**
205 * Optional where parameter for index. Can be used to limit the index to certain rows.
206 */
207 where?: WhereOptions<any>;
208
209 /**
210 * Prefix to append to the index name.
211 */
212 prefix?: string;
213}
214
215export interface QueryInterfaceIndexOptions extends IndexesOptions, QueryInterfaceOptions {}
216
217export interface BaseConstraintOptions {
218 name?: string;
219 fields: string[];
220}
221
222export interface AddUniqueConstraintOptions extends BaseConstraintOptions {
223 type: 'unique';
224 deferrable?: Deferrable;
225}
226
227export interface AddDefaultConstraintOptions extends BaseConstraintOptions {
228 type: 'default';
229 defaultValue?: unknown;
230}
231
232export interface AddCheckConstraintOptions extends BaseConstraintOptions {
233 type: 'check';
234 where?: WhereOptions<any>;
235}
236
237export interface AddPrimaryKeyConstraintOptions extends BaseConstraintOptions {
238 type: 'primary key';
239 deferrable?: Deferrable;
240}
241
242export interface AddForeignKeyConstraintOptions extends BaseConstraintOptions {
243 type: 'foreign key';
244 references?: {
245 table: TableName;
246 field: string;
247 };
248 onDelete: string;
249 onUpdate: string;
250 deferrable?: Deferrable;
251}
252
253export type AddConstraintOptions =
254| AddUniqueConstraintOptions
255| AddDefaultConstraintOptions
256| AddCheckConstraintOptions
257| AddPrimaryKeyConstraintOptions
258| AddForeignKeyConstraintOptions;
259
260export interface CreateDatabaseOptions extends CollateCharsetOptions, QueryOptions {
261 encoding?: string;
262}
263
264export interface FunctionParam {
265 type: string;
266 name?: string;
267 direction?: string;
268}
269
270export interface ColumnDescription {
271 type: string;
272 allowNull: boolean;
273 defaultValue: string;
274 primaryKey: boolean;
275 autoIncrement: boolean;
276 comment: string | null;
277}
278
279export interface ColumnsDescription {
280 [key: string]: ColumnDescription;
281}
282
283/**
284* The interface that Sequelize uses to talk to all databases.
285*
286* This interface is available through sequelize.queryInterface. It should not be commonly used, but it's
287* referenced anyway, so it can be used.
288*/
289export class QueryInterface {
290 /**
291 * Returns the dialect-specific sql generator.
292 *
293 * We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately.
294 */
295 public queryGenerator: unknown;
296
297 /**
298 * Returns the current sequelize instance.
299 */
300 public sequelize: Sequelize;
301
302 constructor(sequelize: Sequelize);
303
304 /**
305 * Queries the schema (table list).
306 *
307 * @param schema The schema to query. Applies only to Postgres.
308 */
309 public createSchema(schema?: string, options?: QueryInterfaceOptions): Promise<void>;
310
311 /**
312 * Drops the specified schema (table).
313 *
314 * @param schema The schema to query. Applies only to Postgres.
315 */
316 public dropSchema(schema?: string, options?: QueryInterfaceOptions): Promise<void>;
317
318 /**
319 * Drops all tables.
320 */
321 public dropAllSchemas(options?: QueryInterfaceDropAllTablesOptions): Promise<void>;
322
323 /**
324 * Queries all table names in the database.
325 *
326 * @param options
327 */
328 public showAllSchemas(options?: QueryOptions): Promise<object>;
329
330 /**
331 * Return database version
332 */
333 public databaseVersion(options?: QueryInterfaceOptions): Promise<string>;
334
335 /**
336 * Creates a table with specified attributes.
337 *
338 * @param tableName Name of table to create
339 * @param attributes Hash of attributes, key is attribute name, value is data type
340 * @param options Table options.
341 */
342 public createTable<M extends Model>(
343 tableName: TableName,
344 attributes: ModelAttributes<M, CreationAttributes<M>>,
345 options?: QueryInterfaceCreateTableOptions
346 ): Promise<void>;
347
348 /**
349 * Drops the specified table.
350 *
351 * @param tableName Table name.
352 * @param options Query options, particularly "force".
353 */
354 public dropTable(tableName: TableName, options?: QueryInterfaceDropTableOptions): Promise<void>;
355
356 /**
357 * Drops all tables.
358 *
359 * @param options
360 */
361 public dropAllTables(options?: QueryInterfaceDropAllTablesOptions): Promise<void>;
362
363 /**
364 * Drops all defined enums
365 *
366 * @param options
367 */
368 public dropAllEnums(options?: QueryOptions): Promise<void>;
369
370 /**
371 * Renames a table
372 */
373 public renameTable(before: TableName, after: TableName, options?: QueryInterfaceOptions): Promise<void>;
374
375 /**
376 * Returns all tables
377 */
378 public showAllTables(options?: QueryOptions): Promise<string[]>;
379
380 /**
381 * Returns a promise that resolves to true if the table exists in the database, false otherwise.
382 *
383 * @param tableName The name of the table
384 * @param options Options passed to {@link Sequelize#query}
385 */
386 public tableExists(tableName: TableName, options?: QueryOptions): Promise<boolean>;
387
388 /**
389 * Describe a table
390 */
391 public describeTable(
392 tableName: TableName,
393 options?: string | { schema?: string; schemaDelimiter?: string } & Logging
394 ): Promise<ColumnsDescription>;
395
396 /**
397 * Adds a new column to a table
398 */
399 public addColumn(
400 table: TableName,
401 key: string,
402 attribute: ModelAttributeColumnOptions | DataType,
403 options?: QueryInterfaceOptions
404 ): Promise<void>;
405
406 /**
407 * Removes a column from a table
408 */
409 public removeColumn(
410 table: TableName,
411 attribute: string,
412 options?: QueryInterfaceOptions
413 ): Promise<void>;
414
415 /**
416 * Changes a column
417 */
418 public changeColumn(
419 tableName: TableName,
420 attributeName: string,
421 dataTypeOrOptions?: DataType | ModelAttributeColumnOptions,
422 options?: QueryInterfaceOptions
423 ): Promise<void>;
424
425 /**
426 * Renames a column
427 */
428 public renameColumn(
429 tableName: TableName,
430 attrNameBefore: string,
431 attrNameAfter: string,
432 options?: QueryInterfaceOptions
433 ): Promise<void>;
434
435 /**
436 * Adds a new index to a table
437 */
438 public addIndex(
439 tableName: TableName,
440 attributes: string[],
441 options?: QueryInterfaceIndexOptions,
442 rawTablename?: string
443 ): Promise<void>;
444 public addIndex(
445 tableName: TableName,
446 options: SetRequired<QueryInterfaceIndexOptions, 'fields'>,
447 rawTablename?: string
448 ): Promise<void>;
449
450 /**
451 * Removes an index of a table
452 */
453 public removeIndex(tableName: TableName, indexName: string, options?: QueryInterfaceIndexOptions): Promise<void>;
454 public removeIndex(tableName: TableName, attributes: string[], options?: QueryInterfaceIndexOptions): Promise<void>;
455
456 /**
457 * Adds constraints to a table
458 */
459 public addConstraint(
460 tableName: TableName,
461 options?: AddConstraintOptions & QueryInterfaceOptions
462 ): Promise<void>;
463
464 /**
465 * Removes constraints from a table
466 */
467 public removeConstraint(tableName: TableName, constraintName: string, options?: QueryInterfaceOptions): Promise<void>;
468
469 /**
470 * Shows the index of a table
471 */
472 public showIndex(tableName: string | object, options?: QueryOptions): Promise<object>;
473
474 /**
475 * Put a name to an index
476 */
477 public nameIndexes(indexes: string[], rawTablename: string): Promise<void>;
478
479 /**
480 * Returns all foreign key constraints of requested tables
481 */
482 public getForeignKeysForTables(tableNames: string[], options?: QueryInterfaceOptions): Promise<object>;
483
484 /**
485 * Get foreign key references details for the table
486 */
487 public getForeignKeyReferencesForTable(tableName: TableName, options?: QueryInterfaceOptions): Promise<object>;
488
489 /**
490 * Inserts a new record
491 */
492 public insert(instance: Model | null, tableName: string, values: object, options?: QueryOptions): Promise<object>;
493
494 /**
495 * Inserts or Updates a record in the database
496 */
497 public upsert<M extends Model>(
498 tableName: TableName,
499 insertValues: object,
500 updateValues: object,
501 where: object,
502 options?: QueryOptionsWithModel<M>
503 ): Promise<object>;
504
505 /**
506 * Inserts multiple records at once
507 */
508 public bulkInsert(
509 tableName: TableName,
510 records: object[],
511 options?: QueryOptions,
512 attributes?: Record<string, ModelAttributeColumnOptions>
513 ): Promise<object | number>;
514
515 /**
516 * Updates a row
517 */
518 public update<M extends Model>(
519 instance: M,
520 tableName: TableName,
521 values: object,
522 identifier: WhereOptions<Attributes<M>>,
523 options?: QueryOptions
524 ): Promise<object>;
525
526 /**
527 * Updates multiple rows at once
528 */
529 public bulkUpdate(
530 tableName: TableName,
531 values: object,
532 identifier: WhereOptions<any>,
533 options?: QueryOptions,
534 attributes?: string[] | string
535 ): Promise<object>;
536
537 /**
538 * Deletes a row
539 */
540 public delete(
541 instance: Model | null,
542 tableName: TableName,
543 identifier: WhereOptions<any>,
544 options?: QueryOptions
545 ): Promise<object>;
546
547 /**
548 * Deletes multiple rows at once
549 */
550 public bulkDelete(
551 tableName: TableName,
552 identifier: WhereOptions<any>,
553 options?: QueryOptions,
554 model?: ModelType
555 ): Promise<object>;
556
557 /**
558 * Returns selected rows
559 */
560 public select(model: ModelType | null, tableName: TableName, options?: QueryOptionsWithWhere): Promise<object[]>;
561
562 /**
563 * Increments a row value
564 */
565 public increment<M extends Model>(
566 instance: Model,
567 tableName: TableName,
568 values: object,
569 identifier: WhereOptions<Attributes<M>>,
570 options?: QueryOptions
571 ): Promise<object>;
572
573 /**
574 * Selects raw without parsing the string into an object
575 */
576 public rawSelect(
577 tableName: TableName,
578 options: QueryOptionsWithWhere,
579 attributeSelector: string | string[],
580 model?: ModelType
581 ): Promise<string[]>;
582
583 /**
584 * Postgres only. Creates a trigger on specified table to call the specified function with supplied
585 * parameters.
586 */
587 public createTrigger(
588 tableName: TableName,
589 triggerName: string,
590 timingType: string,
591 fireOnArray: {
592 [key: string]: unknown;
593 }[],
594 functionName: string,
595 functionParams: FunctionParam[],
596 optionsArray: string[],
597 options?: QueryInterfaceOptions
598 ): Promise<void>;
599
600 /**
601 * Postgres only. Drops the specified trigger.
602 */
603 public dropTrigger(tableName: TableName, triggerName: string, options?: QueryInterfaceOptions): Promise<void>;
604
605 /**
606 * Postgres only. Renames a trigger
607 */
608 public renameTrigger(
609 tableName: TableName,
610 oldTriggerName: string,
611 newTriggerName: string,
612 options?: QueryInterfaceOptions
613 ): Promise<void>;
614
615 /**
616 * Postgres only. Create a function
617 */
618 public createFunction(
619 functionName: string,
620 params: FunctionParam[],
621 returnType: string,
622 language: string,
623 body: string,
624 optionsArray?: string[],
625 options?: QueryOptionsWithForce
626 ): Promise<void>;
627
628 /**
629 * Postgres only. Drops a function
630 */
631 public dropFunction(functionName: string, params: FunctionParam[], options?: QueryInterfaceOptions): Promise<void>;
632
633 /**
634 * Postgres only. Rename a function
635 */
636 public renameFunction(
637 oldFunctionName: string,
638 params: FunctionParam[],
639 newFunctionName: string,
640 options?: QueryInterfaceOptions
641 ): Promise<void>;
642
643 /**
644 * Escape a table name
645 */
646 public quoteTable(identifier: TableName): string;
647
648 /**
649 * Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted
650 * even if the `quoteIdentifiers` option is false.
651 */
652 public quoteIdentifier(identifier: string, force?: boolean): string;
653
654 /**
655 * Split an identifier into .-separated tokens and quote each part.
656 */
657 public quoteIdentifiers(identifiers: string): string;
658
659 /**
660 * Set option for autocommit of a transaction
661 */
662 public setAutocommit(transaction: Transaction, value: boolean, options?: QueryOptions): Promise<void>;
663
664 /**
665 * Set the isolation level of a transaction
666 */
667 public setIsolationLevel(transaction: Transaction, value: string, options?: QueryOptions): Promise<void>;
668
669 /**
670 * Begin a new transaction
671 */
672 public startTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
673
674 /**
675 * Defer constraints
676 */
677 public deferConstraints(transaction: Transaction, options?: QueryOptions): Promise<void>;
678
679 /**
680 * Commit an already started transaction
681 */
682 public commitTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
683
684 /**
685 * Rollback ( revert ) a transaction that has'nt been commited
686 */
687 public rollbackTransaction(transaction: Transaction, options?: QueryOptions): Promise<void>;
688
689 /**
690 * Creates a database
691 */
692 public createDatabase(name: string, options?: CreateDatabaseOptions): Promise<void>;
693
694 /**
695 * Creates a database
696 */
697 public dropDatabase(name: string, options?: QueryOptions): Promise<void>;
698}