uql-orm 0.97.0 → 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 +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 +4 -21
- package/dist/migrate/migrator.js +47 -71
- 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
|
@@ -19,38 +19,26 @@ export class EntityCodeGenerator {
|
|
|
19
19
|
options;
|
|
20
20
|
constructor(ast, options = {}) {
|
|
21
21
|
this.ast = ast;
|
|
22
|
+
const singular = options.singularize ?? singularize;
|
|
22
23
|
this.options = {
|
|
23
24
|
uqlImportPath: options.uqlImportPath ?? 'uql-orm',
|
|
24
25
|
addSyncComments: options.addSyncComments ?? true,
|
|
25
|
-
classNameTransformer: options.classNameTransformer ??
|
|
26
|
-
propertyNameTransformer: options.propertyNameTransformer ??
|
|
26
|
+
classNameTransformer: options.classNameTransformer ?? ((tableName) => pascalCase(singular(tableName))),
|
|
27
|
+
propertyNameTransformer: options.propertyNameTransformer ?? camelCase,
|
|
27
28
|
includeRelations: options.includeRelations ?? true,
|
|
28
29
|
includeIndexes: options.includeIndexes ?? true,
|
|
29
|
-
singularize:
|
|
30
|
+
singularize: singular,
|
|
30
31
|
};
|
|
31
32
|
}
|
|
32
|
-
/**
|
|
33
|
-
* Generate entities for all tables in the AST.
|
|
34
|
-
*/
|
|
33
|
+
/** An entity for each table of the AST. */
|
|
35
34
|
generateAll() {
|
|
36
|
-
|
|
37
|
-
for (const table of this.ast.tables.values()) {
|
|
38
|
-
entities.push(this.generateEntity(table));
|
|
39
|
-
}
|
|
40
|
-
return entities;
|
|
35
|
+
return [...this.ast.tables.values()].map((table) => this.generateEntity(table));
|
|
41
36
|
}
|
|
42
|
-
/**
|
|
43
|
-
* Generate entity for a specific table.
|
|
44
|
-
*/
|
|
37
|
+
/** The entity for the table named, if the AST has it. */
|
|
45
38
|
generateForTable(tableName) {
|
|
46
39
|
const table = this.ast.getTable(tableName);
|
|
47
|
-
|
|
48
|
-
return undefined;
|
|
49
|
-
return this.generateEntity(table);
|
|
40
|
+
return table && this.generateEntity(table);
|
|
50
41
|
}
|
|
51
|
-
/**
|
|
52
|
-
* Generate entity code for a table.
|
|
53
|
-
*/
|
|
54
42
|
generateEntity(table) {
|
|
55
43
|
const className = this.options.classNameTransformer(table.name);
|
|
56
44
|
const fileName = `${className}.ts`;
|
|
@@ -67,9 +55,6 @@ export class EntityCodeGenerator {
|
|
|
67
55
|
fileName,
|
|
68
56
|
};
|
|
69
57
|
}
|
|
70
|
-
/**
|
|
71
|
-
* Build import statements.
|
|
72
|
-
*/
|
|
73
58
|
buildImports(table) {
|
|
74
59
|
const uqlImports = new Set(['Entity', 'Field']);
|
|
75
60
|
const relatedImports = [];
|
|
@@ -117,9 +102,6 @@ export class EntityCodeGenerator {
|
|
|
117
102
|
...relatedImports.sort().map((className) => `import { ${className} } from './${className}.js';`),
|
|
118
103
|
].join('\n');
|
|
119
104
|
}
|
|
120
|
-
/**
|
|
121
|
-
* Build entity decorators.
|
|
122
|
-
*/
|
|
123
105
|
buildEntityDecorators(table) {
|
|
124
106
|
const lines = [];
|
|
125
107
|
if (this.options.includeIndexes) {
|
|
@@ -128,20 +110,17 @@ export class EntityCodeGenerator {
|
|
|
128
110
|
lines.push(buildIndexDecoratorSource(index, this.options.propertyNameTransformer, param));
|
|
129
111
|
}
|
|
130
112
|
}
|
|
131
|
-
// Entity decorator
|
|
132
113
|
lines.push(`@Entity({ name: '${table.name}' })`);
|
|
133
114
|
return lines.join('\n');
|
|
134
115
|
}
|
|
135
|
-
/**
|
|
136
|
-
* Build field definitions.
|
|
137
|
-
*/
|
|
138
116
|
buildFields(table) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
117
|
+
return [...table.columns.values()].map((col) => this.buildField(col)).join('\n\n');
|
|
118
|
+
}
|
|
119
|
+
/** The `@sync-added` JSDoc a generated member opens with, saying `what` it is, where asked for. */
|
|
120
|
+
syncDoc(what) {
|
|
121
|
+
return this.options.addSyncComments
|
|
122
|
+
? [' /**', ` * @sync-added ${new Date().toISOString().split('T')[0]}`, ` * ${what}`, ' */']
|
|
123
|
+
: [];
|
|
145
124
|
}
|
|
146
125
|
/**
|
|
147
126
|
* The `idKey` brand naming the key, which the type level cannot see otherwise: needed unless the key is
|
|
@@ -157,26 +136,14 @@ export class EntityCodeGenerator {
|
|
|
157
136
|
}
|
|
158
137
|
return ` [idKey]?: ${keys.map(quoted).join(' | ')};`;
|
|
159
138
|
}
|
|
160
|
-
/**
|
|
161
|
-
* Build a single field definition.
|
|
162
|
-
*/
|
|
163
139
|
buildField(col) {
|
|
164
|
-
const lines = [];
|
|
165
140
|
const propertyName = this.options.propertyNameTransformer(col.name);
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
lines.push(' */');
|
|
172
|
-
}
|
|
173
|
-
lines.push(` @${col.isPrimaryKey ? 'Id' : 'Field'}(${this.buildFieldOptions(col, propertyName)})`);
|
|
174
|
-
lines.push(` ${propertySource(col, propertyName)};`);
|
|
175
|
-
return lines.join('\n');
|
|
141
|
+
return [
|
|
142
|
+
...this.syncDoc(`Column: ${col.name} (${formatTypeDescription(col.type)})`),
|
|
143
|
+
` @${col.isPrimaryKey ? 'Id' : 'Field'}(${this.buildFieldOptions(col, propertyName)})`,
|
|
144
|
+
` ${propertySource(col, propertyName)};`,
|
|
145
|
+
].join('\n');
|
|
176
146
|
}
|
|
177
|
-
/**
|
|
178
|
-
* Build Field decorator options.
|
|
179
|
-
*/
|
|
180
147
|
buildFieldOptions(col, propertyName) {
|
|
181
148
|
const indexes = this.options.includeIndexes ? col.table.indexes : [];
|
|
182
149
|
const fieldIndex = indexes.find((idx) => isPlainFieldIndex(idx) && idx.entries[0]?.column === col.name);
|
|
@@ -189,54 +156,29 @@ export class EntityCodeGenerator {
|
|
|
189
156
|
declaredIndexes(table) {
|
|
190
157
|
return table.indexes.filter((index) => !isPlainFieldIndex(index));
|
|
191
158
|
}
|
|
192
|
-
/**
|
|
193
|
-
* Build relation definitions.
|
|
194
|
-
*/
|
|
159
|
+
/** The relations on both sides: where this table holds the foreign key, then where another points here. */
|
|
195
160
|
buildRelations(table) {
|
|
196
|
-
const lines = [
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
}
|
|
202
|
-
// Incoming relations (other tables have FK to this)
|
|
203
|
-
for (const rel of table.incomingRelations) {
|
|
204
|
-
const relCode = this.buildIncomingRelation(rel);
|
|
205
|
-
lines.push(relCode);
|
|
206
|
-
}
|
|
207
|
-
if (lines.length > 0) {
|
|
208
|
-
return '\n' + lines.join('\n\n');
|
|
209
|
-
}
|
|
210
|
-
return '';
|
|
161
|
+
const lines = [
|
|
162
|
+
...table.outgoingRelations.map((rel) => this.buildOutgoingRelation(rel)),
|
|
163
|
+
...table.incomingRelations.map((rel) => this.buildIncomingRelation(rel)),
|
|
164
|
+
];
|
|
165
|
+
return lines.length ? `\n${lines.join('\n\n')}` : '';
|
|
211
166
|
}
|
|
212
|
-
/**
|
|
213
|
-
* Build outgoing relation (ManyToOne or OneToOne where this table has FK).
|
|
214
|
-
*/
|
|
167
|
+
/** The side holding the foreign key; `onDelete`/`onUpdate` only where the database states an action of its own. */
|
|
215
168
|
buildOutgoingRelation(rel) {
|
|
216
|
-
const lines = [];
|
|
217
169
|
const relatedClassName = this.options.classNameTransformer(rel.to.table.name);
|
|
218
|
-
const propertyName = this.owningPropertyName(rel);
|
|
219
|
-
// JSDoc
|
|
220
|
-
if (this.options.addSyncComments) {
|
|
221
|
-
lines.push(' /**');
|
|
222
|
-
lines.push(` * @sync-added ${new Date().toISOString().split('T')[0]}`);
|
|
223
|
-
lines.push(` * Relation to ${rel.to.table.name} via ${rel.from.columns.map((c) => c.name).join(', ')}`);
|
|
224
|
-
lines.push(' */');
|
|
225
|
-
}
|
|
226
|
-
// Decorator. `onDelete`/`onUpdate` only when introspection found a real referential action, so a
|
|
227
|
-
// round-trip through an unconstrained column stays as terse as before.
|
|
228
|
-
const options = [`entity: () => ${relatedClassName}`];
|
|
229
170
|
const references = this.referencesSource(rel, relatedClassName);
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
171
|
+
const options = [
|
|
172
|
+
`entity: () => ${relatedClassName}`,
|
|
173
|
+
...(references ? [`references: ${references}`] : []),
|
|
174
|
+
...(rel.onDelete && rel.onDelete !== DEFAULT_FOREIGN_KEY_ACTION ? [`onDelete: '${rel.onDelete}'`] : []),
|
|
175
|
+
...(rel.onUpdate && rel.onUpdate !== DEFAULT_FOREIGN_KEY_ACTION ? [`onUpdate: '${rel.onUpdate}'`] : []),
|
|
176
|
+
];
|
|
177
|
+
return [
|
|
178
|
+
...this.syncDoc(`Relation to ${rel.to.table.name} via ${rel.from.columns.map((c) => c.name).join(', ')}`),
|
|
179
|
+
` @${rel.type}({ ${options.join(', ')} })`,
|
|
180
|
+
` ${this.owningPropertyName(rel)}?: ${relatedClassName};`,
|
|
181
|
+
].join('\n');
|
|
240
182
|
}
|
|
241
183
|
/**
|
|
242
184
|
* The property of the side holding the foreign key: its column's name less an `_id` or `Id` suffix
|
|
@@ -274,80 +216,27 @@ export class EntityCodeGenerator {
|
|
|
274
216
|
const pairs = rel.from.columns.map((column, i) => `{ local: ${member(local, column)}, foreign: ${member(foreign, rel.to.columns[i])} }`);
|
|
275
217
|
return `(${local}, ${foreign}) => [${pairs.join(', ')}]`;
|
|
276
218
|
}
|
|
277
|
-
/**
|
|
278
|
-
* Build incoming relation (OneToMany where other tables have FK to this).
|
|
279
|
-
*/
|
|
219
|
+
/** The inverse side, mapped by the related class's property that points back at this one. */
|
|
280
220
|
buildIncomingRelation(rel) {
|
|
281
|
-
const lines = [];
|
|
282
221
|
const relatedClassName = this.options.classNameTransformer(rel.from.table.name);
|
|
283
|
-
const propertyName = this.inversePropertyName(rel);
|
|
284
|
-
// JSDoc
|
|
285
|
-
if (this.options.addSyncComments) {
|
|
286
|
-
lines.push(' /**');
|
|
287
|
-
lines.push(` * @sync-added ${new Date().toISOString().split('T')[0]}`);
|
|
288
|
-
lines.push(` * Inverse relation from ${rel.from.table.name}`);
|
|
289
|
-
lines.push(' */');
|
|
290
|
-
}
|
|
291
|
-
// The inverse side, mapped by the related class's property that points back at this one.
|
|
292
222
|
const param = lowerFirst(relatedClassName);
|
|
293
223
|
const inverse = memberSource(param, this.owningPropertyName(rel));
|
|
294
224
|
const inverseType = INVERSE_RELATION[rel.type];
|
|
295
|
-
lines.push(` @${inverseType}({ entity: () => ${relatedClassName}, mappedBy: (${param}) => ${inverse} })`);
|
|
296
225
|
const many = inverseType === 'OneToMany' || inverseType === 'ManyToMany';
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
*/
|
|
303
|
-
formatTypeDescription(type) {
|
|
304
|
-
let desc = type.category.toUpperCase();
|
|
305
|
-
if (type.size)
|
|
306
|
-
desc = `${type.size.toUpperCase()}${desc}`;
|
|
307
|
-
if (type.length)
|
|
308
|
-
desc += `(${type.length})`;
|
|
309
|
-
if (type.precision) {
|
|
310
|
-
desc += `(${type.precision}`;
|
|
311
|
-
if (type.scale)
|
|
312
|
-
desc += `,${type.scale}`;
|
|
313
|
-
desc += ')';
|
|
314
|
-
}
|
|
315
|
-
if (type.unsigned)
|
|
316
|
-
desc += ' UNSIGNED';
|
|
317
|
-
return desc;
|
|
318
|
-
}
|
|
319
|
-
/**
|
|
320
|
-
* Default class name transformer: table_name -> TableName (PascalCase, singular).
|
|
321
|
-
*/
|
|
322
|
-
defaultClassNameTransformer(tableName) {
|
|
323
|
-
const singular = this.options.singularize(tableName);
|
|
324
|
-
return this.toPascalCase(singular);
|
|
325
|
-
}
|
|
326
|
-
/**
|
|
327
|
-
* Default property name transformer: column_name -> columnName (camelCase).
|
|
328
|
-
*/
|
|
329
|
-
defaultPropertyNameTransformer(name) {
|
|
330
|
-
return this.toCamelCase(name);
|
|
331
|
-
}
|
|
332
|
-
/**
|
|
333
|
-
* Convert to PascalCase (delegates to shared utility).
|
|
334
|
-
*/
|
|
335
|
-
toPascalCase(str) {
|
|
336
|
-
return pascalCase(str);
|
|
337
|
-
}
|
|
338
|
-
/**
|
|
339
|
-
* Convert to camelCase (delegates to shared utility).
|
|
340
|
-
*/
|
|
341
|
-
toCamelCase(str) {
|
|
342
|
-
return camelCase(str);
|
|
343
|
-
}
|
|
344
|
-
/**
|
|
345
|
-
* Default singularize function (delegates to shared utility).
|
|
346
|
-
*/
|
|
347
|
-
defaultSingularize(name) {
|
|
348
|
-
return singularize(name);
|
|
226
|
+
return [
|
|
227
|
+
...this.syncDoc(`Inverse relation from ${rel.from.table.name}`),
|
|
228
|
+
` @${inverseType}({ entity: () => ${relatedClassName}, mappedBy: (${param}) => ${inverse} })`,
|
|
229
|
+
` ${this.inversePropertyName(rel)}?: ${relatedClassName}${many ? '[]' : ''};`,
|
|
230
|
+
].join('\n');
|
|
349
231
|
}
|
|
350
232
|
}
|
|
233
|
+
/** A canonical type as the JSDoc of its field names it: `BIGINTEGER UNSIGNED`, `STRING(255)`, `DECIMAL(10,2)`. */
|
|
234
|
+
function formatTypeDescription(type) {
|
|
235
|
+
const size = type.size?.toUpperCase() ?? '';
|
|
236
|
+
const length = type.length ? `(${type.length})` : '';
|
|
237
|
+
const precision = type.precision ? `(${type.precision}${type.scale ? `,${type.scale}` : ''})` : '';
|
|
238
|
+
return `${size}${type.category.toUpperCase()}${length}${precision}${type.unsigned ? ' UNSIGNED' : ''}`;
|
|
239
|
+
}
|
|
351
240
|
/**
|
|
352
241
|
* A column's property as source, declared the way every read and insert types it: present (`!`) where
|
|
353
242
|
* the column is NOT NULL, left out of an insert (`?`) where a default fills it (a single-column key stays
|
|
@@ -362,9 +251,3 @@ function propertySource(col, propertyName) {
|
|
|
362
251
|
const filled = !col.isPrimaryKey && col.defaultValue !== undefined;
|
|
363
252
|
return `${written}${propertyName}${filled ? '?' : '!'}: ${type}`;
|
|
364
253
|
}
|
|
365
|
-
/**
|
|
366
|
-
* Create an EntityCodeGenerator from SchemaAST.
|
|
367
|
-
*/
|
|
368
|
-
export function createEntityCodeGenerator(ast, options) {
|
|
369
|
-
return new EntityCodeGenerator(ast, options);
|
|
370
|
-
}
|
|
@@ -7,7 +7,7 @@ import { quoted, rawTag } from './sourceLiteral.js';
|
|
|
7
7
|
const OPTION_SOURCE = {
|
|
8
8
|
// Without this the entity maps to a column named after the property, which for anything the
|
|
9
9
|
// transformer rewrote - every `user_id` - is a column the database does not have.
|
|
10
|
-
name: (col,
|
|
10
|
+
name: (col, propertyName) => (propertyName === col.name ? [] : [`name: ${quoted(col.name)}`]),
|
|
11
11
|
// The column type as `type`, which the decorator checks the property against and the schema reads
|
|
12
12
|
// exactly as it reads `columnType`.
|
|
13
13
|
type: (col) => {
|
|
@@ -32,10 +32,8 @@ const OPTION_SOURCE = {
|
|
|
32
32
|
isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, col.isPrimaryKey && col.table.primaryKey?.columns.length === 1) === col.isAutoIncrement
|
|
33
33
|
? []
|
|
34
34
|
: [`autoIncrement: ${col.isAutoIncrement}`],
|
|
35
|
-
//
|
|
35
|
+
// The graph link: a foreign key becomes a relation decorator, emitted beside the field rather than in it.
|
|
36
36
|
table: null,
|
|
37
|
-
references: null,
|
|
38
|
-
referencedBy: null,
|
|
39
37
|
};
|
|
40
38
|
/** Whether to write `type`'s precision: not for a timestamp at a `Date`'s milliseconds, its default. */
|
|
41
39
|
function writesPrecision(type) {
|
|
@@ -43,9 +41,8 @@ function writesPrecision(type) {
|
|
|
43
41
|
}
|
|
44
42
|
/** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
|
|
45
43
|
export function buildFieldOptionsSource(col, propertyName, indexName) {
|
|
46
|
-
const context = { propertyName, indexName };
|
|
47
44
|
const options = [
|
|
48
|
-
...Object.values(OPTION_SOURCE).flatMap((source) => source?.(col,
|
|
45
|
+
...Object.values(OPTION_SOURCE).flatMap((source) => source?.(col, propertyName) ?? []),
|
|
49
46
|
// Not a column field: the index is a table-level object the field only borrows.
|
|
50
47
|
...(indexName ? [`index: ${quoted(indexName)}`] : []),
|
|
51
48
|
];
|
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
* Code Generation Module
|
|
3
|
-
*
|
|
4
|
-
* Generates TypeScript entity code from database schemas.
|
|
5
|
-
*/
|
|
6
|
-
export { createEntityCodeGenerator, EntityCodeGenerator, type EntityCodeGeneratorOptions, type GeneratedEntity, } from './entityCodeGenerator.js';
|
|
1
|
+
export { EntityCodeGenerator, type EntityCodeGeneratorOptions, type GeneratedEntity } from './entityCodeGenerator.js';
|
|
7
2
|
export { entityTypesSource } from './entityTypes.js';
|
|
8
|
-
export { buildMigrationModule,
|
|
3
|
+
export { buildMigrationModule, type MigrationModuleOptions, type MigrationQuerierType } from './migrationFile.js';
|
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
* Code Generation Module
|
|
3
|
-
*
|
|
4
|
-
* Generates TypeScript entity code from database schemas.
|
|
5
|
-
*/
|
|
6
|
-
// Entity code generator
|
|
7
|
-
export { createEntityCodeGenerator, EntityCodeGenerator, } from './entityCodeGenerator.js';
|
|
1
|
+
export { EntityCodeGenerator } from './entityCodeGenerator.js';
|
|
8
2
|
export { entityTypesSource } from './entityTypes.js';
|
|
9
|
-
export { buildMigrationModule
|
|
3
|
+
export { buildMigrationModule } from './migrationFile.js';
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Source code generation for default-export migrations (`uql-migrate`), on a `SqlQuerier` or a `MongoQuerier`.
|
|
3
|
-
*/
|
|
4
1
|
/** The querier a migration module is written against. */
|
|
5
2
|
export type MigrationQuerierType = 'SqlQuerier' | 'MongoQuerier';
|
|
6
3
|
export type MigrationModuleOptions = {
|
|
@@ -20,14 +17,10 @@ export type MigrationModuleOptions = {
|
|
|
20
17
|
* Uses `JSON.stringify` so SQL with backticks (SQLite/LibSQL), quotes, `${`, etc. stays valid TS source.
|
|
21
18
|
*/
|
|
22
19
|
export declare function emitSqlRunCall(sql: string): string;
|
|
23
|
-
/** Indented `up`/`down` body: one `await querier.run(...)` per SQL string
|
|
20
|
+
/** Indented `up`/`down` body: one `await querier.run(...)` per SQL string. */
|
|
24
21
|
export declare function emitSqlRunCalls(statements: string[]): string;
|
|
25
22
|
/** Indented `up`/`down` body: one awaited driver call on `querier.db` per MongoDB command. */
|
|
26
23
|
export declare function emitMongoCommandCalls(statements: string[]): string;
|
|
27
|
-
/** Body for `up` in a manual (empty) migration scaffold. */
|
|
28
|
-
export declare const EMPTY_MANUAL_MIGRATION_UP_INNER = " // Add your migration logic here.\n // Use one await querier.run(\"...\") per SQL statement when possible (same style as generate:entities).\n // Example (Postgres):\n // await querier.run(\"CREATE TABLE \\\"users\\\" (\\\"id\\\" SERIAL PRIMARY KEY);\");\n";
|
|
29
|
-
/** Body for `down` in a manual (empty) migration scaffold. */
|
|
30
|
-
export declare const EMPTY_MANUAL_MIGRATION_DOWN_INNER = " // Add your rollback logic here.\n // await querier.run(\"DROP TABLE IF EXISTS \\\"users\\\";\");\n";
|
|
31
24
|
/** How a migration on one querier is scaffolded empty, and how a generated statement is spelled in it. */
|
|
32
25
|
export type MigrationSource = {
|
|
33
26
|
readonly querier: MigrationQuerierType;
|
|
@@ -6,7 +6,7 @@ import { mongoCommandSource } from '../../mongo/mongoCommand.js';
|
|
|
6
6
|
export function emitSqlRunCall(sql) {
|
|
7
7
|
return /*ts*/ ` await querier.run(${JSON.stringify(sql)});`;
|
|
8
8
|
}
|
|
9
|
-
/** Indented `up`/`down` body: one `await querier.run(...)` per SQL string
|
|
9
|
+
/** Indented `up`/`down` body: one `await querier.run(...)` per SQL string. */
|
|
10
10
|
export function emitSqlRunCalls(statements) {
|
|
11
11
|
return statements.map(emitSqlRunCall).join('\n');
|
|
12
12
|
}
|
|
@@ -14,22 +14,18 @@ export function emitSqlRunCalls(statements) {
|
|
|
14
14
|
export function emitMongoCommandCalls(statements) {
|
|
15
15
|
return statements.map((statement) => /*ts*/ ` await ${mongoCommandSource(statement, 'querier.db')};`).join('\n');
|
|
16
16
|
}
|
|
17
|
-
/** Body for `up` in a manual (empty) migration scaffold. */
|
|
18
|
-
export const EMPTY_MANUAL_MIGRATION_UP_INNER = ` // Add your migration logic here.
|
|
19
|
-
// Use one await querier.run("...") per SQL statement when possible (same style as generate:entities).
|
|
20
|
-
// Example (Postgres):
|
|
21
|
-
// await querier.run("CREATE TABLE \\"users\\" (\\"id\\" SERIAL PRIMARY KEY);");
|
|
22
|
-
`;
|
|
23
|
-
/** Body for `down` in a manual (empty) migration scaffold. */
|
|
24
|
-
export const EMPTY_MANUAL_MIGRATION_DOWN_INNER = ` // Add your rollback logic here.
|
|
25
|
-
// await querier.run("DROP TABLE IF EXISTS \\"users\\";");
|
|
26
|
-
`;
|
|
27
17
|
export const migrationSource = {
|
|
28
18
|
SqlQuerier: {
|
|
29
19
|
querier: 'SqlQuerier',
|
|
30
20
|
module: 'uql-orm/migrate',
|
|
31
|
-
emptyUp:
|
|
32
|
-
|
|
21
|
+
emptyUp: ` // Add your migration logic here.
|
|
22
|
+
// Use one await querier.run("...") per SQL statement when possible (same style as generate:entities).
|
|
23
|
+
// Example (Postgres):
|
|
24
|
+
// await querier.run("CREATE TABLE \\"users\\" (\\"id\\" SERIAL PRIMARY KEY);");
|
|
25
|
+
`,
|
|
26
|
+
emptyDown: ` // Add your rollback logic here.
|
|
27
|
+
// await querier.run("DROP TABLE IF EXISTS \\"users\\";");
|
|
28
|
+
`,
|
|
33
29
|
emit: emitSqlRunCalls,
|
|
34
30
|
},
|
|
35
31
|
MongoQuerier: {
|
|
@@ -2,7 +2,7 @@ import type { AbstractSqlDialect } from '../../dialect/index.js';
|
|
|
2
2
|
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
3
3
|
import { type SqlDialectName } from '../../type/index.js';
|
|
4
4
|
/** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
|
|
5
|
-
|
|
5
|
+
type DialectDefaults = {
|
|
6
6
|
/** Column types whose `DEFAULT` this engine takes only as a parenthesized expression. */
|
|
7
7
|
readonly wrapTypes?: RegExp;
|
|
8
8
|
/** Column types whose clock default must repeat their precision, captured by the pattern. */
|
|
@@ -29,3 +29,4 @@ export declare function sameDefault(desired: unknown, current: unknown, dialect:
|
|
|
29
29
|
* compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
|
|
30
30
|
*/
|
|
31
31
|
export declare function knownDefault(expression: SqlExpression, dialect: AbstractSqlDialect): SqlExpression;
|
|
32
|
+
export {};
|
|
@@ -35,9 +35,7 @@ export function formatDefaultValue(value, dialect, columnType) {
|
|
|
35
35
|
* and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
|
|
36
36
|
*/
|
|
37
37
|
export function sameDefault(desired, current, dialect) {
|
|
38
|
-
// Both spellings of "no default" are
|
|
39
|
-
// MariaDB says `null` where MySQL says nothing at all. Reading them as different values asked to
|
|
40
|
-
// `MODIFY` every nullable column, on every sync, forever.
|
|
38
|
+
// Both spellings of "no default" are one fact: MariaDB reports `null` where MySQL reports nothing.
|
|
41
39
|
if (desired == null || current == null)
|
|
42
40
|
return desired == null && current == null;
|
|
43
41
|
const [want, have] = [ddlDefault(desired, dialect), ddlDefault(current, dialect)];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type IndexType } from '../../schema/types.js';
|
|
2
|
+
import type { IndexFeature, SqlDialectName } from '../../type/index.js';
|
|
3
|
+
/** What an engine's `CREATE INDEX` can say; an index asking for anything else is refused rather than emitted. */
|
|
4
|
+
export type IndexCapabilities = {
|
|
5
|
+
/** The types its `CREATE INDEX` takes. SQLite's has no `USING`, so every type builds its plain index there. */
|
|
6
|
+
readonly types: ReadonlySet<IndexType>;
|
|
7
|
+
/** The features it can express, each supported by one engine and a hard error at the server on another. */
|
|
8
|
+
readonly features: ReadonlySet<IndexFeature>;
|
|
9
|
+
/**
|
|
10
|
+
* The types it spells as a keyword of their own (`FULLTEXT INDEX`, `VECTOR INDEX`) rather than as an access
|
|
11
|
+
* method: one table drives both, so a keyword never also leaks out as a ` USING` the engine has no word for.
|
|
12
|
+
*/
|
|
13
|
+
readonly keywords: ReadonlyMap<IndexType, string>;
|
|
14
|
+
/** What to declare instead of a type it lacks, appended to the refusal. */
|
|
15
|
+
readonly hints: ReadonlyMap<IndexType, string>;
|
|
16
|
+
};
|
|
17
|
+
/** Each engine's {@link IndexCapabilities}, total over the SQL engines. */
|
|
18
|
+
export declare const INDEX_CAPABILITIES: Readonly<Record<SqlDialectName, IndexCapabilities>>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { INDEX_TYPES } from '../../schema/types.js';
|
|
2
|
+
import { VECTOR_INDEX_TYPES } from '../../type/vector.js';
|
|
3
|
+
const NONE = new Map();
|
|
4
|
+
/** A full-text index is its own keyword in the MySQL family: `USING fulltext` is a syntax error there. */
|
|
5
|
+
const MYSQL_LIKE_KEYWORDS = new Map([['fulltext', 'FULLTEXT INDEX']]);
|
|
6
|
+
const DECLARE_VECTOR = "; declare type: 'vector' instead";
|
|
7
|
+
/** Each engine's {@link IndexCapabilities}, total over the SQL engines. */
|
|
8
|
+
export const INDEX_CAPABILITIES = {
|
|
9
|
+
/** Postgres 18's `pg_am`, with pgvector's two, and `fulltext`, which builds a `gin` one. */
|
|
10
|
+
postgres: {
|
|
11
|
+
types: new Set(['btree', 'hash', 'gin', 'gist', 'brin', 'hnsw', 'ivfflat', 'fulltext']),
|
|
12
|
+
features: new Set(['expression', 'partial', 'nullsOrder', 'opsClass', 'include', 'jsonPath']),
|
|
13
|
+
keywords: NONE,
|
|
14
|
+
hints: NONE,
|
|
15
|
+
},
|
|
16
|
+
/** v26.3 answers `hash` and `brin` "unimplemented", `ivfflat` "unrecognized"; no nulls order nor operator class. */
|
|
17
|
+
cockroachdb: {
|
|
18
|
+
types: new Set(['btree', 'gin', 'gist', 'hnsw', 'vector', 'fulltext']),
|
|
19
|
+
features: new Set(['expression', 'partial', 'include', 'jsonPath']),
|
|
20
|
+
keywords: new Map([['vector', 'VECTOR INDEX']]),
|
|
21
|
+
hints: new Map([['ivfflat', DECLARE_VECTOR]]),
|
|
22
|
+
},
|
|
23
|
+
/** No vector index: MySQL 26.7 has no distance function outside HeatWave, and `VECTOR INDEX` is MariaDB's. */
|
|
24
|
+
mysql: {
|
|
25
|
+
types: new Set(['btree', 'hash', 'fulltext']),
|
|
26
|
+
features: new Set(['expression', 'prefixLength', 'jsonPath', 'jsonArray']),
|
|
27
|
+
keywords: MYSQL_LIKE_KEYWORDS,
|
|
28
|
+
hints: new Map(VECTOR_INDEX_TYPES.map((type) => [type, '. Vector search on MySQL needs HeatWave'])),
|
|
29
|
+
},
|
|
30
|
+
/**
|
|
31
|
+
* No functional index, even on 12.3, where a generated column is the documented workaround: so no JSON index
|
|
32
|
+
* either. A vector index of its own, `CREATE VECTOR INDEX`, 11.7+.
|
|
33
|
+
*/
|
|
34
|
+
mariadb: {
|
|
35
|
+
types: new Set(['btree', 'hash', 'fulltext', 'vector']),
|
|
36
|
+
features: new Set(['prefixLength']),
|
|
37
|
+
keywords: new Map([...MYSQL_LIKE_KEYWORDS, ['vector', 'VECTOR INDEX']]),
|
|
38
|
+
hints: new Map([
|
|
39
|
+
['hnsw', DECLARE_VECTOR],
|
|
40
|
+
['ivfflat', DECLARE_VECTOR],
|
|
41
|
+
]),
|
|
42
|
+
},
|
|
43
|
+
/**
|
|
44
|
+
* 2025 rejects an expression (Msg 16216), the subquery a JSON path compiles to (Msg 1046), and any type but
|
|
45
|
+
* the rowstore B-tree, since the index built in its place fails on a `VECTOR` or `nvarchar(max)` (Msg 1978).
|
|
46
|
+
*/
|
|
47
|
+
mssql: {
|
|
48
|
+
types: new Set(['btree']),
|
|
49
|
+
features: new Set(['partial']),
|
|
50
|
+
keywords: NONE,
|
|
51
|
+
hints: NONE,
|
|
52
|
+
},
|
|
53
|
+
/** Every type builds a plain index, so an entity written for Postgres migrates; libSQL's vector is DiskANN. */
|
|
54
|
+
sqlite: {
|
|
55
|
+
types: new Set(INDEX_TYPES),
|
|
56
|
+
features: new Set(['expression', 'partial', 'jsonPath']),
|
|
57
|
+
keywords: NONE,
|
|
58
|
+
hints: NONE,
|
|
59
|
+
},
|
|
60
|
+
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../../dialect/abstractSqlDialect.js';
|
|
2
|
-
import {
|
|
2
|
+
import type { IndexType } from '../../schema/types.js';
|
|
3
3
|
import { type IndexColumnSchema, type IndexFeature, type IndexJsonPath, type IndexSchema } from '../../type/index.js';
|
|
4
|
+
import { type IndexCapabilities } from './indexCapabilities.js';
|
|
4
5
|
/** Refuses an index of a type `types` lacks, `hints` naming what to declare instead. */
|
|
5
6
|
export declare function assertIndexType(index: IndexSchema, types: ReadonlySet<IndexType>, dialectName: string, hints?: ReadonlyMap<IndexType, string>): void;
|
|
6
7
|
/** Refuses an index asking for a feature `features` lacks. */
|
|
@@ -9,36 +10,20 @@ export declare function assertIndexFeatures(index: IndexSchema, features: Readon
|
|
|
9
10
|
* `CREATE INDEX` in its portable form, which the SQLite family takes as is; the engines with more override
|
|
10
11
|
* the fragments. The migrator's own, so no runtime entry carries it.
|
|
11
12
|
*/
|
|
12
|
-
export declare class IndexDdl
|
|
13
|
-
protected readonly dialect:
|
|
14
|
-
|
|
13
|
+
export declare class IndexDdl {
|
|
14
|
+
protected readonly dialect: AbstractSqlDialect;
|
|
15
|
+
/** What this engine's `CREATE INDEX` can say. */
|
|
16
|
+
protected readonly capabilities: IndexCapabilities;
|
|
17
|
+
constructor(dialect: AbstractSqlDialect);
|
|
15
18
|
getCreateIndexStatement(tableName: string, index: IndexSchema, opts?: {
|
|
16
19
|
ifNotExists?: boolean;
|
|
17
20
|
}): string;
|
|
18
21
|
/** What an index added to a table that has rows needs run after it to serve queries; nothing, mostly. */
|
|
19
22
|
settleStatements(_tableName: string, _index: IndexSchema): string[];
|
|
20
|
-
/**
|
|
21
|
-
* Index features this dialect can express. Everything here is supported by at least one engine and
|
|
22
|
-
* refused by at least one other, so an index asking for a missing one is rejected rather than
|
|
23
|
-
* emitted: each of them is a hard error at the server, not a slower plan.
|
|
24
|
-
*/
|
|
25
|
-
protected readonly indexFeatures: ReadonlySet<IndexFeature>;
|
|
26
|
-
/**
|
|
27
|
-
* Index types this dialect's `CREATE INDEX` takes. SQLite's grammar has no `USING` clause, so every
|
|
28
|
-
* type builds the plain index it has there, which is what lets an entity written for Postgres
|
|
29
|
-
* migrate unchanged. An engine that would reject a type narrows this, and the type is refused.
|
|
30
|
-
*/
|
|
31
|
-
protected readonly indexTypes: ReadonlySet<IndexType>;
|
|
32
|
-
/** What to declare instead of a type this dialect lacks, appended to its refusal. */
|
|
33
|
-
protected readonly indexTypeHints: ReadonlyMap<IndexType, string>;
|
|
34
|
-
/**
|
|
35
|
-
* Index types this dialect spells as a keyword of their own (`FULLTEXT INDEX`, `VECTOR INDEX`)
|
|
36
|
-
* rather than as an access method after the table. One table drives both, so a type that is a
|
|
37
|
-
* keyword here can never also leak out as a ` USING` clause the engine has no word for.
|
|
38
|
-
*/
|
|
39
|
-
protected readonly indexTypeKeywords: ReadonlyMap<IndexType, string>;
|
|
40
23
|
/** The keyword an index type replaces `INDEX` with, or `INDEX` for the types that do not. */
|
|
41
24
|
protected indexKeyword(index: IndexSchema): string;
|
|
25
|
+
/** ` USING <type>`, or nothing for no type or one spelled as its own keyword. */
|
|
26
|
+
protected usingType(index: IndexSchema): string;
|
|
42
27
|
/** What the index is over, between the parentheses: a fulltext one's columns as a search matches them, else its entries. */
|
|
43
28
|
protected indexTarget(index: IndexSchema): string;
|
|
44
29
|
/** One index entry: what is indexed, its operator class if any, then its stored order. */
|
|
@@ -58,6 +43,8 @@ export declare class IndexDdl<D extends AbstractSqlDialect = AbstractSqlDialect>
|
|
|
58
43
|
protected indexColumnOrder(entry: IndexColumnSchema): string;
|
|
59
44
|
/** ` INCLUDE (...)`: non-key columns stored for index-only scans. Postgres-wire only. */
|
|
60
45
|
protected indexInclude(_index: IndexSchema): string;
|
|
46
|
+
/** The metric this engine's vector index names for the index's distance, refusing a distance it has none for. */
|
|
47
|
+
protected indexMetric(index: IndexSchema): string;
|
|
61
48
|
/** ` USING <method>`, which SQLite's grammar has no place for at all. */
|
|
62
49
|
protected indexAccessMethod(_index: IndexSchema): string;
|
|
63
50
|
/** What trails the columns: pgvector's ` WITH (m = ...)`, MySQL's ` USING btree`, MariaDB's ` M=8`. */
|