uql-orm 0.92.0 → 0.93.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.
Files changed (58) hide show
  1. package/dist/browser/uql-browser.min.js.map +2 -2
  2. package/dist/cockroachdb/cockroachDialect.js +1 -1
  3. package/dist/dialect/abstractSqlDialect.d.ts +45 -10
  4. package/dist/dialect/abstractSqlDialect.js +139 -63
  5. package/dist/dialect/mergeSqlDialect.d.ts +11 -2
  6. package/dist/dialect/mergeSqlDialect.js +28 -12
  7. package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
  8. package/dist/dialect/mysqlLikeSqlDialect.js +34 -21
  9. package/dist/dialect/pgLikeSqlDialect.d.ts +5 -1
  10. package/dist/dialect/pgLikeSqlDialect.js +8 -1
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +2 -2
  13. package/dist/maria/mariaDialect.d.ts +3 -1
  14. package/dist/maria/mariaDialect.js +3 -1
  15. package/dist/migrate/builder/index.d.ts +0 -1
  16. package/dist/migrate/builder/index.js +0 -1
  17. package/dist/migrate/builder/tableBuilder.js +2 -2
  18. package/dist/migrate/codegen/fieldOptionsSource.js +4 -11
  19. package/dist/migrate/ddl/defaultSql.d.ts +31 -0
  20. package/dist/migrate/ddl/defaultSql.js +109 -0
  21. package/dist/migrate/ddl/pgTableDdl.js +1 -1
  22. package/dist/migrate/ddl/tableDdl.js +1 -1
  23. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
  24. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +4 -5
  25. package/dist/migrate/introspection/mysqlIntrospector.js +4 -2
  26. package/dist/migrate/schemaGenerator.js +1 -1
  27. package/dist/migrate/storage/databaseStorage.js +2 -2
  28. package/dist/migrate/triggerSql.js +9 -2
  29. package/dist/mongo/mongodbQuerier.d.ts +13 -5
  30. package/dist/mongo/mongodbQuerier.js +39 -5
  31. package/dist/mssql/mssqlDialect.d.ts +9 -4
  32. package/dist/mssql/mssqlDialect.js +18 -5
  33. package/dist/postgres/postgresDialect.d.ts +5 -2
  34. package/dist/postgres/postgresDialect.js +5 -5
  35. package/dist/querier/abstractQuerier.d.ts +5 -5
  36. package/dist/querier/abstractQuerier.js +19 -15
  37. package/dist/querier/abstractSqlQuerier.d.ts +3 -3
  38. package/dist/querier/abstractSqlQuerier.js +7 -7
  39. package/dist/schema/schemaASTBuilder.js +2 -16
  40. package/dist/schema/sqlExpression.d.ts +9 -3
  41. package/dist/schema/sqlExpression.js +14 -0
  42. package/dist/sqlite/sqliteDialect.d.ts +5 -4
  43. package/dist/sqlite/sqliteDialect.js +12 -4
  44. package/dist/type/dialect.d.ts +29 -11
  45. package/dist/type/dialect.js +2 -0
  46. package/dist/type/entity.d.ts +15 -0
  47. package/dist/type/query.d.ts +12 -1
  48. package/dist/type/universalQuerier.d.ts +3 -3
  49. package/dist/util/index.d.ts +1 -1
  50. package/dist/util/index.js +1 -1
  51. package/dist/util/raw.d.ts +13 -3
  52. package/dist/util/raw.js +29 -3
  53. package/dist/util/triggerWrite.d.ts +11 -1
  54. package/dist/util/triggerWrite.js +14 -0
  55. package/package.json +1 -1
  56. package/skills/uql-orm/SKILL.md +3 -2
  57. package/dist/migrate/builder/expressions.d.ts +0 -63
  58. package/dist/migrate/builder/expressions.js +0 -142
@@ -71,6 +71,18 @@ const AGGREGATE_FN = {
71
71
  $min: 'MIN',
72
72
  $max: 'MAX',
73
73
  };
74
+ /** ` FROM <rows> WHERE <narrowing>`: what a set-based trigger's body reads, as {@link TriggerRows} states it. */
75
+ export function fromRows(rows) {
76
+ return ` FROM ${rows.from}${rows.where ? ` WHERE ${rows.where}` : ''}`;
77
+ }
78
+ /** The ANSI spellings, which an engine overrides where it differs. No ANSI function makes a UUID. */
79
+ export const ANSI_SQL_VALUES = {
80
+ currentTimestamp: 'CURRENT_TIMESTAMP',
81
+ currentDate: 'CURRENT_DATE',
82
+ currentTime: 'CURRENT_TIME',
83
+ uuid: undefined,
84
+ uuidv7: undefined,
85
+ };
74
86
  export class AbstractSqlDialect extends VectorSqlDialect {
75
87
  /** Itself, unless the engine is a fork running another's SQL, which is the only case that overrides. */
76
88
  get dialectFamily() {
@@ -89,7 +101,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
89
101
  }
90
102
  isolationLevelStrategy = 'inline';
91
103
  booleanLiteral = 'native';
92
- currentTimestamp = 'CURRENT_TIMESTAMP';
104
+ sqlValues = ANSI_SQL_VALUES;
93
105
  /**
94
106
  * Maximum number of bind parameters the driver accepts in a single statement.
95
107
  * `insertMany` splits larger batches into multiple statements based on this limit.
@@ -1264,29 +1276,47 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1264
1276
  }
1265
1277
  update(ctx, entity, q, payload, opts) {
1266
1278
  const meta = getMeta(entity);
1267
- const [filledPayload] = fillOnFields(meta, payload, 'onUpdate');
1268
- const keys = filterFieldKeys(meta, filledPayload, 'onUpdate');
1269
1279
  ctx.append(`UPDATE ${this.escapedTableName(meta)} SET `);
1270
- for (let i = 0; i < keys.length; i++) {
1280
+ this.appendAssignments(ctx, meta, this.updateEntries(meta, payload));
1281
+ this.search(ctx, entity, q, opts);
1282
+ }
1283
+ /** What an update assigns: the payload's fields, `onUpdate` fills included. */
1284
+ updateEntries(meta, payload) {
1285
+ const [filled] = fillOnFields(meta, payload, 'onUpdate');
1286
+ return filterFieldKeys(meta, filled, 'onUpdate').map((key) => [key, filled[key]]);
1287
+ }
1288
+ /**
1289
+ * A `SET` list, each assignment reading its column as `qualifier` names it, which an upsert sets: `MERGE`'s
1290
+ * source and MySQL's new row share the table's column names.
1291
+ */
1292
+ appendAssignments(ctx, meta, entries, qualifier = '') {
1293
+ entries.forEach(([key, value], i) => {
1271
1294
  if (i > 0) {
1272
1295
  ctx.append(', ');
1273
1296
  }
1274
- this.appendAssignment(ctx, meta, keys[i], filledPayload[keys[i]]);
1275
- }
1276
- this.search(ctx, entity, q, opts);
1297
+ this.appendAssignment(ctx, meta, key, value, qualifier);
1298
+ });
1277
1299
  }
1278
- /** `col = value`, a JSON operator or a `$inc`/`$mul` spelled as the engine's. */
1279
- appendAssignment(ctx, meta, key, value) {
1300
+ /**
1301
+ * `col = value`, a JSON operator or a `$inc`/`$mul` spelled as the engine's. What reads the table, the operators
1302
+ * and the refs in SQL alike, reads it through `qualifier`.
1303
+ */
1304
+ appendAssignment(ctx, meta, key, value, qualifier = '') {
1280
1305
  const field = meta.fields[key];
1281
1306
  const escapedCol = this.escapedColumnName(meta, key);
1307
+ const current = `${qualifier}${escapedCol}`;
1282
1308
  if (isJsonUpdateOp(value)) {
1283
- this.formatJsonUpdate(ctx, escapedCol, value, field);
1309
+ this.formatJsonUpdate(ctx, escapedCol, value, field, current);
1284
1310
  }
1285
1311
  else if (isFieldUpdateOp(value)) {
1286
1312
  const [op, operand] = fieldUpdateOf(key, value);
1287
- ctx.append(`${escapedCol} = COALESCE(${escapedCol}, 0) ${SQL_ARITHMETIC[op]} `);
1313
+ ctx.append(`${escapedCol} = COALESCE(${current}, 0) ${SQL_ARITHMETIC[op]} `);
1288
1314
  ctx.addValue(operand);
1289
1315
  }
1316
+ else if (qualifier && value instanceof QueryRaw) {
1317
+ ctx.append(`${escapedCol} = `);
1318
+ this.getRawValue(ctx, { value, escapedPrefix: qualifier });
1319
+ }
1290
1320
  else {
1291
1321
  ctx.append(`${escapedCol} = `);
1292
1322
  this.formatPersistableValue(ctx, field, value);
@@ -1298,27 +1328,36 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1298
1328
  * trigger has none of. `rows` are what a set-based engine's body reads, narrowed to the ones it fires for.
1299
1329
  */
1300
1330
  triggerWrite(ctx, write, rows) {
1331
+ if (write.kind === 'refuse') {
1332
+ ctx.append(this.refusal(this.escape(write.message), rows));
1333
+ return;
1334
+ }
1301
1335
  const meta = getMeta(write.entity);
1302
1336
  const table = this.escapedTableName(meta);
1303
- if (write.kind === 'insert') {
1337
+ if (write.kind === 'insert' || write.kind === 'upsert') {
1304
1338
  const unfilled = definedEntries(meta.fields).find(([key, field]) => field.onInsert !== undefined && field.defaultValue === undefined && write.row[key] === undefined);
1305
1339
  if (unfilled) {
1306
1340
  throw new UqlUsageError(`'${meta.name}.${unfilled[0]}' is filled on insert by uql, which a trigger does not run: ` +
1307
1341
  'name it, or give it a defaultValue');
1308
1342
  }
1309
1343
  const entries = this.writtenEntries(meta, write.row);
1310
- const columns = entries.map(([key]) => this.escapedColumnName(meta, key)).join(', ');
1311
- const [open, close] = rows
1312
- ? ['SELECT ', ` FROM ${rows.from}${rows.where ? ` WHERE ${rows.where}` : ''};`]
1313
- : ['VALUES (', ');'];
1314
- ctx.append(`INSERT INTO ${table} (${columns}) ${open}`);
1315
- entries.forEach(([key, value], i) => {
1316
- if (i > 0) {
1317
- ctx.append(', ');
1318
- }
1319
- this.formatPersistableValue(ctx, meta.fields[key], value);
1320
- });
1321
- ctx.append(close);
1344
+ if (write.kind === 'insert') {
1345
+ this.appendTriggerInsert(ctx, meta, entries, rows);
1346
+ ctx.append(';');
1347
+ return;
1348
+ }
1349
+ const { conflictPaths, update } = write;
1350
+ // What a conflicting row takes, none filled in JavaScript: the incoming row less the conflict paths, or `update`.
1351
+ const assigned = update === undefined
1352
+ ? entries
1353
+ .filter(([key]) => !conflictPaths[key])
1354
+ .map(([key]) => [key, this.incoming(meta, key)])
1355
+ : hasKeys(update)
1356
+ ? this.writtenEntries(meta, update)
1357
+ : [];
1358
+ this.refuseAccumulating(meta, assigned, rows);
1359
+ const assignments = this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, assigned, `${table}.`));
1360
+ this.appendTriggerUpsert(ctx, meta, conflictPaths, entries, assignments, rows);
1322
1361
  return;
1323
1362
  }
1324
1363
  assertWhere(meta, write.where);
@@ -1327,18 +1366,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1327
1366
  }
1328
1367
  if (write.kind === 'update') {
1329
1368
  const entries = this.writtenEntries(meta, write.set);
1330
- const accumulating = rows && entries.find(([, value]) => accumulates(value));
1331
- if (accumulating) {
1332
- throw new UqlUsageError(`'${meta.name}.${accumulating[0]}' cannot accumulate per row in a trigger fired once per statement, ` +
1333
- 'which applies $inc, $mul and $push once');
1334
- }
1369
+ this.refuseAccumulating(meta, entries, rows);
1335
1370
  ctx.append(`UPDATE ${table} SET `);
1336
- entries.forEach(([key, value], i) => {
1337
- if (i > 0) {
1338
- ctx.append(', ');
1339
- }
1340
- this.appendAssignment(ctx, meta, key, value);
1341
- });
1371
+ this.appendAssignments(ctx, meta, entries);
1342
1372
  }
1343
1373
  else {
1344
1374
  ctx.append(`DELETE FROM ${table}`);
@@ -1352,6 +1382,47 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1352
1382
  this.renderWhere(ctx, write.entity, where, { escapedPrefix: `${table}.` });
1353
1383
  ctx.append(';');
1354
1384
  }
1385
+ /** `$inc`, `$mul` and `$push` refused where the body reads a set, which applies each once for the statement. */
1386
+ refuseAccumulating(meta, entries, rows) {
1387
+ const accumulating = rows && entries.find(([, value]) => accumulates(value));
1388
+ if (accumulating) {
1389
+ throw new UqlUsageError(`'${meta.name}.${accumulating[0]}' cannot accumulate per row in a trigger fired once per statement, ` +
1390
+ 'which applies $inc, $mul and $push once');
1391
+ }
1392
+ }
1393
+ /** A trigger's insert, unterminated: its values, or a `SELECT` of them off the set a set-based engine hands it. */
1394
+ appendTriggerInsert(ctx, meta, entries, rows) {
1395
+ const columns = entries.map(([key]) => this.escapedColumnName(meta, key)).join(', ');
1396
+ ctx.append(`INSERT INTO ${this.escapedTableName(meta)} (${columns}) ${rows ? 'SELECT ' : 'VALUES ('}`);
1397
+ this.appendTriggerValues(ctx, meta, entries);
1398
+ ctx.append(rows ? fromRows(rows) : ')');
1399
+ }
1400
+ /** The values a trigger writes, a literal or SQL each, the rows' refs most often. */
1401
+ appendTriggerValues(ctx, meta, entries) {
1402
+ entries.forEach(([key, value], i) => {
1403
+ if (i > 0) {
1404
+ ctx.append(', ');
1405
+ }
1406
+ this.formatPersistableValue(ctx, meta.fields[key], value);
1407
+ });
1408
+ }
1409
+ /** A trigger's upsert: its insert, then what a conflicting row takes, `assignments`, or nothing where empty. */
1410
+ appendTriggerUpsert(ctx, meta, conflictPaths, entries, assignments, rows) {
1411
+ this.appendTriggerInsert(ctx, meta, entries, rows);
1412
+ ctx.append(`${this.onConflict(meta, conflictPaths, assignments)};`);
1413
+ }
1414
+ /** ` ON CONFLICT (keys) DO UPDATE SET ...`, or `DO NOTHING` with nothing to assign. */
1415
+ onConflict(meta, conflictPaths, assignments) {
1416
+ const keys = this.getUpsertConflictPathsStr(meta, conflictPaths);
1417
+ return ` ON CONFLICT (${keys}) ${assignments ? `DO UPDATE SET ${assignments}` : 'DO NOTHING'}`;
1418
+ }
1419
+ /**
1420
+ * The statement failing a trigger's write with `message`, a quoted literal: SQL/PSM's `SIGNAL`, which the
1421
+ * MySQL family speaks. `rows` are what a set-based engine's body reads, where it fails only if there are any.
1422
+ */
1423
+ refusal(message, _rows) {
1424
+ return `SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = ${message};`;
1425
+ }
1355
1426
  /** The values a write names, refusing one the entity has no column for. */
1356
1427
  writtenEntries(meta, values) {
1357
1428
  const entries = Object.entries(values).filter(([, value]) => value !== undefined);
@@ -1368,43 +1439,48 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1368
1439
  * `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING`. The assignments are built before the insert
1369
1440
  * fills `onInsert` columns, which must stay out of them, and their values bound after it, where a `?` reads them.
1370
1441
  */
1371
- upsert(ctx, entity, conflictPaths, payload,
1372
- /** One more `RETURNING` item, as a bare expression: this joins the list and adds the keyword. */
1373
- extraReturning = '') {
1442
+ upsert(ctx, entity, conflictPaths, payload, { update } = {}) {
1374
1443
  const meta = getMeta(entity);
1375
1444
  const updateCtx = this.upsertUpdateBindsInPlace ? ctx : this.createContext();
1376
- const update = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, this.upsertExcluded);
1377
- const keys = this.getUpsertConflictPathsStr(meta, conflictPaths);
1378
- const onConflict = update ? `DO UPDATE SET ${update}` : 'DO NOTHING';
1445
+ const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
1379
1446
  // Composed rather than concatenated: a composite key contributes no id item, and a dialect's own
1380
1447
  // item (Postgres's created flag) must then come right after the keyword, with no comma before it.
1381
- const returning = [this.returningIdExpression(meta), extraReturning].filter(Boolean).join(', ');
1448
+ const returning = [this.returningIdExpression(meta), this.upsertCreatedReturning].filter(Boolean).join(', ');
1382
1449
  this.appendInsertValues(ctx, entity, payload);
1383
- ctx.append(` ON CONFLICT (${keys}) ${onConflict}${returning ? ` RETURNING ${returning}` : ''}`);
1450
+ ctx.append(`${this.onConflict(meta, conflictPaths, assignments)}${returning ? ` RETURNING ${returning}` : ''}`);
1384
1451
  if (updateCtx !== ctx) {
1385
1452
  ctx.pushValue(...updateCtx.values);
1386
1453
  }
1387
1454
  }
1455
+ /** One more `RETURNING` item saying whether the row was created, where the engine can tell; else empty. */
1456
+ upsertCreatedReturning = '';
1388
1457
  /** Whether the upsert's assignments bind straight into the statement, as numbered `$n` placeholders can. */
1389
1458
  upsertUpdateBindsInPlace = false;
1390
- /** How an `ON CONFLICT` assignment reads the row that was being inserted. */
1391
- upsertExcluded = (columnName) => `EXCLUDED.${columnName}`;
1392
- getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, callback) {
1459
+ /** How an upsert's assignment reads `column` of the row that was being inserted. */
1460
+ upsertIncoming(column) {
1461
+ return `EXCLUDED.${column}`;
1462
+ }
1463
+ /** `key`'s column of the row being inserted, as SQL an assignment takes. */
1464
+ incoming(meta, key) {
1465
+ const column = this.escapedColumnName(meta, key);
1466
+ return raw(() => this.upsertIncoming(column));
1467
+ }
1468
+ /**
1469
+ * What a conflicting row takes: `update` where given, else the incoming row less the conflict paths, and what
1470
+ * `onUpdate` fills. An empty `update` leaves the row as it is, its fills included: nothing to assign.
1471
+ */
1472
+ getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, update) {
1393
1473
  const sample = Array.isArray(payload) ? payload[0] : payload;
1394
- const cloned = { ...sample };
1395
- const [filledPayload] = fillOnFields(meta, cloned, 'onUpdate');
1396
- const fields = filterFieldKeys(meta, filledPayload, 'onUpdate');
1397
- return fields
1398
- .filter((col) => !conflictPaths[col])
1399
- .map((col) => {
1400
- const column = this.escapedColumnName(meta, col);
1401
- if (Object.hasOwn(sample, col)) {
1402
- return `${column} = ${callback(column)}`;
1403
- }
1404
- const text = this.buildFragment(ctx, (fragmentCtx) => this.formatPersistableValue(fragmentCtx, meta.fields[col], filledPayload[col]));
1405
- return `${column} = ${text}`;
1406
- })
1407
- .join(', ');
1474
+ const [filled] = fillOnFields(meta, { ...sample }, 'onUpdate');
1475
+ const entries = update
1476
+ ? hasKeys(update)
1477
+ ? this.updateEntries(meta, update)
1478
+ : []
1479
+ : filterFieldKeys(meta, filled, 'onUpdate')
1480
+ .filter((key) => !conflictPaths[key])
1481
+ .map((key) => [key, Object.hasOwn(sample, key) ? this.incoming(meta, key) : filled[key]]);
1482
+ const qualifier = `${this.escapedTableName(meta)}.`;
1483
+ return this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, entries, qualifier));
1408
1484
  }
1409
1485
  getUpsertConflictPathsStr(meta, conflictPaths) {
1410
1486
  return getKeys(conflictPaths)
@@ -1569,11 +1645,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1569
1645
  * `"col" = <expr>` for a JSON update, each operator wrapping the last: `$pull`, `$set`, `$push`, `$unset`.
1570
1646
  * `$pull` reads the column and every later one its expression once, so no value binds twice.
1571
1647
  */
1572
- formatJsonUpdate(ctx, escapedCol, value, field) {
1648
+ formatJsonUpdate(ctx, escapedCol, value, field, current = escapedCol) {
1573
1649
  const { $pull, $set, $push, $unset } = value;
1574
- let expr = escapedCol;
1650
+ let expr = current;
1575
1651
  if (hasKeys($pull)) {
1576
- expr = this.jsonPull(ctx, expr, escapedCol, $pull);
1652
+ expr = this.jsonPull(ctx, expr, current, $pull);
1577
1653
  }
1578
1654
  if (hasKeys($set)) {
1579
1655
  expr = this.jsonSet(ctx, expr, $set, field);
@@ -1,4 +1,4 @@
1
- import type { QueryConflictPaths, QueryContext, QueryPager, Type } from '../type/index.js';
1
+ import type { EntityMeta, QueryConflictPaths, QueryContext, QueryPager, TriggerRows, Type, UpsertOptions } from '../type/index.js';
2
2
  import { AbstractSqlDialect } from './abstractSqlDialect.js';
3
3
  /** What SQL Server and Oracle share: paging and upsert spelled as the standard does. */
4
4
  export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
@@ -12,7 +12,16 @@ export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
12
12
  * assignments bind their values before the rows, though they follow them in the SQL; this works only because
13
13
  * SQL Server numbers each placeholder (`@p1`).
14
14
  */
15
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[]): void;
15
+ upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], { update }?: UpsertOptions<E>): void;
16
+ /** A trigger's upsert as a `MERGE` of the rows it was handed, `SELECT`ed off them as its source. */
17
+ protected appendTriggerUpsert<E>(ctx: QueryContext, meta: EntityMeta<E>, conflictPaths: QueryConflictPaths<E>, entries: readonly [string, unknown][], assignments: string, rows?: TriggerRows): void;
18
+ /**
19
+ * The rest of a `MERGE` once its source is written: the source named, matched on the conflict keys, updated
20
+ * by `assignments` where it matched, if any, and inserted where it did not.
21
+ */
22
+ private mergeMatch;
23
+ /** The source row through the alias `MERGE` gives it. */
24
+ protected upsertIncoming(column: string): string;
16
25
  /** `<target>.<col> = <source>.<col>` for every conflict key, which is what makes a row "the same". */
17
26
  private mergeOn;
18
27
  /**
@@ -1,6 +1,6 @@
1
1
  import { getMeta } from '../entity/index.js';
2
2
  import { assertNonNegativeInteger, getKeys } from '../util/index.js';
3
- import { AbstractSqlDialect } from './abstractSqlDialect.js';
3
+ import { AbstractSqlDialect, fromRows } from './abstractSqlDialect.js';
4
4
  import { UPSERT_SOURCE_ALIAS } from './aliases.js';
5
5
  /** What SQL Server and Oracle share: paging and upsert spelled as the standard does. */
6
6
  export class MergeSqlDialect extends AbstractSqlDialect {
@@ -25,29 +25,45 @@ export class MergeSqlDialect extends AbstractSqlDialect {
25
25
  * assignments bind their values before the rows, though they follow them in the SQL; this works only because
26
26
  * SQL Server numbers each placeholder (`@p1`).
27
27
  */
28
- upsert(ctx, entity, conflictPaths, payload) {
28
+ upsert(ctx, entity, conflictPaths, payload, { update } = {}) {
29
29
  const meta = getMeta(entity);
30
- const table = this.escapedTableName(meta);
31
- const source = this.escapeId(UPSERT_SOURCE_ALIAS, true);
32
30
  // Before the row source, which is what fills the payload's `onInsert` fields: a column that
33
31
  // exists only there - the generated key, `createdAt` - must not join the update set, or a row
34
32
  // that already existed has both rewritten.
35
- const update = this.getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, (col) => `${source}.${col}`);
33
+ const assignments = this.getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, update);
36
34
  const shape = this.insertShape(entity, payload);
37
- const columns = shape.columns.join(', ');
38
- ctx.append(`MERGE INTO ${table}${this.mergeTargetHint} USING (VALUES `);
35
+ ctx.append(`MERGE INTO ${this.escapedTableName(meta)}${this.mergeTargetHint} USING (VALUES `);
39
36
  this.appendValueRows(ctx, shape);
40
- ctx.append(`) AS ${source} (${columns}) ON ${this.mergeOn(meta, conflictPaths, table, source)}`);
41
- if (update) {
42
- ctx.append(` WHEN MATCHED THEN UPDATE SET ${update}`);
43
- }
44
- ctx.append(` WHEN NOT MATCHED THEN INSERT (${columns}) VALUES (${shape.columns.map((col) => `${source}.${col}`).join(', ')})`);
37
+ ctx.append(`)${this.mergeMatch(meta, conflictPaths, shape.columns, assignments)}`);
45
38
  const returning = this.returningIdExpression(meta);
46
39
  if (returning) {
47
40
  ctx.append(` ${this.mergeReturning(returning)}`);
48
41
  }
49
42
  ctx.append(this.statementTerminator);
50
43
  }
44
+ /** A trigger's upsert as a `MERGE` of the rows it was handed, `SELECT`ed off them as its source. */
45
+ appendTriggerUpsert(ctx, meta, conflictPaths, entries, assignments, rows) {
46
+ ctx.append(`MERGE INTO ${this.escapedTableName(meta)}${this.mergeTargetHint} USING (SELECT `);
47
+ this.appendTriggerValues(ctx, meta, entries);
48
+ const columns = entries.map(([key]) => this.escapedColumnName(meta, key));
49
+ ctx.append(`${rows ? fromRows(rows) : ''})${this.mergeMatch(meta, conflictPaths, columns, assignments)};`);
50
+ }
51
+ /**
52
+ * The rest of a `MERGE` once its source is written: the source named, matched on the conflict keys, updated
53
+ * by `assignments` where it matched, if any, and inserted where it did not.
54
+ */
55
+ mergeMatch(meta, conflictPaths, columns, assignments) {
56
+ const table = this.escapedTableName(meta);
57
+ const source = this.escapeId(UPSERT_SOURCE_ALIAS, true);
58
+ const matched = assignments ? ` WHEN MATCHED THEN UPDATE SET ${assignments}` : '';
59
+ const values = columns.map((col) => `${source}.${col}`).join(', ');
60
+ return (` AS ${source} (${columns.join(', ')}) ON ${this.mergeOn(meta, conflictPaths, table, source)}${matched}` +
61
+ ` WHEN NOT MATCHED THEN INSERT (${columns.join(', ')}) VALUES (${values})`);
62
+ }
63
+ /** The source row through the alias `MERGE` gives it. */
64
+ upsertIncoming(column) {
65
+ return `${this.escapeId(UPSERT_SOURCE_ALIAS, true)}.${column}`;
66
+ }
51
67
  /** `<target>.<col> = <source>.<col>` for every conflict key, which is what makes a row "the same". */
52
68
  mergeOn(meta, conflictPaths, table, source) {
53
69
  return getKeys(conflictPaths)
@@ -1,10 +1,12 @@
1
- import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, Type } from '../type/index.js';
1
+ import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, Type, UpsertOptions } from '../type/index.js';
2
2
  import { AbstractSqlDialect, type DerivedRelation, type RelationRows } from './abstractSqlDialect.js';
3
3
  import { type JsonSlot } from './jsonSql.js';
4
4
  /** Declared apart so MariaDB, which has no `FOR UPDATE OF`, can restate that one part of it. */
5
5
  export declare const MYSQL_ROW_LOCKS: RowLockFeatures;
6
6
  /** The features of MySQL, which MariaDB starts from. */
7
7
  export declare const MYSQL_FEATURES: SqlDialectFeatures;
8
+ /** `(3)` keeps milliseconds, where a bare `CURRENT_TIMESTAMP` has whole seconds; `UUID()` is a version 1. */
9
+ export declare const MYSQL_SQL_VALUES: SqlValues;
8
10
  /** What MySQL and MariaDB share, their JSON functions above all: `JSON_LENGTH`, `JSON_CONTAINS`, `JSON_TABLE`, `JSON_SET`. */
9
11
  export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
10
12
  /** Every member of this family runs the same SQL, so a body written once serves them all. */
@@ -23,14 +25,18 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
23
25
  readonly beginTransactionCommand = "START TRANSACTION";
24
26
  readonly isolationLevelStrategy = "set-before";
25
27
  readonly booleanLiteral = "integer";
26
- /** `(3)` keeps milliseconds; a bare `CURRENT_TIMESTAMP` has whole seconds only. */
27
- readonly currentTimestamp = "CURRENT_TIMESTAMP(3)";
28
+ readonly sqlValues: SqlValues;
28
29
  readonly insertIdSource: InsertIdSource;
30
+ /** `INSERT ... ON DUPLICATE KEY UPDATE`, the assignments bound after the insert, where a `?` reads them. */
31
+ upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], { update }?: UpsertOptions<E>): void;
32
+ protected appendTriggerUpsert<E>(ctx: QueryContext, meta: EntityMeta<E>, _conflictPaths: QueryConflictPaths<E>, entries: readonly [string, unknown][], assignments: string): void;
29
33
  /**
30
- * `INSERT ... ON DUPLICATE KEY UPDATE`, or `INSERT IGNORE` where there is nothing to assign. The
31
- * assignments bind after the insert, where a `?` reads them.
34
+ * `insert` on a duplicate key: `ON DUPLICATE KEY UPDATE` with the new row named, or `INSERT IGNORE` where there
35
+ * is nothing to assign. MySQL matches on any unique key, not just the conflict paths, which it cannot name.
32
36
  */
33
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[]): void;
37
+ private onDuplicateKey;
38
+ /** The new row through the alias it is given, or `VALUE(col)` where the dialect has no such syntax. */
39
+ protected upsertIncoming(column: string): string;
34
40
  /**
35
41
  * The alias the inserted row is given after the values list, and read back by the assignments.
36
42
  * Undefined where the dialect has no such syntax - MariaDB, which reads that row through
@@ -1,7 +1,7 @@
1
1
  import { getMeta } from '../entity/index.js';
2
2
  import { textSearchFields } from '../util/index.js';
3
3
  import { escapeMysqlSqlLiteral, escapeSingleQuotes } from '../util/sqlLiteral.js';
4
- import { AbstractSqlDialect, } from './abstractSqlDialect.js';
4
+ import { ANSI_SQL_VALUES, AbstractSqlDialect, } from './abstractSqlDialect.js';
5
5
  import { AGGREGATE_VALUE_ALIAS } from './aliases.js';
6
6
  import { BYTES_PREFIX } from './hydrateColumn.js';
7
7
  import { jsonPath } from './jsonSql.js';
@@ -44,10 +44,17 @@ export const MYSQL_FEATURES = {
44
44
  layout: 'timingFirst',
45
45
  scope: 'schema',
46
46
  before: true,
47
+ deferrable: false,
47
48
  },
48
49
  };
49
50
  /** The one `JSON_TABLE` column an exploded array reads each element through, as a JSON document. */
50
51
  const ELEM_COLUMN = 'v';
52
+ /** `(3)` keeps milliseconds, where a bare `CURRENT_TIMESTAMP` has whole seconds; `UUID()` is a version 1. */
53
+ export const MYSQL_SQL_VALUES = {
54
+ ...ANSI_SQL_VALUES,
55
+ currentTimestamp: 'CURRENT_TIMESTAMP(3)',
56
+ uuid: 'UUID()',
57
+ };
51
58
  /** What MySQL and MariaDB share, their JSON functions above all: `JSON_LENGTH`, `JSON_CONTAINS`, `JSON_TABLE`, `JSON_SET`. */
52
59
  export class MysqlLikeSqlDialect extends AbstractSqlDialect {
53
60
  /** Every member of this family runs the same SQL, so a body written once serves them all. */
@@ -80,33 +87,39 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
80
87
  beginTransactionCommand = 'START TRANSACTION';
81
88
  isolationLevelStrategy = 'set-before';
82
89
  booleanLiteral = 'integer';
83
- /** `(3)` keeps milliseconds; a bare `CURRENT_TIMESTAMP` has whole seconds only. */
84
- currentTimestamp = 'CURRENT_TIMESTAMP(3)';
90
+ sqlValues = MYSQL_SQL_VALUES;
85
91
  // No `RETURNING` support, so multi-row insert IDs are inferred from the header - see the
86
92
  // `innodb_autoinc_lock_mode` caveat on `buildUpdateResult` in `util/sql.util.ts`.
87
93
  insertIdSource = 'firstId';
88
- /**
89
- * `INSERT ... ON DUPLICATE KEY UPDATE`, or `INSERT IGNORE` where there is nothing to assign. The
90
- * assignments bind after the insert, where a `?` reads them.
91
- */
92
- upsert(ctx, entity, conflictPaths, payload) {
94
+ /** `INSERT ... ON DUPLICATE KEY UPDATE`, the assignments bound after the insert, where a `?` reads them. */
95
+ upsert(ctx, entity, conflictPaths, payload, { update } = {}) {
93
96
  const meta = getMeta(entity);
94
- const alias = this.upsertNewRowAlias && this.escapeId(this.upsertNewRowAlias, true);
95
97
  const updateCtx = this.createContext();
96
- const update = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, (name) => alias ? `${alias}.${name}` : `VALUE(${name})`);
97
- const idReturning = this.insertedIdReturning(meta);
98
- const returning = idReturning && ` ${idReturning}`;
99
- if (update) {
100
- this.appendInsertValues(ctx, entity, payload);
101
- ctx.append(`${alias ? ` AS ${alias}` : ''} ON DUPLICATE KEY UPDATE ${update}${returning}`);
102
- ctx.pushValue(...updateCtx.values);
103
- return;
104
- }
98
+ const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
105
99
  const insertCtx = this.createContext();
106
100
  this.appendInsertValues(insertCtx, entity, payload);
107
- ctx.append(insertCtx.sql.replace(/^INSERT/, 'INSERT IGNORE'));
108
- ctx.append(returning);
109
- ctx.pushValue(...insertCtx.values);
101
+ const idReturning = this.insertedIdReturning(meta);
102
+ ctx.append(`${this.onDuplicateKey(insertCtx.sql, assignments)}${idReturning && ` ${idReturning}`}`);
103
+ ctx.pushValue(...insertCtx.values, ...updateCtx.values);
104
+ }
105
+ appendTriggerUpsert(ctx, meta, _conflictPaths, entries, assignments) {
106
+ const insert = this.buildFragment(ctx, (fragmentCtx) => this.appendTriggerInsert(fragmentCtx, meta, entries));
107
+ ctx.append(`${this.onDuplicateKey(insert, assignments)};`);
108
+ }
109
+ /**
110
+ * `insert` on a duplicate key: `ON DUPLICATE KEY UPDATE` with the new row named, or `INSERT IGNORE` where there
111
+ * is nothing to assign. MySQL matches on any unique key, not just the conflict paths, which it cannot name.
112
+ */
113
+ onDuplicateKey(insert, assignments) {
114
+ if (!assignments) {
115
+ return insert.replace(/^INSERT/, 'INSERT IGNORE');
116
+ }
117
+ const alias = this.upsertNewRowAlias && ` AS ${this.escapeId(this.upsertNewRowAlias, true)}`;
118
+ return `${insert}${alias ?? ''} ON DUPLICATE KEY UPDATE ${assignments}`;
119
+ }
120
+ /** The new row through the alias it is given, or `VALUE(col)` where the dialect has no such syntax. */
121
+ upsertIncoming(column) {
122
+ return this.upsertNewRowAlias ? `${this.escapeId(this.upsertNewRowAlias, true)}.${column}` : `VALUE(${column})`;
110
123
  }
111
124
  /**
112
125
  * The alias the inserted row is given after the values list, and read back by the assignments.
@@ -1,5 +1,5 @@
1
1
  import type { IndexType } from '../schema/types.js';
2
- import type { SqlDialectName } from '../type/index.js';
2
+ import type { SqlDialectName, SqlValues } from '../type/index.js';
3
3
  import { type DriverCapabilities, type EntityMeta, type FieldOptions, type JsonColumnType, type Query, type QueryContext, type QueryTextSearchOptions, type SqlDialectFeatures, type VectorDistance, type VectorMetric } from '../type/index.js';
4
4
  import type { DialectOptions } from './abstractDialect.js';
5
5
  import { AbstractSqlDialect, type RelationRows } from './abstractSqlDialect.js';
@@ -12,6 +12,7 @@ export type PgLikeDialectOptions = DialectOptions & {
12
12
  export declare const PG_VECTOR_METRICS: ReadonlyMap<VectorDistance, VectorMetric>;
13
13
  /** What the Postgres-wire engines have. */
14
14
  export declare const PG_FEATURES: SqlDialectFeatures;
15
+ export declare const PG_SQL_VALUES: SqlValues;
15
16
  /** What Postgres and CockroachDB share: JSONB, full-text search, pgvector's operators, and the upsert. */
16
17
  export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
17
18
  /** Every member of this family runs the same SQL, so a body written once serves them all. */
@@ -20,6 +21,9 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
20
21
  readonly driverCapabilities: DriverCapabilities;
21
22
  constructor(options?: PgLikeDialectOptions);
22
23
  readonly features: SqlDialectFeatures;
24
+ readonly sqlValues: SqlValues;
25
+ /** `USING MESSAGE`, so the text is taken as it is rather than as a format reading each `%`. */
26
+ protected refusal(message: string): string;
23
27
  readonly escapeIdChar = "\"";
24
28
  readonly autoIncrementSuffix: string;
25
29
  /**
@@ -2,7 +2,7 @@ import { QueryRaw, } from '../type/index.js';
2
2
  import { bytesToHex } from '../util/bytes.js';
3
3
  import { fulltextConfig, fulltextIndexOver, hasVectorNear, textSearchFields } from '../util/dialect.util.js';
4
4
  import { escapePgSqlLiteral, escapeSingleQuotes, PG_UTC } from '../util/sqlLiteral.js';
5
- import { AbstractSqlDialect } from './abstractSqlDialect.js';
5
+ import { ANSI_SQL_VALUES, AbstractSqlDialect } from './abstractSqlDialect.js';
6
6
  import { JSON_PULL_ALIAS, RELATION_ROW_ALIAS } from './aliases.js';
7
7
  import { BYTES_PREFIX } from './hydrateColumn.js';
8
8
  import { jsonSetTarget } from './jsonSql.js';
@@ -47,8 +47,10 @@ export const PG_FEATURES = {
47
47
  layout: 'timingFirst',
48
48
  scope: 'table',
49
49
  before: true,
50
+ deferrable: true,
50
51
  },
51
52
  };
53
+ export const PG_SQL_VALUES = { ...ANSI_SQL_VALUES, uuid: 'gen_random_uuid()' };
52
54
  /** What Postgres and CockroachDB share: JSONB, full-text search, pgvector's operators, and the upsert. */
53
55
  export class PgLikeSqlDialect extends AbstractSqlDialect {
54
56
  /** Every member of this family runs the same SQL, so a body written once serves them all. */
@@ -62,6 +64,11 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
62
64
  this.driverCapabilities = { nativeArrays: true, explicitJsonCast: false, ...options.driverCapabilities };
63
65
  }
64
66
  features = PG_FEATURES;
67
+ sqlValues = PG_SQL_VALUES;
68
+ /** `USING MESSAGE`, so the text is taken as it is rather than as a format reading each `%`. */
69
+ refusal(message) {
70
+ return `RAISE EXCEPTION USING MESSAGE = ${message};`;
71
+ }
65
72
  escapeIdChar = '"';
66
73
  // Shared default for both dialects. CockroachDB docs flag sequential PKs as a hotspotting risk
67
74
  // under heavy concurrent insert load (writes concentrate on one range); this default still beats
package/dist/index.d.ts CHANGED
@@ -7,6 +7,6 @@ export * from './type/index.js';
7
7
  export { withDeleted } from './util/filters.util.js';
8
8
  export type { HookContext } from './util/hook.util.js';
9
9
  export { DefaultLogger } from './util/logger.js';
10
- export { currentTimestamp, raw, refs } from './util/raw.js';
11
- export { deleteFrom, insertInto, updateTable } from './util/triggerWrite.js';
10
+ export { currentDate, currentTime, currentTimestamp, raw, refs, uuid, uuidv7 } from './util/raw.js';
11
+ export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
12
12
  export * from './util/uqlError.js';
package/dist/index.js CHANGED
@@ -6,6 +6,6 @@ export * from './querier/index.js';
6
6
  export * from './type/index.js';
7
7
  export { withDeleted } from './util/filters.util.js';
8
8
  export { DefaultLogger } from './util/logger.js';
9
- export { currentTimestamp, raw, refs } from './util/raw.js';
10
- export { deleteFrom, insertInto, updateTable } from './util/triggerWrite.js';
9
+ export { currentDate, currentTime, currentTimestamp, raw, refs, uuid, uuidv7 } from './util/raw.js';
10
+ export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
11
11
  export * from './util/uqlError.js';
@@ -1,7 +1,7 @@
1
1
  import { type RelationRows } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode } from '../dialect/jsonSql.js';
3
3
  import { MysqlLikeSqlDialect } from '../dialect/mysqlLikeSqlDialect.js';
4
- import type { FieldOptions, Query, QueryContext, SqlDialectFeatures, Type, VectorDistance, VectorMetric } from '../type/index.js';
4
+ import type { FieldOptions, Query, QueryContext, SqlDialectFeatures, SqlValues, Type, VectorDistance, VectorMetric } from '../type/index.js';
5
5
  export declare class MariaDialect extends MysqlLikeSqlDialect {
6
6
  readonly dialectName = "mariadb";
7
7
  readonly insertIdSource = "returning";
@@ -11,6 +11,8 @@ export declare class MariaDialect extends MysqlLikeSqlDialect {
11
11
  * to one table of a join.
12
12
  */
13
13
  readonly features: SqlDialectFeatures;
14
+ /** `UUID_v7()` is MariaDB 11.7+; an older server refuses it itself. */
15
+ readonly sqlValues: SqlValues;
14
16
  /**
15
17
  * A derived table here reads no column of the statement around it, so the aggregate reads the
16
18
  * related table itself, and orders and pages inside `JSON_ARRAYAGG`, which takes both.
@@ -1,6 +1,6 @@
1
1
  import { relationTermKey } from '../dialect/abstractSqlDialect.js';
2
2
  import { jsonPath } from '../dialect/jsonSql.js';
3
- import { MYSQL_FEATURES, MYSQL_ROW_LOCKS, MysqlLikeSqlDialect } from '../dialect/mysqlLikeSqlDialect.js';
3
+ import { MYSQL_FEATURES, MYSQL_ROW_LOCKS, MYSQL_SQL_VALUES, MysqlLikeSqlDialect, } from '../dialect/mysqlLikeSqlDialect.js';
4
4
  import { getMeta } from '../entity/index.js';
5
5
  import { columnFamily } from '../util/field.util.js';
6
6
  export class MariaDialect extends MysqlLikeSqlDialect {
@@ -20,6 +20,8 @@ export class MariaDialect extends MysqlLikeSqlDialect {
20
20
  indexIfNotExists: true,
21
21
  rowLocks: { ...MYSQL_ROW_LOCKS, of: false },
22
22
  };
23
+ /** `UUID_v7()` is MariaDB 11.7+; an older server refuses it itself. */
24
+ sqlValues = { ...MYSQL_SQL_VALUES, uuidv7: 'UUID_v7()' };
23
25
  /**
24
26
  * A derived table here reads no column of the statement around it, so the aggregate reads the
25
27
  * related table itself, and orders and pages inside `JSON_ARRAYAGG`, which takes both.
@@ -1,5 +1,4 @@
1
1
  export * from './columnBuilder.js';
2
- export * from './expressions.js';
3
2
  export * from './migrationBuilder.js';
4
3
  export * from './tableBuilder.js';
5
4
  export * from './types.js';