@mikro-orm/sql 7.0.13-dev.8 → 7.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/AbstractSqlConnection.d.ts +94 -58
  2. package/AbstractSqlConnection.js +235 -238
  3. package/AbstractSqlDriver.d.ts +410 -155
  4. package/AbstractSqlDriver.js +2098 -1970
  5. package/AbstractSqlPlatform.d.ts +85 -75
  6. package/AbstractSqlPlatform.js +166 -162
  7. package/PivotCollectionPersister.d.ts +33 -15
  8. package/PivotCollectionPersister.js +158 -160
  9. package/README.md +1 -1
  10. package/SqlEntityManager.d.ts +67 -22
  11. package/SqlEntityManager.js +54 -38
  12. package/SqlEntityRepository.d.ts +14 -14
  13. package/SqlEntityRepository.js +23 -23
  14. package/dialects/mssql/MsSqlNativeQueryBuilder.d.ts +12 -12
  15. package/dialects/mssql/MsSqlNativeQueryBuilder.js +199 -201
  16. package/dialects/mysql/BaseMySqlPlatform.d.ts +65 -46
  17. package/dialects/mysql/BaseMySqlPlatform.js +137 -134
  18. package/dialects/mysql/MySqlExceptionConverter.d.ts +6 -6
  19. package/dialects/mysql/MySqlExceptionConverter.js +91 -77
  20. package/dialects/mysql/MySqlNativeQueryBuilder.d.ts +3 -3
  21. package/dialects/mysql/MySqlNativeQueryBuilder.js +66 -69
  22. package/dialects/mysql/MySqlSchemaHelper.d.ts +58 -39
  23. package/dialects/mysql/MySqlSchemaHelper.js +327 -319
  24. package/dialects/oracledb/OracleDialect.d.ts +81 -52
  25. package/dialects/oracledb/OracleDialect.js +155 -149
  26. package/dialects/oracledb/OracleNativeQueryBuilder.d.ts +12 -12
  27. package/dialects/oracledb/OracleNativeQueryBuilder.js +239 -243
  28. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +110 -107
  29. package/dialects/postgresql/BasePostgreSqlPlatform.js +369 -368
  30. package/dialects/postgresql/FullTextType.d.ts +10 -6
  31. package/dialects/postgresql/FullTextType.js +51 -51
  32. package/dialects/postgresql/PostgreSqlExceptionConverter.d.ts +5 -5
  33. package/dialects/postgresql/PostgreSqlExceptionConverter.js +55 -43
  34. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.d.ts +1 -1
  35. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.js +4 -4
  36. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +117 -82
  37. package/dialects/postgresql/PostgreSqlSchemaHelper.js +748 -712
  38. package/dialects/sqlite/BaseSqliteConnection.d.ts +3 -5
  39. package/dialects/sqlite/BaseSqliteConnection.js +21 -19
  40. package/dialects/sqlite/NodeSqliteDialect.d.ts +1 -1
  41. package/dialects/sqlite/NodeSqliteDialect.js +23 -23
  42. package/dialects/sqlite/SqliteDriver.d.ts +1 -1
  43. package/dialects/sqlite/SqliteDriver.js +3 -3
  44. package/dialects/sqlite/SqliteExceptionConverter.d.ts +6 -6
  45. package/dialects/sqlite/SqliteExceptionConverter.js +67 -51
  46. package/dialects/sqlite/SqliteNativeQueryBuilder.d.ts +2 -2
  47. package/dialects/sqlite/SqliteNativeQueryBuilder.js +7 -7
  48. package/dialects/sqlite/SqlitePlatform.d.ts +64 -73
  49. package/dialects/sqlite/SqlitePlatform.js +143 -143
  50. package/dialects/sqlite/SqliteSchemaHelper.d.ts +78 -61
  51. package/dialects/sqlite/SqliteSchemaHelper.js +541 -522
  52. package/package.json +3 -3
  53. package/plugin/index.d.ts +42 -35
  54. package/plugin/index.js +43 -36
  55. package/plugin/transformer.d.ts +117 -94
  56. package/plugin/transformer.js +890 -881
  57. package/query/ArrayCriteriaNode.d.ts +4 -4
  58. package/query/ArrayCriteriaNode.js +18 -18
  59. package/query/CriteriaNode.d.ts +35 -25
  60. package/query/CriteriaNode.js +142 -132
  61. package/query/CriteriaNodeFactory.d.ts +49 -6
  62. package/query/CriteriaNodeFactory.js +97 -94
  63. package/query/NativeQueryBuilder.d.ts +120 -120
  64. package/query/NativeQueryBuilder.js +507 -501
  65. package/query/ObjectCriteriaNode.d.ts +12 -12
  66. package/query/ObjectCriteriaNode.js +298 -282
  67. package/query/QueryBuilder.d.ts +1558 -906
  68. package/query/QueryBuilder.js +2331 -2202
  69. package/query/QueryBuilderHelper.d.ts +153 -72
  70. package/query/QueryBuilderHelper.js +1084 -1032
  71. package/query/ScalarCriteriaNode.d.ts +3 -3
  72. package/query/ScalarCriteriaNode.js +53 -46
  73. package/query/enums.d.ts +14 -14
  74. package/query/enums.js +14 -14
  75. package/query/raw.d.ts +16 -6
  76. package/query/raw.js +10 -10
  77. package/schema/DatabaseSchema.d.ts +74 -50
  78. package/schema/DatabaseSchema.js +359 -331
  79. package/schema/DatabaseTable.d.ts +96 -73
  80. package/schema/DatabaseTable.js +1046 -974
  81. package/schema/SchemaComparator.d.ts +70 -66
  82. package/schema/SchemaComparator.js +790 -765
  83. package/schema/SchemaHelper.d.ts +128 -97
  84. package/schema/SchemaHelper.js +683 -668
  85. package/schema/SqlSchemaGenerator.d.ts +79 -59
  86. package/schema/SqlSchemaGenerator.js +525 -495
  87. package/typings.d.ts +405 -275
@@ -1,380 +1,381 @@
1
- import { ALIAS_REPLACEMENT, ARRAY_OPERATORS, raw, RawQueryFragment, Type, Utils, } from '@mikro-orm/core';
1
+ import { ALIAS_REPLACEMENT, ARRAY_OPERATORS, raw, RawQueryFragment, Type, Utils } from '@mikro-orm/core';
2
2
  import { AbstractSqlPlatform } from '../../AbstractSqlPlatform.js';
3
3
  import { PostgreSqlNativeQueryBuilder } from './PostgreSqlNativeQueryBuilder.js';
4
4
  import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper.js';
5
5
  import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter.js';
6
6
  import { FullTextType } from './FullTextType.js';
7
7
  export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
8
- schemaHelper = new PostgreSqlSchemaHelper(this);
9
- exceptionConverter = new PostgreSqlExceptionConverter();
10
- /** Maps JS runtime type names to PostgreSQL cast types for JSON property access. @internal */
11
- #jsonTypeCasts = { number: 'float8', bigint: 'int8', boolean: 'bool' };
12
- createNativeQueryBuilder() {
13
- return new PostgreSqlNativeQueryBuilder(this);
14
- }
15
- usesReturningStatement() {
16
- return true;
17
- }
18
- usesCascadeStatement() {
19
- return true;
20
- }
21
- supportsNativeEnums() {
22
- return true;
23
- }
24
- usesEnumCheckConstraints() {
25
- return true;
26
- }
27
- getEnumArrayCheckConstraintExpression(column, items) {
28
- return `${this.quoteIdentifier(column)} <@ array[${items.map(item => `${this.quoteValue(item)}::text`).join(', ')}]`;
29
- }
30
- supportsMaterializedViews() {
31
- return true;
32
- }
33
- supportsCustomPrimaryKeyNames() {
34
- return true;
35
- }
36
- getCurrentTimestampSQL(length) {
37
- return `current_timestamp(${length})`;
38
- }
39
- getDateTimeTypeDeclarationSQL(column) {
40
- /* v8 ignore next */
41
- return 'timestamptz' + (column.length != null ? `(${column.length})` : '');
42
- }
43
- getDefaultDateTimeLength() {
44
- return 6;
45
- }
46
- getTimeTypeDeclarationSQL() {
47
- return 'time(0)';
48
- }
49
- getIntegerTypeDeclarationSQL(column) {
50
- if (column.autoincrement && !column.generated) {
51
- return 'serial';
52
- }
53
- return 'int';
54
- }
55
- getBigIntTypeDeclarationSQL(column) {
56
- /* v8 ignore next */
57
- if (column.autoincrement) {
58
- return `bigserial`;
59
- }
60
- return 'bigint';
61
- }
62
- getTinyIntTypeDeclarationSQL(column) {
63
- return 'smallint';
64
- }
65
- getUuidTypeDeclarationSQL(column) {
66
- return `uuid`;
67
- }
68
- getFullTextWhereClause(prop) {
69
- if (prop.customType instanceof FullTextType) {
70
- return `:column: @@ plainto_tsquery('${prop.customType.regconfig}', :query)`;
71
- }
72
- /* v8 ignore next */
73
- if (prop.columnTypes[0] === 'tsvector') {
74
- return `:column: @@ plainto_tsquery('simple', :query)`;
75
- }
76
- return `to_tsvector('simple', :column:) @@ plainto_tsquery('simple', :query)`;
77
- }
78
- supportsCreatingFullTextIndex() {
79
- return true;
80
- }
81
- getFullTextIndexExpression(indexName, schemaName, tableName, columns) {
82
- /* v8 ignore next */
83
- const quotedTableName = this.quoteIdentifier(schemaName ? `${schemaName}.${tableName}` : tableName);
84
- const quotedColumnNames = columns.map(c => this.quoteIdentifier(c.name));
85
- const quotedIndexName = this.quoteIdentifier(indexName);
86
- if (columns.length === 1 && columns[0].type === 'tsvector') {
87
- return `create index ${quotedIndexName} on ${quotedTableName} using gin(${quotedColumnNames[0]})`;
88
- }
89
- return `create index ${quotedIndexName} on ${quotedTableName} using gin(to_tsvector('simple', ${quotedColumnNames.join(` || ' ' || `)}))`;
90
- }
91
- normalizeColumnType(type, options) {
92
- const simpleType = this.extractSimpleType(type);
93
- if (['int', 'int4', 'integer', 'serial'].includes(simpleType)) {
94
- return this.getIntegerTypeDeclarationSQL({});
95
- }
96
- if (['bigint', 'int8', 'bigserial'].includes(simpleType)) {
97
- return this.getBigIntTypeDeclarationSQL({});
98
- }
99
- if (['smallint', 'int2', 'smallserial'].includes(simpleType)) {
100
- return this.getSmallIntTypeDeclarationSQL({});
101
- }
102
- if (['boolean', 'bool'].includes(simpleType)) {
103
- return this.getBooleanTypeDeclarationSQL();
104
- }
105
- if (['double', 'double precision', 'float8'].includes(simpleType)) {
106
- return this.getDoubleDeclarationSQL();
107
- }
108
- if (['real', 'float4'].includes(simpleType)) {
109
- return this.getFloatDeclarationSQL();
110
- }
111
- if (['timestamptz', 'timestamp with time zone'].includes(simpleType)) {
112
- return this.getDateTimeTypeDeclarationSQL(options);
113
- }
114
- if (['varchar', 'character varying'].includes(simpleType)) {
115
- return this.getVarcharTypeDeclarationSQL(options);
116
- }
117
- if (['char', 'bpchar'].includes(simpleType)) {
118
- return this.getCharTypeDeclarationSQL(options);
119
- }
120
- if (['decimal', 'numeric'].includes(simpleType)) {
121
- return this.getDecimalTypeDeclarationSQL(options);
122
- }
123
- if (['interval'].includes(simpleType)) {
124
- return this.getIntervalTypeDeclarationSQL(options);
125
- }
126
- // TimeType.getColumnType drops the timezone qualifier, so detect tz aliases from the original column type.
127
- const originalType = options.columnTypes?.[0]?.toLowerCase() ?? type;
128
- if (/^timetz\b/.test(originalType) || /^time\s+with\s+time\s+zone\b/.test(originalType)) {
129
- const length = options.length ?? this.getDefaultDateTimeLength();
130
- return `timetz(${length})`;
131
- }
132
- return super.normalizeColumnType(type, options);
133
- }
134
- getMappedType(type) {
135
- switch (this.extractSimpleType(type)) {
136
- case 'tsvector':
137
- return Type.getType(FullTextType);
138
- default:
139
- return super.getMappedType(type);
140
- }
141
- }
142
- getRegExpOperator(val, flags) {
143
- /* v8 ignore next */
144
- if ((val instanceof RegExp && val.flags.includes('i')) || flags?.includes('i')) {
145
- return '~*';
146
- }
147
- return '~';
148
- }
8
+ schemaHelper = new PostgreSqlSchemaHelper(this);
9
+ exceptionConverter = new PostgreSqlExceptionConverter();
10
+ /** Maps JS runtime type names to PostgreSQL cast types for JSON property access. @internal */
11
+ #jsonTypeCasts = { number: 'float8', bigint: 'int8', boolean: 'bool' };
12
+ createNativeQueryBuilder() {
13
+ return new PostgreSqlNativeQueryBuilder(this);
14
+ }
15
+ usesReturningStatement() {
16
+ return true;
17
+ }
18
+ usesCascadeStatement() {
19
+ return true;
20
+ }
21
+ supportsNativeEnums() {
22
+ return true;
23
+ }
24
+ usesEnumCheckConstraints() {
25
+ return true;
26
+ }
27
+ getEnumArrayCheckConstraintExpression(column, items) {
28
+ return `${this.quoteIdentifier(column)} <@ array[${items.map(item => `${this.quoteValue(item)}::text`).join(', ')}]`;
29
+ }
30
+ supportsMaterializedViews() {
31
+ return true;
32
+ }
33
+ supportsCustomPrimaryKeyNames() {
34
+ return true;
35
+ }
36
+ getCurrentTimestampSQL(length) {
37
+ return `current_timestamp(${length})`;
38
+ }
39
+ getDateTimeTypeDeclarationSQL(column) {
149
40
  /* v8 ignore next */
150
- getRegExpValue(val) {
151
- if (val.flags.includes('i')) {
152
- return { $re: val.source, $flags: val.flags };
153
- }
154
- return { $re: val.source };
155
- }
156
- isBigIntProperty(prop) {
157
- return super.isBigIntProperty(prop) || ['bigserial', 'int8'].includes(prop.columnTypes?.[0]);
158
- }
159
- getArrayDeclarationSQL() {
160
- return 'text[]';
161
- }
162
- getFloatDeclarationSQL() {
163
- return 'real';
164
- }
165
- getDoubleDeclarationSQL() {
166
- return 'double precision';
167
- }
168
- getEnumTypeDeclarationSQL(column) {
169
- /* v8 ignore next */
170
- if (column.nativeEnumName) {
171
- return column.nativeEnumName;
172
- }
173
- if (column.items?.every(item => typeof item === 'string')) {
174
- return 'text';
175
- }
176
- return `smallint`;
177
- }
178
- supportsMultipleStatements() {
179
- return true;
180
- }
181
- getBeginTransactionSQL(options) {
182
- if (options?.isolationLevel || options?.readOnly) {
183
- let sql = 'start transaction';
184
- sql += options.isolationLevel ? ` isolation level ${options.isolationLevel}` : '';
185
- sql += options.readOnly ? ` read only` : '';
186
- return [sql];
187
- }
188
- return ['begin'];
189
- }
190
- marshallArray(values) {
191
- const quote = (v) => (v === '' || /["{},\\]/.exec(v) ? JSON.stringify(v) : v);
192
- return `{${values.map(v => quote('' + v)).join(',')}}`;
193
- }
41
+ return 'timestamptz' + (column.length != null ? `(${column.length})` : '');
42
+ }
43
+ getDefaultDateTimeLength() {
44
+ return 6;
45
+ }
46
+ getTimeTypeDeclarationSQL() {
47
+ return 'time(0)';
48
+ }
49
+ getIntegerTypeDeclarationSQL(column) {
50
+ if (column.autoincrement && !column.generated) {
51
+ return 'serial';
52
+ }
53
+ return 'int';
54
+ }
55
+ getBigIntTypeDeclarationSQL(column) {
194
56
  /* v8 ignore next */
195
- unmarshallArray(value) {
196
- if (value === '{}') {
197
- return [];
198
- }
199
- return value
200
- .substring(1, value.length - 1)
201
- .split(',')
202
- .map(v => {
203
- if (v === `""`) {
204
- return '';
205
- }
206
- if (/"(.*)"/.exec(v)) {
207
- return v.substring(1, v.length - 1).replaceAll('\\"', '"');
208
- }
209
- return v;
210
- });
211
- }
212
- getVarcharTypeDeclarationSQL(column) {
213
- if (column.length === -1) {
214
- return 'varchar';
215
- }
216
- return super.getVarcharTypeDeclarationSQL(column);
217
- }
218
- getCharTypeDeclarationSQL(column) {
219
- if (column.length === -1) {
220
- return 'char';
221
- }
222
- return super.getCharTypeDeclarationSQL(column);
223
- }
224
- getIntervalTypeDeclarationSQL(column) {
225
- return 'interval' + (column.length != null ? `(${column.length})` : '');
226
- }
227
- getBlobDeclarationSQL() {
228
- return 'bytea';
229
- }
230
- getJsonDeclarationSQL() {
231
- return 'jsonb';
232
- }
233
- getSearchJsonPropertyKey(path, type, aliased, value) {
234
- const first = path.shift();
235
- const last = path.pop();
236
- const root = this.quoteIdentifier(aliased ? `${ALIAS_REPLACEMENT}.${first}` : first);
237
- type = typeof type === 'string' ? this.getMappedType(type).runtimeType : String(type);
238
- const cast = (key) => raw(type in this.#jsonTypeCasts ? `(${key})::${this.#jsonTypeCasts[type]}` : key);
239
- let lastOperator = '->>';
240
- // force `->` for operator payloads with array values
241
- if (Utils.isPlainObject(value) &&
242
- Object.keys(value).every(key => ARRAY_OPERATORS.includes(key) && Array.isArray(value[key]))) {
243
- lastOperator = '->';
244
- }
245
- if (path.length === 0) {
246
- return cast(`${root}${lastOperator}'${last}'`);
247
- }
248
- return cast(`${root}->${path.map(a => this.quoteValue(a)).join('->')}${lastOperator}'${last}'`);
249
- }
250
- getJsonIndexDefinition(index) {
251
- return index.columnNames.map(column => {
252
- if (!column.includes('.')) {
253
- return column;
254
- }
255
- const path = column.split('.');
256
- const first = path.shift();
257
- const last = path.pop();
258
- if (path.length === 0) {
259
- return `(${this.quoteIdentifier(first)}->>${this.quoteValue(last)})`;
260
- }
261
- return `(${this.quoteIdentifier(first)}->${path.map(c => this.quoteValue(c)).join('->')}->>${this.quoteValue(last)})`;
262
- });
263
- }
264
- quoteIdentifier(id, quote = '"') {
265
- if (RawQueryFragment.isKnownFragment(id)) {
266
- return super.quoteIdentifier(id);
267
- }
268
- return `${quote}${id.toString().replace('.', `${quote}.${quote}`)}${quote}`;
57
+ if (column.autoincrement) {
58
+ return `bigserial`;
59
+ }
60
+ return 'bigint';
61
+ }
62
+ getTinyIntTypeDeclarationSQL(column) {
63
+ return 'smallint';
64
+ }
65
+ getUuidTypeDeclarationSQL(column) {
66
+ return `uuid`;
67
+ }
68
+ getFullTextWhereClause(prop) {
69
+ if (prop.customType instanceof FullTextType) {
70
+ return `:column: @@ plainto_tsquery('${prop.customType.regconfig}', :query)`;
269
71
  }
270
- pad(number, digits) {
271
- return String(number).padStart(digits, '0');
272
- }
273
- /** @internal */
274
- formatDate(date) {
275
- if (this.timezone === 'Z') {
276
- return date.toISOString();
277
- }
278
- let offset = -date.getTimezoneOffset();
279
- let year = date.getFullYear();
280
- const isBCYear = year < 1;
281
- /* v8 ignore next */
282
- if (isBCYear) {
283
- year = Math.abs(year) + 1;
284
- }
285
- const datePart = `${this.pad(year, 4)}-${this.pad(date.getMonth() + 1, 2)}-${this.pad(date.getDate(), 2)}`;
286
- const timePart = `${this.pad(date.getHours(), 2)}:${this.pad(date.getMinutes(), 2)}:${this.pad(date.getSeconds(), 2)}.${this.pad(date.getMilliseconds(), 3)}`;
287
- let ret = `${datePart}T${timePart}`;
288
- /* v8 ignore next */
289
- if (offset < 0) {
290
- ret += '-';
291
- offset *= -1;
292
- }
293
- else {
294
- ret += '+';
295
- }
296
- ret += this.pad(Math.floor(offset / 60), 2) + ':' + this.pad(offset % 60, 2);
297
- /* v8 ignore next */
298
- if (isBCYear) {
299
- ret += ' BC';
300
- }
301
- return ret;
302
- }
303
- indexForeignKeys() {
304
- return false;
305
- }
306
- getDefaultMappedType(type) {
307
- const normalizedType = this.extractSimpleType(type);
308
- const map = {
309
- int2: 'smallint',
310
- smallserial: 'smallint',
311
- int: 'integer',
312
- int4: 'integer',
313
- serial: 'integer',
314
- serial4: 'integer',
315
- int8: 'bigint',
316
- bigserial: 'bigint',
317
- serial8: 'bigint',
318
- numeric: 'decimal',
319
- bool: 'boolean',
320
- real: 'float',
321
- float4: 'float',
322
- float8: 'double',
323
- timestamp: 'datetime',
324
- timestamptz: 'datetime',
325
- bytea: 'blob',
326
- jsonb: 'json',
327
- 'character varying': 'varchar',
328
- bpchar: 'character',
329
- };
330
- return super.getDefaultMappedType(map[normalizedType] ?? type);
331
- }
332
- supportsSchemas() {
333
- return true;
334
- }
335
- getDefaultSchemaName() {
336
- return 'public';
337
- }
338
- /**
339
- * Returns the default name of index for the given columns
340
- * cannot go past 63 character length for identifiers in MySQL
341
- */
342
- getIndexName(tableName, columns, type) {
343
- const indexName = super.getIndexName(tableName, columns, type);
344
- if (indexName.length > 63) {
345
- const suffix = type === 'primary' ? 'pkey' : type;
346
- return `${indexName.substring(0, 55 - type.length)}_${Utils.hash(indexName, 5)}_${suffix}`;
347
- }
348
- return indexName;
349
- }
350
- getDefaultPrimaryName(tableName, columns) {
351
- const indexName = `${tableName}_pkey`;
352
- if (indexName.length > 63) {
353
- return `${indexName.substring(0, 55 - 'pkey'.length)}_${Utils.hash(indexName, 5)}_pkey`;
354
- }
355
- return indexName;
356
- }
357
- /**
358
- * @inheritDoc
359
- */
360
- castColumn(prop) {
361
- switch (prop?.columnTypes?.[0]) {
362
- case this.getUuidTypeDeclarationSQL({}):
363
- return '::text';
364
- case this.getBooleanTypeDeclarationSQL():
365
- return '::int';
366
- default:
367
- return '';
368
- }
369
- }
370
- getJsonArrayFromSQL(column, alias, _properties) {
371
- return `jsonb_array_elements(${column}) as ${this.quoteIdentifier(alias)}`;
372
- }
373
- getJsonArrayElementPropertySQL(alias, property, type) {
374
- const expr = `${this.quoteIdentifier(alias)}->>${this.quoteValue(property)}`;
375
- return type in this.#jsonTypeCasts ? `(${expr})::${this.#jsonTypeCasts[type]}` : expr;
72
+ /* v8 ignore next */
73
+ if (prop.columnTypes[0] === 'tsvector') {
74
+ return `:column: @@ plainto_tsquery('simple', :query)`;
75
+ }
76
+ return `to_tsvector('simple', :column:) @@ plainto_tsquery('simple', :query)`;
77
+ }
78
+ supportsCreatingFullTextIndex() {
79
+ return true;
80
+ }
81
+ getFullTextIndexExpression(indexName, schemaName, tableName, columns) {
82
+ /* v8 ignore next */
83
+ const quotedTableName = this.quoteIdentifier(schemaName ? `${schemaName}.${tableName}` : tableName);
84
+ const quotedColumnNames = columns.map(c => this.quoteIdentifier(c.name));
85
+ const quotedIndexName = this.quoteIdentifier(indexName);
86
+ if (columns.length === 1 && columns[0].type === 'tsvector') {
87
+ return `create index ${quotedIndexName} on ${quotedTableName} using gin(${quotedColumnNames[0]})`;
88
+ }
89
+ return `create index ${quotedIndexName} on ${quotedTableName} using gin(to_tsvector('simple', ${quotedColumnNames.join(` || ' ' || `)}))`;
90
+ }
91
+ normalizeColumnType(type, options) {
92
+ const simpleType = this.extractSimpleType(type);
93
+ if (['int', 'int4', 'integer', 'serial'].includes(simpleType)) {
94
+ return this.getIntegerTypeDeclarationSQL({});
95
+ }
96
+ if (['bigint', 'int8', 'bigserial'].includes(simpleType)) {
97
+ return this.getBigIntTypeDeclarationSQL({});
98
+ }
99
+ if (['smallint', 'int2', 'smallserial'].includes(simpleType)) {
100
+ return this.getSmallIntTypeDeclarationSQL({});
101
+ }
102
+ if (['boolean', 'bool'].includes(simpleType)) {
103
+ return this.getBooleanTypeDeclarationSQL();
104
+ }
105
+ if (['double', 'double precision', 'float8'].includes(simpleType)) {
106
+ return this.getDoubleDeclarationSQL();
107
+ }
108
+ if (['real', 'float4'].includes(simpleType)) {
109
+ return this.getFloatDeclarationSQL();
110
+ }
111
+ if (['timestamptz', 'timestamp with time zone'].includes(simpleType)) {
112
+ return this.getDateTimeTypeDeclarationSQL(options);
113
+ }
114
+ if (['varchar', 'character varying'].includes(simpleType)) {
115
+ return this.getVarcharTypeDeclarationSQL(options);
116
+ }
117
+ if (['char', 'bpchar'].includes(simpleType)) {
118
+ return this.getCharTypeDeclarationSQL(options);
119
+ }
120
+ if (['decimal', 'numeric'].includes(simpleType)) {
121
+ return this.getDecimalTypeDeclarationSQL(options);
122
+ }
123
+ if (['interval'].includes(simpleType)) {
124
+ return this.getIntervalTypeDeclarationSQL(options);
125
+ }
126
+ // TimeType.getColumnType drops the timezone qualifier, so detect tz aliases from the original column type.
127
+ const originalType = options.columnTypes?.[0]?.toLowerCase() ?? type;
128
+ if (/^timetz\b/.test(originalType) || /^time\s+with\s+time\s+zone\b/.test(originalType)) {
129
+ const length = options.length ?? this.getDefaultDateTimeLength();
130
+ return `timetz(${length})`;
131
+ }
132
+ return super.normalizeColumnType(type, options);
133
+ }
134
+ getMappedType(type) {
135
+ switch (this.extractSimpleType(type)) {
136
+ case 'tsvector':
137
+ return Type.getType(FullTextType);
138
+ default:
139
+ return super.getMappedType(type);
140
+ }
141
+ }
142
+ getRegExpOperator(val, flags) {
143
+ /* v8 ignore next */
144
+ if ((val instanceof RegExp && val.flags.includes('i')) || flags?.includes('i')) {
145
+ return '~*';
146
+ }
147
+ return '~';
148
+ }
149
+ /* v8 ignore next */
150
+ getRegExpValue(val) {
151
+ if (val.flags.includes('i')) {
152
+ return { $re: val.source, $flags: val.flags };
153
+ }
154
+ return { $re: val.source };
155
+ }
156
+ isBigIntProperty(prop) {
157
+ return super.isBigIntProperty(prop) || ['bigserial', 'int8'].includes(prop.columnTypes?.[0]);
158
+ }
159
+ getArrayDeclarationSQL() {
160
+ return 'text[]';
161
+ }
162
+ getFloatDeclarationSQL() {
163
+ return 'real';
164
+ }
165
+ getDoubleDeclarationSQL() {
166
+ return 'double precision';
167
+ }
168
+ getEnumTypeDeclarationSQL(column) {
169
+ /* v8 ignore next */
170
+ if (column.nativeEnumName) {
171
+ return column.nativeEnumName;
172
+ }
173
+ if (column.items?.every(item => typeof item === 'string')) {
174
+ return 'text';
175
+ }
176
+ return `smallint`;
177
+ }
178
+ supportsMultipleStatements() {
179
+ return true;
180
+ }
181
+ getBeginTransactionSQL(options) {
182
+ if (options?.isolationLevel || options?.readOnly) {
183
+ let sql = 'start transaction';
184
+ sql += options.isolationLevel ? ` isolation level ${options.isolationLevel}` : '';
185
+ sql += options.readOnly ? ` read only` : '';
186
+ return [sql];
187
+ }
188
+ return ['begin'];
189
+ }
190
+ marshallArray(values) {
191
+ const quote = v => (v === '' || /["{},\\]/.exec(v) ? JSON.stringify(v) : v);
192
+ return `{${values.map(v => quote('' + v)).join(',')}}`;
193
+ }
194
+ /* v8 ignore next */
195
+ unmarshallArray(value) {
196
+ if (value === '{}') {
197
+ return [];
198
+ }
199
+ return value
200
+ .substring(1, value.length - 1)
201
+ .split(',')
202
+ .map(v => {
203
+ if (v === `""`) {
204
+ return '';
205
+ }
206
+ if (/"(.*)"/.exec(v)) {
207
+ return v.substring(1, v.length - 1).replaceAll('\\"', '"');
208
+ }
209
+ return v;
210
+ });
211
+ }
212
+ getVarcharTypeDeclarationSQL(column) {
213
+ if (column.length === -1) {
214
+ return 'varchar';
215
+ }
216
+ return super.getVarcharTypeDeclarationSQL(column);
217
+ }
218
+ getCharTypeDeclarationSQL(column) {
219
+ if (column.length === -1) {
220
+ return 'char';
221
+ }
222
+ return super.getCharTypeDeclarationSQL(column);
223
+ }
224
+ getIntervalTypeDeclarationSQL(column) {
225
+ return 'interval' + (column.length != null ? `(${column.length})` : '');
226
+ }
227
+ getBlobDeclarationSQL() {
228
+ return 'bytea';
229
+ }
230
+ getJsonDeclarationSQL() {
231
+ return 'jsonb';
232
+ }
233
+ getSearchJsonPropertyKey(path, type, aliased, value) {
234
+ const first = path.shift();
235
+ const last = path.pop();
236
+ const root = this.quoteIdentifier(aliased ? `${ALIAS_REPLACEMENT}.${first}` : first);
237
+ type = typeof type === 'string' ? this.getMappedType(type).runtimeType : String(type);
238
+ const cast = key => raw(type in this.#jsonTypeCasts ? `(${key})::${this.#jsonTypeCasts[type]}` : key);
239
+ let lastOperator = '->>';
240
+ // force `->` for operator payloads with array values
241
+ if (
242
+ Utils.isPlainObject(value) &&
243
+ Object.keys(value).every(key => ARRAY_OPERATORS.includes(key) && Array.isArray(value[key]))
244
+ ) {
245
+ lastOperator = '->';
246
+ }
247
+ if (path.length === 0) {
248
+ return cast(`${root}${lastOperator}'${last}'`);
249
+ }
250
+ return cast(`${root}->${path.map(a => this.quoteValue(a)).join('->')}${lastOperator}'${last}'`);
251
+ }
252
+ getJsonIndexDefinition(index) {
253
+ return index.columnNames.map(column => {
254
+ if (!column.includes('.')) {
255
+ return column;
256
+ }
257
+ const path = column.split('.');
258
+ const first = path.shift();
259
+ const last = path.pop();
260
+ if (path.length === 0) {
261
+ return `(${this.quoteIdentifier(first)}->>${this.quoteValue(last)})`;
262
+ }
263
+ return `(${this.quoteIdentifier(first)}->${path.map(c => this.quoteValue(c)).join('->')}->>${this.quoteValue(last)})`;
264
+ });
265
+ }
266
+ quoteIdentifier(id, quote = '"') {
267
+ if (RawQueryFragment.isKnownFragment(id)) {
268
+ return super.quoteIdentifier(id);
269
+ }
270
+ return `${quote}${id.toString().replace('.', `${quote}.${quote}`)}${quote}`;
271
+ }
272
+ pad(number, digits) {
273
+ return String(number).padStart(digits, '0');
274
+ }
275
+ /** @internal */
276
+ formatDate(date) {
277
+ if (this.timezone === 'Z') {
278
+ return date.toISOString();
279
+ }
280
+ let offset = -date.getTimezoneOffset();
281
+ let year = date.getFullYear();
282
+ const isBCYear = year < 1;
283
+ /* v8 ignore next */
284
+ if (isBCYear) {
285
+ year = Math.abs(year) + 1;
376
286
  }
377
- getDefaultClientUrl() {
378
- return 'postgresql://postgres@127.0.0.1:5432';
287
+ const datePart = `${this.pad(year, 4)}-${this.pad(date.getMonth() + 1, 2)}-${this.pad(date.getDate(), 2)}`;
288
+ const timePart = `${this.pad(date.getHours(), 2)}:${this.pad(date.getMinutes(), 2)}:${this.pad(date.getSeconds(), 2)}.${this.pad(date.getMilliseconds(), 3)}`;
289
+ let ret = `${datePart}T${timePart}`;
290
+ /* v8 ignore next */
291
+ if (offset < 0) {
292
+ ret += '-';
293
+ offset *= -1;
294
+ } else {
295
+ ret += '+';
379
296
  }
297
+ ret += this.pad(Math.floor(offset / 60), 2) + ':' + this.pad(offset % 60, 2);
298
+ /* v8 ignore next */
299
+ if (isBCYear) {
300
+ ret += ' BC';
301
+ }
302
+ return ret;
303
+ }
304
+ indexForeignKeys() {
305
+ return false;
306
+ }
307
+ getDefaultMappedType(type) {
308
+ const normalizedType = this.extractSimpleType(type);
309
+ const map = {
310
+ int2: 'smallint',
311
+ smallserial: 'smallint',
312
+ int: 'integer',
313
+ int4: 'integer',
314
+ serial: 'integer',
315
+ serial4: 'integer',
316
+ int8: 'bigint',
317
+ bigserial: 'bigint',
318
+ serial8: 'bigint',
319
+ numeric: 'decimal',
320
+ bool: 'boolean',
321
+ real: 'float',
322
+ float4: 'float',
323
+ float8: 'double',
324
+ timestamp: 'datetime',
325
+ timestamptz: 'datetime',
326
+ bytea: 'blob',
327
+ jsonb: 'json',
328
+ 'character varying': 'varchar',
329
+ bpchar: 'character',
330
+ };
331
+ return super.getDefaultMappedType(map[normalizedType] ?? type);
332
+ }
333
+ supportsSchemas() {
334
+ return true;
335
+ }
336
+ getDefaultSchemaName() {
337
+ return 'public';
338
+ }
339
+ /**
340
+ * Returns the default name of index for the given columns
341
+ * cannot go past 63 character length for identifiers in MySQL
342
+ */
343
+ getIndexName(tableName, columns, type) {
344
+ const indexName = super.getIndexName(tableName, columns, type);
345
+ if (indexName.length > 63) {
346
+ const suffix = type === 'primary' ? 'pkey' : type;
347
+ return `${indexName.substring(0, 55 - type.length)}_${Utils.hash(indexName, 5)}_${suffix}`;
348
+ }
349
+ return indexName;
350
+ }
351
+ getDefaultPrimaryName(tableName, columns) {
352
+ const indexName = `${tableName}_pkey`;
353
+ if (indexName.length > 63) {
354
+ return `${indexName.substring(0, 55 - 'pkey'.length)}_${Utils.hash(indexName, 5)}_pkey`;
355
+ }
356
+ return indexName;
357
+ }
358
+ /**
359
+ * @inheritDoc
360
+ */
361
+ castColumn(prop) {
362
+ switch (prop?.columnTypes?.[0]) {
363
+ case this.getUuidTypeDeclarationSQL({}):
364
+ return '::text';
365
+ case this.getBooleanTypeDeclarationSQL():
366
+ return '::int';
367
+ default:
368
+ return '';
369
+ }
370
+ }
371
+ getJsonArrayFromSQL(column, alias, _properties) {
372
+ return `jsonb_array_elements(${column}) as ${this.quoteIdentifier(alias)}`;
373
+ }
374
+ getJsonArrayElementPropertySQL(alias, property, type) {
375
+ const expr = `${this.quoteIdentifier(alias)}->>${this.quoteValue(property)}`;
376
+ return type in this.#jsonTypeCasts ? `(${expr})::${this.#jsonTypeCasts[type]}` : expr;
377
+ }
378
+ getDefaultClientUrl() {
379
+ return 'postgresql://postgres@127.0.0.1:5432';
380
+ }
380
381
  }