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

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