uql-orm 0.92.0 → 0.93.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) 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 +147 -64
  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/index.d.ts +1 -1
  22. package/dist/migrate/ddl/index.js +3 -3
  23. package/dist/migrate/ddl/mssqlTableDdl.d.ts +3 -1
  24. package/dist/migrate/ddl/mssqlTableDdl.js +4 -0
  25. package/dist/migrate/ddl/mysqlTableDdl.d.ts +1 -1
  26. package/dist/migrate/ddl/mysqlTableDdl.js +2 -2
  27. package/dist/migrate/ddl/pgTableDdl.d.ts +5 -1
  28. package/dist/migrate/ddl/pgTableDdl.js +13 -7
  29. package/dist/migrate/ddl/tableDdl.d.ts +9 -6
  30. package/dist/migrate/ddl/tableDdl.js +16 -7
  31. package/dist/migrate/ddl/tableRebuild.d.ts +2 -5
  32. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
  33. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +4 -5
  34. package/dist/migrate/introspection/mysqlIntrospector.js +4 -2
  35. package/dist/migrate/schemaChange.d.ts +2 -5
  36. package/dist/migrate/schemaGenerator.js +2 -2
  37. package/dist/migrate/storage/databaseStorage.js +2 -2
  38. package/dist/migrate/triggerSql.js +9 -2
  39. package/dist/mongo/mongoDialect.d.ts +0 -2
  40. package/dist/mongo/mongoDialect.js +18 -14
  41. package/dist/mongo/mongodbQuerier.d.ts +13 -5
  42. package/dist/mongo/mongodbQuerier.js +39 -5
  43. package/dist/mssql/mssqlDialect.d.ts +9 -4
  44. package/dist/mssql/mssqlDialect.js +18 -5
  45. package/dist/postgres/postgresDialect.d.ts +5 -2
  46. package/dist/postgres/postgresDialect.js +5 -5
  47. package/dist/querier/abstractQuerier.d.ts +5 -5
  48. package/dist/querier/abstractQuerier.js +19 -15
  49. package/dist/querier/abstractQuerierPool.js +22 -22
  50. package/dist/querier/abstractSqlQuerier.d.ts +3 -3
  51. package/dist/querier/abstractSqlQuerier.js +7 -7
  52. package/dist/schema/schemaASTBuilder.js +2 -16
  53. package/dist/schema/sqlExpression.d.ts +9 -3
  54. package/dist/schema/sqlExpression.js +14 -0
  55. package/dist/schema/types.d.ts +2 -5
  56. package/dist/sqlite/sqliteDialect.d.ts +5 -4
  57. package/dist/sqlite/sqliteDialect.js +12 -4
  58. package/dist/type/dialect.d.ts +29 -11
  59. package/dist/type/dialect.js +2 -0
  60. package/dist/type/entity.d.ts +20 -5
  61. package/dist/type/migration.d.ts +7 -8
  62. package/dist/type/query.d.ts +12 -1
  63. package/dist/type/universalQuerier.d.ts +3 -3
  64. package/dist/util/dialect.util.d.ts +1 -1
  65. package/dist/util/index.d.ts +1 -1
  66. package/dist/util/index.js +1 -1
  67. package/dist/util/raw.d.ts +13 -3
  68. package/dist/util/raw.js +29 -3
  69. package/dist/util/triggerWrite.d.ts +11 -1
  70. package/dist/util/triggerWrite.js +14 -0
  71. package/package.json +10 -10
  72. package/skills/uql-orm/SKILL.md +22 -52
  73. package/dist/migrate/builder/expressions.d.ts +0 -63
  74. 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,28 +1276,53 @@ 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]} `);
1288
- ctx.addValue(operand);
1313
+ ctx.append(`${escapedCol} = COALESCE(${current}, 0) ${SQL_ARITHMETIC[op]} `);
1314
+ if (operand instanceof QueryRaw) {
1315
+ ctx.append('(');
1316
+ this.getRawValue(ctx, { value: operand, escapedPrefix: qualifier });
1317
+ ctx.append(')');
1318
+ }
1319
+ else {
1320
+ ctx.addValue(operand);
1321
+ }
1322
+ }
1323
+ else if (value instanceof QueryRaw) {
1324
+ ctx.append(`${escapedCol} = `);
1325
+ this.getRawValue(ctx, { value, escapedPrefix: qualifier });
1289
1326
  }
1290
1327
  else {
1291
1328
  ctx.append(`${escapedCol} = `);
@@ -1298,27 +1335,36 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1298
1335
  * trigger has none of. `rows` are what a set-based engine's body reads, narrowed to the ones it fires for.
1299
1336
  */
1300
1337
  triggerWrite(ctx, write, rows) {
1338
+ if (write.kind === 'refuse') {
1339
+ ctx.append(this.refusal(this.escape(write.message), rows));
1340
+ return;
1341
+ }
1301
1342
  const meta = getMeta(write.entity);
1302
1343
  const table = this.escapedTableName(meta);
1303
- if (write.kind === 'insert') {
1344
+ if (write.kind === 'insert' || write.kind === 'upsert') {
1304
1345
  const unfilled = definedEntries(meta.fields).find(([key, field]) => field.onInsert !== undefined && field.defaultValue === undefined && write.row[key] === undefined);
1305
1346
  if (unfilled) {
1306
1347
  throw new UqlUsageError(`'${meta.name}.${unfilled[0]}' is filled on insert by uql, which a trigger does not run: ` +
1307
1348
  'name it, or give it a defaultValue');
1308
1349
  }
1309
1350
  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);
1351
+ if (write.kind === 'insert') {
1352
+ this.appendTriggerInsert(ctx, meta, entries, rows);
1353
+ ctx.append(';');
1354
+ return;
1355
+ }
1356
+ const { conflictPaths, update } = write;
1357
+ // What a conflicting row takes, none filled in JavaScript: the incoming row less the conflict paths, or `update`.
1358
+ const assigned = update === undefined
1359
+ ? entries
1360
+ .filter(([key]) => !conflictPaths[key])
1361
+ .map(([key]) => [key, this.incoming(meta, key)])
1362
+ : hasKeys(update)
1363
+ ? this.writtenEntries(meta, update)
1364
+ : [];
1365
+ this.refuseAccumulating(meta, assigned, rows);
1366
+ const assignments = this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, assigned, `${table}.`));
1367
+ this.appendTriggerUpsert(ctx, meta, conflictPaths, entries, assignments, rows);
1322
1368
  return;
1323
1369
  }
1324
1370
  assertWhere(meta, write.where);
@@ -1327,18 +1373,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1327
1373
  }
1328
1374
  if (write.kind === 'update') {
1329
1375
  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
- }
1376
+ this.refuseAccumulating(meta, entries, rows);
1335
1377
  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
- });
1378
+ this.appendAssignments(ctx, meta, entries);
1342
1379
  }
1343
1380
  else {
1344
1381
  ctx.append(`DELETE FROM ${table}`);
@@ -1352,6 +1389,47 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1352
1389
  this.renderWhere(ctx, write.entity, where, { escapedPrefix: `${table}.` });
1353
1390
  ctx.append(';');
1354
1391
  }
1392
+ /** `$inc`, `$mul` and `$push` refused where the body reads a set, which applies each once for the statement. */
1393
+ refuseAccumulating(meta, entries, rows) {
1394
+ const accumulating = rows && entries.find(([, value]) => accumulates(value));
1395
+ if (accumulating) {
1396
+ throw new UqlUsageError(`'${meta.name}.${accumulating[0]}' cannot accumulate per row in a trigger fired once per statement, ` +
1397
+ 'which applies $inc, $mul and $push once');
1398
+ }
1399
+ }
1400
+ /** A trigger's insert, unterminated: its values, or a `SELECT` of them off the set a set-based engine hands it. */
1401
+ appendTriggerInsert(ctx, meta, entries, rows) {
1402
+ const columns = entries.map(([key]) => this.escapedColumnName(meta, key)).join(', ');
1403
+ ctx.append(`INSERT INTO ${this.escapedTableName(meta)} (${columns}) ${rows ? 'SELECT ' : 'VALUES ('}`);
1404
+ this.appendTriggerValues(ctx, meta, entries);
1405
+ ctx.append(rows ? fromRows(rows) : ')');
1406
+ }
1407
+ /** The values a trigger writes, a literal or SQL each, the rows' refs most often. */
1408
+ appendTriggerValues(ctx, meta, entries) {
1409
+ entries.forEach(([key, value], i) => {
1410
+ if (i > 0) {
1411
+ ctx.append(', ');
1412
+ }
1413
+ this.formatPersistableValue(ctx, meta.fields[key], value);
1414
+ });
1415
+ }
1416
+ /** A trigger's upsert: its insert, then what a conflicting row takes, `assignments`, or nothing where empty. */
1417
+ appendTriggerUpsert(ctx, meta, conflictPaths, entries, assignments, rows) {
1418
+ this.appendTriggerInsert(ctx, meta, entries, rows);
1419
+ ctx.append(`${this.onConflict(meta, conflictPaths, assignments)};`);
1420
+ }
1421
+ /** ` ON CONFLICT (keys) DO UPDATE SET ...`, or `DO NOTHING` with nothing to assign. */
1422
+ onConflict(meta, conflictPaths, assignments) {
1423
+ const keys = this.getUpsertConflictPathsStr(meta, conflictPaths);
1424
+ return ` ON CONFLICT (${keys}) ${assignments ? `DO UPDATE SET ${assignments}` : 'DO NOTHING'}`;
1425
+ }
1426
+ /**
1427
+ * The statement failing a trigger's write with `message`, a quoted literal: SQL/PSM's `SIGNAL`, which the
1428
+ * MySQL family speaks. `rows` are what a set-based engine's body reads, where it fails only if there are any.
1429
+ */
1430
+ refusal(message, _rows) {
1431
+ return `SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = ${message};`;
1432
+ }
1355
1433
  /** The values a write names, refusing one the entity has no column for. */
1356
1434
  writtenEntries(meta, values) {
1357
1435
  const entries = Object.entries(values).filter(([, value]) => value !== undefined);
@@ -1368,43 +1446,48 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1368
1446
  * `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING`. The assignments are built before the insert
1369
1447
  * fills `onInsert` columns, which must stay out of them, and their values bound after it, where a `?` reads them.
1370
1448
  */
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 = '') {
1449
+ upsert(ctx, entity, conflictPaths, payload, { update } = {}) {
1374
1450
  const meta = getMeta(entity);
1375
1451
  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';
1452
+ const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
1379
1453
  // Composed rather than concatenated: a composite key contributes no id item, and a dialect's own
1380
1454
  // 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(', ');
1455
+ const returning = [this.returningIdExpression(meta), this.upsertCreatedReturning].filter(Boolean).join(', ');
1382
1456
  this.appendInsertValues(ctx, entity, payload);
1383
- ctx.append(` ON CONFLICT (${keys}) ${onConflict}${returning ? ` RETURNING ${returning}` : ''}`);
1457
+ ctx.append(`${this.onConflict(meta, conflictPaths, assignments)}${returning ? ` RETURNING ${returning}` : ''}`);
1384
1458
  if (updateCtx !== ctx) {
1385
1459
  ctx.pushValue(...updateCtx.values);
1386
1460
  }
1387
1461
  }
1462
+ /** One more `RETURNING` item saying whether the row was created, where the engine can tell; else empty. */
1463
+ upsertCreatedReturning = '';
1388
1464
  /** Whether the upsert's assignments bind straight into the statement, as numbered `$n` placeholders can. */
1389
1465
  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) {
1466
+ /** How an upsert's assignment reads `column` of the row that was being inserted. */
1467
+ upsertIncoming(column) {
1468
+ return `EXCLUDED.${column}`;
1469
+ }
1470
+ /** `key`'s column of the row being inserted, as SQL an assignment takes. */
1471
+ incoming(meta, key) {
1472
+ const column = this.escapedColumnName(meta, key);
1473
+ return raw(() => this.upsertIncoming(column));
1474
+ }
1475
+ /**
1476
+ * What a conflicting row takes: `update` where given, else the incoming row less the conflict paths, and what
1477
+ * `onUpdate` fills. An empty `update` leaves the row as it is, its fills included: nothing to assign.
1478
+ */
1479
+ getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, update) {
1393
1480
  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(', ');
1481
+ const [filled] = fillOnFields(meta, { ...sample }, 'onUpdate');
1482
+ const entries = update
1483
+ ? hasKeys(update)
1484
+ ? this.updateEntries(meta, update)
1485
+ : []
1486
+ : filterFieldKeys(meta, filled, 'onUpdate')
1487
+ .filter((key) => !conflictPaths[key])
1488
+ .map((key) => [key, Object.hasOwn(sample, key) ? this.incoming(meta, key) : filled[key]]);
1489
+ const qualifier = `${this.escapedTableName(meta)}.`;
1490
+ return this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, entries, qualifier));
1408
1491
  }
1409
1492
  getUpsertConflictPathsStr(meta, conflictPaths) {
1410
1493
  return getKeys(conflictPaths)
@@ -1569,11 +1652,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1569
1652
  * `"col" = <expr>` for a JSON update, each operator wrapping the last: `$pull`, `$set`, `$push`, `$unset`.
1570
1653
  * `$pull` reads the column and every later one its expression once, so no value binds twice.
1571
1654
  */
1572
- formatJsonUpdate(ctx, escapedCol, value, field) {
1655
+ formatJsonUpdate(ctx, escapedCol, value, field, current = escapedCol) {
1573
1656
  const { $pull, $set, $push, $unset } = value;
1574
- let expr = escapedCol;
1657
+ let expr = current;
1575
1658
  if (hasKeys($pull)) {
1576
- expr = this.jsonPull(ctx, expr, escapedCol, $pull);
1659
+ expr = this.jsonPull(ctx, expr, current, $pull);
1577
1660
  }
1578
1661
  if (hasKeys($set)) {
1579
1662
  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.