@mikro-orm/sql 7.0.4 → 7.0.5-dev.0

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 +58 -94
  2. package/AbstractSqlConnection.js +238 -235
  3. package/AbstractSqlDriver.d.ts +155 -410
  4. package/AbstractSqlDriver.js +1941 -2064
  5. package/AbstractSqlPlatform.d.ts +73 -83
  6. package/AbstractSqlPlatform.js +158 -162
  7. package/PivotCollectionPersister.d.ts +15 -33
  8. package/PivotCollectionPersister.js +160 -158
  9. package/README.md +1 -1
  10. package/SqlEntityManager.d.ts +22 -67
  11. package/SqlEntityManager.js +38 -54
  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 +194 -192
  16. package/dialects/mysql/BaseMySqlPlatform.d.ts +45 -64
  17. package/dialects/mysql/BaseMySqlPlatform.js +131 -134
  18. package/dialects/mysql/MySqlExceptionConverter.d.ts +6 -6
  19. package/dialects/mysql/MySqlExceptionConverter.js +77 -91
  20. package/dialects/mysql/MySqlNativeQueryBuilder.d.ts +3 -3
  21. package/dialects/mysql/MySqlNativeQueryBuilder.js +69 -66
  22. package/dialects/mysql/MySqlSchemaHelper.d.ts +39 -39
  23. package/dialects/mysql/MySqlSchemaHelper.js +319 -327
  24. package/dialects/oracledb/OracleDialect.d.ts +52 -81
  25. package/dialects/oracledb/OracleDialect.js +149 -155
  26. package/dialects/oracledb/OracleNativeQueryBuilder.d.ts +12 -12
  27. package/dialects/oracledb/OracleNativeQueryBuilder.js +236 -232
  28. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +106 -109
  29. package/dialects/postgresql/BasePostgreSqlPlatform.js +353 -354
  30. package/dialects/postgresql/FullTextType.d.ts +6 -10
  31. package/dialects/postgresql/FullTextType.js +51 -51
  32. package/dialects/postgresql/PostgreSqlExceptionConverter.d.ts +5 -5
  33. package/dialects/postgresql/PostgreSqlExceptionConverter.js +43 -55
  34. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.d.ts +1 -1
  35. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.js +4 -4
  36. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +82 -102
  37. package/dialects/postgresql/PostgreSqlSchemaHelper.js +705 -733
  38. package/dialects/sqlite/BaseSqliteConnection.d.ts +5 -3
  39. package/dialects/sqlite/BaseSqliteConnection.js +19 -21
  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 +51 -67
  46. package/dialects/sqlite/SqliteNativeQueryBuilder.d.ts +2 -2
  47. package/dialects/sqlite/SqliteNativeQueryBuilder.js +7 -7
  48. package/dialects/sqlite/SqlitePlatform.d.ts +72 -63
  49. package/dialects/sqlite/SqlitePlatform.js +139 -139
  50. package/dialects/sqlite/SqliteSchemaHelper.d.ts +60 -70
  51. package/dialects/sqlite/SqliteSchemaHelper.js +520 -533
  52. package/package.json +2 -2
  53. package/plugin/index.d.ts +35 -42
  54. package/plugin/index.js +36 -43
  55. package/plugin/transformer.d.ts +94 -117
  56. package/plugin/transformer.js +881 -890
  57. package/query/ArrayCriteriaNode.d.ts +4 -4
  58. package/query/ArrayCriteriaNode.js +18 -18
  59. package/query/CriteriaNode.d.ts +25 -35
  60. package/query/CriteriaNode.js +123 -133
  61. package/query/CriteriaNodeFactory.d.ts +6 -49
  62. package/query/CriteriaNodeFactory.js +94 -97
  63. package/query/NativeQueryBuilder.d.ts +118 -118
  64. package/query/NativeQueryBuilder.js +480 -484
  65. package/query/ObjectCriteriaNode.d.ts +12 -12
  66. package/query/ObjectCriteriaNode.js +282 -298
  67. package/query/QueryBuilder.d.ts +905 -1557
  68. package/query/QueryBuilder.js +2192 -2322
  69. package/query/QueryBuilderHelper.d.ts +72 -153
  70. package/query/QueryBuilderHelper.js +1028 -1079
  71. package/query/ScalarCriteriaNode.d.ts +3 -3
  72. package/query/ScalarCriteriaNode.js +46 -53
  73. package/query/enums.d.ts +14 -14
  74. package/query/enums.js +14 -14
  75. package/query/raw.d.ts +6 -16
  76. package/query/raw.js +10 -10
  77. package/schema/DatabaseSchema.d.ts +50 -73
  78. package/schema/DatabaseSchema.js +307 -331
  79. package/schema/DatabaseTable.d.ts +73 -96
  80. package/schema/DatabaseTable.js +927 -1012
  81. package/schema/SchemaComparator.d.ts +66 -70
  82. package/schema/SchemaComparator.js +740 -766
  83. package/schema/SchemaHelper.d.ts +95 -109
  84. package/schema/SchemaHelper.js +659 -675
  85. package/schema/SqlSchemaGenerator.d.ts +58 -78
  86. package/schema/SqlSchemaGenerator.js +501 -535
  87. package/typings.d.ts +266 -380
@@ -1,256 +1,250 @@
1
- import { DeferMode, EnumType, Type, Utils } from '@mikro-orm/core';
1
+ import { DeferMode, EnumType, Type, Utils, } from '@mikro-orm/core';
2
2
  import { SchemaHelper } from '../../schema/SchemaHelper.js';
3
3
  /** PostGIS system views that should be automatically ignored */
4
4
  const POSTGIS_VIEWS = ['geography_columns', 'geometry_columns'];
5
5
  export class PostgreSqlSchemaHelper extends SchemaHelper {
6
- static DEFAULT_VALUES = {
7
- 'now()': ['now()', 'current_timestamp'],
8
- 'current_timestamp(?)': ['current_timestamp(?)'],
9
- "('now'::text)::timestamp(?) with time zone": ['current_timestamp(?)'],
10
- "('now'::text)::timestamp(?) without time zone": ['current_timestamp(?)'],
11
- 'null::character varying': ['null'],
12
- 'null::timestamp with time zone': ['null'],
13
- 'null::timestamp without time zone': ['null'],
14
- };
15
- getSchemaBeginning(charset, disableForeignKeys) {
16
- if (disableForeignKeys) {
17
- return `set names '${charset}';\n${this.disableForeignKeysSQL()}\n\n`;
18
- }
19
- return `set names '${charset}';\n\n`;
20
- }
21
- getCreateDatabaseSQL(name) {
22
- return `create database ${this.quote(name)}`;
23
- }
24
- getListTablesSQL() {
25
- return (
26
- `select table_name, table_schema as schema_name, ` +
27
- `(select pg_catalog.obj_description(c.oid) from pg_catalog.pg_class c
6
+ static DEFAULT_VALUES = {
7
+ 'now()': ['now()', 'current_timestamp'],
8
+ 'current_timestamp(?)': ['current_timestamp(?)'],
9
+ "('now'::text)::timestamp(?) with time zone": ['current_timestamp(?)'],
10
+ "('now'::text)::timestamp(?) without time zone": ['current_timestamp(?)'],
11
+ 'null::character varying': ['null'],
12
+ 'null::timestamp with time zone': ['null'],
13
+ 'null::timestamp without time zone': ['null'],
14
+ };
15
+ getSchemaBeginning(charset, disableForeignKeys) {
16
+ if (disableForeignKeys) {
17
+ return `set names '${charset}';\n${this.disableForeignKeysSQL()}\n\n`;
18
+ }
19
+ return `set names '${charset}';\n\n`;
20
+ }
21
+ getCreateDatabaseSQL(name) {
22
+ return `create database ${this.quote(name)}`;
23
+ }
24
+ getListTablesSQL() {
25
+ return (`select table_name, table_schema as schema_name, ` +
26
+ `(select pg_catalog.obj_description(c.oid) from pg_catalog.pg_class c
28
27
  where c.oid = (select ('"' || table_schema || '"."' || table_name || '"')::regclass::oid) and c.relname = table_name) as table_comment ` +
29
- `from information_schema.tables ` +
30
- `where ${this.getIgnoredNamespacesConditionSQL('table_schema')} ` +
31
- `and table_name != 'geometry_columns' and table_name != 'spatial_ref_sys' and table_type != 'VIEW' ` +
32
- `and table_name not in (select inhrelid::regclass::text from pg_inherits) ` +
33
- `order by table_name`
34
- );
35
- }
36
- getIgnoredViewsCondition() {
37
- return POSTGIS_VIEWS.map(v => `table_name != '${v}'`).join(' and ');
38
- }
39
- getListViewsSQL() {
40
- return (
41
- `select table_name as view_name, table_schema as schema_name, view_definition ` +
42
- `from information_schema.views ` +
43
- `where ${this.getIgnoredNamespacesConditionSQL('table_schema')} ` +
44
- `and ${this.getIgnoredViewsCondition()} ` +
45
- `order by table_name`
46
- );
47
- }
48
- async loadViews(schema, connection) {
49
- const views = await connection.execute(this.getListViewsSQL());
50
- for (const view of views) {
51
- const definition = view.view_definition?.trim().replace(/;$/, '') ?? '';
52
- if (definition) {
53
- schema.addView(view.view_name, view.schema_name, definition);
54
- }
55
- }
56
- }
57
- getListMaterializedViewsSQL() {
58
- return (
59
- `select matviewname as view_name, schemaname as schema_name, definition as view_definition ` +
60
- `from pg_matviews ` +
61
- `where ${this.getIgnoredNamespacesConditionSQL('schemaname')} ` +
62
- `order by matviewname`
63
- );
64
- }
65
- async loadMaterializedViews(schema, connection, schemaName) {
66
- const views = await connection.execute(this.getListMaterializedViewsSQL());
67
- for (const view of views) {
68
- const definition = view.view_definition?.trim().replace(/;$/, '') ?? '';
69
- if (definition) {
70
- schema.addView(view.view_name, view.schema_name, definition, true);
71
- }
72
- }
73
- }
74
- createMaterializedView(name, schema, definition, withData = true) {
75
- const viewName = this.quote(this.getTableName(name, schema));
76
- const dataClause = withData ? ' with data' : ' with no data';
77
- return `create materialized view ${viewName} as ${definition}${dataClause}`;
78
- }
79
- dropMaterializedViewIfExists(name, schema) {
80
- return `drop materialized view if exists ${this.quote(this.getTableName(name, schema))} cascade`;
81
- }
82
- refreshMaterializedView(name, schema, concurrently = false) {
83
- const concurrent = concurrently ? ' concurrently' : '';
84
- return `refresh materialized view${concurrent} ${this.quote(this.getTableName(name, schema))}`;
85
- }
86
- async getNamespaces(connection) {
87
- const sql =
88
- `select schema_name from information_schema.schemata ` +
89
- `where ${this.getIgnoredNamespacesConditionSQL()} ` +
90
- `order by schema_name`;
91
- const res = await connection.execute(sql);
92
- return res.map(row => row.schema_name);
93
- }
94
- getIgnoredNamespacesConditionSQL(column = 'schema_name') {
95
- const ignored = [
96
- 'information_schema',
97
- 'tiger',
98
- 'topology',
99
- /* v8 ignore next */
100
- ...(this.platform.getConfig().get('schemaGenerator').ignoreSchema ?? []),
101
- ]
102
- .map(s => this.platform.quoteValue(s))
103
- .join(', ');
104
- const ignoredPrefixes = ['pg_', 'crdb_', '_timescaledb_'].map(p => `"${column}" not like '${p}%'`).join(' and ');
105
- return `${ignoredPrefixes} and "${column}" not in (${ignored})`;
106
- }
107
- async loadInformationSchema(schema, connection, tables, schemas) {
108
- schemas ??= tables.length === 0 ? [schema.name] : tables.map(t => t.schema_name);
109
- const nativeEnums = await this.getNativeEnumDefinitions(connection, schemas);
110
- schema.setNativeEnums(nativeEnums);
111
- if (tables.length === 0) {
112
- return;
113
- }
114
- const tablesBySchema = this.getTablesGroupedBySchemas(tables);
115
- const columns = await this.getAllColumns(connection, tablesBySchema, nativeEnums);
116
- const indexes = await this.getAllIndexes(connection, tables);
117
- const checks = await this.getAllChecks(connection, tablesBySchema);
118
- const fks = await this.getAllForeignKeys(connection, tablesBySchema);
119
- for (const t of tables) {
120
- const key = this.getTableKey(t);
121
- const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
122
- const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
123
- const enums = this.getEnumDefinitions(checks[key] ?? []);
124
- if (columns[key]) {
125
- table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
126
- }
127
- }
128
- }
129
- async getAllIndexes(connection, tables) {
130
- const sql = this.getIndexesSQL(tables);
131
- const unquote = str => str.replace(/['"`]/g, '');
132
- const allIndexes = await connection.execute(sql);
133
- const ret = {};
134
- for (const index of allIndexes) {
135
- const key = this.getTableKey(index);
136
- // Extract INCLUDE columns from expression first, to filter them from key columns
137
- const includeMatch = index.expression?.match(/include\s*\(([^)]+)\)/i);
138
- const includeColumns = includeMatch ? includeMatch[1].split(',').map(col => unquote(col.trim())) : [];
139
- // Filter out INCLUDE columns from the column definitions to get only key columns
140
- const keyColumnDefs = index.index_def.filter(col => !includeColumns.includes(unquote(col)));
141
- // Parse sort order and NULLS ordering from the full expression
142
- // pg_get_indexdef individual columns don't include sort modifiers, so we parse from full expression
143
- const columns = this.parseIndexColumnsFromExpression(index.expression, keyColumnDefs, unquote);
144
- const columnNames = columns.map(col => col.name);
145
- const hasAdvancedColumnOptions = columns.some(col => col.sort || col.nulls || col.collation);
146
- const indexDef = {
147
- columnNames,
148
- composite: columnNames.length > 1,
149
- // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them
150
- constraint: index.contype === 'u',
151
- keyName: index.constraint_name,
152
- unique: index.unique,
153
- primary: index.primary,
154
- };
155
- // Add columns array if there are advanced options
156
- if (hasAdvancedColumnOptions) {
157
- indexDef.columns = columns;
158
- }
159
- if (index.condeferrable) {
160
- indexDef.deferMode = index.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
161
- }
162
- if (index.index_def.some(col => /[(): ,"'`]/.exec(col)) || index.expression?.match(/ where /i)) {
163
- indexDef.expression = index.expression;
164
- }
165
- if (index.deferrable) {
166
- indexDef.deferMode = index.initially_deferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
167
- }
168
- // Extract fillFactor from reloptions
169
- if (index.reloptions) {
170
- const fillFactorMatch = index.reloptions.find(opt => opt.startsWith('fillfactor='));
171
- if (fillFactorMatch) {
172
- indexDef.fillFactor = parseInt(fillFactorMatch.split('=')[1], 10);
173
- }
174
- }
175
- // Add INCLUDE columns (already extracted above)
176
- if (includeColumns.length > 0) {
177
- indexDef.include = includeColumns;
178
- }
179
- // Add index type if not btree (the default)
180
- if (index.index_type && index.index_type !== 'btree') {
181
- indexDef.type = index.index_type;
182
- }
183
- ret[key] ??= [];
184
- ret[key].push(indexDef);
185
- }
186
- return ret;
187
- }
188
- /**
189
- * Parses column definitions from the full CREATE INDEX expression.
190
- * Since pg_get_indexdef(oid, col_num, true) doesn't include sort modifiers,
191
- * we extract them from the full expression instead.
192
- *
193
- * We use columnDefs (from individual pg_get_indexdef calls) as the source
194
- * of column names, and find their modifiers in the expression.
195
- */
196
- parseIndexColumnsFromExpression(expression, columnDefs, unquote) {
197
- // Extract just the column list from the expression (between first parens after USING)
198
- // Pattern: ... USING method (...columns...) [INCLUDE (...)] [WHERE ...]
199
- // Note: pg_get_indexdef always returns a valid expression with USING clause
200
- const usingMatch = /using\s+\w+\s*\(/i.exec(expression);
201
- const startIdx = usingMatch.index + usingMatch[0].length - 1; // Position of opening (
202
- const columnsStr = this.extractParenthesizedContent(expression, startIdx);
203
- // Use the column names from columnDefs and find their modifiers in the expression
204
- return columnDefs.map(colDef => {
205
- const name = unquote(colDef);
206
- const result = { name };
207
- // Find this column in the expression and extract modifiers
208
- // Create a pattern that matches the column name (quoted or unquoted) followed by modifiers
209
- const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
210
- const colPattern = new RegExp(`"?${escapedName}"?\\s*([^,)]*?)(?:,|$)`, 'i');
211
- const colMatch = columnsStr.match(colPattern);
212
- if (colMatch) {
213
- const modifiers = colMatch[1];
214
- // Extract sort order (PostgreSQL omits ASC in output as it's the default)
215
- if (/\bdesc\b/i.test(modifiers)) {
216
- result.sort = 'DESC';
217
- }
218
- // Extract NULLS ordering
219
- const nullsMatch = /nulls\s+(first|last)/i.exec(modifiers);
220
- if (nullsMatch) {
221
- result.nulls = nullsMatch[1].toUpperCase();
222
- }
223
- // Extract collation
224
- const collateMatch = /collate\s+"?([^"\s,)]+)"?/i.exec(modifiers);
225
- if (collateMatch) {
226
- result.collation = collateMatch[1];
227
- }
228
- }
229
- return result;
230
- });
231
- }
232
- /**
233
- * Extracts the content inside parentheses starting at the given position.
234
- * Handles nested parentheses correctly.
235
- */
236
- extractParenthesizedContent(str, startIdx) {
237
- let depth = 0;
238
- const start = startIdx + 1;
239
- for (let i = startIdx; i < str.length; i++) {
240
- if (str[i] === '(') {
241
- depth++;
242
- } else if (str[i] === ')') {
243
- depth--;
244
- if (depth === 0) {
245
- return str.slice(start, i);
246
- }
247
- }
248
- }
249
- /* v8 ignore next - pg_get_indexdef always returns balanced parentheses */
250
- return '';
251
- }
252
- async getAllColumns(connection, tablesBySchemas, nativeEnums) {
253
- const sql = `select table_schema as schema_name, table_name, column_name,
28
+ `from information_schema.tables ` +
29
+ `where ${this.getIgnoredNamespacesConditionSQL('table_schema')} ` +
30
+ `and table_name != 'geometry_columns' and table_name != 'spatial_ref_sys' and table_type != 'VIEW' ` +
31
+ `and table_name not in (select inhrelid::regclass::text from pg_inherits) ` +
32
+ `order by table_name`);
33
+ }
34
+ getIgnoredViewsCondition() {
35
+ return POSTGIS_VIEWS.map(v => `table_name != '${v}'`).join(' and ');
36
+ }
37
+ getListViewsSQL() {
38
+ return (`select table_name as view_name, table_schema as schema_name, view_definition ` +
39
+ `from information_schema.views ` +
40
+ `where ${this.getIgnoredNamespacesConditionSQL('table_schema')} ` +
41
+ `and ${this.getIgnoredViewsCondition()} ` +
42
+ `order by table_name`);
43
+ }
44
+ async loadViews(schema, connection) {
45
+ const views = await connection.execute(this.getListViewsSQL());
46
+ for (const view of views) {
47
+ const definition = view.view_definition?.trim().replace(/;$/, '') ?? '';
48
+ if (definition) {
49
+ schema.addView(view.view_name, view.schema_name, definition);
50
+ }
51
+ }
52
+ }
53
+ getListMaterializedViewsSQL() {
54
+ return (`select matviewname as view_name, schemaname as schema_name, definition as view_definition ` +
55
+ `from pg_matviews ` +
56
+ `where ${this.getIgnoredNamespacesConditionSQL('schemaname')} ` +
57
+ `order by matviewname`);
58
+ }
59
+ async loadMaterializedViews(schema, connection, schemaName) {
60
+ const views = await connection.execute(this.getListMaterializedViewsSQL());
61
+ for (const view of views) {
62
+ const definition = view.view_definition?.trim().replace(/;$/, '') ?? '';
63
+ if (definition) {
64
+ schema.addView(view.view_name, view.schema_name, definition, true);
65
+ }
66
+ }
67
+ }
68
+ createMaterializedView(name, schema, definition, withData = true) {
69
+ const viewName = this.quote(this.getTableName(name, schema));
70
+ const dataClause = withData ? ' with data' : ' with no data';
71
+ return `create materialized view ${viewName} as ${definition}${dataClause}`;
72
+ }
73
+ dropMaterializedViewIfExists(name, schema) {
74
+ return `drop materialized view if exists ${this.quote(this.getTableName(name, schema))} cascade`;
75
+ }
76
+ refreshMaterializedView(name, schema, concurrently = false) {
77
+ const concurrent = concurrently ? ' concurrently' : '';
78
+ return `refresh materialized view${concurrent} ${this.quote(this.getTableName(name, schema))}`;
79
+ }
80
+ async getNamespaces(connection) {
81
+ const sql = `select schema_name from information_schema.schemata ` +
82
+ `where ${this.getIgnoredNamespacesConditionSQL()} ` +
83
+ `order by schema_name`;
84
+ const res = await connection.execute(sql);
85
+ return res.map(row => row.schema_name);
86
+ }
87
+ getIgnoredNamespacesConditionSQL(column = 'schema_name') {
88
+ const ignored = [
89
+ 'information_schema',
90
+ 'tiger',
91
+ 'topology',
92
+ /* v8 ignore next */
93
+ ...(this.platform.getConfig().get('schemaGenerator').ignoreSchema ?? []),
94
+ ]
95
+ .map(s => this.platform.quoteValue(s))
96
+ .join(', ');
97
+ const ignoredPrefixes = ['pg_', 'crdb_', '_timescaledb_'].map(p => `"${column}" not like '${p}%'`).join(' and ');
98
+ return `${ignoredPrefixes} and "${column}" not in (${ignored})`;
99
+ }
100
+ async loadInformationSchema(schema, connection, tables, schemas) {
101
+ schemas ??= tables.length === 0 ? [schema.name] : tables.map(t => t.schema_name);
102
+ const nativeEnums = await this.getNativeEnumDefinitions(connection, schemas);
103
+ schema.setNativeEnums(nativeEnums);
104
+ if (tables.length === 0) {
105
+ return;
106
+ }
107
+ const tablesBySchema = this.getTablesGroupedBySchemas(tables);
108
+ const columns = await this.getAllColumns(connection, tablesBySchema, nativeEnums);
109
+ const indexes = await this.getAllIndexes(connection, tables);
110
+ const checks = await this.getAllChecks(connection, tablesBySchema);
111
+ const fks = await this.getAllForeignKeys(connection, tablesBySchema);
112
+ for (const t of tables) {
113
+ const key = this.getTableKey(t);
114
+ const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
115
+ const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
116
+ const enums = this.getEnumDefinitions(checks[key] ?? []);
117
+ if (columns[key]) {
118
+ table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
119
+ }
120
+ }
121
+ }
122
+ async getAllIndexes(connection, tables) {
123
+ const sql = this.getIndexesSQL(tables);
124
+ const unquote = (str) => str.replace(/['"`]/g, '');
125
+ const allIndexes = await connection.execute(sql);
126
+ const ret = {};
127
+ for (const index of allIndexes) {
128
+ const key = this.getTableKey(index);
129
+ // Extract INCLUDE columns from expression first, to filter them from key columns
130
+ const includeMatch = index.expression?.match(/include\s*\(([^)]+)\)/i);
131
+ const includeColumns = includeMatch ? includeMatch[1].split(',').map((col) => unquote(col.trim())) : [];
132
+ // Filter out INCLUDE columns from the column definitions to get only key columns
133
+ const keyColumnDefs = index.index_def.filter((col) => !includeColumns.includes(unquote(col)));
134
+ // Parse sort order and NULLS ordering from the full expression
135
+ // pg_get_indexdef individual columns don't include sort modifiers, so we parse from full expression
136
+ const columns = this.parseIndexColumnsFromExpression(index.expression, keyColumnDefs, unquote);
137
+ const columnNames = columns.map(col => col.name);
138
+ const hasAdvancedColumnOptions = columns.some(col => col.sort || col.nulls || col.collation);
139
+ const indexDef = {
140
+ columnNames,
141
+ composite: columnNames.length > 1,
142
+ // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them
143
+ constraint: index.contype === 'u',
144
+ keyName: index.constraint_name,
145
+ unique: index.unique,
146
+ primary: index.primary,
147
+ };
148
+ // Add columns array if there are advanced options
149
+ if (hasAdvancedColumnOptions) {
150
+ indexDef.columns = columns;
151
+ }
152
+ if (index.condeferrable) {
153
+ indexDef.deferMode = index.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
154
+ }
155
+ if (index.index_def.some((col) => /[(): ,"'`]/.exec(col)) || index.expression?.match(/ where /i)) {
156
+ indexDef.expression = index.expression;
157
+ }
158
+ if (index.deferrable) {
159
+ indexDef.deferMode = index.initially_deferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
160
+ }
161
+ // Extract fillFactor from reloptions
162
+ if (index.reloptions) {
163
+ const fillFactorMatch = index.reloptions.find((opt) => opt.startsWith('fillfactor='));
164
+ if (fillFactorMatch) {
165
+ indexDef.fillFactor = parseInt(fillFactorMatch.split('=')[1], 10);
166
+ }
167
+ }
168
+ // Add INCLUDE columns (already extracted above)
169
+ if (includeColumns.length > 0) {
170
+ indexDef.include = includeColumns;
171
+ }
172
+ // Add index type if not btree (the default)
173
+ if (index.index_type && index.index_type !== 'btree') {
174
+ indexDef.type = index.index_type;
175
+ }
176
+ ret[key] ??= [];
177
+ ret[key].push(indexDef);
178
+ }
179
+ return ret;
180
+ }
181
+ /**
182
+ * Parses column definitions from the full CREATE INDEX expression.
183
+ * Since pg_get_indexdef(oid, col_num, true) doesn't include sort modifiers,
184
+ * we extract them from the full expression instead.
185
+ *
186
+ * We use columnDefs (from individual pg_get_indexdef calls) as the source
187
+ * of column names, and find their modifiers in the expression.
188
+ */
189
+ parseIndexColumnsFromExpression(expression, columnDefs, unquote) {
190
+ // Extract just the column list from the expression (between first parens after USING)
191
+ // Pattern: ... USING method (...columns...) [INCLUDE (...)] [WHERE ...]
192
+ // Note: pg_get_indexdef always returns a valid expression with USING clause
193
+ const usingMatch = /using\s+\w+\s*\(/i.exec(expression);
194
+ const startIdx = usingMatch.index + usingMatch[0].length - 1; // Position of opening (
195
+ const columnsStr = this.extractParenthesizedContent(expression, startIdx);
196
+ // Use the column names from columnDefs and find their modifiers in the expression
197
+ return columnDefs.map(colDef => {
198
+ const name = unquote(colDef);
199
+ const result = { name };
200
+ // Find this column in the expression and extract modifiers
201
+ // Create a pattern that matches the column name (quoted or unquoted) followed by modifiers
202
+ const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
203
+ const colPattern = new RegExp(`"?${escapedName}"?\\s*([^,)]*?)(?:,|$)`, 'i');
204
+ const colMatch = columnsStr.match(colPattern);
205
+ if (colMatch) {
206
+ const modifiers = colMatch[1];
207
+ // Extract sort order (PostgreSQL omits ASC in output as it's the default)
208
+ if (/\bdesc\b/i.test(modifiers)) {
209
+ result.sort = 'DESC';
210
+ }
211
+ // Extract NULLS ordering
212
+ const nullsMatch = /nulls\s+(first|last)/i.exec(modifiers);
213
+ if (nullsMatch) {
214
+ result.nulls = nullsMatch[1].toUpperCase();
215
+ }
216
+ // Extract collation
217
+ const collateMatch = /collate\s+"?([^"\s,)]+)"?/i.exec(modifiers);
218
+ if (collateMatch) {
219
+ result.collation = collateMatch[1];
220
+ }
221
+ }
222
+ return result;
223
+ });
224
+ }
225
+ /**
226
+ * Extracts the content inside parentheses starting at the given position.
227
+ * Handles nested parentheses correctly.
228
+ */
229
+ extractParenthesizedContent(str, startIdx) {
230
+ let depth = 0;
231
+ const start = startIdx + 1;
232
+ for (let i = startIdx; i < str.length; i++) {
233
+ if (str[i] === '(') {
234
+ depth++;
235
+ }
236
+ else if (str[i] === ')') {
237
+ depth--;
238
+ if (depth === 0) {
239
+ return str.slice(start, i);
240
+ }
241
+ }
242
+ }
243
+ /* v8 ignore next - pg_get_indexdef always returns balanced parentheses */
244
+ return '';
245
+ }
246
+ async getAllColumns(connection, tablesBySchemas, nativeEnums) {
247
+ const sql = `select table_schema as schema_name, table_name, column_name,
254
248
  column_default,
255
249
  is_nullable,
256
250
  udt_name,
@@ -269,115 +263,111 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
269
263
  join pg_attribute pga on pgc.oid = pga.attrelid and cols.column_name = pga.attname
270
264
  where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(table_schema = ${this.platform.quoteValue(schema)} and table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}))`).join(' or ')})
271
265
  order by ordinal_position`;
272
- const allColumns = await connection.execute(sql);
273
- const str = val => (val != null ? '' + val : val);
274
- const ret = {};
275
- for (const col of allColumns) {
276
- const mappedType = connection.getPlatform().getMappedType(col.data_type);
277
- const increments =
278
- (col.column_default?.includes('nextval') || col.is_identity === 'YES') &&
279
- connection.getPlatform().isNumericColumn(mappedType);
280
- const key = this.getTableKey(col);
281
- ret[key] ??= [];
282
- let type = col.data_type.toLowerCase() === 'array' ? col.udt_name.replace(/^_(.*)$/, '$1[]') : col.udt_name;
283
- if (
284
- col.data_type === 'USER-DEFINED' &&
285
- col.udt_schema &&
286
- col.udt_schema !== this.platform.getDefaultSchemaName()
287
- ) {
288
- type = `${col.udt_schema}.${type}`;
289
- }
290
- if (type === 'bpchar') {
291
- type = 'char';
292
- }
293
- if (type === 'vector' && col.length == null && col.custom_length != null && col.custom_length !== -1) {
294
- col.length = col.custom_length;
295
- }
296
- if (col.length != null && !type.endsWith(`(${col.length})`) && !['text', 'date'].includes(type)) {
297
- type += `(${col.length})`;
298
- }
299
- if (type === 'numeric' && col.numeric_precision != null && col.numeric_scale != null) {
300
- type += `(${col.numeric_precision},${col.numeric_scale})`;
301
- }
302
- const length = this.inferLengthFromColumnType(type) === -1 ? -1 : col.length;
303
- const column = {
304
- name: col.column_name,
305
- type,
306
- mappedType,
307
- length,
308
- precision: col.numeric_precision,
309
- scale: col.numeric_scale,
310
- nullable: col.is_nullable === 'YES',
311
- default: str(this.normalizeDefaultValue(col.column_default, col.length)),
312
- unsigned: increments,
313
- autoincrement: increments,
314
- generated:
315
- col.is_identity === 'YES'
316
- ? col.identity_generation === 'BY DEFAULT'
317
- ? 'by default as identity'
318
- : 'identity'
319
- : col.generation_expression
320
- ? col.generation_expression + ' stored'
321
- : undefined,
322
- comment: col.column_comment,
323
- };
324
- let enumKey = column.type;
325
- let enumEntry = nativeEnums?.[enumKey];
326
- // for array enum columns, strip the [] suffix and try the base type,
327
- // try schema-qualified key first for non-default schemas to avoid
328
- // ambiguity when multiple schemas have enums with the same name
329
- if (!enumEntry && enumKey.endsWith('[]')) {
330
- const baseType = enumKey.slice(0, -2);
331
- if (col.udt_schema && col.udt_schema !== this.platform.getDefaultSchemaName()) {
332
- const schemaKey = `${col.udt_schema}.${baseType}`;
333
- enumEntry = nativeEnums?.[schemaKey];
334
- if (enumEntry) {
335
- enumKey = schemaKey;
336
- column.type = `${schemaKey}[]`;
337
- }
338
- }
339
- if (!enumEntry) {
340
- enumEntry = nativeEnums?.[baseType];
341
- if (enumEntry) {
342
- enumKey = baseType;
343
- }
344
- }
345
- }
346
- if (enumEntry) {
347
- column.mappedType = Type.getType(EnumType);
348
- column.nativeEnumName = enumKey;
349
- column.enumItems = enumEntry.items;
350
- }
351
- ret[key].push(column);
352
- }
353
- return ret;
354
- }
355
- async getAllChecks(connection, tablesBySchemas) {
356
- const sql = this.getChecksSQL(tablesBySchemas);
357
- const allChecks = await connection.execute(sql);
358
- const ret = {};
359
- const seen = new Set();
360
- for (const check of allChecks) {
361
- const key = this.getTableKey(check);
362
- const dedupeKey = `${key}:${check.name}`;
363
- if (seen.has(dedupeKey)) {
364
- continue;
365
- }
366
- seen.add(dedupeKey);
367
- ret[key] ??= [];
368
- const m = /^check \(\((.*)\)\)$/is.exec(check.expression);
369
- const def = m?.[1].replace(/\((.*?)\)::\w+/g, '$1');
370
- ret[key].push({
371
- name: check.name,
372
- columnName: check.column_name,
373
- definition: check.expression,
374
- expression: def,
375
- });
376
- }
377
- return ret;
378
- }
379
- async getAllForeignKeys(connection, tablesBySchemas) {
380
- const sql = `select nsp1.nspname schema_name, cls1.relname table_name, nsp2.nspname referenced_schema_name,
266
+ const allColumns = await connection.execute(sql);
267
+ const str = (val) => (val != null ? '' + val : val);
268
+ const ret = {};
269
+ for (const col of allColumns) {
270
+ const mappedType = connection.getPlatform().getMappedType(col.data_type);
271
+ const increments = (col.column_default?.includes('nextval') || col.is_identity === 'YES') &&
272
+ connection.getPlatform().isNumericColumn(mappedType);
273
+ const key = this.getTableKey(col);
274
+ ret[key] ??= [];
275
+ let type = col.data_type.toLowerCase() === 'array' ? col.udt_name.replace(/^_(.*)$/, '$1[]') : col.udt_name;
276
+ if (col.data_type === 'USER-DEFINED' &&
277
+ col.udt_schema &&
278
+ col.udt_schema !== this.platform.getDefaultSchemaName()) {
279
+ type = `${col.udt_schema}.${type}`;
280
+ }
281
+ if (type === 'bpchar') {
282
+ type = 'char';
283
+ }
284
+ if (type === 'vector' && col.length == null && col.custom_length != null && col.custom_length !== -1) {
285
+ col.length = col.custom_length;
286
+ }
287
+ if (col.length != null && !type.endsWith(`(${col.length})`) && !['text', 'date'].includes(type)) {
288
+ type += `(${col.length})`;
289
+ }
290
+ if (type === 'numeric' && col.numeric_precision != null && col.numeric_scale != null) {
291
+ type += `(${col.numeric_precision},${col.numeric_scale})`;
292
+ }
293
+ const length = this.inferLengthFromColumnType(type) === -1 ? -1 : col.length;
294
+ const column = {
295
+ name: col.column_name,
296
+ type,
297
+ mappedType,
298
+ length,
299
+ precision: col.numeric_precision,
300
+ scale: col.numeric_scale,
301
+ nullable: col.is_nullable === 'YES',
302
+ default: str(this.normalizeDefaultValue(col.column_default, col.length)),
303
+ unsigned: increments,
304
+ autoincrement: increments,
305
+ generated: col.is_identity === 'YES'
306
+ ? col.identity_generation === 'BY DEFAULT'
307
+ ? 'by default as identity'
308
+ : 'identity'
309
+ : col.generation_expression
310
+ ? col.generation_expression + ' stored'
311
+ : undefined,
312
+ comment: col.column_comment,
313
+ };
314
+ let enumKey = column.type;
315
+ let enumEntry = nativeEnums?.[enumKey];
316
+ // for array enum columns, strip the [] suffix and try the base type,
317
+ // try schema-qualified key first for non-default schemas to avoid
318
+ // ambiguity when multiple schemas have enums with the same name
319
+ if (!enumEntry && enumKey.endsWith('[]')) {
320
+ const baseType = enumKey.slice(0, -2);
321
+ if (col.udt_schema && col.udt_schema !== this.platform.getDefaultSchemaName()) {
322
+ const schemaKey = `${col.udt_schema}.${baseType}`;
323
+ enumEntry = nativeEnums?.[schemaKey];
324
+ if (enumEntry) {
325
+ enumKey = schemaKey;
326
+ column.type = `${schemaKey}[]`;
327
+ }
328
+ }
329
+ if (!enumEntry) {
330
+ enumEntry = nativeEnums?.[baseType];
331
+ if (enumEntry) {
332
+ enumKey = baseType;
333
+ }
334
+ }
335
+ }
336
+ if (enumEntry) {
337
+ column.mappedType = Type.getType(EnumType);
338
+ column.nativeEnumName = enumKey;
339
+ column.enumItems = enumEntry.items;
340
+ }
341
+ ret[key].push(column);
342
+ }
343
+ return ret;
344
+ }
345
+ async getAllChecks(connection, tablesBySchemas) {
346
+ const sql = this.getChecksSQL(tablesBySchemas);
347
+ const allChecks = await connection.execute(sql);
348
+ const ret = {};
349
+ const seen = new Set();
350
+ for (const check of allChecks) {
351
+ const key = this.getTableKey(check);
352
+ const dedupeKey = `${key}:${check.name}`;
353
+ if (seen.has(dedupeKey)) {
354
+ continue;
355
+ }
356
+ seen.add(dedupeKey);
357
+ ret[key] ??= [];
358
+ const m = /^check \(\((.*)\)\)$/is.exec(check.expression);
359
+ const def = m?.[1].replace(/\((.*?)\)::\w+/g, '$1');
360
+ ret[key].push({
361
+ name: check.name,
362
+ columnName: check.column_name,
363
+ definition: check.expression,
364
+ expression: def,
365
+ });
366
+ }
367
+ return ret;
368
+ }
369
+ async getAllForeignKeys(connection, tablesBySchemas) {
370
+ const sql = `select nsp1.nspname schema_name, cls1.relname table_name, nsp2.nspname referenced_schema_name,
381
371
  cls2.relname referenced_table_name, a.attname column_name, af.attname referenced_column_name, conname constraint_name,
382
372
  confupdtype update_rule, confdeltype delete_rule, array_position(con.conkey,a.attnum) as ord, condeferrable, condeferred,
383
373
  pg_get_constraintdef(con.oid) as constraint_def
@@ -391,360 +381,342 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
391
381
  where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(cls1.relname in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and nsp1.nspname = ${this.platform.quoteValue(schema)})`).join(' or ')})
392
382
  and confrelid > 0
393
383
  order by nsp1.nspname, cls1.relname, constraint_name, ord`;
394
- const allFks = await connection.execute(sql);
395
- const ret = {};
396
- function mapReferentialIntegrity(value, def) {
397
- const match = ['n', 'd'].includes(value) && /ON DELETE (SET (NULL|DEFAULT) \(.*?\))/.exec(def);
398
- if (match) {
399
- return match[1];
400
- }
401
- /* v8 ignore next */
402
- switch (value) {
403
- case 'r':
404
- return 'RESTRICT';
405
- case 'c':
406
- return 'CASCADE';
407
- case 'n':
408
- return 'SET NULL';
409
- case 'd':
410
- return 'SET DEFAULT';
411
- case 'a':
412
- default:
413
- return 'NO ACTION';
414
- }
415
- }
416
- for (const fk of allFks) {
417
- fk.update_rule = mapReferentialIntegrity(fk.update_rule, fk.constraint_def);
418
- fk.delete_rule = mapReferentialIntegrity(fk.delete_rule, fk.constraint_def);
419
- if (fk.condeferrable) {
420
- fk.defer_mode = fk.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
421
- }
422
- const key = this.getTableKey(fk);
423
- ret[key] ??= [];
424
- ret[key].push(fk);
425
- }
426
- Object.keys(ret).forEach(key => {
427
- const [schemaName, tableName] = key.split('.');
428
- ret[key] = this.mapForeignKeys(ret[key], tableName, schemaName);
429
- });
430
- return ret;
431
- }
432
- async getNativeEnumDefinitions(connection, schemas) {
433
- const uniqueSchemas = Utils.unique(schemas);
434
- const res = await connection.execute(
435
- `select t.typname as enum_name, n.nspname as schema_name, array_agg(e.enumlabel order by e.enumsortorder) as enum_value
384
+ const allFks = await connection.execute(sql);
385
+ const ret = {};
386
+ function mapReferentialIntegrity(value, def) {
387
+ const match = ['n', 'd'].includes(value) && /ON DELETE (SET (NULL|DEFAULT) \(.*?\))/.exec(def);
388
+ if (match) {
389
+ return match[1];
390
+ }
391
+ /* v8 ignore next */
392
+ switch (value) {
393
+ case 'r':
394
+ return 'RESTRICT';
395
+ case 'c':
396
+ return 'CASCADE';
397
+ case 'n':
398
+ return 'SET NULL';
399
+ case 'd':
400
+ return 'SET DEFAULT';
401
+ case 'a':
402
+ default:
403
+ return 'NO ACTION';
404
+ }
405
+ }
406
+ for (const fk of allFks) {
407
+ fk.update_rule = mapReferentialIntegrity(fk.update_rule, fk.constraint_def);
408
+ fk.delete_rule = mapReferentialIntegrity(fk.delete_rule, fk.constraint_def);
409
+ if (fk.condeferrable) {
410
+ fk.defer_mode = fk.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
411
+ }
412
+ const key = this.getTableKey(fk);
413
+ ret[key] ??= [];
414
+ ret[key].push(fk);
415
+ }
416
+ Object.keys(ret).forEach(key => {
417
+ const [schemaName, tableName] = key.split('.');
418
+ ret[key] = this.mapForeignKeys(ret[key], tableName, schemaName);
419
+ });
420
+ return ret;
421
+ }
422
+ async getNativeEnumDefinitions(connection, schemas) {
423
+ const uniqueSchemas = Utils.unique(schemas);
424
+ const res = await connection.execute(`select t.typname as enum_name, n.nspname as schema_name, array_agg(e.enumlabel order by e.enumsortorder) as enum_value
436
425
  from pg_type t
437
426
  join pg_enum e on t.oid = e.enumtypid
438
427
  join pg_catalog.pg_namespace n on n.oid = t.typnamespace
439
428
  where n.nspname in (${Array(uniqueSchemas.length).fill('?').join(', ')})
440
- group by t.typname, n.nspname`,
441
- uniqueSchemas,
442
- );
443
- return res.reduce((o, row) => {
444
- let name = row.enum_name;
445
- if (row.schema_name && row.schema_name !== this.platform.getDefaultSchemaName()) {
446
- name = row.schema_name + '.' + name;
447
- }
448
- let items = row.enum_value;
449
- if (!Array.isArray(items)) {
450
- items = this.platform.unmarshallArray(row.enum_value);
451
- }
452
- o[name] = {
453
- name: row.enum_name,
454
- schema: row.schema_name,
455
- items,
456
- };
457
- return o;
458
- }, {});
459
- }
460
- getCreateNativeEnumSQL(name, values, schema) {
461
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
462
- name = schema + '.' + name;
463
- }
464
- return `create type ${this.quote(name)} as enum (${values.map(value => this.platform.quoteValue(value)).join(', ')})`;
465
- }
466
- getDropNativeEnumSQL(name, schema) {
467
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
468
- name = schema + '.' + name;
469
- }
470
- return `drop type ${this.quote(name)}`;
471
- }
472
- getAlterNativeEnumSQL(name, schema, value, items, oldItems) {
473
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
474
- name = schema + '.' + name;
475
- }
476
- let suffix = '';
477
- if (items && value && oldItems) {
478
- const position = items.indexOf(value);
479
- if (position > 0) {
480
- suffix = ` after ${this.platform.quoteValue(items[position - 1])}`;
481
- } else if (items.length > 1 && oldItems.length > 0) {
482
- suffix = ` before ${this.platform.quoteValue(oldItems[0])}`;
483
- }
484
- }
485
- return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
486
- }
487
- getEnumDefinitions(checks) {
488
- return checks.reduce((o, item) => {
489
- // check constraints are defined as one of:
490
- // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
491
- // `CHECK (("columnName" = ANY (ARRAY['local'::text, 'global'::text])))`
492
- // `CHECK (((enum_test)::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
493
- // `CHECK ((("enumTest")::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
494
- // `CHECK ((type = 'a'::text))`
495
- const m1 =
496
- item.definition?.match(/check \(\(\("?(\w+)"?\)::/i) || item.definition?.match(/check \(\("?(\w+)"? = /i);
497
- const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = (.*)\)/i);
498
- if (item.columnName && m1 && m2) {
499
- const m3 = m2[1].match(/('[^']*'::text)/g);
500
- let items;
429
+ group by t.typname, n.nspname`, uniqueSchemas);
430
+ return res.reduce((o, row) => {
431
+ let name = row.enum_name;
432
+ if (row.schema_name && row.schema_name !== this.platform.getDefaultSchemaName()) {
433
+ name = row.schema_name + '.' + name;
434
+ }
435
+ let items = row.enum_value;
436
+ if (!Array.isArray(items)) {
437
+ items = this.platform.unmarshallArray(row.enum_value);
438
+ }
439
+ o[name] = {
440
+ name: row.enum_name,
441
+ schema: row.schema_name,
442
+ items,
443
+ };
444
+ return o;
445
+ }, {});
446
+ }
447
+ getCreateNativeEnumSQL(name, values, schema) {
448
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
449
+ name = schema + '.' + name;
450
+ }
451
+ return `create type ${this.quote(name)} as enum (${values.map(value => this.platform.quoteValue(value)).join(', ')})`;
452
+ }
453
+ getDropNativeEnumSQL(name, schema) {
454
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
455
+ name = schema + '.' + name;
456
+ }
457
+ return `drop type ${this.quote(name)}`;
458
+ }
459
+ getAlterNativeEnumSQL(name, schema, value, items, oldItems) {
460
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
461
+ name = schema + '.' + name;
462
+ }
463
+ let suffix = '';
464
+ if (items && value && oldItems) {
465
+ const position = items.indexOf(value);
466
+ if (position > 0) {
467
+ suffix = ` after ${this.platform.quoteValue(items[position - 1])}`;
468
+ }
469
+ else if (items.length > 1 && oldItems.length > 0) {
470
+ suffix = ` before ${this.platform.quoteValue(oldItems[0])}`;
471
+ }
472
+ }
473
+ return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
474
+ }
475
+ getEnumDefinitions(checks) {
476
+ return checks.reduce((o, item) => {
477
+ // check constraints are defined as one of:
478
+ // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
479
+ // `CHECK (("columnName" = ANY (ARRAY['local'::text, 'global'::text])))`
480
+ // `CHECK (((enum_test)::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
481
+ // `CHECK ((("enumTest")::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
482
+ // `CHECK ((type = 'a'::text))`
483
+ const m1 = item.definition?.match(/check \(\(\("?(\w+)"?\)::/i) || item.definition?.match(/check \(\("?(\w+)"? = /i);
484
+ const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = (.*)\)/i);
485
+ if (item.columnName && m1 && m2) {
486
+ const m3 = m2[1].match(/('[^']*'::text)/g);
487
+ let items;
488
+ /* v8 ignore next */
489
+ if (m3) {
490
+ items = m3.map((item) => /^\(?'(.*)'/.exec(item.trim())?.[1]);
491
+ }
492
+ else {
493
+ items = m2[1].split(',').map((item) => /^\(?'(.*)'/.exec(item.trim())?.[1]);
494
+ }
495
+ items = items.filter(item => item !== undefined);
496
+ if (items.length > 0) {
497
+ o[item.columnName] = items;
498
+ item.expression = `${this.quote(item.columnName)} in ('${items.join("', '")}')`;
499
+ item.definition = `check (${item.expression})`;
500
+ }
501
+ }
502
+ return o;
503
+ }, {});
504
+ }
505
+ createTableColumn(column, table) {
506
+ const pk = table.getPrimaryKey();
507
+ const compositePK = pk?.composite;
508
+ const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
509
+ const col = [this.quote(column.name)];
510
+ if (column.autoincrement && !column.generated && !compositePK) {
511
+ col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
512
+ }
513
+ else {
514
+ let columnType = column.type;
515
+ if (column.nativeEnumName) {
516
+ const parts = column.type.split('.');
517
+ if (parts.length === 2 && parts[0] === '*') {
518
+ columnType = `${table.schema}.${parts[1]}`;
519
+ }
520
+ if (columnType.endsWith('[]')) {
521
+ columnType = this.quote(columnType.substring(0, columnType.length - 2)) + '[]';
522
+ }
523
+ else {
524
+ columnType = this.quote(columnType);
525
+ }
526
+ }
527
+ if (column.generated === 'by default as identity') {
528
+ columnType += ` generated ${column.generated}`;
529
+ }
530
+ else if (column.generated) {
531
+ columnType += ` generated always as ${column.generated}`;
532
+ }
533
+ col.push(columnType);
534
+ Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
535
+ Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
536
+ }
537
+ if (column.autoincrement && !compositePK) {
538
+ Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
539
+ }
540
+ const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
541
+ Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
542
+ return col.join(' ');
543
+ }
544
+ getPreAlterTable(tableDiff, safe) {
545
+ const ret = [];
546
+ const parts = tableDiff.name.split('.');
547
+ const tableName = parts.pop();
548
+ const schemaName = parts.pop();
501
549
  /* v8 ignore next */
502
- if (m3) {
503
- items = m3.map(item => /^\(?'(.*)'/.exec(item.trim())?.[1]);
504
- } else {
505
- items = m2[1].split(',').map(item => /^\(?'(.*)'/.exec(item.trim())?.[1]);
506
- }
507
- items = items.filter(item => item !== undefined);
508
- if (items.length > 0) {
509
- o[item.columnName] = items;
510
- item.expression = `${this.quote(item.columnName)} in ('${items.join("', '")}')`;
511
- item.definition = `check (${item.expression})`;
512
- }
513
- }
514
- return o;
515
- }, {});
516
- }
517
- createTableColumn(column, table) {
518
- const pk = table.getPrimaryKey();
519
- const compositePK = pk?.composite;
520
- const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
521
- const col = [this.quote(column.name)];
522
- if (column.autoincrement && !column.generated && !compositePK) {
523
- col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
524
- } else {
525
- let columnType = column.type;
526
- if (column.nativeEnumName) {
527
- const parts = column.type.split('.');
528
- if (parts.length === 2 && parts[0] === '*') {
529
- columnType = `${table.schema}.${parts[1]}`;
530
- }
531
- if (columnType.endsWith('[]')) {
532
- columnType = this.quote(columnType.substring(0, columnType.length - 2)) + '[]';
533
- } else {
534
- columnType = this.quote(columnType);
535
- }
536
- }
537
- if (column.generated === 'by default as identity') {
538
- columnType += ` generated ${column.generated}`;
539
- } else if (column.generated) {
540
- columnType += ` generated always as ${column.generated}`;
541
- }
542
- col.push(columnType);
543
- Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
544
- Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
545
- }
546
- if (column.autoincrement && !compositePK) {
547
- Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
548
- }
549
- const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
550
- Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
551
- return col.join(' ');
552
- }
553
- getPreAlterTable(tableDiff, safe) {
554
- const ret = [];
555
- const parts = tableDiff.name.split('.');
556
- const tableName = parts.pop();
557
- const schemaName = parts.pop();
558
- /* v8 ignore next */
559
- const name =
560
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
561
- const quotedName = this.quote(name);
562
- // detect that the column was an enum before and remove the check constraint in such case here
563
- const changedEnums = Object.values(tableDiff.changedColumns).filter(
564
- col => col.fromColumn.mappedType instanceof EnumType,
565
- );
566
- for (const col of changedEnums) {
567
- if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
568
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
569
- }
570
- if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
571
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
572
- }
573
- }
574
- // changing uuid column type requires to cast it to text first
575
- const uuids = Object.values(tableDiff.changedColumns).filter(
576
- col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid',
577
- );
578
- for (const col of uuids) {
579
- ret.push(
580
- `alter table ${quotedName} alter column "${col.column.name}" type text using ("${col.column.name}"::text)`,
581
- );
582
- }
583
- for (const { column } of Object.values(tableDiff.changedColumns).filter(diff =>
584
- diff.changedProperties.has('autoincrement'),
585
- )) {
586
- if (!column.autoincrement && column.default == null) {
587
- ret.push(`alter table ${quotedName} alter column ${this.quote(column.name)} drop default`);
588
- }
589
- }
590
- return ret;
591
- }
592
- castColumn(name, type) {
593
- if (type === 'uuid') {
594
- type = 'text::uuid';
595
- }
596
- return ` using (${this.quote(name)}::${type})`;
597
- }
598
- dropForeignKey(tableName, constraintName) {
599
- return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
600
- }
601
- getPostAlterTable(tableDiff, safe) {
602
- const ret = [];
603
- const parts = tableDiff.name.split('.');
604
- const tableName = parts.pop();
605
- const schemaName = parts.pop();
606
- /* v8 ignore next */
607
- const name =
608
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
609
- const quotedName = this.quote(name);
610
- // detect that the column was an enum before and remove the check constraint in such a case here
611
- const changedEnums = Object.values(tableDiff.changedColumns).filter(
612
- col => col.fromColumn.mappedType instanceof EnumType,
613
- );
614
- for (const col of changedEnums) {
615
- if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
616
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
617
- }
618
- if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.column.default) {
619
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
620
- }
621
- }
622
- for (const { column } of Object.values(tableDiff.changedColumns).filter(diff =>
623
- diff.changedProperties.has('autoincrement'),
624
- )) {
625
- ret.push(...this.getAlterColumnAutoincrement(tableName, column, schemaName));
626
- }
627
- return ret;
628
- }
629
- getAlterColumnAutoincrement(tableName, column, schemaName) {
630
- const ret = [];
631
- /* v8 ignore next */
632
- const name =
633
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
634
- if (column.autoincrement) {
635
- const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
636
- ret.push(`create sequence if not exists ${this.quote(seqName)}`);
637
- ret.push(`select setval('${seqName}', (select max(${this.quote(column.name)}) from ${this.quote(name)}))`);
638
- ret.push(
639
- `alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`,
640
- );
641
- }
642
- return ret;
643
- }
644
- getChangeColumnCommentSQL(tableName, to, schemaName) {
645
- const name = this.quote(
646
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName,
647
- );
648
- const value = to.comment ? this.platform.quoteValue(to.comment) : 'null';
649
- return `comment on column ${name}.${this.quote(to.name)} is ${value}`;
650
- }
651
- alterTableComment(table, comment) {
652
- return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
653
- }
654
- normalizeDefaultValue(defaultValue, length) {
655
- if (!defaultValue || typeof defaultValue !== 'string') {
656
- return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
657
- }
658
- const match = /^'(.*)'::(.*)$/.exec(defaultValue);
659
- if (match) {
660
- if (match[2] === 'integer') {
661
- return +match[1];
662
- }
663
- return `'${match[1]}'`;
664
- }
665
- return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
666
- }
667
- appendComments(table) {
668
- const sql = [];
669
- if (table.comment) {
670
- const comment = this.platform.quoteValue(this.processComment(table.comment));
671
- sql.push(`comment on table ${table.getQuotedName()} is ${comment}`);
672
- }
673
- for (const column of table.getColumns()) {
674
- if (column.comment) {
675
- const comment = this.platform.quoteValue(this.processComment(column.comment));
676
- sql.push(`comment on column ${table.getQuotedName()}.${this.quote(column.name)} is ${comment}`);
677
- }
678
- }
679
- return sql;
680
- }
681
- getDatabaseExistsSQL(name) {
682
- return `select 1 from pg_database where datname = '${name}'`;
683
- }
684
- getDatabaseNotExistsError(dbName) {
685
- return `database ${this.quote(dbName)} does not exist`;
686
- }
687
- getManagementDbName() {
688
- return this.platform.getConfig().get('schemaGenerator', {}).managementDbName ?? 'postgres';
689
- }
690
- disableForeignKeysSQL() {
691
- return `set session_replication_role = 'replica';`;
692
- }
693
- enableForeignKeysSQL() {
694
- return `set session_replication_role = 'origin';`;
695
- }
696
- getRenameIndexSQL(tableName, index, oldIndexName) {
697
- oldIndexName = this.quote(oldIndexName);
698
- const keyName = this.quote(index.keyName);
699
- return [`alter index ${oldIndexName} rename to ${keyName}`];
700
- }
701
- dropIndex(table, index, oldIndexName = index.keyName) {
702
- if (index.primary || (index.unique && index.constraint)) {
703
- return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
704
- }
705
- return `drop index ${this.quote(oldIndexName)}`;
706
- }
707
- /**
708
- * Build the column list for a PostgreSQL index.
709
- */
710
- getIndexColumns(index) {
711
- if (index.columns?.length) {
712
- return index.columns
713
- .map(col => {
714
- let colDef = this.quote(col.name);
715
- // PostgreSQL supports collation with double quotes
716
- if (col.collation) {
717
- colDef += ` collate ${this.quote(col.collation)}`;
718
- }
719
- // PostgreSQL supports sort order
720
- if (col.sort) {
721
- colDef += ` ${col.sort}`;
722
- }
723
- // PostgreSQL supports NULLS FIRST/LAST
724
- if (col.nulls) {
725
- colDef += ` nulls ${col.nulls}`;
726
- }
727
- return colDef;
728
- })
729
- .join(', ');
730
- }
731
- return index.columnNames.map(c => this.quote(c)).join(', ');
732
- }
733
- /**
734
- * PostgreSQL-specific index options like fill factor.
735
- */
736
- getCreateIndexSuffix(index) {
737
- const withOptions = [];
738
- if (index.fillFactor != null) {
739
- withOptions.push(`fillfactor = ${index.fillFactor}`);
740
- }
741
- if (withOptions.length > 0) {
742
- return ` with (${withOptions.join(', ')})`;
743
- }
744
- return super.getCreateIndexSuffix(index);
745
- }
746
- getIndexesSQL(tables) {
747
- return `select indrelid::regclass as table_name, ns.nspname as schema_name, relname as constraint_name, idx.indisunique as unique, idx.indisprimary as primary, contype, condeferrable, condeferred,
550
+ const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
551
+ const quotedName = this.quote(name);
552
+ // detect that the column was an enum before and remove the check constraint in such case here
553
+ const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
554
+ for (const col of changedEnums) {
555
+ if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
556
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
557
+ }
558
+ if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
559
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
560
+ }
561
+ }
562
+ // changing uuid column type requires to cast it to text first
563
+ const uuids = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid');
564
+ for (const col of uuids) {
565
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" type text using ("${col.column.name}"::text)`);
566
+ }
567
+ for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
568
+ if (!column.autoincrement && column.default == null) {
569
+ ret.push(`alter table ${quotedName} alter column ${this.quote(column.name)} drop default`);
570
+ }
571
+ }
572
+ return ret;
573
+ }
574
+ castColumn(name, type) {
575
+ if (type === 'uuid') {
576
+ type = 'text::uuid';
577
+ }
578
+ return ` using (${this.quote(name)}::${type})`;
579
+ }
580
+ dropForeignKey(tableName, constraintName) {
581
+ return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
582
+ }
583
+ getPostAlterTable(tableDiff, safe) {
584
+ const ret = [];
585
+ const parts = tableDiff.name.split('.');
586
+ const tableName = parts.pop();
587
+ const schemaName = parts.pop();
588
+ /* v8 ignore next */
589
+ const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
590
+ const quotedName = this.quote(name);
591
+ // detect that the column was an enum before and remove the check constraint in such a case here
592
+ const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
593
+ for (const col of changedEnums) {
594
+ if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
595
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
596
+ }
597
+ if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.column.default) {
598
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
599
+ }
600
+ }
601
+ for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
602
+ ret.push(...this.getAlterColumnAutoincrement(tableName, column, schemaName));
603
+ }
604
+ return ret;
605
+ }
606
+ getAlterColumnAutoincrement(tableName, column, schemaName) {
607
+ const ret = [];
608
+ /* v8 ignore next */
609
+ const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
610
+ if (column.autoincrement) {
611
+ const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
612
+ ret.push(`create sequence if not exists ${this.quote(seqName)}`);
613
+ ret.push(`select setval('${seqName}', (select max(${this.quote(column.name)}) from ${this.quote(name)}))`);
614
+ ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`);
615
+ }
616
+ return ret;
617
+ }
618
+ getChangeColumnCommentSQL(tableName, to, schemaName) {
619
+ const name = this.quote((schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName);
620
+ const value = to.comment ? this.platform.quoteValue(to.comment) : 'null';
621
+ return `comment on column ${name}.${this.quote(to.name)} is ${value}`;
622
+ }
623
+ alterTableComment(table, comment) {
624
+ return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
625
+ }
626
+ normalizeDefaultValue(defaultValue, length) {
627
+ if (!defaultValue || typeof defaultValue !== 'string') {
628
+ return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
629
+ }
630
+ const match = /^'(.*)'::(.*)$/.exec(defaultValue);
631
+ if (match) {
632
+ if (match[2] === 'integer') {
633
+ return +match[1];
634
+ }
635
+ return `'${match[1]}'`;
636
+ }
637
+ return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
638
+ }
639
+ appendComments(table) {
640
+ const sql = [];
641
+ if (table.comment) {
642
+ const comment = this.platform.quoteValue(this.processComment(table.comment));
643
+ sql.push(`comment on table ${table.getQuotedName()} is ${comment}`);
644
+ }
645
+ for (const column of table.getColumns()) {
646
+ if (column.comment) {
647
+ const comment = this.platform.quoteValue(this.processComment(column.comment));
648
+ sql.push(`comment on column ${table.getQuotedName()}.${this.quote(column.name)} is ${comment}`);
649
+ }
650
+ }
651
+ return sql;
652
+ }
653
+ getDatabaseExistsSQL(name) {
654
+ return `select 1 from pg_database where datname = '${name}'`;
655
+ }
656
+ getDatabaseNotExistsError(dbName) {
657
+ return `database ${this.quote(dbName)} does not exist`;
658
+ }
659
+ getManagementDbName() {
660
+ return this.platform.getConfig().get('schemaGenerator', {}).managementDbName ?? 'postgres';
661
+ }
662
+ disableForeignKeysSQL() {
663
+ return `set session_replication_role = 'replica';`;
664
+ }
665
+ enableForeignKeysSQL() {
666
+ return `set session_replication_role = 'origin';`;
667
+ }
668
+ getRenameIndexSQL(tableName, index, oldIndexName) {
669
+ oldIndexName = this.quote(oldIndexName);
670
+ const keyName = this.quote(index.keyName);
671
+ return [`alter index ${oldIndexName} rename to ${keyName}`];
672
+ }
673
+ dropIndex(table, index, oldIndexName = index.keyName) {
674
+ if (index.primary || (index.unique && index.constraint)) {
675
+ return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
676
+ }
677
+ return `drop index ${this.quote(oldIndexName)}`;
678
+ }
679
+ /**
680
+ * Build the column list for a PostgreSQL index.
681
+ */
682
+ getIndexColumns(index) {
683
+ if (index.columns?.length) {
684
+ return index.columns
685
+ .map(col => {
686
+ let colDef = this.quote(col.name);
687
+ // PostgreSQL supports collation with double quotes
688
+ if (col.collation) {
689
+ colDef += ` collate ${this.quote(col.collation)}`;
690
+ }
691
+ // PostgreSQL supports sort order
692
+ if (col.sort) {
693
+ colDef += ` ${col.sort}`;
694
+ }
695
+ // PostgreSQL supports NULLS FIRST/LAST
696
+ if (col.nulls) {
697
+ colDef += ` nulls ${col.nulls}`;
698
+ }
699
+ return colDef;
700
+ })
701
+ .join(', ');
702
+ }
703
+ return index.columnNames.map(c => this.quote(c)).join(', ');
704
+ }
705
+ /**
706
+ * PostgreSQL-specific index options like fill factor.
707
+ */
708
+ getCreateIndexSuffix(index) {
709
+ const withOptions = [];
710
+ if (index.fillFactor != null) {
711
+ withOptions.push(`fillfactor = ${index.fillFactor}`);
712
+ }
713
+ if (withOptions.length > 0) {
714
+ return ` with (${withOptions.join(', ')})`;
715
+ }
716
+ return super.getCreateIndexSuffix(index);
717
+ }
718
+ getIndexesSQL(tables) {
719
+ return `select indrelid::regclass as table_name, ns.nspname as schema_name, relname as constraint_name, idx.indisunique as unique, idx.indisprimary as primary, contype, condeferrable, condeferred,
748
720
  array(
749
721
  select pg_get_indexdef(idx.indexrelid, k + 1, true)
750
722
  from generate_subscripts(idx.indkey, 1) as k
@@ -762,37 +734,37 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
762
734
  left join pg_constraint as c on c.conname = i.relname
763
735
  where indrelid in (${tables.map(t => `${this.platform.quoteValue(`${this.quote(t.schema_name)}.${this.quote(t.table_name)}`)}::regclass`).join(', ')})
764
736
  order by relname`;
765
- }
766
- getChecksSQL(tablesBySchemas) {
767
- return `select ccu.table_name as table_name, ccu.table_schema as schema_name, pgc.conname as name, conrelid::regclass as table_from, ccu.column_name as column_name, pg_get_constraintdef(pgc.oid) as expression
737
+ }
738
+ getChecksSQL(tablesBySchemas) {
739
+ return `select ccu.table_name as table_name, ccu.table_schema as schema_name, pgc.conname as name, conrelid::regclass as table_from, ccu.column_name as column_name, pg_get_constraintdef(pgc.oid) as expression
768
740
  from pg_constraint pgc
769
741
  join pg_namespace nsp on nsp.oid = pgc.connamespace
770
742
  join pg_class cls on pgc.conrelid = cls.oid
771
743
  join information_schema.constraint_column_usage ccu on pgc.conname = ccu.constraint_name and nsp.nspname = ccu.constraint_schema and cls.relname = ccu.table_name
772
744
  where contype = 'c' and (${[...tablesBySchemas.entries()].map(([schema, tables]) => `ccu.table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and ccu.table_schema = ${this.platform.quoteValue(schema)}`).join(' or ')})
773
745
  order by pgc.conname`;
774
- }
775
- inferLengthFromColumnType(type) {
776
- const match = /^(\w+(?:\s+\w+)*)\s*(?:\(\s*(\d+)\s*\)|$)/.exec(type);
777
- if (!match) {
778
- return;
779
- }
780
- if (!match[2]) {
781
- switch (match[1]) {
782
- case 'character varying':
783
- case 'varchar':
784
- case 'bpchar':
785
- case 'char':
786
- case 'character':
787
- return -1;
788
- case 'interval':
789
- case 'time':
790
- case 'timestamp':
791
- case 'timestamptz':
792
- return this.platform.getDefaultDateTimeLength();
793
- }
794
- return;
795
- }
796
- return +match[2];
797
- }
746
+ }
747
+ inferLengthFromColumnType(type) {
748
+ const match = /^(\w+(?:\s+\w+)*)\s*(?:\(\s*(\d+)\s*\)|$)/.exec(type);
749
+ if (!match) {
750
+ return;
751
+ }
752
+ if (!match[2]) {
753
+ switch (match[1]) {
754
+ case 'character varying':
755
+ case 'varchar':
756
+ case 'bpchar':
757
+ case 'char':
758
+ case 'character':
759
+ return -1;
760
+ case 'interval':
761
+ case 'time':
762
+ case 'timestamp':
763
+ case 'timestamptz':
764
+ return this.platform.getDefaultDateTimeLength();
765
+ }
766
+ return;
767
+ }
768
+ return +match[2];
769
+ }
798
770
  }