@mikro-orm/sql 7.0.2-dev.9 → 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,518 +1,553 @@
1
- import { CommitOrderCalculator, TableNotFoundException, Utils, } from '@mikro-orm/core';
1
+ import { CommitOrderCalculator, TableNotFoundException, Utils } from '@mikro-orm/core';
2
2
  import { AbstractSchemaGenerator } from '@mikro-orm/core/schema';
3
3
  import { DatabaseSchema } from './DatabaseSchema.js';
4
4
  import { SchemaComparator } from './SchemaComparator.js';
5
+ /** Generates and manages SQL database schemas based on entity metadata. Supports create, update, and drop operations. */
5
6
  export class SqlSchemaGenerator extends AbstractSchemaGenerator {
6
- helper = this.platform.getSchemaHelper();
7
- options = this.config.get('schemaGenerator');
8
- lastEnsuredDatabase;
9
- static register(orm) {
10
- orm.config.registerExtension('@mikro-orm/schema-generator', () => new SqlSchemaGenerator(orm.em));
11
- }
12
- async create(options) {
13
- await this.ensureDatabase();
14
- const sql = await this.getCreateSchemaSQL(options);
15
- await this.execute(sql);
16
- }
17
- /**
18
- * Returns true if the database was created.
19
- */
20
- async ensureDatabase(options) {
21
- await this.connection.ensureConnection();
22
- const dbName = this.config.get('dbName');
23
- if (this.lastEnsuredDatabase === dbName && !options?.forceCheck) {
24
- return true;
25
- }
26
- const exists = await this.helper.databaseExists(this.connection, dbName);
27
- this.lastEnsuredDatabase = dbName;
28
- if (!exists) {
29
- const managementDbName = this.helper.getManagementDbName();
30
- if (managementDbName) {
31
- this.config.set('dbName', managementDbName);
32
- await this.driver.reconnect({ skipOnConnect: true });
33
- await this.createDatabase(dbName, { skipOnConnect: true });
34
- }
35
- if (options?.create) {
36
- await this.create(options);
37
- }
38
- return true;
39
- }
40
- /* v8 ignore next */
41
- if (options?.clear) {
42
- await this.clear({ ...options, clearIdentityMap: false });
43
- }
44
- return false;
45
- }
46
- getTargetSchema(schema) {
47
- const metadata = this.getOrderedMetadata(schema);
48
- const schemaName = schema ?? this.config.get('schema') ?? this.platform.getDefaultSchemaName();
49
- return DatabaseSchema.fromMetadata(metadata, this.platform, this.config, schemaName, this.em);
50
- }
51
- getOrderedMetadata(schema) {
52
- const metadata = super.getOrderedMetadata(schema);
53
- // Filter out skipped tables
54
- return metadata.filter(meta => {
55
- const tableName = meta.tableName;
56
- const tableSchema = meta.schema ?? schema ?? this.config.get('schema');
57
- return !this.isTableSkipped(tableName, tableSchema);
58
- });
59
- }
60
- async getCreateSchemaSQL(options = {}) {
61
- const toSchema = this.getTargetSchema(options.schema);
62
- const ret = [];
63
- for (const namespace of toSchema.getNamespaces()) {
64
- if (namespace === this.platform.getDefaultSchemaName()) {
65
- continue;
66
- }
67
- const sql = this.helper.getCreateNamespaceSQL(namespace);
68
- this.append(ret, sql);
69
- }
70
- if (this.platform.supportsNativeEnums()) {
71
- const created = [];
72
- for (const [enumName, enumOptions] of Object.entries(toSchema.getNativeEnums())) {
73
- /* v8 ignore next */
74
- if (created.includes(enumName)) {
75
- continue;
76
- }
77
- created.push(enumName);
78
- const sql = this.helper.getCreateNativeEnumSQL(enumOptions.name, enumOptions.items, this.getSchemaName(enumOptions, options));
79
- this.append(ret, sql);
80
- }
81
- }
82
- for (const table of toSchema.getTables()) {
83
- this.append(ret, this.helper.createTable(table), true);
84
- }
85
- if (this.helper.supportsSchemaConstraints()) {
86
- for (const table of toSchema.getTables()) {
87
- const fks = Object.values(table.getForeignKeys()).map(fk => this.helper.createForeignKey(table, fk));
88
- this.append(ret, fks, true);
89
- }
90
- }
91
- // Create views after tables (views may depend on tables)
92
- // Sort views by dependencies (views depending on other views come later)
93
- const sortedViews = this.sortViewsByDependencies(toSchema.getViews());
94
- for (const view of sortedViews) {
95
- if (view.materialized) {
96
- this.append(ret, this.helper.createMaterializedView(view.name, view.schema, view.definition, view.withData ?? true));
97
- }
98
- else {
99
- this.append(ret, this.helper.createView(view.name, view.schema, view.definition), true);
100
- }
101
- }
102
- return this.wrapSchema(ret, options);
7
+ helper = this.platform.getSchemaHelper();
8
+ options = this.config.get('schemaGenerator');
9
+ lastEnsuredDatabase;
10
+ static register(orm) {
11
+ orm.config.registerExtension('@mikro-orm/schema-generator', () => new SqlSchemaGenerator(orm.em));
12
+ }
13
+ async create(options) {
14
+ await this.ensureDatabase();
15
+ const sql = await this.getCreateSchemaSQL(options);
16
+ await this.execute(sql);
17
+ }
18
+ /**
19
+ * Returns true if the database was created.
20
+ */
21
+ async ensureDatabase(options) {
22
+ await this.connection.ensureConnection();
23
+ const dbName = this.config.get('dbName');
24
+ if (this.lastEnsuredDatabase === dbName && !options?.forceCheck) {
25
+ return true;
103
26
  }
104
- async drop(options = {}) {
105
- if (options.dropDb) {
106
- const name = this.config.get('dbName');
107
- return this.dropDatabase(name);
108
- }
109
- const sql = await this.getDropSchemaSQL(options);
110
- await this.execute(sql);
27
+ const exists = await this.helper.databaseExists(this.connection, dbName);
28
+ this.lastEnsuredDatabase = dbName;
29
+ if (!exists) {
30
+ const managementDbName = this.helper.getManagementDbName();
31
+ if (managementDbName) {
32
+ this.config.set('dbName', managementDbName);
33
+ await this.driver.reconnect({ skipOnConnect: true });
34
+ await this.createDatabase(dbName, { skipOnConnect: true });
35
+ }
36
+ if (options?.create) {
37
+ await this.create(options);
38
+ }
39
+ return true;
111
40
  }
112
- async createNamespace(name) {
113
- const sql = this.helper.getCreateNamespaceSQL(name);
114
- await this.execute(sql);
41
+ /* v8 ignore next */
42
+ if (options?.clear) {
43
+ await this.clear({ ...options, clearIdentityMap: false });
115
44
  }
116
- async dropNamespace(name) {
117
- const sql = this.helper.getDropNamespaceSQL(name);
118
- await this.execute(sql);
45
+ return false;
46
+ }
47
+ getTargetSchema(schema) {
48
+ const metadata = this.getOrderedMetadata(schema);
49
+ const schemaName = schema ?? this.config.get('schema') ?? this.platform.getDefaultSchemaName();
50
+ return DatabaseSchema.fromMetadata(metadata, this.platform, this.config, schemaName, this.em);
51
+ }
52
+ getOrderedMetadata(schema) {
53
+ const metadata = super.getOrderedMetadata(schema);
54
+ // Filter out skipped tables
55
+ return metadata.filter(meta => {
56
+ const tableName = meta.tableName;
57
+ const tableSchema = meta.schema ?? schema ?? this.config.get('schema');
58
+ return !this.isTableSkipped(tableName, tableSchema);
59
+ });
60
+ }
61
+ async getCreateSchemaSQL(options = {}) {
62
+ const toSchema = this.getTargetSchema(options.schema);
63
+ const ret = [];
64
+ for (const namespace of toSchema.getNamespaces()) {
65
+ if (namespace === this.platform.getDefaultSchemaName()) {
66
+ continue;
67
+ }
68
+ const sql = this.helper.getCreateNamespaceSQL(namespace);
69
+ this.append(ret, sql);
119
70
  }
120
- async clear(options) {
121
- // truncate by default, so no value is considered as true
71
+ if (this.platform.supportsNativeEnums()) {
72
+ const created = [];
73
+ for (const [enumName, enumOptions] of Object.entries(toSchema.getNativeEnums())) {
122
74
  /* v8 ignore next */
123
- if (options?.truncate === false) {
124
- return super.clear(options);
125
- }
126
- if (this.options.disableForeignKeysForClear) {
127
- await this.execute(this.helper.disableForeignKeysSQL());
128
- }
129
- const schema = options?.schema ?? this.config.get('schema', this.platform.getDefaultSchemaName());
130
- for (const meta of this.getOrderedMetadata(schema).reverse()) {
131
- try {
132
- await this.driver
133
- .createQueryBuilder(meta.class, this.em?.getTransactionContext(), 'write', false)
134
- .withSchema(schema)
135
- .truncate()
136
- .execute();
137
- }
138
- catch (e) {
139
- if (this.platform.getExceptionConverter().convertException(e) instanceof TableNotFoundException) {
140
- continue;
141
- }
142
- throw e;
143
- }
144
- }
145
- if (this.options.disableForeignKeysForClear) {
146
- await this.execute(this.helper.enableForeignKeysSQL());
147
- }
148
- if (options?.clearIdentityMap ?? true) {
149
- this.clearIdentityMap();
150
- }
75
+ if (created.includes(enumName)) {
76
+ continue;
77
+ }
78
+ created.push(enumName);
79
+ const sql = this.helper.getCreateNativeEnumSQL(
80
+ enumOptions.name,
81
+ enumOptions.items,
82
+ this.getSchemaName(enumOptions, options),
83
+ );
84
+ this.append(ret, sql);
85
+ }
151
86
  }
152
- async getDropSchemaSQL(options = {}) {
153
- await this.ensureDatabase();
154
- const metadata = this.getOrderedMetadata(options.schema).reverse();
155
- const schemas = this.getTargetSchema(options.schema).getNamespaces();
156
- const schema = await DatabaseSchema.create(this.connection, this.platform, this.config, options.schema, schemas, undefined, this.options.skipTables, this.options.skipViews);
157
- const ret = [];
158
- // Drop views first (views may depend on tables)
159
- // Drop in reverse dependency order (dependent views first)
160
- const targetSchema = this.getTargetSchema(options.schema);
161
- const sortedViews = this.sortViewsByDependencies(targetSchema.getViews()).reverse();
162
- for (const view of sortedViews) {
163
- if (view.materialized) {
164
- this.append(ret, this.helper.dropMaterializedViewIfExists(view.name, view.schema));
165
- }
166
- else {
167
- this.append(ret, this.helper.dropViewIfExists(view.name, view.schema));
168
- }
169
- }
170
- // remove FKs explicitly if we can't use a cascading statement and we don't disable FK checks (we need this for circular relations)
171
- for (const meta of metadata) {
172
- if (!this.platform.usesCascadeStatement() && (!this.options.disableForeignKeys || options.dropForeignKeys)) {
173
- const table = schema.getTable(meta.tableName);
174
- if (!table) {
175
- continue;
176
- }
177
- const foreignKeys = Object.values(table.getForeignKeys());
178
- for (const fk of foreignKeys) {
179
- this.append(ret, this.helper.dropForeignKey(table.getShortestName(), fk.constraintName));
180
- }
181
- }
182
- }
183
- for (const meta of metadata) {
184
- this.append(ret, this.helper.dropTableIfExists(meta.tableName, this.getSchemaName(meta, options)));
185
- }
186
- if (this.platform.supportsNativeEnums()) {
187
- for (const columnName of Object.keys(schema.getNativeEnums())) {
188
- const sql = this.helper.getDropNativeEnumSQL(columnName, options.schema ?? this.config.get('schema'));
189
- this.append(ret, sql);
190
- }
191
- }
192
- if (options.dropMigrationsTable) {
193
- this.append(ret, this.helper.dropTableIfExists(this.config.get('migrations').tableName, this.config.get('schema')));
194
- }
195
- return this.wrapSchema(ret, options);
87
+ for (const table of toSchema.getTables()) {
88
+ this.append(ret, this.helper.createTable(table), true);
89
+ }
90
+ if (this.helper.supportsSchemaConstraints()) {
91
+ for (const table of toSchema.getTables()) {
92
+ const fks = Object.values(table.getForeignKeys()).map(fk => this.helper.createForeignKey(table, fk));
93
+ this.append(ret, fks, true);
94
+ }
95
+ }
96
+ // Create views after tables (views may depend on tables)
97
+ // Sort views by dependencies (views depending on other views come later)
98
+ const sortedViews = this.sortViewsByDependencies(toSchema.getViews());
99
+ for (const view of sortedViews) {
100
+ if (view.materialized) {
101
+ this.append(
102
+ ret,
103
+ this.helper.createMaterializedView(view.name, view.schema, view.definition, view.withData ?? true),
104
+ );
105
+ } else {
106
+ this.append(ret, this.helper.createView(view.name, view.schema, view.definition), true);
107
+ }
108
+ }
109
+ return this.wrapSchema(ret, options);
110
+ }
111
+ async drop(options = {}) {
112
+ if (options.dropDb) {
113
+ const name = this.config.get('dbName');
114
+ return this.dropDatabase(name);
196
115
  }
197
- getSchemaName(meta, options) {
198
- const schemaName = options.schema ?? this.config.get('schema');
116
+ const sql = await this.getDropSchemaSQL(options);
117
+ await this.execute(sql);
118
+ }
119
+ async createNamespace(name) {
120
+ const sql = this.helper.getCreateNamespaceSQL(name);
121
+ await this.execute(sql);
122
+ }
123
+ async dropNamespace(name) {
124
+ const sql = this.helper.getDropNamespaceSQL(name);
125
+ await this.execute(sql);
126
+ }
127
+ async clear(options) {
128
+ // truncate by default, so no value is considered as true
129
+ /* v8 ignore next */
130
+ if (options?.truncate === false) {
131
+ return super.clear(options);
132
+ }
133
+ if (this.options.disableForeignKeysForClear) {
134
+ await this.execute(this.helper.disableForeignKeysSQL());
135
+ }
136
+ const schema = options?.schema ?? this.config.get('schema', this.platform.getDefaultSchemaName());
137
+ for (const meta of this.getOrderedMetadata(schema).reverse()) {
138
+ try {
139
+ await this.driver
140
+ .createQueryBuilder(meta.class, this.em?.getTransactionContext(), 'write', false)
141
+ .withSchema(schema)
142
+ .truncate()
143
+ .execute();
144
+ } catch (e) {
145
+ if (this.platform.getExceptionConverter().convertException(e) instanceof TableNotFoundException) {
146
+ continue;
147
+ }
148
+ throw e;
149
+ }
150
+ }
151
+ if (this.options.disableForeignKeysForClear) {
152
+ await this.execute(this.helper.enableForeignKeysSQL());
153
+ }
154
+ if (options?.clearIdentityMap ?? true) {
155
+ this.clearIdentityMap();
156
+ }
157
+ }
158
+ async getDropSchemaSQL(options = {}) {
159
+ await this.ensureDatabase();
160
+ const metadata = this.getOrderedMetadata(options.schema).reverse();
161
+ const schemas = this.getTargetSchema(options.schema).getNamespaces();
162
+ const schema = await DatabaseSchema.create(
163
+ this.connection,
164
+ this.platform,
165
+ this.config,
166
+ options.schema,
167
+ schemas,
168
+ undefined,
169
+ this.options.skipTables,
170
+ this.options.skipViews,
171
+ );
172
+ const ret = [];
173
+ // Drop views first (views may depend on tables)
174
+ // Drop in reverse dependency order (dependent views first)
175
+ const targetSchema = this.getTargetSchema(options.schema);
176
+ const sortedViews = this.sortViewsByDependencies(targetSchema.getViews()).reverse();
177
+ for (const view of sortedViews) {
178
+ if (view.materialized) {
179
+ this.append(ret, this.helper.dropMaterializedViewIfExists(view.name, view.schema));
180
+ } else {
181
+ this.append(ret, this.helper.dropViewIfExists(view.name, view.schema));
182
+ }
183
+ }
184
+ // remove FKs explicitly if we can't use a cascading statement and we don't disable FK checks (we need this for circular relations)
185
+ for (const meta of metadata) {
186
+ if (!this.platform.usesCascadeStatement() && (!this.options.disableForeignKeys || options.dropForeignKeys)) {
187
+ const table = schema.getTable(meta.tableName);
188
+ if (!table) {
189
+ continue;
190
+ }
191
+ const foreignKeys = Object.values(table.getForeignKeys());
192
+ for (const fk of foreignKeys) {
193
+ this.append(ret, this.helper.dropForeignKey(table.getShortestName(), fk.constraintName));
194
+ }
195
+ }
196
+ }
197
+ for (const meta of metadata) {
198
+ this.append(ret, this.helper.dropTableIfExists(meta.tableName, this.getSchemaName(meta, options)));
199
+ }
200
+ if (this.platform.supportsNativeEnums()) {
201
+ for (const columnName of Object.keys(schema.getNativeEnums())) {
202
+ const sql = this.helper.getDropNativeEnumSQL(columnName, options.schema ?? this.config.get('schema'));
203
+ this.append(ret, sql);
204
+ }
205
+ }
206
+ if (options.dropMigrationsTable) {
207
+ this.append(
208
+ ret,
209
+ this.helper.dropTableIfExists(this.config.get('migrations').tableName, this.config.get('schema')),
210
+ );
211
+ }
212
+ return this.wrapSchema(ret, options);
213
+ }
214
+ getSchemaName(meta, options) {
215
+ const schemaName = options.schema ?? this.config.get('schema');
216
+ /* v8 ignore next */
217
+ const resolvedName = meta.schema && meta.schema === '*' ? schemaName : (meta.schema ?? schemaName);
218
+ // skip default schema name
219
+ if (resolvedName === this.platform.getDefaultSchemaName()) {
220
+ return undefined;
221
+ }
222
+ return resolvedName;
223
+ }
224
+ async update(options = {}) {
225
+ const sql = await this.getUpdateSchemaSQL(options);
226
+ await this.execute(sql);
227
+ }
228
+ async getUpdateSchemaSQL(options = {}) {
229
+ await this.ensureDatabase();
230
+ const { fromSchema, toSchema } = await this.prepareSchemaForComparison(options);
231
+ const comparator = new SchemaComparator(this.platform);
232
+ const diffUp = comparator.compare(fromSchema, toSchema);
233
+ return this.diffToSQL(diffUp, options);
234
+ }
235
+ async getUpdateSchemaMigrationSQL(options = {}) {
236
+ if (!options.fromSchema) {
237
+ await this.ensureDatabase();
238
+ }
239
+ const { fromSchema, toSchema } = await this.prepareSchemaForComparison(options);
240
+ const comparator = new SchemaComparator(this.platform);
241
+ const diffUp = comparator.compare(fromSchema, toSchema);
242
+ const diffDown = comparator.compare(toSchema, fromSchema, diffUp);
243
+ return {
244
+ up: this.diffToSQL(diffUp, options),
245
+ down: this.platform.supportsDownMigrations() ? this.diffToSQL(diffDown, options) : '',
246
+ };
247
+ }
248
+ async prepareSchemaForComparison(options) {
249
+ options.safe ??= false;
250
+ options.dropTables ??= true;
251
+ const toSchema = this.getTargetSchema(options.schema);
252
+ const schemas = toSchema.getNamespaces();
253
+ const fromSchema =
254
+ options.fromSchema ??
255
+ (await DatabaseSchema.create(
256
+ this.connection,
257
+ this.platform,
258
+ this.config,
259
+ options.schema,
260
+ schemas,
261
+ undefined,
262
+ this.options.skipTables,
263
+ this.options.skipViews,
264
+ ));
265
+ const wildcardSchemaTables = [...this.metadata.getAll().values()]
266
+ .filter(meta => meta.schema === '*')
267
+ .map(meta => meta.tableName);
268
+ fromSchema.prune(options.schema, wildcardSchemaTables);
269
+ toSchema.prune(options.schema, wildcardSchemaTables);
270
+ return { fromSchema, toSchema };
271
+ }
272
+ diffToSQL(schemaDiff, options) {
273
+ const ret = [];
274
+ globalThis.idx = 0;
275
+ if (this.platform.supportsSchemas()) {
276
+ for (const newNamespace of schemaDiff.newNamespaces) {
277
+ const sql = this.helper.getCreateNamespaceSQL(newNamespace);
278
+ this.append(ret, sql);
279
+ }
280
+ }
281
+ if (this.platform.supportsNativeEnums()) {
282
+ for (const newNativeEnum of schemaDiff.newNativeEnums) {
283
+ const sql = this.helper.getCreateNativeEnumSQL(
284
+ newNativeEnum.name,
285
+ newNativeEnum.items,
286
+ this.getSchemaName(newNativeEnum, options),
287
+ );
288
+ this.append(ret, sql);
289
+ }
290
+ }
291
+ // Drop removed and changed views first (before modifying tables they may depend on)
292
+ // Drop in reverse dependency order (dependent views first)
293
+ if (options.dropTables && !options.safe) {
294
+ const sortedRemovedViews = this.sortViewsByDependencies(Object.values(schemaDiff.removedViews)).reverse();
295
+ for (const view of sortedRemovedViews) {
296
+ if (view.materialized) {
297
+ this.append(ret, this.helper.dropMaterializedViewIfExists(view.name, view.schema));
298
+ } else {
299
+ this.append(ret, this.helper.dropViewIfExists(view.name, view.schema));
300
+ }
301
+ }
302
+ }
303
+ // Drop changed views (they will be recreated after table changes)
304
+ // Also in reverse dependency order
305
+ const changedViewsFrom = Object.values(schemaDiff.changedViews).map(v => v.from);
306
+ const sortedChangedViewsFrom = this.sortViewsByDependencies(changedViewsFrom).reverse();
307
+ for (const view of sortedChangedViewsFrom) {
308
+ if (view.materialized) {
309
+ this.append(ret, this.helper.dropMaterializedViewIfExists(view.name, view.schema));
310
+ } else {
311
+ this.append(ret, this.helper.dropViewIfExists(view.name, view.schema));
312
+ }
313
+ }
314
+ if (!options.safe && this.options.createForeignKeyConstraints) {
315
+ for (const orphanedForeignKey of schemaDiff.orphanedForeignKeys) {
316
+ const [schemaName, tableName] = this.helper.splitTableName(orphanedForeignKey.localTableName, true);
199
317
  /* v8 ignore next */
200
- const resolvedName = meta.schema && meta.schema === '*' ? schemaName : (meta.schema ?? schemaName);
201
- // skip default schema name
202
- if (resolvedName === this.platform.getDefaultSchemaName()) {
203
- return undefined;
204
- }
205
- return resolvedName;
206
- }
207
- async update(options = {}) {
208
- const sql = await this.getUpdateSchemaSQL(options);
209
- await this.execute(sql);
210
- }
211
- async getUpdateSchemaSQL(options = {}) {
212
- await this.ensureDatabase();
213
- const { fromSchema, toSchema } = await this.prepareSchemaForComparison(options);
214
- const comparator = new SchemaComparator(this.platform);
215
- const diffUp = comparator.compare(fromSchema, toSchema);
216
- return this.diffToSQL(diffUp, options);
217
- }
218
- async getUpdateSchemaMigrationSQL(options = {}) {
219
- if (!options.fromSchema) {
220
- await this.ensureDatabase();
221
- }
222
- const { fromSchema, toSchema } = await this.prepareSchemaForComparison(options);
223
- const comparator = new SchemaComparator(this.platform);
224
- const diffUp = comparator.compare(fromSchema, toSchema);
225
- const diffDown = comparator.compare(toSchema, fromSchema, diffUp);
226
- return {
227
- up: this.diffToSQL(diffUp, options),
228
- down: this.platform.supportsDownMigrations() ? this.diffToSQL(diffDown, options) : '',
229
- };
230
- }
231
- async prepareSchemaForComparison(options) {
232
- options.safe ??= false;
233
- options.dropTables ??= true;
234
- const toSchema = this.getTargetSchema(options.schema);
235
- const schemas = toSchema.getNamespaces();
236
- const fromSchema = options.fromSchema ??
237
- (await DatabaseSchema.create(this.connection, this.platform, this.config, options.schema, schemas, undefined, this.options.skipTables, this.options.skipViews));
238
- const wildcardSchemaTables = [...this.metadata.getAll().values()]
239
- .filter(meta => meta.schema === '*')
240
- .map(meta => meta.tableName);
241
- fromSchema.prune(options.schema, wildcardSchemaTables);
242
- toSchema.prune(options.schema, wildcardSchemaTables);
243
- return { fromSchema, toSchema };
244
- }
245
- diffToSQL(schemaDiff, options) {
246
- const ret = [];
247
- globalThis.idx = 0;
248
- if (this.platform.supportsSchemas()) {
249
- for (const newNamespace of schemaDiff.newNamespaces) {
250
- const sql = this.helper.getCreateNamespaceSQL(newNamespace);
251
- this.append(ret, sql);
252
- }
253
- }
254
- if (this.platform.supportsNativeEnums()) {
255
- for (const newNativeEnum of schemaDiff.newNativeEnums) {
256
- const sql = this.helper.getCreateNativeEnumSQL(newNativeEnum.name, newNativeEnum.items, this.getSchemaName(newNativeEnum, options));
257
- this.append(ret, sql);
258
- }
259
- }
260
- // Drop removed and changed views first (before modifying tables they may depend on)
261
- // Drop in reverse dependency order (dependent views first)
262
- if (options.dropTables && !options.safe) {
263
- const sortedRemovedViews = this.sortViewsByDependencies(Object.values(schemaDiff.removedViews)).reverse();
264
- for (const view of sortedRemovedViews) {
265
- if (view.materialized) {
266
- this.append(ret, this.helper.dropMaterializedViewIfExists(view.name, view.schema));
267
- }
268
- else {
269
- this.append(ret, this.helper.dropViewIfExists(view.name, view.schema));
270
- }
271
- }
272
- }
273
- // Drop changed views (they will be recreated after table changes)
274
- // Also in reverse dependency order
275
- const changedViewsFrom = Object.values(schemaDiff.changedViews).map(v => v.from);
276
- const sortedChangedViewsFrom = this.sortViewsByDependencies(changedViewsFrom).reverse();
277
- for (const view of sortedChangedViewsFrom) {
278
- if (view.materialized) {
279
- this.append(ret, this.helper.dropMaterializedViewIfExists(view.name, view.schema));
280
- }
281
- else {
282
- this.append(ret, this.helper.dropViewIfExists(view.name, view.schema));
283
- }
284
- }
285
- if (!options.safe && this.options.createForeignKeyConstraints) {
286
- for (const orphanedForeignKey of schemaDiff.orphanedForeignKeys) {
287
- const [schemaName, tableName] = this.helper.splitTableName(orphanedForeignKey.localTableName, true);
288
- /* v8 ignore next */
289
- const name = (schemaName ? schemaName + '.' : '') + tableName;
290
- this.append(ret, this.helper.dropForeignKey(name, orphanedForeignKey.constraintName));
291
- }
292
- if (schemaDiff.orphanedForeignKeys.length > 0) {
293
- ret.push('');
294
- }
295
- }
296
- for (const newTable of Object.values(schemaDiff.newTables)) {
297
- this.append(ret, this.helper.createTable(newTable, true), true);
298
- }
299
- if (this.helper.supportsSchemaConstraints()) {
300
- for (const newTable of Object.values(schemaDiff.newTables)) {
301
- const sql = [];
302
- if (this.options.createForeignKeyConstraints) {
303
- const fks = Object.values(newTable.getForeignKeys()).map(fk => this.helper.createForeignKey(newTable, fk));
304
- this.append(sql, fks);
305
- }
306
- for (const check of newTable.getChecks()) {
307
- this.append(sql, this.helper.createCheck(newTable, check));
308
- }
309
- this.append(ret, sql, true);
310
- }
311
- }
312
- if (options.dropTables && !options.safe) {
313
- for (const table of Object.values(schemaDiff.removedTables)) {
314
- this.append(ret, this.helper.dropTableIfExists(table.name, table.schema));
315
- }
316
- if (Utils.hasObjectKeys(schemaDiff.removedTables)) {
317
- ret.push('');
318
- }
319
- }
320
- for (const changedTable of Object.values(schemaDiff.changedTables)) {
321
- this.append(ret, this.preAlterTable(changedTable, options.safe), true);
322
- }
323
- for (const changedTable of Object.values(schemaDiff.changedTables)) {
324
- this.append(ret, this.helper.alterTable(changedTable, options.safe), true);
325
- }
326
- for (const changedTable of Object.values(schemaDiff.changedTables)) {
327
- this.append(ret, this.helper.getPostAlterTable(changedTable, options.safe), true);
328
- }
329
- if (!options.safe && this.platform.supportsNativeEnums()) {
330
- for (const removedNativeEnum of schemaDiff.removedNativeEnums) {
331
- this.append(ret, this.helper.getDropNativeEnumSQL(removedNativeEnum.name, removedNativeEnum.schema));
332
- }
333
- }
334
- if (options.dropTables && !options.safe) {
335
- for (const removedNamespace of schemaDiff.removedNamespaces) {
336
- const sql = this.helper.getDropNamespaceSQL(removedNamespace);
337
- this.append(ret, sql);
338
- }
339
- }
340
- // Create new views after all table changes are done
341
- // Sort views by dependencies (views depending on other views come later)
342
- const sortedNewViews = this.sortViewsByDependencies(Object.values(schemaDiff.newViews));
343
- for (const view of sortedNewViews) {
344
- if (view.materialized) {
345
- this.append(ret, this.helper.createMaterializedView(view.name, view.schema, view.definition, view.withData ?? true));
346
- }
347
- else {
348
- this.append(ret, this.helper.createView(view.name, view.schema, view.definition), true);
349
- }
350
- }
351
- // Recreate changed views (also sorted by dependencies)
352
- const changedViews = Object.values(schemaDiff.changedViews).map(v => v.to);
353
- const sortedChangedViews = this.sortViewsByDependencies(changedViews);
354
- for (const view of sortedChangedViews) {
355
- if (view.materialized) {
356
- this.append(ret, this.helper.createMaterializedView(view.name, view.schema, view.definition, view.withData ?? true));
357
- }
358
- else {
359
- this.append(ret, this.helper.createView(view.name, view.schema, view.definition), true);
360
- }
361
- }
362
- return this.wrapSchema(ret, options);
363
- }
364
- /**
365
- * We need to drop foreign keys first for all tables to allow dropping PK constraints.
366
- */
367
- preAlterTable(diff, safe) {
368
- const ret = [];
369
- this.append(ret, this.helper.getPreAlterTable(diff, safe));
370
- for (const foreignKey of Object.values(diff.removedForeignKeys)) {
371
- ret.push(this.helper.dropForeignKey(diff.toTable.getShortestName(), foreignKey.constraintName));
372
- }
373
- for (const foreignKey of Object.values(diff.changedForeignKeys)) {
374
- ret.push(this.helper.dropForeignKey(diff.toTable.getShortestName(), foreignKey.constraintName));
375
- }
376
- return ret;
377
- }
378
- /**
379
- * creates new database and connects to it
380
- */
381
- async createDatabase(name, options) {
382
- name ??= this.config.get('dbName');
383
- const sql = this.helper.getCreateDatabaseSQL(name);
384
- if (sql) {
385
- await this.execute(sql);
386
- }
387
- this.config.set('dbName', name);
388
- await this.driver.reconnect(options);
389
- }
390
- async dropDatabase(name) {
391
- name ??= this.config.get('dbName');
392
- this.config.set('dbName', this.helper.getManagementDbName());
393
- await this.driver.reconnect();
394
- await this.execute(this.helper.getDropDatabaseSQL(name));
395
- this.config.set('dbName', name);
396
- }
397
- async execute(sql, options = {}) {
398
- options.wrap ??= false;
399
- const lines = this.wrapSchema(sql, options).split('\n');
400
- const groups = [];
401
- let i = 0;
402
- for (const line of lines) {
403
- if (line.trim() === '') {
404
- if (groups[i]?.length > 0) {
405
- i++;
406
- }
407
- continue;
408
- }
409
- groups[i] ??= [];
410
- groups[i].push(line.trim());
411
- }
412
- if (groups.length === 0) {
413
- return;
414
- }
415
- if (this.platform.supportsMultipleStatements()) {
416
- for (const group of groups) {
417
- const query = group.join('\n');
418
- await this.driver.execute(query);
419
- }
420
- return;
421
- }
422
- const statements = groups.flatMap(group => {
423
- return group
424
- .join('\n')
425
- .split(';\n')
426
- .map(s => s.trim())
427
- .filter(s => s);
428
- });
429
- await Utils.runSerial(statements, stmt => this.driver.execute(stmt));
430
- }
431
- async dropTableIfExists(name, schema) {
432
- const sql = this.helper.dropTableIfExists(name, schema);
433
- return this.execute(sql);
434
- }
435
- wrapSchema(sql, options) {
436
- const array = Utils.asArray(sql);
437
- if (array.length === 0) {
438
- return '';
439
- }
440
- if (array[array.length - 1] === '') {
441
- array.pop();
442
- }
443
- if (options.wrap === false) {
444
- return array.join('\n') + '\n';
445
- }
446
- let ret = this.helper.getSchemaBeginning(this.config.get('charset'), this.options.disableForeignKeys);
447
- ret += array.join('\n') + '\n';
448
- ret += this.helper.getSchemaEnd(this.options.disableForeignKeys);
449
- return ret;
450
- }
451
- append(array, sql, pad) {
452
- return this.helper.append(array, sql, pad);
453
- }
454
- matchName(name, nameToMatch) {
455
- return typeof nameToMatch === 'string'
456
- ? name.toLocaleLowerCase() === nameToMatch.toLocaleLowerCase()
457
- : nameToMatch.test(name);
458
- }
459
- isTableSkipped(tableName, schemaName) {
460
- const skipTables = this.options.skipTables;
461
- if (!skipTables || skipTables.length === 0) {
462
- return false;
463
- }
464
- const fullTableName = schemaName ? `${schemaName}.${tableName}` : tableName;
465
- return skipTables.some(pattern => this.matchName(tableName, pattern) || this.matchName(fullTableName, pattern));
466
- }
467
- /**
468
- * Sorts views by their dependencies so that views depending on other views are created after their dependencies.
469
- * Uses topological sort based on view definition string matching.
470
- */
471
- sortViewsByDependencies(views) {
472
- if (views.length <= 1) {
473
- return views;
474
- }
475
- // Use CommitOrderCalculator for topological sort
476
- const calc = new CommitOrderCalculator();
477
- // Map views to numeric indices for the calculator
478
- const viewToIndex = new Map();
479
- const indexToView = new Map();
480
- for (let i = 0; i < views.length; i++) {
481
- viewToIndex.set(views[i], i);
482
- indexToView.set(i, views[i]);
483
- calc.addNode(i);
484
- }
485
- // Check each view's definition for references to other view names
486
- for (const view of views) {
487
- const definition = view.definition.toLowerCase();
488
- const viewIndex = viewToIndex.get(view);
489
- for (const otherView of views) {
490
- if (otherView === view) {
491
- continue;
492
- }
493
- // Check if the definition references the other view's name
494
- // Use word boundary matching to avoid false positives
495
- const patterns = [new RegExp(`\\b${this.escapeRegExp(otherView.name.toLowerCase())}\\b`)];
496
- if (otherView.schema) {
497
- patterns.push(new RegExp(`\\b${this.escapeRegExp(`${otherView.schema}.${otherView.name}`.toLowerCase())}\\b`));
498
- }
499
- for (const pattern of patterns) {
500
- if (pattern.test(definition)) {
501
- // view depends on otherView, so otherView must come first
502
- // addDependency(from, to) puts `from` before `to` in result
503
- const otherIndex = viewToIndex.get(otherView);
504
- calc.addDependency(otherIndex, viewIndex, 1);
505
- break;
506
- }
507
- }
508
- }
509
- }
510
- // Sort and map back to views
511
- return calc.sort().map(index => indexToView.get(index));
318
+ const name = (schemaName ? schemaName + '.' : '') + tableName;
319
+ this.append(ret, this.helper.dropForeignKey(name, orphanedForeignKey.constraintName));
320
+ }
321
+ if (schemaDiff.orphanedForeignKeys.length > 0) {
322
+ ret.push('');
323
+ }
324
+ }
325
+ for (const newTable of Object.values(schemaDiff.newTables)) {
326
+ this.append(ret, this.helper.createTable(newTable, true), true);
327
+ }
328
+ if (this.helper.supportsSchemaConstraints()) {
329
+ for (const newTable of Object.values(schemaDiff.newTables)) {
330
+ const sql = [];
331
+ if (this.options.createForeignKeyConstraints) {
332
+ const fks = Object.values(newTable.getForeignKeys()).map(fk => this.helper.createForeignKey(newTable, fk));
333
+ this.append(sql, fks);
334
+ }
335
+ for (const check of newTable.getChecks()) {
336
+ this.append(sql, this.helper.createCheck(newTable, check));
337
+ }
338
+ this.append(ret, sql, true);
339
+ }
340
+ }
341
+ if (options.dropTables && !options.safe) {
342
+ for (const table of Object.values(schemaDiff.removedTables)) {
343
+ this.append(ret, this.helper.dropTableIfExists(table.name, table.schema));
344
+ }
345
+ if (Utils.hasObjectKeys(schemaDiff.removedTables)) {
346
+ ret.push('');
347
+ }
348
+ }
349
+ for (const changedTable of Object.values(schemaDiff.changedTables)) {
350
+ this.append(ret, this.preAlterTable(changedTable, options.safe), true);
351
+ }
352
+ for (const changedTable of Object.values(schemaDiff.changedTables)) {
353
+ this.append(ret, this.helper.alterTable(changedTable, options.safe), true);
354
+ }
355
+ for (const changedTable of Object.values(schemaDiff.changedTables)) {
356
+ this.append(ret, this.helper.getPostAlterTable(changedTable, options.safe), true);
357
+ }
358
+ if (!options.safe && this.platform.supportsNativeEnums()) {
359
+ for (const removedNativeEnum of schemaDiff.removedNativeEnums) {
360
+ this.append(ret, this.helper.getDropNativeEnumSQL(removedNativeEnum.name, removedNativeEnum.schema));
361
+ }
362
+ }
363
+ if (options.dropTables && !options.safe) {
364
+ for (const removedNamespace of schemaDiff.removedNamespaces) {
365
+ const sql = this.helper.getDropNamespaceSQL(removedNamespace);
366
+ this.append(ret, sql);
367
+ }
368
+ }
369
+ // Create new views after all table changes are done
370
+ // Sort views by dependencies (views depending on other views come later)
371
+ const sortedNewViews = this.sortViewsByDependencies(Object.values(schemaDiff.newViews));
372
+ for (const view of sortedNewViews) {
373
+ if (view.materialized) {
374
+ this.append(
375
+ ret,
376
+ this.helper.createMaterializedView(view.name, view.schema, view.definition, view.withData ?? true),
377
+ );
378
+ } else {
379
+ this.append(ret, this.helper.createView(view.name, view.schema, view.definition), true);
380
+ }
381
+ }
382
+ // Recreate changed views (also sorted by dependencies)
383
+ const changedViews = Object.values(schemaDiff.changedViews).map(v => v.to);
384
+ const sortedChangedViews = this.sortViewsByDependencies(changedViews);
385
+ for (const view of sortedChangedViews) {
386
+ if (view.materialized) {
387
+ this.append(
388
+ ret,
389
+ this.helper.createMaterializedView(view.name, view.schema, view.definition, view.withData ?? true),
390
+ );
391
+ } else {
392
+ this.append(ret, this.helper.createView(view.name, view.schema, view.definition), true);
393
+ }
394
+ }
395
+ return this.wrapSchema(ret, options);
396
+ }
397
+ /**
398
+ * We need to drop foreign keys first for all tables to allow dropping PK constraints.
399
+ */
400
+ preAlterTable(diff, safe) {
401
+ const ret = [];
402
+ this.append(ret, this.helper.getPreAlterTable(diff, safe));
403
+ for (const foreignKey of Object.values(diff.removedForeignKeys)) {
404
+ ret.push(this.helper.dropForeignKey(diff.toTable.getShortestName(), foreignKey.constraintName));
405
+ }
406
+ for (const foreignKey of Object.values(diff.changedForeignKeys)) {
407
+ ret.push(this.helper.dropForeignKey(diff.toTable.getShortestName(), foreignKey.constraintName));
408
+ }
409
+ return ret;
410
+ }
411
+ /**
412
+ * creates new database and connects to it
413
+ */
414
+ async createDatabase(name, options) {
415
+ name ??= this.config.get('dbName');
416
+ const sql = this.helper.getCreateDatabaseSQL(name);
417
+ if (sql) {
418
+ await this.execute(sql);
419
+ }
420
+ this.config.set('dbName', name);
421
+ await this.driver.reconnect(options);
422
+ }
423
+ async dropDatabase(name) {
424
+ name ??= this.config.get('dbName');
425
+ this.config.set('dbName', this.helper.getManagementDbName());
426
+ await this.driver.reconnect();
427
+ await this.execute(this.helper.getDropDatabaseSQL(name));
428
+ this.config.set('dbName', name);
429
+ }
430
+ async execute(sql, options = {}) {
431
+ options.wrap ??= false;
432
+ const lines = this.wrapSchema(sql, options).split('\n');
433
+ const groups = [];
434
+ let i = 0;
435
+ for (const line of lines) {
436
+ if (line.trim() === '') {
437
+ if (groups[i]?.length > 0) {
438
+ i++;
439
+ }
440
+ continue;
441
+ }
442
+ groups[i] ??= [];
443
+ groups[i].push(line.trim());
444
+ }
445
+ if (groups.length === 0) {
446
+ return;
447
+ }
448
+ if (this.platform.supportsMultipleStatements()) {
449
+ for (const group of groups) {
450
+ const query = group.join('\n');
451
+ await this.driver.execute(query);
452
+ }
453
+ return;
454
+ }
455
+ const statements = groups.flatMap(group => {
456
+ return group
457
+ .join('\n')
458
+ .split(';\n')
459
+ .map(s => s.trim())
460
+ .filter(s => s);
461
+ });
462
+ await Utils.runSerial(statements, stmt => this.driver.execute(stmt));
463
+ }
464
+ async dropTableIfExists(name, schema) {
465
+ const sql = this.helper.dropTableIfExists(name, schema);
466
+ return this.execute(sql);
467
+ }
468
+ wrapSchema(sql, options) {
469
+ const array = Utils.asArray(sql);
470
+ if (array.length === 0) {
471
+ return '';
472
+ }
473
+ if (array[array.length - 1] === '') {
474
+ array.pop();
475
+ }
476
+ if (options.wrap === false) {
477
+ return array.join('\n') + '\n';
478
+ }
479
+ let ret = this.helper.getSchemaBeginning(this.config.get('charset'), this.options.disableForeignKeys);
480
+ ret += array.join('\n') + '\n';
481
+ ret += this.helper.getSchemaEnd(this.options.disableForeignKeys);
482
+ return ret;
483
+ }
484
+ append(array, sql, pad) {
485
+ return this.helper.append(array, sql, pad);
486
+ }
487
+ matchName(name, nameToMatch) {
488
+ return typeof nameToMatch === 'string'
489
+ ? name.toLocaleLowerCase() === nameToMatch.toLocaleLowerCase()
490
+ : nameToMatch.test(name);
491
+ }
492
+ isTableSkipped(tableName, schemaName) {
493
+ const skipTables = this.options.skipTables;
494
+ if (!skipTables || skipTables.length === 0) {
495
+ return false;
496
+ }
497
+ const fullTableName = schemaName ? `${schemaName}.${tableName}` : tableName;
498
+ return skipTables.some(pattern => this.matchName(tableName, pattern) || this.matchName(fullTableName, pattern));
499
+ }
500
+ /**
501
+ * Sorts views by their dependencies so that views depending on other views are created after their dependencies.
502
+ * Uses topological sort based on view definition string matching.
503
+ */
504
+ sortViewsByDependencies(views) {
505
+ if (views.length <= 1) {
506
+ return views;
507
+ }
508
+ // Use CommitOrderCalculator for topological sort
509
+ const calc = new CommitOrderCalculator();
510
+ // Map views to numeric indices for the calculator
511
+ const viewToIndex = new Map();
512
+ const indexToView = new Map();
513
+ for (let i = 0; i < views.length; i++) {
514
+ viewToIndex.set(views[i], i);
515
+ indexToView.set(i, views[i]);
516
+ calc.addNode(i);
512
517
  }
513
- escapeRegExp(string) {
514
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
518
+ // Check each view's definition for references to other view names
519
+ for (const view of views) {
520
+ const definition = view.definition.toLowerCase();
521
+ const viewIndex = viewToIndex.get(view);
522
+ for (const otherView of views) {
523
+ if (otherView === view) {
524
+ continue;
525
+ }
526
+ // Check if the definition references the other view's name
527
+ // Use word boundary matching to avoid false positives
528
+ const patterns = [new RegExp(`\\b${this.escapeRegExp(otherView.name.toLowerCase())}\\b`)];
529
+ if (otherView.schema) {
530
+ patterns.push(
531
+ new RegExp(`\\b${this.escapeRegExp(`${otherView.schema}.${otherView.name}`.toLowerCase())}\\b`),
532
+ );
533
+ }
534
+ for (const pattern of patterns) {
535
+ if (pattern.test(definition)) {
536
+ // view depends on otherView, so otherView must come first
537
+ // addDependency(from, to) puts `from` before `to` in result
538
+ const otherIndex = viewToIndex.get(otherView);
539
+ calc.addDependency(otherIndex, viewIndex, 1);
540
+ break;
541
+ }
542
+ }
543
+ }
515
544
  }
545
+ // Sort and map back to views
546
+ return calc.sort().map(index => indexToView.get(index));
547
+ }
548
+ escapeRegExp(string) {
549
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
550
+ }
516
551
  }
517
552
  // for back compatibility
518
553
  export { SqlSchemaGenerator as SchemaGenerator };