-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.ts
701 lines (645 loc) · 20.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import { freezeDeep, isFunction } from '@sequelize/utils';
import cloneDeep from 'lodash/cloneDeep';
import merge from 'lodash/merge';
import type { Class } from 'type-fest';
import type { DialectName, Sequelize } from '../../sequelize.js';
import { logger } from '../../utils/logger.js';
import type { DeepPartial } from '../../utils/types.js';
import type { AbstractConnectionManager } from './connection-manager.js';
import type { AbstractDataType } from './data-types.js';
import * as BaseDataTypes from './data-types.js';
import type { AbstractQueryGenerator } from './query-generator.js';
import type { AbstractQueryInterface } from './query-interface.js';
import type { AbstractQuery } from './query.js';
export interface SupportableNumericOptions {
zerofill: boolean;
/** Whether this dialect supports the unsigned option natively */
unsigned: boolean;
}
export interface SupportableDecimalNumberOptions extends SupportableNumericOptions {
/** Whether NaN can be inserted in a column that uses this DataType. */
NaN: boolean;
/** Whether Infinity/-Infinity can be inserted in a column that uses this DataType. */
infinity: boolean;
}
export interface SupportableFloatOptions extends SupportableDecimalNumberOptions {
/** Whether scale & precision can be specified as parameters */
scaleAndPrecision: boolean;
}
export interface SupportableExactDecimalOptions extends SupportableDecimalNumberOptions {
/**
* Whether this dialect supports unconstrained numeric/decimal columns. i.e. columns where numeric values of any length can be stored.
* The SQL standard requires that "NUMERIC" with no option be equal to "NUMERIC(0,0)", but some dialects (postgres)
* interpret it as an unconstrained numeric.
*/
unconstrained: boolean;
/**
* Whether this dialect supports constrained numeric/decimal columns. i.e. columns where numeric values of any length can be stored.
*/
constrained: boolean;
}
export type DialectSupports = {
DEFAULT: boolean;
'DEFAULT VALUES': boolean;
'VALUES ()': boolean;
// TODO: rename to `update.limit`
'LIMIT ON UPDATE': boolean;
'ON DUPLICATE KEY': boolean;
'ORDER NULLS': boolean;
UNION: boolean;
'UNION ALL': boolean;
'RIGHT JOIN': boolean;
EXCEPTION: boolean;
forShare?: 'LOCK IN SHARE MODE' | 'FOR SHARE' | undefined;
lock: boolean;
lockOf: boolean;
lockKey: boolean;
lockOuterJoinFailure: boolean;
skipLocked: boolean;
finalTable: boolean;
/* does the dialect support returning values for inserted/updated fields */
returnValues: false | 'output' | 'returning';
/* features specific to autoIncrement values */
autoIncrement: {
/* does the dialect require modification of insert queries when inserting auto increment fields */
identityInsert: boolean;
/* does the dialect support inserting default/null values for autoincrement fields */
defaultValue: boolean;
/* does the dialect support updating autoincrement fields */
update: boolean;
};
/* Do we need to say DEFAULT for bulk insert */
bulkDefault: boolean;
/**
* Whether this dialect has native support for schemas.
* For the purposes of Sequelize, a Schema is considered to be a grouping of tables.
* For instance, in MySQL, "CREATE DATABASE" creates what we consider to be a schema.
*/
schemas: boolean;
/**
* Whether this dialect has native support for having multiple databases per instance (in the postgres or mssql sense).
* For the purposes of Sequelize, a database is considered to be a grouping of schemas.
* For instance, in MySQL, "CREATE DATABASE" creates what we consider to be a schema,
* so we do not consider that MySQL supports this option.
*/
multiDatabases: boolean;
transactions: boolean;
savepoints: boolean;
isolationLevels: boolean;
connectionTransactionMethods: boolean;
settingIsolationLevelDuringTransaction: boolean;
startTransaction: {
useBegin: boolean;
readOnly: boolean;
transactionType: boolean;
};
migrations: boolean;
upserts: boolean;
inserts: {
ignoreDuplicates: string /* dialect specific words for INSERT IGNORE or DO NOTHING */;
updateOnDuplicate: boolean | string /* whether dialect supports ON DUPLICATE KEY UPDATE */;
onConflictDoNothing: string /* dialect specific words for ON CONFLICT DO NOTHING */;
onConflictWhere: boolean /* whether dialect supports ON CONFLICT WHERE */;
conflictFields: boolean /* whether the dialect supports specifying conflict fields or not */;
};
constraints: {
restrict: boolean;
/**
* This dialect supports marking a column's constraints as deferrable.
* e.g. 'DEFERRABLE' and 'INITIALLY DEFERRED'
*/
deferrable: boolean;
unique: boolean;
default: boolean;
check: boolean;
foreignKey: boolean;
/** Whether this dialect supports disabling foreign key checks for the current session */
foreignKeyChecksDisableable: boolean;
primaryKey: boolean;
onUpdate: boolean;
add: boolean;
remove: boolean;
removeOptions: {
cascade: boolean;
ifExists: boolean;
};
};
index: {
collate: boolean;
length: boolean;
parser: boolean;
concurrently: boolean;
type: boolean;
using: boolean | number;
functionBased: boolean;
operator: boolean;
where: boolean;
include: boolean;
};
groupedLimit: boolean;
indexViaAlter: boolean;
alterColumn: {
/**
* Can "ALTER TABLE x ALTER COLUMN y" add UNIQUE to the column in this dialect?
*/
unique: boolean;
};
dataTypes: {
CHAR: boolean;
/**
* Whether this dialect provides a binary collation on text, varchar & char columns.
*/
COLLATE_BINARY: boolean;
/** This dialect supports case-insensitive text */
CITEXT: boolean;
/** Options supportable by all int types (from tinyint to bigint) */
INTS: SupportableNumericOptions;
/** @deprecated */
REAL: SupportableFloatOptions;
/** This dialect supports 4 byte long floating point numbers */
FLOAT: SupportableFloatOptions;
/** This dialect supports 8 byte long floating point numbers */
DOUBLE: SupportableFloatOptions;
/** This dialect supports arbitrary precision numbers */
DECIMAL: false | SupportableExactDecimalOptions;
/** This dialect supports big integers */
BIGINT: boolean;
/**
* The dialect is considered to support JSON if it provides either:
* - A JSON data type.
* - An SQL function that can be used as a CHECK constraint on a text column, to ensure its contents are valid JSON.
*/
JSON: boolean;
JSONB: boolean;
ARRAY: boolean;
RANGE: boolean;
GEOMETRY: boolean;
GEOGRAPHY: boolean;
HSTORE: boolean;
TSVECTOR: boolean;
CIDR: boolean;
INET: boolean;
MACADDR: boolean;
MACADDR8: boolean;
DATETIME: {
/** Whether "infinity" is a valid value in this dialect's DATETIME data type */
infinity: boolean;
};
DATEONLY: {
/** Whether "infinity" is a valid value in this dialect's DATEONLY data type */
infinity: boolean;
};
TIME: {
/** Whether the dialect supports TIME(precision) */
precision: boolean;
};
};
REGEXP: boolean;
/**
* Case-insensitive regexp operator support ('~*' in postgres).
*/
IREGEXP: boolean;
/** Whether this dialect supports SQL JSON functions */
jsonOperations: boolean;
/** Whether this dialect supports returning quoted & unquoted JSON strings */
jsonExtraction: {
unquoted: boolean;
quoted: boolean;
};
tmpTableTrigger: boolean;
indexHints: boolean;
tableHints: boolean;
searchPath: boolean;
/**
* This dialect supports E-prefixed strings, e.g. "E'foo'", which
* enables the ability to use backslash escapes inside the string.
*/
escapeStringConstants: boolean;
/** Whether this dialect supports changing the global timezone option */
globalTimeZoneConfig: boolean;
/** Whether this dialect provides a native way to generate UUID v1 values */
uuidV1Generation: boolean;
/** Whether this dialect provides a native way to generate UUID v4 values */
uuidV4Generation: boolean;
dropTable: {
cascade: boolean;
};
maxExecutionTimeHint: {
select: boolean;
};
truncate: {
cascade: boolean;
restartIdentity: boolean;
};
removeColumn: {
cascade: boolean;
ifExists: boolean;
};
renameTable: {
changeSchema: boolean;
changeSchemaAndTable: boolean;
};
createSchema: {
authorization: boolean;
charset: boolean;
collate: boolean;
comment: boolean;
ifNotExists: boolean;
replace: boolean;
};
dropSchema: {
cascade: boolean;
ifExists: boolean;
};
delete: {
limit: boolean;
};
};
type TypeParser = (...params: any[]) => unknown;
declare const OptionType: unique symbol;
export type DialectOptions<Dialect extends AbstractDialect> = Dialect[typeof OptionType];
export abstract class AbstractDialect<Options extends object = {}> {
declare [OptionType]: Options;
/**
* List of features this dialect supports.
*
* Important: Dialect implementations inherit these values.
* When changing a default, ensure the implementations still properly declare which feature they support.
*/
static readonly supports: DialectSupports = freezeDeep({
DEFAULT: true,
'DEFAULT VALUES': false,
'VALUES ()': false,
'LIMIT ON UPDATE': false,
'ON DUPLICATE KEY': true,
'ORDER NULLS': false,
UNION: true,
'UNION ALL': true,
'RIGHT JOIN': true,
EXCEPTION: false,
lock: false,
lockOf: false,
lockKey: false,
lockOuterJoinFailure: false,
skipLocked: false,
finalTable: false,
returnValues: false,
autoIncrement: {
identityInsert: false,
defaultValue: true,
update: true,
},
bulkDefault: false,
schemas: false,
multiDatabases: false,
transactions: true,
savepoints: true,
isolationLevels: true,
connectionTransactionMethods: false,
settingIsolationLevelDuringTransaction: true,
startTransaction: {
useBegin: false,
readOnly: false,
transactionType: false,
},
migrations: true,
upserts: true,
inserts: {
ignoreDuplicates: '',
updateOnDuplicate: false,
onConflictDoNothing: '',
onConflictWhere: false,
conflictFields: false,
},
constraints: {
restrict: true,
deferrable: false,
unique: true,
default: false,
check: true,
foreignKey: true,
foreignKeyChecksDisableable: false,
primaryKey: true,
onUpdate: true,
add: true,
remove: true,
removeOptions: {
cascade: false,
ifExists: false,
},
},
index: {
collate: true,
length: false,
parser: false,
concurrently: false,
type: false,
using: true,
functionBased: false,
operator: false,
where: false,
include: false,
},
groupedLimit: true,
indexViaAlter: false,
alterColumn: {
unique: true,
},
dataTypes: {
CHAR: true,
COLLATE_BINARY: false,
CITEXT: false,
INTS: { zerofill: false, unsigned: false },
FLOAT: {
NaN: false,
infinity: false,
zerofill: false,
unsigned: false,
scaleAndPrecision: false,
},
REAL: {
NaN: false,
infinity: false,
zerofill: false,
unsigned: false,
scaleAndPrecision: false,
},
DOUBLE: {
NaN: false,
infinity: false,
zerofill: false,
unsigned: false,
scaleAndPrecision: false,
},
DECIMAL: {
constrained: true,
unconstrained: false,
NaN: false,
infinity: false,
zerofill: false,
unsigned: false,
},
BIGINT: true,
CIDR: false,
MACADDR: false,
MACADDR8: false,
INET: false,
JSON: false,
JSONB: false,
ARRAY: false,
RANGE: false,
GEOMETRY: false,
GEOGRAPHY: false,
HSTORE: false,
TSVECTOR: false,
DATETIME: {
infinity: false,
},
DATEONLY: {
infinity: false,
},
TIME: {
precision: true,
},
},
jsonOperations: false,
jsonExtraction: {
unquoted: false,
quoted: false,
},
REGEXP: false,
IREGEXP: false,
tmpTableTrigger: false,
indexHints: false,
tableHints: false,
searchPath: false,
escapeStringConstants: false,
globalTimeZoneConfig: false,
uuidV1Generation: false,
uuidV4Generation: false,
dropTable: {
cascade: false,
},
maxExecutionTimeHint: {
select: false,
},
truncate: {
cascade: false,
restartIdentity: false,
},
removeColumn: {
cascade: false,
ifExists: false,
},
renameTable: {
changeSchema: true,
changeSchemaAndTable: true,
},
createSchema: {
authorization: false,
charset: false,
collate: false,
comment: false,
ifNotExists: false,
replace: false,
},
dropSchema: {
cascade: false,
ifExists: false,
},
delete: {
limit: true,
},
});
protected static extendSupport(supportsOverwrite: DeepPartial<DialectSupports>): DialectSupports {
return merge(cloneDeep(this.supports) ?? {}, supportsOverwrite);
}
readonly sequelize: Sequelize;
abstract readonly defaultVersion: string;
abstract readonly Query: typeof AbstractQuery;
abstract readonly TICK_CHAR_LEFT: string;
abstract readonly TICK_CHAR_RIGHT: string;
abstract readonly queryGenerator: AbstractQueryGenerator;
abstract readonly queryInterface: AbstractQueryInterface;
abstract readonly connectionManager: AbstractConnectionManager<any, any>;
abstract readonly dataTypesDocumentationUrl: string;
readonly name: DialectName;
readonly DataTypes: Record<string, Class<AbstractDataType<any>>>;
/** dialect-specific implementation of shared data types */
readonly #dataTypeOverrides: Map<string, Class<AbstractDataType<any>>>;
/** base implementations of shared data types */
readonly #baseDataTypes: Map<string, Class<AbstractDataType<any>>>;
readonly #dataTypeParsers = new Map<unknown, TypeParser>();
get supports(): DialectSupports {
const Dialect = this.constructor as typeof AbstractDialect;
return Dialect.supports;
}
constructor(
sequelize: Sequelize,
dialectDataTypes: Record<string, Class<AbstractDataType<any>>>,
dialectName: DialectName,
) {
this.sequelize = sequelize;
this.DataTypes = dialectDataTypes;
this.name = dialectName;
const baseDataTypes = new Map<string, Class<AbstractDataType<any>>>();
for (const dataType of Object.values(BaseDataTypes) as Array<Class<AbstractDataType<any>>>) {
// Some exports are not Data Types
if (!isFunction(dataType)) {
continue;
}
const dataTypeId: string = (dataType as unknown as typeof AbstractDataType).getDataTypeId();
// intermediary data type
if (!dataTypeId) {
continue;
}
if (baseDataTypes.has(dataTypeId)) {
throw new Error(
`Internal Error: Sequelize declares more than one base implementation for DataType ID ${dataTypeId}.`,
);
}
baseDataTypes.set(dataTypeId, dataType);
}
const dataTypeOverrides = new Map<string, Class<AbstractDataType<any>>>();
for (const dataType of Object.values(this.DataTypes)) {
const replacedDataTypeId: string = (
dataType as unknown as typeof AbstractDataType
).getDataTypeId();
if (dataTypeOverrides.has(replacedDataTypeId)) {
throw new Error(
`Dialect ${this.name} declares more than one implementation for DataType ID ${replacedDataTypeId}.`,
);
}
dataTypeOverrides.set(replacedDataTypeId, dataType);
}
this.#dataTypeOverrides = dataTypeOverrides;
this.#baseDataTypes = baseDataTypes;
}
/**
* Returns the dialect-specific implementation of a shared data type, or null if no such implementation exists
* (in which case you need to use the base implementation).
*
* @param dataType The shared data type.
*/
getDataTypeForDialect(
dataType: Class<AbstractDataType<any>>,
): Class<AbstractDataType<any>> | null {
const typeId = (dataType as unknown as typeof AbstractDataType).getDataTypeId();
const baseType = this.#baseDataTypes.get(typeId);
// this is not one of our types. May be a custom type by a user. We don't replace it.
if (baseType != null && baseType !== dataType) {
return null;
}
return this.#dataTypeOverrides.get(typeId) ?? null;
}
readonly #printedWarnings = new Set<string>();
warnDataTypeIssue(text: string): void {
// TODO: log this to sequelize's log option instead (requires a logger with multiple log levels first)
if (this.#printedWarnings.has(text)) {
return;
}
this.#printedWarnings.add(text);
logger.warn(`${text} \n>> Check: ${this.dataTypesDocumentationUrl}`);
}
abstract createBindCollector(): BindCollector;
/**
* Produces a safe representation of a Buffer for this dialect, that can be inlined in a SQL string.
* Used mainly by DataTypes.
*
* @param buffer The buffer to escape
* @returns The string, escaped for SQL.
*/
escapeBuffer(buffer: Buffer): string {
const hex = buffer.toString('hex');
return `X'${hex}'`;
}
/**
* Produces a safe representation of a string for this dialect, that can be inlined in a SQL string.
* Used mainly by DataTypes.
*
* @param value The string to escape
* @returns The string, escaped for SQL.
*/
escapeString(value: string): string {
// http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
// http://stackoverflow.com/q/603572/130598
value = value.replaceAll("'", "''");
return `'${value}'`;
}
// Keep the logic of this class synchronized with the logic in the JSON DataType.
escapeJson(value: unknown): string {
return this.escapeString(JSON.stringify(value));
}
/**
* Whether this dialect can use \ in strings to escape string delimiters.
*
* @returns
*/
canBackslashEscape(): boolean {
return false;
}
getDefaultPort(): number {
// @ts-expect-error -- untyped constructor
return this.constructor.getDefaultPort();
}
/**
* Used to register a base parser for a Database type.
* Parsers are based on the Database Type, not the JS type.
* Only one parser can be assigned as the parser for a Database Type.
* For this reason, prefer neutral implementations.
*
* For instance, when implementing "parse" for a Date type,
* prefer returning a String rather than a Date object.
*
* The {@link DataTypes.ABSTRACT#parseDatabaseValue} method will then be called on the DataType instance defined by the user,
* which can decide on a more specific JS type (e.g. parse the date string & return a Date instance or a Temporal instance).
*
* You typically do not need to implement this method. This is used to provide default parsers when no DataType
* is provided (e.g. raw queries that don't specify a model). Sequelize already provides a default parser for most types.
* For a custom Data Type, implementing {@link DataTypes.ABSTRACT#parseDatabaseValue} is typically what you want.
*
* @param databaseDataTypes Dialect-specific DB data type identifiers that will use this parser.
* @param parser The parser function to call when parsing the data type. Parameters are dialect-specific.
*/
registerDataTypeParser(databaseDataTypes: unknown[], parser: TypeParser) {
for (const databaseDataType of databaseDataTypes) {
if (this.#dataTypeParsers.has(databaseDataType)) {
throw new Error(
`Sequelize DataType for DB DataType ${databaseDataType} already registered for dialect ${this.name}`,
);
}
this.#dataTypeParsers.set(databaseDataType, parser);
}
}
getParserForDatabaseDataType(databaseDataType: unknown): TypeParser | undefined {
return this.#dataTypeParsers.get(databaseDataType);
}
abstract getDefaultSchema(): string;
static getDefaultPort(): number {
throw new Error(`getDefaultPort not implemented in ${this.name}`);
}
static getSupportedOptions(): readonly string[] {
throw new Error(
`Dialect ${this.name} does not implement the static method getSupportedOptions.
It must return the list of option names that can be passed to the dialect constructor.`,
);
}
}
export type BindCollector = {
/**
*
*
* @param {string} bindParameterName The name of the bind parameter
* @returns {string}
*/
collect(bindParameterName: string): string;
/**
* Returns either an array of orders if the bind parameters are mapped to numeric parameters (e.g. '?', $1, @1),
* or null if no mapping was necessary because the dialect supports named parameters.
*/
getBindParameterOrder(): string[] | null;
};
export enum ParameterStyle {
bind = 'bind',
replacement = 'replacement',
}