uql-orm 0.102.6 → 0.102.7

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 (94) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +3 -3
  4. package/dist/bunSql/bunSqlQuerier.d.ts +9 -3
  5. package/dist/bunSql/bunSqlQuerier.js +7 -15
  6. package/dist/d1/d1Querier.d.ts +18 -14
  7. package/dist/d1/d1Querier.js +21 -8
  8. package/dist/d1/d1SqliteDialect.d.ts +2 -0
  9. package/dist/d1/d1SqliteDialect.js +3 -0
  10. package/dist/dialect/abstractDialect.d.ts +3 -0
  11. package/dist/dialect/abstractDialect.js +6 -2
  12. package/dist/dialect/abstractSqlDialect.d.ts +24 -5
  13. package/dist/dialect/abstractSqlDialect.js +86 -57
  14. package/dist/dialect/mysqlLikeSqlDialect.js +6 -1
  15. package/dist/dialect/operators.d.ts +9 -3
  16. package/dist/dialect/operators.js +32 -9
  17. package/dist/dialect/vectorSqlDialect.js +2 -2
  18. package/dist/entity/metadata/definition.d.ts +11 -1
  19. package/dist/entity/metadata/definition.js +18 -0
  20. package/dist/mariadb/mariadbQuerier.d.ts +5 -2
  21. package/dist/mariadb/mariadbQuerier.js +5 -10
  22. package/dist/migrate/ddl/defaultSql.js +1 -1
  23. package/dist/migrate/ddl/indexDdl.d.ts +3 -3
  24. package/dist/migrate/ddl/indexDdl.js +7 -7
  25. package/dist/migrate/ddl/mysqlIndexDdl.js +2 -2
  26. package/dist/migrate/ddl/tableDdl.js +2 -2
  27. package/dist/migrate/indexPredicate.d.ts +4 -3
  28. package/dist/migrate/indexPredicate.js +5 -5
  29. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +2 -6
  30. package/dist/migrate/schemaGenerator.js +1 -1
  31. package/dist/migrate/triggerSql.js +7 -5
  32. package/dist/mongodb/mongoDialect.js +17 -41
  33. package/dist/mongodb/mongoSchemaGenerator.js +12 -12
  34. package/dist/mongodb/mongodbQuerier.d.ts +4 -3
  35. package/dist/mongodb/mongodbQuerier.js +75 -102
  36. package/dist/mssql/mssqlDialect.js +2 -7
  37. package/dist/mssql/mssqlQuerier.d.ts +9 -3
  38. package/dist/mssql/mssqlQuerier.js +9 -11
  39. package/dist/mysql/mysql2Querier.d.ts +11 -2
  40. package/dist/mysql/mysql2Querier.js +4 -7
  41. package/dist/neon/index.d.ts +2 -0
  42. package/dist/neon/index.js +2 -0
  43. package/dist/neon/neonDialect.d.ts +7 -0
  44. package/dist/neon/neonDialect.js +8 -0
  45. package/dist/neon/neonQuerier.d.ts +26 -0
  46. package/dist/neon/neonQuerier.js +47 -0
  47. package/dist/neon/neonQuerierPool.d.ts +12 -2
  48. package/dist/neon/neonQuerierPool.js +22 -3
  49. package/dist/pglite/pgliteQuerier.d.ts +9 -5
  50. package/dist/pglite/pgliteQuerier.js +7 -11
  51. package/dist/postgres/pgExecution.d.ts +8 -0
  52. package/dist/postgres/pgExecution.js +3 -0
  53. package/dist/postgres/pgQuerier.d.ts +3 -6
  54. package/dist/postgres/pgQuerier.js +3 -7
  55. package/dist/querier/abstractQuerier.d.ts +24 -20
  56. package/dist/querier/abstractQuerier.js +79 -58
  57. package/dist/querier/abstractSqlQuerier.d.ts +42 -28
  58. package/dist/querier/abstractSqlQuerier.js +134 -116
  59. package/dist/querier/queryError.d.ts +2 -0
  60. package/dist/querier/queryError.js +9 -0
  61. package/dist/querier/transaction.js +2 -6
  62. package/dist/schema/canonicalType.d.ts +3 -3
  63. package/dist/schema/canonicalType.js +4 -10
  64. package/dist/sqlite/bindValues.d.ts +10 -0
  65. package/dist/sqlite/bindValues.js +8 -0
  66. package/dist/sqlite/hranaQuerier.d.ts +17 -11
  67. package/dist/sqlite/hranaQuerier.js +16 -5
  68. package/dist/sqlite/index.d.ts +1 -1
  69. package/dist/sqlite/index.js +0 -1
  70. package/dist/sqlite/localSqliteQuerierPool.js +19 -9
  71. package/dist/sqlite/sqliteQuerier.d.ts +9 -4
  72. package/dist/sqlite/sqliteQuerier.js +14 -8
  73. package/dist/turso/tursoSessionQuerier.d.ts +19 -7
  74. package/dist/turso/tursoSessionQuerier.js +31 -20
  75. package/dist/type/dialect.d.ts +3 -0
  76. package/dist/type/querier.d.ts +12 -0
  77. package/dist/type/querier.js +10 -0
  78. package/dist/type/vector.d.ts +2 -1
  79. package/dist/type/vector.js +2 -2
  80. package/dist/util/dialect.util.d.ts +21 -6
  81. package/dist/util/dialect.util.js +34 -9
  82. package/dist/util/filters.util.d.ts +5 -4
  83. package/dist/util/filters.util.js +4 -7
  84. package/dist/util/logger.js +2 -6
  85. package/dist/util/object.util.d.ts +7 -0
  86. package/dist/util/object.util.js +17 -0
  87. package/dist/util/query.util.d.ts +3 -2
  88. package/dist/util/sql.js +1 -1
  89. package/dist/util/sql.util.d.ts +15 -15
  90. package/dist/util/sql.util.js +5 -5
  91. package/package.json +5 -5
  92. package/skills/uql-orm/SKILL.md +4 -2
  93. package/dist/sqlite/abstractSqliteQuerier.d.ts +0 -28
  94. package/dist/sqlite/abstractSqliteQuerier.js +0 -36
@@ -1,14 +1,15 @@
1
1
  import { fieldOf, getMeta, relationOf } from '../entity/index.js';
2
+ import { soleId, valueFieldOf } from '../entity/metadata/definition.js';
2
3
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, RAW_ALIAS, } from '../type/index.js';
3
4
  import { utcTimestamp } from '../util/date.js';
4
5
  import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
5
- import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
6
- import { isJsonScalar } from '../util/object.util.js';
6
+ import { isAutoIncrement, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, upsertAssigned, } from '../util/index.js';
7
+ import { cachedIn, isJsonScalar } from '../util/object.util.js';
7
8
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
8
9
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
9
10
  import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
10
11
  import { holdsOperator, chainedCall, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, unlessThen, } from './jsonSql.js';
11
- import { betweenBounds, COMPARE_OPS, EQUALITY_OPS, GROUP_OPS, groupClauses, inOperands, isGroupOp, isOrderedOp, isVectorQuery, LIKE_OPS, namesRows, ORDERED_OPS, VECTOR_QUERY_KEY_SET, whereOperators, } from './operators.js';
12
+ import { betweenBounds, EQUALITY_OPS, GROUP_OPS, groupClauses, inOperands, isGroupOp, isOrderedOp, isVectorQuery, LIKE_OPS, namesRows, ORDERED_OPS, ORDERED_SYMBOLS, sizeComparisons, VECTOR_QUERY_KEY_SET, whereOperators, } from './operators.js';
12
13
  import { SqlQueryContext } from './queryContext.js';
13
14
  import { groupPathField, NO_JOINS, aggregateColumnField, resolveGroupJoins, resolveQueryJoins, relationSortTerms, resolveSortableJoin, } from './queryJoins.js';
14
15
  import { resolveVectorCast } from './vectorCast.js';
@@ -307,7 +308,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
307
308
  * than inheriting another engine's syntax.
308
309
  */
309
310
  appendTextSearch(_ctx, _meta, _search, _prefix) {
310
- throw new UqlUsageError(`${this.dialectName} does not support $text full-text search`);
311
+ throw new UqlUsageError(`${this.engineName} does not support $text full-text search`);
311
312
  }
312
313
  /**
313
314
  * A row's relevance to a `$text` search, what `$sort: { $text }` orders by. Where the fulltext index
@@ -338,7 +339,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
338
339
  * searches scores too, so a dialect overrides this beside {@link appendTextSearch}.
339
340
  */
340
341
  appendTextScore(_ctx, _meta, _search, _keys, _prefix) {
341
- throw new UqlUsageError(`${this.dialectName} does not support $text full-text search`);
342
+ throw new UqlUsageError(`${this.engineName} does not support $text full-text search`);
342
343
  }
343
344
  /** The columns a `$text` over `keys` reads, qualified by `prefix` where the statement joins, as any column is. */
344
345
  textColumns(meta, keys, prefix) {
@@ -669,28 +670,24 @@ export class AbstractSqlDialect extends VectorSqlDialect {
669
670
  * engine compares it: `<>`, `NOT IN` and `NOT` are unknown on a NULL, which SQL drops.
670
671
  */
671
672
  operatorCondition(ctx, operand, op, val, bind = (value) => this.addValue(ctx, value)) {
672
- const compareOp = COMPARE_OPS.get(op);
673
- if (compareOp) {
674
- return `${operand}${compareOp}${bind(val)}`;
675
- }
676
673
  const like = this.likeCondition(ctx, operand, op, val);
677
674
  if (like) {
678
675
  return like;
679
676
  }
680
677
  switch (op) {
681
678
  case '$eq':
682
- return val === null ? `${operand} IS NULL` : `${operand} = ${bind(val)}`;
683
679
  case '$ne':
684
- return val === null ? `${operand} IS NOT NULL` : `${operand} <> ${bind(val)}`;
680
+ case '$gt':
681
+ case '$gte':
682
+ case '$lt':
683
+ case '$lte':
684
+ case '$between':
685
+ return this.comparisonCondition(operand, op, val, bind);
685
686
  case '$regex':
686
687
  return this.regexCondition(operand, this.addValue(ctx, val));
687
688
  case '$in':
688
689
  case '$nin':
689
690
  return this.formatIn(ctx, operand, inOperands(op, val), op === '$nin', bind);
690
- case '$between': {
691
- const [min, max] = betweenBounds(val);
692
- return `${operand} BETWEEN ${bind(min)} AND ${bind(max)}`;
693
- }
694
691
  case '$isNull':
695
692
  return operand + (val ? ' IS NULL' : ' IS NOT NULL');
696
693
  case '$isNotNull':
@@ -699,6 +696,21 @@ export class AbstractSqlDialect extends VectorSqlDialect {
699
696
  return undefined;
700
697
  }
701
698
  }
699
+ /** `<operand> <op> <value>` for a comparison a number takes: an equality, an ordered one or `$between`. */
700
+ comparisonCondition(operand, op, val, bind) {
701
+ switch (op) {
702
+ case '$eq':
703
+ return val === null ? `${operand} IS NULL` : `${operand} = ${bind(val)}`;
704
+ case '$ne':
705
+ return val === null ? `${operand} IS NOT NULL` : `${operand} <> ${bind(val)}`;
706
+ case '$between': {
707
+ const [min, max] = betweenBounds(val);
708
+ return `${operand} BETWEEN ${bind(min)} AND ${bind(max)}`;
709
+ }
710
+ default:
711
+ return `${operand} ${ORDERED_SYMBOLS[op]} ${bind(val)}`;
712
+ }
713
+ }
702
714
  /** `$all`, `$size` and `$elemMatch`, which read the JSON array at `slot`; `undefined` for the rest. */
703
715
  jsonArrayCondition(ctx, slot, op, val) {
704
716
  switch (op) {
@@ -988,7 +1000,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
988
1000
  }
989
1001
  joins ??= resolveQueryJoins(getMeta(entity), q);
990
1002
  if (joins.size > 0) {
991
- throw new UqlUsageError(`${this.dialectName} cannot narrow a row lock to one table, so $lock cannot be combined with a joined relation`);
1003
+ throw new UqlUsageError(`${this.engineName} cannot narrow a row lock to one table, so $lock cannot be combined with a joined relation`);
992
1004
  }
993
1005
  }
994
1006
  /**
@@ -1057,7 +1069,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1057
1069
  * caller reached for this to avoid, and only say so by taking a long time.
1058
1070
  */
1059
1071
  estimatedCount(_ctx, _entity) {
1060
- throw new UqlUsageError(`${this.dialectName} does not support estimatedCount`);
1072
+ throw new UqlUsageError(`${this.engineName} does not support estimatedCount`);
1061
1073
  }
1062
1074
  aggregate(ctx, entity, q, opts = {}) {
1063
1075
  const meta = getMeta(entity);
@@ -1513,11 +1525,28 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1513
1525
  ctx.pushValue(...updateCtx.values);
1514
1526
  }
1515
1527
  }
1516
- /** What an upsert's assignments bind once per statement beside its rows, which all assign as `row` does. */
1517
- upsertAssignmentBinds(entity, conflictPaths, row, update) {
1528
+ /**
1529
+ * What an upsert of rows shaped as `row` assigns a row it finds: the values its assignments bind once per
1530
+ * statement beside its rows, and whether there are any, where none is `DO NOTHING`, which skips that row.
1531
+ */
1532
+ upsertAssignments(entity, conflictPaths, row, update) {
1518
1533
  const ctx = this.createContext();
1519
- this.getUpsertUpdateAssignments(ctx, getMeta(entity), conflictPaths, row, update);
1520
- return ctx.values.length;
1534
+ const assignments = this.getUpsertUpdateAssignments(ctx, getMeta(entity), conflictPaths, row, update);
1535
+ return { binds: ctx.values.length, assigns: assignments !== '' };
1536
+ }
1537
+ /**
1538
+ * Whether an upsert of `rows` rows that assigns a found row something reports each row's sole key in order, so
1539
+ * nothing reads them back: `RETURNING`, in order on an engine answering so, and for one row on any; the header,
1540
+ * for one row's generated key, a found row's too, since the upsert assigns it through `LAST_INSERT_ID`.
1541
+ */
1542
+ upsertReportsIds(meta, rows) {
1543
+ const id = soleId(meta);
1544
+ if (!id) {
1545
+ return false;
1546
+ }
1547
+ return this.insertIdSource === 'returning'
1548
+ ? rows === 1 || this.features.orderedUpsertReturning
1549
+ : rows === 1 && isAutoIncrement(id.field, true);
1521
1550
  }
1522
1551
  /** Whether the upsert's assignments bind straight into the statement, as numbered `$n` placeholders can. */
1523
1552
  upsertUpdateBindsInPlace = false;
@@ -1535,18 +1564,19 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1535
1564
  * `onUpdate` fills. An empty `update` leaves the row as it is, its fills included: nothing to assign.
1536
1565
  */
1537
1566
  getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, update) {
1538
- const sample = Array.isArray(payload) ? payload[0] : payload;
1539
- const [filled] = fillOnFields(meta, { ...sample }, 'onUpdate');
1540
1567
  const entries = update
1541
1568
  ? hasKeys(update)
1542
1569
  ? this.updateEntries(meta, update)
1543
1570
  : []
1544
- : filterFieldKeys(meta, filled, 'onUpdate')
1545
- .filter((key) => !conflictPaths[key])
1546
- .map((key) => [key, Object.hasOwn(sample, key) ? this.incoming(meta, key) : filled[key]]);
1571
+ : this.conflictEntries(meta, conflictPaths, Array.isArray(payload) ? payload[0] : payload);
1547
1572
  const qualifier = `${this.escapedTableName(meta)}.`;
1548
1573
  return this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, entries, qualifier));
1549
1574
  }
1575
+ /** What a found row takes by default: each payload column as the incoming row has it, and the `onUpdate` fills. */
1576
+ conflictEntries(meta, conflictPaths, row) {
1577
+ const always = upsertAssigned(meta, row, conflictPaths);
1578
+ return getKeys(always).map((key) => [key, Object.hasOwn(row, key) ? this.incoming(meta, key) : always[key]]);
1579
+ }
1550
1580
  getUpsertConflictPathsStr(meta, conflictPaths) {
1551
1581
  return getKeys(conflictPaths)
1552
1582
  .map((key) => this.escapedColumnName(meta, key))
@@ -1555,18 +1585,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1555
1585
  delete(ctx, entity, q, opts = {}) {
1556
1586
  const meta = getMeta(entity);
1557
1587
  const tableName = this.escapedTableName(meta);
1558
- // Soft-delete (stamp only live rows) unless `hardDelete` is requested or the entity has no
1559
- // soft-delete field (e.g. a cascade onto a non-soft-deletable child).
1560
- if (!opts.hardDelete && meta.softDelete) {
1588
+ const { stamp, opts: read } = deletionOf(meta, opts);
1589
+ if (stamp) {
1561
1590
  ctx.append(`UPDATE ${tableName} SET `);
1562
- this.appendAssignment(ctx, meta, meta.softDelete, getSoftDeleteValue(fieldOf(meta, meta.softDelete)));
1563
- this.search(ctx, entity, q, opts);
1564
- return;
1591
+ this.appendAssignment(ctx, meta, stamp.key, stamp.value());
1592
+ }
1593
+ else {
1594
+ ctx.append(`DELETE FROM ${tableName}`);
1565
1595
  }
1566
- // Hard delete removes matching rows regardless of soft-delete state (keeps other filters, e.g. tenant).
1567
- // Only rewrite the filters when there is a soft-delete filter to disable.
1568
- ctx.append(`DELETE FROM ${tableName}`);
1569
- this.search(ctx, entity, q, meta.softDelete ? { ...opts, filters: withoutSoftDeleteFilter(opts.filters) } : opts);
1596
+ this.search(ctx, entity, q, read);
1570
1597
  }
1571
1598
  escapeId(val, forbidQualified, addDot) {
1572
1599
  return escapeSqlId(val, this.escapeIdChar, forbidQualified, addDot);
@@ -1628,13 +1655,17 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1628
1655
  const target = getMeta(relationOf(meta, spec.relation).entity());
1629
1656
  return this.aggregateKind(spec.op, spec.field ? this.fieldKind(target, target.fields[spec.field], true) : undefined);
1630
1657
  }
1631
- /** What one column decodes as, the inverse of {@link persistKind}. `BigInt` first, since it shares the numeric family. */
1658
+ /**
1659
+ * What one column decodes as, the inverse of {@link persistKind}: a foreign key typed by its reference as its
1660
+ * key does. `BigInt` first, since it shares the numeric family.
1661
+ */
1632
1662
  hydrateKind(field) {
1633
- const type = field?.type;
1663
+ const valued = field && valueFieldOf(field);
1664
+ const type = valued?.type;
1634
1665
  if (type === BigInt) {
1635
1666
  return 'bigint';
1636
1667
  }
1637
- if (field && isExactDecimal(field)) {
1668
+ if (valued && isExactDecimal(valued)) {
1638
1669
  return 'decimal';
1639
1670
  }
1640
1671
  switch (columnFamily(type)) {
@@ -1845,12 +1876,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1845
1876
  if (!field) {
1846
1877
  return this.escapeId(this.resolveColumnName(key, field));
1847
1878
  }
1848
- let escaped = this.escapedColumns.get(field);
1849
- if (escaped === undefined) {
1850
- escaped = this.escapeId(this.resolveColumnName(key, field));
1851
- this.escapedColumns.set(field, escaped);
1852
- }
1853
- return escaped;
1879
+ return cachedIn(this.escapedColumns, field, () => this.escapeId(this.resolveColumnName(key, field)));
1854
1880
  }
1855
1881
  escapedColumnName(meta, key) {
1856
1882
  return this.escapedColumnOf(key, meta.fields[key]);
@@ -2123,27 +2149,24 @@ export class AbstractSqlDialect extends VectorSqlDialect {
2123
2149
  }
2124
2150
  /**
2125
2151
  * `<expr> <op> <value>` for each bound, `AND`-joined. `expr` is spelled once per bound because it is an
2126
- * expression, not a column: a `WHERE` has no output alias to refer back to. Shared by `$size`, which
2127
- * counts, and `$near`, which measures a distance.
2152
+ * expression, not a column: a `WHERE` has no output alias to refer back to. A count for `$size`, a
2153
+ * distance for `$near`.
2128
2154
  */
2129
- boundConditions(ctx, expr, bounds, condition, refusal) {
2130
- const parts = Object.entries(bounds)
2131
- .filter(([, val]) => val !== undefined)
2132
- .map(([op, val]) => orRefuse(condition(this.buildFragment(ctx, expr), op, val), `${refusal}: ${op}`));
2133
- return conjunction(parts);
2155
+ boundConditions(ctx, expr, bounds) {
2156
+ const bind = (value) => this.addValue(ctx, value);
2157
+ return conjunction(bounds.map(([op, val]) => this.comparisonCondition(this.buildFragment(ctx, expr), op, val, bind)));
2134
2158
  }
2135
2159
  /** A count compared with `size`, a number or its bounds. */
2136
2160
  sizeCondition(ctx, count, size) {
2137
- const bounds = typeof size === 'number' ? { $eq: size } : size;
2138
- return this.boundConditions(ctx, count, bounds, (operand, op, val) => op === '$eq' || op === '$ne' || isOrderedOp(op) ? this.operatorCondition(ctx, operand, op, val) : undefined, 'unsupported $size comparison operator');
2161
+ return this.boundConditions(ctx, count, sizeComparisons(size));
2139
2162
  }
2140
2163
  /** `<distance> <op> ?`, the `$where` half of a vector search, its bounds checked here since `/http` input is untyped. */
2141
2164
  vectorNearCondition(ctx, meta, key, near, prefix) {
2142
2165
  if (!isOperatorMap(near)) {
2143
2166
  throw new UqlUsageError(`$near on '${key}' expects an object of its $vector and bounds, got ${kindOf(near)}`);
2144
2167
  }
2145
- const bounds = Object.fromEntries(Object.entries(near).filter(([op, val]) => !VECTOR_QUERY_KEY_SET.has(op) && val !== undefined));
2146
- if (!hasKeys(bounds)) {
2168
+ const bounds = Object.entries(near).filter(([op, val]) => !VECTOR_QUERY_KEY_SET.has(op) && val !== undefined);
2169
+ if (!bounds.length) {
2147
2170
  const boundOps = [...ORDERED_OPS].join(', ');
2148
2171
  throw new UqlUsageError(`$near on '${key}' needs a bound (${boundOps}); without one it filters nothing`);
2149
2172
  }
@@ -2154,7 +2177,13 @@ export class AbstractSqlDialect extends VectorSqlDialect {
2154
2177
  throw new UqlUsageError(`$near on '${key}' needs its own $vector`);
2155
2178
  }
2156
2179
  const distance = (fragmentCtx) => this.appendVectorDistance(fragmentCtx, meta, key, near, prefix);
2157
- return this.boundConditions(ctx, distance, bounds, (operand, op, val) => (isOrderedOp(op) ? this.operatorCondition(ctx, operand, op, val) : undefined), 'unsupported $near bound');
2180
+ const comparisons = bounds.map(([op, val]) => {
2181
+ if (!isOrderedOp(op)) {
2182
+ throw new UqlUsageError(`unsupported $near bound: ${op}`);
2183
+ }
2184
+ return [op, val];
2185
+ });
2186
+ return this.boundConditions(ctx, distance, comparisons);
2158
2187
  }
2159
2188
  /** ANSI-style single-quote escaping. */
2160
2189
  escape(value) {
@@ -106,7 +106,12 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
106
106
  const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
107
107
  const insert = this.buildFragment(ctx, (fragment) => this.appendInsertValues(fragment, entity, payload));
108
108
  const idReturning = this.insertedIdReturning(meta);
109
- ctx.append(`${this.onDuplicateKey(insert, assignments)}${idReturning && ` ${idReturning}`}`);
109
+ const rows = Array.isArray(payload) ? payload.length : 1;
110
+ const headerId = assignments && this.insertIdSource === 'firstId' && this.upsertReportsIds(meta, rows);
111
+ // Qualified: where the rows name the key, the new row's alias carries a column of the same name.
112
+ const key = headerId ? `${this.escapedTableName(meta)}.${this.escapedColumnName(meta, meta.ids[0])}` : '';
113
+ const assigned = key ? `${key} = LAST_INSERT_ID(${key}), ${assignments}` : assignments;
114
+ ctx.append(`${this.onDuplicateKey(insert, assigned)}${idReturning && ` ${idReturning}`}`);
110
115
  ctx.pushValue(...updateCtx.values);
111
116
  }
112
117
  appendTriggerUpsert(ctx, meta, _conflictPaths, entries, assignments) {
@@ -1,4 +1,4 @@
1
- import { type QueryGroupOp, type QueryOrderedOp, type QueryVectorQuery, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp } from '../type/index.js';
1
+ import { type QueryCompareOp, type QueryGroupOp, type QueryOrderedOp, type QuerySizeComparisonOps, type QueryVectorQuery, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp } from '../type/index.js';
2
2
  /**
3
3
  * How each grouping operator renders: the operator joining its clauses, and whether the group is
4
4
  * negated (`$not` is `NOT (a AND b)`). Total over {@link QueryGroupOp}.
@@ -50,14 +50,20 @@ export type LikeOp = {
50
50
  readonly pattern: (value: string) => string;
51
51
  readonly insensitive: boolean;
52
52
  };
53
- export declare const COMPARE_OPS: ReadonlyMap<QueryWhereFieldOp, string>;
53
+ /** Each ordered comparison as SQL spells it, the one source of its spelling. */
54
+ export declare const ORDERED_SYMBOLS: Readonly<Record<QueryCompareOp, string>>;
54
55
  /**
55
- * The ordered comparisons, `QueryOrderedOp` at runtime, derived from {@link COMPARE_OPS} rather than spelled
56
+ * The ordered comparisons, `QueryOrderedOp` at runtime, derived from {@link ORDERED_SYMBOLS} rather than spelled
56
57
  * again: {@link QueryVectorNear}'s bounds, so `$near` never accepts one the renderer has no operator
57
58
  * for, and the operators that read a JSON path as a number.
58
59
  */
59
60
  export declare const ORDERED_OPS: ReadonlySet<string>;
60
61
  export declare function isOrderedOp(op: string): op is QueryOrderedOp;
62
+ /**
63
+ * A `$size` operand as the comparisons of a length it makes, the same on every engine: a number is `$eq`, a
64
+ * map each of `$eq`, `$ne`, an ordered comparison or `$between`, at least one. Anything else is refused.
65
+ */
66
+ export declare function sizeComparisons(size: unknown): [keyof QuerySizeComparisonOps, unknown][];
61
67
  /** The operators an equality compares by value, which a JSON path reads the way that value compares. */
62
68
  export declare const EQUALITY_OPS: ReadonlySet<string>;
63
69
  /**
@@ -1,6 +1,6 @@
1
1
  import { QuerySql, VECTOR_QUERY_KEYS, } from '../type/index.js';
2
2
  import { isOperatorMap } from '../util/dialect.util.js';
3
- import { hasKeys, isWhereMap, someKey } from '../util/object.util.js';
3
+ import { getKeys, hasKeys, isWhereMap, someKey } from '../util/object.util.js';
4
4
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
5
5
  /**
6
6
  * How each grouping operator renders: the operator joining its clauses, and whether the group is
@@ -104,21 +104,44 @@ function isFieldOp(op) {
104
104
  export function isVectorQuery(near) {
105
105
  return Boolean(near['$vector']);
106
106
  }
107
- export const COMPARE_OPS = new Map([
108
- ['$gt', ' > '],
109
- ['$gte', ' >= '],
110
- ['$lt', ' < '],
111
- ['$lte', ' <= '],
112
- ]);
107
+ /** Each ordered comparison as SQL spells it, the one source of its spelling. */
108
+ export const ORDERED_SYMBOLS = {
109
+ $gt: '>',
110
+ $gte: '>=',
111
+ $lt: '<',
112
+ $lte: '<=',
113
+ };
113
114
  /**
114
- * The ordered comparisons, `QueryOrderedOp` at runtime, derived from {@link COMPARE_OPS} rather than spelled
115
+ * The ordered comparisons, `QueryOrderedOp` at runtime, derived from {@link ORDERED_SYMBOLS} rather than spelled
115
116
  * again: {@link QueryVectorNear}'s bounds, so `$near` never accepts one the renderer has no operator
116
117
  * for, and the operators that read a JSON path as a number.
117
118
  */
118
- export const ORDERED_OPS = new Set([...COMPARE_OPS.keys(), '$between']);
119
+ export const ORDERED_OPS = new Set([...getKeys(ORDERED_SYMBOLS), '$between']);
119
120
  export function isOrderedOp(op) {
120
121
  return ORDERED_OPS.has(op);
121
122
  }
123
+ /**
124
+ * A `$size` operand as the comparisons of a length it makes, the same on every engine: a number is `$eq`, a
125
+ * map each of `$eq`, `$ne`, an ordered comparison or `$between`, at least one. Anything else is refused.
126
+ */
127
+ export function sizeComparisons(size) {
128
+ if (typeof size === 'number') {
129
+ return [['$eq', size]];
130
+ }
131
+ if (!isOperatorMap(size)) {
132
+ throw new UqlUsageError(`$size expects a number or bounds, got ${kindOf(size)}`);
133
+ }
134
+ const comparisons = Object.entries(size).filter(([, bound]) => bound !== undefined);
135
+ if (!comparisons.length) {
136
+ throw new UqlUsageError('$size needs at least one comparison');
137
+ }
138
+ return comparisons.map(([op, bound]) => {
139
+ if (op !== '$eq' && op !== '$ne' && !isOrderedOp(op)) {
140
+ throw new UqlUsageError(`unsupported $size comparison operator: ${op}`);
141
+ }
142
+ return [op, bound];
143
+ });
144
+ }
122
145
  /** The operators an equality compares by value, which a JSON path reads the way that value compares. */
123
146
  export const EQUALITY_OPS = new Set(['$eq', '$ne', '$in', '$nin']);
124
147
  /**
@@ -75,12 +75,12 @@ export class VectorSqlDialect extends AbstractDialect {
75
75
  */
76
76
  appendVectorDistance(ctx, meta, key, search, prefix) {
77
77
  if (this.vectorMetrics.size === 0) {
78
- throw new UqlUsageError(`${this.dialectName} does not support vector similarity search. Use sql() for vector queries.`);
78
+ throw new UqlUsageError(`${this.engineName} does not support vector similarity search. Use sql() for vector queries.`);
79
79
  }
80
80
  const { colName, distance, field } = this.resolveVectorDistance(meta, key, search);
81
81
  const metric = this.vectorMetrics.get(distance);
82
82
  if (!metric) {
83
- throw unsupportedVectorMetric(this.dialectName, distance);
83
+ throw unsupportedVectorMetric(this.engineName, distance);
84
84
  }
85
85
  const column = this.escapeId(prefix, true, true) + this.escapeId(colName);
86
86
  if ('fn' in metric) {
@@ -1,4 +1,4 @@
1
- import type { EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldMeta, FieldOptions, FilterName, FilterOptions, HookEvent, IdKey, KeyMap, RelationKey, RelationMeta, RelationOptions, RelationRegistration, TriggerOptions, Type, WrittenId } from '../../type/index.js';
1
+ import type { EntityGetter, EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldMeta, FieldOptions, FilterName, FilterOptions, HookEvent, IdKey, KeyMap, RelationKey, RelationMeta, RelationOptions, RelationRegistration, TriggerOptions, Type, WrittenId } from '../../type/index.js';
2
2
  export declare function defineField<E>(entity: Type<E>, key: string, opts?: FieldOptions): EntityMeta<E>;
3
3
  export declare function defineId<E>(entity: Type<E>, key: string, opts: FieldOptions): EntityMeta<E>;
4
4
  /** `T` is the relation's target, independent of the owner `E`. */
@@ -45,8 +45,18 @@ export declare function defineEntity<E>(entity: Type<E>, opts?: EntityOptions<E>
45
45
  export declare function assertSoleId<E>(meta: EntityMeta<E>, what: string): void;
46
46
  /** The entity's one primary key, for a path that cannot express a composite. See {@link assertSoleId}. */
47
47
  export declare function soleIdOf<E>(meta: EntityMeta<E>, what: string): IdKey<E>;
48
+ /** The one key column and its field, or nothing on a composite key. */
49
+ export declare function soleId<E>(meta: EntityMeta<E>): {
50
+ readonly key: IdKey<E>;
51
+ readonly field: FieldMeta;
52
+ } | undefined;
48
53
  /** The field `key` names, for a caller that took `key` from the metadata itself. */
49
54
  export declare function fieldOf<E>(meta: EntityMeta<E>, key: string): FieldMeta;
55
+ /**
56
+ * The field whose type `field`'s values take: the key it references where it gave `references` and neither a
57
+ * `type` nor a `columnType`, followed down a chain of them; `field` itself otherwise.
58
+ */
59
+ export declare function valueFieldOf(field: FieldMeta, seen?: Set<EntityGetter>): FieldMeta;
50
60
  /** The relation `key` names, for a caller that took `key` from the metadata itself. */
51
61
  export declare function relationOf<E>(meta: EntityMeta<E>, key: RelationKey<E>): RelationMeta;
52
62
  /** A row of `E` as far as reading its key goes: a record or a write, whatever its values. */
@@ -276,6 +276,12 @@ export function soleIdOf(meta, what) {
276
276
  assertSoleId(meta, what);
277
277
  return meta.ids[0];
278
278
  }
279
+ /** The one key column and its field, or nothing on a composite key. */
280
+ export function soleId(meta) {
281
+ const [key] = meta.ids;
282
+ const field = meta.ids.length === 1 ? meta.fields[key] : undefined;
283
+ return field && { key, field };
284
+ }
279
285
  /** The field `key` names, for a caller that took `key` from the metadata itself. */
280
286
  export function fieldOf(meta, key) {
281
287
  const field = meta.fields[key];
@@ -284,6 +290,18 @@ export function fieldOf(meta, key) {
284
290
  }
285
291
  return field;
286
292
  }
293
+ /**
294
+ * The field whose type `field`'s values take: the key it references where it gave `references` and neither a
295
+ * `type` nor a `columnType`, followed down a chain of them; `field` itself otherwise.
296
+ */
297
+ export function valueFieldOf(field, seen) {
298
+ if (field.columnType || !field.typeFromReference || !field.references || seen?.has(field.references)) {
299
+ return field;
300
+ }
301
+ seen = (seen ?? new Set()).add(field.references);
302
+ const target = getMeta(field.references());
303
+ return valueFieldOf(fieldOf(target, soleIdOf(target, 'a foreign key')), seen);
304
+ }
287
305
  /** The relation `key` names, for a caller that took `key` from the metadata itself. */
288
306
  export function relationOf(meta, key) {
289
307
  const relation = meta.relations[key];
@@ -2,8 +2,11 @@ import type { PoolConnection } from 'mariadb';
2
2
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
3
  import type { RawRow } from '../type/index.js';
4
4
  export declare class MariadbQuerier extends AbstractPoolQuerier<PoolConnection> {
5
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
6
- internalRun(query: string, values?: unknown[]): Promise<import("../type/query.js").QueryUpdateResult>;
5
+ /** A read, or a `RETURNING` write, answers rows, counted by them; any other write an OK packet reporting `affectedRows`. */
6
+ protected execute(sql: string, values?: unknown[]): Promise<{
7
+ rows: RawRow[];
8
+ changes: any;
9
+ }>;
7
10
  /**
8
11
  * Closed through the driver's own `close`, which `Readable` does not type: a loop leaving early only destroys
9
12
  * the stream, which leaves the socket paused mid-result and the connection hung for its next statement.
@@ -7,16 +7,11 @@ function toBindValues(values) {
7
7
  : value);
8
8
  }
9
9
  export class MariadbQuerier extends AbstractPoolQuerier {
10
- async internalAll(query, values) {
11
- const rows = await this.getConn().query(query, toBindValues(values));
12
- return Array.from(rows, decodeBigInts);
13
- }
14
- async internalRun(query, values) {
15
- const res = await this.getConn().query(query, toBindValues(values));
16
- // An OK packet reports `affectedRows`; a `RETURNING` statement answers rows instead, and counts by them.
17
- const changes = res.affectedRows ?? res.length;
18
- const rows = res.length ? Array.from(res, decodeBigInts) : [];
19
- return this.buildUpdateResult({ rows, changes });
10
+ /** A read, or a `RETURNING` write, answers rows, counted by them; any other write an OK packet reporting `affectedRows`. */
11
+ async execute(sql, values) {
12
+ const res = await this.getConn().query(sql, toBindValues(values));
13
+ const rows = Array.isArray(res) ? Array.from(res, decodeBigInts) : [];
14
+ return { rows, changes: res.affectedRows };
20
15
  }
21
16
  /**
22
17
  * Closed through the driver's own `close`, which `Readable` does not type: a loop leaving early only destroys
@@ -103,7 +103,7 @@ function expressionSql({ kind, sql }, dialect, columnType) {
103
103
  }
104
104
  const spelled = kind === 'sql' ? undefined : dialect.sqlValues[kind];
105
105
  if (spelled === undefined) {
106
- throw new UqlUsageError(`${dialect.dialectName} has no ${kind}; write it as raw SQL this engine accepts`);
106
+ throw new UqlUsageError(`${dialect.engineName} has no ${kind}; write it as raw SQL this engine accepts`);
107
107
  }
108
108
  return spelled;
109
109
  }
@@ -1,11 +1,11 @@
1
1
  import type { AbstractSqlDialect } from '../../dialect/abstractSqlDialect.js';
2
2
  import type { IndexType } from '../../schema/types.js';
3
- import { type IndexColumnSchema, type IndexFeature, type IndexJsonPath, type IndexSchema } from '../../type/index.js';
3
+ import { type EngineName, type IndexColumnSchema, type IndexFeature, type IndexJsonPath, type IndexSchema } from '../../type/index.js';
4
4
  import { type IndexCapabilities } from './indexCapabilities.js';
5
5
  /** Refuses an index of a type `types` lacks, `hints` naming what to declare instead. */
6
- export declare function assertIndexType(index: IndexSchema, types: ReadonlySet<IndexType>, dialectName: string, hints?: ReadonlyMap<IndexType, string>): void;
6
+ export declare function assertIndexType(index: IndexSchema, types: ReadonlySet<IndexType>, engine: EngineName, hints?: ReadonlyMap<IndexType, string>): void;
7
7
  /** Refuses an index asking for a feature `features` lacks. */
8
- export declare function assertIndexFeatures(index: IndexSchema, features: ReadonlySet<IndexFeature>, dialectName: string): void;
8
+ export declare function assertIndexFeatures(index: IndexSchema, features: ReadonlySet<IndexFeature>, engine: EngineName): void;
9
9
  /**
10
10
  * `CREATE INDEX` in its portable form, which the SQLite family takes as is; the engines with more override
11
11
  * the fragments. The migrator's own, so no runtime entry carries it.
@@ -20,16 +20,16 @@ const INDEX_FEATURE_PROBES = {
20
20
  include: (index) => Boolean(index.include?.length),
21
21
  };
22
22
  /** Refuses an index of a type `types` lacks, `hints` naming what to declare instead. */
23
- export function assertIndexType(index, types, dialectName, hints = new Map()) {
23
+ export function assertIndexType(index, types, engine, hints = new Map()) {
24
24
  if (index.type && !types.has(index.type)) {
25
- throw new UqlUsageError(`${dialectName} has no ${index.type} index (index "${index.name}")` + (hints.get(index.type) ?? ''));
25
+ throw new UqlUsageError(`${engine} has no ${index.type} index (index "${index.name}")` + (hints.get(index.type) ?? ''));
26
26
  }
27
27
  }
28
28
  /** Refuses an index asking for a feature `features` lacks. */
29
- export function assertIndexFeatures(index, features, dialectName) {
29
+ export function assertIndexFeatures(index, features, engine) {
30
30
  for (const feature of getKeys(INDEX_FEATURE_PROBES)) {
31
31
  if (INDEX_FEATURE_PROBES[feature](index) && !features.has(feature)) {
32
- throw new UqlUsageError(`${dialectName} does not support ${INDEX_FEATURE_LABELS[feature]} (index "${index.name}")`);
32
+ throw new UqlUsageError(`${engine} does not support ${INDEX_FEATURE_LABELS[feature]} (index "${index.name}")`);
33
33
  }
34
34
  }
35
35
  }
@@ -65,8 +65,8 @@ export class IndexDdl {
65
65
  }
66
66
  assertExpressible(index) {
67
67
  const { types, features, hints } = this.capabilities;
68
- assertIndexType(index, types, this.dialect.dialectName, hints);
69
- assertIndexFeatures(index, features, this.dialect.dialectName);
68
+ assertIndexType(index, types, this.dialect.engineName, hints);
69
+ assertIndexFeatures(index, features, this.dialect.engineName);
70
70
  }
71
71
  /** What follows the name and access method, in either form: the columns, then what qualifies them. */
72
72
  indexBody(index) {
@@ -134,7 +134,7 @@ export class IndexDdl {
134
134
  const distance = indexDistance(index);
135
135
  const metric = this.dialect.vectorMetrics.get(distance)?.index;
136
136
  if (!metric) {
137
- throw unsupportedVectorMetric(this.dialect.dialectName, distance, index.name);
137
+ throw unsupportedVectorMetric(this.dialect.engineName, distance, index.name);
138
138
  }
139
139
  return metric;
140
140
  }
@@ -25,7 +25,7 @@ export class MySqlIndexDdl extends MysqlLikeIndexDdl {
25
25
  jsonPathIndexExpr(escapedColumn, json) {
26
26
  const mode = jsonTypeMode(json.type);
27
27
  if (mode === 'json') {
28
- throw new UqlUsageError(`mysql cannot index the boolean JSON path '${json.path}', which compares as JSON`);
28
+ throw new UqlUsageError(`MySQL cannot index the boolean JSON path '${json.path}', which compares as JSON`);
29
29
  }
30
30
  const expr = super.jsonPathIndexExpr(escapedColumn, json);
31
31
  if (mode === 'numeric') {
@@ -94,7 +94,7 @@ function arrayCastType(json) {
94
94
  const type = json.type;
95
95
  const cast = ARRAY_CASTS.get(typeof type === 'string' ? type.toLowerCase() : type);
96
96
  if (!cast) {
97
- throw new UqlUsageError(`mysql has no array cast for ${typeof type === 'string' ? type : type.name} elements`);
97
+ throw new UqlUsageError(`MySQL has no array cast for ${typeof type === 'string' ? type : type.name} elements`);
98
98
  }
99
99
  if (cast !== 'CHAR' && cast !== 'BINARY') {
100
100
  return cast;
@@ -94,7 +94,7 @@ export class TableDdl {
94
94
  /** The clause dropping `key` by its real constraint name: the introspected one, or the one uql derived adding it. */
95
95
  dropPrimaryKey(table, key) {
96
96
  if (!key.name) {
97
- throw new UqlUsageError(`Cannot drop the primary key of "${table}": ${this.dialect.dialectName} names the constraint, and ` +
97
+ throw new UqlUsageError(`Cannot drop the primary key of "${table}": ${this.dialect.engineName} names the constraint, and ` +
98
98
  'introspection did not report a name for it.');
99
99
  }
100
100
  return `DROP CONSTRAINT ${this.dialect.escapeId(key.name)}`;
@@ -119,6 +119,6 @@ export function dropIndexOnTable(dialect, table, index) {
119
119
  }
120
120
  /** What an engine that changes a table only by rebuilding it says to `what`, done in place. */
121
121
  export function rebuildRefusal(dialect, what) {
122
- return new UqlUsageError(`${dialect.dialectName}: ${what} rebuilds the table, which a migration generated from the entities does ` +
122
+ return new UqlUsageError(`${dialect.engineName}: ${what} rebuilds the table, which a migration generated from the entities does ` +
123
123
  '(`uql-migrate generate:entities`) and a hand-written one cannot.');
124
124
  }
@@ -1,8 +1,9 @@
1
- import type { DialectName, EntityWhereMeta } from '../type/index.js';
1
+ import type { AbstractDialect } from '../dialect/abstractDialect.js';
2
+ import type { EngineName, EntityWhereMeta } from '../type/index.js';
2
3
  /**
3
4
  * Refuses a partial index's predicate reaching past what the engine takes, before it compiles to what
4
5
  * only the server would reject, naming the operator as its author wrote it. A `sql` one is left to the server.
5
6
  */
6
- export declare function assertIndexPredicate<E>(where: EntityWhereMeta<E>, dialectName: DialectName, indexName: string): void;
7
+ export declare function assertIndexPredicate<E>(where: EntityWhereMeta<E>, dialect: Pick<AbstractDialect, 'dialectName' | 'engineName'>, indexName: string): void;
7
8
  /** What refusing any part of a partial index's predicate reports. */
8
- export declare function refusedIndexPredicate(dialectName: string, part: string, indexName: string): TypeError;
9
+ export declare function refusedIndexPredicate(engine: EngineName, part: string, indexName: string): TypeError;