-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
query-generator-typescript.ts
969 lines (836 loc) · 30.3 KB
/
query-generator-typescript.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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
import type { RequiredBy } from '@sequelize/utils';
import { EMPTY_OBJECT, isPlainObject, join, map } from '@sequelize/utils';
import isObject from 'lodash/isObject';
import { randomUUID } from 'node:crypto';
import NodeUtil from 'node:util';
import type { Class } from 'type-fest';
import { ConstraintChecking } from '../deferrable.js';
import { AssociationPath } from '../expression-builders/association-path.js';
import { Attribute } from '../expression-builders/attribute.js';
import { BaseSqlExpression } from '../expression-builders/base-sql-expression.js';
import { Cast } from '../expression-builders/cast.js';
import { Col } from '../expression-builders/col.js';
import { DialectAwareFn } from '../expression-builders/dialect-aware-fn.js';
import { Fn } from '../expression-builders/fn.js';
import { Identifier } from '../expression-builders/identifier.js';
import { JsonPath } from '../expression-builders/json-path.js';
import { List } from '../expression-builders/list.js';
import { Literal } from '../expression-builders/literal.js';
import { Value } from '../expression-builders/value.js';
import { Where } from '../expression-builders/where.js';
import { IndexHints } from '../index-hints.js';
import type { ModelDefinition } from '../model-definition.js';
import type { Attributes, Model, ModelStatic } from '../model.js';
import { Op } from '../operators.js';
import type { BindOrReplacements, Expression, Sequelize } from '../sequelize.js';
import type { NormalizedOptions } from '../sequelize.types.js';
import { bestGuessDataTypeOfVal } from '../sql-string.js';
import { TableHints } from '../table-hints.js';
import type { IsolationLevel } from '../transaction.js';
import { rejectInvalidOptions } from '../utils/check.js';
import { noOpCol } from '../utils/deprecations.js';
import { quoteIdentifier } from '../utils/dialect.js';
import { joinSQLFragments } from '../utils/join-sql-fragments.js';
import {
extractModelDefinition,
extractTableIdentifier,
isModelStatic,
} from '../utils/model-utils.js';
import type { BindParamOptions, DataType } from './data-types.js';
import { AbstractDataType } from './data-types.js';
import type { AbstractDialect } from './dialect.js';
import { AbstractQueryGeneratorInternal } from './query-generator-internal.js';
import type {
AddConstraintQueryOptions,
BulkDeleteQueryOptions,
CreateDatabaseQueryOptions,
CreateSchemaQueryOptions,
DropSchemaQueryOptions,
DropTableQueryOptions,
ListDatabasesQueryOptions,
ListSchemasQueryOptions,
ListTablesQueryOptions,
QuoteTableOptions,
RemoveColumnQueryOptions,
RemoveConstraintQueryOptions,
RemoveIndexQueryOptions,
RenameTableQueryOptions,
ShowConstraintsQueryOptions,
StartTransactionQueryOptions,
TableOrModel,
TruncateTableQueryOptions,
} from './query-generator.types.js';
import type { TableNameWithSchema } from './query-interface.js';
import type { WhereOptions } from './where-sql-builder-types.js';
import type { WhereSqlBuilder } from './where-sql-builder.js';
import { PojoWhere } from './where-sql-builder.js';
export const CREATE_DATABASE_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof CreateDatabaseQueryOptions>([
'charset',
'collate',
'ctype',
'encoding',
'template',
]);
export const CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof CreateSchemaQueryOptions>([
'authorization',
'charset',
'collate',
'comment',
'ifNotExists',
'replace',
]);
export const DROP_SCHEMA_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof DropSchemaQueryOptions>([
'cascade',
'ifExists',
]);
export const DROP_TABLE_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof DropTableQueryOptions>([
'cascade',
]);
export const LIST_DATABASES_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof ListDatabasesQueryOptions>([
'skip',
]);
export const LIST_TABLES_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof ListTablesQueryOptions>([
'schema',
]);
export const QUOTE_TABLE_SUPPORTABLE_OPTIONS = new Set<keyof QuoteTableOptions>([
'indexHints',
'tableHints',
]);
export const REMOVE_COLUMN_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof RemoveColumnQueryOptions>([
'ifExists',
'cascade',
]);
export const REMOVE_CONSTRAINT_QUERY_SUPPORTABLE_OPTIONS = new Set<
keyof RemoveConstraintQueryOptions
>(['ifExists', 'cascade']);
export const REMOVE_INDEX_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof RemoveIndexQueryOptions>([
'concurrently',
'ifExists',
'cascade',
]);
export const RENAME_TABLE_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof RenameTableQueryOptions>([
'changeSchema',
]);
export const SHOW_CONSTRAINTS_QUERY_SUPPORTABLE_OPTIONS = new Set<
keyof ShowConstraintsQueryOptions
>(['columnName', 'constraintName', 'constraintType']);
export const START_TRANSACTION_QUERY_SUPPORTABLE_OPTIONS = new Set<
keyof StartTransactionQueryOptions
>(['readOnly', 'transactionType']);
export const TRUNCATE_TABLE_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof TruncateTableQueryOptions>([
'cascade',
'restartIdentity',
]);
/**
* Options accepted by {@link AbstractQueryGeneratorTypeScript#escape}
*/
export interface EscapeOptions extends FormatWhereOptions {
readonly type?: DataType | undefined;
}
export interface FormatWhereOptions extends Bindable {
/**
* These are used to inline replacements into the query, when one is found inside of a {@link Literal}.
*/
readonly replacements?: BindOrReplacements | undefined;
/**
* The model of the main alias. Used to determine the type & column name of attributes referenced in the where clause.
*/
readonly model?: ModelStatic | ModelDefinition | null | undefined;
/**
* The alias of the main table corresponding to {@link FormatWhereOptions.model}.
* Used as the prefix for attributes that do not reference an association, e.g.
*
* ```ts
* const where = { name: 'foo' };
* ```
*
* will produce
*
* ```sql
* WHERE "<mainAlias>"."name" = 'foo'
* ```
*/
readonly mainAlias?: string | undefined;
}
/**
* Methods that support this option are functions that add values to the query.
* If {@link Bindable.bindParam} is specified, the value will be added to the query as a bind parameter.
* If it is not specified, the value will be added to the query as a literal.
*/
export interface Bindable {
bindParam?: ((value: unknown) => string) | undefined;
}
// DO NOT MAKE THIS CLASS PUBLIC!
/**
* This is a temporary class used to progressively migrate the AbstractQueryGenerator class to TypeScript by slowly moving its functions here.
* Always use {@link AbstractQueryGenerator} instead.
*/
export class AbstractQueryGeneratorTypeScript<Dialect extends AbstractDialect = AbstractDialect> {
readonly dialect: Dialect;
readonly #internals: AbstractQueryGeneratorInternal;
constructor(
dialect: Dialect,
internals: AbstractQueryGeneratorInternal = new AbstractQueryGeneratorInternal(dialect),
) {
this.dialect = dialect;
this.#internals = internals;
}
get #whereGenerator(): WhereSqlBuilder {
return this.#internals.whereSqlBuilder;
}
protected get sequelize(): Sequelize<Dialect> {
return this.dialect.sequelize;
}
protected get options(): NormalizedOptions<Dialect> {
return this.sequelize.options;
}
createDatabaseQuery(_database: string, _options?: CreateDatabaseQueryOptions): string {
if (this.dialect.supports.multiDatabases) {
throw new Error(
`${this.dialect.name} declares supporting databases but createDatabaseQuery is not implemented.`,
);
}
throw new Error(`Databases are not supported in ${this.dialect.name}.`);
}
dropDatabaseQuery(database: string): string {
if (this.dialect.supports.multiDatabases) {
return `DROP DATABASE IF EXISTS ${this.quoteIdentifier(database)}`;
}
throw new Error(`Databases are not supported in ${this.dialect.name}.`);
}
listDatabasesQuery(_options?: ListDatabasesQueryOptions): string {
if (this.dialect.supports.multiDatabases) {
throw new Error(
`${this.dialect.name} declares supporting databases but listDatabasesQuery is not implemented.`,
);
}
throw new Error(`Databases are not supported in ${this.dialect.name}.`);
}
createSchemaQuery(schemaName: string, options?: CreateSchemaQueryOptions): string {
if (!this.dialect.supports.schemas) {
throw new Error(`Schemas are not supported in ${this.dialect.name}.`);
}
if (options) {
rejectInvalidOptions(
'createSchemaQuery',
this.dialect,
CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTIONS,
this.dialect.supports.createSchema,
options,
);
}
return joinSQLFragments([
'CREATE',
options?.replace ? 'OR REPLACE' : '',
'SCHEMA',
options?.ifNotExists ? 'IF NOT EXISTS' : '',
this.quoteIdentifier(schemaName),
options?.authorization
? `AUTHORIZATION ${options.authorization instanceof Literal ? this.#internals.formatLiteral(options.authorization) : this.quoteIdentifier(options.authorization)}`
: '',
options?.charset ? `DEFAULT CHARACTER SET ${this.escape(options.charset)}` : '',
options?.collate ? `DEFAULT COLLATE ${this.escape(options.collate)}` : '',
options?.comment ? `COMMENT ${this.escape(options.comment)}` : '',
]);
}
dropSchemaQuery(schemaName: string, options?: DropSchemaQueryOptions): string {
if (!this.dialect.supports.schemas) {
throw new Error(`Schemas are not supported in ${this.dialect.name}.`);
}
if (options) {
rejectInvalidOptions(
'dropSchemaQuery',
this.dialect,
DROP_SCHEMA_QUERY_SUPPORTABLE_OPTIONS,
this.dialect.supports.dropSchema,
options,
);
}
return joinSQLFragments([
'DROP SCHEMA',
options?.ifExists ? 'IF EXISTS' : '',
this.quoteIdentifier(schemaName),
options?.cascade ? 'CASCADE' : '',
]);
}
listSchemasQuery(_options?: ListSchemasQueryOptions): string {
if (this.dialect.supports.schemas) {
throw new Error(
`${this.dialect.name} declares supporting schema but listSchemasQuery is not implemented.`,
);
}
throw new Error(`Schemas are not supported in ${this.dialect.name}.`);
}
describeTableQuery(tableName: TableOrModel) {
return `DESCRIBE ${this.quoteTable(tableName)};`;
}
dropTableQuery(tableName: TableOrModel, options?: DropTableQueryOptions): string {
if (options) {
rejectInvalidOptions(
'dropTableQuery',
this.dialect,
DROP_TABLE_QUERY_SUPPORTABLE_OPTIONS,
this.dialect.supports.dropTable,
options,
);
}
return joinSQLFragments([
'DROP TABLE IF EXISTS',
this.quoteTable(tableName),
options?.cascade ? 'CASCADE' : '',
]);
}
listTablesQuery(_options?: ListTablesQueryOptions): string {
throw new Error(`listTablesQuery has not been implemented in ${this.dialect.name}.`);
}
renameTableQuery(
beforeTableName: TableOrModel,
afterTableName: TableOrModel,
options?: RenameTableQueryOptions,
): string {
const beforeTable = this.extractTableDetails(beforeTableName);
const afterTable = this.extractTableDetails(afterTableName);
if (beforeTable.schema !== afterTable.schema && !options?.changeSchema) {
throw new Error(
'To move a table between schemas, you must set `options.changeSchema` to true.',
);
}
return `ALTER TABLE ${this.quoteTable(beforeTableName)} RENAME TO ${this.quoteTable(afterTableName)}`;
}
truncateTableQuery(
_tableName: TableOrModel,
_options?: TruncateTableQueryOptions,
): string | string[] {
throw new Error(`truncateTableQuery has not been implemented in ${this.dialect.name}.`);
}
removeColumnQuery(
tableName: TableOrModel,
columnName: string,
options?: RemoveColumnQueryOptions,
): string {
if (options) {
rejectInvalidOptions(
'removeColumnQuery',
this.dialect,
REMOVE_COLUMN_QUERY_SUPPORTABLE_OPTIONS,
this.dialect.supports.removeColumn,
options,
);
}
return joinSQLFragments([
'ALTER TABLE',
this.quoteTable(tableName),
'DROP COLUMN',
options?.ifExists ? 'IF EXISTS' : '',
this.quoteIdentifier(columnName),
options?.cascade ? 'CASCADE' : '',
]);
}
addConstraintQuery(tableName: TableOrModel, options: AddConstraintQueryOptions): string {
if (!this.dialect.supports.constraints.add) {
throw new Error(`Add constraint queries are not supported by ${this.dialect.name} dialect`);
}
return joinSQLFragments([
'ALTER TABLE',
this.quoteTable(tableName),
'ADD',
this.#internals.getConstraintSnippet(tableName, options),
]);
}
removeConstraintQuery(
tableName: TableOrModel,
constraintName: string,
options?: RemoveConstraintQueryOptions,
) {
if (!this.dialect.supports.constraints.remove) {
throw new Error(
`Remove constraint queries are not supported by ${this.dialect.name} dialect`,
);
}
if (options) {
rejectInvalidOptions(
'removeConstraintQuery',
this.dialect,
REMOVE_CONSTRAINT_QUERY_SUPPORTABLE_OPTIONS,
this.dialect.supports.constraints.removeOptions,
options,
);
}
return joinSQLFragments([
'ALTER TABLE',
this.quoteTable(tableName),
'DROP CONSTRAINT',
options?.ifExists ? 'IF EXISTS' : '',
this.quoteIdentifier(constraintName),
options?.cascade ? 'CASCADE' : '',
]);
}
setConstraintCheckingQuery(type: ConstraintChecking): string;
setConstraintCheckingQuery(
type: Class<ConstraintChecking>,
constraints?: readonly string[],
): string;
setConstraintCheckingQuery(
type: ConstraintChecking | Class<ConstraintChecking>,
constraints?: readonly string[],
) {
if (!this.dialect.supports.constraints.deferrable) {
throw new Error(`Deferrable constraints are not supported by ${this.dialect.name} dialect`);
}
let constraintFragment = 'ALL';
if (type instanceof ConstraintChecking) {
if (type.constraints?.length) {
constraintFragment = type.constraints
.map(constraint => this.quoteIdentifier(constraint))
.join(', ');
}
return `SET CONSTRAINTS ${constraintFragment} ${type.toString()}`;
}
if (constraints?.length) {
constraintFragment = constraints
.map(constraint => this.quoteIdentifier(constraint))
.join(', ');
}
return `SET CONSTRAINTS ${constraintFragment} ${type.toString()}`;
}
showConstraintsQuery(_tableName: TableOrModel, _options?: ShowConstraintsQueryOptions): string {
throw new Error(`showConstraintsQuery has not been implemented in ${this.dialect.name}.`);
}
showIndexesQuery(_tableName: TableOrModel): string {
throw new Error(`showIndexesQuery has not been implemented in ${this.dialect.name}.`);
}
removeIndexQuery(
_tableName: TableOrModel,
_indexNameOrAttributes: string | string[],
_options?: RemoveIndexQueryOptions,
): string {
throw new Error(`removeIndexQuery has not been implemented in ${this.dialect.name}.`);
}
/**
* Generates an SQL query that returns all foreign keys of a table or the foreign key constraint of a given column.
*
* @deprecated Use {@link showConstraintsQuery} instead.
* @param _tableName The table or associated model.
* @param _columnName The name of the column. Not supported by SQLite.
* @returns The generated SQL query.
*/
getForeignKeyQuery(_tableName: TableOrModel, _columnName?: string): Error {
throw new Error(`getForeignKeyQuery has been deprecated. Use showConstraintsQuery instead.`);
}
/**
* Generates an SQL query that drops a foreign key constraint.
*
* @deprecated Use {@link removeConstraintQuery} instead.
* @param _tableName The table or associated model.
* @param _foreignKey The name of the foreign key constraint.
*/
dropForeignKeyQuery(_tableName: TableOrModel, _foreignKey: string): Error {
throw new Error(`dropForeignKeyQuery has been deprecated. Use removeConstraintQuery instead.`);
}
/**
* Returns a query that commits a transaction.
*/
commitTransactionQuery(): string {
if (this.dialect.supports.connectionTransactionMethods) {
throw new Error(
`commitTransactionQuery is not supported by the ${this.dialect.name} dialect.`,
);
}
return 'COMMIT';
}
/**
* Returns a query that creates a savepoint.
*
* @param savepointName
*/
createSavepointQuery(savepointName: string): string {
if (!this.dialect.supports.savepoints) {
throw new Error(`Savepoints are not supported by ${this.dialect.name}.`);
}
return `SAVEPOINT ${this.quoteIdentifier(savepointName)}`;
}
/**
* Returns a query that rollbacks a savepoint.
*
* @param savepointName
*/
rollbackSavepointQuery(savepointName: string): string {
if (!this.dialect.supports.savepoints) {
throw new Error(`Savepoints are not supported by ${this.dialect.name}.`);
}
return `ROLLBACK TO SAVEPOINT ${this.quoteIdentifier(savepointName)}`;
}
/**
* Returns a query that rollbacks a transaction.
*/
rollbackTransactionQuery(): string {
if (this.dialect.supports.connectionTransactionMethods) {
throw new Error(
`rollbackTransactionQuery is not supported by the ${this.dialect.name} dialect.`,
);
}
return 'ROLLBACK';
}
/**
* Returns a query that sets the transaction isolation level.
*
* @param isolationLevel
*/
setIsolationLevelQuery(isolationLevel: IsolationLevel): string {
if (!this.dialect.supports.isolationLevels) {
throw new Error(`Isolation levels are not supported by ${this.dialect.name}.`);
}
if (!this.dialect.supports.connectionTransactionMethods) {
return `SET TRANSACTION ISOLATION LEVEL ${isolationLevel}`;
}
throw new Error(`setIsolationLevelQuery is not supported by the ${this.dialect.name} dialect.`);
}
/**
* Returns a query that starts a transaction.
*
* @param options
*/
startTransactionQuery(options?: StartTransactionQueryOptions): string {
if (this.dialect.supports.connectionTransactionMethods) {
throw new Error(
`startTransactionQuery is not supported by the ${this.dialect.name} dialect.`,
);
}
if (options) {
rejectInvalidOptions(
'startTransactionQuery',
this.dialect,
START_TRANSACTION_QUERY_SUPPORTABLE_OPTIONS,
this.dialect.supports.startTransaction,
options,
);
}
return joinSQLFragments([
this.dialect.supports.startTransaction.useBegin ? 'BEGIN' : 'START',
'TRANSACTION',
options?.readOnly ? 'READ ONLY' : '',
]);
}
/**
* Generates a unique identifier for the current transaction.
*/
generateTransactionId(): string {
return randomUUID();
}
// TODO: rename to "normalizeTable" & move to sequelize class
extractTableDetails(
tableOrModel: TableOrModel,
options?: { schema?: string; delimiter?: string },
): RequiredBy<TableNameWithSchema, 'schema'> {
const tableIdentifier = extractTableIdentifier(tableOrModel);
if (!isPlainObject(tableIdentifier)) {
throw new Error(
`Invalid input received, got ${NodeUtil.inspect(tableOrModel)}, expected a Model Class, a TableNameWithSchema object, or a table name string`,
);
}
return {
...tableIdentifier,
schema:
options?.schema ||
tableIdentifier.schema ||
this.options.schema ||
this.dialect.getDefaultSchema(),
delimiter: options?.delimiter || tableIdentifier.delimiter || '.',
};
}
/**
* Quote table name with optional alias and schema attribution
*
* @param param table string or object
* @param options options
*/
quoteTable(param: TableOrModel, options?: QuoteTableOptions): string {
if (options) {
rejectInvalidOptions(
'quoteTable',
this.dialect,
QUOTE_TABLE_SUPPORTABLE_OPTIONS,
{
indexHints: this.dialect.supports.indexHints,
tableHints: this.dialect.supports.tableHints,
},
options,
);
}
if (isModelStatic(param)) {
param = param.table;
}
const tableName = this.extractTableDetails(param);
if (isObject(param) && ('as' in param || 'name' in param)) {
throw new Error(
'parameters "as" and "name" are not allowed in the first parameter of quoteTable, pass them as the second parameter.',
);
}
let sql = '';
if (this.dialect.supports.schemas) {
// Some users sync the same set of tables in different schemas for various reasons
// They then set `searchPath` when running a query to use different schemas.
// See https://github.com/sequelize/sequelize/pull/15274#discussion_r1020770364
// For this reason, we treat the default schema as equivalent to "no schema specified"
if (tableName.schema && tableName.schema !== this.dialect.getDefaultSchema()) {
sql += `${this.quoteIdentifier(tableName.schema)}.`;
}
sql += this.quoteIdentifier(tableName.tableName);
} else {
const fakeSchemaPrefix =
tableName.schema && tableName.schema !== this.dialect.getDefaultSchema()
? tableName.schema + (tableName.delimiter || '.')
: '';
sql += this.quoteIdentifier(fakeSchemaPrefix + tableName.tableName);
}
if (options?.alias) {
sql += ` AS ${this.quoteIdentifier(options.alias === true ? tableName.tableName : options.alias)}`;
}
if (options?.indexHints) {
for (const hint of options.indexHints) {
if (IndexHints[hint.type]) {
sql += ` ${IndexHints[hint.type]} INDEX (${hint.values.map(indexName => this.quoteIdentifier(indexName)).join(',')})`;
} else {
throw new Error(
`The index hint type "${hint.type}" is invalid or not supported by dialect "${this.dialect.name}".`,
);
}
}
}
if (options?.tableHints) {
const hints: TableHints[] = [];
for (const hint of options.tableHints) {
if (TableHints[hint]) {
hints.push(TableHints[hint]);
} else {
throw new Error(
`The table hint "${hint}" is invalid or not supported by dialect "${this.dialect.name}".`,
);
}
}
if (hints.length) {
sql += ` WITH (${hints.join(', ')})`;
}
}
return sql;
}
/**
* Adds quotes to identifier
*
* @param identifier
* @param _force
*/
// TODO: memoize last result
quoteIdentifier(identifier: string, _force?: boolean) {
return quoteIdentifier(identifier, this.dialect.TICK_CHAR_LEFT, this.dialect.TICK_CHAR_RIGHT);
}
isSameTable(tableA: TableOrModel, tableB: TableOrModel) {
if (tableA === tableB) {
return true;
}
tableA = this.extractTableDetails(tableA);
tableB = this.extractTableDetails(tableB);
return tableA.tableName === tableB.tableName && tableA.schema === tableB.schema;
}
whereQuery<M extends Model>(where: WhereOptions<Attributes<M>>, options?: FormatWhereOptions) {
const query = this.whereItemsQuery(where, options);
if (query && query.length > 0) {
return `WHERE ${query}`;
}
return '';
}
whereItemsQuery<M extends Model>(
where: WhereOptions<Attributes<M>> | undefined,
options?: FormatWhereOptions,
) {
return this.#whereGenerator.formatWhereOptions(where, options);
}
formatSqlExpression(piece: BaseSqlExpression, options?: EscapeOptions): string {
if (piece instanceof Literal) {
return this.#internals.formatLiteral(piece, options);
}
if (piece instanceof Fn) {
return this.#internals.formatFn(piece, options);
}
if (piece instanceof List) {
return this.escapeList(piece.values, options);
}
if (piece instanceof Value) {
return this.escape(piece.value, options);
}
if (piece instanceof Identifier) {
return this.quoteIdentifier(piece.value);
}
if (piece instanceof Cast) {
return this.#internals.formatCast(piece, options);
}
if (piece instanceof Col) {
return this.#internals.formatCol(piece, options);
}
if (piece instanceof Attribute) {
return this.#internals.formatAttribute(piece, options);
}
if (piece instanceof Where) {
if (piece.where instanceof PojoWhere) {
return this.#whereGenerator.formatPojoWhere(piece.where, options);
}
return this.#whereGenerator.formatWhereOptions(piece.where, options);
}
if (piece instanceof JsonPath) {
return this.#internals.formatJsonPath(piece, options);
}
if (piece instanceof AssociationPath) {
return this.#internals.formatAssociationPath(piece);
}
if (piece instanceof DialectAwareFn) {
return this.#internals.formatDialectAwareFn(piece, options);
}
throw new Error(`Unknown sequelize method ${piece.constructor.name}`);
}
/**
* The goal of this method is to execute the equivalent of json_unquote for the current dialect.
*
* @param _arg
* @param _options
*/
formatUnquoteJson(_arg: Expression, _options: EscapeOptions | undefined): string {
if (!this.dialect.supports.jsonOperations) {
throw new Error(`Unquoting JSON is not supported by ${this.dialect.name} dialect.`);
}
throw new Error(`formatUnquoteJson has not been implemented in ${this.dialect.name}.`);
}
/**
* @param _sqlExpression ⚠️ This is not an identifier, it's a raw SQL expression. It will be inlined in the query.
* @param _path The JSON path, where each item is one level of the path
* @param _unquote Whether the result should be unquoted (depending on dialect: ->> and #>> operators, json_unquote function). Defaults to `false`.
*/
jsonPathExtractionQuery(
_sqlExpression: string,
_path: ReadonlyArray<number | string>,
_unquote: boolean,
): string {
if (!this.dialect.supports.jsonOperations) {
throw new Error(`JSON Paths are not supported in ${this.dialect.name}.`);
}
throw new Error(`jsonPathExtractionQuery has not been implemented in ${this.dialect.name}.`);
}
/**
* Escapes a value (e.g. a string, number or date) as an SQL value (as opposed to an identifier).
*
* @param value The value to escape
* @param options The options to use when escaping the value
*/
escape(value: unknown, options: EscapeOptions = EMPTY_OBJECT): string {
if (isPlainObject(value) && Op.col in value) {
noOpCol();
value = new Col(value[Op.col] as string);
}
if (value instanceof BaseSqlExpression) {
return this.formatSqlExpression(value, options);
}
if (value === undefined) {
throw new TypeError('"undefined" cannot be escaped');
}
let { type } = options;
if (type != null) {
type = this.sequelize.normalizeDataType(type);
}
if (
value === null &&
// we handle null values ourselves by default, unless the data type explicitly accepts null
(!(type instanceof AbstractDataType) || !type.acceptsNull())
) {
if (options.bindParam) {
return options.bindParam(null);
}
return 'NULL';
}
if (type == null || typeof type === 'string') {
type = bestGuessDataTypeOfVal(value, this.dialect);
} else {
type = this.sequelize.normalizeDataType(type);
}
this.sequelize.validateValue(value, type);
if (options.bindParam) {
return type.getBindParamSql(value, options as BindParamOptions);
}
return type.escape(value);
}
/**
* Escapes an array of values (e.g. strings, numbers or dates) as an SQL List of values.
*
* @param values The list of values to escape
* @param options
*
* @example
* ```ts
* const values = [1, 2, 3];
* queryGenerator.escapeList([1, 2, 3]); // '(1, 2, 3)'
*/
escapeList(values: unknown[], options?: EscapeOptions): string {
return `(${values.map(value => this.escape(value, options)).join(', ')})`;
}
getUuidV1FunctionCall(): string {
if (!this.dialect.supports.uuidV1Generation) {
throw new Error(`UUID V1 generation is not supported by ${this.dialect.name} dialect.`);
}
throw new Error(`getUuidV1FunctionCall has not been implemented in ${this.dialect.name}.`);
}
getUuidV4FunctionCall(): string {
if (!this.dialect.supports.uuidV4Generation) {
throw new Error(`UUID V4 generation is not supported by ${this.dialect.name} dialect.`);
}
throw new Error(`getUuidV4FunctionCall has not been implemented in ${this.dialect.name}.`);
}
getToggleForeignKeyChecksQuery(_enable: boolean): string {
throw new Error(`${this.dialect.name} does not support toggling foreign key checks`);
}
versionQuery(): string {
throw new Error(`${this.dialect.name} did not implement versionQuery`);
}
tableExistsQuery(tableName: TableOrModel): string {
const table = this.extractTableDetails(tableName);
return `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = ${this.escape(table.tableName)} AND TABLE_SCHEMA = ${this.escape(table.schema)}`;
}
bulkDeleteQuery(tableOrModel: TableOrModel, options: BulkDeleteQueryOptions): string {
const table = this.quoteTable(tableOrModel);
const modelDefinition = extractModelDefinition(tableOrModel);
const whereOptions = { ...options, model: modelDefinition };
const whereFragment = whereOptions.where
? this.whereQuery(whereOptions.where, whereOptions)
: '';
if (whereOptions.limit && !this.dialect.supports.delete.limit) {
if (!modelDefinition) {
throw new Error(
'Using LIMIT in bulkDeleteQuery requires specifying a model or model definition.',
);
}
const pks = join(
map(modelDefinition.primaryKeysAttributeNames.values(), attrName =>
this.quoteIdentifier(modelDefinition.getColumnName(attrName)),
),
', ',
);
const primaryKeys = modelDefinition.primaryKeysAttributeNames.size > 1 ? `(${pks})` : pks;
return joinSQLFragments([
`DELETE FROM ${table} WHERE ${primaryKeys} IN (`,
`SELECT ${pks} FROM ${table}`,
whereFragment,
`ORDER BY ${pks}`,
this.#internals.addLimitAndOffset(whereOptions),
')',
]);
}
return joinSQLFragments([
`DELETE FROM ${this.quoteTable(tableOrModel)}`,
whereFragment,
this.#internals.addLimitAndOffset(whereOptions),
]);
}
__TEST__getInternals() {
if (process.env.npm_lifecycle_event !== 'mocha') {
throw new Error('You can only access the internals of the query generator in test mode.');
}
return this.#internals;
}
}