kern-orm 0.5.0 → 0.6.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.
@@ -1,4 +1,5 @@
1
- import { B as trueNode, C as toNode, D as isType, E as defineType, F as createNode, I as createSelectNode, L as falseNode, M as valuesQueryNode, O as Column, P as createList, R as noFilters, S as toFunctionOperandNode, T as getBooleanType, _ as isOperandSource, a as stringifyJson, b as toCastValueNode, d as orderingOperators, g as isExpression, h as getType, j as isEqualityCompatible, m as createIsNullNode, n as text, p as compareNodes, s as encodeBytea, v as operandNode, w as toValueNode, x as toExpression, y as toBooleanExpression, z as oneNode } from "./text-BTFErHIi.mjs";
1
+ import { B as noOrder, C as toNode, D as isType, E as defineType, F as createNode, H as oneNode, I as createSelectNode, L as falseNode, M as valuesQueryNode, O as Column, P as createList, R as noFilters, S as toFunctionOperandNode, T as getBooleanType, U as trueNode, V as noProjections, _ as isOperandSource, a as stringifyJson, b as toCastValueNode, d as orderingOperators, g as isExpression, h as getType, j as isEqualityCompatible, m as createIsNullNode, n as text, p as compareNodes, s as encodeBytea, v as operandNode, w as toValueNode, x as toExpression, y as toBooleanExpression, z as noJoins } from "./text-Cti9QLK7.mjs";
2
+ import { types } from "node:util";
2
3
  import { AsyncLocalStorage } from "node:async_hooks";
3
4
  // src/ast/boolean.ts
4
5
  /** Combines predicate nodes with `AND` or `OR`, flattening nested groups of the same kind. */
@@ -173,6 +174,12 @@ const aggregateDefinitions = /* @__PURE__ */ Object.freeze({
173
174
  type: toArgumentType
174
175
  }
175
176
  });
177
+ /** Argument `*` of `count(*)`. */
178
+ const allRowsNode = /* @__PURE__ */ createNode({
179
+ kind: "raw",
180
+ fragments: ["*"],
181
+ values: []
182
+ });
176
183
  /** Projection of `count(*)`, which `count` without an argument selects; its value does not depend on the values or the order of the rows. */
177
184
  const countProjection = /* @__PURE__ */ Object.freeze({
178
185
  key: "count",
@@ -180,12 +187,9 @@ const countProjection = /* @__PURE__ */ Object.freeze({
180
187
  kind: "aggregate",
181
188
  name: "count",
182
189
  distinct: false,
183
- arguments: [/* @__PURE__ */ createNode({
184
- kind: "raw",
185
- fragments: ["*"],
186
- values: []
187
- })],
188
- orderBy: []
190
+ arguments: [allRowsNode],
191
+ orderBy: noOrder,
192
+ filter: void 0
189
193
  }),
190
194
  type: countType,
191
195
  ordered: false,
@@ -197,27 +201,51 @@ const countProjection = /* @__PURE__ */ Object.freeze({
197
201
  * `delimiter` is the delimiter of `stringAgg`, sent as a parameter.
198
202
  */
199
203
  function projectAggregate(method, argument, delimiter) {
204
+ return Object.freeze({
205
+ key: method,
206
+ expression: createAggregateCall(method, argument.expression, delimiter),
207
+ type: toAggregateType(method, argument.type),
208
+ ordered: aggregateDefinitions[method].ordered,
209
+ fallbacks: noFallbacks
210
+ });
211
+ }
212
+ /**
213
+ * Creates the call of the aggregate function of `method` over the values of `argument`.
214
+ *
215
+ * `delimiter` is the delimiter of `stringAgg`, sent as a parameter, `orderBy` the order of the rows that the function takes, and `filter` their condition.
216
+ */
217
+ function createAggregateCall(method, argument, delimiter, orderBy = noOrder, filter) {
200
218
  const definition = aggregateDefinitions[method];
201
- const args = [argument.expression];
219
+ const args = [argument];
202
220
  if (delimiter !== void 0) args.push(createNode({
203
221
  kind: "param",
204
222
  value: delimiter,
205
223
  type: void 0
206
224
  }));
207
- return Object.freeze({
208
- key: method,
209
- expression: createNode({
210
- kind: "aggregate",
211
- name: definition.name,
212
- distinct: definition.distinct,
213
- arguments: args,
214
- orderBy: []
215
- }),
216
- type: definition.type(argument.type),
217
- ordered: definition.ordered,
218
- fallbacks: noFallbacks
225
+ return createNode({
226
+ kind: "aggregate",
227
+ name: definition.name,
228
+ distinct: definition.distinct,
229
+ arguments: args,
230
+ orderBy,
231
+ filter
232
+ });
233
+ }
234
+ /** Creates the call of `count(*)` over the rows that `filter` takes. */
235
+ function createCountCall(filter) {
236
+ return createNode({
237
+ kind: "aggregate",
238
+ name: "count",
239
+ distinct: false,
240
+ arguments: [allRowsNode],
241
+ orderBy: noOrder,
242
+ filter
219
243
  });
220
244
  }
245
+ /** Returns the type that decodes the value of the aggregate of `method` over the values of type `argument`, rejecting what `method` cannot decode, such as `avg` of a type of the SQL type `bigint`. */
246
+ function toAggregateType(method, argument) {
247
+ return aggregateDefinitions[method].type(argument);
248
+ }
221
249
  /** Creates the projection of the aggregate of `field` whose `NULL` `fallback` replaces after its earlier fallbacks. */
222
250
  function addFallback(field, fallback) {
223
251
  const fallbacks = field.fallbacks.slice();
@@ -234,9 +262,9 @@ function addFallback(field, fallback) {
234
262
  function isAggregateQuery(node) {
235
263
  return node.value && isAggregateProjection(node.projections[0]);
236
264
  }
237
- /** Tells whether `node`, a nested query, is selected as its value rather than as packed rows: an aggregate query as a scalar subquery of its statement, and a query of `exists` as `EXISTS` of its rows. */
265
+ /** Tells whether `node`, a nested query, is selected as its value rather than as packed rows: an aggregate query as a scalar subquery of its statement, and a query of `exists` as `EXISTS` of its rows, unless `map` or `transform` converts its value. */
238
266
  function isSelectedAsValue(node) {
239
- return isAggregateQuery(node) || isExistsQuery(node);
267
+ return node.conversion === void 0 && (isAggregateQuery(node) || isExistsQuery(node));
240
268
  }
241
269
  /** Tells whether a selected field is the projection of an aggregate, which only the aggregate methods select. */
242
270
  function isAggregateProjection(field) {
@@ -289,6 +317,21 @@ function createSelectionRefs(source, context) {
289
317
  }), columns[key].type);
290
318
  return Object.defineProperties(refs, context.relations);
291
319
  }
320
+ // src/ast/projections.ts
321
+ /**
322
+ * Returns the position of the projection that has the value of `expression`, such as a sort expression or a key of a group: a projection of the same value, as `isSameValue` tells, or `-1`.
323
+ */
324
+ function findValueProjection(projections, expression) {
325
+ return projections.findIndex((projection) => isSameValue(projection.expression, expression));
326
+ }
327
+ /**
328
+ * Tells whether `left` and `right` are sure to have the same value: they are the same column of the same source or the same expression node.
329
+ *
330
+ * Only the same node or column guarantees one value: PostgreSQL may or may not evaluate equal expressions built apart once, and gives each its own parameters.
331
+ */
332
+ function isSameValue(left, right) {
333
+ return left.kind === "column" && right.kind === "column" ? left.source === right.source && left.key === right.key : left === right;
334
+ }
292
335
  // src/result/result.ts
293
336
  /** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
294
337
  var NotFoundError = class extends Error {
@@ -315,7 +358,7 @@ var RequiredRelationError = class extends Error {
315
358
  this.path = path;
316
359
  }
317
360
  };
318
- /** Error thrown when a row does not match the result fields or a value fails to decode; the failure of the value is its cause. */
361
+ /** Error thrown when a row does not match the result fields, a value fails to decode, or a callback of `transform` or `map` fails; the failure is its cause. */
319
362
  var ResultDecodeError = class extends Error {
320
363
  path;
321
364
  name = "ResultDecodeError";
@@ -334,9 +377,13 @@ function isRecordKey(key) {
334
377
  * A statement of one row that returns its number or a record without fields rejects as a query of one row does: with `NotFoundError` without a row, unless it is optional or nullable, and with several rows.
335
378
  */
336
379
  function decodeStatement(plan, result) {
337
- const { counted } = plan;
380
+ const { counted, conversion } = plan;
338
381
  if (counted === void 0) return decodeResult(plan, plan.named ? selectColumns(plan, result) : result.rows);
339
- const { count } = result;
382
+ const decoded = decodeCount(plan, counted, result.count);
383
+ return conversion === void 0 ? decoded : convertTopResult(plan, conversion, decoded, counted === "records" && plan.rows !== "many" && result.count === 0);
384
+ }
385
+ /** Returns what a statement resolves to by `count`, the number of the rows of its command tag, as `counted` tells: the number, or as many records without fields. */
386
+ function decodeCount(plan, counted, count) {
340
387
  if (plan.rows !== "many") {
341
388
  if (count > 1) throw new Error(plan.named ? `Query of one row reported ${count} rows` : `Query of one row changed ${count} rows`);
342
389
  if (count === 0) {
@@ -382,11 +429,47 @@ function selectColumns(plan, result) {
382
429
  return selected;
383
430
  }
384
431
  /**
385
- * Decodes driver rows into the result of a query by its result plan.
432
+ * Decodes driver rows into the result of a query by its result plan, and converts the result as its conversion tells.
386
433
  *
387
434
  * It rejects a row whose values do not match the result fields, and names the path of the value that fails to decode from its result field, such as `fields[2].label`, after the index of the row of rows `many`, such as `[2].fields[2].label`.
388
435
  */
389
436
  function decodeResult(plan, rows) {
437
+ const result = decodeRows(plan, rows);
438
+ const { conversion } = plan;
439
+ return conversion === void 0 ? result : convertTopResult(plan, conversion, result, rows.length === 0);
440
+ }
441
+ /** Converts `result`, which `plan` decoded for a statement rather than for nested rows, as `convertResult` does, rejecting with the error of the statement. */
442
+ function convertTopResult(plan, conversion, result, missing) {
443
+ try {
444
+ return convertResult(plan, conversion, result, missing);
445
+ } catch (error) {
446
+ throw error instanceof NestedFailure ? createRowError("", error) : new ResultDecodeError(`Cannot convert the result${describeCause(error)}`, void 0, { cause: error });
447
+ }
448
+ }
449
+ /**
450
+ * Converts `result`, which `plan` decoded, by `conversion`.
451
+ *
452
+ * It tells a missing row by `missing` rather than by the value, since a row may decode to `null` or `undefined`.
453
+ * A failure of `map` of rows `many` is a `NestedFailure` of the index of its row; any other failure is the error of the callback, which the enclosing field adds its path to.
454
+ */
455
+ function convertResult(plan, conversion, result, missing) {
456
+ const { map, transform } = conversion;
457
+ let converted = result;
458
+ if (map !== void 0) {
459
+ if (plan.rows === "many") {
460
+ const rows = result;
461
+ let index = 0;
462
+ try {
463
+ for (; index < rows.length; index++) rows[index] = map(rows[index]);
464
+ } catch (error) {
465
+ throw new NestedFailure(`[${index}]`, error);
466
+ }
467
+ } else if (!missing) converted = map(result);
468
+ }
469
+ return transform === void 0 ? converted : transform(converted);
470
+ }
471
+ /** Decodes driver rows into the result of a query before its conversion: an array of rows `many`, one row, or the result of a missing row. */
472
+ function decodeRows(plan, rows) {
390
473
  if (plan.rows === "many") {
391
474
  const results = [];
392
475
  let index = 0;
@@ -450,7 +533,11 @@ function createRowError(prefix, error) {
450
533
  const path = prefix + error.path;
451
534
  const { cause } = error;
452
535
  if (cause instanceof MissingRow) return cause.guaranteedBy === void 0 ? new NotFoundError(`Nested query of result field "${path}" returned no rows`, path) : new RequiredRelationError(cause.guaranteedBy, path);
453
- return new ResultDecodeError(`Cannot decode result field "${path}"${cause instanceof Error ? `: ${cause.message}` : ""}`, path, { cause });
536
+ return new ResultDecodeError(`Cannot decode result field "${path}"${describeCause(cause)}`, path, { cause });
537
+ }
538
+ /** Describes the failure `cause` at the end of the message of an error. */
539
+ function describeCause(cause) {
540
+ return cause instanceof Error ? `: ${cause.message}` : "";
454
541
  }
455
542
  /**
456
543
  * Decodes a row into a record keyed by the result fields, or into the value of its only field.
@@ -500,8 +587,14 @@ function decodePackedValue(field, value) {
500
587
  if (typeof value !== "string") throw new TypeError(`Nested value must be text, not ${describeJson(value)}`);
501
588
  return field.type.decode(value);
502
589
  }
503
- /** Decodes the rows of a nested query from JSON: an array of packed rows for rows `many`, and a packed row or `null` otherwise. */
590
+ /** Decodes the rows of a nested query from JSON, as `decodeNestedRows` does, and converts them as the conversion of `plan` tells. */
504
591
  function decodeNested(plan, json) {
592
+ const result = decodeNestedRows(plan, json);
593
+ const { conversion } = plan;
594
+ return conversion === void 0 ? result : convertResult(plan, conversion, result, json === null);
595
+ }
596
+ /** Decodes the rows of a nested query from JSON: an array of packed rows for rows `many`, and a packed row or `null` otherwise. */
597
+ function decodeNestedRows(plan, json) {
505
598
  if (plan.rows === "many") {
506
599
  if (!Array.isArray(json)) throw new TypeError(`Nested rows must be an array, not ${describeJson(json)}`);
507
600
  const results = [];
@@ -532,6 +625,20 @@ function describeJson(value) {
532
625
  }
533
626
  // src/table/table.ts
534
627
  function defineTable(name, definitions, options) {
628
+ return createTable(name, definitions, options, void 0);
629
+ }
630
+ /**
631
+ * Creates a table-definition function with the given naming convention, for an application to define its tables with.
632
+ *
633
+ * Its tables have the same types as those of `defineTable`.
634
+ */
635
+ function createTableFactory(factoryOptions) {
636
+ const deriveColumnName = factoryOptions.columnName;
637
+ if (typeof deriveColumnName !== "function") throw new TypeError("The columnName option of createTableFactory must be a function");
638
+ return ((name, definitions, options) => createTable(name, definitions, options, deriveColumnName));
639
+ }
640
+ /** Creates the table that `defineTable` defines, naming its columns by `deriveColumnName` if given. */
641
+ function createTable(name, definitions, options, deriveColumnName) {
535
642
  const columns = {};
536
643
  for (const [key, definition] of Object.entries(definitions)) {
537
644
  if (key.startsWith("$")) throw new Error(`Column key "${key}" of table "${name}" must not start with "$"`);
@@ -540,6 +647,7 @@ function defineTable(name, definitions, options) {
540
647
  if (!column) throw new TypeError(`Column "${key}" of table "${name}" must be a type or a column`);
541
648
  columns[key] = column;
542
649
  }
650
+ if (deriveColumnName) nameColumns(name, columns, deriveColumnName);
543
651
  return Object.freeze({
544
652
  kind: "table",
545
653
  name,
@@ -548,6 +656,30 @@ function defineTable(name, definitions, options) {
548
656
  });
549
657
  }
550
658
  /**
659
+ * Replaces unnamed columns of table `name` with copies whose physical names are derived from their keys, so that a column shared with other tables stays as it is.
660
+ *
661
+ * It calls `deriveColumnName`, which an application gives, once for each such column.
662
+ * It rejects a derived name that is not a non-empty string, which PostgreSQL rejects only when a query runs, and a derived name that another column has, since two keys would silently read one column.
663
+ * Duplicate names set with `columnName` are allowed, as in `defineTable`.
664
+ */
665
+ function nameColumns(name, columns, deriveColumnName) {
666
+ const keys = Object.keys(columns);
667
+ const derivedKeys = [];
668
+ for (const key of keys) {
669
+ const column = columns[key];
670
+ if (column.attributes.name === void 0) {
671
+ const columnName = deriveColumnName(key);
672
+ if (typeof columnName !== "string" || columnName === "") throw new TypeError(`The name derived for column "${key}" of table "${name}" must be a non-empty string`);
673
+ columns[key] = column.columnName(columnName);
674
+ derivedKeys.push(key);
675
+ }
676
+ }
677
+ for (const key of derivedKeys) {
678
+ const columnName = columns[key].attributes.name;
679
+ for (const other of keys) if (other !== key && columns[other].attributes.name === columnName) throw new Error(`Columns "${key}" and "${other}" of table "${name}" have one physical name "${columnName}"; set another name with columnName()`);
680
+ }
681
+ }
682
+ /**
551
683
  * Defines the keys of table `name` of `columns` from the keys marked on the columns and those of `options`.
552
684
  *
553
685
  * The unique keys are those of the columns in their order, followed by those of the options.
@@ -631,108 +763,6 @@ function toColumn(definition) {
631
763
  hasDefault: false
632
764
  }) : void 0;
633
765
  }
634
- // src/query/resolve-values.ts
635
- /**
636
- * Replaces objects of column values in a predicate with conditions on the columns of `source`.
637
- *
638
- * Groups are rebuilt, so constants that appear after resolution, such as an empty object, are simplified.
639
- */
640
- function resolveValues(node, source) {
641
- switch (node.kind) {
642
- case "values": {
643
- const conditions = [];
644
- for (const key of Object.keys(node.values)) conditions.push(matchColumn(source, key, node.values[key]));
645
- return combineNodes("and", conditions);
646
- }
647
- case "and":
648
- case "or": {
649
- const operands = [];
650
- for (const operand of node.operands) operands.push(resolveValues(operand, source));
651
- return combineNodes(node.kind, operands);
652
- }
653
- case "not": return negateNode(resolveValues(node.operand, source));
654
- case "raw": return createNode({
655
- ...node,
656
- values: node.values.map((value) => resolveValues(value, source))
657
- });
658
- default: return node;
659
- }
660
- }
661
- /** Creates the condition of column `key` of `source` in an object of column values: `IS NULL` of `null`, or the `eq` operator of its type for another value. */
662
- function matchColumn(source, key, value) {
663
- const type = findColumn(source.table, key)?.type;
664
- const column = createNode({
665
- kind: "column",
666
- source,
667
- key
668
- });
669
- if (value === null) return createIsNullNode(column);
670
- if (type) return matchValue(source, column, type, value);
671
- return compareNodes("=", column, value, void 0);
672
- }
673
- /** Matches a column with a value of an object condition by calling the `eq` operator of its type, whichever operator it is. */
674
- function matchValue(source, column, type, value) {
675
- const expression = toExpression(column, type);
676
- if (typeof expression.eq !== "function") throw new TypeError(`Column "${column.key}" of table "${source.table.name}" has no eq operator; an object condition can only match it with null`);
677
- const predicate = expression.eq(value);
678
- if (!isExpression(predicate)) throw new TypeError(`The eq operator of column "${column.key}" of table "${source.table.name}" must return an expression`);
679
- return toNode(predicate);
680
- }
681
- // src/query/filters.ts
682
- /** Creates query filters with the filter of `where` over `source` with the relations of `context` combined with `AND` with the user filters of `filters`. */
683
- function addUserFilter(filters, filter, source, context) {
684
- const predicate = resolveValues(toConditionNode(typeof filter === "function" ? filter(createSelectionRefs(source, context)) : filter), source);
685
- const { user } = filters;
686
- return Object.freeze({
687
- ...filters,
688
- user: user ? combineNodes("and", [user, predicate]) : predicate
689
- });
690
- }
691
- // src/query/find.ts
692
- /**
693
- * Returns the object of column values that `find` filters a query of `table` by: `values` of the columns of its primary key, in their order.
694
- *
695
- * It rejects a table without a primary key, a number of values other than the number of its columns, and `null` and `undefined`.
696
- */
697
- function toPrimaryKeyValues(table, values) {
698
- const { primaryKey } = table.keys;
699
- if (primaryKey === void 0) throw new Error(`find takes the values of a primary key, which table "${table.name}" does not have; use findBy with a unique key`);
700
- if (values.length !== primaryKey.length) throw new Error(`find takes one value for each column of the primary key of table "${table.name}", ${quoteColumns(primaryKey)}, not ${values.length}`);
701
- const filter = {};
702
- for (let index = 0; index < primaryKey.length; index++) {
703
- const column = primaryKey[index];
704
- filter[column] = requireKeyValue(table, column, values[index], "find");
705
- }
706
- return filter;
707
- }
708
- /**
709
- * Returns the object of column values that `findBy` filters a query of `table` by: a copy of `values`, read once.
710
- *
711
- * It rejects columns that are not exactly a key of `table`, primary or unique, as `isKey` tells, and `null` and `undefined`.
712
- */
713
- function toKeyValues(table, values) {
714
- if (typeof values !== "object" || values === null) throw new TypeError(`findBy takes an object of the columns of a key of table "${table.name}"`);
715
- const columns = Object.keys(values);
716
- if (!isKey(table, columns)) {
717
- const listed = columns.length === 0 ? "an object without columns" : `columns ${quoteColumns(columns)}`;
718
- throw new Error(`findBy takes the columns of one key of table "${table.name}", primary or unique, not ${listed}`);
719
- }
720
- const filter = {};
721
- for (const column of columns) {
722
- const value = values[column];
723
- filter[column] = requireKeyValue(table, column, value, "findBy");
724
- }
725
- return filter;
726
- }
727
- /** Returns `value` of column `column` of a key of `table` that `method` takes, rejecting `null` and `undefined`. */
728
- function requireKeyValue(table, column, value, method) {
729
- if (value === null || value === void 0) throw new TypeError(`${method} got ${value} for column "${column}" of table "${table.name}"; a value of a key is never null or undefined`);
730
- return value;
731
- }
732
- /** Lists `columns` in quotes, separated by commas. */
733
- function quoteColumns(columns) {
734
- return columns.map((column) => `"${column}"`).join(", ");
735
- }
736
766
  // src/type/untyped.ts
737
767
  /** Encodes a parameter without a type, such as a value interpolated into `sql`, by its JavaScript type. */
738
768
  function encodeUntyped(value) {
@@ -785,7 +815,12 @@ var CompileContext = class {
785
815
  tables;
786
816
  db;
787
817
  parameters = [];
818
+ /** Whether a select statement of the compilation locks rows. */
819
+ locksRows = false;
820
+ /** Whether the clauses being compiled belong to a query of groups, which binds the parameter of a cast once by `bindOnce`. */
821
+ grouped = false;
788
822
  #aliases = /* @__PURE__ */ new Set();
823
+ #placeholders;
789
824
  constructor(schemaName, tables = void 0, db = void 0) {
790
825
  this.schemaName = schemaName;
791
826
  this.tables = tables;
@@ -809,6 +844,16 @@ var CompileContext = class {
809
844
  this.parameters.push(value);
810
845
  return `$${this.parameters.length}`;
811
846
  }
847
+ /** Binds `value` as the parameter of `cast` unless `bindOnce` has bound the cast before, and returns its placeholder. */
848
+ bindOnce(cast, value) {
849
+ this.#placeholders ??= /* @__PURE__ */ new Map();
850
+ let placeholder = this.#placeholders.get(cast);
851
+ if (placeholder === void 0) {
852
+ placeholder = this.bind(value);
853
+ this.#placeholders.set(cast, placeholder);
854
+ }
855
+ return placeholder;
856
+ }
812
857
  };
813
858
  // src/compiler/postgres/parentheses.ts
814
859
  /** Tells whether an operand of `kind` needs parentheses at `position`, so that the SQL keeps the structure of the tree. */
@@ -885,10 +930,12 @@ function compileStatement(node, options = {}, tables, db) {
885
930
  parameters: context.parameters,
886
931
  fields: node.projections,
887
932
  recordTemplate: node.recordTemplate,
933
+ conversion: node.conversion,
888
934
  rows: node.rows,
889
935
  value: node.value,
890
936
  counted: void 0,
891
- named: false
937
+ named: false,
938
+ locksRows: context.locksRows
892
939
  };
893
940
  case "text": {
894
941
  const { fields } = node;
@@ -899,7 +946,8 @@ function compileStatement(node, options = {}, tables, db) {
899
946
  rows: node.rows,
900
947
  value: node.value,
901
948
  counted: fields === void 0 ? "number" : void 0,
902
- named: true
949
+ named: true,
950
+ locksRows: false
903
951
  };
904
952
  }
905
953
  default: {
@@ -909,10 +957,12 @@ function compileStatement(node, options = {}, tables, db) {
909
957
  parameters: context.parameters,
910
958
  fields: returning ?? noFields,
911
959
  recordTemplate: node.recordTemplate,
960
+ conversion: node.conversion,
912
961
  rows: node.rows,
913
962
  value: node.value,
914
963
  counted: returning === void 0 ? "number" : returning.length === 0 ? "records" : void 0,
915
- named: false
964
+ named: false,
965
+ locksRows: false
916
966
  };
917
967
  }
918
968
  }
@@ -981,7 +1031,14 @@ function compileQuery(context, outer, node) {
981
1031
  scope = declareSource(context, scope, join.source);
982
1032
  joinScopes.push(scope);
983
1033
  }
984
- let text = `SELECT${compileProjections(context, scope, node.projections)}`;
1034
+ const { groupBy, having } = node;
1035
+ const { grouped } = context;
1036
+ context.grouped = groupBy !== void 0;
1037
+ let text = "SELECT";
1038
+ if (node.distinct) text += " DISTINCT";
1039
+ const { distinctOn } = node;
1040
+ if (distinctOn !== void 0) text += ` DISTINCT ON (${compileKeys(context, scope, distinctOn, node.projections)})`;
1041
+ text += compileProjections(context, scope, node.projections);
985
1042
  if (fromScope !== void 0) {
986
1043
  text += ` FROM ${compileSource(context, outer, fromScope)}`;
987
1044
  for (let index = 0; index < node.joins.length; index++) {
@@ -990,9 +1047,18 @@ function compileQuery(context, outer, node) {
990
1047
  }
991
1048
  }
992
1049
  text += compileWhere(context, scope, node.filters);
1050
+ if (groupBy !== void 0) text += ` GROUP BY ${compileKeys(context, scope, groupBy, node.projections)}`;
1051
+ if (having !== void 0) text += ` HAVING ${compileExpression(context, scope, having)}`;
993
1052
  if (node.orderBy.length > 0) text += ` ${compileOrderBy(context, scope, node.orderBy)}`;
994
1053
  if (node.limit) text += ` LIMIT ${compileExpression(context, outer, node.limit)}`;
995
1054
  if (node.offset) text += ` OFFSET ${compileExpression(context, outer, node.offset)}`;
1055
+ const { lock } = node;
1056
+ if (lock !== void 0) {
1057
+ context.locksRows = true;
1058
+ text += ` FOR ${lock.strength}`;
1059
+ if (lock.onLocked !== void 0) text += ` ${lock.onLocked}`;
1060
+ }
1061
+ context.grouped = grouped;
996
1062
  return text;
997
1063
  }
998
1064
  /** Compiles the projections of a select list or of `RETURNING`, each after a space or a comma. */
@@ -1009,6 +1075,16 @@ function compileWhere(context, scope, filters) {
1009
1075
  const where = combineFilters(filters);
1010
1076
  return where.kind === "boolean" && where.value ? "" : ` WHERE ${compileExpression(context, scope, where)}`;
1011
1077
  }
1078
+ /** Compiles the keys of `GROUP BY` or `DISTINCT ON` of a query of `projections`, its final select list, also with those that lowering adds, such as of a sort key of packed rows: each key is the position of the projection that has its value, or its expression without one. */
1079
+ function compileKeys(context, scope, keys, projections) {
1080
+ let text = "";
1081
+ for (let index = 0; index < keys.length; index++) {
1082
+ const key = keys[index];
1083
+ const position = findValueProjection(projections, key);
1084
+ text += `${index === 0 ? "" : ", "}${position === -1 ? compileExpression(context, scope, key) : String(position + 1)}`;
1085
+ }
1086
+ return text;
1087
+ }
1012
1088
  /** Compiles the `ORDER BY` clause of a query or an aggregate, which has at least one sort key. */
1013
1089
  function compileOrderBy(context, scope, orderBy) {
1014
1090
  let text = "ORDER BY";
@@ -1055,7 +1131,10 @@ function compileExpression(context, scope, node) {
1055
1131
  switch (node.kind) {
1056
1132
  case "column": return compileColumn(scope, node);
1057
1133
  case "param": return context.bind(encodeParameter(node));
1058
- case "cast": return `${compileOperand(context, scope, node.operand, "value")}::${node.type.castType}`;
1134
+ case "cast": {
1135
+ const { operand } = node;
1136
+ return `${context.grouped && operand.kind === "param" ? context.bindOnce(node, encodeParameter(operand)) : compileOperand(context, scope, operand, "value")}::${node.type.castType}`;
1137
+ }
1059
1138
  case "boolean": return node.value ? "TRUE" : "FALSE";
1060
1139
  case "and":
1061
1140
  case "or": return node.operands.map((operand) => compileOperand(context, scope, operand, "condition")).join(node.kind === "and" ? " AND " : " OR ");
@@ -1087,7 +1166,9 @@ function compileExpression(context, scope, node) {
1087
1166
  let text = `${node.name}(${node.distinct ? "DISTINCT " : ""}`;
1088
1167
  for (let index = 0; index < node.arguments.length; index++) text += `${index === 0 ? "" : ", "}${compileExpression(context, scope, node.arguments[index])}`;
1089
1168
  if (node.orderBy.length > 0) text += ` ${compileOrderBy(context, scope, node.orderBy)}`;
1090
- return `${text})`;
1169
+ text += ")";
1170
+ if (node.filter !== void 0) text += ` FILTER (WHERE ${compileExpression(context, scope, node.filter)})`;
1171
+ return text;
1091
1172
  }
1092
1173
  default: return node;
1093
1174
  }
@@ -1117,174 +1198,41 @@ function createStatement(text, parameters = []) {
1117
1198
  parameters
1118
1199
  };
1119
1200
  }
1120
- // src/ast/references.ts
1121
- /** Adds to `keys` the key of each column reference to `source` in `node` at any depth, including the queries nested in it. */
1122
- function collectColumnKeys(node, source, keys) {
1123
- visitNodes(node, true, (child) => {
1124
- if (child.kind === "column" && child.source === source) keys.add(child.key);
1125
- });
1201
+ // src/schema/relation.ts
1202
+ /** Runtime mark of the declarations of `many` and `one`. */
1203
+ const declarationBrand = Symbol("kern-orm.relation");
1204
+ /** Returns the name of relation `name` of the table under key `key` in messages and errors, such as `field.form`. */
1205
+ function formatRelationName(key, name) {
1206
+ return `${key}.${name}`;
1126
1207
  }
1127
1208
  /**
1128
- * Tells whether `node` holds, at any depth, a SQL fragment that refers to a column of `source` outside the queries nested in the fragment.
1209
+ * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1129
1210
  *
1130
- * PostgreSQL assigns an aggregate whose arguments refer only to the sources of an enclosing query to that query ([PostgreSQL](https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-AGGREGATES)).
1131
- * Lowering does not parse SQL fragments to identify their aggregates, so such a fragment in a nested query, such as `sum` of a column of the parent row, may aggregate the rows of the query of `source`.
1211
+ * A composite key lists its columns in arrays of the same length.
1132
1212
  */
1133
- function holdsFragmentOfSource(node, source) {
1134
- let found = false;
1135
- visitNodes(node, true, (child) => {
1136
- if (found || child.kind !== "raw") return;
1137
- visitNodes(child, false, (value) => {
1138
- if (value.kind === "column" && value.source === source) found = true;
1139
- });
1140
- });
1141
- return found;
1213
+ function many(target, keys) {
1214
+ return declareRelation("many", target, keys, false);
1142
1215
  }
1143
- /** Calls `visit` for `node` and each expression node in it, also in the queries nested in it when `deep` is set. */
1144
- function visitNodes(node, deep, visit) {
1145
- visit(node);
1146
- switch (node.kind) {
1147
- case "column":
1148
- case "param":
1149
- case "boolean":
1150
- case "tableName":
1151
- case "values":
1152
- case "nestedQuery": return;
1153
- case "cast":
1154
- case "not":
1155
- case "isNull":
1156
- visitNodes(node.operand, deep, visit);
1157
- return;
1158
- case "and":
1159
- case "or":
1160
- for (const operand of node.operands) visitNodes(operand, deep, visit);
1161
- return;
1162
- case "comparison":
1163
- visitNodes(node.left, deep, visit);
1164
- visitNodes(node.right, deep, visit);
1165
- return;
1166
- case "in":
1167
- visitNodes(node.operand, deep, visit);
1168
- for (const item of node.list) visitNodes(item, deep, visit);
1169
- return;
1170
- case "inQuery":
1171
- visitNodes(node.operand, deep, visit);
1172
- if (deep && node.query.kind === "select") visitQuery(node.query, visit);
1173
- return;
1174
- case "raw":
1175
- for (const value of node.values) visitNodes(value, deep, visit);
1176
- return;
1177
- case "subquery":
1178
- case "exists":
1179
- case "textSubquery":
1180
- if (deep) visitQuery(node.query, visit);
1181
- return;
1182
- case "aggregate":
1183
- for (const argument of node.arguments) visitNodes(argument, deep, visit);
1184
- for (const order of node.orderBy) visitNodes(order.expression, deep, visit);
1185
- return;
1186
- }
1216
+ /**
1217
+ * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1218
+ *
1219
+ * A composite key lists its columns in arrays of the same length.
1220
+ * The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
1221
+ * Without the record, a query of the relation gives `null`, and a query of a relation declared with `required: true` rejects unless it filters the record.
1222
+ * Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
1223
+ */
1224
+ function one(target, keys) {
1225
+ return declareRelation("one", target, keys, keys.required === true);
1187
1226
  }
1188
- /** Calls `visit` for each expression node in the clauses and the derived sources of `query` at any depth. */
1189
- function visitQuery(query, visit) {
1190
- const { from, filters } = query;
1191
- if (from?.kind === "derived") visitQuery(from.query, visit);
1192
- for (const join of query.joins) {
1193
- if (join.source.kind === "derived") visitQuery(join.source.query, visit);
1194
- visitNodes(join.on, true, visit);
1195
- }
1196
- for (const projection of query.projections) visitNodes(projection.expression, true, visit);
1197
- if (filters.relation !== void 0) visitNodes(filters.relation, true, visit);
1198
- if (filters.scope !== void 0) visitNodes(filters.scope, true, visit);
1199
- if (filters.user !== void 0) visitNodes(filters.user, true, visit);
1200
- for (const order of query.orderBy) visitNodes(order.expression, true, visit);
1201
- if (query.limit !== void 0) visitNodes(query.limit, true, visit);
1202
- if (query.offset !== void 0) visitNodes(query.offset, true, visit);
1203
- }
1204
- // src/query/rows.ts
1205
- /** Returns the rows mode of a query of the records of `relation`, as `RelationRows` gives it in types. */
1206
- function getRelationRows(relation) {
1207
- if (relation.kind === "many") return "many";
1208
- return relation.required ? "one" : "nullable";
1209
- }
1210
- /** Returns the rows mode after a filter of a query of rows mode `rows`, of values when `value`, whose row is `guaranteed`, as `FilteredStateRows` gives it in types. */
1211
- function toFilteredRows(rows, value, guaranteed) {
1212
- if (!guaranteed || rows !== "one") return rows;
1213
- return value ? "optional" : "nullable";
1214
- }
1215
- /** Returns the limit of a query of many rows that becomes a query of one row, given its limit `limit`: one row, or none under a limit of zero. */
1216
- function limitToOne(limit) {
1217
- return limit?.kind === "param" && limit.value === 0 ? limit : oneNode;
1218
- }
1219
- /** Returns the rows mode after `pluck` of a query of rows mode `rows`, as `ValueRows` gives it in types. */
1220
- function toValueRows(rows) {
1221
- return rows === "nullable" ? "optional" : rows;
1222
- }
1223
- // src/query/node.ts
1224
- /** Creates a query of all rows of `from`, or of the records of `relation` with `filters` in the rows mode of the relation. */
1225
- function createQueryNode(from, relation, filters = noFilters) {
1226
- return Object.freeze({
1227
- kind: "query",
1228
- from,
1229
- relation,
1230
- projections: [],
1231
- filters,
1232
- orderBy: [],
1233
- limit: void 0,
1234
- offset: void 0,
1235
- rows: relation === void 0 ? "many" : getRelationRows(relation),
1236
- value: false,
1237
- guaranteed: relation?.required ?? false,
1238
- all: false
1239
- });
1240
- }
1241
- /** Tells whether `node` is a query of a table without clauses, such as a table of a `Db`: no relation, filters, selected fields, order, limit, offset, rows other than `many`, or `all`. */
1242
- function isTableQuery(node) {
1243
- return node.relation === void 0 && node.projections.length === 0 && node.filters.relation === void 0 && node.filters.scope === void 0 && node.filters.user === void 0 && node.orderBy.length === 0 && node.limit === void 0 && node.offset === void 0 && node.rows === "many" && !node.all;
1244
- }
1245
- /** Tells whether a selected field is the rows of a nested query. */
1246
- function isNestedSelection(node) {
1247
- return "query" in node;
1248
- }
1249
- /** Tells whether a selected field is a literal. */
1250
- function isLiteralSelection(node) {
1251
- return "literal" in node;
1252
- }
1253
- // src/schema/relation.ts
1254
- /** Runtime mark of the declarations of `many` and `one`. */
1255
- const declarationBrand = Symbol("kern-orm.relation");
1256
- /** Returns the name of relation `name` of the table under key `key` in messages and errors, such as `field.form`. */
1257
- function formatRelationName(key, name) {
1258
- return `${key}.${name}`;
1259
- }
1260
- /**
1261
- * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1262
- *
1263
- * A composite key lists its columns in arrays of the same length.
1264
- */
1265
- function many(target, keys) {
1266
- return declareRelation("many", target, keys, false);
1267
- }
1268
- /**
1269
- * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1270
- *
1271
- * A composite key lists its columns in arrays of the same length.
1272
- * The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
1273
- * Without the record, a query of the relation gives `null`, and a query of a relation declared with `required: true` rejects unless it filters the record.
1274
- * Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
1275
- */
1276
- function one(target, keys) {
1277
- return declareRelation("one", target, keys, keys.required === true);
1278
- }
1279
- function declareRelation(kind, target, keys, required) {
1280
- return Object.freeze({
1281
- [declarationBrand]: true,
1282
- kind,
1283
- target,
1284
- from: toKeyList(keys.from),
1285
- to: toKeyList(keys.to),
1286
- required
1287
- });
1227
+ function declareRelation(kind, target, keys, required) {
1228
+ return Object.freeze({
1229
+ [declarationBrand]: true,
1230
+ kind,
1231
+ target,
1232
+ from: toKeyList(keys.from),
1233
+ to: toKeyList(keys.to),
1234
+ required
1235
+ });
1288
1236
  }
1289
1237
  function toKeyList(key) {
1290
1238
  return Object.freeze(Array.isArray(key) ? key.slice() : [key]);
@@ -1365,628 +1313,473 @@ function freezeRelations(relations) {
1365
1313
  function isRelationDeclaration(value) {
1366
1314
  return typeof value === "object" && value !== null && declarationBrand in value;
1367
1315
  }
1368
- // src/lowering/order.ts
1369
- /**
1370
- * Returns the position of the projection that has the value of the sort expression `expression`: a projection of the same column or of the same expression node, or `-1`.
1371
- *
1372
- * Only the same node or column guarantees one value: PostgreSQL may or may not evaluate equal expressions built apart once, and gives each its own parameters.
1373
- */
1374
- function findSortProjection(projections, expression) {
1375
- return projections.findIndex((projection) => {
1376
- const selected = projection.expression;
1377
- return expression.kind === "column" && selected.kind === "column" ? selected.source === expression.source && selected.key === expression.key : selected === expression;
1378
- });
1316
+ // src/query/rows.ts
1317
+ /** Returns the rows mode of a query of the records of `relation`, as `RelationRows` gives it in types. */
1318
+ function getRelationRows(relation) {
1319
+ if (relation.kind === "many") return "many";
1320
+ return relation.required ? "one" : "nullable";
1379
1321
  }
1380
- /** Creates the number of the projection at `position`, by which `ORDER BY` sorts by its value instead of evaluating an expression again. */
1381
- function createPositionNode(position) {
1382
- return createNode({
1383
- kind: "raw",
1384
- fragments: [String(position + 1)],
1385
- values: []
1386
- });
1322
+ /** Returns the rows mode after a filter of a query of rows mode `rows`, of values when `value`, whose row is `guaranteed`, as `FilteredStateRows` gives it in types. */
1323
+ function toFilteredRows(rows, value, guaranteed) {
1324
+ if (!guaranteed || rows !== "one") return rows;
1325
+ return value ? "optional" : "nullable";
1387
1326
  }
1388
- /** Creates the order of a statement that sorts by the positions of the projections among `projections` that have the values of its sort expressions, and by the other expressions as they are. */
1389
- function sortByPositions(orderBy, projections) {
1390
- const result = [];
1391
- for (const order of orderBy) {
1392
- const position = findSortProjection(projections, order.expression);
1393
- result.push(position === -1 ? order : Object.freeze({
1394
- expression: createPositionNode(position),
1395
- direction: order.direction,
1396
- nulls: order.nulls
1397
- }));
1398
- }
1399
- return result;
1327
+ /** Returns the limit of a query of many rows that becomes a query of one row, given its limit `limit`: one row, or none under a limit of zero. */
1328
+ function limitToOne(limit) {
1329
+ return limit?.kind === "param" && limit.value === 0 ? limit : oneNode;
1400
1330
  }
1401
- /**
1402
- * Creates the derived source of the rows of `query`, and, when `ordered`, the order of the query over the projections of the source, in which its reader takes the rows, such as an aggregate.
1403
- *
1404
- * The order of a derived source does not carry into the query that reads it, so the reader sorts by sort keys: the projections that have the values of the sort expressions, as for an executed query, or projections of the sort expressions added to the source.
1405
- * With a limit or an offset, the source sorts by the positions of the sort keys, so that the rows it chooses, their values, and their order in the reader come from one evaluation; without them, it has no order.
1406
- * `offset` replaces the offset of `query` in the source, such as `OFFSET 0` that keeps PostgreSQL from merging it, and the source replaces the occurrence of a table `replaces` for its reader.
1407
- */
1408
- function deriveOrderedSource(query, ordered, offset = query.offset, replaces) {
1409
- const { orderBy } = query;
1410
- const projections = query.projections.slice();
1411
- const paginated = query.limit !== void 0 || query.offset !== void 0;
1412
- const sortKeys = [];
1413
- const positions = [];
1414
- if (orderBy.length > 0 && (ordered || paginated)) for (let index = 0; index < orderBy.length; index++) {
1415
- const { expression, direction, nulls } = orderBy[index];
1416
- const position = projectSortKey(projections, expression, index);
1417
- if (ordered) sortKeys.push({
1418
- key: projections[position].key,
1419
- direction,
1420
- nulls
1421
- });
1422
- if (paginated) positions.push(Object.freeze({
1423
- expression: createPositionNode(position),
1424
- direction,
1425
- nulls
1426
- }));
1427
- }
1428
- const derivedQuery = Object.freeze({
1429
- ...query,
1430
- projections,
1431
- orderBy: positions,
1432
- offset
1433
- });
1434
- const source = Object.freeze(replaces === void 0 ? {
1435
- kind: "derived",
1436
- query: derivedQuery,
1437
- lateral: false
1438
- } : {
1439
- kind: "derived",
1440
- query: derivedQuery,
1441
- lateral: false,
1442
- replaces
1331
+ /** Returns the rows mode after `pluck` of a query of rows mode `rows`, as `ValueRows` gives it in types. */
1332
+ function toValueRows(rows) {
1333
+ return rows === "nullable" ? "optional" : rows;
1334
+ }
1335
+ // src/query/node.ts
1336
+ /** Creates a query of all rows of `from`, or of the records of `relation` with `filters` in the rows mode of the relation. */
1337
+ function createQueryNode(from, relation, filters = noFilters) {
1338
+ return Object.freeze({
1339
+ kind: "query",
1340
+ from,
1341
+ relation,
1342
+ projections: [],
1343
+ filters,
1344
+ groupBy: [],
1345
+ having: void 0,
1346
+ orderBy: [],
1347
+ limit: void 0,
1348
+ offset: void 0,
1349
+ distinct: false,
1350
+ distinctOn: [],
1351
+ distinctFields: void 0,
1352
+ lock: void 0,
1353
+ rows: relation === void 0 ? "many" : getRelationRows(relation),
1354
+ value: false,
1355
+ guaranteed: relation?.required ?? false,
1356
+ all: false,
1357
+ conversion: void 0
1443
1358
  });
1444
- const order = [];
1445
- for (const { key, direction, nulls } of sortKeys) order.push(Object.freeze({
1446
- expression: createNode({
1447
- kind: "column",
1448
- source,
1449
- key
1450
- }),
1451
- direction,
1452
- nulls
1453
- }));
1454
- return {
1455
- source,
1456
- order
1457
- };
1458
1359
  }
1459
- /**
1460
- * Returns the position of the projection that sorts by `expression`: the projection of `findSortProjection`, or one added to `projections`.
1461
- *
1462
- * `index` is the position of the expression in the order.
1463
- */
1464
- function projectSortKey(projections, expression, index) {
1465
- const position = findSortProjection(projections, expression);
1466
- if (position !== -1) return position;
1467
- projections.push(Object.freeze({
1468
- key: createSortProjectionKey(projections, index),
1469
- expression,
1470
- type: text
1471
- }));
1472
- return projections.length - 1;
1360
+ /** Tells whether `node` is a query of a table without clauses, such as a table of a `Db`: no relation, filters, selected fields, keys of groups, order, limit, offset, `distinct`, keys of `distinctOn`, row lock, rows other than `many`, `all`, or conversion. */
1361
+ function isTableQuery(node) {
1362
+ return node.relation === void 0 && node.projections.length === 0 && node.filters.relation === void 0 && node.filters.scope === void 0 && node.filters.user === void 0 && node.groupBy.length === 0 && node.orderBy.length === 0 && node.limit === void 0 && node.offset === void 0 && !node.distinct && node.distinctOn.length === 0 && node.lock === void 0 && node.rows === "many" && !node.all && node.conversion === void 0;
1473
1363
  }
1474
- /** Creates the key of the sort key projection at `index` of the sort keys, which no other projection has. */
1475
- function createSortProjectionKey(projections, index) {
1476
- const base = `$order${index + 1}`;
1477
- let key = base;
1478
- for (let number = 2; projections.some((projection) => projection.key === key); number++) key = `${base}_${number}`;
1479
- return key;
1364
+ /** Tells whether a selected field is the rows of a nested query. */
1365
+ function isNestedSelection(node) {
1366
+ return "query" in node;
1480
1367
  }
1481
- // src/lowering/nested.ts
1482
- /** Maximum number of arguments of a PostgreSQL function, `FUNC_MAX_ARGS` of its default build. */
1483
- const maxFunctionArguments = 100;
1484
- /** Number `0`, the offset that keeps PostgreSQL from merging a derived source into its query. */
1485
- const zeroNode = /* @__PURE__ */ createNode({
1486
- kind: "raw",
1487
- fragments: ["0"],
1488
- values: []
1489
- });
1490
- /**
1491
- * Creates the projection of the rows of `query` packed as JSON under `key`, selected as a scalar subquery and decoded by the result plan of `query`.
1492
- *
1493
- * Rows `many` are one array, and the other rows modes are one packed row or `NULL` without a row; a scalar subquery fails with several rows.
1494
- */
1495
- function projectRows(key, query) {
1496
- const packed = packRows(query);
1497
- const { nested } = packed.projections[0];
1498
- return Object.freeze({
1499
- key,
1500
- expression: createNode({
1501
- kind: "subquery",
1502
- query: packed
1503
- }),
1504
- nested
1505
- });
1368
+ /** Tells whether a selected field is a literal. */
1369
+ function isLiteralSelection(node) {
1370
+ return "literal" in node;
1371
+ }
1372
+ // src/lowering/context.ts
1373
+ /** Rejects a query of a relation outside the definitions of `context`. */
1374
+ function checkRelation(node, context) {
1375
+ const { relation } = node;
1376
+ const { definitions } = context;
1377
+ if (relation !== void 0 && definitions !== void 0 && !definitions.has(relation)) throw new Error(`Relation "${formatRelationName(relation.key, relation.name)}" is not part of the schema`);
1378
+ }
1379
+ /** Rejects a nested query bound to `db`, which the error names as `subject`, unless `db` is the `Db` of `context` or `undefined`. */
1380
+ function checkDb(db, context, subject) {
1381
+ if (db !== void 0 && db !== context.db) throw new Error(context.db === void 0 ? `${subject} is bound to a Db, so only that Db can compile the query` : `${subject} is bound to another Db`);
1506
1382
  }
1383
+ // src/lowering/expression.ts
1507
1384
  /**
1508
- * Creates a query whose only projection is the rows of `query` packed as JSON, a field decoded by the result plan of `query`.
1385
+ * Lowers an expression, replacing each query in it and checking the query as a nested query.
1386
+ * A query of `exists`, such as in a condition, becomes `EXISTS` of its rows, another query of one value a scalar subquery of its value, the query of the values of `IN` its statement, and another query in SQL text its statement in parentheses.
1509
1387
  *
1510
- * Rows `many` are packed as an array in the order of `query`, and the created query returns one row.
1511
- * Otherwise the created query returns a packed row for each row of `query`, so a scalar subquery of it gives the packed row, `NULL` without a row, and fails with several rows.
1388
+ * It returns `node` itself when it holds no query, and creates only the nodes that hold one.
1512
1389
  */
1513
- function packRows(query) {
1514
- const { projections } = query;
1515
- const many = query.rows === "many";
1516
- const { source, order } = deriveOrderedSource(query, many, query.limit === void 0 && query.offset === void 0 && projections.some((projection) => projection.nested === void 0 && !isTableColumn(projection.expression)) ? zeroNode : query.offset);
1517
- const wide = projections.length > maxFunctionArguments;
1518
- const values = [];
1519
- for (const projection of projections) {
1520
- const value = createRef(source, projection.key);
1521
- if (projection.nested !== void 0) values.push(value);
1522
- else values.push(wide ? createList("to_json(", [packScalar(value)], ")") : packScalar(value));
1523
- }
1524
- const row = wide ? createList("array_to_json(ARRAY[", values, "])") : createList("json_build_array(", values, ")");
1525
- let packed = row;
1526
- if (many) packed = createNode({
1527
- kind: "raw",
1528
- fragments: ["coalesce(", ", '[]'::json)"],
1529
- values: [createNode({
1530
- kind: "aggregate",
1531
- name: "json_agg",
1532
- distinct: false,
1533
- arguments: [row],
1534
- orderBy: order
1535
- })]
1536
- });
1537
- const plan = Object.freeze({
1538
- fields: projections,
1539
- rows: query.rows,
1540
- value: query.value,
1541
- guaranteedBy: query.guaranteedBy,
1542
- recordTemplate: query.recordTemplate
1543
- });
1544
- const projection = Object.freeze({
1545
- key: "rows",
1546
- expression: packed,
1547
- nested: plan
1548
- });
1549
- return createSelectNode(source, [projection]);
1550
- }
1551
- /** Tells whether `node` is a column of a table, which PostgreSQL reads rather than evaluates, so it can be repeated. */
1552
- function isTableColumn(node) {
1553
- return node.kind === "column" && node.source.kind === "table";
1554
- }
1555
- /**
1556
- * Packs a scalar as its PostgreSQL text representation, or `NULL`.
1557
- *
1558
- * `format` uses the output function of the type, as the driver receives the values of a row; a cast to `text` differs from it for types such as `boolean`, `inet`, and `char`.
1559
- */
1560
- function packScalar(value) {
1561
- return createNode({
1562
- kind: "raw",
1563
- fragments: [
1564
- "CASE WHEN ",
1565
- " IS NOT DISTINCT FROM NULL THEN NULL ELSE format('%s', ",
1566
- ") END"
1567
- ],
1568
- values: [value, value]
1569
- });
1570
- }
1571
- function createRef(source, key) {
1572
- return createNode({
1573
- kind: "column",
1574
- source,
1575
- key
1576
- });
1577
- }
1578
- // src/lowering/lower.ts
1579
- const noJoins = /* @__PURE__ */ Object.freeze([]);
1580
- const noOrder = /* @__PURE__ */ Object.freeze([]);
1581
- const noProjections = /* @__PURE__ */ Object.freeze([]);
1582
- function lowerStatement(node, definitions, db) {
1583
- const context = {
1584
- definitions,
1585
- db
1586
- };
1587
- switch (node.kind) {
1588
- case "query": return lowerSelect(node, context, true);
1589
- case "record": return lowerRecord(node, context);
1590
- case "text": return lowerText(node, context);
1591
- default: return lowerMutation(node, context);
1592
- }
1593
- }
1594
- /** Lowers a statement of SQL text, replacing the queries in the expressions interpolated into it. */
1595
- function lowerText(node, context) {
1596
- const sql = lowerExpression(node.sql, context);
1597
- if (sql === node.sql) return node;
1598
- return Object.freeze({
1599
- kind: "text",
1600
- sql,
1601
- fields: node.fields,
1602
- rows: node.rows,
1603
- value: node.value
1604
- });
1605
- }
1606
- /** Lowers a mutation to its statement, replacing the queries in its expressions, and packing the rows of each nested query of `RETURNING` into the value of its field, or selecting the value of a nested aggregate query, as a select list does. */
1607
- function lowerMutation(node, context) {
1608
- const { target, returning, rows, value } = node;
1609
- const recordTemplate = returning === void 0 ? void 0 : createRecordTemplate(returning);
1610
- const lowered = returning === void 0 ? void 0 : lowerProjections(dropLiterals(returning), context);
1390
+ function lowerExpression(node, context) {
1611
1391
  switch (node.kind) {
1612
- case "insert": {
1613
- const values = lowerEach(node.values, context, lowerRow);
1614
- if (lowered === returning && values === node.values) return node;
1615
- return Object.freeze({
1616
- kind: "insert",
1617
- target,
1618
- columns: node.columns,
1619
- values,
1620
- returning: lowered,
1621
- recordTemplate,
1622
- rows,
1623
- value
1392
+ case "column":
1393
+ case "param":
1394
+ case "boolean":
1395
+ case "values":
1396
+ case "tableName":
1397
+ case "subquery":
1398
+ case "exists":
1399
+ case "textSubquery": return node;
1400
+ case "nestedQuery": return lowerNestedQuery(node, context);
1401
+ case "cast": {
1402
+ const operand = lowerExpression(node.operand, context);
1403
+ return operand === node.operand ? node : createNode({
1404
+ kind: "cast",
1405
+ operand,
1406
+ type: node.type
1624
1407
  });
1625
1408
  }
1626
- case "update": {
1627
- const set = lowerEach(node.set, context, lowerAssignment);
1628
- const filters = lowerFilters(node.filters, context);
1629
- if (lowered === returning && set === node.set && filters === node.filters) return node;
1630
- return Object.freeze({
1631
- kind: "update",
1632
- target,
1633
- set,
1634
- filters,
1635
- returning: lowered,
1636
- recordTemplate,
1637
- rows,
1638
- value
1409
+ case "not": {
1410
+ const operand = lowerExpression(node.operand, context);
1411
+ return operand === node.operand ? node : createNode({
1412
+ kind: "not",
1413
+ operand
1639
1414
  });
1640
1415
  }
1641
- case "delete": {
1642
- const filters = lowerFilters(node.filters, context);
1643
- if (lowered === returning && filters === node.filters) return node;
1644
- return Object.freeze({
1645
- kind: "delete",
1646
- target,
1647
- filters,
1648
- returning: lowered,
1649
- recordTemplate,
1650
- rows,
1651
- value
1416
+ case "isNull": {
1417
+ const operand = lowerExpression(node.operand, context);
1418
+ return operand === node.operand ? node : createNode({
1419
+ kind: "isNull",
1420
+ operand
1421
+ });
1422
+ }
1423
+ case "and":
1424
+ case "or": {
1425
+ const operands = lowerEach(node.operands, context, lowerExpression);
1426
+ return operands === node.operands ? node : createNode({
1427
+ kind: node.kind,
1428
+ operands
1429
+ });
1430
+ }
1431
+ case "comparison": {
1432
+ const left = lowerExpression(node.left, context);
1433
+ const right = lowerExpression(node.right, context);
1434
+ return left === node.left && right === node.right ? node : createNode({
1435
+ kind: "comparison",
1436
+ operator: node.operator,
1437
+ left,
1438
+ right
1439
+ });
1440
+ }
1441
+ case "in": {
1442
+ const operand = lowerExpression(node.operand, context);
1443
+ const list = lowerEach(node.list, context, lowerExpression);
1444
+ return operand === node.operand && list === node.list ? node : createNode({
1445
+ kind: "in",
1446
+ operand,
1447
+ list
1448
+ });
1449
+ }
1450
+ case "inQuery": {
1451
+ const operand = lowerExpression(node.operand, context);
1452
+ const query = node.query.kind === "nestedQuery" ? lowerQueryOfValues(node.query, context) : node.query;
1453
+ return operand === node.operand && query === node.query ? node : createNode({
1454
+ kind: "inQuery",
1455
+ operand,
1456
+ query
1457
+ });
1458
+ }
1459
+ case "raw": {
1460
+ const values = lowerEach(node.values, context, lowerExpression);
1461
+ return values === node.values ? node : createNode({
1462
+ kind: "raw",
1463
+ fragments: node.fragments,
1464
+ values
1465
+ });
1466
+ }
1467
+ case "aggregate": {
1468
+ const args = lowerEach(node.arguments, context, lowerExpression);
1469
+ const orderBy = lowerOrder(node.orderBy, context);
1470
+ const filter = lowerValue(node.filter, context);
1471
+ return args === node.arguments && orderBy === node.orderBy && filter === node.filter ? node : createNode({
1472
+ kind: "aggregate",
1473
+ name: node.name,
1474
+ distinct: node.distinct,
1475
+ arguments: args,
1476
+ orderBy,
1477
+ filter
1652
1478
  });
1653
1479
  }
1654
1480
  default: return node;
1655
1481
  }
1656
1482
  }
1657
- /** Lowers a row of `VALUES` of an insert, whose `undefined` stands for `DEFAULT`. */
1658
- function lowerRow(row, context) {
1659
- return lowerEach(row, context, lowerValue);
1660
- }
1483
+ /** Lowers an optional expression, such as `having` of a query or a value of a row of an insert, as `lowerExpression` does. */
1661
1484
  function lowerValue(node, context) {
1662
1485
  return node === void 0 ? void 0 : lowerExpression(node, context);
1663
1486
  }
1664
- function lowerAssignment(assignment, context) {
1665
- const value = lowerExpression(assignment.value, context);
1666
- return value === assignment.value ? assignment : Object.freeze({
1667
- key: assignment.key,
1668
- value
1487
+ /**
1488
+ * Lowers a query in an expression to `EXISTS` of the rows of a query of `exists`, to a scalar subquery of the value of another query of one value, or to its statement in parentheses for a query of records or of rows `many`, which only SQL text holds.
1489
+ *
1490
+ * In SQL text, a query of `exists` stays `EXISTS` rather than a subquery of its value, so that PostgreSQL can join its rows in a condition, as a semi-join.
1491
+ */
1492
+ function lowerNestedQuery(node, context) {
1493
+ checkDb(node.db, context, "A query in an expression");
1494
+ const { query } = node;
1495
+ if (isExistsQuery(query)) return context.lowerExists(query);
1496
+ return createNode({
1497
+ kind: query.value && query.rows !== "many" ? "subquery" : "textSubquery",
1498
+ query: context.lowerSelect(query, sortsByPositions(query))
1669
1499
  });
1670
1500
  }
1671
- /** Lowers a query as `lowerQuery` does, or as `lowerStatement` does when `positions` is set. */
1672
- function lowerSelect(node, context, positions) {
1673
- if (isExistsQuery(node)) return selectExists(node, context);
1674
- checkRelation(node, context);
1675
- if (isAggregateQuery(node)) return lowerAggregate(node, context);
1676
- const recordTemplate = createRecordTemplate(node.projections);
1677
- const selected = dropLiterals(node.projections);
1678
- const projections = lowerProjections(selected, context);
1679
- const filters = lowerFilters(node.filters, context);
1680
- const orderBy = lowerOrder(node.orderBy, context, selected, projections);
1681
- const { relation } = node;
1682
- const guaranteedBy = node.guaranteed && relation !== void 0 ? formatRelationName(relation.key, relation.name) : void 0;
1683
- const page = node.offset !== void 0 && selected.some((field, index) => isPagedField(field, projections[index], orderBy)) ? lowerPage(node, selected, projections, filters, orderBy, positions, guaranteedBy, recordTemplate) : void 0;
1684
- if (page !== void 0) return page;
1685
- return Object.freeze({
1686
- kind: "select",
1687
- from: node.from,
1688
- joins: noJoins,
1689
- projections,
1690
- filters,
1691
- orderBy: positions && orderBy.length > 0 ? sortByPositions(orderBy, projections) : orderBy,
1692
- limit: node.limit,
1693
- offset: node.offset,
1694
- rows: node.rows,
1695
- value: node.value,
1696
- guaranteedBy,
1697
- recordTemplate
1698
- });
1501
+ /** Lowers the query of the values of `IN` to its statement, whatever its rows; it tells positions as `sortsByPositions` does. */
1502
+ function lowerQueryOfValues(node, context) {
1503
+ checkDb(node.db, context, "A query in an expression");
1504
+ return context.lowerSelect(node.query, sortsByPositions(node.query));
1699
1505
  }
1700
- /** Returns the fields of `selected` that a statement selects, or `selected` itself without literals. */
1701
- function dropLiterals(selected) {
1702
- if (!selected.some(isLiteralSelection)) return selected;
1703
- const fields = [];
1704
- for (const field of selected) if (!isLiteralSelection(field)) fields.push(field);
1705
- return fields;
1506
+ /** Tells whether the statement of `node` in a subquery sorts by the positions of its projections: PostgreSQL finds a sort expression of `SELECT DISTINCT` or `GROUP BY` only when it is equal to a selected one or a key, and the keys of `DISTINCT ON` with the order only when they are equal, while a repeated expression has aliases of its own and, apart from the parameters of casts in a query of groups, parameters of its own. */
1507
+ function sortsByPositions(node) {
1508
+ return node.distinct || node.distinctOn.length > 0 || node.groupBy.length > 0;
1706
1509
  }
1707
- /** Creates the template of the records of `selected`: every field in its order with the value of a literal, or `undefined` without literals. */
1708
- function createRecordTemplate(selected) {
1709
- if (!selected.some(isLiteralSelection)) return;
1710
- const template = [];
1711
- for (const field of selected) template.push(Object.freeze({
1712
- key: field.key,
1713
- value: isLiteralSelection(field) ? field.literal : void 0
1714
- }));
1715
- return template;
1510
+ /** Lowers the filters of a query, replacing the queries in their expressions; without queries, it returns `filters` itself. */
1511
+ function lowerFilters(filters, context) {
1512
+ const { relation, scope, user } = filters;
1513
+ const loweredRelation = relation === void 0 ? void 0 : lowerExpression(relation, context);
1514
+ const loweredScope = scope === void 0 ? void 0 : lowerExpression(scope, context);
1515
+ const loweredUser = user === void 0 ? void 0 : lowerExpression(user, context);
1516
+ if (loweredRelation === relation && loweredScope === scope && loweredUser === user) return filters;
1517
+ const lowered = {};
1518
+ if (loweredRelation !== void 0) lowered.relation = loweredRelation;
1519
+ if (loweredScope !== void 0) lowered.scope = loweredScope;
1520
+ if (loweredUser !== void 0) lowered.user = loweredUser;
1521
+ return Object.freeze(lowered);
1716
1522
  }
1717
1523
  /**
1718
- * Tells whether `field`, a field of a query lowered to `projection`, is a nested query that a page after an offset evaluates only over its rows: one that no sort key of `orderBy`, the lowered order, sorts by.
1524
+ * Lowers the sort keys of a query, replacing the queries in their expressions; without queries, it returns `orderBy` itself.
1719
1525
  *
1720
- * The query evaluates a field that it sorts by, of an aggregate or of `exists`, for every row anyway.
1526
+ * Each sort key is lowered by `lowerSelectedValue` over `selected`, the fields of the query, and `projections`, their lowered projections.
1721
1527
  */
1722
- function isPagedField(field, projection, orderBy) {
1723
- if (!isNestedSelection(field)) return false;
1724
- const { expression } = projection;
1725
- return !orderBy.some((order) => order.expression === expression);
1726
- }
1727
- /** Rejects a query of a relation outside the definitions of `context`. */
1728
- function checkRelation(node, context) {
1729
- const { relation } = node;
1730
- const { definitions } = context;
1731
- if (relation !== void 0 && definitions !== void 0 && !definitions.has(relation)) throw new Error(`Relation "${formatRelationName(relation.key, relation.name)}" is not part of the schema`);
1732
- }
1733
- /** Rejects a nested query bound to `db`, which the error names as `subject`, unless `db` is the `Db` of `context` or `undefined`. */
1734
- function checkDb(db, context, subject) {
1735
- if (db !== void 0 && db !== context.db) throw new Error(context.db === void 0 ? `${subject} is bound to a Db, so only that Db can compile the query` : `${subject} is bound to another Db`);
1528
+ function lowerOrder(orderBy, context, selected, projections) {
1529
+ let lowered;
1530
+ for (let index = 0; index < orderBy.length; index++) {
1531
+ const order = orderBy[index];
1532
+ const { expression } = order;
1533
+ const sorted = lowerSelectedValue(expression, context, selected, projections);
1534
+ if (lowered === void 0 && sorted === expression) continue;
1535
+ lowered ??= orderBy.slice(0, index);
1536
+ lowered.push(sorted === expression ? order : Object.freeze({
1537
+ expression: sorted,
1538
+ direction: order.direction,
1539
+ nulls: order.nulls
1540
+ }));
1541
+ }
1542
+ return lowered ?? orderBy;
1736
1543
  }
1737
1544
  /**
1738
- * Lowers `node` with `projections`, `filters`, and `orderBy`, the lowered parts of the node, to a statement that evaluates its nested queries, apart from those that it sorts by, over the rows of a derived page.
1739
- * `queryFields` are the fields of the query without literals, and `projections` their lowered projections in the same order.
1740
- * The derived source applies the filters, the order, the limit, and the offset, and replaces the occurrence of the table.
1545
+ * Lowers the keys of `groupBy` or `distinctOn` of a query, or `undefined` for a query without them.
1741
1546
  *
1742
- * It returns `undefined` when a nested query that it evaluates over the rows of the page holds a SQL fragment that refers to a column of the table outside the queries nested in the fragment.
1743
- * Such a fragment may hold an aggregate of the query, which the limit and the offset apply after.
1547
+ * Each key is lowered by `lowerSelectedValue` over `selected`, the fields of the query, and `projections`, their lowered projections.
1548
+ */
1549
+ function lowerKeys(keys, context, selected, projections) {
1550
+ return keys.length === 0 ? void 0 : lowerEach(keys, context, (key, keyContext) => lowerSelectedValue(key, keyContext, selected, projections));
1551
+ }
1552
+ /**
1553
+ * Lowers `expression`, a sort key, a key of a group, or the argument of an aggregate: the value of a field of `selected` gets the expression of its lowered projection among `projections`, and another expression is lowered as it is.
1744
1554
  *
1745
- * The source selects the columns of the table that the fields and the nested queries of the query read, under their keys, and the other scalar fields of the query, which it evaluates before the limit and the offset as the query would, such as a window function over all its rows.
1746
- * A field of an aggregate or of `exists` that the query sorts by is such a scalar field: the order needs its value for every row.
1747
- * A column that no field reads stays out of the source, which could not select it beside an aggregate of a SQL fragment, such as `count(*)`.
1748
- * The order of a derived source does not carry into the query that reads it, so the statement sorts the rows of the page again by the sort keys of the source, by positions when `positions` is set.
1555
+ * Lowering a field that holds a query gives its projection a new node, so reusing that node keeps the projection identifiable by its position.
1556
+ * A field of an aggregate or of `exists` is identified by the node of its reference, which holds the field.
1749
1557
  */
1750
- function lowerPage(node, queryFields, projections, filters, orderBy, positions, guaranteedBy, recordTemplate) {
1751
- const { from } = node;
1752
- const columnKeys = /* @__PURE__ */ new Set();
1753
- const fields = [];
1754
- const fieldKeys = [];
1755
- for (let index = 0; index < projections.length; index++) {
1756
- const { expression } = projections[index];
1757
- let key;
1758
- if (isPagedField(queryFields[index], projections[index], orderBy)) {
1759
- if (holdsFragmentOfSource(expression, from)) return;
1760
- collectColumnKeys(expression, from, columnKeys);
1761
- } else if (expression.kind === "column" && expression.source === from) columnKeys.add(expression.key);
1762
- else {
1763
- key = `$field${index + 1}`;
1764
- fields.push(Object.freeze({
1765
- key,
1766
- expression,
1767
- type: text
1768
- }));
1558
+ function lowerSelectedValue(expression, context, selected, projections) {
1559
+ const position = selected === void 0 || projections === void 0 || projections === selected ? -1 : selected.findIndex((field) => isFieldValue(field, expression));
1560
+ return position === -1 ? lowerExpression(expression, context) : projections[position].expression;
1561
+ }
1562
+ /** Tells whether `expression`, a sort key, a key of a group, or the argument of an aggregate, is the value of `field`: its expression, or for a field of an aggregate or of `exists`, the node of its reference in the callback of `orderBy` or `groupBy`. */
1563
+ function isFieldValue(field, expression) {
1564
+ return isNestedSelection(field) ? expression.kind === "nestedQuery" && expression.field === field : field.expression === expression;
1565
+ }
1566
+ /** Lowers each of `items` with `lower`; when none changes, it returns `items` itself. */
1567
+ function lowerEach(items, context, lower) {
1568
+ let lowered;
1569
+ for (let index = 0; index < items.length; index++) {
1570
+ const item = items[index];
1571
+ const result = lower(item, context);
1572
+ if (lowered !== void 0) lowered.push(result);
1573
+ else if (result !== item) {
1574
+ lowered = items.slice(0, index);
1575
+ lowered.push(result);
1769
1576
  }
1770
- fieldKeys.push(key);
1771
1577
  }
1772
- const sourced = [];
1773
- for (const key of columnKeys) sourced.push(Object.freeze({
1774
- key,
1775
- expression: createNode({
1776
- kind: "column",
1777
- source: from,
1778
- key
1779
- }),
1780
- type: text
1781
- }));
1782
- for (const field of fields) sourced.push(field);
1783
- const page = deriveOrderedSource({
1784
- kind: "select",
1785
- from,
1786
- joins: noJoins,
1787
- projections: sourced,
1788
- filters,
1789
- orderBy,
1790
- limit: node.limit,
1791
- offset: node.offset,
1792
- rows: "many",
1793
- value: false,
1794
- guaranteedBy: void 0
1795
- }, true, node.offset, from);
1796
- const selected = [];
1797
- for (let index = 0; index < projections.length; index++) {
1798
- const projection = projections[index];
1799
- const key = fieldKeys[index];
1800
- selected.push(key === void 0 ? projection : Object.freeze({
1801
- key: projection.key,
1802
- expression: createNode({
1803
- kind: "column",
1804
- source: page.source,
1805
- key
1806
- }),
1807
- type: projection.type
1578
+ return lowered ?? items;
1579
+ }
1580
+ // src/lowering/order.ts
1581
+ /** Creates the number of the projection at `position`, by which `ORDER BY` sorts by its value instead of evaluating an expression again. */
1582
+ function createPositionNode(position) {
1583
+ return createNode({
1584
+ kind: "raw",
1585
+ fragments: [String(position + 1)],
1586
+ values: []
1587
+ });
1588
+ }
1589
+ /** Creates the order of a statement that sorts by the positions of the projections among `projections` that have the values of its sort expressions, and by the other expressions as they are. */
1590
+ function sortByPositions(orderBy, projections) {
1591
+ const result = [];
1592
+ for (const order of orderBy) {
1593
+ const position = findValueProjection(projections, order.expression);
1594
+ result.push(position === -1 ? order : Object.freeze({
1595
+ expression: createPositionNode(position),
1596
+ direction: order.direction,
1597
+ nulls: order.nulls
1808
1598
  }));
1809
1599
  }
1810
- return Object.freeze({
1811
- kind: "select",
1812
- from: page.source,
1813
- joins: noJoins,
1814
- projections: selected,
1815
- filters: noFilters,
1816
- orderBy: positions ? sortByPositions(page.order, selected) : page.order,
1817
- limit: void 0,
1818
- offset: void 0,
1819
- rows: node.rows,
1820
- value: node.value,
1821
- guaranteedBy,
1822
- recordTemplate
1823
- });
1600
+ return result;
1824
1601
  }
1825
- /** Lowers an aggregate query to a statement of the value of its aggregate over the rows that its filters, limit, and offset choose. */
1826
- function lowerAggregate(node, context) {
1827
- const field = node.projections[0];
1828
- const aggregate = field.expression;
1829
- const orderBy = lowerOrder(node.orderBy, context);
1830
- let from = node.from;
1831
- let filters = lowerFilters(node.filters, context);
1832
- let args = lowerEach(aggregate.arguments, context, lowerExpression);
1833
- let order = field.ordered ? orderBy : noOrder;
1834
- const counted = aggregate === countProjection.expression;
1835
- if (node.limit !== void 0 || node.offset !== void 0 || !counted && !refersToSource(args[0], node.from)) {
1836
- const projections = [];
1837
- if (!counted) projections.push(Object.freeze({
1838
- key: "value",
1839
- expression: args[0],
1840
- type: field.type
1602
+ /**
1603
+ * Creates the derived source of the rows of `query`, and, when `ordered`, the order of the query over the projections of the source, in which its reader takes the rows, such as an aggregate.
1604
+ *
1605
+ * The order of a derived source does not carry into the query that reads it, so the reader sorts by sort keys: the projections that have the values of the sort expressions, as for an executed query, or projections of the sort expressions added to the source.
1606
+ * With a limit or an offset, the source sorts by the positions of the sort keys, so that the rows it chooses, their values, and their order in the reader come from one evaluation; so it does with `DISTINCT ON`, whose order chooses the first row of each group, and with a row lock, which takes the rows in the order of its query.
1607
+ * Without them, it has no order.
1608
+ * `offset` replaces the offset of `query` in the source, such as `OFFSET 0` that keeps PostgreSQL from merging it, and the source replaces the occurrence of a table `replaces` for its reader.
1609
+ */
1610
+ function deriveOrderedSource(query, ordered, offset = query.offset, replaces) {
1611
+ const { orderBy } = query;
1612
+ const projections = query.projections.slice();
1613
+ const sorted = query.limit !== void 0 || query.offset !== void 0 || query.distinctOn !== void 0 || query.lock !== void 0;
1614
+ const sortKeys = [];
1615
+ const positions = [];
1616
+ if (orderBy.length > 0 && (ordered || sorted)) for (let index = 0; index < orderBy.length; index++) {
1617
+ const { expression, direction, nulls } = orderBy[index];
1618
+ const position = projectSortKey(projections, expression, index);
1619
+ if (ordered) sortKeys.push({
1620
+ key: projections[position].key,
1621
+ direction,
1622
+ nulls
1623
+ });
1624
+ if (sorted) positions.push(Object.freeze({
1625
+ expression: createPositionNode(position),
1626
+ direction,
1627
+ nulls
1841
1628
  }));
1842
- const rows = deriveOrderedSource({
1843
- kind: "select",
1844
- from: node.from,
1845
- joins: noJoins,
1846
- projections,
1847
- filters,
1848
- orderBy: counted ? noOrder : orderBy,
1849
- limit: node.limit,
1850
- offset: node.offset,
1851
- rows: "many",
1852
- value: false,
1853
- guaranteedBy: void 0
1854
- }, field.ordered);
1855
- from = rows.source;
1856
- filters = noFilters;
1857
- if (!counted) {
1858
- const sourceArgs = [createNode({
1859
- kind: "column",
1860
- source: from,
1861
- key: "value"
1862
- })];
1863
- for (let index = 1; index < args.length; index++) sourceArgs.push(args[index]);
1864
- args = sourceArgs;
1865
- }
1866
- order = rows.order;
1867
1629
  }
1868
- const call = args === aggregate.arguments && order.length === 0 ? aggregate : createNode({
1869
- kind: "aggregate",
1870
- name: aggregate.name,
1871
- distinct: aggregate.distinct,
1872
- arguments: args,
1873
- orderBy: order
1630
+ const derivedQuery = Object.freeze({
1631
+ ...query,
1632
+ projections,
1633
+ orderBy: positions,
1634
+ offset
1874
1635
  });
1875
- const fallbacks = lowerEach(field.fallbacks, context, lowerExpression);
1876
- let value = call;
1877
- if (fallbacks.length > 0) {
1878
- const values = [call];
1879
- for (const fallback of fallbacks) values.push(fallback);
1880
- value = createList("coalesce(", values, ")");
1881
- }
1882
- return Object.freeze({
1883
- kind: "select",
1884
- from,
1885
- joins: noJoins,
1886
- projections: [value === aggregate ? field : Object.freeze({
1887
- key: field.key,
1888
- expression: value,
1889
- type: field.type
1890
- })],
1891
- filters,
1892
- orderBy: noOrder,
1893
- limit: void 0,
1894
- offset: void 0,
1895
- rows: node.rows,
1896
- value: true,
1897
- guaranteedBy: void 0
1636
+ const source = Object.freeze(replaces === void 0 ? {
1637
+ kind: "derived",
1638
+ query: derivedQuery,
1639
+ lateral: false
1640
+ } : {
1641
+ kind: "derived",
1642
+ query: derivedQuery,
1643
+ lateral: false,
1644
+ replaces
1898
1645
  });
1646
+ const order = [];
1647
+ for (const { key, direction, nulls } of sortKeys) order.push(Object.freeze({
1648
+ expression: createNode({
1649
+ kind: "column",
1650
+ source,
1651
+ key
1652
+ }),
1653
+ direction,
1654
+ nulls
1655
+ }));
1656
+ return {
1657
+ source,
1658
+ order
1659
+ };
1899
1660
  }
1900
1661
  /**
1901
- * Tells whether `node` refers to `source` outside the queries nested in it.
1662
+ * Returns the position of the projection that sorts by `expression`: the projection of `findValueProjection`, or one added to `projections`.
1902
1663
  *
1903
- * A reference inside a nested query is not counted, so an argument that refers to the source only there is read from a derived source, which is correct either way.
1664
+ * `index` is the position of the expression in the order.
1904
1665
  */
1905
- function refersToSource(node, source) {
1906
- switch (node.kind) {
1907
- case "column": return node.source === source;
1908
- case "param":
1909
- case "boolean":
1910
- case "values":
1911
- case "nestedQuery":
1912
- case "tableName":
1913
- case "subquery":
1914
- case "exists":
1915
- case "textSubquery": return false;
1916
- case "cast":
1917
- case "not":
1918
- case "isNull":
1919
- case "inQuery": return refersToSource(node.operand, source);
1920
- case "and":
1921
- case "or": return node.operands.some((operand) => refersToSource(operand, source));
1922
- case "comparison": return refersToSource(node.left, source) || refersToSource(node.right, source);
1923
- case "in": return refersToSource(node.operand, source) || node.list.some((item) => refersToSource(item, source));
1924
- case "raw": return node.values.some((value) => refersToSource(value, source));
1925
- case "aggregate": return node.arguments.some((argument) => refersToSource(argument, source));
1926
- default: return node;
1927
- }
1666
+ function projectSortKey(projections, expression, index) {
1667
+ const position = findValueProjection(projections, expression);
1668
+ if (position !== -1) return position;
1669
+ projections.push(Object.freeze({
1670
+ key: createSortProjectionKey(projections, index),
1671
+ expression,
1672
+ type: text
1673
+ }));
1674
+ return projections.length - 1;
1928
1675
  }
1929
- /** Lowers a query of `exists` to `EXISTS` of the rows that its filters, limit, and offset choose. */
1930
- function lowerExists(node, context) {
1931
- checkRelation(node, context);
1932
- return createNode({
1933
- kind: "exists",
1934
- query: Object.freeze({
1935
- kind: "select",
1936
- from: node.from,
1937
- joins: noJoins,
1938
- projections: noProjections,
1939
- filters: lowerFilters(node.filters, context),
1940
- orderBy: noOrder,
1941
- limit: node.limit,
1942
- offset: node.offset,
1943
- rows: "many",
1944
- value: false,
1945
- guaranteedBy: void 0
1946
- })
1947
- });
1676
+ /** Creates the key of the sort key projection at `index` of the sort keys, which no other projection has. */
1677
+ function createSortProjectionKey(projections, index) {
1678
+ const base = `$order${index + 1}`;
1679
+ let key = base;
1680
+ for (let number = 2; projections.some((projection) => projection.key === key); number++) key = `${base}_${number}`;
1681
+ return key;
1948
1682
  }
1949
- /** Lowers a query of `exists` to a statement without a source of one row of `EXISTS` of its rows. */
1950
- function selectExists(node, context) {
1683
+ // src/lowering/nested.ts
1684
+ /** Maximum number of arguments of a PostgreSQL function, `FUNC_MAX_ARGS` of its default build. */
1685
+ const maxFunctionArguments = 100;
1686
+ /** Number `0`, the offset that keeps PostgreSQL from merging a derived source into its query. */
1687
+ const zeroNode = /* @__PURE__ */ createNode({
1688
+ kind: "raw",
1689
+ fragments: ["0"],
1690
+ values: []
1691
+ });
1692
+ /**
1693
+ * Creates the projection of the rows of `query` packed as JSON under `key`, selected as a scalar subquery and decoded by the result plan of `query`.
1694
+ *
1695
+ * Rows `many` are one array, and the other rows modes are one packed row or `NULL` without a row; a scalar subquery fails with several rows.
1696
+ */
1697
+ function projectRows(key, query) {
1698
+ const packed = packRows(query);
1699
+ const { nested } = packed.projections[0];
1951
1700
  return Object.freeze({
1952
- kind: "select",
1953
- from: void 0,
1954
- joins: noJoins,
1955
- projections: [projectExists(node.projections[0].key, node, context)],
1956
- filters: noFilters,
1957
- orderBy: noOrder,
1958
- limit: void 0,
1959
- offset: void 0,
1960
- rows: node.rows,
1961
- value: true,
1962
- guaranteedBy: void 0
1701
+ key,
1702
+ expression: createNode({
1703
+ kind: "subquery",
1704
+ query: packed
1705
+ }),
1706
+ nested
1963
1707
  });
1964
1708
  }
1965
- /** Creates the projection of `EXISTS` of the rows of `node`, a query of `exists`, under `key`, decoded by the type of the projection of `exists`. */
1966
- function projectExists(key, node, context) {
1967
- return Object.freeze({
1968
- key,
1969
- expression: lowerExists(node, context),
1970
- type: node.projections[0].type
1709
+ /**
1710
+ * Creates a query whose only projection is the rows of `query` packed as JSON, a field decoded by the result plan of `query`.
1711
+ *
1712
+ * Rows `many` are packed as an array in the order of `query`, and the created query returns one row.
1713
+ * Otherwise the created query returns a packed row for each row of `query`, so a scalar subquery of it gives the packed row, `NULL` without a row, and fails with several rows.
1714
+ */
1715
+ function packRows(query) {
1716
+ const { projections } = query;
1717
+ const many = query.rows === "many";
1718
+ const { source, order } = deriveOrderedSource(query, many, !query.distinct && query.distinctOn === void 0 && query.groupBy === void 0 && query.lock === void 0 && query.limit === void 0 && query.offset === void 0 && projections.some((projection) => projection.nested === void 0 && !isTableColumn(projection.expression)) ? zeroNode : query.offset);
1719
+ const wide = projections.length > maxFunctionArguments;
1720
+ const values = [];
1721
+ for (const projection of projections) {
1722
+ const value = createRef(source, projection.key);
1723
+ if (projection.nested !== void 0) values.push(value);
1724
+ else values.push(wide ? createList("to_json(", [packScalar(value)], ")") : packScalar(value));
1725
+ }
1726
+ const row = wide ? createList("array_to_json(ARRAY[", values, "])") : createList("json_build_array(", values, ")");
1727
+ let packed = row;
1728
+ if (many) packed = createNode({
1729
+ kind: "raw",
1730
+ fragments: ["coalesce(", ", '[]'::json)"],
1731
+ values: [createNode({
1732
+ kind: "aggregate",
1733
+ name: "json_agg",
1734
+ distinct: false,
1735
+ arguments: [row],
1736
+ orderBy: order,
1737
+ filter: void 0
1738
+ })]
1739
+ });
1740
+ const plan = Object.freeze({
1741
+ fields: projections,
1742
+ rows: query.rows,
1743
+ value: query.value,
1744
+ guaranteedBy: query.guaranteedBy,
1745
+ recordTemplate: query.recordTemplate,
1746
+ conversion: query.conversion
1971
1747
  });
1748
+ const projection = Object.freeze({
1749
+ key: "rows",
1750
+ expression: packed,
1751
+ nested: plan
1752
+ });
1753
+ return createSelectNode(source, [projection]);
1972
1754
  }
1973
- /** Lowers a query of `$select` to a statement without a source, which returns one row of its fields. */
1974
- function lowerRecord(node, context) {
1975
- return Object.freeze({
1976
- kind: "select",
1977
- from: void 0,
1978
- joins: noJoins,
1979
- projections: lowerProjections(dropLiterals(node.projections), context),
1980
- filters: noFilters,
1981
- orderBy: noOrder,
1982
- limit: void 0,
1983
- offset: void 0,
1984
- rows: "one",
1985
- value: false,
1986
- guaranteedBy: void 0,
1987
- recordTemplate: createRecordTemplate(node.projections)
1755
+ /** Tells whether `node` is a column of a table, which PostgreSQL reads rather than evaluates, so it can be repeated. */
1756
+ function isTableColumn(node) {
1757
+ return node.kind === "column" && node.source.kind === "table";
1758
+ }
1759
+ /**
1760
+ * Packs a scalar as its PostgreSQL text representation, or `NULL`.
1761
+ *
1762
+ * `format` uses the output function of the type, as the driver receives the values of a row; a cast to `text` differs from it for types such as `boolean`, `inet`, and `char`.
1763
+ */
1764
+ function packScalar(value) {
1765
+ return createNode({
1766
+ kind: "raw",
1767
+ fragments: [
1768
+ "CASE WHEN ",
1769
+ " IS NOT DISTINCT FROM NULL THEN NULL ELSE format('%s', ",
1770
+ ") END"
1771
+ ],
1772
+ values: [value, value]
1773
+ });
1774
+ }
1775
+ function createRef(source, key) {
1776
+ return createNode({
1777
+ kind: "column",
1778
+ source,
1779
+ key
1988
1780
  });
1989
1781
  }
1782
+ // src/lowering/projection.ts
1990
1783
  /**
1991
1784
  * Lowers the fields of a query to projections, packing the rows of each nested query into the value of its field, or selecting the value of an aggregate query or `EXISTS` of a query of `exists`, and replacing the queries in the expressions of the other fields; checks them as `lowerQuery` does.
1992
1785
  *
@@ -2016,11 +1809,18 @@ function lowerProjections(selected, context) {
2016
1809
  }
2017
1810
  return lowered ?? selected;
2018
1811
  }
2019
- /** Creates the projection of the value of `node`, a nested query, under `key`: `EXISTS` of a query of `exists`, the value of an aggregate query, or the packed rows of another query. */
1812
+ /** Creates the projection of the value of `node`, a nested query, under `key`: `EXISTS` of a query of `exists`, the value of an aggregate query, or the packed rows of another query or of one whose result code converts. */
2020
1813
  function projectQuery(key, node, context) {
2021
- if (isExistsQuery(node)) return projectExists(key, node, context);
2022
- const query = lowerSelect(node, context, false);
2023
- return isAggregateQuery(node) ? projectAggregateValue(key, query) : projectRows(key, query);
1814
+ if (!isSelectedAsValue(node)) return projectRows(key, context.lowerSelect(node, false));
1815
+ return isExistsQuery(node) ? projectExists(key, node, context) : projectAggregateValue(key, context.lowerSelect(node, false));
1816
+ }
1817
+ /** Creates the projection of `EXISTS` of the rows of `node`, a query of `exists`, under `key`, decoded by the type of the projection of `exists`. */
1818
+ function projectExists(key, node, context) {
1819
+ return Object.freeze({
1820
+ key,
1821
+ expression: context.lowerExists(node),
1822
+ type: node.projections[0].type
1823
+ });
2024
1824
  }
2025
1825
  /** Creates the projection of the value of `query`, the statement of an aggregate query, under `key`, selected as a scalar subquery and decoded by the type of the aggregate. */
2026
1826
  function projectAggregateValue(key, query) {
@@ -2033,190 +1833,1130 @@ function projectAggregateValue(key, query) {
2033
1833
  type: query.projections[0].type
2034
1834
  });
2035
1835
  }
2036
- /** Lowers the filters of a query, replacing the queries in their expressions; without queries, it returns `filters` itself. */
2037
- function lowerFilters(filters, context) {
2038
- const { relation, scope, user } = filters;
2039
- const loweredRelation = relation === void 0 ? void 0 : lowerExpression(relation, context);
2040
- const loweredScope = scope === void 0 ? void 0 : lowerExpression(scope, context);
2041
- const loweredUser = user === void 0 ? void 0 : lowerExpression(user, context);
2042
- if (loweredRelation === relation && loweredScope === scope && loweredUser === user) return filters;
2043
- const lowered = {};
2044
- if (loweredRelation !== void 0) lowered.relation = loweredRelation;
2045
- if (loweredScope !== void 0) lowered.scope = loweredScope;
2046
- if (loweredUser !== void 0) lowered.user = loweredUser;
2047
- return Object.freeze(lowered);
1836
+ /** Returns the fields of `selected` that a statement selects, or `selected` itself without literals. */
1837
+ function dropLiterals(selected) {
1838
+ if (!selected.some(isLiteralSelection)) return selected;
1839
+ const fields = [];
1840
+ for (const field of selected) if (!isLiteralSelection(field)) fields.push(field);
1841
+ return fields;
1842
+ }
1843
+ /** Creates the template of the records of `selected`: every field in its order with the value of a literal, or `undefined` without literals. */
1844
+ function createRecordTemplate(selected) {
1845
+ if (!selected.some(isLiteralSelection)) return;
1846
+ const template = [];
1847
+ for (const field of selected) template.push(Object.freeze({
1848
+ key: field.key,
1849
+ value: isLiteralSelection(field) ? field.literal : void 0
1850
+ }));
1851
+ return template;
2048
1852
  }
1853
+ // src/lowering/distinct.ts
2049
1854
  /**
2050
- * Lowers the sort keys of a query, replacing the queries in their expressions; without queries, it returns `orderBy` itself.
1855
+ * Rejects a query of `distinct` of the lowered `projections` and `orderBy` that `SELECT DISTINCT` cannot give the rows of, with an error that does not depend on where the query is:
2051
1856
  *
2052
- * A sort key of a field of `selected`, the fields of the query, takes the expression of its projection among `projections`, the lowered fields, so that the statement still finds the projection that has its value.
2053
- * A field of an aggregate or of `exists` is identified by the node of its reference, which holds the field.
1857
+ * - A query without projections, such as of only literals, has nothing to compare, and PostgreSQL has no syntax for it.
1858
+ * - Nested rows are JSON, which PostgreSQL cannot compare.
1859
+ * - PostgreSQL rejects a sort key that is not a projection, since duplicates can differ in its value, whereas a packed query would add it to the projections of its derived source and compare it too.
1860
+ * Only a projection of the same column or of the same expression node is sure to have its value, as in `findValueProjection`.
2054
1861
  */
2055
- function lowerOrder(orderBy, context, selected, projections) {
2056
- let lowered;
2057
- for (let index = 0; index < orderBy.length; index++) {
2058
- const order = orderBy[index];
2059
- const { expression } = order;
2060
- const position = selected === void 0 || projections === void 0 || projections === selected ? -1 : selected.findIndex((field) => isFieldValue(field, expression));
2061
- const sorted = position === -1 ? lowerExpression(expression, context) : projections[position].expression;
2062
- if (lowered === void 0 && sorted === expression) continue;
2063
- lowered ??= orderBy.slice(0, index);
2064
- lowered.push(sorted === expression ? order : Object.freeze({
2065
- expression: sorted,
2066
- direction: order.direction,
2067
- nulls: order.nulls
2068
- }));
2069
- }
2070
- return lowered ?? orderBy;
1862
+ function checkDistinct(projections, orderBy) {
1863
+ if (projections.length === 0) throw new Error("distinct requires at least one selected column or SQL expression; literal fields are not compared");
1864
+ for (const { key, nested } of projections) if (nested !== void 0) throw new Error(`distinct cannot compare the nested rows of the selected field "${key}"`);
1865
+ for (const { expression } of orderBy) if (findValueProjection(projections, expression) === -1) throw new Error("A query of distinct sorts only by its selected fields, since duplicates can differ in any other value; select the value to sort by it");
2071
1866
  }
2072
- /** Tells whether the sort expression `expression` is the value of `field`: its expression, or for a field of an aggregate or of `exists`, the node of its reference in the callback of `orderBy`. */
2073
- function isFieldValue(field, expression) {
2074
- return isNestedSelection(field) ? expression.kind === "nestedQuery" && expression.field === field : field.expression === expression;
1867
+ /**
1868
+ * Rejects a query of `distinctOn` of the lowered `projections`, `keys`, and `orderBy` that `SELECT DISTINCT ON` cannot give the rows of, with an error that does not depend on where the query is: a query without projections, such as of only literals, since PostgreSQL requires a select list with `DISTINCT ON`, and an order that `checkDistinctOnOrder` rejects.
1869
+ */
1870
+ function checkDistinctOn(projections, keys, orderBy) {
1871
+ if (projections.length === 0) throw new Error("distinctOn requires at least one selected column or SQL expression; literal fields are not selected");
1872
+ checkDistinctOnOrder(projections, keys, orderBy);
2075
1873
  }
2076
1874
  /**
2077
- * Lowers an expression, replacing each query in it and checking the query as a nested query.
2078
- * A query of `exists`, such as in a condition, becomes `EXISTS` of its rows, another query of one value a scalar subquery of its value, the query of the values of `IN` its statement, and another query in SQL text its statement in parentheses.
1875
+ * Rejects an order of a query of `distinctOn` of the lowered `projections`, `keys`, and `orderBy` that sorts by a value other than the keys before it sorts by all of them, in any order and direction, which PostgreSQL rejects, since the order sorts the groups apart and then chooses the first row of each; an order of only keys may omit some, which PostgreSQL adds.
2079
1876
  *
2080
- * It returns `node` itself when it holds no query, and creates only the nodes that hold one.
1877
+ * A sort key is a key when it is the same column, or the same expression node that a projection of the query has, as `findValueProjection` tells, so that both compile to the same column or position.
1878
+ * Another expression may compile at each place with parameters and aliases of its own, so PostgreSQL may find the two unequal; the check runs before packing, which would add the expression to the projections of its derived source and make both positions, so that it counts as another value wherever the query is.
2081
1879
  */
2082
- function lowerExpression(node, context) {
2083
- switch (node.kind) {
2084
- case "column":
2085
- case "param":
2086
- case "boolean":
2087
- case "values":
2088
- case "tableName":
2089
- case "subquery":
2090
- case "exists":
2091
- case "textSubquery": return node;
2092
- case "nestedQuery": return lowerNestedQuery(node, context);
2093
- case "cast": {
2094
- const operand = lowerExpression(node.operand, context);
2095
- return operand === node.operand ? node : createNode({
2096
- kind: "cast",
2097
- operand,
2098
- type: node.type
2099
- });
2100
- }
2101
- case "not": {
2102
- const operand = lowerExpression(node.operand, context);
2103
- return operand === node.operand ? node : createNode({
2104
- kind: "not",
2105
- operand
2106
- });
1880
+ function checkDistinctOnOrder(projections, keys, orderBy) {
1881
+ const isKey = (key, expression) => isSameValue(key, expression) && (key.kind === "column" || findValueProjection(projections, key) !== -1);
1882
+ let leading = 0;
1883
+ while (leading < orderBy.length && keys.some((key) => isKey(key, orderBy[leading].expression))) leading++;
1884
+ if (leading === orderBy.length) return;
1885
+ for (const key of keys) {
1886
+ let sorted = false;
1887
+ for (let index = 0; index < leading && !sorted; index++) sorted = isKey(key, orderBy[index].expression);
1888
+ if (!sorted) throw new Error("A query of distinctOn must sort by all its keys before any other value; sort by a key of an expression through its selected field");
1889
+ }
1890
+ }
1891
+ /**
1892
+ * Lowers the rows of `node`, a query of `distinct` or `distinctOn` made by an aggregate method or `exists`, to the statement that gives them, which an aggregate reads from a derived source and `EXISTS` reads as it is.
1893
+ *
1894
+ * It lowers the fields that the query kept, its keys, its order, and `argument`, the first argument of the aggregate, through those fields, as `lowerSelectedValue` does, so that each value of a selected field is its projection, and checks the query as the statement of the query of those fields is checked, except that a query of `distinctOn` needs no selected field, since the statement selects its keys.
1895
+ *
1896
+ * - The statement of `distinct` selects the fields, which `DISTINCT` compares, and `argument` must be one of them, as a sort key must be, since duplicates can differ in any other value.
1897
+ * - The statement of `distinctOn` selects `argument` and each key that it does not select otherwise, so that it has a select list, which PostgreSQL requires with `DISTINCT ON`.
1898
+ * It selects no other field, since an aggregate reads the rows of the source rather than of the select list, as for a query without `distinctOn`, so it does not lower the fields of nested rows, which neither a key nor a sort key reads.
1899
+ *
1900
+ * The statement has the order of the query when `sorted` is set; the number of the rows, which `count(*)` and `EXISTS` read, does not depend on it.
1901
+ */
1902
+ function lowerDistinctRows(node, context, argument, sorted) {
1903
+ const fields = dropLiterals(node.distinctFields);
1904
+ let selected = fields;
1905
+ if (!node.distinct) {
1906
+ const scalars = [];
1907
+ for (const field of fields) if (!isNestedSelection(field) || isSelectedAsValue(field.query)) scalars.push(field);
1908
+ selected = scalars;
1909
+ }
1910
+ const projections = lowerProjections(selected, context);
1911
+ const orderBy = lowerOrder(node.orderBy, context, selected, projections);
1912
+ const groupBy = lowerKeys(node.groupBy, context, selected, projections);
1913
+ const keys = lowerKeys(node.distinctOn, context, selected, projections);
1914
+ const value = argument === void 0 ? void 0 : lowerSelectedValue(argument, context, selected, projections);
1915
+ let sourced;
1916
+ let valueKey;
1917
+ if (keys === void 0) {
1918
+ checkDistinct(projections, orderBy);
1919
+ sourced = projections;
1920
+ if (value !== void 0) {
1921
+ const position = findValueProjection(projections, value);
1922
+ if (position === -1) throw new Error("An aggregate of a query of distinct reads only its selected fields, since duplicates can differ in any other value; select the value to aggregate it");
1923
+ valueKey = projections[position].key;
2107
1924
  }
2108
- case "isNull": {
2109
- const operand = lowerExpression(node.operand, context);
2110
- return operand === node.operand ? node : createNode({
2111
- kind: "isNull",
2112
- operand
2113
- });
1925
+ } else {
1926
+ checkDistinctOnOrder(projections, keys, orderBy);
1927
+ const keyed = [];
1928
+ if (value !== void 0) {
1929
+ valueKey = "value";
1930
+ keyed.push(Object.freeze({
1931
+ key: valueKey,
1932
+ expression: value,
1933
+ type: text
1934
+ }));
2114
1935
  }
2115
- case "and":
2116
- case "or": {
2117
- const operands = lowerEach(node.operands, context, lowerExpression);
2118
- return operands === node.operands ? node : createNode({
2119
- kind: node.kind,
2120
- operands
2121
- });
1936
+ for (let index = 0; index < keys.length; index++) {
1937
+ const key = keys[index];
1938
+ if (findValueProjection(keyed, key) === -1) keyed.push(Object.freeze({
1939
+ key: `$key${index + 1}`,
1940
+ expression: key,
1941
+ type: text
1942
+ }));
2122
1943
  }
2123
- case "comparison": {
2124
- const left = lowerExpression(node.left, context);
2125
- const right = lowerExpression(node.right, context);
2126
- return left === node.left && right === node.right ? node : createNode({
2127
- kind: "comparison",
2128
- operator: node.operator,
2129
- left,
2130
- right
2131
- });
1944
+ sourced = keyed;
1945
+ }
1946
+ return {
1947
+ query: Object.freeze({
1948
+ kind: "select",
1949
+ from: node.from,
1950
+ joins: noJoins,
1951
+ projections: sourced,
1952
+ filters: lowerFilters(node.filters, context),
1953
+ groupBy,
1954
+ having: lowerValue(node.having, context),
1955
+ orderBy: sorted ? orderBy : noOrder,
1956
+ limit: node.limit,
1957
+ offset: node.offset,
1958
+ distinct: node.distinct,
1959
+ distinctOn: keys,
1960
+ rows: "many",
1961
+ value: false,
1962
+ guaranteedBy: void 0
1963
+ }),
1964
+ valueKey
1965
+ };
1966
+ }
1967
+ // src/lowering/aggregate.ts
1968
+ /** Lowers an aggregate query to a statement of the value of its aggregate over the rows that its filters, limit, and offset choose, also the distinct rows of `distinct` and the first rows of `distinctOn`. */
1969
+ function lowerAggregate(node, context) {
1970
+ const field = node.projections[0];
1971
+ const aggregate = field.expression;
1972
+ const counted = aggregate === countProjection.expression;
1973
+ let from = node.from;
1974
+ let filters = noFilters;
1975
+ let args = aggregate.arguments;
1976
+ let order = noOrder;
1977
+ let rows;
1978
+ let valueKey;
1979
+ if (node.distinctFields !== void 0) {
1980
+ const distinctRows = lowerDistinctRows(node, context, counted ? void 0 : aggregate.arguments[0], !counted);
1981
+ rows = distinctRows.query;
1982
+ valueKey = distinctRows.valueKey;
1983
+ } else {
1984
+ const orderBy = lowerOrder(node.orderBy, context);
1985
+ const groupBy = lowerKeys(node.groupBy, context);
1986
+ filters = lowerFilters(node.filters, context);
1987
+ args = lowerEach(aggregate.arguments, context, lowerExpression);
1988
+ order = field.ordered ? orderBy : noOrder;
1989
+ if (groupBy !== void 0 || node.limit !== void 0 || node.offset !== void 0 || !counted && !refersToSource(args[0], node.from)) {
1990
+ const projections = [];
1991
+ if (!counted) {
1992
+ valueKey = "value";
1993
+ projections.push(Object.freeze({
1994
+ key: valueKey,
1995
+ expression: args[0],
1996
+ type: field.type
1997
+ }));
1998
+ }
1999
+ rows = {
2000
+ kind: "select",
2001
+ from: node.from,
2002
+ joins: noJoins,
2003
+ projections,
2004
+ filters,
2005
+ groupBy,
2006
+ having: lowerValue(node.having, context),
2007
+ orderBy: counted ? noOrder : orderBy,
2008
+ limit: node.limit,
2009
+ offset: node.offset,
2010
+ rows: "many",
2011
+ value: false,
2012
+ guaranteedBy: void 0
2013
+ };
2132
2014
  }
2133
- case "in": {
2134
- const operand = lowerExpression(node.operand, context);
2135
- const list = lowerEach(node.list, context, lowerExpression);
2136
- return operand === node.operand && list === node.list ? node : createNode({
2137
- kind: "in",
2138
- operand,
2139
- list
2140
- });
2015
+ }
2016
+ if (rows !== void 0) {
2017
+ const derived = deriveOrderedSource(rows, field.ordered);
2018
+ from = derived.source;
2019
+ filters = noFilters;
2020
+ if (valueKey !== void 0) {
2021
+ const sourceArgs = [createNode({
2022
+ kind: "column",
2023
+ source: from,
2024
+ key: valueKey
2025
+ })];
2026
+ for (let index = 1; index < args.length; index++) sourceArgs.push(args[index]);
2027
+ args = sourceArgs;
2141
2028
  }
2142
- case "inQuery": {
2143
- const operand = lowerExpression(node.operand, context);
2144
- const query = node.query.kind === "nestedQuery" ? lowerQueryOfValues(node.query, context) : node.query;
2145
- return operand === node.operand && query === node.query ? node : createNode({
2146
- kind: "inQuery",
2147
- operand,
2148
- query
2149
- });
2029
+ order = derived.order;
2030
+ }
2031
+ const call = args === aggregate.arguments && order.length === 0 ? aggregate : createNode({
2032
+ kind: "aggregate",
2033
+ name: aggregate.name,
2034
+ distinct: aggregate.distinct,
2035
+ arguments: args,
2036
+ orderBy: order,
2037
+ filter: aggregate.filter
2038
+ });
2039
+ const fallbacks = lowerEach(field.fallbacks, context, lowerExpression);
2040
+ let value = call;
2041
+ if (fallbacks.length > 0) {
2042
+ const values = [call];
2043
+ for (const fallback of fallbacks) values.push(fallback);
2044
+ value = createList("coalesce(", values, ")");
2045
+ }
2046
+ return Object.freeze({
2047
+ kind: "select",
2048
+ from,
2049
+ joins: noJoins,
2050
+ projections: [value === aggregate ? field : Object.freeze({
2051
+ key: field.key,
2052
+ expression: value,
2053
+ type: field.type
2054
+ })],
2055
+ filters,
2056
+ orderBy: noOrder,
2057
+ limit: void 0,
2058
+ offset: void 0,
2059
+ rows: node.rows,
2060
+ value: true,
2061
+ guaranteedBy: void 0
2062
+ });
2063
+ }
2064
+ /**
2065
+ * Tells whether `node` refers to `source` outside the queries nested in it.
2066
+ *
2067
+ * A reference inside a nested query is not counted, so an argument that refers to the source only there is read from a derived source, which is correct either way.
2068
+ */
2069
+ function refersToSource(node, source) {
2070
+ switch (node.kind) {
2071
+ case "column": return node.source === source;
2072
+ case "param":
2073
+ case "boolean":
2074
+ case "values":
2075
+ case "nestedQuery":
2076
+ case "tableName":
2077
+ case "subquery":
2078
+ case "exists":
2079
+ case "textSubquery": return false;
2080
+ case "cast":
2081
+ case "not":
2082
+ case "isNull":
2083
+ case "inQuery": return refersToSource(node.operand, source);
2084
+ case "and":
2085
+ case "or": return node.operands.some((operand) => refersToSource(operand, source));
2086
+ case "comparison": return refersToSource(node.left, source) || refersToSource(node.right, source);
2087
+ case "in": return refersToSource(node.operand, source) || node.list.some((item) => refersToSource(item, source));
2088
+ case "raw": return node.values.some((value) => refersToSource(value, source));
2089
+ case "aggregate": return node.arguments.some((argument) => refersToSource(argument, source)) || node.filter !== void 0 && refersToSource(node.filter, source);
2090
+ default: return node;
2091
+ }
2092
+ }
2093
+ // src/lowering/exists.ts
2094
+ /** Lowers a query of `exists` to `EXISTS` of the rows that its filters, limit, and offset choose, also the distinct rows of `distinct` and the first rows of `distinctOn`. */
2095
+ function lowerExists(node, context) {
2096
+ checkRelation(node, context);
2097
+ return createNode({
2098
+ kind: "exists",
2099
+ query: node.distinctFields === void 0 ? Object.freeze({
2100
+ kind: "select",
2101
+ from: node.from,
2102
+ joins: noJoins,
2103
+ projections: noProjections,
2104
+ filters: lowerFilters(node.filters, context),
2105
+ groupBy: lowerKeys(node.groupBy, context),
2106
+ having: lowerValue(node.having, context),
2107
+ orderBy: noOrder,
2108
+ limit: node.limit,
2109
+ offset: node.offset,
2110
+ rows: "many",
2111
+ value: false,
2112
+ guaranteedBy: void 0
2113
+ }) : lowerDistinctRows(node, context, void 0, false).query
2114
+ });
2115
+ }
2116
+ // src/ast/references.ts
2117
+ /** Adds to `keys` the key of each column reference to `source` in `node` at any depth, including the queries nested in it. */
2118
+ function collectColumnKeys(node, source, keys) {
2119
+ visitNodes(node, (child) => {
2120
+ if (child.kind === "column" && child.source === source) keys.add(child.key);
2121
+ });
2122
+ }
2123
+ /**
2124
+ * Tells whether `node` holds, at any depth, what may aggregate the rows of the query of `source`: an `aggregate` node or a SQL fragment that refers to a column of `source` at any depth, also in the queries nested in it.
2125
+ *
2126
+ * PostgreSQL assigns an aggregate whose arguments and filter refer only to the sources of an enclosing query to that query, also through a query nested in them ([PostgreSQL](https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-AGGREGATES)), so such a call in a nested query, such as `sum` of a column of the parent row, aggregates the rows of the query of `source`.
2127
+ * Lowering does not parse SQL fragments to identify their aggregates, so a fragment counts as such a call.
2128
+ *
2129
+ * It is conservative: an aggregate whose arguments read both `source` and its own query belongs to its own query, yet it counts, since this walk cannot tell a source of the query that holds the aggregate from one of an enclosing query.
2130
+ * So does a scalar fragment, also one that reads `source` only through a query correlated with it, such as of a relation.
2131
+ */
2132
+ function mayAggregateSource(node, source) {
2133
+ let found = false;
2134
+ const check = (value) => {
2135
+ if (value.kind === "column" && value.source === source) found = true;
2136
+ };
2137
+ visitNodes(node, (child) => {
2138
+ if (!found && (child.kind === "aggregate" || child.kind === "raw")) visitNodes(child, check);
2139
+ });
2140
+ return found;
2141
+ }
2142
+ /**
2143
+ * Tells whether an aggregate belongs to an enclosing query rather than the query of `source`.
2144
+ *
2145
+ * Only references free in its arguments, order, and filter decide its owner: columns bound by a subquery do not count, but references through that subquery to its enclosing queries do.
2146
+ * Without such references, an aggregate of constants belongs to the query that contains it.
2147
+ * The node must have been lowered, so that subqueries expose their sources.
2148
+ */
2149
+ function aggregatesOuterSource(node, source) {
2150
+ let local = false;
2151
+ let outer = false;
2152
+ const queries = [];
2153
+ visitNodes(node, (child) => {
2154
+ if (child.kind !== "column" || local) return;
2155
+ for (const query of queries) {
2156
+ if (bindsSource(query.from, child.source)) return;
2157
+ for (const join of query.joins) if (bindsSource(join.source, child.source)) return;
2150
2158
  }
2151
- case "raw": {
2152
- const values = lowerEach(node.values, context, lowerExpression);
2153
- return values === node.values ? node : createNode({
2154
- kind: "raw",
2155
- fragments: node.fragments,
2156
- values
2159
+ if (child.source === source) local = true;
2160
+ else outer = true;
2161
+ }, queries);
2162
+ return outer && !local;
2163
+ }
2164
+ /** Tells whether a declared source binds a reference, including the table occurrence a derived source replaces. */
2165
+ function bindsSource(declared, source) {
2166
+ return declared === source || declared?.kind === "derived" && declared.replaces === source;
2167
+ }
2168
+ /**
2169
+ * Calls `visit` for `node` and each expression node in it at any depth, including the queries nested in it.
2170
+ * When supplied, `queries` holds the nested queries enclosing each node passed to `visit`.
2171
+ */
2172
+ function visitNodes(node, visit, queries) {
2173
+ visit(node);
2174
+ switch (node.kind) {
2175
+ case "column":
2176
+ case "param":
2177
+ case "boolean":
2178
+ case "tableName":
2179
+ case "values":
2180
+ case "nestedQuery": return;
2181
+ case "cast":
2182
+ case "not":
2183
+ case "isNull":
2184
+ visitNodes(node.operand, visit, queries);
2185
+ return;
2186
+ case "and":
2187
+ case "or":
2188
+ for (const operand of node.operands) visitNodes(operand, visit, queries);
2189
+ return;
2190
+ case "comparison":
2191
+ visitNodes(node.left, visit, queries);
2192
+ visitNodes(node.right, visit, queries);
2193
+ return;
2194
+ case "in":
2195
+ visitNodes(node.operand, visit, queries);
2196
+ for (const item of node.list) visitNodes(item, visit, queries);
2197
+ return;
2198
+ case "inQuery":
2199
+ visitNodes(node.operand, visit, queries);
2200
+ if (node.query.kind === "select") visitQuery(node.query, visit, queries);
2201
+ return;
2202
+ case "raw":
2203
+ for (const value of node.values) visitNodes(value, visit, queries);
2204
+ return;
2205
+ case "subquery":
2206
+ case "exists":
2207
+ case "textSubquery":
2208
+ visitQuery(node.query, visit, queries);
2209
+ return;
2210
+ case "aggregate":
2211
+ for (const argument of node.arguments) visitNodes(argument, visit, queries);
2212
+ for (const order of node.orderBy) visitNodes(order.expression, visit, queries);
2213
+ if (node.filter !== void 0) visitNodes(node.filter, visit, queries);
2214
+ return;
2215
+ }
2216
+ }
2217
+ /**
2218
+ * Calls `visit` for each expression node in the clauses and the derived sources of `query` at any depth.
2219
+ * When supplied, `queries` holds the nested queries enclosing each node passed to `visit`; this call adds `query` for its duration.
2220
+ */
2221
+ function visitQuery(query, visit, queries) {
2222
+ queries?.push(query);
2223
+ const { from, filters } = query;
2224
+ if (from?.kind === "derived") visitQuery(from.query, visit, queries);
2225
+ for (const join of query.joins) {
2226
+ if (join.source.kind === "derived") visitQuery(join.source.query, visit, queries);
2227
+ visitNodes(join.on, visit, queries);
2228
+ }
2229
+ if (query.distinctOn !== void 0) for (const key of query.distinctOn) visitNodes(key, visit, queries);
2230
+ for (const projection of query.projections) visitNodes(projection.expression, visit, queries);
2231
+ if (filters.relation !== void 0) visitNodes(filters.relation, visit, queries);
2232
+ if (filters.scope !== void 0) visitNodes(filters.scope, visit, queries);
2233
+ if (filters.user !== void 0) visitNodes(filters.user, visit, queries);
2234
+ if (query.groupBy !== void 0) for (const key of query.groupBy) visitNodes(key, visit, queries);
2235
+ if (query.having !== void 0) visitNodes(query.having, visit, queries);
2236
+ for (const order of query.orderBy) visitNodes(order.expression, visit, queries);
2237
+ if (query.limit !== void 0) visitNodes(query.limit, visit, queries);
2238
+ if (query.offset !== void 0) visitNodes(query.offset, visit, queries);
2239
+ queries?.pop();
2240
+ }
2241
+ // src/lowering/group.ts
2242
+ /**
2243
+ * Rejects directly selected, unfiltered aggregates of an enclosing query in a query of groups.
2244
+ *
2245
+ * Types give these aggregates the nullability of their arguments in a nonempty group, but an enclosing query can have no rows.
2246
+ * A typed SQL fragment keeps its declared nullability and is the explicit escape hatch for an outer aggregate.
2247
+ */
2248
+ function checkGroupAggregates(projections, query) {
2249
+ for (const field of projections) {
2250
+ const expression = field.expression;
2251
+ if (expression.kind === "aggregate" && expression.name !== "count" && expression.filter === void 0 && aggregatesOuterSource(expression, query.from)) throw new Error(`An aggregate function of ${query.value ? "the grouped value" : `grouped field ${JSON.stringify(field.key)}`} refers only to enclosing queries; use an explicitly nullable sql expression for an outer aggregate`);
2252
+ }
2253
+ }
2254
+ // src/lowering/mutation.ts
2255
+ /** Lowers a mutation to its statement, replacing the queries in its expressions, and packing the rows of each nested query of `RETURNING` into the value of its field, or selecting the value of a nested aggregate query, as a select list does. */
2256
+ function lowerMutation(node, context) {
2257
+ const { target, returning, rows, value, conversion } = node;
2258
+ const recordTemplate = returning === void 0 ? void 0 : createRecordTemplate(returning);
2259
+ const lowered = returning === void 0 ? void 0 : lowerProjections(dropLiterals(returning), context);
2260
+ switch (node.kind) {
2261
+ case "insert": {
2262
+ const values = lowerEach(node.values, context, lowerRow);
2263
+ if (lowered === returning && values === node.values) return node;
2264
+ return Object.freeze({
2265
+ kind: "insert",
2266
+ target,
2267
+ columns: node.columns,
2268
+ values,
2269
+ returning: lowered,
2270
+ recordTemplate,
2271
+ conversion,
2272
+ rows,
2273
+ value
2157
2274
  });
2158
2275
  }
2159
- case "aggregate": {
2160
- const args = lowerEach(node.arguments, context, lowerExpression);
2161
- const orderBy = lowerOrder(node.orderBy, context);
2162
- return args === node.arguments && orderBy === node.orderBy ? node : createNode({
2163
- kind: "aggregate",
2164
- name: node.name,
2165
- distinct: node.distinct,
2166
- arguments: args,
2167
- orderBy
2168
- });
2276
+ case "update": {
2277
+ const set = lowerEach(node.set, context, lowerAssignment);
2278
+ const filters = lowerFilters(node.filters, context);
2279
+ if (lowered === returning && set === node.set && filters === node.filters) return node;
2280
+ return Object.freeze({
2281
+ kind: "update",
2282
+ target,
2283
+ set,
2284
+ filters,
2285
+ returning: lowered,
2286
+ recordTemplate,
2287
+ conversion,
2288
+ rows,
2289
+ value
2290
+ });
2291
+ }
2292
+ case "delete": {
2293
+ const filters = lowerFilters(node.filters, context);
2294
+ if (lowered === returning && filters === node.filters) return node;
2295
+ return Object.freeze({
2296
+ kind: "delete",
2297
+ target,
2298
+ filters,
2299
+ returning: lowered,
2300
+ recordTemplate,
2301
+ conversion,
2302
+ rows,
2303
+ value
2304
+ });
2169
2305
  }
2170
2306
  default: return node;
2171
2307
  }
2172
2308
  }
2309
+ /** Lowers a row of `VALUES` of an insert, whose `undefined` stands for `DEFAULT`. */
2310
+ function lowerRow(row, context) {
2311
+ return lowerEach(row, context, lowerValue);
2312
+ }
2313
+ function lowerAssignment(assignment, context) {
2314
+ const value = lowerExpression(assignment.value, context);
2315
+ return value === assignment.value ? assignment : Object.freeze({
2316
+ key: assignment.key,
2317
+ value
2318
+ });
2319
+ }
2320
+ // src/lowering/page.ts
2321
+ /**
2322
+ * Lowers `query`, the statement of a query on its table that sorts by its sort expressions, to a statement that evaluates its nested queries, apart from those that it sorts by, groups by, or compares, over the rows of a derived page, or returns `undefined` for a query that keeps its page on its table.
2323
+ * `queryFields` are the fields of the query without literals, whose lowered projections the statement has in the same order.
2324
+ * The derived source applies `DISTINCT ON`, the filters, the keys and the condition of the groups, the order, the limit, and the offset, and replaces the occurrence of the table.
2325
+ * It selects each key of `distinctOn` that it does not select otherwise, so that it has a select list, which PostgreSQL requires with `DISTINCT ON`, and evaluates each key once; a key of `groupBy` needs no projection of its own, since it compiles as the position of a projection that has its value or as its expression.
2326
+ *
2327
+ * A query keeps its page on its table without an offset and `distinctOn`, without nested queries that the page would evaluate over its rows, or when `mayAggregateSource` tells that such a nested query may aggregate the rows of the query, which the limit and the offset apply after.
2328
+ *
2329
+ * The source selects the columns of the table that the fields and the nested queries of the query read, under their keys, and the other scalar fields of the query, which it evaluates before the limit and the offset as the query would, such as a window function over all its rows or an aggregate of a group.
2330
+ * A field of an aggregate or of `exists` that the query sorts by or that is a key is such a scalar field: the order and the keys need its value for every row.
2331
+ * A column that no field reads stays out of the source, which could not select it beside an aggregate of a SQL fragment, such as `count(*)`.
2332
+ * The order of a derived source does not carry into the query that reads it, so the statement sorts the rows of the page again by the sort keys of the source, by positions when `positions` is set.
2333
+ */
2334
+ function lowerPage(query, queryFields, positions) {
2335
+ const { from, projections, orderBy, groupBy, distinctOn, offset } = query;
2336
+ if (offset === void 0 && distinctOn === void 0 || query.distinct || query.lock !== void 0 || !queryFields.some((field, index) => isPagedField(field, projections[index], orderBy, groupBy, distinctOn))) return;
2337
+ const columnKeys = /* @__PURE__ */ new Set();
2338
+ const fields = [];
2339
+ const fieldKeys = [];
2340
+ for (let index = 0; index < projections.length; index++) {
2341
+ const { expression } = projections[index];
2342
+ let key;
2343
+ if (isPagedField(queryFields[index], projections[index], orderBy, groupBy, distinctOn)) {
2344
+ if (mayAggregateSource(expression, from)) return;
2345
+ collectColumnKeys(expression, from, columnKeys);
2346
+ } else if (expression.kind === "column" && expression.source === from) columnKeys.add(expression.key);
2347
+ else {
2348
+ key = `$field${index + 1}`;
2349
+ fields.push(Object.freeze({
2350
+ key,
2351
+ expression,
2352
+ type: text
2353
+ }));
2354
+ }
2355
+ fieldKeys.push(key);
2356
+ }
2357
+ const sourced = [];
2358
+ for (const key of columnKeys) sourced.push(Object.freeze({
2359
+ key,
2360
+ expression: createNode({
2361
+ kind: "column",
2362
+ source: from,
2363
+ key
2364
+ }),
2365
+ type: text
2366
+ }));
2367
+ for (const field of fields) sourced.push(field);
2368
+ if (distinctOn !== void 0) for (let index = 0; index < distinctOn.length; index++) {
2369
+ const key = distinctOn[index];
2370
+ if (findValueProjection(sourced, key) === -1) sourced.push(Object.freeze({
2371
+ key: `$key${index + 1}`,
2372
+ expression: key,
2373
+ type: text
2374
+ }));
2375
+ }
2376
+ const page = deriveOrderedSource({
2377
+ kind: "select",
2378
+ from,
2379
+ joins: noJoins,
2380
+ projections: sourced,
2381
+ filters: query.filters,
2382
+ groupBy,
2383
+ having: query.having,
2384
+ orderBy,
2385
+ limit: query.limit,
2386
+ offset,
2387
+ distinctOn,
2388
+ rows: "many",
2389
+ value: false,
2390
+ guaranteedBy: void 0
2391
+ }, true, offset, from);
2392
+ const selected = [];
2393
+ for (let index = 0; index < projections.length; index++) {
2394
+ const projection = projections[index];
2395
+ const key = fieldKeys[index];
2396
+ selected.push(key === void 0 ? projection : Object.freeze({
2397
+ key: projection.key,
2398
+ expression: createNode({
2399
+ kind: "column",
2400
+ source: page.source,
2401
+ key
2402
+ }),
2403
+ type: projection.type
2404
+ }));
2405
+ }
2406
+ return Object.freeze({
2407
+ kind: "select",
2408
+ from: page.source,
2409
+ joins: noJoins,
2410
+ projections: selected,
2411
+ filters: noFilters,
2412
+ orderBy: positions ? sortByPositions(page.order, selected) : page.order,
2413
+ limit: void 0,
2414
+ offset: void 0,
2415
+ rows: query.rows,
2416
+ value: query.value,
2417
+ guaranteedBy: query.guaranteedBy,
2418
+ recordTemplate: query.recordTemplate
2419
+ });
2420
+ }
2421
+ /**
2422
+ * Tells whether `field`, a field of a query lowered to `projection`, is a nested query that a derived page evaluates only over its rows: one that no sort key of `orderBy`, the lowered order, sorts by, and that is none of `groupBy` and `distinctOn`, the lowered keys of the query.
2423
+ *
2424
+ * The query evaluates a field that it sorts by, groups by, or compares, of an aggregate or of `exists`, for every row anyway.
2425
+ */
2426
+ function isPagedField(field, projection, orderBy, groupBy, distinctOn) {
2427
+ if (!isNestedSelection(field)) return false;
2428
+ const { expression } = projection;
2429
+ return !orderBy.some((order) => order.expression === expression) && (groupBy === void 0 || !groupBy.includes(expression)) && (distinctOn === void 0 || !distinctOn.includes(expression));
2430
+ }
2431
+ // src/lowering/lower.ts
2432
+ function lowerStatement(node, definitions, db) {
2433
+ const context = createContext(definitions, db);
2434
+ switch (node.kind) {
2435
+ case "query": return lowerSelect(node, context, true);
2436
+ case "record": return lowerRecord(node, context);
2437
+ case "text": return lowerText(node, context);
2438
+ default: return lowerMutation(node, context);
2439
+ }
2440
+ }
2441
+ /** Creates the context of lowering a statement with `definitions` and `db`, whose nested queries `lowerSelect` lowers. */
2442
+ function createContext(definitions, db) {
2443
+ const context = {
2444
+ definitions,
2445
+ db,
2446
+ lowerSelect: (node, positions) => lowerSelect(node, context, positions),
2447
+ lowerExists: (node) => lowerExists(node, context)
2448
+ };
2449
+ return context;
2450
+ }
2451
+ /** Lowers a statement of SQL text, replacing the queries in the expressions interpolated into it. */
2452
+ function lowerText(node, context) {
2453
+ const sql = lowerExpression(node.sql, context);
2454
+ if (sql === node.sql) return node;
2455
+ return Object.freeze({
2456
+ kind: "text",
2457
+ sql,
2458
+ fields: node.fields,
2459
+ rows: node.rows,
2460
+ value: node.value
2461
+ });
2462
+ }
2463
+ /** Lowers a query as `lowerQuery` does, or as `lowerStatement` does when `positions` is set, with the conversion of its result. */
2464
+ function lowerSelect(node, context, positions) {
2465
+ const statement = lowerSelectStatement(node, context, positions);
2466
+ const { conversion } = node;
2467
+ return conversion === void 0 ? statement : Object.freeze({
2468
+ ...statement,
2469
+ conversion
2470
+ });
2471
+ }
2472
+ /** Lowers a query to its statement, whichever it is: of `exists`, of an aggregate, of a page that evaluates its nested queries only over its rows, or of the rows of its source. */
2473
+ function lowerSelectStatement(node, context, positions) {
2474
+ if (isExistsQuery(node)) return selectExists(node, context);
2475
+ checkRelation(node, context);
2476
+ if (isAggregateQuery(node)) return lowerAggregate(node, context);
2477
+ const recordTemplate = createRecordTemplate(node.projections);
2478
+ const selected = dropLiterals(node.projections);
2479
+ const projections = lowerProjections(selected, context);
2480
+ if (node.groupBy.length > 0) checkGroupAggregates(projections, node);
2481
+ const filters = lowerFilters(node.filters, context);
2482
+ const orderBy = lowerOrder(node.orderBy, context, selected, projections);
2483
+ const groupBy = lowerKeys(node.groupBy, context, selected, projections);
2484
+ const having = lowerValue(node.having, context);
2485
+ const distinctOn = lowerKeys(node.distinctOn, context, selected, projections);
2486
+ if (node.distinct) checkDistinct(projections, orderBy);
2487
+ if (distinctOn !== void 0) checkDistinctOn(projections, distinctOn, orderBy);
2488
+ const { relation } = node;
2489
+ const guaranteedBy = node.guaranteed && relation !== void 0 ? formatRelationName(relation.key, relation.name) : void 0;
2490
+ const statement = {
2491
+ kind: "select",
2492
+ from: node.from,
2493
+ joins: noJoins,
2494
+ projections,
2495
+ filters,
2496
+ groupBy,
2497
+ having,
2498
+ orderBy,
2499
+ limit: node.limit,
2500
+ offset: node.offset,
2501
+ distinct: node.distinct,
2502
+ distinctOn,
2503
+ lock: node.lock,
2504
+ rows: node.rows,
2505
+ value: node.value,
2506
+ guaranteedBy,
2507
+ recordTemplate
2508
+ };
2509
+ const page = lowerPage(statement, selected, positions);
2510
+ if (page !== void 0) return page;
2511
+ if (positions && orderBy.length > 0) statement.orderBy = sortByPositions(orderBy, projections);
2512
+ return Object.freeze(statement);
2513
+ }
2514
+ /** Lowers a query of `exists` to a statement without a source of one row of `EXISTS` of its rows. */
2515
+ function selectExists(node, context) {
2516
+ return Object.freeze({
2517
+ kind: "select",
2518
+ from: void 0,
2519
+ joins: noJoins,
2520
+ projections: [projectExists(node.projections[0].key, node, context)],
2521
+ filters: noFilters,
2522
+ orderBy: noOrder,
2523
+ limit: void 0,
2524
+ offset: void 0,
2525
+ rows: node.rows,
2526
+ value: true,
2527
+ guaranteedBy: void 0
2528
+ });
2529
+ }
2530
+ /** Lowers a query of `$select` to a statement without a source, which returns one row of its fields. */
2531
+ function lowerRecord(node, context) {
2532
+ return Object.freeze({
2533
+ kind: "select",
2534
+ from: void 0,
2535
+ joins: noJoins,
2536
+ projections: lowerProjections(dropLiterals(node.projections), context),
2537
+ filters: noFilters,
2538
+ orderBy: noOrder,
2539
+ limit: void 0,
2540
+ offset: void 0,
2541
+ rows: "one",
2542
+ value: false,
2543
+ guaranteedBy: void 0,
2544
+ recordTemplate: createRecordTemplate(node.projections)
2545
+ });
2546
+ }
2547
+ // src/query/kind.ts
2548
+ /** `then` of every bound query, which executes the query on its `Db`. */
2549
+ function executeOnAwait(onFulfilled, onRejected) {
2550
+ return this.db.$execute(this).then(onFulfilled, onRejected);
2551
+ }
2552
+ /** Compiles `query` as its `toSQL` does: an unbound query with `options`, and a bound query as its `Db` executes it, which takes no options. */
2553
+ function compileToSQL(query, options) {
2554
+ const { db } = query;
2555
+ if (db === void 0) {
2556
+ const { text, parameters } = compileStatement(lowerStatement(query.node), options);
2557
+ return createStatement(text, parameters);
2558
+ }
2559
+ if (options !== void 0) throw new Error("A query bound to a Db compiles with the options of its Db");
2560
+ return db.$compile(query);
2561
+ }
2562
+ // src/query/conversion.ts
2563
+ /**
2564
+ * Immutable query of a table of state `S` whose whole result `transform` converts after decoding, unbound or bound to a `Db`.
2565
+ *
2566
+ * It executes and nests in a selection as the query it comes from, with the same SQL, so it has only `transform`, which converts the result further: another method would change what the callback receives, and an expression does not take it, since SQL does not see the conversion.
2567
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
2568
+ * A bound query executes on its `Db` when awaited.
2569
+ */
2570
+ var TransformedQuery = class {
2571
+ node;
2572
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
2573
+ db;
2574
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
2575
+ then;
2576
+ constructor(node, db) {
2577
+ this.node = node;
2578
+ this.db = db;
2579
+ this.then = db === void 0 ? void 0 : executeOnAwait;
2580
+ Object.freeze(this);
2581
+ }
2582
+ transform(callback) {
2583
+ return transformQuery(this.node, this.db, callback);
2584
+ }
2585
+ toSQL(options) {
2586
+ return compileToSQL(this, options);
2587
+ }
2588
+ /** Rejects the query as an operand of an expression, whose value SQL reads without its conversion. */
2589
+ [operandNode]() {
2590
+ throw new TypeError("An expression takes a query of one value of a table, such as of get, an aggregate, or exists, not a query of transform");
2591
+ }
2592
+ };
2593
+ /** Creates the query of `transform` of `node`, a query of a table bound to `db` when given, whose whole result `callback` converts after the earlier conversions. */
2594
+ function transformQuery(node, db, callback) {
2595
+ return new TransformedQuery(Object.freeze({
2596
+ ...node,
2597
+ conversion: addTransform(node.conversion, callback)
2598
+ }), db);
2599
+ }
2600
+ /**
2601
+ * Returns `conversion` of a query with `callback` of `map` after its earlier one.
2602
+ *
2603
+ * It rejects a conversion of `transform`, whose result has no rows to convert.
2604
+ */
2605
+ function addMap(conversion, callback) {
2606
+ if (conversion?.transform !== void 0) throw new Error("map cannot be used after transform; convert the rows in its callback instead");
2607
+ return Object.freeze({
2608
+ map: chainConversions(conversion?.map, createConversion(callback, "map")),
2609
+ transform: void 0
2610
+ });
2611
+ }
2612
+ /** Returns `conversion` of a query with `callback` of `transform` after its earlier one. */
2613
+ function addTransform(conversion, callback) {
2614
+ return Object.freeze({
2615
+ map: conversion?.map,
2616
+ transform: chainConversions(conversion?.transform, createConversion(callback, "transform"))
2617
+ });
2618
+ }
2619
+ /** Returns the conversion that applies `next` after `previous`, if any. */
2620
+ function chainConversions(previous, next) {
2621
+ return previous === void 0 ? next : (value) => next(previous(value));
2622
+ }
2623
+ /**
2624
+ * Creates the conversion of `callback` of `method`, which rejects a Promise or another thenable returned by the callback: `SynchronousResult` rejects it in types, and a callback may still return one through `any`.
2625
+ *
2626
+ * It rejects a `callback` that is not a function when it is called, since decoding calls it long after, where its error would read as a failure of a row.
2627
+ */
2628
+ function createConversion(callback, method) {
2629
+ if (typeof callback !== "function") throw new TypeError(`${method} takes a callback`);
2630
+ return (value) => {
2631
+ const result = callback(value);
2632
+ if (typeof result?.then === "function") {
2633
+ if (types.isPromise(result)) result.catch(ignoreRejection);
2634
+ throw new TypeError(`The callback of ${method} must return its result synchronously, not a Promise or a query`);
2635
+ }
2636
+ return result;
2637
+ };
2638
+ }
2639
+ /** Handles the rejection of a Promise that a callback returned, whose query has failed already. */
2640
+ function ignoreRejection() {}
2641
+ // src/query/resolve-values.ts
2642
+ /**
2643
+ * Replaces objects of column values in a predicate with conditions on the columns of `source`.
2644
+ *
2645
+ * Groups are rebuilt, so constants that appear after resolution, such as an empty object, are simplified.
2646
+ */
2647
+ function resolveValues(node, source) {
2648
+ switch (node.kind) {
2649
+ case "values": {
2650
+ const conditions = [];
2651
+ for (const key of Object.keys(node.values)) conditions.push(matchColumn(source, key, node.values[key]));
2652
+ return combineNodes("and", conditions);
2653
+ }
2654
+ case "and":
2655
+ case "or": {
2656
+ const operands = [];
2657
+ for (const operand of node.operands) operands.push(resolveValues(operand, source));
2658
+ return combineNodes(node.kind, operands);
2659
+ }
2660
+ case "not": return negateNode(resolveValues(node.operand, source));
2661
+ case "raw": return createNode({
2662
+ ...node,
2663
+ values: node.values.map((value) => resolveValues(value, source))
2664
+ });
2665
+ default: return node;
2666
+ }
2667
+ }
2668
+ /** Creates the condition of column `key` of `source` in an object of column values: `IS NULL` of `null`, or the `eq` operator of its type for another value. */
2669
+ function matchColumn(source, key, value) {
2670
+ const type = findColumn(source.table, key)?.type;
2671
+ const column = createNode({
2672
+ kind: "column",
2673
+ source,
2674
+ key
2675
+ });
2676
+ if (value === null) return createIsNullNode(column);
2677
+ if (type) return matchValue(source, column, type, value);
2678
+ return compareNodes("=", column, value, void 0);
2679
+ }
2680
+ /** Matches a column with a value of an object condition by calling the `eq` operator of its type, whichever operator it is. */
2681
+ function matchValue(source, column, type, value) {
2682
+ const expression = toExpression(column, type);
2683
+ if (typeof expression.eq !== "function") throw new TypeError(`Column "${column.key}" of table "${source.table.name}" has no eq operator; an object condition can only match it with null`);
2684
+ const predicate = expression.eq(value);
2685
+ if (!isExpression(predicate)) throw new TypeError(`The eq operator of column "${column.key}" of table "${source.table.name}" must return an expression`);
2686
+ return toNode(predicate);
2687
+ }
2688
+ // src/query/filters.ts
2689
+ /** Creates query filters with the filter of `where` over `source` with the relations of `context` combined with `AND` with the user filters of `filters`. */
2690
+ function addUserFilter(filters, filter, source, context) {
2691
+ const predicate = toFilterNode(filter, source, context);
2692
+ const { user } = filters;
2693
+ return Object.freeze({
2694
+ ...filters,
2695
+ user: user ? combineNodes("and", [user, predicate]) : predicate
2696
+ });
2697
+ }
2698
+ /**
2699
+ * Converts a filter of `where` or `having` over `source` with the relations of `context` into the node of its condition, whose objects of column values it resolves.
2700
+ *
2701
+ * A callback receives the columns with the relations, and what `readSelected` returns, such as the selected fields for `having`.
2702
+ */
2703
+ function toFilterNode(filter, source, context, readSelected) {
2704
+ return resolveValues(toConditionNode(typeof filter === "function" ? filter(createSelectionRefs(source, context), readSelected?.()) : filter), source);
2705
+ }
2706
+ // src/query/find.ts
2707
+ /**
2708
+ * Returns the object of column values that `find` filters a query of `table` by: `values` of the columns of its primary key, in their order.
2709
+ *
2710
+ * It rejects a table without a primary key, a number of values other than the number of its columns, and `null` and `undefined`.
2711
+ */
2712
+ function toPrimaryKeyValues(table, values) {
2713
+ const { primaryKey } = table.keys;
2714
+ if (primaryKey === void 0) throw new Error(`find takes the values of a primary key, which table "${table.name}" does not have; use findBy with a unique key`);
2715
+ if (values.length !== primaryKey.length) throw new Error(`find takes one value for each column of the primary key of table "${table.name}", ${quoteColumns(primaryKey)}, not ${values.length}`);
2716
+ const filter = {};
2717
+ for (let index = 0; index < primaryKey.length; index++) {
2718
+ const column = primaryKey[index];
2719
+ filter[column] = requireKeyValue(table, column, values[index], "find");
2720
+ }
2721
+ return filter;
2722
+ }
2723
+ /**
2724
+ * Returns the object of column values that `findBy` filters a query of `table` by: a copy of `values`, read once.
2725
+ *
2726
+ * It rejects columns that are not exactly a key of `table`, primary or unique, as `isKey` tells, and `null` and `undefined`.
2727
+ */
2728
+ function toKeyValues(table, values) {
2729
+ if (typeof values !== "object" || values === null) throw new TypeError(`findBy takes an object of the columns of a key of table "${table.name}"`);
2730
+ const columns = Object.keys(values);
2731
+ if (!isKey(table, columns)) {
2732
+ const listed = columns.length === 0 ? "an object without columns" : `columns ${quoteColumns(columns)}`;
2733
+ throw new Error(`findBy takes the columns of one key of table "${table.name}", primary or unique, not ${listed}`);
2734
+ }
2735
+ const filter = {};
2736
+ for (const column of columns) {
2737
+ const value = values[column];
2738
+ filter[column] = requireKeyValue(table, column, value, "findBy");
2739
+ }
2740
+ return filter;
2741
+ }
2742
+ /** Returns `value` of column `column` of a key of `table` that `method` takes, rejecting `null` and `undefined`. */
2743
+ function requireKeyValue(table, column, value, method) {
2744
+ if (value === null || value === void 0) throw new TypeError(`${method} got ${value} for column "${column}" of table "${table.name}"; a value of a key is never null or undefined`);
2745
+ return value;
2746
+ }
2747
+ /** Lists `columns` in quotes, separated by commas. */
2748
+ function quoteColumns(columns) {
2749
+ return columns.map((column) => `"${column}"`).join(", ");
2750
+ }
2751
+ // src/query/order.ts
2752
+ /** Direction and placement of `NULL` of a sort key node, by `OrderDirection`. */
2753
+ const directions = /* @__PURE__ */ Object.freeze({
2754
+ asc: {
2755
+ direction: "asc",
2756
+ nulls: void 0
2757
+ },
2758
+ desc: {
2759
+ direction: "desc",
2760
+ nulls: void 0
2761
+ },
2762
+ "asc nulls first": {
2763
+ direction: "asc",
2764
+ nulls: "first"
2765
+ },
2766
+ "asc nulls last": {
2767
+ direction: "asc",
2768
+ nulls: "last"
2769
+ },
2770
+ "desc nulls first": {
2771
+ direction: "desc",
2772
+ nulls: "first"
2773
+ },
2774
+ "desc nulls last": {
2775
+ direction: "desc",
2776
+ nulls: "last"
2777
+ }
2778
+ });
2779
+ const orderingNode = Symbol("kern-orm.ordering.node");
2780
+ /** Runtime class of an expression with a direction, which holds its sort key node. */
2781
+ var OrderingObject = class {
2782
+ [orderingNode];
2783
+ constructor(node) {
2784
+ this[orderingNode] = node;
2785
+ Object.freeze(this);
2786
+ }
2787
+ };
2788
+ /** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
2789
+ function asc(value) {
2790
+ return orderBy(value, "asc");
2791
+ }
2792
+ /** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
2793
+ function desc(value) {
2794
+ return orderBy(value, "desc");
2795
+ }
2796
+ /** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
2797
+ function orderBy(value, direction) {
2798
+ if (!isOperandSource(value)) throw new TypeError("A sort key must be an expression or a query of one value");
2799
+ return new OrderingObject(createOrderNode(value[operandNode](), direction));
2800
+ }
2801
+ /**
2802
+ * Creates the order of `node` with the sort keys of the arguments of `orderBy` after its own.
2803
+ *
2804
+ * `args` are column keys and objects of columns with directions, or a callback that receives the columns with the relations of `context` and the selected fields, and returns one sort key or an array of them.
2805
+ */
2806
+ function addOrder(node, context, args) {
2807
+ const order = node.orderBy.slice();
2808
+ const first = args[0];
2809
+ if (typeof first === "function") {
2810
+ addTerms(order, first(createSelectionRefs(node.from, context), createSelectedRefs(node, "sorted by")), "The callback of orderBy must return");
2811
+ return order;
2812
+ }
2813
+ for (const arg of args) if (typeof arg === "string") order.push(createOrderNode(createColumnNode(node.from, arg), "asc"));
2814
+ else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) {
2815
+ const columns = arg;
2816
+ for (const key of Object.keys(columns)) order.push(createOrderNode(createColumnNode(node.from, key), columns[key]));
2817
+ } else throw new TypeError("orderBy takes column keys and objects of columns with directions, or a callback");
2818
+ return order;
2819
+ }
2820
+ /** Adds to `order` the sort key nodes of `terms`, `OrderTerms` checked at runtime; `subject` starts the error of another value, such as `The callback of orderBy must return`. */
2821
+ function addTerms(order, terms, subject) {
2822
+ if (Array.isArray(terms)) for (const term of terms) order.push(readTerm$1(term, subject));
2823
+ else order.push(readTerm$1(terms, subject));
2824
+ }
2173
2825
  /**
2174
- * Lowers a query in an expression to `EXISTS` of the rows of a query of `exists`, to a scalar subquery of the value of another query of one value, or to its statement in parentheses for a query of records or of rows `many`, which only SQL text holds.
2826
+ * Creates the sort key node of a sort key, `OrderTerm` checked at runtime, whose error starts with `subject`.
2175
2827
  *
2176
- * In SQL text, a query of `exists` stays `EXISTS` rather than a subquery of its value, so that PostgreSQL can join its rows in a condition, as a semi-join.
2828
+ * A query is converted by the method of `operandNode`, which rejects a query other than of one value.
2177
2829
  */
2178
- function lowerNestedQuery(node, context) {
2179
- checkDb(node.db, context, "A query in an expression");
2180
- const { query } = node;
2181
- if (isExistsQuery(query)) return lowerExists(query, context);
2182
- return createNode({
2183
- kind: query.value && query.rows !== "many" ? "subquery" : "textSubquery",
2184
- query: lowerSelect(query, context, false)
2830
+ function readTerm$1(term, subject) {
2831
+ if (term instanceof OrderingObject) return term[orderingNode];
2832
+ if (isOperandSource(term)) return createOrderNode(term[operandNode](), "asc");
2833
+ throw new TypeError(`${subject} expressions, queries of one value, or sort keys of asc, desc, and orderBy`);
2834
+ }
2835
+ /** Creates the sort key node of `expression` in `direction`, an `OrderDirection` checked at runtime. */
2836
+ function createOrderNode(expression, direction) {
2837
+ const placement = typeof direction === "string" && Object.hasOwn(directions, direction) ? directions[direction] : void 0;
2838
+ if (placement === void 0) throw new TypeError(`Unknown sort direction ${JSON.stringify(direction)}`);
2839
+ return Object.freeze({
2840
+ expression,
2841
+ direction: placement.direction,
2842
+ nulls: placement.nulls
2185
2843
  });
2186
2844
  }
2187
- /** Lowers the query of the values of `IN` to its statement, whatever its rows. */
2188
- function lowerQueryOfValues(node, context) {
2189
- checkDb(node.db, context, "A query in an expression");
2190
- return lowerSelect(node.query, context, false);
2845
+ /** Creates a reference to the column `key` of the table of `source`. */
2846
+ function createColumnNode(source, key) {
2847
+ requireColumn(source.table, key);
2848
+ return createNode({
2849
+ kind: "column",
2850
+ source,
2851
+ key
2852
+ });
2191
2853
  }
2192
- /** Lowers each of `items` with `lower`; when none changes, it returns `items` itself. */
2193
- function lowerEach(items, context, lower) {
2194
- let lowered;
2195
- for (let index = 0; index < items.length; index++) {
2196
- const item = items[index];
2197
- const result = lower(item, context);
2198
- if (lowered !== void 0) lowered.push(result);
2199
- else if (result !== item) {
2200
- lowered = items.slice(0, index);
2201
- lowered.push(result);
2202
- }
2854
+ /**
2855
+ * Creates the references of the callback of `orderBy`, `groupBy`, `distinctOn`, or `having` to the fields selected by `node`; `purpose` completes the error of a field that cannot be read, such as `sorted by`.
2856
+ *
2857
+ * Each is an expression over the node of its projection, so that a sort key or a key of a group of it is the projection itself; `HAVING` compiles the expression again, since it cannot refer to a projection.
2858
+ * A field of an aggregate or of `exists` is an expression of its query that holds the field, by which lowering finds the projection of the field.
2859
+ */
2860
+ function createSelectedRefs(node, purpose) {
2861
+ const { projections } = node;
2862
+ if (node.value) return toSelectedExpression(projections[0]);
2863
+ const refs = {};
2864
+ for (const projection of projections) {
2865
+ const { key } = projection;
2866
+ if (isLiteralSelection(projection)) Object.defineProperty(refs, key, {
2867
+ get() {
2868
+ throw new Error(`Field "${key}" holds a literal and cannot be ${purpose}`);
2869
+ },
2870
+ enumerable: true
2871
+ });
2872
+ else if (isNestedSelection(projection)) {
2873
+ if (isSelectedAsValue(projection.query)) refs[key] = toQueryExpression(projection);
2874
+ else Object.defineProperty(refs, key, {
2875
+ get() {
2876
+ throw new Error(`Field "${key}" holds nested rows and cannot be ${purpose}`);
2877
+ },
2878
+ enumerable: true
2879
+ });
2880
+ } else refs[key] = toSelectedExpression(projection);
2203
2881
  }
2204
- return lowered ?? items;
2882
+ return refs;
2205
2883
  }
2206
- // src/query/kind.ts
2207
- /** `then` of every bound query, which executes the query on its `Db`. */
2208
- function executeOnAwait(onFulfilled, onRejected) {
2209
- return this.db.$execute(this).then(onFulfilled, onRejected);
2884
+ /** Creates an expression over the node of a projection of a query, which has a type: only lowering adds projections of nested queries. */
2885
+ function toSelectedExpression(projection) {
2886
+ return toExpression(projection.expression, projection.type);
2210
2887
  }
2211
- /** Compiles `query` as its `toSQL` does: an unbound query with `options`, and a bound query as its `Db` executes it, which takes no options. */
2212
- function compileToSQL(query, options) {
2213
- const { db } = query;
2214
- if (db === void 0) {
2215
- const { text, parameters } = compileStatement(lowerStatement(query.node), options);
2216
- return createStatement(text, parameters);
2888
+ /** Creates an expression of the value of `field`, a selected aggregate query or query of `exists`, with the type of its value. */
2889
+ function toQueryExpression(field) {
2890
+ const { query } = field;
2891
+ return toExpression(createNode({
2892
+ kind: "nestedQuery",
2893
+ query,
2894
+ db: field.db,
2895
+ field
2896
+ }), query.projections[0].type);
2897
+ }
2898
+ // src/query/group.ts
2899
+ /** Method that takes the keys of groups, and the phrase of what it does with a field that cannot be a key, for its errors. */
2900
+ const keyMethods = {
2901
+ groupBy: "grouped by",
2902
+ distinctOn: "a key of distinctOn"
2903
+ };
2904
+ /**
2905
+ * Creates the keys of `method`, `groupBy` or `distinctOn`, of `node` with the keys of the arguments of the call after its own.
2906
+ *
2907
+ * `args` are column keys, or a callback that receives the columns with the relations of `context` and the selected fields, and returns one key or an array of them.
2908
+ * A string names a column, never a selected field, whose key names only the field of a record.
2909
+ * It rejects a call without keys, which would leave the rows of a query ungrouped, or keep all of them, when a list built in code is empty.
2910
+ */
2911
+ function addGroupKeys(method, node, context, args) {
2912
+ const existing = node[method];
2913
+ const keys = existing.slice();
2914
+ const first = args[0];
2915
+ if (typeof first === "function") {
2916
+ const terms = first(createSelectionRefs(node.from, context), createSelectedRefs(node, keyMethods[method]));
2917
+ if (Array.isArray(terms)) for (const term of terms) keys.push(readTerm(term, method));
2918
+ else keys.push(readTerm(terms, method));
2919
+ } else for (const arg of args) {
2920
+ if (typeof arg !== "string") throw new TypeError(`${method} takes column keys or a callback`);
2921
+ keys.push(createColumnNode(node.from, arg));
2217
2922
  }
2218
- if (options !== void 0) throw new Error("A query bound to a Db compiles with the options of its Db");
2219
- return db.$compile(query);
2923
+ if (keys.length === existing.length) throw new TypeError(`${method} requires at least one key`);
2924
+ return keys;
2925
+ }
2926
+ /**
2927
+ * Creates the condition of the groups of `node` with `filter`, what `where` takes, combined with `AND` with its earlier condition.
2928
+ *
2929
+ * A callback also receives the fields selected so far, as `HavingFields` tells, so that a condition reads an aggregate or a key of an expression by its field.
2930
+ * The condition stands apart from the filters of the rows, so it requires keys: without them, `having` would read as a filter of rows while PostgreSQL takes the whole query for one group.
2931
+ */
2932
+ function addHaving(node, filter, context) {
2933
+ if (node.groupBy.length === 0) throw new Error("having requires an earlier groupBy; filter the rows with where");
2934
+ const predicate = toFilterNode(filter, node.from, context, () => node.conversion !== void 0 || isAggregateQuery(node) || isExistsQuery(node) ? void 0 : createSelectedRefs(node, "read in having"));
2935
+ return node.having === void 0 ? predicate : combineNodes("and", [node.having, predicate]);
2936
+ }
2937
+ /**
2938
+ * Creates the node of a key returned by the callback of `method`.
2939
+ *
2940
+ * A query is converted by the method of `operandNode`, which rejects a query other than of one value.
2941
+ */
2942
+ function readTerm(term, method) {
2943
+ if (isOperandSource(term)) return term[operandNode]();
2944
+ throw new TypeError(`The callback of ${method} must return expressions or queries of one value`);
2945
+ }
2946
+ // src/query/lock.ts
2947
+ /** Creates the row lock of `strength` for `method`, rejecting a query whose rows it cannot lock and options that contradict each other. */
2948
+ function createRowLock(node, method, strength, options = {}) {
2949
+ if (isAggregateQuery(node)) throw new Error(`${method} cannot be used after an aggregate`);
2950
+ if (isExistsQuery(node)) throw new Error(`${method} cannot be used after exists`);
2951
+ if (node.distinct) throw new Error(`${method} cannot be used after distinct, since a row without duplicates comes from several rows of the table`);
2952
+ if (node.distinctOn.length > 0) throw new Error(`${method} cannot be used after distinctOn; PostgreSQL does not allow row locks with DISTINCT ON`);
2953
+ if (node.groupBy.length > 0) throw new Error(`${method} cannot be used after groupBy, since a group comes from several rows of the table`);
2954
+ const { noWait, skipLocked } = options;
2955
+ if (noWait && skipLocked) throw new Error(`${method} takes either noWait or skipLocked, not both`);
2956
+ return Object.freeze({
2957
+ strength,
2958
+ onLocked: noWait ? "NOWAIT" : skipLocked ? "SKIP LOCKED" : void 0
2959
+ });
2220
2960
  }
2221
2961
  // src/query/record.ts
2222
2962
  /**
@@ -2422,7 +3162,7 @@ function selectValue(key, value) {
2422
3162
  key,
2423
3163
  literal: value.literal
2424
3164
  });
2425
- if (value instanceof SelectQuery) return Object.freeze({
3165
+ if (value instanceof SelectQuery || value instanceof TransformedQuery) return Object.freeze({
2426
3166
  key,
2427
3167
  query: value.node,
2428
3168
  db: value.db
@@ -2529,7 +3269,7 @@ function resolveValue(table, key, value) {
2529
3269
  /**
2530
3270
  * Immutable query of state `S` that inserts, updates, or deletes rows, unbound or bound to a `Db`.
2531
3271
  *
2532
- * Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead.
3272
+ * Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead, and `map` and `transform` convert them in code.
2533
3273
  * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
2534
3274
  * A bound query executes on its `Db` when awaited.
2535
3275
  */
@@ -2550,6 +3290,7 @@ var MutationQuery = class MutationQuery {
2550
3290
  Object.freeze(this);
2551
3291
  }
2552
3292
  select(...args) {
3293
+ this.rejectConverted("select");
2553
3294
  const { node } = this;
2554
3295
  const { returning } = node;
2555
3296
  if (returning !== void 0 && node.value) throw new Error("select cannot be used after get or pluck; call get or pluck to replace the value");
@@ -2565,6 +3306,19 @@ var MutationQuery = class MutationQuery {
2565
3306
  pluck(arg) {
2566
3307
  return this.deriveValue(arg, "pluck");
2567
3308
  }
3309
+ map(callback) {
3310
+ const { node } = this;
3311
+ if (node.returning === void 0) throw new Error("map applies only to a mutation that returns the fields of its rows; select them before map, or call transform to convert the number of the rows");
3312
+ return this.derive({ conversion: addMap(node.conversion, callback) });
3313
+ }
3314
+ transform(callback) {
3315
+ return this.derive({ conversion: addTransform(this.node.conversion, callback) });
3316
+ }
3317
+ use(callback, ...args) {
3318
+ const result = requireDerived(this, callback(this, ...args), "The callback of use");
3319
+ if (this.node.returning === void 0 && result.node.returning?.length === 0) throw new Error("The callback of use must select at least one field, or not call select to return the number of the rows");
3320
+ return result;
3321
+ }
2568
3322
  toSQL(options) {
2569
3323
  return compileToSQL(this, options);
2570
3324
  }
@@ -2581,6 +3335,7 @@ var MutationQuery = class MutationQuery {
2581
3335
  }
2582
3336
  /** Creates the mutation that returns the value of `arg` of `method`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value, of each changed row. */
2583
3337
  deriveValue(arg, method) {
3338
+ this.rejectConverted(method);
2584
3339
  const { node } = this;
2585
3340
  return this.derive({
2586
3341
  returning: [projectValue(node.target, arg, method, this.context)],
@@ -2588,6 +3343,10 @@ var MutationQuery = class MutationQuery {
2588
3343
  rows: toValueRows(node.rows)
2589
3344
  });
2590
3345
  }
3346
+ /** Rejects `method`, which changes the fields that the mutation returns, on a mutation that `map` or `transform` converts. */
3347
+ rejectConverted(method) {
3348
+ if (this.node.conversion !== void 0) throw new Error(`${method} cannot be used after map or transform; call it before them`);
3349
+ }
2591
3350
  };
2592
3351
  /**
2593
3352
  * Creates the insert of `records` into the table of `query`, which must have no clauses, in rows mode `rows`: `one` for `insert` and `many` for `insertMany`, named by `method`.
@@ -2636,160 +3395,19 @@ function createDelete(query) {
2636
3395
  }), query.context, query.db);
2637
3396
  }
2638
3397
  /**
2639
- * Rejects a query whose rows `method`, `update` or `delete`, cannot change: one of a relation, with selected fields, which a mutation selects after it, with an order, a limit, or an offset, or without a filter that restricts its rows unless `all` allows it.
3398
+ * Rejects a query whose rows `method`, `update` or `delete`, cannot change: one of a relation, with selected fields, which a mutation selects after it, with a conversion of `map`, which a mutation takes after it too, with keys of groups, whose rows SQL does not give, with an order, a limit, an offset, `distinct`, or `distinctOn`, with a row lock, which a mutation takes on its rows itself, or without a filter that restricts its rows unless `all` allows it.
2640
3399
  *
2641
3400
  * A filter simplified to `TRUE`, such as `where({})`, restricts no row.
2642
3401
  */
2643
3402
  function checkChangedRows(node, method) {
2644
3403
  if (node.relation !== void 0) throw new Error(`${method} applies only to a query of a table, not of a relation`);
2645
- if (node.projections.length > 0) throw new Error(`${method} returns the fields selected after it, not before; call select, get, or pluck after ${method}`);
2646
- if (node.orderBy.length > 0 || node.limit !== void 0 || node.offset !== void 0) throw new Error(`${method} cannot sort or limit the rows it changes; choose them with where, find, or findBy instead of take, limit, offset, or orderBy`);
2647
- const predicate = combineFilters(node.filters);
2648
- if (!node.all && predicate.kind === "boolean" && predicate.value) throw new Error(`${method} requires a filter that restricts the rows, such as of where or find; call all() to ${method} every row`);
2649
- }
2650
- // src/query/order.ts
2651
- /** Direction and placement of `NULL` of a sort key node, by `OrderDirection`. */
2652
- const directions = /* @__PURE__ */ Object.freeze({
2653
- asc: {
2654
- direction: "asc",
2655
- nulls: void 0
2656
- },
2657
- desc: {
2658
- direction: "desc",
2659
- nulls: void 0
2660
- },
2661
- "asc nulls first": {
2662
- direction: "asc",
2663
- nulls: "first"
2664
- },
2665
- "asc nulls last": {
2666
- direction: "asc",
2667
- nulls: "last"
2668
- },
2669
- "desc nulls first": {
2670
- direction: "desc",
2671
- nulls: "first"
2672
- },
2673
- "desc nulls last": {
2674
- direction: "desc",
2675
- nulls: "last"
2676
- }
2677
- });
2678
- const orderingNode = Symbol("kern-orm.ordering.node");
2679
- /** Runtime class of an expression with a direction, which holds its sort key node. */
2680
- var OrderingObject = class {
2681
- [orderingNode];
2682
- constructor(node) {
2683
- this[orderingNode] = node;
2684
- Object.freeze(this);
2685
- }
2686
- };
2687
- /** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
2688
- function asc(value) {
2689
- return orderBy(value, "asc");
2690
- }
2691
- /** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
2692
- function desc(value) {
2693
- return orderBy(value, "desc");
2694
- }
2695
- /** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
2696
- function orderBy(value, direction) {
2697
- if (!isOperandSource(value)) throw new TypeError("A sort key must be an expression or a query of one value");
2698
- return new OrderingObject(createOrderNode(value[operandNode](), direction));
2699
- }
2700
- /**
2701
- * Creates the order of `node` with the sort keys of the arguments of `orderBy` after its own.
2702
- *
2703
- * `args` are column keys and objects of columns with directions, or a callback that receives the columns with the relations of `context` and the selected fields, and returns one sort key or an array of them.
2704
- */
2705
- function addOrder(node, context, args) {
2706
- const order = node.orderBy.slice();
2707
- const first = args[0];
2708
- if (typeof first === "function") {
2709
- const terms = first(createSelectionRefs(node.from, context), createSelectedRefs(node));
2710
- if (Array.isArray(terms)) for (const term of terms) order.push(readTerm(term));
2711
- else order.push(readTerm(terms));
2712
- return order;
2713
- }
2714
- for (const arg of args) if (typeof arg === "string") order.push(createOrderNode(createColumnNode(node.from, arg), "asc"));
2715
- else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) {
2716
- const columns = arg;
2717
- for (const key of Object.keys(columns)) order.push(createOrderNode(createColumnNode(node.from, key), columns[key]));
2718
- } else throw new TypeError("orderBy takes column keys and objects of columns with directions, or a callback");
2719
- return order;
2720
- }
2721
- /**
2722
- * Creates the sort key node of a sort key returned by the callback of `orderBy`.
2723
- *
2724
- * A query is converted by the method of `operandNode`, which rejects a query other than of one value.
2725
- */
2726
- function readTerm(term) {
2727
- if (term instanceof OrderingObject) return term[orderingNode];
2728
- if (isOperandSource(term)) return createOrderNode(term[operandNode](), "asc");
2729
- throw new TypeError("The callback of orderBy must return expressions, queries of one value, or sort keys of asc, desc, and orderBy");
2730
- }
2731
- /** Creates the sort key node of `expression` in `direction`, an `OrderDirection` checked at runtime. */
2732
- function createOrderNode(expression, direction) {
2733
- const placement = typeof direction === "string" && Object.hasOwn(directions, direction) ? directions[direction] : void 0;
2734
- if (placement === void 0) throw new TypeError(`Unknown sort direction ${JSON.stringify(direction)}`);
2735
- return Object.freeze({
2736
- expression,
2737
- direction: placement.direction,
2738
- nulls: placement.nulls
2739
- });
2740
- }
2741
- /** Creates a reference to the column `key` of the table of `source`. */
2742
- function createColumnNode(source, key) {
2743
- requireColumn(source.table, key);
2744
- return createNode({
2745
- kind: "column",
2746
- source,
2747
- key
2748
- });
2749
- }
2750
- /**
2751
- * Creates the references of the callback of `orderBy` to the fields selected by `node`.
2752
- *
2753
- * Each is an expression over the node of its projection, so that a sort key of it is the projection itself.
2754
- * A field of an aggregate or of `exists` is an expression of its query that holds the field, by which lowering finds the projection of the field.
2755
- */
2756
- function createSelectedRefs(node) {
2757
- const { projections } = node;
2758
- if (node.value) return toSelectedExpression(projections[0]);
2759
- const refs = {};
2760
- for (const projection of projections) {
2761
- const { key } = projection;
2762
- if (isLiteralSelection(projection)) Object.defineProperty(refs, key, {
2763
- get() {
2764
- throw new Error(`Field "${key}" holds a literal and cannot be sorted by`);
2765
- },
2766
- enumerable: true
2767
- });
2768
- else if (isNestedSelection(projection)) {
2769
- if (isSelectedAsValue(projection.query)) refs[key] = toQueryExpression(projection);
2770
- else Object.defineProperty(refs, key, {
2771
- get() {
2772
- throw new Error(`Field "${key}" holds nested rows and cannot be sorted by`);
2773
- },
2774
- enumerable: true
2775
- });
2776
- } else refs[key] = toSelectedExpression(projection);
2777
- }
2778
- return refs;
2779
- }
2780
- /** Creates an expression over the node of a projection of a query, which has a type: only lowering adds projections of nested queries. */
2781
- function toSelectedExpression(projection) {
2782
- return toExpression(projection.expression, projection.type);
2783
- }
2784
- /** Creates an expression of the value of `field`, a selected aggregate query or query of `exists`, with the type of its value. */
2785
- function toQueryExpression(field) {
2786
- const { query } = field;
2787
- return toExpression(createNode({
2788
- kind: "nestedQuery",
2789
- query,
2790
- db: field.db,
2791
- field
2792
- }), query.projections[0].type);
3404
+ if (node.projections.length > 0) throw new Error(`${method} returns the fields selected after it, not before; call select, get, or pluck after ${method}`);
3405
+ if (node.conversion !== void 0) throw new Error(`${method} returns what map converts after it, not before; call map after ${method}`);
3406
+ if (node.groupBy.length > 0) throw new Error(`${method} changes rows rather than groups; choose them with where, find, or findBy instead of groupBy`);
3407
+ if (node.orderBy.length > 0 || node.limit !== void 0 || node.offset !== void 0 || node.distinct || node.distinctOn.length > 0) throw new Error(`${method} cannot sort or limit the rows it changes; choose them with where, find, or findBy instead of take, limit, offset, orderBy, distinct, or distinctOn`);
3408
+ if (node.lock !== void 0) throw new Error(`${method} locks the rows it changes itself, so its query takes no row lock`);
3409
+ const predicate = combineFilters(node.filters);
3410
+ if (!node.all && predicate.kind === "boolean" && predicate.value) throw new Error(`${method} requires a filter that restricts the rows, such as of where or find; call all() to ${method} every row`);
2793
3411
  }
2794
3412
  // src/query/pagination.ts
2795
3413
  /** Creates the parameter of the number of rows of `limit` or `offset`, named by `method`, of query `node`, rejecting a query of one row and a count that is not a non-negative safe integer. */
@@ -2871,7 +3489,7 @@ var SelectQuery = class SelectQuery {
2871
3489
  }
2872
3490
  count(arg) {
2873
3491
  if (arg !== void 0) return this.aggregateBy("count", arg);
2874
- this.rejectAggregate("count");
3492
+ this.rejectAggregation("count");
2875
3493
  return this.deriveAggregate(countProjection);
2876
3494
  }
2877
3495
  countDistinct(arg) {
@@ -2899,10 +3517,11 @@ var SelectQuery = class SelectQuery {
2899
3517
  return this.aggregateBy("stringAgg", arg, delimiter);
2900
3518
  }
2901
3519
  exists() {
2902
- this.rejectAggregate("exists");
3520
+ this.rejectAggregation("exists");
2903
3521
  return this.deriveAggregate(getExistsProjection());
2904
3522
  }
2905
3523
  coalesce(fallback) {
3524
+ this.rejectMapped("coalesce");
2906
3525
  const { node } = this;
2907
3526
  if (!node.value) throw new Error("coalesce applies only to a query of values, such as one made by get, pluck, or an aggregate");
2908
3527
  return this.derive({ projections: [coalesceValue(node.projections[0], fallback)] });
@@ -2911,6 +3530,18 @@ var SelectQuery = class SelectQuery {
2911
3530
  const value = this[operandNode]();
2912
3531
  return toExpression(value, this.node.projections[0].type);
2913
3532
  }
3533
+ groupBy(...args) {
3534
+ this.rejectAggregate("groupBy");
3535
+ if (this.node.lock !== void 0) throw new Error("groupBy cannot be used after a row lock, since a group comes from several rows of the table");
3536
+ return this.derive({ groupBy: addGroupKeys("groupBy", this.node, this.context, args) });
3537
+ }
3538
+ having(filter) {
3539
+ return this.derive({
3540
+ having: addHaving(this.node, filter, this.context),
3541
+ rows: this.getFilteredRows(),
3542
+ guaranteed: false
3543
+ });
3544
+ }
2914
3545
  orderBy(...args) {
2915
3546
  return this.derive({ orderBy: addOrder(this.node, this.context, args) });
2916
3547
  }
@@ -2920,11 +3551,36 @@ var SelectQuery = class SelectQuery {
2920
3551
  offset(count) {
2921
3552
  return this.derive({ offset: createPageCount(this.node, "offset", count) });
2922
3553
  }
3554
+ distinct() {
3555
+ if (this.node.rows !== "many") throw new Error("distinct applies only to a query of many rows");
3556
+ if (this.node.distinctOn.length > 0) throw new Error("distinct cannot be used after distinctOn, which compares only its keys");
3557
+ if (this.node.lock !== void 0) throw new Error("distinct cannot be used after a row lock, since a row without duplicates comes from several rows of the table");
3558
+ return this.derive({ distinct: true });
3559
+ }
3560
+ distinctOn(...args) {
3561
+ const { node } = this;
3562
+ if (node.rows !== "many") throw new Error("distinctOn applies only to a query of many rows");
3563
+ if (node.distinct) throw new Error("distinctOn cannot be used after distinct, which compares every selected field");
3564
+ if (node.lock !== void 0) throw new Error("distinctOn cannot be used after a row lock; PostgreSQL does not allow row locks with DISTINCT ON");
3565
+ return this.derive({ distinctOn: addGroupKeys("distinctOn", node, this.context, args) });
3566
+ }
3567
+ forUpdate(options) {
3568
+ return this.derive({ lock: createRowLock(this.node, "forUpdate", "UPDATE", options) });
3569
+ }
3570
+ forNoKeyUpdate(options) {
3571
+ return this.derive({ lock: createRowLock(this.node, "forNoKeyUpdate", "NO KEY UPDATE", options) });
3572
+ }
3573
+ forShare(options) {
3574
+ return this.derive({ lock: createRowLock(this.node, "forShare", "SHARE", options) });
3575
+ }
3576
+ forKeyShare(options) {
3577
+ return this.derive({ lock: createRowLock(this.node, "forKeyShare", "KEY SHARE", options) });
3578
+ }
2923
3579
  optional() {
2924
3580
  return this.changeOneRow("optional", "optional");
2925
3581
  }
2926
3582
  nullable() {
2927
- if (this.node.value) throw new Error("nullable applies only to a query of records; use optional after get, pluck, or an aggregate");
3583
+ if (this.node.value && this.node.conversion === void 0) throw new Error("nullable applies only to a query of records; use optional after get, pluck, or an aggregate");
2928
3584
  return this.changeOneRow("nullable", "nullable");
2929
3585
  }
2930
3586
  required() {
@@ -2947,6 +3603,12 @@ var SelectQuery = class SelectQuery {
2947
3603
  if (this.node.rows !== "many") throw new Error("all applies only to a query of many rows");
2948
3604
  return this.derive({ all: true });
2949
3605
  }
3606
+ map(callback) {
3607
+ return this.derive({ conversion: addMap(this.node.conversion, callback) });
3608
+ }
3609
+ transform(callback) {
3610
+ return transformQuery(this.node, this.db, callback);
3611
+ }
2950
3612
  use(callback, ...args) {
2951
3613
  return requireDerived(this, callback(this, ...args), "The callback of use");
2952
3614
  }
@@ -2961,6 +3623,7 @@ var SelectQuery = class SelectQuery {
2961
3623
  [operandNode]() {
2962
3624
  const { node } = this;
2963
3625
  if (!node.value || node.rows === "many") throw new TypeError("An expression takes a query of one value, such as of get, an aggregate, or exists, not a query of records or of an array");
3626
+ if (node.conversion !== void 0) throw new TypeError("An expression takes a query of one value, such as of get, an aggregate, or exists, not a query of map");
2964
3627
  return createNode({
2965
3628
  kind: "nestedQuery",
2966
3629
  query: node,
@@ -2975,6 +3638,7 @@ var SelectQuery = class SelectQuery {
2975
3638
  [valuesQueryNode]() {
2976
3639
  const { node } = this;
2977
3640
  if (!node.value) throw new TypeError("in takes a query of values, such as of pluck, not a query of records");
3641
+ if (node.conversion !== void 0) throw new TypeError("in takes a query of values, such as of pluck, not a query of map");
2978
3642
  return createNode({
2979
3643
  kind: "nestedQuery",
2980
3644
  query: node,
@@ -3000,18 +3664,25 @@ var SelectQuery = class SelectQuery {
3000
3664
  }
3001
3665
  return this.derive(changes);
3002
3666
  }
3003
- /** Creates the query of the value of `projection`, of an aggregate or of `exists` over the rows of this query, which always returns one row. */
3667
+ /**
3668
+ * Creates the query of the value of `projection`, of an aggregate or of `exists` over the rows of this query, which always returns one row.
3669
+ *
3670
+ * A query of `distinct` or `distinctOn` keeps the fields that `projection` replaces: `distinct` compares them, and the keys, the order, and the argument of an aggregate read a selected field through its projection.
3671
+ */
3004
3672
  deriveAggregate(projection) {
3005
- return this.derive({
3673
+ const { node } = this;
3674
+ const changes = {
3006
3675
  projections: [projection],
3007
3676
  rows: "one",
3008
3677
  value: true,
3009
3678
  guaranteed: false
3010
- });
3679
+ };
3680
+ if (node.distinct || node.distinctOn.length > 0) changes.distinctFields = node.projections;
3681
+ return this.derive(changes);
3011
3682
  }
3012
3683
  /** Creates the query of the aggregate of `method` over `arg`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value; `delimiter` is the delimiter of `stringAgg`. */
3013
3684
  aggregateBy(method, arg, delimiter) {
3014
- this.rejectAggregate(method);
3685
+ this.rejectAggregation(method);
3015
3686
  return this.deriveAggregate(projectAggregate(method, projectValue(this.node.from, arg, method, this.context), delimiter));
3016
3687
  }
3017
3688
  /** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
@@ -3019,10 +3690,15 @@ var SelectQuery = class SelectQuery {
3019
3690
  const { node } = this;
3020
3691
  return {
3021
3692
  filters: addUserFilter(node.filters, filter, node.from, this.context),
3022
- rows: toFilteredRows(node.rows, node.value, node.guaranteed),
3693
+ rows: this.getFilteredRows(),
3023
3694
  guaranteed: false
3024
3695
  };
3025
3696
  }
3697
+ /** Returns the rows mode of this query after a filter, as `FilteredStateRows` gives it in types. */
3698
+ getFilteredRows() {
3699
+ const { node } = this;
3700
+ return toFilteredRows(node.rows, node.value && node.conversion === void 0, node.guaranteed);
3701
+ }
3026
3702
  /** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
3027
3703
  takeWhere(values) {
3028
3704
  const changes = this.addFilter(values);
@@ -3037,26 +3713,37 @@ var SelectQuery = class SelectQuery {
3037
3713
  guaranteed: false
3038
3714
  });
3039
3715
  }
3716
+ /** Rejects `method`, which reads or changes the fields of the query, on a query that `map` converts. */
3717
+ rejectMapped(method) {
3718
+ if (this.node.conversion !== void 0) throw new Error(`${method} cannot be used after map; call it before map`);
3719
+ }
3040
3720
  /** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
3041
3721
  rejectValue(method) {
3722
+ this.rejectMapped(method);
3042
3723
  if (!this.node.value) return;
3043
3724
  this.rejectAggregate(method);
3044
3725
  throw new Error(`${method} cannot be used after get or pluck; call get or pluck to replace the value`);
3045
3726
  }
3046
3727
  /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method or `exists`. */
3047
3728
  rejectAggregate(method) {
3729
+ this.rejectMapped(method);
3048
3730
  const { node } = this;
3049
3731
  if (isAggregateQuery(node)) throw new Error(`${method} cannot be used after an aggregate`);
3050
3732
  if (isExistsQuery(node)) throw new Error(`${method} cannot be used after exists`);
3051
3733
  }
3734
+ /** Rejects `method`, an aggregate method or `exists`, on a query made by one of them or with a row lock. */
3735
+ rejectAggregation(method) {
3736
+ this.rejectAggregate(method);
3737
+ if (this.node.lock !== void 0) throw new Error(`${method} cannot be used after a row lock, since it returns no rows of the table to lock`);
3738
+ }
3052
3739
  };
3053
3740
  /**
3054
- * Returns `result`, which a callback named by `subject` returned for `query`, after checking that it is `query` or a query derived from it.
3741
+ * Returns `result`, which a callback named by `subject` returned for `query`, a query of a table or a mutation, after checking that it is `query` or a query of the same class derived from it.
3055
3742
  *
3056
3743
  * An ancestor of `query` also passes, since only the source occurrence is compared.
3057
3744
  */
3058
3745
  function requireDerived(query, result, subject) {
3059
- if (!(result instanceof SelectQuery) || result.node.from !== query.node.from) throw new Error(`${subject} must return the query it receives or one derived from it`);
3746
+ if (!(query instanceof SelectQuery ? result instanceof SelectQuery && result.node.from === query.node.from : result instanceof MutationQuery && result.node.target === query.node.target)) throw new Error(`${subject} must return the query it receives or one derived from it`);
3060
3747
  return result;
3061
3748
  }
3062
3749
  /** Binds a query to `db`, so that awaiting it executes it there. */
@@ -3247,6 +3934,7 @@ function toRawSqlNode(strings, values) {
3247
3934
  function toInterpolatedNode(value) {
3248
3935
  if (value instanceof SelectQuery) {
3249
3936
  const { node } = value;
3937
+ if (node.conversion !== void 0) throw new TypeError("sql takes a query of a table, such as db.form or a query of its records, not a query of map or transform");
3250
3938
  return isTableQuery(node) ? createNode({
3251
3939
  kind: "tableName",
3252
3940
  table: value.table,
@@ -3257,7 +3945,7 @@ function toInterpolatedNode(value) {
3257
3945
  db: value.db
3258
3946
  });
3259
3947
  }
3260
- if (value instanceof RecordQuery || value instanceof MutationQuery || value instanceof SqlQuery) throw new TypeError("sql takes a query of a table, such as db.form or a query of its records, not a query of $select, a mutation, or a query of SQL text");
3948
+ if (value instanceof RecordQuery || value instanceof MutationQuery || value instanceof SqlQuery || value instanceof TransformedQuery) throw new TypeError("sql takes a query of a table, such as db.form or a query of its records, not a query of $select, a mutation, a query of SQL text, or a query of map or transform");
3261
3949
  return toValueNode(value);
3262
3950
  }
3263
3951
  // src/execution/db.ts
@@ -3284,6 +3972,7 @@ function bindSchema(schema, database, options = {}) {
3284
3972
  },
3285
3973
  async $execute(query) {
3286
3974
  const compiled = compile(query);
3975
+ if (compiled.locksRows && !database.isInTransaction()) throw new Error("Cannot lock the rows of a query outside a transaction, where the locks would end with its statement; a test transaction alone does not count");
3287
3976
  return decodeStatement(compiled, await database.execute(compiled));
3288
3977
  },
3289
3978
  $select: (selection) => startRecordQuery(selection, db),
@@ -3303,124 +3992,316 @@ function bindSchema(schema, database, options = {}) {
3303
3992
  const db = defineEntries(methods, schema.$tables, (key) => bindQuery(startQuery(schema.$tables[key], contexts[key]), db));
3304
3993
  return db;
3305
3994
  }
3306
- // src/execution/transaction.ts
3995
+ // src/execution/transaction/abort.ts
3307
3996
  /**
3308
- * Routes statements and scripts to the ambient transaction of the current async context or to the pool.
3997
+ * Runs `start` and settles as its promise, or rejects with the reason of `signal` when it aborts first and `abort`, called on the abort, returns `true`.
3309
3998
  *
3310
- * This is the only place that decides which connection executes a statement.
3999
+ * It listens from before `start`, which may abort the signal before it returns, and stops once the promise of `start` settles, such as for the signal that `node:test` aborts after every test.
4000
+ * A later rejection of that promise stays handled, and a value it resolves with after the rejection goes to `discard`, which handles its own failures.
3311
4001
  */
3312
- var TransactionCoordinator = class {
3313
- driver;
3314
- test;
3315
- #storage = new AsyncLocalStorage();
3316
- /** Open test fixtures, the innermost last. */
3317
- #fixtures = [];
3318
- /** Changes of the fixture stack, run one after another so that each one sees the stack the previous one left. */
3319
- #transitions = Promise.resolve();
3320
- /**
3321
- * The `close` functions of the test fixtures that are still opening, from the call that starts the opening until the fixture enters the stack or the opening ends otherwise.
3322
- *
3323
- * An opening holds the queue of the fixture stack while its seed runs, so a closing of the stack queued behind it would wait for a seed that may never settle.
3324
- * Closing the stack therefore calls these first: each one tells its opening to stop waiting for the seed.
3325
- */
3326
- #openings = /* @__PURE__ */ new Set();
3327
- /**
3328
- * Outermost fixture in the stack whose closing is queued but has not finished.
3329
- *
3330
- * Openings that start after that closing is requested nest outside of the fixture once it closes, so a repeated closing of it, or a closing of a fixture nested in it, must not close them.
3331
- */
3332
- #closing;
3333
- /** Closing of the database, set by the first `close`; from then on, operations outside a transaction reject. */
3334
- #closed;
3335
- constructor(driver, test = false) {
3336
- this.driver = driver;
3337
- this.test = test;
4002
+ function settleUnlessAborted(start, signal, abort, discard) {
4003
+ const settled = Promise.withResolvers();
4004
+ let abandoned = false;
4005
+ const onAbort = () => {
4006
+ if (abort()) {
4007
+ abandoned = true;
4008
+ settled.reject(signal.reason);
4009
+ }
4010
+ };
4011
+ signal.addEventListener("abort", onAbort, { once: true });
4012
+ let running;
4013
+ try {
4014
+ running = start();
4015
+ } catch (error) {
4016
+ signal.removeEventListener("abort", onAbort);
4017
+ settled.reject(error);
4018
+ return settled.promise;
3338
4019
  }
3339
- execute(statement) {
3340
- const target = this.#route("execute a query");
3341
- return target instanceof Error ? Promise.reject(target) : target.execute(statement);
4020
+ running.then((value) => {
4021
+ signal.removeEventListener("abort", onAbort);
4022
+ if (abandoned) discard?.(value);
4023
+ else settled.resolve(value);
4024
+ }, (error) => {
4025
+ signal.removeEventListener("abort", onAbort);
4026
+ settled.reject(error);
4027
+ });
4028
+ return settled.promise;
4029
+ }
4030
+ /**
4031
+ * Acquires a connection for a test transaction, rejecting with the reason of `signal` when it aborts first.
4032
+ *
4033
+ * A connection acquired after the abort returns to the pool as best-effort cleanup: the test transaction has already rejected, so nothing awaits the release, and its failure is ignored.
4034
+ */
4035
+ function acquireUnlessAborted(driver, signal) {
4036
+ if (signal.aborted) return Promise.reject(signal.reason);
4037
+ return settleUnlessAborted(() => driver.acquire(), signal, () => true, (connection) => {
4038
+ Promise.resolve().then(() => connection.release()).catch(() => {});
4039
+ });
4040
+ }
4041
+ // src/execution/transaction/settings.ts
4042
+ /** Settings of a level of `transaction` with `options`, or `undefined` when it has none. */
4043
+ function getLevelSettings(options) {
4044
+ return options?.searchPath ? [{
4045
+ name: "search_path",
4046
+ value: options.searchPath.map(quoteIdentifier).join(", ")
4047
+ }] : void 0;
4048
+ }
4049
+ /**
4050
+ * Applies `settings` to a level whose `BEGIN` or `SAVEPOINT` completed, unless its cleanup has started.
4051
+ *
4052
+ * A nested level first reads the values they replace, which it restores before its `RELEASE`: PostgreSQL keeps a setting of a released savepoint until the transaction ends, while `ROLLBACK TO` restores it itself.
4053
+ */
4054
+ async function applySettings(level, settings) {
4055
+ if (level.cleanup) return;
4056
+ if (level.parent) {
4057
+ let text = "SELECT";
4058
+ const names = [];
4059
+ for (const { name } of settings) {
4060
+ names.push(name);
4061
+ text += `${names.length > 1 ? "," : ""} current_setting($${names.length})`;
4062
+ }
4063
+ const values = (await level.connection.execute(createStatement(text, names))).rows[0];
4064
+ level.restore = createSettingStatement(settings.map(({ name }, index) => ({
4065
+ name,
4066
+ value: values[index]
4067
+ })));
4068
+ if (level.cleanup) return;
3342
4069
  }
3343
- /** Executes a script of statements without parameters where `execute` executes a statement. */
3344
- executeScript(text) {
3345
- const target = this.#route("execute a script");
3346
- return target instanceof Error ? Promise.reject(target) : target.executeScript(text);
4070
+ await level.connection.execute(createSettingStatement(settings));
4071
+ }
4072
+ /** Creates the statement that sets `settings` until the transaction ends or rolls back to an earlier savepoint, as `SET LOCAL` does. */
4073
+ function createSettingStatement(settings) {
4074
+ let text = "SELECT";
4075
+ const parameters = [];
4076
+ for (const { name, value } of settings) {
4077
+ parameters.push(name, value);
4078
+ text += `${parameters.length > 2 ? "," : ""} set_config($${parameters.length - 1}, $${parameters.length}, true)`;
3347
4079
  }
3348
- /** Returns the connection of the ambient transaction or the driver of the pool that runs `operation`, or the error that rejects it. */
3349
- #route(operation) {
3350
- const level = this.#storage.getStore();
3351
- if (!level) {
3352
- if (this.#closed) return createDatabaseClosedError(operation);
3353
- return this.test ? new Error(describeOutsideTest(operation)) : this.driver;
4080
+ return createStatement(text, parameters);
4081
+ }
4082
+ // src/execution/transaction/level.ts
4083
+ /** Statement that starts the transaction of a level without a parent: a transaction of `transaction`, a test transaction, or the first test fixture. */
4084
+ const beginStatement = /* @__PURE__ */ createStatement("BEGIN");
4085
+ const commitStatement = /* @__PURE__ */ createStatement("COMMIT");
4086
+ const rollbackStatement = /* @__PURE__ */ createStatement("ROLLBACK");
4087
+ /**
4088
+ * Creates the state of a `starting` level on `connection`, nested in `parent` if given.
4089
+ *
4090
+ * It sends no SQL and does not reserve the level as the `child` of `parent`; the caller does both.
4091
+ * `transaction` tells whether the level is a transaction of `transaction` rather than a level of the test helpers.
4092
+ */
4093
+ function createLevel(connection, parent, transaction) {
4094
+ return {
4095
+ connection,
4096
+ parent,
4097
+ depth: parent ? parent.depth + 1 : 0,
4098
+ inTransaction: transaction || (parent?.inTransaction ?? false),
4099
+ state: "starting",
4100
+ child: void 0,
4101
+ rollbackOnly: void 0,
4102
+ cleanup: void 0,
4103
+ endedBy: void 0,
4104
+ restore: void 0
4105
+ };
4106
+ }
4107
+ /**
4108
+ * Reserves a nested level of `parent`, sends its `SAVEPOINT`, and applies its `settings`, rejecting when one of them fails.
4109
+ *
4110
+ * `transaction` tells whether the level is a transaction of `transaction` rather than a level of the test helpers.
4111
+ * A level whose settings fail rolls back to its savepoint first.
4112
+ * The failure suppresses the reason of `signal` when the signal aborted before it.
4113
+ */
4114
+ async function startNestedLevel(parent, transaction, signal, settings) {
4115
+ const level = createLevel(parent.connection, parent, transaction);
4116
+ parent.child = level;
4117
+ try {
4118
+ await level.connection.execute(createStatement(`SAVEPOINT ${getSavepointName(level)}`));
4119
+ } catch (error) {
4120
+ if (!level.cleanup) {
4121
+ closeStarting(level);
4122
+ throw suppressAbortReason(error, signal);
3354
4123
  }
3355
- return createUnavailableError(level, operation) ?? level.connection;
4124
+ throw suppressAbortReason(combineRejections({ error }, await level.cleanup).error, signal);
3356
4125
  }
3357
- /**
3358
- * Runs `callback` in a transaction that commits when it resolves and rolls back when it rejects, with the settings of `options`.
3359
- *
3360
- * Inside a transaction, it runs `callback` in a savepoint nested in it, which restores the settings it changed when it ends.
3361
- * A failed cleanup after an error rejects with a `SuppressedError` that keeps the original error in its `suppressed` chain.
3362
- */
3363
- transaction(callback, options) {
3364
- const settings = getLevelSettings(options);
3365
- const parent = this.#storage.getStore();
3366
- if (parent) return this.#runNested(parent, callback, true, void 0, settings);
3367
- if (this.#closed) return Promise.reject(createDatabaseClosedError("start a transaction"));
3368
- return this.test ? Promise.reject(new Error(describeOutsideTest("start a transaction"))) : this.#runRoot(callback, true, void 0, settings);
4126
+ if (settings) try {
4127
+ await applySettings(level, settings);
4128
+ } catch (error) {
4129
+ throw suppressAbortReason(combineRejections({ error }, await endLevel(level, false)).error, signal);
3369
4130
  }
3370
- /**
3371
- * Runs `callback` in the current transaction, or in a new transaction outside of one.
3372
- *
3373
- * Joining starts no savepoint, so a rejection of `callback` does not undo its changes.
3374
- * It rejects without calling `callback` when the current level accepts no statements, as a nested transaction would.
3375
- */
3376
- async ensureTransaction(callback) {
3377
- const level = this.#storage.getStore();
3378
- if (!level?.inTransaction) return this.transaction(callback);
3379
- const unavailable = createUnavailableError(level, "join the transaction");
3380
- if (unavailable) throw unavailable;
3381
- return callback();
4131
+ return level;
4132
+ }
4133
+ /**
4134
+ * Runs `callback` in the context of a started `level` in `storage`, then ends the level.
4135
+ *
4136
+ * A level that `commits` commits only when the callback resolves with no nested level running and no nested level that failed to end.
4137
+ * When `signal` aborts, the level ends at once without waiting for the callback, and its outcome is a rejection with the reason of the signal.
4138
+ */
4139
+ async function runLevel(storage, level, callback, commits, signal) {
4140
+ if (level.cleanup) return getEndedOutcome(level.cleanup, createClosedError(level, void 0));
4141
+ let result;
4142
+ let rejection;
4143
+ if (signal?.aborted) endLevel(level, false, "abort");
4144
+ else {
4145
+ level.state = "open";
4146
+ try {
4147
+ result = await (signal ? settleUnlessAborted(() => storage.run(level, callback), signal, () => {
4148
+ endLevel(level, false, "abort");
4149
+ return true;
4150
+ }) : storage.run(level, callback));
4151
+ } catch (error) {
4152
+ rejection = { error };
4153
+ }
3382
4154
  }
3383
- /**
3384
- * Tells whether the current async context runs in a transaction of `transaction`.
3385
- *
3386
- * A test transaction and the seed of a test fixture are not transactions, unless they run inside one, so that code under test behaves as in production.
3387
- */
3388
- isInTransaction() {
3389
- return this.#storage.getStore()?.inTransaction ?? false;
4155
+ if (level.cleanup) return getEndedOutcome(level.cleanup, level.endedBy === "abort" ? signal?.reason : createClosedError(level, rejection));
4156
+ if (!rejection && level.child) rejection = { error: /* @__PURE__ */ new Error("Transaction was rolled back: a nested transaction was still running when its callback finished") };
4157
+ if (!rejection && level.rollbackOnly) rejection = { error: new Error("Transaction was rolled back: a nested transaction failed to end", { cause: level.rollbackOnly.error }) };
4158
+ const cleanup = await endLevel(level, commits && !rejection);
4159
+ return {
4160
+ result,
4161
+ rejection: combineRejections(rejection, cleanup),
4162
+ failure: cleanup.failure
4163
+ };
4164
+ }
4165
+ /**
4166
+ * Ends `level` once, whoever ends it: later calls return the cleanup already started.
4167
+ *
4168
+ * Statements of the level and of all levels nested in it fail from the start of the cleanup, and the nested levels end before it.
4169
+ */
4170
+ function endLevel(level, commit, endedBy) {
4171
+ if (level.cleanup) return level.cleanup;
4172
+ level.endedBy = endedBy;
4173
+ level.state = "closing";
4174
+ level.cleanup = cleanUpLevel(level, commit, level.child && endLevel(level.child, false, "enclosing level"));
4175
+ return level.cleanup;
4176
+ }
4177
+ async function cleanUpLevel(level, commit, nested) {
4178
+ const nestedCleanup = await nested;
4179
+ const { parent } = level;
4180
+ const cleanup = parent ? await endSavepoint(level, commit && !level.rollbackOnly) : await endTransaction(level.connection, commit);
4181
+ level.state = "closed";
4182
+ if (parent) {
4183
+ if (parent.child === level) parent.child = void 0;
4184
+ parent.rollbackOnly ??= cleanup.rejection;
4185
+ }
4186
+ return {
4187
+ rejection: combineRejections(nestedCleanup?.rejection, cleanup),
4188
+ failure: cleanup.failure
4189
+ };
4190
+ }
4191
+ /** Ends a transaction with `COMMIT` or `ROLLBACK`. */
4192
+ async function endTransaction(connection, commit) {
4193
+ try {
4194
+ const { command } = await connection.execute(commit ? commitStatement : rollbackStatement);
4195
+ if (commit && command !== "COMMIT") return { rejection: { error: /* @__PURE__ */ new Error("Transaction was rolled back: a statement in it failed") } };
4196
+ return {};
4197
+ } catch (error) {
4198
+ return {
4199
+ rejection: { error },
4200
+ failure: { error }
4201
+ };
4202
+ }
4203
+ }
4204
+ /**
4205
+ * Ends the savepoint of a nested level, releasing it on commit and rolling back to it otherwise.
4206
+ *
4207
+ * Before a release, it restores the settings that the level changed; a rollback restores them itself.
4208
+ */
4209
+ async function endSavepoint(level, commit) {
4210
+ const name = getSavepointName(level);
4211
+ try {
4212
+ if (!commit) await level.connection.execute(createStatement(`ROLLBACK TO SAVEPOINT ${name}`));
4213
+ else if (level.restore) await level.connection.execute(level.restore);
4214
+ await level.connection.execute(createStatement(`RELEASE SAVEPOINT ${name}`));
4215
+ return {};
4216
+ } catch (error) {
4217
+ return { rejection: { error } };
4218
+ }
4219
+ }
4220
+ /** Name of the savepoint of a nested level; a level has at most one nested level, so the depth makes it unique. */
4221
+ function getSavepointName(level) {
4222
+ return `kern_${level.depth}`;
4223
+ }
4224
+ /** Closes a nested level whose `SAVEPOINT` failed, freeing its parent for other statements. */
4225
+ function closeStarting(level) {
4226
+ level.state = "closed";
4227
+ if (level.parent?.child === level) level.parent.child = void 0;
4228
+ }
4229
+ /**
4230
+ * Creates the error of `operation` on a level that rejects statements and nested levels, or returns `undefined` when it accepts them.
4231
+ *
4232
+ * A level that can only roll back keeps the failure of its nested level as the cause.
4233
+ */
4234
+ function createUnavailableError(level, operation) {
4235
+ if (level.state !== "open") return /* @__PURE__ */ new Error(`Cannot ${operation}: its transaction is already finished`);
4236
+ if (level.child) return /* @__PURE__ */ new Error(`Cannot ${operation}: a nested transaction is running; await it first`);
4237
+ if (level.rollbackOnly) return new Error(`Cannot ${operation}: a nested transaction failed to end, so the transaction can only roll back`, { cause: level.rollbackOnly.error });
4238
+ }
4239
+ /** Error of a level that another level ended, keeping the rejection of its callback as the cause. */
4240
+ function createClosedError(level, rejection) {
4241
+ return new Error(level.endedBy === "preemption" ? "Transaction was rolled back: its test fixture started another level before it finished" : "Transaction was rolled back: its enclosing transaction ended first", rejection && { cause: rejection.error });
4242
+ }
4243
+ /** Outcome of a level that something other than its callback ended: a rejection with `error`, which a failed cleanup suppresses. */
4244
+ async function getEndedOutcome(cleanup, error) {
4245
+ const ended = await cleanup;
4246
+ return {
4247
+ rejection: combineRejections({ error }, ended),
4248
+ failure: ended.failure
4249
+ };
4250
+ }
4251
+ /** Returns the connection of a transaction to the driver, keeping a failed release as a rejection that suppresses `rejection`. */
4252
+ async function releaseConnection(connection, failure, rejection) {
4253
+ try {
4254
+ await connection.release(failure);
4255
+ return rejection;
4256
+ } catch (error) {
4257
+ return suppress(error, rejection, "Releasing the transaction connection failed");
3390
4258
  }
4259
+ }
4260
+ /** Error of a failure to start a test transaction, which suppresses the reason of `signal` when the signal aborted before the failure. */
4261
+ function suppressAbortReason(error, signal) {
4262
+ return signal?.aborted ? suppress(error, { error: signal.reason }, "Starting the test transaction failed").error : error;
4263
+ }
4264
+ /** Rejection with the error of a cleanup, which suppresses the `earlier` rejection if there is one. */
4265
+ function combineRejections(earlier, cleanup) {
4266
+ return cleanup.rejection ? suppress(cleanup.rejection.error, earlier, "Transaction rollback failed") : earlier;
4267
+ }
4268
+ /** Rejection with `error`, which suppresses the `earlier` rejection if there is one. */
4269
+ function suppress(error, earlier, message) {
4270
+ return { error: earlier ? new SuppressedError(error, earlier.error, message) : error };
4271
+ }
4272
+ // src/execution/transaction/fixture-stack.ts
4273
+ /** Open test fixtures of a transaction coordinator and the queue of the changes of their stack. */
4274
+ var TestFixtureStack = class {
4275
+ #driver;
4276
+ /** Async context of the levels of the coordinator, which tells whether a call runs inside a level. */
4277
+ #storage;
4278
+ /** Open test fixtures, the innermost last. */
4279
+ #fixtures = [];
4280
+ /** Changes of the fixture stack, run one after another so that each one sees the stack the previous one left. */
4281
+ #transitions = Promise.resolve();
3391
4282
  /**
3392
- * Runs `callback` in a transaction that always rolls back, on a coordinator created for tests.
4283
+ * The `close` functions of the test fixtures that are still opening, from the call that starts the opening until the fixture enters the stack or the opening ends otherwise.
3393
4284
  *
3394
- * Inside a transaction, it runs `callback` in a savepoint nested in it that always rolls back.
3395
- * When `signal` aborts, the level stops accepting statements at once and ends without waiting for `callback`.
3396
- * Once the level ends, the transaction rejects with the reason of the signal.
3397
- * A failure to start or end the level after the abort suppresses the reason in a `SuppressedError`.
3398
- * Aborted while it waits for its turn in the fixture stack or for a connection, it rejects at once; after the abort, it never calls `callback`.
4285
+ * An opening holds the queue of the fixture stack while its seed runs, so a closing of the stack queued behind it would wait for a seed that may never settle.
4286
+ * Closing the stack therefore calls these first: each one tells its opening to stop waiting for the seed.
3399
4287
  */
3400
- testTransaction(callback, { signal } = {}) {
3401
- if (!this.test) return Promise.reject(/* @__PURE__ */ new Error("testTransaction requires a database created with test: true"));
3402
- if (signal?.aborted) return Promise.reject(signal.reason);
3403
- const parent = this.#storage.getStore();
3404
- if (parent) return this.#runNested(parent, callback, false, signal);
3405
- if (this.#closed) return Promise.reject(createDatabaseClosedError("start a test transaction"));
3406
- return this.#startTestLevel(signal).then((level) => level ? this.#runStarted(level, callback, false, signal) : this.#runRoot(callback, false, signal));
3407
- }
4288
+ #openings = /* @__PURE__ */ new Set();
3408
4289
  /**
3409
- * Opens a test fixture: a transaction on a reserved connection, or a savepoint in the innermost open fixture, and runs `seed` in it.
4290
+ * Outermost fixture in the stack whose closing is queued but has not finished.
3410
4291
  *
3411
- * Test transactions started outside any transaction run in the innermost fixture.
3412
- * A fixture whose `seed` rejects rolls back and closes.
4292
+ * Openings that start after that closing is requested nest outside of the fixture once it closes, so a repeated closing of it, or a closing of a fixture nested in it, must not close them.
3413
4293
  */
3414
- createTestFixture(seed) {
3415
- return this.startTestFixture(seed).fixture;
4294
+ #closing;
4295
+ constructor(driver, storage) {
4296
+ this.#driver = driver;
4297
+ this.#storage = storage;
3416
4298
  }
3417
4299
  /**
3418
- * Starts opening a test fixture, see `createTestFixture`, and returns it with a `close` that can be called before it opens.
4300
+ * Starts opening a test fixture, see `startTestFixture` of the coordinator, or, given `refusal`, returns a fixture that rejects with it.
3419
4301
  *
3420
- * Closing before the fixture opens rejects the opening without waiting for `seed` and rolls the fixture back, so a fixture or test transaction started after `close` never nests in it, even when its `seed` never settles.
3421
- * Closing an open fixture also closes the fixtures opening in it.
4302
+ * The `close` of a refused fixture resolves once the earlier changes of the stack end.
3422
4303
  */
3423
- startTestFixture(seed) {
4304
+ start(seed, refusal) {
3424
4305
  let level;
3425
4306
  let closeRequested = false;
3426
4307
  const closing = Promise.withResolvers();
@@ -3447,16 +4328,8 @@ var TransactionCoordinator = class {
3447
4328
  if (rejection) throw rejection.error;
3448
4329
  });
3449
4330
  };
3450
- if (!this.test) return {
3451
- fixture: Promise.reject(/* @__PURE__ */ new Error("createTestFixture requires a database created with test: true")),
3452
- close
3453
- };
3454
- if (this.#storage.getStore()) return {
3455
- fixture: Promise.reject(/* @__PURE__ */ new Error("Cannot create a test fixture inside a transaction")),
3456
- close
3457
- };
3458
- if (this.#closed) return {
3459
- fixture: Promise.reject(createDatabaseClosedError("create a test fixture")),
4331
+ if (refusal) return {
4332
+ fixture: Promise.reject(refusal),
3460
4333
  close
3461
4334
  };
3462
4335
  /**
@@ -3506,34 +4379,31 @@ var TransactionCoordinator = class {
3506
4379
  };
3507
4380
  }
3508
4381
  /**
3509
- * Closes the test fixtures, including those still opening, and then the driver, which waits for the running transactions to end.
4382
+ * Starts the level of a test transaction in the innermost test fixture as a change of the fixture stack, resolving to `undefined` when no fixture is open.
3510
4383
  *
3511
- * A driver waits for every reserved connection, so closing it under an open fixture would wait forever.
3512
- * A failed closing of the driver suppresses the failures of closing the fixtures.
3513
- * From the first call, statements, transactions, and fixtures started outside a transaction reject, while the levels already running can still end; a repeated call returns the same closing.
4384
+ * Aborted while it waits for its turn, it rejects at once and its change starts nothing, so that a test that has already ended never preempts the active level of the fixture.
4385
+ * From its turn on, it settles with its change.
3514
4386
  */
3515
- close() {
3516
- if (this.#storage.getStore()) return Promise.reject(/* @__PURE__ */ new Error("Cannot close the database inside a transaction"));
3517
- this.#closed ??= this.#close();
3518
- return this.#closed;
4387
+ startTestLevel(signal) {
4388
+ let waiting = true;
4389
+ const start = () => this.#enqueue(() => {
4390
+ if (signal?.aborted) return;
4391
+ waiting = false;
4392
+ const fixture = this.#fixtures.at(-1);
4393
+ return fixture && this.#startInFixture(fixture, signal);
4394
+ });
4395
+ return signal ? settleUnlessAborted(start, signal, () => waiting) : start();
3519
4396
  }
3520
- /** Closes the test fixtures and then the driver, see `close`. */
3521
- async #close() {
3522
- let rejection;
3523
- try {
3524
- await this.#closeAfterOpenings(() => this.#enqueue(() => {
3525
- const root = this.#fixtures[0];
3526
- return root && this.#closeFixture(root);
3527
- }));
3528
- } catch (error) {
3529
- rejection = { error };
3530
- }
3531
- try {
3532
- await this.driver.close();
3533
- } catch (error) {
3534
- rejection = suppress(error, rejection, "Closing the driver failed");
3535
- }
3536
- if (rejection) throw rejection.error;
4397
+ /**
4398
+ * Closes every fixture, including those still opening, rejecting with the failures of all of them.
4399
+ *
4400
+ * Unlike closing a fixture, it closes every opening, including one started after a closing of the stack was requested, since nothing may stay open.
4401
+ */
4402
+ close() {
4403
+ return this.#closeAfterOpenings(() => this.#enqueue(() => {
4404
+ const root = this.#fixtures[0];
4405
+ return root && this.#closeFixture(root);
4406
+ }));
3537
4407
  }
3538
4408
  /**
3539
4409
  * Closes the fixtures still opening and runs `closeStack`, rejecting with the failures of all of them.
@@ -3555,7 +4425,7 @@ var TransactionCoordinator = class {
3555
4425
  */
3556
4426
  async #seedFixture(fixture, seed) {
3557
4427
  try {
3558
- return await this.#run(await this.#startNested(fixture, false), seed, true);
4428
+ return await runLevel(this.#storage, await startNestedLevel(fixture, false), seed, true);
3559
4429
  } catch (error) {
3560
4430
  return { rejection: { error } };
3561
4431
  }
@@ -3574,56 +4444,179 @@ var TransactionCoordinator = class {
3574
4444
  }
3575
4445
  /** Rolls back a fixture and releases the connection of the first one, returning the error to reject with. */
3576
4446
  async #endFixture(fixture) {
3577
- const cleanup = await this.#end(fixture, false);
4447
+ const cleanup = await endLevel(fixture, false);
3578
4448
  return fixture.parent ? cleanup.rejection : releaseConnection(fixture.connection, cleanup.failure, cleanup.rejection);
3579
4449
  }
3580
- /**
3581
- * Starts the level of a test transaction in the innermost test fixture as a change of the fixture stack, resolving to `undefined` when no fixture is open.
3582
- *
3583
- * Aborted while it waits for its turn, it rejects at once and its change starts nothing, so that a test that has already ended never preempts the active level of the fixture.
3584
- * From its turn on, it settles with its change.
3585
- */
3586
- #startTestLevel(signal) {
3587
- let waiting = true;
3588
- const start = () => this.#enqueue(() => {
3589
- if (signal?.aborted) return;
3590
- waiting = false;
3591
- const fixture = this.#fixtures.at(-1);
3592
- return fixture && this.#startInFixture(fixture, signal);
3593
- });
3594
- return signal ? settleUnlessAborted(start, signal, () => waiting) : start();
3595
- }
3596
4450
  /** Runs a change of the fixture stack after the earlier ones. */
3597
4451
  #enqueue(transition) {
3598
4452
  const result = this.#transitions.then(transition);
3599
4453
  this.#transitions = result.catch(() => {});
3600
4454
  return result;
3601
4455
  }
3602
- /** Starts the first test fixture: a transaction on a reserved connection. */
3603
- async #beginFixture() {
3604
- const connection = await this.driver.acquire();
3605
- try {
3606
- await connection.execute(beginStatement);
3607
- } catch (error) {
3608
- throw (await releaseConnection(connection, { error }, { error })).error;
3609
- }
3610
- return createLevel(connection, void 0, false);
4456
+ /** Starts the first test fixture: a transaction on a reserved connection. */
4457
+ async #beginFixture() {
4458
+ const connection = await this.#driver.acquire();
4459
+ try {
4460
+ await connection.execute(beginStatement);
4461
+ } catch (error) {
4462
+ throw (await releaseConnection(connection, { error }, { error })).error;
4463
+ }
4464
+ return createLevel(connection, void 0, false);
4465
+ }
4466
+ /**
4467
+ * Starts a nested level of a test fixture, preempting its active one.
4468
+ *
4469
+ * A fixture runs one nested level at a time, so a new one ends the previous one, such as a test that timed out.
4470
+ * A level whose `signal` aborts while it preempts rejects with its reason instead of starting, and a failure to start after the abort suppresses the reason.
4471
+ */
4472
+ async #startInFixture(fixture, signal) {
4473
+ if (fixture.child) {
4474
+ const cleanup = await endLevel(fixture.child, false, "preemption");
4475
+ if (cleanup.rejection) throw suppressAbortReason(new Error("Cannot start a level of the test fixture: ending its active level failed", { cause: cleanup.rejection.error }), signal);
4476
+ }
4477
+ const unavailable = createUnavailableError(fixture, "start a level of the test fixture");
4478
+ if (unavailable) throw suppressAbortReason(unavailable, signal);
4479
+ signal?.throwIfAborted();
4480
+ return startNestedLevel(fixture, false, signal);
4481
+ }
4482
+ };
4483
+ // src/execution/transaction/coordinator.ts
4484
+ /**
4485
+ * Routes statements and scripts to the ambient transaction of the current async context or to the pool.
4486
+ *
4487
+ * This is the only place that decides which connection executes a statement.
4488
+ */
4489
+ var TransactionCoordinator = class {
4490
+ driver;
4491
+ test;
4492
+ #storage = new AsyncLocalStorage();
4493
+ #fixtures;
4494
+ /** Closing of the database, set by the first `close`; from then on, operations outside a transaction reject. */
4495
+ #closed;
4496
+ constructor(driver, test = false) {
4497
+ this.driver = driver;
4498
+ this.test = test;
4499
+ this.#fixtures = new TestFixtureStack(driver, this.#storage);
4500
+ }
4501
+ execute(statement) {
4502
+ const target = this.#route("execute a query");
4503
+ return target instanceof Error ? Promise.reject(target) : target.execute(statement);
4504
+ }
4505
+ /** Executes a script of statements without parameters where `execute` executes a statement. */
4506
+ executeScript(text) {
4507
+ const target = this.#route("execute a script");
4508
+ return target instanceof Error ? Promise.reject(target) : target.executeScript(text);
4509
+ }
4510
+ /** Returns the connection of the ambient transaction or the driver of the pool that runs `operation`, or the error that rejects it. */
4511
+ #route(operation) {
4512
+ const level = this.#storage.getStore();
4513
+ if (!level) {
4514
+ if (this.#closed) return createDatabaseClosedError(operation);
4515
+ return this.test ? new Error(describeOutsideTest(operation)) : this.driver;
4516
+ }
4517
+ return createUnavailableError(level, operation) ?? level.connection;
4518
+ }
4519
+ /**
4520
+ * Runs `callback` in a transaction that commits when it resolves and rolls back when it rejects, with the settings of `options`.
4521
+ *
4522
+ * Inside a transaction, it runs `callback` in a savepoint nested in it, which restores the settings it changed when it ends.
4523
+ * A failed cleanup after an error rejects with a `SuppressedError` that keeps the original error in its `suppressed` chain.
4524
+ */
4525
+ transaction(callback, options) {
4526
+ const settings = getLevelSettings(options);
4527
+ const parent = this.#storage.getStore();
4528
+ if (parent) return this.#runNested(parent, callback, true, void 0, settings);
4529
+ if (this.#closed) return Promise.reject(createDatabaseClosedError("start a transaction"));
4530
+ return this.test ? Promise.reject(new Error(describeOutsideTest("start a transaction"))) : this.#runRoot(callback, true, void 0, settings);
4531
+ }
4532
+ /**
4533
+ * Runs `callback` in the current transaction, or in a new transaction outside of one.
4534
+ *
4535
+ * Joining starts no savepoint, so a rejection of `callback` does not undo its changes.
4536
+ * It rejects without calling `callback` when the current level accepts no statements, as a nested transaction would.
4537
+ */
4538
+ async ensureTransaction(callback) {
4539
+ const level = this.#storage.getStore();
4540
+ if (!level?.inTransaction) return this.transaction(callback);
4541
+ const unavailable = createUnavailableError(level, "join the transaction");
4542
+ if (unavailable) throw unavailable;
4543
+ return callback();
4544
+ }
4545
+ /**
4546
+ * Tells whether the current async context runs in a transaction of `transaction`.
4547
+ *
4548
+ * A test transaction and the seed of a test fixture are not transactions, unless they run inside one, so that code under test behaves as in production.
4549
+ */
4550
+ isInTransaction() {
4551
+ return this.#storage.getStore()?.inTransaction ?? false;
4552
+ }
4553
+ /**
4554
+ * Runs `callback` in a transaction that always rolls back, on a coordinator created for tests.
4555
+ *
4556
+ * Inside a transaction, it runs `callback` in a savepoint nested in it that always rolls back.
4557
+ * When `signal` aborts, the level stops accepting statements at once and ends without waiting for `callback`.
4558
+ * Once the level ends, the transaction rejects with the reason of the signal.
4559
+ * A failure to start or end the level after the abort suppresses the reason in a `SuppressedError`.
4560
+ * Aborted while it waits for its turn in the fixture stack or for a connection, it rejects at once; after the abort, it never calls `callback`.
4561
+ */
4562
+ testTransaction(callback, { signal } = {}) {
4563
+ if (!this.test) return Promise.reject(/* @__PURE__ */ new Error("testTransaction requires a database created with test: true"));
4564
+ if (signal?.aborted) return Promise.reject(signal.reason);
4565
+ const parent = this.#storage.getStore();
4566
+ if (parent) return this.#runNested(parent, callback, false, signal);
4567
+ if (this.#closed) return Promise.reject(createDatabaseClosedError("start a test transaction"));
4568
+ return this.#fixtures.startTestLevel(signal).then((level) => level ? this.#runStarted(level, callback, false, signal) : this.#runRoot(callback, false, signal));
4569
+ }
4570
+ /**
4571
+ * Opens a test fixture: a transaction on a reserved connection, or a savepoint in the innermost open fixture, and runs `seed` in it.
4572
+ *
4573
+ * Test transactions started outside any transaction run in the innermost fixture.
4574
+ * A fixture whose `seed` rejects rolls back and closes.
4575
+ */
4576
+ createTestFixture(seed) {
4577
+ return this.startTestFixture(seed).fixture;
4578
+ }
4579
+ /**
4580
+ * Starts opening a test fixture, see `createTestFixture`, and returns it with a `close` that can be called before it opens.
4581
+ *
4582
+ * Closing before the fixture opens rejects the opening without waiting for `seed` and rolls the fixture back, so a fixture or test transaction started after `close` never nests in it, even when its `seed` never settles.
4583
+ * Closing an open fixture also closes the fixtures opening in it.
4584
+ */
4585
+ startTestFixture(seed) {
4586
+ return this.#fixtures.start(seed, this.#getFixtureRefusal());
4587
+ }
4588
+ /** Returns the error that rejects a test fixture created now, or `undefined` when it can open. */
4589
+ #getFixtureRefusal() {
4590
+ if (!this.test) return /* @__PURE__ */ new Error("createTestFixture requires a database created with test: true");
4591
+ if (this.#storage.getStore()) return /* @__PURE__ */ new Error("Cannot create a test fixture inside a transaction");
4592
+ if (this.#closed) return createDatabaseClosedError("create a test fixture");
3611
4593
  }
3612
4594
  /**
3613
- * Starts a nested level of a test fixture, preempting its active one.
4595
+ * Closes the test fixtures, including those still opening, and then the driver, which waits for the running transactions to end.
3614
4596
  *
3615
- * A fixture runs one nested level at a time, so a new one ends the previous one, such as a test that timed out.
3616
- * A level whose `signal` aborts while it preempts rejects with its reason instead of starting, and a failure to start after the abort suppresses the reason.
4597
+ * A driver waits for every reserved connection, so closing it under an open fixture would wait forever.
4598
+ * A failed closing of the driver suppresses the failures of closing the fixtures.
4599
+ * From the first call, statements, transactions, and fixtures started outside a transaction reject, while the levels already running can still end; a repeated call returns the same closing.
3617
4600
  */
3618
- async #startInFixture(fixture, signal) {
3619
- if (fixture.child) {
3620
- const cleanup = await this.#end(fixture.child, false, "preemption");
3621
- if (cleanup.rejection) throw suppressAbortReason(new Error("Cannot start a level of the test fixture: ending its active level failed", { cause: cleanup.rejection.error }), signal);
4601
+ close() {
4602
+ if (this.#storage.getStore()) return Promise.reject(/* @__PURE__ */ new Error("Cannot close the database inside a transaction"));
4603
+ this.#closed ??= this.#close();
4604
+ return this.#closed;
4605
+ }
4606
+ /** Closes the test fixtures and then the driver, see `close`. */
4607
+ async #close() {
4608
+ let rejection;
4609
+ try {
4610
+ await this.#fixtures.close();
4611
+ } catch (error) {
4612
+ rejection = { error };
3622
4613
  }
3623
- const unavailable = createUnavailableError(fixture, "start a level of the test fixture");
3624
- if (unavailable) throw suppressAbortReason(unavailable, signal);
3625
- signal?.throwIfAborted();
3626
- return this.#startNested(fixture, false, signal);
4614
+ try {
4615
+ await this.driver.close();
4616
+ } catch (error) {
4617
+ rejection = suppress(error, rejection, "Closing the driver failed");
4618
+ }
4619
+ if (rejection) throw rejection.error;
3627
4620
  }
3628
4621
  async #runRoot(callback, commits, signal, settings) {
3629
4622
  const connection = await (signal ? acquireUnlessAborted(this.driver, signal) : this.driver.acquire());
@@ -3642,9 +4635,9 @@ var TransactionCoordinator = class {
3642
4635
  if (!outcome && settings) try {
3643
4636
  await applySettings(level, settings);
3644
4637
  } catch (error) {
3645
- outcome = await getEndedOutcome(this.#end(level, false), error);
4638
+ outcome = await getEndedOutcome(endLevel(level, false), error);
3646
4639
  }
3647
- outcome ??= await this.#run(level, callback, commits, signal);
4640
+ outcome ??= await runLevel(this.#storage, level, callback, commits, signal);
3648
4641
  const rejection = await releaseConnection(connection, outcome.failure, outcome.rejection);
3649
4642
  if (rejection) throw rejection.error;
3650
4643
  return outcome.result;
@@ -3652,171 +4645,15 @@ var TransactionCoordinator = class {
3652
4645
  async #runNested(parent, callback, commits, signal, settings) {
3653
4646
  const unavailable = createUnavailableError(parent, "start a nested transaction");
3654
4647
  if (unavailable) throw unavailable;
3655
- return this.#runStarted(await this.#startNested(parent, commits, signal, settings), callback, commits, signal);
3656
- }
3657
- /**
3658
- * Reserves a nested level of `parent`, sends its `SAVEPOINT`, and applies its `settings`, rejecting when one of them fails.
3659
- *
3660
- * `transaction` tells whether the level is a transaction of `transaction` rather than a level of the test helpers.
3661
- * A level whose settings fail rolls back to its savepoint first.
3662
- * The failure suppresses the reason of `signal` when the signal aborted before it.
3663
- */
3664
- async #startNested(parent, transaction, signal, settings) {
3665
- const level = createLevel(parent.connection, parent, transaction);
3666
- parent.child = level;
3667
- try {
3668
- await level.connection.execute(createStatement(`SAVEPOINT ${getSavepointName(level)}`));
3669
- } catch (error) {
3670
- if (!level.cleanup) {
3671
- closeStarting(level);
3672
- throw suppressAbortReason(error, signal);
3673
- }
3674
- throw suppressAbortReason(combineRejections({ error }, await level.cleanup).error, signal);
3675
- }
3676
- if (settings) try {
3677
- await applySettings(level, settings);
3678
- } catch (error) {
3679
- throw suppressAbortReason(combineRejections({ error }, await this.#end(level, false)).error, signal);
3680
- }
3681
- return level;
4648
+ return this.#runStarted(await startNestedLevel(parent, commits, signal, settings), callback, commits, signal);
3682
4649
  }
3683
4650
  /** Runs `callback` in a started level, returning its result or throwing its rejection. */
3684
4651
  async #runStarted(level, callback, commits, signal) {
3685
- const { result, rejection } = await this.#run(level, callback, commits, signal);
4652
+ const { result, rejection } = await runLevel(this.#storage, level, callback, commits, signal);
3686
4653
  if (rejection) throw rejection.error;
3687
4654
  return result;
3688
4655
  }
3689
- /**
3690
- * Runs `callback` in the context of a started `level`, then ends the level.
3691
- *
3692
- * A level that `commits` commits only when the callback resolves with no nested level running and no nested level that failed to end.
3693
- * When `signal` aborts, the level ends at once without waiting for the callback, and its outcome is a rejection with the reason of the signal.
3694
- */
3695
- async #run(level, callback, commits, signal) {
3696
- if (level.cleanup) return getEndedOutcome(level.cleanup, createClosedError(level, void 0));
3697
- let result;
3698
- let rejection;
3699
- if (signal?.aborted) this.#end(level, false, "abort");
3700
- else {
3701
- level.state = "open";
3702
- try {
3703
- result = await (signal ? settleUnlessAborted(() => this.#storage.run(level, callback), signal, () => {
3704
- this.#end(level, false, "abort");
3705
- return true;
3706
- }) : this.#storage.run(level, callback));
3707
- } catch (error) {
3708
- rejection = { error };
3709
- }
3710
- }
3711
- if (level.cleanup) return getEndedOutcome(level.cleanup, level.endedBy === "abort" ? signal?.reason : createClosedError(level, rejection));
3712
- if (!rejection && level.child) rejection = { error: /* @__PURE__ */ new Error("Transaction was rolled back: a nested transaction was still running when its callback finished") };
3713
- if (!rejection && level.rollbackOnly) rejection = { error: new Error("Transaction was rolled back: a nested transaction failed to end", { cause: level.rollbackOnly.error }) };
3714
- const cleanup = await this.#end(level, commits && !rejection);
3715
- return {
3716
- result,
3717
- rejection: combineRejections(rejection, cleanup),
3718
- failure: cleanup.failure
3719
- };
3720
- }
3721
- /**
3722
- * Ends `level` once, whoever ends it: later calls return the cleanup already started.
3723
- *
3724
- * Statements of the level and of all levels nested in it fail from the start of the cleanup, and the nested levels end before it.
3725
- */
3726
- #end(level, commit, endedBy) {
3727
- if (level.cleanup) return level.cleanup;
3728
- level.endedBy = endedBy;
3729
- level.state = "closing";
3730
- const nested = level.child && this.#end(level.child, false, "enclosing level");
3731
- level.cleanup = this.#cleanUp(level, commit, nested);
3732
- return level.cleanup;
3733
- }
3734
- async #cleanUp(level, commit, nested) {
3735
- const nestedCleanup = await nested;
3736
- const { parent } = level;
3737
- const cleanup = parent ? await endSavepoint(level, commit && !level.rollbackOnly) : await endTransaction(level.connection, commit);
3738
- level.state = "closed";
3739
- if (parent) {
3740
- if (parent.child === level) parent.child = void 0;
3741
- parent.rollbackOnly ??= cleanup.rejection;
3742
- }
3743
- return {
3744
- rejection: combineRejections(nestedCleanup?.rejection, cleanup),
3745
- failure: cleanup.failure
3746
- };
3747
- }
3748
4656
  };
3749
- const beginStatement = createStatement("BEGIN");
3750
- const commitStatement = createStatement("COMMIT");
3751
- const rollbackStatement = createStatement("ROLLBACK");
3752
- function createLevel(connection, parent, transaction) {
3753
- return {
3754
- connection,
3755
- parent,
3756
- depth: parent ? parent.depth + 1 : 0,
3757
- inTransaction: transaction || (parent?.inTransaction ?? false),
3758
- state: "starting",
3759
- child: void 0,
3760
- rollbackOnly: void 0,
3761
- cleanup: void 0,
3762
- endedBy: void 0,
3763
- restore: void 0
3764
- };
3765
- }
3766
- /** Settings of a level of `transaction` with `options`, or `undefined` when it has none. */
3767
- function getLevelSettings(options) {
3768
- return options?.searchPath ? [{
3769
- name: "search_path",
3770
- value: options.searchPath.map(quoteIdentifier).join(", ")
3771
- }] : void 0;
3772
- }
3773
- /**
3774
- * Applies `settings` to a level whose `BEGIN` or `SAVEPOINT` completed, unless its cleanup has started.
3775
- *
3776
- * A nested level first reads the values they replace, which it restores before its `RELEASE`: PostgreSQL keeps a setting of a released savepoint until the transaction ends, while `ROLLBACK TO` restores it itself.
3777
- */
3778
- async function applySettings(level, settings) {
3779
- if (level.cleanup) return;
3780
- if (level.parent) {
3781
- let text = "SELECT";
3782
- const names = [];
3783
- for (const { name } of settings) {
3784
- names.push(name);
3785
- text += `${names.length > 1 ? "," : ""} current_setting($${names.length})`;
3786
- }
3787
- const values = (await level.connection.execute(createStatement(text, names))).rows[0];
3788
- level.restore = createSettingStatement(settings.map(({ name }, index) => ({
3789
- name,
3790
- value: values[index]
3791
- })));
3792
- if (level.cleanup) return;
3793
- }
3794
- await level.connection.execute(createSettingStatement(settings));
3795
- }
3796
- /** Creates the statement that sets `settings` until the transaction ends or rolls back to an earlier savepoint, as `SET LOCAL` does. */
3797
- function createSettingStatement(settings) {
3798
- let text = "SELECT";
3799
- const parameters = [];
3800
- for (const { name, value } of settings) {
3801
- parameters.push(name, value);
3802
- text += `${parameters.length > 2 ? "," : ""} set_config($${parameters.length - 1}, $${parameters.length}, true)`;
3803
- }
3804
- return createStatement(text, parameters);
3805
- }
3806
- /** Name of the savepoint of a nested level; a level has at most one nested level, so the depth makes it unique. */
3807
- function getSavepointName(level) {
3808
- return `kern_${level.depth}`;
3809
- }
3810
- /**
3811
- * Creates the error of `operation` on a level that rejects statements and nested levels, or returns `undefined` when it accepts them.
3812
- *
3813
- * A level that can only roll back keeps the failure of its nested level as the cause.
3814
- */
3815
- function createUnavailableError(level, operation) {
3816
- if (level.state !== "open") return /* @__PURE__ */ new Error(`Cannot ${operation}: its transaction is already finished`);
3817
- if (level.child) return /* @__PURE__ */ new Error(`Cannot ${operation}: a nested transaction is running; await it first`);
3818
- if (level.rollbackOnly) return new Error(`Cannot ${operation}: a nested transaction failed to end, so the transaction can only roll back`, { cause: level.rollbackOnly.error });
3819
- }
3820
4657
  /** Error message of an operation outside a test transaction on a coordinator created for tests. */
3821
4658
  function describeOutsideTest(operation) {
3822
4659
  return `Cannot ${operation} outside a test transaction: the database was created with test: true, so wrap the test in testTransaction`;
@@ -3825,118 +4662,6 @@ function describeOutsideTest(operation) {
3825
4662
  function createDatabaseClosedError(operation) {
3826
4663
  return /* @__PURE__ */ new Error(`Cannot ${operation}: the database is closed`);
3827
4664
  }
3828
- /** Closes a nested level whose `SAVEPOINT` failed, freeing its parent for other statements. */
3829
- function closeStarting(level) {
3830
- level.state = "closed";
3831
- if (level.parent?.child === level) level.parent.child = void 0;
3832
- }
3833
- /** Error of a level that another level ended, keeping the rejection of its callback as the cause. */
3834
- function createClosedError(level, rejection) {
3835
- return new Error(level.endedBy === "preemption" ? "Transaction was rolled back: its test fixture started another level before it finished" : "Transaction was rolled back: its enclosing transaction ended first", rejection && { cause: rejection.error });
3836
- }
3837
- /** Error of a failure to start a test transaction, which suppresses the reason of `signal` when the signal aborted before the failure. */
3838
- function suppressAbortReason(error, signal) {
3839
- return signal?.aborted ? suppress(error, { error: signal.reason }, "Starting the test transaction failed").error : error;
3840
- }
3841
- /** Outcome of a level that something other than its callback ended: a rejection with `error`, which a failed cleanup suppresses. */
3842
- async function getEndedOutcome(cleanup, error) {
3843
- const ended = await cleanup;
3844
- return {
3845
- rejection: combineRejections({ error }, ended),
3846
- failure: ended.failure
3847
- };
3848
- }
3849
- /**
3850
- * Runs `start` and settles as its promise, or rejects with the reason of `signal` when it aborts first and `abort`, called on the abort, returns `true`.
3851
- *
3852
- * It listens from before `start`, which may abort the signal before it returns, and stops once the promise of `start` settles, such as for the signal that `node:test` aborts after every test.
3853
- * A later rejection of that promise stays handled, and a value it resolves with after the rejection goes to `discard`, which handles its own failures.
3854
- */
3855
- function settleUnlessAborted(start, signal, abort, discard) {
3856
- const settled = Promise.withResolvers();
3857
- let abandoned = false;
3858
- const onAbort = () => {
3859
- if (abort()) {
3860
- abandoned = true;
3861
- settled.reject(signal.reason);
3862
- }
3863
- };
3864
- signal.addEventListener("abort", onAbort, { once: true });
3865
- let running;
3866
- try {
3867
- running = start();
3868
- } catch (error) {
3869
- signal.removeEventListener("abort", onAbort);
3870
- settled.reject(error);
3871
- return settled.promise;
3872
- }
3873
- running.then((value) => {
3874
- signal.removeEventListener("abort", onAbort);
3875
- if (abandoned) discard?.(value);
3876
- else settled.resolve(value);
3877
- }, (error) => {
3878
- signal.removeEventListener("abort", onAbort);
3879
- settled.reject(error);
3880
- });
3881
- return settled.promise;
3882
- }
3883
- /**
3884
- * Acquires a connection for a test transaction, rejecting with the reason of `signal` when it aborts first.
3885
- *
3886
- * A connection acquired after the abort returns to the pool as best-effort cleanup: the test transaction has already rejected, so nothing awaits the release, and its failure is ignored.
3887
- */
3888
- function acquireUnlessAborted(driver, signal) {
3889
- if (signal.aborted) return Promise.reject(signal.reason);
3890
- return settleUnlessAborted(() => driver.acquire(), signal, () => true, (connection) => {
3891
- Promise.resolve().then(() => connection.release()).catch(() => {});
3892
- });
3893
- }
3894
- /** Returns the connection of a transaction to the driver, keeping a failed release as a rejection that suppresses `rejection`. */
3895
- async function releaseConnection(connection, failure, rejection) {
3896
- try {
3897
- await connection.release(failure);
3898
- return rejection;
3899
- } catch (error) {
3900
- return suppress(error, rejection, "Releasing the transaction connection failed");
3901
- }
3902
- }
3903
- /** Ends a transaction with `COMMIT` or `ROLLBACK`. */
3904
- async function endTransaction(connection, commit) {
3905
- try {
3906
- const { command } = await connection.execute(commit ? commitStatement : rollbackStatement);
3907
- if (commit && command !== "COMMIT") return { rejection: { error: /* @__PURE__ */ new Error("Transaction was rolled back: a statement in it failed") } };
3908
- return {};
3909
- } catch (error) {
3910
- return {
3911
- rejection: { error },
3912
- failure: { error }
3913
- };
3914
- }
3915
- }
3916
- /**
3917
- * Ends the savepoint of a nested level, releasing it on commit and rolling back to it otherwise.
3918
- *
3919
- * Before a release, it restores the settings that the level changed; a rollback restores them itself.
3920
- */
3921
- async function endSavepoint(level, commit) {
3922
- const name = getSavepointName(level);
3923
- try {
3924
- if (!commit) await level.connection.execute(createStatement(`ROLLBACK TO SAVEPOINT ${name}`));
3925
- else if (level.restore) await level.connection.execute(level.restore);
3926
- await level.connection.execute(createStatement(`RELEASE SAVEPOINT ${name}`));
3927
- return {};
3928
- } catch (error) {
3929
- return { rejection: { error } };
3930
- }
3931
- }
3932
- /** Rejection with the error of a cleanup, which suppresses the `earlier` rejection if there is one. */
3933
- function combineRejections(earlier, cleanup) {
3934
- return cleanup.rejection ? suppress(cleanup.rejection.error, earlier, "Transaction rollback failed") : earlier;
3935
- }
3936
- /** Rejection with `error`, which suppresses the `earlier` rejection if there is one. */
3937
- function suppress(error, earlier, message) {
3938
- return { error: earlier ? new SuppressedError(error, earlier.error, message) : error };
3939
- }
3940
4665
  // src/execution/database.ts
3941
4666
  /** Creates a database over a driver; its transactions are shared by every schema bound to it. */
3942
4667
  function createDatabase({ driver, test }) {
@@ -3965,4 +4690,4 @@ function createDatabase({ driver, test }) {
3965
4690
  function createLockStatement(key) {
3966
4691
  return createStatement("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [key]);
3967
4692
  }
3968
- export { not as C, isColumnValues as S, combineNodes as T, NotFoundError as _, defineSchema as a, literal as b, requireDerived as c, orderBy as d, many as f, defineTable as g, matchColumn as h, sql as i, asc as l, createStatement as m, identifier as n, SelectQuery as o, one as p, param as r, from as s, createDatabase as t, desc as u, RequiredRelationError as v, or as w, and as x, ResultDecodeError as y };
4693
+ export { not as A, countType as C, literal as D, toAggregateType as E, combineNodes as M, and as O, countProjection as S, createCountCall as T, createTableFactory as _, defineSchema as a, RequiredRelationError as b, requireDerived as c, desc as d, orderBy as f, createStatement as g, one as h, sql as i, or as j, isColumnValues as k, addTerms as l, many as m, identifier as n, SelectQuery as o, matchColumn as p, param as r, from as s, createDatabase as t, asc as u, defineTable as v, createAggregateCall as w, ResultDecodeError as x, NotFoundError as y };