uql-orm 0.97.0 → 0.99.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dialect/abstractSqlDialect.d.ts +1 -7
- package/dist/dialect/abstractSqlDialect.js +1 -9
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -0
- package/dist/dialect/mysqlLikeSqlDialect.js +4 -1
- package/dist/dialect/pgLikeSqlDialect.js +0 -1
- package/dist/migrate/acquireQuerierForMigrations.d.ts +4 -8
- package/dist/migrate/acquireQuerierForMigrations.js +10 -18
- package/dist/migrate/builder/columnBuilder.d.ts +1 -2
- package/dist/migrate/builder/columnBuilder.js +3 -10
- package/dist/migrate/builder/migrationBuilder.d.ts +6 -26
- package/dist/migrate/builder/migrationBuilder.js +21 -78
- package/dist/migrate/builder/tableBuilder.js +2 -3
- package/dist/migrate/builder/types.d.ts +57 -120
- package/dist/migrate/cli-config.d.ts +1 -0
- package/dist/migrate/cli-config.js +11 -26
- package/dist/migrate/cli.d.ts +0 -13
- package/dist/migrate/cli.js +55 -118
- package/dist/migrate/codegen/entityCodeGenerator.d.ts +7 -61
- package/dist/migrate/codegen/entityCodeGenerator.js +51 -168
- package/dist/migrate/codegen/fieldOptionsSource.js +3 -6
- package/dist/migrate/codegen/index.d.ts +2 -7
- package/dist/migrate/codegen/index.js +2 -8
- package/dist/migrate/codegen/migrationFile.d.ts +1 -8
- package/dist/migrate/codegen/migrationFile.js +9 -13
- package/dist/migrate/ddl/defaultSql.d.ts +2 -1
- package/dist/migrate/ddl/defaultSql.js +1 -3
- package/dist/migrate/ddl/indexCapabilities.d.ts +18 -0
- package/dist/migrate/ddl/indexCapabilities.js +60 -0
- package/dist/migrate/ddl/indexDdl.d.ts +11 -24
- package/dist/migrate/ddl/indexDdl.js +22 -28
- package/dist/migrate/ddl/mssqlIndexDdl.d.ts +1 -7
- package/dist/migrate/ddl/mssqlIndexDdl.js +1 -7
- package/dist/migrate/ddl/mssqlTableDdl.d.ts +6 -9
- package/dist/migrate/ddl/mssqlTableDdl.js +14 -17
- package/dist/migrate/ddl/mysqlIndexDdl.d.ts +0 -21
- package/dist/migrate/ddl/mysqlIndexDdl.js +4 -48
- package/dist/migrate/ddl/mysqlTableDdl.d.ts +6 -5
- package/dist/migrate/ddl/mysqlTableDdl.js +15 -10
- package/dist/migrate/ddl/pgIndexDdl.d.ts +0 -10
- package/dist/migrate/ddl/pgIndexDdl.js +5 -44
- package/dist/migrate/ddl/pgTableDdl.d.ts +6 -2
- package/dist/migrate/ddl/pgTableDdl.js +17 -1
- package/dist/migrate/ddl/sqliteIndexDdl.js +2 -7
- package/dist/migrate/ddl/tableDdl.d.ts +43 -24
- package/dist/migrate/ddl/tableDdl.js +56 -37
- package/dist/migrate/ddl/tableRebuild.d.ts +2 -1
- package/dist/migrate/drift/driftDetector.d.ts +29 -32
- package/dist/migrate/drift/driftDetector.js +139 -205
- package/dist/migrate/drift/index.d.ts +1 -6
- package/dist/migrate/drift/index.js +1 -6
- package/dist/migrate/generator/definitionToNode.js +3 -3
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +53 -76
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +68 -90
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +8 -43
- package/dist/migrate/introspection/mssqlIntrospector.js +44 -77
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -38
- package/dist/migrate/introspection/mysqlIntrospector.js +48 -57
- package/dist/migrate/introspection/postgresIntrospector.d.ts +12 -60
- package/dist/migrate/introspection/postgresIntrospector.js +62 -77
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +14 -53
- package/dist/migrate/introspection/sqliteIntrospector.js +59 -119
- package/dist/migrate/introspection/tableSchemaAST.d.ts +13 -0
- package/dist/migrate/introspection/tableSchemaAST.js +85 -0
- package/dist/migrate/migrationTarget.js +10 -2
- package/dist/migrate/migrator.d.ts +14 -37
- package/dist/migrate/migrator.js +89 -126
- package/dist/migrate/schemaChange.d.ts +0 -2
- package/dist/migrate/schemaChange.js +1 -1
- package/dist/migrate/schemaGenerator.d.ts +22 -97
- package/dist/migrate/schemaGenerator.js +113 -298
- package/dist/migrate/storage/databaseStorage.d.ts +2 -1
- package/dist/migrate/storage/databaseStorage.js +3 -2
- package/dist/migrate/storage/jsonStorage.d.ts +1 -2
- package/dist/migrate/storage/jsonStorage.js +11 -20
- package/dist/migrate/triggerSql.d.ts +3 -3
- package/dist/migrate/triggerSql.js +5 -4
- package/dist/mongo/index.d.ts +0 -1
- package/dist/mongo/index.js +0 -1
- package/dist/mongo/mongoDialect.js +0 -1
- package/dist/mongo/mongoIntrospector.d.ts +0 -3
- package/dist/mongo/mongoIntrospector.js +7 -14
- package/dist/mongo/mongoSchemaGenerator.d.ts +7 -20
- package/dist/mongo/mongoSchemaGenerator.js +51 -70
- package/dist/mssql/mssqlDialect.js +0 -1
- package/dist/schema/canonicalType.d.ts +15 -19
- package/dist/schema/canonicalType.js +20 -43
- package/dist/schema/dependencyGraph.d.ts +2 -3
- package/dist/schema/dependencyGraph.js +0 -4
- package/dist/schema/indexDifferences.js +2 -2
- package/dist/schema/schemaAST.d.ts +1 -1
- package/dist/schema/schemaAST.js +4 -12
- package/dist/schema/schemaASTBuilder.d.ts +2 -5
- package/dist/schema/schemaASTBuilder.js +11 -14
- package/dist/schema/schemaASTDiffer.d.ts +4 -5
- package/dist/schema/schemaASTDiffer.js +22 -70
- package/dist/schema/types.d.ts +1 -48
- package/dist/sqlite/localSqliteQuerierPool.d.ts +16 -2
- package/dist/sqlite/localSqliteQuerierPool.js +20 -4
- package/dist/sqlite/nodeSqliteQuerierPool.js +2 -2
- package/dist/sqlite/sqliteDialect.js +0 -1
- package/dist/sqlite/sqliteQuerierPool.js +3 -3
- package/dist/type/dialect.d.ts +0 -2
- package/dist/type/migration.d.ts +3 -54
- package/dist/util/ddlExpression.util.d.ts +2 -2
- package/dist/util/ddlExpression.util.js +3 -3
- package/dist/util/sql.util.d.ts +0 -8
- package/dist/util/sql.util.js +7 -12
- package/package.json +1 -1
- package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -36
- package/dist/migrate/introspection/baseSqlIntrospector.js +0 -133
- package/dist/schema/index.d.ts +0 -2
- package/dist/schema/index.js +0 -1
- package/dist/sqlite/sqlitePragmas.d.ts +0 -3
- package/dist/sqlite/sqlitePragmas.js +0 -15
package/dist/migrate/migrator.js
CHANGED
|
@@ -2,7 +2,7 @@ import { mkdir, readdir, writeFile } from 'node:fs/promises';
|
|
|
2
2
|
import { basename, extname, join } from 'node:path';
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
4
|
import { getEntities, getMeta } from '../entity/index.js';
|
|
5
|
-
import { SchemaAST } from '../schema/
|
|
5
|
+
import { SchemaAST } from '../schema/schemaAST.js';
|
|
6
6
|
import { columnRenames, tableRenameCandidates } from '../schema/schemaASTDiffer.js';
|
|
7
7
|
import { definedEntries, isRecord, LoggerWrapper } from '../util/index.js';
|
|
8
8
|
import { isOwnedName, qualifyName } from '../util/sql.util.js';
|
|
@@ -45,27 +45,18 @@ export class Migrator {
|
|
|
45
45
|
return this.schemaGenerator;
|
|
46
46
|
}
|
|
47
47
|
/**
|
|
48
|
-
*
|
|
48
|
+
* The migration files by name, the names the storage records as run, and those on disk it does not, all in
|
|
49
|
+
* name order. Read from names alone: a file is imported only when it is about to run.
|
|
49
50
|
*/
|
|
50
|
-
async
|
|
51
|
-
const files = await this.
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (migration) {
|
|
56
|
-
migrations.push(migration);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
// Sort by name (which typically includes timestamp)
|
|
60
|
-
return migrations.sort((a, b) => a.name.localeCompare(b.name));
|
|
51
|
+
async journal() {
|
|
52
|
+
const [files, recorded] = await Promise.all([this.migrationFiles(), this.storage.executed()]);
|
|
53
|
+
const executed = recorded.toSorted();
|
|
54
|
+
const ran = new Set(executed);
|
|
55
|
+
return { files, executed, pending: [...files.keys()].sort().filter((name) => !ran.has(name)) };
|
|
61
56
|
}
|
|
62
|
-
/**
|
|
63
|
-
* Get list of pending migrations (not yet executed)
|
|
64
|
-
*/
|
|
57
|
+
/** The names of the migrations not yet run, in the order `up` runs them. */
|
|
65
58
|
async pending() {
|
|
66
|
-
|
|
67
|
-
const executedSet = new Set(executed);
|
|
68
|
-
return migrations.filter((m) => !executedSet.has(m.name));
|
|
59
|
+
return (await this.journal()).pending;
|
|
69
60
|
}
|
|
70
61
|
/**
|
|
71
62
|
* Get list of executed migrations
|
|
@@ -77,22 +68,24 @@ export class Migrator {
|
|
|
77
68
|
* Run all pending migrations
|
|
78
69
|
*/
|
|
79
70
|
async up(options = {}) {
|
|
80
|
-
|
|
71
|
+
const { files, pending } = await this.journal();
|
|
72
|
+
return this.runInOrder(files, pending, 'up', options);
|
|
81
73
|
}
|
|
82
74
|
/**
|
|
83
75
|
* Rollback migrations
|
|
84
76
|
*/
|
|
85
77
|
async down(options = {}) {
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
78
|
+
const { files, executed } = await this.journal();
|
|
79
|
+
return this.runInOrder(files, executed.reverse(), 'down', options);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Runs the names narrowed by `to`/`step`, stopping at the first failure: `up` over the pending, `down` over
|
|
83
|
+
* the executed reversed. Every one is loaded before any runs, so a file that cannot be leaves the database as it was.
|
|
84
|
+
*/
|
|
85
|
+
async runInOrder(files, names, direction, options) {
|
|
86
|
+
let selected = names;
|
|
94
87
|
if (options.to) {
|
|
95
|
-
const toIndex = selected.
|
|
88
|
+
const toIndex = selected.indexOf(options.to);
|
|
96
89
|
if (toIndex === -1) {
|
|
97
90
|
throw new UqlUsageError(`Migration '${options.to}' not found`);
|
|
98
91
|
}
|
|
@@ -101,8 +94,9 @@ export class Migrator {
|
|
|
101
94
|
if (options.step !== undefined) {
|
|
102
95
|
selected = selected.slice(0, options.step);
|
|
103
96
|
}
|
|
97
|
+
const migrations = await Promise.all(selected.map((name) => this.loadMigration(name, files.get(name))));
|
|
104
98
|
const results = [];
|
|
105
|
-
for (const migration of
|
|
99
|
+
for (const migration of migrations) {
|
|
106
100
|
const result = await this.runMigration(migration, direction);
|
|
107
101
|
results.push(result);
|
|
108
102
|
if (!result.success) {
|
|
@@ -117,6 +111,13 @@ export class Migrator {
|
|
|
117
111
|
*/
|
|
118
112
|
async runMigration(migration, direction) {
|
|
119
113
|
const startTime = Date.now();
|
|
114
|
+
const finished = (error) => ({
|
|
115
|
+
name: migration.name,
|
|
116
|
+
direction,
|
|
117
|
+
duration: Date.now() - startTime,
|
|
118
|
+
success: error === undefined,
|
|
119
|
+
...(error && { error }),
|
|
120
|
+
});
|
|
120
121
|
return this.target.withSession(async ({ querier, transaction }) => {
|
|
121
122
|
try {
|
|
122
123
|
this.logger.logMigration(`${direction === 'up' ? 'Running' : 'Reverting'} migration: ${migration.name}`);
|
|
@@ -131,25 +132,13 @@ export class Migrator {
|
|
|
131
132
|
}
|
|
132
133
|
};
|
|
133
134
|
await (migration.transaction === false ? work() : transaction(work));
|
|
134
|
-
const
|
|
135
|
-
this.logger.logMigration(`Migration ${migration.name} ${direction === 'up' ? 'applied' : 'reverted'} in ${duration}ms`);
|
|
136
|
-
return
|
|
137
|
-
name: migration.name,
|
|
138
|
-
direction,
|
|
139
|
-
duration,
|
|
140
|
-
success: true,
|
|
141
|
-
};
|
|
135
|
+
const result = finished();
|
|
136
|
+
this.logger.logMigration(`Migration ${migration.name} ${direction === 'up' ? 'applied' : 'reverted'} in ${result.duration}ms`);
|
|
137
|
+
return result;
|
|
142
138
|
}
|
|
143
139
|
catch (error) {
|
|
144
|
-
const duration = Date.now() - startTime;
|
|
145
140
|
this.logger.logError(`Migration ${migration.name} failed: ${error.message}`, error);
|
|
146
|
-
return
|
|
147
|
-
name: migration.name,
|
|
148
|
-
direction,
|
|
149
|
-
duration,
|
|
150
|
-
success: false,
|
|
151
|
-
error: error,
|
|
152
|
-
};
|
|
141
|
+
return finished(error);
|
|
153
142
|
}
|
|
154
143
|
});
|
|
155
144
|
}
|
|
@@ -164,7 +153,7 @@ export class Migrator {
|
|
|
164
153
|
}
|
|
165
154
|
/** Writes a migration module on this dialect's querier to a new timestamped file, and returns its path. */
|
|
166
155
|
async writeMigration(name, body) {
|
|
167
|
-
const filePath = join(this.migrationsPath, `${
|
|
156
|
+
const filePath = join(this.migrationsPath, `${timestamp()}_${slugify(name)}.ts`);
|
|
168
157
|
const content = buildMigrationModule({
|
|
169
158
|
migrationName: name,
|
|
170
159
|
createdAt: new Date(),
|
|
@@ -294,7 +283,7 @@ export class Migrator {
|
|
|
294
283
|
this.noteForeignChecks(desiredAst, ast);
|
|
295
284
|
}
|
|
296
285
|
return this.entities.flatMap((entity) => {
|
|
297
|
-
const tableName =
|
|
286
|
+
const tableName = this.tableOf(entity);
|
|
298
287
|
const diff = generator.diffSchema(entity, ast.getTable(tableName), desiredAst, renames.get(tableName));
|
|
299
288
|
return diff ? [diff] : [];
|
|
300
289
|
});
|
|
@@ -355,7 +344,7 @@ export class Migrator {
|
|
|
355
344
|
const meta = getMeta(entity);
|
|
356
345
|
const { dialect } = this.pool;
|
|
357
346
|
const introspector = this.schemaIntrospectorFor(dialect.resolveSchema(meta));
|
|
358
|
-
const tableName =
|
|
347
|
+
const tableName = this.tableOf(entity);
|
|
359
348
|
if (!(await introspector.tableExists(dialect.resolveTableAlias(meta)))) {
|
|
360
349
|
// Spanning the whole set, so a foreign key resolves against the tables it points at, and always
|
|
361
350
|
// including this entity: `only` is what keeps the statements to this table.
|
|
@@ -363,16 +352,10 @@ export class Migrator {
|
|
|
363
352
|
}
|
|
364
353
|
// With the tables it references, which its foreign keys resolve against.
|
|
365
354
|
const ast = await this.introspectEntities([entity, ...referencedEntities(meta)]);
|
|
366
|
-
const
|
|
355
|
+
const diff = generator.diffSchema(entity, ast.getTable(tableName), generator.buildAST?.(this.entitiesWith(entity)));
|
|
356
|
+
const altered = diff?.type === 'alter' ? [this.filterDiff(diff, options)] : [];
|
|
367
357
|
await this.assertFillable(altered);
|
|
368
|
-
return altered.flatMap((
|
|
369
|
-
}
|
|
370
|
-
/** The diff for one entity against the table it already has, and none where the two agree. */
|
|
371
|
-
alterFromEntity(generator, entity, table, options) {
|
|
372
|
-
// Spanning the set for the reason `planEntity` spells out: a foreign key needs the table it
|
|
373
|
-
// points at, which a sync of one entity outside the configured list would not otherwise have.
|
|
374
|
-
const diff = generator.diffSchema(entity, table, generator.buildAST?.(this.entitiesWith(entity)));
|
|
375
|
-
return diff?.type === 'alter' ? [this.filterDiff(diff, options)] : [];
|
|
358
|
+
return altered.flatMap((change) => generator.generateAlterTable(change));
|
|
376
359
|
}
|
|
377
360
|
/** The configured entities, with `entity` among them however the migrator was built. */
|
|
378
361
|
entitiesWith(entity) {
|
|
@@ -479,88 +462,68 @@ export class Migrator {
|
|
|
479
462
|
* Get migration status
|
|
480
463
|
*/
|
|
481
464
|
async status() {
|
|
482
|
-
const
|
|
465
|
+
const { pending, executed } = await this.journal();
|
|
483
466
|
return { pending, executed };
|
|
484
467
|
}
|
|
485
|
-
/**
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
async getMigrationFiles() {
|
|
468
|
+
/** The migration files in the migrations directory, by the name each runs as; none where it is missing. */
|
|
469
|
+
async migrationFiles() {
|
|
470
|
+
let entries;
|
|
489
471
|
try {
|
|
490
|
-
|
|
491
|
-
return files
|
|
492
|
-
.filter((f) => /\.(ts|js|mjs)$/.test(f))
|
|
493
|
-
.filter((f) => !f.endsWith('.d.ts'))
|
|
494
|
-
.sort();
|
|
472
|
+
entries = await readdir(this.migrationsPath);
|
|
495
473
|
}
|
|
496
474
|
catch (error) {
|
|
497
475
|
if (error.code === 'ENOENT') {
|
|
498
|
-
return
|
|
476
|
+
return new Map();
|
|
499
477
|
}
|
|
500
478
|
throw error;
|
|
501
479
|
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
const fileUrl = pathToFileURL(filePath).href;
|
|
509
|
-
try {
|
|
510
|
-
const module = await import(fileUrl);
|
|
511
|
-
const migration = module.default ?? module;
|
|
512
|
-
if (this.isMigration(migration)) {
|
|
513
|
-
return {
|
|
514
|
-
name: this.getMigrationName(fileName),
|
|
515
|
-
up: migration.up.bind(migration),
|
|
516
|
-
down: migration.down.bind(migration),
|
|
517
|
-
transaction: migration.transaction,
|
|
518
|
-
};
|
|
480
|
+
const files = new Map();
|
|
481
|
+
for (const file of entries.filter((entry) => /\.(ts|js|mjs)$/.test(entry) && !entry.endsWith('.d.ts'))) {
|
|
482
|
+
const name = basename(file, extname(file));
|
|
483
|
+
const other = files.get(name);
|
|
484
|
+
if (other) {
|
|
485
|
+
throw new UqlUsageError(`Migrations ${other} and ${file} share the name '${name}'`);
|
|
519
486
|
}
|
|
520
|
-
|
|
521
|
-
return undefined;
|
|
522
|
-
}
|
|
523
|
-
catch (error) {
|
|
524
|
-
this.logger.logError(`Error loading migration ${fileName}: ${error.message}`, error);
|
|
525
|
-
return undefined;
|
|
487
|
+
files.set(name, file);
|
|
526
488
|
}
|
|
489
|
+
return files;
|
|
527
490
|
}
|
|
528
|
-
/**
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
now.getFullYear(),
|
|
547
|
-
String(now.getMonth() + 1).padStart(2, '0'),
|
|
548
|
-
String(now.getDate()).padStart(2, '0'),
|
|
549
|
-
String(now.getHours()).padStart(2, '0'),
|
|
550
|
-
String(now.getMinutes()).padStart(2, '0'),
|
|
551
|
-
String(now.getSeconds()).padStart(2, '0'),
|
|
552
|
-
].join('');
|
|
553
|
-
}
|
|
554
|
-
/**
|
|
555
|
-
* Convert a string to a slug for filenames
|
|
556
|
-
*/
|
|
557
|
-
slugify(text) {
|
|
558
|
-
return text
|
|
559
|
-
.toLowerCase()
|
|
560
|
-
.replace(/[^a-z0-9]+/g, '_')
|
|
561
|
-
.replace(/^_+|_+$/g, '');
|
|
491
|
+
/** The migration `name`, from its `file`: a missing file, one that fails to import, or one exporting no migration throws. */
|
|
492
|
+
async loadMigration(name, file) {
|
|
493
|
+
if (!file) {
|
|
494
|
+
throw new UqlUsageError(`Migration '${name}' is recorded as run but has no file in ${this.migrationsPath}`);
|
|
495
|
+
}
|
|
496
|
+
const module = await import(pathToFileURL(join(this.migrationsPath, file)).href).catch((error) => {
|
|
497
|
+
throw new UqlUsageError(`Migration ${file} failed to load: ${error.message}`, { cause: error });
|
|
498
|
+
});
|
|
499
|
+
const migration = module.default ?? module;
|
|
500
|
+
if (!isMigrationDefinition(migration)) {
|
|
501
|
+
throw new UqlUsageError(`Migration ${file} exports no migration: \`up\` and \`down\` functions, as its default export or its own`);
|
|
502
|
+
}
|
|
503
|
+
return {
|
|
504
|
+
name,
|
|
505
|
+
up: migration.up.bind(migration),
|
|
506
|
+
down: migration.down.bind(migration),
|
|
507
|
+
transaction: migration.transaction,
|
|
508
|
+
};
|
|
562
509
|
}
|
|
563
510
|
}
|
|
511
|
+
function isMigrationDefinition(value) {
|
|
512
|
+
return isRecord(value) && typeof value['up'] === 'function' && typeof value['down'] === 'function';
|
|
513
|
+
}
|
|
514
|
+
/** The local time a migration file is named by, `YYYYMMDDHHmmss`, so names sort in the order they were made. */
|
|
515
|
+
function timestamp() {
|
|
516
|
+
const now = new Date();
|
|
517
|
+
const parts = [now.getMonth() + 1, now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()];
|
|
518
|
+
return `${now.getFullYear()}${parts.map((part) => String(part).padStart(2, '0')).join('')}`;
|
|
519
|
+
}
|
|
520
|
+
/** `text` as a file name's part: lower case, each run of anything else an underscore. */
|
|
521
|
+
function slugify(text) {
|
|
522
|
+
return text
|
|
523
|
+
.toLowerCase()
|
|
524
|
+
.replace(/[^a-z0-9]+/g, '_')
|
|
525
|
+
.replace(/^_+|_+$/g, '');
|
|
526
|
+
}
|
|
564
527
|
/**
|
|
565
528
|
* Helper function to define a migration with proper typing
|
|
566
529
|
*/
|
|
@@ -20,8 +20,6 @@ export declare function needsRebuild(diff: SchemaDiff): boolean;
|
|
|
20
20
|
export declare function withoutRebuild(diff: SchemaDiff): SchemaDiff;
|
|
21
21
|
/** `items`, or nothing where it has none, so an empty change list is left off a diff. */
|
|
22
22
|
export declare function nonEmpty<T>(items: readonly T[]): readonly T[] | undefined;
|
|
23
|
-
/** `change` undone: an add becomes a drop, a drop an add, and an alter runs the other way. */
|
|
24
|
-
export declare function swap<T>({ from, to }: Change<T>): Change<T>;
|
|
25
23
|
/**
|
|
26
24
|
* `diff` undone: every change swapped, which is what a migration's `down` runs. Renames run before the adds
|
|
27
25
|
* either way, so a key, index or foreign key put back names a renamed column as the rename back leaves it.
|
|
@@ -49,7 +49,7 @@ export function nonEmpty(items) {
|
|
|
49
49
|
return items.length ? items : undefined;
|
|
50
50
|
}
|
|
51
51
|
/** `change` undone: an add becomes a drop, a drop an add, and an alter runs the other way. */
|
|
52
|
-
|
|
52
|
+
function swap({ from, to }) {
|
|
53
53
|
return { from: to, to: from };
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../dialect/index.js';
|
|
2
2
|
import type { SchemaAST } from '../schema/schemaAST.js';
|
|
3
|
-
import { type BuildSchemaASTOptions } from '../schema/schemaASTBuilder.js';
|
|
4
3
|
import { type DiffOptions } from '../schema/schemaASTDiffer.js';
|
|
5
|
-
import { type
|
|
6
|
-
import type {
|
|
7
|
-
import type { AnyMigrationOperation,
|
|
4
|
+
import { type ForeignKeyAction, type TableNode } from '../schema/types.js';
|
|
5
|
+
import type { CreateSchemaOptions, DropSchemaOptions, ForeignKeySchema, Rename, SchemaDiff, SchemaGenerator, Type } from '../type/index.js';
|
|
6
|
+
import type { AnyMigrationOperation, TableDefinition } from './builder/types.js';
|
|
8
7
|
import { type IndexDdl, type TableDdl } from './ddl/index.js';
|
|
9
|
-
/**
|
|
10
|
-
* Unified SQL schema generator.
|
|
11
|
-
* Parameterized by dialect to handle Postgres, MySQL, MariaDB, and SQLite.
|
|
12
|
-
*/
|
|
8
|
+
/** The SQL schema generator, one for every SQL engine, its spellings taken from the dialect and its DDL classes. */
|
|
13
9
|
export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
14
10
|
protected readonly dialect: AbstractSqlDialect;
|
|
15
11
|
protected readonly defaultForeignKeyAction: ForeignKeyAction;
|
|
@@ -18,25 +14,18 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
18
14
|
/** The `ALTER TABLE` statements this dialect spells its own way, the migrator's for the same reason. */
|
|
19
15
|
protected readonly tableDdl: TableDdl;
|
|
20
16
|
constructor(dialect: AbstractSqlDialect, defaultForeignKeyAction?: ForeignKeyAction);
|
|
21
|
-
get
|
|
22
|
-
get features(): DialectFeatures;
|
|
23
|
-
resolveTableName<E>(meta: EntityMeta<E>): string;
|
|
24
|
-
resolveTableAlias<E>(meta: EntityMeta<E>): string;
|
|
25
|
-
resolveSchema<E>(meta: EntityMeta<E>): string | undefined;
|
|
26
|
-
resolveColumnName(key: string, field: FieldOptions): string;
|
|
27
|
-
compileDdl(sql: EntityWhereMeta<object>, entity: Type<object>): string;
|
|
28
|
-
compileIndexPredicate(where: EntityWhereMeta<object>, entity: Type<object>, indexName: string): string;
|
|
17
|
+
private get features();
|
|
29
18
|
/** Escape an identifier (table name, column name, etc.) */
|
|
30
|
-
|
|
19
|
+
private escapeId;
|
|
20
|
+
/**
|
|
21
|
+
* The SQL type a column is spelled with: its canonical type, plus the engine's generated suffix on an
|
|
22
|
+
* auto-increment key, so a foreign key taking its type from the key gets the same one.
|
|
23
|
+
*/
|
|
24
|
+
private columnSqlType;
|
|
31
25
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
26
|
+
* The entity side as an AST, carrying this generator's default referential action. Named by the dialect's
|
|
27
|
+
* resolvers rather than a naming strategy, which would also rename an explicit `@Entity({ name })`.
|
|
34
28
|
*/
|
|
35
|
-
protected serialType(type: CanonicalType): string;
|
|
36
|
-
/** The SQL type a column is spelled with: the generated-key form for an auto-increment key, the canonical type otherwise. */
|
|
37
|
-
protected columnSqlType(col: Pick<ColumnNode, 'type' | 'isPrimaryKey' | 'isAutoIncrement'>): string;
|
|
38
|
-
protected canonicalTypeToSql(type: CanonicalType): string;
|
|
39
|
-
/** The entity side as an AST, carrying this generator's default referential action. */
|
|
40
29
|
buildAST(entities: readonly Type<object>[]): SchemaAST;
|
|
41
30
|
/**
|
|
42
31
|
* Every `CREATE TABLE` for `entities`, then their foreign keys, since a relation graph is routinely
|
|
@@ -48,7 +37,7 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
48
37
|
* the tables actually being created, so a narrowed `only` does not declare namespaces it is not
|
|
49
38
|
* about to fill. Empty on an engine without schemas, whose tables are never qualified.
|
|
50
39
|
*/
|
|
51
|
-
private
|
|
40
|
+
private createNamespaces;
|
|
52
41
|
/**
|
|
53
42
|
* The inverse of {@link generateCreateSchema}: a table's drop takes its triggers along, so only what they
|
|
54
43
|
* leave behind follows it.
|
|
@@ -60,7 +49,7 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
60
49
|
* resolves instead of being silently dropped.
|
|
61
50
|
*/
|
|
62
51
|
private orderedTables;
|
|
63
|
-
|
|
52
|
+
private dropTableSql;
|
|
64
53
|
/**
|
|
65
54
|
* The statements taking a table through `diff`, in the one order both directions need: whatever holds
|
|
66
55
|
* something down goes before it and comes back after it. A foreign key holds its columns and the key it
|
|
@@ -78,44 +67,13 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
78
67
|
* already there hold a null it has to replace, and it is the only value the entity says it may take.
|
|
79
68
|
*/
|
|
80
69
|
private defaultFills;
|
|
81
|
-
/** `ADD CONSTRAINT` for each of `foreignKeys`. */
|
|
82
|
-
private addForeignKeyStatements;
|
|
83
70
|
/** An index added to a table that may already have rows: its `CREATE`, then what the engine needs after. */
|
|
84
71
|
private addIndexStatements;
|
|
85
72
|
/**
|
|
86
|
-
* A column added to a table that exists
|
|
87
|
-
*
|
|
73
|
+
* A column added to a table that exists. `checks` go inline, which is the one way to constrain a table that is
|
|
74
|
+
* rebuilt to alter; a stored generated column, an engine that rebuilds tables takes only in a `CREATE TABLE`.
|
|
88
75
|
*/
|
|
89
76
|
private addColumnStatements;
|
|
90
|
-
generateCreateIndex(tableName: string, index: IndexSchema, options?: {
|
|
91
|
-
ifNotExists?: boolean;
|
|
92
|
-
}): string;
|
|
93
|
-
/**
|
|
94
|
-
* `schema` is the table's, because that is where its indexes live. MySQL takes it from the table
|
|
95
|
-
* operand instead, which is already qualified.
|
|
96
|
-
*/
|
|
97
|
-
generateDropIndex(tableName: string, indexName: string, schema?: string): string;
|
|
98
|
-
/**
|
|
99
|
-
* A column definition from a {@link ColumnSchema}, whose type is already the engine's spelling. Apart from
|
|
100
|
-
* {@link generateColumnFromNode}, which sizes a canonical type; both render through {@link renderColumn}.
|
|
101
|
-
*/
|
|
102
|
-
generateColumnDefinitionFromSchema(column: ColumnSchema): string;
|
|
103
|
-
/**
|
|
104
|
-
* The one place a column definition is spelled, so the `ColumnSchema` and `ColumnNode` paths cannot
|
|
105
|
-
* drift. A key column states `NOT NULL` rather than leave it to the key: SQLite lets a key column hold
|
|
106
|
-
* NULL otherwise, and SQL Server adds no key over a nullable column. Never `UNIQUE`: a unique column is
|
|
107
|
-
* a unique index, which the table creates beside it. Nor an enum's `CHECK`, which is the table's, named.
|
|
108
|
-
*/
|
|
109
|
-
private renderColumn;
|
|
110
|
-
/** The inline ` COMMENT '...'` a column declaration carries, where the engine takes one there. */
|
|
111
|
-
generateColumnComment(comment: string): string;
|
|
112
|
-
/** The `COMMENT ON` statements a table and its columns need, after the `CREATE TABLE`, where the engine uses them. */
|
|
113
|
-
protected generateCommentStatements(table: TableNode): string[];
|
|
114
|
-
/** The `COMMENT ON COLUMN` a column needs where the engine uses one, for `CREATE TABLE` and every path adding a column. */
|
|
115
|
-
protected generateColumnCommentStatement(tableName: string, column: {
|
|
116
|
-
name: string;
|
|
117
|
-
comment?: string;
|
|
118
|
-
}, schema?: string): string[];
|
|
119
77
|
/**
|
|
120
78
|
* How the entity differs from the table the database reported, compared by {@link diffTable}, the one
|
|
121
79
|
* drift detection runs, with types normalized as the engine stores them.
|
|
@@ -137,51 +95,23 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
137
95
|
generateCreateTableFromNode(table: TableNode, options?: {
|
|
138
96
|
ifNotExists?: boolean;
|
|
139
97
|
}): string[];
|
|
140
|
-
/**
|
|
141
|
-
|
|
142
|
-
* constraint, so a later `DROP` can name it.
|
|
143
|
-
*/
|
|
144
|
-
protected generateColumnFromNode(col: ColumnNode): string;
|
|
145
|
-
/**
|
|
146
|
-
* Generate CREATE INDEX SQL from an IndexNode.
|
|
147
|
-
* Delegates to `generateCreateIndex` for unified SQL assembly.
|
|
148
|
-
*/
|
|
149
|
-
generateCreateIndexFromNode(index: IndexNode, options?: {
|
|
150
|
-
ifNotExists: boolean;
|
|
151
|
-
}): string;
|
|
98
|
+
/** The `CREATE INDEX` for an index of the AST. */
|
|
99
|
+
private createIndexFromNode;
|
|
152
100
|
generateCreateTableFromDefinition(table: TableDefinition, options?: {
|
|
153
101
|
ifNotExists?: boolean;
|
|
154
102
|
}): string[];
|
|
155
|
-
generateRenameTableSql(oldName: string, newName: string): string;
|
|
156
103
|
/** `raw` is split, being the one SQL no generator wrote. */
|
|
157
104
|
generateOperation(operation: AnyMigrationOperation): string[];
|
|
158
105
|
/** `ADD COLUMN`, plus the foreign key and index the column declares, as `CREATE TABLE` lifts them. */
|
|
159
|
-
|
|
160
|
-
generateAlterColumnSql(tableName: string, columnName: string, column: FullColumnDefinition): string[];
|
|
161
|
-
generateDropColumnSql(tableName: string, columnName: string): string[];
|
|
162
|
-
generateRenameColumnSql(tableName: string, oldName: string, newName: string): string;
|
|
106
|
+
private addColumnSql;
|
|
163
107
|
/**
|
|
164
108
|
* `CONSTRAINT <name> FOREIGN KEY (...) REFERENCES ... ON DELETE ... ON UPDATE ...`.
|
|
165
109
|
*
|
|
166
110
|
* One spelling for the two places that need it - inline in a `CREATE TABLE`, and after `ADD` in an
|
|
167
111
|
* `ALTER`. Written twice, the two drifted over which end they qualified with a schema.
|
|
168
112
|
*/
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
generateDropForeignKeySql(tableName: string, constraintName: string): string;
|
|
172
|
-
/**
|
|
173
|
-
* `ALTER TABLE ... ADD CONSTRAINT <name> PRIMARY KEY (...)`, the other half of
|
|
174
|
-
* {@link generateDropPrimaryKeySql}. Refused where the engine cannot alter a key at all, by name,
|
|
175
|
-
* rather than emitting DDL it will reject.
|
|
176
|
-
*/
|
|
177
|
-
generateAddPrimaryKeySql(tableName: string, columns: readonly string[], name?: string): string;
|
|
178
|
-
/**
|
|
179
|
-
* Drops the table's key, by the name the constraint really has: introspected, or derived where this
|
|
180
|
-
* generator added it. MySQL takes no name.
|
|
181
|
-
*/
|
|
182
|
-
generateDropPrimaryKeySql(tableName: string, constraintName?: string): string;
|
|
183
|
-
/** A stored generated column, which an engine that rebuilds tables takes only in a `CREATE TABLE`. */
|
|
184
|
-
private assertColumnAddable;
|
|
113
|
+
private foreignKeyConstraint;
|
|
114
|
+
private addForeignKeySql;
|
|
185
115
|
/**
|
|
186
116
|
* Refuses `what` where the engine makes it only by rebuilding the table, which a migration generated
|
|
187
117
|
* from the entities does and a lone statement of the builder cannot.
|
|
@@ -193,8 +123,3 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
193
123
|
* Shared by the add and the drop so a `DROP CONSTRAINT` names exactly what an `ADD CONSTRAINT` made.
|
|
194
124
|
*/
|
|
195
125
|
export declare function constraintNameOf(tableName: string, foreignKey: ForeignKeySchema): string;
|
|
196
|
-
/**
|
|
197
|
-
* The entities as an AST, named by `generator`'s resolvers rather than a naming strategy, which would
|
|
198
|
-
* also rename an explicit `@Entity({ name })` and so compare each table under another name.
|
|
199
|
-
*/
|
|
200
|
-
export declare function buildEntityAST(generator: Pick<SchemaGenerator, 'resolveTableAlias' | 'resolveSchema' | 'resolveColumnName' | 'compileDdl' | 'compileIndexPredicate'>, entities: readonly Type<object>[], options?: Pick<BuildSchemaASTOptions, 'defaultForeignKeyAction' | 'textScoreIndexes' | 'vectorIndexRequiresNotNull' | 'renderTriggers'>): SchemaAST;
|