uql-orm 0.96.1 → 0.98.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 +59 -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 +53 -174
- package/dist/migrate/codegen/fieldOptionsSource.d.ts +1 -3
- package/dist/migrate/codegen/fieldOptionsSource.js +3 -11
- 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 +155 -205
- package/dist/migrate/drift/index.d.ts +1 -6
- package/dist/migrate/drift/index.js +1 -6
- package/dist/migrate/generator/definitionToNode.d.ts +2 -2
- package/dist/migrate/generator/definitionToNode.js +6 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +56 -77
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +75 -98
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +10 -43
- package/dist/migrate/introspection/mssqlIntrospector.js +52 -77
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +21 -37
- package/dist/migrate/introspection/mysqlIntrospector.js +75 -56
- package/dist/migrate/introspection/postgresIntrospector.d.ts +15 -60
- package/dist/migrate/introspection/postgresIntrospector.js +74 -77
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +19 -53
- package/dist/migrate/introspection/sqliteIntrospector.js +73 -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 +9 -44
- package/dist/migrate/migrator.js +72 -150
- package/dist/migrate/schemaChange.d.ts +8 -5
- package/dist/migrate/schemaChange.js +25 -8
- package/dist/migrate/schemaGenerator.d.ts +35 -109
- package/dist/migrate/schemaGenerator.js +179 -353
- 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 +7 -9
- package/dist/migrate/triggerSql.js +17 -18
- 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 +1 -6
- package/dist/mongo/mongoIntrospector.js +7 -18
- package/dist/mongo/mongoSchemaGenerator.d.ts +7 -26
- package/dist/mongo/mongoSchemaGenerator.js +51 -75
- 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 +5 -12
- package/dist/schema/schemaASTBuilder.d.ts +5 -6
- package/dist/schema/schemaASTBuilder.js +17 -18
- package/dist/schema/schemaASTDiffer.d.ts +4 -5
- package/dist/schema/schemaASTDiffer.js +40 -73
- package/dist/schema/types.d.ts +24 -54
- 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 +13 -73
- package/dist/util/ddlExpression.util.d.ts +13 -2
- package/dist/util/ddlExpression.util.js +27 -4
- package/dist/util/sql.util.d.ts +2 -12
- package/dist/util/sql.util.js +9 -18
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +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
|
@@ -1,25 +1,24 @@
|
|
|
1
1
|
import { getMeta } from '../entity/index.js';
|
|
2
2
|
import { canonicalToSql, engineType, isVectorCategory } from '../schema/canonicalType.js';
|
|
3
3
|
import { indexChanges } from '../schema/indexDifferences.js';
|
|
4
|
+
import { matchByKey } from '../schema/matchByKey.js';
|
|
4
5
|
import { buildSchemaAST } from '../schema/schemaASTBuilder.js';
|
|
5
6
|
import { diffRelationshipNodes, diffTable } from '../schema/schemaASTDiffer.js';
|
|
6
7
|
import { DEFAULT_FOREIGN_KEY_ACTION, } from '../schema/types.js';
|
|
8
|
+
import { enumCheck } from '../util/ddlExpression.util.js';
|
|
7
9
|
import { qualifyName } from '../util/index.js';
|
|
8
|
-
import {
|
|
10
|
+
import { derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName, splitQualifiedName } from '../util/sql.util.js';
|
|
9
11
|
import { splitSqlStatements } from './builder/splitSqlStatements.js';
|
|
10
12
|
import { formatDefaultValue, sameDefault } from './ddl/defaultSql.js';
|
|
11
13
|
import { indexDdlFor, tableDdlFor } from './ddl/index.js';
|
|
12
|
-
import { rebuildRefusal
|
|
14
|
+
import { rebuildRefusal } from './ddl/tableDdl.js';
|
|
13
15
|
import { rebuildTable } from './ddl/tableRebuild.js';
|
|
14
16
|
import { columnForeignKey, columnIndex, bareColumn, renderIndexDefinition, tableDefinitionToNode, } from './generator/definitionToNode.js';
|
|
15
17
|
import { indexNodeToSchema } from './generator/indexNodeToSchema.js';
|
|
16
18
|
import { assertIndexPredicate } from './indexPredicate.js';
|
|
17
19
|
import { added, alterations, dropped, needsRebuild, newlyRequired, nonEmpty, sides } from './schemaChange.js';
|
|
18
|
-
import { dropTrigger, renderTrigger, stampTriggers } from './triggerSql.js';
|
|
19
|
-
/**
|
|
20
|
-
* Unified SQL schema generator.
|
|
21
|
-
* Parameterized by dialect to handle Postgres, MySQL, MariaDB, and SQLite.
|
|
22
|
-
*/
|
|
20
|
+
import { dropTrigger, dropTriggerBody, renderTrigger, stampTriggers } from './triggerSql.js';
|
|
21
|
+
/** The SQL schema generator, one for every SQL engine, its spellings taken from the dialect and its DDL classes. */
|
|
23
22
|
export class SqlSchemaGenerator {
|
|
24
23
|
dialect;
|
|
25
24
|
defaultForeignKeyAction;
|
|
@@ -33,53 +32,39 @@ export class SqlSchemaGenerator {
|
|
|
33
32
|
this.indexDdl = indexDdlFor(dialect);
|
|
34
33
|
this.tableDdl = tableDdlFor(dialect);
|
|
35
34
|
}
|
|
36
|
-
get namingStrategy() {
|
|
37
|
-
return this.dialect.namingStrategy;
|
|
38
|
-
}
|
|
39
35
|
get features() {
|
|
40
36
|
return this.dialect.features;
|
|
41
37
|
}
|
|
42
|
-
resolveTableName(meta) {
|
|
43
|
-
return this.dialect.resolveTableName(meta);
|
|
44
|
-
}
|
|
45
|
-
resolveTableAlias(meta) {
|
|
46
|
-
return this.dialect.resolveTableAlias(meta);
|
|
47
|
-
}
|
|
48
|
-
resolveSchema(meta) {
|
|
49
|
-
return this.dialect.resolveSchema(meta);
|
|
50
|
-
}
|
|
51
|
-
resolveColumnName(key, field) {
|
|
52
|
-
return this.dialect.resolveColumnName(key, field);
|
|
53
|
-
}
|
|
54
|
-
compileDdl(sql, entity) {
|
|
55
|
-
return this.dialect.compileDdl(sql, entity);
|
|
56
|
-
}
|
|
57
|
-
compileIndexPredicate(where, entity, indexName) {
|
|
58
|
-
assertIndexPredicate(where, this.dialect.dialectName, indexName);
|
|
59
|
-
return this.dialect.compileDdl(where, entity);
|
|
60
|
-
}
|
|
61
38
|
/** Escape an identifier (table name, column name, etc.) */
|
|
62
39
|
escapeId(identifier) {
|
|
63
40
|
return this.dialect.escapeId(identifier);
|
|
64
41
|
}
|
|
65
42
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
43
|
+
* The SQL type a column is spelled with: its canonical type, plus the engine's generated suffix on an
|
|
44
|
+
* auto-increment key, so a foreign key taking its type from the key gets the same one.
|
|
68
45
|
*/
|
|
69
|
-
serialType(type) {
|
|
70
|
-
return `${this.canonicalTypeToSql(type)} ${this.dialect.autoIncrementSuffix}`;
|
|
71
|
-
}
|
|
72
|
-
/** The SQL type a column is spelled with: the generated-key form for an auto-increment key, the canonical type otherwise. */
|
|
73
46
|
columnSqlType(col) {
|
|
74
|
-
|
|
47
|
+
const type = canonicalToSql(col.type, this.dialect);
|
|
48
|
+
return col.isPrimaryKey && col.isAutoIncrement ? `${type} ${this.dialect.autoIncrementSuffix}` : type;
|
|
75
49
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
50
|
+
/**
|
|
51
|
+
* The entity side as an AST, carrying this generator's default referential action. Named by the dialect's
|
|
52
|
+
* resolvers rather than a naming strategy, which would also rename an explicit `@Entity({ name })`.
|
|
53
|
+
*/
|
|
80
54
|
buildAST(entities) {
|
|
81
|
-
|
|
55
|
+
const { dialect } = this;
|
|
56
|
+
return buildSchemaAST(entities, {
|
|
57
|
+
// The alias, not `resolveTableName`: a node holds its schema apart, so a name derived from it is one identifier.
|
|
58
|
+
resolveTableName: (meta) => dialect.resolveTableAlias(meta),
|
|
59
|
+
resolveSchema: (meta) => dialect.resolveSchema(meta),
|
|
60
|
+
resolveColumnName: (key, field) => dialect.resolveColumnName(key, field),
|
|
61
|
+
compileDdl: (sql, entity) => dialect.compileDdl(sql, entity),
|
|
62
|
+
compileIndexPredicate: (where, entity, indexName) => {
|
|
63
|
+
assertIndexPredicate(where, dialect.dialectName, indexName);
|
|
64
|
+
return dialect.compileDdl(where, entity);
|
|
65
|
+
},
|
|
82
66
|
defaultForeignKeyAction: this.defaultForeignKeyAction,
|
|
67
|
+
renderTriggers: (meta) => [...(meta.triggers ?? []), ...stampTriggers(this.dialect, meta)].map((trigger, i) => renderTrigger(this.dialect, meta, trigger, i)),
|
|
83
68
|
textScoreIndexes: this.dialect.features.textScoreIndexes,
|
|
84
69
|
vectorIndexRequiresNotNull: this.features.vectorIndexRequiresNotNull,
|
|
85
70
|
});
|
|
@@ -90,72 +75,34 @@ export class SqlSchemaGenerator {
|
|
|
90
75
|
*/
|
|
91
76
|
generateCreateSchema(entities, options = {}) {
|
|
92
77
|
const tables = this.orderedTables(entities, 'create', options.only);
|
|
93
|
-
// Inline only where a constraint cannot be added afterwards, which is what makes the cyclic case
|
|
94
|
-
// work everywhere else.
|
|
78
|
+
// Inline only where a constraint cannot be added afterwards, which is what makes the cyclic case work elsewhere.
|
|
95
79
|
const inline = this.features.rebuildsTables;
|
|
96
|
-
// Namespaces first: a qualified `CREATE TABLE` fails against a schema nobody created, and the
|
|
97
|
-
// schema is the one part of the layout a migration cannot infer from the table it is making.
|
|
98
|
-
const statements = this.generateCreateSchemas(tables);
|
|
99
|
-
statements.push(...tables.flatMap((table) => this.generateCreateTableFromNode(inline ? table : { ...table, outgoingRelations: [] }, options)));
|
|
100
|
-
if (!inline) {
|
|
101
|
-
for (const table of tables) {
|
|
102
|
-
statements.push(...this.addForeignKeyStatements(qualifyName(table.name, table.schema), table.outgoingRelations.map(foreignKeyOf)));
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
// Triggers last: each needs its own table, and a body may read any other the same schema just made.
|
|
106
|
-
const made = new Set(tables.map((table) => qualifyName(table.name, table.schema)));
|
|
107
|
-
statements.push(...entities
|
|
108
|
-
.filter((entity) => made.has(this.resolveTableName(getMeta(entity))))
|
|
109
|
-
.flatMap((entity) => this.generateTriggers(entity)));
|
|
110
|
-
return statements;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* The installed triggers on `entity`'s table it does not declare, and the declared ones not installed,
|
|
114
|
-
* compared by name alone: a name carries a hash of the trigger's SQL, so an edited one is a new name.
|
|
115
|
-
* Every trigger counts - the ones it authored, and one per event each stamp names.
|
|
116
|
-
*/
|
|
117
|
-
triggerChanges(entity, installed) {
|
|
118
|
-
const meta = getMeta(entity);
|
|
119
|
-
const triggers = [...(meta.triggers ?? []), ...stampTriggers(this.dialect, meta)];
|
|
120
|
-
const rendered = triggers.map((trigger, i) => renderTrigger(this.dialect, meta, trigger, i));
|
|
121
|
-
const declared = new Set(rendered.map((trigger) => trigger.name));
|
|
122
|
-
return {
|
|
123
|
-
stale: [...installed]
|
|
124
|
-
.filter(([name]) => isOwnedName(name) && !declared.has(name))
|
|
125
|
-
.map(([name, statements]) => ({ name, statements })),
|
|
126
|
-
missing: rendered.filter((trigger) => !installed.has(trigger.name)),
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
generateTriggers(entity, installed = new Map()) {
|
|
130
|
-
const { stale, missing } = this.triggerChanges(entity, installed);
|
|
131
|
-
return this.swapTriggers(entity, stale, missing);
|
|
132
|
-
}
|
|
133
|
-
generateTriggersDown(entity, installed = new Map()) {
|
|
134
|
-
const { stale, missing } = this.triggerChanges(entity, installed);
|
|
135
|
-
return this.swapTriggers(entity, missing, stale);
|
|
136
|
-
}
|
|
137
|
-
/** `dropped` taken off `entity`'s table and `created` put on, which is a reconcile read either way. */
|
|
138
|
-
swapTriggers(entity, dropped, created) {
|
|
139
80
|
return [
|
|
140
|
-
|
|
141
|
-
...
|
|
81
|
+
// Namespaces first: a qualified `CREATE TABLE` fails against a schema nobody created.
|
|
82
|
+
...this.createNamespaces(tables),
|
|
83
|
+
...tables.flatMap((table) => this.generateCreateTableFromNode(inline ? table : { ...table, outgoingRelations: [] }, options)),
|
|
84
|
+
...(inline
|
|
85
|
+
? []
|
|
86
|
+
: tables.flatMap((table) => table.outgoingRelations.map((relation) => this.addForeignKeySql(qualifyName(table.name, table.schema), foreignKeyOf(relation))))),
|
|
87
|
+
// Triggers last: each needs its own table, and a body may read any other the same schema just made.
|
|
88
|
+
...terminated(tables.flatMap((table) => table.triggers.flatMap((trigger) => trigger.statements))),
|
|
142
89
|
];
|
|
143
90
|
}
|
|
144
|
-
generateTriggerDrops(entity, names) {
|
|
145
|
-
const meta = getMeta(entity);
|
|
146
|
-
return names.filter(isOwnedName).flatMap((name) => dropTrigger(this.dialect, meta, name).map((sql) => `${sql};`));
|
|
147
|
-
}
|
|
148
91
|
/**
|
|
149
92
|
* One statement per distinct schema the tables being created live in, in first-seen order. Only
|
|
150
93
|
* the tables actually being created, so a narrowed `only` does not declare namespaces it is not
|
|
151
94
|
* about to fill. Empty on an engine without schemas, whose tables are never qualified.
|
|
152
95
|
*/
|
|
153
|
-
|
|
96
|
+
createNamespaces(tables) {
|
|
154
97
|
const named = tables.map((table) => table.schema).filter((it) => it !== undefined);
|
|
155
98
|
return [...new Set(named)].map((schema) => this.dialect.createSchemaSql(schema));
|
|
156
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* The inverse of {@link generateCreateSchema}: a table's drop takes its triggers along, so only what they
|
|
102
|
+
* leave behind follows it.
|
|
103
|
+
*/
|
|
157
104
|
generateDropSchema(entities, options = {}) {
|
|
158
|
-
const tables = this.orderedTables(entities, 'drop')
|
|
105
|
+
const tables = this.orderedTables(entities, 'drop');
|
|
159
106
|
// A `CASCADE` drop takes the foreign keys with it, and SQLite drops with its constraints off.
|
|
160
107
|
const cascades = options.cascade && this.features.dropTableCascade;
|
|
161
108
|
const existing = cascades || this.features.rebuildsTables ? [] : (options.existing?.getTables() ?? []);
|
|
@@ -165,9 +112,20 @@ export class SqlSchemaGenerator {
|
|
|
165
112
|
...table.outgoingRelations.map((relation) => relation.name),
|
|
166
113
|
...table.externalForeignKeys.map((foreignKey) => constraintNameOf(tableName, foreignKey)),
|
|
167
114
|
];
|
|
168
|
-
return names.map((name) => this.
|
|
115
|
+
return names.map((name) => this.tableDdl.dropForeignKey(tableName, name));
|
|
169
116
|
});
|
|
170
|
-
return [
|
|
117
|
+
return [
|
|
118
|
+
...foreignKeyDrops,
|
|
119
|
+
...tables.flatMap((table) => {
|
|
120
|
+
const name = qualifyName(table.name, table.schema);
|
|
121
|
+
// A table the database lacks left no function: CockroachDB refuses one named in a schema not made yet.
|
|
122
|
+
const triggers = options.existing && !options.existing.getTable(name) ? [] : table.triggers;
|
|
123
|
+
return [
|
|
124
|
+
this.dropTableSql(name, options),
|
|
125
|
+
...terminated(triggers.flatMap((trigger) => dropTriggerBody(this.dialect, table.schema, trigger.name))),
|
|
126
|
+
];
|
|
127
|
+
}),
|
|
128
|
+
];
|
|
171
129
|
}
|
|
172
130
|
/**
|
|
173
131
|
* The tables of `entities` in dependency order, optionally narrowed to `only`. The AST always spans
|
|
@@ -183,7 +141,7 @@ export class SqlSchemaGenerator {
|
|
|
183
141
|
const wanted = new Set(only);
|
|
184
142
|
return tables.filter((table) => wanted.has(qualifyName(table.name, table.schema)));
|
|
185
143
|
}
|
|
186
|
-
|
|
144
|
+
dropTableSql(tableName, options = {}) {
|
|
187
145
|
const ifExists = options.ifExists ? 'IF EXISTS ' : '';
|
|
188
146
|
const cascade = options.cascade && this.features.dropTableCascade ? ' CASCADE' : '';
|
|
189
147
|
return `DROP TABLE ${ifExists}${this.escapeId(tableName)}${cascade};`;
|
|
@@ -192,31 +150,56 @@ export class SqlSchemaGenerator {
|
|
|
192
150
|
* The statements taking a table through `diff`, in the one order both directions need: whatever holds
|
|
193
151
|
* something down goes before it and comes back after it. A foreign key holds its columns and the key it
|
|
194
152
|
* points at, so it goes first and comes back last; the key holds its columns; and some engines drop an
|
|
195
|
-
* index along with its column, which would leave nothing to name.
|
|
153
|
+
* index along with its column, which would leave nothing to name. A check holds the columns it names, which
|
|
154
|
+
* MySQL refuses to rename or drop under one. An alter is its drop, then its add.
|
|
196
155
|
*/
|
|
197
156
|
generateAlterTable(diff) {
|
|
198
|
-
const { tableName,
|
|
157
|
+
const { tableName, primaryKey, columns, rebuild } = diff;
|
|
199
158
|
const fills = this.defaultFills(columns);
|
|
159
|
+
const moved = Boolean(rebuild || diff.renamedColumns?.length || sides(columns, 'from').length);
|
|
160
|
+
const triggers = (diff.triggers ?? []).filter(({ from, to }) => moved || !from || !to);
|
|
161
|
+
const triggerDrops = terminated(sides(triggers, 'from').flatMap((trigger) => dropTrigger(this.dialect, tableName, trigger.name)));
|
|
162
|
+
const triggerCreates = terminated(sides(triggers, 'to').flatMap((trigger) => trigger.statements));
|
|
200
163
|
if (rebuild) {
|
|
201
|
-
return
|
|
164
|
+
return [
|
|
165
|
+
...triggerDrops,
|
|
166
|
+
...rebuildTable(this.dialect, tableName, rebuild, { renames: diff.renamedColumns ?? [], fills }),
|
|
167
|
+
...triggerCreates,
|
|
168
|
+
];
|
|
202
169
|
}
|
|
203
170
|
const target = this.escapeId(tableName);
|
|
171
|
+
const [dropKey, addKey] = this.tableDdl.replacePrimaryKey(tableName, primaryKey?.from, primaryKey?.to);
|
|
204
172
|
return [
|
|
205
|
-
...
|
|
206
|
-
...(
|
|
207
|
-
...
|
|
208
|
-
...
|
|
173
|
+
...triggerDrops,
|
|
174
|
+
...sides(diff.foreignKeys, 'from').map((foreignKey) => this.tableDdl.dropForeignKey(tableName, constraintNameOf(tableName, foreignKey))),
|
|
175
|
+
...dropKey,
|
|
176
|
+
...sides(diff.indexes, 'from').map((index) => this.tableDdl.dropIndex(tableName, index.name)),
|
|
177
|
+
...sides(diff.checks, 'from').map((check) => this.dropCheckSql(tableName, check)),
|
|
178
|
+
...(diff.renamedColumns ?? []).map(({ from, to }) => this.tableDdl.renameColumn(tableName, from, to)),
|
|
179
|
+
...added(columns).flatMap((column) => this.addColumnStatements(tableName, column)),
|
|
209
180
|
...[...fills].map(([column, value]) => {
|
|
210
181
|
const name = this.escapeId(column);
|
|
211
182
|
return `UPDATE ${target} SET ${name} = ${value} WHERE ${name} IS NULL;`;
|
|
212
183
|
}),
|
|
213
|
-
...this.tableDdl.alterColumns(tableName, alterations(columns)
|
|
184
|
+
...this.tableDdl.alterColumns(tableName, alterations(columns)),
|
|
185
|
+
...addKey,
|
|
214
186
|
...dropped(columns).flatMap((column) => this.tableDdl.dropColumn(tableName, column.name)),
|
|
215
187
|
...this.addIndexStatements(tableName, sides(diff.indexes, 'to')),
|
|
216
|
-
...(
|
|
217
|
-
...
|
|
188
|
+
...sides(diff.foreignKeys, 'to').map((foreignKey) => this.addForeignKeySql(tableName, foreignKey)),
|
|
189
|
+
...sides(diff.checks, 'to').map((check) => this.addCheckSql(tableName, check)),
|
|
190
|
+
...triggerCreates,
|
|
218
191
|
];
|
|
219
192
|
}
|
|
193
|
+
/** `CONSTRAINT <name> CHECK (...)`, in a `CREATE TABLE`, after `ADD`, or inline where a column brings it. */
|
|
194
|
+
checkConstraint(check) {
|
|
195
|
+
return `CONSTRAINT ${this.escapeId(check.name)} CHECK (${check.expression})`;
|
|
196
|
+
}
|
|
197
|
+
addCheckSql(tableName, check) {
|
|
198
|
+
return `ALTER TABLE ${this.escapeId(tableName)} ADD ${this.checkConstraint(check)};`;
|
|
199
|
+
}
|
|
200
|
+
dropCheckSql(tableName, check) {
|
|
201
|
+
return `ALTER TABLE ${this.escapeId(tableName)} DROP CONSTRAINT ${this.escapeId(check.name)};`;
|
|
202
|
+
}
|
|
220
203
|
/**
|
|
221
204
|
* Each column the changes make required while declaring a default, and that default as SQL: the rows
|
|
222
205
|
* already there hold a null it has to replace, and it is the only value the entity says it may take.
|
|
@@ -226,89 +209,23 @@ export class SqlSchemaGenerator {
|
|
|
226
209
|
.filter(({ from, to }) => from && to.defaultValue !== undefined)
|
|
227
210
|
.map(({ to }) => [to.name, formatDefaultValue(to.defaultValue, this.dialect, to.type)]));
|
|
228
211
|
}
|
|
229
|
-
/** `ADD CONSTRAINT` for each of `foreignKeys`. */
|
|
230
|
-
addForeignKeyStatements(tableName, foreignKeys) {
|
|
231
|
-
return foreignKeys.map((foreignKey) => this.generateAddForeignKeySql(tableName, foreignKey));
|
|
232
|
-
}
|
|
233
212
|
/** An index added to a table that may already have rows: its `CREATE`, then what the engine needs after. */
|
|
234
213
|
addIndexStatements(tableName, indexes) {
|
|
235
214
|
return indexes.flatMap((index) => [
|
|
236
|
-
this.
|
|
215
|
+
this.indexDdl.getCreateIndexStatement(tableName, index),
|
|
237
216
|
...this.indexDdl.settleStatements(tableName, index),
|
|
238
217
|
]);
|
|
239
218
|
}
|
|
240
|
-
/** A column added to a table that exists, and its comment where the engine keeps one apart. */
|
|
241
|
-
addColumnStatements(tableName, column, schema) {
|
|
242
|
-
this.assertColumnAddable(tableName, column);
|
|
243
|
-
return [
|
|
244
|
-
...this.tableDdl.addColumnStatements(tableName, column, (it) => this.generateColumnDefinitionFromSchema(it)),
|
|
245
|
-
...this.generateColumnCommentStatement(tableName, column, schema),
|
|
246
|
-
];
|
|
247
|
-
}
|
|
248
|
-
generateCreateIndex(tableName, index, options = {}) {
|
|
249
|
-
return this.indexDdl.getCreateIndexStatement(tableName, index, options);
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
|
-
* `schema` is the table's, because that is where its indexes live. MySQL takes it from the table
|
|
253
|
-
* operand instead, which is already qualified.
|
|
254
|
-
*/
|
|
255
|
-
generateDropIndex(tableName, indexName, schema) {
|
|
256
|
-
return this.tableDdl.dropIndex(tableName, indexName, schema);
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* A column definition from a {@link ColumnSchema}, whose type is already the engine's spelling. Apart from
|
|
260
|
-
* {@link generateColumnFromNode}, which alone knows an `enum`; both render through {@link renderColumn}.
|
|
261
|
-
*/
|
|
262
|
-
generateColumnDefinitionFromSchema(column) {
|
|
263
|
-
return this.renderColumn({ ...column, type: sizedType(column) });
|
|
264
|
-
}
|
|
265
219
|
/**
|
|
266
|
-
*
|
|
267
|
-
*
|
|
268
|
-
* NULL otherwise, and SQL Server adds no key over a nullable column. Never `UNIQUE`: a unique column is
|
|
269
|
-
* a unique index, which the table creates beside it. An enum's `CHECK` comes last, the only place MariaDB takes it.
|
|
220
|
+
* A column added to a table that exists. `checks` go inline, which is the one way to constrain a table that is
|
|
221
|
+
* rebuilt to alter; a stored generated column, an engine that rebuilds tables takes only in a `CREATE TABLE`.
|
|
270
222
|
*/
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
: column.type;
|
|
275
|
-
let def = `${this.escapeId(column.name)} ${type}`;
|
|
276
|
-
if (!column.nullable) {
|
|
277
|
-
def += ' NOT NULL';
|
|
278
|
-
}
|
|
279
|
-
def += this.tableDdl.defaultClause(column);
|
|
280
|
-
if (column.comment) {
|
|
281
|
-
def += this.generateColumnComment(column.comment);
|
|
282
|
-
}
|
|
283
|
-
if (column.enum?.length) {
|
|
284
|
-
const values = column.enum.map((value) => this.dialect.escape(value)).join(', ');
|
|
285
|
-
def += ` CHECK (${this.escapeId(column.name)} IN (${values}))`;
|
|
286
|
-
}
|
|
287
|
-
return def;
|
|
288
|
-
}
|
|
289
|
-
/** The inline ` COMMENT '...'` a column declaration carries, where the engine takes one there. */
|
|
290
|
-
generateColumnComment(comment) {
|
|
291
|
-
return this.features.commentSyntax === 'inline' ? ` COMMENT ${this.dialect.escape(comment)}` : '';
|
|
292
|
-
}
|
|
293
|
-
/** The `COMMENT ON` statements a table and its columns need, after the `CREATE TABLE`, where the engine uses them. */
|
|
294
|
-
generateCommentStatements(table) {
|
|
295
|
-
if (this.features.commentSyntax !== 'statement') {
|
|
296
|
-
return [];
|
|
297
|
-
}
|
|
298
|
-
const tableRef = this.dialect.escapeQualifiedId(table.name, table.schema);
|
|
299
|
-
const statements = table.comment ? [`COMMENT ON TABLE ${tableRef} IS ${this.dialect.escape(table.comment)};`] : [];
|
|
300
|
-
for (const col of table.columns.values()) {
|
|
301
|
-
statements.push(...this.generateColumnCommentStatement(table.name, col, table.schema));
|
|
302
|
-
}
|
|
303
|
-
return statements;
|
|
304
|
-
}
|
|
305
|
-
/** The `COMMENT ON COLUMN` a column needs where the engine uses one, for `CREATE TABLE` and every path adding a column. */
|
|
306
|
-
generateColumnCommentStatement(tableName, column, schema) {
|
|
307
|
-
if (!column.comment || this.features.commentSyntax !== 'statement') {
|
|
308
|
-
return [];
|
|
223
|
+
addColumnStatements(tableName, column, checks = []) {
|
|
224
|
+
if (column.generatedAs) {
|
|
225
|
+
this.assertAlterable(`Adding the stored column "${column.name}" to "${tableName}"`);
|
|
309
226
|
}
|
|
310
|
-
const
|
|
311
|
-
return
|
|
227
|
+
const inline = checks.map((check) => ` ${this.checkConstraint(check)}`).join('');
|
|
228
|
+
return this.tableDdl.addColumnStatements(tableName, column, inline);
|
|
312
229
|
}
|
|
313
230
|
/**
|
|
314
231
|
* How the entity differs from the table the database reported, compared by {@link diffTable}, the one
|
|
@@ -316,10 +233,9 @@ export class SqlSchemaGenerator {
|
|
|
316
233
|
*/
|
|
317
234
|
diffSchema(entity, currentTable, desiredAst, renamedColumns) {
|
|
318
235
|
const meta = getMeta(entity);
|
|
319
|
-
const tableName = this.resolveTableName(meta);
|
|
320
|
-
const schema = this.resolveSchema(meta);
|
|
236
|
+
const tableName = this.dialect.resolveTableName(meta);
|
|
321
237
|
if (!currentTable) {
|
|
322
|
-
return { tableName,
|
|
238
|
+
return { tableName, type: 'create' };
|
|
323
239
|
}
|
|
324
240
|
// Keyed by the qualified name this generator resolves, which is the key the AST stores the table
|
|
325
241
|
// under.
|
|
@@ -327,25 +243,13 @@ export class SqlSchemaGenerator {
|
|
|
327
243
|
if (!desired) {
|
|
328
244
|
return undefined;
|
|
329
245
|
}
|
|
330
|
-
const tableDiff = diffTable(desired, currentTable,
|
|
246
|
+
const tableDiff = diffTable(desired, currentTable, this.diffOptions());
|
|
331
247
|
const indexes = indexChanges(currentTable.name, desired.indexes, currentTable.indexes, currentTable.indexFacets);
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
if (it.from === undefined) {
|
|
338
|
-
return { to: this.columnNodeToSchema(it.to) };
|
|
339
|
-
}
|
|
340
|
-
if (it.to === undefined) {
|
|
341
|
-
return { from: this.columnNodeToSchema(it.from), isBreaking: true };
|
|
342
|
-
}
|
|
343
|
-
return {
|
|
344
|
-
from: this.columnNodeToSchema(it.from),
|
|
345
|
-
to: { ...this.columnNodeToSchema(it.to), enum: undefined },
|
|
346
|
-
isBreaking: it.isBreaking,
|
|
347
|
-
};
|
|
348
|
-
});
|
|
248
|
+
const columns = (tableDiff?.columns ?? []).map(({ from, to, isBreaking }) => ({
|
|
249
|
+
from: from && this.columnNodeToSchema(from),
|
|
250
|
+
to: to && this.columnNodeToSchema(to),
|
|
251
|
+
isBreaking,
|
|
252
|
+
}));
|
|
349
253
|
const keyDiff = tableDiff?.primaryKey;
|
|
350
254
|
// The key added named as this generator names it, so the rollback can drop it by that name.
|
|
351
255
|
const primaryKey = keyDiff && {
|
|
@@ -355,7 +259,6 @@ export class SqlSchemaGenerator {
|
|
|
355
259
|
const foreignKeys = diffRelationshipNodes(desired.outgoingRelations, currentTable.outgoingRelations).map(({ from, to }) => ({ from: from && foreignKeyOf(from), to: to && foreignKeyOf(to) }));
|
|
356
260
|
const alter = {
|
|
357
261
|
tableName,
|
|
358
|
-
schema,
|
|
359
262
|
type: 'alter',
|
|
360
263
|
primaryKey,
|
|
361
264
|
columns: nonEmpty(columns),
|
|
@@ -364,9 +267,18 @@ export class SqlSchemaGenerator {
|
|
|
364
267
|
to: to && indexNodeToSchema(to),
|
|
365
268
|
}))),
|
|
366
269
|
foreignKeys: nonEmpty(foreignKeys),
|
|
270
|
+
checks: nonEmpty(tableDiff?.checks ?? []),
|
|
271
|
+
// A kept trigger as both sides, which the alter cycles only where a column moves under it.
|
|
272
|
+
triggers: nonEmpty([
|
|
273
|
+
...(tableDiff?.triggers ?? []),
|
|
274
|
+
...matchByKey(desired.triggers, currentTable.triggers, (it) => it.name).matched.map(([to, from]) => ({
|
|
275
|
+
from,
|
|
276
|
+
to,
|
|
277
|
+
})),
|
|
278
|
+
]),
|
|
367
279
|
renamedColumns: nonEmpty(renamedColumns ?? []),
|
|
368
280
|
};
|
|
369
|
-
if (!(
|
|
281
|
+
if (!(tableDiff || alter.indexes || alter.foreignKeys || alter.renamedColumns)) {
|
|
370
282
|
return undefined;
|
|
371
283
|
}
|
|
372
284
|
return this.features.rebuildsTables && needsRebuild(alter)
|
|
@@ -375,25 +287,30 @@ export class SqlSchemaGenerator {
|
|
|
375
287
|
}
|
|
376
288
|
/**
|
|
377
289
|
* Both ends of rebuilding `actual` as `desired`. The new table is the entity's, keeping what it cannot
|
|
378
|
-
* know of: the indexes and triggers uql did not make, and foreign keys to tables no entity names.
|
|
379
|
-
* old one is the engine's own statements, so a rollback restores it exactly
|
|
290
|
+
* know of: the indexes, checks and triggers uql did not make, and foreign keys to tables no entity names.
|
|
291
|
+
* The old one is the engine's own statements, so a rollback restores it exactly.
|
|
380
292
|
*/
|
|
381
293
|
rebuildOf(desired, actual, kept, renames) {
|
|
382
294
|
const definition = actual.definition ?? [];
|
|
383
295
|
const read = new Set(actual.indexes.map((index) => index.name));
|
|
384
296
|
const own = (entry) => entry.kind === 'trigger' && isOwnedName(entry.name);
|
|
385
|
-
const verbatim = (entries) => entries.map((entry) => `${entry.sql};`);
|
|
386
297
|
const stored = (table) => [...table.columns.values()].filter((column) => !column.generatedAs).map((column) => column.name);
|
|
387
298
|
return {
|
|
388
299
|
from: {
|
|
389
|
-
statements:
|
|
300
|
+
statements: terminated(definition.filter((entry) => !own(entry)).map((entry) => entry.sql)),
|
|
390
301
|
columns: stored(actual).map((name) => renames.find((rename) => rename.to === name)?.from ?? name),
|
|
391
302
|
},
|
|
392
303
|
to: {
|
|
393
304
|
statements: [
|
|
394
|
-
...this.generateCreateTableFromNode({
|
|
395
|
-
|
|
396
|
-
|
|
305
|
+
...this.generateCreateTableFromNode({
|
|
306
|
+
...desired,
|
|
307
|
+
checks: [...desired.checks, ...actual.checks.filter((check) => !isOwnedName(check.name))],
|
|
308
|
+
externalForeignKeys: actual.externalForeignKeys,
|
|
309
|
+
}),
|
|
310
|
+
...kept.map((index) => this.createIndexFromNode(index)),
|
|
311
|
+
...terminated(definition
|
|
312
|
+
.filter((entry) => (entry.kind === 'index' && !read.has(entry.name)) || (entry.kind === 'trigger' && !own(entry)))
|
|
313
|
+
.map((entry) => entry.sql)),
|
|
397
314
|
],
|
|
398
315
|
columns: stored(desired),
|
|
399
316
|
},
|
|
@@ -412,151 +329,100 @@ export class SqlSchemaGenerator {
|
|
|
412
329
|
}
|
|
413
330
|
/** Spread, not copied field by field, so a field the node gains cannot go missing here. */
|
|
414
331
|
columnNodeToSchema(col) {
|
|
415
|
-
const { table: _table,
|
|
332
|
+
const { table: _table, ...column } = col;
|
|
416
333
|
return { ...column, type: this.columnSqlType(col) };
|
|
417
334
|
}
|
|
418
335
|
/** Whether a column's stored default is the one the entity declares, as this engine reprints it. */
|
|
419
336
|
defaultsEqual = (desired, current) => sameDefault(desired, current, this.dialect);
|
|
420
337
|
generateCreateTableFromNode(table, options = {}) {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
for (const col of table.columns.values()) {
|
|
424
|
-
columns.push(this.generateColumnFromNode(col));
|
|
425
|
-
}
|
|
426
|
-
// Every key, of any width, as one named constraint beside the checks and foreign keys - so a
|
|
427
|
-
// later `DROP` has something to name. The exception is a dialect whose serial type states the key
|
|
428
|
-
// itself (SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT`, which cannot be split): there the column
|
|
429
|
-
// has already declared it, and saying it again is a second primary key.
|
|
338
|
+
// Every key, of any width, as one named constraint, so a later `DROP` has something to name. Except where
|
|
339
|
+
// the serial type states the key itself (SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT`): a second one there.
|
|
430
340
|
const key = table.primaryKey;
|
|
431
341
|
const declaredByColumn = this.dialect.features.serialDeclaresPrimaryKey &&
|
|
432
342
|
key?.columns.length === 1 &&
|
|
433
343
|
table.columns.get(key.columns[0])?.isAutoIncrement;
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
constraints.push(`CONSTRAINT ${this.escapeId(name)} CHECK (${check.expression})`);
|
|
442
|
-
});
|
|
443
|
-
for (const rel of table.outgoingRelations) {
|
|
444
|
-
const refTable = this.dialect.escapeQualifiedId(rel.to.table.name, rel.to.table.schema);
|
|
445
|
-
constraints.push(this.foreignKeyConstraint(table.name, foreignKeyOf(rel), refTable));
|
|
446
|
-
}
|
|
447
|
-
for (const foreignKey of table.externalForeignKeys) {
|
|
448
|
-
constraints.push(this.foreignKeyConstraint(table.name, foreignKey, this.escapeId(foreignKey.references.table)));
|
|
449
|
-
}
|
|
344
|
+
const definitions = [
|
|
345
|
+
...[...table.columns.values()].map((column) => this.tableDdl.columnDefinition(this.columnNodeToSchema(column))),
|
|
346
|
+
...(key && !declaredByColumn ? [this.tableDdl.primaryKeyConstraint(table.name, key)] : []),
|
|
347
|
+
...table.checks.map((check) => this.checkConstraint(check)),
|
|
348
|
+
...table.outgoingRelations.map((relation) => this.foreignKeyConstraint(table.name, foreignKeyOf(relation), this.dialect.escapeQualifiedId(relation.to.table.name, relation.to.table.schema))),
|
|
349
|
+
...table.externalForeignKeys.map((foreignKey) => this.foreignKeyConstraint(table.name, foreignKey, this.escapeId(foreignKey.references.table))),
|
|
350
|
+
];
|
|
450
351
|
const target = this.dialect.escapeQualifiedId(table.name, table.schema);
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
createSql += ',\n';
|
|
455
|
-
createSql += constraints.map((c) => ` ${c}`).join(',\n');
|
|
456
|
-
}
|
|
457
|
-
createSql += '\n)';
|
|
458
|
-
if (this.tableDdl.tableOptions) {
|
|
459
|
-
createSql += ` ${this.tableDdl.tableOptions}`;
|
|
460
|
-
}
|
|
461
|
-
if (table.comment && this.features.commentSyntax === 'inline') {
|
|
462
|
-
createSql += ` COMMENT=${this.dialect.escape(table.comment)}`;
|
|
463
|
-
}
|
|
464
|
-
createSql += ';';
|
|
465
|
-
const statements = [];
|
|
466
|
-
if (this.dialect.vectorExtension) {
|
|
467
|
-
const hasVectorCol = [...table.columns.values()].some((c) => isVectorCategory(c.type.category));
|
|
468
|
-
if (hasVectorCol) {
|
|
469
|
-
statements.push(`CREATE EXTENSION IF NOT EXISTS ${this.dialect.vectorExtension};`);
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
statements.push(createSql);
|
|
473
|
-
statements.push(...this.generateCommentStatements(table));
|
|
352
|
+
const body = definitions.map((definition) => ` ${definition}`).join(',\n');
|
|
353
|
+
const vector = this.dialect.vectorExtension &&
|
|
354
|
+
[...table.columns.values()].some((column) => isVectorCategory(column.type.category));
|
|
474
355
|
// A table created only if missing creates its indexes the same way, or re-creating a schema fails on the first.
|
|
475
356
|
const indexOptions = { ifNotExists: !!options.ifNotExists && this.features.indexIfNotExists };
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
*/
|
|
485
|
-
generateColumnFromNode(col) {
|
|
486
|
-
return this.renderColumn({ ...col, type: this.columnSqlType(col) });
|
|
357
|
+
return [
|
|
358
|
+
...(vector ? [`CREATE EXTENSION IF NOT EXISTS ${this.dialect.vectorExtension};`] : []),
|
|
359
|
+
`${this.tableDdl.createTable(target, !!options.ifNotExists)} (\n${body}\n)${this.tableDdl.tableSuffix(table.comment)};`,
|
|
360
|
+
...this.tableDdl.commentStatements(qualifyName(table.name, table.schema), table.comment, [
|
|
361
|
+
...table.columns.values(),
|
|
362
|
+
]),
|
|
363
|
+
...table.indexes.map((index) => this.createIndexFromNode(index, indexOptions)),
|
|
364
|
+
];
|
|
487
365
|
}
|
|
488
|
-
/**
|
|
489
|
-
|
|
490
|
-
* Delegates to `generateCreateIndex` for unified SQL assembly.
|
|
491
|
-
*/
|
|
492
|
-
generateCreateIndexFromNode(index, options = { ifNotExists: false }) {
|
|
366
|
+
/** The `CREATE INDEX` for an index of the AST. */
|
|
367
|
+
createIndexFromNode(index, options = { ifNotExists: false }) {
|
|
493
368
|
// The index's own name stays unqualified: it is created in the schema of the table it is on.
|
|
494
|
-
return this.
|
|
369
|
+
return this.indexDdl.getCreateIndexStatement(qualifyName(index.table.name, index.table.schema), indexNodeToSchema(index), options);
|
|
495
370
|
}
|
|
496
371
|
generateCreateTableFromDefinition(table, options = {}) {
|
|
497
372
|
const tableNode = tableDefinitionToNode(table, (sql) => this.dialect.compileDdl(sql));
|
|
498
373
|
return this.generateCreateTableFromNode(tableNode, options);
|
|
499
374
|
}
|
|
500
|
-
generateRenameTableSql(oldName, newName) {
|
|
501
|
-
return this.tableDdl.renameTable(oldName, newName);
|
|
502
|
-
}
|
|
503
375
|
/** `raw` is split, being the one SQL no generator wrote. */
|
|
504
376
|
generateOperation(operation) {
|
|
505
377
|
switch (operation.type) {
|
|
506
378
|
case 'createTable':
|
|
507
379
|
return this.generateCreateTableFromDefinition(operation.table);
|
|
508
380
|
case 'dropTable':
|
|
509
|
-
return [
|
|
510
|
-
this.generateDropTable(operation.tableName, { ifExists: operation.ifExists, cascade: operation.cascade }),
|
|
511
|
-
];
|
|
381
|
+
return [this.dropTableSql(operation.tableName, { ifExists: operation.ifExists, cascade: operation.cascade })];
|
|
512
382
|
case 'renameTable':
|
|
513
|
-
return [this.
|
|
383
|
+
return [this.tableDdl.renameTable(operation.oldName, operation.newName)];
|
|
514
384
|
case 'addColumn':
|
|
515
|
-
return this.
|
|
385
|
+
return this.addColumnSql(operation.tableName, operation.column);
|
|
516
386
|
case 'dropColumn':
|
|
517
|
-
return this.
|
|
387
|
+
return this.tableDdl.dropColumn(operation.tableName, operation.columnName);
|
|
518
388
|
case 'renameColumn':
|
|
519
|
-
return [this.
|
|
389
|
+
return [this.tableDdl.renameColumn(operation.tableName, operation.oldName, operation.newName)];
|
|
520
390
|
case 'alterColumn':
|
|
521
|
-
|
|
391
|
+
this.assertAlterable(`Altering the column "${operation.changes.name}" of "${operation.tableName}"`);
|
|
392
|
+
return this.tableDdl.alterColumns(operation.tableName, [{ to: this.definitionColumn(operation.changes) }]);
|
|
522
393
|
case 'createIndex':
|
|
523
394
|
return this.addIndexStatements(operation.tableName, [
|
|
524
395
|
renderIndexDefinition(operation.index, (sql) => this.dialect.compileDdl(sql)),
|
|
525
396
|
]);
|
|
526
397
|
case 'dropIndex':
|
|
527
|
-
return [this.
|
|
398
|
+
return [this.tableDdl.dropIndex(operation.tableName, operation.indexName)];
|
|
528
399
|
case 'addForeignKey':
|
|
529
|
-
return [this.
|
|
400
|
+
return [this.addForeignKeySql(operation.tableName, operation.foreignKey)];
|
|
530
401
|
case 'dropForeignKey':
|
|
531
|
-
return [this.
|
|
402
|
+
return [this.tableDdl.dropForeignKey(operation.tableName, operation.constraintName)];
|
|
532
403
|
case 'raw':
|
|
533
404
|
return splitSqlStatements(operation.sql);
|
|
534
405
|
}
|
|
535
406
|
}
|
|
536
407
|
/** `ADD COLUMN`, plus the foreign key and index the column declares, as `CREATE TABLE` lifts them. */
|
|
537
|
-
|
|
538
|
-
const
|
|
408
|
+
addColumnSql(tableName, column) {
|
|
409
|
+
const checks = enumCheck(splitQualifiedName(tableName).name, column, (sql) => this.dialect.compileDdl(sql));
|
|
410
|
+
const statements = this.features.rebuildsTables
|
|
411
|
+
? this.addColumnStatements(tableName, this.definitionColumn(column), checks)
|
|
412
|
+
: [
|
|
413
|
+
...this.addColumnStatements(tableName, this.definitionColumn(column)),
|
|
414
|
+
...checks.map((check) => this.addCheckSql(tableName, check)),
|
|
415
|
+
];
|
|
539
416
|
const foreignKey = columnForeignKey(column);
|
|
540
417
|
if (foreignKey) {
|
|
541
|
-
statements.push(
|
|
418
|
+
statements.push(this.addForeignKeySql(tableName, foreignKey));
|
|
542
419
|
}
|
|
543
420
|
const index = columnIndex(tableName, column);
|
|
544
421
|
if (index) {
|
|
545
|
-
statements.push(this.
|
|
422
|
+
statements.push(this.indexDdl.getCreateIndexStatement(tableName, index));
|
|
546
423
|
}
|
|
547
424
|
return statements;
|
|
548
425
|
}
|
|
549
|
-
generateAlterColumnSql(tableName, columnName, column) {
|
|
550
|
-
this.assertAlterable(`Altering the column "${columnName}" of "${tableName}"`);
|
|
551
|
-
const schema = this.definitionColumn(column);
|
|
552
|
-
return this.tableDdl.alterColumn(tableName, { ...schema, name: columnName }, this.renderColumn(schema));
|
|
553
|
-
}
|
|
554
|
-
generateDropColumnSql(tableName, columnName) {
|
|
555
|
-
return this.tableDdl.dropColumn(tableName, columnName);
|
|
556
|
-
}
|
|
557
|
-
generateRenameColumnSql(tableName, oldName, newName) {
|
|
558
|
-
return this.tableDdl.renameColumn(tableName, oldName, newName);
|
|
559
|
-
}
|
|
560
426
|
/**
|
|
561
427
|
* `CONSTRAINT <name> FOREIGN KEY (...) REFERENCES ... ON DELETE ... ON UPDATE ...`.
|
|
562
428
|
*
|
|
@@ -571,39 +437,11 @@ export class SqlSchemaGenerator {
|
|
|
571
437
|
`ON DELETE ${foreignKey.onDelete ?? this.defaultForeignKeyAction} ` +
|
|
572
438
|
`ON UPDATE ${foreignKey.onUpdate ?? this.defaultForeignKeyAction}`);
|
|
573
439
|
}
|
|
574
|
-
|
|
440
|
+
addForeignKeySql(tableName, foreignKey) {
|
|
575
441
|
this.assertAlterable(`Adding a foreign key to "${tableName}"`);
|
|
576
442
|
const constraint = this.foreignKeyConstraint(tableName, foreignKey, this.escapeId(foreignKey.references.table));
|
|
577
443
|
return `ALTER TABLE ${this.escapeId(tableName)} ADD ${constraint};`;
|
|
578
444
|
}
|
|
579
|
-
generateDropForeignKeySql(tableName, constraintName) {
|
|
580
|
-
return this.tableDdl.dropForeignKey(tableName, constraintName);
|
|
581
|
-
}
|
|
582
|
-
/**
|
|
583
|
-
* `ALTER TABLE ... ADD CONSTRAINT <name> PRIMARY KEY (...)`, the other half of
|
|
584
|
-
* {@link generateDropPrimaryKeySql}. Refused where the engine cannot alter a key at all, by name,
|
|
585
|
-
* rather than emitting DDL it will reject.
|
|
586
|
-
*/
|
|
587
|
-
generateAddPrimaryKeySql(tableName, columns, name) {
|
|
588
|
-
this.assertAlterable(`Changing the primary key of "${tableName}"`);
|
|
589
|
-
const constraintName = this.escapeId(name ?? derivedPrimaryKeyName(tableName, columns));
|
|
590
|
-
const pkCols = columns.map((c) => this.escapeId(c)).join(', ');
|
|
591
|
-
return `ALTER TABLE ${this.escapeId(tableName)} ADD CONSTRAINT ${constraintName} PRIMARY KEY (${pkCols});`;
|
|
592
|
-
}
|
|
593
|
-
/**
|
|
594
|
-
* Drops the table's key, by the name the constraint really has: introspected, or derived where this
|
|
595
|
-
* generator added it. MySQL takes no name.
|
|
596
|
-
*/
|
|
597
|
-
generateDropPrimaryKeySql(tableName, constraintName) {
|
|
598
|
-
this.assertAlterable(`Changing the primary key of "${tableName}"`);
|
|
599
|
-
return this.tableDdl.dropPrimaryKey(tableName, constraintName);
|
|
600
|
-
}
|
|
601
|
-
/** A stored generated column, which an engine that rebuilds tables takes only in a `CREATE TABLE`. */
|
|
602
|
-
assertColumnAddable(tableName, column) {
|
|
603
|
-
if (column.generatedAs) {
|
|
604
|
-
this.assertAlterable(`Adding the stored column "${column.name}" to "${tableName}"`);
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
445
|
/**
|
|
608
446
|
* Refuses `what` where the engine makes it only by rebuilding the table, which a migration generated
|
|
609
447
|
* from the entities does and a lone statement of the builder cannot.
|
|
@@ -614,6 +452,10 @@ export class SqlSchemaGenerator {
|
|
|
614
452
|
}
|
|
615
453
|
}
|
|
616
454
|
}
|
|
455
|
+
/** Statements as a migration runs them, each ended. */
|
|
456
|
+
function terminated(statements) {
|
|
457
|
+
return statements.map((sql) => `${sql};`);
|
|
458
|
+
}
|
|
617
459
|
/**
|
|
618
460
|
* What a constraint is called: its own name, or one derived from its columns where nothing named it.
|
|
619
461
|
* Shared by the add and the drop so a `DROP CONSTRAINT` names exactly what an `ADD CONSTRAINT` made.
|
|
@@ -624,8 +466,8 @@ export function constraintNameOf(tableName, foreignKey) {
|
|
|
624
466
|
/**
|
|
625
467
|
* A relationship node as the migration's own `ForeignKeySchema`. The node's `name` is kept rather
|
|
626
468
|
* than derived: on the database's side it is the only name a `DROP` can use, and on the entity's it
|
|
627
|
-
* is already the derived one. An unset action stays unset
|
|
628
|
-
* that spends it, `
|
|
469
|
+
* is already the derived one. An unset action stays unset: the default belongs to the one place
|
|
470
|
+
* that spends it, `foreignKeyConstraint`.
|
|
629
471
|
*/
|
|
630
472
|
function foreignKeyOf(relation) {
|
|
631
473
|
return {
|
|
@@ -639,19 +481,3 @@ function foreignKeyOf(relation) {
|
|
|
639
481
|
onUpdate: relation.onUpdate,
|
|
640
482
|
};
|
|
641
483
|
}
|
|
642
|
-
/**
|
|
643
|
-
* The entities as an AST, named by `generator`'s resolvers rather than a naming strategy, which would
|
|
644
|
-
* also rename an explicit `@Entity({ name })` and so compare each table under another name.
|
|
645
|
-
*/
|
|
646
|
-
export function buildEntityAST(generator, entities, options = {}) {
|
|
647
|
-
return buildSchemaAST(entities, {
|
|
648
|
-
// The alias, not `resolveTableName`: a node holds its schema separately, so that a name derived
|
|
649
|
-
// from it stays a single identifier.
|
|
650
|
-
resolveTableName: (meta) => generator.resolveTableAlias(meta),
|
|
651
|
-
resolveSchema: (meta) => generator.resolveSchema(meta),
|
|
652
|
-
resolveColumnName: (key, field) => generator.resolveColumnName(key, field),
|
|
653
|
-
compileDdl: (sql, entity) => generator.compileDdl(sql, entity),
|
|
654
|
-
compileIndexPredicate: (where, entity, indexName) => generator.compileIndexPredicate(where, entity, indexName),
|
|
655
|
-
...options,
|
|
656
|
-
});
|
|
657
|
-
}
|