kern-orm 0.0.0-stage → 0.2.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,3422 @@
1
+ import { A as falseNode, C as equalityOperators, D as createList, E as defineGenericOperator, M as oneNode, N as trueNode, O as createNode, S as Column, T as isEqualityCompatible, _ as toNode, a as stringifyJson, b as defineType, c as textOperators, d as compareNodes, f as createIsNullNode, g as toExpression, h as toBooleanExpression, j as noFilters, k as createSelectNode, l as orderingOperators, m as isExpression, n as text, p as getType, s as encodeBytea, u as compare, v as toValueNode, x as isType } from "./text-4Xs09pIf.mjs";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ // src/ast/boolean.ts
4
+ /** Combines predicate nodes with `AND` or `OR`, flattening nested groups of the same kind. */
5
+ function combineNodes(kind, operands) {
6
+ const neutral = kind === "and";
7
+ const flat = [];
8
+ for (const operand of operands) if (operand.kind === "boolean") {
9
+ if (operand.value !== neutral) return operand;
10
+ } else if (operand.kind === kind) flat.push(...operand.operands);
11
+ else flat.push(operand);
12
+ if (flat.length === 0) return neutral ? trueNode : falseNode;
13
+ return flat.length === 1 ? flat[0] : createNode({
14
+ kind,
15
+ operands: flat
16
+ });
17
+ }
18
+ /** Negates a predicate node, simplifying constants and double negation. */
19
+ function negateNode(operand) {
20
+ if (operand.kind === "boolean") return operand.value ? falseNode : trueNode;
21
+ if (operand.kind === "not") return operand.operand;
22
+ return createNode({
23
+ kind: "not",
24
+ operand
25
+ });
26
+ }
27
+ /** Combines the filters of a query into its effective predicate, `relation AND scope AND user`, which is `TRUE` when they restrict no row. */
28
+ function combineFilters(filters) {
29
+ const operands = [];
30
+ if (filters.relation !== void 0) operands.push(filters.relation);
31
+ if (filters.scope !== void 0) operands.push(filters.scope);
32
+ if (filters.user !== void 0) operands.push(filters.user);
33
+ return combineNodes("and", operands);
34
+ }
35
+ // src/expression/predicates.ts
36
+ /** Converts a condition operand into a node; an object of column values stays unresolved until `where`. */
37
+ function toConditionNode(operand) {
38
+ return isExpression(operand) ? toNode(operand) : createNode({
39
+ kind: "values",
40
+ values: operand
41
+ });
42
+ }
43
+ function and(...operands) {
44
+ return combineConditions("and", operands);
45
+ }
46
+ function or(...operands) {
47
+ return combineConditions("or", operands);
48
+ }
49
+ function not(operand) {
50
+ return toBooleanExpression(negateNode(toConditionNode(operand)));
51
+ }
52
+ function combineConditions(kind, operands) {
53
+ const nodes = [];
54
+ for (const operand of operands) nodes.push(toConditionNode(operand));
55
+ return toBooleanExpression(combineNodes(kind, nodes));
56
+ }
57
+ // src/result/result.ts
58
+ /** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
59
+ var NotFoundError = class extends Error {
60
+ name = "NotFoundError";
61
+ /** Path of the missing nested rows from the result field that holds them, such as `user` or `fields[2].form`, after the index of the row of an executed query of rows `many`, such as `[2].form`; `undefined` when the executed query itself finds no row. */
62
+ path;
63
+ constructor(message, path) {
64
+ super(message);
65
+ this.path = path;
66
+ }
67
+ };
68
+ /**
69
+ * Error thrown when a required relation, such as `field.form`, has no record for a row.
70
+ *
71
+ * A required relation promises the record, so its absence means that the database breaks the promise, such as without a foreign key, or that the relation should not be required.
72
+ */
73
+ var RequiredRelationError = class extends Error {
74
+ relation;
75
+ path;
76
+ name = "RequiredRelationError";
77
+ constructor(relation, path) {
78
+ super(`Required relation "${relation}" has no record for result field "${path}"`);
79
+ this.relation = relation;
80
+ this.path = path;
81
+ }
82
+ };
83
+ /** 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. */
84
+ var ResultDecodeError = class extends Error {
85
+ path;
86
+ name = "ResultDecodeError";
87
+ constructor(message, path, options) {
88
+ super(message, options);
89
+ this.path = path;
90
+ }
91
+ };
92
+ /** Tells whether `key` can be a key of a decoded record, such as a column key: assigning `__proto__` would change the prototype of the record instead. */
93
+ function isRecordKey(key) {
94
+ return key !== "__proto__";
95
+ }
96
+ /**
97
+ * Decodes the result of a statement by its plan: its rows, as `decodeResult` does, or the number of the rows of its command tag, such as of the rows that a mutation changes.
98
+ *
99
+ * 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.
100
+ */
101
+ function decodeStatement(plan, result) {
102
+ const { counted } = plan;
103
+ if (counted === void 0) return decodeResult(plan, plan.named ? selectColumns(plan, result) : result.rows);
104
+ const { count } = result;
105
+ if (plan.rows !== "many") {
106
+ if (count > 1) throw new Error(plan.named ? `Query of one row reported ${count} rows` : `Query of one row changed ${count} rows`);
107
+ if (count === 0) {
108
+ if (plan.rows === "one") throw new NotFoundError(plan.named ? "Query reported no rows" : "Query found no row to change");
109
+ if (counted === "records") return decodeMissing(plan);
110
+ }
111
+ }
112
+ if (counted === "number") return count;
113
+ if (plan.rows !== "many") return {};
114
+ const records = [];
115
+ for (let index = 0; index < count; index++) records.push({});
116
+ return records;
117
+ }
118
+ /**
119
+ * Returns the rows of `result` with the values of the fields of `plan` in their order, read from the result columns of their keys: a value from the only column.
120
+ *
121
+ * It rejects a missing column or one that the result has twice, and other columns than one for a value; it ignores the other columns of records.
122
+ */
123
+ function selectColumns(plan, result) {
124
+ const { columns, rows } = result;
125
+ if (plan.value) {
126
+ if (columns.length !== 1) throw new ResultDecodeError(`Statement returned ${columns.length} columns for one value`, void 0);
127
+ return rows;
128
+ }
129
+ const { fields } = plan;
130
+ const indexes = [];
131
+ let ordered = fields.length === columns.length;
132
+ for (let index = 0; index < fields.length; index++) {
133
+ const { key } = fields[index];
134
+ const column = columns.indexOf(key);
135
+ if (column === -1) throw new ResultDecodeError(`Statement returned no column "${key}"`, void 0);
136
+ if (columns.indexOf(key, column + 1) !== -1) throw new ResultDecodeError(`Statement returned column "${key}" more than once`, void 0);
137
+ indexes.push(column);
138
+ ordered &&= column === index;
139
+ }
140
+ if (ordered) return rows;
141
+ const selected = [];
142
+ for (let row = 0; row < rows.length; row++) {
143
+ const values = [];
144
+ for (let index = 0; index < indexes.length; index++) values.push(rows[row][indexes[index]]);
145
+ selected.push(values);
146
+ }
147
+ return selected;
148
+ }
149
+ /**
150
+ * Decodes driver rows into the result of a query by its result plan.
151
+ *
152
+ * 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`.
153
+ */
154
+ function decodeResult(plan, rows) {
155
+ if (plan.rows === "many") {
156
+ const results = [];
157
+ let index = 0;
158
+ try {
159
+ for (; index < rows.length; index++) results.push(decodeRow(plan, rows[index], false));
160
+ } catch (error) {
161
+ throw createRowError(`[${index}].`, error);
162
+ }
163
+ return results;
164
+ }
165
+ if (rows.length > 1) throw new Error(`Query of one row returned ${rows.length} rows`);
166
+ const row = rows[0];
167
+ if (row === void 0) {
168
+ if (plan.rows === "one") throw new NotFoundError("Query returned no rows");
169
+ return decodeMissing(plan);
170
+ }
171
+ try {
172
+ return decodeRow(plan, row, false);
173
+ } catch (error) {
174
+ throw createRowError("", error);
175
+ }
176
+ }
177
+ /** Returns the result of a query of rows `nullable` or `optional` without a row: `null` or `undefined`. */
178
+ function decodeMissing(plan) {
179
+ return plan.rows === "nullable" ? null : void 0;
180
+ }
181
+ /** Missing row of nested rows `one`, which the query turns into its error once the path is known. */
182
+ var MissingRow = class extends Error {
183
+ guaranteedBy;
184
+ constructor(guaranteedBy) {
185
+ super();
186
+ this.guaranteedBy = guaranteedBy;
187
+ }
188
+ };
189
+ /**
190
+ * Failure inside a row, with the path to it, such as `[2].label` from the field of nested rows or `fields[2].label` from a row of the driver: a missing row or a value that fails to decode.
191
+ *
192
+ * Every enclosing level adds its own part of the path, and the query turns it into its error.
193
+ */
194
+ var NestedFailure = class extends Error {
195
+ path;
196
+ cause;
197
+ constructor(path, cause) {
198
+ super();
199
+ this.path = path;
200
+ this.cause = cause;
201
+ }
202
+ };
203
+ /** Adds `segment` before the path of a failure inside a row. */
204
+ function prefixPath(segment, error) {
205
+ return error instanceof NestedFailure ? new NestedFailure(segment + error.path, error.cause) : new NestedFailure(segment, error);
206
+ }
207
+ /**
208
+ * Creates the error of a query from the failure of a row of the driver, adding `prefix`, such as the index of the row, before its path: `NotFoundError` or `RequiredRelationError` for a missing row of nested rows, and `ResultDecodeError` for a value that fails to decode.
209
+ *
210
+ * A missing row keeps its class wherever it is nested, so it is never reported as a decoding failure.
211
+ * A row of another width than the result fields is already the error of the query.
212
+ */
213
+ function createRowError(prefix, error) {
214
+ if (!(error instanceof NestedFailure)) return error;
215
+ const path = prefix + error.path;
216
+ const { cause } = error;
217
+ 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);
218
+ return new ResultDecodeError(`Cannot decode result field "${path}"${cause instanceof Error ? `: ${cause.message}` : ""}`, path, { cause });
219
+ }
220
+ /**
221
+ * Decodes a row into a record keyed by the result fields, or into the value of its only field.
222
+ *
223
+ * A row of the driver holds text and `null`; a packed row of nested rows holds parsed JSON.
224
+ */
225
+ function decodeRow(plan, row, packed) {
226
+ const { fields } = plan;
227
+ if (row.length !== fields.length) {
228
+ if (packed) throw new Error(`Nested row of ${row.length} values for ${fields.length} result fields`);
229
+ throw new ResultDecodeError(`Driver returned a row of ${row.length} values for ${fields.length} result fields`, void 0);
230
+ }
231
+ let index = 0;
232
+ try {
233
+ if (plan.value) return packed ? decodePackedValue(fields[0], row[0]) : decodeDriverValue(fields[0], row[0]);
234
+ const record = {};
235
+ for (; index < fields.length; index++) {
236
+ const field = fields[index];
237
+ record[field.key] = packed ? decodePackedValue(field, row[index]) : decodeDriverValue(field, row[index]);
238
+ }
239
+ return record;
240
+ } catch (error) {
241
+ const { key } = fields[index];
242
+ throw prefixPath(packed ? `.${key}` : key, error);
243
+ }
244
+ }
245
+ /** Decodes the value of a field in a row of the driver: a scalar from its text, keeping `NULL` as `null`, or nested rows from JSON text. */
246
+ function decodeDriverValue(field, value) {
247
+ if (value === void 0) throw new Error("Driver returned no value");
248
+ if (field.nested !== void 0) return decodeNested(field.nested, value === null ? null : JSON.parse(value));
249
+ return value === null ? null : field.type.decode(value);
250
+ }
251
+ /** Decodes the value of a field in a packed row: a scalar from its text, keeping JSON `null` as `null`, or nested rows from parsed JSON. */
252
+ function decodePackedValue(field, value) {
253
+ if (field.nested !== void 0) return decodeNested(field.nested, value);
254
+ if (value === null) return null;
255
+ if (typeof value !== "string") throw new TypeError(`Nested value must be text, not ${describeJson(value)}`);
256
+ return field.type.decode(value);
257
+ }
258
+ /** Decodes the rows of a nested query from JSON: an array of packed rows for rows `many`, and a packed row or `null` otherwise. */
259
+ function decodeNested(plan, json) {
260
+ if (plan.rows === "many") {
261
+ if (!Array.isArray(json)) throw new TypeError(`Nested rows must be an array, not ${describeJson(json)}`);
262
+ const results = [];
263
+ let index = 0;
264
+ try {
265
+ for (; index < json.length; index++) results.push(decodePackedRow(plan, json[index]));
266
+ } catch (error) {
267
+ throw prefixPath(`[${index}]`, error);
268
+ }
269
+ return results;
270
+ }
271
+ if (json === null) {
272
+ if (plan.rows === "one") throw new MissingRow(plan.guaranteedBy);
273
+ return decodeMissing(plan);
274
+ }
275
+ return decodePackedRow(plan, json);
276
+ }
277
+ /** Decodes a packed row, which must be an array. */
278
+ function decodePackedRow(plan, json) {
279
+ if (!Array.isArray(json)) throw new TypeError(`Nested row must be an array, not ${describeJson(json)}`);
280
+ return decodeRow(plan, json, true);
281
+ }
282
+ /** Describes the kind of a parsed JSON value for an error message. */
283
+ function describeJson(value) {
284
+ if (value === null) return "null";
285
+ if (typeof value === "object") return Array.isArray(value) ? "an array" : "an object";
286
+ return `a ${typeof value}`;
287
+ }
288
+ // src/table/table.ts
289
+ function defineTable(name, definitions, options) {
290
+ const columns = {};
291
+ for (const [key, definition] of Object.entries(definitions)) {
292
+ if (key.startsWith("$")) throw new Error(`Column key "${key}" of table "${name}" must not start with "$"`);
293
+ if (!isRecordKey(key)) throw new Error(`Column key "__proto__" of table "${name}" is not allowed; use columnName("__proto__")`);
294
+ const column = toColumn(definition);
295
+ if (!column) throw new TypeError(`Column "${key}" of table "${name}" must be a type or a column`);
296
+ columns[key] = column;
297
+ }
298
+ return Object.freeze({
299
+ kind: "table",
300
+ name,
301
+ columns: Object.freeze(columns),
302
+ keys: defineKeys(name, columns, options)
303
+ });
304
+ }
305
+ /**
306
+ * Defines the keys of table `name` of `columns` from the keys marked on the columns and those of `options`.
307
+ *
308
+ * The unique keys are those of the columns in their order, followed by those of the options.
309
+ * It rejects a primary key declared twice, a key of the options with fewer than two columns, an unknown column or a column listed twice in such a key, a nullable column of the primary key, and two keys of the same columns.
310
+ */
311
+ function defineKeys(name, columns, options) {
312
+ let primaryKey;
313
+ const unique = [];
314
+ for (const key of Object.keys(columns)) {
315
+ const keyKind = columns[key].attributes.keyKind;
316
+ if (keyKind === "primaryKey") {
317
+ if (primaryKey !== void 0) throw new Error(`Table "${name}" marks columns "${primaryKey[0]}" and "${key}" with primaryKey(); list the columns of a primary key of several columns in the options`);
318
+ primaryKey = Object.freeze([key]);
319
+ } else if (keyKind === "unique") unique.push(Object.freeze([key]));
320
+ }
321
+ if (options?.primaryKey !== void 0) {
322
+ if (primaryKey !== void 0) throw new Error(`Table "${name}" declares its primary key both on column "${primaryKey[0]}" and in the options`);
323
+ primaryKey = toKeyColumns(name, columns, options.primaryKey);
324
+ }
325
+ if (options?.unique !== void 0) {
326
+ if (!Array.isArray(options.unique)) throw new TypeError(`Unique keys in the options of table "${name}" must be an array`);
327
+ for (const key of options.unique) unique.push(toKeyColumns(name, columns, key));
328
+ }
329
+ for (const key of primaryKey ?? []) if (columns[key].type.isNullable) throw new Error(`Primary key column "${key}" of table "${name}" must not be nullable`);
330
+ const keys = primaryKey === void 0 ? unique : [primaryKey, ...unique];
331
+ for (let index = 1; index < keys.length; index++) for (let other = 0; other < index; other++) if (hasSameColumns(keys[index], keys[other])) throw new Error(`Table "${name}" declares the key of columns ${keys[index].map((key) => `"${key}"`).join(", ")} twice`);
332
+ return Object.freeze({
333
+ primaryKey,
334
+ unique: Object.freeze(unique)
335
+ });
336
+ }
337
+ /** Returns the column keys of a key of several columns from the options of table `name`, frozen, rejecting what `defineKeys` rejects in such a key. */
338
+ function toKeyColumns(name, columns, key) {
339
+ if (!Array.isArray(key) || key.length < 2) throw new Error(`A key in the options of table "${name}" must list at least two columns; mark a key of one column with primaryKey() or unique()`);
340
+ for (let index = 0; index < key.length; index++) {
341
+ const column = key[index];
342
+ if (typeof column !== "string" || !Object.hasOwn(columns, column)) throw new Error(`A key in the options of table "${name}" lists unknown column "${column}"`);
343
+ if (key.indexOf(column) !== index) throw new Error(`A key in the options of table "${name}" lists column "${column}" twice`);
344
+ }
345
+ return Object.freeze(key.slice());
346
+ }
347
+ /** Tells whether keys `key` and `other` have the same columns, in any order; neither lists a column twice. */
348
+ function hasSameColumns(key, other) {
349
+ return key.length === other.length && key.every((column) => other.includes(column));
350
+ }
351
+ /** Finds the column of `table` under `key`, ignoring properties inherited from the object prototype, such as `toString`. */
352
+ function findColumn(table, key) {
353
+ return Object.hasOwn(table.columns, key) ? table.columns[key] : void 0;
354
+ }
355
+ /** Tells whether the columns of `table` under `columns` are exactly a key of it, primary or unique, in any order, as `IsKey` does in types. */
356
+ function isKey(table, columns) {
357
+ const listed = new Set(columns);
358
+ return someKey(table, (key) => key.length === listed.size && isKeyAmong(key, listed));
359
+ }
360
+ /** Tells whether the columns of `table` under `columns` include a key of it, primary or unique, as `ContainsKey` does in types. */
361
+ function containsKey(table, columns) {
362
+ const listed = new Set(columns);
363
+ return someKey(table, (key) => isKeyAmong(key, listed));
364
+ }
365
+ /** Tells whether `predicate` holds for a key of `table`, primary or unique. */
366
+ function someKey(table, predicate) {
367
+ const { primaryKey, unique } = table.keys;
368
+ return primaryKey !== void 0 && predicate(primaryKey) || unique.some(predicate);
369
+ }
370
+ /** Tells whether every column of `key` is in `columns`. */
371
+ function isKeyAmong(key, columns) {
372
+ return key.every((column) => columns.has(column));
373
+ }
374
+ /** Returns the column of `table` under `key` as `findColumn` finds it, rejecting a key that is not a column. */
375
+ function requireColumn(table, key) {
376
+ const column = findColumn(table, key);
377
+ if (!column) throw new Error(`Unknown column "${key}" of table "${table.name}"`);
378
+ return column;
379
+ }
380
+ /** Creates a column from a column definition, or returns `undefined` for a value that is neither a type nor a column. */
381
+ function toColumn(definition) {
382
+ if (definition instanceof Column) return definition;
383
+ return isType(definition) ? new Column(definition, {
384
+ name: void 0,
385
+ keyKind: void 0,
386
+ hasDefault: false
387
+ }) : void 0;
388
+ }
389
+ // src/type/untyped.ts
390
+ /** Encodes a parameter without a type, such as a value interpolated into `sql`, by its JavaScript type. */
391
+ function encodeUntyped(value) {
392
+ if (typeof value === "string") return value;
393
+ if (typeof value === "number" || typeof value === "bigint") return String(value);
394
+ if (typeof value === "boolean") return value ? "t" : "f";
395
+ if (value instanceof Date) return value.toISOString();
396
+ if (value instanceof Uint8Array) return encodeBytea(value);
397
+ if (Array.isArray(value)) throw new TypeError("Pass an array with param(type, value), so that its elements are encoded by type");
398
+ return stringifyJson(value);
399
+ }
400
+ // src/compiler/postgres/identifier.ts
401
+ /** Most bytes a character other than ASCII takes in a server encoding, such as UTF-8 and EUC_TW ([PostgreSQL](https://www.postgresql.org/docs/current/multibyte.html)). */
402
+ const maxCharacterBytes = 4;
403
+ function quoteIdentifier(name) {
404
+ return `"${name.replaceAll("\"", "\"\"")}"`;
405
+ }
406
+ /**
407
+ * Returns the longest prefix of `name` that takes at most `maxBytes` bytes in any server encoding.
408
+ *
409
+ * Every server encoding takes one byte for an ASCII character, and a character other than ASCII counts as the most bytes it can take.
410
+ */
411
+ function cutIdentifier(name, maxBytes) {
412
+ if (name.length * maxCharacterBytes <= maxBytes) return name;
413
+ let bytes = 0;
414
+ for (let index = 0; index < name.length;) {
415
+ const code = name.codePointAt(index);
416
+ bytes += code < 128 ? 1 : maxCharacterBytes;
417
+ if (bytes > maxBytes) return name.slice(0, index);
418
+ index += code < 65536 ? 1 : 2;
419
+ }
420
+ return name;
421
+ }
422
+ /**
423
+ * Returns the SQL name of the projection with `key` at `index` of its query.
424
+ *
425
+ * A key of up to 50 bytes is the name itself.
426
+ * A longer key is named by its prefix of at most 54 bytes, which takes more than 50 since a character takes at most 4, and by its position, so the name differs from the names of the other projections.
427
+ */
428
+ function nameProjection(key, index) {
429
+ if (cutIdentifier(key, 50).length === key.length) return key;
430
+ return `${cutIdentifier(key, 54)}_${index + 1}`;
431
+ }
432
+ // src/compiler/postgres/context.ts
433
+ /** Most parameters that PostgreSQL takes in a statement. */
434
+ const maxParameters = 65535;
435
+ /** State of one compilation shared by all queries of the statement, never by reusable nodes: parameters and the aliases of all sources. */
436
+ var CompileContext = class {
437
+ schemaName;
438
+ tables;
439
+ db;
440
+ parameters = [];
441
+ #aliases = /* @__PURE__ */ new Set();
442
+ constructor(schemaName, tables = void 0, db = void 0) {
443
+ this.schemaName = schemaName;
444
+ this.tables = tables;
445
+ this.db = db;
446
+ }
447
+ /**
448
+ * Creates an alias based on `name` that is unique in the statement, so that no source shadows another one in SQL.
449
+ *
450
+ * The name is cut to 50 bytes and numbered when the statement already has it, so an alias fits an identifier and PostgreSQL compares aliases as created rather than truncated.
451
+ */
452
+ createAlias(name) {
453
+ const base = cutIdentifier(name.toWellFormed(), 50);
454
+ let alias = base;
455
+ for (let index = 2; this.#aliases.has(alias); index++) alias = `${base}_${index}`;
456
+ this.#aliases.add(alias);
457
+ return alias;
458
+ }
459
+ /** Adds a parameter of the statement and returns its placeholder, rejecting more parameters than PostgreSQL takes. */
460
+ bind(value) {
461
+ if (this.parameters.length === 65535) throw new Error(`Statement has more than ${maxParameters} parameters, which PostgreSQL does not take; split it into several statements, such as in a transaction`);
462
+ this.parameters.push(value);
463
+ return `$${this.parameters.length}`;
464
+ }
465
+ };
466
+ // src/compiler/postgres/parentheses.ts
467
+ /** Tells whether an operand of `kind` needs parentheses at `position`, so that the SQL keeps the structure of the tree. */
468
+ function needsParentheses(kind, position) {
469
+ switch (kind) {
470
+ case "column":
471
+ case "param":
472
+ case "boolean":
473
+ case "values":
474
+ case "tableName":
475
+ case "subquery":
476
+ case "exists":
477
+ case "aggregate": return false;
478
+ case "cast": return position === "interpolation";
479
+ case "raw": return position !== "interpolation";
480
+ case "and":
481
+ case "or": return true;
482
+ case "not":
483
+ case "comparison":
484
+ case "in":
485
+ case "isNull": return position !== "condition";
486
+ default: return kind;
487
+ }
488
+ }
489
+ // src/compiler/postgres/scope.ts
490
+ /**
491
+ * Declares a source of `FROM` on top of `outer` with a new alias.
492
+ *
493
+ * It rejects a source already visible there, such as a query nested in itself: a column reference could not tell its occurrences apart.
494
+ */
495
+ function declareSource(context, outer, source) {
496
+ if (findSource(outer, source) !== void 0 || source.kind === "derived" && source.replaces !== void 0 && findSource(outer, source.replaces) !== void 0) throw new Error(`An occurrence of ${describeSource(source)} appears where it is already visible, so its column references would be ambiguous`);
497
+ const name = source.kind === "table" ? source.table.name : source.replaces?.table.name ?? "subquery";
498
+ return {
499
+ source,
500
+ alias: context.createAlias(name),
501
+ outer
502
+ };
503
+ }
504
+ /**
505
+ * Returns the declared source that a column reference reads in `scope`: its source, or a derived source that replaces it; rejects a source that is not visible there.
506
+ */
507
+ function resolveSource(scope, column) {
508
+ const declared = findSource(scope, column.source);
509
+ if (declared === void 0) throw new Error(`Column "${column.key}" of ${describeSource(column.source)} refers to a source that is not visible where it is used`);
510
+ return declared;
511
+ }
512
+ /** Returns the declared source of `scope` that is `source` or replaces it, or `undefined` when the source is not visible there. */
513
+ function findSource(scope, source) {
514
+ for (let current = scope; current; current = current.outer) {
515
+ const declared = current.source;
516
+ if (declared === source || declared.kind === "derived" && declared.replaces === source) return current;
517
+ }
518
+ }
519
+ function describeSource(source) {
520
+ return source.kind === "table" ? `table "${source.table.name}"` : "a subquery";
521
+ }
522
+ // src/compiler/postgres/compile.ts
523
+ const noFields = /* @__PURE__ */ Object.freeze([]);
524
+ /**
525
+ * Compiles a statement for PostgreSQL: a select statement, a mutation, or a statement of SQL text.
526
+ *
527
+ * With `tables`, such as the tables of the schema of a `Db`, an occurrence or an interpolated name of any other table at any depth of the statement is rejected.
528
+ * `db` is the `Db` that runs the statement: a table interpolated from a query bound to another `Db`, or to any `Db` without it, is rejected.
529
+ */
530
+ function compileStatement(node, options = {}, tables, db) {
531
+ const context = new CompileContext(options.schemaName, tables, db);
532
+ switch (node.kind) {
533
+ case "select": return {
534
+ text: compileQuery(context, void 0, node),
535
+ parameters: context.parameters,
536
+ fields: node.projections,
537
+ rows: node.rows,
538
+ value: node.value,
539
+ counted: void 0,
540
+ named: false
541
+ };
542
+ case "text": {
543
+ const { fields } = node;
544
+ return {
545
+ text: compileExpression(context, void 0, node.sql),
546
+ parameters: context.parameters,
547
+ fields: fields ?? noFields,
548
+ rows: node.rows,
549
+ value: node.value,
550
+ counted: fields === void 0 ? "number" : void 0,
551
+ named: true
552
+ };
553
+ }
554
+ default: {
555
+ const { returning } = node;
556
+ return {
557
+ text: compileMutation(context, node),
558
+ parameters: context.parameters,
559
+ fields: returning ?? noFields,
560
+ rows: node.rows,
561
+ value: node.value,
562
+ counted: returning === void 0 ? "number" : returning.length === 0 ? "records" : void 0,
563
+ named: false
564
+ };
565
+ }
566
+ }
567
+ }
568
+ /** Compiles a mutation, whose expressions see only the occurrence of its table, apart from the values of an insert, which see no source. */
569
+ function compileMutation(context, node) {
570
+ const scope = declareSource(context, void 0, node.target);
571
+ const target = compileSource(context, void 0, scope);
572
+ let text;
573
+ switch (node.kind) {
574
+ case "insert":
575
+ text = `INSERT INTO ${target}${compileValues(context, node)}`;
576
+ break;
577
+ case "update": {
578
+ text = `UPDATE ${target} SET`;
579
+ const { set } = node;
580
+ for (let index = 0; index < set.length; index++) {
581
+ const { key, value } = set[index];
582
+ text += `${index === 0 ? " " : ", "}${compileColumnName(node.target, key)} = ${compileExpression(context, scope, value)}`;
583
+ }
584
+ text += compileWhere(context, scope, node.filters);
585
+ break;
586
+ }
587
+ case "delete":
588
+ text = `DELETE FROM ${target}${compileWhere(context, scope, node.filters)}`;
589
+ break;
590
+ default: return node;
591
+ }
592
+ const { returning } = node;
593
+ if (returning !== void 0 && returning.length > 0) text += ` RETURNING${compileProjections(context, scope, returning)}`;
594
+ return text;
595
+ }
596
+ /** Compiles the columns and the rows of `VALUES` of an insert, or `DEFAULT VALUES` for one row of the defaults of every column. */
597
+ function compileValues(context, node) {
598
+ const { columns, values } = node;
599
+ if (columns.length === 0) {
600
+ if (values.length !== 1) throw new Error("An insert of several rows must list a column");
601
+ return " DEFAULT VALUES";
602
+ }
603
+ let text = " (";
604
+ for (let index = 0; index < columns.length; index++) text += `${index === 0 ? "" : ", "}${compileColumnName(node.target, columns[index])}`;
605
+ text += ") VALUES";
606
+ for (let row = 0; row < values.length; row++) {
607
+ const items = values[row];
608
+ text += row === 0 ? " (" : ", (";
609
+ for (let index = 0; index < items.length; index++) {
610
+ const item = items[index];
611
+ text += `${index === 0 ? "" : ", "}${item === void 0 ? "DEFAULT" : compileExpression(context, void 0, item)}`;
612
+ }
613
+ text += ")";
614
+ }
615
+ return text;
616
+ }
617
+ /** Compiles the physical name of the column of the table of `target` under `key`, as `SET` and the column list of an insert name it, without an alias. */
618
+ function compileColumnName(target, key) {
619
+ return quoteIdentifier(requireColumn(target.table, key).attributes.name ?? key);
620
+ }
621
+ /** Compiles a query at a position of the statement where the sources of `outer` are visible. */
622
+ function compileQuery(context, outer, node) {
623
+ const { from } = node;
624
+ if (from === void 0 && node.joins.length > 0) throw new Error("A query without FROM cannot join sources");
625
+ const fromScope = from === void 0 ? void 0 : declareSource(context, outer, from);
626
+ let scope = fromScope ?? outer;
627
+ const joinScopes = [];
628
+ for (const join of node.joins) {
629
+ scope = declareSource(context, scope, join.source);
630
+ joinScopes.push(scope);
631
+ }
632
+ let text = `SELECT${compileProjections(context, scope, node.projections)}`;
633
+ if (fromScope !== void 0) {
634
+ text += ` FROM ${compileSource(context, outer, fromScope)}`;
635
+ for (let index = 0; index < node.joins.length; index++) {
636
+ const joinScope = joinScopes[index];
637
+ text += ` LEFT JOIN ${compileSource(context, outer, joinScope)} ON ${compileExpression(context, joinScope, node.joins[index].on)}`;
638
+ }
639
+ }
640
+ text += compileWhere(context, scope, node.filters);
641
+ if (node.orderBy.length > 0) text += ` ${compileOrderBy(context, scope, node.orderBy)}`;
642
+ if (node.limit) text += ` LIMIT ${compileExpression(context, outer, node.limit)}`;
643
+ if (node.offset) text += ` OFFSET ${compileExpression(context, outer, node.offset)}`;
644
+ return text;
645
+ }
646
+ /** Compiles the projections of a select list or of `RETURNING`, each after a space or a comma. */
647
+ function compileProjections(context, scope, projections) {
648
+ let text = "";
649
+ for (let index = 0; index < projections.length; index++) {
650
+ const projection = projections[index];
651
+ text += `${index === 0 ? " " : ", "}${compileExpression(context, scope, projection.expression)} AS ${quoteIdentifier(nameProjection(projection.key, index))}`;
652
+ }
653
+ return text;
654
+ }
655
+ /** Compiles the `WHERE` clause of the effective predicate of `filters` after a space, or nothing when they restrict no row. */
656
+ function compileWhere(context, scope, filters) {
657
+ const where = combineFilters(filters);
658
+ return where.kind === "boolean" && where.value ? "" : ` WHERE ${compileExpression(context, scope, where)}`;
659
+ }
660
+ /** Compiles the `ORDER BY` clause of a query or an aggregate, which has at least one sort key. */
661
+ function compileOrderBy(context, scope, orderBy) {
662
+ let text = "ORDER BY";
663
+ for (let index = 0; index < orderBy.length; index++) {
664
+ const order = orderBy[index];
665
+ text += `${index === 0 ? " " : ", "}${compileExpression(context, scope, order.expression)}`;
666
+ if (order.direction === "desc") text += " DESC";
667
+ if (order.nulls !== void 0) text += order.nulls === "first" ? " NULLS FIRST" : " NULLS LAST";
668
+ }
669
+ return text;
670
+ }
671
+ /** Compiles a declared source of a query at a position of the statement where the sources of `outer` are visible. */
672
+ function compileSource(context, outer, declared) {
673
+ const { source, alias } = declared;
674
+ if (source.kind === "table") return `${compileTableName(context, source.table)} AS ${quoteIdentifier(alias)}`;
675
+ const query = compileQuery(context, source.lateral ? declared.outer : outer, source.query);
676
+ return `${source.lateral ? "LATERAL " : ""}(${query}) AS ${quoteIdentifier(alias)}`;
677
+ }
678
+ /** Compiles the name of `table`, qualified by the PostgreSQL schema of the statement, rejecting a table outside the tables of the statement. */
679
+ function compileTableName(context, table) {
680
+ if (context.tables !== void 0 && !context.tables.has(table)) throw new Error(`Table "${table.name}" is not part of the schema`);
681
+ return context.schemaName === void 0 ? quoteIdentifier(table.name) : `${quoteIdentifier(context.schemaName)}.${quoteIdentifier(table.name)}`;
682
+ }
683
+ /** Compiles the name of a table interpolated into a SQL fragment, rejecting a table of a query bound to a `Db` other than the one that runs the statement. */
684
+ function compileInterpolatedTable(context, node) {
685
+ const { db, table } = node;
686
+ if (db !== void 0 && db !== context.db) throw new Error(context.db === void 0 ? `Table "${table.name}" interpolated into SQL is bound to a Db, so only that Db can compile the query` : `Table "${table.name}" interpolated into SQL is bound to another Db`);
687
+ return compileTableName(context, table);
688
+ }
689
+ function compileColumn(scope, node) {
690
+ const { key } = node;
691
+ const declared = resolveSource(scope, node);
692
+ const { source } = declared;
693
+ let name;
694
+ if (source.kind === "table") name = requireColumn(source.table, key).attributes.name ?? key;
695
+ else {
696
+ const index = source.query.projections.findIndex((projection) => projection.key === key);
697
+ if (index === -1) throw new Error(`Unknown field "${key}" of a subquery`);
698
+ name = nameProjection(key, index);
699
+ }
700
+ return `${quoteIdentifier(declared.alias)}.${quoteIdentifier(name)}`;
701
+ }
702
+ function compileExpression(context, scope, node) {
703
+ switch (node.kind) {
704
+ case "column": return compileColumn(scope, node);
705
+ case "param": return context.bind(encodeParameter(node));
706
+ case "cast": return `${compileOperand(context, scope, node.operand, "value")}::${node.type.castType}`;
707
+ case "boolean": return node.value ? "TRUE" : "FALSE";
708
+ case "and":
709
+ case "or": return node.operands.map((operand) => compileOperand(context, scope, operand, "condition")).join(node.kind === "and" ? " AND " : " OR ");
710
+ case "not": return `NOT ${compileOperand(context, scope, node.operand, "condition")}`;
711
+ case "values": throw new Error("An object condition can only be used in `where`");
712
+ case "comparison": return `${compileOperand(context, scope, node.left, "value")} ${node.operator} ${compileOperand(context, scope, node.right, "value")}`;
713
+ case "in": {
714
+ let text = `${compileOperand(context, scope, node.operand, "value")} IN (${compileOperand(context, scope, node.list[0], "value")}`;
715
+ for (let index = 1; index < node.list.length; index++) text += `, ${compileOperand(context, scope, node.list[index], "value")}`;
716
+ return `${text})`;
717
+ }
718
+ case "isNull": return `${compileOperand(context, scope, node.operand, "value")} IS NULL`;
719
+ case "raw": {
720
+ let text = node.fragments[0];
721
+ for (let index = 0; index < node.values.length; index++) text += compileOperand(context, scope, node.values[index], "interpolation") + node.fragments[index + 1];
722
+ return text;
723
+ }
724
+ case "tableName": return compileInterpolatedTable(context, node);
725
+ case "subquery": {
726
+ const { length } = node.query.projections;
727
+ if (length !== 1) throw new Error(`A scalar subquery must select one field, not ${length}`);
728
+ return `(${compileQuery(context, scope, node.query)})`;
729
+ }
730
+ case "exists": return `EXISTS (${compileQuery(context, scope, node.query)})`;
731
+ case "aggregate": {
732
+ let text = `${node.name}(${node.distinct ? "DISTINCT " : ""}`;
733
+ for (let index = 0; index < node.arguments.length; index++) text += `${index === 0 ? "" : ", "}${compileExpression(context, scope, node.arguments[index])}`;
734
+ if (node.orderBy.length > 0) text += ` ${compileOrderBy(context, scope, node.orderBy)}`;
735
+ return `${text})`;
736
+ }
737
+ default: return node;
738
+ }
739
+ }
740
+ /** Encodes the value of a parameter node with its type, or by its JavaScript type without one. */
741
+ function encodeParameter(node) {
742
+ if (node.value === void 0) throw new TypeError("Query parameter is undefined; use null for NULL");
743
+ if (node.value === null) return null;
744
+ return node.type ? node.type.encode(node.value) : encodeUntyped(node.value);
745
+ }
746
+ /** Compiles an operand at `position` of its parent, parenthesizing it where its own operators could regroup with the parent. */
747
+ function compileOperand(context, scope, node, position) {
748
+ const sql = compileExpression(context, scope, node);
749
+ return needsParentheses(node.kind, position) ? `(${sql})` : sql;
750
+ }
751
+ // src/execution/driver.ts
752
+ /** Creates a statement from SQL text and the text representations of its parameters, such as `createStatement("BEGIN")`. */
753
+ function createStatement(text, parameters = []) {
754
+ return {
755
+ text,
756
+ parameters
757
+ };
758
+ }
759
+ // src/ast/references.ts
760
+ /** Adds to `keys` the key of each column reference to `source` in `node` at any depth, including the queries nested in it. */
761
+ function collectColumnKeys(node, source, keys) {
762
+ visitNodes(node, true, (child) => {
763
+ if (child.kind === "column" && child.source === source) keys.add(child.key);
764
+ });
765
+ }
766
+ /**
767
+ * Tells whether `node` holds, at any depth, a SQL fragment that refers to a column of `source` outside the queries nested in the fragment.
768
+ *
769
+ * 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)).
770
+ * 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`.
771
+ */
772
+ function holdsFragmentOfSource(node, source) {
773
+ let found = false;
774
+ visitNodes(node, true, (child) => {
775
+ if (found || child.kind !== "raw") return;
776
+ visitNodes(child, false, (value) => {
777
+ if (value.kind === "column" && value.source === source) found = true;
778
+ });
779
+ });
780
+ return found;
781
+ }
782
+ /** Calls `visit` for `node` and each expression node in it, also in the queries nested in it when `deep` is set. */
783
+ function visitNodes(node, deep, visit) {
784
+ visit(node);
785
+ switch (node.kind) {
786
+ case "column":
787
+ case "param":
788
+ case "boolean":
789
+ case "tableName":
790
+ case "values": return;
791
+ case "cast":
792
+ case "not":
793
+ case "isNull":
794
+ visitNodes(node.operand, deep, visit);
795
+ return;
796
+ case "and":
797
+ case "or":
798
+ for (const operand of node.operands) visitNodes(operand, deep, visit);
799
+ return;
800
+ case "comparison":
801
+ visitNodes(node.left, deep, visit);
802
+ visitNodes(node.right, deep, visit);
803
+ return;
804
+ case "in":
805
+ visitNodes(node.operand, deep, visit);
806
+ for (const item of node.list) visitNodes(item, deep, visit);
807
+ return;
808
+ case "raw":
809
+ for (const value of node.values) visitNodes(value, deep, visit);
810
+ return;
811
+ case "subquery":
812
+ case "exists":
813
+ if (deep) visitQuery(node.query, visit);
814
+ return;
815
+ case "aggregate":
816
+ for (const argument of node.arguments) visitNodes(argument, deep, visit);
817
+ for (const order of node.orderBy) visitNodes(order.expression, deep, visit);
818
+ return;
819
+ }
820
+ }
821
+ /** Calls `visit` for each expression node in the clauses and the derived sources of `query` at any depth. */
822
+ function visitQuery(query, visit) {
823
+ const { from, filters } = query;
824
+ if (from?.kind === "derived") visitQuery(from.query, visit);
825
+ for (const join of query.joins) {
826
+ if (join.source.kind === "derived") visitQuery(join.source.query, visit);
827
+ visitNodes(join.on, true, visit);
828
+ }
829
+ for (const projection of query.projections) visitNodes(projection.expression, true, visit);
830
+ if (filters.relation !== void 0) visitNodes(filters.relation, true, visit);
831
+ if (filters.scope !== void 0) visitNodes(filters.scope, true, visit);
832
+ if (filters.user !== void 0) visitNodes(filters.user, true, visit);
833
+ for (const order of query.orderBy) visitNodes(order.expression, true, visit);
834
+ if (query.limit !== void 0) visitNodes(query.limit, true, visit);
835
+ if (query.offset !== void 0) visitNodes(query.offset, true, visit);
836
+ }
837
+ // src/query/aggregate.ts
838
+ /** Type of a count: a `bigint` of PostgreSQL decoded as a number, rejecting a count that a number cannot hold exactly. */
839
+ const countType = /* @__PURE__ */ defineType({ sqlType: "bigint" }).transform({
840
+ decode: (text) => decodeSafeInteger(text, "Count"),
841
+ encode: (value) => String(value)
842
+ });
843
+ /** Types of the sums of the values of `smallint` and `integer` types, by the type of the values, created once for each. */
844
+ const sumTypes = /* @__PURE__ */ new WeakMap();
845
+ const noFallbacks = /* @__PURE__ */ Object.freeze([]);
846
+ /** Definitions of the aggregate methods that take a column or an expression. */
847
+ const aggregateDefinitions = /* @__PURE__ */ Object.freeze({
848
+ count: {
849
+ name: "count",
850
+ distinct: false,
851
+ ordered: false,
852
+ type: toCountType
853
+ },
854
+ countDistinct: {
855
+ name: "count",
856
+ distinct: true,
857
+ ordered: false,
858
+ type: toCountType
859
+ },
860
+ min: {
861
+ name: "min",
862
+ distinct: false,
863
+ ordered: false,
864
+ type: toArgumentType
865
+ },
866
+ max: {
867
+ name: "max",
868
+ distinct: false,
869
+ ordered: false,
870
+ type: toArgumentType
871
+ },
872
+ sum: {
873
+ name: "sum",
874
+ distinct: false,
875
+ ordered: false,
876
+ type: toSumType
877
+ },
878
+ avg: {
879
+ name: "avg",
880
+ distinct: false,
881
+ ordered: false,
882
+ type: toAverageType
883
+ },
884
+ every: {
885
+ name: "bool_and",
886
+ distinct: false,
887
+ ordered: false,
888
+ type: toArgumentType
889
+ },
890
+ some: {
891
+ name: "bool_or",
892
+ distinct: false,
893
+ ordered: false,
894
+ type: toArgumentType
895
+ },
896
+ stringAgg: {
897
+ name: "string_agg",
898
+ distinct: false,
899
+ ordered: true,
900
+ type: toArgumentType
901
+ }
902
+ });
903
+ /** Projection of `count(*)`, which `count` without an argument selects; its value does not depend on the values or the order of the rows. */
904
+ const countProjection = /* @__PURE__ */ Object.freeze({
905
+ key: "count",
906
+ expression: /* @__PURE__ */ createNode({
907
+ kind: "aggregate",
908
+ name: "count",
909
+ distinct: false,
910
+ arguments: [/* @__PURE__ */ createNode({
911
+ kind: "raw",
912
+ fragments: ["*"],
913
+ values: []
914
+ })],
915
+ orderBy: []
916
+ }),
917
+ type: countType,
918
+ ordered: false,
919
+ fallbacks: noFallbacks
920
+ });
921
+ /**
922
+ * Creates the projection of the aggregate of `method` over the values of `argument`, the projection of a column or an expression of each row.
923
+ *
924
+ * `delimiter` is the delimiter of `stringAgg`, sent as a parameter.
925
+ */
926
+ function projectAggregate(method, argument, delimiter) {
927
+ const definition = aggregateDefinitions[method];
928
+ const args = [argument.expression];
929
+ if (delimiter !== void 0) args.push(createNode({
930
+ kind: "param",
931
+ value: delimiter,
932
+ type: void 0
933
+ }));
934
+ return Object.freeze({
935
+ key: method,
936
+ expression: createNode({
937
+ kind: "aggregate",
938
+ name: definition.name,
939
+ distinct: definition.distinct,
940
+ arguments: args,
941
+ orderBy: []
942
+ }),
943
+ type: definition.type(argument.type),
944
+ ordered: definition.ordered,
945
+ fallbacks: noFallbacks
946
+ });
947
+ }
948
+ /** Creates the projection of the aggregate of `field` whose `NULL` `fallback` replaces after its earlier fallbacks. */
949
+ function addFallback(field, fallback) {
950
+ const fallbacks = field.fallbacks.slice();
951
+ fallbacks.push(fallback);
952
+ return Object.freeze({
953
+ key: field.key,
954
+ expression: field.expression,
955
+ type: field.type,
956
+ ordered: field.ordered,
957
+ fallbacks
958
+ });
959
+ }
960
+ /** Tells whether `node` is an aggregate query, whose value is the aggregate over the rows that its filters, limit, and offset choose. */
961
+ function isAggregateQuery(node) {
962
+ return node.value && isAggregateProjection(node.projections[0]);
963
+ }
964
+ /** Tells whether a selected field is the projection of an aggregate, which only the aggregate methods select. */
965
+ function isAggregateProjection(field) {
966
+ return "ordered" in field;
967
+ }
968
+ function toCountType() {
969
+ return countType;
970
+ }
971
+ function toArgumentType(argument) {
972
+ return argument;
973
+ }
974
+ /** Returns the type of the sum of the values of type `argument`: for `smallint` and `integer` values, `argument` that rejects a sum that a number cannot hold exactly, and `argument` for others. */
975
+ function toSumType(argument) {
976
+ if (argument.castType !== "smallint" && argument.castType !== "integer") return argument;
977
+ let type = sumTypes.get(argument);
978
+ if (type === void 0) {
979
+ type = defineType({ sqlType: "bigint" }).transform({
980
+ decode: (text) => {
981
+ decodeSafeInteger(text, "Sum");
982
+ return argument.decode(text);
983
+ },
984
+ encode: (value) => argument.encode(value)
985
+ });
986
+ sumTypes.set(argument, type);
987
+ }
988
+ return type;
989
+ }
990
+ /** Returns the type of the average of the values of type `argument`, which decodes a fractional value where PostgreSQL gives one, such as `Number` of `integer`; rejects a type of the SQL type `bigint`. */
991
+ function toAverageType(argument) {
992
+ if (argument.castType === "bigint") throw new TypeError("avg of bigint values requires a type that can represent fractional values; average a sql fragment of the column with t.doublePrecision or t.numeric");
993
+ return argument;
994
+ }
995
+ /** Decodes `text` of a `bigint` as a number, rejecting one that a number cannot hold exactly; `subject` names it in the error. */
996
+ function decodeSafeInteger(text, subject) {
997
+ const number = Number(text);
998
+ if (!Number.isSafeInteger(number)) throw new RangeError(`${subject} ${text} is outside the safe integer range of numbers`);
999
+ return number;
1000
+ }
1001
+ // src/query/rows.ts
1002
+ /** Returns the rows mode of a query of the records of `relation`, as `RelationRows` gives it in types. */
1003
+ function getRelationRows(relation) {
1004
+ if (relation.kind === "many") return "many";
1005
+ return relation.required ? "one" : "nullable";
1006
+ }
1007
+ /** 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. */
1008
+ function toFilteredRows(rows, value, guaranteed) {
1009
+ if (!guaranteed || rows !== "one") return rows;
1010
+ return value ? "optional" : "nullable";
1011
+ }
1012
+ /** 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. */
1013
+ function limitToOne(limit) {
1014
+ return limit?.kind === "param" && limit.value === 0 ? limit : oneNode;
1015
+ }
1016
+ /** Returns the rows mode after `pluck` of a query of rows mode `rows`, as `ValueRows` gives it in types. */
1017
+ function toValueRows(rows) {
1018
+ return rows === "nullable" ? "optional" : rows;
1019
+ }
1020
+ // src/query/node.ts
1021
+ /** Creates a query of all rows of `from`, or of the records of `relation` with `filters` in the rows mode of the relation. */
1022
+ function createQueryNode(from, relation, filters = noFilters) {
1023
+ return Object.freeze({
1024
+ kind: "query",
1025
+ from,
1026
+ relation,
1027
+ projections: [],
1028
+ filters,
1029
+ orderBy: [],
1030
+ limit: void 0,
1031
+ offset: void 0,
1032
+ rows: relation === void 0 ? "many" : getRelationRows(relation),
1033
+ value: false,
1034
+ guaranteed: relation?.required ?? false,
1035
+ all: false
1036
+ });
1037
+ }
1038
+ /** 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`. */
1039
+ function isTableQuery(node) {
1040
+ 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;
1041
+ }
1042
+ /** Tells whether a selected field is the rows of a nested query. */
1043
+ function isNestedSelection(node) {
1044
+ return "query" in node;
1045
+ }
1046
+ // src/schema/relation.ts
1047
+ /** Runtime mark of the declarations of `many` and `one`. */
1048
+ const declarationBrand = Symbol("kern-orm.relation");
1049
+ /** Returns the name of relation `name` of the table under key `key` in messages and errors, such as `field.form`. */
1050
+ function formatRelationName(key, name) {
1051
+ return `${key}.${name}`;
1052
+ }
1053
+ /**
1054
+ * Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1055
+ *
1056
+ * A composite key lists its columns in arrays of the same length.
1057
+ */
1058
+ function many(target, keys) {
1059
+ return declareRelation("many", target, keys, false);
1060
+ }
1061
+ /**
1062
+ * Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
1063
+ *
1064
+ * A composite key lists its columns in arrays of the same length.
1065
+ * The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
1066
+ * 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.
1067
+ * Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
1068
+ */
1069
+ function one(target, keys) {
1070
+ return declareRelation("one", target, keys, keys.required === true);
1071
+ }
1072
+ function declareRelation(kind, target, keys, required) {
1073
+ return Object.freeze({
1074
+ [declarationBrand]: true,
1075
+ kind,
1076
+ target,
1077
+ from: toKeyList(keys.from),
1078
+ to: toKeyList(keys.to),
1079
+ required
1080
+ });
1081
+ }
1082
+ function toKeyList(key) {
1083
+ return Object.freeze(Array.isArray(key) ? key.slice() : [key]);
1084
+ }
1085
+ /**
1086
+ * Defines relation `name` of table `source`, declared under its key `key` in a schema, checking its target and its keys.
1087
+ *
1088
+ * `findKey` returns the key of a table in the schema, or `undefined` for a table outside it.
1089
+ * Each pair of columns of the keys must satisfy `isEqualityCompatible`, the columns `to` of a relation `one` must include a key of the target, and the columns `from` of a required relation must not be nullable by `isNullable` of their types.
1090
+ */
1091
+ function defineRelation(source, key, name, declaration, findKey) {
1092
+ const subject = `Relation "${formatRelationName(key, name)}"`;
1093
+ if (!isRelationDeclaration(declaration)) throw new TypeError(`${subject} must be declared with many or one`);
1094
+ if (name.startsWith("$")) throw new Error(`${subject}: a relation name must not start with "$"`);
1095
+ if (findColumn(source, name)) throw new Error(`${subject}: a relation name must differ from the column keys of table "${source.name}"`);
1096
+ const { kind, target, from, to, required } = declaration;
1097
+ const targetKey = findKey(target);
1098
+ if (targetKey === void 0) throw new Error(`${subject} refers to table "${target.name}", which is not part of the schema`);
1099
+ if (from.length === 0 || from.length !== to.length) throw new Error(`${subject} must list as many columns in "to" as in "from", at least one`);
1100
+ for (let index = 0; index < from.length; index++) {
1101
+ const fromColumn = findColumn(source, from[index]);
1102
+ if (!fromColumn) throw new Error(`${subject}: unknown column "${from[index]}" of table "${source.name}"`);
1103
+ if (required && fromColumn.type.isNullable) throw new Error(`${subject} cannot be required: column "${from[index]}" of table "${source.name}" is nullable`);
1104
+ const toColumn = findColumn(target, to[index]);
1105
+ if (!toColumn) throw new Error(`${subject}: unknown column "${to[index]}" of table "${target.name}"`);
1106
+ if (!isEqualityCompatible(fromColumn.type, toColumn.type)) throw new Error(`${subject} cannot compare column "${from[index]}" (${fromColumn.type.sqlType}) with column "${to[index]}" (${toColumn.type.sqlType}) of table "${target.name}" by SQL =`);
1107
+ }
1108
+ if (kind === "one" && !containsKey(target, to)) throw new Error(`${subject}: columns "to" must include a key of table "${target.name}", primary or unique`);
1109
+ return Object.freeze({
1110
+ kind,
1111
+ name,
1112
+ key,
1113
+ source,
1114
+ target,
1115
+ targetKey,
1116
+ from,
1117
+ to,
1118
+ required
1119
+ });
1120
+ }
1121
+ /** Adds `definition` of relation `name` of the table under `key` to `relations`, rejecting another definition of the relation there. */
1122
+ function addRelation(relations, key, name, definition) {
1123
+ let named = relations.get(key);
1124
+ if (named === void 0) {
1125
+ named = /* @__PURE__ */ new Map();
1126
+ relations.set(key, named);
1127
+ }
1128
+ const existing = named.get(name);
1129
+ if (existing !== void 0 && existing !== definition) throw new Error(`Relation "${formatRelationName(key, name)}" has two different definitions`);
1130
+ named.set(name, definition);
1131
+ }
1132
+ /** Adds the relation definitions of a schema to `relations`, rejecting another definition of a relation there. */
1133
+ function addRelations(relations, added) {
1134
+ for (const key of Object.keys(added)) {
1135
+ const named = added[key];
1136
+ for (const name of Object.keys(named)) addRelation(relations, key, name, named[name]);
1137
+ }
1138
+ }
1139
+ /** Collects the relation definitions of a schema, which a `Db` of the schema accepts in its queries. */
1140
+ function collectDefinitions(relations) {
1141
+ const definitions = /* @__PURE__ */ new Set();
1142
+ for (const key of Object.keys(relations)) {
1143
+ const named = relations[key];
1144
+ for (const name of Object.keys(named)) definitions.add(named[name]);
1145
+ }
1146
+ return definitions;
1147
+ }
1148
+ /** Creates frozen relations of a schema from `relations`; objects without a prototype keep any key, such as `__proto__`, an own property. */
1149
+ function freezeRelations(relations) {
1150
+ const result = Object.create(null);
1151
+ for (const [key, named] of relations) {
1152
+ const table = Object.create(null);
1153
+ for (const [name, definition] of named) table[name] = definition;
1154
+ result[key] = Object.freeze(table);
1155
+ }
1156
+ return Object.freeze(result);
1157
+ }
1158
+ function isRelationDeclaration(value) {
1159
+ return typeof value === "object" && value !== null && declarationBrand in value;
1160
+ }
1161
+ // src/lowering/order.ts
1162
+ /**
1163
+ * 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`.
1164
+ *
1165
+ * 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.
1166
+ */
1167
+ function findSortProjection(projections, expression) {
1168
+ return projections.findIndex((projection) => {
1169
+ const selected = projection.expression;
1170
+ return expression.kind === "column" && selected.kind === "column" ? selected.source === expression.source && selected.key === expression.key : selected === expression;
1171
+ });
1172
+ }
1173
+ /** Creates the number of the projection at `position`, by which `ORDER BY` sorts by its value instead of evaluating an expression again. */
1174
+ function createPositionNode(position) {
1175
+ return createNode({
1176
+ kind: "raw",
1177
+ fragments: [String(position + 1)],
1178
+ values: []
1179
+ });
1180
+ }
1181
+ /** 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. */
1182
+ function sortByPositions(orderBy, projections) {
1183
+ const result = [];
1184
+ for (const order of orderBy) {
1185
+ const position = findSortProjection(projections, order.expression);
1186
+ result.push(position === -1 ? order : Object.freeze({
1187
+ expression: createPositionNode(position),
1188
+ direction: order.direction,
1189
+ nulls: order.nulls
1190
+ }));
1191
+ }
1192
+ return result;
1193
+ }
1194
+ /**
1195
+ * 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.
1196
+ *
1197
+ * 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.
1198
+ * 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.
1199
+ * `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.
1200
+ */
1201
+ function deriveOrderedSource(query, ordered, offset = query.offset, replaces) {
1202
+ const { orderBy } = query;
1203
+ const projections = query.projections.slice();
1204
+ const paginated = query.limit !== void 0 || query.offset !== void 0;
1205
+ const sortKeys = [];
1206
+ const positions = [];
1207
+ if (orderBy.length > 0 && (ordered || paginated)) for (let index = 0; index < orderBy.length; index++) {
1208
+ const { expression, direction, nulls } = orderBy[index];
1209
+ const position = projectSortKey(projections, expression, index);
1210
+ if (ordered) sortKeys.push({
1211
+ key: projections[position].key,
1212
+ direction,
1213
+ nulls
1214
+ });
1215
+ if (paginated) positions.push(Object.freeze({
1216
+ expression: createPositionNode(position),
1217
+ direction,
1218
+ nulls
1219
+ }));
1220
+ }
1221
+ const derivedQuery = Object.freeze({
1222
+ ...query,
1223
+ projections,
1224
+ orderBy: positions,
1225
+ offset
1226
+ });
1227
+ const source = Object.freeze(replaces === void 0 ? {
1228
+ kind: "derived",
1229
+ query: derivedQuery,
1230
+ lateral: false
1231
+ } : {
1232
+ kind: "derived",
1233
+ query: derivedQuery,
1234
+ lateral: false,
1235
+ replaces
1236
+ });
1237
+ const order = [];
1238
+ for (const { key, direction, nulls } of sortKeys) order.push(Object.freeze({
1239
+ expression: createNode({
1240
+ kind: "column",
1241
+ source,
1242
+ key
1243
+ }),
1244
+ direction,
1245
+ nulls
1246
+ }));
1247
+ return {
1248
+ source,
1249
+ order
1250
+ };
1251
+ }
1252
+ /**
1253
+ * Returns the position of the projection that sorts by `expression`: the projection of `findSortProjection`, or one added to `projections`.
1254
+ *
1255
+ * `index` is the position of the expression in the order.
1256
+ */
1257
+ function projectSortKey(projections, expression, index) {
1258
+ const position = findSortProjection(projections, expression);
1259
+ if (position !== -1) return position;
1260
+ projections.push(Object.freeze({
1261
+ key: createSortProjectionKey(projections, index),
1262
+ expression,
1263
+ type: text
1264
+ }));
1265
+ return projections.length - 1;
1266
+ }
1267
+ /** Creates the key of the sort key projection at `index` of the sort keys, which no other projection has. */
1268
+ function createSortProjectionKey(projections, index) {
1269
+ const base = `$order${index + 1}`;
1270
+ let key = base;
1271
+ for (let number = 2; projections.some((projection) => projection.key === key); number++) key = `${base}_${number}`;
1272
+ return key;
1273
+ }
1274
+ // src/lowering/nested.ts
1275
+ /** Maximum number of arguments of a PostgreSQL function, `FUNC_MAX_ARGS` of its default build. */
1276
+ const maxFunctionArguments = 100;
1277
+ /** Number `0`, the offset that keeps PostgreSQL from merging a derived source into its query. */
1278
+ const zeroNode = /* @__PURE__ */ createNode({
1279
+ kind: "raw",
1280
+ fragments: ["0"],
1281
+ values: []
1282
+ });
1283
+ /**
1284
+ * 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`.
1285
+ *
1286
+ * 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.
1287
+ */
1288
+ function projectRows(key, query) {
1289
+ const packed = packRows(query);
1290
+ const { nested } = packed.projections[0];
1291
+ return Object.freeze({
1292
+ key,
1293
+ expression: createNode({
1294
+ kind: "subquery",
1295
+ query: packed
1296
+ }),
1297
+ nested
1298
+ });
1299
+ }
1300
+ /**
1301
+ * Creates a query whose only projection is the rows of `query` packed as JSON, a field decoded by the result plan of `query`.
1302
+ *
1303
+ * Rows `many` are packed as an array in the order of `query`, and the created query returns one row.
1304
+ * 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.
1305
+ */
1306
+ function packRows(query) {
1307
+ const { projections } = query;
1308
+ const many = query.rows === "many";
1309
+ 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);
1310
+ const wide = projections.length > maxFunctionArguments;
1311
+ const values = [];
1312
+ for (const projection of projections) {
1313
+ const value = createRef(source, projection.key);
1314
+ if (projection.nested !== void 0) values.push(value);
1315
+ else values.push(wide ? createList("to_json(", [packScalar(value)], ")") : packScalar(value));
1316
+ }
1317
+ const row = wide ? createList("array_to_json(ARRAY[", values, "])") : createList("json_build_array(", values, ")");
1318
+ let packed = row;
1319
+ if (many) packed = createNode({
1320
+ kind: "raw",
1321
+ fragments: ["coalesce(", ", '[]'::json)"],
1322
+ values: [createNode({
1323
+ kind: "aggregate",
1324
+ name: "json_agg",
1325
+ distinct: false,
1326
+ arguments: [row],
1327
+ orderBy: order
1328
+ })]
1329
+ });
1330
+ const plan = Object.freeze({
1331
+ fields: projections,
1332
+ rows: query.rows,
1333
+ value: query.value,
1334
+ guaranteedBy: query.guaranteedBy
1335
+ });
1336
+ const projection = Object.freeze({
1337
+ key: "rows",
1338
+ expression: packed,
1339
+ nested: plan
1340
+ });
1341
+ return createSelectNode(source, [projection]);
1342
+ }
1343
+ /** Tells whether `node` is a column of a table, which PostgreSQL reads rather than evaluates, so it can be repeated. */
1344
+ function isTableColumn(node) {
1345
+ return node.kind === "column" && node.source.kind === "table";
1346
+ }
1347
+ /**
1348
+ * Packs a scalar as its PostgreSQL text representation, or `NULL`.
1349
+ *
1350
+ * `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`.
1351
+ */
1352
+ function packScalar(value) {
1353
+ return createNode({
1354
+ kind: "raw",
1355
+ fragments: [
1356
+ "CASE WHEN ",
1357
+ " IS NOT DISTINCT FROM NULL THEN NULL ELSE format('%s', ",
1358
+ ") END"
1359
+ ],
1360
+ values: [value, value]
1361
+ });
1362
+ }
1363
+ function createRef(source, key) {
1364
+ return createNode({
1365
+ kind: "column",
1366
+ source,
1367
+ key
1368
+ });
1369
+ }
1370
+ // src/lowering/lower.ts
1371
+ const noJoins = /* @__PURE__ */ Object.freeze([]);
1372
+ const noOrder = /* @__PURE__ */ Object.freeze([]);
1373
+ function lowerStatement(node, definitions, db) {
1374
+ switch (node.kind) {
1375
+ case "query": return lowerSelect(node, definitions, db, true);
1376
+ case "record": return lowerRecord(node, definitions, db);
1377
+ case "text": return node;
1378
+ default: return lowerMutation(node, definitions, db);
1379
+ }
1380
+ }
1381
+ /** Lowers a mutation to its statement, 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. */
1382
+ function lowerMutation(node, definitions, db) {
1383
+ const { returning } = node;
1384
+ const lowered = returning === void 0 ? void 0 : lowerProjections(returning, definitions, db);
1385
+ if (lowered === returning) return node;
1386
+ const { target, rows, value } = node;
1387
+ switch (node.kind) {
1388
+ case "insert": return Object.freeze({
1389
+ kind: "insert",
1390
+ target,
1391
+ columns: node.columns,
1392
+ values: node.values,
1393
+ returning: lowered,
1394
+ rows,
1395
+ value
1396
+ });
1397
+ case "update": return Object.freeze({
1398
+ kind: "update",
1399
+ target,
1400
+ set: node.set,
1401
+ filters: node.filters,
1402
+ returning: lowered,
1403
+ rows,
1404
+ value
1405
+ });
1406
+ case "delete": return Object.freeze({
1407
+ kind: "delete",
1408
+ target,
1409
+ filters: node.filters,
1410
+ returning: lowered,
1411
+ rows,
1412
+ value
1413
+ });
1414
+ default: return node;
1415
+ }
1416
+ }
1417
+ /** Lowers a query as `lowerQuery` does, or as `lowerStatement` does when `positions` is set. */
1418
+ function lowerSelect(node, definitions, db, positions) {
1419
+ const { relation } = node;
1420
+ 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`);
1421
+ if (isAggregateQuery(node)) return lowerAggregate(node);
1422
+ const projections = lowerProjections(node.projections, definitions, db);
1423
+ const guaranteedBy = node.guaranteed && relation !== void 0 ? formatRelationName(relation.key, relation.name) : void 0;
1424
+ const page = node.offset !== void 0 && projections !== node.projections ? lowerPage(node, projections, positions, guaranteedBy) : void 0;
1425
+ if (page !== void 0) return page;
1426
+ return Object.freeze({
1427
+ kind: "select",
1428
+ from: node.from,
1429
+ joins: noJoins,
1430
+ projections,
1431
+ filters: node.filters,
1432
+ orderBy: positions && node.orderBy.length > 0 ? sortByPositions(node.orderBy, projections) : node.orderBy,
1433
+ limit: node.limit,
1434
+ offset: node.offset,
1435
+ rows: node.rows,
1436
+ value: node.value,
1437
+ guaranteedBy
1438
+ });
1439
+ }
1440
+ /**
1441
+ * Lowers `node` with `projections` to a statement that evaluates its nested queries over the rows of a derived page.
1442
+ * The derived source applies the filters, the order, the limit, and the offset, and replaces the occurrence of the table.
1443
+ *
1444
+ * It returns `undefined` when a nested query holds a SQL fragment that refers to a column of the table outside the queries nested in the fragment.
1445
+ * Such a fragment may hold an aggregate of the query, which the limit and the offset apply after.
1446
+ *
1447
+ * 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.
1448
+ * 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(*)`.
1449
+ * 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.
1450
+ */
1451
+ function lowerPage(node, projections, positions, guaranteedBy) {
1452
+ const { from } = node;
1453
+ const columnKeys = /* @__PURE__ */ new Set();
1454
+ const fields = [];
1455
+ const fieldKeys = [];
1456
+ for (let index = 0; index < projections.length; index++) {
1457
+ const { expression } = projections[index];
1458
+ let key;
1459
+ if (isNestedSelection(node.projections[index])) {
1460
+ if (holdsFragmentOfSource(expression, from)) return;
1461
+ collectColumnKeys(expression, from, columnKeys);
1462
+ } else if (expression.kind === "column" && expression.source === from) columnKeys.add(expression.key);
1463
+ else {
1464
+ key = `$field${index + 1}`;
1465
+ fields.push(Object.freeze({
1466
+ key,
1467
+ expression,
1468
+ type: text
1469
+ }));
1470
+ }
1471
+ fieldKeys.push(key);
1472
+ }
1473
+ const sourced = [];
1474
+ for (const key of columnKeys) sourced.push(Object.freeze({
1475
+ key,
1476
+ expression: createNode({
1477
+ kind: "column",
1478
+ source: from,
1479
+ key
1480
+ }),
1481
+ type: text
1482
+ }));
1483
+ for (const field of fields) sourced.push(field);
1484
+ const page = deriveOrderedSource({
1485
+ kind: "select",
1486
+ from,
1487
+ joins: noJoins,
1488
+ projections: sourced,
1489
+ filters: node.filters,
1490
+ orderBy: node.orderBy,
1491
+ limit: node.limit,
1492
+ offset: node.offset,
1493
+ rows: "many",
1494
+ value: false,
1495
+ guaranteedBy: void 0
1496
+ }, true, node.offset, from);
1497
+ const selected = [];
1498
+ for (let index = 0; index < projections.length; index++) {
1499
+ const projection = projections[index];
1500
+ const key = fieldKeys[index];
1501
+ selected.push(key === void 0 ? projection : Object.freeze({
1502
+ key: projection.key,
1503
+ expression: createNode({
1504
+ kind: "column",
1505
+ source: page.source,
1506
+ key
1507
+ }),
1508
+ type: projection.type
1509
+ }));
1510
+ }
1511
+ return Object.freeze({
1512
+ kind: "select",
1513
+ from: page.source,
1514
+ joins: noJoins,
1515
+ projections: selected,
1516
+ filters: noFilters,
1517
+ orderBy: positions ? sortByPositions(page.order, selected) : page.order,
1518
+ limit: void 0,
1519
+ offset: void 0,
1520
+ rows: node.rows,
1521
+ value: node.value,
1522
+ guaranteedBy
1523
+ });
1524
+ }
1525
+ /** Lowers an aggregate query to a statement of the value of its aggregate over the rows that its filters, limit, and offset choose. */
1526
+ function lowerAggregate(node) {
1527
+ const field = node.projections[0];
1528
+ const aggregate = field.expression;
1529
+ let from = node.from;
1530
+ let filters = node.filters;
1531
+ let args = aggregate.arguments;
1532
+ let order = field.ordered ? node.orderBy : noOrder;
1533
+ const counted = aggregate === countProjection.expression;
1534
+ if (node.limit !== void 0 || node.offset !== void 0 || !counted && !refersToSource(args[0], node.from)) {
1535
+ const projections = [];
1536
+ if (!counted) projections.push(Object.freeze({
1537
+ key: "value",
1538
+ expression: args[0],
1539
+ type: field.type
1540
+ }));
1541
+ const rows = deriveOrderedSource({
1542
+ kind: "select",
1543
+ from: node.from,
1544
+ joins: noJoins,
1545
+ projections,
1546
+ filters: node.filters,
1547
+ orderBy: counted ? noOrder : node.orderBy,
1548
+ limit: node.limit,
1549
+ offset: node.offset,
1550
+ rows: "many",
1551
+ value: false,
1552
+ guaranteedBy: void 0
1553
+ }, field.ordered);
1554
+ from = rows.source;
1555
+ filters = noFilters;
1556
+ if (!counted) {
1557
+ const sourceArgs = [createNode({
1558
+ kind: "column",
1559
+ source: from,
1560
+ key: "value"
1561
+ })];
1562
+ for (let index = 1; index < args.length; index++) sourceArgs.push(args[index]);
1563
+ args = sourceArgs;
1564
+ }
1565
+ order = rows.order;
1566
+ }
1567
+ const call = args === aggregate.arguments && order.length === 0 ? aggregate : createNode({
1568
+ kind: "aggregate",
1569
+ name: aggregate.name,
1570
+ distinct: aggregate.distinct,
1571
+ arguments: args,
1572
+ orderBy: order
1573
+ });
1574
+ const { fallbacks } = field;
1575
+ let value = call;
1576
+ if (fallbacks.length > 0) {
1577
+ const values = [call];
1578
+ for (const fallback of fallbacks) values.push(fallback);
1579
+ value = createList("coalesce(", values, ")");
1580
+ }
1581
+ return Object.freeze({
1582
+ kind: "select",
1583
+ from,
1584
+ joins: noJoins,
1585
+ projections: [value === aggregate ? field : Object.freeze({
1586
+ key: field.key,
1587
+ expression: value,
1588
+ type: field.type
1589
+ })],
1590
+ filters,
1591
+ orderBy: noOrder,
1592
+ limit: void 0,
1593
+ offset: void 0,
1594
+ rows: node.rows,
1595
+ value: true,
1596
+ guaranteedBy: void 0
1597
+ });
1598
+ }
1599
+ /**
1600
+ * Tells whether `node` refers to `source` outside the queries nested in it.
1601
+ *
1602
+ * 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.
1603
+ */
1604
+ function refersToSource(node, source) {
1605
+ switch (node.kind) {
1606
+ case "column": return node.source === source;
1607
+ case "param":
1608
+ case "boolean":
1609
+ case "values":
1610
+ case "tableName":
1611
+ case "subquery":
1612
+ case "exists": return false;
1613
+ case "cast":
1614
+ case "not":
1615
+ case "isNull": return refersToSource(node.operand, source);
1616
+ case "and":
1617
+ case "or": return node.operands.some((operand) => refersToSource(operand, source));
1618
+ case "comparison": return refersToSource(node.left, source) || refersToSource(node.right, source);
1619
+ case "in": return refersToSource(node.operand, source) || node.list.some((item) => refersToSource(item, source));
1620
+ case "raw": return node.values.some((value) => refersToSource(value, source));
1621
+ case "aggregate": return node.arguments.some((argument) => refersToSource(argument, source));
1622
+ default: return node;
1623
+ }
1624
+ }
1625
+ /** Lowers a query of `$select` to a statement without a source, which returns one row of its fields. */
1626
+ function lowerRecord(node, definitions, db) {
1627
+ return Object.freeze({
1628
+ kind: "select",
1629
+ from: void 0,
1630
+ joins: noJoins,
1631
+ projections: lowerProjections(node.projections, definitions, db),
1632
+ filters: noFilters,
1633
+ orderBy: noOrder,
1634
+ limit: void 0,
1635
+ offset: void 0,
1636
+ rows: "one",
1637
+ value: false,
1638
+ guaranteedBy: void 0
1639
+ });
1640
+ }
1641
+ /**
1642
+ * 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; checks them as `lowerQuery` does.
1643
+ *
1644
+ * Without nested queries, it returns `selected` itself.
1645
+ */
1646
+ function lowerProjections(selected, definitions, db) {
1647
+ let lowered;
1648
+ for (let index = 0; index < selected.length; index++) {
1649
+ const field = selected[index];
1650
+ if (isNestedSelection(field)) {
1651
+ if (field.db !== void 0 && field.db !== db) throw new Error(db === void 0 ? `Selected field "${field.key}" is bound to a Db, so only that Db can compile the query` : `Selected field "${field.key}" is bound to another Db`);
1652
+ lowered ??= selected.slice(0, index);
1653
+ const query = lowerSelect(field.query, definitions, db, false);
1654
+ lowered.push(isAggregateQuery(field.query) ? projectAggregateValue(field.key, query) : projectRows(field.key, query));
1655
+ } else if (lowered !== void 0) lowered.push(field);
1656
+ }
1657
+ return lowered ?? selected;
1658
+ }
1659
+ /** 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. */
1660
+ function projectAggregateValue(key, query) {
1661
+ return Object.freeze({
1662
+ key,
1663
+ expression: createNode({
1664
+ kind: "subquery",
1665
+ query
1666
+ }),
1667
+ type: query.projections[0].type
1668
+ });
1669
+ }
1670
+ // src/query/kind.ts
1671
+ /** `then` of every bound query, which executes the query on its `Db`. */
1672
+ function executeOnAwait(onFulfilled, onRejected) {
1673
+ return this.db.$execute(this).then(onFulfilled, onRejected);
1674
+ }
1675
+ /** Compiles `query` as its `toSQL` does: an unbound query with `options`, and a bound query as its `Db` executes it, which takes no options. */
1676
+ function compileToSQL(query, options) {
1677
+ const { db } = query;
1678
+ if (db === void 0) {
1679
+ const { text, parameters } = compileStatement(lowerStatement(query.node), options);
1680
+ return createStatement(text, parameters);
1681
+ }
1682
+ if (options !== void 0) throw new Error("A query bound to a Db compiles with the options of its Db");
1683
+ return db.$compile(query);
1684
+ }
1685
+ // src/query/column-refs.ts
1686
+ /** Context of a query whose table has no relations, such as one of `from(table)`. */
1687
+ const noContext = /* @__PURE__ */ Object.freeze({ relations: /* @__PURE__ */ Object.freeze({}) });
1688
+ /** Creates expressions of the columns of `source`, each with the type of its column. */
1689
+ function createColumnRefs(source) {
1690
+ return addColumns({}, source);
1691
+ }
1692
+ /** Creates the references of the callback of `select` over `source`: its columns, and the relations of `context`. */
1693
+ function createSelectionRefs(source, context) {
1694
+ return Object.defineProperties(addColumns({}, source), context.relations);
1695
+ }
1696
+ function addColumns(refs, source) {
1697
+ const { columns } = source.table;
1698
+ for (const key of Object.keys(columns)) refs[key] = toExpression(createNode({
1699
+ kind: "column",
1700
+ source,
1701
+ key
1702
+ }), columns[key].type);
1703
+ return refs;
1704
+ }
1705
+ // src/query/resolve-values.ts
1706
+ /**
1707
+ * Replaces objects of column values in a predicate with conditions on the columns of `source`.
1708
+ *
1709
+ * Groups are rebuilt, so constants that appear after resolution, such as an empty object, are simplified.
1710
+ */
1711
+ function resolveValues(node, source) {
1712
+ switch (node.kind) {
1713
+ case "values": {
1714
+ const conditions = [];
1715
+ for (const key of Object.keys(node.values)) {
1716
+ const value = node.values[key];
1717
+ const type = findColumn(source.table, key)?.type;
1718
+ const column = createNode({
1719
+ kind: "column",
1720
+ source,
1721
+ key
1722
+ });
1723
+ if (value === null) conditions.push(createIsNullNode(column));
1724
+ else if (type) conditions.push(matchValue(source, column, type, value));
1725
+ else conditions.push(compareNodes("=", column, value, void 0));
1726
+ }
1727
+ return combineNodes("and", conditions);
1728
+ }
1729
+ case "and":
1730
+ case "or": {
1731
+ const operands = [];
1732
+ for (const operand of node.operands) operands.push(resolveValues(operand, source));
1733
+ return combineNodes(node.kind, operands);
1734
+ }
1735
+ case "not": return negateNode(resolveValues(node.operand, source));
1736
+ case "raw": return createNode({
1737
+ ...node,
1738
+ values: node.values.map((value) => resolveValues(value, source))
1739
+ });
1740
+ default: return node;
1741
+ }
1742
+ }
1743
+ /** Matches a column with a value of an object condition by calling the `eq` operator of its type, whichever operator it is. */
1744
+ function matchValue(source, column, type, value) {
1745
+ const expression = toExpression(column, type);
1746
+ 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`);
1747
+ const predicate = expression.eq(value);
1748
+ if (!isExpression(predicate)) throw new TypeError(`The eq operator of column "${column.key}" of table "${source.table.name}" must return an expression`);
1749
+ return toNode(predicate);
1750
+ }
1751
+ // src/query/filters.ts
1752
+ /** Creates query filters with the filter of `where` over `source` combined with `AND` with the user filters of `filters`. */
1753
+ function addUserFilter(filters, filter, source) {
1754
+ const predicate = resolveValues(toConditionNode(typeof filter === "function" ? filter(createColumnRefs(source)) : filter), source);
1755
+ const { user } = filters;
1756
+ return Object.freeze({
1757
+ ...filters,
1758
+ user: user ? combineNodes("and", [user, predicate]) : predicate
1759
+ });
1760
+ }
1761
+ function defineFilter(_table, filter) {
1762
+ return filter;
1763
+ }
1764
+ // src/query/find.ts
1765
+ /**
1766
+ * 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.
1767
+ *
1768
+ * It rejects a table without a primary key, a number of values other than the number of its columns, and `null` and `undefined`.
1769
+ */
1770
+ function toPrimaryKeyValues(table, values) {
1771
+ const { primaryKey } = table.keys;
1772
+ 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`);
1773
+ 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}`);
1774
+ const filter = {};
1775
+ for (let index = 0; index < primaryKey.length; index++) {
1776
+ const column = primaryKey[index];
1777
+ filter[column] = requireKeyValue(table, column, values[index], "find");
1778
+ }
1779
+ return filter;
1780
+ }
1781
+ /**
1782
+ * Returns the object of column values that `findBy` filters a query of `table` by: a copy of `values`, read once.
1783
+ *
1784
+ * It rejects columns that are not exactly a key of `table`, primary or unique, as `isKey` tells, and `null` and `undefined`.
1785
+ */
1786
+ function toKeyValues(table, values) {
1787
+ if (typeof values !== "object" || values === null) throw new TypeError(`findBy takes an object of the columns of a key of table "${table.name}"`);
1788
+ const columns = Object.keys(values);
1789
+ if (!isKey(table, columns)) {
1790
+ const listed = columns.length === 0 ? "an object without columns" : `columns ${quoteColumns(columns)}`;
1791
+ throw new Error(`findBy takes the columns of one key of table "${table.name}", primary or unique, not ${listed}`);
1792
+ }
1793
+ const filter = {};
1794
+ for (const column of columns) {
1795
+ const value = values[column];
1796
+ filter[column] = requireKeyValue(table, column, value, "findBy");
1797
+ }
1798
+ return filter;
1799
+ }
1800
+ /** Returns `value` of column `column` of a key of `table` that `method` takes, rejecting `null` and `undefined`. */
1801
+ function requireKeyValue(table, column, value, method) {
1802
+ 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`);
1803
+ return value;
1804
+ }
1805
+ /** Lists `columns` in quotes, separated by commas. */
1806
+ function quoteColumns(columns) {
1807
+ return columns.map((column) => `"${column}"`).join(", ");
1808
+ }
1809
+ // src/query/order.ts
1810
+ /** Direction and placement of `NULL` of a sort key node, by `OrderDirection`. */
1811
+ const directions = /* @__PURE__ */ Object.freeze({
1812
+ asc: {
1813
+ direction: "asc",
1814
+ nulls: void 0
1815
+ },
1816
+ desc: {
1817
+ direction: "desc",
1818
+ nulls: void 0
1819
+ },
1820
+ "asc nulls first": {
1821
+ direction: "asc",
1822
+ nulls: "first"
1823
+ },
1824
+ "asc nulls last": {
1825
+ direction: "asc",
1826
+ nulls: "last"
1827
+ },
1828
+ "desc nulls first": {
1829
+ direction: "desc",
1830
+ nulls: "first"
1831
+ },
1832
+ "desc nulls last": {
1833
+ direction: "desc",
1834
+ nulls: "last"
1835
+ }
1836
+ });
1837
+ const orderingNode = Symbol("kern-orm.ordering.node");
1838
+ /** Runtime class of an expression with a direction, which holds its sort key node. */
1839
+ var OrderingObject = class {
1840
+ [orderingNode];
1841
+ constructor(node) {
1842
+ this[orderingNode] = node;
1843
+ Object.freeze(this);
1844
+ }
1845
+ };
1846
+ /** Sorts by `expression` in ascending order, in the callback of `orderBy`. */
1847
+ function asc(expression) {
1848
+ return orderBy(expression, "asc");
1849
+ }
1850
+ /** Sorts by `expression` in descending order, in the callback of `orderBy`. */
1851
+ function desc(expression) {
1852
+ return orderBy(expression, "desc");
1853
+ }
1854
+ /** Sorts by `expression` in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
1855
+ function orderBy(expression, direction) {
1856
+ if (!isExpression(expression)) throw new TypeError("A sort key must be an expression");
1857
+ return new OrderingObject(createOrderNode(toNode(expression), direction));
1858
+ }
1859
+ /**
1860
+ * Creates the order of `node` with the sort keys of the arguments of `orderBy` after its own.
1861
+ *
1862
+ * `args` are column keys and objects of columns with directions, or a callback that receives the columns and the selected fields and returns one sort key or an array of them.
1863
+ */
1864
+ function addOrder(node, args) {
1865
+ const order = node.orderBy.slice();
1866
+ const first = args[0];
1867
+ if (typeof first === "function") {
1868
+ const terms = first(createColumnRefs(node.from), createSelectedRefs(node));
1869
+ if (Array.isArray(terms)) for (const term of terms) order.push(readTerm(term));
1870
+ else order.push(readTerm(terms));
1871
+ return order;
1872
+ }
1873
+ for (const arg of args) if (typeof arg === "string") order.push(createOrderNode(createColumnNode(node.from, arg), "asc"));
1874
+ else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) {
1875
+ const columns = arg;
1876
+ for (const key of Object.keys(columns)) order.push(createOrderNode(createColumnNode(node.from, key), columns[key]));
1877
+ } else throw new TypeError("orderBy takes column keys and objects of columns with directions, or a callback");
1878
+ return order;
1879
+ }
1880
+ /** Creates the sort key node of a sort key returned by the callback of `orderBy`. */
1881
+ function readTerm(term) {
1882
+ if (term instanceof OrderingObject) return term[orderingNode];
1883
+ if (isExpression(term)) return createOrderNode(toNode(term), "asc");
1884
+ throw new TypeError("The callback of orderBy must return expressions, or sort keys of asc, desc, and orderBy");
1885
+ }
1886
+ /** Creates the sort key node of `expression` in `direction`, an `OrderDirection` checked at runtime. */
1887
+ function createOrderNode(expression, direction) {
1888
+ const placement = typeof direction === "string" && Object.hasOwn(directions, direction) ? directions[direction] : void 0;
1889
+ if (placement === void 0) throw new TypeError(`Unknown sort direction ${JSON.stringify(direction)}`);
1890
+ return Object.freeze({
1891
+ expression,
1892
+ direction: placement.direction,
1893
+ nulls: placement.nulls
1894
+ });
1895
+ }
1896
+ /** Creates a reference to the column `key` of the table of `source`. */
1897
+ function createColumnNode(source, key) {
1898
+ requireColumn(source.table, key);
1899
+ return createNode({
1900
+ kind: "column",
1901
+ source,
1902
+ key
1903
+ });
1904
+ }
1905
+ /**
1906
+ * Creates the references of the callback of `orderBy` to the fields selected by `node`.
1907
+ *
1908
+ * Each is an expression over the node of its projection, so that a sort key of it is the projection itself.
1909
+ */
1910
+ function createSelectedRefs(node) {
1911
+ const { projections } = node;
1912
+ if (node.value) return toSelectedExpression(projections[0]);
1913
+ const refs = {};
1914
+ for (const projection of projections) {
1915
+ const { key } = projection;
1916
+ if (isNestedSelection(projection)) Object.defineProperty(refs, key, {
1917
+ get() {
1918
+ throw new Error(`Field "${key}" holds a nested query and cannot be sorted by`);
1919
+ },
1920
+ enumerable: true
1921
+ });
1922
+ else refs[key] = toSelectedExpression(projection);
1923
+ }
1924
+ return refs;
1925
+ }
1926
+ /** Creates an expression over the node of a projection of a query, which has a type: only lowering adds projections of nested queries. */
1927
+ function toSelectedExpression(projection) {
1928
+ return toExpression(projection.expression, projection.type);
1929
+ }
1930
+ // src/query/pagination.ts
1931
+ /** 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. */
1932
+ function createPageCount(node, method, count) {
1933
+ if (node.rows !== "many") throw new Error(`${method} applies only to a query of many rows${createPaginationHint(node)}`);
1934
+ if (!Number.isSafeInteger(count) || count < 0) throw new RangeError(`${method} takes a non-negative integer, not ${count}`);
1935
+ return createNode({
1936
+ kind: "param",
1937
+ value: count,
1938
+ type: void 0
1939
+ });
1940
+ }
1941
+ /** Creates the hint of the error of `limit` or `offset` of query `node` of one row: the method to call them before, if any. */
1942
+ function createPaginationHint(node) {
1943
+ if (node.relation?.kind === "one") return "";
1944
+ return isAggregateQuery(node) ? "; call it before count or another aggregate to aggregate the rows of a page" : "; call it before take or get";
1945
+ }
1946
+ // src/query/select.ts
1947
+ /**
1948
+ * Immutable select query of state `S`, unbound or bound to a `Db`.
1949
+ *
1950
+ * Every method returns a query of the same kind and leaves this query unchanged.
1951
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
1952
+ * A bound query executes on its `Db` when awaited.
1953
+ */
1954
+ var SelectQuery = class SelectQuery {
1955
+ table;
1956
+ node;
1957
+ context;
1958
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
1959
+ db;
1960
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
1961
+ then;
1962
+ constructor(table, node, context, db) {
1963
+ this.table = table;
1964
+ this.node = node;
1965
+ this.context = context;
1966
+ this.db = db;
1967
+ this.then = db === void 0 ? void 0 : executeOnAwait;
1968
+ Object.freeze(this);
1969
+ }
1970
+ where(filter) {
1971
+ return this.derive(this.addFilter(filter));
1972
+ }
1973
+ select(...args) {
1974
+ this.rejectValue("select");
1975
+ return this.derive({ projections: mergeProjections(this.node.projections, this.node.from, args, this.context) });
1976
+ }
1977
+ clearSelect() {
1978
+ this.rejectValue("clearSelect");
1979
+ return this.derive({ projections: [] });
1980
+ }
1981
+ take() {
1982
+ return this.deriveTaken({});
1983
+ }
1984
+ find(...values) {
1985
+ return this.takeWhere(toPrimaryKeyValues(this.table, values));
1986
+ }
1987
+ findBy(values) {
1988
+ return this.takeWhere(toKeyValues(this.table, values));
1989
+ }
1990
+ get(arg) {
1991
+ this.rejectAggregate("get");
1992
+ return this.deriveTaken({
1993
+ projections: [projectValue(this.node.from, arg, "get")],
1994
+ value: true,
1995
+ rows: toValueRows(this.node.rows)
1996
+ });
1997
+ }
1998
+ pluck(arg) {
1999
+ this.rejectAggregate("pluck");
2000
+ return this.derive({
2001
+ projections: [projectValue(this.node.from, arg, "pluck")],
2002
+ value: true,
2003
+ rows: toValueRows(this.node.rows)
2004
+ });
2005
+ }
2006
+ count(arg) {
2007
+ if (arg !== void 0) return this.aggregateBy("count", arg);
2008
+ this.rejectAggregate("count");
2009
+ return this.deriveAggregate(countProjection);
2010
+ }
2011
+ countDistinct(arg) {
2012
+ return this.aggregateBy("countDistinct", arg);
2013
+ }
2014
+ min(arg) {
2015
+ return this.aggregateBy("min", arg);
2016
+ }
2017
+ max(arg) {
2018
+ return this.aggregateBy("max", arg);
2019
+ }
2020
+ sum(arg) {
2021
+ return this.aggregateBy("sum", arg);
2022
+ }
2023
+ avg(arg) {
2024
+ return this.aggregateBy("avg", arg);
2025
+ }
2026
+ every(arg) {
2027
+ return this.aggregateBy("every", arg);
2028
+ }
2029
+ some(arg) {
2030
+ return this.aggregateBy("some", arg);
2031
+ }
2032
+ stringAgg(arg, delimiter) {
2033
+ return this.aggregateBy("stringAgg", arg, delimiter);
2034
+ }
2035
+ coalesce(fallback) {
2036
+ const { node } = this;
2037
+ if (!node.value) throw new Error("coalesce applies only to a query of values, such as one made by get, pluck, or an aggregate");
2038
+ return this.derive({ projections: [coalesceValue(node.projections[0], fallback)] });
2039
+ }
2040
+ orderBy(...args) {
2041
+ return this.derive({ orderBy: addOrder(this.node, args) });
2042
+ }
2043
+ limit(count) {
2044
+ return this.derive({ limit: createPageCount(this.node, "limit", count) });
2045
+ }
2046
+ offset(count) {
2047
+ return this.derive({ offset: createPageCount(this.node, "offset", count) });
2048
+ }
2049
+ optional() {
2050
+ return this.changeOneRow("optional", "optional");
2051
+ }
2052
+ nullable() {
2053
+ if (this.node.value) throw new Error("nullable applies only to a query of records; use optional after get, pluck, or an aggregate");
2054
+ return this.changeOneRow("nullable", "nullable");
2055
+ }
2056
+ required() {
2057
+ return this.changeOneRow("required", "one");
2058
+ }
2059
+ insert(values) {
2060
+ return createInsert(this, [values], "one", "insert");
2061
+ }
2062
+ insertMany(records) {
2063
+ if (!Array.isArray(records)) throw new TypeError("insertMany takes an array of records");
2064
+ return createInsert(this, records, "many", "insertMany");
2065
+ }
2066
+ update(set) {
2067
+ return createUpdate(this, set);
2068
+ }
2069
+ delete() {
2070
+ return createDelete(this);
2071
+ }
2072
+ all() {
2073
+ if (this.node.rows !== "many") throw new Error("all applies only to a query of many rows");
2074
+ return this.derive({ all: true });
2075
+ }
2076
+ use(callback, ...args) {
2077
+ return requireDerived(this, callback(this, ...args), "The callback of use");
2078
+ }
2079
+ toSQL(options) {
2080
+ return compileToSQL(this, options);
2081
+ }
2082
+ /** Creates a query of the same kind and `Db` with the node changes applied. */
2083
+ derive(changes) {
2084
+ return new SelectQuery(this.table, Object.freeze({
2085
+ ...this.node,
2086
+ ...changes
2087
+ }), this.context, this.db);
2088
+ }
2089
+ /**
2090
+ * Creates a query of the same kind and `Db` with the node changes applied and then those of `take`, in one derived query.
2091
+ *
2092
+ * It adds the changes of `take` to `changes`, which must leave the limit as it is.
2093
+ */
2094
+ deriveTaken(changes) {
2095
+ if ((changes.rows ?? this.node.rows) === "many") {
2096
+ changes.limit = limitToOne(this.node.limit);
2097
+ changes.rows = "one";
2098
+ }
2099
+ return this.derive(changes);
2100
+ }
2101
+ /** Creates the query of the value of `projection`, an aggregate over the rows of this query, which always returns one row. */
2102
+ deriveAggregate(projection) {
2103
+ return this.derive({
2104
+ projections: [projection],
2105
+ rows: "one",
2106
+ value: true,
2107
+ guaranteed: false
2108
+ });
2109
+ }
2110
+ /** Creates the query of the aggregate of `method` over `arg`, a column key or a callback that receives the columns and returns an expression; `delimiter` is the delimiter of `stringAgg`. */
2111
+ aggregateBy(method, arg, delimiter) {
2112
+ this.rejectAggregate(method);
2113
+ return this.deriveAggregate(projectAggregate(method, projectValue(this.node.from, arg, method), delimiter));
2114
+ }
2115
+ /** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
2116
+ addFilter(filter) {
2117
+ const { node } = this;
2118
+ return {
2119
+ filters: addUserFilter(node.filters, filter, node.from),
2120
+ rows: toFilteredRows(node.rows, node.value, node.guaranteed),
2121
+ guaranteed: false
2122
+ };
2123
+ }
2124
+ /** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
2125
+ takeWhere(values) {
2126
+ const changes = this.addFilter(values);
2127
+ if (changes.rows === "many") changes.rows = "one";
2128
+ return this.derive(changes);
2129
+ }
2130
+ /** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
2131
+ changeOneRow(method, rows) {
2132
+ if (this.node.rows === "many") throw new Error(`${method} applies only to a query of one row, such as one made by take`);
2133
+ return this.derive({
2134
+ rows,
2135
+ guaranteed: false
2136
+ });
2137
+ }
2138
+ /** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
2139
+ rejectValue(method) {
2140
+ if (!this.node.value) return;
2141
+ this.rejectAggregate(method);
2142
+ throw new Error(`${method} cannot be used after get or pluck; call get or pluck to replace the value`);
2143
+ }
2144
+ /** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method. */
2145
+ rejectAggregate(method) {
2146
+ if (isAggregateQuery(this.node)) throw new Error(`${method} cannot be used after an aggregate`);
2147
+ }
2148
+ };
2149
+ /**
2150
+ * Returns `result`, which a callback named by `subject` returned for `query`, after checking that it is `query` or a query derived from it.
2151
+ *
2152
+ * An ancestor of `query` also passes, since only the source occurrence is compared.
2153
+ */
2154
+ function requireDerived(query, result, subject) {
2155
+ 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`);
2156
+ return result;
2157
+ }
2158
+ /** Binds a query to `db`, so that awaiting it executes it there. */
2159
+ function bindQuery(query, db) {
2160
+ return new SelectQuery(query.table, query.node, query.context, db);
2161
+ }
2162
+ /** Starts a query over a new occurrence of the table. */
2163
+ function from(table) {
2164
+ return startQuery(table, noContext);
2165
+ }
2166
+ /** Starts a query over a new occurrence of the table with the relations of `context`, such as a query of a table of a schema. */
2167
+ function startQuery(table, context) {
2168
+ return new SelectQuery(table, createQueryNode(Object.freeze({
2169
+ kind: "table",
2170
+ table
2171
+ })), context);
2172
+ }
2173
+ // src/query/sql-query.ts
2174
+ /**
2175
+ * Immutable query of a statement of SQL text, bound to the `Db` that executes it when awaited.
2176
+ *
2177
+ * Without a selection, it resolves to the number of the rows of the command tag of its statement, such as the rows that an `UPDATE` changes; `select`, `get`, and `pluck` return the fields of the rows of the statement instead, decoded by types.
2178
+ */
2179
+ var SqlQuery = class SqlQuery {
2180
+ node;
2181
+ db;
2182
+ /** Executes the query on its `Db`. */
2183
+ then;
2184
+ constructor(node, db) {
2185
+ this.node = node;
2186
+ this.db = db;
2187
+ this.then = executeOnAwait;
2188
+ Object.freeze(this);
2189
+ }
2190
+ select(fields) {
2191
+ const { node } = this;
2192
+ if (node.fields !== void 0 && node.value) throw new Error("select cannot be used after get or pluck; call get or pluck to replace the value");
2193
+ if (typeof fields !== "object" || fields === null) throw new TypeError("select takes an object of the types of the fields by their columns");
2194
+ const added = Reflect.ownKeys(fields);
2195
+ const selected = [];
2196
+ for (const field of node.fields ?? []) if (!added.includes(field.key)) selected.push(field);
2197
+ for (const key of added) {
2198
+ if (typeof key === "symbol") throw new TypeError("A selected field must have a string key");
2199
+ if (!isRecordKey(key)) throw new Error(`Field "${key}" cannot be a key of a record`);
2200
+ selected.push(Object.freeze({
2201
+ key,
2202
+ type: requireType(fields[key], `field "${key}"`)
2203
+ }));
2204
+ }
2205
+ return this.derive({
2206
+ fields: selected,
2207
+ value: false
2208
+ });
2209
+ }
2210
+ get(type) {
2211
+ const { rows } = this.node;
2212
+ return this.deriveValue(type, "get", rows === "many" ? "one" : toValueRows(rows));
2213
+ }
2214
+ pluck(type) {
2215
+ return this.deriveValue(type, "pluck", toValueRows(this.node.rows));
2216
+ }
2217
+ take() {
2218
+ const { rows } = this.node;
2219
+ return this.derive({ rows: rows === "many" ? "one" : rows });
2220
+ }
2221
+ optional() {
2222
+ return this.changeOneRow("optional");
2223
+ }
2224
+ nullable() {
2225
+ const { node } = this;
2226
+ if (node.fields !== void 0 && node.value) throw new Error("nullable applies only to a query of records; use optional after get or pluck");
2227
+ return this.changeOneRow("nullable");
2228
+ }
2229
+ /** Compiles the query into SQL text and parameters, as its `Db` executes it. */
2230
+ toSQL() {
2231
+ return this.db.$compile(this);
2232
+ }
2233
+ /** Creates a query of the same `Db` with the node changes applied. */
2234
+ derive(changes) {
2235
+ return new SqlQuery(Object.freeze({
2236
+ ...this.node,
2237
+ ...changes
2238
+ }), this.db);
2239
+ }
2240
+ /** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
2241
+ deriveValue(type, method, rows) {
2242
+ const field = Object.freeze({
2243
+ key: "value",
2244
+ type: requireType(type, method)
2245
+ });
2246
+ return this.derive({
2247
+ fields: [field],
2248
+ value: true,
2249
+ rows
2250
+ });
2251
+ }
2252
+ /** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
2253
+ changeOneRow(rows) {
2254
+ if (this.node.rows === "many") throw new Error(`${rows} applies only to a query of one row, such as one made by take`);
2255
+ return this.derive({ rows });
2256
+ }
2257
+ };
2258
+ /** Starts the query of the statement of `sql` bound to `db`, which resolves to the number of the rows of its command tag. */
2259
+ function startSqlQuery(sql, db) {
2260
+ return new SqlQuery(Object.freeze({
2261
+ kind: "text",
2262
+ sql,
2263
+ fields: void 0,
2264
+ rows: "many",
2265
+ value: false
2266
+ }), db);
2267
+ }
2268
+ /** Returns `value` that `what` takes as its type, rejecting a value that is not a type, such as a column. */
2269
+ function requireType(value, what) {
2270
+ if (!isType(value)) throw new TypeError(`${what} takes a type, such as t.integer, not a column or another value`);
2271
+ return value;
2272
+ }
2273
+ // src/query/values.ts
2274
+ /**
2275
+ * Returns the columns and the rows of `VALUES` of an insert of `records`, at least one, into `table`, reading the keys and values of each record when it is called.
2276
+ *
2277
+ * The columns are those that some record gives a value other than `undefined`, in the order that the records first give them, and a record that omits one inserts its `DEFAULT`.
2278
+ * Several records without values insert the `DEFAULT` of the first column of the table, since `DEFAULT VALUES` inserts one row.
2279
+ * It rejects a key that is not a column of `table`, and a query as a value.
2280
+ */
2281
+ function toInsertRows(table, records, method) {
2282
+ if (records.length === 0) throw new Error(`${method} takes at least one record`);
2283
+ const columns = [];
2284
+ const rows = [];
2285
+ for (const record of records) {
2286
+ if (typeof record !== "object" || record === null) throw new TypeError(`${method} takes records of the values of the columns of table "${table.name}"`);
2287
+ const row = [];
2288
+ for (const key of Object.keys(record)) {
2289
+ const value = record[key];
2290
+ if (value === void 0) continue;
2291
+ let index = columns.indexOf(key);
2292
+ if (index === -1) index = columns.push(key) - 1;
2293
+ row[index] = resolveValue(table, key, value);
2294
+ }
2295
+ rows.push(row);
2296
+ }
2297
+ if (columns.length === 0 && rows.length > 1) {
2298
+ const first = Object.keys(table.columns)[0];
2299
+ if (first !== void 0) columns.push(first);
2300
+ }
2301
+ for (const row of rows) while (row.length < columns.length) row.push(void 0);
2302
+ return {
2303
+ columns,
2304
+ values: rows
2305
+ };
2306
+ }
2307
+ /**
2308
+ * Returns the assignments of an update of the rows of `source` that `set` gives: the values of its columns, or a callback that receives the columns and returns them, read when it is called.
2309
+ *
2310
+ * A value of `undefined` keeps its column, and an update must set at least one column.
2311
+ * It rejects a key that is not a column of the table of `source`, and a query as a value.
2312
+ */
2313
+ function toAssignments(source, set) {
2314
+ const { table } = source;
2315
+ const values = typeof set === "function" ? set(createColumnRefs(source)) : set;
2316
+ if (typeof values !== "object" || values === null) throw new TypeError(`update takes the values of the columns of table "${table.name}" or a callback that returns them`);
2317
+ const assignments = [];
2318
+ for (const key of Object.keys(values)) {
2319
+ const value = values[key];
2320
+ if (value !== void 0) assignments.push(Object.freeze({
2321
+ key,
2322
+ value: resolveValue(table, key, value)
2323
+ }));
2324
+ }
2325
+ if (assignments.length === 0) throw new Error(`update takes the value of at least one column of table "${table.name}"; a column given as undefined keeps its value`);
2326
+ return assignments;
2327
+ }
2328
+ /** Returns the node of `value` of the column of `table` under `key`: an expression, or a parameter encoded with the type of the column. */
2329
+ function resolveValue(table, key, value) {
2330
+ const column = requireColumn(table, key);
2331
+ if (value instanceof SelectQuery || value instanceof RecordQuery || value instanceof MutationQuery || value instanceof SqlQuery) throw new TypeError(`Column "${key}" of table "${table.name}" takes a value or an expression, not a query`);
2332
+ return toValueNode(value, column.type);
2333
+ }
2334
+ // src/query/mutation.ts
2335
+ /**
2336
+ * Immutable query of state `S` that inserts, updates, or deletes rows, unbound or bound to a `Db`.
2337
+ *
2338
+ * Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead.
2339
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
2340
+ * A bound query executes on its `Db` when awaited.
2341
+ */
2342
+ var MutationQuery = class MutationQuery {
2343
+ table;
2344
+ node;
2345
+ context;
2346
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
2347
+ db;
2348
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
2349
+ then;
2350
+ constructor(table, node, context, db) {
2351
+ this.table = table;
2352
+ this.node = node;
2353
+ this.context = context;
2354
+ this.db = db;
2355
+ this.then = db === void 0 ? void 0 : executeOnAwait;
2356
+ Object.freeze(this);
2357
+ }
2358
+ select(...args) {
2359
+ const { node } = this;
2360
+ const { returning } = node;
2361
+ 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");
2362
+ return this.derive({
2363
+ returning: mergeProjections(returning ?? [], node.target, args, this.context),
2364
+ value: false
2365
+ });
2366
+ }
2367
+ get(arg) {
2368
+ if (this.node.rows === "many") throw new Error("get applies only to a query that changes one row, such as of insert or find; use pluck to return the values of several rows");
2369
+ return this.deriveValue(arg, "get");
2370
+ }
2371
+ pluck(arg) {
2372
+ return this.deriveValue(arg, "pluck");
2373
+ }
2374
+ toSQL(options) {
2375
+ return compileToSQL(this, options);
2376
+ }
2377
+ /** Creates a mutation of the same kind and `Db` with the node changes applied. */
2378
+ derive(changes) {
2379
+ return new MutationQuery(this.table, Object.freeze({
2380
+ ...this.node,
2381
+ ...changes
2382
+ }), this.context, this.db);
2383
+ }
2384
+ /** Creates the mutation that returns the value of `arg` of `method`, a column key or a callback that receives the columns and returns an expression, of each changed row. */
2385
+ deriveValue(arg, method) {
2386
+ const { node } = this;
2387
+ return this.derive({
2388
+ returning: [projectValue(node.target, arg, method)],
2389
+ value: true,
2390
+ rows: toValueRows(node.rows)
2391
+ });
2392
+ }
2393
+ };
2394
+ /**
2395
+ * 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`.
2396
+ *
2397
+ * It returns the number of the inserted rows, until a selection returns their fields.
2398
+ */
2399
+ function createInsert(query, records, rows, method) {
2400
+ const { node } = query;
2401
+ if (!isTableQuery(node)) throw new Error(`${method} applies only to a query of a table without clauses, such as filters or selected fields; select the fields that it returns after it`);
2402
+ const { columns, values } = toInsertRows(node.from.table, records, method);
2403
+ return new MutationQuery(query.table, Object.freeze({
2404
+ kind: "insert",
2405
+ target: node.from,
2406
+ columns,
2407
+ values,
2408
+ returning: void 0,
2409
+ rows,
2410
+ value: false
2411
+ }), query.context, query.db);
2412
+ }
2413
+ /** Creates the update of the rows of `query` that `set` gives, as `update` takes it, in the rows mode of the query. */
2414
+ function createUpdate(query, set) {
2415
+ const { node } = query;
2416
+ checkChangedRows(node, "update");
2417
+ return new MutationQuery(query.table, Object.freeze({
2418
+ kind: "update",
2419
+ target: node.from,
2420
+ set: toAssignments(node.from, set),
2421
+ filters: node.filters,
2422
+ returning: void 0,
2423
+ rows: node.rows,
2424
+ value: false
2425
+ }), query.context, query.db);
2426
+ }
2427
+ /** Creates the delete of the rows of `query`, in the rows mode of the query. */
2428
+ function createDelete(query) {
2429
+ const { node } = query;
2430
+ checkChangedRows(node, "delete");
2431
+ return new MutationQuery(query.table, Object.freeze({
2432
+ kind: "delete",
2433
+ target: node.from,
2434
+ filters: node.filters,
2435
+ returning: void 0,
2436
+ rows: node.rows,
2437
+ value: false
2438
+ }), query.context, query.db);
2439
+ }
2440
+ /**
2441
+ * 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.
2442
+ *
2443
+ * A filter simplified to `TRUE`, such as `where({})`, restricts no row.
2444
+ */
2445
+ function checkChangedRows(node, method) {
2446
+ if (node.relation !== void 0) throw new Error(`${method} applies only to a query of a table, not of a relation`);
2447
+ if (node.projections.length > 0) throw new Error(`${method} returns the fields selected after it, not before; call select, get, or pluck after ${method}`);
2448
+ 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`);
2449
+ const predicate = combineFilters(node.filters);
2450
+ 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`);
2451
+ }
2452
+ // src/query/projections.ts
2453
+ /**
2454
+ * Creates the fields of `select` over `source`, appending new keys and replacing existing ones in place.
2455
+ *
2456
+ * `args` are the arguments of `select`: `"*"`, column keys, or a callback that receives the references of `source` with the relations of `context` and returns a selection.
2457
+ */
2458
+ function mergeProjections(projections, source, args, context) {
2459
+ const result = projections.slice();
2460
+ const first = args[0];
2461
+ if (typeof first === "function") addSelection(result, first(createSelectionRefs(source, context)));
2462
+ else {
2463
+ const keys = first === "*" ? Object.keys(source.table.columns) : args;
2464
+ for (const key of keys) setProjection(result, projectColumn(source, key));
2465
+ }
2466
+ return result;
2467
+ }
2468
+ /** Adds the fields of `selection`, expressions and queries by key, to `projections`, replacing existing keys in place. */
2469
+ function addSelection(projections, selection) {
2470
+ for (const key of Reflect.ownKeys(selection)) {
2471
+ if (typeof key === "symbol") throw new TypeError("A selected field must have a string key");
2472
+ setProjection(projections, selectValue(key, selection[key]));
2473
+ }
2474
+ }
2475
+ /**
2476
+ * Creates the projection of the value of `get` or `pluck`, or of the argument of an aggregate method, such as `max`, over `source`.
2477
+ *
2478
+ * `arg` is the argument of `method`: a column key, or a callback that receives the columns and returns an expression.
2479
+ */
2480
+ function projectValue(source, arg, method) {
2481
+ if (typeof arg !== "function") return projectColumn(source, arg);
2482
+ const value = arg(createColumnRefs(source));
2483
+ if (!isExpression(value)) throw new TypeError(`The callback of ${method} must return an expression`);
2484
+ const type = getType(value);
2485
+ if (!type) throw new TypeError(`The expression of ${method} has no type to decode its values; build a sql fragment with a type, such as sql(t.integer)`);
2486
+ return projectExpression("value", value, type);
2487
+ }
2488
+ /**
2489
+ * Creates the projection of the value of `field`, the only projection of a query of values, whose `NULL` `fallback` replaces: a value that the type of the field encodes, or an expression.
2490
+ *
2491
+ * The projection of an aggregate keeps its call, which lowering builds, and adds the fallback after its earlier ones.
2492
+ */
2493
+ function coalesceValue(field, fallback) {
2494
+ if (fallback === null || fallback === void 0) throw new TypeError(`coalesce takes a value other than ${String(fallback)}`);
2495
+ const value = toValueNode(fallback, field.type);
2496
+ if (isAggregateProjection(field)) return addFallback(field, value);
2497
+ return Object.freeze({
2498
+ key: field.key,
2499
+ expression: createList("coalesce(", [field.expression, value], ")"),
2500
+ type: field.type
2501
+ });
2502
+ }
2503
+ /** Creates the field of a value of a selection under `key`: an expression with a type, or a query whose rows become its value. */
2504
+ function selectValue(key, value) {
2505
+ if (value instanceof SelectQuery) return Object.freeze({
2506
+ key,
2507
+ query: value.node,
2508
+ db: value.db
2509
+ });
2510
+ if (value instanceof RecordQuery) throw new TypeError(`Selected field "${key}" is a query of $select, which cannot be nested; select its fields directly instead`);
2511
+ if (value instanceof MutationQuery) throw new TypeError(`Selected field "${key}" is a query of insert, update, or delete, which cannot be nested`);
2512
+ if (value instanceof SqlQuery) throw new TypeError(`Selected field "${key}" is a query of $query, which cannot be nested`);
2513
+ if (!isExpression(value)) throw new TypeError(`Selected field "${key}" must be an expression or a query`);
2514
+ const type = getType(value);
2515
+ if (!type) throw new TypeError(`Selected field "${key}" has no type to decode its values; build a sql fragment with a type, such as sql(t.integer)`);
2516
+ return projectExpression(key, value, type);
2517
+ }
2518
+ /** Creates the projection of a column of the table of `source` under its key. */
2519
+ function projectColumn(source, key) {
2520
+ const { type } = requireColumn(source.table, key);
2521
+ return Object.freeze({
2522
+ key,
2523
+ expression: createNode({
2524
+ kind: "column",
2525
+ source,
2526
+ key
2527
+ }),
2528
+ type
2529
+ });
2530
+ }
2531
+ /** Creates the projection of an expression under `key`, decoded with `type`, the type of the expression. */
2532
+ function projectExpression(key, value, type) {
2533
+ return Object.freeze({
2534
+ key,
2535
+ expression: toNode(value),
2536
+ type
2537
+ });
2538
+ }
2539
+ /** Adds or replaces a field by key, rejecting a key that a record cannot have. */
2540
+ function setProjection(projections, projection) {
2541
+ const { key } = projection;
2542
+ if (!isRecordKey(key)) throw new Error(`Field "${key}" cannot be selected: it is not a valid record key`);
2543
+ for (let index = 0; index < projections.length; index++) if (projections[index].key === key) {
2544
+ projections[index] = projection;
2545
+ return;
2546
+ }
2547
+ projections.push(projection);
2548
+ }
2549
+ // src/query/record.ts
2550
+ /**
2551
+ * Immutable query of `$select` of state `S`, unbound or bound to a `Db`: one record whose fields are the values of expressions and the results of independent queries, selected in one statement.
2552
+ *
2553
+ * An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
2554
+ * A bound query executes on its `Db` when awaited.
2555
+ */
2556
+ var RecordQuery = class {
2557
+ node;
2558
+ /** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
2559
+ db;
2560
+ /** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
2561
+ then;
2562
+ constructor(node, db) {
2563
+ this.node = node;
2564
+ this.db = db;
2565
+ this.then = db === void 0 ? void 0 : executeOnAwait;
2566
+ Object.freeze(this);
2567
+ }
2568
+ toSQL(options) {
2569
+ return compileToSQL(this, options);
2570
+ }
2571
+ };
2572
+ /**
2573
+ * Starts the query of `$select` of `selection`, an object of expressions and queries by key, bound to `db` when given.
2574
+ *
2575
+ * It reads the keys and values of `selection` when it is called.
2576
+ */
2577
+ function startRecordQuery(selection, db) {
2578
+ const projections = [];
2579
+ addSelection(projections, selection);
2580
+ return new RecordQuery(Object.freeze({
2581
+ kind: "record",
2582
+ projections
2583
+ }), db);
2584
+ }
2585
+ // src/query/relations.ts
2586
+ /** Creates the contexts of the queries of the tables under `keys` in a schema of relations `relations`, by table key. */
2587
+ function createQueryContexts(keys, relations) {
2588
+ const contexts = Object.create(null);
2589
+ for (const key of keys) {
2590
+ const named = relations[key];
2591
+ if (named === void 0) {
2592
+ contexts[key] = noContext;
2593
+ continue;
2594
+ }
2595
+ const getters = Object.create(null);
2596
+ for (const name of Object.keys(named)) {
2597
+ const definition = named[name];
2598
+ getters[name] = Object.freeze({
2599
+ get() {
2600
+ return startRelated(this, definition, contexts[definition.targetKey]);
2601
+ },
2602
+ enumerable: true
2603
+ });
2604
+ }
2605
+ contexts[key] = Object.freeze({ relations: Object.freeze(getters) });
2606
+ }
2607
+ return Object.freeze(contexts);
2608
+ }
2609
+ /**
2610
+ * Starts the query of the records of relation `definition` of the row of `parent`, the references of `select`, in the context of the target table.
2611
+ *
2612
+ * The relation filter compares the key columns of the target with those of `parent` with SQL `=` directly rather than with the `eq` operators of their types, which a custom type can replace.
2613
+ */
2614
+ function startRelated(parent, definition, context) {
2615
+ const { target, from, to } = definition;
2616
+ const source = Object.freeze({
2617
+ kind: "table",
2618
+ table: target
2619
+ });
2620
+ const conditions = [];
2621
+ for (let index = 0; index < from.length; index++) conditions.push(createNode({
2622
+ kind: "comparison",
2623
+ operator: "=",
2624
+ left: createNode({
2625
+ kind: "column",
2626
+ source,
2627
+ key: to[index]
2628
+ }),
2629
+ right: toNode(parent[from[index]])
2630
+ }));
2631
+ return new SelectQuery(target, createQueryNode(source, definition, Object.freeze({ relation: combineNodes("and", conditions) })), context);
2632
+ }
2633
+ // src/schema/schema.ts
2634
+ const schemaBrand = Symbol("kern-orm.schema");
2635
+ /** Key of the relation definitions of a schema, which composition reads. */
2636
+ const schemaRelations = Symbol("kern-orm.schema.relations");
2637
+ /**
2638
+ * Defines a schema of the tables of `parts`, keyed by their names in queries.
2639
+ *
2640
+ * A part is an object of tables by their keys or another schema, whose tables and relations the new schema includes as they are, so queries built from that schema run on the new one.
2641
+ * A key of two different tables, a table under two keys, and two different definitions of a relation of a table are rejected; the same table under the same key or the same relation in several parts is one.
2642
+ */
2643
+ function defineSchema(...parts) {
2644
+ const tables = /* @__PURE__ */ new Map();
2645
+ const keys = /* @__PURE__ */ new Map();
2646
+ const relations = /* @__PURE__ */ new Map();
2647
+ for (const part of parts) {
2648
+ const partTables = isSchema(part) ? part.$tables : part;
2649
+ for (const key of Object.keys(partTables)) {
2650
+ if (key.startsWith("$")) throw new Error(`Table key "${key}" must not start with "$"`);
2651
+ const table = partTables[key];
2652
+ const keyTable = tables.get(key);
2653
+ if (keyTable !== void 0 && keyTable !== table) throw new Error(`Table key "${key}" refers to two different tables`);
2654
+ const tableKey = keys.get(table);
2655
+ if (tableKey !== void 0 && tableKey !== key) throw new Error(`Table "${table.name}" is included under two keys, "${tableKey}" and "${key}"`);
2656
+ tables.set(key, table);
2657
+ keys.set(table, key);
2658
+ }
2659
+ if (isSchema(part)) addRelations(relations, part[schemaRelations]);
2660
+ }
2661
+ return createSchema(Object.freeze(Object.fromEntries(tables)), keys, freezeRelations(relations));
2662
+ }
2663
+ /** Creates a schema of tables and relation definitions that are already checked; `keys` gives the key of each table. */
2664
+ function createSchema(tables, keys, relations) {
2665
+ const methods = {
2666
+ [schemaBrand]: true,
2667
+ $tables: tables,
2668
+ [schemaRelations]: relations,
2669
+ $relations(declarations) {
2670
+ const added = /* @__PURE__ */ new Map();
2671
+ addRelations(added, relations);
2672
+ for (const key of Object.keys(declarations)) {
2673
+ if (!Object.hasOwn(tables, key)) throw new Error(`Relations are declared for table key "${key}", which is not part of the schema`);
2674
+ const named = declarations[key];
2675
+ if (named === void 0) continue;
2676
+ for (const name of Object.keys(named)) addRelation(added, key, name, defineRelation(tables[key], key, name, named[name], (table) => keys.get(table)));
2677
+ }
2678
+ return createSchema(tables, keys, freezeRelations(added));
2679
+ },
2680
+ $select: (selection) => startRecordQuery(selection)
2681
+ };
2682
+ const contexts = createQueryContexts(Object.keys(tables), relations);
2683
+ return defineEntries(methods, tables, (key) => startQuery(tables[key], contexts[key]));
2684
+ }
2685
+ function isSchema(part) {
2686
+ return schemaBrand in part;
2687
+ }
2688
+ /** Adds a getter per table key to `methods` that starts a query with `start`, and freezes the result. */
2689
+ function defineEntries(methods, tables, start) {
2690
+ const result = Object.defineProperties(methods, Object.fromEntries(Object.keys(tables).map((key) => [key, {
2691
+ get: () => start(key),
2692
+ enumerable: true
2693
+ }])));
2694
+ return Object.freeze(result);
2695
+ }
2696
+ // src/expression/sql.ts
2697
+ function sql(first, ...values) {
2698
+ if (isTemplateStrings(first)) return createFragment(first, values, void 0);
2699
+ if (!isType(first)) throw new TypeError("sql() accepts a type, not a column");
2700
+ return (strings, ...values) => createFragment(strings, values, first);
2701
+ }
2702
+ function param(type, value) {
2703
+ if (!isType(type) && !isExpression(type)) throw new TypeError("param() accepts a type or an expression, not a column");
2704
+ if (isExpression(type)) {
2705
+ if (isExpression(value)) return value;
2706
+ const valueType = getType(type);
2707
+ return toExpression(toValueNode(value, valueType), valueType);
2708
+ }
2709
+ const node = toValueNode(value, type);
2710
+ return toExpression(node.kind === "param" ? createNode({
2711
+ kind: "cast",
2712
+ operand: node,
2713
+ type
2714
+ }) : node, type);
2715
+ }
2716
+ function isTemplateStrings(value) {
2717
+ return Array.isArray(value);
2718
+ }
2719
+ function createFragment(strings, values, type) {
2720
+ return toExpression(toRawSqlNode(strings, values), type);
2721
+ }
2722
+ /**
2723
+ * Creates the node of the SQL of a template: interpolated expressions keep their nodes, a query of a table without clauses becomes the name of the table, qualified by the PostgreSQL schema of the statement, and other values become query parameters.
2724
+ *
2725
+ * It rejects other queries, which a parameter would encode as text.
2726
+ */
2727
+ function toRawSqlNode(strings, values) {
2728
+ const nodes = [];
2729
+ for (let index = 0; index < values.length; index++) nodes.push(toInterpolatedNode(values[index]));
2730
+ return createNode({
2731
+ kind: "raw",
2732
+ fragments: [...strings],
2733
+ values: nodes
2734
+ });
2735
+ }
2736
+ /** Returns the node of a value interpolated into SQL, as `toRawSqlNode` takes it. */
2737
+ function toInterpolatedNode(value) {
2738
+ if (value instanceof SelectQuery) {
2739
+ if (!isTableQuery(value.node)) throw new TypeError("sql takes a query of a table without clauses, such as db.form, as the name of the table, not a query with clauses");
2740
+ return createNode({
2741
+ kind: "tableName",
2742
+ table: value.table,
2743
+ db: value.db
2744
+ });
2745
+ }
2746
+ if (value instanceof RecordQuery || value instanceof MutationQuery || value instanceof SqlQuery) throw new TypeError("sql takes a query of a table without clauses, such as db.form, as the name of the table, not another query");
2747
+ return toValueNode(value);
2748
+ }
2749
+ // src/execution/db.ts
2750
+ /** Binds `schema` to `database`; see `Database.bind`. */
2751
+ function bindSchema(schema, database, options = {}) {
2752
+ const tables = new Set(Object.values(schema.$tables));
2753
+ const relations = schema[schemaRelations];
2754
+ const definitions = collectDefinitions(relations);
2755
+ const { schemaName } = options;
2756
+ const resolveSchemaName = () => typeof schemaName === "function" ? schemaName() : schemaName;
2757
+ function compile(query) {
2758
+ if (query.db !== void 0 && query.db !== db) throw new Error("Cannot run a query bound to another Db");
2759
+ return compileStatement(lowerStatement(query.node, definitions, db), { schemaName: resolveSchemaName() }, tables, db);
2760
+ }
2761
+ const methods = {
2762
+ $schema: schema,
2763
+ $database: database,
2764
+ get $schemaName() {
2765
+ return resolveSchemaName();
2766
+ },
2767
+ $compile(query) {
2768
+ const { text, parameters } = compile(query);
2769
+ return createStatement(text, parameters);
2770
+ },
2771
+ async $execute(query) {
2772
+ const compiled = compile(query);
2773
+ return decodeStatement(compiled, await database.execute(compiled));
2774
+ },
2775
+ $select: (selection) => startRecordQuery(selection, db),
2776
+ $query: (strings, ...values) => startSqlQuery(toRawSqlNode(strings, values), db),
2777
+ async $script(script, ...values) {
2778
+ if (typeof script === "string") return database.script(script);
2779
+ const { text, parameters } = compile(startSqlQuery(toRawSqlNode(script, values), db));
2780
+ if (parameters.length > 0) throw new Error("A script takes no values, since it has no parameters; interpolate only tables and sql fragments without values");
2781
+ return database.script(text);
2782
+ },
2783
+ $transaction: (callback, options) => database.transaction(callback, options)
2784
+ };
2785
+ const contexts = createQueryContexts(Object.keys(schema.$tables), relations);
2786
+ const db = defineEntries(methods, schema.$tables, (key) => bindQuery(startQuery(schema.$tables[key], contexts[key]), db));
2787
+ return db;
2788
+ }
2789
+ // src/execution/transaction.ts
2790
+ /**
2791
+ * Routes statements and scripts to the ambient transaction of the current async context or to the pool.
2792
+ *
2793
+ * This is the only place that decides which connection executes a statement.
2794
+ */
2795
+ var TransactionCoordinator = class {
2796
+ driver;
2797
+ test;
2798
+ #storage = new AsyncLocalStorage();
2799
+ /** Open test fixtures, the innermost last. */
2800
+ #fixtures = [];
2801
+ /** Changes of the fixture stack, run one after another so that each one sees the stack the previous one left. */
2802
+ #transitions = Promise.resolve();
2803
+ /**
2804
+ * 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.
2805
+ *
2806
+ * 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.
2807
+ * Closing the stack therefore calls these first: each one tells its opening to stop waiting for the seed.
2808
+ */
2809
+ #openings = /* @__PURE__ */ new Set();
2810
+ /**
2811
+ * Outermost fixture in the stack whose closing is queued but has not finished.
2812
+ *
2813
+ * 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.
2814
+ */
2815
+ #closing;
2816
+ /** Closing of the database, set by the first `close`; from then on, operations outside a transaction reject. */
2817
+ #closed;
2818
+ constructor(driver, test = false) {
2819
+ this.driver = driver;
2820
+ this.test = test;
2821
+ }
2822
+ execute(statement) {
2823
+ const target = this.#route("execute a query");
2824
+ return target instanceof Error ? Promise.reject(target) : target.execute(statement);
2825
+ }
2826
+ /** Executes a script of statements without parameters where `execute` executes a statement. */
2827
+ executeScript(text) {
2828
+ const target = this.#route("execute a script");
2829
+ return target instanceof Error ? Promise.reject(target) : target.executeScript(text);
2830
+ }
2831
+ /** Returns the connection of the ambient transaction or the driver of the pool that runs `operation`, or the error that rejects it. */
2832
+ #route(operation) {
2833
+ const level = this.#storage.getStore();
2834
+ if (!level) {
2835
+ if (this.#closed) return createDatabaseClosedError(operation);
2836
+ return this.test ? new Error(describeOutsideTest(operation)) : this.driver;
2837
+ }
2838
+ return createUnavailableError(level, operation) ?? level.connection;
2839
+ }
2840
+ /**
2841
+ * Runs `callback` in a transaction that commits when it resolves and rolls back when it rejects, with the settings of `options`.
2842
+ *
2843
+ * Inside a transaction, it runs `callback` in a savepoint nested in it, which restores the settings it changed when it ends.
2844
+ * A failed cleanup after an error rejects with a `SuppressedError` that keeps the original error in its `suppressed` chain.
2845
+ */
2846
+ transaction(callback, options) {
2847
+ const settings = getLevelSettings(options);
2848
+ const parent = this.#storage.getStore();
2849
+ if (parent) return this.#runNested(parent, callback, true, void 0, settings);
2850
+ if (this.#closed) return Promise.reject(createDatabaseClosedError("start a transaction"));
2851
+ return this.test ? Promise.reject(new Error(describeOutsideTest("start a transaction"))) : this.#runRoot(callback, true, void 0, settings);
2852
+ }
2853
+ /**
2854
+ * Runs `callback` in a transaction that always rolls back, on a coordinator created for tests.
2855
+ *
2856
+ * Inside a transaction, it runs `callback` in a savepoint nested in it that always rolls back.
2857
+ * When `signal` aborts, the level stops accepting statements at once and ends without waiting for `callback`.
2858
+ * Once the level ends, the transaction rejects with the reason of the signal.
2859
+ * A failure to start or end the level after the abort suppresses the reason in a `SuppressedError`.
2860
+ * 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`.
2861
+ */
2862
+ testTransaction(callback, { signal } = {}) {
2863
+ if (!this.test) return Promise.reject(/* @__PURE__ */ new Error("testTransaction requires a database created with test: true"));
2864
+ if (signal?.aborted) return Promise.reject(signal.reason);
2865
+ const parent = this.#storage.getStore();
2866
+ if (parent) return this.#runNested(parent, callback, false, signal);
2867
+ if (this.#closed) return Promise.reject(createDatabaseClosedError("start a test transaction"));
2868
+ return this.#startTestLevel(signal).then((level) => level ? this.#runStarted(level, callback, false, signal) : this.#runRoot(callback, false, signal));
2869
+ }
2870
+ /**
2871
+ * Opens a test fixture: a transaction on a reserved connection, or a savepoint in the innermost open fixture, and runs `seed` in it.
2872
+ *
2873
+ * Test transactions started outside any transaction run in the innermost fixture.
2874
+ * A fixture whose `seed` rejects rolls back and closes.
2875
+ */
2876
+ createTestFixture(seed) {
2877
+ return this.startTestFixture(seed).fixture;
2878
+ }
2879
+ /**
2880
+ * Starts opening a test fixture, see `createTestFixture`, and returns it with a `close` that can be called before it opens.
2881
+ *
2882
+ * 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.
2883
+ * Closing an open fixture also closes the fixtures opening in it.
2884
+ */
2885
+ startTestFixture(seed) {
2886
+ let level;
2887
+ let closeRequested = false;
2888
+ const closing = Promise.withResolvers();
2889
+ let closedRejection;
2890
+ const close = () => {
2891
+ if (this.#storage.getStore()) return Promise.reject(/* @__PURE__ */ new Error("Cannot close a test fixture inside a transaction"));
2892
+ closeRequested = true;
2893
+ closing.resolve();
2894
+ if (level && this.#fixtures.includes(level)) {
2895
+ const opened = level;
2896
+ if (this.#closing && this.#closing.depth <= opened.depth) return this.#enqueue(() => this.#closeFixture(opened));
2897
+ this.#closing = opened;
2898
+ return this.#closeAfterOpenings(() => this.#enqueue(async () => {
2899
+ try {
2900
+ await this.#closeFixture(opened);
2901
+ } finally {
2902
+ if (this.#closing === opened) this.#closing = void 0;
2903
+ }
2904
+ }));
2905
+ }
2906
+ return this.#enqueue(() => {
2907
+ const rejection = closedRejection;
2908
+ closedRejection = void 0;
2909
+ if (rejection) throw rejection.error;
2910
+ });
2911
+ };
2912
+ if (!this.test) return {
2913
+ fixture: Promise.reject(/* @__PURE__ */ new Error("createTestFixture requires a database created with test: true")),
2914
+ close
2915
+ };
2916
+ if (this.#storage.getStore()) return {
2917
+ fixture: Promise.reject(/* @__PURE__ */ new Error("Cannot create a test fixture inside a transaction")),
2918
+ close
2919
+ };
2920
+ if (this.#closed) return {
2921
+ fixture: Promise.reject(createDatabaseClosedError("create a test fixture")),
2922
+ close
2923
+ };
2924
+ /**
2925
+ * Runs stages 2 and 3 of the fixture and puts it in the stack, returning `undefined` when closing was requested and the fixture rolled back cleanly.
2926
+ *
2927
+ * It rejects with a failure to start the fixture, with the rejection of `seed`, or with a failure to roll back, which suppresses the rejection of `seed`.
2928
+ */
2929
+ const open = async () => {
2930
+ if (closeRequested) return;
2931
+ const parent = this.#fixtures.at(-1);
2932
+ const started = parent ? await this.#startInFixture(parent) : await this.#beginFixture();
2933
+ started.state = "open";
2934
+ const outcome = closeRequested ? void 0 : await Promise.race([this.#seedFixture(started, seed), closing.promise]);
2935
+ if (outcome && !outcome.rejection && !closeRequested) {
2936
+ this.#fixtures.push(started);
2937
+ level = started;
2938
+ this.#openings.delete(close);
2939
+ const { result } = outcome;
2940
+ return {
2941
+ get data() {
2942
+ if (started.state !== "open") throw new Error("Test fixture is closed");
2943
+ return result;
2944
+ },
2945
+ close,
2946
+ [Symbol.asyncDispose]: close
2947
+ };
2948
+ }
2949
+ const rejection = combineRejections(outcome?.rejection, { rejection: await this.#endFixture(started) });
2950
+ if (rejection) throw rejection.error;
2951
+ };
2952
+ this.#openings.add(close);
2953
+ return {
2954
+ fixture: this.#enqueue(async () => {
2955
+ let opened;
2956
+ try {
2957
+ opened = await open();
2958
+ } catch (error) {
2959
+ if (!closeRequested) throw error;
2960
+ closedRejection = { error };
2961
+ } finally {
2962
+ this.#openings.delete(close);
2963
+ }
2964
+ if (!opened) throw new Error("Test fixture was closed before it opened");
2965
+ return opened;
2966
+ }),
2967
+ close
2968
+ };
2969
+ }
2970
+ /**
2971
+ * Closes the test fixtures, including those still opening, and then the driver, which waits for the running transactions to end.
2972
+ *
2973
+ * A driver waits for every reserved connection, so closing it under an open fixture would wait forever.
2974
+ * A failed closing of the driver suppresses the failures of closing the fixtures.
2975
+ * 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.
2976
+ */
2977
+ close() {
2978
+ if (this.#storage.getStore()) return Promise.reject(/* @__PURE__ */ new Error("Cannot close the database inside a transaction"));
2979
+ this.#closed ??= this.#close();
2980
+ return this.#closed;
2981
+ }
2982
+ /** Closes the test fixtures and then the driver, see `close`. */
2983
+ async #close() {
2984
+ let rejection;
2985
+ try {
2986
+ await this.#closeAfterOpenings(() => this.#enqueue(() => {
2987
+ const root = this.#fixtures[0];
2988
+ return root && this.#closeFixture(root);
2989
+ }));
2990
+ } catch (error) {
2991
+ rejection = { error };
2992
+ }
2993
+ try {
2994
+ await this.driver.close();
2995
+ } catch (error) {
2996
+ rejection = suppress(error, rejection, "Closing the driver failed");
2997
+ }
2998
+ if (rejection) throw rejection.error;
2999
+ }
3000
+ /**
3001
+ * Closes the fixtures still opening and runs `closeStack`, rejecting with the failures of all of them.
3002
+ *
3003
+ * A seed that never settles holds the queue of the fixture stack, so closing is requested for every opening before `closeStack` queues its change, and the rollback does not wait for the seeds.
3004
+ */
3005
+ async #closeAfterOpenings(closeStack) {
3006
+ const closings = [];
3007
+ for (const closeOpening of this.#openings) closings.push(closeOpening());
3008
+ closings.push(closeStack());
3009
+ let rejection;
3010
+ for (const closing of await Promise.allSettled(closings)) if (closing.status === "rejected") rejection = suppress(closing.reason, rejection, "Closing a test fixture failed");
3011
+ if (rejection) throw rejection.error;
3012
+ }
3013
+ /**
3014
+ * Runs `seed` in a savepoint of a fixture that is released when it resolves, returning its result or rejection.
3015
+ *
3016
+ * The savepoint has its own context, so late code of `seed` cannot reach the fixture after it ends.
3017
+ */
3018
+ async #seedFixture(fixture, seed) {
3019
+ try {
3020
+ return await this.#run(await this.#startNested(fixture), seed, true);
3021
+ } catch (error) {
3022
+ return { rejection: { error } };
3023
+ }
3024
+ }
3025
+ /** Closes an opened fixture as a change of the fixture stack. */
3026
+ async #closeFixture(fixture) {
3027
+ const index = this.#fixtures.indexOf(fixture);
3028
+ if (index < 0) return;
3029
+ let rejection;
3030
+ try {
3031
+ rejection = await this.#endFixture(fixture);
3032
+ } finally {
3033
+ this.#fixtures.length = index;
3034
+ }
3035
+ if (rejection) throw rejection.error;
3036
+ }
3037
+ /** Rolls back a fixture and releases the connection of the first one, returning the error to reject with. */
3038
+ async #endFixture(fixture) {
3039
+ const cleanup = await this.#end(fixture, false);
3040
+ return fixture.parent ? cleanup.rejection : releaseConnection(fixture.connection, cleanup.failure, cleanup.rejection);
3041
+ }
3042
+ /**
3043
+ * 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.
3044
+ *
3045
+ * 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.
3046
+ * From its turn on, it settles with its change.
3047
+ */
3048
+ #startTestLevel(signal) {
3049
+ let waiting = true;
3050
+ const start = () => this.#enqueue(() => {
3051
+ if (signal?.aborted) return;
3052
+ waiting = false;
3053
+ const fixture = this.#fixtures.at(-1);
3054
+ return fixture && this.#startInFixture(fixture, signal);
3055
+ });
3056
+ return signal ? settleUnlessAborted(start, signal, () => waiting) : start();
3057
+ }
3058
+ /** Runs a change of the fixture stack after the earlier ones. */
3059
+ #enqueue(transition) {
3060
+ const result = this.#transitions.then(transition);
3061
+ this.#transitions = result.catch(() => {});
3062
+ return result;
3063
+ }
3064
+ /** Starts the first test fixture: a transaction on a reserved connection. */
3065
+ async #beginFixture() {
3066
+ const connection = await this.driver.acquire();
3067
+ try {
3068
+ await connection.execute(beginStatement);
3069
+ } catch (error) {
3070
+ throw (await releaseConnection(connection, { error }, { error })).error;
3071
+ }
3072
+ return createLevel(connection, void 0);
3073
+ }
3074
+ /**
3075
+ * Starts a nested level of a test fixture, preempting its active one.
3076
+ *
3077
+ * A fixture runs one nested level at a time, so a new one ends the previous one, such as a test that timed out.
3078
+ * 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.
3079
+ */
3080
+ async #startInFixture(fixture, signal) {
3081
+ if (fixture.child) {
3082
+ const cleanup = await this.#end(fixture.child, false, "preemption");
3083
+ 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);
3084
+ }
3085
+ const unavailable = createUnavailableError(fixture, "start a level of the test fixture");
3086
+ if (unavailable) throw suppressAbortReason(unavailable, signal);
3087
+ signal?.throwIfAborted();
3088
+ return this.#startNested(fixture, signal);
3089
+ }
3090
+ async #runRoot(callback, commits, signal, settings) {
3091
+ const connection = await (signal ? acquireUnlessAborted(this.driver, signal) : this.driver.acquire());
3092
+ if (signal?.aborted) throw (await releaseConnection(connection, void 0, { error: signal.reason })).error;
3093
+ const level = createLevel(connection, void 0);
3094
+ let outcome;
3095
+ try {
3096
+ await connection.execute(beginStatement);
3097
+ } catch (error) {
3098
+ level.state = "closed";
3099
+ outcome = {
3100
+ rejection: { error: suppressAbortReason(error, signal) },
3101
+ failure: { error }
3102
+ };
3103
+ }
3104
+ if (!outcome && settings) try {
3105
+ await applySettings(level, settings);
3106
+ } catch (error) {
3107
+ outcome = await getEndedOutcome(this.#end(level, false), error);
3108
+ }
3109
+ outcome ??= await this.#run(level, callback, commits, signal);
3110
+ const rejection = await releaseConnection(connection, outcome.failure, outcome.rejection);
3111
+ if (rejection) throw rejection.error;
3112
+ return outcome.result;
3113
+ }
3114
+ async #runNested(parent, callback, commits, signal, settings) {
3115
+ const unavailable = createUnavailableError(parent, "start a nested transaction");
3116
+ if (unavailable) throw unavailable;
3117
+ return this.#runStarted(await this.#startNested(parent, signal, settings), callback, commits, signal);
3118
+ }
3119
+ /**
3120
+ * Reserves a nested level of `parent`, sends its `SAVEPOINT`, and applies its `settings`, rejecting when one of them fails.
3121
+ *
3122
+ * A level whose settings fail rolls back to its savepoint first.
3123
+ * The failure suppresses the reason of `signal` when the signal aborted before it.
3124
+ */
3125
+ async #startNested(parent, signal, settings) {
3126
+ const level = createLevel(parent.connection, parent);
3127
+ parent.child = level;
3128
+ try {
3129
+ await level.connection.execute(createStatement(`SAVEPOINT ${getSavepointName(level)}`));
3130
+ } catch (error) {
3131
+ if (!level.cleanup) {
3132
+ closeStarting(level);
3133
+ throw suppressAbortReason(error, signal);
3134
+ }
3135
+ throw suppressAbortReason(combineRejections({ error }, await level.cleanup).error, signal);
3136
+ }
3137
+ if (settings) try {
3138
+ await applySettings(level, settings);
3139
+ } catch (error) {
3140
+ throw suppressAbortReason(combineRejections({ error }, await this.#end(level, false)).error, signal);
3141
+ }
3142
+ return level;
3143
+ }
3144
+ /** Runs `callback` in a started level, returning its result or throwing its rejection. */
3145
+ async #runStarted(level, callback, commits, signal) {
3146
+ const { result, rejection } = await this.#run(level, callback, commits, signal);
3147
+ if (rejection) throw rejection.error;
3148
+ return result;
3149
+ }
3150
+ /**
3151
+ * Runs `callback` in the context of a started `level`, then ends the level.
3152
+ *
3153
+ * A level that `commits` commits only when the callback resolves with no nested level running and no nested level that failed to end.
3154
+ * 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.
3155
+ */
3156
+ async #run(level, callback, commits, signal) {
3157
+ if (level.cleanup) return getEndedOutcome(level.cleanup, createClosedError(level, void 0));
3158
+ let result;
3159
+ let rejection;
3160
+ if (signal?.aborted) this.#end(level, false, "abort");
3161
+ else {
3162
+ level.state = "open";
3163
+ try {
3164
+ result = await (signal ? settleUnlessAborted(() => this.#storage.run(level, callback), signal, () => {
3165
+ this.#end(level, false, "abort");
3166
+ return true;
3167
+ }) : this.#storage.run(level, callback));
3168
+ } catch (error) {
3169
+ rejection = { error };
3170
+ }
3171
+ }
3172
+ if (level.cleanup) return getEndedOutcome(level.cleanup, level.endedBy === "abort" ? signal?.reason : createClosedError(level, rejection));
3173
+ if (!rejection && level.child) rejection = { error: /* @__PURE__ */ new Error("Transaction was rolled back: a nested transaction was still running when its callback finished") };
3174
+ if (!rejection && level.rollbackOnly) rejection = { error: new Error("Transaction was rolled back: a nested transaction failed to end", { cause: level.rollbackOnly.error }) };
3175
+ const cleanup = await this.#end(level, commits && !rejection);
3176
+ return {
3177
+ result,
3178
+ rejection: combineRejections(rejection, cleanup),
3179
+ failure: cleanup.failure
3180
+ };
3181
+ }
3182
+ /**
3183
+ * Ends `level` once, whoever ends it: later calls return the cleanup already started.
3184
+ *
3185
+ * 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.
3186
+ */
3187
+ #end(level, commit, endedBy) {
3188
+ if (level.cleanup) return level.cleanup;
3189
+ level.endedBy = endedBy;
3190
+ level.state = "closing";
3191
+ const nested = level.child && this.#end(level.child, false, "enclosing level");
3192
+ level.cleanup = this.#cleanUp(level, commit, nested);
3193
+ return level.cleanup;
3194
+ }
3195
+ async #cleanUp(level, commit, nested) {
3196
+ const nestedCleanup = await nested;
3197
+ const { parent } = level;
3198
+ const cleanup = parent ? await endSavepoint(level, commit && !level.rollbackOnly) : await endTransaction(level.connection, commit);
3199
+ level.state = "closed";
3200
+ if (parent) {
3201
+ if (parent.child === level) parent.child = void 0;
3202
+ parent.rollbackOnly ??= cleanup.rejection;
3203
+ }
3204
+ return {
3205
+ rejection: combineRejections(nestedCleanup?.rejection, cleanup),
3206
+ failure: cleanup.failure
3207
+ };
3208
+ }
3209
+ };
3210
+ const beginStatement = createStatement("BEGIN");
3211
+ const commitStatement = createStatement("COMMIT");
3212
+ const rollbackStatement = createStatement("ROLLBACK");
3213
+ function createLevel(connection, parent) {
3214
+ return {
3215
+ connection,
3216
+ parent,
3217
+ depth: parent ? parent.depth + 1 : 0,
3218
+ state: "starting",
3219
+ child: void 0,
3220
+ rollbackOnly: void 0,
3221
+ cleanup: void 0,
3222
+ endedBy: void 0,
3223
+ restore: void 0
3224
+ };
3225
+ }
3226
+ /** Settings of a level of `transaction` with `options`, or `undefined` when it has none. */
3227
+ function getLevelSettings(options) {
3228
+ return options?.searchPath ? [{
3229
+ name: "search_path",
3230
+ value: options.searchPath.map(quoteIdentifier).join(", ")
3231
+ }] : void 0;
3232
+ }
3233
+ /**
3234
+ * Applies `settings` to a level whose `BEGIN` or `SAVEPOINT` completed, unless its cleanup has started.
3235
+ *
3236
+ * 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.
3237
+ */
3238
+ async function applySettings(level, settings) {
3239
+ if (level.cleanup) return;
3240
+ if (level.parent) {
3241
+ let text = "SELECT";
3242
+ const names = [];
3243
+ for (const { name } of settings) {
3244
+ names.push(name);
3245
+ text += `${names.length > 1 ? "," : ""} current_setting($${names.length})`;
3246
+ }
3247
+ const values = (await level.connection.execute(createStatement(text, names))).rows[0];
3248
+ level.restore = createSettingStatement(settings.map(({ name }, index) => ({
3249
+ name,
3250
+ value: values[index]
3251
+ })));
3252
+ if (level.cleanup) return;
3253
+ }
3254
+ await level.connection.execute(createSettingStatement(settings));
3255
+ }
3256
+ /** Creates the statement that sets `settings` until the transaction ends or rolls back to an earlier savepoint, as `SET LOCAL` does. */
3257
+ function createSettingStatement(settings) {
3258
+ let text = "SELECT";
3259
+ const parameters = [];
3260
+ for (const { name, value } of settings) {
3261
+ parameters.push(name, value);
3262
+ text += `${parameters.length > 2 ? "," : ""} set_config($${parameters.length - 1}, $${parameters.length}, true)`;
3263
+ }
3264
+ return createStatement(text, parameters);
3265
+ }
3266
+ /** Name of the savepoint of a nested level; a level has at most one nested level, so the depth makes it unique. */
3267
+ function getSavepointName(level) {
3268
+ return `kern_${level.depth}`;
3269
+ }
3270
+ /**
3271
+ * Creates the error of `operation` on a level that rejects statements and nested levels, or returns `undefined` when it accepts them.
3272
+ *
3273
+ * A level that can only roll back keeps the failure of its nested level as the cause.
3274
+ */
3275
+ function createUnavailableError(level, operation) {
3276
+ if (level.state !== "open") return /* @__PURE__ */ new Error(`Cannot ${operation}: its transaction is already finished`);
3277
+ if (level.child) return /* @__PURE__ */ new Error(`Cannot ${operation}: a nested transaction is running; await it first`);
3278
+ 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 });
3279
+ }
3280
+ /** Error message of an operation outside a test transaction on a coordinator created for tests. */
3281
+ function describeOutsideTest(operation) {
3282
+ return `Cannot ${operation} outside a test transaction: the database was created with test: true, so wrap the test in testTransaction`;
3283
+ }
3284
+ /** Error of `operation` started outside a transaction after closing the database was requested. */
3285
+ function createDatabaseClosedError(operation) {
3286
+ return /* @__PURE__ */ new Error(`Cannot ${operation}: the database is closed`);
3287
+ }
3288
+ /** Closes a nested level whose `SAVEPOINT` failed, freeing its parent for other statements. */
3289
+ function closeStarting(level) {
3290
+ level.state = "closed";
3291
+ if (level.parent?.child === level) level.parent.child = void 0;
3292
+ }
3293
+ /** Error of a level that another level ended, keeping the rejection of its callback as the cause. */
3294
+ function createClosedError(level, rejection) {
3295
+ 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 });
3296
+ }
3297
+ /** Error of a failure to start a test transaction, which suppresses the reason of `signal` when the signal aborted before the failure. */
3298
+ function suppressAbortReason(error, signal) {
3299
+ return signal?.aborted ? suppress(error, { error: signal.reason }, "Starting the test transaction failed").error : error;
3300
+ }
3301
+ /** Outcome of a level that something other than its callback ended: a rejection with `error`, which a failed cleanup suppresses. */
3302
+ async function getEndedOutcome(cleanup, error) {
3303
+ const ended = await cleanup;
3304
+ return {
3305
+ rejection: combineRejections({ error }, ended),
3306
+ failure: ended.failure
3307
+ };
3308
+ }
3309
+ /**
3310
+ * 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`.
3311
+ *
3312
+ * 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.
3313
+ * 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.
3314
+ */
3315
+ function settleUnlessAborted(start, signal, abort, discard) {
3316
+ const settled = Promise.withResolvers();
3317
+ let abandoned = false;
3318
+ const onAbort = () => {
3319
+ if (abort()) {
3320
+ abandoned = true;
3321
+ settled.reject(signal.reason);
3322
+ }
3323
+ };
3324
+ signal.addEventListener("abort", onAbort, { once: true });
3325
+ let running;
3326
+ try {
3327
+ running = start();
3328
+ } catch (error) {
3329
+ signal.removeEventListener("abort", onAbort);
3330
+ settled.reject(error);
3331
+ return settled.promise;
3332
+ }
3333
+ running.then((value) => {
3334
+ signal.removeEventListener("abort", onAbort);
3335
+ if (abandoned) discard?.(value);
3336
+ else settled.resolve(value);
3337
+ }, (error) => {
3338
+ signal.removeEventListener("abort", onAbort);
3339
+ settled.reject(error);
3340
+ });
3341
+ return settled.promise;
3342
+ }
3343
+ /**
3344
+ * Acquires a connection for a test transaction, rejecting with the reason of `signal` when it aborts first.
3345
+ *
3346
+ * 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.
3347
+ */
3348
+ function acquireUnlessAborted(driver, signal) {
3349
+ if (signal.aborted) return Promise.reject(signal.reason);
3350
+ return settleUnlessAborted(() => driver.acquire(), signal, () => true, (connection) => {
3351
+ Promise.resolve().then(() => connection.release()).catch(() => {});
3352
+ });
3353
+ }
3354
+ /** Returns the connection of a transaction to the driver, keeping a failed release as a rejection that suppresses `rejection`. */
3355
+ async function releaseConnection(connection, failure, rejection) {
3356
+ try {
3357
+ await connection.release(failure);
3358
+ return rejection;
3359
+ } catch (error) {
3360
+ return suppress(error, rejection, "Releasing the transaction connection failed");
3361
+ }
3362
+ }
3363
+ /** Ends a transaction with `COMMIT` or `ROLLBACK`. */
3364
+ async function endTransaction(connection, commit) {
3365
+ try {
3366
+ const { command } = await connection.execute(commit ? commitStatement : rollbackStatement);
3367
+ if (commit && command !== "COMMIT") return { rejection: { error: /* @__PURE__ */ new Error("Transaction was rolled back: a statement in it failed") } };
3368
+ return {};
3369
+ } catch (error) {
3370
+ return {
3371
+ rejection: { error },
3372
+ failure: { error }
3373
+ };
3374
+ }
3375
+ }
3376
+ /**
3377
+ * Ends the savepoint of a nested level, releasing it on commit and rolling back to it otherwise.
3378
+ *
3379
+ * Before a release, it restores the settings that the level changed; a rollback restores them itself.
3380
+ */
3381
+ async function endSavepoint(level, commit) {
3382
+ const name = getSavepointName(level);
3383
+ try {
3384
+ if (!commit) await level.connection.execute(createStatement(`ROLLBACK TO SAVEPOINT ${name}`));
3385
+ else if (level.restore) await level.connection.execute(level.restore);
3386
+ await level.connection.execute(createStatement(`RELEASE SAVEPOINT ${name}`));
3387
+ return {};
3388
+ } catch (error) {
3389
+ return { rejection: { error } };
3390
+ }
3391
+ }
3392
+ /** Rejection with the error of a cleanup, which suppresses the `earlier` rejection if there is one. */
3393
+ function combineRejections(earlier, cleanup) {
3394
+ return cleanup.rejection ? suppress(cleanup.rejection.error, earlier, "Transaction rollback failed") : earlier;
3395
+ }
3396
+ /** Rejection with `error`, which suppresses the `earlier` rejection if there is one. */
3397
+ function suppress(error, earlier, message) {
3398
+ return { error: earlier ? new SuppressedError(error, earlier.error, message) : error };
3399
+ }
3400
+ // src/execution/database.ts
3401
+ /** Creates a database over a driver; its transactions are shared by every schema bound to it. */
3402
+ function createDatabase({ driver, test }) {
3403
+ const coordinator = new TransactionCoordinator(driver, test);
3404
+ let tablelessDb;
3405
+ const getTablelessDb = () => tablelessDb ??= bindSchema(defineSchema(), database);
3406
+ const database = {
3407
+ coordinator,
3408
+ bind: (schema, options) => bindSchema(schema, database, options),
3409
+ query: (strings, ...values) => getTablelessDb().$query(strings, ...values),
3410
+ script: (script, ...values) => typeof script === "string" ? coordinator.executeScript(script) : getTablelessDb().$script(script, ...values),
3411
+ execute: (statement) => coordinator.execute(statement),
3412
+ transaction: (callback, options) => coordinator.transaction(callback, options),
3413
+ close: () => coordinator.close(),
3414
+ [Symbol.asyncDispose]: () => coordinator.close()
3415
+ };
3416
+ return database;
3417
+ }
3418
+ // src/query/helper.ts
3419
+ function defineHelper(_table, helper) {
3420
+ return (query, ...args) => requireDerived(query, helper(query, ...args), "The callback of a helper");
3421
+ }
3422
+ export { NotFoundError, RequiredRelationError, ResultDecodeError, and, asc, compare, createDatabase, createStatement, defineFilter, defineGenericOperator, defineHelper, defineSchema, defineTable, defineType, desc, equalityOperators, from, many, not, one, or, orderBy, orderingOperators, param, sql, textOperators };