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

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 +95 -47
  2. package/AbstractSqlConnection.js +240 -232
  3. package/AbstractSqlDriver.d.ts +412 -155
  4. package/AbstractSqlDriver.js +2062 -1937
  5. package/AbstractSqlPlatform.d.ts +84 -73
  6. package/AbstractSqlPlatform.js +163 -158
  7. package/PivotCollectionPersister.d.ts +33 -15
  8. package/PivotCollectionPersister.js +158 -160
  9. package/README.md +128 -294
  10. package/SqlEntityManager.d.ts +68 -20
  11. package/SqlEntityManager.js +54 -37
  12. package/SqlEntityRepository.d.ts +15 -14
  13. package/SqlEntityRepository.js +24 -23
  14. package/dialects/mssql/MsSqlNativeQueryBuilder.d.ts +12 -12
  15. package/dialects/mssql/MsSqlNativeQueryBuilder.js +192 -194
  16. package/dialects/mysql/BaseMySqlPlatform.d.ts +64 -45
  17. package/dialects/mysql/BaseMySqlPlatform.js +134 -131
  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 +39 -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 +232 -236
  28. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +108 -105
  29. package/dialects/postgresql/BasePostgreSqlPlatform.js +351 -350
  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 +102 -82
  37. package/dialects/postgresql/PostgreSqlSchemaHelper.js +711 -683
  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 +63 -72
  49. package/dialects/sqlite/SqlitePlatform.js +139 -139
  50. package/dialects/sqlite/SqliteSchemaHelper.d.ts +70 -60
  51. package/dialects/sqlite/SqliteSchemaHelper.js +533 -520
  52. package/package.json +4 -4
  53. package/plugin/index.d.ts +44 -35
  54. package/plugin/index.js +44 -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 +133 -123
  61. package/query/CriteriaNodeFactory.d.ts +49 -6
  62. package/query/CriteriaNodeFactory.js +97 -94
  63. package/query/NativeQueryBuilder.d.ts +120 -117
  64. package/query/NativeQueryBuilder.js +484 -480
  65. package/query/ObjectCriteriaNode.d.ts +12 -12
  66. package/query/ObjectCriteriaNode.js +298 -282
  67. package/query/QueryBuilder.d.ts +1546 -904
  68. package/query/QueryBuilder.js +2270 -2145
  69. package/query/QueryBuilderHelper.d.ts +153 -72
  70. package/query/QueryBuilderHelper.js +1079 -1028
  71. package/query/ScalarCriteriaNode.d.ts +3 -3
  72. package/query/ScalarCriteriaNode.js +53 -46
  73. package/query/enums.d.ts +16 -14
  74. package/query/enums.js +16 -14
  75. package/query/raw.d.ts +16 -6
  76. package/query/raw.js +10 -10
  77. package/schema/DatabaseSchema.d.ts +73 -50
  78. package/schema/DatabaseSchema.js +331 -307
  79. package/schema/DatabaseTable.d.ts +96 -73
  80. package/schema/DatabaseTable.js +1012 -927
  81. package/schema/SchemaComparator.d.ts +58 -54
  82. package/schema/SchemaComparator.js +745 -719
  83. package/schema/SchemaHelper.d.ts +110 -80
  84. package/schema/SchemaHelper.js +676 -645
  85. package/schema/SqlSchemaGenerator.d.ts +79 -58
  86. package/schema/SqlSchemaGenerator.js +536 -501
  87. package/typings.d.ts +380 -266
@@ -1,250 +1,256 @@
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 (`select table_name, table_schema as schema_name, ` +
26
- `(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 (
26
+ `select table_name, table_schema as schema_name, ` +
27
+ `(select pg_catalog.obj_description(c.oid) from pg_catalog.pg_class c
27
28
  where c.oid = (select ('"' || table_schema || '"."' || table_name || '"')::regclass::oid) and c.relname = table_name) as table_comment ` +
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,
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,
248
254
  column_default,
249
255
  is_nullable,
250
256
  udt_name,
@@ -263,89 +269,93 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
263
269
  join pg_attribute pga on pgc.oid = pga.attrelid and cols.column_name = pga.attname
264
270
  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 ')})
265
271
  order by ordinal_position`;
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
- if (nativeEnums?.[column.type]) {
315
- column.mappedType = Type.getType(EnumType);
316
- column.nativeEnumName = column.type;
317
- column.enumItems = nativeEnums[column.type]?.items;
318
- }
319
- ret[key].push(column);
320
- }
321
- return ret;
322
- }
323
- async getAllChecks(connection, tablesBySchemas) {
324
- const sql = this.getChecksSQL(tablesBySchemas);
325
- const allChecks = await connection.execute(sql);
326
- const ret = {};
327
- const seen = new Set();
328
- for (const check of allChecks) {
329
- const key = this.getTableKey(check);
330
- const dedupeKey = `${key}:${check.name}`;
331
- if (seen.has(dedupeKey)) {
332
- continue;
333
- }
334
- seen.add(dedupeKey);
335
- ret[key] ??= [];
336
- const m = /^check \(\((.*)\)\)$/is.exec(check.expression);
337
- const def = m?.[1].replace(/\((.*?)\)::\w+/g, '$1');
338
- ret[key].push({
339
- name: check.name,
340
- columnName: check.column_name,
341
- definition: check.expression,
342
- expression: def,
343
- });
344
- }
345
- return ret;
346
- }
347
- async getAllForeignKeys(connection, tablesBySchemas) {
348
- const sql = `select nsp1.nspname schema_name, cls1.relname table_name, nsp2.nspname referenced_schema_name,
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
+ if (nativeEnums?.[column.type]) {
325
+ column.mappedType = Type.getType(EnumType);
326
+ column.nativeEnumName = column.type;
327
+ column.enumItems = nativeEnums[column.type]?.items;
328
+ }
329
+ ret[key].push(column);
330
+ }
331
+ return ret;
332
+ }
333
+ async getAllChecks(connection, tablesBySchemas) {
334
+ const sql = this.getChecksSQL(tablesBySchemas);
335
+ const allChecks = await connection.execute(sql);
336
+ const ret = {};
337
+ const seen = new Set();
338
+ for (const check of allChecks) {
339
+ const key = this.getTableKey(check);
340
+ const dedupeKey = `${key}:${check.name}`;
341
+ if (seen.has(dedupeKey)) {
342
+ continue;
343
+ }
344
+ seen.add(dedupeKey);
345
+ ret[key] ??= [];
346
+ const m = /^check \(\((.*)\)\)$/is.exec(check.expression);
347
+ const def = m?.[1].replace(/\((.*?)\)::\w+/g, '$1');
348
+ ret[key].push({
349
+ name: check.name,
350
+ columnName: check.column_name,
351
+ definition: check.expression,
352
+ expression: def,
353
+ });
354
+ }
355
+ return ret;
356
+ }
357
+ async getAllForeignKeys(connection, tablesBySchemas) {
358
+ const sql = `select nsp1.nspname schema_name, cls1.relname table_name, nsp2.nspname referenced_schema_name,
349
359
  cls2.relname referenced_table_name, a.attname column_name, af.attname referenced_column_name, conname constraint_name,
350
360
  confupdtype update_rule, confdeltype delete_rule, array_position(con.conkey,a.attnum) as ord, condeferrable, condeferred,
351
361
  pg_get_constraintdef(con.oid) as constraint_def
@@ -359,342 +369,360 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
359
369
  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 ')})
360
370
  and confrelid > 0
361
371
  order by nsp1.nspname, cls1.relname, constraint_name, ord`;
362
- const allFks = await connection.execute(sql);
363
- const ret = {};
364
- function mapReferentialIntegrity(value, def) {
365
- const match = ['n', 'd'].includes(value) && /ON DELETE (SET (NULL|DEFAULT) \(.*?\))/.exec(def);
366
- if (match) {
367
- return match[1];
368
- }
369
- /* v8 ignore next */
370
- switch (value) {
371
- case 'r':
372
- return 'RESTRICT';
373
- case 'c':
374
- return 'CASCADE';
375
- case 'n':
376
- return 'SET NULL';
377
- case 'd':
378
- return 'SET DEFAULT';
379
- case 'a':
380
- default:
381
- return 'NO ACTION';
382
- }
383
- }
384
- for (const fk of allFks) {
385
- fk.update_rule = mapReferentialIntegrity(fk.update_rule, fk.constraint_def);
386
- fk.delete_rule = mapReferentialIntegrity(fk.delete_rule, fk.constraint_def);
387
- if (fk.condeferrable) {
388
- fk.defer_mode = fk.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
389
- }
390
- const key = this.getTableKey(fk);
391
- ret[key] ??= [];
392
- ret[key].push(fk);
393
- }
394
- Object.keys(ret).forEach(key => {
395
- const [schemaName, tableName] = key.split('.');
396
- ret[key] = this.mapForeignKeys(ret[key], tableName, schemaName);
397
- });
398
- return ret;
399
- }
400
- async getNativeEnumDefinitions(connection, schemas) {
401
- const uniqueSchemas = Utils.unique(schemas);
402
- 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
372
+ const allFks = await connection.execute(sql);
373
+ const ret = {};
374
+ function mapReferentialIntegrity(value, def) {
375
+ const match = ['n', 'd'].includes(value) && /ON DELETE (SET (NULL|DEFAULT) \(.*?\))/.exec(def);
376
+ if (match) {
377
+ return match[1];
378
+ }
379
+ /* v8 ignore next */
380
+ switch (value) {
381
+ case 'r':
382
+ return 'RESTRICT';
383
+ case 'c':
384
+ return 'CASCADE';
385
+ case 'n':
386
+ return 'SET NULL';
387
+ case 'd':
388
+ return 'SET DEFAULT';
389
+ case 'a':
390
+ default:
391
+ return 'NO ACTION';
392
+ }
393
+ }
394
+ for (const fk of allFks) {
395
+ fk.update_rule = mapReferentialIntegrity(fk.update_rule, fk.constraint_def);
396
+ fk.delete_rule = mapReferentialIntegrity(fk.delete_rule, fk.constraint_def);
397
+ if (fk.condeferrable) {
398
+ fk.defer_mode = fk.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
399
+ }
400
+ const key = this.getTableKey(fk);
401
+ ret[key] ??= [];
402
+ ret[key].push(fk);
403
+ }
404
+ Object.keys(ret).forEach(key => {
405
+ const [schemaName, tableName] = key.split('.');
406
+ ret[key] = this.mapForeignKeys(ret[key], tableName, schemaName);
407
+ });
408
+ return ret;
409
+ }
410
+ async getNativeEnumDefinitions(connection, schemas) {
411
+ const uniqueSchemas = Utils.unique(schemas);
412
+ const res = await connection.execute(
413
+ `select t.typname as enum_name, n.nspname as schema_name, array_agg(e.enumlabel order by e.enumsortorder) as enum_value
403
414
  from pg_type t
404
415
  join pg_enum e on t.oid = e.enumtypid
405
416
  join pg_catalog.pg_namespace n on n.oid = t.typnamespace
406
417
  where n.nspname in (${Array(uniqueSchemas.length).fill('?').join(', ')})
407
- group by t.typname, n.nspname`, uniqueSchemas);
408
- return res.reduce((o, row) => {
409
- let name = row.enum_name;
410
- if (row.schema_name && row.schema_name !== this.platform.getDefaultSchemaName()) {
411
- name = row.schema_name + '.' + name;
412
- }
413
- let items = row.enum_value;
414
- if (!Array.isArray(items)) {
415
- items = this.platform.unmarshallArray(row.enum_value);
416
- }
417
- o[name] = {
418
- name: row.enum_name,
419
- schema: row.schema_name,
420
- items,
421
- };
422
- return o;
423
- }, {});
424
- }
425
- getCreateNativeEnumSQL(name, values, schema) {
426
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
427
- name = schema + '.' + name;
428
- }
429
- return `create type ${this.quote(name)} as enum (${values.map(value => this.platform.quoteValue(value)).join(', ')})`;
430
- }
431
- getDropNativeEnumSQL(name, schema) {
432
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
433
- name = schema + '.' + name;
434
- }
435
- return `drop type ${this.quote(name)}`;
436
- }
437
- getAlterNativeEnumSQL(name, schema, value, items, oldItems) {
438
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
439
- name = schema + '.' + name;
440
- }
441
- let suffix = '';
442
- if (items && value && oldItems) {
443
- const position = items.indexOf(value);
444
- if (position > 0) {
445
- suffix = ` after ${this.platform.quoteValue(items[position - 1])}`;
446
- }
447
- else if (items.length > 1 && oldItems.length > 0) {
448
- suffix = ` before ${this.platform.quoteValue(oldItems[0])}`;
449
- }
450
- }
451
- return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
452
- }
453
- getEnumDefinitions(checks) {
454
- return checks.reduce((o, item) => {
455
- // check constraints are defined as one of:
456
- // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
457
- // `CHECK (("columnName" = ANY (ARRAY['local'::text, 'global'::text])))`
458
- // `CHECK (((enum_test)::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
459
- // `CHECK ((("enumTest")::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
460
- // `CHECK ((type = 'a'::text))`
461
- const m1 = item.definition?.match(/check \(\(\("?(\w+)"?\)::/i) || item.definition?.match(/check \(\("?(\w+)"? = /i);
462
- const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = (.*)\)/i);
463
- if (item.columnName && m1 && m2) {
464
- const m3 = m2[1].match(/('[^']*'::text)/g);
465
- let items;
466
- /* v8 ignore next */
467
- if (m3) {
468
- items = m3.map((item) => /^\(?'(.*)'/.exec(item.trim())?.[1]);
469
- }
470
- else {
471
- items = m2[1].split(',').map((item) => /^\(?'(.*)'/.exec(item.trim())?.[1]);
472
- }
473
- items = items.filter(item => item !== undefined);
474
- if (items.length > 0) {
475
- o[item.columnName] = items;
476
- item.expression = `${this.quote(item.columnName)} in ('${items.join("', '")}')`;
477
- item.definition = `check (${item.expression})`;
478
- }
479
- }
480
- return o;
481
- }, {});
482
- }
483
- createTableColumn(column, table) {
484
- const pk = table.getPrimaryKey();
485
- const compositePK = pk?.composite;
486
- const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
487
- const col = [this.quote(column.name)];
488
- if (column.autoincrement && !column.generated && !compositePK) {
489
- col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
490
- }
491
- else {
492
- let columnType = column.type;
493
- if (column.nativeEnumName) {
494
- const parts = column.type.split('.');
495
- if (parts.length === 2 && parts[0] === '*') {
496
- columnType = `${table.schema}.${parts[1]}`;
497
- }
498
- if (columnType.endsWith('[]')) {
499
- columnType = this.quote(columnType.substring(0, columnType.length - 2)) + '[]';
500
- }
501
- else {
502
- columnType = this.quote(columnType);
503
- }
504
- }
505
- if (column.generated === 'by default as identity') {
506
- columnType += ` generated ${column.generated}`;
507
- }
508
- else if (column.generated) {
509
- columnType += ` generated always as ${column.generated}`;
510
- }
511
- col.push(columnType);
512
- Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
513
- Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
514
- }
515
- if (column.autoincrement && !compositePK) {
516
- Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
517
- }
518
- const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
519
- Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
520
- return col.join(' ');
521
- }
522
- getPreAlterTable(tableDiff, safe) {
523
- const ret = [];
524
- const parts = tableDiff.name.split('.');
525
- const tableName = parts.pop();
526
- const schemaName = parts.pop();
418
+ group by t.typname, n.nspname`,
419
+ uniqueSchemas,
420
+ );
421
+ return res.reduce((o, row) => {
422
+ let name = row.enum_name;
423
+ if (row.schema_name && row.schema_name !== this.platform.getDefaultSchemaName()) {
424
+ name = row.schema_name + '.' + name;
425
+ }
426
+ let items = row.enum_value;
427
+ if (!Array.isArray(items)) {
428
+ items = this.platform.unmarshallArray(row.enum_value);
429
+ }
430
+ o[name] = {
431
+ name: row.enum_name,
432
+ schema: row.schema_name,
433
+ items,
434
+ };
435
+ return o;
436
+ }, {});
437
+ }
438
+ getCreateNativeEnumSQL(name, values, schema) {
439
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
440
+ name = schema + '.' + name;
441
+ }
442
+ return `create type ${this.quote(name)} as enum (${values.map(value => this.platform.quoteValue(value)).join(', ')})`;
443
+ }
444
+ getDropNativeEnumSQL(name, schema) {
445
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
446
+ name = schema + '.' + name;
447
+ }
448
+ return `drop type ${this.quote(name)}`;
449
+ }
450
+ getAlterNativeEnumSQL(name, schema, value, items, oldItems) {
451
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
452
+ name = schema + '.' + name;
453
+ }
454
+ let suffix = '';
455
+ if (items && value && oldItems) {
456
+ const position = items.indexOf(value);
457
+ if (position > 0) {
458
+ suffix = ` after ${this.platform.quoteValue(items[position - 1])}`;
459
+ } else if (items.length > 1 && oldItems.length > 0) {
460
+ suffix = ` before ${this.platform.quoteValue(oldItems[0])}`;
461
+ }
462
+ }
463
+ return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
464
+ }
465
+ getEnumDefinitions(checks) {
466
+ return checks.reduce((o, item) => {
467
+ // check constraints are defined as one of:
468
+ // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
469
+ // `CHECK (("columnName" = ANY (ARRAY['local'::text, 'global'::text])))`
470
+ // `CHECK (((enum_test)::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
471
+ // `CHECK ((("enumTest")::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
472
+ // `CHECK ((type = 'a'::text))`
473
+ const m1 =
474
+ item.definition?.match(/check \(\(\("?(\w+)"?\)::/i) || item.definition?.match(/check \(\("?(\w+)"? = /i);
475
+ const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = (.*)\)/i);
476
+ if (item.columnName && m1 && m2) {
477
+ const m3 = m2[1].match(/('[^']*'::text)/g);
478
+ let items;
527
479
  /* v8 ignore next */
528
- const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
529
- const quotedName = this.quote(name);
530
- // detect that the column was an enum before and remove the check constraint in such case here
531
- const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
532
- for (const col of changedEnums) {
533
- if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
534
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
535
- }
536
- if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
537
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
538
- }
539
- }
540
- // changing uuid column type requires to cast it to text first
541
- const uuids = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid');
542
- for (const col of uuids) {
543
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" type text using ("${col.column.name}"::text)`);
544
- }
545
- for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
546
- if (!column.autoincrement && column.default == null) {
547
- ret.push(`alter table ${quotedName} alter column ${this.quote(column.name)} drop default`);
548
- }
549
- }
550
- return ret;
551
- }
552
- castColumn(name, type) {
553
- if (type === 'uuid') {
554
- type = 'text::uuid';
555
- }
556
- return ` using (${this.quote(name)}::${type})`;
557
- }
558
- dropForeignKey(tableName, constraintName) {
559
- return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
560
- }
561
- getPostAlterTable(tableDiff, safe) {
562
- const ret = [];
563
- const parts = tableDiff.name.split('.');
564
- const tableName = parts.pop();
565
- const schemaName = parts.pop();
566
- /* v8 ignore next */
567
- const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
568
- const quotedName = this.quote(name);
569
- // detect that the column was an enum before and remove the check constraint in such a case here
570
- const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
571
- for (const col of changedEnums) {
572
- if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
573
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
574
- }
575
- if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.column.default) {
576
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
577
- }
578
- }
579
- for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
580
- ret.push(...this.getAlterColumnAutoincrement(tableName, column, schemaName));
581
- }
582
- return ret;
583
- }
584
- getAlterColumnAutoincrement(tableName, column, schemaName) {
585
- const ret = [];
586
- /* v8 ignore next */
587
- const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
588
- if (column.autoincrement) {
589
- const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
590
- ret.push(`create sequence if not exists ${this.quote(seqName)}`);
591
- ret.push(`select setval('${seqName}', (select max(${this.quote(column.name)}) from ${this.quote(name)}))`);
592
- ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`);
593
- }
594
- return ret;
595
- }
596
- getChangeColumnCommentSQL(tableName, to, schemaName) {
597
- const name = this.quote((schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName);
598
- const value = to.comment ? this.platform.quoteValue(to.comment) : 'null';
599
- return `comment on column ${name}.${this.quote(to.name)} is ${value}`;
600
- }
601
- alterTableComment(table, comment) {
602
- return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
603
- }
604
- normalizeDefaultValue(defaultValue, length) {
605
- if (!defaultValue || typeof defaultValue !== 'string') {
606
- return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
607
- }
608
- const match = /^'(.*)'::(.*)$/.exec(defaultValue);
609
- if (match) {
610
- if (match[2] === 'integer') {
611
- return +match[1];
612
- }
613
- return `'${match[1]}'`;
614
- }
615
- return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
616
- }
617
- appendComments(table) {
618
- const sql = [];
619
- if (table.comment) {
620
- const comment = this.platform.quoteValue(this.processComment(table.comment));
621
- sql.push(`comment on table ${table.getQuotedName()} is ${comment}`);
622
- }
623
- for (const column of table.getColumns()) {
624
- if (column.comment) {
625
- const comment = this.platform.quoteValue(this.processComment(column.comment));
626
- sql.push(`comment on column ${table.getQuotedName()}.${this.quote(column.name)} is ${comment}`);
627
- }
628
- }
629
- return sql;
630
- }
631
- getDatabaseExistsSQL(name) {
632
- return `select 1 from pg_database where datname = '${name}'`;
633
- }
634
- getDatabaseNotExistsError(dbName) {
635
- return `database ${this.quote(dbName)} does not exist`;
636
- }
637
- getManagementDbName() {
638
- return this.platform.getConfig().get('schemaGenerator', {}).managementDbName ?? 'postgres';
639
- }
640
- disableForeignKeysSQL() {
641
- return `set session_replication_role = 'replica';`;
642
- }
643
- enableForeignKeysSQL() {
644
- return `set session_replication_role = 'origin';`;
645
- }
646
- getRenameIndexSQL(tableName, index, oldIndexName) {
647
- oldIndexName = this.quote(oldIndexName);
648
- const keyName = this.quote(index.keyName);
649
- return [`alter index ${oldIndexName} rename to ${keyName}`];
650
- }
651
- dropIndex(table, index, oldIndexName = index.keyName) {
652
- if (index.primary || (index.unique && index.constraint)) {
653
- return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
654
- }
655
- return `drop index ${this.quote(oldIndexName)}`;
656
- }
657
- /**
658
- * Build the column list for a PostgreSQL index.
659
- */
660
- getIndexColumns(index) {
661
- if (index.columns?.length) {
662
- return index.columns
663
- .map(col => {
664
- let colDef = this.quote(col.name);
665
- // PostgreSQL supports collation with double quotes
666
- if (col.collation) {
667
- colDef += ` collate ${this.quote(col.collation)}`;
668
- }
669
- // PostgreSQL supports sort order
670
- if (col.sort) {
671
- colDef += ` ${col.sort}`;
672
- }
673
- // PostgreSQL supports NULLS FIRST/LAST
674
- if (col.nulls) {
675
- colDef += ` nulls ${col.nulls}`;
676
- }
677
- return colDef;
678
- })
679
- .join(', ');
680
- }
681
- return index.columnNames.map(c => this.quote(c)).join(', ');
682
- }
683
- /**
684
- * PostgreSQL-specific index options like fill factor.
685
- */
686
- getCreateIndexSuffix(index) {
687
- const withOptions = [];
688
- if (index.fillFactor != null) {
689
- withOptions.push(`fillfactor = ${index.fillFactor}`);
690
- }
691
- if (withOptions.length > 0) {
692
- return ` with (${withOptions.join(', ')})`;
693
- }
694
- return super.getCreateIndexSuffix(index);
695
- }
696
- getIndexesSQL(tables) {
697
- 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,
480
+ if (m3) {
481
+ items = m3.map(item => /^\(?'(.*)'/.exec(item.trim())?.[1]);
482
+ } else {
483
+ items = m2[1].split(',').map(item => /^\(?'(.*)'/.exec(item.trim())?.[1]);
484
+ }
485
+ items = items.filter(item => item !== undefined);
486
+ if (items.length > 0) {
487
+ o[item.columnName] = items;
488
+ item.expression = `${this.quote(item.columnName)} in ('${items.join("', '")}')`;
489
+ item.definition = `check (${item.expression})`;
490
+ }
491
+ }
492
+ return o;
493
+ }, {});
494
+ }
495
+ createTableColumn(column, table) {
496
+ const pk = table.getPrimaryKey();
497
+ const compositePK = pk?.composite;
498
+ const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
499
+ const col = [this.quote(column.name)];
500
+ if (column.autoincrement && !column.generated && !compositePK) {
501
+ col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
502
+ } else {
503
+ let columnType = column.type;
504
+ if (column.nativeEnumName) {
505
+ const parts = column.type.split('.');
506
+ if (parts.length === 2 && parts[0] === '*') {
507
+ columnType = `${table.schema}.${parts[1]}`;
508
+ }
509
+ if (columnType.endsWith('[]')) {
510
+ columnType = this.quote(columnType.substring(0, columnType.length - 2)) + '[]';
511
+ } else {
512
+ columnType = this.quote(columnType);
513
+ }
514
+ }
515
+ if (column.generated === 'by default as identity') {
516
+ columnType += ` generated ${column.generated}`;
517
+ } else if (column.generated) {
518
+ columnType += ` generated always as ${column.generated}`;
519
+ }
520
+ col.push(columnType);
521
+ Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
522
+ Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
523
+ }
524
+ if (column.autoincrement && !compositePK) {
525
+ Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
526
+ }
527
+ const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
528
+ Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
529
+ return col.join(' ');
530
+ }
531
+ getPreAlterTable(tableDiff, safe) {
532
+ const ret = [];
533
+ const parts = tableDiff.name.split('.');
534
+ const tableName = parts.pop();
535
+ const schemaName = parts.pop();
536
+ /* v8 ignore next */
537
+ const name =
538
+ (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
539
+ const quotedName = this.quote(name);
540
+ // detect that the column was an enum before and remove the check constraint in such case here
541
+ const changedEnums = Object.values(tableDiff.changedColumns).filter(
542
+ col => col.fromColumn.mappedType instanceof EnumType,
543
+ );
544
+ for (const col of changedEnums) {
545
+ if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
546
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
547
+ }
548
+ if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
549
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
550
+ }
551
+ }
552
+ // changing uuid column type requires to cast it to text first
553
+ const uuids = Object.values(tableDiff.changedColumns).filter(
554
+ col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid',
555
+ );
556
+ for (const col of uuids) {
557
+ ret.push(
558
+ `alter table ${quotedName} alter column "${col.column.name}" type text using ("${col.column.name}"::text)`,
559
+ );
560
+ }
561
+ for (const { column } of Object.values(tableDiff.changedColumns).filter(diff =>
562
+ diff.changedProperties.has('autoincrement'),
563
+ )) {
564
+ if (!column.autoincrement && column.default == null) {
565
+ ret.push(`alter table ${quotedName} alter column ${this.quote(column.name)} drop default`);
566
+ }
567
+ }
568
+ return ret;
569
+ }
570
+ castColumn(name, type) {
571
+ if (type === 'uuid') {
572
+ type = 'text::uuid';
573
+ }
574
+ return ` using (${this.quote(name)}::${type})`;
575
+ }
576
+ dropForeignKey(tableName, constraintName) {
577
+ return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
578
+ }
579
+ getPostAlterTable(tableDiff, safe) {
580
+ const ret = [];
581
+ const parts = tableDiff.name.split('.');
582
+ const tableName = parts.pop();
583
+ const schemaName = parts.pop();
584
+ /* v8 ignore next */
585
+ const name =
586
+ (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
587
+ const quotedName = this.quote(name);
588
+ // detect that the column was an enum before and remove the check constraint in such a case here
589
+ const changedEnums = Object.values(tableDiff.changedColumns).filter(
590
+ col => col.fromColumn.mappedType instanceof EnumType,
591
+ );
592
+ for (const col of changedEnums) {
593
+ if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
594
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
595
+ }
596
+ if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.column.default) {
597
+ ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
598
+ }
599
+ }
600
+ for (const { column } of Object.values(tableDiff.changedColumns).filter(diff =>
601
+ diff.changedProperties.has('autoincrement'),
602
+ )) {
603
+ ret.push(...this.getAlterColumnAutoincrement(tableName, column, schemaName));
604
+ }
605
+ return ret;
606
+ }
607
+ getAlterColumnAutoincrement(tableName, column, schemaName) {
608
+ const ret = [];
609
+ /* v8 ignore next */
610
+ const name =
611
+ (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
612
+ if (column.autoincrement) {
613
+ const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
614
+ ret.push(`create sequence if not exists ${this.quote(seqName)}`);
615
+ ret.push(`select setval('${seqName}', (select max(${this.quote(column.name)}) from ${this.quote(name)}))`);
616
+ ret.push(
617
+ `alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`,
618
+ );
619
+ }
620
+ return ret;
621
+ }
622
+ getChangeColumnCommentSQL(tableName, to, schemaName) {
623
+ const name = this.quote(
624
+ (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName,
625
+ );
626
+ const value = to.comment ? this.platform.quoteValue(to.comment) : 'null';
627
+ return `comment on column ${name}.${this.quote(to.name)} is ${value}`;
628
+ }
629
+ alterTableComment(table, comment) {
630
+ return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
631
+ }
632
+ normalizeDefaultValue(defaultValue, length) {
633
+ if (!defaultValue || typeof defaultValue !== 'string') {
634
+ return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
635
+ }
636
+ const match = /^'(.*)'::(.*)$/.exec(defaultValue);
637
+ if (match) {
638
+ if (match[2] === 'integer') {
639
+ return +match[1];
640
+ }
641
+ return `'${match[1]}'`;
642
+ }
643
+ return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
644
+ }
645
+ appendComments(table) {
646
+ const sql = [];
647
+ if (table.comment) {
648
+ const comment = this.platform.quoteValue(this.processComment(table.comment));
649
+ sql.push(`comment on table ${table.getQuotedName()} is ${comment}`);
650
+ }
651
+ for (const column of table.getColumns()) {
652
+ if (column.comment) {
653
+ const comment = this.platform.quoteValue(this.processComment(column.comment));
654
+ sql.push(`comment on column ${table.getQuotedName()}.${this.quote(column.name)} is ${comment}`);
655
+ }
656
+ }
657
+ return sql;
658
+ }
659
+ getDatabaseExistsSQL(name) {
660
+ return `select 1 from pg_database where datname = '${name}'`;
661
+ }
662
+ getDatabaseNotExistsError(dbName) {
663
+ return `database ${this.quote(dbName)} does not exist`;
664
+ }
665
+ getManagementDbName() {
666
+ return this.platform.getConfig().get('schemaGenerator', {}).managementDbName ?? 'postgres';
667
+ }
668
+ disableForeignKeysSQL() {
669
+ return `set session_replication_role = 'replica';`;
670
+ }
671
+ enableForeignKeysSQL() {
672
+ return `set session_replication_role = 'origin';`;
673
+ }
674
+ getRenameIndexSQL(tableName, index, oldIndexName) {
675
+ oldIndexName = this.quote(oldIndexName);
676
+ const keyName = this.quote(index.keyName);
677
+ return [`alter index ${oldIndexName} rename to ${keyName}`];
678
+ }
679
+ dropIndex(table, index, oldIndexName = index.keyName) {
680
+ if (index.primary || (index.unique && index.constraint)) {
681
+ return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
682
+ }
683
+ return `drop index ${this.quote(oldIndexName)}`;
684
+ }
685
+ /**
686
+ * Build the column list for a PostgreSQL index.
687
+ */
688
+ getIndexColumns(index) {
689
+ if (index.columns?.length) {
690
+ return index.columns
691
+ .map(col => {
692
+ let colDef = this.quote(col.name);
693
+ // PostgreSQL supports collation with double quotes
694
+ if (col.collation) {
695
+ colDef += ` collate ${this.quote(col.collation)}`;
696
+ }
697
+ // PostgreSQL supports sort order
698
+ if (col.sort) {
699
+ colDef += ` ${col.sort}`;
700
+ }
701
+ // PostgreSQL supports NULLS FIRST/LAST
702
+ if (col.nulls) {
703
+ colDef += ` nulls ${col.nulls}`;
704
+ }
705
+ return colDef;
706
+ })
707
+ .join(', ');
708
+ }
709
+ return index.columnNames.map(c => this.quote(c)).join(', ');
710
+ }
711
+ /**
712
+ * PostgreSQL-specific index options like fill factor.
713
+ */
714
+ getCreateIndexSuffix(index) {
715
+ const withOptions = [];
716
+ if (index.fillFactor != null) {
717
+ withOptions.push(`fillfactor = ${index.fillFactor}`);
718
+ }
719
+ if (withOptions.length > 0) {
720
+ return ` with (${withOptions.join(', ')})`;
721
+ }
722
+ return super.getCreateIndexSuffix(index);
723
+ }
724
+ getIndexesSQL(tables) {
725
+ 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,
698
726
  array(
699
727
  select pg_get_indexdef(idx.indexrelid, k + 1, true)
700
728
  from generate_subscripts(idx.indkey, 1) as k
@@ -712,37 +740,37 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
712
740
  left join pg_constraint as c on c.conname = i.relname
713
741
  where indrelid in (${tables.map(t => `${this.platform.quoteValue(`${this.quote(t.schema_name)}.${this.quote(t.table_name)}`)}::regclass`).join(', ')})
714
742
  order by relname`;
715
- }
716
- getChecksSQL(tablesBySchemas) {
717
- 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
743
+ }
744
+ getChecksSQL(tablesBySchemas) {
745
+ 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
718
746
  from pg_constraint pgc
719
747
  join pg_namespace nsp on nsp.oid = pgc.connamespace
720
748
  join pg_class cls on pgc.conrelid = cls.oid
721
749
  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
722
750
  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 ')})
723
751
  order by pgc.conname`;
724
- }
725
- inferLengthFromColumnType(type) {
726
- const match = /^(\w+(?:\s+\w+)*)\s*(?:\(\s*(\d+)\s*\)|$)/.exec(type);
727
- if (!match) {
728
- return;
729
- }
730
- if (!match[2]) {
731
- switch (match[1]) {
732
- case 'character varying':
733
- case 'varchar':
734
- case 'bpchar':
735
- case 'char':
736
- case 'character':
737
- return -1;
738
- case 'interval':
739
- case 'time':
740
- case 'timestamp':
741
- case 'timestamptz':
742
- return this.platform.getDefaultDateTimeLength();
743
- }
744
- return;
745
- }
746
- return +match[2];
747
- }
752
+ }
753
+ inferLengthFromColumnType(type) {
754
+ const match = /^(\w+(?:\s+\w+)*)\s*(?:\(\s*(\d+)\s*\)|$)/.exec(type);
755
+ if (!match) {
756
+ return;
757
+ }
758
+ if (!match[2]) {
759
+ switch (match[1]) {
760
+ case 'character varying':
761
+ case 'varchar':
762
+ case 'bpchar':
763
+ case 'char':
764
+ case 'character':
765
+ return -1;
766
+ case 'interval':
767
+ case 'time':
768
+ case 'timestamp':
769
+ case 'timestamptz':
770
+ return this.platform.getDefaultDateTimeLength();
771
+ }
772
+ return;
773
+ }
774
+ return +match[2];
775
+ }
748
776
  }