uql-orm 0.107.3 → 0.108.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/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +5 -5
- package/dist/cockroachdb/cockroachDialect.d.ts +1 -4
- package/dist/cockroachdb/cockroachDialect.js +1 -5
- package/dist/dialect/abstractSqlDialect.d.ts +84 -43
- package/dist/dialect/abstractSqlDialect.js +270 -192
- package/dist/dialect/aliases.d.ts +2 -0
- package/dist/dialect/aliases.js +2 -0
- package/dist/dialect/jsonSql.d.ts +9 -7
- package/dist/dialect/jsonSql.js +16 -10
- package/dist/dialect/mergeSqlDialect.d.ts +5 -7
- package/dist/dialect/mergeSqlDialect.js +20 -19
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
- package/dist/dialect/mysqlLikeSqlDialect.js +34 -12
- package/dist/dialect/operators.d.ts +7 -1
- package/dist/dialect/operators.js +37 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +4 -4
- package/dist/dialect/pgLikeSqlDialect.js +8 -7
- package/dist/entity/index.d.ts +1 -1
- package/dist/entity/index.js +1 -1
- package/dist/entity/metadata/definedFixture/author.d.ts +4 -4
- package/dist/entity/metadata/definedFixture/book.d.ts +5 -5
- package/dist/entity/metadata/definition.d.ts +2 -0
- package/dist/entity/metadata/definition.js +19 -11
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mariadb/mariaDialect.d.ts +2 -2
- package/dist/mariadb/mariaDialect.js +3 -2
- package/dist/migrate/codegen/fieldOptionsSource.js +28 -7
- package/dist/migrate/ddl/defaultSql.d.ts +3 -2
- package/dist/migrate/ddl/defaultSql.js +8 -12
- package/dist/migrate/ddl/mysqlTableDdl.js +1 -1
- package/dist/migrate/ddl/tableDdl.d.ts +1 -1
- package/dist/migrate/drift/driftDetector.js +10 -3
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +2 -2
- package/dist/migrate/migrator.js +2 -1
- package/dist/migrate/schemaChange.d.ts +0 -2
- package/dist/migrate/schemaChange.js +1 -4
- package/dist/migrate/schemaGenerator.d.ts +2 -2
- package/dist/migrate/triggerSql.js +11 -15
- package/dist/mongodb/mongoDialect.d.ts +6 -1
- package/dist/mongodb/mongoDialect.js +90 -46
- package/dist/mongodb/mongoSchemaGenerator.js +2 -2
- package/dist/mongodb/mongodbQuerier.d.ts +7 -9
- package/dist/mongodb/mongodbQuerier.js +54 -47
- package/dist/mssql/mssqlDialect.d.ts +9 -9
- package/dist/mssql/mssqlDialect.js +51 -28
- package/dist/mssql/mssqlWireTypes.d.ts +1 -4
- package/dist/mssql/mssqlWireTypes.js +19 -10
- package/dist/querier/abstractQuerier.d.ts +53 -29
- package/dist/querier/abstractQuerier.js +154 -102
- package/dist/querier/abstractSqlQuerier.d.ts +41 -10
- package/dist/querier/abstractSqlQuerier.js +145 -79
- package/dist/schema/declaredColumn.js +2 -2
- package/dist/schema/schemaASTDiffer.d.ts +3 -3
- package/dist/schema/sqlExpression.d.ts +7 -5
- package/dist/schema/sqlExpression.js +20 -16
- package/dist/schema/types.d.ts +8 -2
- package/dist/sqlite/sqliteDialect.js +1 -2
- package/dist/type/definedEntity.d.ts +5 -5
- package/dist/type/dialect.d.ts +26 -15
- package/dist/type/entity.d.ts +14 -8
- package/dist/type/query.d.ts +7 -2
- package/dist/type/queryAggregate.d.ts +4 -4
- package/dist/type/querySql.d.ts +4 -1
- package/dist/type/querySql.js +5 -1
- package/dist/type/queryWhere.d.ts +16 -11
- package/dist/type/universalQuerier.d.ts +7 -7
- package/dist/util/ddlExpression.util.d.ts +5 -0
- package/dist/util/ddlExpression.util.js +9 -2
- package/dist/util/dialect.util.d.ts +14 -6
- package/dist/util/dialect.util.js +17 -13
- package/dist/util/field.util.d.ts +12 -0
- package/dist/util/field.util.js +17 -1
- package/dist/util/fieldOption.util.js +5 -1
- package/dist/util/object.util.d.ts +4 -0
- package/dist/util/object.util.js +13 -0
- package/dist/util/query.util.d.ts +5 -3
- package/dist/util/query.util.js +7 -2
- package/dist/util/sql.d.ts +25 -7
- package/dist/util/sql.js +58 -18
- package/dist/util/triggerWrite.d.ts +7 -4
- package/dist/util/triggerWrite.js +5 -4
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +10 -8
|
@@ -169,10 +169,10 @@ export function defineEntity(options) {
|
|
|
169
169
|
declaredEntities.set(entity, { options, sections: {} });
|
|
170
170
|
for (const section of SECTIONS) {
|
|
171
171
|
Object.defineProperty(entity, section, {
|
|
172
|
-
value(declared,
|
|
172
|
+
value(declared, aggregates) {
|
|
173
173
|
declareSection(this, section, declared);
|
|
174
|
-
if (section === 'relations' &&
|
|
175
|
-
declareSection(this, '
|
|
174
|
+
if (section === 'relations' && aggregates) {
|
|
175
|
+
declareSection(this, 'aggregates', aggregates);
|
|
176
176
|
}
|
|
177
177
|
return this;
|
|
178
178
|
},
|
|
@@ -180,7 +180,7 @@ export function defineEntity(options) {
|
|
|
180
180
|
}
|
|
181
181
|
return entity;
|
|
182
182
|
}
|
|
183
|
-
/** The sections a defined entity declares as methods. `
|
|
183
|
+
/** The sections a defined entity declares as methods. `aggregates` is no method: `relations` takes it as its second argument. */
|
|
184
184
|
const SECTIONS = ['computed', 'indexes', 'checks', 'triggers', 'filters', 'hooks', 'relations'];
|
|
185
185
|
/** Records one section of a pending defined entity, refusing a second of it and one declared after the entity was read. */
|
|
186
186
|
function declareSection(entity, section, declared) {
|
|
@@ -208,7 +208,7 @@ function settleEntity(entity) {
|
|
|
208
208
|
const refs = memberRefs();
|
|
209
209
|
for (const added of [
|
|
210
210
|
fieldsOf(options.name, sections.computed?.(refs) ?? {}),
|
|
211
|
-
fieldsOf(options.name,
|
|
211
|
+
fieldsOf(options.name, readAggregates(sections.aggregates, refs)),
|
|
212
212
|
]) {
|
|
213
213
|
const taken = Object.keys(added).find((key) => key in fields);
|
|
214
214
|
if (taken) {
|
|
@@ -256,9 +256,9 @@ function fieldsOf(name, values) {
|
|
|
256
256
|
function isColumn(field) {
|
|
257
257
|
return isRecord(field) && COLUMN_OPTIONS in field;
|
|
258
258
|
}
|
|
259
|
-
/** A relation's
|
|
260
|
-
function
|
|
261
|
-
return Object.fromEntries(Object.entries(
|
|
259
|
+
/** A relation's aggregate fields, each a thunk read lazily; a value that is no thunk is passed on to be refused. */
|
|
260
|
+
function readAggregates(aggregates, refs) {
|
|
261
|
+
return Object.fromEntries(Object.entries(aggregates?.(refs) ?? {}).map(([key, read]) => [key, typeof read === 'function' ? read() : read]));
|
|
262
262
|
}
|
|
263
263
|
const RELATION_BUILDER = {
|
|
264
264
|
oneToOne: (target, options) => ({ target, cardinality: '11', options }),
|
|
@@ -280,7 +280,11 @@ function settleRelations(meta) {
|
|
|
280
280
|
const declared = declaredEntities.get(meta.entity)?.sections.relations;
|
|
281
281
|
for (const [key, read] of Object.entries(declared?.(RELATION_BUILDER) ?? {})) {
|
|
282
282
|
const { target, cardinality, options } = read();
|
|
283
|
-
addRelation(meta, key, relationRegistration({
|
|
283
|
+
addRelation(meta, key, relationRegistration({
|
|
284
|
+
...options,
|
|
285
|
+
cardinality,
|
|
286
|
+
entity: () => relationTable(target),
|
|
287
|
+
}));
|
|
284
288
|
}
|
|
285
289
|
// A copy per entity: resolving a relation writes the columns it joins on into it, and those are the resolving
|
|
286
290
|
// entity's, so one shared object would leave every later entity without them.
|
|
@@ -421,7 +425,11 @@ export function relationOf(meta, key) {
|
|
|
421
425
|
}
|
|
422
426
|
/** Whether the row names every column of its primary key, `0` and `''` included. */
|
|
423
427
|
export function namesKey(meta, row) {
|
|
424
|
-
return meta.ids
|
|
428
|
+
return namesEvery(row, meta.ids);
|
|
429
|
+
}
|
|
430
|
+
/** Whether the row holds a value in each of `keys`, `0` and `''` included: a null one names no row, nor conflicts. */
|
|
431
|
+
export function namesEvery(row, keys) {
|
|
432
|
+
return keys.every((key) => row[key] != null);
|
|
425
433
|
}
|
|
426
434
|
/** A row's primary key: its value, or a map of every column on a composite, checked at run time. */
|
|
427
435
|
export function idOf(meta, row) {
|
|
@@ -448,7 +456,7 @@ export function getEntities() {
|
|
|
448
456
|
.filter(isTable);
|
|
449
457
|
}
|
|
450
458
|
/** The class a defined relation targets, refused where it is abstract: a relation needs a table to join. */
|
|
451
|
-
function
|
|
459
|
+
function relationTable(target) {
|
|
452
460
|
if (!isTable(target)) {
|
|
453
461
|
throw new UqlUsageError(`'${target.name}' is abstract: a relation needs a table to join`);
|
|
454
462
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,6 @@ export { filledKey, idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
|
10
10
|
export { withDeleted } from './util/filters.util.js';
|
|
11
11
|
export { sortOf } from './util/query.util.js';
|
|
12
12
|
export { DefaultLogger } from './util/logger.js';
|
|
13
|
-
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, uuid, uuidv7 } from './util/sql.js';
|
|
13
|
+
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, tableOf, uuid, uuidv7 } from './util/sql.js';
|
|
14
14
|
export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
|
|
15
15
|
export { type QueryErrorKind, UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
|
package/dist/index.js
CHANGED
|
@@ -9,6 +9,6 @@ export { filledKey, idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
|
9
9
|
export { withDeleted } from './util/filters.util.js';
|
|
10
10
|
export { sortOf } from './util/query.util.js';
|
|
11
11
|
export { DefaultLogger } from './util/logger.js';
|
|
12
|
-
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, uuid, uuidv7 } from './util/sql.js';
|
|
12
|
+
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, tableOf, uuid, uuidv7 } from './util/sql.js';
|
|
13
13
|
export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
|
|
14
14
|
export { UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
|
|
@@ -7,8 +7,8 @@ export declare class MariaDialect extends MysqlLikeSqlDialect {
|
|
|
7
7
|
readonly insertIdSource = "returning";
|
|
8
8
|
/**
|
|
9
9
|
* Unlike MySQL: `VECTOR(n)` takes its dimension and binds as packed float32 bytes, every column of a
|
|
10
|
-
* vector index has to be NOT NULL, `CREATE INDEX` takes `IF NOT EXISTS`,
|
|
11
|
-
* to one table of a join
|
|
10
|
+
* vector index has to be NOT NULL, `CREATE INDEX` takes `IF NOT EXISTS`, a lock cannot be narrowed
|
|
11
|
+
* to one table of a join, and every write but an `UPDATE` takes a `RETURNING`.
|
|
12
12
|
*/
|
|
13
13
|
readonly features: SqlDialectFeatures;
|
|
14
14
|
/** `UUID_v7()` is MariaDB 11.7+; an older server refuses it itself. */
|
|
@@ -9,11 +9,12 @@ export class MariaDialect extends MysqlLikeSqlDialect {
|
|
|
9
9
|
insertIdSource = 'returning';
|
|
10
10
|
/**
|
|
11
11
|
* Unlike MySQL: `VECTOR(n)` takes its dimension and binds as packed float32 bytes, every column of a
|
|
12
|
-
* vector index has to be NOT NULL, `CREATE INDEX` takes `IF NOT EXISTS`,
|
|
13
|
-
* to one table of a join
|
|
12
|
+
* vector index has to be NOT NULL, `CREATE INDEX` takes `IF NOT EXISTS`, a lock cannot be narrowed
|
|
13
|
+
* to one table of a join, and every write but an `UPDATE` takes a `RETURNING`.
|
|
14
14
|
*/
|
|
15
15
|
features = {
|
|
16
16
|
...MYSQL_FEATURES,
|
|
17
|
+
reportsWrites: ['insert', 'delete', 'upsert'],
|
|
17
18
|
vectorSupportsLength: true,
|
|
18
19
|
vectorBytes: true,
|
|
19
20
|
vectorIndexRequiresNotNull: true,
|
|
@@ -2,6 +2,8 @@ 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 { jsonDocument } from '../../util/object.util.js';
|
|
6
|
+
import { escapeSingleQuotes } from '../../util/sqlLiteral.js';
|
|
5
7
|
import { quoted, sqlTag } from './sourceLiteral.js';
|
|
6
8
|
/**
|
|
7
9
|
* What each field of a {@link ColumnNode} chains onto its builder, in emit order; `satisfies` makes a new field
|
|
@@ -23,7 +25,10 @@ const METHOD_SOURCE = {
|
|
|
23
25
|
? []
|
|
24
26
|
: [col.isAutoIncrement ? '.autoIncrement()' : '.autoIncrement(false)'],
|
|
25
27
|
isUnique: (col) => (col.isUnique ? ['.unique()'] : []),
|
|
26
|
-
defaultValue: (col) =>
|
|
28
|
+
defaultValue: (col) => {
|
|
29
|
+
const value = defaultSource(col);
|
|
30
|
+
return value ? [`.default(${value.source})`] : [];
|
|
31
|
+
},
|
|
27
32
|
// Without this the entity maps to a column named after the property, which for anything the
|
|
28
33
|
// transformer rewrote - every `user_id` - is a column the database does not have.
|
|
29
34
|
name: (col, propertyName) => (propertyName === col.name ? [] : [`.name(${quoted(col.name)})`]),
|
|
@@ -58,15 +63,31 @@ export function fieldDecoratorSource(builder, col) {
|
|
|
58
63
|
}
|
|
59
64
|
/** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
|
|
60
65
|
export function fieldImports(col) {
|
|
61
|
-
const
|
|
62
|
-
return [...(col.generatedAs === undefined ? [] : ['sql']), ...
|
|
66
|
+
const name = defaultSource(col)?.name;
|
|
67
|
+
return [...(col.generatedAs === undefined ? [] : ['sql']), ...(name ? [name] : [])];
|
|
63
68
|
}
|
|
64
|
-
/**
|
|
65
|
-
|
|
69
|
+
/**
|
|
70
|
+
* A column's default as source code, with the name it imports: SQL the way an entity declares it, a JSON column's
|
|
71
|
+
* text as the document it spells (as SQL where that document is itself JSON text), and any other string quoted.
|
|
72
|
+
*/
|
|
73
|
+
function defaultSource(col) {
|
|
74
|
+
const value = col.defaultValue;
|
|
75
|
+
if (value === undefined) {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
66
78
|
if (SqlExpression.isExpression(value)) {
|
|
67
|
-
return sqlDefaultSource(value)
|
|
79
|
+
return sqlDefaultSource(value);
|
|
80
|
+
}
|
|
81
|
+
if (col.type.category === 'json' && typeof value === 'string') {
|
|
82
|
+
const document = jsonDocument(value);
|
|
83
|
+
if (typeof document === 'string' && jsonDocument(document) !== undefined) {
|
|
84
|
+
return { source: sqlTag(`'${escapeSingleQuotes(value)}'`), name: 'sql' };
|
|
85
|
+
}
|
|
86
|
+
if (document !== undefined) {
|
|
87
|
+
return { source: JSON.stringify(document) };
|
|
88
|
+
}
|
|
68
89
|
}
|
|
69
|
-
return typeof value === 'string' ? quoted(value) : JSON.stringify(value);
|
|
90
|
+
return { source: typeof value === 'string' ? quoted(value) : JSON.stringify(value) };
|
|
70
91
|
}
|
|
71
92
|
/**
|
|
72
93
|
* A SQL default as an entity declares it, with the name to import for it: the value uql exports by its own
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../../dialect/index.js';
|
|
2
2
|
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
3
|
+
import type { ColumnDefault } from '../../schema/types.js';
|
|
3
4
|
import { type SqlDialectName } from '../../type/index.js';
|
|
4
5
|
/** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
|
|
5
6
|
type DialectDefaults = {
|
|
@@ -18,12 +19,12 @@ export declare const DIALECT_DEFAULTS: Readonly<Record<SqlDialectName, DialectDe
|
|
|
18
19
|
* else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
|
|
19
20
|
* the result needs wrapping, which MySQL demands on its large types whatever the value.
|
|
20
21
|
*/
|
|
21
|
-
export declare function formatDefaultValue(value:
|
|
22
|
+
export declare function formatDefaultValue(value: ColumnDefault | undefined, dialect: AbstractSqlDialect, columnType?: string): string;
|
|
22
23
|
/**
|
|
23
24
|
* Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
|
|
24
25
|
* and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
|
|
25
26
|
*/
|
|
26
|
-
export declare function sameDefault(
|
|
27
|
+
export declare function sameDefault(want: ColumnDefault | undefined, have: ColumnDefault | undefined, dialect: AbstractSqlDialect): boolean;
|
|
27
28
|
/**
|
|
28
29
|
* Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
|
|
29
30
|
* compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { SqlExpression,
|
|
1
|
+
import { SqlExpression, writtenDefault } from '../../schema/sqlExpression.js';
|
|
2
2
|
import { SQL_VALUE_NAMES } from '../../type/index.js';
|
|
3
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
4
|
/** MySQL 8.0.13+ rejects `DEFAULT 'x'` on these but accepts `DEFAULT ('x')`, whatever the value. */
|
|
7
5
|
const MYSQL_LARGE_TYPES = /^\s*(TINY|MEDIUM|LONG)?(TEXT|BLOB)|^\s*(JSON|GEOMETRY)\b/i;
|
|
8
6
|
/** A `DATETIME(3)` or `TIMESTAMP(3)`, whose fractional-second precision is captured. */
|
|
@@ -26,7 +24,7 @@ export const DIALECT_DEFAULTS = {
|
|
|
26
24
|
* the result needs wrapping, which MySQL demands on its large types whatever the value.
|
|
27
25
|
*/
|
|
28
26
|
export function formatDefaultValue(value, dialect, columnType) {
|
|
29
|
-
const sql = defaultLiteral(
|
|
27
|
+
const sql = defaultLiteral(value, dialect, columnType);
|
|
30
28
|
const { wrapTypes } = DIALECT_DEFAULTS[dialect.dialectName];
|
|
31
29
|
return columnType !== undefined && wrapTypes?.test(columnType) ? `(${sql})` : sql;
|
|
32
30
|
}
|
|
@@ -34,11 +32,10 @@ export function formatDefaultValue(value, dialect, columnType) {
|
|
|
34
32
|
* Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
|
|
35
33
|
* and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
|
|
36
34
|
*/
|
|
37
|
-
export function sameDefault(
|
|
35
|
+
export function sameDefault(want, have, dialect) {
|
|
38
36
|
// Both spellings of "no default" are one fact: MariaDB reports `null` where MySQL reports nothing.
|
|
39
|
-
if (
|
|
40
|
-
return
|
|
41
|
-
const [want, have] = [ddlDefault(desired, dialect), ddlDefault(current, dialect)];
|
|
37
|
+
if (want == null || have == null)
|
|
38
|
+
return want == null && have == null;
|
|
42
39
|
if (SqlExpression.isExpression(want) || SqlExpression.isExpression(have)) {
|
|
43
40
|
return (SqlExpression.isExpression(want) &&
|
|
44
41
|
SqlExpression.isExpression(have) &&
|
|
@@ -75,9 +72,8 @@ function reprinted(sql) {
|
|
|
75
72
|
}
|
|
76
73
|
/**
|
|
77
74
|
* 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
|
|
79
|
-
* cannot serve
|
|
80
|
-
* is JSON rather than the throw and the IN-list `escape` gives them.
|
|
75
|
+
* it - MySQL takes `'a\b'` as a backspace where Postgres takes it literally. Only the case `escape`
|
|
76
|
+
* cannot serve stays here: a boolean is `1` where booleans are integers.
|
|
81
77
|
*/
|
|
82
78
|
function defaultLiteral(value, dialect, columnType) {
|
|
83
79
|
if (value === undefined || value === null) {
|
|
@@ -89,7 +85,7 @@ function defaultLiteral(value, dialect, columnType) {
|
|
|
89
85
|
if (typeof value === 'boolean') {
|
|
90
86
|
return dialect.booleanLiteral === 'native' ? (value ? 'TRUE' : 'FALSE') : value ? '1' : '0';
|
|
91
87
|
}
|
|
92
|
-
return dialect.escape(
|
|
88
|
+
return dialect.escape(value);
|
|
93
89
|
}
|
|
94
90
|
/** A raw expression's own SQL, else the engine's spelling of the value it names. */
|
|
95
91
|
function expressionSql(expression, dialect, columnType) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { lacksValue } from '
|
|
1
|
+
import { lacksValue } from '../../util/field.util.js';
|
|
2
2
|
import { dropIndexOnTable, TableDdl } from './tableDdl.js';
|
|
3
3
|
/** Table DDL for the MySQL family: `MODIFY COLUMN`, inline comments, and dedicated clauses to drop a key. */
|
|
4
4
|
export class MySqlTableDdl extends TableDdl {
|
|
@@ -65,7 +65,7 @@ export declare class TableDdl {
|
|
|
65
65
|
* an absent default stays absent - `defaultValue: null` is the way to ask for one.
|
|
66
66
|
*/
|
|
67
67
|
protected defaultClause(column: {
|
|
68
|
-
readonly defaultValue?:
|
|
68
|
+
readonly defaultValue?: ColumnSchema['defaultValue'];
|
|
69
69
|
readonly type: string;
|
|
70
70
|
}): string;
|
|
71
71
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { canonicalToSql } from '../../schema/canonicalType.js';
|
|
2
2
|
import { diffSchemas, referentialActions } from '../../schema/schemaASTDiffer.js';
|
|
3
|
-
import { SqlExpression, sqlExpressionText
|
|
3
|
+
import { SqlExpression, sqlExpressionText } from '../../schema/sqlExpression.js';
|
|
4
4
|
/**
|
|
5
5
|
* Compare an expected schema (from entities) with an actual one (from the database) and report every
|
|
6
6
|
* way they have drifted apart.
|
|
@@ -217,9 +217,16 @@ function relationshipDrift(change) {
|
|
|
217
217
|
suggestion: 'Generate a migration, which drops and re-adds the constraint',
|
|
218
218
|
};
|
|
219
219
|
}
|
|
220
|
-
/** A default as a report shows it: SQL as its SQL, a
|
|
220
|
+
/** A default as a report shows it: SQL as its SQL, a literal as written. */
|
|
221
221
|
function shownDefault(value) {
|
|
222
|
-
|
|
222
|
+
if (value == null) {
|
|
223
|
+
return 'NULL';
|
|
224
|
+
}
|
|
225
|
+
return SqlExpression.isExpression(value)
|
|
226
|
+
? sqlExpressionText(value)
|
|
227
|
+
: value instanceof Date
|
|
228
|
+
? value.toISOString()
|
|
229
|
+
: String(value);
|
|
223
230
|
}
|
|
224
231
|
/** Both actions spelled out, so a side that left one unstated reads the same as one that stated the default. */
|
|
225
232
|
function formatActions(rel) {
|
|
@@ -2,7 +2,7 @@ import type { AbstractSqlDialect } from '../../dialect/index.js';
|
|
|
2
2
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
3
3
|
import type { SchemaAST } from '../../schema/schemaAST.js';
|
|
4
4
|
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
5
|
-
import type { CheckSchema, TriggerSchema } from '../../schema/types.js';
|
|
5
|
+
import type { CheckSchema, ColumnDefault, TriggerSchema } from '../../schema/types.js';
|
|
6
6
|
import { type ForeignKeyAction } from '../../schema/types.js';
|
|
7
7
|
import type { ColumnRenames, ColumnSchema, Except, ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerierPool, QuerySql, RawRow, SchemaIntrospector, SqlQuerier, StoredDefinition, TableSchema } from '../../type/index.js';
|
|
8
8
|
/**
|
|
@@ -92,7 +92,7 @@ export declare abstract class AbstractSqlSchemaIntrospector implements SchemaInt
|
|
|
92
92
|
/** A catalogue's number, which a driver may answer as a `bigint`, or `undefined` for none. */
|
|
93
93
|
protected toNumber(value: unknown): number | undefined;
|
|
94
94
|
/** Parses a default as the catalogue reports it: to its literal value, or through {@link sqlDefault} if SQL. */
|
|
95
|
-
protected abstract parseDefaultValue(defaultValue: string | null):
|
|
95
|
+
protected abstract parseDefaultValue(defaultValue: string | null): ColumnDefault | undefined;
|
|
96
96
|
/**
|
|
97
97
|
* A SQL default, wrapped in parentheses, or the value uql exports that it spells (`currentTimestamp`), so it
|
|
98
98
|
* compares equal on every engine and `generate:from-db` writes it by name.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CheckSchema } from '../../schema/types.js';
|
|
1
|
+
import type { CheckSchema, ColumnDefault } from '../../schema/types.js';
|
|
2
2
|
import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerySql } from '../../type/index.js';
|
|
3
3
|
import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
4
4
|
/** SQL Server schema introspector: `INFORMATION_SCHEMA` has no view of indexes, which come from `sys.indexes`. */
|
|
@@ -18,5 +18,5 @@ export declare class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospect
|
|
|
18
18
|
* The engine reprints a default from its own parse tree: all of it in one pair of parentheses, and a
|
|
19
19
|
* number in a second, so `((0))`, `((1)+(2))`, `(N'x')` and `(getdate())`.
|
|
20
20
|
*/
|
|
21
|
-
protected parseDefaultValue(defaultValue: string | null):
|
|
21
|
+
protected parseDefaultValue(defaultValue: string | null): ColumnDefault | undefined;
|
|
22
22
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
2
|
-
import type { CheckSchema } from '../../schema/types.js';
|
|
2
|
+
import type { CheckSchema, ColumnDefault } from '../../schema/types.js';
|
|
3
3
|
import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerySql } from '../../type/index.js';
|
|
4
4
|
import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
5
5
|
/**
|
|
@@ -28,7 +28,7 @@ export declare class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospect
|
|
|
28
28
|
* column takes. That one comes with a charset introducer and every quote and backslash escaped again:
|
|
29
29
|
* `_utf8mb4\'x\'`.
|
|
30
30
|
*/
|
|
31
|
-
protected parseDefaultValue(defaultValue: string | null, extra?: string):
|
|
31
|
+
protected parseDefaultValue(defaultValue: string | null, extra?: string): ColumnDefault | undefined;
|
|
32
32
|
/** A default's SQL, or `undefined` for a literal: MySQL flags a SQL default `DEFAULT_GENERATED`. */
|
|
33
33
|
protected sqlText(defaultValue: string, extra: string): string | undefined;
|
|
34
34
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
2
|
-
import { type CheckSchema } from '../../schema/types.js';
|
|
2
|
+
import { type CheckSchema, type ColumnDefault } from '../../schema/types.js';
|
|
3
3
|
import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerySql } from '../../type/index.js';
|
|
4
4
|
import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
5
5
|
/**
|
|
@@ -64,7 +64,7 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
|
|
|
64
64
|
* writes a string containing a quote in escape syntax (`e'it\'s'`). Other casts are dropped, and a
|
|
65
65
|
* default that is not a literal is SQL, such as `now()` or `nextval(...)`.
|
|
66
66
|
*/
|
|
67
|
-
protected parseDefaultValue(defaultValue: string | null):
|
|
67
|
+
protected parseDefaultValue(defaultValue: string | null): ColumnDefault | undefined;
|
|
68
68
|
protected isAutoIncrement(columnDefault: string | null, isIdentity: string): boolean;
|
|
69
69
|
}
|
|
70
70
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
2
|
-
import type { CheckSchema } from '../../schema/types.js';
|
|
2
|
+
import type { CheckSchema, ColumnDefault } from '../../schema/types.js';
|
|
3
3
|
import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerySql, StoredDefinition } from '../../type/index.js';
|
|
4
4
|
import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
5
5
|
/**
|
|
@@ -37,7 +37,7 @@ export declare class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospec
|
|
|
37
37
|
private pragma;
|
|
38
38
|
protected normalizeType(type: string): string;
|
|
39
39
|
protected extractLength(type: string): number | undefined;
|
|
40
|
-
protected parseDefaultValue(defaultValue: string | null):
|
|
40
|
+
protected parseDefaultValue(defaultValue: string | null): ColumnDefault | undefined;
|
|
41
41
|
}
|
|
42
42
|
/**
|
|
43
43
|
* The expression a generated column is computed from, read out of the `CREATE TABLE` itself: no PRAGMA
|
package/dist/migrate/migrator.js
CHANGED
|
@@ -4,6 +4,7 @@ import { pathToFileURL } from 'node:url';
|
|
|
4
4
|
import { getEntities, getMeta } from '../entity/index.js';
|
|
5
5
|
import { SchemaAST } from '../schema/schemaAST.js';
|
|
6
6
|
import { columnRenameCandidates, columnRenames, tableRenameCandidates, } from '../schema/schemaASTDiffer.js';
|
|
7
|
+
import { lacksValue } from '../util/field.util.js';
|
|
7
8
|
import { definedEntries, isRecord, LoggerWrapper } from '../util/index.js';
|
|
8
9
|
import { sql } from '../util/sql.js';
|
|
9
10
|
import { isOwnedName, qualifyName } from '../util/sql.util.js';
|
|
@@ -13,7 +14,7 @@ import { buildMigrationModule } from './codegen/migrationFile.js';
|
|
|
13
14
|
import { introspectorFor } from './introspection/registry.js';
|
|
14
15
|
import { DEFAULT_LOCK_TIMEOUT } from './migrationLock.js';
|
|
15
16
|
import { migrationBuilderFor, migrationTargetFor, } from './migrationTarget.js';
|
|
16
|
-
import { dropped,
|
|
17
|
+
import { dropped, newlyRequired, nonEmpty, rollbackDiff, sides, unfillableRestores, withoutRebuild, } from './schemaChange.js';
|
|
17
18
|
import { constraintNameOf, dropsForeignKeysFirst } from './schemaGenerator.js';
|
|
18
19
|
import { DEFAULT_MIGRATIONS_TABLE } from './storage/databaseStorage.js';
|
|
19
20
|
/**
|
|
@@ -12,8 +12,6 @@ export declare function newlyRequired(changes?: readonly Change<ColumnSchema>[])
|
|
|
12
12
|
readonly from?: ColumnSchema;
|
|
13
13
|
readonly to: ColumnSchema;
|
|
14
14
|
}[];
|
|
15
|
-
/** Whether a row already in the table would hold nothing in `column`: required, with no default, and not one the engine fills. */
|
|
16
|
-
export declare function lacksValue(column: ColumnSchema): boolean;
|
|
17
15
|
/** Whether `diff` holds anything an engine that rebuilds tables makes no other way: a key, a foreign key or a check included. */
|
|
18
16
|
export declare function needsRebuild(diff: SchemaDiff): boolean;
|
|
19
17
|
/** `diff` less its rebuild and everything only a rebuild makes: what an `ALTER` can still apply alone. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { lacksValue } from '../util/field.util.js';
|
|
1
2
|
import { renamedEntry } from '../util/indexEntry.util.js';
|
|
2
3
|
/** Each change's end on `side`, where it has one: what a drop half removes (`from`), or an add half creates (`to`). */
|
|
3
4
|
export function sides(changes, side) {
|
|
@@ -22,10 +23,6 @@ export function alterations(changes = []) {
|
|
|
22
23
|
export function newlyRequired(changes = []) {
|
|
23
24
|
return changes.flatMap(({ from, to }) => (to && !to.nullable && (!from || from.nullable) ? [{ from, to }] : []));
|
|
24
25
|
}
|
|
25
|
-
/** Whether a row already in the table would hold nothing in `column`: required, with no default, and not one the engine fills. */
|
|
26
|
-
export function lacksValue(column) {
|
|
27
|
-
return !column.nullable && column.defaultValue === undefined && !column.generatedAs && !column.isAutoIncrement;
|
|
28
|
-
}
|
|
29
26
|
/** Whether an engine that rebuilds tables makes `change` no other way: a column changed in place, or a stored generated one added. */
|
|
30
27
|
function onlyRebuilt({ from, to }) {
|
|
31
28
|
return from === undefined ? Boolean(to?.generatedAs) : to !== undefined;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../dialect/index.js';
|
|
2
2
|
import type { SchemaAST } from '../schema/schemaAST.js';
|
|
3
3
|
import { type DiffOptions } from '../schema/schemaASTDiffer.js';
|
|
4
|
-
import { type ForeignKeyAction, type TableNode } from '../schema/types.js';
|
|
4
|
+
import { type ColumnDefault, type ForeignKeyAction, type TableNode } from '../schema/types.js';
|
|
5
5
|
import type { CreateSchemaOptions, DialectFeatures, DropSchemaOptions, ForeignKeySchema, Rename, SchemaDiff, SchemaGenerator, AbstractType } from '../type/index.js';
|
|
6
6
|
import type { AnyMigrationOperation, TableDefinition } from './builder/types.js';
|
|
7
7
|
import { type IndexDdl, type TableDdl } from './ddl/index.js';
|
|
@@ -91,7 +91,7 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
91
91
|
/** Spread, not copied field by field, so a field the node gains cannot go missing here. */
|
|
92
92
|
private columnNodeToSchema;
|
|
93
93
|
/** Whether a column's stored default is the one the entity declares, as this engine reprints it. */
|
|
94
|
-
readonly defaultsEqual: (desired:
|
|
94
|
+
readonly defaultsEqual: (desired: ColumnDefault | undefined, current: ColumnDefault | undefined) => boolean;
|
|
95
95
|
generateCreateTableFromNode(table: TableNode, options?: {
|
|
96
96
|
ifNotExists?: boolean;
|
|
97
97
|
}): string[];
|
|
@@ -3,6 +3,7 @@ import { stampEvents } from '../util/field.util.js';
|
|
|
3
3
|
import { definedEntries } from '../util/object.util.js';
|
|
4
4
|
import { sql, refs, rowRefs } from '../util/sql.js';
|
|
5
5
|
import { ownedName, splitQualifiedName } from '../util/sql.util.js';
|
|
6
|
+
import { escapeRegExp } from '../util/string.util.js';
|
|
6
7
|
import { written } from '../util/triggerWrite.js';
|
|
7
8
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
8
9
|
/**
|
|
@@ -199,17 +200,21 @@ const STAMP_EVENTS = {
|
|
|
199
200
|
*/
|
|
200
201
|
function stampBody(dialect, meta, key, value, newRow) {
|
|
201
202
|
const { entity } = meta;
|
|
202
|
-
|
|
203
|
+
const { triggers } = dialect.features;
|
|
204
|
+
// Its own row's columns read off the row being written: the incoming record, or the table the `UPDATE` restates.
|
|
205
|
+
const rowPrefix = triggers.assignsRow ? `${rowNames(dialect).$new}.` : `${dialect.escapedTableName(meta)}.`;
|
|
206
|
+
const stamped = dialect.compileDdl(value, entity, { escapedPrefix: rowPrefix });
|
|
207
|
+
const expression = sql(() => stamped);
|
|
208
|
+
if (triggers.assignsRow) {
|
|
203
209
|
const target = newRow[key];
|
|
204
|
-
return
|
|
210
|
+
return triggers.body === 'function' ? sql `${target} := ${expression};` : sql `SET ${target} = ${expression};`;
|
|
205
211
|
}
|
|
206
212
|
const table = refs(entity);
|
|
207
213
|
const keyed = meta.ids.map((id) => sql `${table[id]} = ${newRow[id]}`);
|
|
208
214
|
// Read through the write's own qualifier, as `keyed` is: `inserted` holds the same column name.
|
|
209
|
-
const stamped = dialect.compileDdl(value, entity);
|
|
210
215
|
const differs = sql(({ ctx, escapedPrefix }) => ctx.append(dialect.neExpr(`${escapedPrefix}${dialect.escapedColumnName(meta, key)}`, stamped)));
|
|
211
216
|
const where = { $and: [...keyed, differs] };
|
|
212
|
-
const restated = written({ kind: 'update', entity, set: { [key]:
|
|
217
|
+
const restated = written({ kind: 'update', entity, set: { [key]: expression }, where });
|
|
213
218
|
const { reentryGuard } = dialect.features.triggers;
|
|
214
219
|
return reentryGuard ? sql `${sql(() => reentryGuard)}\n${restated}` : restated;
|
|
215
220
|
}
|
|
@@ -247,17 +252,8 @@ function rowsFrom(dialect, meta, operation, { $new, $old }, filter) {
|
|
|
247
252
|
const from = operation === 'UPDATE' ? `${$new} JOIN ${$old} ON ${keyed.join(' AND ')}` : operation === 'INSERT' ? $new : $old;
|
|
248
253
|
return { from, where: filter || undefined };
|
|
249
254
|
}
|
|
250
|
-
const IDENTIFIER_CHAR = /[\p{L}\p{N}_$]/u;
|
|
251
255
|
/** Whether `statement` names any of `columns` as a whole identifier, quoted or not, in any case. */
|
|
252
256
|
export function namesAny(statement, columns) {
|
|
253
|
-
const
|
|
254
|
-
return columns.
|
|
255
|
-
const name = column.toLowerCase();
|
|
256
|
-
for (let at = text.indexOf(name); at >= 0; at = text.indexOf(name, at + 1)) {
|
|
257
|
-
if (!IDENTIFIER_CHAR.test(text.charAt(at - 1)) && !IDENTIFIER_CHAR.test(text.charAt(at + name.length))) {
|
|
258
|
-
return true;
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
return false;
|
|
262
|
-
});
|
|
257
|
+
const names = columns.map(escapeRegExp).join('|');
|
|
258
|
+
return (columns.length > 0 && new RegExp(`(?<![\\p{L}\\p{N}_$])(?:${names})(?![\\p{L}\\p{N}_$])`, 'iu').test(statement));
|
|
263
259
|
}
|
|
@@ -261,9 +261,14 @@ export declare class MongoDialect extends AbstractDialect {
|
|
|
261
261
|
private whereExpression;
|
|
262
262
|
/**
|
|
263
263
|
* One field's condition as an expression, read as {@link transformOperators} reads it in a query: a value
|
|
264
|
-
* it equals, a list it is in, or operators. `
|
|
264
|
+
* it equals, a list it is in, or operators. `read` reads what the field is compared with.
|
|
265
265
|
*/
|
|
266
266
|
private fieldExpression;
|
|
267
|
+
/**
|
|
268
|
+
* How what a field of `meta` is compared with reads in an expression, the one reader of it on every path: a ref
|
|
269
|
+
* as the field it names, of the same document; any other SQL refused; a value as itself, a key's in its wire form.
|
|
270
|
+
*/
|
|
271
|
+
private operandOf;
|
|
267
272
|
/**
|
|
268
273
|
* What `ref` satisfies to hold `value`, as {@link held} reads it in a query: an array each of its
|
|
269
274
|
* elements, an object each of its keys as a path, anything else as a field condition.
|