uql-orm 0.96.1 → 0.97.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/migrate/builder/types.d.ts +2 -0
- package/dist/migrate/codegen/entityCodeGenerator.js +2 -6
- package/dist/migrate/codegen/fieldOptionsSource.d.ts +1 -3
- package/dist/migrate/codegen/fieldOptionsSource.js +0 -5
- package/dist/migrate/drift/driftDetector.js +16 -0
- package/dist/migrate/generator/definitionToNode.d.ts +2 -2
- package/dist/migrate/generator/definitionToNode.js +4 -3
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +7 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +10 -11
- package/dist/migrate/introspection/baseSqlIntrospector.js +4 -4
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +2 -0
- package/dist/migrate/introspection/mssqlIntrospector.js +8 -0
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -0
- package/dist/migrate/introspection/mysqlIntrospector.js +28 -0
- package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -0
- package/dist/migrate/introspection/postgresIntrospector.js +12 -0
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +5 -0
- package/dist/migrate/introspection/sqliteIntrospector.js +14 -0
- package/dist/migrate/migrator.d.ts +5 -23
- package/dist/migrate/migrator.js +26 -80
- package/dist/migrate/schemaChange.d.ts +8 -3
- package/dist/migrate/schemaChange.js +24 -7
- package/dist/migrate/schemaGenerator.d.ts +20 -19
- package/dist/migrate/schemaGenerator.js +87 -76
- package/dist/migrate/triggerSql.d.ts +6 -8
- package/dist/migrate/triggerSql.js +14 -16
- package/dist/mongo/mongoIntrospector.d.ts +1 -3
- package/dist/mongo/mongoIntrospector.js +0 -4
- package/dist/mongo/mongoSchemaGenerator.d.ts +0 -6
- package/dist/mongo/mongoSchemaGenerator.js +0 -5
- package/dist/schema/schemaAST.js +1 -0
- package/dist/schema/schemaASTBuilder.d.ts +3 -1
- package/dist/schema/schemaASTBuilder.js +6 -4
- package/dist/schema/schemaASTDiffer.js +20 -5
- package/dist/schema/types.d.ts +23 -6
- package/dist/type/migration.d.ts +10 -19
- package/dist/util/ddlExpression.util.d.ts +11 -0
- package/dist/util/ddlExpression.util.js +24 -1
- package/dist/util/sql.util.d.ts +4 -6
- package/dist/util/sql.util.js +2 -6
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +1 -1
|
@@ -79,6 +79,8 @@ export type ForeignKeyDefinition = Except<ForeignKeySchema, 'columns'>;
|
|
|
79
79
|
* Full column definition including foreign key.
|
|
80
80
|
*/
|
|
81
81
|
export interface FullColumnDefinition extends ColumnDefinition {
|
|
82
|
+
/** The values the column accepts, lifted onto the table as its check. */
|
|
83
|
+
enum?: EnumValues;
|
|
82
84
|
/** Foreign key reference (if any) */
|
|
83
85
|
foreignKey?: ForeignKeyDefinition;
|
|
84
86
|
/** Index name (if indexed) */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { canonicalToTypeScript } from '../../schema/canonicalType.js';
|
|
2
2
|
import { DEFAULT_FOREIGN_KEY_ACTION, } from '../../schema/types.js';
|
|
3
3
|
import { camelCase, lowerFirst, pascalCase, singularize, upperFirst } from '../../util/string.util.js';
|
|
4
|
-
import { buildFieldOptionsSource,
|
|
4
|
+
import { buildFieldOptionsSource, fieldImports } from './fieldOptionsSource.js';
|
|
5
5
|
import { buildIndexDecoratorSource, indexNeedsRaw, isPlainFieldIndex } from './indexDecoratorSource.js';
|
|
6
6
|
import { memberSource, quoted } from './sourceLiteral.js';
|
|
7
7
|
/** The decorator on the other side of a relation. */
|
|
@@ -354,11 +354,7 @@ export class EntityCodeGenerator {
|
|
|
354
354
|
* `!`, which an insert leaves out anyway), `| null` where it holds NULL, `readonly` where the database computes it.
|
|
355
355
|
*/
|
|
356
356
|
function propertySource(col, propertyName) {
|
|
357
|
-
const type = col.
|
|
358
|
-
? enumMembersSource(col.enum).join(' | ')
|
|
359
|
-
: col.type.category === 'json'
|
|
360
|
-
? 'Json<unknown>'
|
|
361
|
-
: canonicalToTypeScript(col.type);
|
|
357
|
+
const type = col.type.category === 'json' ? 'Json<unknown>' : canonicalToTypeScript(col.type);
|
|
362
358
|
const written = col.generatedAs === undefined ? '' : 'readonly ';
|
|
363
359
|
if (col.nullable && !col.isPrimaryKey) {
|
|
364
360
|
return `${written}${propertyName}?: ${type} | null`;
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import type { ColumnNode
|
|
1
|
+
import type { ColumnNode } from '../../schema/types.js';
|
|
2
2
|
/** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
|
|
3
3
|
export declare function buildFieldOptionsSource(col: ColumnNode, propertyName: string, indexName?: string): string;
|
|
4
|
-
/** An enum's members as source literals, which are also the property's type as a union. */
|
|
5
|
-
export declare function enumMembersSource(members: EnumValues): string[];
|
|
6
4
|
/** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
|
|
7
5
|
export declare function fieldImports(col: ColumnNode): string[];
|
|
@@ -23,7 +23,6 @@ const OPTION_SOURCE = {
|
|
|
23
23
|
// A column is nullable unless it says otherwise, and a key is NOT NULL without saying so.
|
|
24
24
|
nullable: (col) => (col.nullable || col.isPrimaryKey ? [] : ['nullable: false']),
|
|
25
25
|
isUnique: (col) => (col.isUnique ? ['unique: true'] : []),
|
|
26
|
-
enum: (col) => (col.enum ? [`enum: [${enumMembersSource(col.enum).join(', ')}] as const`] : []),
|
|
27
26
|
defaultValue: (col) => col.defaultValue === undefined ? [] : [`defaultValue: ${defaultValueSource(col.defaultValue)}`],
|
|
28
27
|
generatedAs: (col) => (col.generatedAs ? [`computed: ${rawTag(col.generatedAs)}`, 'stored: true'] : []),
|
|
29
28
|
comment: (col) => (col.comment ? [`comment: ${quoted(col.comment)}`] : []),
|
|
@@ -52,10 +51,6 @@ export function buildFieldOptionsSource(col, propertyName, indexName) {
|
|
|
52
51
|
];
|
|
53
52
|
return `{ ${options.join(', ')} }`;
|
|
54
53
|
}
|
|
55
|
-
/** An enum's members as source literals, which are also the property's type as a union. */
|
|
56
|
-
export function enumMembersSource(members) {
|
|
57
|
-
return members.map((it) => (typeof it === 'number' ? String(it) : quoted(it)));
|
|
58
|
-
}
|
|
59
54
|
/** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
|
|
60
55
|
export function fieldImports(col) {
|
|
61
56
|
const sql = SqlExpression.isExpression(col.defaultValue) ? [sqlDefaultSource(col.defaultValue).name] : [];
|
|
@@ -39,6 +39,8 @@ export function detectDrift(expectedAST, actualAST, options = {}) {
|
|
|
39
39
|
...detectColumnDrifts(diff, opts),
|
|
40
40
|
...detectIndexDrifts(diff),
|
|
41
41
|
...detectPrimaryKeyDrifts(diff),
|
|
42
|
+
...detectOwnedDrifts('Check', diff.checks),
|
|
43
|
+
...detectOwnedDrifts('Trigger', diff.triggers),
|
|
42
44
|
...detectRelationshipDrifts(diff),
|
|
43
45
|
];
|
|
44
46
|
return {
|
|
@@ -63,6 +65,20 @@ function detectPrimaryKeyDrifts(diff) {
|
|
|
63
65
|
suggestion: 'Generate a migration to change the primary key',
|
|
64
66
|
}));
|
|
65
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* A check or trigger the database lacks, critical since rows are written otherwise than the entity says, or
|
|
70
|
+
* one uql installed that nothing declares.
|
|
71
|
+
*/
|
|
72
|
+
function detectOwnedDrifts(kind, changes) {
|
|
73
|
+
return changes.map(({ table, from, to }) => ({
|
|
74
|
+
type: 'constraint_mismatch',
|
|
75
|
+
table,
|
|
76
|
+
suggestion: 'Generate a migration to match the entity',
|
|
77
|
+
...(to
|
|
78
|
+
? { severity: 'critical', details: `${kind} "${to.name}" expected but not found in database` }
|
|
79
|
+
: { severity: 'warning', details: `${kind} "${from?.name}" exists in database but not in entity` }),
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
66
82
|
/** A key's columns as a drift names them, `none` where there is no key. */
|
|
67
83
|
function keyColumns(key) {
|
|
68
84
|
return key?.columns.join(', ') || 'none';
|
|
@@ -9,8 +9,8 @@ import type { ColumnDefinition, FullColumnDefinition, IndexDefinition, TableDefi
|
|
|
9
9
|
* `render`. Free functions and not generator methods: the dialect reaches them only through `render`.
|
|
10
10
|
*/
|
|
11
11
|
export declare function tableDefinitionToNode(def: TableDefinition, render: (sql: QueryRaw) => string): TableNode;
|
|
12
|
-
/** A builder's column without its `index` and `
|
|
13
|
-
export declare function bareColumn({ index: _index, foreignKey: _foreignKey, ...column }: FullColumnDefinition): ColumnDefinition;
|
|
12
|
+
/** A builder's column without its `index`, `foreignKey` and `enum`, which are lifted onto the table. */
|
|
13
|
+
export declare function bareColumn({ index: _index, foreignKey: _foreignKey, enum: _enum, ...column }: FullColumnDefinition): ColumnDefinition;
|
|
14
14
|
/**
|
|
15
15
|
* The index a column-level `index` or `unique` declares, or nothing: a unique column is a unique index.
|
|
16
16
|
*
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createTableNode, keyOfColumns } from '../../schema/schemaAST.js';
|
|
2
|
-
import { indexNameParts, normalizeIndexColumn, renderIndexColumn } from '../../util/ddlExpression.util.js';
|
|
2
|
+
import { enumCheck, indexNameParts, normalizeIndexColumn, renderIndexColumn } from '../../util/ddlExpression.util.js';
|
|
3
3
|
import { derivedIndexName, splitQualifiedName } from '../../util/sql.util.js';
|
|
4
4
|
/**
|
|
5
5
|
* A migration builder's table definition as the AST nodes the generators render from, so a hand-written
|
|
@@ -18,6 +18,7 @@ export function tableDefinitionToNode(def, render) {
|
|
|
18
18
|
for (const colDef of def.columns) {
|
|
19
19
|
columns.set(colDef.name, { ...bareColumn(colDef), table, referencedBy: [] });
|
|
20
20
|
}
|
|
21
|
+
table.checks.push(...def.columns.flatMap((column) => enumCheck(name, column, render)));
|
|
21
22
|
// A declared key keeps only the columns the table has, in its own order.
|
|
22
23
|
table.primaryKey = def.primaryKey
|
|
23
24
|
? { columns: def.primaryKey.filter((name) => columns.has(name)) }
|
|
@@ -27,8 +28,8 @@ export function tableDefinitionToNode(def, render) {
|
|
|
27
28
|
}
|
|
28
29
|
return table;
|
|
29
30
|
}
|
|
30
|
-
/** A builder's column without its `index` and `
|
|
31
|
-
export function bareColumn({ index: _index, foreignKey: _foreignKey, ...column }) {
|
|
31
|
+
/** A builder's column without its `index`, `foreignKey` and `enum`, which are lifted onto the table. */
|
|
32
|
+
export function bareColumn({ index: _index, foreignKey: _foreignKey, enum: _enum, ...column }) {
|
|
32
33
|
return column;
|
|
33
34
|
}
|
|
34
35
|
/**
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
2
|
+
import type { CheckSchema, TriggerSchema } from '../../schema/types.js';
|
|
2
3
|
import { type ForeignKeyAction } from '../../schema/types.js';
|
|
3
|
-
import type { ColumnSchema,
|
|
4
|
+
import type { ColumnSchema, ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerierPool, RawRow, SchemaIntrospector, SqlQuerier, StoredDefinition, TableSchema } from '../../type/index.js';
|
|
4
5
|
import { BaseSqlIntrospector } from './baseSqlIntrospector.js';
|
|
5
6
|
/**
|
|
6
7
|
* Reads the rows of one statement while introspecting a table.
|
|
@@ -42,11 +43,10 @@ export declare abstract class AbstractSqlSchemaIntrospector extends BaseSqlIntro
|
|
|
42
43
|
protected getDefinition(_read: TableRowReader, _tableName: string): Promise<StoredDefinition[] | undefined>;
|
|
43
44
|
getTableNames(): Promise<string[]>;
|
|
44
45
|
/**
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
* drop. Ownership is matched here rather than with `LIKE`, whose `_` wildcard would take in a hand-written one.
|
|
46
|
+
* The triggers uql installed on the table, each with the statements recreating it as the engine keeps it.
|
|
47
|
+
* Ownership is matched here rather than with `LIKE`, whose `_` wildcard would take in a hand-written one.
|
|
48
48
|
*/
|
|
49
|
-
|
|
49
|
+
protected getTriggers(read: TableRowReader, tableName: string): Promise<TriggerSchema[]>;
|
|
50
50
|
tableExists(tableName: string): Promise<boolean>;
|
|
51
51
|
/**
|
|
52
52
|
* Introspection reads, so `withQuerier` rather than `transaction`: the pool owns the release either
|
|
@@ -85,6 +85,8 @@ export declare abstract class AbstractSqlSchemaIntrospector extends BaseSqlIntro
|
|
|
85
85
|
protected abstract getForeignKeysQuery(tableName: string): string;
|
|
86
86
|
/** SQL query to get primary key columns. Parameter: tableName (for PRAGMA-style). */
|
|
87
87
|
protected abstract getPrimaryKeyQuery(tableName: string): string;
|
|
88
|
+
/** Every check on the table, each `expression` as the engine reprints it, which is what a rollback restores. */
|
|
89
|
+
protected abstract getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
88
90
|
/**
|
|
89
91
|
* SQL listing the triggers on the table named by its single parameter: each one's `name`, its `definition`
|
|
90
92
|
* as the engine reprints it, and what it `requires` to be recreated first. It reads what is installed, not
|
|
@@ -32,11 +32,13 @@ export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
|
|
|
32
32
|
if (!exists) {
|
|
33
33
|
return undefined;
|
|
34
34
|
}
|
|
35
|
-
const [columns, indexes, foreignKeys, primaryKey, definition] = await Promise.all([
|
|
35
|
+
const [columns, indexes, foreignKeys, primaryKey, checks, triggers, definition] = await Promise.all([
|
|
36
36
|
this.getColumns(read, tableName),
|
|
37
37
|
this.getIndexes(read, tableName),
|
|
38
38
|
this.getForeignKeys(read, tableName),
|
|
39
39
|
this.getPrimaryKey(read, tableName),
|
|
40
|
+
this.getChecks(read, tableName),
|
|
41
|
+
this.getTriggers(read, tableName),
|
|
40
42
|
this.getDefinition(read, tableName),
|
|
41
43
|
]);
|
|
42
44
|
return {
|
|
@@ -45,6 +47,8 @@ export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
|
|
|
45
47
|
primaryKey,
|
|
46
48
|
indexes,
|
|
47
49
|
foreignKeys,
|
|
50
|
+
checks,
|
|
51
|
+
triggers,
|
|
48
52
|
definition,
|
|
49
53
|
};
|
|
50
54
|
});
|
|
@@ -60,17 +64,12 @@ export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
|
|
|
60
64
|
});
|
|
61
65
|
}
|
|
62
66
|
/**
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* drop. Ownership is matched here rather than with `LIKE`, whose `_` wildcard would take in a hand-written one.
|
|
67
|
+
* The triggers uql installed on the table, each with the statements recreating it as the engine keeps it.
|
|
68
|
+
* Ownership is matched here rather than with `LIKE`, whose `_` wildcard would take in a hand-written one.
|
|
66
69
|
*/
|
|
67
|
-
async
|
|
68
|
-
const rows = await
|
|
69
|
-
return
|
|
70
|
-
const name = String(row['name']);
|
|
71
|
-
const statements = [row['requires'], row['definition']].filter(Boolean).map((sql) => String(sql));
|
|
72
|
-
return isOwnedName(name) ? [[name, statements]] : [];
|
|
73
|
-
}));
|
|
70
|
+
async getTriggers(read, tableName) {
|
|
71
|
+
const rows = await read(this.triggersQuery(), [tableName]);
|
|
72
|
+
return rows.flatMap(({ name, requires, definition }) => isOwnedName(name) ? [{ name, statements: [requires, definition].filter((sql) => typeof sql === 'string') }] : []);
|
|
74
73
|
}
|
|
75
74
|
async tableExists(tableName) {
|
|
76
75
|
return this.withSqlQuerier((querier) => this.tableExistsInternal(createTableRowReader(querier), tableName));
|
|
@@ -2,6 +2,7 @@ import { canonicalColumnType, defaultTimestampPrecision, withTimestampPrecision
|
|
|
2
2
|
import { createTableNode, keyOfColumns, SchemaAST } from '../../schema/schemaAST.js';
|
|
3
3
|
import { DEFAULT_FOREIGN_KEY_ACTION, } from '../../schema/types.js';
|
|
4
4
|
import { derivedForeignKeyName, qualifyName } from '../../util/sql.util.js';
|
|
5
|
+
import { renameIndexEntries } from '../schemaChange.js';
|
|
5
6
|
/**
|
|
6
7
|
* Base class for SQL introspectors with shared AST building logic.
|
|
7
8
|
*/
|
|
@@ -43,10 +44,7 @@ export class BaseSqlIntrospector {
|
|
|
43
44
|
...table,
|
|
44
45
|
columns: table.columns.map((column) => ({ ...column, name: own(column.name) })),
|
|
45
46
|
primaryKey: table.primaryKey && { ...table.primaryKey, columns: table.primaryKey.columns.map(own) },
|
|
46
|
-
indexes: table.indexes?.map((index) => ({
|
|
47
|
-
...index,
|
|
48
|
-
entries: index.entries.map((entry) => (entry.expression ? entry : { ...entry, column: own(entry.column) })),
|
|
49
|
-
})),
|
|
47
|
+
indexes: table.indexes?.map((index) => ({ ...index, entries: renameIndexEntries(index.entries, own) })),
|
|
50
48
|
foreignKeys: table.foreignKeys?.map((foreignKey) => ({
|
|
51
49
|
...foreignKey,
|
|
52
50
|
columns: foreignKey.columns.map(own),
|
|
@@ -95,6 +93,8 @@ export class BaseSqlIntrospector {
|
|
|
95
93
|
// key from `(b, a)`, and a flag says only that a column is *in* the key. Falls back to the flags
|
|
96
94
|
// for an introspector that reports no key of its own.
|
|
97
95
|
table.primaryKey = schema.primaryKey ?? keyOfColumns(schema.columns);
|
|
96
|
+
table.checks.push(...(schema.checks ?? []));
|
|
97
|
+
table.triggers.push(...(schema.triggers ?? []));
|
|
98
98
|
table.definition = schema.definition;
|
|
99
99
|
return table;
|
|
100
100
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CheckSchema } from '../../schema/types.js';
|
|
1
2
|
import type { ColumnSchema, ForeignKeySchema, IndexSchema } from '../../type/index.js';
|
|
2
3
|
import { AbstractSqlSchemaIntrospector, type JoinedForeignKeyRow, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
3
4
|
/**
|
|
@@ -11,6 +12,7 @@ import { AbstractSqlSchemaIntrospector, type JoinedForeignKeyRow, type TableRowR
|
|
|
11
12
|
export declare class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
12
13
|
protected readonly defaultSchemaExpr = "SCHEMA_NAME()";
|
|
13
14
|
protected triggersQuery(): string;
|
|
15
|
+
protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
14
16
|
protected getTableNamesQuery(): string;
|
|
15
17
|
protected tableExistsQuery(): string;
|
|
16
18
|
protected parseTableExistsResult([row]: {
|
|
@@ -18,6 +18,14 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
18
18
|
AND OBJECT_NAME(t.parent_id) = ${this.dialect.placeholder(1)}
|
|
19
19
|
`;
|
|
20
20
|
}
|
|
21
|
+
async getChecks(read, tableName) {
|
|
22
|
+
return read(
|
|
23
|
+
/*sql*/ `
|
|
24
|
+
SELECT k.name AS name, k.definition AS expression
|
|
25
|
+
FROM sys.check_constraints k
|
|
26
|
+
WHERE OBJECT_SCHEMA_NAME(k.parent_object_id) = ${this.schemaExpr} AND OBJECT_NAME(k.parent_object_id) = @p1
|
|
27
|
+
`, [tableName]);
|
|
28
|
+
}
|
|
21
29
|
getTableNamesQuery() {
|
|
22
30
|
return /*sql*/ `
|
|
23
31
|
SELECT TABLE_NAME as table_name
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
2
|
+
import type { CheckSchema } from '../../schema/types.js';
|
|
2
3
|
import type { ColumnSchema, ForeignKeySchema, IndexSchema } from '../../type/index.js';
|
|
3
4
|
import { AbstractSqlSchemaIntrospector, type JoinedForeignKeyRow, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
4
5
|
/**
|
|
@@ -8,6 +9,11 @@ import { AbstractSqlSchemaIntrospector, type JoinedForeignKeyRow, type TableRowR
|
|
|
8
9
|
export declare class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
9
10
|
protected readonly defaultSchemaExpr = "DATABASE()";
|
|
10
11
|
protected triggersQuery(): string;
|
|
12
|
+
/**
|
|
13
|
+
* `CHECK_CONSTRAINTS` names no table on MySQL, where a check's name is unique in its schema, so the
|
|
14
|
+
* table comes from `TABLE_CONSTRAINTS`. It reports the clause escaped as a literal's body (`\'a\'`).
|
|
15
|
+
*/
|
|
16
|
+
protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
11
17
|
protected getTableNamesQuery(): string;
|
|
12
18
|
protected tableExistsQuery(): string;
|
|
13
19
|
protected parseTableExistsResult([row]: {
|
|
@@ -56,6 +62,11 @@ type MysqlColumnRow = {
|
|
|
56
62
|
* JSON, got LONGTEXT", flagged as data loss) on a table uql created itself.
|
|
57
63
|
*/
|
|
58
64
|
export declare class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
|
|
65
|
+
/**
|
|
66
|
+
* A check's name is unique only in its table on MariaDB, whose `CHECK_CONSTRAINTS` names the table. A
|
|
67
|
+
* JSON column's `json_valid()` is its type, read by {@link mapColumnsResult}, so it is left out.
|
|
68
|
+
*/
|
|
69
|
+
protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
59
70
|
/** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
|
|
60
71
|
protected sqlText(defaultValue: string): string | undefined;
|
|
61
72
|
/** Whether an index is MariaDB's vector index, and the distance it was built for. */
|
|
@@ -17,6 +17,21 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
17
17
|
WHERE TRIGGER_SCHEMA = ${this.schemaExpr} AND EVENT_OBJECT_TABLE = ${this.dialect.placeholder(1)}
|
|
18
18
|
`;
|
|
19
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* `CHECK_CONSTRAINTS` names no table on MySQL, where a check's name is unique in its schema, so the
|
|
22
|
+
* table comes from `TABLE_CONSTRAINTS`. It reports the clause escaped as a literal's body (`\'a\'`).
|
|
23
|
+
*/
|
|
24
|
+
async getChecks(read, tableName) {
|
|
25
|
+
const rows = await read(
|
|
26
|
+
/*sql*/ `
|
|
27
|
+
SELECT k.CONSTRAINT_NAME AS name, c.CHECK_CLAUSE AS expression
|
|
28
|
+
FROM information_schema.TABLE_CONSTRAINTS k
|
|
29
|
+
JOIN information_schema.CHECK_CONSTRAINTS c
|
|
30
|
+
ON c.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA AND c.CONSTRAINT_NAME = k.CONSTRAINT_NAME
|
|
31
|
+
WHERE k.CONSTRAINT_TYPE = 'CHECK' AND k.TABLE_SCHEMA = ${this.schemaExpr} AND k.TABLE_NAME = ?
|
|
32
|
+
`, [tableName]);
|
|
33
|
+
return rows.map(({ name, expression }) => ({ name, expression: unescapeMysqlString(expression) }));
|
|
34
|
+
}
|
|
20
35
|
getTableNamesQuery() {
|
|
21
36
|
return /*sql*/ `
|
|
22
37
|
SELECT TABLE_NAME as table_name
|
|
@@ -183,6 +198,19 @@ const TIMESTAMP_TYPES = new Set(['datetime', 'timestamp']);
|
|
|
183
198
|
* JSON, got LONGTEXT", flagged as data loss) on a table uql created itself.
|
|
184
199
|
*/
|
|
185
200
|
export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
|
|
201
|
+
/**
|
|
202
|
+
* A check's name is unique only in its table on MariaDB, whose `CHECK_CONSTRAINTS` names the table. A
|
|
203
|
+
* JSON column's `json_valid()` is its type, read by {@link mapColumnsResult}, so it is left out.
|
|
204
|
+
*/
|
|
205
|
+
async getChecks(read, tableName) {
|
|
206
|
+
return read(
|
|
207
|
+
/*sql*/ `
|
|
208
|
+
SELECT CONSTRAINT_NAME AS name, CHECK_CLAUSE AS expression
|
|
209
|
+
FROM information_schema.CHECK_CONSTRAINTS
|
|
210
|
+
WHERE CONSTRAINT_SCHEMA = ${this.schemaExpr} AND TABLE_NAME = ?
|
|
211
|
+
AND CHECK_CLAUSE <> CONCAT('json_valid(\`', CONSTRAINT_NAME, '\`)')
|
|
212
|
+
`, [tableName]);
|
|
213
|
+
}
|
|
186
214
|
/** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
|
|
187
215
|
sqlText(defaultValue) {
|
|
188
216
|
return defaultValue.startsWith("'") ? undefined : defaultValue;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
2
|
+
import { type CheckSchema } from '../../schema/types.js';
|
|
2
3
|
import type { ColumnSchema, ForeignKeySchema, IndexSchema, RawRow } from '../../type/index.js';
|
|
3
4
|
import { AbstractSqlSchemaIntrospector, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
4
5
|
/**
|
|
@@ -12,6 +13,8 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
|
|
|
12
13
|
*/
|
|
13
14
|
readonly indexFacets: ReadonlySet<IndexFacet>;
|
|
14
15
|
protected triggersQuery(): string;
|
|
16
|
+
/** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
|
|
17
|
+
protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
15
18
|
protected getTableNamesQuery(): string;
|
|
16
19
|
protected tableExistsQuery(): string;
|
|
17
20
|
protected parseTableExistsResult([row]: RawRow[]): boolean;
|
|
@@ -27,6 +27,18 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
27
27
|
WHERE NOT t.tgisinternal AND n.nspname = ${this.schemaExpr} AND c.relname = ${this.dialect.placeholder(1)}
|
|
28
28
|
`;
|
|
29
29
|
}
|
|
30
|
+
/** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
|
|
31
|
+
async getChecks(read, tableName) {
|
|
32
|
+
const rows = await read(
|
|
33
|
+
/*sql*/ `
|
|
34
|
+
SELECT con.conname AS name, pg_get_expr(con.conbin, con.conrelid) AS expression
|
|
35
|
+
FROM pg_constraint con
|
|
36
|
+
JOIN pg_class t ON t.oid = con.conrelid
|
|
37
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
38
|
+
WHERE con.contype = 'c' AND t.relname = $1 AND n.nspname = ${this.schemaExpr}
|
|
39
|
+
`, [tableName]);
|
|
40
|
+
return rows.flatMap(({ name, expression }) => (expression === null ? [] : [{ name, expression }]));
|
|
41
|
+
}
|
|
30
42
|
getTableNamesQuery() {
|
|
31
43
|
return /*sql*/ `
|
|
32
44
|
SELECT table_name
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
2
|
+
import type { CheckSchema } from '../../schema/types.js';
|
|
2
3
|
import type { ColumnSchema, ForeignKeySchema, IndexSchema, StoredDefinition } from '../../type/index.js';
|
|
3
4
|
import { AbstractSqlSchemaIntrospector, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
4
5
|
/**
|
|
@@ -32,6 +33,8 @@ export declare class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospec
|
|
|
32
33
|
protected mapColumnsResult(read: TableRowReader, tableName: string, results: SqliteColumnRow[]): Promise<ColumnSchema[]>;
|
|
33
34
|
protected mapIndexesResult(read: TableRowReader, _tableName: string, results: SqliteIndexRow[]): Promise<IndexSchema[]>;
|
|
34
35
|
protected mapForeignKeysResult(_read: TableRowReader, _tableName: string, results: SqliteForeignKeyRow[]): Promise<ForeignKeySchema[]>;
|
|
36
|
+
/** The named checks in the table's `CREATE TABLE`, the only place SQLite keeps one. */
|
|
37
|
+
protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
35
38
|
/** Every statement `sqlite_master` keeps for the table, its `CREATE TABLE` first. An automatic index has none. */
|
|
36
39
|
protected getDefinition(read: TableRowReader, tableName: string): Promise<StoredDefinition[]>;
|
|
37
40
|
protected mapPrimaryKeyResult(results: SqliteColumnRow[]): string[] | undefined;
|
|
@@ -77,4 +80,6 @@ type SqliteForeignKeyRow = {
|
|
|
77
80
|
on_delete: string;
|
|
78
81
|
match: string;
|
|
79
82
|
};
|
|
83
|
+
/** Each `CONSTRAINT <name> CHECK (...)` in a `CREATE TABLE`, the only place SQLite keeps one. */
|
|
84
|
+
export declare function namedChecks(ddl: string): CheckSchema[];
|
|
80
85
|
export {};
|
|
@@ -136,6 +136,11 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
136
136
|
};
|
|
137
137
|
});
|
|
138
138
|
}
|
|
139
|
+
/** The named checks in the table's `CREATE TABLE`, the only place SQLite keeps one. */
|
|
140
|
+
async getChecks(read, tableName) {
|
|
141
|
+
const [table] = await this.getDefinition(read, tableName);
|
|
142
|
+
return table ? namedChecks(table.sql) : [];
|
|
143
|
+
}
|
|
139
144
|
/** Every statement `sqlite_master` keeps for the table, its `CREATE TABLE` first. An automatic index has none. */
|
|
140
145
|
getDefinition(read, tableName) {
|
|
141
146
|
return read(
|
|
@@ -286,3 +291,12 @@ function leadingIdentifier(entry) {
|
|
|
286
291
|
const token = entry.trimStart().replace(/^("[^"]*"|`[^`]*`|\[[^\]]*\]|[^\s(]*)[\s\S]*$/, '$1');
|
|
287
292
|
return token.replace(/^["`[]|["`\]]$/g, '');
|
|
288
293
|
}
|
|
294
|
+
/** Where a named check starts, its name quoted any way SQLite takes, up to its opening parenthesis. */
|
|
295
|
+
const NAMED_CHECK = /CONSTRAINT\s+("[^"]*"|`[^`]*`|\[[^\]]*\]|\w+)\s+CHECK\s*\(/gi;
|
|
296
|
+
/** Each `CONSTRAINT <name> CHECK (...)` in a `CREATE TABLE`, the only place SQLite keeps one. */
|
|
297
|
+
export function namedChecks(ddl) {
|
|
298
|
+
return [...ddl.matchAll(NAMED_CHECK)].map((match) => ({
|
|
299
|
+
name: leadingIdentifier(match[1]),
|
|
300
|
+
expression: parenthesized(ddl.slice(match.index + match[0].length - 1)),
|
|
301
|
+
}));
|
|
302
|
+
}
|
|
@@ -61,29 +61,6 @@ export declare class Migrator {
|
|
|
61
61
|
* Generate a migration based on entity schema differences
|
|
62
62
|
*/
|
|
63
63
|
generateFromEntities(name: string): Promise<string>;
|
|
64
|
-
/**
|
|
65
|
-
* Each entity on a table this plan does not create - a new one carries its triggers in its `CREATE` -
|
|
66
|
-
* beside the triggers uql has installed there, read once per schema. Kept only where either side has
|
|
67
|
-
* any: one declaring none on a table holding none has nothing to reconcile.
|
|
68
|
-
*/
|
|
69
|
-
private installedTriggers;
|
|
70
|
-
/**
|
|
71
|
-
* The alters, with the triggers reconciled around them. Postgres refuses to retype or drop a column a
|
|
72
|
-
* trigger names, so every trigger on a table whose columns change comes off before the alters and what
|
|
73
|
-
* its entity declares goes back on after. `down` is lazy: SQLite cannot express every alter's inverse.
|
|
74
|
-
*/
|
|
75
|
-
private alterPlan;
|
|
76
|
-
/**
|
|
77
|
-
* Each entity's triggers taken from what the catalogue holds to what it declares. Against the catalogue
|
|
78
|
-
* rather than a diff, because a trigger hangs off a table whose columns may be unchanged: a body edited
|
|
79
|
-
* on a settled table appears in no diff at all.
|
|
80
|
-
*/
|
|
81
|
-
private reconcileTriggers;
|
|
82
|
-
/**
|
|
83
|
-
* The inverse: what the reconcile created dropped, and what it dropped restored as the engine reprints
|
|
84
|
-
* it. Read off the catalogue rather than recorded by uql, and exactly right for restoring one.
|
|
85
|
-
*/
|
|
86
|
-
private revertedTriggers;
|
|
87
64
|
/**
|
|
88
65
|
* What a generated migration does that its reader must not miss: each column it drops or retypes, which
|
|
89
66
|
* can lose data, and each table it creates empty while the database holds one no entity names with the
|
|
@@ -108,6 +85,11 @@ export declare class Migrator {
|
|
|
108
85
|
getDiffs(options?: {
|
|
109
86
|
renames?: boolean;
|
|
110
87
|
}): Promise<SchemaDiff[]>;
|
|
88
|
+
/**
|
|
89
|
+
* Each check uql did not install on a table whose entity declares checks: never changed or dropped, so
|
|
90
|
+
* one an owned check replaces, such as an enum's from before checks were named, goes on enforcing itself.
|
|
91
|
+
*/
|
|
92
|
+
private noteForeignChecks;
|
|
111
93
|
/**
|
|
112
94
|
* The tables `entities` name, read a schema at a time so each is keyed as its entity spells it. Those
|
|
113
95
|
* alone: nothing else is diffed, and another table can be dropped mid-scan by whatever else is running.
|