@yandjin-mikro-orm/knex 6.1.4-rc-sti-changes-1

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 (52) hide show
  1. package/AbstractSqlConnection.d.ts +58 -0
  2. package/AbstractSqlConnection.js +206 -0
  3. package/AbstractSqlDriver.d.ts +73 -0
  4. package/AbstractSqlDriver.js +1378 -0
  5. package/AbstractSqlPlatform.d.ts +25 -0
  6. package/AbstractSqlPlatform.js +86 -0
  7. package/LICENSE +21 -0
  8. package/MonkeyPatchable.d.ts +11 -0
  9. package/MonkeyPatchable.js +39 -0
  10. package/PivotCollectionPersister.d.ts +17 -0
  11. package/PivotCollectionPersister.js +131 -0
  12. package/README.md +383 -0
  13. package/SqlEntityManager.d.ts +25 -0
  14. package/SqlEntityManager.js +40 -0
  15. package/SqlEntityRepository.d.ts +24 -0
  16. package/SqlEntityRepository.js +36 -0
  17. package/index.d.ts +18 -0
  18. package/index.js +40 -0
  19. package/index.mjs +215 -0
  20. package/package.json +71 -0
  21. package/query/ArrayCriteriaNode.d.ts +10 -0
  22. package/query/ArrayCriteriaNode.js +25 -0
  23. package/query/CriteriaNode.d.ts +31 -0
  24. package/query/CriteriaNode.js +147 -0
  25. package/query/CriteriaNodeFactory.d.ts +12 -0
  26. package/query/CriteriaNodeFactory.js +90 -0
  27. package/query/ObjectCriteriaNode.d.ts +15 -0
  28. package/query/ObjectCriteriaNode.js +233 -0
  29. package/query/QueryBuilder.d.ts +291 -0
  30. package/query/QueryBuilder.js +1445 -0
  31. package/query/QueryBuilderHelper.d.ts +64 -0
  32. package/query/QueryBuilderHelper.js +747 -0
  33. package/query/ScalarCriteriaNode.d.ts +10 -0
  34. package/query/ScalarCriteriaNode.js +56 -0
  35. package/query/enums.d.ts +15 -0
  36. package/query/enums.js +20 -0
  37. package/query/index.d.ts +8 -0
  38. package/query/index.js +24 -0
  39. package/schema/DatabaseSchema.d.ts +29 -0
  40. package/schema/DatabaseSchema.js +140 -0
  41. package/schema/DatabaseTable.d.ts +61 -0
  42. package/schema/DatabaseTable.js +727 -0
  43. package/schema/SchemaComparator.d.ts +59 -0
  44. package/schema/SchemaComparator.js +603 -0
  45. package/schema/SchemaHelper.d.ts +56 -0
  46. package/schema/SchemaHelper.js +274 -0
  47. package/schema/SqlSchemaGenerator.d.ts +63 -0
  48. package/schema/SqlSchemaGenerator.js +598 -0
  49. package/schema/index.d.ts +5 -0
  50. package/schema/index.js +21 -0
  51. package/typings.d.ts +174 -0
  52. package/typings.js +2 -0
@@ -0,0 +1,598 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SchemaGenerator = exports.SqlSchemaGenerator = void 0;
4
+ const core_1 = require("@yandjin-mikro-orm/core");
5
+ const DatabaseSchema_1 = require("./DatabaseSchema");
6
+ const SchemaComparator_1 = require("./SchemaComparator");
7
+ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
8
+ helper = this.platform.getSchemaHelper();
9
+ options = this.config.get("schemaGenerator");
10
+ lastEnsuredDatabase;
11
+ static register(orm) {
12
+ orm.config.registerExtension("@mikro-orm/schema-generator", () => new SqlSchemaGenerator(orm.em));
13
+ }
14
+ async createSchema(options) {
15
+ await this.ensureDatabase();
16
+ const sql = await this.getCreateSchemaSQL(options);
17
+ await this.execute(sql);
18
+ }
19
+ /**
20
+ * Returns true if the database was created.
21
+ */
22
+ async ensureDatabase(options) {
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();
34
+ await this.createDatabase(dbName);
35
+ this.config.set("dbName", dbName);
36
+ await this.driver.reconnect();
37
+ }
38
+ if (options?.create) {
39
+ await this.createSchema(options);
40
+ }
41
+ return true;
42
+ }
43
+ if (options?.clear) {
44
+ await this.clearDatabase(options);
45
+ }
46
+ return false;
47
+ }
48
+ getTargetSchema(schema) {
49
+ const metadataRootOrdered = this.getOrderedMetadata(schema);
50
+ const schemaName = schema ??
51
+ this.config.get("schema") ??
52
+ this.platform.getDefaultSchemaName();
53
+ const metadata = Object.values(this.metadata.getAll());
54
+ const metadataOrdered = metadataRootOrdered.reduce((prev, curr) => [
55
+ ...prev,
56
+ ...metadata.filter((m) => m.root.className === curr.className),
57
+ ], []);
58
+ return DatabaseSchema_1.DatabaseSchema.fromMetadata(metadataOrdered, this.platform, this.config, schemaName);
59
+ }
60
+ async getCreateSchemaSQL(options = {}) {
61
+ const wrap = options.wrap ?? this.options.disableForeignKeys;
62
+ const toSchema = this.getTargetSchema(options.schema);
63
+ let ret = "";
64
+ for (const namespace of toSchema.getNamespaces()) {
65
+ if (namespace === this.platform.getDefaultSchemaName()) {
66
+ continue;
67
+ }
68
+ ret += await this.dump(this.knex.schema.createSchemaIfNotExists(namespace));
69
+ }
70
+ for (const tableDef of toSchema.getTables()) {
71
+ ret += await this.dump(this.createTable(tableDef));
72
+ }
73
+ for (const tableDef of toSchema.getTables()) {
74
+ ret += await this.dump(this.createSchemaBuilder(tableDef.schema).alterTable(tableDef.name, (table) => this.createForeignKeys(table, tableDef, options.schema)));
75
+ }
76
+ return this.wrapSchema(ret, { wrap });
77
+ }
78
+ async dropSchema(options = {}) {
79
+ if (options.dropDb) {
80
+ const name = this.config.get("dbName");
81
+ return this.dropDatabase(name);
82
+ }
83
+ const sql = await this.getDropSchemaSQL(options);
84
+ await this.execute(sql);
85
+ }
86
+ async clearDatabase(options) {
87
+ // truncate by default, so no value is considered as true
88
+ /* istanbul ignore if */
89
+ if (options?.truncate === false) {
90
+ return super.clearDatabase(options);
91
+ }
92
+ await this.execute(this.helper.disableForeignKeysSQL());
93
+ for (const meta of this.getOrderedMetadata(options?.schema).reverse()) {
94
+ await this.driver
95
+ .createQueryBuilder(meta.className, this.em?.getTransactionContext(), "write", false)
96
+ .withSchema(options?.schema)
97
+ .truncate();
98
+ }
99
+ await this.execute(this.helper.enableForeignKeysSQL());
100
+ if (this.em) {
101
+ const allowGlobalContext = this.config.get("allowGlobalContext");
102
+ this.config.set("allowGlobalContext", true);
103
+ this.em.clear();
104
+ this.config.set("allowGlobalContext", allowGlobalContext);
105
+ }
106
+ }
107
+ async getDropSchemaSQL(options = {}) {
108
+ await this.ensureDatabase();
109
+ const wrap = options.wrap ?? this.options.disableForeignKeys;
110
+ const metadata = this.getOrderedMetadata(options.schema).reverse();
111
+ const schemas = this.getTargetSchema(options.schema).getNamespaces();
112
+ const schema = await DatabaseSchema_1.DatabaseSchema.create(this.connection, this.platform, this.config, options.schema, schemas);
113
+ let ret = "";
114
+ // remove FKs explicitly if we can't use cascading statement and we don't disable FK checks (we need this for circular relations)
115
+ for (const meta of metadata) {
116
+ const table = schema.getTable(meta.tableName);
117
+ if (!this.platform.usesCascadeStatement() && table && !wrap) {
118
+ for (const fk of Object.values(table.getForeignKeys())) {
119
+ const builder = this.createSchemaBuilder(table.schema).alterTable(table.name, (tbl) => {
120
+ tbl.dropForeign(fk.columnNames, fk.constraintName);
121
+ });
122
+ ret += await this.dump(builder, "\n");
123
+ }
124
+ }
125
+ }
126
+ for (const meta of metadata) {
127
+ ret += await this.dump(this.dropTable(meta.collection, this.getSchemaName(meta, options)), "\n");
128
+ }
129
+ if (this.platform.supportsNativeEnums()) {
130
+ for (const columnName of Object.keys(schema.getNativeEnums())) {
131
+ const sql = this.helper.getDropNativeEnumSQL(columnName, options.schema ?? this.config.get("schema"));
132
+ ret += await this.dump(this.knex.schema.raw(sql), "\n");
133
+ }
134
+ }
135
+ if (options.dropMigrationsTable) {
136
+ ret += await this.dump(this.dropTable(this.config.get("migrations").tableName, this.config.get("schema")), "\n");
137
+ }
138
+ return this.wrapSchema(ret + "\n", { wrap });
139
+ }
140
+ getSchemaName(meta, options) {
141
+ const schemaName = options.schema ?? this.config.get("schema");
142
+ /* istanbul ignore next */
143
+ return meta.schema && meta.schema === "*"
144
+ ? schemaName
145
+ : (meta.schema ?? schemaName);
146
+ }
147
+ async updateSchema(options = {}) {
148
+ const sql = await this.getUpdateSchemaSQL(options);
149
+ await this.execute(sql);
150
+ }
151
+ async getUpdateSchemaSQL(options = {}) {
152
+ await this.ensureDatabase();
153
+ const { fromSchema, toSchema } = await this.prepareSchemaForComparison(options);
154
+ const comparator = new SchemaComparator_1.SchemaComparator(this.platform);
155
+ const diffUp = comparator.compare(fromSchema, toSchema);
156
+ return this.diffToSQL(diffUp, options);
157
+ }
158
+ async getUpdateSchemaMigrationSQL(options = {}) {
159
+ if (!options.fromSchema) {
160
+ await this.ensureDatabase();
161
+ }
162
+ const { fromSchema, toSchema } = await this.prepareSchemaForComparison(options);
163
+ const comparator = new SchemaComparator_1.SchemaComparator(this.platform);
164
+ const diffUp = comparator.compare(fromSchema, toSchema);
165
+ const diffDown = comparator.compare(toSchema, fromSchema, diffUp);
166
+ return {
167
+ up: await this.diffToSQL(diffUp, options),
168
+ down: this.platform.supportsDownMigrations()
169
+ ? await this.diffToSQL(diffDown, options)
170
+ : "",
171
+ };
172
+ }
173
+ async prepareSchemaForComparison(options) {
174
+ options.wrap ??= this.options.disableForeignKeys;
175
+ options.safe ??= false;
176
+ options.dropTables ??= true;
177
+ const toSchema = this.getTargetSchema(options.schema);
178
+ const schemas = toSchema.getNamespaces();
179
+ const fromSchema = options.fromSchema ??
180
+ (await DatabaseSchema_1.DatabaseSchema.create(this.connection, this.platform, this.config, options.schema, schemas));
181
+ const wildcardSchemaTables = Object.values(this.metadata.getAll())
182
+ .filter((meta) => meta.schema === "*")
183
+ .map((meta) => meta.tableName);
184
+ fromSchema.prune(options.schema, wildcardSchemaTables);
185
+ toSchema.prune(options.schema, wildcardSchemaTables);
186
+ toSchema.setNativeEnums(fromSchema.getNativeEnums());
187
+ return { fromSchema, toSchema };
188
+ }
189
+ async diffToSQL(schemaDiff, options) {
190
+ let ret = "";
191
+ if (this.platform.supportsSchemas()) {
192
+ for (const newNamespace of schemaDiff.newNamespaces) {
193
+ // schema might already exist, e.g. explicit usage of `public` in postgres
194
+ ret += await this.dump(this.knex.schema.createSchemaIfNotExists(newNamespace));
195
+ }
196
+ }
197
+ if (!options.safe) {
198
+ for (const orphanedForeignKey of schemaDiff.orphanedForeignKeys) {
199
+ const [schemaName, tableName] = this.splitTableName(orphanedForeignKey.localTableName);
200
+ ret += await this.dump(this.createSchemaBuilder(schemaName).alterTable(tableName, (table) => {
201
+ return table.dropForeign(orphanedForeignKey.columnNames, orphanedForeignKey.constraintName);
202
+ }));
203
+ }
204
+ }
205
+ for (const newTable of Object.values(schemaDiff.newTables)) {
206
+ ret += await this.dump(this.createTable(newTable, true));
207
+ }
208
+ for (const newTable of Object.values(schemaDiff.newTables)) {
209
+ ret += await this.dump(this.createSchemaBuilder(newTable.schema).alterTable(newTable.name, (table) => {
210
+ this.createForeignKeys(table, newTable, options.schema);
211
+ }));
212
+ }
213
+ if (options.dropTables && !options.safe) {
214
+ for (const table of Object.values(schemaDiff.removedTables)) {
215
+ ret += await this.dump(this.dropTable(table.name, table.schema));
216
+ }
217
+ }
218
+ for (const changedTable of Object.values(schemaDiff.changedTables)) {
219
+ for (const builder of this.preAlterTable(changedTable, options.safe)) {
220
+ ret += await this.dump(builder);
221
+ }
222
+ }
223
+ for (const changedTable of Object.values(schemaDiff.changedTables)) {
224
+ for (const builder of this.alterTable(changedTable, options.safe)) {
225
+ ret += await this.dump(builder);
226
+ }
227
+ }
228
+ for (const changedTable of Object.values(schemaDiff.changedTables)) {
229
+ for (const builder of this.postAlterTable(changedTable, options.safe)) {
230
+ ret += await this.dump(builder);
231
+ }
232
+ }
233
+ if (options.dropTables && !options.safe) {
234
+ for (const removedNamespace of schemaDiff.removedNamespaces) {
235
+ ret += await this.dump(this.knex.schema.dropSchema(removedNamespace));
236
+ }
237
+ }
238
+ return this.wrapSchema(ret, options);
239
+ }
240
+ getReferencedTableName(referencedTableName, schema) {
241
+ const [schemaName, tableName] = this.splitTableName(referencedTableName);
242
+ schema = schemaName ?? schema ?? this.config.get("schema");
243
+ /* istanbul ignore next */
244
+ if (schema && schemaName === "*") {
245
+ return `${schema}.${referencedTableName.replace(/^\*\./, "")}`;
246
+ }
247
+ if (!schemaName || schemaName === this.platform.getDefaultSchemaName()) {
248
+ return tableName;
249
+ }
250
+ return `${schemaName}.${tableName}`;
251
+ }
252
+ createForeignKey(table, foreignKey, schema) {
253
+ if (!this.options.createForeignKeyConstraints) {
254
+ return;
255
+ }
256
+ const builder = table
257
+ .foreign(foreignKey.columnNames, foreignKey.constraintName)
258
+ .references(foreignKey.referencedColumnNames)
259
+ .inTable(this.getReferencedTableName(foreignKey.referencedTableName, schema))
260
+ .withKeyName(foreignKey.constraintName);
261
+ if (foreignKey.updateRule) {
262
+ builder.onUpdate(foreignKey.updateRule);
263
+ }
264
+ if (foreignKey.deleteRule) {
265
+ builder.onDelete(foreignKey.deleteRule);
266
+ }
267
+ }
268
+ /**
269
+ * We need to drop foreign keys first for all tables to allow dropping PK constraints.
270
+ */
271
+ preAlterTable(diff, safe) {
272
+ const ret = [];
273
+ const push = (sql) => sql ? ret.push(this.knex.schema.raw(sql)) : undefined;
274
+ push(this.helper.getPreAlterTable(diff, safe));
275
+ const [schemaName, tableName] = this.splitTableName(diff.name);
276
+ ret.push(this.createSchemaBuilder(schemaName).alterTable(tableName, (table) => {
277
+ for (const foreignKey of Object.values(diff.removedForeignKeys)) {
278
+ table.dropForeign(foreignKey.columnNames, foreignKey.constraintName);
279
+ }
280
+ for (const foreignKey of Object.values(diff.changedForeignKeys)) {
281
+ table.dropForeign(foreignKey.columnNames, foreignKey.constraintName);
282
+ }
283
+ }));
284
+ return ret;
285
+ }
286
+ postAlterTable(diff, safe) {
287
+ const ret = [];
288
+ const push = (sql) => sql ? ret.push(this.knex.schema.raw(sql)) : undefined;
289
+ push(this.helper.getPostAlterTable(diff, safe));
290
+ return ret;
291
+ }
292
+ splitTableName(name) {
293
+ const parts = name.split(".");
294
+ const tableName = parts.pop();
295
+ const schemaName = parts.pop();
296
+ return [schemaName, tableName];
297
+ }
298
+ alterTable(diff, safe) {
299
+ const ret = [];
300
+ const [schemaName, tableName] = this.splitTableName(diff.name);
301
+ if (this.platform.supportsNativeEnums()) {
302
+ const changedNativeEnums = [];
303
+ for (const { column, changedProperties } of Object.values(diff.changedColumns)) {
304
+ if (column.nativeEnumName &&
305
+ changedProperties.has("enumItems") &&
306
+ column.nativeEnumName in diff.fromTable.nativeEnums) {
307
+ changedNativeEnums.push([
308
+ column.nativeEnumName,
309
+ column.enumItems,
310
+ diff.fromTable.getColumn(column.name).enumItems,
311
+ ]);
312
+ }
313
+ }
314
+ core_1.Utils.removeDuplicates(changedNativeEnums).forEach(([enumName, itemsNew, itemsOld]) => {
315
+ // postgres allows only adding new items, the values are case insensitive
316
+ itemsOld = itemsOld.map((v) => v.toLowerCase());
317
+ const newItems = itemsNew.filter((val) => !itemsOld.includes(val.toLowerCase()));
318
+ ret.push(...newItems.map((val) => this.knex.schema.raw(this.helper.getAlterNativeEnumSQL(enumName, schemaName, val))));
319
+ });
320
+ }
321
+ ret.push(this.createSchemaBuilder(schemaName).alterTable(tableName, (table) => {
322
+ for (const index of Object.values(diff.removedIndexes)) {
323
+ this.dropIndex(table, index);
324
+ }
325
+ for (const index of Object.values(diff.changedIndexes)) {
326
+ this.dropIndex(table, index);
327
+ }
328
+ for (const check of Object.values(diff.removedChecks)) {
329
+ this.dropCheck(table, check);
330
+ }
331
+ for (const check of Object.values(diff.changedChecks)) {
332
+ this.dropCheck(table, check);
333
+ }
334
+ /* istanbul ignore else */
335
+ if (!safe) {
336
+ for (const column of Object.values(diff.removedColumns)) {
337
+ this.helper.pushTableQuery(table, `alter table ${this.platform.quoteIdentifier(tableName)} drop column ${this.platform.quoteIdentifier(column.name)}`);
338
+ }
339
+ }
340
+ }));
341
+ ret.push(this.createSchemaBuilder(schemaName).alterTable(tableName, (table) => {
342
+ for (const column of Object.values(diff.addedColumns)) {
343
+ const col = this.helper.createTableColumn(table, column, diff.fromTable, undefined, true);
344
+ this.helper.configureColumn(column, col, this.knex);
345
+ const foreignKey = Object.values(diff.addedForeignKeys).find((fk) => fk.columnNames.length === 1 && fk.columnNames[0] === column.name);
346
+ if (foreignKey && this.options.createForeignKeyConstraints) {
347
+ delete diff.addedForeignKeys[foreignKey.constraintName];
348
+ col
349
+ .references(foreignKey.referencedColumnNames[0])
350
+ .inTable(this.getReferencedTableName(foreignKey.referencedTableName))
351
+ .withKeyName(foreignKey.constraintName)
352
+ .onUpdate(foreignKey.updateRule)
353
+ .onDelete(foreignKey.deleteRule);
354
+ }
355
+ }
356
+ for (const { column, changedProperties } of Object.values(diff.changedColumns)) {
357
+ if (changedProperties.size === 1 &&
358
+ changedProperties.has("comment")) {
359
+ continue;
360
+ }
361
+ if (changedProperties.size === 1 &&
362
+ changedProperties.has("enumItems") &&
363
+ column.nativeEnumName) {
364
+ continue;
365
+ }
366
+ const col = this.helper
367
+ .createTableColumn(table, column, diff.fromTable, changedProperties, true)
368
+ .alter();
369
+ this.helper.configureColumn(column, col, this.knex, changedProperties);
370
+ }
371
+ for (const { column } of Object.values(diff.changedColumns).filter((diff) => diff.changedProperties.has("autoincrement"))) {
372
+ this.helper.pushTableQuery(table, this.helper.getAlterColumnAutoincrement(tableName, column, schemaName));
373
+ }
374
+ for (const { column, changedProperties } of Object.values(diff.changedColumns).filter((diff) => diff.changedProperties.has("comment"))) {
375
+ if ([
376
+ "type",
377
+ "nullable",
378
+ "autoincrement",
379
+ "unsigned",
380
+ "default",
381
+ "enumItems",
382
+ ].some((t) => changedProperties.has(t))) {
383
+ continue; // will be handled via knex
384
+ }
385
+ this.helper.pushTableQuery(table, this.helper.getChangeColumnCommentSQL(tableName, column, schemaName));
386
+ }
387
+ for (const [oldColumnName, column] of Object.entries(diff.renamedColumns)) {
388
+ this.helper.pushTableQuery(table, this.helper.getRenameColumnSQL(tableName, oldColumnName, column, schemaName));
389
+ }
390
+ for (const foreignKey of Object.values(diff.addedForeignKeys)) {
391
+ this.createForeignKey(table, foreignKey);
392
+ }
393
+ for (const foreignKey of Object.values(diff.changedForeignKeys)) {
394
+ this.createForeignKey(table, foreignKey);
395
+ }
396
+ for (const index of Object.values(diff.addedIndexes)) {
397
+ this.createIndex(table, index, diff.toTable);
398
+ }
399
+ for (const index of Object.values(diff.changedIndexes)) {
400
+ this.createIndex(table, index, diff.toTable, true);
401
+ }
402
+ for (const [oldIndexName, index] of Object.entries(diff.renamedIndexes)) {
403
+ if (index.unique) {
404
+ this.dropIndex(table, index, oldIndexName);
405
+ this.createIndex(table, index, diff.toTable);
406
+ }
407
+ else {
408
+ this.helper.pushTableQuery(table, this.helper.getRenameIndexSQL(diff.name, index, oldIndexName));
409
+ }
410
+ }
411
+ for (const check of Object.values(diff.addedChecks)) {
412
+ this.createCheck(table, check);
413
+ }
414
+ for (const check of Object.values(diff.changedChecks)) {
415
+ this.createCheck(table, check);
416
+ }
417
+ if ("changedComment" in diff) {
418
+ const comment = diff.changedComment
419
+ ? this.platform
420
+ .quoteValue(diff.changedComment)
421
+ .replace(/^'|'$/g, "")
422
+ : "";
423
+ table.comment(comment);
424
+ }
425
+ }));
426
+ return ret;
427
+ }
428
+ /**
429
+ * creates new database and connects to it
430
+ */
431
+ async createDatabase(name) {
432
+ const sql = this.helper.getCreateDatabaseSQL("" + this.knex.ref(name));
433
+ if (sql) {
434
+ await this.driver.execute(sql);
435
+ }
436
+ this.config.set("dbName", name);
437
+ await this.driver.reconnect();
438
+ }
439
+ async dropDatabase(name) {
440
+ name ??= this.config.get("dbName");
441
+ this.config.set("dbName", this.helper.getManagementDbName());
442
+ await this.driver.reconnect();
443
+ await this.driver.execute(this.helper.getDropDatabaseSQL("" + this.knex.ref(name)));
444
+ }
445
+ async execute(sql, options = {}) {
446
+ options.wrap ??= false;
447
+ const lines = this.wrapSchema(sql, options)
448
+ .split("\n")
449
+ .filter((i) => i.trim());
450
+ if (lines.length === 0) {
451
+ return;
452
+ }
453
+ if (this.platform.supportsMultipleStatements()) {
454
+ const query = lines.join("\n");
455
+ await this.driver.execute(query);
456
+ return;
457
+ }
458
+ await core_1.Utils.runSerial(lines, (line) => this.driver.execute(line));
459
+ }
460
+ wrapSchema(sql, options) {
461
+ options.wrap ??= this.options.disableForeignKeys;
462
+ if (!options.wrap || sql.trim() === "") {
463
+ return sql;
464
+ }
465
+ let ret = this.helper.getSchemaBeginning(this.config.get("charset"));
466
+ ret += sql;
467
+ ret += this.helper.getSchemaEnd();
468
+ return ret;
469
+ }
470
+ createSchemaBuilder(schema) {
471
+ const builder = this.knex.schema;
472
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
473
+ builder.withSchema(schema);
474
+ }
475
+ return builder;
476
+ }
477
+ createTable(tableDef, alter) {
478
+ return this.createSchemaBuilder(tableDef.schema).createTable(tableDef.name, (table) => {
479
+ tableDef.getColumns().forEach((column) => {
480
+ const col = this.helper.createTableColumn(table, column, tableDef, undefined, alter);
481
+ this.helper.configureColumn(column, col, this.knex);
482
+ });
483
+ for (const index of tableDef.getIndexes()) {
484
+ const createPrimary = !tableDef.getColumns().some((c) => c.autoincrement && c.primary) ||
485
+ this.helper.hasNonDefaultPrimaryKeyName(tableDef);
486
+ this.createIndex(table, index, tableDef, createPrimary);
487
+ }
488
+ for (const check of tableDef.getChecks()) {
489
+ this.createCheck(table, check);
490
+ }
491
+ if (tableDef.comment) {
492
+ const comment = this.platform
493
+ .quoteValue(tableDef.comment)
494
+ .replace(/^'|'$/g, "");
495
+ table.comment(comment);
496
+ }
497
+ if (!this.helper.supportsSchemaConstraints()) {
498
+ for (const fk of Object.values(tableDef.getForeignKeys())) {
499
+ this.createForeignKey(table, fk);
500
+ }
501
+ }
502
+ this.helper.finalizeTable(table, this.config.get("charset"), this.config.get("collate"));
503
+ });
504
+ }
505
+ createIndex(table, index, tableDef, createPrimary = false) {
506
+ if (index.primary && !createPrimary) {
507
+ return;
508
+ }
509
+ if (index.primary) {
510
+ const keyName = this.helper.hasNonDefaultPrimaryKeyName(tableDef)
511
+ ? index.keyName
512
+ : undefined;
513
+ table.primary(index.columnNames, keyName);
514
+ }
515
+ else if (index.unique) {
516
+ // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them
517
+ if (index.columnNames.some((column) => column.includes("."))) {
518
+ const columns = this.platform.getJsonIndexDefinition(index);
519
+ table.index(columns.map((column) => this.knex.raw(`(${column})`)), index.keyName, { indexType: "unique" });
520
+ }
521
+ else {
522
+ table.unique(index.columnNames, { indexName: index.keyName });
523
+ }
524
+ }
525
+ else if (index.expression) {
526
+ this.helper.pushTableQuery(table, index.expression);
527
+ }
528
+ else if (index.type === "fulltext") {
529
+ const columns = index.columnNames.map((name) => ({
530
+ name,
531
+ type: tableDef.getColumn(name).type,
532
+ }));
533
+ if (this.platform.supportsCreatingFullTextIndex()) {
534
+ this.helper.pushTableQuery(table, this.platform.getFullTextIndexExpression(index.keyName, tableDef.schema, tableDef.name, columns));
535
+ }
536
+ }
537
+ else {
538
+ // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them
539
+ if (index.columnNames.some((column) => column.includes("."))) {
540
+ const columns = this.platform.getJsonIndexDefinition(index);
541
+ table.index(columns.map((column) => this.knex.raw(`(${column})`)), index.keyName, index.type);
542
+ }
543
+ else {
544
+ table.index(index.columnNames, index.keyName, index.type);
545
+ }
546
+ }
547
+ }
548
+ dropIndex(table, index, oldIndexName = index.keyName) {
549
+ if (index.primary) {
550
+ table.dropPrimary(oldIndexName);
551
+ }
552
+ else if (index.unique && index.constraint) {
553
+ table.dropUnique(index.columnNames, oldIndexName);
554
+ }
555
+ else {
556
+ table.dropIndex(index.columnNames, oldIndexName);
557
+ }
558
+ }
559
+ createCheck(table, check) {
560
+ table.check(check.expression, {}, check.name);
561
+ }
562
+ dropCheck(table, check) {
563
+ table.dropChecks(check.name);
564
+ }
565
+ dropTable(name, schema) {
566
+ let builder = this.createSchemaBuilder(schema).dropTableIfExists(name);
567
+ if (this.platform.usesCascadeStatement()) {
568
+ builder = this.knex.schema.raw(builder.toQuery() + " cascade");
569
+ }
570
+ return builder;
571
+ }
572
+ createForeignKeys(table, tableDef, schema) {
573
+ if (!this.helper.supportsSchemaConstraints()) {
574
+ return;
575
+ }
576
+ for (const fk of Object.values(tableDef.getForeignKeys())) {
577
+ this.createForeignKey(table, fk, schema);
578
+ }
579
+ }
580
+ async dump(builder, append = "\n\n") {
581
+ const sql = await builder.generateDdlCommands();
582
+ const queries = [...sql.pre, ...sql.sql, ...sql.post];
583
+ if (queries.length === 0) {
584
+ return "";
585
+ }
586
+ const dump = `${queries.map((q) => (typeof q === "object" ? q.sql : q)).join(";\n")};${append}`;
587
+ const tmp = dump
588
+ .replace(/pragma table_.+/gi, "")
589
+ .replace(/\n\n+/g, "\n")
590
+ .trim();
591
+ return tmp ? tmp + append : "";
592
+ }
593
+ get knex() {
594
+ return this.connection.getKnex();
595
+ }
596
+ }
597
+ exports.SqlSchemaGenerator = SqlSchemaGenerator;
598
+ exports.SchemaGenerator = SqlSchemaGenerator;
@@ -0,0 +1,5 @@
1
+ export * from './DatabaseSchema';
2
+ export * from './DatabaseTable';
3
+ export * from './SqlSchemaGenerator';
4
+ export * from './SchemaHelper';
5
+ export * from './SchemaComparator';
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./DatabaseSchema"), exports);
18
+ __exportStar(require("./DatabaseTable"), exports);
19
+ __exportStar(require("./SqlSchemaGenerator"), exports);
20
+ __exportStar(require("./SchemaHelper"), exports);
21
+ __exportStar(require("./SchemaComparator"), exports);