uql-orm 0.91.1 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/browser/http/bus.js +3 -4
  2. package/dist/browser/http/http.d.ts +1 -2
  3. package/dist/browser/http/http.js +8 -7
  4. package/dist/browser/index.d.ts +0 -1
  5. package/dist/browser/index.js +0 -1
  6. package/dist/browser/querier/httpQuerier.d.ts +18 -20
  7. package/dist/browser/querier/httpQuerier.js +20 -56
  8. package/dist/browser/type/index.d.ts +0 -1
  9. package/dist/browser/type/index.js +0 -1
  10. package/dist/browser/uql-browser.min.js +2 -2
  11. package/dist/browser/uql-browser.min.js.map +11 -12
  12. package/dist/cockroachdb/cockroachDialect.d.ts +4 -1
  13. package/dist/cockroachdb/cockroachDialect.js +6 -2
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +68 -37
  17. package/dist/dialect/abstractSqlDialect.js +185 -107
  18. package/dist/dialect/aliases.d.ts +4 -1
  19. package/dist/dialect/aliases.js +5 -2
  20. package/dist/dialect/hydrateColumn.js +3 -10
  21. package/dist/dialect/jsonSql.d.ts +4 -1
  22. package/dist/dialect/jsonSql.js +4 -1
  23. package/dist/dialect/mergeSqlDialect.d.ts +14 -4
  24. package/dist/dialect/mergeSqlDialect.js +32 -15
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +16 -24
  26. package/dist/dialect/mysqlLikeSqlDialect.js +38 -52
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -8
  28. package/dist/dialect/pgLikeSqlDialect.js +19 -22
  29. package/dist/http/contract.d.ts +4 -0
  30. package/dist/http/contract.js +1 -0
  31. package/dist/http/handler.d.ts +2 -2
  32. package/dist/http/handler.js +17 -19
  33. package/dist/http/query.d.ts +5 -3
  34. package/dist/http/query.js +42 -42
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +2 -2
  37. package/dist/maria/mariaDialect.d.ts +4 -3
  38. package/dist/maria/mariaDialect.js +4 -6
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/index.d.ts +0 -1
  42. package/dist/migrate/builder/index.js +0 -1
  43. package/dist/migrate/builder/migrationBuilder.d.ts +3 -11
  44. package/dist/migrate/builder/migrationBuilder.js +41 -81
  45. package/dist/migrate/builder/tableBuilder.d.ts +0 -7
  46. package/dist/migrate/builder/tableBuilder.js +19 -30
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +3 -3
  49. package/dist/migrate/codegen/entityTypes.js +2 -2
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +22 -14
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/defaultSql.d.ts +31 -0
  54. package/dist/migrate/ddl/defaultSql.js +109 -0
  55. package/dist/migrate/ddl/index.d.ts +2 -4
  56. package/dist/migrate/ddl/index.js +14 -5
  57. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  58. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  59. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  60. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  61. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  62. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  63. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  64. package/dist/migrate/ddl/tableDdl.js +31 -32
  65. package/dist/migrate/drift/driftDetector.js +46 -59
  66. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  67. package/dist/migrate/generator/definitionToNode.js +27 -34
  68. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  69. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  70. package/dist/migrate/index.js +1 -1
  71. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  72. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +9 -0
  73. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  74. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  75. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  76. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  77. package/dist/migrate/introspection/mysqlIntrospector.js +27 -11
  78. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  79. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  80. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  81. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  82. package/dist/migrate/migrationTarget.js +3 -3
  83. package/dist/migrate/schemaGenerator.d.ts +8 -12
  84. package/dist/migrate/schemaGenerator.js +36 -62
  85. package/dist/migrate/storage/databaseStorage.js +2 -2
  86. package/dist/migrate/triggerSql.d.ts +1 -1
  87. package/dist/migrate/triggerSql.js +17 -8
  88. package/dist/mongo/mongoDialect.d.ts +4 -3
  89. package/dist/mongo/mongoDialect.js +52 -38
  90. package/dist/mongo/mongoIntrospector.js +1 -1
  91. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  92. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  93. package/dist/mongo/mongodbQuerier.d.ts +15 -8
  94. package/dist/mongo/mongodbQuerier.js +48 -33
  95. package/dist/mssql/mssqlDialect.d.ts +9 -5
  96. package/dist/mssql/mssqlDialect.js +23 -8
  97. package/dist/postgres/postgresDialect.d.ts +5 -2
  98. package/dist/postgres/postgresDialect.js +6 -6
  99. package/dist/querier/abstractQuerier.d.ts +20 -15
  100. package/dist/querier/abstractQuerier.js +93 -41
  101. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  102. package/dist/querier/abstractQuerierPool.js +26 -64
  103. package/dist/querier/abstractSqlQuerier.d.ts +5 -6
  104. package/dist/querier/abstractSqlQuerier.js +15 -33
  105. package/dist/querier/cursor.d.ts +10 -0
  106. package/dist/querier/cursor.js +81 -0
  107. package/dist/querier/keyset.d.ts +19 -0
  108. package/dist/querier/keyset.js +198 -0
  109. package/dist/schema/canonicalType.d.ts +3 -3
  110. package/dist/schema/canonicalType.js +13 -12
  111. package/dist/schema/indexDifferences.d.ts +14 -7
  112. package/dist/schema/indexDifferences.js +7 -5
  113. package/dist/schema/schemaAST.d.ts +0 -1
  114. package/dist/schema/schemaAST.js +0 -2
  115. package/dist/schema/schemaASTBuilder.js +14 -20
  116. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  117. package/dist/schema/schemaASTDiffer.js +54 -107
  118. package/dist/schema/sqlExpression.d.ts +28 -0
  119. package/dist/schema/sqlExpression.js +42 -0
  120. package/dist/schema/types.d.ts +48 -105
  121. package/dist/sqlite/sqliteDialect.d.ts +10 -13
  122. package/dist/sqlite/sqliteDialect.js +19 -30
  123. package/dist/type/dialect.d.ts +46 -11
  124. package/dist/type/dialect.js +2 -0
  125. package/dist/type/entity.d.ts +18 -3
  126. package/dist/type/migration.d.ts +7 -7
  127. package/dist/type/querier.d.ts +19 -26
  128. package/dist/type/query.d.ts +116 -25
  129. package/dist/type/query.js +21 -28
  130. package/dist/type/universalQuerier.d.ts +33 -7
  131. package/dist/type/utility.d.ts +10 -0
  132. package/dist/util/bytes.d.ts +7 -0
  133. package/dist/util/bytes.js +22 -0
  134. package/dist/util/date.d.ts +5 -0
  135. package/dist/util/date.js +5 -0
  136. package/dist/util/dialect.util.d.ts +1 -25
  137. package/dist/util/dialect.util.js +4 -50
  138. package/dist/util/field.util.d.ts +9 -0
  139. package/dist/util/field.util.js +15 -0
  140. package/dist/util/fieldOption.util.js +2 -2
  141. package/dist/util/index.d.ts +2 -1
  142. package/dist/util/index.js +2 -1
  143. package/dist/util/object.util.d.ts +0 -2
  144. package/dist/util/object.util.js +0 -7
  145. package/dist/util/query.util.d.ts +40 -0
  146. package/dist/util/query.util.js +76 -0
  147. package/dist/util/raw.d.ts +16 -1
  148. package/dist/util/raw.js +31 -0
  149. package/dist/util/relationQuery.util.js +18 -16
  150. package/dist/util/rowKey.util.js +2 -3
  151. package/dist/util/sql.util.d.ts +8 -2
  152. package/dist/util/sql.util.js +16 -17
  153. package/dist/util/sqlLiteral.js +2 -12
  154. package/dist/util/string.util.d.ts +5 -0
  155. package/dist/util/string.util.js +12 -0
  156. package/dist/util/triggerWrite.d.ts +11 -1
  157. package/dist/util/triggerWrite.js +14 -0
  158. package/package.json +1 -1
  159. package/skills/uql-orm/SKILL.md +22 -10
  160. package/dist/browser/options.d.ts +0 -4
  161. package/dist/browser/options.js +0 -13
  162. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  163. package/dist/browser/type/clientQuerierPool.js +0 -1
  164. package/dist/migrate/builder/expressions.d.ts +0 -69
  165. package/dist/migrate/builder/expressions.js +0 -145
@@ -1,11 +1,12 @@
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
+ import { utcTimestamp } from '../util/date.js';
3
4
  import { isInlinedExpression } from '../util/field.util.js';
4
- import { isSelectList, assertNonNegativeInteger, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, columnFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetKeyColumns, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, populatesRelations, aggregateOf, raw, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.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';
5
6
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
6
7
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
7
8
  import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
8
- import { holdsOperator, isJsonScalar, jsonCompareMode, jsonElemExists, jsonPath, } from './jsonSql.js';
9
+ import { holdsOperator, isJsonScalar, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, } from './jsonSql.js';
9
10
  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';
10
11
  import { SqlQueryContext } from './queryContext.js';
11
12
  import { groupPathField, NO_JOINS, aggregateColumnField, resolveGroupJoins, resolveQueryJoins, relationSortTerms, resolveSortableJoin, } from './queryJoins.js';
@@ -70,21 +71,26 @@ const AGGREGATE_FN = {
70
71
  $min: 'MIN',
71
72
  $max: 'MAX',
72
73
  };
73
- const SORT_DIRECTION_MAP = new Map([
74
- [1, {}],
75
- ['asc', {}],
76
- ['desc', { direction: ' DESC' }],
77
- [-1, { direction: ' DESC' }],
78
- ['ascNullsFirst', { nulls: 'first' }],
79
- ['ascNullsLast', { nulls: 'last' }],
80
- ['descNullsFirst', { direction: ' DESC', nulls: 'first' }],
81
- ['descNullsLast', { direction: ' DESC', nulls: 'last' }],
82
- ]);
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
+ };
83
86
  export class AbstractSqlDialect extends VectorSqlDialect {
84
87
  /** Itself, unless the engine is a fork running another's SQL, which is the only case that overrides. */
85
88
  get dialectFamily() {
86
89
  return this.dialectName;
87
90
  }
91
+ beginTransactionCommand = 'BEGIN';
92
+ commitTransactionCommand = 'COMMIT';
93
+ rollbackTransactionCommand = 'ROLLBACK';
88
94
  /**
89
95
  * How this engine declares a namespace, so a generated migration creates the schemas its tables
90
96
  * need before creating them. Only reached where {@link DialectFeatures.schemas} is on. MySQL and
@@ -94,16 +100,8 @@ export class AbstractSqlDialect extends VectorSqlDialect {
94
100
  return `CREATE SCHEMA IF NOT EXISTS ${this.escapeId(schema, true)}`;
95
101
  }
96
102
  isolationLevelStrategy = 'inline';
97
- alterColumnStrategy = 'single-statement';
98
- alterColumnSyntax = 'ALTER COLUMN';
99
- dropForeignKeySyntax = 'DROP CONSTRAINT';
100
- /**
101
- * `DROP CONSTRAINT <name>` where a primary key is a named constraint like any other; MySQL spells
102
- * it `DROP PRIMARY KEY` and takes no name, since a table's key is always called `PRIMARY` there.
103
- */
104
- dropPrimaryKeySyntax = 'DROP CONSTRAINT';
105
- dropIndexSyntax = 'standalone';
106
103
  booleanLiteral = 'native';
104
+ sqlValues = ANSI_SQL_VALUES;
107
105
  /**
108
106
  * Maximum number of bind parameters the driver accepts in a single statement.
109
107
  * `insertMany` splits larger batches into multiple statements based on this limit.
@@ -161,12 +159,17 @@ export class AbstractSqlDialect extends VectorSqlDialect {
161
159
  ctx.values.push(this.normalizeValue(value));
162
160
  return this.placeholder(ctx.values.length);
163
161
  }
162
+ /** When set, a `Date` binds as UTC text with this zone suffix (`''` for none). Unset, the driver gets the `Date`. */
163
+ dateZone;
164
164
  /**
165
- * A parameter value as this engine's driver takes it: a boolean as the integer an engine with no
166
- * boolean type stores, and everything else as it is - a `bigint` included, which every driver here
167
- * binds exactly, where a number would round it past 2^53. A driver that refuses one (D1) overrides.
165
+ * Converts a parameter value to what this engine's driver takes: a `Date` per {@link dateZone}, a boolean to
166
+ * 1/0 on an engine with no boolean type, and anything else unchanged. A `bigint` passes as is, since every
167
+ * driver here binds it exactly where a number would round past 2^53; a driver that refuses one (D1) overrides.
168
168
  */
169
169
  normalizeValue(value) {
170
+ if (value instanceof Date && this.dateZone !== undefined) {
171
+ return utcTimestamp(value, this.dateZone);
172
+ }
170
173
  if (typeof value === 'boolean' && this.booleanLiteral !== 'native') {
171
174
  return value ? 1 : 0;
172
175
  }
@@ -839,7 +842,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
839
842
  // Where projected in the SELECT list, ordered by that alias rather than scored twice.
840
843
  const { order, project } = textSortOf(sort);
841
844
  const expr = project ? this.escapeId(project) : this.buildFragment(ctx, opts.rankText);
842
- columns.push({ key, expr, ...this.resolveSortDirection(order), output: project !== undefined });
845
+ columns.push({ key, expr, ...parseSortDirection(order), output: project !== undefined });
843
846
  continue;
844
847
  }
845
848
  if (relation) {
@@ -856,7 +859,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
856
859
  vectors.push({ key: name, expr, output: false });
857
860
  }
858
861
  else {
859
- columns.push({ key: keyPath, expr, ...this.resolveSortDirection(direction), output: false });
862
+ columns.push({ key: keyPath, expr, ...parseSortDirection(direction), output: false });
860
863
  }
861
864
  }
862
865
  if (rest === undefined) {
@@ -882,7 +885,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
882
885
  });
883
886
  continue;
884
887
  }
885
- const order = this.resolveSortDirection(value);
888
+ const order = parseSortDirection(value);
886
889
  // A JSON path can sort by more than one reading, each carried under a name of its own.
887
890
  this.sortColumns(ctx, meta, key, prefix).forEach((column, index) => {
888
891
  columns.push({ key: index ? `${keyPath}:${index}` : keyPath, ...column, ...order });
@@ -915,6 +918,8 @@ export class AbstractSqlDialect extends VectorSqlDialect {
915
918
  * value. An engine that orders JSON as text reads a number first, then the text.
916
919
  */
917
920
  jsonSortModes = ['json'];
921
+ /** The `LIMIT` meaning all rows, for an engine that accepts an `OFFSET` only after a `LIMIT`. */
922
+ unboundedLimit;
918
923
  /**
919
924
  * `LIMIT`/`OFFSET`. `sorted` says whether an `ORDER BY` was emitted just before, which
920
925
  * {@link MergeSqlDialect} needs: SQL Server refuses to page a statement that has none.
@@ -924,6 +929,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
924
929
  if (opts.$limit !== undefined) {
925
930
  ctx.append(` LIMIT ${assertNonNegativeInteger(opts.$limit, '$limit')}`);
926
931
  }
932
+ else if (opts.$skip !== undefined && this.unboundedLimit) {
933
+ ctx.append(` LIMIT ${this.unboundedLimit}`);
934
+ }
927
935
  if (opts.$skip !== undefined) {
928
936
  ctx.append(` OFFSET ${assertNonNegativeInteger(opts.$skip, '$skip')}`);
929
937
  }
@@ -1093,7 +1101,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1093
1101
  Object.entries(sort).forEach(([key, dir], index) => {
1094
1102
  if (index > 0)
1095
1103
  ctx.append(', ');
1096
- ctx.append(this.orderByTerm(this.aggregateRef(emittedColumns, key, '$sort'), this.resolveSortDirection(dir)));
1104
+ ctx.append(this.orderByTerm(this.aggregateRef(emittedColumns, key, '$sort'), parseSortDirection(dir)));
1097
1105
  });
1098
1106
  return true;
1099
1107
  }
@@ -1114,16 +1122,13 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1114
1122
  this.havingCondition(ctx, this.aggregateRef(emittedColumns, alias, '$having'), condition);
1115
1123
  });
1116
1124
  }
1117
- resolveSortDirection(sort) {
1118
- const order = SORT_DIRECTION_MAP.get(sort);
1119
- return orRefuse(order, `unknown sort direction: ${sort}`);
1120
- }
1121
1125
  /**
1122
1126
  * One `ORDER BY` term. A placement the engine has no `NULLS FIRST/LAST` for becomes a term of its
1123
1127
  * own in front of it, which is why one is only ever emitted where the caller asked for it: no index
1124
1128
  * serves an expression. SQL Server needs a `CASE`, having no orderable boolean.
1125
1129
  */
1126
- orderByTerm(expr, { direction = '', nulls }) {
1130
+ orderByTerm(expr, { desc, nulls }) {
1131
+ const direction = desc ? ' DESC' : '';
1127
1132
  if (!nulls) {
1128
1133
  return expr + direction;
1129
1134
  }
@@ -1177,11 +1182,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1177
1182
  const alias = ctx.claimAlias(name);
1178
1183
  return alias === name ? opts : { ...opts, alias };
1179
1184
  }
1185
+ /**
1186
+ * The clause that returns the written ids, shared by every insert and upsert. It is `''` on an engine whose
1187
+ * statement cannot return them, and on a composite key, which has no id to ask for.
1188
+ */
1189
+ insertedIdReturning(meta) {
1190
+ return this.insertIdSource === 'returning' ? this.returningId(meta) : '';
1191
+ }
1180
1192
  insert(ctx, entity, payload, opts) {
1181
- // Every engine whose ids come back from the statement itself wants the same clause, so it is
1182
- // built once here instead of in an identical `insert` override per dialect. `returningId` is
1183
- // empty on a composite key, which has no id to ask for.
1184
- const returning = this.insertIdSource === 'returning' ? this.returningId(getMeta(entity)) : '';
1193
+ const returning = this.insertedIdReturning(getMeta(entity));
1185
1194
  if (returning && this.returningPosition === 'after-target') {
1186
1195
  this.appendInsertValues(ctx, entity, payload, returning);
1187
1196
  return;
@@ -1267,29 +1276,47 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1267
1276
  }
1268
1277
  update(ctx, entity, q, payload, opts) {
1269
1278
  const meta = getMeta(entity);
1270
- const [filledPayload] = fillOnFields(meta, payload, 'onUpdate');
1271
- const keys = filterFieldKeys(meta, filledPayload, 'onUpdate');
1272
1279
  ctx.append(`UPDATE ${this.escapedTableName(meta)} SET `);
1273
- 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) => {
1274
1294
  if (i > 0) {
1275
1295
  ctx.append(', ');
1276
1296
  }
1277
- this.appendAssignment(ctx, meta, keys[i], filledPayload[keys[i]]);
1278
- }
1279
- this.search(ctx, entity, q, opts);
1297
+ this.appendAssignment(ctx, meta, key, value, qualifier);
1298
+ });
1280
1299
  }
1281
- /** `col = value`, a JSON operator or a `$inc`/`$mul` spelled as the engine's. */
1282
- 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 = '') {
1283
1305
  const field = meta.fields[key];
1284
1306
  const escapedCol = this.escapedColumnName(meta, key);
1307
+ const current = `${qualifier}${escapedCol}`;
1285
1308
  if (isJsonUpdateOp(value)) {
1286
- this.formatJsonUpdate(ctx, escapedCol, value, field);
1309
+ this.formatJsonUpdate(ctx, escapedCol, value, field, current);
1287
1310
  }
1288
1311
  else if (isFieldUpdateOp(value)) {
1289
1312
  const [op, operand] = fieldUpdateOf(key, value);
1290
- ctx.append(`${escapedCol} = COALESCE(${escapedCol}, 0) ${SQL_ARITHMETIC[op]} `);
1313
+ ctx.append(`${escapedCol} = COALESCE(${current}, 0) ${SQL_ARITHMETIC[op]} `);
1291
1314
  ctx.addValue(operand);
1292
1315
  }
1316
+ else if (qualifier && value instanceof QueryRaw) {
1317
+ ctx.append(`${escapedCol} = `);
1318
+ this.getRawValue(ctx, { value, escapedPrefix: qualifier });
1319
+ }
1293
1320
  else {
1294
1321
  ctx.append(`${escapedCol} = `);
1295
1322
  this.formatPersistableValue(ctx, field, value);
@@ -1301,27 +1328,36 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1301
1328
  * trigger has none of. `rows` are what a set-based engine's body reads, narrowed to the ones it fires for.
1302
1329
  */
1303
1330
  triggerWrite(ctx, write, rows) {
1331
+ if (write.kind === 'refuse') {
1332
+ ctx.append(this.refusal(this.escape(write.message), rows));
1333
+ return;
1334
+ }
1304
1335
  const meta = getMeta(write.entity);
1305
1336
  const table = this.escapedTableName(meta);
1306
- if (write.kind === 'insert') {
1337
+ if (write.kind === 'insert' || write.kind === 'upsert') {
1307
1338
  const unfilled = definedEntries(meta.fields).find(([key, field]) => field.onInsert !== undefined && field.defaultValue === undefined && write.row[key] === undefined);
1308
1339
  if (unfilled) {
1309
1340
  throw new UqlUsageError(`'${meta.name}.${unfilled[0]}' is filled on insert by uql, which a trigger does not run: ` +
1310
1341
  'name it, or give it a defaultValue');
1311
1342
  }
1312
1343
  const entries = this.writtenEntries(meta, write.row);
1313
- const columns = entries.map(([key]) => this.escapedColumnName(meta, key)).join(', ');
1314
- const [open, close] = rows
1315
- ? ['SELECT ', ` FROM ${rows.from}${rows.where ? ` WHERE ${rows.where}` : ''};`]
1316
- : ['VALUES (', ');'];
1317
- ctx.append(`INSERT INTO ${table} (${columns}) ${open}`);
1318
- entries.forEach(([key, value], i) => {
1319
- if (i > 0) {
1320
- ctx.append(', ');
1321
- }
1322
- this.formatPersistableValue(ctx, meta.fields[key], value);
1323
- });
1324
- ctx.append(close);
1344
+ if (write.kind === 'insert') {
1345
+ this.appendTriggerInsert(ctx, meta, entries, rows);
1346
+ ctx.append(';');
1347
+ return;
1348
+ }
1349
+ const { conflictPaths, update } = write;
1350
+ // What a conflicting row takes, none filled in JavaScript: the incoming row less the conflict paths, or `update`.
1351
+ const assigned = update === undefined
1352
+ ? entries
1353
+ .filter(([key]) => !conflictPaths[key])
1354
+ .map(([key]) => [key, this.incoming(meta, key)])
1355
+ : hasKeys(update)
1356
+ ? this.writtenEntries(meta, update)
1357
+ : [];
1358
+ this.refuseAccumulating(meta, assigned, rows);
1359
+ const assignments = this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, assigned, `${table}.`));
1360
+ this.appendTriggerUpsert(ctx, meta, conflictPaths, entries, assignments, rows);
1325
1361
  return;
1326
1362
  }
1327
1363
  assertWhere(meta, write.where);
@@ -1330,18 +1366,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1330
1366
  }
1331
1367
  if (write.kind === 'update') {
1332
1368
  const entries = this.writtenEntries(meta, write.set);
1333
- const accumulating = rows && entries.find(([, value]) => accumulates(value));
1334
- if (accumulating) {
1335
- throw new UqlUsageError(`'${meta.name}.${accumulating[0]}' cannot accumulate per row in a trigger fired once per statement, ` +
1336
- 'which applies $inc, $mul and $push once');
1337
- }
1369
+ this.refuseAccumulating(meta, entries, rows);
1338
1370
  ctx.append(`UPDATE ${table} SET `);
1339
- entries.forEach(([key, value], i) => {
1340
- if (i > 0) {
1341
- ctx.append(', ');
1342
- }
1343
- this.appendAssignment(ctx, meta, key, value);
1344
- });
1371
+ this.appendAssignments(ctx, meta, entries);
1345
1372
  }
1346
1373
  else {
1347
1374
  ctx.append(`DELETE FROM ${table}`);
@@ -1355,6 +1382,47 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1355
1382
  this.renderWhere(ctx, write.entity, where, { escapedPrefix: `${table}.` });
1356
1383
  ctx.append(';');
1357
1384
  }
1385
+ /** `$inc`, `$mul` and `$push` refused where the body reads a set, which applies each once for the statement. */
1386
+ refuseAccumulating(meta, entries, rows) {
1387
+ const accumulating = rows && entries.find(([, value]) => accumulates(value));
1388
+ if (accumulating) {
1389
+ throw new UqlUsageError(`'${meta.name}.${accumulating[0]}' cannot accumulate per row in a trigger fired once per statement, ` +
1390
+ 'which applies $inc, $mul and $push once');
1391
+ }
1392
+ }
1393
+ /** A trigger's insert, unterminated: its values, or a `SELECT` of them off the set a set-based engine hands it. */
1394
+ appendTriggerInsert(ctx, meta, entries, rows) {
1395
+ const columns = entries.map(([key]) => this.escapedColumnName(meta, key)).join(', ');
1396
+ ctx.append(`INSERT INTO ${this.escapedTableName(meta)} (${columns}) ${rows ? 'SELECT ' : 'VALUES ('}`);
1397
+ this.appendTriggerValues(ctx, meta, entries);
1398
+ ctx.append(rows ? fromRows(rows) : ')');
1399
+ }
1400
+ /** The values a trigger writes, a literal or SQL each, the rows' refs most often. */
1401
+ appendTriggerValues(ctx, meta, entries) {
1402
+ entries.forEach(([key, value], i) => {
1403
+ if (i > 0) {
1404
+ ctx.append(', ');
1405
+ }
1406
+ this.formatPersistableValue(ctx, meta.fields[key], value);
1407
+ });
1408
+ }
1409
+ /** A trigger's upsert: its insert, then what a conflicting row takes, `assignments`, or nothing where empty. */
1410
+ appendTriggerUpsert(ctx, meta, conflictPaths, entries, assignments, rows) {
1411
+ this.appendTriggerInsert(ctx, meta, entries, rows);
1412
+ ctx.append(`${this.onConflict(meta, conflictPaths, assignments)};`);
1413
+ }
1414
+ /** ` ON CONFLICT (keys) DO UPDATE SET ...`, or `DO NOTHING` with nothing to assign. */
1415
+ onConflict(meta, conflictPaths, assignments) {
1416
+ const keys = this.getUpsertConflictPathsStr(meta, conflictPaths);
1417
+ return ` ON CONFLICT (${keys}) ${assignments ? `DO UPDATE SET ${assignments}` : 'DO NOTHING'}`;
1418
+ }
1419
+ /**
1420
+ * The statement failing a trigger's write with `message`, a quoted literal: SQL/PSM's `SIGNAL`, which the
1421
+ * MySQL family speaks. `rows` are what a set-based engine's body reads, where it fails only if there are any.
1422
+ */
1423
+ refusal(message, _rows) {
1424
+ return `SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = ${message};`;
1425
+ }
1358
1426
  /** The values a write names, refusing one the entity has no column for. */
1359
1427
  writtenEntries(meta, values) {
1360
1428
  const entries = Object.entries(values).filter(([, value]) => value !== undefined);
@@ -1371,43 +1439,48 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1371
1439
  * `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING`. The assignments are built before the insert
1372
1440
  * fills `onInsert` columns, which must stay out of them, and their values bound after it, where a `?` reads them.
1373
1441
  */
1374
- upsert(ctx, entity, conflictPaths, payload,
1375
- /** One more `RETURNING` item, as a bare expression: this joins the list and adds the keyword. */
1376
- extraReturning = '') {
1442
+ upsert(ctx, entity, conflictPaths, payload, { update } = {}) {
1377
1443
  const meta = getMeta(entity);
1378
1444
  const updateCtx = this.upsertUpdateBindsInPlace ? ctx : this.createContext();
1379
- const update = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, this.upsertExcluded);
1380
- const keys = this.getUpsertConflictPathsStr(meta, conflictPaths);
1381
- const onConflict = update ? `DO UPDATE SET ${update}` : 'DO NOTHING';
1445
+ const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
1382
1446
  // Composed rather than concatenated: a composite key contributes no id item, and a dialect's own
1383
- // item (Postgres's `_created`) still has to be the *first* thing after the keyword when it is.
1384
- const returning = [this.returningIdExpression(meta), extraReturning].filter(Boolean).join(', ');
1447
+ // item (Postgres's created flag) must then come right after the keyword, with no comma before it.
1448
+ const returning = [this.returningIdExpression(meta), this.upsertCreatedReturning].filter(Boolean).join(', ');
1385
1449
  this.appendInsertValues(ctx, entity, payload);
1386
- ctx.append(` ON CONFLICT (${keys}) ${onConflict}${returning ? ` RETURNING ${returning}` : ''}`);
1450
+ ctx.append(`${this.onConflict(meta, conflictPaths, assignments)}${returning ? ` RETURNING ${returning}` : ''}`);
1387
1451
  if (updateCtx !== ctx) {
1388
1452
  ctx.pushValue(...updateCtx.values);
1389
1453
  }
1390
1454
  }
1455
+ /** One more `RETURNING` item saying whether the row was created, where the engine can tell; else empty. */
1456
+ upsertCreatedReturning = '';
1391
1457
  /** Whether the upsert's assignments bind straight into the statement, as numbered `$n` placeholders can. */
1392
1458
  upsertUpdateBindsInPlace = false;
1393
- /** How an `ON CONFLICT` assignment reads the row that was being inserted. */
1394
- upsertExcluded = (columnName) => `EXCLUDED.${columnName}`;
1395
- getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, callback) {
1459
+ /** How an upsert's assignment reads `column` of the row that was being inserted. */
1460
+ upsertIncoming(column) {
1461
+ return `EXCLUDED.${column}`;
1462
+ }
1463
+ /** `key`'s column of the row being inserted, as SQL an assignment takes. */
1464
+ incoming(meta, key) {
1465
+ const column = this.escapedColumnName(meta, key);
1466
+ return raw(() => this.upsertIncoming(column));
1467
+ }
1468
+ /**
1469
+ * What a conflicting row takes: `update` where given, else the incoming row less the conflict paths, and what
1470
+ * `onUpdate` fills. An empty `update` leaves the row as it is, its fills included: nothing to assign.
1471
+ */
1472
+ getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, update) {
1396
1473
  const sample = Array.isArray(payload) ? payload[0] : payload;
1397
- const cloned = { ...sample };
1398
- const [filledPayload] = fillOnFields(meta, cloned, 'onUpdate');
1399
- const fields = filterFieldKeys(meta, filledPayload, 'onUpdate');
1400
- return fields
1401
- .filter((col) => !conflictPaths[col])
1402
- .map((col) => {
1403
- const column = this.escapedColumnName(meta, col);
1404
- if (Object.hasOwn(sample, col)) {
1405
- return `${column} = ${callback(column)}`;
1406
- }
1407
- const text = this.buildFragment(ctx, (fragmentCtx) => this.formatPersistableValue(fragmentCtx, meta.fields[col], filledPayload[col]));
1408
- return `${column} = ${text}`;
1409
- })
1410
- .join(', ');
1474
+ const [filled] = fillOnFields(meta, { ...sample }, 'onUpdate');
1475
+ const entries = update
1476
+ ? hasKeys(update)
1477
+ ? this.updateEntries(meta, update)
1478
+ : []
1479
+ : filterFieldKeys(meta, filled, 'onUpdate')
1480
+ .filter((key) => !conflictPaths[key])
1481
+ .map((key) => [key, Object.hasOwn(sample, key) ? this.incoming(meta, key) : filled[key]]);
1482
+ const qualifier = `${this.escapedTableName(meta)}.`;
1483
+ return this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, entries, qualifier));
1411
1484
  }
1412
1485
  getUpsertConflictPathsStr(meta, conflictPaths) {
1413
1486
  return getKeys(conflictPaths)
@@ -1572,11 +1645,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1572
1645
  * `"col" = <expr>` for a JSON update, each operator wrapping the last: `$pull`, `$set`, `$push`, `$unset`.
1573
1646
  * `$pull` reads the column and every later one its expression once, so no value binds twice.
1574
1647
  */
1575
- formatJsonUpdate(ctx, escapedCol, value, field) {
1648
+ formatJsonUpdate(ctx, escapedCol, value, field, current = escapedCol) {
1576
1649
  const { $pull, $set, $push, $unset } = value;
1577
- let expr = escapedCol;
1650
+ let expr = current;
1578
1651
  if (hasKeys($pull)) {
1579
- expr = this.jsonPull(ctx, expr, escapedCol, $pull);
1652
+ expr = this.jsonPull(ctx, expr, current, $pull);
1580
1653
  }
1581
1654
  if (hasKeys($set)) {
1582
1655
  expr = this.jsonSet(ctx, expr, $set, field);
@@ -1618,6 +1691,14 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1618
1691
  jsonDiffers(elem, operand) {
1619
1692
  return `${elem} <> ${operand}`;
1620
1693
  }
1694
+ /** Shallow assignment of top-level keys, matching PostgreSQL's `jsonb || jsonb`, through `JSON_SET`. */
1695
+ jsonSet(ctx, expr, set, field) {
1696
+ return jsonSetCall((value) => this.jsonScalarParam(ctx, value), jsonSetTarget(expr, field, `'{}'`), set, this.maxFunctionArgs);
1697
+ }
1698
+ /** Remove object keys, through `JSON_REMOVE`. */
1699
+ jsonUnset(_ctx, expr, unset) {
1700
+ return jsonRemoveCall(expr, unset, this.maxFunctionArgs);
1701
+ }
1621
1702
  compileDdl(sql, entity, { rows, escapedPrefix, operand } = {}) {
1622
1703
  const ctx = this.createContext({ inlineValues: true });
1623
1704
  if (sql instanceof QueryRaw) {
@@ -1785,7 +1866,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1785
1866
  const query = {
1786
1867
  ...page,
1787
1868
  $select: [read.as(AGGREGATE_VALUE_ALIAS)],
1788
- $where: { ...$where, $and: [...($where?.$and ?? []), correlation] },
1869
+ $where: whereAnd($where, [correlation]),
1789
1870
  };
1790
1871
  const joins = resolveQueryJoins(getMeta(entity), query, (path) => ctx.claimAlias(path));
1791
1872
  this.read(ctx, entity, query, { alias }, joins);
@@ -1839,7 +1920,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1839
1920
  this.assertDistinctSort(relMeta, relKey, query);
1840
1921
  const alias = ctx.claimAlias(relKey, parent);
1841
1922
  const correlation = raw(({ ctx: rowsCtx }) => this.appendCorrelation(rowsCtx, meta, relation, parent, alias));
1842
- const rows = { ...query, $where: { ...query.$where, $and: [...(query.$where?.$and ?? []), correlation] } };
1923
+ const rows = { ...query, $where: whereAnd(query.$where, [correlation]) };
1843
1924
  const joins = resolveQueryJoins(relMeta, rows, (path) => ctx.claimAlias(path));
1844
1925
  this.appendRelationArray(ctx, { entity, query: rows, alias, joins, distinct });
1845
1926
  }
@@ -1913,7 +1994,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1913
1994
  carriedFields = {};
1914
1995
  /** `expr` as it crosses JSON, by its field's family: see {@link carriedFields}. */
1915
1996
  carried(expr, field) {
1916
- const family = columnFamily(field.columnType ?? field.type);
1997
+ const family = fieldFamily(field);
1917
1998
  return (family && this.carriedFields[family]?.(expr, field)) ?? expr;
1918
1999
  }
1919
2000
  /** `'key', column, ...`: the arguments of a JSON object call over `pairs`. */
@@ -1969,9 +2050,6 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1969
2050
  escape(value) {
1970
2051
  return escapeAnsiSqlLiteral(value);
1971
2052
  }
1972
- get regexpOp() {
1973
- return 'REGEXP';
1974
- }
1975
2053
  /**
1976
2054
  * The `$regex` predicate. An infix operator on the MySQL family (`REGEXP`) and the Postgres one
1977
2055
  * (`~`), but a function on Oracle and SQL Server 2025 (`REGEXP_LIKE(col, ?)`) - which is why this
@@ -1979,7 +2057,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1979
2057
  * throw, the way {@link appendTextSearch} already does.
1980
2058
  */
1981
2059
  regexCondition(operand, placeholder) {
1982
- return `${operand} ${this.regexpOp} ${placeholder}`;
2060
+ return `${operand} REGEXP ${placeholder}`;
1983
2061
  }
1984
2062
  /** `operand IN (...)` of each value as `bind` renders it, or the constant an empty set reduces to: no value is in it. */
1985
2063
  formatIn(_ctx, operand, values, negate, bind) {
@@ -32,6 +32,7 @@ export declare const TEXT_SCORE_ALIAS = "_uql_text_score";
32
32
  /**
33
33
  * The field a MongoDB `$sort` placing nulls orders by first: 1 where the value is null or missing, 0
34
34
  * where it is not. MongoDB takes no `NULLS FIRST`, so the placement is this flag plus the sort on it.
35
+ * A dot becomes `_o` and an underscore `__`, so two paths such as `a.b` and `a_b` never share a flag.
35
36
  */
36
37
  export declare function nullsSortField(path: string): string;
37
38
  /** Prefix for the field a MongoDB relation lookup parks its result on, one per condition. */
@@ -41,11 +42,13 @@ export declare const REL_NESTED_KEY = "_uql_target";
41
42
  /**
42
43
  * The alias MySQL's upsert gives the row being inserted, so its `ON DUPLICATE KEY UPDATE`
43
44
  * assignments read `_uql_new.col` instead of the deprecated `VALUES(col)`. MariaDB has no such
44
- * syntax and keeps `VALUES(col)`.
45
+ * syntax and reads `VALUE(col)`.
45
46
  */
46
47
  export declare const UPSERT_NEW_ROW_ALIAS = "_uql_new";
47
48
  /** The row source a `MERGE` upsert reads its incoming values from, on SQL Server and Oracle. */
48
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";
49
52
  /**
50
53
  * Where a `$sort` by a relation's aggregate - its size, or its nearest row - parks the value until the
51
54
  * ordering has run. A function, so the `$sort` that names the field and the stage that produces it cannot
@@ -33,9 +33,10 @@ export const TEXT_SCORE_ALIAS = '_uql_text_score';
33
33
  /**
34
34
  * The field a MongoDB `$sort` placing nulls orders by first: 1 where the value is null or missing, 0
35
35
  * where it is not. MongoDB takes no `NULLS FIRST`, so the placement is this flag plus the sort on it.
36
+ * A dot becomes `_o` and an underscore `__`, so two paths such as `a.b` and `a_b` never share a flag.
36
37
  */
37
38
  export function nullsSortField(path) {
38
- return `_uql_nulls_${path.replace(/\./g, '_')}`;
39
+ return `_uql_nulls_${path.replace(/[._]/g, (char) => (char === '.' ? '_o' : '__'))}`;
39
40
  }
40
41
  /** Prefix for the field a MongoDB relation lookup parks its result on, one per condition. */
41
42
  export const REL_TEMP_PREFIX = '_uql_rel_';
@@ -44,11 +45,13 @@ export const REL_NESTED_KEY = '_uql_target';
44
45
  /**
45
46
  * The alias MySQL's upsert gives the row being inserted, so its `ON DUPLICATE KEY UPDATE`
46
47
  * assignments read `_uql_new.col` instead of the deprecated `VALUES(col)`. MariaDB has no such
47
- * syntax and keeps `VALUES(col)`.
48
+ * syntax and reads `VALUE(col)`.
48
49
  */
49
50
  export const UPSERT_NEW_ROW_ALIAS = '_uql_new';
50
51
  /** The row source a `MERGE` upsert reads its incoming values from, on SQL Server and Oracle. */
51
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';
52
55
  /**
53
56
  * Where a `$sort` by a relation's aggregate - its size, or its nearest row - parks the value until the
54
57
  * ordering has run. A function, so the `$sort` that names the field and the stage that produces it cannot
@@ -1,3 +1,4 @@
1
+ import { hexToBytes } from '../util/bytes.js';
1
2
  import { decodeDate } from '../util/date.js';
2
3
  import { decodeWideNumber } from '../util/wideNumber.js';
3
4
  import { decodeFloat32s, parseVectorLiteral } from './vectorCast.js';
@@ -18,7 +19,7 @@ function fromText(decode) {
18
19
  /** A vector's text in the literal its cast writes, or its packed float32s in hex, which MariaDB reads. */
19
20
  function vectorDecoder(cast) {
20
21
  return fromText((text, value) => text.startsWith(BYTES_PREFIX)
21
- ? decodeFloat32s(hexBytes(text.slice(BYTES_PREFIX.length)))
22
+ ? decodeFloat32s(hexToBytes(text.slice(BYTES_PREFIX.length)))
22
23
  : (parseVectorLiteral(text, cast) ?? value));
23
24
  }
24
25
  const denseVector = vectorDecoder('vector');
@@ -34,7 +35,7 @@ const DECODERS = {
34
35
  boolean: (value) => (typeof value === 'boolean' ? value : Boolean(value)),
35
36
  date: (value) => (typeof value === 'string' ? decodeDate(value) : value),
36
37
  // Only a string can be bytes that crossed JSON: bytes a driver already decoded stay as they are.
37
- bytes: (value) => typeof value === 'string' && value.startsWith(BYTES_PREFIX) ? hexBytes(value.slice(BYTES_PREFIX.length)) : value,
38
+ bytes: (value) => typeof value === 'string' && value.startsWith(BYTES_PREFIX) ? hexToBytes(value.slice(BYTES_PREFIX.length)) : value,
38
39
  // A number too, not just text: `type: BigInt` is BIGINT, which the pg pools decode at the wire.
39
40
  bigint: (value) => {
40
41
  if (typeof value === 'bigint') {
@@ -67,14 +68,6 @@ const DECODERS = {
67
68
  * which every dialect spells, so a string a driver reads from a column on its own is never mistaken.
68
69
  */
69
70
  export const BYTES_PREFIX = '\\x';
70
- /** Two hex digits per byte, back to bytes. */
71
- function hexBytes(hex) {
72
- const bytes = new Uint8Array(hex.length / 2);
73
- for (let at = 0; at < bytes.length; at++) {
74
- bytes[at] = Number.parseInt(hex.slice(at * 2, at * 2 + 2), 16);
75
- }
76
- return bytes;
77
- }
78
71
  /** Lazy so a consumer that never reads an encoded column never constructs one. */
79
72
  let decoder;
80
73
  /** The text a driver returned, bytes included (`bun:sql` hands a MySQL decimal as a `Buffer`), or `undefined`. */
@@ -30,7 +30,10 @@ export declare function chainedCall(fn: string, target: string, groups: readonly
30
30
  * appends an accessor per key (SQLite's `[#]` append). Values bind in key order through `bindValue`.
31
31
  */
32
32
  export declare function jsonSetCall(bindValue: (value: unknown) => string, target: string, entries: Record<string, unknown>, maxArgs: number, pathSuffix?: string): string;
33
- /** The `$set` target: a nullable column needs a `COALESCE` fallback to build on. */
33
+ /**
34
+ * The target a `$set` builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL one goes in bare,
35
+ * which keeps MySQL's partial in-place JSON update, since that needs the column itself as `JSON_SET`'s input.
36
+ */
34
37
  export declare function jsonSetTarget(expr: string, field: FieldOptions | undefined, empty: string): string;
35
38
  /** `JSON_REMOVE(expr, path, ...)`, which MySQL and SQLite share, nested past `maxArgs`. */
36
39
  export declare function jsonRemoveCall(expr: string, keys: readonly string[], maxArgs: number): string;
@@ -47,7 +47,10 @@ export function jsonSetCall(bindValue, target, entries, maxArgs, pathSuffix = ''
47
47
  const pairs = Object.entries(entries).map(([key, value]) => `${jsonPath(key, pathSuffix)}, ${bindValue(value)}`);
48
48
  return chainedCall('JSON_SET', target, pairs, 2, maxArgs);
49
49
  }
50
- /** The `$set` target: a nullable column needs a `COALESCE` fallback to build on. */
50
+ /**
51
+ * The target a `$set` builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL one goes in bare,
52
+ * which keeps MySQL's partial in-place JSON update, since that needs the column itself as `JSON_SET`'s input.
53
+ */
51
54
  export function jsonSetTarget(expr, field, empty) {
52
55
  return field?.nullable === false ? expr : `COALESCE(${expr}, ${empty})`;
53
56
  }