uql-orm 0.99.0 → 0.100.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 (174) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +1 -1
  3. package/dist/browser/uql-browser.min.js +2 -2
  4. package/dist/browser/uql-browser.min.js.map +5 -5
  5. package/dist/bunSql/bunSql.util.js +2 -2
  6. package/dist/bunSql/bunSqlQuerier.js +0 -1
  7. package/dist/bunSql/bunSqlQuerierPool.js +1 -1
  8. package/dist/cockroachdb/cockroachDialect.js +1 -0
  9. package/dist/context/context.browser.d.ts +5 -0
  10. package/dist/context/context.browser.js +21 -11
  11. package/dist/context/context.d.ts +5 -0
  12. package/dist/context/context.js +8 -3
  13. package/dist/dialect/abstractDialect.js +4 -2
  14. package/dist/dialect/abstractSqlDialect.d.ts +5 -5
  15. package/dist/dialect/abstractSqlDialect.js +26 -18
  16. package/dist/dialect/aliases.d.ts +0 -2
  17. package/dist/dialect/aliases.js +0 -2
  18. package/dist/dialect/hydrateColumn.d.ts +3 -3
  19. package/dist/dialect/hydrateColumn.js +1 -0
  20. package/dist/dialect/index.js +0 -2
  21. package/dist/dialect/jsonSql.d.ts +2 -3
  22. package/dist/dialect/jsonSql.js +4 -6
  23. package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -1
  24. package/dist/dialect/mysqlLikeSqlDialect.js +5 -3
  25. package/dist/dialect/operators.d.ts +2 -3
  26. package/dist/dialect/operators.js +3 -4
  27. package/dist/dialect/pgLikeSqlDialect.js +12 -12
  28. package/dist/entity/decorator/members.d.ts +4 -12
  29. package/dist/entity/metadata/definition.js +8 -5
  30. package/dist/http/handler.d.ts +6 -6
  31. package/dist/http/handler.js +20 -5
  32. package/dist/index.d.ts +6 -5
  33. package/dist/index.js +6 -5
  34. package/dist/{maria → mariadb}/mariadbQuerier.js +1 -1
  35. package/dist/migrate/builder/columnBuilder.d.ts +3 -3
  36. package/dist/migrate/builder/columnBuilder.js +1 -1
  37. package/dist/migrate/builder/index.d.ts +0 -3
  38. package/dist/migrate/builder/index.js +0 -3
  39. package/dist/migrate/builder/migrationBuilder.d.ts +6 -6
  40. package/dist/migrate/builder/migrationBuilder.js +7 -7
  41. package/dist/migrate/builder/tableBuilder.d.ts +25 -25
  42. package/dist/migrate/builder/tableBuilder.js +5 -5
  43. package/dist/migrate/builder/types.d.ts +37 -37
  44. package/dist/migrate/cli-config.d.ts +9 -0
  45. package/dist/migrate/cli-config.js +14 -4
  46. package/dist/migrate/cli.js +9 -18
  47. package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
  48. package/dist/migrate/codegen/migrationFile.d.ts +7 -7
  49. package/dist/migrate/codegen/migrationFile.js +11 -12
  50. package/dist/migrate/ddl/indexCapabilities.d.ts +2 -0
  51. package/dist/migrate/ddl/indexCapabilities.js +6 -0
  52. package/dist/migrate/ddl/indexDdl.d.ts +8 -0
  53. package/dist/migrate/ddl/indexDdl.js +22 -6
  54. package/dist/migrate/generator/definitionToNode.d.ts +1 -1
  55. package/dist/migrate/generator/definitionToNode.js +1 -1
  56. package/dist/migrate/index.d.ts +1 -3
  57. package/dist/migrate/index.js +0 -3
  58. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +11 -15
  59. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +13 -15
  60. package/dist/migrate/introspection/mssqlIntrospector.d.ts +5 -5
  61. package/dist/migrate/introspection/mssqlIntrospector.js +24 -28
  62. package/dist/migrate/introspection/mysqlIntrospector.d.ts +5 -5
  63. package/dist/migrate/introspection/mysqlIntrospector.js +31 -37
  64. package/dist/migrate/introspection/postgresIntrospector.d.ts +13 -13
  65. package/dist/migrate/introspection/postgresIntrospector.js +35 -39
  66. package/dist/migrate/introspection/registry.js +1 -1
  67. package/dist/migrate/introspection/sqliteIntrospector.d.ts +6 -4
  68. package/dist/migrate/introspection/sqliteIntrospector.js +15 -12
  69. package/dist/migrate/migrationLock.d.ts +38 -0
  70. package/dist/migrate/migrationLock.js +103 -0
  71. package/dist/migrate/migrationTarget.d.ts +6 -2
  72. package/dist/migrate/migrationTarget.js +30 -14
  73. package/dist/migrate/migrator.d.ts +39 -23
  74. package/dist/migrate/migrator.js +110 -74
  75. package/dist/migrate/schemaGenerator.d.ts +3 -1
  76. package/dist/migrate/schemaGenerator.js +14 -5
  77. package/dist/migrate/storage/databaseStorage.d.ts +28 -20
  78. package/dist/migrate/storage/databaseStorage.js +36 -54
  79. package/dist/migrate/storage/index.d.ts +0 -1
  80. package/dist/migrate/storage/index.js +0 -1
  81. package/dist/{mongo → mongodb}/index.d.ts +0 -1
  82. package/dist/{mongo → mongodb}/index.js +0 -1
  83. package/dist/{mongo → mongodb}/mongoCommand.d.ts +17 -1
  84. package/dist/{mongo → mongodb}/mongoCommand.js +15 -2
  85. package/dist/{mongo → mongodb}/mongoDialect.js +8 -12
  86. package/dist/{mongo → mongodb}/mongoIntrospector.js +12 -3
  87. package/dist/{mongo → mongodb}/mongoMigrationStorage.d.ts +5 -5
  88. package/dist/{mongo → mongodb}/mongoMigrationStorage.js +8 -12
  89. package/dist/{mongo → mongodb}/mongoQuerier.d.ts +3 -1
  90. package/dist/{mongo → mongodb}/mongoSchemaGenerator.d.ts +11 -1
  91. package/dist/{mongo → mongodb}/mongoSchemaGenerator.js +56 -11
  92. package/dist/{mongo → mongodb}/mongodbQuerier.d.ts +7 -18
  93. package/dist/{mongo → mongodb}/mongodbQuerier.js +44 -78
  94. package/dist/mssql/mssqlDialect.d.ts +6 -4
  95. package/dist/mssql/mssqlDialect.js +20 -10
  96. package/dist/mssql/mssqlQuerier.d.ts +2 -2
  97. package/dist/mssql/mssqlQuerier.js +3 -3
  98. package/dist/mssql/mssqlQuerierPool.d.ts +1 -1
  99. package/dist/mssql/mssqlQuerierPool.js +2 -2
  100. package/dist/mysql/mysql2Querier.js +1 -5
  101. package/dist/namingStrategy/defaultNamingStrategy.d.ts +0 -1
  102. package/dist/namingStrategy/defaultNamingStrategy.js +0 -3
  103. package/dist/pglite/pgliteDialect.d.ts +3 -0
  104. package/dist/pglite/pgliteDialect.js +3 -1
  105. package/dist/pglite/pgliteQuerier.d.ts +2 -0
  106. package/dist/pglite/pgliteQuerier.js +4 -0
  107. package/dist/postgres/postgresDialect.d.ts +3 -4
  108. package/dist/postgres/postgresDialect.js +5 -6
  109. package/dist/querier/abstractQuerier.d.ts +119 -36
  110. package/dist/querier/abstractQuerier.js +465 -161
  111. package/dist/querier/abstractQuerierPool.d.ts +5 -6
  112. package/dist/querier/abstractQuerierPool.js +20 -6
  113. package/dist/querier/abstractSqlQuerier.d.ts +15 -10
  114. package/dist/querier/abstractSqlQuerier.js +54 -47
  115. package/dist/querier/abstractSqlQuerierPool.d.ts +5 -3
  116. package/dist/querier/abstractSqlQuerierPool.js +7 -4
  117. package/dist/querier/transaction.d.ts +46 -0
  118. package/dist/querier/transaction.js +56 -0
  119. package/dist/schema/canonicalType.js +2 -2
  120. package/dist/schema/schemaASTDiffer.d.ts +11 -3
  121. package/dist/schema/schemaASTDiffer.js +20 -8
  122. package/dist/sqlite/nodeSqliteQuerierPool.d.ts +1 -1
  123. package/dist/sqlite/nodeSqliteQuerierPool.js +1 -1
  124. package/dist/sqlite/sqliteDialect.d.ts +1 -1
  125. package/dist/sqlite/sqliteDialect.js +3 -1
  126. package/dist/sqlite/sqliteQuerier.d.ts +2 -0
  127. package/dist/sqlite/sqliteQuerier.js +4 -0
  128. package/dist/sqlite/sqliteQuerierPool.d.ts +4 -4
  129. package/dist/sqlite/sqliteQuerierPool.js +1 -1
  130. package/dist/type/dialect.d.ts +16 -2
  131. package/dist/type/entity.d.ts +32 -32
  132. package/dist/type/migration.d.ts +10 -27
  133. package/dist/type/namingStrategy.d.ts +0 -4
  134. package/dist/type/querier.d.ts +18 -10
  135. package/dist/type/query.d.ts +7 -22
  136. package/dist/type/queryRaw.d.ts +11 -6
  137. package/dist/type/queryRaw.js +2 -3
  138. package/dist/type/universalQuerier.d.ts +26 -28
  139. package/dist/type/utility.d.ts +7 -2
  140. package/dist/util/dialect.util.d.ts +2 -2
  141. package/dist/util/dialect.util.js +4 -1
  142. package/dist/util/field.util.d.ts +12 -0
  143. package/dist/util/field.util.js +24 -0
  144. package/dist/util/hook.util.d.ts +3 -2
  145. package/dist/util/query.util.d.ts +5 -0
  146. package/dist/util/query.util.js +34 -1
  147. package/dist/util/raw.d.ts +8 -2
  148. package/dist/util/raw.js +22 -0
  149. package/dist/util/relationQuery.util.d.ts +2 -0
  150. package/dist/util/relationQuery.util.js +4 -0
  151. package/dist/util/sql.util.d.ts +0 -5
  152. package/dist/util/sql.util.js +3 -9
  153. package/dist/util/uqlError.d.ts +0 -6
  154. package/dist/util/uqlError.js +0 -5
  155. package/package.json +20 -26
  156. package/skills/uql-orm/SKILL.md +13 -10
  157. package/dist/migrate/storage/jsonStorage.d.ts +0 -14
  158. package/dist/migrate/storage/jsonStorage.js +0 -33
  159. /package/dist/{maria → mariadb}/index.d.ts +0 -0
  160. /package/dist/{maria → mariadb}/index.js +0 -0
  161. /package/dist/{maria → mariadb}/mariaDialect.d.ts +0 -0
  162. /package/dist/{maria → mariadb}/mariaDialect.js +0 -0
  163. /package/dist/{maria → mariadb}/mariadbQuerier.d.ts +0 -0
  164. /package/dist/{maria → mariadb}/mariadbQuerierPool.d.ts +0 -0
  165. /package/dist/{maria → mariadb}/mariadbQuerierPool.js +0 -0
  166. /package/dist/{mongo → mongodb}/mongoDialect.d.ts +0 -0
  167. /package/dist/{mongo → mongodb}/mongoIntrospector.d.ts +0 -0
  168. /package/dist/{mongo → mongodb}/mongoQuerier.js +0 -0
  169. /package/dist/{mongo → mongodb}/mongodbQuerierPool.d.ts +0 -0
  170. /package/dist/{mongo → mongodb}/mongodbQuerierPool.js +0 -0
  171. /package/dist/{mongo → mongodb}/textLanguage.d.ts +0 -0
  172. /package/dist/{mongo → mongodb}/textLanguage.js +0 -0
  173. /package/dist/{mongo → mongodb}/vectorDistance.d.ts +0 -0
  174. /package/dist/{mongo → mongodb}/vectorDistance.js +0 -0
@@ -1,8 +1,8 @@
1
1
  import { fieldOf, getMeta, relationOf, soleIdOf } from '../entity/index.js';
2
2
  import { COUNT_RESULT_KEY, parseQueryLock, QueryRaw, RAW_ALIAS, } from '../type/index.js';
3
3
  import { utcTimestamp } from '../util/date.js';
4
- import { isInlinedExpression } from '../util/field.util.js';
5
- import { isSelectList, assertNonNegativeInteger, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetKeyColumns, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, raw, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
4
+ import { isExactDecimal, isInlinedExpression, jsonKey, jsonPathKeys } from '../util/field.util.js';
5
+ import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetKeyColumns, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, raw, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
6
6
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
7
7
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
8
8
  import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
@@ -104,6 +104,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
104
104
  beginTransactionCommand = 'BEGIN';
105
105
  commitTransactionCommand = 'COMMIT';
106
106
  rollbackTransactionCommand = 'ROLLBACK';
107
+ /** The statement a savepoint command sends, `''` where the engine needs none. */
108
+ savepointStatement(command, name) {
109
+ const statements = {
110
+ open: `SAVEPOINT ${name}`,
111
+ release: `RELEASE SAVEPOINT ${name}`,
112
+ rollback: `ROLLBACK TO SAVEPOINT ${name}`,
113
+ };
114
+ return statements[command];
115
+ }
107
116
  /**
108
117
  * How this engine declares a namespace, so a generated migration creates the schemas its tables
109
118
  * need before creating them. Only reached where {@link DialectFeatures.schemas} is on. MySQL and
@@ -135,7 +144,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
135
144
  if (strategy === 'inline') {
136
145
  return [`${this.beginTransactionCommand} ISOLATION LEVEL ${level}`];
137
146
  }
138
- // 'set-before' - MySQL/MariaDB pattern
147
+ // 'setBefore' - MySQL/MariaDB pattern
139
148
  return [`SET TRANSACTION ISOLATION LEVEL ${level}`, this.beginTransactionCommand];
140
149
  }
141
150
  createContext(options = {}) {
@@ -475,9 +484,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
475
484
  /** Renders a `$where` tree without applying entity filters (used for same-scope group-operator recursion). */
476
485
  renderWhere(ctx, entity, where = {}, opts = {}) {
477
486
  const { clause = 'WHERE' } = opts;
478
- // An `undefined` value emits nothing, so it must not count towards the terms either: it decides
479
- // whether the keys below render as operands of an `AND`.
480
- const whereKeys = getKeys(where).filter((key) => where[key] !== undefined);
487
+ const whereKeys = getKeys(where);
481
488
  // Each key is an operand of the `AND` joining them; a lone key emits this fragment verbatim, so
482
489
  // it inherits this one's position instead.
483
490
  const childOperand = whereKeys.length > 1 || opts.operand || clause === 'AND';
@@ -1070,9 +1077,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1070
1077
  if (groupKeys.length) {
1071
1078
  ctx.append(` GROUP BY ${groupKeys.join(', ')}`);
1072
1079
  }
1073
- if (q.$having) {
1074
- this.having(ctx, q.$having, emittedColumns);
1075
- }
1080
+ this.having(ctx, q.$having ?? {}, emittedColumns);
1076
1081
  const sorted = this.aggregateSort(ctx, q.$sort, emittedColumns);
1077
1082
  this.pager(ctx, q, sorted);
1078
1083
  }
@@ -1125,7 +1130,8 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1125
1130
  return emittedColumns[key] ?? throwUnknownAggregateColumn(key, clause);
1126
1131
  }
1127
1132
  having(ctx, having, emittedColumns) {
1128
- const entries = Object.entries(having).filter(([, v]) => v !== undefined);
1133
+ assertNoUndefined(having, '$having');
1134
+ const entries = Object.entries(having);
1129
1135
  if (!entries.length)
1130
1136
  return;
1131
1137
  ctx.append(' HAVING ');
@@ -1203,7 +1209,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1203
1209
  }
1204
1210
  insert(ctx, entity, payload, opts) {
1205
1211
  const returning = this.insertedIdReturning(getMeta(entity));
1206
- if (returning && this.returningPosition === 'after-target') {
1212
+ if (returning && this.returningPosition === 'afterTarget') {
1207
1213
  this.appendInsertValues(ctx, entity, payload, returning);
1208
1214
  return;
1209
1215
  }
@@ -1390,6 +1396,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1390
1396
  return;
1391
1397
  }
1392
1398
  assertWhere(meta, write.where);
1399
+ assertNoUndefined(write.where, `the $where of a trigger's ${write.kind} over '${meta.name}'`);
1393
1400
  if (!namesRows(write.where)) {
1394
1401
  throw new UqlUsageError(`a trigger's ${write.kind} over '${meta.name}' names no rows, so it would address every one`);
1395
1402
  }
@@ -1472,9 +1479,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1472
1479
  const meta = getMeta(entity);
1473
1480
  const updateCtx = this.upsertUpdateBindsInPlace ? ctx : this.createContext();
1474
1481
  const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
1475
- // Composed rather than concatenated: a composite key contributes no id item, and a dialect's own
1476
- // item (Postgres's created flag) must then come right after the keyword, with no comma before it.
1477
- const returning = [this.returningIdExpression(meta), this.upsertCreatedReturning].filter(Boolean).join(', ');
1482
+ const returning = this.returningIdExpression(meta);
1478
1483
  this.appendInsertValues(ctx, entity, payload);
1479
1484
  ctx.append(`${this.onConflict(meta, conflictPaths, assignments)}${returning ? ` RETURNING ${returning}` : ''}`);
1480
1485
  if (updateCtx !== ctx) {
@@ -1487,8 +1492,6 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1487
1492
  this.getUpsertUpdateAssignments(ctx, getMeta(entity), conflictPaths, row, update);
1488
1493
  return ctx.values.length;
1489
1494
  }
1490
- /** One more `RETURNING` item saying whether the row was created, where the engine can tell; else empty. */
1491
- upsertCreatedReturning = '';
1492
1495
  /** Whether the upsert's assignments bind straight into the statement, as numbered `$n` placeholders can. */
1493
1496
  upsertUpdateBindsInPlace = false;
1494
1497
  /** How an upsert's assignment reads `column` of the row that was being inserted. */
@@ -1631,9 +1634,12 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1631
1634
  if (type === BigInt) {
1632
1635
  return 'bigint';
1633
1636
  }
1637
+ if (field && isExactDecimal(field)) {
1638
+ return 'decimal';
1639
+ }
1634
1640
  switch (columnFamily(type)) {
1635
1641
  case 'json':
1636
- return 'json';
1642
+ return this.features.jsonArrivesDecoded ? undefined : 'json';
1637
1643
  case 'vector':
1638
1644
  return this.features.vectorBytes ? 'float32' : this.supportedVectorType(resolveVectorCast(field));
1639
1645
  case 'boolean':
@@ -1682,6 +1688,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1682
1688
  */
1683
1689
  formatJsonUpdate(ctx, escapedCol, value, field, current = escapedCol) {
1684
1690
  const { $pull, $set, $push, $unset } = value;
1691
+ [...getKeys($pull), ...getKeys($set), ...getKeys($push), ...($unset ?? [])].forEach(jsonKey);
1685
1692
  let expr = current;
1686
1693
  if (hasKeys($pull)) {
1687
1694
  expr = this.jsonPull(ctx, expr, current, $pull);
@@ -1740,6 +1747,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1740
1747
  sql.render({ ctx, dialect: this, prefix: '', escapedPrefix: escapedPrefix ?? '', entity, rows });
1741
1748
  }
1742
1749
  else if (entity) {
1750
+ assertNoUndefined(sql, `a predicate over '${entity.name}'`);
1743
1751
  this.renderWhere(ctx, entity, sql, { clause: false, escapedPrefix, operand });
1744
1752
  }
1745
1753
  else {
@@ -1773,7 +1781,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1773
1781
  }
1774
1782
  const colName = this.resolveColumnName(root, field);
1775
1783
  const prefixed = (prefix ? this.escapeId(prefix, true, true) : '') + this.escapeId(colName);
1776
- return { base: prefixed, path: key.slice(dotIndex + 1) };
1784
+ return { base: prefixed, path: jsonPathKeys(key.slice(dotIndex + 1)).join('.') };
1777
1785
  }
1778
1786
  /**
1779
1787
  * One JSON path, read the way `mode` asks for: the one place the three readings are chosen between,
@@ -47,8 +47,6 @@ export declare const REL_NESTED_KEY = "_uql_target";
47
47
  export declare const UPSERT_NEW_ROW_ALIAS = "_uql_new";
48
48
  /** The row source a `MERGE` upsert reads its incoming values from, on SQL Server and Oracle. */
49
49
  export declare const UPSERT_SOURCE_ALIAS = "_uql_src";
50
- /** The column a Postgres upsert returns beside the id: `(xmax = 0)`, true when it inserted the row. */
51
- export declare const UPSERT_CREATED_ALIAS = "_uql_created";
52
50
  /**
53
51
  * Where a `$sort` by a relation's aggregate - its size, or its nearest row - parks the value until the
54
52
  * ordering has run. A function, so the `$sort` that names the field and the stage that produces it cannot
@@ -50,8 +50,6 @@ export const REL_NESTED_KEY = '_uql_target';
50
50
  export const UPSERT_NEW_ROW_ALIAS = '_uql_new';
51
51
  /** The row source a `MERGE` upsert reads its incoming values from, on SQL Server and Oracle. */
52
52
  export const UPSERT_SOURCE_ALIAS = '_uql_src';
53
- /** The column a Postgres upsert returns beside the id: `(xmax = 0)`, true when it inserted the row. */
54
- export const UPSERT_CREATED_ALIAS = '_uql_created';
55
53
  /**
56
54
  * Where a `$sort` by a relation's aggregate - its size, or its nearest row - parks the value until the
57
55
  * ordering has run. A function, so the `$sort` that names the field and the stage that produces it cannot
@@ -2,11 +2,11 @@ import { type VectorCast } from './vectorCast.js';
2
2
  /**
3
3
  * How a stored column is decoded on read: the inverse of `AbstractSqlDialect.persistKind`. `json`
4
4
  * parses; a {@link VectorCast} says which literal; `boolean` undoes an engine with no boolean type,
5
- * `number` and `bigint` a driver that hands a wide integer or a decimal back as text, and `date` and
6
- * `bytes` a row that crossed JSON inside its parent's statement, which spells both as text. `float32` is
5
+ * `number` and `bigint` a driver that hands a wide integer or a decimal back as text, `decimal` an exact
6
+ * decimal read as its text, whatever the driver hands, and `date` and `bytes` a row that crossed JSON inside its parent's statement, which spells both as text. `float32` is
7
7
  * a vector bound as bytes (`DialectFeatures.vectorBytes`).
8
8
  */
9
- export type HydrateKind = 'json' | 'boolean' | 'number' | 'bigint' | 'date' | 'bytes' | 'float32' | VectorCast;
9
+ export type HydrateKind = 'json' | 'boolean' | 'number' | 'bigint' | 'decimal' | 'date' | 'bytes' | 'float32' | VectorCast;
10
10
  /**
11
11
  * Decodes one non-null cell. A no-op where the driver already decoded it, since that varies per driver,
12
12
  * and untouched where it does not match its column's format.
@@ -50,6 +50,7 @@ const DECODERS = {
50
50
  }
51
51
  },
52
52
  number: fromText(decodeWideNumber),
53
+ decimal: (value) => asText(value) ?? String(value),
53
54
  json: fromText((text, value) => {
54
55
  try {
55
56
  return JSON.parse(text);
@@ -1,5 +1,3 @@
1
- // Each engine's dialect is behind its own entry, and the family bases they extend behind none: the root
2
- // carries no engine's SQL.
3
1
  export * from './abstractDialect.js';
4
2
  export * from './abstractSqlDialect.js';
5
3
  export * from './queryContext.js';
@@ -1,8 +1,7 @@
1
1
  import type { FieldOptions, FieldType } from '../type/index.js';
2
2
  /**
3
- * A `'$.a.b'` JSON path literal, each dot-separated segment escaped, and `'$'` for an empty path, the
4
- * document itself. `suffix` appends an accessor such as `[#]` or `[*]`. Shared across dialects
5
- * unchanged: no dialect escapes a JSON path key differently from an ANSI string literal.
3
+ * A `'$.a.b'` JSON path literal, and `'$'` for an empty path, the document itself. `suffix` appends an
4
+ * accessor such as `[#]` or `[*]`.
6
5
  */
7
6
  export declare function jsonPath(path: string, suffix?: string): string;
8
7
  /** A JSON value a condition reads: `path` of the JSON in `base`, `''` for all of it. */
@@ -1,14 +1,12 @@
1
1
  import { isOperatorMap } from '../util/dialect.util.js';
2
- import { columnFamily } from '../util/field.util.js';
2
+ import { columnFamily, jsonPathKeys } from '../util/field.util.js';
3
3
  import { isOperatorKey, someKey } from '../util/object.util.js';
4
- import { escapeSingleQuotes } from '../util/sqlLiteral.js';
5
4
  /**
6
- * A `'$.a.b'` JSON path literal, each dot-separated segment escaped, and `'$'` for an empty path, the
7
- * document itself. `suffix` appends an accessor such as `[#]` or `[*]`. Shared across dialects
8
- * unchanged: no dialect escapes a JSON path key differently from an ANSI string literal.
5
+ * A `'$.a.b'` JSON path literal, and `'$'` for an empty path, the document itself. `suffix` appends an
6
+ * accessor such as `[#]` or `[*]`.
9
7
  */
10
8
  export function jsonPath(path, suffix = '') {
11
- const segments = path && `.${path.split('.').map(escapeSingleQuotes).join('.')}`;
9
+ const segments = path && `.${jsonPathKeys(path).join('.')}`;
12
10
  return `'$${segments}${suffix}'`;
13
11
  }
14
12
  /** `base, '$.a.b'`, how `JSON_EACH`, `OPENJSON` and the like take the value at `slot`: no path for the whole document. */
@@ -25,7 +25,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
25
25
  readonly autoIncrementSuffix = "AUTO_INCREMENT";
26
26
  readonly escapeIdChar = "`";
27
27
  readonly beginTransactionCommand = "START TRANSACTION";
28
- readonly isolationLevelStrategy = "set-before";
28
+ readonly isolationLevelStrategy = "setBefore";
29
29
  readonly booleanLiteral = "integer";
30
30
  readonly sqlValues: SqlValues;
31
31
  readonly insertIdSource: InsertIdSource;
@@ -1,6 +1,6 @@
1
1
  import { getMeta } from '../entity/index.js';
2
2
  import { textSearchFields } from '../util/index.js';
3
- import { escapeMysqlSqlLiteral, escapeSingleQuotes } from '../util/sqlLiteral.js';
3
+ import { escapeMysqlSqlLiteral } from '../util/sqlLiteral.js';
4
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';
@@ -25,6 +25,7 @@ export const MYSQL_FEATURES = {
25
25
  supportsTimestamptz: false,
26
26
  stringSizing: 'varchar',
27
27
  supportsUnsigned: true,
28
+ jsonArrivesDecoded: true,
28
29
  serverSideCursors: false,
29
30
  correlatedWrites: true,
30
31
  rowLocks: MYSQL_ROW_LOCKS,
@@ -45,6 +46,7 @@ export const MYSQL_FEATURES = {
45
46
  before: true,
46
47
  deferrable: false,
47
48
  },
49
+ namedLocks: 'session',
48
50
  };
49
51
  /** The one `JSON_TABLE` column an exploded array reads each element through, as a JSON document. */
50
52
  const ELEM_COLUMN = 'v';
@@ -88,7 +90,7 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
88
90
  autoIncrementSuffix = 'AUTO_INCREMENT';
89
91
  escapeIdChar = '`';
90
92
  beginTransactionCommand = 'START TRANSACTION';
91
- isolationLevelStrategy = 'set-before';
93
+ isolationLevelStrategy = 'setBefore';
92
94
  booleanLiteral = 'integer';
93
95
  sqlValues = MYSQL_SQL_VALUES;
94
96
  // No `RETURNING` support, so multi-row insert IDs are inferred from the header - see the
@@ -219,7 +221,7 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
219
221
  * second reference for the array source and returns NULL on MariaDB for an absent key.
220
222
  */
221
223
  jsonPush(ctx, expr, push) {
222
- const entries = Object.entries(push).map(([key, value]) => `'${escapeSingleQuotes(key)}', JSON_ARRAY(${this.jsonScalarParam(ctx, value)})`);
224
+ const entries = Object.entries(push).map(([key, value]) => `'${key}', JSON_ARRAY(${this.jsonScalarParam(ctx, value)})`);
223
225
  return `JSON_MERGE_PRESERVE(${expr}, JSON_OBJECT(${entries.join(', ')}))`;
224
226
  }
225
227
  /**
@@ -30,9 +30,8 @@ export declare function isGroupOp(key: string): key is QueryGroupOp;
30
30
  */
31
31
  export declare function groupClauses<E>(key: QueryGroupOp, val: QueryWhereArray<E> | undefined): QueryWhereArray<E>;
32
32
  /**
33
- * Whether a `$where` names any rows, as the WHERE it renders would: an `undefined` value, an empty
34
- * operator map and a group none of whose clauses names one all render nothing, which a write reads as
35
- * the whole table.
33
+ * Whether a `$where` names any rows, as the WHERE it renders would: an empty operator map and a group
34
+ * none of whose clauses names one render nothing, which a write reads as the whole table.
36
35
  */
37
36
  export declare function namesRows<E>(where: QueryWhere<E> | undefined): boolean;
38
37
  /**
@@ -28,15 +28,14 @@ export function groupClauses(key, val) {
28
28
  return val ?? [];
29
29
  }
30
30
  /**
31
- * Whether a `$where` names any rows, as the WHERE it renders would: an `undefined` value, an empty
32
- * operator map and a group none of whose clauses names one all render nothing, which a write reads as
33
- * the whole table.
31
+ * Whether a `$where` names any rows, as the WHERE it renders would: an empty operator map and a group
32
+ * none of whose clauses names one render nothing, which a write reads as the whole table.
34
33
  */
35
34
  export function namesRows(where) {
36
35
  return (where !== undefined &&
37
36
  someKey(where, (key) => isGroupOp(key)
38
37
  ? groupClauses(key, where[key]).some((clause) => clause instanceof QueryRaw || namesRows(clause))
39
- : where[key] !== undefined && !(isWhereMap(where[key]) && !hasKeys(where[key]))));
38
+ : !(isWhereMap(where[key]) && !hasKeys(where[key]))));
40
39
  }
41
40
  /**
42
41
  * A WHERE value as the operators it applies: an array is `$in`, an operator map its own entries, and
@@ -1,7 +1,8 @@
1
1
  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
- import { escapePgSqlLiteral, escapeSingleQuotes, PG_UTC } from '../util/sqlLiteral.js';
4
+ import { jsonPathKeys } from '../util/field.util.js';
5
+ import { escapePgSqlLiteral, PG_UTC } from '../util/sqlLiteral.js';
5
6
  import { ANSI_SQL_VALUES, AbstractSqlDialect } from './abstractSqlDialect.js';
6
7
  import { JSON_PULL_ALIAS, RELATION_ROW_ALIAS } from './aliases.js';
7
8
  import { BYTES_PREFIX } from './hydrateColumn.js';
@@ -26,8 +27,9 @@ export const PG_FEATURES = {
26
27
  vectorSupportsLength: true,
27
28
  vectorBytes: false,
28
29
  supportsTimestamptz: true,
29
- stringSizing: 'bounded-text',
30
+ stringSizing: 'boundedText',
30
31
  supportsUnsigned: false,
32
+ jsonArrivesDecoded: true,
31
33
  serverSideCursors: true,
32
34
  correlatedWrites: true,
33
35
  rowLocks: { of: true, withWindow: false, placement: 'suffix' },
@@ -48,6 +50,7 @@ export const PG_FEATURES = {
48
50
  before: true,
49
51
  deferrable: true,
50
52
  },
53
+ namedLocks: 'session',
51
54
  };
52
55
  export const PG_SQL_VALUES = { ...ANSI_SQL_VALUES, uuid: 'gen_random_uuid()' };
53
56
  /** What Postgres and CockroachDB share: JSONB, full-text search, pgvector's operators, and the upsert. */
@@ -209,10 +212,10 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
209
212
  if (!path) {
210
213
  return mode === 'json' ? escapedColumn : `(${escapedColumn} #>> '{}')`;
211
214
  }
212
- const segments = path.split('.');
213
- return segments.reduce((expr, segment, index) => {
214
- const op = mode === 'text' && index === segments.length - 1 ? '->>' : '->';
215
- return `(${expr}${op}'${escapeSingleQuotes(segment)}')`;
215
+ const keys = jsonPathKeys(path);
216
+ return keys.reduce((expr, key, index) => {
217
+ const op = mode === 'text' && index === keys.length - 1 ? '->>' : '->';
218
+ return `(${expr}${op}'${key}')`;
216
219
  }, escapedColumn);
217
220
  }
218
221
  /** A number only where the value is one: the cast throws on any other text, failing the whole read. */
@@ -271,7 +274,7 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
271
274
  const slot = { base: escapedCol, path: key };
272
275
  const kept = `SELECT JSONB_AGG(${JSON_PULL_ALIAS}.val ORDER BY ${JSON_PULL_ALIAS}.ord) FROM JSONB_ARRAY_ELEMENTS(${this.jsonValue(slot)}) WITH ORDINALITY AS ${JSON_PULL_ALIAS}(val, ord) WHERE ${JSON_PULL_ALIAS}.val <> ${this.jsonVal(ctx, value)}`;
273
276
  const pulled = `CASE WHEN ${this.jsonIsArray(slot)} THEN COALESCE((${kept}), '[]'::jsonb) ELSE COALESCE(${this.jsonValue(slot)}, 'null') END`;
274
- return `JSONB_SET(${expr}, '{${escapeSingleQuotes(key)}}', ${pulled}, false)`;
277
+ return `JSONB_SET(${expr}, '{"${key}"}', ${pulled}, false)`;
275
278
  }
276
279
  /**
277
280
  * The plain values merge as one bound object; a `raw()` one is an SQL expression rather than JSON,
@@ -281,17 +284,14 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
281
284
  jsonSet(ctx, expr, set, field) {
282
285
  const entries = Object.entries(set);
283
286
  const merged = this.jsonVal(ctx, Object.fromEntries(entries.filter(([, value]) => !(value instanceof QueryRaw))));
284
- const raws = entries.flatMap(([key, value]) => value instanceof QueryRaw
285
- ? [` || JSONB_BUILD_OBJECT('${escapeSingleQuotes(key)}', ${this.rawFragment(ctx, value)})`]
286
- : []);
287
+ const raws = entries.flatMap(([key, value]) => value instanceof QueryRaw ? [` || JSONB_BUILD_OBJECT('${key}', ${this.rawFragment(ctx, value)})`] : []);
287
288
  return `${jsonSetTarget(expr, field, `'{}'::jsonb`)} || ${merged}${raws.join('')}`;
288
289
  }
289
290
  /** The only fragment that references `expr` twice - safe here because placeholders are numbered. */
290
291
  jsonPush(ctx, expr, push) {
291
292
  return Object.entries(push).reduce((acc, [key, value]) => {
292
- const escapedKey = escapeSingleQuotes(key);
293
293
  const ph = this.jsonVal(ctx, value);
294
- return `JSONB_SET(${acc}, '{${escapedKey}}', COALESCE((${acc})->'${escapedKey}', '[]'::jsonb) || JSONB_BUILD_ARRAY(${ph}))`;
294
+ return `JSONB_SET(${acc}, '{"${key}"}', COALESCE((${acc})->'${key}', '[]'::jsonb) || JSONB_BUILD_ARRAY(${ph}))`;
295
295
  }, expr);
296
296
  }
297
297
  jsonUnset(ctx, expr, unset) {
@@ -1,4 +1,4 @@
1
- import type { AggregateValue, ComputedRefs, EntityAggregate, EntityGetter, Except, FieldOptions, FieldType, HasCompositeKey, IdValue, NamedIdKey, VersionKey, RejectKeys, RelationManyToManyOptions, RelationManyToOneOptions, RelationOneToManyOptions, RelationOneToOneOptions, RelationAggregate, TsTypeOf, Writable } from '../../type/index.js';
1
+ import type { AggregateValue, EntityAggregate, EntityGetter, Except, FieldOptions, FieldType, HasCompositeKey, IdValue, NamedIdKey, VersionKey, RejectKeys, RelationManyToManyOptions, RelationManyToOneOptions, RelationOneToManyOptions, RelationOneToOneOptions, TsTypeOf, Writable } from '../../type/index.js';
2
2
  import type { RejectIncompatible } from '../../util/index.js';
3
3
  /** A member decorator that also constrains the property it may be applied to, on a class `O`. */
4
4
  type MemberDecorator<V, O = unknown> = (value: undefined, context: ClassFieldDecoratorContext<O, V>) => void;
@@ -61,19 +61,11 @@ export declare function Field<This, O extends FieldOptions<DeclaredValue<O>, Thi
61
61
  * @example `@Field({ computed: (user) => user.resources.count() }) readonly resourceCount?: number;`
62
62
  */
63
63
  export declare function Field<This, O extends AggregateOptions<This> & RejectKeys<Exclude<keyof O, keyof FieldOptions>>>(opts: O): AdmittingDecorator<AggregateValue<O>, AggregateValue<O>, This>;
64
- /**
65
- * A field the aggregate itself types: `stored: true` only where a trigger could keep it, and every other
66
- * option as a column takes it.
67
- */
68
- type AggregateOptions<E> = (Except<FieldOptions<never, E>, 'computed' | 'stored' | 'type'> & {
64
+ /** A field the aggregate itself types, read on each query, never `stored`, and every other option as a column takes it. */
65
+ type AggregateOptions<E> = Except<FieldOptions<never, E>, 'computed' | 'stored' | 'type'> & {
69
66
  readonly computed: EntityAggregate<E>;
70
67
  readonly stored?: false;
71
- }) | (Except<FieldOptions<never, E>, 'computed' | 'stored' | 'type'> & {
72
- readonly computed: {
73
- agg(refs: ComputedRefs<E>): RelationAggregate<unknown, true>;
74
- }['agg'];
75
- readonly stored: true;
76
- });
68
+ };
77
69
  /**
78
70
  * A key the type level cannot name, reported on each `@Id` that leaves it unnamed. Where no `idKey`
79
71
  * brand and no conventional name applies, `IdKey` falls back to every field, and `IdValue`,
@@ -1,6 +1,6 @@
1
1
  import { RelationAggregate, SOFT_DELETE_FILTER } from '../../type/index.js';
2
2
  import { fieldKeys, isInlinedExpression } from '../../util/field.util.js';
3
- import { entitySql, entityWhere, fieldOptionConflict, hasKeys, isToManyRelation, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, whereWith, } from '../../util/index.js';
3
+ import { entitySql, entityWhere, fieldOptionConflict, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, whereWith, } from '../../util/index.js';
4
4
  import { UqlUsageError } from '../../util/uqlError.js';
5
5
  import { ownRegistrations } from '../decorator/bag.js';
6
6
  /**
@@ -20,8 +20,7 @@ export function defineField(entity, key, opts = {}) {
20
20
  const meta = ensureWritableMeta(entity);
21
21
  const { computed, ...rest } = opts;
22
22
  const sql = computed === undefined ? undefined : entitySql(computed);
23
- // A relation aggregate reads as a correlated subquery, which no engine accepts in a generated column:
24
- // keeping one on the row takes the triggers a write fires, which are not built yet.
23
+ // The types refuse this too; an untyped caller still reaches here.
25
24
  if (opts.stored && sql instanceof RelationAggregate) {
26
25
  throw new UqlUsageError(`'${entity.name}.${key}' cannot be 'stored': a relation aggregate reads as a subquery, which no ` +
27
26
  "engine keeps in a generated column. Drop 'stored' to have it read on each query.");
@@ -354,6 +353,10 @@ function fillRelations(meta) {
354
353
  if (!relation.through) {
355
354
  assertJoins(at, meta, relation, references);
356
355
  }
356
+ if (holdsForeignKey(relation) && isCascadable('delete', relation.cascade)) {
357
+ throw new UqlUsageError(`${at} holds the key of a '${relation.entity().name}' other rows may point at too, so it cascades ` +
358
+ "'persist' only: cascade a delete from the side that owns the rows.");
359
+ }
357
360
  }
358
361
  // A column `references` names is a foreign key with or without a relation over it, and one cannot point
359
362
  // at a composite key: refused on first read, as a relation that cannot join is, not at the schema build.
@@ -442,7 +445,7 @@ function fillInverseSide(at, meta, relOpts, mappedBy) {
442
445
  function assertJoins(at, meta, relOpts, pairs) {
443
446
  const target = registeredMeta(relOpts.entity());
444
447
  // Only the owning side of a to-one holds its foreign key; an inverse side and a to-many join on the target's.
445
- const holdsLocally = !relOpts.mappedBy && !isToManyRelation(relOpts);
448
+ const holdsLocally = holdsForeignKey(relOpts);
446
449
  const sides = [
447
450
  { meta: columnsOf(meta), keys: pairs.map(({ local }) => local), joins: target.entity, holds: holdsLocally },
448
451
  { meta: columnsOf(target), keys: pairs.map(({ foreign }) => foreign), joins: meta.entity, holds: !holdsLocally },
@@ -476,7 +479,7 @@ function isA(entity, base) {
476
479
  */
477
480
  export function foreignKeysOf(meta) {
478
481
  const owning = definedEntries(meta.relations)
479
- .filter(([, relation]) => !relation.mappedBy && !relation.through && !isToManyRelation(relation))
482
+ .filter(([, relation]) => holdsForeignKey(relation))
480
483
  .map(([relKey, relation]) => {
481
484
  settledReferences(`'${meta.entity.name}.${relKey}'`, meta, relKey, relation);
482
485
  return relation;
@@ -26,7 +26,7 @@ export type HandlerResponse = {
26
26
  readonly status: number;
27
27
  readonly body: unknown;
28
28
  };
29
- export type HookContext<E extends object, Ctx = unknown> = {
29
+ export type RequestHookContext<E extends object, Ctx = unknown> = {
30
30
  readonly meta: EntityMeta<E>;
31
31
  readonly op: CrudOperation;
32
32
  readonly method: HttpMethod;
@@ -41,8 +41,8 @@ export type HookContext<E extends object, Ctx = unknown> = {
41
41
  */
42
42
  readonly context: Ctx;
43
43
  };
44
- export type Hook<Ctx = unknown> = <E extends object>(ctx: HookContext<E, Ctx>) => void | Promise<void>;
45
- export type ResponseHook<Ctx = unknown> = <E extends object>(ctx: HookContext<E, Ctx>, envelope: RequestSuccessResponse<unknown>) => void | Promise<void>;
44
+ export type RequestHook<Ctx = unknown> = <E extends object>(ctx: RequestHookContext<E, Ctx>) => void | Promise<void>;
45
+ export type ResponseHook<Ctx = unknown> = <E extends object>(ctx: RequestHookContext<E, Ctx>, envelope: RequestSuccessResponse<unknown>) => void | Promise<void>;
46
46
  export type RequestHandlerOptions<Ctx = unknown> = {
47
47
  /**
48
48
  * The entities served, and the only ones a request reaches, through a relation too: nothing is served
@@ -55,15 +55,15 @@ export type RequestHandlerOptions<Ctx = unknown> = {
55
55
  * Allow augment any kind of request before it runs. Hooks may be async
56
56
  * and abort the request by throwing (a numeric `status` on the error is honored).
57
57
  */
58
- pre?: Hook<Ctx>;
58
+ pre?: RequestHook<Ctx>;
59
59
  /**
60
60
  * Allow augment a save request (POST | PUT | PATCH) before it runs.
61
61
  */
62
- preSave?: Hook<Ctx>;
62
+ preSave?: RequestHook<Ctx>;
63
63
  /**
64
64
  * Allow augment a filter request (GET | DELETE) before it runs.
65
65
  */
66
- preFilter?: Hook<Ctx>;
66
+ preFilter?: RequestHook<Ctx>;
67
67
  /**
68
68
  * Shape the successful response before it is sent: strip sensitive fields,
69
69
  * derive presentation fields, or coerce null data. Mutate `envelope.data` in place
@@ -1,5 +1,6 @@
1
1
  import { withContext } from '../context/context.js';
2
2
  import { getMeta, soleIdOf } from '../entity/index.js';
3
+ import { isRecord } from '../util/object.util.js';
3
4
  import { whereWith } from '../util/query.util.js';
4
5
  import { UqlUsageError } from '../util/uqlError.js';
5
6
  import { CRUD_ROUTES, entityPath, matchRoute, } from './contract.js';
@@ -92,21 +93,21 @@ export function createRequestHandler(opts) {
92
93
  return { data: await querier.findManyPage(entity, { ...query, $limit }) };
93
94
  }
94
95
  case 'insertOne':
95
- return { data: await querier.insertOne(entity, body), count: 1 };
96
+ return { data: await querier.insertOne(entity, rowOf(body)), count: 1 };
96
97
  case 'saveOne':
97
- return { data: await querier.saveOne(entity, body), count: 1 };
98
+ return { data: await querier.saveOne(entity, rowOf(body)), count: 1 };
98
99
  case 'insertMany': {
99
- const data = await querier.insertMany(entity, body);
100
+ const data = await querier.insertMany(entity, rowsOf(body));
100
101
  return { data, count: data.length };
101
102
  }
102
103
  case 'saveMany': {
103
- const data = await querier.saveMany(entity, body);
104
+ const data = await querier.saveMany(entity, rowsOf(body));
104
105
  return { data, count: data.length };
105
106
  }
106
107
  // A write returns how many rows it changed, and the querier still refuses a delete that names no rows.
107
108
  case 'updateMany':
108
109
  case 'updateOneById': {
109
- const count = await querier.updateMany(entity, scoped, body);
110
+ const count = await querier.updateMany(entity, scoped, rowOf(body));
110
111
  return { data: count, count };
111
112
  }
112
113
  case 'deleteMany':
@@ -118,6 +119,20 @@ export function createRequestHandler(opts) {
118
119
  }
119
120
  }
120
121
  }
122
+ /** The one row a write sends: a JSON object, refused otherwise as a malformed query is. */
123
+ function rowOf(body) {
124
+ if (!isRecord(body)) {
125
+ throw new UqlUsageError('the body must be a JSON object');
126
+ }
127
+ return body;
128
+ }
129
+ /** The rows a `many` write sends: a JSON array of objects. */
130
+ function rowsOf(body) {
131
+ if (!Array.isArray(body) || !body.every(isRecord)) {
132
+ throw new UqlUsageError('the body must be a JSON array of rows');
133
+ }
134
+ return body;
135
+ }
121
136
  /**
122
137
  * Refuses a relation, at any depth of what a client sent, leading to an entity this handler does not
123
138
  * serve: `include` fences the routes, and this the rows a `$populate`, a filter, a sort, a tally or a
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- export * from './context/context.js';
2
- export * from './dialect/index.js';
3
- export * from './entity/index.js';
1
+ export { captureContext, getContext, withContext } from './context/context.js';
2
+ export * from './entity/decorator/entity.js';
3
+ export * from './entity/decorator/members.js';
4
+ export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, removeEntity, } from './entity/metadata/definition.js';
4
5
  export * from './namingStrategy/index.js';
5
- export * from './querier/index.js';
6
+ export { type QueryError, queryErrorKind } from './querier/queryError.js';
6
7
  export * from './type/index.js';
7
8
  export { withDeleted } from './util/filters.util.js';
8
9
  export type { HookContext } from './util/hook.util.js';
9
10
  export { DefaultLogger } from './util/logger.js';
10
11
  export { currentDate, currentTime, currentTimestamp, raw, refs, uuid, uuidv7 } from './util/raw.js';
11
12
  export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
12
- export * from './util/uqlError.js';
13
+ export { type QueryErrorKind, UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
- export * from './context/context.js';
2
- export * from './dialect/index.js';
3
- export * from './entity/index.js';
1
+ export { captureContext, getContext, withContext } from './context/context.js';
2
+ export * from './entity/decorator/entity.js';
3
+ export * from './entity/decorator/members.js';
4
+ export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, removeEntity, } from './entity/metadata/definition.js';
4
5
  export * from './namingStrategy/index.js';
5
- export * from './querier/index.js';
6
+ export { queryErrorKind } from './querier/queryError.js';
6
7
  export * from './type/index.js';
7
8
  export { withDeleted } from './util/filters.util.js';
8
9
  export { DefaultLogger } from './util/logger.js';
9
10
  export { currentDate, currentTime, currentTimestamp, raw, refs, uuid, uuidv7 } from './util/raw.js';
10
11
  export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
11
- export * from './util/uqlError.js';
12
+ export { UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
@@ -16,7 +16,7 @@ export class MariadbQuerier extends AbstractPoolQuerier {
16
16
  // An OK packet reports `affectedRows`; a `RETURNING` statement answers rows instead, and counts by them.
17
17
  const changes = res.affectedRows ?? res.length;
18
18
  const rows = res.length ? Array.from(res, decodeBigInts) : [];
19
- return this.buildUpdateResult({ rows, changes, upsertStatus: res.affectedRows });
19
+ return this.buildUpdateResult({ rows, changes });
20
20
  }
21
21
  /**
22
22
  * Closed through the driver's own `close`, which `Readable` does not type: a loop leaving early only destroys