uql-orm 0.92.0 → 0.93.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/uql-browser.min.js.map +2 -2
- package/dist/cockroachdb/cockroachDialect.js +1 -1
- package/dist/dialect/abstractSqlDialect.d.ts +45 -10
- package/dist/dialect/abstractSqlDialect.js +147 -64
- package/dist/dialect/mergeSqlDialect.d.ts +11 -2
- package/dist/dialect/mergeSqlDialect.js +28 -12
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
- package/dist/dialect/mysqlLikeSqlDialect.js +34 -21
- package/dist/dialect/pgLikeSqlDialect.d.ts +5 -1
- package/dist/dialect/pgLikeSqlDialect.js +8 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/maria/mariaDialect.d.ts +3 -1
- package/dist/maria/mariaDialect.js +3 -1
- package/dist/migrate/builder/index.d.ts +0 -1
- package/dist/migrate/builder/index.js +0 -1
- package/dist/migrate/builder/tableBuilder.js +2 -2
- package/dist/migrate/codegen/fieldOptionsSource.js +4 -11
- package/dist/migrate/ddl/defaultSql.d.ts +31 -0
- package/dist/migrate/ddl/defaultSql.js +109 -0
- package/dist/migrate/ddl/index.d.ts +1 -1
- package/dist/migrate/ddl/index.js +3 -3
- package/dist/migrate/ddl/mssqlTableDdl.d.ts +3 -1
- package/dist/migrate/ddl/mssqlTableDdl.js +4 -0
- package/dist/migrate/ddl/mysqlTableDdl.d.ts +1 -1
- package/dist/migrate/ddl/mysqlTableDdl.js +2 -2
- package/dist/migrate/ddl/pgTableDdl.d.ts +5 -1
- package/dist/migrate/ddl/pgTableDdl.js +13 -7
- package/dist/migrate/ddl/tableDdl.d.ts +9 -6
- package/dist/migrate/ddl/tableDdl.js +16 -7
- package/dist/migrate/ddl/tableRebuild.d.ts +2 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +4 -5
- package/dist/migrate/introspection/mysqlIntrospector.js +4 -2
- package/dist/migrate/schemaChange.d.ts +2 -5
- package/dist/migrate/schemaGenerator.js +2 -2
- package/dist/migrate/storage/databaseStorage.js +2 -2
- package/dist/migrate/triggerSql.js +9 -2
- package/dist/mongo/mongoDialect.d.ts +0 -2
- package/dist/mongo/mongoDialect.js +18 -14
- package/dist/mongo/mongodbQuerier.d.ts +13 -5
- package/dist/mongo/mongodbQuerier.js +39 -5
- package/dist/mssql/mssqlDialect.d.ts +9 -4
- package/dist/mssql/mssqlDialect.js +18 -5
- package/dist/postgres/postgresDialect.d.ts +5 -2
- package/dist/postgres/postgresDialect.js +5 -5
- package/dist/querier/abstractQuerier.d.ts +5 -5
- package/dist/querier/abstractQuerier.js +19 -15
- package/dist/querier/abstractQuerierPool.js +22 -22
- package/dist/querier/abstractSqlQuerier.d.ts +3 -3
- package/dist/querier/abstractSqlQuerier.js +7 -7
- package/dist/schema/schemaASTBuilder.js +2 -16
- package/dist/schema/sqlExpression.d.ts +9 -3
- package/dist/schema/sqlExpression.js +14 -0
- package/dist/schema/types.d.ts +2 -5
- package/dist/sqlite/sqliteDialect.d.ts +5 -4
- package/dist/sqlite/sqliteDialect.js +12 -4
- package/dist/type/dialect.d.ts +29 -11
- package/dist/type/dialect.js +2 -0
- package/dist/type/entity.d.ts +20 -5
- package/dist/type/migration.d.ts +7 -8
- package/dist/type/query.d.ts +12 -1
- package/dist/type/universalQuerier.d.ts +3 -3
- package/dist/util/dialect.util.d.ts +1 -1
- package/dist/util/index.d.ts +1 -1
- package/dist/util/index.js +1 -1
- package/dist/util/raw.d.ts +13 -3
- package/dist/util/raw.js +29 -3
- package/dist/util/triggerWrite.d.ts +11 -1
- package/dist/util/triggerWrite.js +14 -0
- package/package.json +10 -10
- package/skills/uql-orm/SKILL.md +22 -52
- package/dist/migrate/builder/expressions.d.ts +0 -63
- package/dist/migrate/builder/expressions.js +0 -142
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { DEFAULT_FOREIGN_KEY_ACTION } from '../../schema/types.js';
|
|
7
7
|
import { DATE_PRECISION } from '../../util/date.js';
|
|
8
|
+
import { currentTimestamp } from '../../util/raw.js';
|
|
8
9
|
import { columnForeignKey, columnIndex, indexDefinition } from '../generator/definitionToNode.js';
|
|
9
10
|
import { ColumnBuilder } from './columnBuilder.js';
|
|
10
|
-
import { expr } from './expressions.js';
|
|
11
11
|
/** Normalizes `table.index` options, where a bare string is the index name. */
|
|
12
12
|
function namedOptions(options) {
|
|
13
13
|
return typeof options === 'string' ? { name: options } : (options ?? {});
|
|
@@ -148,7 +148,7 @@ export class TableBuilder {
|
|
|
148
148
|
return this.timestampNow('updatedAt');
|
|
149
149
|
}
|
|
150
150
|
timestampNow(name) {
|
|
151
|
-
return this.timestamptz(name, { defaultValue:
|
|
151
|
+
return this.timestamptz(name, { defaultValue: currentTimestamp });
|
|
152
152
|
}
|
|
153
153
|
timestamps() {
|
|
154
154
|
this.createdAt();
|
|
@@ -2,7 +2,6 @@ import { canonicalToColumnType, isVectorCategory } from '../../schema/canonicalT
|
|
|
2
2
|
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
3
3
|
import { DATE_PRECISION } from '../../util/date.js';
|
|
4
4
|
import { isAutoIncrement } from '../../util/field.util.js';
|
|
5
|
-
import { UqlUsageError } from '../../util/uqlError.js';
|
|
6
5
|
import { quoted, rawTag } from './sourceLiteral.js';
|
|
7
6
|
/** What each field of a {@link ColumnNode} contributes to `@Field({ ... })`, in emit order; `satisfies` makes a new field answer. */
|
|
8
7
|
const OPTION_SOURCE = {
|
|
@@ -70,15 +69,9 @@ function defaultValueSource(value) {
|
|
|
70
69
|
return typeof value === 'string' ? quoted(value) : JSON.stringify(value);
|
|
71
70
|
}
|
|
72
71
|
/**
|
|
73
|
-
* A SQL default as an entity declares it, with the name to import for it:
|
|
74
|
-
*
|
|
72
|
+
* A SQL default as an entity declares it, with the name to import for it: the value uql exports by its own
|
|
73
|
+
* name (`currentTimestamp`), and `raw` for any other SQL, as introspection reads it back.
|
|
75
74
|
*/
|
|
76
|
-
function sqlDefaultSource(
|
|
77
|
-
|
|
78
|
-
return { name: 'currentTimestamp', source: 'currentTimestamp' };
|
|
79
|
-
}
|
|
80
|
-
if (value.sql === undefined) {
|
|
81
|
-
throw new UqlUsageError(`an entity declares a SQL default as raw or currentTimestamp, and '${value.kind}' is neither`);
|
|
82
|
-
}
|
|
83
|
-
return { name: 'raw', source: rawTag(value.sql) };
|
|
75
|
+
function sqlDefaultSource({ kind, sql }) {
|
|
76
|
+
return sql === undefined ? { name: kind, source: kind } : { name: 'raw', source: rawTag(sql) };
|
|
84
77
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { AbstractSqlDialect } from '../../dialect/index.js';
|
|
2
|
+
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
3
|
+
import { type SqlDialectName } from '../../type/index.js';
|
|
4
|
+
/** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
|
|
5
|
+
export type DialectDefaults = {
|
|
6
|
+
/** Column types whose `DEFAULT` this engine takes only as a parenthesized expression. */
|
|
7
|
+
readonly wrapTypes?: RegExp;
|
|
8
|
+
/** Column types whose clock default must repeat their precision, captured by the pattern. */
|
|
9
|
+
readonly preciseTypes?: RegExp;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Looked up by name rather than carried on the dialect, which keeps DDL data out of the query bundle - the
|
|
13
|
+
* same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`.
|
|
14
|
+
*/
|
|
15
|
+
export declare const DIALECT_DEFAULTS: Readonly<Record<SqlDialectName, DialectDefaults>>;
|
|
16
|
+
/**
|
|
17
|
+
* The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
|
|
18
|
+
* else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
|
|
19
|
+
* the result needs wrapping, which MySQL demands on its large types whatever the value.
|
|
20
|
+
*/
|
|
21
|
+
export declare function formatDefaultValue(value: unknown, dialect: AbstractSqlDialect, columnType?: string): string;
|
|
22
|
+
/**
|
|
23
|
+
* Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
|
|
24
|
+
* and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
|
|
25
|
+
*/
|
|
26
|
+
export declare function sameDefault(desired: unknown, current: unknown, dialect: AbstractSqlDialect): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
|
|
29
|
+
* compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
|
|
30
|
+
*/
|
|
31
|
+
export declare function knownDefault(expression: SqlExpression, dialect: AbstractSqlDialect): SqlExpression;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { SqlExpression, schemaDefault, writtenDefault } from '../../schema/sqlExpression.js';
|
|
2
|
+
import { SQL_VALUE_NAMES } from '../../type/index.js';
|
|
3
|
+
import { UqlUsageError } from '../../util/uqlError.js';
|
|
4
|
+
/** A default in schema form, its SQL compiled with no entity to read: a migration's names no field. */
|
|
5
|
+
const ddlDefault = (value, dialect) => schemaDefault(value, (sql) => dialect.compileDdl(sql));
|
|
6
|
+
/** MySQL 8.0.13+ rejects `DEFAULT 'x'` on these but accepts `DEFAULT ('x')`, whatever the value. */
|
|
7
|
+
const MYSQL_LARGE_TYPES = /^\s*(TINY|MEDIUM|LONG)?(TEXT|BLOB)|^\s*(JSON|GEOMETRY)\b/i;
|
|
8
|
+
/** A `DATETIME(3)` or `TIMESTAMP(3)`, whose fractional-second precision is captured. */
|
|
9
|
+
const MYSQL_PRECISE_TYPES = /^\s*(?:DATETIME|TIMESTAMP)\((\d)\)/i;
|
|
10
|
+
const MYSQL_DEFAULTS = { wrapTypes: MYSQL_LARGE_TYPES, preciseTypes: MYSQL_PRECISE_TYPES };
|
|
11
|
+
/**
|
|
12
|
+
* Looked up by name rather than carried on the dialect, which keeps DDL data out of the query bundle - the
|
|
13
|
+
* same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`.
|
|
14
|
+
*/
|
|
15
|
+
export const DIALECT_DEFAULTS = {
|
|
16
|
+
postgres: {},
|
|
17
|
+
cockroachdb: {},
|
|
18
|
+
mysql: MYSQL_DEFAULTS,
|
|
19
|
+
mariadb: MYSQL_DEFAULTS,
|
|
20
|
+
sqlite: {},
|
|
21
|
+
mssql: {},
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
|
|
25
|
+
* else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
|
|
26
|
+
* the result needs wrapping, which MySQL demands on its large types whatever the value.
|
|
27
|
+
*/
|
|
28
|
+
export function formatDefaultValue(value, dialect, columnType) {
|
|
29
|
+
const sql = defaultLiteral(ddlDefault(value, dialect), dialect, columnType);
|
|
30
|
+
const { wrapTypes } = DIALECT_DEFAULTS[dialect.dialectName];
|
|
31
|
+
return columnType !== undefined && wrapTypes?.test(columnType) ? `(${sql})` : sql;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
|
|
35
|
+
* and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
|
|
36
|
+
*/
|
|
37
|
+
export function sameDefault(desired, current, dialect) {
|
|
38
|
+
// Both spellings of "no default" are the same fact, and engines disagree on which they report:
|
|
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.
|
|
41
|
+
if (desired == null || current == null)
|
|
42
|
+
return desired == null && current == null;
|
|
43
|
+
const [want, have] = [ddlDefault(desired, dialect), ddlDefault(current, dialect)];
|
|
44
|
+
if (SqlExpression.isExpression(want) || SqlExpression.isExpression(have)) {
|
|
45
|
+
return (SqlExpression.isExpression(want) &&
|
|
46
|
+
SqlExpression.isExpression(have) &&
|
|
47
|
+
reprinted(formatDefaultValue(want, dialect)) === reprinted(formatDefaultValue(have, dialect)));
|
|
48
|
+
}
|
|
49
|
+
// Compared as text, since a catalogue may report a number either as a number or as its text.
|
|
50
|
+
return writtenDefault(want) === writtenDefault(have);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
|
|
54
|
+
* compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
|
|
55
|
+
*/
|
|
56
|
+
export function knownDefault(expression, dialect) {
|
|
57
|
+
const name = SQL_VALUE_NAMES.find((kind) => dialect.sqlValues[kind] !== undefined && sameDefault(new SqlExpression(kind), expression, dialect));
|
|
58
|
+
return name ? new SqlExpression(name) : expression;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Normalizes what engines reprint differently in SQL: it lowercases, collapses spacing, and strips wrapping
|
|
62
|
+
* parentheses (SQLite and MySQL drop them, SQL Server adds them) and the empty argument list of
|
|
63
|
+
* CockroachDB's `current_timestamp()`.
|
|
64
|
+
*/
|
|
65
|
+
function reprinted(sql) {
|
|
66
|
+
let text = sql
|
|
67
|
+
.toLowerCase()
|
|
68
|
+
.replace(/\s*([(),])\s*/g, '$1')
|
|
69
|
+
.replace(/\s+/g, ' ')
|
|
70
|
+
.trim();
|
|
71
|
+
while (/^\(.*\)$/s.test(text)) {
|
|
72
|
+
text = text.slice(1, -1);
|
|
73
|
+
}
|
|
74
|
+
return text.replace(/\(\)$/, '');
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Quoting is the dialect's `escape`, so a backslash in a default is escaped the way the engine reads
|
|
78
|
+
* it - MySQL takes `'a\b'` as a backspace where Postgres takes it literally. Only the cases `escape`
|
|
79
|
+
* cannot serve stay here: a boolean is `1` where booleans are integers, and a plain object or array
|
|
80
|
+
* is JSON rather than the throw and the IN-list `escape` gives them.
|
|
81
|
+
*/
|
|
82
|
+
function defaultLiteral(value, dialect, columnType) {
|
|
83
|
+
if (value === undefined || value === null) {
|
|
84
|
+
return 'NULL';
|
|
85
|
+
}
|
|
86
|
+
if (SqlExpression.isExpression(value)) {
|
|
87
|
+
return expressionSql(value, dialect, columnType);
|
|
88
|
+
}
|
|
89
|
+
if (typeof value === 'boolean') {
|
|
90
|
+
return dialect.booleanLiteral === 'native' ? (value ? 'TRUE' : 'FALSE') : value ? '1' : '0';
|
|
91
|
+
}
|
|
92
|
+
return dialect.escape(typeof value === 'object' && !(value instanceof Date) ? JSON.stringify(value) : value);
|
|
93
|
+
}
|
|
94
|
+
/** A raw expression's own SQL, else the engine's spelling of the value it names. */
|
|
95
|
+
function expressionSql({ kind, sql }, dialect, columnType) {
|
|
96
|
+
if (sql !== undefined) {
|
|
97
|
+
return sql;
|
|
98
|
+
}
|
|
99
|
+
const { preciseTypes } = DIALECT_DEFAULTS[dialect.dialectName];
|
|
100
|
+
if (kind === 'currentTimestamp' && preciseTypes) {
|
|
101
|
+
const precision = columnType === undefined ? undefined : preciseTypes.exec(columnType)?.[1];
|
|
102
|
+
return precision ? `CURRENT_TIMESTAMP(${precision})` : 'CURRENT_TIMESTAMP';
|
|
103
|
+
}
|
|
104
|
+
const spelled = kind === 'raw' ? undefined : dialect.sqlValues[kind];
|
|
105
|
+
if (spelled === undefined) {
|
|
106
|
+
throw new UqlUsageError(`${dialect.dialectName} has no ${kind}; write it as raw SQL this engine accepts`);
|
|
107
|
+
}
|
|
108
|
+
return spelled;
|
|
109
|
+
}
|
|
@@ -7,7 +7,7 @@ export { MsSqlTableDdl } from './mssqlTableDdl.js';
|
|
|
7
7
|
export { MariaIndexDdl, MySqlIndexDdl, MysqlLikeIndexDdl } from './mysqlIndexDdl.js';
|
|
8
8
|
export { MySqlTableDdl } from './mysqlTableDdl.js';
|
|
9
9
|
export { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
|
|
10
|
-
export { PgTableDdl } from './pgTableDdl.js';
|
|
10
|
+
export { CockroachTableDdl, PgTableDdl } from './pgTableDdl.js';
|
|
11
11
|
export { SqliteIndexDdl } from './sqliteIndexDdl.js';
|
|
12
12
|
export { TableDdl } from './tableDdl.js';
|
|
13
13
|
export declare function indexDdlFor(dialect: AbstractSqlDialect): IndexDdl;
|
|
@@ -4,7 +4,7 @@ import { MsSqlTableDdl } from './mssqlTableDdl.js';
|
|
|
4
4
|
import { MariaIndexDdl, MySqlIndexDdl } from './mysqlIndexDdl.js';
|
|
5
5
|
import { MySqlTableDdl } from './mysqlTableDdl.js';
|
|
6
6
|
import { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
|
|
7
|
-
import { PgTableDdl } from './pgTableDdl.js';
|
|
7
|
+
import { CockroachTableDdl, PgTableDdl } from './pgTableDdl.js';
|
|
8
8
|
import { SqliteIndexDdl } from './sqliteIndexDdl.js';
|
|
9
9
|
import { TableDdl } from './tableDdl.js';
|
|
10
10
|
export { IndexDdl } from './indexDdl.js';
|
|
@@ -13,7 +13,7 @@ export { MsSqlTableDdl } from './mssqlTableDdl.js';
|
|
|
13
13
|
export { MariaIndexDdl, MySqlIndexDdl, MysqlLikeIndexDdl } from './mysqlIndexDdl.js';
|
|
14
14
|
export { MySqlTableDdl } from './mysqlTableDdl.js';
|
|
15
15
|
export { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
|
|
16
|
-
export { PgTableDdl } from './pgTableDdl.js';
|
|
16
|
+
export { CockroachTableDdl, PgTableDdl } from './pgTableDdl.js';
|
|
17
17
|
export { SqliteIndexDdl } from './sqliteIndexDdl.js';
|
|
18
18
|
export { TableDdl } from './tableDdl.js';
|
|
19
19
|
/**
|
|
@@ -34,7 +34,7 @@ export function indexDdlFor(dialect) {
|
|
|
34
34
|
/** Each engine's table DDL, keyed by `dialectName` and exhaustive, for the same reasons as {@link INDEX_DDL}. */
|
|
35
35
|
const TABLE_DDL = {
|
|
36
36
|
postgres: PgTableDdl,
|
|
37
|
-
cockroachdb:
|
|
37
|
+
cockroachdb: CockroachTableDdl,
|
|
38
38
|
mysql: MySqlTableDdl,
|
|
39
39
|
mariadb: MySqlTableDdl,
|
|
40
40
|
mssql: MsSqlTableDdl,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ColumnSchema } from '../../type/index.js';
|
|
1
|
+
import type { Alteration, ColumnSchema } from '../../type/index.js';
|
|
2
2
|
import { TableDdl } from './tableDdl.js';
|
|
3
3
|
/**
|
|
4
4
|
* SQL Server keeps a column's `DEFAULT`, `CHECK` and `UNIQUE` as constraints under names it picks, and
|
|
@@ -17,6 +17,8 @@ export declare class MsSqlTableDdl extends TableDdl {
|
|
|
17
17
|
* constraint of its own. A `CHECK` or `UNIQUE` stays, and the server refuses a retype it blocks.
|
|
18
18
|
*/
|
|
19
19
|
alterColumn(table: string, column: ColumnSchema): string[];
|
|
20
|
+
/** One column an `ALTER COLUMN`, each with the batch {@link alterColumn} writes. */
|
|
21
|
+
alterColumns(table: string, alterations: readonly Alteration<ColumnSchema>[]): string[];
|
|
20
22
|
renameColumn(table: string, oldName: string, newName: string): string;
|
|
21
23
|
renameTable(oldName: string, newName: string): string;
|
|
22
24
|
dropIndex(table: string, index: string): string;
|
|
@@ -49,6 +49,10 @@ export class MsSqlTableDdl extends TableDdl {
|
|
|
49
49
|
}
|
|
50
50
|
return statements;
|
|
51
51
|
}
|
|
52
|
+
/** One column an `ALTER COLUMN`, each with the batch {@link alterColumn} writes. */
|
|
53
|
+
alterColumns(table, alterations) {
|
|
54
|
+
return alterations.flatMap(({ to }) => this.alterColumn(table, to));
|
|
55
|
+
}
|
|
52
56
|
renameColumn(table, oldName, newName) {
|
|
53
57
|
const qualified = `${this.dialect.escapeId(table)}.${this.dialect.escapeId(oldName)}`;
|
|
54
58
|
return /*sql*/ `EXEC sp_rename ${this.dialect.escape(qualified)}, ${this.dialect.escape(newName)}, 'COLUMN';`;
|
|
@@ -8,7 +8,7 @@ export declare class MySqlTableDdl extends TableDdl {
|
|
|
8
8
|
* is added nullable and then made required, which fails on those rows as it does on other engines.
|
|
9
9
|
*/
|
|
10
10
|
addColumnStatements(table: string, column: ColumnSchema, render: (column: ColumnSchema) => string): string[];
|
|
11
|
-
|
|
11
|
+
protected alterClauses(_column: ColumnSchema, definition: string): string[];
|
|
12
12
|
/** Ignores `schema`: MySQL reads it from the table name, which is already qualified. */
|
|
13
13
|
dropIndex(table: string, index: string): string;
|
|
14
14
|
dropForeignKey(table: string, constraint: string): string;
|
|
@@ -16,8 +16,8 @@ export class MySqlTableDdl extends TableDdl {
|
|
|
16
16
|
...this.alterColumn(table, column, render(column)),
|
|
17
17
|
];
|
|
18
18
|
}
|
|
19
|
-
|
|
20
|
-
return [`
|
|
19
|
+
alterClauses(_column, definition) {
|
|
20
|
+
return [`MODIFY COLUMN ${definition}`];
|
|
21
21
|
}
|
|
22
22
|
/** Ignores `schema`: MySQL reads it from the table name, which is already qualified. */
|
|
23
23
|
dropIndex(table, index) {
|
|
@@ -3,5 +3,9 @@ import { TableDdl } from './tableDdl.js';
|
|
|
3
3
|
/** Table DDL for the Postgres family, which alters each part of a column in a separate clause. */
|
|
4
4
|
export declare class PgTableDdl extends TableDdl {
|
|
5
5
|
/** A clause for each part that differs from `from`, the column as it was, or for every part without it. */
|
|
6
|
-
|
|
6
|
+
protected alterClauses(column: ColumnSchema, _definition: string, from?: ColumnSchema): string[];
|
|
7
|
+
}
|
|
8
|
+
/** CockroachDB refuses a rewriting retype beside any other clause, and changes a schema online anyway. */
|
|
9
|
+
export declare class CockroachTableDdl extends PgTableDdl {
|
|
10
|
+
protected alterTable(table: string, clauses: readonly string[]): string[];
|
|
7
11
|
}
|
|
@@ -1,17 +1,23 @@
|
|
|
1
|
-
import { sameDefault } from '
|
|
1
|
+
import { sameDefault } from './defaultSql.js';
|
|
2
2
|
import { TableDdl } from './tableDdl.js';
|
|
3
3
|
/** Table DDL for the Postgres family, which alters each part of a column in a separate clause. */
|
|
4
4
|
export class PgTableDdl extends TableDdl {
|
|
5
5
|
/** A clause for each part that differs from `from`, the column as it was, or for every part without it. */
|
|
6
|
-
|
|
6
|
+
alterClauses(column, _definition, from) {
|
|
7
7
|
const name = this.dialect.escapeId(column.name);
|
|
8
|
-
const alter = `ALTER
|
|
8
|
+
const alter = `ALTER COLUMN ${name}`;
|
|
9
9
|
return [
|
|
10
10
|
// Casts explicitly: Postgres converts on its own only between compatible types, and text to integer is not.
|
|
11
|
-
(!from || from.type !== column.type) && `${alter} TYPE ${column.type} USING ${name}::${column.type}
|
|
12
|
-
(!from || from.nullable !== column.nullable) && `${alter} ${column.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'}
|
|
11
|
+
(!from || from.type !== column.type) && `${alter} TYPE ${column.type} USING ${name}::${column.type}`,
|
|
12
|
+
(!from || from.nullable !== column.nullable) && `${alter} ${column.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'}`,
|
|
13
13
|
(!from || !sameDefault(column.defaultValue, from.defaultValue, this.dialect)) &&
|
|
14
|
-
(column.defaultValue === undefined ? `${alter} DROP DEFAULT
|
|
15
|
-
].filter((
|
|
14
|
+
(column.defaultValue === undefined ? `${alter} DROP DEFAULT` : `${alter} SET${this.defaultClause(column)}`),
|
|
15
|
+
].filter((clause) => clause !== false);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** CockroachDB refuses a rewriting retype beside any other clause, and changes a schema online anyway. */
|
|
19
|
+
export class CockroachTableDdl extends PgTableDdl {
|
|
20
|
+
alterTable(table, clauses) {
|
|
21
|
+
return clauses.flatMap((clause) => super.alterTable(table, [clause]));
|
|
16
22
|
}
|
|
17
23
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../../dialect/abstractSqlDialect.js';
|
|
2
|
-
import type { ColumnSchema } from '../../type/index.js';
|
|
2
|
+
import type { Alteration, ColumnSchema } from '../../type/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* A column's type with the size it was read back with, unless its spelling already carries one:
|
|
5
5
|
* introspection reports `VARCHAR` and `255` apart, where a type from an entity is already whole.
|
|
@@ -20,11 +20,14 @@ export declare class TableDdl {
|
|
|
20
20
|
/** The statements that add `column`, whose definition `render` writes. */
|
|
21
21
|
addColumnStatements(table: string, column: ColumnSchema, render: (column: ColumnSchema) => string): string[];
|
|
22
22
|
dropColumn(table: string, column: string): string[];
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
/** The statements that change a column from `from`, what it was, to `column`, whose definition is `definition`. */
|
|
24
|
+
alterColumn(table: string, column: ColumnSchema, definition: string, from?: ColumnSchema): string[];
|
|
25
|
+
/** The statements making `alterations` to one table, whose new definitions `render` writes. */
|
|
26
|
+
alterColumns(table: string, alterations: readonly Alteration<ColumnSchema>[], render: (column: ColumnSchema) => string): string[];
|
|
27
|
+
/** The `ALTER TABLE` clauses that change a column, as {@link alterColumn} takes it. */
|
|
28
|
+
protected alterClauses(_column: ColumnSchema, definition: string, _from?: ColumnSchema): string[];
|
|
29
|
+
/** One `ALTER TABLE` making every clause, and none for no clause. */
|
|
30
|
+
protected alterTable(table: string, clauses: readonly string[]): string[];
|
|
28
31
|
renameColumn(table: string, oldName: string, newName: string): string;
|
|
29
32
|
renameTable(oldName: string, newName: string): string;
|
|
30
33
|
/** `schema` is the table's schema, which also holds its indexes. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { UqlUsageError } from '../../util/uqlError.js';
|
|
2
|
-
import { formatDefaultValue } from '
|
|
2
|
+
import { formatDefaultValue } from './defaultSql.js';
|
|
3
3
|
/**
|
|
4
4
|
* A column's type with the size it was read back with, unless its spelling already carries one:
|
|
5
5
|
* introspection reports `VARCHAR` and `255` apart, where a type from an entity is already whole.
|
|
@@ -39,12 +39,21 @@ export class TableDdl {
|
|
|
39
39
|
dropColumn(table, column) {
|
|
40
40
|
return [`ALTER TABLE ${this.dialect.escapeId(table)} DROP COLUMN ${this.dialect.escapeId(column)};`];
|
|
41
41
|
}
|
|
42
|
-
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
42
|
+
/** The statements that change a column from `from`, what it was, to `column`, whose definition is `definition`. */
|
|
43
|
+
alterColumn(table, column, definition, from) {
|
|
44
|
+
return this.alterTable(table, this.alterClauses(column, definition, from));
|
|
45
|
+
}
|
|
46
|
+
/** The statements making `alterations` to one table, whose new definitions `render` writes. */
|
|
47
|
+
alterColumns(table, alterations, render) {
|
|
48
|
+
return this.alterTable(table, alterations.flatMap(({ from, to }) => this.alterClauses(to, render(to), from)));
|
|
49
|
+
}
|
|
50
|
+
/** The `ALTER TABLE` clauses that change a column, as {@link alterColumn} takes it. */
|
|
51
|
+
alterClauses(_column, definition, _from) {
|
|
52
|
+
return [`ALTER COLUMN ${definition}`];
|
|
53
|
+
}
|
|
54
|
+
/** One `ALTER TABLE` making every clause, and none for no clause. */
|
|
55
|
+
alterTable(table, clauses) {
|
|
56
|
+
return clauses.length ? [`ALTER TABLE ${this.dialect.escapeId(table)} ${clauses.join(', ')};`] : [];
|
|
48
57
|
}
|
|
49
58
|
renameColumn(table, oldName, newName) {
|
|
50
59
|
const [target, from, to] = [table, oldName, newName].map((name) => this.dialect.escapeId(name));
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../../dialect/index.js';
|
|
2
|
-
import type { RebuiltTable, Rename } from '../../type/index.js';
|
|
2
|
+
import type { Alteration, RebuiltTable, Rename } from '../../type/index.js';
|
|
3
3
|
/** What the copy reads besides the columns both sides share: renamed ones, and a default filling a column's nulls. */
|
|
4
4
|
export type RebuildCopy = {
|
|
5
5
|
readonly renames: readonly Rename[];
|
|
@@ -11,7 +11,4 @@ export type RebuildCopy = {
|
|
|
11
11
|
* key pointing at the table would delete or null its rows with the drop, so the guard fails the whole
|
|
12
12
|
* rebuild first unless foreign keys are off, as the migrator turns them off on a SQLite connection.
|
|
13
13
|
*/
|
|
14
|
-
export declare function rebuildTable(dialect: AbstractSqlDialect, table: string, { from, to }:
|
|
15
|
-
readonly from: RebuiltTable;
|
|
16
|
-
readonly to: RebuiltTable;
|
|
17
|
-
}, copy: RebuildCopy): string[];
|
|
14
|
+
export declare function rebuildTable(dialect: AbstractSqlDialect, table: string, { from, to }: Alteration<RebuiltTable>, copy: RebuildCopy): string[];
|
|
@@ -119,8 +119,8 @@ export declare abstract class AbstractSqlSchemaIntrospector extends BaseSqlIntro
|
|
|
119
119
|
/** Parses a default as the catalogue reports it: to its literal value, or through {@link sqlDefault} if SQL. */
|
|
120
120
|
protected abstract parseDefaultValue(defaultValue: string | null): unknown;
|
|
121
121
|
/**
|
|
122
|
-
* A SQL default, wrapped in parentheses
|
|
123
|
-
*
|
|
122
|
+
* A SQL default, wrapped in parentheses, or the value uql exports that it spells (`currentTimestamp`), so it
|
|
123
|
+
* compares equal on every engine and `generate:from-db` writes it by name.
|
|
124
124
|
*/
|
|
125
125
|
protected sqlDefault(sql: string): SqlExpression;
|
|
126
126
|
}
|
|
@@ -3,7 +3,7 @@ import { FOREIGN_KEY_ACTIONS } from '../../schema/types.js';
|
|
|
3
3
|
import { isSqlQuerier } from '../../type/index.js';
|
|
4
4
|
import { isOwnedName } from '../../util/sql.util.js';
|
|
5
5
|
import { UqlUsageError } from '../../util/uqlError.js';
|
|
6
|
-
import {
|
|
6
|
+
import { knownDefault } from '../ddl/defaultSql.js';
|
|
7
7
|
import { BaseSqlIntrospector } from './baseSqlIntrospector.js';
|
|
8
8
|
/** A SQL introspector: an engine states its catalogue queries (`get*Query`) and how their rows map (`map*Result`). */
|
|
9
9
|
export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
|
|
@@ -175,12 +175,11 @@ export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
|
|
|
175
175
|
return name === undefined || name === null ? undefined : String(name);
|
|
176
176
|
}
|
|
177
177
|
/**
|
|
178
|
-
* A SQL default, wrapped in parentheses
|
|
179
|
-
*
|
|
178
|
+
* A SQL default, wrapped in parentheses, or the value uql exports that it spells (`currentTimestamp`), so it
|
|
179
|
+
* compares equal on every engine and `generate:from-db` writes it by name.
|
|
180
180
|
*/
|
|
181
181
|
sqlDefault(sql) {
|
|
182
|
-
|
|
183
|
-
return sameDefault(expr.now(), expression, this.dialect) ? expr.now() : expression;
|
|
182
|
+
return knownDefault(SqlExpression.parenthesized(sql), this.dialect);
|
|
184
183
|
}
|
|
185
184
|
}
|
|
186
185
|
/** A {@link TableRowReader} over one querier: the same statement is only ever sent once. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
1
2
|
import { unescapeMysqlString } from '../../util/sqlLiteral.js';
|
|
2
|
-
import { expr } from '../builder/expressions.js';
|
|
3
3
|
import { AbstractSqlSchemaIntrospector, } from './abstractSqlSchemaIntrospector.js';
|
|
4
4
|
/**
|
|
5
5
|
* MySQL/MariaDB schema introspector.
|
|
@@ -155,7 +155,9 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
155
155
|
const sql = introduced ? undefined : this.sqlText(defaultValue, extra);
|
|
156
156
|
if (sql !== undefined) {
|
|
157
157
|
// Any precision here repeats the column's own, which the column type already states.
|
|
158
|
-
return /^CURRENT_TIMESTAMP(?:\(\d?\))?$/i.test(sql)
|
|
158
|
+
return /^CURRENT_TIMESTAMP(?:\(\d?\))?$/i.test(sql)
|
|
159
|
+
? new SqlExpression('currentTimestamp')
|
|
160
|
+
: this.sqlDefault(sql);
|
|
159
161
|
}
|
|
160
162
|
const literal = introduced ? unescapeMysqlString(introduced[1]) : defaultValue;
|
|
161
163
|
const quoted = /^'(.*)'$/s.exec(literal);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Change, ColumnSchema, SchemaDiff } from '../type/index.js';
|
|
1
|
+
import type { Alteration, Change, ColumnSchema, SchemaDiff } from '../type/index.js';
|
|
2
2
|
/** Each change's end on `side`, where it has one: what a drop half removes (`from`), or an add half creates (`to`). */
|
|
3
3
|
export declare function sides<T>(changes: readonly Change<T>[] | undefined, side: 'from' | 'to'): T[];
|
|
4
4
|
/** What the changes add: each `to` with no `from`. */
|
|
@@ -6,10 +6,7 @@ export declare function added<T>(changes?: readonly Change<T>[]): T[];
|
|
|
6
6
|
/** What the changes drop: each `from` with no `to`. */
|
|
7
7
|
export declare function dropped<T>(changes?: readonly Change<T>[]): T[];
|
|
8
8
|
/** The changes that alter an object in place, which only a column can. */
|
|
9
|
-
export declare function alterations<T>(changes?: readonly Change<T>[]):
|
|
10
|
-
readonly from: T;
|
|
11
|
-
readonly to: T;
|
|
12
|
-
}[];
|
|
9
|
+
export declare function alterations<T>(changes?: readonly Change<T>[]): Alteration<T>[];
|
|
13
10
|
/** Each column `changes` make required on the rows already there: added so, or no longer nullable. */
|
|
14
11
|
export declare function newlyRequired(changes?: readonly Change<ColumnSchema>[]): {
|
|
15
12
|
readonly from?: ColumnSchema;
|
|
@@ -7,8 +7,8 @@ import { DEFAULT_FOREIGN_KEY_ACTION, } from '../schema/types.js';
|
|
|
7
7
|
import { qualifyName } from '../util/index.js';
|
|
8
8
|
import { derivedCheckName, derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName } from '../util/sql.util.js';
|
|
9
9
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
10
|
-
import { formatDefaultValue, sameDefault } from './builder/expressions.js';
|
|
11
10
|
import { splitSqlStatements } from './builder/splitSqlStatements.js';
|
|
11
|
+
import { formatDefaultValue, sameDefault } from './ddl/defaultSql.js';
|
|
12
12
|
import { indexDdlFor, tableDdlFor } from './ddl/index.js';
|
|
13
13
|
import { sizedType } from './ddl/tableDdl.js';
|
|
14
14
|
import { rebuildTable } from './ddl/tableRebuild.js';
|
|
@@ -200,7 +200,7 @@ export class SqlSchemaGenerator {
|
|
|
200
200
|
const name = this.escapeId(column);
|
|
201
201
|
return `UPDATE ${target} SET ${name} = ${value} WHERE ${name} IS NULL;`;
|
|
202
202
|
}),
|
|
203
|
-
...alterations(columns)
|
|
203
|
+
...this.tableDdl.alterColumns(tableName, alterations(columns), (column) => this.generateColumnDefinitionFromSchema(column)),
|
|
204
204
|
...dropped(columns).flatMap((column) => this.tableDdl.dropColumn(tableName, column.name)),
|
|
205
205
|
...this.addIndexStatements(tableName, sides(diff.indexes, 'to')),
|
|
206
206
|
...(primaryKey?.to ? [this.generateAddPrimaryKeySql(tableName, primaryKey.to.columns, primaryKey.to.name)] : []),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { currentTimestamp } from '../../util/raw.js';
|
|
1
2
|
import { withSqlQuerierForMigrations } from '../acquireQuerierForMigrations.js';
|
|
2
|
-
import { expr } from '../builder/expressions.js';
|
|
3
3
|
import { TableBuilder } from '../builder/tableBuilder.js';
|
|
4
4
|
import { SqlSchemaGenerator } from '../schemaGenerator.js';
|
|
5
5
|
/** Where executed migrations are recorded when the config does not name a table. */
|
|
@@ -32,7 +32,7 @@ export class DatabaseMigrationStorage {
|
|
|
32
32
|
async createTableIfNotExists(querier) {
|
|
33
33
|
const table = new TableBuilder(this.tableName);
|
|
34
34
|
table.string('name', { length: 255, primaryKey: true });
|
|
35
|
-
table.timestamptz('executed_at', { defaultValue:
|
|
35
|
+
table.timestamptz('executed_at', { defaultValue: currentTimestamp });
|
|
36
36
|
const generator = new SqlSchemaGenerator(querier.dialect);
|
|
37
37
|
for (const sql of generator.generateCreateTableFromDefinition(table.build(), { ifNotExists: true })) {
|
|
38
38
|
await querier.run(sql);
|
|
@@ -50,6 +50,9 @@ function triggerStatements(dialect, meta, trigger, name) {
|
|
|
50
50
|
const features = dialect.features.triggers;
|
|
51
51
|
const [timing, operation] = EVENT_PARTS[trigger.on];
|
|
52
52
|
const before = timing === 'BEFORE';
|
|
53
|
+
if (trigger.deferred && !features.deferrable) {
|
|
54
|
+
throw new UqlUsageError(`${dialect.dialectName} cannot defer a trigger to commit, which ${meta.entity.name} asks for; only Postgres can`);
|
|
55
|
+
}
|
|
53
56
|
const { fires } = features;
|
|
54
57
|
const perStatement = fires === 'eachStatement';
|
|
55
58
|
const names = rowNames(dialect);
|
|
@@ -76,9 +79,13 @@ function triggerStatements(dialect, meta, trigger, name) {
|
|
|
76
79
|
const each = perStatement ? '' : '\nFOR EACH ROW';
|
|
77
80
|
const whenClause = filter && byWhen ? `\nWHEN (${filter})` : '';
|
|
78
81
|
const event = `${timing} ${operation}${of}`;
|
|
82
|
+
// Deferred, it is a constraint trigger, which is what Postgres lets wait for the commit.
|
|
83
|
+
const [kind, deferral] = trigger.deferred
|
|
84
|
+
? ['CONSTRAINT TRIGGER', '\nDEFERRABLE INITIALLY DEFERRED']
|
|
85
|
+
: ['TRIGGER', ''];
|
|
79
86
|
const header = features.layout === 'tableFirst'
|
|
80
|
-
? `CREATE
|
|
81
|
-
: `CREATE
|
|
87
|
+
? `CREATE ${kind} ${id}\nON ${table} ${event}${each}${whenClause}\nAS`
|
|
88
|
+
: `CREATE ${kind} ${id}\n${event} ON ${table}${deferral}${each}${whenClause}`;
|
|
82
89
|
if (features.body !== 'function') {
|
|
83
90
|
return [`${header}\nBEGIN\n${opened}\nEND`];
|
|
84
91
|
}
|
|
@@ -79,8 +79,6 @@ export declare class MongoDialect extends AbstractDialect {
|
|
|
79
79
|
* Each end is one field matched against one `_id`, so both sides must be sole-keyed.
|
|
80
80
|
*/
|
|
81
81
|
private junctionOf;
|
|
82
|
-
/** `raw()` renders SQL, so it has no MongoDB equivalent - say so instead of emitting `{}`. */
|
|
83
|
-
private assertNoRaw;
|
|
84
82
|
/**
|
|
85
83
|
* A dotted key addresses an embedded path, whose root must still be a declared field - otherwise it
|
|
86
84
|
* is a typo (or an injected key) that would silently match nothing, the same guard the SQL dialects
|