uql-orm 0.101.0 → 0.101.2
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/README.md +1 -1
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +6 -6
- package/dist/d1/d1SqliteDialect.d.ts +1 -1
- package/dist/d1/d1SqliteDialect.js +1 -1
- package/dist/dialect/abstractDialect.js +2 -2
- package/dist/dialect/abstractSqlDialect.d.ts +10 -10
- package/dist/dialect/abstractSqlDialect.js +24 -24
- package/dist/dialect/operators.js +2 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +1 -1
- package/dist/dialect/pgLikeSqlDialect.js +5 -5
- package/dist/dialect/queryContext.d.ts +1 -1
- package/dist/dialect/queryContext.js +1 -1
- package/dist/dialect/vectorSqlDialect.js +1 -1
- package/dist/entity/decorator/entity.d.ts +2 -2
- package/dist/entity/decorator/entity.js +2 -2
- package/dist/http/index.d.ts +2 -2
- package/dist/http/index.js +1 -2
- package/dist/http/query.d.ts +1 -1
- package/dist/http/query.js +4 -4
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/libsql/index.d.ts +1 -1
- package/dist/libsql/index.js +1 -1
- package/dist/migrate/builder/tableBuilder.js +1 -1
- package/dist/migrate/builder/types.d.ts +2 -2
- package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
- package/dist/migrate/codegen/fieldOptionsSource.js +5 -5
- package/dist/migrate/codegen/indexDecoratorSource.d.ts +2 -2
- package/dist/migrate/codegen/indexDecoratorSource.js +5 -5
- package/dist/migrate/codegen/sourceLiteral.d.ts +2 -2
- package/dist/migrate/codegen/sourceLiteral.js +3 -3
- package/dist/migrate/ddl/defaultSql.js +1 -1
- package/dist/migrate/generator/definitionToNode.d.ts +3 -3
- package/dist/migrate/index.d.ts +8 -11
- package/dist/migrate/index.js +7 -17
- package/dist/migrate/indexPredicate.d.ts +1 -1
- package/dist/migrate/indexPredicate.js +5 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +8 -8
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +3 -3
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +5 -5
- package/dist/migrate/introspection/mssqlIntrospector.js +10 -10
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +5 -5
- package/dist/migrate/introspection/mysqlIntrospector.js +13 -13
- package/dist/migrate/introspection/postgresIntrospector.d.ts +13 -13
- package/dist/migrate/introspection/postgresIntrospector.js +21 -21
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +4 -4
- package/dist/migrate/introspection/sqliteIntrospector.js +6 -6
- package/dist/migrate/migrationLock.d.ts +3 -3
- package/dist/migrate/migrationLock.js +7 -7
- package/dist/migrate/migrationTarget.js +2 -2
- package/dist/migrate/migrator.js +2 -2
- package/dist/migrate/schemaGenerator.d.ts +1 -1
- package/dist/migrate/schemaGenerator.js +1 -1
- package/dist/migrate/storage/databaseStorage.d.ts +3 -3
- package/dist/migrate/storage/databaseStorage.js +4 -4
- package/dist/migrate/triggerSql.js +7 -7
- package/dist/mongodb/index.d.ts +1 -1
- package/dist/mongodb/index.js +1 -1
- package/dist/mongodb/mongoDialect.js +4 -4
- package/dist/mongodb/mongoSchemaGenerator.js +3 -3
- package/dist/mongodb/mongodbQuerier.d.ts +3 -2
- package/dist/mssql/mssqlDialect.js +3 -3
- package/dist/postgres/index.d.ts +1 -1
- package/dist/postgres/index.js +1 -1
- package/dist/querier/abstractQuerier.d.ts +10 -3
- package/dist/querier/abstractQuerier.js +12 -12
- package/dist/querier/abstractSqlQuerier.d.ts +3 -3
- package/dist/querier/abstractSqlQuerier.js +3 -3
- package/dist/schema/canonicalType.d.ts +1 -1
- package/dist/schema/canonicalType.js +6 -6
- package/dist/schema/sqlExpression.d.ts +4 -4
- package/dist/schema/sqlExpression.js +5 -5
- package/dist/sqlite/index.d.ts +1 -1
- package/dist/sqlite/index.js +1 -1
- package/dist/sqlite/sqliteDialect.js +2 -2
- package/dist/type/dialect.d.ts +3 -3
- package/dist/type/entity.d.ts +39 -39
- package/dist/type/index.d.ts +1 -1
- package/dist/type/index.js +1 -1
- package/dist/type/migration.d.ts +1 -1
- package/dist/type/querier.d.ts +5 -5
- package/dist/type/query.d.ts +32 -32
- package/dist/type/queryAggregate.d.ts +2 -2
- package/dist/type/{queryRaw.d.ts → querySql.d.ts} +33 -33
- package/dist/type/{queryRaw.js → querySql.js} +17 -17
- package/dist/type/queryWhere.d.ts +22 -22
- package/dist/type/universalQuerier.d.ts +12 -12
- package/dist/type/wire.d.ts +4 -4
- package/dist/util/ddlExpression.util.d.ts +4 -4
- package/dist/util/ddlExpression.util.js +7 -7
- package/dist/util/dialect.util.d.ts +7 -7
- package/dist/util/dialect.util.js +4 -4
- package/dist/util/fieldOption.util.d.ts +3 -3
- package/dist/util/fieldOption.util.js +5 -5
- package/dist/util/index.d.ts +1 -1
- package/dist/util/index.js +1 -1
- package/dist/util/query.util.js +1 -1
- package/dist/util/{raw.d.ts → sql.d.ts} +22 -20
- package/dist/util/{raw.js → sql.js} +28 -26
- package/dist/util/triggerWrite.d.ts +7 -7
- package/dist/util/triggerWrite.js +2 -2
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +7 -7
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { sql } from '../../util/sql.js';
|
|
2
2
|
import { AbstractSqlSchemaIntrospector, } from './abstractSqlSchemaIntrospector.js';
|
|
3
3
|
/**
|
|
4
4
|
* SQLite schema introspector
|
|
@@ -7,11 +7,11 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
7
7
|
/** Whether an index is libSQL's vector index, where the engine has one; elsewhere a declared one is built plain. */
|
|
8
8
|
indexFacets = new Set(this.dialect.hasVectorIndex() ? ['vector', 'distance'] : []);
|
|
9
9
|
triggersQuery(tableName) {
|
|
10
|
-
return
|
|
10
|
+
return sql `SELECT name, sql AS definition FROM sqlite_master WHERE type = 'trigger' AND tbl_name = ${tableName}`;
|
|
11
11
|
}
|
|
12
12
|
/** User tables only: skips SQLite's own and libSQL's vector index tables (its metadata and `<index>_shadow`). */
|
|
13
13
|
getTableNamesQuery() {
|
|
14
|
-
return
|
|
14
|
+
return sql `
|
|
15
15
|
SELECT name AS table_name
|
|
16
16
|
FROM sqlite_master
|
|
17
17
|
WHERE type = 'table'
|
|
@@ -22,7 +22,7 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
22
22
|
`;
|
|
23
23
|
}
|
|
24
24
|
tableExistsQuery(tableName) {
|
|
25
|
-
return
|
|
25
|
+
return sql `SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${tableName}`;
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
28
|
* `table_xinfo`, not `table_info`: the latter omits generated columns entirely, so a table carrying
|
|
@@ -96,7 +96,7 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
96
96
|
}
|
|
97
97
|
/** Every statement `sqlite_master` keeps for the table, its `CREATE TABLE` first. An automatic index has none. */
|
|
98
98
|
getDefinition(read, tableName) {
|
|
99
|
-
return read(
|
|
99
|
+
return read(sql `SELECT type AS kind, name, sql FROM sqlite_master WHERE tbl_name = ${tableName} AND sql IS NOT NULL ORDER BY type <> 'table'`);
|
|
100
100
|
}
|
|
101
101
|
/** libSQL's `libsql_vector_idx(col, 'metric=...')`, read back from the statement that created it. */
|
|
102
102
|
vectorIndex(name, sql) {
|
|
@@ -118,7 +118,7 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
118
118
|
}
|
|
119
119
|
/** A PRAGMA takes no parameters, so the name it reads is written into the statement, escaped. */
|
|
120
120
|
pragma(name, of) {
|
|
121
|
-
return
|
|
121
|
+
return sql.text(`PRAGMA ${name}(${this.dialect.escapeId(of)})`);
|
|
122
122
|
}
|
|
123
123
|
normalizeType(type) {
|
|
124
124
|
// Extract base type without length/precision
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../dialect/abstractSqlDialect.js';
|
|
2
|
-
import type { QuerierPool,
|
|
2
|
+
import type { QuerierPool, QuerySql, SqlQuerier } from '../type/index.js';
|
|
3
3
|
/** How long `up` and `down` wait for the lock another run holds, unless told otherwise. */
|
|
4
4
|
export declare const DEFAULT_LOCK_TIMEOUT: number;
|
|
5
5
|
/** The statements taking and releasing a named lock: `acquire` takes it without waiting, answering a row only when it did. */
|
|
6
6
|
type NamedLockSql = {
|
|
7
|
-
readonly acquire:
|
|
8
|
-
readonly release:
|
|
7
|
+
readonly acquire: QuerySql;
|
|
8
|
+
readonly release: QuerySql;
|
|
9
9
|
};
|
|
10
10
|
/** The statements of the lock named `name` on `dialect`'s engine, where it has one its sessions can hold. */
|
|
11
11
|
export declare function namedLockSql(dialect: AbstractSqlDialect, name: string): NamedLockSql | undefined;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { sql } from '../util/sql.js';
|
|
2
2
|
import { fnv1a } from '../util/string.util.js';
|
|
3
3
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
4
4
|
import { withSqlQuerierForMigrations } from './acquireQuerierForMigrations.js';
|
|
@@ -9,26 +9,26 @@ export const DEFAULT_LOCK_TIMEOUT = 5 * 60_000;
|
|
|
9
9
|
const POLL_INTERVAL = 250;
|
|
10
10
|
/** MySQL's lock names are server-wide, so the database prefixes each, cut to the 64 characters it takes. */
|
|
11
11
|
const mysqlLock = (name) => {
|
|
12
|
-
const lock =
|
|
13
|
-
return { acquire:
|
|
12
|
+
const lock = sql `LEFT(CONCAT(DATABASE(), '.', ${name}), 64)`;
|
|
13
|
+
return { acquire: sql `SELECT 1 FROM DUAL WHERE GET_LOCK(${lock}, 0) = 1`, release: sql `DO RELEASE_LOCK(${lock})` };
|
|
14
14
|
};
|
|
15
15
|
/** Each engine's named lock, as `features.namedLocks` says what holds it. None on CockroachDB and SQLite. */
|
|
16
16
|
const NAMED_LOCK_SQL = {
|
|
17
17
|
postgres: (name) => {
|
|
18
18
|
const key = fnv1a(name);
|
|
19
19
|
return {
|
|
20
|
-
acquire:
|
|
21
|
-
release:
|
|
20
|
+
acquire: sql `SELECT 1 WHERE pg_try_advisory_lock(${key})`,
|
|
21
|
+
release: sql `SELECT pg_advisory_unlock(${key})`,
|
|
22
22
|
};
|
|
23
23
|
},
|
|
24
24
|
cockroachdb: undefined,
|
|
25
25
|
mysql: mysqlLock,
|
|
26
26
|
mariadb: mysqlLock,
|
|
27
27
|
mssql: (name) => ({
|
|
28
|
-
acquire:
|
|
28
|
+
acquire: sql `DECLARE @_uql_lock INT;
|
|
29
29
|
EXEC @_uql_lock = sp_getapplock @Resource = ${name}, @LockMode = 'Exclusive', @LockOwner = 'Transaction', @LockTimeout = 0;
|
|
30
30
|
SELECT 1 WHERE @_uql_lock >= 0`,
|
|
31
|
-
release:
|
|
31
|
+
release: sql `EXEC sp_releaseapplock @Resource = ${name}, @LockOwner = 'Transaction'`,
|
|
32
32
|
}),
|
|
33
33
|
sqlite: undefined,
|
|
34
34
|
};
|
|
@@ -2,7 +2,7 @@ import { runMongoCommand } from '../mongodb/mongoCommand.js';
|
|
|
2
2
|
import { MongoMigrationStorage } from '../mongodb/mongoMigrationStorage.js';
|
|
3
3
|
import { isMongoQuerier, withMongoQuerierForMigrations } from '../mongodb/mongoQuerier.js';
|
|
4
4
|
import { isSqlQuerier, } from '../type/index.js';
|
|
5
|
-
import {
|
|
5
|
+
import { sql } from '../util/sql.js';
|
|
6
6
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
7
7
|
import { withSqlQuerierForMigrations } from './acquireQuerierForMigrations.js';
|
|
8
8
|
import { MigrationOperationBuilder } from './builder/migrationBuilder.js';
|
|
@@ -12,7 +12,7 @@ import { SqlSchemaGenerator } from './schemaGenerator.js';
|
|
|
12
12
|
import { DatabaseMigrationStorage, LOCK_RECORD } from './storage/databaseStorage.js';
|
|
13
13
|
const sqlSession = (querier) => ({
|
|
14
14
|
querier,
|
|
15
|
-
run: (statement) => querier.run(
|
|
15
|
+
run: (statement) => querier.run(sql.text(statement)),
|
|
16
16
|
transaction: (work) => querier.dialect.features.rebuildsTables ? withForeignKeysOff(querier, work) : querier.transaction(work),
|
|
17
17
|
});
|
|
18
18
|
/**
|
package/dist/migrate/migrator.js
CHANGED
|
@@ -5,7 +5,7 @@ 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
7
|
import { definedEntries, isRecord, LoggerWrapper } from '../util/index.js';
|
|
8
|
-
import {
|
|
8
|
+
import { sql } from '../util/sql.js';
|
|
9
9
|
import { isOwnedName, qualifyName } from '../util/sql.util.js';
|
|
10
10
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
11
11
|
import { withSqlQuerierForMigrations } from './acquireQuerierForMigrations.js';
|
|
@@ -233,7 +233,7 @@ export class Migrator {
|
|
|
233
233
|
const found = [];
|
|
234
234
|
for (const { tableName, column, nullable } of counts) {
|
|
235
235
|
const empty = nullable ? ` WHERE ${escapeId(column)} IS NULL` : '';
|
|
236
|
-
const [{ rows }] = await querier.all(
|
|
236
|
+
const [{ rows }] = await querier.all(sql.text(`SELECT COUNT(*) AS ${escapeId('rows')} FROM ${escapeId(tableName)}${empty}`));
|
|
237
237
|
const count = Number(rows);
|
|
238
238
|
if (count) {
|
|
239
239
|
found.push(`"${tableName}"."${column}" is required with no default, and ${count} ${count === 1 ? 'row holds' : 'rows hold'} none`);
|
|
@@ -100,7 +100,7 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
100
100
|
generateCreateTableFromDefinition(table: TableDefinition, options?: {
|
|
101
101
|
ifNotExists?: boolean;
|
|
102
102
|
}): string[];
|
|
103
|
-
/** `
|
|
103
|
+
/** `sql` is split, being the one SQL no generator wrote. */
|
|
104
104
|
generateOperation(operation: AnyMigrationOperation): string[];
|
|
105
105
|
/** `ADD COLUMN`, plus the foreign key and index the column declares, as `CREATE TABLE` lifts them. */
|
|
106
106
|
private addColumnSql;
|
|
@@ -377,7 +377,7 @@ export class SqlSchemaGenerator {
|
|
|
377
377
|
const tableNode = tableDefinitionToNode(table, (sql) => this.dialect.compileDdl(sql));
|
|
378
378
|
return this.generateCreateTableFromNode(tableNode, options);
|
|
379
379
|
}
|
|
380
|
-
/** `
|
|
380
|
+
/** `sql` is split, being the one SQL no generator wrote. */
|
|
381
381
|
generateOperation(operation) {
|
|
382
382
|
switch (operation.type) {
|
|
383
383
|
case 'createTable':
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Querier,
|
|
1
|
+
import type { Querier, QuerySql, SqlQuerier } from '../../type/index.js';
|
|
2
2
|
/** Where executed migrations are recorded when the config does not name a table. */
|
|
3
3
|
export declare const DEFAULT_MIGRATIONS_TABLE = "uql_migrations";
|
|
4
4
|
/**
|
|
@@ -34,6 +34,6 @@ export declare class DatabaseMigrationStorage implements MigrationStorage {
|
|
|
34
34
|
}
|
|
35
35
|
/** The journal `tableName` and its one column, escaped as `querier`'s engine spells them. */
|
|
36
36
|
export declare function journalIds({ dialect }: SqlQuerier, tableName: string): {
|
|
37
|
-
table:
|
|
38
|
-
name:
|
|
37
|
+
table: QuerySql;
|
|
38
|
+
name: QuerySql;
|
|
39
39
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { currentTimestamp,
|
|
1
|
+
import { currentTimestamp, sql } from '../../util/sql.js';
|
|
2
2
|
import { TableDefinitionBuilder } from '../builder/tableBuilder.js';
|
|
3
3
|
import { SqlSchemaGenerator } from '../schemaGenerator.js';
|
|
4
4
|
/** Where executed migrations are recorded when the config does not name a table. */
|
|
@@ -18,8 +18,8 @@ export async function createMigrationsTable(querier, tableName) {
|
|
|
18
18
|
table.string('name', { length: 255, primaryKey: true });
|
|
19
19
|
table.timestamptz('executed_at', { defaultValue: currentTimestamp });
|
|
20
20
|
const generator = new SqlSchemaGenerator(querier.dialect);
|
|
21
|
-
for (const
|
|
22
|
-
await querier.run(
|
|
21
|
+
for (const statement of generator.generateCreateTableFromDefinition(table.build(), { ifNotExists: true })) {
|
|
22
|
+
await querier.run(sql.text(statement));
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
/** Records the migrations run in a table, on the querier each call is handed, which the lock created. */
|
|
@@ -47,5 +47,5 @@ export class DatabaseMigrationStorage {
|
|
|
47
47
|
}
|
|
48
48
|
/** The journal `tableName` and its one column, escaped as `querier`'s engine spells them. */
|
|
49
49
|
export function journalIds({ dialect }, tableName) {
|
|
50
|
-
return { table:
|
|
50
|
+
return { table: sql.text(dialect.escapeId(tableName)), name: sql.text(dialect.escapeId('name')) };
|
|
51
51
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { TriggerWriteSql } from '../type/index.js';
|
|
2
2
|
import { stampEvents } from '../util/field.util.js';
|
|
3
3
|
import { definedEntries } from '../util/object.util.js';
|
|
4
|
-
import {
|
|
4
|
+
import { sql, refs, rowRefs } from '../util/sql.js';
|
|
5
5
|
import { ownedName, splitQualifiedName } from '../util/sql.util.js';
|
|
6
6
|
import { written } from '../util/triggerWrite.js';
|
|
7
7
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
@@ -58,7 +58,7 @@ function triggerStatements(dialect, meta, trigger, name) {
|
|
|
58
58
|
const rows = [rowRefs(meta.entity, names.$new), rowRefs(meta.entity, names.$old)];
|
|
59
59
|
const filter = triggerFilter(dialect, meta, trigger, rows, names);
|
|
60
60
|
const body = triggerBody(dialect, meta, trigger, before)(...rows);
|
|
61
|
-
if (perStatement && filter && !(body instanceof
|
|
61
|
+
if (perStatement && filter && !(body instanceof TriggerWriteSql)) {
|
|
62
62
|
throw new UqlUsageError(`${dialect.dialectName} fires a trigger once per statement, so 'of' and 'where' narrow only what ` +
|
|
63
63
|
`insertInto, updateTable or deleteFrom reads, and '${meta.entity.name}' has one running its own SQL. ` +
|
|
64
64
|
'Keep the body to those writes, or filter inserted and deleted in that SQL.');
|
|
@@ -199,17 +199,17 @@ function stampBody(dialect, meta, key, value, newRow) {
|
|
|
199
199
|
const { entity } = meta;
|
|
200
200
|
if (dialect.features.triggers.assignsRow) {
|
|
201
201
|
const target = newRow[key];
|
|
202
|
-
return dialect.features.triggers.body === 'function' ?
|
|
202
|
+
return dialect.features.triggers.body === 'function' ? sql `${target} := ${value};` : sql `SET ${target} = ${value};`;
|
|
203
203
|
}
|
|
204
204
|
const table = refs(entity);
|
|
205
|
-
const keyed = meta.ids.map((id) =>
|
|
205
|
+
const keyed = meta.ids.map((id) => sql `${table[id]} = ${newRow[id]}`);
|
|
206
206
|
// Read through the write's own qualifier, as `keyed` is: `inserted` holds the same column name.
|
|
207
207
|
const stamped = dialect.compileDdl(value, entity);
|
|
208
|
-
const differs =
|
|
208
|
+
const differs = sql(({ ctx, escapedPrefix }) => ctx.append(dialect.neExpr(`${escapedPrefix}${dialect.escapedColumnName(meta, key)}`, stamped)));
|
|
209
209
|
const where = { $and: [...keyed, differs] };
|
|
210
210
|
const restated = written({ kind: 'update', entity, set: { [key]: value }, where });
|
|
211
211
|
const { reentryGuard } = dialect.features.triggers;
|
|
212
|
-
return reentryGuard ?
|
|
212
|
+
return reentryGuard ? sql `${sql(() => reentryGuard)}\n${restated}` : restated;
|
|
213
213
|
}
|
|
214
214
|
/** A dollar quote the body does not contain, so no `$$` in it - a literal, a comment - ends the function early. */
|
|
215
215
|
function dollarQuote(body) {
|
package/dist/mongodb/index.d.ts
CHANGED
package/dist/mongodb/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { betweenBounds, GROUP_OPS, groupClauses, isGroupOp, LIKE_OPS, likeRegex,
|
|
|
5
5
|
import { aggregateColumnField, groupPathField, resolveGroupJoins, relationSortTerms, resolveQueryJoins, resolveSortableJoin, } from '../dialect/queryJoins.js';
|
|
6
6
|
import { assertSoleId, fieldOf, getMeta, relationOf, soleIdOf } from '../entity/index.js';
|
|
7
7
|
import { COUNT_RESULT_KEY } from '../type/query.js';
|
|
8
|
-
import {
|
|
8
|
+
import { QuerySql } from '../type/querySql.js';
|
|
9
9
|
import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetJoins, textSortOf, vectorDistanceOf, } from '../util/index.js';
|
|
10
10
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
11
11
|
import { decodeBigIntsExcept } from '../util/wideNumber.js';
|
|
@@ -32,12 +32,12 @@ export const mongoDialectFeatures = {
|
|
|
32
32
|
};
|
|
33
33
|
/** What `toWireId` converts: the hex spelling of an `ObjectId`, and nothing looser. */
|
|
34
34
|
const HEX_24 = /^[0-9a-f]{24}$/i;
|
|
35
|
-
/** `
|
|
35
|
+
/** `sql()` renders SQL, which MongoDB has no equivalent of: refused rather than emitted as `{}`. */
|
|
36
36
|
function rawRefusal(place) {
|
|
37
|
-
return new UqlUsageError(`
|
|
37
|
+
return new UqlUsageError(`sql() in ${place} is not supported on MongoDB`);
|
|
38
38
|
}
|
|
39
39
|
function assertNoRaw(value, place) {
|
|
40
|
-
if (value instanceof
|
|
40
|
+
if (value instanceof QuerySql) {
|
|
41
41
|
throw rawRefusal(place);
|
|
42
42
|
}
|
|
43
43
|
}
|
|
@@ -5,7 +5,7 @@ import { indexNodeToSchema } from '../migrate/generator/indexNodeToSchema.js';
|
|
|
5
5
|
import { assertIndexPredicate, refusedIndexPredicate } from '../migrate/indexPredicate.js';
|
|
6
6
|
import { sides } from '../migrate/schemaChange.js';
|
|
7
7
|
import { indexChanges } from '../schema/indexDifferences.js';
|
|
8
|
-
import {
|
|
8
|
+
import { QuerySql, } from '../type/index.js';
|
|
9
9
|
import { indexDistance, unsupportedVectorMetric } from '../type/vector.js';
|
|
10
10
|
import { declaredIndexes, declaredIndexName, renderIndexColumn } from '../util/ddlExpression.util.js';
|
|
11
11
|
import { fulltextConfig, fulltextWeights } from '../util/dialect.util.js';
|
|
@@ -83,7 +83,7 @@ export class MongoSchemaGenerator extends MongoDialect {
|
|
|
83
83
|
* what that holds or what a migration carries as JSON.
|
|
84
84
|
*/
|
|
85
85
|
indexFilter(where, entity, indexName) {
|
|
86
|
-
if (where instanceof
|
|
86
|
+
if (where instanceof QuerySql) {
|
|
87
87
|
throw new UqlUsageError(`mongodb does not support partial indexes from a SQL predicate (index "${indexName}")`);
|
|
88
88
|
}
|
|
89
89
|
assertIndexPredicate(where, this.dialectName, indexName);
|
|
@@ -107,7 +107,7 @@ export class MongoSchemaGenerator extends MongoDialect {
|
|
|
107
107
|
}
|
|
108
108
|
/** A check's filter, refused where it is SQL or holds what a migration cannot carry as JSON. */
|
|
109
109
|
checkFilter(where, entity, collectionName) {
|
|
110
|
-
if (where instanceof
|
|
110
|
+
if (where instanceof QuerySql) {
|
|
111
111
|
throw new UqlUsageError(`mongodb does not support checks from a SQL predicate (collection "${collectionName}")`);
|
|
112
112
|
}
|
|
113
113
|
const filter = this.renderFilter(entity, where);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ClientSession, Document, MongoClient } from 'mongodb';
|
|
2
|
+
import type { UpsertedId } from '../querier/abstractQuerier.js';
|
|
2
3
|
import { AbstractQuerier } from '../querier/index.js';
|
|
3
|
-
import type { EntityData, ExtraOptions,
|
|
4
|
+
import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
|
|
4
5
|
import type { MongoDialect } from './mongoDialect.js';
|
|
5
6
|
import type { MongoQuerier } from './mongoQuerier.js';
|
|
6
7
|
export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
|
|
@@ -61,7 +62,7 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
|
|
|
61
62
|
* a concurrent one included, then takes `update`.
|
|
62
63
|
*/
|
|
63
64
|
private upsertWithUpdate;
|
|
64
|
-
protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(
|
|
65
|
+
protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[]>;
|
|
65
66
|
protected internalDeleteMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
|
|
66
67
|
get hasOpenTransaction(): boolean;
|
|
67
68
|
/** Every read and write goes through here, which makes it where a released querier is caught. */
|
|
@@ -5,7 +5,7 @@ import { jsonArraySlotArgs, jsonPath, jsonSlotArgs } from '../dialect/jsonSql.js
|
|
|
5
5
|
import { MergeSqlDialect } from '../dialect/mergeSqlDialect.js';
|
|
6
6
|
import { getMeta } from '../entity/index.js';
|
|
7
7
|
import { canonicalToSql, resolveColumnCanonicalType } from '../schema/canonicalType.js';
|
|
8
|
-
import {
|
|
8
|
+
import { QuerySql } from '../type/index.js';
|
|
9
9
|
import { parseQueryLock } from '../type/index.js';
|
|
10
10
|
import { bytesToHex } from '../util/bytes.js';
|
|
11
11
|
import { isAutoIncrement, isExactDecimal, jsonPathKeys } from '../util/field.util.js';
|
|
@@ -337,11 +337,11 @@ export class MsSqlDialect extends MergeSqlDialect {
|
|
|
337
337
|
return typeof value === 'boolean' ? `CAST(${placeholder} AS BIT)` : placeholder;
|
|
338
338
|
}
|
|
339
339
|
/**
|
|
340
|
-
* An object or array bound as JSON, or a `
|
|
340
|
+
* An object or array bound as JSON, or a `sql()` rendered in place, which is the half both binders
|
|
341
341
|
* spell the same way; `undefined` for a scalar - where they diverge.
|
|
342
342
|
*/
|
|
343
343
|
#jsonCompound(ctx, value) {
|
|
344
|
-
if (value instanceof
|
|
344
|
+
if (value instanceof QuerySql) {
|
|
345
345
|
return this.rawFragment(ctx, value);
|
|
346
346
|
}
|
|
347
347
|
if (value === null || typeof value !== 'object') {
|
package/dist/postgres/index.d.ts
CHANGED
package/dist/postgres/index.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import type { AbstractDialect } from '../dialect/abstractDialect.js';
|
|
2
|
-
import type { BooleanLike, CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch,
|
|
2
|
+
import type { BooleanLike, CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, RelationKey, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, ReturningResult, WriteOptions, PrimaryKey, WrittenId } from '../type/index.js';
|
|
3
3
|
import { LoggerWrapper } from '../util/index.js';
|
|
4
4
|
import { type TransactionScope } from './transaction.js';
|
|
5
|
+
/**
|
|
6
|
+
* Writes the key an upsert reported onto each row that named none - only the key, since an `onInsert`
|
|
7
|
+
* value was never written to a row the upsert updated. A report aligns with the rows only when it
|
|
8
|
+
* speaks for every one: a `firstId` dialect reports nothing for a batch.
|
|
9
|
+
*/
|
|
10
|
+
/** What an upsert reports of a row: the value a driver answers for a lone key, or the key the read back names. */
|
|
11
|
+
export type UpsertedId<E> = PrimaryKey | WrittenId<E>;
|
|
5
12
|
/** Base class for all database queriers. */
|
|
6
13
|
export declare abstract class AbstractQuerier implements Querier {
|
|
7
14
|
#private;
|
|
@@ -174,7 +181,7 @@ export declare abstract class AbstractQuerier implements Querier {
|
|
|
174
181
|
*/
|
|
175
182
|
private readThenUpsert;
|
|
176
183
|
/** Upserts `payload`, answering each row's key in payload order where the engine reports every one. */
|
|
177
|
-
protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(
|
|
184
|
+
protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[] | undefined>;
|
|
178
185
|
deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V> | undefined>>;
|
|
179
186
|
/** Delete records matching the query, the entity passed first or as `$entity`; soft-deletes unless `opts.hardDelete`. */
|
|
180
187
|
deleteMany<E extends object>(q: QuerySearch<E> & {
|
|
@@ -278,7 +285,7 @@ export declare abstract class AbstractQuerier implements Querier {
|
|
|
278
285
|
* statement that could not report them in payload order, or before a guarded upsert. A row that no
|
|
279
286
|
* read row matches, or that two do, keeps `undefined`: a missing id is honest where a guessed one is not.
|
|
280
287
|
*/
|
|
281
|
-
protected idsByConflict<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, rows: EntityData<E>[]): Promise<(
|
|
288
|
+
protected idsByConflict<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, rows: EntityData<E>[]): Promise<(WrittenId<E> | undefined)[]>;
|
|
282
289
|
/**
|
|
283
290
|
* Runs `write` between the event's `before`/`after` pair. The before hooks get the caller's rows, so
|
|
284
291
|
* what they assign is written; `write` and the after hooks get a copy, which by then carries what
|
|
@@ -99,19 +99,20 @@ function conflictAssignments(row, conflictPaths) {
|
|
|
99
99
|
}
|
|
100
100
|
return assigned;
|
|
101
101
|
}
|
|
102
|
-
/**
|
|
103
|
-
* Writes the key an upsert reported onto each row that named none - only the key, since an `onInsert`
|
|
104
|
-
* value was never written to a row the upsert updated. A report aligns with the rows only when it
|
|
105
|
-
* speaks for every one: a `firstId` dialect reports nothing for a batch.
|
|
106
|
-
*/
|
|
107
102
|
function adoptReportedIds(meta, rows, reported) {
|
|
108
|
-
if (
|
|
103
|
+
if (reported?.length !== rows.length) {
|
|
109
104
|
return;
|
|
110
105
|
}
|
|
111
106
|
const [idKey] = meta.ids;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
107
|
+
rows.forEach((row, index) => {
|
|
108
|
+
const id = reported[index];
|
|
109
|
+
if (meta.ids.length > 1) {
|
|
110
|
+
Object.assign(row, id);
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
row[idKey] ??= id;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
115
116
|
}
|
|
116
117
|
/** Normalizes either call form to `[entity, query, opts]`, throwing when a query object has no `$entity`. */
|
|
117
118
|
function entityArgs(args) {
|
|
@@ -1016,20 +1017,19 @@ export class AbstractQuerier {
|
|
|
1016
1017
|
*/
|
|
1017
1018
|
async idsByConflict(entity, conflictPaths, rows) {
|
|
1018
1019
|
const meta = getMeta(entity);
|
|
1019
|
-
const [idKey] = meta.ids;
|
|
1020
1020
|
const keys = getKeys(conflictPaths);
|
|
1021
1021
|
// A null key never conflicts, so no row is read back for it, whether one key names the row or several.
|
|
1022
1022
|
const named = rows.filter((row) => keys.every((key) => row[key] != null));
|
|
1023
1023
|
const distinct = [...new Map(named.map((row) => [rowKey(row, keys), row])).values()];
|
|
1024
1024
|
const found = [];
|
|
1025
1025
|
for (const batch of chunk(distinct, this.dialect.keyListCapacity(keys.length))) {
|
|
1026
|
-
const q = { $select: keySet([
|
|
1026
|
+
const q = { $select: keySet([...meta.ids, ...keys]), $where: whereKeysIn(keys, batch) };
|
|
1027
1027
|
found.push(await this.internalFindMany(entity, q, { filters: withoutSoftDeleteFilter(undefined) }));
|
|
1028
1028
|
}
|
|
1029
1029
|
const byConflict = new Map();
|
|
1030
1030
|
for (const row of found.flat()) {
|
|
1031
1031
|
const key = rowKey(row, keys);
|
|
1032
|
-
byConflict.set(key, byConflict.has(key) ? undefined : row
|
|
1032
|
+
byConflict.set(key, byConflict.has(key) ? undefined : idOf(meta, row));
|
|
1033
1033
|
}
|
|
1034
1034
|
return rows.map((row) => byConflict.get(rowKey(row, keys)));
|
|
1035
1035
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../dialect/index.js';
|
|
2
|
-
import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap,
|
|
2
|
+
import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
|
|
3
3
|
import type { BuildUpdateResultPayload } from '../util/sql.util.js';
|
|
4
|
-
import { AbstractQuerier } from './abstractQuerier.js';
|
|
4
|
+
import { AbstractQuerier, type UpsertedId } from './abstractQuerier.js';
|
|
5
5
|
export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
|
|
6
6
|
#private;
|
|
7
7
|
readonly dialect: AbstractSqlDialect;
|
|
@@ -83,7 +83,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
|
|
|
83
83
|
protected internalAggregate<E extends object, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
|
|
84
84
|
internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
|
|
85
85
|
internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
|
|
86
|
-
protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(
|
|
86
|
+
protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[] | undefined>;
|
|
87
87
|
private runUpsert;
|
|
88
88
|
protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
|
|
89
89
|
protected openTransaction(opts?: TransactionOptions): Promise<void>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AGGREGATE_VALUE_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
|
|
2
2
|
import { getMeta, namesKey } from '../entity/index.js';
|
|
3
3
|
import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf, isAutoIncrement } from '../util/index.js';
|
|
4
|
-
import { statementOf } from '../util/
|
|
4
|
+
import { statementOf } from '../util/sql.js';
|
|
5
5
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
6
6
|
import { AbstractQuerier } from './abstractQuerier.js';
|
|
7
7
|
import { streamViaCursor } from './cursorStream.js';
|
|
@@ -313,11 +313,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
313
313
|
async runUpsert(entity, conflictPaths, payload, update) {
|
|
314
314
|
const meta = getMeta(entity);
|
|
315
315
|
// Asked first: the statement fills an `onInsert` key into these rows whether it inserts them or not.
|
|
316
|
-
const unnamed =
|
|
316
|
+
const unnamed = payload.some((row) => !namesKey(meta, row));
|
|
317
317
|
const { ids } = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload, update));
|
|
318
318
|
const ordered = payload.length === 1 ||
|
|
319
319
|
(this.dialect.insertIdSource === 'returning' && this.dialect.features.orderedUpsertReturning);
|
|
320
|
-
if (ordered && ids?.length === payload.length) {
|
|
320
|
+
if (meta.ids.length === 1 && ordered && ids?.length === payload.length) {
|
|
321
321
|
return ids;
|
|
322
322
|
}
|
|
323
323
|
// The statement's ids name its rows only in order and for every one. A MySQL batch reports a
|
|
@@ -34,7 +34,7 @@ export declare function storedType(dialectName: DialectName, sqlType: string, re
|
|
|
34
34
|
* the engine settles an unstated bound. Migrations and drift both compare through it.
|
|
35
35
|
*/
|
|
36
36
|
export declare function engineType(dialect: AbstractDialect): (type: CanonicalType) => CanonicalType;
|
|
37
|
-
/** A field's canonical type; a timestamp without precision gets a `Date`'s milliseconds, unless it is `
|
|
37
|
+
/** A field's canonical type; a timestamp without precision gets a `Date`'s milliseconds, unless it is `sql` SQL. */
|
|
38
38
|
export declare function fieldOptionsToCanonical(options: FieldOptions): CanonicalType;
|
|
39
39
|
/** Whether two canonical types are equal, guessing no engine default: `DiffOptions.normalizeType` settles those. */
|
|
40
40
|
export declare function areTypesEqual(a: CanonicalType, b: CanonicalType): boolean;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// Canonical types, between an engine's SQL types and TypeScript's.
|
|
2
2
|
import { fieldOf, getMeta, soleIdOf } from '../entity/metadata/definition.js';
|
|
3
|
-
import {
|
|
3
|
+
import { QuerySql } from '../type/index.js';
|
|
4
4
|
import { DATE_PRECISION } from '../util/date.js';
|
|
5
5
|
import { columnFamily, isIntegerColumn } from '../util/field.util.js';
|
|
6
|
-
import { constantSql } from '../util/
|
|
6
|
+
import { constantSql } from '../util/sql.js';
|
|
7
7
|
/** Whether a category is one of the vector types, narrowing it to the cast pgvector names use. */
|
|
8
8
|
export function isVectorCategory(category) {
|
|
9
9
|
return category === 'vector' || category === 'halfvec' || category === 'sparsevec';
|
|
@@ -267,12 +267,12 @@ export function sqlToCanonical(sqlType, reported = {}) {
|
|
|
267
267
|
};
|
|
268
268
|
}
|
|
269
269
|
/**
|
|
270
|
-
* The SQL type a field declares, however it named one: `columnType`, the engine's own as a `
|
|
270
|
+
* The SQL type a field declares, however it named one: `columnType`, the engine's own as a `sql`
|
|
271
271
|
* constant, or a `type` that is a SQL string rather than a constructor.
|
|
272
272
|
*/
|
|
273
273
|
function declaredSqlType(options) {
|
|
274
274
|
const { columnType, type } = options;
|
|
275
|
-
if (columnType instanceof
|
|
275
|
+
if (columnType instanceof QuerySql) {
|
|
276
276
|
return constantSql(columnType);
|
|
277
277
|
}
|
|
278
278
|
return columnType ?? (typeof type === 'string' ? type : undefined);
|
|
@@ -346,10 +346,10 @@ export function storedType(dialectName, sqlType, reported) {
|
|
|
346
346
|
export function engineType(dialect) {
|
|
347
347
|
return (type) => storedType(dialect.dialectName, canonicalToSql(type, dialect));
|
|
348
348
|
}
|
|
349
|
-
/** A field's canonical type; a timestamp without precision gets a `Date`'s milliseconds, unless it is `
|
|
349
|
+
/** A field's canonical type; a timestamp without precision gets a `Date`'s milliseconds, unless it is `sql` SQL. */
|
|
350
350
|
export function fieldOptionsToCanonical(options) {
|
|
351
351
|
const type = fieldType(options);
|
|
352
|
-
return options.columnType instanceof
|
|
352
|
+
return options.columnType instanceof QuerySql ? type : withTimestampPrecision(type, DATE_PRECISION);
|
|
353
353
|
}
|
|
354
354
|
function fieldType(options) {
|
|
355
355
|
// A SQL type is read exactly as an introspected one is, whichever option named it, so a bound stated
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { QuerySql, type SqlValueName } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* The kind of a {@link SqlExpression}: a value uql exports by name, which `formatDefaultValue` spells for the
|
|
4
4
|
* engine at DDL time, or `raw`, carrying its own SQL.
|
|
5
5
|
*/
|
|
6
|
-
export type SqlExpressionKind = SqlValueName | '
|
|
6
|
+
export type SqlExpressionKind = SqlValueName | 'sql';
|
|
7
7
|
/**
|
|
8
8
|
* A column default that is SQL rather than a literal, whether an entity or a migration declares it or
|
|
9
9
|
* introspection reads it back. It is a class, not a plain object, so a JSON default cannot pass for one.
|
|
@@ -11,7 +11,7 @@ export type SqlExpressionKind = SqlValueName | 'raw';
|
|
|
11
11
|
export declare class SqlExpression {
|
|
12
12
|
readonly kind: SqlExpressionKind;
|
|
13
13
|
readonly sql?: string | undefined;
|
|
14
|
-
/** `sql` is set only for the `
|
|
14
|
+
/** `sql` is set only for the `sql` kind, which carries its own text verbatim. */
|
|
15
15
|
constructor(kind: SqlExpressionKind, sql?: string | undefined);
|
|
16
16
|
static isExpression(value: unknown): value is SqlExpression;
|
|
17
17
|
/** Wraps `sql` in parentheses, which every engine accepts for a default expression and SQLite and MySQL require. */
|
|
@@ -23,7 +23,7 @@ export declare class SqlExpression {
|
|
|
23
23
|
* A default in schema form: a value uql exports (`currentTimestamp`) becomes its kind, so each engine spells it
|
|
24
24
|
* for the column it fills; other `raw` becomes the SQL `compile` renders, parenthesized; a literal is kept.
|
|
25
25
|
*/
|
|
26
|
-
export declare function schemaDefault(value: unknown, compile: (sql:
|
|
26
|
+
export declare function schemaDefault(value: unknown, compile: (sql: QuerySql) => string): unknown;
|
|
27
27
|
/**
|
|
28
28
|
* A default as text to compare: numbers as their digits, other text as written, and objects (SQL included) and text
|
|
29
29
|
* holding a JSON object or list as JSON with its keys in order, equal as documents, since `jsonb` reprints them.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { QuerySql, SQL_VALUE_NAMES } from '../type/index.js';
|
|
2
2
|
import { isRecord } from '../util/object.util.js';
|
|
3
|
-
import { SQL_VALUES } from '../util/
|
|
3
|
+
import { SQL_VALUES } from '../util/sql.js';
|
|
4
4
|
/**
|
|
5
5
|
* A column default that is SQL rather than a literal, whether an entity or a migration declares it or
|
|
6
6
|
* introspection reads it back. It is a class, not a plain object, so a JSON default cannot pass for one.
|
|
@@ -8,7 +8,7 @@ import { SQL_VALUES } from '../util/raw.js';
|
|
|
8
8
|
export class SqlExpression {
|
|
9
9
|
kind;
|
|
10
10
|
sql;
|
|
11
|
-
/** `sql` is set only for the `
|
|
11
|
+
/** `sql` is set only for the `sql` kind, which carries its own text verbatim. */
|
|
12
12
|
constructor(kind, sql) {
|
|
13
13
|
this.kind = kind;
|
|
14
14
|
this.sql = sql;
|
|
@@ -18,7 +18,7 @@ export class SqlExpression {
|
|
|
18
18
|
}
|
|
19
19
|
/** Wraps `sql` in parentheses, which every engine accepts for a default expression and SQLite and MySQL require. */
|
|
20
20
|
static parenthesized(sql) {
|
|
21
|
-
return new SqlExpression('
|
|
21
|
+
return new SqlExpression('sql', `(${sql})`);
|
|
22
22
|
}
|
|
23
23
|
/** Its SQL, or its kind, as diffs and drift reports show it. */
|
|
24
24
|
toString() {
|
|
@@ -35,7 +35,7 @@ export function schemaDefault(value, compile) {
|
|
|
35
35
|
if (name) {
|
|
36
36
|
return new SqlExpression(name);
|
|
37
37
|
}
|
|
38
|
-
return value instanceof
|
|
38
|
+
return value instanceof QuerySql ? SqlExpression.parenthesized(compile(value)) : value;
|
|
39
39
|
}
|
|
40
40
|
/**
|
|
41
41
|
* A default as text to compare: numbers as their digits, other text as written, and objects (SQL included) and text
|