uql-orm 0.102.5 → 0.102.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +3 -3
  4. package/dist/bunSql/bunSqlQuerier.d.ts +9 -3
  5. package/dist/bunSql/bunSqlQuerier.js +7 -15
  6. package/dist/d1/d1Querier.d.ts +18 -14
  7. package/dist/d1/d1Querier.js +21 -8
  8. package/dist/d1/d1SqliteDialect.d.ts +2 -0
  9. package/dist/d1/d1SqliteDialect.js +3 -0
  10. package/dist/dialect/abstractDialect.d.ts +3 -0
  11. package/dist/dialect/abstractDialect.js +6 -2
  12. package/dist/dialect/abstractSqlDialect.d.ts +24 -5
  13. package/dist/dialect/abstractSqlDialect.js +86 -57
  14. package/dist/dialect/mysqlLikeSqlDialect.js +6 -1
  15. package/dist/dialect/operators.d.ts +9 -3
  16. package/dist/dialect/operators.js +32 -9
  17. package/dist/dialect/vectorSqlDialect.js +2 -2
  18. package/dist/entity/index.d.ts +1 -1
  19. package/dist/entity/index.js +1 -1
  20. package/dist/entity/metadata/definition.d.ts +16 -1
  21. package/dist/entity/metadata/definition.js +26 -1
  22. package/dist/index.d.ts +2 -1
  23. package/dist/index.js +2 -1
  24. package/dist/mariadb/mariadbQuerier.d.ts +5 -2
  25. package/dist/mariadb/mariadbQuerier.js +5 -10
  26. package/dist/migrate/ddl/defaultSql.js +1 -1
  27. package/dist/migrate/ddl/indexDdl.d.ts +3 -3
  28. package/dist/migrate/ddl/indexDdl.js +7 -7
  29. package/dist/migrate/ddl/mysqlIndexDdl.js +2 -2
  30. package/dist/migrate/ddl/tableDdl.js +2 -2
  31. package/dist/migrate/indexPredicate.d.ts +4 -3
  32. package/dist/migrate/indexPredicate.js +5 -5
  33. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +2 -6
  34. package/dist/migrate/schemaGenerator.js +1 -1
  35. package/dist/migrate/triggerSql.js +7 -5
  36. package/dist/mongodb/mongoDialect.js +17 -41
  37. package/dist/mongodb/mongoSchemaGenerator.js +12 -12
  38. package/dist/mongodb/mongodbQuerier.d.ts +4 -3
  39. package/dist/mongodb/mongodbQuerier.js +75 -102
  40. package/dist/mssql/mssqlDialect.js +2 -7
  41. package/dist/mssql/mssqlQuerier.d.ts +9 -3
  42. package/dist/mssql/mssqlQuerier.js +9 -11
  43. package/dist/mysql/mysql2Querier.d.ts +11 -2
  44. package/dist/mysql/mysql2Querier.js +4 -7
  45. package/dist/neon/index.d.ts +2 -0
  46. package/dist/neon/index.js +2 -0
  47. package/dist/neon/neonDialect.d.ts +7 -0
  48. package/dist/neon/neonDialect.js +8 -0
  49. package/dist/neon/neonQuerier.d.ts +26 -0
  50. package/dist/neon/neonQuerier.js +47 -0
  51. package/dist/neon/neonQuerierPool.d.ts +12 -2
  52. package/dist/neon/neonQuerierPool.js +22 -3
  53. package/dist/pglite/pgliteQuerier.d.ts +9 -5
  54. package/dist/pglite/pgliteQuerier.js +7 -11
  55. package/dist/postgres/pgExecution.d.ts +8 -0
  56. package/dist/postgres/pgExecution.js +3 -0
  57. package/dist/postgres/pgQuerier.d.ts +3 -6
  58. package/dist/postgres/pgQuerier.js +3 -7
  59. package/dist/querier/abstractQuerier.d.ts +24 -20
  60. package/dist/querier/abstractQuerier.js +79 -58
  61. package/dist/querier/abstractSqlQuerier.d.ts +42 -28
  62. package/dist/querier/abstractSqlQuerier.js +134 -116
  63. package/dist/querier/queryError.d.ts +2 -0
  64. package/dist/querier/queryError.js +9 -0
  65. package/dist/querier/transaction.js +2 -6
  66. package/dist/schema/canonicalType.d.ts +3 -3
  67. package/dist/schema/canonicalType.js +4 -10
  68. package/dist/sqlite/bindValues.d.ts +10 -0
  69. package/dist/sqlite/bindValues.js +8 -0
  70. package/dist/sqlite/hranaQuerier.d.ts +17 -11
  71. package/dist/sqlite/hranaQuerier.js +16 -5
  72. package/dist/sqlite/index.d.ts +1 -1
  73. package/dist/sqlite/index.js +0 -1
  74. package/dist/sqlite/localSqliteQuerierPool.js +19 -9
  75. package/dist/sqlite/sqliteQuerier.d.ts +9 -4
  76. package/dist/sqlite/sqliteQuerier.js +14 -8
  77. package/dist/turso/tursoSessionQuerier.d.ts +19 -7
  78. package/dist/turso/tursoSessionQuerier.js +31 -20
  79. package/dist/type/dialect.d.ts +3 -0
  80. package/dist/type/querier.d.ts +12 -0
  81. package/dist/type/querier.js +10 -0
  82. package/dist/type/vector.d.ts +2 -1
  83. package/dist/type/vector.js +2 -2
  84. package/dist/util/dialect.util.d.ts +21 -6
  85. package/dist/util/dialect.util.js +34 -9
  86. package/dist/util/filters.util.d.ts +5 -4
  87. package/dist/util/filters.util.js +4 -7
  88. package/dist/util/logger.js +2 -6
  89. package/dist/util/object.util.d.ts +7 -0
  90. package/dist/util/object.util.js +17 -0
  91. package/dist/util/query.util.d.ts +3 -2
  92. package/dist/util/sql.js +1 -1
  93. package/dist/util/sql.util.d.ts +15 -15
  94. package/dist/util/sql.util.js +5 -5
  95. package/package.json +7 -7
  96. package/skills/uql-orm/SKILL.md +58 -51
  97. package/dist/sqlite/abstractSqliteQuerier.d.ts +0 -28
  98. package/dist/sqlite/abstractSqliteQuerier.js +0 -36
@@ -1,8 +1,8 @@
1
1
  import { AGGREGATE_VALUE_ALIAS } from '../dialect/aliases.js';
2
2
  import { hasRequiredJoin } from '../dialect/queryJoins.js';
3
- import { fieldOf, getMeta, namesKey, soleIdOf } from '../entity/index.js';
3
+ import { getMeta, soleIdOf } from '../entity/index.js';
4
4
  import { AbstractQuerier } from '../querier/index.js';
5
- import { clone, getKeys, getSoftDeleteValue, hasKeys, hasTriggers, populatesRelations, textSortOf, vectorCandidates, withoutSoftDeleteFilter, whereEach, } from '../util/index.js';
5
+ import { clone, getKeys, deletionOf, hasKeys, hasTriggers, populatesRelations, textSortOf, vectorCandidates, whereEach, upsertKeepsOwnKey, } from '../util/index.js';
6
6
  import { UqlUsageError } from '../util/uqlError.js';
7
7
  /**
8
8
  * `$limit: 0` asks for no rows, the way it does on every SQL dialect - but MongoDB reads `limit(0)`
@@ -38,26 +38,24 @@ export class MongodbQuerier extends AbstractQuerier {
38
38
  this.conn = conn;
39
39
  this.extra = extra;
40
40
  }
41
- async execute(task) {
42
- return this.serialize(async () => {
43
- return task(this.#session);
44
- });
41
+ /** Runs `task` on the open transaction's session, if any, after everything queued before it, timed as `label`. */
42
+ execute(label, task) {
43
+ return this.serialize(() => this.timed(label, undefined, () => task(this.#session)));
45
44
  }
46
45
  async internalFindMany(entity, q, opts) {
47
46
  if (asksForNoRows(q)) {
48
47
  return [];
49
48
  }
50
- return this.timed('internalFindMany', undefined, async () => {
51
- const cursor = this.readCursor(entity, q, opts);
52
- return this.dialect.normalizeIds(getMeta(entity), await this.execute(() => cursor.toArray()));
53
- });
49
+ const docs = await this.execute('internalFindMany', (session) => this.readCursor(entity, q, opts, session).toArray());
50
+ return this.dialect.normalizeIds(getMeta(entity), docs);
54
51
  }
55
52
  async *internalFindManyStream(entity, q, opts) {
56
53
  if (asksForNoRows(q)) {
57
54
  return;
58
55
  }
59
56
  const meta = getMeta(entity);
60
- for await (const doc of this.timedStream('internalFindManyStream', undefined, this.readCursor(entity, q, opts))) {
57
+ const cursor = this.readCursor(entity, q, opts, this.#session);
58
+ for await (const doc of this.timedStream('internalFindManyStream', undefined, cursor)) {
61
59
  yield this.dialect.normalizeId(meta, doc);
62
60
  }
63
61
  }
@@ -66,14 +64,14 @@ export class MongodbQuerier extends AbstractQuerier {
66
64
  * lookup, a grouping, a vector search - and the plain `find` cursor for everything else. One routing
67
65
  * for a read and a stream alike, so both load the same relations.
68
66
  */
69
- readCursor(entity, q, opts) {
67
+ readCursor(entity, q, opts, session) {
70
68
  const vectorSort = this.dialect.extractVectorSort(q.$sort);
71
69
  const pipeline = vectorSort
72
70
  ? this.buildVectorPipeline(entity, q, vectorSort, opts)
73
71
  : this.readsThroughPipeline(entity, q) && this.dialect.aggregationPipeline(entity, q, opts);
74
72
  return pipeline
75
- ? this.collection(entity).aggregate(pipeline, { session: this.#session })
76
- : this.buildFindCursor(entity, q, opts);
73
+ ? this.collection(entity).aggregate(pipeline, { session })
74
+ : this.buildFindCursor(entity, q, opts, session);
77
75
  }
78
76
  /**
79
77
  * Whether a read needs stages a `find` cursor cannot express: a lookup to populate, count, filter or
@@ -94,8 +92,8 @@ export class MongodbQuerier extends AbstractQuerier {
94
92
  return this.dialect.select(entity, q.$select, q.$exclude);
95
93
  }
96
94
  /** Build a MongoDB FindCursor with filter, projection, sort, skip, and limit from the query. */
97
- buildFindCursor(entity, q, opts) {
98
- const cursor = this.collection(entity).find({}, { session: this.#session });
95
+ buildFindCursor(entity, q, opts, session) {
96
+ const cursor = this.collection(entity).find({}, { session });
99
97
  const filter = this.dialect.where(entity, q.$where, opts);
100
98
  if (hasKeys(filter)) {
101
99
  cursor.filter(filter);
@@ -133,11 +131,9 @@ export class MongodbQuerier extends AbstractQuerier {
133
131
  ];
134
132
  }
135
133
  async internalAggregate(entity, q, opts) {
136
- return this.timed('internalAggregate', undefined, async () => {
137
- const pipeline = this.dialect.buildAggregateStages(entity, q, opts);
138
- const rows = await this.execute((session) => this.collection(entity).aggregate(pipeline, { session }).toArray());
139
- return this.dialect.normalizeAggregateRows(entity, q, rows);
140
- });
134
+ const pipeline = this.dialect.buildAggregateStages(entity, q, opts);
135
+ const rows = await this.execute('internalAggregate', (session) => this.collection(entity).aggregate(pipeline, { session }).toArray());
136
+ return this.dialect.normalizeAggregateRows(entity, q, rows);
141
137
  }
142
138
  /**
143
139
  * A `$required` relation drops parents that have no match, and `$distinct` collapses them, so both
@@ -151,7 +147,7 @@ export class MongodbQuerier extends AbstractQuerier {
151
147
  const { $sort: _sort, $skip: _skip, $limit: _limit, ...unpaged } = q;
152
148
  const [founds, counted] = await Promise.all([
153
149
  this.internalFindMany(entity, q, opts),
154
- this.execute((session) => this.collection(entity)
150
+ this.execute('internalFindManyAndCount', (session) => this.collection(entity)
155
151
  .aggregate([...this.dialect.aggregationPipeline(entity, unpaged, opts), { $count: AGGREGATE_VALUE_ALIAS }], { session })
156
152
  .toArray()),
157
153
  ]);
@@ -162,47 +158,39 @@ export class MongodbQuerier extends AbstractQuerier {
162
158
  if (asksForNoRows(q)) {
163
159
  return 0;
164
160
  }
165
- return this.timed('internalCount', undefined, async () => {
166
- const pipeline = [
167
- ...this.dialect.matchStages(entity, q.$where, opts),
168
- ...this.dialect.pagerStages(q),
169
- { $count: AGGREGATE_VALUE_ALIAS },
170
- ];
171
- const [counted] = await this.execute((session) => this.collection(entity)
172
- .aggregate(pipeline, { session })
173
- .toArray());
174
- return counted?.[AGGREGATE_VALUE_ALIAS] ?? 0;
175
- });
161
+ const pipeline = [
162
+ ...this.dialect.matchStages(entity, q.$where, opts),
163
+ ...this.dialect.pagerStages(q),
164
+ { $count: AGGREGATE_VALUE_ALIAS },
165
+ ];
166
+ const [counted] = await this.execute('internalCount', (session) => this.collection(entity).aggregate(pipeline, { session }).toArray());
167
+ return counted?.[AGGREGATE_VALUE_ALIAS] ?? 0;
176
168
  }
177
169
  /**
178
170
  * The collection's metadata count, which the driver exposes as its own call and which takes no
179
171
  * filter - the reason {@link UniversalQuerier.estimatedCount} takes none either.
180
172
  */
181
173
  async estimatedCount(entity) {
182
- return this.timed('estimatedCount', undefined, async () => this.execute((session) => this.collection(entity).estimatedDocumentCount({ session })));
174
+ return this.execute('estimatedCount', (session) => this.collection(entity).estimatedDocumentCount({ session }));
183
175
  }
184
176
  async internalInsertMany(entity, rows) {
185
177
  refuseTriggers(entity);
186
- return this.timed('internalInsertMany', undefined, async () => {
187
- const meta = getMeta(entity);
188
- const persistables = this.dialect.getPersistables(meta, rows, 'onInsert');
189
- const { insertedIds } = await this.execute((session) => this.collection(entity).insertMany(persistables, { session }));
190
- const ids = Object.values(insertedIds).map((id) => this.dialect.fromWireId(id));
191
- const idKey = soleIdOf(meta, 'insert');
192
- for (let index = 0; index < rows.length; index++) {
193
- rows[index][idKey] = ids[index];
194
- }
195
- });
178
+ const meta = getMeta(entity);
179
+ const persistables = this.dialect.getPersistables(meta, rows, 'onInsert');
180
+ const { insertedIds } = await this.execute('internalInsertMany', (session) => this.collection(entity).insertMany(persistables, { session }));
181
+ const ids = Object.values(insertedIds).map((id) => this.dialect.fromWireId(id));
182
+ const idKey = soleIdOf(meta, 'insert');
183
+ for (let index = 0; index < rows.length; index++) {
184
+ rows[index][idKey] = ids[index];
185
+ }
196
186
  }
197
187
  async internalUpdateMany(entity, qm, payload, opts) {
198
188
  refuseTriggers(entity);
199
- return this.timed('internalUpdateMany', undefined, async () => {
200
- const persistable = this.dialect.getPersistable(getMeta(entity), payload, 'onUpdate');
201
- const filter = this.dialect.where(entity, qm.$where, opts);
202
- const update = this.dialect.getUpdateFilter(persistable);
203
- const { matchedCount } = await this.execute((session) => this.collection(entity).updateMany(filter, update, { session }));
204
- return matchedCount;
205
- });
189
+ const persistable = this.dialect.getPersistable(getMeta(entity), payload, 'onUpdate');
190
+ const filter = this.dialect.where(entity, qm.$where, opts);
191
+ const update = this.dialect.getUpdateFilter(persistable);
192
+ const { matchedCount } = await this.execute('internalUpdateMany', (session) => this.collection(entity).updateMany(filter, update, { session }));
193
+ return matchedCount;
206
194
  }
207
195
  /**
208
196
  * What an upsert writes, as SQL's does: a found document takes the payload and the `onUpdate` fills, and only
@@ -225,13 +213,14 @@ export class MongodbQuerier extends AbstractQuerier {
225
213
  return this.dialect.where(entity, whereEach(getKeys(conflictPaths), (key) => item[key]));
226
214
  }
227
215
  /**
228
- * An upsert whose conflicting document takes `update`, which no single call pairs with inserting the payload:
229
- * `$setOnInsert` and `$inc` on one field conflict. So the row inserts if absent, and a document it found,
230
- * a concurrent one included, then takes `update`.
216
+ * An upsert of `row` whose found document takes `update`, which no single call pairs with inserting the payload:
217
+ * `$setOnInsert` and `$inc` on one field conflict. So the row inserts if absent, and a document it found, a
218
+ * concurrent one included, then takes `update`.
231
219
  */
232
220
  async upsertWithUpdate(entity, conflictPaths, row, update) {
233
221
  const persistable = this.dialect.getPersistable(getMeta(entity), clone(row), 'onInsert');
234
- const res = await this.execute((session) => this.collection(entity).findOneAndUpdate(this.buildConflictFilter(entity, conflictPaths, row), { $setOnInsert: persistable }, { upsert: true, returnDocument: 'after', includeResultMetadata: true, session }));
222
+ const filter = this.buildConflictFilter(entity, conflictPaths, row);
223
+ const res = await this.execute('upsertMany', (session) => this.collection(entity).findOneAndUpdate(filter, { $setOnInsert: persistable }, { upsert: true, returnDocument: 'after', includeResultMetadata: true, session }));
235
224
  // `updatedExisting` is false where the document was inserted; an empty `update` leaves a found one
236
225
  // as it is, as `DO NOTHING` does.
237
226
  if (res.lastErrorObject?.['updatedExisting'] && hasKeys(update)) {
@@ -248,63 +237,47 @@ export class MongodbQuerier extends AbstractQuerier {
248
237
  }
249
238
  return ids;
250
239
  }
251
- return this.timed('upsertMany', undefined, async () => {
252
- if (!payload.length) {
253
- return [];
254
- }
255
- const meta = getMeta(entity);
256
- // Asked before `getPersistable` fills an `onInsert` key into rows it may only update.
257
- const unnamed = payload.map((row) => !namesKey(meta, row));
258
- const operations = payload.map((item) => ({
259
- updateOne: {
260
- filter: this.buildConflictFilter(entity, conflictPaths, item),
261
- update: this.upsertUpdate(meta, item),
262
- upsert: true,
263
- },
264
- }));
265
- const res = await this.execute((session) => this.collection(entity).bulkWrite(operations, { session }));
266
- // `upsertedIds` names only the documents inserted, keyed by operation index, so each lands on
267
- // its own row; an updated document's `_id` is read back by the conflict fields instead.
268
- const reported = payload.map((_, index) => {
269
- const id = res.upsertedIds[index];
270
- return id === undefined ? undefined : this.dialect.fromWireId(id);
271
- });
272
- const unplaced = reported.some((id, index) => id === undefined && unnamed[index]);
273
- const found = unplaced ? await this.idsByConflict(entity, conflictPaths, payload) : [];
274
- return reported.map((id, index) => id ?? found[index]);
240
+ if (!payload.length) {
241
+ return [];
242
+ }
243
+ const meta = getMeta(entity);
244
+ const kept = payload.map((row) => upsertKeepsOwnKey(meta, conflictPaths, row));
245
+ const operations = payload.map((item) => ({
246
+ updateOne: {
247
+ filter: this.buildConflictFilter(entity, conflictPaths, item),
248
+ update: this.upsertUpdate(meta, item),
249
+ upsert: true,
250
+ },
251
+ }));
252
+ const res = await this.execute('upsertMany', (session) => this.collection(entity).bulkWrite(operations, { session }));
253
+ // `upsertedIds` names only the documents inserted, keyed by operation index, so each lands on
254
+ // its own row; an updated document's `_id` is read back by the conflict fields instead.
255
+ const reported = payload.map((_, index) => {
256
+ const id = res.upsertedIds[index];
257
+ return id === undefined ? undefined : this.dialect.fromWireId(id);
275
258
  });
259
+ return this.withUnreportedIds(entity, conflictPaths, payload, reported, kept);
276
260
  }
277
261
  async internalDeleteMany(entity, qm, opts = {}) {
278
262
  refuseTriggers(entity);
279
- return this.timed('internalDeleteMany', undefined, async () => {
280
- const meta = getMeta(entity);
281
- // Soft-delete (stamp) unless `hardDelete` is requested or the entity has no soft-delete field.
282
- const softDelete = opts.hardDelete ? undefined : meta.softDelete;
283
- if (!softDelete) {
284
- const filter = this.dialect.where(entity, qm.$where, {
285
- ...opts,
286
- filters: withoutSoftDeleteFilter(opts.filters),
287
- });
288
- const { deletedCount } = await this.execute((session) => this.collection(entity).deleteMany(filter, { session }));
289
- return deletedCount;
290
- }
291
- const field = fieldOf(meta, softDelete);
292
- // The mapped column, which reads filter on: a `@Field({ name })` mismatch would leave the row visible.
293
- const column = this.dialect.resolveColumnName(softDelete, field);
294
- const update = { $set: { [column]: getSoftDeleteValue(field) } };
295
- const filter = this.dialect.where(entity, qm.$where, opts);
296
- const { matchedCount } = await this.execute((session) => this.collection(entity).updateMany(filter, update, { session }));
297
- return matchedCount;
298
- });
263
+ const { stamp, opts: read } = deletionOf(getMeta(entity), opts);
264
+ const filter = this.dialect.where(entity, qm.$where, read);
265
+ if (!stamp) {
266
+ const { deletedCount } = await this.execute('internalDeleteMany', (session) => this.collection(entity).deleteMany(filter, { session }));
267
+ return deletedCount;
268
+ }
269
+ // The mapped column, which reads filter on: a `@Field({ name })` mismatch would leave the row visible.
270
+ const column = this.dialect.resolveColumnName(stamp.key, stamp.field);
271
+ const update = { $set: { [column]: stamp.value() } };
272
+ const { matchedCount } = await this.execute('internalDeleteMany', (session) => this.collection(entity).updateMany(filter, update, { session }));
273
+ return matchedCount;
299
274
  }
300
275
  get hasOpenTransaction() {
301
276
  return !!this.#session?.inTransaction();
302
277
  }
303
278
  /** Every read and write goes through here, which makes it where a released querier is caught. */
304
279
  collection(entity) {
305
- if (this.released) {
306
- throw new UqlUsageError('querier already released');
307
- }
280
+ this.assertActive();
308
281
  const { name } = getMeta(entity);
309
282
  return this.db.collection(name);
310
283
  }
@@ -4,6 +4,7 @@ import { BYTES_PREFIX } from '../dialect/hydrateColumn.js';
4
4
  import { skippablePath, jsonArraySlotArgs, jsonPath, jsonSlotArgs, } from '../dialect/jsonSql.js';
5
5
  import { MergeSqlDialect } from '../dialect/mergeSqlDialect.js';
6
6
  import { getMeta } from '../entity/index.js';
7
+ import { soleId } from '../entity/metadata/definition.js';
7
8
  import { canonicalToSql, resolveColumnCanonicalType } from '../schema/canonicalType.js';
8
9
  import { QuerySql } from '../type/index.js';
9
10
  import { parseQueryLock } from '../type/index.js';
@@ -67,12 +68,6 @@ function openJsonType(value) {
67
68
  }
68
69
  return typeof value === 'boolean' ? OPENJSON_TYPE.boolean : OPENJSON_TYPE.string;
69
70
  }
70
- /** The one key column and its field, or nothing on a composite key. */
71
- function soleId(meta) {
72
- const [key] = meta.ids;
73
- const field = meta.ids.length === 1 ? meta.fields[key] : undefined;
74
- return field && { key, field };
75
- }
76
71
  /** Microsoft SQL Server 2017 and up. Identifiers are `"`-quoted, the ANSI spelling `tedious` enables. */
77
72
  export class MsSqlDialect extends MergeSqlDialect {
78
73
  features = MSSQL_FEATURES;
@@ -403,7 +398,7 @@ export class MsSqlDialect extends MergeSqlDialect {
403
398
  jsonSet(ctx, expr, set) {
404
399
  for (const [key, value] of Object.entries(set)) {
405
400
  if (value === null) {
406
- throw new UqlUsageError(`mssql cannot $set '${key}' to null: JSON_MODIFY deletes the key instead. Use $unset, or store a JSON null through a whole-column write.`);
401
+ throw new UqlUsageError(`SQL Server cannot $set '${key}' to null: JSON_MODIFY deletes the key instead. Use $unset, or store a JSON null through a whole-column write.`);
407
402
  }
408
403
  }
409
404
  return Object.entries(set).reduce((acc, [key, value]) => `JSON_MODIFY(${acc}, ${jsonPath(key)}, ${this.jsonWriteParam(ctx, value)})`, expr);
@@ -1,6 +1,6 @@
1
1
  import mssql from 'mssql';
2
2
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
- import type { QueryUpdateResult, RawRow, TransactionOptions } from '../type/index.js';
3
+ import type { RawRow, TransactionOptions } from '../type/index.js';
4
4
  /** What `tedious` hands back for one statement, whichever shape it took. */
5
5
  type MsSqlResult = {
6
6
  recordset?: RawRow[] & {
@@ -42,8 +42,14 @@ export type MsSqlConnection = {
42
42
  */
43
43
  export declare class MsSqlQuerier extends AbstractPoolQuerier<MsSqlConnection> {
44
44
  #private;
45
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
46
- internalRun(query: string, values?: unknown[]): Promise<QueryUpdateResult>;
45
+ /**
46
+ * `rowsAffected` carries one entry per statement, and a write runs in a batch of several - the table variable
47
+ * its ids go through, the read handing them back uncounted - so the counts are summed.
48
+ */
49
+ protected execute(sql: string, values?: unknown[]): Promise<{
50
+ rows: RawRow[];
51
+ changes: number;
52
+ }>;
47
53
  /**
48
54
  * The driver's own stream over the request, which pauses the request while the loop is behind, so
49
55
  * rows arrive only as fast as they are read. A failure the driver reports through the promise alone
@@ -21,18 +21,16 @@ export class MsSqlQuerier extends AbstractPoolQuerier {
21
21
  });
22
22
  return request;
23
23
  }
24
- async internalAll(query, values) {
25
- const res = await this.#request(values).query(query);
26
- return decodeWireTypes(res.recordset, res.recordset?.columns);
27
- }
28
- async internalRun(query, values) {
29
- const res = await this.#request(values).query(query);
30
- return this.buildUpdateResult({
31
- // `rowsAffected` carries one entry per statement, and a write runs in a batch of several - the table
32
- // variable its ids go through, the read handing them back uncounted - so the counts are summed.
33
- changes: res.rowsAffected.reduce((total, count) => total + count, 0),
24
+ /**
25
+ * `rowsAffected` carries one entry per statement, and a write runs in a batch of several - the table variable
26
+ * its ids go through, the read handing them back uncounted - so the counts are summed.
27
+ */
28
+ async execute(sql, values) {
29
+ const res = await this.#request(values).query(sql);
30
+ return {
34
31
  rows: decodeWireTypes(res.recordset, res.recordset?.columns),
35
- });
32
+ changes: res.rowsAffected.reduce((total, count) => total + count, 0),
33
+ };
36
34
  }
37
35
  /**
38
36
  * The driver's own stream over the request, which pauses the request while the loop is behind, so
@@ -1,12 +1,21 @@
1
1
  import type { PoolConnection } from 'mysql2';
2
+ import type { RowDataPacket } from 'mysql2/promise';
2
3
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
4
  /**
4
5
  * Holds the driver's own connection rather than its promise wrapper, whose types name the connection
5
6
  * inside it a promise one too: streaming is the own connection's alone.
6
7
  */
7
8
  export declare class MySql2Querier extends AbstractPoolQuerier<PoolConnection> {
8
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
9
- internalRun(query: string, values?: unknown[]): Promise<import("../index.js").QueryUpdateResult>;
9
+ /** A read answers its rows; a write, the header naming how many rows it changed and the first id it generated. */
10
+ protected execute(sql: string, values?: unknown[]): Promise<{
11
+ rows: RowDataPacket[];
12
+ changes?: undefined;
13
+ id?: undefined;
14
+ } | {
15
+ rows: never[];
16
+ changes: number;
17
+ id: number;
18
+ }>;
10
19
  internalStream(query: string, values?: unknown[]): AsyncGenerator<any, void, any>;
11
20
  protected releaseConn(conn: PoolConnection, discard: boolean): Promise<void>;
12
21
  }
@@ -4,13 +4,10 @@ import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
4
4
  * inside it a promise one too: streaming is the own connection's alone.
5
5
  */
6
6
  export class MySql2Querier extends AbstractPoolQuerier {
7
- async internalAll(query, values) {
8
- const [res] = await this.getConn().promise().query(query, values);
9
- return res;
10
- }
11
- async internalRun(query, values) {
12
- const [res] = await this.getConn().promise().query(query, values);
13
- return this.buildUpdateResult({ changes: res.affectedRows, id: res.insertId });
7
+ /** A read answers its rows; a write, the header naming how many rows it changed and the first id it generated. */
8
+ async execute(sql, values) {
9
+ const [res] = await this.getConn().promise().query(sql, values);
10
+ return Array.isArray(res) ? { rows: res } : { rows: [], changes: res.affectedRows, id: res.insertId };
14
11
  }
15
12
  async *internalStream(query, values) {
16
13
  yield* this.getConn().query(query, values).stream();
@@ -1 +1,3 @@
1
+ export * from './neonDialect.js';
2
+ export * from './neonQuerier.js';
1
3
  export * from './neonQuerierPool.js';
@@ -1 +1,3 @@
1
+ export * from './neonDialect.js';
2
+ export * from './neonQuerier.js';
1
3
  export * from './neonQuerierPool.js';
@@ -0,0 +1,7 @@
1
+ import { PostgresDialect } from '../postgres/postgresDialect.js';
2
+ import type { EngineName } from '../type/querier.js';
3
+ /** Postgres as Neon serves it: its proxy binds at most 32,767 values a statement over HTTP, half what Postgres takes. */
4
+ export declare class NeonDialect extends PostgresDialect {
5
+ get engineName(): EngineName;
6
+ readonly maxBindValues: number;
7
+ }
@@ -0,0 +1,8 @@
1
+ import { PostgresDialect } from '../postgres/postgresDialect.js';
2
+ /** Postgres as Neon serves it: its proxy binds at most 32,767 values a statement over HTTP, half what Postgres takes. */
3
+ export class NeonDialect extends PostgresDialect {
4
+ get engineName() {
5
+ return 'Neon';
6
+ }
7
+ maxBindValues = 32_767;
8
+ }
@@ -0,0 +1,26 @@
1
+ import type { CustomTypesConfig, NeonQueryFunction, PoolClient } from '@neondatabase/serverless';
2
+ import { PgQuerier } from '../postgres/pgQuerier.js';
3
+ import type { BoundStatement } from '../querier/index.js';
4
+ import type { ExtraOptions, TransactionOptions } from '../type/index.js';
5
+ import type { SqlExecution } from '../util/sql.util.js';
6
+ import type { NeonDialect } from './neonDialect.js';
7
+ /** Neon's HTTP query function, answering each statement's whole result: what a statement goes through outside a session. */
8
+ export type NeonHttp = NeonQueryFunction<false, true>;
9
+ /**
10
+ * Querier for Neon, over HTTP first: a statement is one request, and a list one request running it as a
11
+ * transaction. A WebSocket session, taken from the pool for what one request cannot hold (a transaction a
12
+ * callback runs in, a stream's loop), serves the querier until it is released. Every query passes the pool's
13
+ * `types` itself, since `neon()` ignores them, so a row decodes as it does over the session.
14
+ */
15
+ export declare class NeonQuerier extends PgQuerier<PoolClient> {
16
+ private readonly http;
17
+ private readonly types;
18
+ constructor(http: NeonHttp, types: CustomTypesConfig, connect: () => Promise<PoolClient>, dialect: NeonDialect, extra?: ExtraOptions);
19
+ /** Connects nothing: a statement goes over HTTP until a session holds the connection. */
20
+ protected lazyConnect(): Promise<void>;
21
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
22
+ /** A list as one HTTP transaction, all or none; inside an open transaction, in turn on its session, which it joins. */
23
+ protected executeBatch(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
24
+ protected openTransaction(opts?: TransactionOptions): Promise<void>;
25
+ internalStream(query: string, values?: unknown[]): AsyncGenerator<import("../type/utility.js").RawRow, void, any>;
26
+ }
@@ -0,0 +1,47 @@
1
+ import { pgExecution } from '../postgres/pgExecution.js';
2
+ import { PgQuerier } from '../postgres/pgQuerier.js';
3
+ /**
4
+ * Querier for Neon, over HTTP first: a statement is one request, and a list one request running it as a
5
+ * transaction. A WebSocket session, taken from the pool for what one request cannot hold (a transaction a
6
+ * callback runs in, a stream's loop), serves the querier until it is released. Every query passes the pool's
7
+ * `types` itself, since `neon()` ignores them, so a row decodes as it does over the session.
8
+ */
9
+ export class NeonQuerier extends PgQuerier {
10
+ http;
11
+ types;
12
+ constructor(http, types, connect, dialect, extra) {
13
+ super(connect, dialect, extra);
14
+ this.http = http;
15
+ this.types = types;
16
+ }
17
+ /** Connects nothing: a statement goes over HTTP until a session holds the connection. */
18
+ async lazyConnect() {
19
+ this.assertActive();
20
+ }
21
+ async execute(sql, values) {
22
+ if (this.conn) {
23
+ return super.execute(sql, values);
24
+ }
25
+ return pgExecution(await this.http.query(sql, values, { types: this.types }));
26
+ }
27
+ /** A list as one HTTP transaction, all or none; inside an open transaction, in turn on its session, which it joins. */
28
+ async executeBatch(statements) {
29
+ if (this.hasOpenTransaction) {
30
+ const results = [];
31
+ for (const { sql, values } of statements) {
32
+ results.push(await super.execute(sql, values));
33
+ }
34
+ return results;
35
+ }
36
+ const results = await this.http.transaction(statements.map(({ sql, values }) => this.http.query(sql, values, { types: this.types })));
37
+ return results.map(pgExecution);
38
+ }
39
+ async openTransaction(opts) {
40
+ await super.lazyConnect();
41
+ await super.openTransaction(opts);
42
+ }
43
+ async *internalStream(query, values) {
44
+ await super.lazyConnect();
45
+ yield* super.internalStream(query, values);
46
+ }
47
+ }
@@ -1,8 +1,18 @@
1
1
  import { Pool, type PoolClient, type PoolConfig } from '@neondatabase/serverless';
2
2
  import { AbstractPgQuerierPool } from '../postgres/abstractPgQuerierPool.js';
3
- import { PostgresDialect } from '../postgres/postgresDialect.js';
3
+ import { PgQuerier } from '../postgres/pgQuerier.js';
4
4
  import type { ExtraOptions } from '../type/index.js';
5
- export declare class NeonQuerierPool extends AbstractPgQuerierPool<PoolClient, PostgresDialect> {
5
+ import { NeonDialect } from './neonDialect.js';
6
+ import { NeonQuerier } from './neonQuerier.js';
7
+ /**
8
+ * Pool for Neon, over HTTP first: its queriers send statements and lists over HTTP, taking a WebSocket session
9
+ * from its `pool` only for a transaction or a stream. A migration runs on a session throughout, since its lock
10
+ * is the session's. [The design](../../../../architecture/split-writes.md).
11
+ */
12
+ export declare class NeonQuerierPool extends AbstractPgQuerierPool<PoolClient, NeonDialect> {
13
+ #private;
6
14
  readonly pool: Pool;
7
15
  constructor(opts: PoolConfig, extra?: ExtraOptions);
16
+ getQuerier(): Promise<NeonQuerier>;
17
+ getMigrationQuerier(): Promise<PgQuerier<PoolClient>>;
8
18
  }
@@ -1,11 +1,30 @@
1
- import { Pool, types } from '@neondatabase/serverless';
1
+ import { neon, Pool, types } from '@neondatabase/serverless';
2
2
  import { dialectOptionsFrom } from '../dialect/abstractDialect.js';
3
3
  import { AbstractPgQuerierPool } from '../postgres/abstractPgQuerierPool.js';
4
+ import { PgQuerier } from '../postgres/pgQuerier.js';
4
5
  import { wireTypes } from '../postgres/pgWireTypes.js';
5
- import { PostgresDialect } from '../postgres/postgresDialect.js';
6
+ import { NeonDialect } from './neonDialect.js';
7
+ import { NeonQuerier } from './neonQuerier.js';
8
+ /**
9
+ * Pool for Neon, over HTTP first: its queriers send statements and lists over HTTP, taking a WebSocket session
10
+ * from its `pool` only for a transaction or a stream. A migration runs on a session throughout, since its lock
11
+ * is the session's. [The design](../../../../architecture/split-writes.md).
12
+ */
6
13
  export class NeonQuerierPool extends AbstractPgQuerierPool {
14
+ #http;
15
+ #types;
7
16
  constructor(opts, extra) {
8
17
  // Neon's own `types`, not `pg`'s: this entry has to load on an edge runtime where `pg` is absent.
9
- super(new PostgresDialect(dialectOptionsFrom(extra)), new Pool({ types: wireTypes(types), ...opts }), extra);
18
+ const wire = opts.types ?? wireTypes(types);
19
+ super(new NeonDialect(dialectOptionsFrom(extra)), new Pool({ ...opts, types: wire }), extra);
20
+ const { connectionString, host, port, user, password, database } = opts;
21
+ this.#http = neon({ connectionString, host, port, user, password, database, fullResults: true });
22
+ this.#types = wire;
23
+ }
24
+ async getQuerier() {
25
+ return new NeonQuerier(this.#http, this.#types, () => this.pool.connect(), this.dialect, this.extra);
26
+ }
27
+ async getMigrationQuerier() {
28
+ return new PgQuerier(() => this.pool.connect(), this.dialect, this.extra);
10
29
  }
11
30
  }
@@ -1,5 +1,5 @@
1
1
  import { AbstractSqlQuerier } from '../querier/index.js';
2
- import type { ExtraOptions } from '../type/index.js';
2
+ import type { ExtraOptions, RawRow } from '../type/index.js';
3
3
  import type { PgliteDialect } from './pgliteDialect.js';
4
4
  /** The two methods uql uses of `@electric-sql/pglite`, stated so its published types do not depend on a pre-1.0 package. */
5
5
  export type PgliteDatabase = {
@@ -21,8 +21,12 @@ export declare class PgliteQuerier extends AbstractSqlQuerier {
21
21
  constructor(db: PgliteDatabase, dialect: PgliteDialect, extra?: ExtraOptions | undefined);
22
22
  /** Every querier of the pool is this one handle's session, so they share its transaction. */
23
23
  protected get connection(): object;
24
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
25
- internalRun(query: string, values?: unknown[]): Promise<import("../type/query.js").QueryUpdateResult>;
26
- /** The handle belongs to the pool, which hands out one querier per unit of work over it. */
27
- internalRelease(): Promise<void>;
24
+ /**
25
+ * `affectedRows`, not `rowCount`: PGlite derives the former from the command tag of a write only, where the
26
+ * latter also counts a `SELECT`'s rows and is absent altogether from a DDL tag.
27
+ */
28
+ protected execute(sql: string, values?: unknown[]): Promise<{
29
+ rows: RawRow[];
30
+ changes: number | undefined;
31
+ }>;
28
32
  }
@@ -17,16 +17,12 @@ export class PgliteQuerier extends AbstractSqlQuerier {
17
17
  get connection() {
18
18
  return this.db;
19
19
  }
20
- async internalAll(query, values) {
21
- const res = await this.db.query(query, values);
22
- return res.rows;
20
+ /**
21
+ * `affectedRows`, not `rowCount`: PGlite derives the former from the command tag of a write only, where the
22
+ * latter also counts a `SELECT`'s rows and is absent altogether from a DDL tag.
23
+ */
24
+ async execute(sql, values) {
25
+ const { rows, affectedRows } = await this.db.query(sql, values);
26
+ return { rows, changes: affectedRows };
23
27
  }
24
- async internalRun(query, values) {
25
- const res = await this.db.query(query, values);
26
- // `affectedRows`, not `rowCount`: PGlite derives the former from the command tag of a write only,
27
- // where the latter also counts a `SELECT`'s rows and is absent altogether from a DDL tag.
28
- return this.buildUpdateResult({ rows: res.rows, changes: res.affectedRows });
29
- }
30
- /** The handle belongs to the pool, which hands out one querier per unit of work over it. */
31
- async internalRelease() { }
32
28
  }