kern-orm 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/database-CP4oapsQ.mjs +4693 -0
- package/dist/{index--0tyG7sU.d.mts → index-CoKpXcBp.d.mts} +1347 -703
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +87 -3961
- package/dist/testing.d.mts +28 -2
- package/dist/testing.mjs +530 -1
- package/dist/{text-BTFErHIi.mjs → text-Cti9QLK7.mjs} +7 -1
- package/dist/types-DfoL8Oi9.mjs +248 -0
- package/dist/types.d.mts +49 -49
- package/dist/types.mjs +2 -247
- package/package.json +3 -1
|
@@ -0,0 +1,4693 @@
|
|
|
1
|
+
import { B as noOrder, C as toNode, D as isType, E as defineType, F as createNode, H as oneNode, I as createSelectNode, L as falseNode, M as valuesQueryNode, O as Column, P as createList, R as noFilters, S as toFunctionOperandNode, T as getBooleanType, U as trueNode, V as noProjections, _ as isOperandSource, a as stringifyJson, b as toCastValueNode, d as orderingOperators, g as isExpression, h as getType, j as isEqualityCompatible, m as createIsNullNode, n as text, p as compareNodes, s as encodeBytea, v as operandNode, w as toValueNode, x as toExpression, y as toBooleanExpression, z as noJoins } from "./text-Cti9QLK7.mjs";
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
// src/ast/boolean.ts
|
|
5
|
+
/** Combines predicate nodes with `AND` or `OR`, flattening nested groups of the same kind. */
|
|
6
|
+
function combineNodes(kind, operands) {
|
|
7
|
+
const neutral = kind === "and";
|
|
8
|
+
const flat = [];
|
|
9
|
+
for (const operand of operands) if (operand.kind === "boolean") {
|
|
10
|
+
if (operand.value !== neutral) return operand;
|
|
11
|
+
} else if (operand.kind === kind) flat.push(...operand.operands);
|
|
12
|
+
else flat.push(operand);
|
|
13
|
+
if (flat.length === 0) return neutral ? trueNode : falseNode;
|
|
14
|
+
return flat.length === 1 ? flat[0] : createNode({
|
|
15
|
+
kind,
|
|
16
|
+
operands: flat
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/** Negates a predicate node, simplifying constants and double negation. */
|
|
20
|
+
function negateNode(operand) {
|
|
21
|
+
if (operand.kind === "boolean") return operand.value ? falseNode : trueNode;
|
|
22
|
+
if (operand.kind === "not") return operand.operand;
|
|
23
|
+
return createNode({
|
|
24
|
+
kind: "not",
|
|
25
|
+
operand
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Combines the filters of a query into its effective predicate, `relation AND scope AND user`, which is `TRUE` when they restrict no row. */
|
|
29
|
+
function combineFilters(filters) {
|
|
30
|
+
const operands = [];
|
|
31
|
+
if (filters.relation !== void 0) operands.push(filters.relation);
|
|
32
|
+
if (filters.scope !== void 0) operands.push(filters.scope);
|
|
33
|
+
if (filters.user !== void 0) operands.push(filters.user);
|
|
34
|
+
return combineNodes("and", operands);
|
|
35
|
+
}
|
|
36
|
+
// src/expression/predicates.ts
|
|
37
|
+
/** Converts a condition operand into a node: a query nests in it, and an object of column values stays unresolved until `where`; it rejects any other value. */
|
|
38
|
+
function toConditionNode(operand) {
|
|
39
|
+
if (isOperandSource(operand)) return operand[operandNode]();
|
|
40
|
+
if (!isColumnValues(operand)) throw new TypeError("A condition must be an expression, such as TRUE or FALSE, a query of one Boolean value, or an object of column values");
|
|
41
|
+
return createNode({
|
|
42
|
+
kind: "values",
|
|
43
|
+
values: operand
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/** Tells whether `value` can be an object of column values: a plain object, of this or another realm, or an object that has keys. */
|
|
47
|
+
function isColumnValues(value) {
|
|
48
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
49
|
+
const prototype = Object.getPrototypeOf(value);
|
|
50
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null || Object.keys(value).length > 0;
|
|
51
|
+
}
|
|
52
|
+
function and(...operands) {
|
|
53
|
+
return combineConditions("and", operands);
|
|
54
|
+
}
|
|
55
|
+
function or(...operands) {
|
|
56
|
+
return combineConditions("or", operands);
|
|
57
|
+
}
|
|
58
|
+
function not(operand) {
|
|
59
|
+
return toBooleanExpression(negateNode(toConditionNode(operand)));
|
|
60
|
+
}
|
|
61
|
+
function combineConditions(kind, operands) {
|
|
62
|
+
const nodes = [];
|
|
63
|
+
for (const operand of operands) nodes.push(toConditionNode(operand));
|
|
64
|
+
return toBooleanExpression(combineNodes(kind, nodes));
|
|
65
|
+
}
|
|
66
|
+
// src/query/literal.ts
|
|
67
|
+
/**
|
|
68
|
+
* Field of a selection whose value is `T`, made by `literal`.
|
|
69
|
+
*
|
|
70
|
+
* It is not an expression: it has no SQL, so only a selection takes it.
|
|
71
|
+
*/
|
|
72
|
+
var Literal = class {
|
|
73
|
+
literal;
|
|
74
|
+
constructor(literal) {
|
|
75
|
+
this.literal = literal;
|
|
76
|
+
Object.freeze(this);
|
|
77
|
+
}
|
|
78
|
+
/** Rejects the literal as an operand of an expression: a statement has no SQL of it. */
|
|
79
|
+
[operandNode]() {
|
|
80
|
+
throw new TypeError("A literal is only a selected field and has no SQL; pass a value to an expression through param");
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Creates a field of a selection with `value` in every record, without selecting anything in SQL: the query returns the value itself, not a copy of it, whatever it is.
|
|
85
|
+
*
|
|
86
|
+
* It lets a branch of a selection skip a column or a nested query, such as `withHint ? field.hint : literal(null)`.
|
|
87
|
+
* To use a value in SQL, such as in a condition, pass it through `param` instead.
|
|
88
|
+
*/
|
|
89
|
+
function literal(value) {
|
|
90
|
+
return new Literal(value);
|
|
91
|
+
}
|
|
92
|
+
// src/query/exists.ts
|
|
93
|
+
let existsProjection;
|
|
94
|
+
/** Returns the projection of whether a query has a row, the only projection of a query made by `exists`. */
|
|
95
|
+
function getExistsProjection() {
|
|
96
|
+
existsProjection ??= Object.freeze({
|
|
97
|
+
key: "exists",
|
|
98
|
+
expression: trueNode,
|
|
99
|
+
type: getBooleanType()
|
|
100
|
+
});
|
|
101
|
+
return existsProjection;
|
|
102
|
+
}
|
|
103
|
+
/** Tells whether `node` is a query of `exists`, whose value is whether the rows that its filters, limit, and offset choose exist. */
|
|
104
|
+
function isExistsQuery(node) {
|
|
105
|
+
return node.value && isExistsProjection(node.projections[0]);
|
|
106
|
+
}
|
|
107
|
+
/** Tells whether a selected field is the projection of `exists`, which only `exists` selects. */
|
|
108
|
+
function isExistsProjection(field) {
|
|
109
|
+
return field === existsProjection;
|
|
110
|
+
}
|
|
111
|
+
// src/query/aggregate.ts
|
|
112
|
+
/** Type of a count: a `bigint` of PostgreSQL decoded as a number, rejecting a count that a number cannot hold exactly. */
|
|
113
|
+
const countType = /* @__PURE__ */ defineType({ sqlType: "bigint" }).transform({
|
|
114
|
+
decode: (text) => decodeSafeInteger(text, "Count"),
|
|
115
|
+
encode: (value) => String(value)
|
|
116
|
+
}).withOperators(orderingOperators);
|
|
117
|
+
/** Types of the sums of the values of `smallint` and `integer` types, by the type of the values, created once for each. */
|
|
118
|
+
const sumTypes = /* @__PURE__ */ new WeakMap();
|
|
119
|
+
const noFallbacks = /* @__PURE__ */ Object.freeze([]);
|
|
120
|
+
/** Definitions of the aggregate methods that take a column or an expression. */
|
|
121
|
+
const aggregateDefinitions = /* @__PURE__ */ Object.freeze({
|
|
122
|
+
count: {
|
|
123
|
+
name: "count",
|
|
124
|
+
distinct: false,
|
|
125
|
+
ordered: false,
|
|
126
|
+
type: toCountType
|
|
127
|
+
},
|
|
128
|
+
countDistinct: {
|
|
129
|
+
name: "count",
|
|
130
|
+
distinct: true,
|
|
131
|
+
ordered: false,
|
|
132
|
+
type: toCountType
|
|
133
|
+
},
|
|
134
|
+
min: {
|
|
135
|
+
name: "min",
|
|
136
|
+
distinct: false,
|
|
137
|
+
ordered: false,
|
|
138
|
+
type: toArgumentType
|
|
139
|
+
},
|
|
140
|
+
max: {
|
|
141
|
+
name: "max",
|
|
142
|
+
distinct: false,
|
|
143
|
+
ordered: false,
|
|
144
|
+
type: toArgumentType
|
|
145
|
+
},
|
|
146
|
+
sum: {
|
|
147
|
+
name: "sum",
|
|
148
|
+
distinct: false,
|
|
149
|
+
ordered: false,
|
|
150
|
+
type: toSumType
|
|
151
|
+
},
|
|
152
|
+
avg: {
|
|
153
|
+
name: "avg",
|
|
154
|
+
distinct: false,
|
|
155
|
+
ordered: false,
|
|
156
|
+
type: toAverageType
|
|
157
|
+
},
|
|
158
|
+
every: {
|
|
159
|
+
name: "bool_and",
|
|
160
|
+
distinct: false,
|
|
161
|
+
ordered: false,
|
|
162
|
+
type: toArgumentType
|
|
163
|
+
},
|
|
164
|
+
some: {
|
|
165
|
+
name: "bool_or",
|
|
166
|
+
distinct: false,
|
|
167
|
+
ordered: false,
|
|
168
|
+
type: toArgumentType
|
|
169
|
+
},
|
|
170
|
+
stringAgg: {
|
|
171
|
+
name: "string_agg",
|
|
172
|
+
distinct: false,
|
|
173
|
+
ordered: true,
|
|
174
|
+
type: toArgumentType
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
/** Argument `*` of `count(*)`. */
|
|
178
|
+
const allRowsNode = /* @__PURE__ */ createNode({
|
|
179
|
+
kind: "raw",
|
|
180
|
+
fragments: ["*"],
|
|
181
|
+
values: []
|
|
182
|
+
});
|
|
183
|
+
/** Projection of `count(*)`, which `count` without an argument selects; its value does not depend on the values or the order of the rows. */
|
|
184
|
+
const countProjection = /* @__PURE__ */ Object.freeze({
|
|
185
|
+
key: "count",
|
|
186
|
+
expression: /* @__PURE__ */ createNode({
|
|
187
|
+
kind: "aggregate",
|
|
188
|
+
name: "count",
|
|
189
|
+
distinct: false,
|
|
190
|
+
arguments: [allRowsNode],
|
|
191
|
+
orderBy: noOrder,
|
|
192
|
+
filter: void 0
|
|
193
|
+
}),
|
|
194
|
+
type: countType,
|
|
195
|
+
ordered: false,
|
|
196
|
+
fallbacks: noFallbacks
|
|
197
|
+
});
|
|
198
|
+
/**
|
|
199
|
+
* Creates the projection of the aggregate of `method` over the values of `argument`, the projection of a column or an expression of each row.
|
|
200
|
+
*
|
|
201
|
+
* `delimiter` is the delimiter of `stringAgg`, sent as a parameter.
|
|
202
|
+
*/
|
|
203
|
+
function projectAggregate(method, argument, delimiter) {
|
|
204
|
+
return Object.freeze({
|
|
205
|
+
key: method,
|
|
206
|
+
expression: createAggregateCall(method, argument.expression, delimiter),
|
|
207
|
+
type: toAggregateType(method, argument.type),
|
|
208
|
+
ordered: aggregateDefinitions[method].ordered,
|
|
209
|
+
fallbacks: noFallbacks
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Creates the call of the aggregate function of `method` over the values of `argument`.
|
|
214
|
+
*
|
|
215
|
+
* `delimiter` is the delimiter of `stringAgg`, sent as a parameter, `orderBy` the order of the rows that the function takes, and `filter` their condition.
|
|
216
|
+
*/
|
|
217
|
+
function createAggregateCall(method, argument, delimiter, orderBy = noOrder, filter) {
|
|
218
|
+
const definition = aggregateDefinitions[method];
|
|
219
|
+
const args = [argument];
|
|
220
|
+
if (delimiter !== void 0) args.push(createNode({
|
|
221
|
+
kind: "param",
|
|
222
|
+
value: delimiter,
|
|
223
|
+
type: void 0
|
|
224
|
+
}));
|
|
225
|
+
return createNode({
|
|
226
|
+
kind: "aggregate",
|
|
227
|
+
name: definition.name,
|
|
228
|
+
distinct: definition.distinct,
|
|
229
|
+
arguments: args,
|
|
230
|
+
orderBy,
|
|
231
|
+
filter
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
/** Creates the call of `count(*)` over the rows that `filter` takes. */
|
|
235
|
+
function createCountCall(filter) {
|
|
236
|
+
return createNode({
|
|
237
|
+
kind: "aggregate",
|
|
238
|
+
name: "count",
|
|
239
|
+
distinct: false,
|
|
240
|
+
arguments: [allRowsNode],
|
|
241
|
+
orderBy: noOrder,
|
|
242
|
+
filter
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/** Returns the type that decodes the value of the aggregate of `method` over the values of type `argument`, rejecting what `method` cannot decode, such as `avg` of a type of the SQL type `bigint`. */
|
|
246
|
+
function toAggregateType(method, argument) {
|
|
247
|
+
return aggregateDefinitions[method].type(argument);
|
|
248
|
+
}
|
|
249
|
+
/** Creates the projection of the aggregate of `field` whose `NULL` `fallback` replaces after its earlier fallbacks. */
|
|
250
|
+
function addFallback(field, fallback) {
|
|
251
|
+
const fallbacks = field.fallbacks.slice();
|
|
252
|
+
fallbacks.push(fallback);
|
|
253
|
+
return Object.freeze({
|
|
254
|
+
key: field.key,
|
|
255
|
+
expression: field.expression,
|
|
256
|
+
type: field.type,
|
|
257
|
+
ordered: field.ordered,
|
|
258
|
+
fallbacks
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
/** Tells whether `node` is an aggregate query, whose value is the aggregate over the rows that its filters, limit, and offset choose. */
|
|
262
|
+
function isAggregateQuery(node) {
|
|
263
|
+
return node.value && isAggregateProjection(node.projections[0]);
|
|
264
|
+
}
|
|
265
|
+
/** Tells whether `node`, a nested query, is selected as its value rather than as packed rows: an aggregate query as a scalar subquery of its statement, and a query of `exists` as `EXISTS` of its rows, unless `map` or `transform` converts its value. */
|
|
266
|
+
function isSelectedAsValue(node) {
|
|
267
|
+
return node.conversion === void 0 && (isAggregateQuery(node) || isExistsQuery(node));
|
|
268
|
+
}
|
|
269
|
+
/** Tells whether a selected field is the projection of an aggregate, which only the aggregate methods select. */
|
|
270
|
+
function isAggregateProjection(field) {
|
|
271
|
+
return "ordered" in field;
|
|
272
|
+
}
|
|
273
|
+
function toCountType() {
|
|
274
|
+
return countType;
|
|
275
|
+
}
|
|
276
|
+
function toArgumentType(argument) {
|
|
277
|
+
return argument;
|
|
278
|
+
}
|
|
279
|
+
/** Returns the type of the sum of the values of type `argument`: for `smallint` and `integer` values, a `bigint` with the operators of `argument` that rejects a sum that a number cannot hold exactly, and `argument` for others. */
|
|
280
|
+
function toSumType(argument) {
|
|
281
|
+
if (argument.castType !== "smallint" && argument.castType !== "integer") return argument;
|
|
282
|
+
let type = sumTypes.get(argument);
|
|
283
|
+
if (type === void 0) {
|
|
284
|
+
type = defineType({ sqlType: "bigint" }).transform({
|
|
285
|
+
decode: (text) => {
|
|
286
|
+
decodeSafeInteger(text, "Sum");
|
|
287
|
+
return argument.decode(text);
|
|
288
|
+
},
|
|
289
|
+
encode: (value) => argument.encode(value)
|
|
290
|
+
}).withOperators(argument.operators);
|
|
291
|
+
sumTypes.set(argument, type);
|
|
292
|
+
}
|
|
293
|
+
return type;
|
|
294
|
+
}
|
|
295
|
+
/** 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`. */
|
|
296
|
+
function toAverageType(argument) {
|
|
297
|
+
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");
|
|
298
|
+
return argument;
|
|
299
|
+
}
|
|
300
|
+
/** Decodes `text` of a `bigint` as a number, rejecting one that a number cannot hold exactly; `subject` names it in the error. */
|
|
301
|
+
function decodeSafeInteger(text, subject) {
|
|
302
|
+
const number = Number(text);
|
|
303
|
+
if (!Number.isSafeInteger(number)) throw new RangeError(`${subject} ${text} is outside the safe integer range of numbers`);
|
|
304
|
+
return number;
|
|
305
|
+
}
|
|
306
|
+
// src/query/column-refs.ts
|
|
307
|
+
/** Context of a query whose table has no relations, such as one of `from(table)`. */
|
|
308
|
+
const noContext = /* @__PURE__ */ Object.freeze({ relations: /* @__PURE__ */ Object.freeze({}) });
|
|
309
|
+
/** Creates the references of the callbacks of queries over `source`: expressions of its columns, each with the type of its column, and the relations of `context`. */
|
|
310
|
+
function createSelectionRefs(source, context) {
|
|
311
|
+
const refs = {};
|
|
312
|
+
const { columns } = source.table;
|
|
313
|
+
for (const key of Object.keys(columns)) refs[key] = toExpression(createNode({
|
|
314
|
+
kind: "column",
|
|
315
|
+
source,
|
|
316
|
+
key
|
|
317
|
+
}), columns[key].type);
|
|
318
|
+
return Object.defineProperties(refs, context.relations);
|
|
319
|
+
}
|
|
320
|
+
// src/ast/projections.ts
|
|
321
|
+
/**
|
|
322
|
+
* Returns the position of the projection that has the value of `expression`, such as a sort expression or a key of a group: a projection of the same value, as `isSameValue` tells, or `-1`.
|
|
323
|
+
*/
|
|
324
|
+
function findValueProjection(projections, expression) {
|
|
325
|
+
return projections.findIndex((projection) => isSameValue(projection.expression, expression));
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Tells whether `left` and `right` are sure to have the same value: they are the same column of the same source or the same expression node.
|
|
329
|
+
*
|
|
330
|
+
* Only the same node or column guarantees one value: PostgreSQL may or may not evaluate equal expressions built apart once, and gives each its own parameters.
|
|
331
|
+
*/
|
|
332
|
+
function isSameValue(left, right) {
|
|
333
|
+
return left.kind === "column" && right.kind === "column" ? left.source === right.source && left.key === right.key : left === right;
|
|
334
|
+
}
|
|
335
|
+
// src/result/result.ts
|
|
336
|
+
/** Error thrown when a query of one row finds no row, executed or nested, unless a required relation guarantees the row. */
|
|
337
|
+
var NotFoundError = class extends Error {
|
|
338
|
+
name = "NotFoundError";
|
|
339
|
+
/** 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. */
|
|
340
|
+
path;
|
|
341
|
+
constructor(message, path) {
|
|
342
|
+
super(message);
|
|
343
|
+
this.path = path;
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
/**
|
|
347
|
+
* Error thrown when a required relation, such as `field.form`, has no record for a row.
|
|
348
|
+
*
|
|
349
|
+
* 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.
|
|
350
|
+
*/
|
|
351
|
+
var RequiredRelationError = class extends Error {
|
|
352
|
+
relation;
|
|
353
|
+
path;
|
|
354
|
+
name = "RequiredRelationError";
|
|
355
|
+
constructor(relation, path) {
|
|
356
|
+
super(`Required relation "${relation}" has no record for result field "${path}"`);
|
|
357
|
+
this.relation = relation;
|
|
358
|
+
this.path = path;
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
/** Error thrown when a row does not match the result fields, a value fails to decode, or a callback of `transform` or `map` fails; the failure is its cause. */
|
|
362
|
+
var ResultDecodeError = class extends Error {
|
|
363
|
+
path;
|
|
364
|
+
name = "ResultDecodeError";
|
|
365
|
+
constructor(message, path, options) {
|
|
366
|
+
super(message, options);
|
|
367
|
+
this.path = path;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
/** 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. */
|
|
371
|
+
function isRecordKey(key) {
|
|
372
|
+
return key !== "__proto__";
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* 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.
|
|
376
|
+
*
|
|
377
|
+
* A statement of one row that returns its number or a record without fields rejects as a query of one row does: with `NotFoundError` without a row, unless it is optional or nullable, and with several rows.
|
|
378
|
+
*/
|
|
379
|
+
function decodeStatement(plan, result) {
|
|
380
|
+
const { counted, conversion } = plan;
|
|
381
|
+
if (counted === void 0) return decodeResult(plan, plan.named ? selectColumns(plan, result) : result.rows);
|
|
382
|
+
const decoded = decodeCount(plan, counted, result.count);
|
|
383
|
+
return conversion === void 0 ? decoded : convertTopResult(plan, conversion, decoded, counted === "records" && plan.rows !== "many" && result.count === 0);
|
|
384
|
+
}
|
|
385
|
+
/** Returns what a statement resolves to by `count`, the number of the rows of its command tag, as `counted` tells: the number, or as many records without fields. */
|
|
386
|
+
function decodeCount(plan, counted, count) {
|
|
387
|
+
if (plan.rows !== "many") {
|
|
388
|
+
if (count > 1) throw new Error(plan.named ? `Query of one row reported ${count} rows` : `Query of one row changed ${count} rows`);
|
|
389
|
+
if (count === 0) {
|
|
390
|
+
if (plan.rows === "one") throw new NotFoundError(plan.named ? "Query reported no rows" : "Query found no row to change");
|
|
391
|
+
if (counted === "records") return decodeMissing(plan);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (counted === "number") return count;
|
|
395
|
+
if (plan.rows !== "many") return createRecord(plan);
|
|
396
|
+
const records = [];
|
|
397
|
+
for (let index = 0; index < count; index++) records.push(createRecord(plan));
|
|
398
|
+
return records;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* 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.
|
|
402
|
+
*
|
|
403
|
+
* 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.
|
|
404
|
+
*/
|
|
405
|
+
function selectColumns(plan, result) {
|
|
406
|
+
const { columns, rows } = result;
|
|
407
|
+
if (plan.value) {
|
|
408
|
+
if (columns.length !== 1) throw new ResultDecodeError(`Statement returned ${columns.length} columns for one value`, void 0);
|
|
409
|
+
return rows;
|
|
410
|
+
}
|
|
411
|
+
const { fields } = plan;
|
|
412
|
+
const indexes = [];
|
|
413
|
+
let ordered = fields.length === columns.length;
|
|
414
|
+
for (let index = 0; index < fields.length; index++) {
|
|
415
|
+
const { key } = fields[index];
|
|
416
|
+
const column = columns.indexOf(key);
|
|
417
|
+
if (column === -1) throw new ResultDecodeError(`Statement returned no column "${key}"`, void 0);
|
|
418
|
+
if (columns.indexOf(key, column + 1) !== -1) throw new ResultDecodeError(`Statement returned column "${key}" more than once`, void 0);
|
|
419
|
+
indexes.push(column);
|
|
420
|
+
ordered &&= column === index;
|
|
421
|
+
}
|
|
422
|
+
if (ordered) return rows;
|
|
423
|
+
const selected = [];
|
|
424
|
+
for (let row = 0; row < rows.length; row++) {
|
|
425
|
+
const values = [];
|
|
426
|
+
for (let index = 0; index < indexes.length; index++) values.push(rows[row][indexes[index]]);
|
|
427
|
+
selected.push(values);
|
|
428
|
+
}
|
|
429
|
+
return selected;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Decodes driver rows into the result of a query by its result plan, and converts the result as its conversion tells.
|
|
433
|
+
*
|
|
434
|
+
* It rejects a row whose values do not match the result fields, and names the path of the value that fails to decode from its result field, such as `fields[2].label`, after the index of the row of rows `many`, such as `[2].fields[2].label`.
|
|
435
|
+
*/
|
|
436
|
+
function decodeResult(plan, rows) {
|
|
437
|
+
const result = decodeRows(plan, rows);
|
|
438
|
+
const { conversion } = plan;
|
|
439
|
+
return conversion === void 0 ? result : convertTopResult(plan, conversion, result, rows.length === 0);
|
|
440
|
+
}
|
|
441
|
+
/** Converts `result`, which `plan` decoded for a statement rather than for nested rows, as `convertResult` does, rejecting with the error of the statement. */
|
|
442
|
+
function convertTopResult(plan, conversion, result, missing) {
|
|
443
|
+
try {
|
|
444
|
+
return convertResult(plan, conversion, result, missing);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
throw error instanceof NestedFailure ? createRowError("", error) : new ResultDecodeError(`Cannot convert the result${describeCause(error)}`, void 0, { cause: error });
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Converts `result`, which `plan` decoded, by `conversion`.
|
|
451
|
+
*
|
|
452
|
+
* It tells a missing row by `missing` rather than by the value, since a row may decode to `null` or `undefined`.
|
|
453
|
+
* A failure of `map` of rows `many` is a `NestedFailure` of the index of its row; any other failure is the error of the callback, which the enclosing field adds its path to.
|
|
454
|
+
*/
|
|
455
|
+
function convertResult(plan, conversion, result, missing) {
|
|
456
|
+
const { map, transform } = conversion;
|
|
457
|
+
let converted = result;
|
|
458
|
+
if (map !== void 0) {
|
|
459
|
+
if (plan.rows === "many") {
|
|
460
|
+
const rows = result;
|
|
461
|
+
let index = 0;
|
|
462
|
+
try {
|
|
463
|
+
for (; index < rows.length; index++) rows[index] = map(rows[index]);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
throw new NestedFailure(`[${index}]`, error);
|
|
466
|
+
}
|
|
467
|
+
} else if (!missing) converted = map(result);
|
|
468
|
+
}
|
|
469
|
+
return transform === void 0 ? converted : transform(converted);
|
|
470
|
+
}
|
|
471
|
+
/** Decodes driver rows into the result of a query before its conversion: an array of rows `many`, one row, or the result of a missing row. */
|
|
472
|
+
function decodeRows(plan, rows) {
|
|
473
|
+
if (plan.rows === "many") {
|
|
474
|
+
const results = [];
|
|
475
|
+
let index = 0;
|
|
476
|
+
try {
|
|
477
|
+
for (; index < rows.length; index++) results.push(decodeRow(plan, rows[index], false));
|
|
478
|
+
} catch (error) {
|
|
479
|
+
throw createRowError(`[${index}].`, error);
|
|
480
|
+
}
|
|
481
|
+
return results;
|
|
482
|
+
}
|
|
483
|
+
if (rows.length > 1) throw new Error(`Query of one row returned ${rows.length} rows`);
|
|
484
|
+
const row = rows[0];
|
|
485
|
+
if (row === void 0) {
|
|
486
|
+
if (plan.rows === "one") throw new NotFoundError("Query returned no rows");
|
|
487
|
+
return decodeMissing(plan);
|
|
488
|
+
}
|
|
489
|
+
try {
|
|
490
|
+
return decodeRow(plan, row, false);
|
|
491
|
+
} catch (error) {
|
|
492
|
+
throw createRowError("", error);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
/** Returns the result of a query of rows `nullable` or `optional` without a row: `null` or `undefined`. */
|
|
496
|
+
function decodeMissing(plan) {
|
|
497
|
+
return plan.rows === "nullable" ? null : void 0;
|
|
498
|
+
}
|
|
499
|
+
/** Missing row of nested rows `one`, which the query turns into its error once the path is known. */
|
|
500
|
+
var MissingRow = class extends Error {
|
|
501
|
+
guaranteedBy;
|
|
502
|
+
constructor(guaranteedBy) {
|
|
503
|
+
super();
|
|
504
|
+
this.guaranteedBy = guaranteedBy;
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
/**
|
|
508
|
+
* 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.
|
|
509
|
+
*
|
|
510
|
+
* Every enclosing level adds its own part of the path, and the query turns it into its error.
|
|
511
|
+
*/
|
|
512
|
+
var NestedFailure = class extends Error {
|
|
513
|
+
path;
|
|
514
|
+
cause;
|
|
515
|
+
constructor(path, cause) {
|
|
516
|
+
super();
|
|
517
|
+
this.path = path;
|
|
518
|
+
this.cause = cause;
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
/** Adds `segment` before the path of a failure inside a row. */
|
|
522
|
+
function prefixPath(segment, error) {
|
|
523
|
+
return error instanceof NestedFailure ? new NestedFailure(segment + error.path, error.cause) : new NestedFailure(segment, error);
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* 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.
|
|
527
|
+
*
|
|
528
|
+
* A missing row keeps its class wherever it is nested, so it is never reported as a decoding failure.
|
|
529
|
+
* A row of another width than the result fields is already the error of the query.
|
|
530
|
+
*/
|
|
531
|
+
function createRowError(prefix, error) {
|
|
532
|
+
if (!(error instanceof NestedFailure)) return error;
|
|
533
|
+
const path = prefix + error.path;
|
|
534
|
+
const { cause } = error;
|
|
535
|
+
if (cause instanceof MissingRow) return cause.guaranteedBy === void 0 ? new NotFoundError(`Nested query of result field "${path}" returned no rows`, path) : new RequiredRelationError(cause.guaranteedBy, path);
|
|
536
|
+
return new ResultDecodeError(`Cannot decode result field "${path}"${describeCause(cause)}`, path, { cause });
|
|
537
|
+
}
|
|
538
|
+
/** Describes the failure `cause` at the end of the message of an error. */
|
|
539
|
+
function describeCause(cause) {
|
|
540
|
+
return cause instanceof Error ? `: ${cause.message}` : "";
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Decodes a row into a record keyed by the result fields, or into the value of its only field.
|
|
544
|
+
*
|
|
545
|
+
* A row of the driver holds text and `null`; a packed row of nested rows holds parsed JSON.
|
|
546
|
+
*/
|
|
547
|
+
function decodeRow(plan, row, packed) {
|
|
548
|
+
const { fields } = plan;
|
|
549
|
+
if (row.length !== fields.length) {
|
|
550
|
+
if (packed) throw new Error(`Nested row of ${row.length} values for ${fields.length} result fields`);
|
|
551
|
+
throw new ResultDecodeError(`Driver returned a row of ${row.length} values for ${fields.length} result fields`, void 0);
|
|
552
|
+
}
|
|
553
|
+
let index = 0;
|
|
554
|
+
try {
|
|
555
|
+
if (plan.value) return packed ? decodePackedValue(fields[0], row[0]) : decodeDriverValue(fields[0], row[0]);
|
|
556
|
+
const record = createRecord(plan);
|
|
557
|
+
for (; index < fields.length; index++) {
|
|
558
|
+
const field = fields[index];
|
|
559
|
+
record[field.key] = packed ? decodePackedValue(field, row[index]) : decodeDriverValue(field, row[index]);
|
|
560
|
+
}
|
|
561
|
+
return record;
|
|
562
|
+
} catch (error) {
|
|
563
|
+
const { key } = fields[index];
|
|
564
|
+
throw prefixPath(packed ? `.${key}` : key, error);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
/** Creates a record of `plan` before the values of a row are assigned: empty, or with the fields of its template. */
|
|
568
|
+
function createRecord(plan) {
|
|
569
|
+
const record = {};
|
|
570
|
+
const { recordTemplate } = plan;
|
|
571
|
+
if (recordTemplate !== void 0) for (let index = 0; index < recordTemplate.length; index++) {
|
|
572
|
+
const { key, value } = recordTemplate[index];
|
|
573
|
+
record[key] = value;
|
|
574
|
+
}
|
|
575
|
+
return record;
|
|
576
|
+
}
|
|
577
|
+
/** 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. */
|
|
578
|
+
function decodeDriverValue(field, value) {
|
|
579
|
+
if (value === void 0) throw new Error("Driver returned no value");
|
|
580
|
+
if (field.nested !== void 0) return decodeNested(field.nested, value === null ? null : JSON.parse(value));
|
|
581
|
+
return value === null ? null : field.type.decode(value);
|
|
582
|
+
}
|
|
583
|
+
/** 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. */
|
|
584
|
+
function decodePackedValue(field, value) {
|
|
585
|
+
if (field.nested !== void 0) return decodeNested(field.nested, value);
|
|
586
|
+
if (value === null) return null;
|
|
587
|
+
if (typeof value !== "string") throw new TypeError(`Nested value must be text, not ${describeJson(value)}`);
|
|
588
|
+
return field.type.decode(value);
|
|
589
|
+
}
|
|
590
|
+
/** Decodes the rows of a nested query from JSON, as `decodeNestedRows` does, and converts them as the conversion of `plan` tells. */
|
|
591
|
+
function decodeNested(plan, json) {
|
|
592
|
+
const result = decodeNestedRows(plan, json);
|
|
593
|
+
const { conversion } = plan;
|
|
594
|
+
return conversion === void 0 ? result : convertResult(plan, conversion, result, json === null);
|
|
595
|
+
}
|
|
596
|
+
/** Decodes the rows of a nested query from JSON: an array of packed rows for rows `many`, and a packed row or `null` otherwise. */
|
|
597
|
+
function decodeNestedRows(plan, json) {
|
|
598
|
+
if (plan.rows === "many") {
|
|
599
|
+
if (!Array.isArray(json)) throw new TypeError(`Nested rows must be an array, not ${describeJson(json)}`);
|
|
600
|
+
const results = [];
|
|
601
|
+
let index = 0;
|
|
602
|
+
try {
|
|
603
|
+
for (; index < json.length; index++) results.push(decodePackedRow(plan, json[index]));
|
|
604
|
+
} catch (error) {
|
|
605
|
+
throw prefixPath(`[${index}]`, error);
|
|
606
|
+
}
|
|
607
|
+
return results;
|
|
608
|
+
}
|
|
609
|
+
if (json === null) {
|
|
610
|
+
if (plan.rows === "one") throw new MissingRow(plan.guaranteedBy);
|
|
611
|
+
return decodeMissing(plan);
|
|
612
|
+
}
|
|
613
|
+
return decodePackedRow(plan, json);
|
|
614
|
+
}
|
|
615
|
+
/** Decodes a packed row, which must be an array. */
|
|
616
|
+
function decodePackedRow(plan, json) {
|
|
617
|
+
if (!Array.isArray(json)) throw new TypeError(`Nested row must be an array, not ${describeJson(json)}`);
|
|
618
|
+
return decodeRow(plan, json, true);
|
|
619
|
+
}
|
|
620
|
+
/** Describes the kind of a parsed JSON value for an error message. */
|
|
621
|
+
function describeJson(value) {
|
|
622
|
+
if (value === null) return "null";
|
|
623
|
+
if (typeof value === "object") return Array.isArray(value) ? "an array" : "an object";
|
|
624
|
+
return `a ${typeof value}`;
|
|
625
|
+
}
|
|
626
|
+
// src/table/table.ts
|
|
627
|
+
function defineTable(name, definitions, options) {
|
|
628
|
+
return createTable(name, definitions, options, void 0);
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Creates a table-definition function with the given naming convention, for an application to define its tables with.
|
|
632
|
+
*
|
|
633
|
+
* Its tables have the same types as those of `defineTable`.
|
|
634
|
+
*/
|
|
635
|
+
function createTableFactory(factoryOptions) {
|
|
636
|
+
const deriveColumnName = factoryOptions.columnName;
|
|
637
|
+
if (typeof deriveColumnName !== "function") throw new TypeError("The columnName option of createTableFactory must be a function");
|
|
638
|
+
return ((name, definitions, options) => createTable(name, definitions, options, deriveColumnName));
|
|
639
|
+
}
|
|
640
|
+
/** Creates the table that `defineTable` defines, naming its columns by `deriveColumnName` if given. */
|
|
641
|
+
function createTable(name, definitions, options, deriveColumnName) {
|
|
642
|
+
const columns = {};
|
|
643
|
+
for (const [key, definition] of Object.entries(definitions)) {
|
|
644
|
+
if (key.startsWith("$")) throw new Error(`Column key "${key}" of table "${name}" must not start with "$"`);
|
|
645
|
+
if (!isRecordKey(key)) throw new Error(`Column key "__proto__" of table "${name}" is not allowed; use columnName("__proto__")`);
|
|
646
|
+
const column = toColumn(definition);
|
|
647
|
+
if (!column) throw new TypeError(`Column "${key}" of table "${name}" must be a type or a column`);
|
|
648
|
+
columns[key] = column;
|
|
649
|
+
}
|
|
650
|
+
if (deriveColumnName) nameColumns(name, columns, deriveColumnName);
|
|
651
|
+
return Object.freeze({
|
|
652
|
+
kind: "table",
|
|
653
|
+
name,
|
|
654
|
+
columns: Object.freeze(columns),
|
|
655
|
+
keys: defineKeys(name, columns, options)
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Replaces unnamed columns of table `name` with copies whose physical names are derived from their keys, so that a column shared with other tables stays as it is.
|
|
660
|
+
*
|
|
661
|
+
* It calls `deriveColumnName`, which an application gives, once for each such column.
|
|
662
|
+
* It rejects a derived name that is not a non-empty string, which PostgreSQL rejects only when a query runs, and a derived name that another column has, since two keys would silently read one column.
|
|
663
|
+
* Duplicate names set with `columnName` are allowed, as in `defineTable`.
|
|
664
|
+
*/
|
|
665
|
+
function nameColumns(name, columns, deriveColumnName) {
|
|
666
|
+
const keys = Object.keys(columns);
|
|
667
|
+
const derivedKeys = [];
|
|
668
|
+
for (const key of keys) {
|
|
669
|
+
const column = columns[key];
|
|
670
|
+
if (column.attributes.name === void 0) {
|
|
671
|
+
const columnName = deriveColumnName(key);
|
|
672
|
+
if (typeof columnName !== "string" || columnName === "") throw new TypeError(`The name derived for column "${key}" of table "${name}" must be a non-empty string`);
|
|
673
|
+
columns[key] = column.columnName(columnName);
|
|
674
|
+
derivedKeys.push(key);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
for (const key of derivedKeys) {
|
|
678
|
+
const columnName = columns[key].attributes.name;
|
|
679
|
+
for (const other of keys) if (other !== key && columns[other].attributes.name === columnName) throw new Error(`Columns "${key}" and "${other}" of table "${name}" have one physical name "${columnName}"; set another name with columnName()`);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Defines the keys of table `name` of `columns` from the keys marked on the columns and those of `options`.
|
|
684
|
+
*
|
|
685
|
+
* The unique keys are those of the columns in their order, followed by those of the options.
|
|
686
|
+
* 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.
|
|
687
|
+
*/
|
|
688
|
+
function defineKeys(name, columns, options) {
|
|
689
|
+
let primaryKey;
|
|
690
|
+
const unique = [];
|
|
691
|
+
for (const key of Object.keys(columns)) {
|
|
692
|
+
const keyKind = columns[key].attributes.keyKind;
|
|
693
|
+
if (keyKind === "primaryKey") {
|
|
694
|
+
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`);
|
|
695
|
+
primaryKey = Object.freeze([key]);
|
|
696
|
+
} else if (keyKind === "unique") unique.push(Object.freeze([key]));
|
|
697
|
+
}
|
|
698
|
+
if (options?.primaryKey !== void 0) {
|
|
699
|
+
if (primaryKey !== void 0) throw new Error(`Table "${name}" declares its primary key both on column "${primaryKey[0]}" and in the options`);
|
|
700
|
+
primaryKey = toKeyColumns(name, columns, options.primaryKey);
|
|
701
|
+
}
|
|
702
|
+
if (options?.unique !== void 0) {
|
|
703
|
+
if (!Array.isArray(options.unique)) throw new TypeError(`Unique keys in the options of table "${name}" must be an array`);
|
|
704
|
+
for (const key of options.unique) unique.push(toKeyColumns(name, columns, key));
|
|
705
|
+
}
|
|
706
|
+
for (const key of primaryKey ?? []) if (columns[key].type.isNullable) throw new Error(`Primary key column "${key}" of table "${name}" must not be nullable`);
|
|
707
|
+
const keys = primaryKey === void 0 ? unique : [primaryKey, ...unique];
|
|
708
|
+
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`);
|
|
709
|
+
return Object.freeze({
|
|
710
|
+
primaryKey,
|
|
711
|
+
unique: Object.freeze(unique)
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
/** 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. */
|
|
715
|
+
function toKeyColumns(name, columns, key) {
|
|
716
|
+
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()`);
|
|
717
|
+
for (let index = 0; index < key.length; index++) {
|
|
718
|
+
const column = key[index];
|
|
719
|
+
if (typeof column !== "string" || !Object.hasOwn(columns, column)) throw new Error(`A key in the options of table "${name}" lists unknown column "${column}"`);
|
|
720
|
+
if (key.indexOf(column) !== index) throw new Error(`A key in the options of table "${name}" lists column "${column}" twice`);
|
|
721
|
+
}
|
|
722
|
+
return Object.freeze(key.slice());
|
|
723
|
+
}
|
|
724
|
+
/** Tells whether keys `key` and `other` have the same columns, in any order; neither lists a column twice. */
|
|
725
|
+
function hasSameColumns(key, other) {
|
|
726
|
+
return key.length === other.length && key.every((column) => other.includes(column));
|
|
727
|
+
}
|
|
728
|
+
/** Finds the column of `table` under `key`, ignoring properties inherited from the object prototype, such as `toString`. */
|
|
729
|
+
function findColumn(table, key) {
|
|
730
|
+
return Object.hasOwn(table.columns, key) ? table.columns[key] : void 0;
|
|
731
|
+
}
|
|
732
|
+
/** 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. */
|
|
733
|
+
function isKey(table, columns) {
|
|
734
|
+
const listed = new Set(columns);
|
|
735
|
+
return someKey(table, (key) => key.length === listed.size && isKeyAmong(key, listed));
|
|
736
|
+
}
|
|
737
|
+
/** Tells whether the columns of `table` under `columns` include a key of it, primary or unique, as `ContainsKey` does in types. */
|
|
738
|
+
function containsKey(table, columns) {
|
|
739
|
+
const listed = new Set(columns);
|
|
740
|
+
return someKey(table, (key) => isKeyAmong(key, listed));
|
|
741
|
+
}
|
|
742
|
+
/** Tells whether `predicate` holds for a key of `table`, primary or unique. */
|
|
743
|
+
function someKey(table, predicate) {
|
|
744
|
+
const { primaryKey, unique } = table.keys;
|
|
745
|
+
return primaryKey !== void 0 && predicate(primaryKey) || unique.some(predicate);
|
|
746
|
+
}
|
|
747
|
+
/** Tells whether every column of `key` is in `columns`. */
|
|
748
|
+
function isKeyAmong(key, columns) {
|
|
749
|
+
return key.every((column) => columns.has(column));
|
|
750
|
+
}
|
|
751
|
+
/** Returns the column of `table` under `key` as `findColumn` finds it, rejecting a key that is not a column. */
|
|
752
|
+
function requireColumn(table, key) {
|
|
753
|
+
const column = findColumn(table, key);
|
|
754
|
+
if (!column) throw new Error(`Unknown column "${key}" of table "${table.name}"`);
|
|
755
|
+
return column;
|
|
756
|
+
}
|
|
757
|
+
/** Creates a column from a column definition, or returns `undefined` for a value that is neither a type nor a column. */
|
|
758
|
+
function toColumn(definition) {
|
|
759
|
+
if (definition instanceof Column) return definition;
|
|
760
|
+
return isType(definition) ? new Column(definition, {
|
|
761
|
+
name: void 0,
|
|
762
|
+
keyKind: void 0,
|
|
763
|
+
hasDefault: false
|
|
764
|
+
}) : void 0;
|
|
765
|
+
}
|
|
766
|
+
// src/type/untyped.ts
|
|
767
|
+
/** Encodes a parameter without a type, such as a value interpolated into `sql`, by its JavaScript type. */
|
|
768
|
+
function encodeUntyped(value) {
|
|
769
|
+
if (typeof value === "string") return value;
|
|
770
|
+
if (typeof value === "number" || typeof value === "bigint") return String(value);
|
|
771
|
+
if (typeof value === "boolean") return value ? "t" : "f";
|
|
772
|
+
if (value instanceof Date) return value.toISOString();
|
|
773
|
+
if (value instanceof Uint8Array) return encodeBytea(value);
|
|
774
|
+
if (Array.isArray(value)) throw new TypeError("Pass an array with param(type, value), so that its elements are encoded by type");
|
|
775
|
+
return stringifyJson(value);
|
|
776
|
+
}
|
|
777
|
+
// src/compiler/postgres/identifier.ts
|
|
778
|
+
/** 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)). */
|
|
779
|
+
const maxCharacterBytes = 4;
|
|
780
|
+
function quoteIdentifier(name) {
|
|
781
|
+
return `"${name.replaceAll("\"", "\"\"")}"`;
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Returns the longest prefix of `name` that takes at most `maxBytes` bytes in any server encoding.
|
|
785
|
+
*
|
|
786
|
+
* Every server encoding takes one byte for an ASCII character, and a character other than ASCII counts as the most bytes it can take.
|
|
787
|
+
*/
|
|
788
|
+
function cutIdentifier(name, maxBytes) {
|
|
789
|
+
if (name.length * maxCharacterBytes <= maxBytes) return name;
|
|
790
|
+
let bytes = 0;
|
|
791
|
+
for (let index = 0; index < name.length;) {
|
|
792
|
+
const code = name.codePointAt(index);
|
|
793
|
+
bytes += code < 128 ? 1 : maxCharacterBytes;
|
|
794
|
+
if (bytes > maxBytes) return name.slice(0, index);
|
|
795
|
+
index += code < 65536 ? 1 : 2;
|
|
796
|
+
}
|
|
797
|
+
return name;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Returns the SQL name of the projection with `key` at `index` of its query.
|
|
801
|
+
*
|
|
802
|
+
* A key of up to 50 bytes is the name itself.
|
|
803
|
+
* 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.
|
|
804
|
+
*/
|
|
805
|
+
function nameProjection(key, index) {
|
|
806
|
+
if (cutIdentifier(key, 50).length === key.length) return key;
|
|
807
|
+
return `${cutIdentifier(key, 54)}_${index + 1}`;
|
|
808
|
+
}
|
|
809
|
+
// src/compiler/postgres/context.ts
|
|
810
|
+
/** Most parameters that PostgreSQL takes in a statement. */
|
|
811
|
+
const maxParameters = 65535;
|
|
812
|
+
/** State of one compilation shared by all queries of the statement, never by reusable nodes: parameters and the aliases of all sources. */
|
|
813
|
+
var CompileContext = class {
|
|
814
|
+
schemaName;
|
|
815
|
+
tables;
|
|
816
|
+
db;
|
|
817
|
+
parameters = [];
|
|
818
|
+
/** Whether a select statement of the compilation locks rows. */
|
|
819
|
+
locksRows = false;
|
|
820
|
+
/** Whether the clauses being compiled belong to a query of groups, which binds the parameter of a cast once by `bindOnce`. */
|
|
821
|
+
grouped = false;
|
|
822
|
+
#aliases = /* @__PURE__ */ new Set();
|
|
823
|
+
#placeholders;
|
|
824
|
+
constructor(schemaName, tables = void 0, db = void 0) {
|
|
825
|
+
this.schemaName = schemaName;
|
|
826
|
+
this.tables = tables;
|
|
827
|
+
this.db = db;
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Creates an alias based on `name` that is unique in the statement, so that no source shadows another one in SQL.
|
|
831
|
+
*
|
|
832
|
+
* 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.
|
|
833
|
+
*/
|
|
834
|
+
createAlias(name) {
|
|
835
|
+
const base = cutIdentifier(name.toWellFormed(), 50);
|
|
836
|
+
let alias = base;
|
|
837
|
+
for (let index = 2; this.#aliases.has(alias); index++) alias = `${base}_${index}`;
|
|
838
|
+
this.#aliases.add(alias);
|
|
839
|
+
return alias;
|
|
840
|
+
}
|
|
841
|
+
/** Adds a parameter of the statement and returns its placeholder, rejecting more parameters than PostgreSQL takes. */
|
|
842
|
+
bind(value) {
|
|
843
|
+
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`);
|
|
844
|
+
this.parameters.push(value);
|
|
845
|
+
return `$${this.parameters.length}`;
|
|
846
|
+
}
|
|
847
|
+
/** Binds `value` as the parameter of `cast` unless `bindOnce` has bound the cast before, and returns its placeholder. */
|
|
848
|
+
bindOnce(cast, value) {
|
|
849
|
+
this.#placeholders ??= /* @__PURE__ */ new Map();
|
|
850
|
+
let placeholder = this.#placeholders.get(cast);
|
|
851
|
+
if (placeholder === void 0) {
|
|
852
|
+
placeholder = this.bind(value);
|
|
853
|
+
this.#placeholders.set(cast, placeholder);
|
|
854
|
+
}
|
|
855
|
+
return placeholder;
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
// src/compiler/postgres/parentheses.ts
|
|
859
|
+
/** Tells whether an operand of `kind` needs parentheses at `position`, so that the SQL keeps the structure of the tree. */
|
|
860
|
+
function needsParentheses(kind, position) {
|
|
861
|
+
switch (kind) {
|
|
862
|
+
case "column":
|
|
863
|
+
case "param":
|
|
864
|
+
case "boolean":
|
|
865
|
+
case "values":
|
|
866
|
+
case "nestedQuery":
|
|
867
|
+
case "tableName":
|
|
868
|
+
case "subquery":
|
|
869
|
+
case "exists":
|
|
870
|
+
case "textSubquery":
|
|
871
|
+
case "aggregate": return false;
|
|
872
|
+
case "cast": return position === "interpolation";
|
|
873
|
+
case "raw": return position !== "interpolation";
|
|
874
|
+
case "and":
|
|
875
|
+
case "or": return true;
|
|
876
|
+
case "not":
|
|
877
|
+
case "comparison":
|
|
878
|
+
case "in":
|
|
879
|
+
case "inQuery":
|
|
880
|
+
case "isNull": return position !== "condition";
|
|
881
|
+
default: return kind;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
// src/compiler/postgres/scope.ts
|
|
885
|
+
/**
|
|
886
|
+
* Declares a source of `FROM` on top of `outer` with a new alias.
|
|
887
|
+
*
|
|
888
|
+
* It rejects a source already visible there, such as a query nested in itself: a column reference could not tell its occurrences apart.
|
|
889
|
+
*/
|
|
890
|
+
function declareSource(context, outer, source) {
|
|
891
|
+
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`);
|
|
892
|
+
const name = source.kind === "table" ? source.table.name : source.replaces?.table.name ?? "subquery";
|
|
893
|
+
return {
|
|
894
|
+
source,
|
|
895
|
+
alias: context.createAlias(name),
|
|
896
|
+
outer
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* 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.
|
|
901
|
+
*/
|
|
902
|
+
function resolveSource(scope, column) {
|
|
903
|
+
const declared = findSource(scope, column.source);
|
|
904
|
+
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`);
|
|
905
|
+
return declared;
|
|
906
|
+
}
|
|
907
|
+
/** Returns the declared source of `scope` that is `source` or replaces it, or `undefined` when the source is not visible there. */
|
|
908
|
+
function findSource(scope, source) {
|
|
909
|
+
for (let current = scope; current; current = current.outer) {
|
|
910
|
+
const declared = current.source;
|
|
911
|
+
if (declared === source || declared.kind === "derived" && declared.replaces === source) return current;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
function describeSource(source) {
|
|
915
|
+
return source.kind === "table" ? `table "${source.table.name}"` : "a subquery";
|
|
916
|
+
}
|
|
917
|
+
// src/compiler/postgres/compile.ts
|
|
918
|
+
const noFields = /* @__PURE__ */ Object.freeze([]);
|
|
919
|
+
/**
|
|
920
|
+
* Compiles a statement for PostgreSQL: a select statement, a mutation, or a statement of SQL text.
|
|
921
|
+
*
|
|
922
|
+
* 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.
|
|
923
|
+
* `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.
|
|
924
|
+
*/
|
|
925
|
+
function compileStatement(node, options = {}, tables, db) {
|
|
926
|
+
const context = new CompileContext(options.schemaName, tables, db);
|
|
927
|
+
switch (node.kind) {
|
|
928
|
+
case "select": return {
|
|
929
|
+
text: compileQuery(context, void 0, node),
|
|
930
|
+
parameters: context.parameters,
|
|
931
|
+
fields: node.projections,
|
|
932
|
+
recordTemplate: node.recordTemplate,
|
|
933
|
+
conversion: node.conversion,
|
|
934
|
+
rows: node.rows,
|
|
935
|
+
value: node.value,
|
|
936
|
+
counted: void 0,
|
|
937
|
+
named: false,
|
|
938
|
+
locksRows: context.locksRows
|
|
939
|
+
};
|
|
940
|
+
case "text": {
|
|
941
|
+
const { fields } = node;
|
|
942
|
+
return {
|
|
943
|
+
text: compileExpression(context, void 0, node.sql),
|
|
944
|
+
parameters: context.parameters,
|
|
945
|
+
fields: fields ?? noFields,
|
|
946
|
+
rows: node.rows,
|
|
947
|
+
value: node.value,
|
|
948
|
+
counted: fields === void 0 ? "number" : void 0,
|
|
949
|
+
named: true,
|
|
950
|
+
locksRows: false
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
default: {
|
|
954
|
+
const { returning } = node;
|
|
955
|
+
return {
|
|
956
|
+
text: compileMutation(context, node),
|
|
957
|
+
parameters: context.parameters,
|
|
958
|
+
fields: returning ?? noFields,
|
|
959
|
+
recordTemplate: node.recordTemplate,
|
|
960
|
+
conversion: node.conversion,
|
|
961
|
+
rows: node.rows,
|
|
962
|
+
value: node.value,
|
|
963
|
+
counted: returning === void 0 ? "number" : returning.length === 0 ? "records" : void 0,
|
|
964
|
+
named: false,
|
|
965
|
+
locksRows: false
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
/** Compiles a mutation, whose expressions see only the occurrence of its table, apart from the values of an insert, which see no source. */
|
|
971
|
+
function compileMutation(context, node) {
|
|
972
|
+
const scope = declareSource(context, void 0, node.target);
|
|
973
|
+
const target = compileSource(context, void 0, scope);
|
|
974
|
+
let text;
|
|
975
|
+
switch (node.kind) {
|
|
976
|
+
case "insert":
|
|
977
|
+
text = `INSERT INTO ${target}${compileValues(context, node)}`;
|
|
978
|
+
break;
|
|
979
|
+
case "update": {
|
|
980
|
+
text = `UPDATE ${target} SET`;
|
|
981
|
+
const { set } = node;
|
|
982
|
+
for (let index = 0; index < set.length; index++) {
|
|
983
|
+
const { key, value } = set[index];
|
|
984
|
+
text += `${index === 0 ? " " : ", "}${compileColumnName(node.target, key)} = ${compileExpression(context, scope, value)}`;
|
|
985
|
+
}
|
|
986
|
+
text += compileWhere(context, scope, node.filters);
|
|
987
|
+
break;
|
|
988
|
+
}
|
|
989
|
+
case "delete":
|
|
990
|
+
text = `DELETE FROM ${target}${compileWhere(context, scope, node.filters)}`;
|
|
991
|
+
break;
|
|
992
|
+
default: return node;
|
|
993
|
+
}
|
|
994
|
+
const { returning } = node;
|
|
995
|
+
if (returning !== void 0 && returning.length > 0) text += ` RETURNING${compileProjections(context, scope, returning)}`;
|
|
996
|
+
return text;
|
|
997
|
+
}
|
|
998
|
+
/** Compiles the columns and the rows of `VALUES` of an insert, or `DEFAULT VALUES` for one row of the defaults of every column. */
|
|
999
|
+
function compileValues(context, node) {
|
|
1000
|
+
const { columns, values } = node;
|
|
1001
|
+
if (columns.length === 0) {
|
|
1002
|
+
if (values.length !== 1) throw new Error("An insert of several rows must list a column");
|
|
1003
|
+
return " DEFAULT VALUES";
|
|
1004
|
+
}
|
|
1005
|
+
let text = " (";
|
|
1006
|
+
for (let index = 0; index < columns.length; index++) text += `${index === 0 ? "" : ", "}${compileColumnName(node.target, columns[index])}`;
|
|
1007
|
+
text += ") VALUES";
|
|
1008
|
+
for (let row = 0; row < values.length; row++) {
|
|
1009
|
+
const items = values[row];
|
|
1010
|
+
text += row === 0 ? " (" : ", (";
|
|
1011
|
+
for (let index = 0; index < items.length; index++) {
|
|
1012
|
+
const item = items[index];
|
|
1013
|
+
text += `${index === 0 ? "" : ", "}${item === void 0 ? "DEFAULT" : compileExpression(context, void 0, item)}`;
|
|
1014
|
+
}
|
|
1015
|
+
text += ")";
|
|
1016
|
+
}
|
|
1017
|
+
return text;
|
|
1018
|
+
}
|
|
1019
|
+
/** 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. */
|
|
1020
|
+
function compileColumnName(target, key) {
|
|
1021
|
+
return quoteIdentifier(requireColumn(target.table, key).attributes.name ?? key);
|
|
1022
|
+
}
|
|
1023
|
+
/** Compiles a query at a position of the statement where the sources of `outer` are visible. */
|
|
1024
|
+
function compileQuery(context, outer, node) {
|
|
1025
|
+
const { from } = node;
|
|
1026
|
+
if (from === void 0 && node.joins.length > 0) throw new Error("A query without FROM cannot join sources");
|
|
1027
|
+
const fromScope = from === void 0 ? void 0 : declareSource(context, outer, from);
|
|
1028
|
+
let scope = fromScope ?? outer;
|
|
1029
|
+
const joinScopes = [];
|
|
1030
|
+
for (const join of node.joins) {
|
|
1031
|
+
scope = declareSource(context, scope, join.source);
|
|
1032
|
+
joinScopes.push(scope);
|
|
1033
|
+
}
|
|
1034
|
+
const { groupBy, having } = node;
|
|
1035
|
+
const { grouped } = context;
|
|
1036
|
+
context.grouped = groupBy !== void 0;
|
|
1037
|
+
let text = "SELECT";
|
|
1038
|
+
if (node.distinct) text += " DISTINCT";
|
|
1039
|
+
const { distinctOn } = node;
|
|
1040
|
+
if (distinctOn !== void 0) text += ` DISTINCT ON (${compileKeys(context, scope, distinctOn, node.projections)})`;
|
|
1041
|
+
text += compileProjections(context, scope, node.projections);
|
|
1042
|
+
if (fromScope !== void 0) {
|
|
1043
|
+
text += ` FROM ${compileSource(context, outer, fromScope)}`;
|
|
1044
|
+
for (let index = 0; index < node.joins.length; index++) {
|
|
1045
|
+
const joinScope = joinScopes[index];
|
|
1046
|
+
text += ` LEFT JOIN ${compileSource(context, outer, joinScope)} ON ${compileExpression(context, joinScope, node.joins[index].on)}`;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
text += compileWhere(context, scope, node.filters);
|
|
1050
|
+
if (groupBy !== void 0) text += ` GROUP BY ${compileKeys(context, scope, groupBy, node.projections)}`;
|
|
1051
|
+
if (having !== void 0) text += ` HAVING ${compileExpression(context, scope, having)}`;
|
|
1052
|
+
if (node.orderBy.length > 0) text += ` ${compileOrderBy(context, scope, node.orderBy)}`;
|
|
1053
|
+
if (node.limit) text += ` LIMIT ${compileExpression(context, outer, node.limit)}`;
|
|
1054
|
+
if (node.offset) text += ` OFFSET ${compileExpression(context, outer, node.offset)}`;
|
|
1055
|
+
const { lock } = node;
|
|
1056
|
+
if (lock !== void 0) {
|
|
1057
|
+
context.locksRows = true;
|
|
1058
|
+
text += ` FOR ${lock.strength}`;
|
|
1059
|
+
if (lock.onLocked !== void 0) text += ` ${lock.onLocked}`;
|
|
1060
|
+
}
|
|
1061
|
+
context.grouped = grouped;
|
|
1062
|
+
return text;
|
|
1063
|
+
}
|
|
1064
|
+
/** Compiles the projections of a select list or of `RETURNING`, each after a space or a comma. */
|
|
1065
|
+
function compileProjections(context, scope, projections) {
|
|
1066
|
+
let text = "";
|
|
1067
|
+
for (let index = 0; index < projections.length; index++) {
|
|
1068
|
+
const projection = projections[index];
|
|
1069
|
+
text += `${index === 0 ? " " : ", "}${compileExpression(context, scope, projection.expression)} AS ${quoteIdentifier(nameProjection(projection.key, index))}`;
|
|
1070
|
+
}
|
|
1071
|
+
return text;
|
|
1072
|
+
}
|
|
1073
|
+
/** Compiles the `WHERE` clause of the effective predicate of `filters` after a space, or nothing when they restrict no row. */
|
|
1074
|
+
function compileWhere(context, scope, filters) {
|
|
1075
|
+
const where = combineFilters(filters);
|
|
1076
|
+
return where.kind === "boolean" && where.value ? "" : ` WHERE ${compileExpression(context, scope, where)}`;
|
|
1077
|
+
}
|
|
1078
|
+
/** Compiles the keys of `GROUP BY` or `DISTINCT ON` of a query of `projections`, its final select list, also with those that lowering adds, such as of a sort key of packed rows: each key is the position of the projection that has its value, or its expression without one. */
|
|
1079
|
+
function compileKeys(context, scope, keys, projections) {
|
|
1080
|
+
let text = "";
|
|
1081
|
+
for (let index = 0; index < keys.length; index++) {
|
|
1082
|
+
const key = keys[index];
|
|
1083
|
+
const position = findValueProjection(projections, key);
|
|
1084
|
+
text += `${index === 0 ? "" : ", "}${position === -1 ? compileExpression(context, scope, key) : String(position + 1)}`;
|
|
1085
|
+
}
|
|
1086
|
+
return text;
|
|
1087
|
+
}
|
|
1088
|
+
/** Compiles the `ORDER BY` clause of a query or an aggregate, which has at least one sort key. */
|
|
1089
|
+
function compileOrderBy(context, scope, orderBy) {
|
|
1090
|
+
let text = "ORDER BY";
|
|
1091
|
+
for (let index = 0; index < orderBy.length; index++) {
|
|
1092
|
+
const order = orderBy[index];
|
|
1093
|
+
text += `${index === 0 ? " " : ", "}${compileExpression(context, scope, order.expression)}`;
|
|
1094
|
+
if (order.direction === "desc") text += " DESC";
|
|
1095
|
+
if (order.nulls !== void 0) text += order.nulls === "first" ? " NULLS FIRST" : " NULLS LAST";
|
|
1096
|
+
}
|
|
1097
|
+
return text;
|
|
1098
|
+
}
|
|
1099
|
+
/** Compiles a declared source of a query at a position of the statement where the sources of `outer` are visible. */
|
|
1100
|
+
function compileSource(context, outer, declared) {
|
|
1101
|
+
const { source, alias } = declared;
|
|
1102
|
+
if (source.kind === "table") return `${compileTableName(context, source.table)} AS ${quoteIdentifier(alias)}`;
|
|
1103
|
+
const query = compileQuery(context, source.lateral ? declared.outer : outer, source.query);
|
|
1104
|
+
return `${source.lateral ? "LATERAL " : ""}(${query}) AS ${quoteIdentifier(alias)}`;
|
|
1105
|
+
}
|
|
1106
|
+
/** Compiles the name of `table`, qualified by the PostgreSQL schema of the statement, rejecting a table outside the tables of the statement. */
|
|
1107
|
+
function compileTableName(context, table) {
|
|
1108
|
+
if (context.tables !== void 0 && !context.tables.has(table)) throw new Error(`Table "${table.name}" is not part of the schema`);
|
|
1109
|
+
return context.schemaName === void 0 ? quoteIdentifier(table.name) : `${quoteIdentifier(context.schemaName)}.${quoteIdentifier(table.name)}`;
|
|
1110
|
+
}
|
|
1111
|
+
/** 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. */
|
|
1112
|
+
function compileInterpolatedTable(context, node) {
|
|
1113
|
+
const { db, table } = node;
|
|
1114
|
+
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`);
|
|
1115
|
+
return compileTableName(context, table);
|
|
1116
|
+
}
|
|
1117
|
+
function compileColumn(scope, node) {
|
|
1118
|
+
const { key } = node;
|
|
1119
|
+
const declared = resolveSource(scope, node);
|
|
1120
|
+
const { source } = declared;
|
|
1121
|
+
let name;
|
|
1122
|
+
if (source.kind === "table") name = requireColumn(source.table, key).attributes.name ?? key;
|
|
1123
|
+
else {
|
|
1124
|
+
const index = source.query.projections.findIndex((projection) => projection.key === key);
|
|
1125
|
+
if (index === -1) throw new Error(`Unknown field "${key}" of a subquery`);
|
|
1126
|
+
name = nameProjection(key, index);
|
|
1127
|
+
}
|
|
1128
|
+
return `${quoteIdentifier(declared.alias)}.${quoteIdentifier(name)}`;
|
|
1129
|
+
}
|
|
1130
|
+
function compileExpression(context, scope, node) {
|
|
1131
|
+
switch (node.kind) {
|
|
1132
|
+
case "column": return compileColumn(scope, node);
|
|
1133
|
+
case "param": return context.bind(encodeParameter(node));
|
|
1134
|
+
case "cast": {
|
|
1135
|
+
const { operand } = node;
|
|
1136
|
+
return `${context.grouped && operand.kind === "param" ? context.bindOnce(node, encodeParameter(operand)) : compileOperand(context, scope, operand, "value")}::${node.type.castType}`;
|
|
1137
|
+
}
|
|
1138
|
+
case "boolean": return node.value ? "TRUE" : "FALSE";
|
|
1139
|
+
case "and":
|
|
1140
|
+
case "or": return node.operands.map((operand) => compileOperand(context, scope, operand, "condition")).join(node.kind === "and" ? " AND " : " OR ");
|
|
1141
|
+
case "not": return `NOT ${compileOperand(context, scope, node.operand, "condition")}`;
|
|
1142
|
+
case "values": throw new Error("An object condition can only be used in `where`");
|
|
1143
|
+
case "nestedQuery": throw new Error("A query in an expression must be lowered before compilation");
|
|
1144
|
+
case "comparison": return `${compileOperand(context, scope, node.left, "value")} ${node.operator} ${compileOperand(context, scope, node.right, "value")}`;
|
|
1145
|
+
case "in": {
|
|
1146
|
+
let text = `${compileOperand(context, scope, node.operand, "value")} IN (${compileOperand(context, scope, node.list[0], "value")}`;
|
|
1147
|
+
for (let index = 1; index < node.list.length; index++) text += `, ${compileOperand(context, scope, node.list[index], "value")}`;
|
|
1148
|
+
return `${text})`;
|
|
1149
|
+
}
|
|
1150
|
+
case "inQuery": {
|
|
1151
|
+
const { query } = node;
|
|
1152
|
+
if (query.kind === "nestedQuery") throw new Error("A query in an expression must be lowered before compilation");
|
|
1153
|
+
return `${compileOperand(context, scope, node.operand, "value")} IN ${compileSubquery(context, scope, query, "A subquery of IN")}`;
|
|
1154
|
+
}
|
|
1155
|
+
case "isNull": return `${compileOperand(context, scope, node.operand, "value")} IS NULL`;
|
|
1156
|
+
case "raw": {
|
|
1157
|
+
let text = node.fragments[0];
|
|
1158
|
+
for (let index = 0; index < node.values.length; index++) text += compileOperand(context, scope, node.values[index], "interpolation") + node.fragments[index + 1];
|
|
1159
|
+
return text;
|
|
1160
|
+
}
|
|
1161
|
+
case "tableName": return compileInterpolatedTable(context, node);
|
|
1162
|
+
case "subquery": return compileSubquery(context, scope, node.query, "A scalar subquery");
|
|
1163
|
+
case "exists": return `EXISTS (${compileQuery(context, scope, node.query)})`;
|
|
1164
|
+
case "textSubquery": return `(${compileQuery(context, scope, node.query)})`;
|
|
1165
|
+
case "aggregate": {
|
|
1166
|
+
let text = `${node.name}(${node.distinct ? "DISTINCT " : ""}`;
|
|
1167
|
+
for (let index = 0; index < node.arguments.length; index++) text += `${index === 0 ? "" : ", "}${compileExpression(context, scope, node.arguments[index])}`;
|
|
1168
|
+
if (node.orderBy.length > 0) text += ` ${compileOrderBy(context, scope, node.orderBy)}`;
|
|
1169
|
+
text += ")";
|
|
1170
|
+
if (node.filter !== void 0) text += ` FILTER (WHERE ${compileExpression(context, scope, node.filter)})`;
|
|
1171
|
+
return text;
|
|
1172
|
+
}
|
|
1173
|
+
default: return node;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
/** Compiles `query` in parentheses as a subquery of one field, and rejects a query of another number of fields, naming the subquery as `subject`. */
|
|
1177
|
+
function compileSubquery(context, scope, query, subject) {
|
|
1178
|
+
const { length } = query.projections;
|
|
1179
|
+
if (length !== 1) throw new Error(`${subject} must select one field, not ${length}`);
|
|
1180
|
+
return `(${compileQuery(context, scope, query)})`;
|
|
1181
|
+
}
|
|
1182
|
+
/** Encodes the value of a parameter node with its type, or by its JavaScript type without one. */
|
|
1183
|
+
function encodeParameter(node) {
|
|
1184
|
+
if (node.value === void 0) throw new TypeError("Query parameter is undefined; use null for NULL");
|
|
1185
|
+
if (node.value === null) return null;
|
|
1186
|
+
return node.type ? node.type.encode(node.value) : encodeUntyped(node.value);
|
|
1187
|
+
}
|
|
1188
|
+
/** Compiles an operand at `position` of its parent, parenthesizing it where its own operators could regroup with the parent. */
|
|
1189
|
+
function compileOperand(context, scope, node, position) {
|
|
1190
|
+
const sql = compileExpression(context, scope, node);
|
|
1191
|
+
return needsParentheses(node.kind, position) ? `(${sql})` : sql;
|
|
1192
|
+
}
|
|
1193
|
+
// src/execution/driver.ts
|
|
1194
|
+
/** Creates a statement from SQL text and the text representations of its parameters, such as `createStatement("BEGIN")`. */
|
|
1195
|
+
function createStatement(text, parameters = []) {
|
|
1196
|
+
return {
|
|
1197
|
+
text,
|
|
1198
|
+
parameters
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
// src/schema/relation.ts
|
|
1202
|
+
/** Runtime mark of the declarations of `many` and `one`. */
|
|
1203
|
+
const declarationBrand = Symbol("kern-orm.relation");
|
|
1204
|
+
/** Returns the name of relation `name` of the table under key `key` in messages and errors, such as `field.form`. */
|
|
1205
|
+
function formatRelationName(key, name) {
|
|
1206
|
+
return `${key}.${name}`;
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Declares a relation of a table to the records of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
|
|
1210
|
+
*
|
|
1211
|
+
* A composite key lists its columns in arrays of the same length.
|
|
1212
|
+
*/
|
|
1213
|
+
function many(target, keys) {
|
|
1214
|
+
return declareRelation("many", target, keys, false);
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Declares a relation of a table to the record of `target` whose columns `to` equal its columns `from`, for `$relations` of a schema.
|
|
1218
|
+
*
|
|
1219
|
+
* A composite key lists its columns in arrays of the same length.
|
|
1220
|
+
* The columns `to` must include a key of `target`, primary or unique, so that they match at most one record.
|
|
1221
|
+
* Without the record, a query of the relation gives `null`, and a query of a relation declared with `required: true` rejects unless it filters the record.
|
|
1222
|
+
* Set `required: true` only where the database guarantees the record, such as by a foreign key on columns `from` that are not nullable.
|
|
1223
|
+
*/
|
|
1224
|
+
function one(target, keys) {
|
|
1225
|
+
return declareRelation("one", target, keys, keys.required === true);
|
|
1226
|
+
}
|
|
1227
|
+
function declareRelation(kind, target, keys, required) {
|
|
1228
|
+
return Object.freeze({
|
|
1229
|
+
[declarationBrand]: true,
|
|
1230
|
+
kind,
|
|
1231
|
+
target,
|
|
1232
|
+
from: toKeyList(keys.from),
|
|
1233
|
+
to: toKeyList(keys.to),
|
|
1234
|
+
required
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
function toKeyList(key) {
|
|
1238
|
+
return Object.freeze(Array.isArray(key) ? key.slice() : [key]);
|
|
1239
|
+
}
|
|
1240
|
+
/**
|
|
1241
|
+
* Defines relation `name` of table `source`, declared under its key `key` in a schema, checking its target and its keys.
|
|
1242
|
+
*
|
|
1243
|
+
* `findKey` returns the key of a table in the schema, or `undefined` for a table outside it.
|
|
1244
|
+
* 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.
|
|
1245
|
+
*/
|
|
1246
|
+
function defineRelation(source, key, name, declaration, findKey) {
|
|
1247
|
+
const subject = `Relation "${formatRelationName(key, name)}"`;
|
|
1248
|
+
if (!isRelationDeclaration(declaration)) throw new TypeError(`${subject} must be declared with many or one`);
|
|
1249
|
+
if (name.startsWith("$")) throw new Error(`${subject}: a relation name must not start with "$"`);
|
|
1250
|
+
if (findColumn(source, name)) throw new Error(`${subject}: a relation name must differ from the column keys of table "${source.name}"`);
|
|
1251
|
+
const { kind, target, from, to, required } = declaration;
|
|
1252
|
+
const targetKey = findKey(target);
|
|
1253
|
+
if (targetKey === void 0) throw new Error(`${subject} refers to table "${target.name}", which is not part of the schema`);
|
|
1254
|
+
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`);
|
|
1255
|
+
for (let index = 0; index < from.length; index++) {
|
|
1256
|
+
const fromColumn = findColumn(source, from[index]);
|
|
1257
|
+
if (!fromColumn) throw new Error(`${subject}: unknown column "${from[index]}" of table "${source.name}"`);
|
|
1258
|
+
if (required && fromColumn.type.isNullable) throw new Error(`${subject} cannot be required: column "${from[index]}" of table "${source.name}" is nullable`);
|
|
1259
|
+
const toColumn = findColumn(target, to[index]);
|
|
1260
|
+
if (!toColumn) throw new Error(`${subject}: unknown column "${to[index]}" of table "${target.name}"`);
|
|
1261
|
+
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 =`);
|
|
1262
|
+
}
|
|
1263
|
+
if (kind === "one" && !containsKey(target, to)) throw new Error(`${subject}: columns "to" must include a key of table "${target.name}", primary or unique`);
|
|
1264
|
+
return Object.freeze({
|
|
1265
|
+
kind,
|
|
1266
|
+
name,
|
|
1267
|
+
key,
|
|
1268
|
+
source,
|
|
1269
|
+
target,
|
|
1270
|
+
targetKey,
|
|
1271
|
+
from,
|
|
1272
|
+
to,
|
|
1273
|
+
required
|
|
1274
|
+
});
|
|
1275
|
+
}
|
|
1276
|
+
/** Adds `definition` of relation `name` of the table under `key` to `relations`, rejecting another definition of the relation there. */
|
|
1277
|
+
function addRelation(relations, key, name, definition) {
|
|
1278
|
+
let named = relations.get(key);
|
|
1279
|
+
if (named === void 0) {
|
|
1280
|
+
named = /* @__PURE__ */ new Map();
|
|
1281
|
+
relations.set(key, named);
|
|
1282
|
+
}
|
|
1283
|
+
const existing = named.get(name);
|
|
1284
|
+
if (existing !== void 0 && existing !== definition) throw new Error(`Relation "${formatRelationName(key, name)}" has two different definitions`);
|
|
1285
|
+
named.set(name, definition);
|
|
1286
|
+
}
|
|
1287
|
+
/** Adds the relation definitions of a schema to `relations`, rejecting another definition of a relation there. */
|
|
1288
|
+
function addRelations(relations, added) {
|
|
1289
|
+
for (const key of Object.keys(added)) {
|
|
1290
|
+
const named = added[key];
|
|
1291
|
+
for (const name of Object.keys(named)) addRelation(relations, key, name, named[name]);
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
/** Collects the relation definitions of a schema, which a `Db` of the schema accepts in its queries. */
|
|
1295
|
+
function collectDefinitions(relations) {
|
|
1296
|
+
const definitions = /* @__PURE__ */ new Set();
|
|
1297
|
+
for (const key of Object.keys(relations)) {
|
|
1298
|
+
const named = relations[key];
|
|
1299
|
+
for (const name of Object.keys(named)) definitions.add(named[name]);
|
|
1300
|
+
}
|
|
1301
|
+
return definitions;
|
|
1302
|
+
}
|
|
1303
|
+
/** Creates frozen relations of a schema from `relations`; objects without a prototype keep any key, such as `__proto__`, an own property. */
|
|
1304
|
+
function freezeRelations(relations) {
|
|
1305
|
+
const result = Object.create(null);
|
|
1306
|
+
for (const [key, named] of relations) {
|
|
1307
|
+
const table = Object.create(null);
|
|
1308
|
+
for (const [name, definition] of named) table[name] = definition;
|
|
1309
|
+
result[key] = Object.freeze(table);
|
|
1310
|
+
}
|
|
1311
|
+
return Object.freeze(result);
|
|
1312
|
+
}
|
|
1313
|
+
function isRelationDeclaration(value) {
|
|
1314
|
+
return typeof value === "object" && value !== null && declarationBrand in value;
|
|
1315
|
+
}
|
|
1316
|
+
// src/query/rows.ts
|
|
1317
|
+
/** Returns the rows mode of a query of the records of `relation`, as `RelationRows` gives it in types. */
|
|
1318
|
+
function getRelationRows(relation) {
|
|
1319
|
+
if (relation.kind === "many") return "many";
|
|
1320
|
+
return relation.required ? "one" : "nullable";
|
|
1321
|
+
}
|
|
1322
|
+
/** Returns the rows mode after a filter of a query of rows mode `rows`, of values when `value`, whose row is `guaranteed`, as `FilteredStateRows` gives it in types. */
|
|
1323
|
+
function toFilteredRows(rows, value, guaranteed) {
|
|
1324
|
+
if (!guaranteed || rows !== "one") return rows;
|
|
1325
|
+
return value ? "optional" : "nullable";
|
|
1326
|
+
}
|
|
1327
|
+
/** Returns the limit of a query of many rows that becomes a query of one row, given its limit `limit`: one row, or none under a limit of zero. */
|
|
1328
|
+
function limitToOne(limit) {
|
|
1329
|
+
return limit?.kind === "param" && limit.value === 0 ? limit : oneNode;
|
|
1330
|
+
}
|
|
1331
|
+
/** Returns the rows mode after `pluck` of a query of rows mode `rows`, as `ValueRows` gives it in types. */
|
|
1332
|
+
function toValueRows(rows) {
|
|
1333
|
+
return rows === "nullable" ? "optional" : rows;
|
|
1334
|
+
}
|
|
1335
|
+
// src/query/node.ts
|
|
1336
|
+
/** Creates a query of all rows of `from`, or of the records of `relation` with `filters` in the rows mode of the relation. */
|
|
1337
|
+
function createQueryNode(from, relation, filters = noFilters) {
|
|
1338
|
+
return Object.freeze({
|
|
1339
|
+
kind: "query",
|
|
1340
|
+
from,
|
|
1341
|
+
relation,
|
|
1342
|
+
projections: [],
|
|
1343
|
+
filters,
|
|
1344
|
+
groupBy: [],
|
|
1345
|
+
having: void 0,
|
|
1346
|
+
orderBy: [],
|
|
1347
|
+
limit: void 0,
|
|
1348
|
+
offset: void 0,
|
|
1349
|
+
distinct: false,
|
|
1350
|
+
distinctOn: [],
|
|
1351
|
+
distinctFields: void 0,
|
|
1352
|
+
lock: void 0,
|
|
1353
|
+
rows: relation === void 0 ? "many" : getRelationRows(relation),
|
|
1354
|
+
value: false,
|
|
1355
|
+
guaranteed: relation?.required ?? false,
|
|
1356
|
+
all: false,
|
|
1357
|
+
conversion: void 0
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
/** Tells whether `node` is a query of a table without clauses, such as a table of a `Db`: no relation, filters, selected fields, keys of groups, order, limit, offset, `distinct`, keys of `distinctOn`, row lock, rows other than `many`, `all`, or conversion. */
|
|
1361
|
+
function isTableQuery(node) {
|
|
1362
|
+
return node.relation === void 0 && node.projections.length === 0 && node.filters.relation === void 0 && node.filters.scope === void 0 && node.filters.user === void 0 && node.groupBy.length === 0 && node.orderBy.length === 0 && node.limit === void 0 && node.offset === void 0 && !node.distinct && node.distinctOn.length === 0 && node.lock === void 0 && node.rows === "many" && !node.all && node.conversion === void 0;
|
|
1363
|
+
}
|
|
1364
|
+
/** Tells whether a selected field is the rows of a nested query. */
|
|
1365
|
+
function isNestedSelection(node) {
|
|
1366
|
+
return "query" in node;
|
|
1367
|
+
}
|
|
1368
|
+
/** Tells whether a selected field is a literal. */
|
|
1369
|
+
function isLiteralSelection(node) {
|
|
1370
|
+
return "literal" in node;
|
|
1371
|
+
}
|
|
1372
|
+
// src/lowering/context.ts
|
|
1373
|
+
/** Rejects a query of a relation outside the definitions of `context`. */
|
|
1374
|
+
function checkRelation(node, context) {
|
|
1375
|
+
const { relation } = node;
|
|
1376
|
+
const { definitions } = context;
|
|
1377
|
+
if (relation !== void 0 && definitions !== void 0 && !definitions.has(relation)) throw new Error(`Relation "${formatRelationName(relation.key, relation.name)}" is not part of the schema`);
|
|
1378
|
+
}
|
|
1379
|
+
/** Rejects a nested query bound to `db`, which the error names as `subject`, unless `db` is the `Db` of `context` or `undefined`. */
|
|
1380
|
+
function checkDb(db, context, subject) {
|
|
1381
|
+
if (db !== void 0 && db !== context.db) throw new Error(context.db === void 0 ? `${subject} is bound to a Db, so only that Db can compile the query` : `${subject} is bound to another Db`);
|
|
1382
|
+
}
|
|
1383
|
+
// src/lowering/expression.ts
|
|
1384
|
+
/**
|
|
1385
|
+
* Lowers an expression, replacing each query in it and checking the query as a nested query.
|
|
1386
|
+
* A query of `exists`, such as in a condition, becomes `EXISTS` of its rows, another query of one value a scalar subquery of its value, the query of the values of `IN` its statement, and another query in SQL text its statement in parentheses.
|
|
1387
|
+
*
|
|
1388
|
+
* It returns `node` itself when it holds no query, and creates only the nodes that hold one.
|
|
1389
|
+
*/
|
|
1390
|
+
function lowerExpression(node, context) {
|
|
1391
|
+
switch (node.kind) {
|
|
1392
|
+
case "column":
|
|
1393
|
+
case "param":
|
|
1394
|
+
case "boolean":
|
|
1395
|
+
case "values":
|
|
1396
|
+
case "tableName":
|
|
1397
|
+
case "subquery":
|
|
1398
|
+
case "exists":
|
|
1399
|
+
case "textSubquery": return node;
|
|
1400
|
+
case "nestedQuery": return lowerNestedQuery(node, context);
|
|
1401
|
+
case "cast": {
|
|
1402
|
+
const operand = lowerExpression(node.operand, context);
|
|
1403
|
+
return operand === node.operand ? node : createNode({
|
|
1404
|
+
kind: "cast",
|
|
1405
|
+
operand,
|
|
1406
|
+
type: node.type
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
case "not": {
|
|
1410
|
+
const operand = lowerExpression(node.operand, context);
|
|
1411
|
+
return operand === node.operand ? node : createNode({
|
|
1412
|
+
kind: "not",
|
|
1413
|
+
operand
|
|
1414
|
+
});
|
|
1415
|
+
}
|
|
1416
|
+
case "isNull": {
|
|
1417
|
+
const operand = lowerExpression(node.operand, context);
|
|
1418
|
+
return operand === node.operand ? node : createNode({
|
|
1419
|
+
kind: "isNull",
|
|
1420
|
+
operand
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
case "and":
|
|
1424
|
+
case "or": {
|
|
1425
|
+
const operands = lowerEach(node.operands, context, lowerExpression);
|
|
1426
|
+
return operands === node.operands ? node : createNode({
|
|
1427
|
+
kind: node.kind,
|
|
1428
|
+
operands
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
case "comparison": {
|
|
1432
|
+
const left = lowerExpression(node.left, context);
|
|
1433
|
+
const right = lowerExpression(node.right, context);
|
|
1434
|
+
return left === node.left && right === node.right ? node : createNode({
|
|
1435
|
+
kind: "comparison",
|
|
1436
|
+
operator: node.operator,
|
|
1437
|
+
left,
|
|
1438
|
+
right
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
case "in": {
|
|
1442
|
+
const operand = lowerExpression(node.operand, context);
|
|
1443
|
+
const list = lowerEach(node.list, context, lowerExpression);
|
|
1444
|
+
return operand === node.operand && list === node.list ? node : createNode({
|
|
1445
|
+
kind: "in",
|
|
1446
|
+
operand,
|
|
1447
|
+
list
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
case "inQuery": {
|
|
1451
|
+
const operand = lowerExpression(node.operand, context);
|
|
1452
|
+
const query = node.query.kind === "nestedQuery" ? lowerQueryOfValues(node.query, context) : node.query;
|
|
1453
|
+
return operand === node.operand && query === node.query ? node : createNode({
|
|
1454
|
+
kind: "inQuery",
|
|
1455
|
+
operand,
|
|
1456
|
+
query
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
case "raw": {
|
|
1460
|
+
const values = lowerEach(node.values, context, lowerExpression);
|
|
1461
|
+
return values === node.values ? node : createNode({
|
|
1462
|
+
kind: "raw",
|
|
1463
|
+
fragments: node.fragments,
|
|
1464
|
+
values
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
1467
|
+
case "aggregate": {
|
|
1468
|
+
const args = lowerEach(node.arguments, context, lowerExpression);
|
|
1469
|
+
const orderBy = lowerOrder(node.orderBy, context);
|
|
1470
|
+
const filter = lowerValue(node.filter, context);
|
|
1471
|
+
return args === node.arguments && orderBy === node.orderBy && filter === node.filter ? node : createNode({
|
|
1472
|
+
kind: "aggregate",
|
|
1473
|
+
name: node.name,
|
|
1474
|
+
distinct: node.distinct,
|
|
1475
|
+
arguments: args,
|
|
1476
|
+
orderBy,
|
|
1477
|
+
filter
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
default: return node;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
/** Lowers an optional expression, such as `having` of a query or a value of a row of an insert, as `lowerExpression` does. */
|
|
1484
|
+
function lowerValue(node, context) {
|
|
1485
|
+
return node === void 0 ? void 0 : lowerExpression(node, context);
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* Lowers a query in an expression to `EXISTS` of the rows of a query of `exists`, to a scalar subquery of the value of another query of one value, or to its statement in parentheses for a query of records or of rows `many`, which only SQL text holds.
|
|
1489
|
+
*
|
|
1490
|
+
* In SQL text, a query of `exists` stays `EXISTS` rather than a subquery of its value, so that PostgreSQL can join its rows in a condition, as a semi-join.
|
|
1491
|
+
*/
|
|
1492
|
+
function lowerNestedQuery(node, context) {
|
|
1493
|
+
checkDb(node.db, context, "A query in an expression");
|
|
1494
|
+
const { query } = node;
|
|
1495
|
+
if (isExistsQuery(query)) return context.lowerExists(query);
|
|
1496
|
+
return createNode({
|
|
1497
|
+
kind: query.value && query.rows !== "many" ? "subquery" : "textSubquery",
|
|
1498
|
+
query: context.lowerSelect(query, sortsByPositions(query))
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
/** Lowers the query of the values of `IN` to its statement, whatever its rows; it tells positions as `sortsByPositions` does. */
|
|
1502
|
+
function lowerQueryOfValues(node, context) {
|
|
1503
|
+
checkDb(node.db, context, "A query in an expression");
|
|
1504
|
+
return context.lowerSelect(node.query, sortsByPositions(node.query));
|
|
1505
|
+
}
|
|
1506
|
+
/** Tells whether the statement of `node` in a subquery sorts by the positions of its projections: PostgreSQL finds a sort expression of `SELECT DISTINCT` or `GROUP BY` only when it is equal to a selected one or a key, and the keys of `DISTINCT ON` with the order only when they are equal, while a repeated expression has aliases of its own and, apart from the parameters of casts in a query of groups, parameters of its own. */
|
|
1507
|
+
function sortsByPositions(node) {
|
|
1508
|
+
return node.distinct || node.distinctOn.length > 0 || node.groupBy.length > 0;
|
|
1509
|
+
}
|
|
1510
|
+
/** Lowers the filters of a query, replacing the queries in their expressions; without queries, it returns `filters` itself. */
|
|
1511
|
+
function lowerFilters(filters, context) {
|
|
1512
|
+
const { relation, scope, user } = filters;
|
|
1513
|
+
const loweredRelation = relation === void 0 ? void 0 : lowerExpression(relation, context);
|
|
1514
|
+
const loweredScope = scope === void 0 ? void 0 : lowerExpression(scope, context);
|
|
1515
|
+
const loweredUser = user === void 0 ? void 0 : lowerExpression(user, context);
|
|
1516
|
+
if (loweredRelation === relation && loweredScope === scope && loweredUser === user) return filters;
|
|
1517
|
+
const lowered = {};
|
|
1518
|
+
if (loweredRelation !== void 0) lowered.relation = loweredRelation;
|
|
1519
|
+
if (loweredScope !== void 0) lowered.scope = loweredScope;
|
|
1520
|
+
if (loweredUser !== void 0) lowered.user = loweredUser;
|
|
1521
|
+
return Object.freeze(lowered);
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Lowers the sort keys of a query, replacing the queries in their expressions; without queries, it returns `orderBy` itself.
|
|
1525
|
+
*
|
|
1526
|
+
* Each sort key is lowered by `lowerSelectedValue` over `selected`, the fields of the query, and `projections`, their lowered projections.
|
|
1527
|
+
*/
|
|
1528
|
+
function lowerOrder(orderBy, context, selected, projections) {
|
|
1529
|
+
let lowered;
|
|
1530
|
+
for (let index = 0; index < orderBy.length; index++) {
|
|
1531
|
+
const order = orderBy[index];
|
|
1532
|
+
const { expression } = order;
|
|
1533
|
+
const sorted = lowerSelectedValue(expression, context, selected, projections);
|
|
1534
|
+
if (lowered === void 0 && sorted === expression) continue;
|
|
1535
|
+
lowered ??= orderBy.slice(0, index);
|
|
1536
|
+
lowered.push(sorted === expression ? order : Object.freeze({
|
|
1537
|
+
expression: sorted,
|
|
1538
|
+
direction: order.direction,
|
|
1539
|
+
nulls: order.nulls
|
|
1540
|
+
}));
|
|
1541
|
+
}
|
|
1542
|
+
return lowered ?? orderBy;
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1545
|
+
* Lowers the keys of `groupBy` or `distinctOn` of a query, or `undefined` for a query without them.
|
|
1546
|
+
*
|
|
1547
|
+
* Each key is lowered by `lowerSelectedValue` over `selected`, the fields of the query, and `projections`, their lowered projections.
|
|
1548
|
+
*/
|
|
1549
|
+
function lowerKeys(keys, context, selected, projections) {
|
|
1550
|
+
return keys.length === 0 ? void 0 : lowerEach(keys, context, (key, keyContext) => lowerSelectedValue(key, keyContext, selected, projections));
|
|
1551
|
+
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Lowers `expression`, a sort key, a key of a group, or the argument of an aggregate: the value of a field of `selected` gets the expression of its lowered projection among `projections`, and another expression is lowered as it is.
|
|
1554
|
+
*
|
|
1555
|
+
* Lowering a field that holds a query gives its projection a new node, so reusing that node keeps the projection identifiable by its position.
|
|
1556
|
+
* A field of an aggregate or of `exists` is identified by the node of its reference, which holds the field.
|
|
1557
|
+
*/
|
|
1558
|
+
function lowerSelectedValue(expression, context, selected, projections) {
|
|
1559
|
+
const position = selected === void 0 || projections === void 0 || projections === selected ? -1 : selected.findIndex((field) => isFieldValue(field, expression));
|
|
1560
|
+
return position === -1 ? lowerExpression(expression, context) : projections[position].expression;
|
|
1561
|
+
}
|
|
1562
|
+
/** Tells whether `expression`, a sort key, a key of a group, or the argument of an aggregate, is the value of `field`: its expression, or for a field of an aggregate or of `exists`, the node of its reference in the callback of `orderBy` or `groupBy`. */
|
|
1563
|
+
function isFieldValue(field, expression) {
|
|
1564
|
+
return isNestedSelection(field) ? expression.kind === "nestedQuery" && expression.field === field : field.expression === expression;
|
|
1565
|
+
}
|
|
1566
|
+
/** Lowers each of `items` with `lower`; when none changes, it returns `items` itself. */
|
|
1567
|
+
function lowerEach(items, context, lower) {
|
|
1568
|
+
let lowered;
|
|
1569
|
+
for (let index = 0; index < items.length; index++) {
|
|
1570
|
+
const item = items[index];
|
|
1571
|
+
const result = lower(item, context);
|
|
1572
|
+
if (lowered !== void 0) lowered.push(result);
|
|
1573
|
+
else if (result !== item) {
|
|
1574
|
+
lowered = items.slice(0, index);
|
|
1575
|
+
lowered.push(result);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
return lowered ?? items;
|
|
1579
|
+
}
|
|
1580
|
+
// src/lowering/order.ts
|
|
1581
|
+
/** Creates the number of the projection at `position`, by which `ORDER BY` sorts by its value instead of evaluating an expression again. */
|
|
1582
|
+
function createPositionNode(position) {
|
|
1583
|
+
return createNode({
|
|
1584
|
+
kind: "raw",
|
|
1585
|
+
fragments: [String(position + 1)],
|
|
1586
|
+
values: []
|
|
1587
|
+
});
|
|
1588
|
+
}
|
|
1589
|
+
/** Creates the order of a statement that sorts by the positions of the projections among `projections` that have the values of its sort expressions, and by the other expressions as they are. */
|
|
1590
|
+
function sortByPositions(orderBy, projections) {
|
|
1591
|
+
const result = [];
|
|
1592
|
+
for (const order of orderBy) {
|
|
1593
|
+
const position = findValueProjection(projections, order.expression);
|
|
1594
|
+
result.push(position === -1 ? order : Object.freeze({
|
|
1595
|
+
expression: createPositionNode(position),
|
|
1596
|
+
direction: order.direction,
|
|
1597
|
+
nulls: order.nulls
|
|
1598
|
+
}));
|
|
1599
|
+
}
|
|
1600
|
+
return result;
|
|
1601
|
+
}
|
|
1602
|
+
/**
|
|
1603
|
+
* Creates the derived source of the rows of `query`, and, when `ordered`, the order of the query over the projections of the source, in which its reader takes the rows, such as an aggregate.
|
|
1604
|
+
*
|
|
1605
|
+
* The order of a derived source does not carry into the query that reads it, so the reader sorts by sort keys: the projections that have the values of the sort expressions, as for an executed query, or projections of the sort expressions added to the source.
|
|
1606
|
+
* With a limit or an offset, the source sorts by the positions of the sort keys, so that the rows it chooses, their values, and their order in the reader come from one evaluation; so it does with `DISTINCT ON`, whose order chooses the first row of each group, and with a row lock, which takes the rows in the order of its query.
|
|
1607
|
+
* Without them, it has no order.
|
|
1608
|
+
* `offset` replaces the offset of `query` in the source, such as `OFFSET 0` that keeps PostgreSQL from merging it, and the source replaces the occurrence of a table `replaces` for its reader.
|
|
1609
|
+
*/
|
|
1610
|
+
function deriveOrderedSource(query, ordered, offset = query.offset, replaces) {
|
|
1611
|
+
const { orderBy } = query;
|
|
1612
|
+
const projections = query.projections.slice();
|
|
1613
|
+
const sorted = query.limit !== void 0 || query.offset !== void 0 || query.distinctOn !== void 0 || query.lock !== void 0;
|
|
1614
|
+
const sortKeys = [];
|
|
1615
|
+
const positions = [];
|
|
1616
|
+
if (orderBy.length > 0 && (ordered || sorted)) for (let index = 0; index < orderBy.length; index++) {
|
|
1617
|
+
const { expression, direction, nulls } = orderBy[index];
|
|
1618
|
+
const position = projectSortKey(projections, expression, index);
|
|
1619
|
+
if (ordered) sortKeys.push({
|
|
1620
|
+
key: projections[position].key,
|
|
1621
|
+
direction,
|
|
1622
|
+
nulls
|
|
1623
|
+
});
|
|
1624
|
+
if (sorted) positions.push(Object.freeze({
|
|
1625
|
+
expression: createPositionNode(position),
|
|
1626
|
+
direction,
|
|
1627
|
+
nulls
|
|
1628
|
+
}));
|
|
1629
|
+
}
|
|
1630
|
+
const derivedQuery = Object.freeze({
|
|
1631
|
+
...query,
|
|
1632
|
+
projections,
|
|
1633
|
+
orderBy: positions,
|
|
1634
|
+
offset
|
|
1635
|
+
});
|
|
1636
|
+
const source = Object.freeze(replaces === void 0 ? {
|
|
1637
|
+
kind: "derived",
|
|
1638
|
+
query: derivedQuery,
|
|
1639
|
+
lateral: false
|
|
1640
|
+
} : {
|
|
1641
|
+
kind: "derived",
|
|
1642
|
+
query: derivedQuery,
|
|
1643
|
+
lateral: false,
|
|
1644
|
+
replaces
|
|
1645
|
+
});
|
|
1646
|
+
const order = [];
|
|
1647
|
+
for (const { key, direction, nulls } of sortKeys) order.push(Object.freeze({
|
|
1648
|
+
expression: createNode({
|
|
1649
|
+
kind: "column",
|
|
1650
|
+
source,
|
|
1651
|
+
key
|
|
1652
|
+
}),
|
|
1653
|
+
direction,
|
|
1654
|
+
nulls
|
|
1655
|
+
}));
|
|
1656
|
+
return {
|
|
1657
|
+
source,
|
|
1658
|
+
order
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Returns the position of the projection that sorts by `expression`: the projection of `findValueProjection`, or one added to `projections`.
|
|
1663
|
+
*
|
|
1664
|
+
* `index` is the position of the expression in the order.
|
|
1665
|
+
*/
|
|
1666
|
+
function projectSortKey(projections, expression, index) {
|
|
1667
|
+
const position = findValueProjection(projections, expression);
|
|
1668
|
+
if (position !== -1) return position;
|
|
1669
|
+
projections.push(Object.freeze({
|
|
1670
|
+
key: createSortProjectionKey(projections, index),
|
|
1671
|
+
expression,
|
|
1672
|
+
type: text
|
|
1673
|
+
}));
|
|
1674
|
+
return projections.length - 1;
|
|
1675
|
+
}
|
|
1676
|
+
/** Creates the key of the sort key projection at `index` of the sort keys, which no other projection has. */
|
|
1677
|
+
function createSortProjectionKey(projections, index) {
|
|
1678
|
+
const base = `$order${index + 1}`;
|
|
1679
|
+
let key = base;
|
|
1680
|
+
for (let number = 2; projections.some((projection) => projection.key === key); number++) key = `${base}_${number}`;
|
|
1681
|
+
return key;
|
|
1682
|
+
}
|
|
1683
|
+
// src/lowering/nested.ts
|
|
1684
|
+
/** Maximum number of arguments of a PostgreSQL function, `FUNC_MAX_ARGS` of its default build. */
|
|
1685
|
+
const maxFunctionArguments = 100;
|
|
1686
|
+
/** Number `0`, the offset that keeps PostgreSQL from merging a derived source into its query. */
|
|
1687
|
+
const zeroNode = /* @__PURE__ */ createNode({
|
|
1688
|
+
kind: "raw",
|
|
1689
|
+
fragments: ["0"],
|
|
1690
|
+
values: []
|
|
1691
|
+
});
|
|
1692
|
+
/**
|
|
1693
|
+
* Creates the projection of the rows of `query` packed as JSON under `key`, selected as a scalar subquery and decoded by the result plan of `query`.
|
|
1694
|
+
*
|
|
1695
|
+
* Rows `many` are one array, and the other rows modes are one packed row or `NULL` without a row; a scalar subquery fails with several rows.
|
|
1696
|
+
*/
|
|
1697
|
+
function projectRows(key, query) {
|
|
1698
|
+
const packed = packRows(query);
|
|
1699
|
+
const { nested } = packed.projections[0];
|
|
1700
|
+
return Object.freeze({
|
|
1701
|
+
key,
|
|
1702
|
+
expression: createNode({
|
|
1703
|
+
kind: "subquery",
|
|
1704
|
+
query: packed
|
|
1705
|
+
}),
|
|
1706
|
+
nested
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
/**
|
|
1710
|
+
* Creates a query whose only projection is the rows of `query` packed as JSON, a field decoded by the result plan of `query`.
|
|
1711
|
+
*
|
|
1712
|
+
* Rows `many` are packed as an array in the order of `query`, and the created query returns one row.
|
|
1713
|
+
* Otherwise the created query returns a packed row for each row of `query`, so a scalar subquery of it gives the packed row, `NULL` without a row, and fails with several rows.
|
|
1714
|
+
*/
|
|
1715
|
+
function packRows(query) {
|
|
1716
|
+
const { projections } = query;
|
|
1717
|
+
const many = query.rows === "many";
|
|
1718
|
+
const { source, order } = deriveOrderedSource(query, many, !query.distinct && query.distinctOn === void 0 && query.groupBy === void 0 && query.lock === void 0 && query.limit === void 0 && query.offset === void 0 && projections.some((projection) => projection.nested === void 0 && !isTableColumn(projection.expression)) ? zeroNode : query.offset);
|
|
1719
|
+
const wide = projections.length > maxFunctionArguments;
|
|
1720
|
+
const values = [];
|
|
1721
|
+
for (const projection of projections) {
|
|
1722
|
+
const value = createRef(source, projection.key);
|
|
1723
|
+
if (projection.nested !== void 0) values.push(value);
|
|
1724
|
+
else values.push(wide ? createList("to_json(", [packScalar(value)], ")") : packScalar(value));
|
|
1725
|
+
}
|
|
1726
|
+
const row = wide ? createList("array_to_json(ARRAY[", values, "])") : createList("json_build_array(", values, ")");
|
|
1727
|
+
let packed = row;
|
|
1728
|
+
if (many) packed = createNode({
|
|
1729
|
+
kind: "raw",
|
|
1730
|
+
fragments: ["coalesce(", ", '[]'::json)"],
|
|
1731
|
+
values: [createNode({
|
|
1732
|
+
kind: "aggregate",
|
|
1733
|
+
name: "json_agg",
|
|
1734
|
+
distinct: false,
|
|
1735
|
+
arguments: [row],
|
|
1736
|
+
orderBy: order,
|
|
1737
|
+
filter: void 0
|
|
1738
|
+
})]
|
|
1739
|
+
});
|
|
1740
|
+
const plan = Object.freeze({
|
|
1741
|
+
fields: projections,
|
|
1742
|
+
rows: query.rows,
|
|
1743
|
+
value: query.value,
|
|
1744
|
+
guaranteedBy: query.guaranteedBy,
|
|
1745
|
+
recordTemplate: query.recordTemplate,
|
|
1746
|
+
conversion: query.conversion
|
|
1747
|
+
});
|
|
1748
|
+
const projection = Object.freeze({
|
|
1749
|
+
key: "rows",
|
|
1750
|
+
expression: packed,
|
|
1751
|
+
nested: plan
|
|
1752
|
+
});
|
|
1753
|
+
return createSelectNode(source, [projection]);
|
|
1754
|
+
}
|
|
1755
|
+
/** Tells whether `node` is a column of a table, which PostgreSQL reads rather than evaluates, so it can be repeated. */
|
|
1756
|
+
function isTableColumn(node) {
|
|
1757
|
+
return node.kind === "column" && node.source.kind === "table";
|
|
1758
|
+
}
|
|
1759
|
+
/**
|
|
1760
|
+
* Packs a scalar as its PostgreSQL text representation, or `NULL`.
|
|
1761
|
+
*
|
|
1762
|
+
* `format` uses the output function of the type, as the driver receives the values of a row; a cast to `text` differs from it for types such as `boolean`, `inet`, and `char`.
|
|
1763
|
+
*/
|
|
1764
|
+
function packScalar(value) {
|
|
1765
|
+
return createNode({
|
|
1766
|
+
kind: "raw",
|
|
1767
|
+
fragments: [
|
|
1768
|
+
"CASE WHEN ",
|
|
1769
|
+
" IS NOT DISTINCT FROM NULL THEN NULL ELSE format('%s', ",
|
|
1770
|
+
") END"
|
|
1771
|
+
],
|
|
1772
|
+
values: [value, value]
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
function createRef(source, key) {
|
|
1776
|
+
return createNode({
|
|
1777
|
+
kind: "column",
|
|
1778
|
+
source,
|
|
1779
|
+
key
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
// src/lowering/projection.ts
|
|
1783
|
+
/**
|
|
1784
|
+
* Lowers the fields of a query to projections, packing the rows of each nested query into the value of its field, or selecting the value of an aggregate query or `EXISTS` of a query of `exists`, and replacing the queries in the expressions of the other fields; checks them as `lowerQuery` does.
|
|
1785
|
+
*
|
|
1786
|
+
* Without queries, it returns `selected` itself.
|
|
1787
|
+
*/
|
|
1788
|
+
function lowerProjections(selected, context) {
|
|
1789
|
+
let lowered;
|
|
1790
|
+
for (let index = 0; index < selected.length; index++) {
|
|
1791
|
+
const field = selected[index];
|
|
1792
|
+
let projection;
|
|
1793
|
+
if (isNestedSelection(field)) {
|
|
1794
|
+
checkDb(field.db, context, `Selected field "${field.key}"`);
|
|
1795
|
+
projection = projectQuery(field.key, field.query, context);
|
|
1796
|
+
} else {
|
|
1797
|
+
const expression = lowerExpression(field.expression, context);
|
|
1798
|
+
projection = expression === field.expression ? field : Object.freeze({
|
|
1799
|
+
key: field.key,
|
|
1800
|
+
expression,
|
|
1801
|
+
type: field.type
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
if (lowered !== void 0) lowered.push(projection);
|
|
1805
|
+
else if (projection !== field) {
|
|
1806
|
+
lowered = selected.slice(0, index);
|
|
1807
|
+
lowered.push(projection);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
return lowered ?? selected;
|
|
1811
|
+
}
|
|
1812
|
+
/** Creates the projection of the value of `node`, a nested query, under `key`: `EXISTS` of a query of `exists`, the value of an aggregate query, or the packed rows of another query or of one whose result code converts. */
|
|
1813
|
+
function projectQuery(key, node, context) {
|
|
1814
|
+
if (!isSelectedAsValue(node)) return projectRows(key, context.lowerSelect(node, false));
|
|
1815
|
+
return isExistsQuery(node) ? projectExists(key, node, context) : projectAggregateValue(key, context.lowerSelect(node, false));
|
|
1816
|
+
}
|
|
1817
|
+
/** Creates the projection of `EXISTS` of the rows of `node`, a query of `exists`, under `key`, decoded by the type of the projection of `exists`. */
|
|
1818
|
+
function projectExists(key, node, context) {
|
|
1819
|
+
return Object.freeze({
|
|
1820
|
+
key,
|
|
1821
|
+
expression: context.lowerExists(node),
|
|
1822
|
+
type: node.projections[0].type
|
|
1823
|
+
});
|
|
1824
|
+
}
|
|
1825
|
+
/** Creates the projection of the value of `query`, the statement of an aggregate query, under `key`, selected as a scalar subquery and decoded by the type of the aggregate. */
|
|
1826
|
+
function projectAggregateValue(key, query) {
|
|
1827
|
+
return Object.freeze({
|
|
1828
|
+
key,
|
|
1829
|
+
expression: createNode({
|
|
1830
|
+
kind: "subquery",
|
|
1831
|
+
query
|
|
1832
|
+
}),
|
|
1833
|
+
type: query.projections[0].type
|
|
1834
|
+
});
|
|
1835
|
+
}
|
|
1836
|
+
/** Returns the fields of `selected` that a statement selects, or `selected` itself without literals. */
|
|
1837
|
+
function dropLiterals(selected) {
|
|
1838
|
+
if (!selected.some(isLiteralSelection)) return selected;
|
|
1839
|
+
const fields = [];
|
|
1840
|
+
for (const field of selected) if (!isLiteralSelection(field)) fields.push(field);
|
|
1841
|
+
return fields;
|
|
1842
|
+
}
|
|
1843
|
+
/** Creates the template of the records of `selected`: every field in its order with the value of a literal, or `undefined` without literals. */
|
|
1844
|
+
function createRecordTemplate(selected) {
|
|
1845
|
+
if (!selected.some(isLiteralSelection)) return;
|
|
1846
|
+
const template = [];
|
|
1847
|
+
for (const field of selected) template.push(Object.freeze({
|
|
1848
|
+
key: field.key,
|
|
1849
|
+
value: isLiteralSelection(field) ? field.literal : void 0
|
|
1850
|
+
}));
|
|
1851
|
+
return template;
|
|
1852
|
+
}
|
|
1853
|
+
// src/lowering/distinct.ts
|
|
1854
|
+
/**
|
|
1855
|
+
* Rejects a query of `distinct` of the lowered `projections` and `orderBy` that `SELECT DISTINCT` cannot give the rows of, with an error that does not depend on where the query is:
|
|
1856
|
+
*
|
|
1857
|
+
* - A query without projections, such as of only literals, has nothing to compare, and PostgreSQL has no syntax for it.
|
|
1858
|
+
* - Nested rows are JSON, which PostgreSQL cannot compare.
|
|
1859
|
+
* - PostgreSQL rejects a sort key that is not a projection, since duplicates can differ in its value, whereas a packed query would add it to the projections of its derived source and compare it too.
|
|
1860
|
+
* Only a projection of the same column or of the same expression node is sure to have its value, as in `findValueProjection`.
|
|
1861
|
+
*/
|
|
1862
|
+
function checkDistinct(projections, orderBy) {
|
|
1863
|
+
if (projections.length === 0) throw new Error("distinct requires at least one selected column or SQL expression; literal fields are not compared");
|
|
1864
|
+
for (const { key, nested } of projections) if (nested !== void 0) throw new Error(`distinct cannot compare the nested rows of the selected field "${key}"`);
|
|
1865
|
+
for (const { expression } of orderBy) if (findValueProjection(projections, expression) === -1) throw new Error("A query of distinct sorts only by its selected fields, since duplicates can differ in any other value; select the value to sort by it");
|
|
1866
|
+
}
|
|
1867
|
+
/**
|
|
1868
|
+
* Rejects a query of `distinctOn` of the lowered `projections`, `keys`, and `orderBy` that `SELECT DISTINCT ON` cannot give the rows of, with an error that does not depend on where the query is: a query without projections, such as of only literals, since PostgreSQL requires a select list with `DISTINCT ON`, and an order that `checkDistinctOnOrder` rejects.
|
|
1869
|
+
*/
|
|
1870
|
+
function checkDistinctOn(projections, keys, orderBy) {
|
|
1871
|
+
if (projections.length === 0) throw new Error("distinctOn requires at least one selected column or SQL expression; literal fields are not selected");
|
|
1872
|
+
checkDistinctOnOrder(projections, keys, orderBy);
|
|
1873
|
+
}
|
|
1874
|
+
/**
|
|
1875
|
+
* Rejects an order of a query of `distinctOn` of the lowered `projections`, `keys`, and `orderBy` that sorts by a value other than the keys before it sorts by all of them, in any order and direction, which PostgreSQL rejects, since the order sorts the groups apart and then chooses the first row of each; an order of only keys may omit some, which PostgreSQL adds.
|
|
1876
|
+
*
|
|
1877
|
+
* A sort key is a key when it is the same column, or the same expression node that a projection of the query has, as `findValueProjection` tells, so that both compile to the same column or position.
|
|
1878
|
+
* Another expression may compile at each place with parameters and aliases of its own, so PostgreSQL may find the two unequal; the check runs before packing, which would add the expression to the projections of its derived source and make both positions, so that it counts as another value wherever the query is.
|
|
1879
|
+
*/
|
|
1880
|
+
function checkDistinctOnOrder(projections, keys, orderBy) {
|
|
1881
|
+
const isKey = (key, expression) => isSameValue(key, expression) && (key.kind === "column" || findValueProjection(projections, key) !== -1);
|
|
1882
|
+
let leading = 0;
|
|
1883
|
+
while (leading < orderBy.length && keys.some((key) => isKey(key, orderBy[leading].expression))) leading++;
|
|
1884
|
+
if (leading === orderBy.length) return;
|
|
1885
|
+
for (const key of keys) {
|
|
1886
|
+
let sorted = false;
|
|
1887
|
+
for (let index = 0; index < leading && !sorted; index++) sorted = isKey(key, orderBy[index].expression);
|
|
1888
|
+
if (!sorted) throw new Error("A query of distinctOn must sort by all its keys before any other value; sort by a key of an expression through its selected field");
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
/**
|
|
1892
|
+
* Lowers the rows of `node`, a query of `distinct` or `distinctOn` made by an aggregate method or `exists`, to the statement that gives them, which an aggregate reads from a derived source and `EXISTS` reads as it is.
|
|
1893
|
+
*
|
|
1894
|
+
* It lowers the fields that the query kept, its keys, its order, and `argument`, the first argument of the aggregate, through those fields, as `lowerSelectedValue` does, so that each value of a selected field is its projection, and checks the query as the statement of the query of those fields is checked, except that a query of `distinctOn` needs no selected field, since the statement selects its keys.
|
|
1895
|
+
*
|
|
1896
|
+
* - The statement of `distinct` selects the fields, which `DISTINCT` compares, and `argument` must be one of them, as a sort key must be, since duplicates can differ in any other value.
|
|
1897
|
+
* - The statement of `distinctOn` selects `argument` and each key that it does not select otherwise, so that it has a select list, which PostgreSQL requires with `DISTINCT ON`.
|
|
1898
|
+
* It selects no other field, since an aggregate reads the rows of the source rather than of the select list, as for a query without `distinctOn`, so it does not lower the fields of nested rows, which neither a key nor a sort key reads.
|
|
1899
|
+
*
|
|
1900
|
+
* The statement has the order of the query when `sorted` is set; the number of the rows, which `count(*)` and `EXISTS` read, does not depend on it.
|
|
1901
|
+
*/
|
|
1902
|
+
function lowerDistinctRows(node, context, argument, sorted) {
|
|
1903
|
+
const fields = dropLiterals(node.distinctFields);
|
|
1904
|
+
let selected = fields;
|
|
1905
|
+
if (!node.distinct) {
|
|
1906
|
+
const scalars = [];
|
|
1907
|
+
for (const field of fields) if (!isNestedSelection(field) || isSelectedAsValue(field.query)) scalars.push(field);
|
|
1908
|
+
selected = scalars;
|
|
1909
|
+
}
|
|
1910
|
+
const projections = lowerProjections(selected, context);
|
|
1911
|
+
const orderBy = lowerOrder(node.orderBy, context, selected, projections);
|
|
1912
|
+
const groupBy = lowerKeys(node.groupBy, context, selected, projections);
|
|
1913
|
+
const keys = lowerKeys(node.distinctOn, context, selected, projections);
|
|
1914
|
+
const value = argument === void 0 ? void 0 : lowerSelectedValue(argument, context, selected, projections);
|
|
1915
|
+
let sourced;
|
|
1916
|
+
let valueKey;
|
|
1917
|
+
if (keys === void 0) {
|
|
1918
|
+
checkDistinct(projections, orderBy);
|
|
1919
|
+
sourced = projections;
|
|
1920
|
+
if (value !== void 0) {
|
|
1921
|
+
const position = findValueProjection(projections, value);
|
|
1922
|
+
if (position === -1) throw new Error("An aggregate of a query of distinct reads only its selected fields, since duplicates can differ in any other value; select the value to aggregate it");
|
|
1923
|
+
valueKey = projections[position].key;
|
|
1924
|
+
}
|
|
1925
|
+
} else {
|
|
1926
|
+
checkDistinctOnOrder(projections, keys, orderBy);
|
|
1927
|
+
const keyed = [];
|
|
1928
|
+
if (value !== void 0) {
|
|
1929
|
+
valueKey = "value";
|
|
1930
|
+
keyed.push(Object.freeze({
|
|
1931
|
+
key: valueKey,
|
|
1932
|
+
expression: value,
|
|
1933
|
+
type: text
|
|
1934
|
+
}));
|
|
1935
|
+
}
|
|
1936
|
+
for (let index = 0; index < keys.length; index++) {
|
|
1937
|
+
const key = keys[index];
|
|
1938
|
+
if (findValueProjection(keyed, key) === -1) keyed.push(Object.freeze({
|
|
1939
|
+
key: `$key${index + 1}`,
|
|
1940
|
+
expression: key,
|
|
1941
|
+
type: text
|
|
1942
|
+
}));
|
|
1943
|
+
}
|
|
1944
|
+
sourced = keyed;
|
|
1945
|
+
}
|
|
1946
|
+
return {
|
|
1947
|
+
query: Object.freeze({
|
|
1948
|
+
kind: "select",
|
|
1949
|
+
from: node.from,
|
|
1950
|
+
joins: noJoins,
|
|
1951
|
+
projections: sourced,
|
|
1952
|
+
filters: lowerFilters(node.filters, context),
|
|
1953
|
+
groupBy,
|
|
1954
|
+
having: lowerValue(node.having, context),
|
|
1955
|
+
orderBy: sorted ? orderBy : noOrder,
|
|
1956
|
+
limit: node.limit,
|
|
1957
|
+
offset: node.offset,
|
|
1958
|
+
distinct: node.distinct,
|
|
1959
|
+
distinctOn: keys,
|
|
1960
|
+
rows: "many",
|
|
1961
|
+
value: false,
|
|
1962
|
+
guaranteedBy: void 0
|
|
1963
|
+
}),
|
|
1964
|
+
valueKey
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
// src/lowering/aggregate.ts
|
|
1968
|
+
/** Lowers an aggregate query to a statement of the value of its aggregate over the rows that its filters, limit, and offset choose, also the distinct rows of `distinct` and the first rows of `distinctOn`. */
|
|
1969
|
+
function lowerAggregate(node, context) {
|
|
1970
|
+
const field = node.projections[0];
|
|
1971
|
+
const aggregate = field.expression;
|
|
1972
|
+
const counted = aggregate === countProjection.expression;
|
|
1973
|
+
let from = node.from;
|
|
1974
|
+
let filters = noFilters;
|
|
1975
|
+
let args = aggregate.arguments;
|
|
1976
|
+
let order = noOrder;
|
|
1977
|
+
let rows;
|
|
1978
|
+
let valueKey;
|
|
1979
|
+
if (node.distinctFields !== void 0) {
|
|
1980
|
+
const distinctRows = lowerDistinctRows(node, context, counted ? void 0 : aggregate.arguments[0], !counted);
|
|
1981
|
+
rows = distinctRows.query;
|
|
1982
|
+
valueKey = distinctRows.valueKey;
|
|
1983
|
+
} else {
|
|
1984
|
+
const orderBy = lowerOrder(node.orderBy, context);
|
|
1985
|
+
const groupBy = lowerKeys(node.groupBy, context);
|
|
1986
|
+
filters = lowerFilters(node.filters, context);
|
|
1987
|
+
args = lowerEach(aggregate.arguments, context, lowerExpression);
|
|
1988
|
+
order = field.ordered ? orderBy : noOrder;
|
|
1989
|
+
if (groupBy !== void 0 || node.limit !== void 0 || node.offset !== void 0 || !counted && !refersToSource(args[0], node.from)) {
|
|
1990
|
+
const projections = [];
|
|
1991
|
+
if (!counted) {
|
|
1992
|
+
valueKey = "value";
|
|
1993
|
+
projections.push(Object.freeze({
|
|
1994
|
+
key: valueKey,
|
|
1995
|
+
expression: args[0],
|
|
1996
|
+
type: field.type
|
|
1997
|
+
}));
|
|
1998
|
+
}
|
|
1999
|
+
rows = {
|
|
2000
|
+
kind: "select",
|
|
2001
|
+
from: node.from,
|
|
2002
|
+
joins: noJoins,
|
|
2003
|
+
projections,
|
|
2004
|
+
filters,
|
|
2005
|
+
groupBy,
|
|
2006
|
+
having: lowerValue(node.having, context),
|
|
2007
|
+
orderBy: counted ? noOrder : orderBy,
|
|
2008
|
+
limit: node.limit,
|
|
2009
|
+
offset: node.offset,
|
|
2010
|
+
rows: "many",
|
|
2011
|
+
value: false,
|
|
2012
|
+
guaranteedBy: void 0
|
|
2013
|
+
};
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
if (rows !== void 0) {
|
|
2017
|
+
const derived = deriveOrderedSource(rows, field.ordered);
|
|
2018
|
+
from = derived.source;
|
|
2019
|
+
filters = noFilters;
|
|
2020
|
+
if (valueKey !== void 0) {
|
|
2021
|
+
const sourceArgs = [createNode({
|
|
2022
|
+
kind: "column",
|
|
2023
|
+
source: from,
|
|
2024
|
+
key: valueKey
|
|
2025
|
+
})];
|
|
2026
|
+
for (let index = 1; index < args.length; index++) sourceArgs.push(args[index]);
|
|
2027
|
+
args = sourceArgs;
|
|
2028
|
+
}
|
|
2029
|
+
order = derived.order;
|
|
2030
|
+
}
|
|
2031
|
+
const call = args === aggregate.arguments && order.length === 0 ? aggregate : createNode({
|
|
2032
|
+
kind: "aggregate",
|
|
2033
|
+
name: aggregate.name,
|
|
2034
|
+
distinct: aggregate.distinct,
|
|
2035
|
+
arguments: args,
|
|
2036
|
+
orderBy: order,
|
|
2037
|
+
filter: aggregate.filter
|
|
2038
|
+
});
|
|
2039
|
+
const fallbacks = lowerEach(field.fallbacks, context, lowerExpression);
|
|
2040
|
+
let value = call;
|
|
2041
|
+
if (fallbacks.length > 0) {
|
|
2042
|
+
const values = [call];
|
|
2043
|
+
for (const fallback of fallbacks) values.push(fallback);
|
|
2044
|
+
value = createList("coalesce(", values, ")");
|
|
2045
|
+
}
|
|
2046
|
+
return Object.freeze({
|
|
2047
|
+
kind: "select",
|
|
2048
|
+
from,
|
|
2049
|
+
joins: noJoins,
|
|
2050
|
+
projections: [value === aggregate ? field : Object.freeze({
|
|
2051
|
+
key: field.key,
|
|
2052
|
+
expression: value,
|
|
2053
|
+
type: field.type
|
|
2054
|
+
})],
|
|
2055
|
+
filters,
|
|
2056
|
+
orderBy: noOrder,
|
|
2057
|
+
limit: void 0,
|
|
2058
|
+
offset: void 0,
|
|
2059
|
+
rows: node.rows,
|
|
2060
|
+
value: true,
|
|
2061
|
+
guaranteedBy: void 0
|
|
2062
|
+
});
|
|
2063
|
+
}
|
|
2064
|
+
/**
|
|
2065
|
+
* Tells whether `node` refers to `source` outside the queries nested in it.
|
|
2066
|
+
*
|
|
2067
|
+
* A reference inside a nested query is not counted, so an argument that refers to the source only there is read from a derived source, which is correct either way.
|
|
2068
|
+
*/
|
|
2069
|
+
function refersToSource(node, source) {
|
|
2070
|
+
switch (node.kind) {
|
|
2071
|
+
case "column": return node.source === source;
|
|
2072
|
+
case "param":
|
|
2073
|
+
case "boolean":
|
|
2074
|
+
case "values":
|
|
2075
|
+
case "nestedQuery":
|
|
2076
|
+
case "tableName":
|
|
2077
|
+
case "subquery":
|
|
2078
|
+
case "exists":
|
|
2079
|
+
case "textSubquery": return false;
|
|
2080
|
+
case "cast":
|
|
2081
|
+
case "not":
|
|
2082
|
+
case "isNull":
|
|
2083
|
+
case "inQuery": return refersToSource(node.operand, source);
|
|
2084
|
+
case "and":
|
|
2085
|
+
case "or": return node.operands.some((operand) => refersToSource(operand, source));
|
|
2086
|
+
case "comparison": return refersToSource(node.left, source) || refersToSource(node.right, source);
|
|
2087
|
+
case "in": return refersToSource(node.operand, source) || node.list.some((item) => refersToSource(item, source));
|
|
2088
|
+
case "raw": return node.values.some((value) => refersToSource(value, source));
|
|
2089
|
+
case "aggregate": return node.arguments.some((argument) => refersToSource(argument, source)) || node.filter !== void 0 && refersToSource(node.filter, source);
|
|
2090
|
+
default: return node;
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
// src/lowering/exists.ts
|
|
2094
|
+
/** Lowers a query of `exists` to `EXISTS` of the rows that its filters, limit, and offset choose, also the distinct rows of `distinct` and the first rows of `distinctOn`. */
|
|
2095
|
+
function lowerExists(node, context) {
|
|
2096
|
+
checkRelation(node, context);
|
|
2097
|
+
return createNode({
|
|
2098
|
+
kind: "exists",
|
|
2099
|
+
query: node.distinctFields === void 0 ? Object.freeze({
|
|
2100
|
+
kind: "select",
|
|
2101
|
+
from: node.from,
|
|
2102
|
+
joins: noJoins,
|
|
2103
|
+
projections: noProjections,
|
|
2104
|
+
filters: lowerFilters(node.filters, context),
|
|
2105
|
+
groupBy: lowerKeys(node.groupBy, context),
|
|
2106
|
+
having: lowerValue(node.having, context),
|
|
2107
|
+
orderBy: noOrder,
|
|
2108
|
+
limit: node.limit,
|
|
2109
|
+
offset: node.offset,
|
|
2110
|
+
rows: "many",
|
|
2111
|
+
value: false,
|
|
2112
|
+
guaranteedBy: void 0
|
|
2113
|
+
}) : lowerDistinctRows(node, context, void 0, false).query
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
// src/ast/references.ts
|
|
2117
|
+
/** Adds to `keys` the key of each column reference to `source` in `node` at any depth, including the queries nested in it. */
|
|
2118
|
+
function collectColumnKeys(node, source, keys) {
|
|
2119
|
+
visitNodes(node, (child) => {
|
|
2120
|
+
if (child.kind === "column" && child.source === source) keys.add(child.key);
|
|
2121
|
+
});
|
|
2122
|
+
}
|
|
2123
|
+
/**
|
|
2124
|
+
* Tells whether `node` holds, at any depth, what may aggregate the rows of the query of `source`: an `aggregate` node or a SQL fragment that refers to a column of `source` at any depth, also in the queries nested in it.
|
|
2125
|
+
*
|
|
2126
|
+
* PostgreSQL assigns an aggregate whose arguments and filter refer only to the sources of an enclosing query to that query, also through a query nested in them ([PostgreSQL](https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-AGGREGATES)), so such a call in a nested query, such as `sum` of a column of the parent row, aggregates the rows of the query of `source`.
|
|
2127
|
+
* Lowering does not parse SQL fragments to identify their aggregates, so a fragment counts as such a call.
|
|
2128
|
+
*
|
|
2129
|
+
* It is conservative: an aggregate whose arguments read both `source` and its own query belongs to its own query, yet it counts, since this walk cannot tell a source of the query that holds the aggregate from one of an enclosing query.
|
|
2130
|
+
* So does a scalar fragment, also one that reads `source` only through a query correlated with it, such as of a relation.
|
|
2131
|
+
*/
|
|
2132
|
+
function mayAggregateSource(node, source) {
|
|
2133
|
+
let found = false;
|
|
2134
|
+
const check = (value) => {
|
|
2135
|
+
if (value.kind === "column" && value.source === source) found = true;
|
|
2136
|
+
};
|
|
2137
|
+
visitNodes(node, (child) => {
|
|
2138
|
+
if (!found && (child.kind === "aggregate" || child.kind === "raw")) visitNodes(child, check);
|
|
2139
|
+
});
|
|
2140
|
+
return found;
|
|
2141
|
+
}
|
|
2142
|
+
/**
|
|
2143
|
+
* Tells whether an aggregate belongs to an enclosing query rather than the query of `source`.
|
|
2144
|
+
*
|
|
2145
|
+
* Only references free in its arguments, order, and filter decide its owner: columns bound by a subquery do not count, but references through that subquery to its enclosing queries do.
|
|
2146
|
+
* Without such references, an aggregate of constants belongs to the query that contains it.
|
|
2147
|
+
* The node must have been lowered, so that subqueries expose their sources.
|
|
2148
|
+
*/
|
|
2149
|
+
function aggregatesOuterSource(node, source) {
|
|
2150
|
+
let local = false;
|
|
2151
|
+
let outer = false;
|
|
2152
|
+
const queries = [];
|
|
2153
|
+
visitNodes(node, (child) => {
|
|
2154
|
+
if (child.kind !== "column" || local) return;
|
|
2155
|
+
for (const query of queries) {
|
|
2156
|
+
if (bindsSource(query.from, child.source)) return;
|
|
2157
|
+
for (const join of query.joins) if (bindsSource(join.source, child.source)) return;
|
|
2158
|
+
}
|
|
2159
|
+
if (child.source === source) local = true;
|
|
2160
|
+
else outer = true;
|
|
2161
|
+
}, queries);
|
|
2162
|
+
return outer && !local;
|
|
2163
|
+
}
|
|
2164
|
+
/** Tells whether a declared source binds a reference, including the table occurrence a derived source replaces. */
|
|
2165
|
+
function bindsSource(declared, source) {
|
|
2166
|
+
return declared === source || declared?.kind === "derived" && declared.replaces === source;
|
|
2167
|
+
}
|
|
2168
|
+
/**
|
|
2169
|
+
* Calls `visit` for `node` and each expression node in it at any depth, including the queries nested in it.
|
|
2170
|
+
* When supplied, `queries` holds the nested queries enclosing each node passed to `visit`.
|
|
2171
|
+
*/
|
|
2172
|
+
function visitNodes(node, visit, queries) {
|
|
2173
|
+
visit(node);
|
|
2174
|
+
switch (node.kind) {
|
|
2175
|
+
case "column":
|
|
2176
|
+
case "param":
|
|
2177
|
+
case "boolean":
|
|
2178
|
+
case "tableName":
|
|
2179
|
+
case "values":
|
|
2180
|
+
case "nestedQuery": return;
|
|
2181
|
+
case "cast":
|
|
2182
|
+
case "not":
|
|
2183
|
+
case "isNull":
|
|
2184
|
+
visitNodes(node.operand, visit, queries);
|
|
2185
|
+
return;
|
|
2186
|
+
case "and":
|
|
2187
|
+
case "or":
|
|
2188
|
+
for (const operand of node.operands) visitNodes(operand, visit, queries);
|
|
2189
|
+
return;
|
|
2190
|
+
case "comparison":
|
|
2191
|
+
visitNodes(node.left, visit, queries);
|
|
2192
|
+
visitNodes(node.right, visit, queries);
|
|
2193
|
+
return;
|
|
2194
|
+
case "in":
|
|
2195
|
+
visitNodes(node.operand, visit, queries);
|
|
2196
|
+
for (const item of node.list) visitNodes(item, visit, queries);
|
|
2197
|
+
return;
|
|
2198
|
+
case "inQuery":
|
|
2199
|
+
visitNodes(node.operand, visit, queries);
|
|
2200
|
+
if (node.query.kind === "select") visitQuery(node.query, visit, queries);
|
|
2201
|
+
return;
|
|
2202
|
+
case "raw":
|
|
2203
|
+
for (const value of node.values) visitNodes(value, visit, queries);
|
|
2204
|
+
return;
|
|
2205
|
+
case "subquery":
|
|
2206
|
+
case "exists":
|
|
2207
|
+
case "textSubquery":
|
|
2208
|
+
visitQuery(node.query, visit, queries);
|
|
2209
|
+
return;
|
|
2210
|
+
case "aggregate":
|
|
2211
|
+
for (const argument of node.arguments) visitNodes(argument, visit, queries);
|
|
2212
|
+
for (const order of node.orderBy) visitNodes(order.expression, visit, queries);
|
|
2213
|
+
if (node.filter !== void 0) visitNodes(node.filter, visit, queries);
|
|
2214
|
+
return;
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
/**
|
|
2218
|
+
* Calls `visit` for each expression node in the clauses and the derived sources of `query` at any depth.
|
|
2219
|
+
* When supplied, `queries` holds the nested queries enclosing each node passed to `visit`; this call adds `query` for its duration.
|
|
2220
|
+
*/
|
|
2221
|
+
function visitQuery(query, visit, queries) {
|
|
2222
|
+
queries?.push(query);
|
|
2223
|
+
const { from, filters } = query;
|
|
2224
|
+
if (from?.kind === "derived") visitQuery(from.query, visit, queries);
|
|
2225
|
+
for (const join of query.joins) {
|
|
2226
|
+
if (join.source.kind === "derived") visitQuery(join.source.query, visit, queries);
|
|
2227
|
+
visitNodes(join.on, visit, queries);
|
|
2228
|
+
}
|
|
2229
|
+
if (query.distinctOn !== void 0) for (const key of query.distinctOn) visitNodes(key, visit, queries);
|
|
2230
|
+
for (const projection of query.projections) visitNodes(projection.expression, visit, queries);
|
|
2231
|
+
if (filters.relation !== void 0) visitNodes(filters.relation, visit, queries);
|
|
2232
|
+
if (filters.scope !== void 0) visitNodes(filters.scope, visit, queries);
|
|
2233
|
+
if (filters.user !== void 0) visitNodes(filters.user, visit, queries);
|
|
2234
|
+
if (query.groupBy !== void 0) for (const key of query.groupBy) visitNodes(key, visit, queries);
|
|
2235
|
+
if (query.having !== void 0) visitNodes(query.having, visit, queries);
|
|
2236
|
+
for (const order of query.orderBy) visitNodes(order.expression, visit, queries);
|
|
2237
|
+
if (query.limit !== void 0) visitNodes(query.limit, visit, queries);
|
|
2238
|
+
if (query.offset !== void 0) visitNodes(query.offset, visit, queries);
|
|
2239
|
+
queries?.pop();
|
|
2240
|
+
}
|
|
2241
|
+
// src/lowering/group.ts
|
|
2242
|
+
/**
|
|
2243
|
+
* Rejects directly selected, unfiltered aggregates of an enclosing query in a query of groups.
|
|
2244
|
+
*
|
|
2245
|
+
* Types give these aggregates the nullability of their arguments in a nonempty group, but an enclosing query can have no rows.
|
|
2246
|
+
* A typed SQL fragment keeps its declared nullability and is the explicit escape hatch for an outer aggregate.
|
|
2247
|
+
*/
|
|
2248
|
+
function checkGroupAggregates(projections, query) {
|
|
2249
|
+
for (const field of projections) {
|
|
2250
|
+
const expression = field.expression;
|
|
2251
|
+
if (expression.kind === "aggregate" && expression.name !== "count" && expression.filter === void 0 && aggregatesOuterSource(expression, query.from)) throw new Error(`An aggregate function of ${query.value ? "the grouped value" : `grouped field ${JSON.stringify(field.key)}`} refers only to enclosing queries; use an explicitly nullable sql expression for an outer aggregate`);
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
// src/lowering/mutation.ts
|
|
2255
|
+
/** Lowers a mutation to its statement, replacing the queries in its expressions, and packing the rows of each nested query of `RETURNING` into the value of its field, or selecting the value of a nested aggregate query, as a select list does. */
|
|
2256
|
+
function lowerMutation(node, context) {
|
|
2257
|
+
const { target, returning, rows, value, conversion } = node;
|
|
2258
|
+
const recordTemplate = returning === void 0 ? void 0 : createRecordTemplate(returning);
|
|
2259
|
+
const lowered = returning === void 0 ? void 0 : lowerProjections(dropLiterals(returning), context);
|
|
2260
|
+
switch (node.kind) {
|
|
2261
|
+
case "insert": {
|
|
2262
|
+
const values = lowerEach(node.values, context, lowerRow);
|
|
2263
|
+
if (lowered === returning && values === node.values) return node;
|
|
2264
|
+
return Object.freeze({
|
|
2265
|
+
kind: "insert",
|
|
2266
|
+
target,
|
|
2267
|
+
columns: node.columns,
|
|
2268
|
+
values,
|
|
2269
|
+
returning: lowered,
|
|
2270
|
+
recordTemplate,
|
|
2271
|
+
conversion,
|
|
2272
|
+
rows,
|
|
2273
|
+
value
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
case "update": {
|
|
2277
|
+
const set = lowerEach(node.set, context, lowerAssignment);
|
|
2278
|
+
const filters = lowerFilters(node.filters, context);
|
|
2279
|
+
if (lowered === returning && set === node.set && filters === node.filters) return node;
|
|
2280
|
+
return Object.freeze({
|
|
2281
|
+
kind: "update",
|
|
2282
|
+
target,
|
|
2283
|
+
set,
|
|
2284
|
+
filters,
|
|
2285
|
+
returning: lowered,
|
|
2286
|
+
recordTemplate,
|
|
2287
|
+
conversion,
|
|
2288
|
+
rows,
|
|
2289
|
+
value
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2292
|
+
case "delete": {
|
|
2293
|
+
const filters = lowerFilters(node.filters, context);
|
|
2294
|
+
if (lowered === returning && filters === node.filters) return node;
|
|
2295
|
+
return Object.freeze({
|
|
2296
|
+
kind: "delete",
|
|
2297
|
+
target,
|
|
2298
|
+
filters,
|
|
2299
|
+
returning: lowered,
|
|
2300
|
+
recordTemplate,
|
|
2301
|
+
conversion,
|
|
2302
|
+
rows,
|
|
2303
|
+
value
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
default: return node;
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
/** Lowers a row of `VALUES` of an insert, whose `undefined` stands for `DEFAULT`. */
|
|
2310
|
+
function lowerRow(row, context) {
|
|
2311
|
+
return lowerEach(row, context, lowerValue);
|
|
2312
|
+
}
|
|
2313
|
+
function lowerAssignment(assignment, context) {
|
|
2314
|
+
const value = lowerExpression(assignment.value, context);
|
|
2315
|
+
return value === assignment.value ? assignment : Object.freeze({
|
|
2316
|
+
key: assignment.key,
|
|
2317
|
+
value
|
|
2318
|
+
});
|
|
2319
|
+
}
|
|
2320
|
+
// src/lowering/page.ts
|
|
2321
|
+
/**
|
|
2322
|
+
* Lowers `query`, the statement of a query on its table that sorts by its sort expressions, to a statement that evaluates its nested queries, apart from those that it sorts by, groups by, or compares, over the rows of a derived page, or returns `undefined` for a query that keeps its page on its table.
|
|
2323
|
+
* `queryFields` are the fields of the query without literals, whose lowered projections the statement has in the same order.
|
|
2324
|
+
* The derived source applies `DISTINCT ON`, the filters, the keys and the condition of the groups, the order, the limit, and the offset, and replaces the occurrence of the table.
|
|
2325
|
+
* It selects each key of `distinctOn` that it does not select otherwise, so that it has a select list, which PostgreSQL requires with `DISTINCT ON`, and evaluates each key once; a key of `groupBy` needs no projection of its own, since it compiles as the position of a projection that has its value or as its expression.
|
|
2326
|
+
*
|
|
2327
|
+
* A query keeps its page on its table without an offset and `distinctOn`, without nested queries that the page would evaluate over its rows, or when `mayAggregateSource` tells that such a nested query may aggregate the rows of the query, which the limit and the offset apply after.
|
|
2328
|
+
*
|
|
2329
|
+
* The source selects the columns of the table that the fields and the nested queries of the query read, under their keys, and the other scalar fields of the query, which it evaluates before the limit and the offset as the query would, such as a window function over all its rows or an aggregate of a group.
|
|
2330
|
+
* A field of an aggregate or of `exists` that the query sorts by or that is a key is such a scalar field: the order and the keys need its value for every row.
|
|
2331
|
+
* A column that no field reads stays out of the source, which could not select it beside an aggregate of a SQL fragment, such as `count(*)`.
|
|
2332
|
+
* The order of a derived source does not carry into the query that reads it, so the statement sorts the rows of the page again by the sort keys of the source, by positions when `positions` is set.
|
|
2333
|
+
*/
|
|
2334
|
+
function lowerPage(query, queryFields, positions) {
|
|
2335
|
+
const { from, projections, orderBy, groupBy, distinctOn, offset } = query;
|
|
2336
|
+
if (offset === void 0 && distinctOn === void 0 || query.distinct || query.lock !== void 0 || !queryFields.some((field, index) => isPagedField(field, projections[index], orderBy, groupBy, distinctOn))) return;
|
|
2337
|
+
const columnKeys = /* @__PURE__ */ new Set();
|
|
2338
|
+
const fields = [];
|
|
2339
|
+
const fieldKeys = [];
|
|
2340
|
+
for (let index = 0; index < projections.length; index++) {
|
|
2341
|
+
const { expression } = projections[index];
|
|
2342
|
+
let key;
|
|
2343
|
+
if (isPagedField(queryFields[index], projections[index], orderBy, groupBy, distinctOn)) {
|
|
2344
|
+
if (mayAggregateSource(expression, from)) return;
|
|
2345
|
+
collectColumnKeys(expression, from, columnKeys);
|
|
2346
|
+
} else if (expression.kind === "column" && expression.source === from) columnKeys.add(expression.key);
|
|
2347
|
+
else {
|
|
2348
|
+
key = `$field${index + 1}`;
|
|
2349
|
+
fields.push(Object.freeze({
|
|
2350
|
+
key,
|
|
2351
|
+
expression,
|
|
2352
|
+
type: text
|
|
2353
|
+
}));
|
|
2354
|
+
}
|
|
2355
|
+
fieldKeys.push(key);
|
|
2356
|
+
}
|
|
2357
|
+
const sourced = [];
|
|
2358
|
+
for (const key of columnKeys) sourced.push(Object.freeze({
|
|
2359
|
+
key,
|
|
2360
|
+
expression: createNode({
|
|
2361
|
+
kind: "column",
|
|
2362
|
+
source: from,
|
|
2363
|
+
key
|
|
2364
|
+
}),
|
|
2365
|
+
type: text
|
|
2366
|
+
}));
|
|
2367
|
+
for (const field of fields) sourced.push(field);
|
|
2368
|
+
if (distinctOn !== void 0) for (let index = 0; index < distinctOn.length; index++) {
|
|
2369
|
+
const key = distinctOn[index];
|
|
2370
|
+
if (findValueProjection(sourced, key) === -1) sourced.push(Object.freeze({
|
|
2371
|
+
key: `$key${index + 1}`,
|
|
2372
|
+
expression: key,
|
|
2373
|
+
type: text
|
|
2374
|
+
}));
|
|
2375
|
+
}
|
|
2376
|
+
const page = deriveOrderedSource({
|
|
2377
|
+
kind: "select",
|
|
2378
|
+
from,
|
|
2379
|
+
joins: noJoins,
|
|
2380
|
+
projections: sourced,
|
|
2381
|
+
filters: query.filters,
|
|
2382
|
+
groupBy,
|
|
2383
|
+
having: query.having,
|
|
2384
|
+
orderBy,
|
|
2385
|
+
limit: query.limit,
|
|
2386
|
+
offset,
|
|
2387
|
+
distinctOn,
|
|
2388
|
+
rows: "many",
|
|
2389
|
+
value: false,
|
|
2390
|
+
guaranteedBy: void 0
|
|
2391
|
+
}, true, offset, from);
|
|
2392
|
+
const selected = [];
|
|
2393
|
+
for (let index = 0; index < projections.length; index++) {
|
|
2394
|
+
const projection = projections[index];
|
|
2395
|
+
const key = fieldKeys[index];
|
|
2396
|
+
selected.push(key === void 0 ? projection : Object.freeze({
|
|
2397
|
+
key: projection.key,
|
|
2398
|
+
expression: createNode({
|
|
2399
|
+
kind: "column",
|
|
2400
|
+
source: page.source,
|
|
2401
|
+
key
|
|
2402
|
+
}),
|
|
2403
|
+
type: projection.type
|
|
2404
|
+
}));
|
|
2405
|
+
}
|
|
2406
|
+
return Object.freeze({
|
|
2407
|
+
kind: "select",
|
|
2408
|
+
from: page.source,
|
|
2409
|
+
joins: noJoins,
|
|
2410
|
+
projections: selected,
|
|
2411
|
+
filters: noFilters,
|
|
2412
|
+
orderBy: positions ? sortByPositions(page.order, selected) : page.order,
|
|
2413
|
+
limit: void 0,
|
|
2414
|
+
offset: void 0,
|
|
2415
|
+
rows: query.rows,
|
|
2416
|
+
value: query.value,
|
|
2417
|
+
guaranteedBy: query.guaranteedBy,
|
|
2418
|
+
recordTemplate: query.recordTemplate
|
|
2419
|
+
});
|
|
2420
|
+
}
|
|
2421
|
+
/**
|
|
2422
|
+
* Tells whether `field`, a field of a query lowered to `projection`, is a nested query that a derived page evaluates only over its rows: one that no sort key of `orderBy`, the lowered order, sorts by, and that is none of `groupBy` and `distinctOn`, the lowered keys of the query.
|
|
2423
|
+
*
|
|
2424
|
+
* The query evaluates a field that it sorts by, groups by, or compares, of an aggregate or of `exists`, for every row anyway.
|
|
2425
|
+
*/
|
|
2426
|
+
function isPagedField(field, projection, orderBy, groupBy, distinctOn) {
|
|
2427
|
+
if (!isNestedSelection(field)) return false;
|
|
2428
|
+
const { expression } = projection;
|
|
2429
|
+
return !orderBy.some((order) => order.expression === expression) && (groupBy === void 0 || !groupBy.includes(expression)) && (distinctOn === void 0 || !distinctOn.includes(expression));
|
|
2430
|
+
}
|
|
2431
|
+
// src/lowering/lower.ts
|
|
2432
|
+
function lowerStatement(node, definitions, db) {
|
|
2433
|
+
const context = createContext(definitions, db);
|
|
2434
|
+
switch (node.kind) {
|
|
2435
|
+
case "query": return lowerSelect(node, context, true);
|
|
2436
|
+
case "record": return lowerRecord(node, context);
|
|
2437
|
+
case "text": return lowerText(node, context);
|
|
2438
|
+
default: return lowerMutation(node, context);
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
/** Creates the context of lowering a statement with `definitions` and `db`, whose nested queries `lowerSelect` lowers. */
|
|
2442
|
+
function createContext(definitions, db) {
|
|
2443
|
+
const context = {
|
|
2444
|
+
definitions,
|
|
2445
|
+
db,
|
|
2446
|
+
lowerSelect: (node, positions) => lowerSelect(node, context, positions),
|
|
2447
|
+
lowerExists: (node) => lowerExists(node, context)
|
|
2448
|
+
};
|
|
2449
|
+
return context;
|
|
2450
|
+
}
|
|
2451
|
+
/** Lowers a statement of SQL text, replacing the queries in the expressions interpolated into it. */
|
|
2452
|
+
function lowerText(node, context) {
|
|
2453
|
+
const sql = lowerExpression(node.sql, context);
|
|
2454
|
+
if (sql === node.sql) return node;
|
|
2455
|
+
return Object.freeze({
|
|
2456
|
+
kind: "text",
|
|
2457
|
+
sql,
|
|
2458
|
+
fields: node.fields,
|
|
2459
|
+
rows: node.rows,
|
|
2460
|
+
value: node.value
|
|
2461
|
+
});
|
|
2462
|
+
}
|
|
2463
|
+
/** Lowers a query as `lowerQuery` does, or as `lowerStatement` does when `positions` is set, with the conversion of its result. */
|
|
2464
|
+
function lowerSelect(node, context, positions) {
|
|
2465
|
+
const statement = lowerSelectStatement(node, context, positions);
|
|
2466
|
+
const { conversion } = node;
|
|
2467
|
+
return conversion === void 0 ? statement : Object.freeze({
|
|
2468
|
+
...statement,
|
|
2469
|
+
conversion
|
|
2470
|
+
});
|
|
2471
|
+
}
|
|
2472
|
+
/** Lowers a query to its statement, whichever it is: of `exists`, of an aggregate, of a page that evaluates its nested queries only over its rows, or of the rows of its source. */
|
|
2473
|
+
function lowerSelectStatement(node, context, positions) {
|
|
2474
|
+
if (isExistsQuery(node)) return selectExists(node, context);
|
|
2475
|
+
checkRelation(node, context);
|
|
2476
|
+
if (isAggregateQuery(node)) return lowerAggregate(node, context);
|
|
2477
|
+
const recordTemplate = createRecordTemplate(node.projections);
|
|
2478
|
+
const selected = dropLiterals(node.projections);
|
|
2479
|
+
const projections = lowerProjections(selected, context);
|
|
2480
|
+
if (node.groupBy.length > 0) checkGroupAggregates(projections, node);
|
|
2481
|
+
const filters = lowerFilters(node.filters, context);
|
|
2482
|
+
const orderBy = lowerOrder(node.orderBy, context, selected, projections);
|
|
2483
|
+
const groupBy = lowerKeys(node.groupBy, context, selected, projections);
|
|
2484
|
+
const having = lowerValue(node.having, context);
|
|
2485
|
+
const distinctOn = lowerKeys(node.distinctOn, context, selected, projections);
|
|
2486
|
+
if (node.distinct) checkDistinct(projections, orderBy);
|
|
2487
|
+
if (distinctOn !== void 0) checkDistinctOn(projections, distinctOn, orderBy);
|
|
2488
|
+
const { relation } = node;
|
|
2489
|
+
const guaranteedBy = node.guaranteed && relation !== void 0 ? formatRelationName(relation.key, relation.name) : void 0;
|
|
2490
|
+
const statement = {
|
|
2491
|
+
kind: "select",
|
|
2492
|
+
from: node.from,
|
|
2493
|
+
joins: noJoins,
|
|
2494
|
+
projections,
|
|
2495
|
+
filters,
|
|
2496
|
+
groupBy,
|
|
2497
|
+
having,
|
|
2498
|
+
orderBy,
|
|
2499
|
+
limit: node.limit,
|
|
2500
|
+
offset: node.offset,
|
|
2501
|
+
distinct: node.distinct,
|
|
2502
|
+
distinctOn,
|
|
2503
|
+
lock: node.lock,
|
|
2504
|
+
rows: node.rows,
|
|
2505
|
+
value: node.value,
|
|
2506
|
+
guaranteedBy,
|
|
2507
|
+
recordTemplate
|
|
2508
|
+
};
|
|
2509
|
+
const page = lowerPage(statement, selected, positions);
|
|
2510
|
+
if (page !== void 0) return page;
|
|
2511
|
+
if (positions && orderBy.length > 0) statement.orderBy = sortByPositions(orderBy, projections);
|
|
2512
|
+
return Object.freeze(statement);
|
|
2513
|
+
}
|
|
2514
|
+
/** Lowers a query of `exists` to a statement without a source of one row of `EXISTS` of its rows. */
|
|
2515
|
+
function selectExists(node, context) {
|
|
2516
|
+
return Object.freeze({
|
|
2517
|
+
kind: "select",
|
|
2518
|
+
from: void 0,
|
|
2519
|
+
joins: noJoins,
|
|
2520
|
+
projections: [projectExists(node.projections[0].key, node, context)],
|
|
2521
|
+
filters: noFilters,
|
|
2522
|
+
orderBy: noOrder,
|
|
2523
|
+
limit: void 0,
|
|
2524
|
+
offset: void 0,
|
|
2525
|
+
rows: node.rows,
|
|
2526
|
+
value: true,
|
|
2527
|
+
guaranteedBy: void 0
|
|
2528
|
+
});
|
|
2529
|
+
}
|
|
2530
|
+
/** Lowers a query of `$select` to a statement without a source, which returns one row of its fields. */
|
|
2531
|
+
function lowerRecord(node, context) {
|
|
2532
|
+
return Object.freeze({
|
|
2533
|
+
kind: "select",
|
|
2534
|
+
from: void 0,
|
|
2535
|
+
joins: noJoins,
|
|
2536
|
+
projections: lowerProjections(dropLiterals(node.projections), context),
|
|
2537
|
+
filters: noFilters,
|
|
2538
|
+
orderBy: noOrder,
|
|
2539
|
+
limit: void 0,
|
|
2540
|
+
offset: void 0,
|
|
2541
|
+
rows: "one",
|
|
2542
|
+
value: false,
|
|
2543
|
+
guaranteedBy: void 0,
|
|
2544
|
+
recordTemplate: createRecordTemplate(node.projections)
|
|
2545
|
+
});
|
|
2546
|
+
}
|
|
2547
|
+
// src/query/kind.ts
|
|
2548
|
+
/** `then` of every bound query, which executes the query on its `Db`. */
|
|
2549
|
+
function executeOnAwait(onFulfilled, onRejected) {
|
|
2550
|
+
return this.db.$execute(this).then(onFulfilled, onRejected);
|
|
2551
|
+
}
|
|
2552
|
+
/** Compiles `query` as its `toSQL` does: an unbound query with `options`, and a bound query as its `Db` executes it, which takes no options. */
|
|
2553
|
+
function compileToSQL(query, options) {
|
|
2554
|
+
const { db } = query;
|
|
2555
|
+
if (db === void 0) {
|
|
2556
|
+
const { text, parameters } = compileStatement(lowerStatement(query.node), options);
|
|
2557
|
+
return createStatement(text, parameters);
|
|
2558
|
+
}
|
|
2559
|
+
if (options !== void 0) throw new Error("A query bound to a Db compiles with the options of its Db");
|
|
2560
|
+
return db.$compile(query);
|
|
2561
|
+
}
|
|
2562
|
+
// src/query/conversion.ts
|
|
2563
|
+
/**
|
|
2564
|
+
* Immutable query of a table of state `S` whose whole result `transform` converts after decoding, unbound or bound to a `Db`.
|
|
2565
|
+
*
|
|
2566
|
+
* It executes and nests in a selection as the query it comes from, with the same SQL, so it has only `transform`, which converts the result further: another method would change what the callback receives, and an expression does not take it, since SQL does not see the conversion.
|
|
2567
|
+
* An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
|
|
2568
|
+
* A bound query executes on its `Db` when awaited.
|
|
2569
|
+
*/
|
|
2570
|
+
var TransformedQuery = class {
|
|
2571
|
+
node;
|
|
2572
|
+
/** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
|
|
2573
|
+
db;
|
|
2574
|
+
/** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
|
|
2575
|
+
then;
|
|
2576
|
+
constructor(node, db) {
|
|
2577
|
+
this.node = node;
|
|
2578
|
+
this.db = db;
|
|
2579
|
+
this.then = db === void 0 ? void 0 : executeOnAwait;
|
|
2580
|
+
Object.freeze(this);
|
|
2581
|
+
}
|
|
2582
|
+
transform(callback) {
|
|
2583
|
+
return transformQuery(this.node, this.db, callback);
|
|
2584
|
+
}
|
|
2585
|
+
toSQL(options) {
|
|
2586
|
+
return compileToSQL(this, options);
|
|
2587
|
+
}
|
|
2588
|
+
/** Rejects the query as an operand of an expression, whose value SQL reads without its conversion. */
|
|
2589
|
+
[operandNode]() {
|
|
2590
|
+
throw new TypeError("An expression takes a query of one value of a table, such as of get, an aggregate, or exists, not a query of transform");
|
|
2591
|
+
}
|
|
2592
|
+
};
|
|
2593
|
+
/** Creates the query of `transform` of `node`, a query of a table bound to `db` when given, whose whole result `callback` converts after the earlier conversions. */
|
|
2594
|
+
function transformQuery(node, db, callback) {
|
|
2595
|
+
return new TransformedQuery(Object.freeze({
|
|
2596
|
+
...node,
|
|
2597
|
+
conversion: addTransform(node.conversion, callback)
|
|
2598
|
+
}), db);
|
|
2599
|
+
}
|
|
2600
|
+
/**
|
|
2601
|
+
* Returns `conversion` of a query with `callback` of `map` after its earlier one.
|
|
2602
|
+
*
|
|
2603
|
+
* It rejects a conversion of `transform`, whose result has no rows to convert.
|
|
2604
|
+
*/
|
|
2605
|
+
function addMap(conversion, callback) {
|
|
2606
|
+
if (conversion?.transform !== void 0) throw new Error("map cannot be used after transform; convert the rows in its callback instead");
|
|
2607
|
+
return Object.freeze({
|
|
2608
|
+
map: chainConversions(conversion?.map, createConversion(callback, "map")),
|
|
2609
|
+
transform: void 0
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
/** Returns `conversion` of a query with `callback` of `transform` after its earlier one. */
|
|
2613
|
+
function addTransform(conversion, callback) {
|
|
2614
|
+
return Object.freeze({
|
|
2615
|
+
map: conversion?.map,
|
|
2616
|
+
transform: chainConversions(conversion?.transform, createConversion(callback, "transform"))
|
|
2617
|
+
});
|
|
2618
|
+
}
|
|
2619
|
+
/** Returns the conversion that applies `next` after `previous`, if any. */
|
|
2620
|
+
function chainConversions(previous, next) {
|
|
2621
|
+
return previous === void 0 ? next : (value) => next(previous(value));
|
|
2622
|
+
}
|
|
2623
|
+
/**
|
|
2624
|
+
* Creates the conversion of `callback` of `method`, which rejects a Promise or another thenable returned by the callback: `SynchronousResult` rejects it in types, and a callback may still return one through `any`.
|
|
2625
|
+
*
|
|
2626
|
+
* It rejects a `callback` that is not a function when it is called, since decoding calls it long after, where its error would read as a failure of a row.
|
|
2627
|
+
*/
|
|
2628
|
+
function createConversion(callback, method) {
|
|
2629
|
+
if (typeof callback !== "function") throw new TypeError(`${method} takes a callback`);
|
|
2630
|
+
return (value) => {
|
|
2631
|
+
const result = callback(value);
|
|
2632
|
+
if (typeof result?.then === "function") {
|
|
2633
|
+
if (types.isPromise(result)) result.catch(ignoreRejection);
|
|
2634
|
+
throw new TypeError(`The callback of ${method} must return its result synchronously, not a Promise or a query`);
|
|
2635
|
+
}
|
|
2636
|
+
return result;
|
|
2637
|
+
};
|
|
2638
|
+
}
|
|
2639
|
+
/** Handles the rejection of a Promise that a callback returned, whose query has failed already. */
|
|
2640
|
+
function ignoreRejection() {}
|
|
2641
|
+
// src/query/resolve-values.ts
|
|
2642
|
+
/**
|
|
2643
|
+
* Replaces objects of column values in a predicate with conditions on the columns of `source`.
|
|
2644
|
+
*
|
|
2645
|
+
* Groups are rebuilt, so constants that appear after resolution, such as an empty object, are simplified.
|
|
2646
|
+
*/
|
|
2647
|
+
function resolveValues(node, source) {
|
|
2648
|
+
switch (node.kind) {
|
|
2649
|
+
case "values": {
|
|
2650
|
+
const conditions = [];
|
|
2651
|
+
for (const key of Object.keys(node.values)) conditions.push(matchColumn(source, key, node.values[key]));
|
|
2652
|
+
return combineNodes("and", conditions);
|
|
2653
|
+
}
|
|
2654
|
+
case "and":
|
|
2655
|
+
case "or": {
|
|
2656
|
+
const operands = [];
|
|
2657
|
+
for (const operand of node.operands) operands.push(resolveValues(operand, source));
|
|
2658
|
+
return combineNodes(node.kind, operands);
|
|
2659
|
+
}
|
|
2660
|
+
case "not": return negateNode(resolveValues(node.operand, source));
|
|
2661
|
+
case "raw": return createNode({
|
|
2662
|
+
...node,
|
|
2663
|
+
values: node.values.map((value) => resolveValues(value, source))
|
|
2664
|
+
});
|
|
2665
|
+
default: return node;
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
/** Creates the condition of column `key` of `source` in an object of column values: `IS NULL` of `null`, or the `eq` operator of its type for another value. */
|
|
2669
|
+
function matchColumn(source, key, value) {
|
|
2670
|
+
const type = findColumn(source.table, key)?.type;
|
|
2671
|
+
const column = createNode({
|
|
2672
|
+
kind: "column",
|
|
2673
|
+
source,
|
|
2674
|
+
key
|
|
2675
|
+
});
|
|
2676
|
+
if (value === null) return createIsNullNode(column);
|
|
2677
|
+
if (type) return matchValue(source, column, type, value);
|
|
2678
|
+
return compareNodes("=", column, value, void 0);
|
|
2679
|
+
}
|
|
2680
|
+
/** Matches a column with a value of an object condition by calling the `eq` operator of its type, whichever operator it is. */
|
|
2681
|
+
function matchValue(source, column, type, value) {
|
|
2682
|
+
const expression = toExpression(column, type);
|
|
2683
|
+
if (typeof expression.eq !== "function") throw new TypeError(`Column "${column.key}" of table "${source.table.name}" has no eq operator; an object condition can only match it with null`);
|
|
2684
|
+
const predicate = expression.eq(value);
|
|
2685
|
+
if (!isExpression(predicate)) throw new TypeError(`The eq operator of column "${column.key}" of table "${source.table.name}" must return an expression`);
|
|
2686
|
+
return toNode(predicate);
|
|
2687
|
+
}
|
|
2688
|
+
// src/query/filters.ts
|
|
2689
|
+
/** Creates query filters with the filter of `where` over `source` with the relations of `context` combined with `AND` with the user filters of `filters`. */
|
|
2690
|
+
function addUserFilter(filters, filter, source, context) {
|
|
2691
|
+
const predicate = toFilterNode(filter, source, context);
|
|
2692
|
+
const { user } = filters;
|
|
2693
|
+
return Object.freeze({
|
|
2694
|
+
...filters,
|
|
2695
|
+
user: user ? combineNodes("and", [user, predicate]) : predicate
|
|
2696
|
+
});
|
|
2697
|
+
}
|
|
2698
|
+
/**
|
|
2699
|
+
* Converts a filter of `where` or `having` over `source` with the relations of `context` into the node of its condition, whose objects of column values it resolves.
|
|
2700
|
+
*
|
|
2701
|
+
* A callback receives the columns with the relations, and what `readSelected` returns, such as the selected fields for `having`.
|
|
2702
|
+
*/
|
|
2703
|
+
function toFilterNode(filter, source, context, readSelected) {
|
|
2704
|
+
return resolveValues(toConditionNode(typeof filter === "function" ? filter(createSelectionRefs(source, context), readSelected?.()) : filter), source);
|
|
2705
|
+
}
|
|
2706
|
+
// src/query/find.ts
|
|
2707
|
+
/**
|
|
2708
|
+
* Returns the object of column values that `find` filters a query of `table` by: `values` of the columns of its primary key, in their order.
|
|
2709
|
+
*
|
|
2710
|
+
* It rejects a table without a primary key, a number of values other than the number of its columns, and `null` and `undefined`.
|
|
2711
|
+
*/
|
|
2712
|
+
function toPrimaryKeyValues(table, values) {
|
|
2713
|
+
const { primaryKey } = table.keys;
|
|
2714
|
+
if (primaryKey === void 0) throw new Error(`find takes the values of a primary key, which table "${table.name}" does not have; use findBy with a unique key`);
|
|
2715
|
+
if (values.length !== primaryKey.length) throw new Error(`find takes one value for each column of the primary key of table "${table.name}", ${quoteColumns(primaryKey)}, not ${values.length}`);
|
|
2716
|
+
const filter = {};
|
|
2717
|
+
for (let index = 0; index < primaryKey.length; index++) {
|
|
2718
|
+
const column = primaryKey[index];
|
|
2719
|
+
filter[column] = requireKeyValue(table, column, values[index], "find");
|
|
2720
|
+
}
|
|
2721
|
+
return filter;
|
|
2722
|
+
}
|
|
2723
|
+
/**
|
|
2724
|
+
* Returns the object of column values that `findBy` filters a query of `table` by: a copy of `values`, read once.
|
|
2725
|
+
*
|
|
2726
|
+
* It rejects columns that are not exactly a key of `table`, primary or unique, as `isKey` tells, and `null` and `undefined`.
|
|
2727
|
+
*/
|
|
2728
|
+
function toKeyValues(table, values) {
|
|
2729
|
+
if (typeof values !== "object" || values === null) throw new TypeError(`findBy takes an object of the columns of a key of table "${table.name}"`);
|
|
2730
|
+
const columns = Object.keys(values);
|
|
2731
|
+
if (!isKey(table, columns)) {
|
|
2732
|
+
const listed = columns.length === 0 ? "an object without columns" : `columns ${quoteColumns(columns)}`;
|
|
2733
|
+
throw new Error(`findBy takes the columns of one key of table "${table.name}", primary or unique, not ${listed}`);
|
|
2734
|
+
}
|
|
2735
|
+
const filter = {};
|
|
2736
|
+
for (const column of columns) {
|
|
2737
|
+
const value = values[column];
|
|
2738
|
+
filter[column] = requireKeyValue(table, column, value, "findBy");
|
|
2739
|
+
}
|
|
2740
|
+
return filter;
|
|
2741
|
+
}
|
|
2742
|
+
/** Returns `value` of column `column` of a key of `table` that `method` takes, rejecting `null` and `undefined`. */
|
|
2743
|
+
function requireKeyValue(table, column, value, method) {
|
|
2744
|
+
if (value === null || value === void 0) throw new TypeError(`${method} got ${value} for column "${column}" of table "${table.name}"; a value of a key is never null or undefined`);
|
|
2745
|
+
return value;
|
|
2746
|
+
}
|
|
2747
|
+
/** Lists `columns` in quotes, separated by commas. */
|
|
2748
|
+
function quoteColumns(columns) {
|
|
2749
|
+
return columns.map((column) => `"${column}"`).join(", ");
|
|
2750
|
+
}
|
|
2751
|
+
// src/query/order.ts
|
|
2752
|
+
/** Direction and placement of `NULL` of a sort key node, by `OrderDirection`. */
|
|
2753
|
+
const directions = /* @__PURE__ */ Object.freeze({
|
|
2754
|
+
asc: {
|
|
2755
|
+
direction: "asc",
|
|
2756
|
+
nulls: void 0
|
|
2757
|
+
},
|
|
2758
|
+
desc: {
|
|
2759
|
+
direction: "desc",
|
|
2760
|
+
nulls: void 0
|
|
2761
|
+
},
|
|
2762
|
+
"asc nulls first": {
|
|
2763
|
+
direction: "asc",
|
|
2764
|
+
nulls: "first"
|
|
2765
|
+
},
|
|
2766
|
+
"asc nulls last": {
|
|
2767
|
+
direction: "asc",
|
|
2768
|
+
nulls: "last"
|
|
2769
|
+
},
|
|
2770
|
+
"desc nulls first": {
|
|
2771
|
+
direction: "desc",
|
|
2772
|
+
nulls: "first"
|
|
2773
|
+
},
|
|
2774
|
+
"desc nulls last": {
|
|
2775
|
+
direction: "desc",
|
|
2776
|
+
nulls: "last"
|
|
2777
|
+
}
|
|
2778
|
+
});
|
|
2779
|
+
const orderingNode = Symbol("kern-orm.ordering.node");
|
|
2780
|
+
/** Runtime class of an expression with a direction, which holds its sort key node. */
|
|
2781
|
+
var OrderingObject = class {
|
|
2782
|
+
[orderingNode];
|
|
2783
|
+
constructor(node) {
|
|
2784
|
+
this[orderingNode] = node;
|
|
2785
|
+
Object.freeze(this);
|
|
2786
|
+
}
|
|
2787
|
+
};
|
|
2788
|
+
/** Sorts by `value`, an expression or a query of one value, in ascending order, in the callback of `orderBy`. */
|
|
2789
|
+
function asc(value) {
|
|
2790
|
+
return orderBy(value, "asc");
|
|
2791
|
+
}
|
|
2792
|
+
/** Sorts by `value`, an expression or a query of one value, in descending order, in the callback of `orderBy`. */
|
|
2793
|
+
function desc(value) {
|
|
2794
|
+
return orderBy(value, "desc");
|
|
2795
|
+
}
|
|
2796
|
+
/** Sorts by `value`, an expression or a query of one value, in `direction`, such as `"desc nulls last"`, in the callback of `orderBy`. */
|
|
2797
|
+
function orderBy(value, direction) {
|
|
2798
|
+
if (!isOperandSource(value)) throw new TypeError("A sort key must be an expression or a query of one value");
|
|
2799
|
+
return new OrderingObject(createOrderNode(value[operandNode](), direction));
|
|
2800
|
+
}
|
|
2801
|
+
/**
|
|
2802
|
+
* Creates the order of `node` with the sort keys of the arguments of `orderBy` after its own.
|
|
2803
|
+
*
|
|
2804
|
+
* `args` are column keys and objects of columns with directions, or a callback that receives the columns with the relations of `context` and the selected fields, and returns one sort key or an array of them.
|
|
2805
|
+
*/
|
|
2806
|
+
function addOrder(node, context, args) {
|
|
2807
|
+
const order = node.orderBy.slice();
|
|
2808
|
+
const first = args[0];
|
|
2809
|
+
if (typeof first === "function") {
|
|
2810
|
+
addTerms(order, first(createSelectionRefs(node.from, context), createSelectedRefs(node, "sorted by")), "The callback of orderBy must return");
|
|
2811
|
+
return order;
|
|
2812
|
+
}
|
|
2813
|
+
for (const arg of args) if (typeof arg === "string") order.push(createOrderNode(createColumnNode(node.from, arg), "asc"));
|
|
2814
|
+
else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) {
|
|
2815
|
+
const columns = arg;
|
|
2816
|
+
for (const key of Object.keys(columns)) order.push(createOrderNode(createColumnNode(node.from, key), columns[key]));
|
|
2817
|
+
} else throw new TypeError("orderBy takes column keys and objects of columns with directions, or a callback");
|
|
2818
|
+
return order;
|
|
2819
|
+
}
|
|
2820
|
+
/** Adds to `order` the sort key nodes of `terms`, `OrderTerms` checked at runtime; `subject` starts the error of another value, such as `The callback of orderBy must return`. */
|
|
2821
|
+
function addTerms(order, terms, subject) {
|
|
2822
|
+
if (Array.isArray(terms)) for (const term of terms) order.push(readTerm$1(term, subject));
|
|
2823
|
+
else order.push(readTerm$1(terms, subject));
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* Creates the sort key node of a sort key, `OrderTerm` checked at runtime, whose error starts with `subject`.
|
|
2827
|
+
*
|
|
2828
|
+
* A query is converted by the method of `operandNode`, which rejects a query other than of one value.
|
|
2829
|
+
*/
|
|
2830
|
+
function readTerm$1(term, subject) {
|
|
2831
|
+
if (term instanceof OrderingObject) return term[orderingNode];
|
|
2832
|
+
if (isOperandSource(term)) return createOrderNode(term[operandNode](), "asc");
|
|
2833
|
+
throw new TypeError(`${subject} expressions, queries of one value, or sort keys of asc, desc, and orderBy`);
|
|
2834
|
+
}
|
|
2835
|
+
/** Creates the sort key node of `expression` in `direction`, an `OrderDirection` checked at runtime. */
|
|
2836
|
+
function createOrderNode(expression, direction) {
|
|
2837
|
+
const placement = typeof direction === "string" && Object.hasOwn(directions, direction) ? directions[direction] : void 0;
|
|
2838
|
+
if (placement === void 0) throw new TypeError(`Unknown sort direction ${JSON.stringify(direction)}`);
|
|
2839
|
+
return Object.freeze({
|
|
2840
|
+
expression,
|
|
2841
|
+
direction: placement.direction,
|
|
2842
|
+
nulls: placement.nulls
|
|
2843
|
+
});
|
|
2844
|
+
}
|
|
2845
|
+
/** Creates a reference to the column `key` of the table of `source`. */
|
|
2846
|
+
function createColumnNode(source, key) {
|
|
2847
|
+
requireColumn(source.table, key);
|
|
2848
|
+
return createNode({
|
|
2849
|
+
kind: "column",
|
|
2850
|
+
source,
|
|
2851
|
+
key
|
|
2852
|
+
});
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2855
|
+
* Creates the references of the callback of `orderBy`, `groupBy`, `distinctOn`, or `having` to the fields selected by `node`; `purpose` completes the error of a field that cannot be read, such as `sorted by`.
|
|
2856
|
+
*
|
|
2857
|
+
* Each is an expression over the node of its projection, so that a sort key or a key of a group of it is the projection itself; `HAVING` compiles the expression again, since it cannot refer to a projection.
|
|
2858
|
+
* A field of an aggregate or of `exists` is an expression of its query that holds the field, by which lowering finds the projection of the field.
|
|
2859
|
+
*/
|
|
2860
|
+
function createSelectedRefs(node, purpose) {
|
|
2861
|
+
const { projections } = node;
|
|
2862
|
+
if (node.value) return toSelectedExpression(projections[0]);
|
|
2863
|
+
const refs = {};
|
|
2864
|
+
for (const projection of projections) {
|
|
2865
|
+
const { key } = projection;
|
|
2866
|
+
if (isLiteralSelection(projection)) Object.defineProperty(refs, key, {
|
|
2867
|
+
get() {
|
|
2868
|
+
throw new Error(`Field "${key}" holds a literal and cannot be ${purpose}`);
|
|
2869
|
+
},
|
|
2870
|
+
enumerable: true
|
|
2871
|
+
});
|
|
2872
|
+
else if (isNestedSelection(projection)) {
|
|
2873
|
+
if (isSelectedAsValue(projection.query)) refs[key] = toQueryExpression(projection);
|
|
2874
|
+
else Object.defineProperty(refs, key, {
|
|
2875
|
+
get() {
|
|
2876
|
+
throw new Error(`Field "${key}" holds nested rows and cannot be ${purpose}`);
|
|
2877
|
+
},
|
|
2878
|
+
enumerable: true
|
|
2879
|
+
});
|
|
2880
|
+
} else refs[key] = toSelectedExpression(projection);
|
|
2881
|
+
}
|
|
2882
|
+
return refs;
|
|
2883
|
+
}
|
|
2884
|
+
/** Creates an expression over the node of a projection of a query, which has a type: only lowering adds projections of nested queries. */
|
|
2885
|
+
function toSelectedExpression(projection) {
|
|
2886
|
+
return toExpression(projection.expression, projection.type);
|
|
2887
|
+
}
|
|
2888
|
+
/** Creates an expression of the value of `field`, a selected aggregate query or query of `exists`, with the type of its value. */
|
|
2889
|
+
function toQueryExpression(field) {
|
|
2890
|
+
const { query } = field;
|
|
2891
|
+
return toExpression(createNode({
|
|
2892
|
+
kind: "nestedQuery",
|
|
2893
|
+
query,
|
|
2894
|
+
db: field.db,
|
|
2895
|
+
field
|
|
2896
|
+
}), query.projections[0].type);
|
|
2897
|
+
}
|
|
2898
|
+
// src/query/group.ts
|
|
2899
|
+
/** Method that takes the keys of groups, and the phrase of what it does with a field that cannot be a key, for its errors. */
|
|
2900
|
+
const keyMethods = {
|
|
2901
|
+
groupBy: "grouped by",
|
|
2902
|
+
distinctOn: "a key of distinctOn"
|
|
2903
|
+
};
|
|
2904
|
+
/**
|
|
2905
|
+
* Creates the keys of `method`, `groupBy` or `distinctOn`, of `node` with the keys of the arguments of the call after its own.
|
|
2906
|
+
*
|
|
2907
|
+
* `args` are column keys, or a callback that receives the columns with the relations of `context` and the selected fields, and returns one key or an array of them.
|
|
2908
|
+
* A string names a column, never a selected field, whose key names only the field of a record.
|
|
2909
|
+
* It rejects a call without keys, which would leave the rows of a query ungrouped, or keep all of them, when a list built in code is empty.
|
|
2910
|
+
*/
|
|
2911
|
+
function addGroupKeys(method, node, context, args) {
|
|
2912
|
+
const existing = node[method];
|
|
2913
|
+
const keys = existing.slice();
|
|
2914
|
+
const first = args[0];
|
|
2915
|
+
if (typeof first === "function") {
|
|
2916
|
+
const terms = first(createSelectionRefs(node.from, context), createSelectedRefs(node, keyMethods[method]));
|
|
2917
|
+
if (Array.isArray(terms)) for (const term of terms) keys.push(readTerm(term, method));
|
|
2918
|
+
else keys.push(readTerm(terms, method));
|
|
2919
|
+
} else for (const arg of args) {
|
|
2920
|
+
if (typeof arg !== "string") throw new TypeError(`${method} takes column keys or a callback`);
|
|
2921
|
+
keys.push(createColumnNode(node.from, arg));
|
|
2922
|
+
}
|
|
2923
|
+
if (keys.length === existing.length) throw new TypeError(`${method} requires at least one key`);
|
|
2924
|
+
return keys;
|
|
2925
|
+
}
|
|
2926
|
+
/**
|
|
2927
|
+
* Creates the condition of the groups of `node` with `filter`, what `where` takes, combined with `AND` with its earlier condition.
|
|
2928
|
+
*
|
|
2929
|
+
* A callback also receives the fields selected so far, as `HavingFields` tells, so that a condition reads an aggregate or a key of an expression by its field.
|
|
2930
|
+
* The condition stands apart from the filters of the rows, so it requires keys: without them, `having` would read as a filter of rows while PostgreSQL takes the whole query for one group.
|
|
2931
|
+
*/
|
|
2932
|
+
function addHaving(node, filter, context) {
|
|
2933
|
+
if (node.groupBy.length === 0) throw new Error("having requires an earlier groupBy; filter the rows with where");
|
|
2934
|
+
const predicate = toFilterNode(filter, node.from, context, () => node.conversion !== void 0 || isAggregateQuery(node) || isExistsQuery(node) ? void 0 : createSelectedRefs(node, "read in having"));
|
|
2935
|
+
return node.having === void 0 ? predicate : combineNodes("and", [node.having, predicate]);
|
|
2936
|
+
}
|
|
2937
|
+
/**
|
|
2938
|
+
* Creates the node of a key returned by the callback of `method`.
|
|
2939
|
+
*
|
|
2940
|
+
* A query is converted by the method of `operandNode`, which rejects a query other than of one value.
|
|
2941
|
+
*/
|
|
2942
|
+
function readTerm(term, method) {
|
|
2943
|
+
if (isOperandSource(term)) return term[operandNode]();
|
|
2944
|
+
throw new TypeError(`The callback of ${method} must return expressions or queries of one value`);
|
|
2945
|
+
}
|
|
2946
|
+
// src/query/lock.ts
|
|
2947
|
+
/** Creates the row lock of `strength` for `method`, rejecting a query whose rows it cannot lock and options that contradict each other. */
|
|
2948
|
+
function createRowLock(node, method, strength, options = {}) {
|
|
2949
|
+
if (isAggregateQuery(node)) throw new Error(`${method} cannot be used after an aggregate`);
|
|
2950
|
+
if (isExistsQuery(node)) throw new Error(`${method} cannot be used after exists`);
|
|
2951
|
+
if (node.distinct) throw new Error(`${method} cannot be used after distinct, since a row without duplicates comes from several rows of the table`);
|
|
2952
|
+
if (node.distinctOn.length > 0) throw new Error(`${method} cannot be used after distinctOn; PostgreSQL does not allow row locks with DISTINCT ON`);
|
|
2953
|
+
if (node.groupBy.length > 0) throw new Error(`${method} cannot be used after groupBy, since a group comes from several rows of the table`);
|
|
2954
|
+
const { noWait, skipLocked } = options;
|
|
2955
|
+
if (noWait && skipLocked) throw new Error(`${method} takes either noWait or skipLocked, not both`);
|
|
2956
|
+
return Object.freeze({
|
|
2957
|
+
strength,
|
|
2958
|
+
onLocked: noWait ? "NOWAIT" : skipLocked ? "SKIP LOCKED" : void 0
|
|
2959
|
+
});
|
|
2960
|
+
}
|
|
2961
|
+
// src/query/record.ts
|
|
2962
|
+
/**
|
|
2963
|
+
* Immutable query of `$select` of state `S`, unbound or bound to a `Db`: one record whose fields are the values of expressions and of literals and the results of independent queries, selected in one statement.
|
|
2964
|
+
*
|
|
2965
|
+
* An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
|
|
2966
|
+
* A bound query executes on its `Db` when awaited.
|
|
2967
|
+
*/
|
|
2968
|
+
var RecordQuery = class {
|
|
2969
|
+
node;
|
|
2970
|
+
/** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
|
|
2971
|
+
db;
|
|
2972
|
+
/** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
|
|
2973
|
+
then;
|
|
2974
|
+
constructor(node, db) {
|
|
2975
|
+
this.node = node;
|
|
2976
|
+
this.db = db;
|
|
2977
|
+
this.then = db === void 0 ? void 0 : executeOnAwait;
|
|
2978
|
+
Object.freeze(this);
|
|
2979
|
+
}
|
|
2980
|
+
toSQL(options) {
|
|
2981
|
+
return compileToSQL(this, options);
|
|
2982
|
+
}
|
|
2983
|
+
/** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
|
|
2984
|
+
[operandNode]() {
|
|
2985
|
+
throw new TypeError("An expression takes a query of one value of a table, such as of get, an aggregate, or exists, not a query of $select");
|
|
2986
|
+
}
|
|
2987
|
+
};
|
|
2988
|
+
/**
|
|
2989
|
+
* Starts the query of `$select` of `selection`, an object of expressions, queries, and literals by key, bound to `db` when given.
|
|
2990
|
+
*
|
|
2991
|
+
* It reads the keys and values of `selection` when it is called.
|
|
2992
|
+
*/
|
|
2993
|
+
function startRecordQuery(selection, db) {
|
|
2994
|
+
const projections = [];
|
|
2995
|
+
addSelection(projections, selection);
|
|
2996
|
+
return new RecordQuery(Object.freeze({
|
|
2997
|
+
kind: "record",
|
|
2998
|
+
projections
|
|
2999
|
+
}), db);
|
|
3000
|
+
}
|
|
3001
|
+
// src/query/sql-query.ts
|
|
3002
|
+
/**
|
|
3003
|
+
* Immutable query of a statement of SQL text, bound to the `Db` that executes it when awaited.
|
|
3004
|
+
*
|
|
3005
|
+
* 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.
|
|
3006
|
+
*/
|
|
3007
|
+
var SqlQuery = class SqlQuery {
|
|
3008
|
+
node;
|
|
3009
|
+
db;
|
|
3010
|
+
/** Executes the query on its `Db`. */
|
|
3011
|
+
then;
|
|
3012
|
+
constructor(node, db) {
|
|
3013
|
+
this.node = node;
|
|
3014
|
+
this.db = db;
|
|
3015
|
+
this.then = executeOnAwait;
|
|
3016
|
+
Object.freeze(this);
|
|
3017
|
+
}
|
|
3018
|
+
select(fields) {
|
|
3019
|
+
const { node } = this;
|
|
3020
|
+
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");
|
|
3021
|
+
if (typeof fields !== "object" || fields === null) throw new TypeError("select takes an object of the types of the fields by their columns");
|
|
3022
|
+
const added = Reflect.ownKeys(fields);
|
|
3023
|
+
const selected = [];
|
|
3024
|
+
for (const field of node.fields ?? []) if (!added.includes(field.key)) selected.push(field);
|
|
3025
|
+
for (const key of added) {
|
|
3026
|
+
if (typeof key === "symbol") throw new TypeError("A selected field must have a string key");
|
|
3027
|
+
if (!isRecordKey(key)) throw new Error(`Field "${key}" cannot be a key of a record`);
|
|
3028
|
+
selected.push(Object.freeze({
|
|
3029
|
+
key,
|
|
3030
|
+
type: requireType(fields[key], `field "${key}"`)
|
|
3031
|
+
}));
|
|
3032
|
+
}
|
|
3033
|
+
return this.derive({
|
|
3034
|
+
fields: selected,
|
|
3035
|
+
value: false
|
|
3036
|
+
});
|
|
3037
|
+
}
|
|
3038
|
+
get(type) {
|
|
3039
|
+
const { rows } = this.node;
|
|
3040
|
+
return this.deriveValue(type, "get", rows === "many" ? "one" : toValueRows(rows));
|
|
3041
|
+
}
|
|
3042
|
+
pluck(type) {
|
|
3043
|
+
return this.deriveValue(type, "pluck", toValueRows(this.node.rows));
|
|
3044
|
+
}
|
|
3045
|
+
take() {
|
|
3046
|
+
const { rows } = this.node;
|
|
3047
|
+
return this.derive({ rows: rows === "many" ? "one" : rows });
|
|
3048
|
+
}
|
|
3049
|
+
optional() {
|
|
3050
|
+
return this.changeOneRow("optional");
|
|
3051
|
+
}
|
|
3052
|
+
nullable() {
|
|
3053
|
+
const { node } = this;
|
|
3054
|
+
if (node.fields !== void 0 && node.value) throw new Error("nullable applies only to a query of records; use optional after get or pluck");
|
|
3055
|
+
return this.changeOneRow("nullable");
|
|
3056
|
+
}
|
|
3057
|
+
/** Compiles the query into SQL text and parameters, as its `Db` executes it. */
|
|
3058
|
+
toSQL() {
|
|
3059
|
+
return this.db.$compile(this);
|
|
3060
|
+
}
|
|
3061
|
+
/** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
|
|
3062
|
+
[operandNode]() {
|
|
3063
|
+
throw new TypeError("An expression takes a query of one value of a table, such as of get, an aggregate, or exists, not a query of $query");
|
|
3064
|
+
}
|
|
3065
|
+
/** Creates a query of the same `Db` with the node changes applied. */
|
|
3066
|
+
derive(changes) {
|
|
3067
|
+
return new SqlQuery(Object.freeze({
|
|
3068
|
+
...this.node,
|
|
3069
|
+
...changes
|
|
3070
|
+
}), this.db);
|
|
3071
|
+
}
|
|
3072
|
+
/** Creates the query that returns the value of the only column of each row in rows mode `rows`, decoded by `type` of `method`. */
|
|
3073
|
+
deriveValue(type, method, rows) {
|
|
3074
|
+
const field = Object.freeze({
|
|
3075
|
+
key: "value",
|
|
3076
|
+
type: requireType(type, method)
|
|
3077
|
+
});
|
|
3078
|
+
return this.derive({
|
|
3079
|
+
fields: [field],
|
|
3080
|
+
value: true,
|
|
3081
|
+
rows
|
|
3082
|
+
});
|
|
3083
|
+
}
|
|
3084
|
+
/** Creates the query of one row in rows mode `rows`, rejecting a query of many rows. */
|
|
3085
|
+
changeOneRow(rows) {
|
|
3086
|
+
if (this.node.rows === "many") throw new Error(`${rows} applies only to a query of one row, such as one made by take`);
|
|
3087
|
+
return this.derive({ rows });
|
|
3088
|
+
}
|
|
3089
|
+
};
|
|
3090
|
+
/** Starts the query of the statement of `sql` bound to `db`, which resolves to the number of the rows of its command tag. */
|
|
3091
|
+
function startSqlQuery(sql, db) {
|
|
3092
|
+
return new SqlQuery(Object.freeze({
|
|
3093
|
+
kind: "text",
|
|
3094
|
+
sql,
|
|
3095
|
+
fields: void 0,
|
|
3096
|
+
rows: "many",
|
|
3097
|
+
value: false
|
|
3098
|
+
}), db);
|
|
3099
|
+
}
|
|
3100
|
+
/** Returns `value` that `what` takes as its type, rejecting a value that is not a type, such as a column. */
|
|
3101
|
+
function requireType(value, what) {
|
|
3102
|
+
if (!isType(value)) throw new TypeError(`${what} takes a type, such as t.integer, not a column or another value`);
|
|
3103
|
+
return value;
|
|
3104
|
+
}
|
|
3105
|
+
// src/query/projections.ts
|
|
3106
|
+
/**
|
|
3107
|
+
* Creates the fields of `select` over `source`, appending new keys and replacing existing ones in place.
|
|
3108
|
+
*
|
|
3109
|
+
* `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.
|
|
3110
|
+
*/
|
|
3111
|
+
function mergeProjections(projections, source, args, context) {
|
|
3112
|
+
const result = projections.slice();
|
|
3113
|
+
const first = args[0];
|
|
3114
|
+
if (typeof first === "function") addSelection(result, first(createSelectionRefs(source, context)));
|
|
3115
|
+
else {
|
|
3116
|
+
const keys = first === "*" ? Object.keys(source.table.columns) : args;
|
|
3117
|
+
for (const key of keys) setProjection(result, projectColumn(source, key));
|
|
3118
|
+
}
|
|
3119
|
+
return result;
|
|
3120
|
+
}
|
|
3121
|
+
/** Adds the fields of `selection`, expressions, queries, and literals by key, to `projections`, replacing existing keys in place. */
|
|
3122
|
+
function addSelection(projections, selection) {
|
|
3123
|
+
for (const key of Reflect.ownKeys(selection)) {
|
|
3124
|
+
if (typeof key === "symbol") throw new TypeError("A selected field must have a string key");
|
|
3125
|
+
setProjection(projections, selectValue(key, selection[key]));
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
/**
|
|
3129
|
+
* Creates the projection of the value of `get` or `pluck`, or of the argument of an aggregate method, such as `max`, over `source`.
|
|
3130
|
+
*
|
|
3131
|
+
* `arg` is the argument of `method`: a column key, or a callback that receives the references of `source` with the relations of `context` and returns an expression or a query of one value.
|
|
3132
|
+
* The value of such a query is that of `expr`, `NULL` without its row, since the projection holds one scalar rather than nested rows.
|
|
3133
|
+
*/
|
|
3134
|
+
function projectValue(source, arg, method, context) {
|
|
3135
|
+
if (typeof arg !== "function") return projectColumn(source, arg);
|
|
3136
|
+
const result = arg(createSelectionRefs(source, context));
|
|
3137
|
+
const value = result instanceof SelectQuery ? result.expr() : result;
|
|
3138
|
+
if (!isExpression(value)) throw new TypeError(`The callback of ${method} must return an expression or a query of one value`);
|
|
3139
|
+
const type = getType(value);
|
|
3140
|
+
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)`);
|
|
3141
|
+
return projectExpression("value", value, type);
|
|
3142
|
+
}
|
|
3143
|
+
/**
|
|
3144
|
+
* 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, an expression, or a query of one value.
|
|
3145
|
+
*
|
|
3146
|
+
* The projection of an aggregate keeps its call, which lowering builds, and adds the fallback after its earlier ones.
|
|
3147
|
+
* The projection of `exists` stays as it is, since `EXISTS` is never `NULL`.
|
|
3148
|
+
*/
|
|
3149
|
+
function coalesceValue(field, fallback) {
|
|
3150
|
+
const value = toFunctionOperandNode(fallback, field.type, "coalesce");
|
|
3151
|
+
if (isExistsProjection(field)) return field;
|
|
3152
|
+
if (isAggregateProjection(field)) return addFallback(field, value);
|
|
3153
|
+
return Object.freeze({
|
|
3154
|
+
key: field.key,
|
|
3155
|
+
expression: createList("coalesce(", [field.expression, value], ")"),
|
|
3156
|
+
type: field.type
|
|
3157
|
+
});
|
|
3158
|
+
}
|
|
3159
|
+
/** Creates the field of a value of a selection under `key`: an expression with a type, a query whose rows become its value, or a literal. */
|
|
3160
|
+
function selectValue(key, value) {
|
|
3161
|
+
if (value instanceof Literal) return Object.freeze({
|
|
3162
|
+
key,
|
|
3163
|
+
literal: value.literal
|
|
3164
|
+
});
|
|
3165
|
+
if (value instanceof SelectQuery || value instanceof TransformedQuery) return Object.freeze({
|
|
3166
|
+
key,
|
|
3167
|
+
query: value.node,
|
|
3168
|
+
db: value.db
|
|
3169
|
+
});
|
|
3170
|
+
if (value instanceof RecordQuery) throw new TypeError(`Selected field "${key}" is a query of $select, which cannot be nested; select its fields directly instead`);
|
|
3171
|
+
if (value instanceof MutationQuery) throw new TypeError(`Selected field "${key}" is a query of insert, update, or delete, which cannot be nested`);
|
|
3172
|
+
if (value instanceof SqlQuery) throw new TypeError(`Selected field "${key}" is a query of $query, which cannot be nested`);
|
|
3173
|
+
if (!isExpression(value)) throw new TypeError(`Selected field "${key}" must be an expression, a query, or a literal`);
|
|
3174
|
+
const type = getType(value);
|
|
3175
|
+
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)`);
|
|
3176
|
+
return projectExpression(key, value, type);
|
|
3177
|
+
}
|
|
3178
|
+
/** Creates the projection of a column of the table of `source` under its key. */
|
|
3179
|
+
function projectColumn(source, key) {
|
|
3180
|
+
const { type } = requireColumn(source.table, key);
|
|
3181
|
+
return Object.freeze({
|
|
3182
|
+
key,
|
|
3183
|
+
expression: createNode({
|
|
3184
|
+
kind: "column",
|
|
3185
|
+
source,
|
|
3186
|
+
key
|
|
3187
|
+
}),
|
|
3188
|
+
type
|
|
3189
|
+
});
|
|
3190
|
+
}
|
|
3191
|
+
/** Creates the projection of an expression under `key`, decoded with `type`, the type of the expression. */
|
|
3192
|
+
function projectExpression(key, value, type) {
|
|
3193
|
+
return Object.freeze({
|
|
3194
|
+
key,
|
|
3195
|
+
expression: toNode(value),
|
|
3196
|
+
type
|
|
3197
|
+
});
|
|
3198
|
+
}
|
|
3199
|
+
/** Adds or replaces a field by key, rejecting a key that a record cannot have. */
|
|
3200
|
+
function setProjection(projections, projection) {
|
|
3201
|
+
const { key } = projection;
|
|
3202
|
+
if (!isRecordKey(key)) throw new Error(`Field "${key}" cannot be selected: it is not a valid record key`);
|
|
3203
|
+
for (let index = 0; index < projections.length; index++) if (projections[index].key === key) {
|
|
3204
|
+
projections[index] = projection;
|
|
3205
|
+
return;
|
|
3206
|
+
}
|
|
3207
|
+
projections.push(projection);
|
|
3208
|
+
}
|
|
3209
|
+
// src/query/values.ts
|
|
3210
|
+
/**
|
|
3211
|
+
* 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.
|
|
3212
|
+
*
|
|
3213
|
+
* 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`.
|
|
3214
|
+
* Several records without values insert the `DEFAULT` of the first column of the table, since `DEFAULT VALUES` inserts one row.
|
|
3215
|
+
* It rejects a key that is not a column of `table`, and a query other than of one value.
|
|
3216
|
+
*/
|
|
3217
|
+
function toInsertRows(table, records, method) {
|
|
3218
|
+
if (records.length === 0) throw new Error(`${method} takes at least one record`);
|
|
3219
|
+
const columns = [];
|
|
3220
|
+
const rows = [];
|
|
3221
|
+
for (const record of records) {
|
|
3222
|
+
if (typeof record !== "object" || record === null) throw new TypeError(`${method} takes records of the values of the columns of table "${table.name}"`);
|
|
3223
|
+
const row = [];
|
|
3224
|
+
for (const key of Object.keys(record)) {
|
|
3225
|
+
const value = record[key];
|
|
3226
|
+
if (value === void 0) continue;
|
|
3227
|
+
let index = columns.indexOf(key);
|
|
3228
|
+
if (index === -1) index = columns.push(key) - 1;
|
|
3229
|
+
row[index] = resolveValue(table, key, value);
|
|
3230
|
+
}
|
|
3231
|
+
rows.push(row);
|
|
3232
|
+
}
|
|
3233
|
+
if (columns.length === 0 && rows.length > 1) {
|
|
3234
|
+
const first = Object.keys(table.columns)[0];
|
|
3235
|
+
if (first !== void 0) columns.push(first);
|
|
3236
|
+
}
|
|
3237
|
+
for (const row of rows) while (row.length < columns.length) row.push(void 0);
|
|
3238
|
+
return {
|
|
3239
|
+
columns,
|
|
3240
|
+
values: rows
|
|
3241
|
+
};
|
|
3242
|
+
}
|
|
3243
|
+
/**
|
|
3244
|
+
* 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 references of `source` with the relations of `context` and returns them, read when it is called.
|
|
3245
|
+
*
|
|
3246
|
+
* A value of `undefined` keeps its column, and an update must set at least one column.
|
|
3247
|
+
* It rejects a key that is not a column of the table of `source`, and a query other than of one value.
|
|
3248
|
+
*/
|
|
3249
|
+
function toAssignments(source, set, context) {
|
|
3250
|
+
const { table } = source;
|
|
3251
|
+
const values = typeof set === "function" ? set(createSelectionRefs(source, context)) : set;
|
|
3252
|
+
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`);
|
|
3253
|
+
const assignments = [];
|
|
3254
|
+
for (const key of Object.keys(values)) {
|
|
3255
|
+
const value = values[key];
|
|
3256
|
+
if (value !== void 0) assignments.push(Object.freeze({
|
|
3257
|
+
key,
|
|
3258
|
+
value: resolveValue(table, key, value)
|
|
3259
|
+
}));
|
|
3260
|
+
}
|
|
3261
|
+
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`);
|
|
3262
|
+
return assignments;
|
|
3263
|
+
}
|
|
3264
|
+
/** Returns the node of `value` of the column of `table` under `key`: an expression or a query of one value, which lowering replaces with a scalar subquery, or a parameter encoded with the type of the column. */
|
|
3265
|
+
function resolveValue(table, key, value) {
|
|
3266
|
+
return toValueNode(value, requireColumn(table, key).type);
|
|
3267
|
+
}
|
|
3268
|
+
// src/query/mutation.ts
|
|
3269
|
+
/**
|
|
3270
|
+
* Immutable query of state `S` that inserts, updates, or deletes rows, unbound or bound to a `Db`.
|
|
3271
|
+
*
|
|
3272
|
+
* Without a selection, it resolves to the number of the rows it changes; `select`, `get`, and `pluck` return the fields of those rows instead, and `map` and `transform` convert them in code.
|
|
3273
|
+
* An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
|
|
3274
|
+
* A bound query executes on its `Db` when awaited.
|
|
3275
|
+
*/
|
|
3276
|
+
var MutationQuery = class MutationQuery {
|
|
3277
|
+
table;
|
|
3278
|
+
node;
|
|
3279
|
+
context;
|
|
3280
|
+
/** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
|
|
3281
|
+
db;
|
|
3282
|
+
/** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
|
|
3283
|
+
then;
|
|
3284
|
+
constructor(table, node, context, db) {
|
|
3285
|
+
this.table = table;
|
|
3286
|
+
this.node = node;
|
|
3287
|
+
this.context = context;
|
|
3288
|
+
this.db = db;
|
|
3289
|
+
this.then = db === void 0 ? void 0 : executeOnAwait;
|
|
3290
|
+
Object.freeze(this);
|
|
3291
|
+
}
|
|
3292
|
+
select(...args) {
|
|
3293
|
+
this.rejectConverted("select");
|
|
3294
|
+
const { node } = this;
|
|
3295
|
+
const { returning } = node;
|
|
3296
|
+
if (returning !== void 0 && node.value) throw new Error("select cannot be used after get or pluck; call get or pluck to replace the value");
|
|
3297
|
+
return this.derive({
|
|
3298
|
+
returning: mergeProjections(returning ?? [], node.target, args, this.context),
|
|
3299
|
+
value: false
|
|
3300
|
+
});
|
|
3301
|
+
}
|
|
3302
|
+
get(arg) {
|
|
3303
|
+
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");
|
|
3304
|
+
return this.deriveValue(arg, "get");
|
|
3305
|
+
}
|
|
3306
|
+
pluck(arg) {
|
|
3307
|
+
return this.deriveValue(arg, "pluck");
|
|
3308
|
+
}
|
|
3309
|
+
map(callback) {
|
|
3310
|
+
const { node } = this;
|
|
3311
|
+
if (node.returning === void 0) throw new Error("map applies only to a mutation that returns the fields of its rows; select them before map, or call transform to convert the number of the rows");
|
|
3312
|
+
return this.derive({ conversion: addMap(node.conversion, callback) });
|
|
3313
|
+
}
|
|
3314
|
+
transform(callback) {
|
|
3315
|
+
return this.derive({ conversion: addTransform(this.node.conversion, callback) });
|
|
3316
|
+
}
|
|
3317
|
+
use(callback, ...args) {
|
|
3318
|
+
const result = requireDerived(this, callback(this, ...args), "The callback of use");
|
|
3319
|
+
if (this.node.returning === void 0 && result.node.returning?.length === 0) throw new Error("The callback of use must select at least one field, or not call select to return the number of the rows");
|
|
3320
|
+
return result;
|
|
3321
|
+
}
|
|
3322
|
+
toSQL(options) {
|
|
3323
|
+
return compileToSQL(this, options);
|
|
3324
|
+
}
|
|
3325
|
+
/** Rejects the query as an operand of an expression, which takes a query of one value of a table. */
|
|
3326
|
+
[operandNode]() {
|
|
3327
|
+
throw new TypeError("An expression takes a query of one value of a table, such as of get, an aggregate, or exists, not a query of insert, update, or delete");
|
|
3328
|
+
}
|
|
3329
|
+
/** Creates a mutation of the same kind and `Db` with the node changes applied. */
|
|
3330
|
+
derive(changes) {
|
|
3331
|
+
return new MutationQuery(this.table, Object.freeze({
|
|
3332
|
+
...this.node,
|
|
3333
|
+
...changes
|
|
3334
|
+
}), this.context, this.db);
|
|
3335
|
+
}
|
|
3336
|
+
/** Creates the mutation that returns the value of `arg` of `method`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value, of each changed row. */
|
|
3337
|
+
deriveValue(arg, method) {
|
|
3338
|
+
this.rejectConverted(method);
|
|
3339
|
+
const { node } = this;
|
|
3340
|
+
return this.derive({
|
|
3341
|
+
returning: [projectValue(node.target, arg, method, this.context)],
|
|
3342
|
+
value: true,
|
|
3343
|
+
rows: toValueRows(node.rows)
|
|
3344
|
+
});
|
|
3345
|
+
}
|
|
3346
|
+
/** Rejects `method`, which changes the fields that the mutation returns, on a mutation that `map` or `transform` converts. */
|
|
3347
|
+
rejectConverted(method) {
|
|
3348
|
+
if (this.node.conversion !== void 0) throw new Error(`${method} cannot be used after map or transform; call it before them`);
|
|
3349
|
+
}
|
|
3350
|
+
};
|
|
3351
|
+
/**
|
|
3352
|
+
* Creates the insert of `records` into the table of `query`, which must have no clauses, in rows mode `rows`: `one` for `insert` and `many` for `insertMany`, named by `method`.
|
|
3353
|
+
*
|
|
3354
|
+
* It returns the number of the inserted rows, until a selection returns their fields.
|
|
3355
|
+
*/
|
|
3356
|
+
function createInsert(query, records, rows, method) {
|
|
3357
|
+
const { node } = query;
|
|
3358
|
+
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`);
|
|
3359
|
+
const { columns, values } = toInsertRows(node.from.table, records, method);
|
|
3360
|
+
return new MutationQuery(query.table, Object.freeze({
|
|
3361
|
+
kind: "insert",
|
|
3362
|
+
target: node.from,
|
|
3363
|
+
columns,
|
|
3364
|
+
values,
|
|
3365
|
+
returning: void 0,
|
|
3366
|
+
rows,
|
|
3367
|
+
value: false
|
|
3368
|
+
}), query.context, query.db);
|
|
3369
|
+
}
|
|
3370
|
+
/** Creates the update of the rows of `query` that `set` gives, as `update` takes it, in the rows mode of the query. */
|
|
3371
|
+
function createUpdate(query, set) {
|
|
3372
|
+
const { node } = query;
|
|
3373
|
+
checkChangedRows(node, "update");
|
|
3374
|
+
return new MutationQuery(query.table, Object.freeze({
|
|
3375
|
+
kind: "update",
|
|
3376
|
+
target: node.from,
|
|
3377
|
+
set: toAssignments(node.from, set, query.context),
|
|
3378
|
+
filters: node.filters,
|
|
3379
|
+
returning: void 0,
|
|
3380
|
+
rows: node.rows,
|
|
3381
|
+
value: false
|
|
3382
|
+
}), query.context, query.db);
|
|
3383
|
+
}
|
|
3384
|
+
/** Creates the delete of the rows of `query`, in the rows mode of the query. */
|
|
3385
|
+
function createDelete(query) {
|
|
3386
|
+
const { node } = query;
|
|
3387
|
+
checkChangedRows(node, "delete");
|
|
3388
|
+
return new MutationQuery(query.table, Object.freeze({
|
|
3389
|
+
kind: "delete",
|
|
3390
|
+
target: node.from,
|
|
3391
|
+
filters: node.filters,
|
|
3392
|
+
returning: void 0,
|
|
3393
|
+
rows: node.rows,
|
|
3394
|
+
value: false
|
|
3395
|
+
}), query.context, query.db);
|
|
3396
|
+
}
|
|
3397
|
+
/**
|
|
3398
|
+
* Rejects a query whose rows `method`, `update` or `delete`, cannot change: one of a relation, with selected fields, which a mutation selects after it, with a conversion of `map`, which a mutation takes after it too, with keys of groups, whose rows SQL does not give, with an order, a limit, an offset, `distinct`, or `distinctOn`, with a row lock, which a mutation takes on its rows itself, or without a filter that restricts its rows unless `all` allows it.
|
|
3399
|
+
*
|
|
3400
|
+
* A filter simplified to `TRUE`, such as `where({})`, restricts no row.
|
|
3401
|
+
*/
|
|
3402
|
+
function checkChangedRows(node, method) {
|
|
3403
|
+
if (node.relation !== void 0) throw new Error(`${method} applies only to a query of a table, not of a relation`);
|
|
3404
|
+
if (node.projections.length > 0) throw new Error(`${method} returns the fields selected after it, not before; call select, get, or pluck after ${method}`);
|
|
3405
|
+
if (node.conversion !== void 0) throw new Error(`${method} returns what map converts after it, not before; call map after ${method}`);
|
|
3406
|
+
if (node.groupBy.length > 0) throw new Error(`${method} changes rows rather than groups; choose them with where, find, or findBy instead of groupBy`);
|
|
3407
|
+
if (node.orderBy.length > 0 || node.limit !== void 0 || node.offset !== void 0 || node.distinct || node.distinctOn.length > 0) throw new Error(`${method} cannot sort or limit the rows it changes; choose them with where, find, or findBy instead of take, limit, offset, orderBy, distinct, or distinctOn`);
|
|
3408
|
+
if (node.lock !== void 0) throw new Error(`${method} locks the rows it changes itself, so its query takes no row lock`);
|
|
3409
|
+
const predicate = combineFilters(node.filters);
|
|
3410
|
+
if (!node.all && predicate.kind === "boolean" && predicate.value) throw new Error(`${method} requires a filter that restricts the rows, such as of where or find; call all() to ${method} every row`);
|
|
3411
|
+
}
|
|
3412
|
+
// src/query/pagination.ts
|
|
3413
|
+
/** Creates the parameter of the number of rows of `limit` or `offset`, named by `method`, of query `node`, rejecting a query of one row and a count that is not a non-negative safe integer. */
|
|
3414
|
+
function createPageCount(node, method, count) {
|
|
3415
|
+
if (node.rows !== "many") throw new Error(`${method} applies only to a query of many rows${createPaginationHint(node)}`);
|
|
3416
|
+
if (!Number.isSafeInteger(count) || count < 0) throw new RangeError(`${method} takes a non-negative integer, not ${count}`);
|
|
3417
|
+
return createNode({
|
|
3418
|
+
kind: "param",
|
|
3419
|
+
value: count,
|
|
3420
|
+
type: void 0
|
|
3421
|
+
});
|
|
3422
|
+
}
|
|
3423
|
+
/** Creates the hint of the error of `limit` or `offset` of query `node` of one row: the method to call them before, if any. */
|
|
3424
|
+
function createPaginationHint(node) {
|
|
3425
|
+
if (node.relation?.kind === "one") return "";
|
|
3426
|
+
if (isAggregateQuery(node)) return "; call it before count or another aggregate to aggregate the rows of a page";
|
|
3427
|
+
if (isExistsQuery(node)) return "; call it before exists to check the rows of a page";
|
|
3428
|
+
return "; call it before take or get";
|
|
3429
|
+
}
|
|
3430
|
+
// src/query/select.ts
|
|
3431
|
+
/**
|
|
3432
|
+
* Immutable select query of state `S`, unbound or bound to a `Db`.
|
|
3433
|
+
*
|
|
3434
|
+
* Every method returns a query of the same kind and leaves this query unchanged.
|
|
3435
|
+
* An unbound query is not thenable, so it can be returned from async functions; it is compiled with `toSQL` or executed by a `Db`.
|
|
3436
|
+
* A bound query executes on its `Db` when awaited.
|
|
3437
|
+
*/
|
|
3438
|
+
var SelectQuery = class SelectQuery {
|
|
3439
|
+
table;
|
|
3440
|
+
node;
|
|
3441
|
+
context;
|
|
3442
|
+
/** `Db` that executes the query when it is awaited; `undefined` for an unbound query. */
|
|
3443
|
+
db;
|
|
3444
|
+
/** Executes a bound query on its `Db`; `undefined` for an unbound query, so that it is not thenable. */
|
|
3445
|
+
then;
|
|
3446
|
+
constructor(table, node, context, db) {
|
|
3447
|
+
this.table = table;
|
|
3448
|
+
this.node = node;
|
|
3449
|
+
this.context = context;
|
|
3450
|
+
this.db = db;
|
|
3451
|
+
this.then = db === void 0 ? void 0 : executeOnAwait;
|
|
3452
|
+
Object.freeze(this);
|
|
3453
|
+
}
|
|
3454
|
+
where(filter) {
|
|
3455
|
+
return this.derive(this.addFilter(filter));
|
|
3456
|
+
}
|
|
3457
|
+
select(...args) {
|
|
3458
|
+
this.rejectValue("select");
|
|
3459
|
+
return this.derive({ projections: mergeProjections(this.node.projections, this.node.from, args, this.context) });
|
|
3460
|
+
}
|
|
3461
|
+
clearSelect() {
|
|
3462
|
+
this.rejectValue("clearSelect");
|
|
3463
|
+
return this.derive({ projections: [] });
|
|
3464
|
+
}
|
|
3465
|
+
take() {
|
|
3466
|
+
return this.deriveTaken({});
|
|
3467
|
+
}
|
|
3468
|
+
find(...values) {
|
|
3469
|
+
return this.takeWhere(toPrimaryKeyValues(this.table, values));
|
|
3470
|
+
}
|
|
3471
|
+
findBy(values) {
|
|
3472
|
+
return this.takeWhere(toKeyValues(this.table, values));
|
|
3473
|
+
}
|
|
3474
|
+
get(arg) {
|
|
3475
|
+
this.rejectAggregate("get");
|
|
3476
|
+
return this.deriveTaken({
|
|
3477
|
+
projections: [projectValue(this.node.from, arg, "get", this.context)],
|
|
3478
|
+
value: true,
|
|
3479
|
+
rows: toValueRows(this.node.rows)
|
|
3480
|
+
});
|
|
3481
|
+
}
|
|
3482
|
+
pluck(arg) {
|
|
3483
|
+
this.rejectAggregate("pluck");
|
|
3484
|
+
return this.derive({
|
|
3485
|
+
projections: [projectValue(this.node.from, arg, "pluck", this.context)],
|
|
3486
|
+
value: true,
|
|
3487
|
+
rows: toValueRows(this.node.rows)
|
|
3488
|
+
});
|
|
3489
|
+
}
|
|
3490
|
+
count(arg) {
|
|
3491
|
+
if (arg !== void 0) return this.aggregateBy("count", arg);
|
|
3492
|
+
this.rejectAggregation("count");
|
|
3493
|
+
return this.deriveAggregate(countProjection);
|
|
3494
|
+
}
|
|
3495
|
+
countDistinct(arg) {
|
|
3496
|
+
return this.aggregateBy("countDistinct", arg);
|
|
3497
|
+
}
|
|
3498
|
+
min(arg) {
|
|
3499
|
+
return this.aggregateBy("min", arg);
|
|
3500
|
+
}
|
|
3501
|
+
max(arg) {
|
|
3502
|
+
return this.aggregateBy("max", arg);
|
|
3503
|
+
}
|
|
3504
|
+
sum(arg) {
|
|
3505
|
+
return this.aggregateBy("sum", arg);
|
|
3506
|
+
}
|
|
3507
|
+
avg(arg) {
|
|
3508
|
+
return this.aggregateBy("avg", arg);
|
|
3509
|
+
}
|
|
3510
|
+
every(arg) {
|
|
3511
|
+
return this.aggregateBy("every", arg);
|
|
3512
|
+
}
|
|
3513
|
+
some(arg) {
|
|
3514
|
+
return this.aggregateBy("some", arg);
|
|
3515
|
+
}
|
|
3516
|
+
stringAgg(arg, delimiter) {
|
|
3517
|
+
return this.aggregateBy("stringAgg", arg, delimiter);
|
|
3518
|
+
}
|
|
3519
|
+
exists() {
|
|
3520
|
+
this.rejectAggregation("exists");
|
|
3521
|
+
return this.deriveAggregate(getExistsProjection());
|
|
3522
|
+
}
|
|
3523
|
+
coalesce(fallback) {
|
|
3524
|
+
this.rejectMapped("coalesce");
|
|
3525
|
+
const { node } = this;
|
|
3526
|
+
if (!node.value) throw new Error("coalesce applies only to a query of values, such as one made by get, pluck, or an aggregate");
|
|
3527
|
+
return this.derive({ projections: [coalesceValue(node.projections[0], fallback)] });
|
|
3528
|
+
}
|
|
3529
|
+
expr() {
|
|
3530
|
+
const value = this[operandNode]();
|
|
3531
|
+
return toExpression(value, this.node.projections[0].type);
|
|
3532
|
+
}
|
|
3533
|
+
groupBy(...args) {
|
|
3534
|
+
this.rejectAggregate("groupBy");
|
|
3535
|
+
if (this.node.lock !== void 0) throw new Error("groupBy cannot be used after a row lock, since a group comes from several rows of the table");
|
|
3536
|
+
return this.derive({ groupBy: addGroupKeys("groupBy", this.node, this.context, args) });
|
|
3537
|
+
}
|
|
3538
|
+
having(filter) {
|
|
3539
|
+
return this.derive({
|
|
3540
|
+
having: addHaving(this.node, filter, this.context),
|
|
3541
|
+
rows: this.getFilteredRows(),
|
|
3542
|
+
guaranteed: false
|
|
3543
|
+
});
|
|
3544
|
+
}
|
|
3545
|
+
orderBy(...args) {
|
|
3546
|
+
return this.derive({ orderBy: addOrder(this.node, this.context, args) });
|
|
3547
|
+
}
|
|
3548
|
+
limit(count) {
|
|
3549
|
+
return this.derive({ limit: createPageCount(this.node, "limit", count) });
|
|
3550
|
+
}
|
|
3551
|
+
offset(count) {
|
|
3552
|
+
return this.derive({ offset: createPageCount(this.node, "offset", count) });
|
|
3553
|
+
}
|
|
3554
|
+
distinct() {
|
|
3555
|
+
if (this.node.rows !== "many") throw new Error("distinct applies only to a query of many rows");
|
|
3556
|
+
if (this.node.distinctOn.length > 0) throw new Error("distinct cannot be used after distinctOn, which compares only its keys");
|
|
3557
|
+
if (this.node.lock !== void 0) throw new Error("distinct cannot be used after a row lock, since a row without duplicates comes from several rows of the table");
|
|
3558
|
+
return this.derive({ distinct: true });
|
|
3559
|
+
}
|
|
3560
|
+
distinctOn(...args) {
|
|
3561
|
+
const { node } = this;
|
|
3562
|
+
if (node.rows !== "many") throw new Error("distinctOn applies only to a query of many rows");
|
|
3563
|
+
if (node.distinct) throw new Error("distinctOn cannot be used after distinct, which compares every selected field");
|
|
3564
|
+
if (node.lock !== void 0) throw new Error("distinctOn cannot be used after a row lock; PostgreSQL does not allow row locks with DISTINCT ON");
|
|
3565
|
+
return this.derive({ distinctOn: addGroupKeys("distinctOn", node, this.context, args) });
|
|
3566
|
+
}
|
|
3567
|
+
forUpdate(options) {
|
|
3568
|
+
return this.derive({ lock: createRowLock(this.node, "forUpdate", "UPDATE", options) });
|
|
3569
|
+
}
|
|
3570
|
+
forNoKeyUpdate(options) {
|
|
3571
|
+
return this.derive({ lock: createRowLock(this.node, "forNoKeyUpdate", "NO KEY UPDATE", options) });
|
|
3572
|
+
}
|
|
3573
|
+
forShare(options) {
|
|
3574
|
+
return this.derive({ lock: createRowLock(this.node, "forShare", "SHARE", options) });
|
|
3575
|
+
}
|
|
3576
|
+
forKeyShare(options) {
|
|
3577
|
+
return this.derive({ lock: createRowLock(this.node, "forKeyShare", "KEY SHARE", options) });
|
|
3578
|
+
}
|
|
3579
|
+
optional() {
|
|
3580
|
+
return this.changeOneRow("optional", "optional");
|
|
3581
|
+
}
|
|
3582
|
+
nullable() {
|
|
3583
|
+
if (this.node.value && this.node.conversion === void 0) throw new Error("nullable applies only to a query of records; use optional after get, pluck, or an aggregate");
|
|
3584
|
+
return this.changeOneRow("nullable", "nullable");
|
|
3585
|
+
}
|
|
3586
|
+
required() {
|
|
3587
|
+
return this.changeOneRow("required", "one");
|
|
3588
|
+
}
|
|
3589
|
+
insert(values) {
|
|
3590
|
+
return createInsert(this, [values], "one", "insert");
|
|
3591
|
+
}
|
|
3592
|
+
insertMany(records) {
|
|
3593
|
+
if (!Array.isArray(records)) throw new TypeError("insertMany takes an array of records");
|
|
3594
|
+
return createInsert(this, records, "many", "insertMany");
|
|
3595
|
+
}
|
|
3596
|
+
update(set) {
|
|
3597
|
+
return createUpdate(this, set);
|
|
3598
|
+
}
|
|
3599
|
+
delete() {
|
|
3600
|
+
return createDelete(this);
|
|
3601
|
+
}
|
|
3602
|
+
all() {
|
|
3603
|
+
if (this.node.rows !== "many") throw new Error("all applies only to a query of many rows");
|
|
3604
|
+
return this.derive({ all: true });
|
|
3605
|
+
}
|
|
3606
|
+
map(callback) {
|
|
3607
|
+
return this.derive({ conversion: addMap(this.node.conversion, callback) });
|
|
3608
|
+
}
|
|
3609
|
+
transform(callback) {
|
|
3610
|
+
return transformQuery(this.node, this.db, callback);
|
|
3611
|
+
}
|
|
3612
|
+
use(callback, ...args) {
|
|
3613
|
+
return requireDerived(this, callback(this, ...args), "The callback of use");
|
|
3614
|
+
}
|
|
3615
|
+
toSQL(options) {
|
|
3616
|
+
return compileToSQL(this, options);
|
|
3617
|
+
}
|
|
3618
|
+
/**
|
|
3619
|
+
* Returns the node of the query as an operand of an expression, which lowering replaces with a scalar subquery of its value, or with `EXISTS` of its rows for a query of `exists`.
|
|
3620
|
+
*
|
|
3621
|
+
* It rejects a query of records or of rows `many`, which `ScalarQuery` rejects in types.
|
|
3622
|
+
*/
|
|
3623
|
+
[operandNode]() {
|
|
3624
|
+
const { node } = this;
|
|
3625
|
+
if (!node.value || node.rows === "many") throw new TypeError("An expression takes a query of one value, such as of get, an aggregate, or exists, not a query of records or of an array");
|
|
3626
|
+
if (node.conversion !== void 0) throw new TypeError("An expression takes a query of one value, such as of get, an aggregate, or exists, not a query of map");
|
|
3627
|
+
return createNode({
|
|
3628
|
+
kind: "nestedQuery",
|
|
3629
|
+
query: node,
|
|
3630
|
+
db: this.db
|
|
3631
|
+
});
|
|
3632
|
+
}
|
|
3633
|
+
/**
|
|
3634
|
+
* Returns the node of the query as the values of `in`, which lowering replaces with its statement.
|
|
3635
|
+
*
|
|
3636
|
+
* It rejects a query of records, which `ValuesQuery` rejects in types.
|
|
3637
|
+
*/
|
|
3638
|
+
[valuesQueryNode]() {
|
|
3639
|
+
const { node } = this;
|
|
3640
|
+
if (!node.value) throw new TypeError("in takes a query of values, such as of pluck, not a query of records");
|
|
3641
|
+
if (node.conversion !== void 0) throw new TypeError("in takes a query of values, such as of pluck, not a query of map");
|
|
3642
|
+
return createNode({
|
|
3643
|
+
kind: "nestedQuery",
|
|
3644
|
+
query: node,
|
|
3645
|
+
db: this.db
|
|
3646
|
+
});
|
|
3647
|
+
}
|
|
3648
|
+
/** Creates a query of the same kind and `Db` with the node changes applied. */
|
|
3649
|
+
derive(changes) {
|
|
3650
|
+
return new SelectQuery(this.table, Object.freeze({
|
|
3651
|
+
...this.node,
|
|
3652
|
+
...changes
|
|
3653
|
+
}), this.context, this.db);
|
|
3654
|
+
}
|
|
3655
|
+
/**
|
|
3656
|
+
* Creates a query of the same kind and `Db` with the node changes applied and then those of `take`, in one derived query.
|
|
3657
|
+
*
|
|
3658
|
+
* It adds the changes of `take` to `changes`, which must leave the limit as it is.
|
|
3659
|
+
*/
|
|
3660
|
+
deriveTaken(changes) {
|
|
3661
|
+
if ((changes.rows ?? this.node.rows) === "many") {
|
|
3662
|
+
changes.limit = limitToOne(this.node.limit);
|
|
3663
|
+
changes.rows = "one";
|
|
3664
|
+
}
|
|
3665
|
+
return this.derive(changes);
|
|
3666
|
+
}
|
|
3667
|
+
/**
|
|
3668
|
+
* Creates the query of the value of `projection`, of an aggregate or of `exists` over the rows of this query, which always returns one row.
|
|
3669
|
+
*
|
|
3670
|
+
* A query of `distinct` or `distinctOn` keeps the fields that `projection` replaces: `distinct` compares them, and the keys, the order, and the argument of an aggregate read a selected field through its projection.
|
|
3671
|
+
*/
|
|
3672
|
+
deriveAggregate(projection) {
|
|
3673
|
+
const { node } = this;
|
|
3674
|
+
const changes = {
|
|
3675
|
+
projections: [projection],
|
|
3676
|
+
rows: "one",
|
|
3677
|
+
value: true,
|
|
3678
|
+
guaranteed: false
|
|
3679
|
+
};
|
|
3680
|
+
if (node.distinct || node.distinctOn.length > 0) changes.distinctFields = node.projections;
|
|
3681
|
+
return this.derive(changes);
|
|
3682
|
+
}
|
|
3683
|
+
/** Creates the query of the aggregate of `method` over `arg`, a column key or a callback that receives the columns and the relations and returns an expression or a query of one value; `delimiter` is the delimiter of `stringAgg`. */
|
|
3684
|
+
aggregateBy(method, arg, delimiter) {
|
|
3685
|
+
this.rejectAggregation(method);
|
|
3686
|
+
return this.deriveAggregate(projectAggregate(method, projectValue(this.node.from, arg, method, this.context), delimiter));
|
|
3687
|
+
}
|
|
3688
|
+
/** Returns the changes of the node that add `filter` with `AND`, ending the guarantee of the row as `FilteredState` does in types. */
|
|
3689
|
+
addFilter(filter) {
|
|
3690
|
+
const { node } = this;
|
|
3691
|
+
return {
|
|
3692
|
+
filters: addUserFilter(node.filters, filter, node.from, this.context),
|
|
3693
|
+
rows: this.getFilteredRows(),
|
|
3694
|
+
guaranteed: false
|
|
3695
|
+
};
|
|
3696
|
+
}
|
|
3697
|
+
/** Returns the rows mode of this query after a filter, as `FilteredStateRows` gives it in types. */
|
|
3698
|
+
getFilteredRows() {
|
|
3699
|
+
const { node } = this;
|
|
3700
|
+
return toFilteredRows(node.rows, node.value && node.conversion === void 0, node.guaranteed);
|
|
3701
|
+
}
|
|
3702
|
+
/** Creates the query of `find` and `findBy`: `where` of `values`, an object of column values, returning one row like `take`. */
|
|
3703
|
+
takeWhere(values) {
|
|
3704
|
+
const changes = this.addFilter(values);
|
|
3705
|
+
if (changes.rows === "many") changes.rows = "one";
|
|
3706
|
+
return this.derive(changes);
|
|
3707
|
+
}
|
|
3708
|
+
/** Creates the query of one row with rows mode `rows` that `method` returns, rejecting a query of many rows. */
|
|
3709
|
+
changeOneRow(method, rows) {
|
|
3710
|
+
if (this.node.rows === "many") throw new Error(`${method} applies only to a query of one row, such as one made by take`);
|
|
3711
|
+
return this.derive({
|
|
3712
|
+
rows,
|
|
3713
|
+
guaranteed: false
|
|
3714
|
+
});
|
|
3715
|
+
}
|
|
3716
|
+
/** Rejects `method`, which reads or changes the fields of the query, on a query that `map` converts. */
|
|
3717
|
+
rejectMapped(method) {
|
|
3718
|
+
if (this.node.conversion !== void 0) throw new Error(`${method} cannot be used after map; call it before map`);
|
|
3719
|
+
}
|
|
3720
|
+
/** Rejects a change of the selection by `method` of a query made by `get`, `pluck`, or an aggregate method. */
|
|
3721
|
+
rejectValue(method) {
|
|
3722
|
+
this.rejectMapped(method);
|
|
3723
|
+
if (!this.node.value) return;
|
|
3724
|
+
this.rejectAggregate(method);
|
|
3725
|
+
throw new Error(`${method} cannot be used after get or pluck; call get or pluck to replace the value`);
|
|
3726
|
+
}
|
|
3727
|
+
/** Rejects `method`, which replaces the value or the selection, on a query made by an aggregate method or `exists`. */
|
|
3728
|
+
rejectAggregate(method) {
|
|
3729
|
+
this.rejectMapped(method);
|
|
3730
|
+
const { node } = this;
|
|
3731
|
+
if (isAggregateQuery(node)) throw new Error(`${method} cannot be used after an aggregate`);
|
|
3732
|
+
if (isExistsQuery(node)) throw new Error(`${method} cannot be used after exists`);
|
|
3733
|
+
}
|
|
3734
|
+
/** Rejects `method`, an aggregate method or `exists`, on a query made by one of them or with a row lock. */
|
|
3735
|
+
rejectAggregation(method) {
|
|
3736
|
+
this.rejectAggregate(method);
|
|
3737
|
+
if (this.node.lock !== void 0) throw new Error(`${method} cannot be used after a row lock, since it returns no rows of the table to lock`);
|
|
3738
|
+
}
|
|
3739
|
+
};
|
|
3740
|
+
/**
|
|
3741
|
+
* Returns `result`, which a callback named by `subject` returned for `query`, a query of a table or a mutation, after checking that it is `query` or a query of the same class derived from it.
|
|
3742
|
+
*
|
|
3743
|
+
* An ancestor of `query` also passes, since only the source occurrence is compared.
|
|
3744
|
+
*/
|
|
3745
|
+
function requireDerived(query, result, subject) {
|
|
3746
|
+
if (!(query instanceof SelectQuery ? result instanceof SelectQuery && result.node.from === query.node.from : result instanceof MutationQuery && result.node.target === query.node.target)) throw new Error(`${subject} must return the query it receives or one derived from it`);
|
|
3747
|
+
return result;
|
|
3748
|
+
}
|
|
3749
|
+
/** Binds a query to `db`, so that awaiting it executes it there. */
|
|
3750
|
+
function bindQuery(query, db) {
|
|
3751
|
+
return new SelectQuery(query.table, query.node, query.context, db);
|
|
3752
|
+
}
|
|
3753
|
+
/** Starts a query over a new occurrence of the table. */
|
|
3754
|
+
function from(table) {
|
|
3755
|
+
return startQuery(table, noContext);
|
|
3756
|
+
}
|
|
3757
|
+
/** 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. */
|
|
3758
|
+
function startQuery(table, context) {
|
|
3759
|
+
return new SelectQuery(table, createQueryNode(Object.freeze({
|
|
3760
|
+
kind: "table",
|
|
3761
|
+
table
|
|
3762
|
+
})), context);
|
|
3763
|
+
}
|
|
3764
|
+
// src/query/relations.ts
|
|
3765
|
+
/** Creates the contexts of the queries of the tables under `keys` in a schema of relations `relations`, by table key. */
|
|
3766
|
+
function createQueryContexts(keys, relations) {
|
|
3767
|
+
const contexts = Object.create(null);
|
|
3768
|
+
for (const key of keys) {
|
|
3769
|
+
const named = relations[key];
|
|
3770
|
+
if (named === void 0) {
|
|
3771
|
+
contexts[key] = noContext;
|
|
3772
|
+
continue;
|
|
3773
|
+
}
|
|
3774
|
+
const getters = Object.create(null);
|
|
3775
|
+
for (const name of Object.keys(named)) {
|
|
3776
|
+
const definition = named[name];
|
|
3777
|
+
getters[name] = Object.freeze({
|
|
3778
|
+
get() {
|
|
3779
|
+
return startRelated(this, definition, contexts[definition.targetKey]);
|
|
3780
|
+
},
|
|
3781
|
+
enumerable: true
|
|
3782
|
+
});
|
|
3783
|
+
}
|
|
3784
|
+
contexts[key] = Object.freeze({ relations: Object.freeze(getters) });
|
|
3785
|
+
}
|
|
3786
|
+
return Object.freeze(contexts);
|
|
3787
|
+
}
|
|
3788
|
+
/**
|
|
3789
|
+
* Starts the query of the records of relation `definition` of the row of `parent`, the references of the callback of a query, in the context of the target table.
|
|
3790
|
+
*
|
|
3791
|
+
* 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.
|
|
3792
|
+
*/
|
|
3793
|
+
function startRelated(parent, definition, context) {
|
|
3794
|
+
const { target, from, to } = definition;
|
|
3795
|
+
const source = Object.freeze({
|
|
3796
|
+
kind: "table",
|
|
3797
|
+
table: target
|
|
3798
|
+
});
|
|
3799
|
+
const conditions = [];
|
|
3800
|
+
for (let index = 0; index < from.length; index++) conditions.push(createNode({
|
|
3801
|
+
kind: "comparison",
|
|
3802
|
+
operator: "=",
|
|
3803
|
+
left: createNode({
|
|
3804
|
+
kind: "column",
|
|
3805
|
+
source,
|
|
3806
|
+
key: to[index]
|
|
3807
|
+
}),
|
|
3808
|
+
right: toNode(parent[from[index]])
|
|
3809
|
+
}));
|
|
3810
|
+
return new SelectQuery(target, createQueryNode(source, definition, Object.freeze({ relation: combineNodes("and", conditions) })), context);
|
|
3811
|
+
}
|
|
3812
|
+
// src/schema/schema.ts
|
|
3813
|
+
const schemaBrand = Symbol("kern-orm.schema");
|
|
3814
|
+
/** Key of the relation definitions of a schema, which composition reads. */
|
|
3815
|
+
const schemaRelations = Symbol("kern-orm.schema.relations");
|
|
3816
|
+
/**
|
|
3817
|
+
* Defines a schema of the tables of `parts`, keyed by their names in queries.
|
|
3818
|
+
*
|
|
3819
|
+
* 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.
|
|
3820
|
+
* 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.
|
|
3821
|
+
*/
|
|
3822
|
+
function defineSchema(...parts) {
|
|
3823
|
+
const tables = /* @__PURE__ */ new Map();
|
|
3824
|
+
const keys = /* @__PURE__ */ new Map();
|
|
3825
|
+
const relations = /* @__PURE__ */ new Map();
|
|
3826
|
+
for (const part of parts) {
|
|
3827
|
+
const partTables = isSchema(part) ? part.$tables : part;
|
|
3828
|
+
for (const key of Object.keys(partTables)) {
|
|
3829
|
+
if (key.startsWith("$")) throw new Error(`Table key "${key}" must not start with "$"`);
|
|
3830
|
+
const table = partTables[key];
|
|
3831
|
+
const keyTable = tables.get(key);
|
|
3832
|
+
if (keyTable !== void 0 && keyTable !== table) throw new Error(`Table key "${key}" refers to two different tables`);
|
|
3833
|
+
const tableKey = keys.get(table);
|
|
3834
|
+
if (tableKey !== void 0 && tableKey !== key) throw new Error(`Table "${table.name}" is included under two keys, "${tableKey}" and "${key}"`);
|
|
3835
|
+
tables.set(key, table);
|
|
3836
|
+
keys.set(table, key);
|
|
3837
|
+
}
|
|
3838
|
+
if (isSchema(part)) addRelations(relations, part[schemaRelations]);
|
|
3839
|
+
}
|
|
3840
|
+
return createSchema(Object.freeze(Object.fromEntries(tables)), keys, freezeRelations(relations));
|
|
3841
|
+
}
|
|
3842
|
+
/** Creates a schema of tables and relation definitions that are already checked; `keys` gives the key of each table. */
|
|
3843
|
+
function createSchema(tables, keys, relations) {
|
|
3844
|
+
const methods = {
|
|
3845
|
+
[schemaBrand]: true,
|
|
3846
|
+
$tables: tables,
|
|
3847
|
+
[schemaRelations]: relations,
|
|
3848
|
+
$relations(declarations) {
|
|
3849
|
+
const added = /* @__PURE__ */ new Map();
|
|
3850
|
+
addRelations(added, relations);
|
|
3851
|
+
for (const key of Object.keys(declarations)) {
|
|
3852
|
+
if (!Object.hasOwn(tables, key)) throw new Error(`Relations are declared for table key "${key}", which is not part of the schema`);
|
|
3853
|
+
const named = declarations[key];
|
|
3854
|
+
if (named === void 0) continue;
|
|
3855
|
+
for (const name of Object.keys(named)) addRelation(added, key, name, defineRelation(tables[key], key, name, named[name], (table) => keys.get(table)));
|
|
3856
|
+
}
|
|
3857
|
+
return createSchema(tables, keys, freezeRelations(added));
|
|
3858
|
+
},
|
|
3859
|
+
$select: (selection) => startRecordQuery(selection)
|
|
3860
|
+
};
|
|
3861
|
+
const contexts = createQueryContexts(Object.keys(tables), relations);
|
|
3862
|
+
return defineEntries(methods, tables, (key) => startQuery(tables[key], contexts[key]));
|
|
3863
|
+
}
|
|
3864
|
+
function isSchema(part) {
|
|
3865
|
+
return schemaBrand in part;
|
|
3866
|
+
}
|
|
3867
|
+
/** Adds a getter per table key to `methods` that starts a query with `start`, and freezes the result. */
|
|
3868
|
+
function defineEntries(methods, tables, start) {
|
|
3869
|
+
const result = Object.defineProperties(methods, Object.fromEntries(Object.keys(tables).map((key) => [key, {
|
|
3870
|
+
get: () => start(key),
|
|
3871
|
+
enumerable: true
|
|
3872
|
+
}])));
|
|
3873
|
+
return Object.freeze(result);
|
|
3874
|
+
}
|
|
3875
|
+
// src/expression/sql.ts
|
|
3876
|
+
function sql(first, ...values) {
|
|
3877
|
+
if (isTemplateStrings(first)) return createFragment(first, values, void 0);
|
|
3878
|
+
if (!isType(first)) throw new TypeError("sql() accepts a type, not a column");
|
|
3879
|
+
return (strings, ...values) => createFragment(strings, values, first);
|
|
3880
|
+
}
|
|
3881
|
+
/**
|
|
3882
|
+
* Creates a SQL fragment of a quoted name, such as of a table or a column known only at runtime, for the templates of `sql`, of `$query` and `$script` of a `Db`, and of `query` and `script` of a `Database`.
|
|
3883
|
+
*
|
|
3884
|
+
* Several names make a qualified name, such as `identifier(schema, table)` for `"schema"."table"`.
|
|
3885
|
+
* The fragment has no parameters, so a script takes it.
|
|
3886
|
+
* The name is not qualified by the PostgreSQL schema of the statement.
|
|
3887
|
+
*/
|
|
3888
|
+
function identifier(...names) {
|
|
3889
|
+
let text = "";
|
|
3890
|
+
for (const name of names) {
|
|
3891
|
+
if (typeof name !== "string" || name === "") throw new TypeError("identifier() takes names as non-empty strings");
|
|
3892
|
+
text += (text === "" ? "" : ".") + quoteIdentifier(name);
|
|
3893
|
+
}
|
|
3894
|
+
if (text === "") throw new TypeError("identifier() takes at least one name");
|
|
3895
|
+
return toExpression(createNode({
|
|
3896
|
+
kind: "raw",
|
|
3897
|
+
fragments: [text],
|
|
3898
|
+
values: []
|
|
3899
|
+
}));
|
|
3900
|
+
}
|
|
3901
|
+
function param(type, value) {
|
|
3902
|
+
if (!isType(type) && !isExpression(type)) throw new TypeError("param() accepts a type or an expression, not a column");
|
|
3903
|
+
if (isExpression(type)) {
|
|
3904
|
+
if (isExpression(value)) return value;
|
|
3905
|
+
const valueType = getType(type);
|
|
3906
|
+
return toExpression(toValueNode(value, valueType), valueType);
|
|
3907
|
+
}
|
|
3908
|
+
return toExpression(toCastValueNode(value, type), type);
|
|
3909
|
+
}
|
|
3910
|
+
function isTemplateStrings(value) {
|
|
3911
|
+
return Array.isArray(value);
|
|
3912
|
+
}
|
|
3913
|
+
function createFragment(strings, values, type) {
|
|
3914
|
+
return toExpression(toRawSqlNode(strings, values), type);
|
|
3915
|
+
}
|
|
3916
|
+
/**
|
|
3917
|
+
* Creates the node of the SQL of a template, whose interpolations stay structured nodes.
|
|
3918
|
+
*
|
|
3919
|
+
* An interpolated expression keeps its node, and a query of a table without clauses becomes the name of the table, qualified by the PostgreSQL schema of the statement.
|
|
3920
|
+
* Another query of a table becomes a query in an expression, which lowering replaces with its SQL.
|
|
3921
|
+
* Other values become query parameters.
|
|
3922
|
+
* It rejects the other queries, which a parameter would encode as text.
|
|
3923
|
+
*/
|
|
3924
|
+
function toRawSqlNode(strings, values) {
|
|
3925
|
+
const nodes = [];
|
|
3926
|
+
for (let index = 0; index < values.length; index++) nodes.push(toInterpolatedNode(values[index]));
|
|
3927
|
+
return createNode({
|
|
3928
|
+
kind: "raw",
|
|
3929
|
+
fragments: [...strings],
|
|
3930
|
+
values: nodes
|
|
3931
|
+
});
|
|
3932
|
+
}
|
|
3933
|
+
/** Returns the node of a value interpolated into SQL, as `toRawSqlNode` takes it. */
|
|
3934
|
+
function toInterpolatedNode(value) {
|
|
3935
|
+
if (value instanceof SelectQuery) {
|
|
3936
|
+
const { node } = value;
|
|
3937
|
+
if (node.conversion !== void 0) throw new TypeError("sql takes a query of a table, such as db.form or a query of its records, not a query of map or transform");
|
|
3938
|
+
return isTableQuery(node) ? createNode({
|
|
3939
|
+
kind: "tableName",
|
|
3940
|
+
table: value.table,
|
|
3941
|
+
db: value.db
|
|
3942
|
+
}) : createNode({
|
|
3943
|
+
kind: "nestedQuery",
|
|
3944
|
+
query: node,
|
|
3945
|
+
db: value.db
|
|
3946
|
+
});
|
|
3947
|
+
}
|
|
3948
|
+
if (value instanceof RecordQuery || value instanceof MutationQuery || value instanceof SqlQuery || value instanceof TransformedQuery) throw new TypeError("sql takes a query of a table, such as db.form or a query of its records, not a query of $select, a mutation, a query of SQL text, or a query of map or transform");
|
|
3949
|
+
return toValueNode(value);
|
|
3950
|
+
}
|
|
3951
|
+
// src/execution/db.ts
|
|
3952
|
+
/** Binds `schema` to `database`; see `Database.bind`. */
|
|
3953
|
+
function bindSchema(schema, database, options = {}) {
|
|
3954
|
+
const tables = new Set(Object.values(schema.$tables));
|
|
3955
|
+
const relations = schema[schemaRelations];
|
|
3956
|
+
const definitions = collectDefinitions(relations);
|
|
3957
|
+
const { schemaName } = options;
|
|
3958
|
+
const resolveSchemaName = () => typeof schemaName === "function" ? schemaName() : schemaName;
|
|
3959
|
+
function compile(query) {
|
|
3960
|
+
if (query.db !== void 0 && query.db !== db) throw new Error("Cannot run a query bound to another Db");
|
|
3961
|
+
return compileStatement(lowerStatement(query.node, definitions, db), { schemaName: resolveSchemaName() }, tables, db);
|
|
3962
|
+
}
|
|
3963
|
+
const methods = {
|
|
3964
|
+
$schema: schema,
|
|
3965
|
+
$database: database,
|
|
3966
|
+
get $schemaName() {
|
|
3967
|
+
return resolveSchemaName();
|
|
3968
|
+
},
|
|
3969
|
+
$compile(query) {
|
|
3970
|
+
const { text, parameters } = compile(query);
|
|
3971
|
+
return createStatement(text, parameters);
|
|
3972
|
+
},
|
|
3973
|
+
async $execute(query) {
|
|
3974
|
+
const compiled = compile(query);
|
|
3975
|
+
if (compiled.locksRows && !database.isInTransaction()) throw new Error("Cannot lock the rows of a query outside a transaction, where the locks would end with its statement; a test transaction alone does not count");
|
|
3976
|
+
return decodeStatement(compiled, await database.execute(compiled));
|
|
3977
|
+
},
|
|
3978
|
+
$select: (selection) => startRecordQuery(selection, db),
|
|
3979
|
+
$query: (strings, ...values) => startSqlQuery(toRawSqlNode(strings, values), db),
|
|
3980
|
+
async $script(script, ...values) {
|
|
3981
|
+
if (typeof script === "string") return database.script(script);
|
|
3982
|
+
const { text, parameters } = compile(startSqlQuery(toRawSqlNode(script, values), db));
|
|
3983
|
+
if (parameters.length > 0) throw new Error("A script has no parameters, so it takes no values, also in the queries and sql fragments that it interpolates");
|
|
3984
|
+
return database.script(text);
|
|
3985
|
+
},
|
|
3986
|
+
$transaction: (callback, options) => database.transaction(callback, options),
|
|
3987
|
+
$ensureTransaction: (callback) => database.ensureTransaction(callback),
|
|
3988
|
+
$isInTransaction: () => database.isInTransaction(),
|
|
3989
|
+
$lock: (key) => database.lock(key)
|
|
3990
|
+
};
|
|
3991
|
+
const contexts = createQueryContexts(Object.keys(schema.$tables), relations);
|
|
3992
|
+
const db = defineEntries(methods, schema.$tables, (key) => bindQuery(startQuery(schema.$tables[key], contexts[key]), db));
|
|
3993
|
+
return db;
|
|
3994
|
+
}
|
|
3995
|
+
// src/execution/transaction/abort.ts
|
|
3996
|
+
/**
|
|
3997
|
+
* Runs `start` and settles as its promise, or rejects with the reason of `signal` when it aborts first and `abort`, called on the abort, returns `true`.
|
|
3998
|
+
*
|
|
3999
|
+
* It listens from before `start`, which may abort the signal before it returns, and stops once the promise of `start` settles, such as for the signal that `node:test` aborts after every test.
|
|
4000
|
+
* A later rejection of that promise stays handled, and a value it resolves with after the rejection goes to `discard`, which handles its own failures.
|
|
4001
|
+
*/
|
|
4002
|
+
function settleUnlessAborted(start, signal, abort, discard) {
|
|
4003
|
+
const settled = Promise.withResolvers();
|
|
4004
|
+
let abandoned = false;
|
|
4005
|
+
const onAbort = () => {
|
|
4006
|
+
if (abort()) {
|
|
4007
|
+
abandoned = true;
|
|
4008
|
+
settled.reject(signal.reason);
|
|
4009
|
+
}
|
|
4010
|
+
};
|
|
4011
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
4012
|
+
let running;
|
|
4013
|
+
try {
|
|
4014
|
+
running = start();
|
|
4015
|
+
} catch (error) {
|
|
4016
|
+
signal.removeEventListener("abort", onAbort);
|
|
4017
|
+
settled.reject(error);
|
|
4018
|
+
return settled.promise;
|
|
4019
|
+
}
|
|
4020
|
+
running.then((value) => {
|
|
4021
|
+
signal.removeEventListener("abort", onAbort);
|
|
4022
|
+
if (abandoned) discard?.(value);
|
|
4023
|
+
else settled.resolve(value);
|
|
4024
|
+
}, (error) => {
|
|
4025
|
+
signal.removeEventListener("abort", onAbort);
|
|
4026
|
+
settled.reject(error);
|
|
4027
|
+
});
|
|
4028
|
+
return settled.promise;
|
|
4029
|
+
}
|
|
4030
|
+
/**
|
|
4031
|
+
* Acquires a connection for a test transaction, rejecting with the reason of `signal` when it aborts first.
|
|
4032
|
+
*
|
|
4033
|
+
* A connection acquired after the abort returns to the pool as best-effort cleanup: the test transaction has already rejected, so nothing awaits the release, and its failure is ignored.
|
|
4034
|
+
*/
|
|
4035
|
+
function acquireUnlessAborted(driver, signal) {
|
|
4036
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
4037
|
+
return settleUnlessAborted(() => driver.acquire(), signal, () => true, (connection) => {
|
|
4038
|
+
Promise.resolve().then(() => connection.release()).catch(() => {});
|
|
4039
|
+
});
|
|
4040
|
+
}
|
|
4041
|
+
// src/execution/transaction/settings.ts
|
|
4042
|
+
/** Settings of a level of `transaction` with `options`, or `undefined` when it has none. */
|
|
4043
|
+
function getLevelSettings(options) {
|
|
4044
|
+
return options?.searchPath ? [{
|
|
4045
|
+
name: "search_path",
|
|
4046
|
+
value: options.searchPath.map(quoteIdentifier).join(", ")
|
|
4047
|
+
}] : void 0;
|
|
4048
|
+
}
|
|
4049
|
+
/**
|
|
4050
|
+
* Applies `settings` to a level whose `BEGIN` or `SAVEPOINT` completed, unless its cleanup has started.
|
|
4051
|
+
*
|
|
4052
|
+
* A nested level first reads the values they replace, which it restores before its `RELEASE`: PostgreSQL keeps a setting of a released savepoint until the transaction ends, while `ROLLBACK TO` restores it itself.
|
|
4053
|
+
*/
|
|
4054
|
+
async function applySettings(level, settings) {
|
|
4055
|
+
if (level.cleanup) return;
|
|
4056
|
+
if (level.parent) {
|
|
4057
|
+
let text = "SELECT";
|
|
4058
|
+
const names = [];
|
|
4059
|
+
for (const { name } of settings) {
|
|
4060
|
+
names.push(name);
|
|
4061
|
+
text += `${names.length > 1 ? "," : ""} current_setting($${names.length})`;
|
|
4062
|
+
}
|
|
4063
|
+
const values = (await level.connection.execute(createStatement(text, names))).rows[0];
|
|
4064
|
+
level.restore = createSettingStatement(settings.map(({ name }, index) => ({
|
|
4065
|
+
name,
|
|
4066
|
+
value: values[index]
|
|
4067
|
+
})));
|
|
4068
|
+
if (level.cleanup) return;
|
|
4069
|
+
}
|
|
4070
|
+
await level.connection.execute(createSettingStatement(settings));
|
|
4071
|
+
}
|
|
4072
|
+
/** Creates the statement that sets `settings` until the transaction ends or rolls back to an earlier savepoint, as `SET LOCAL` does. */
|
|
4073
|
+
function createSettingStatement(settings) {
|
|
4074
|
+
let text = "SELECT";
|
|
4075
|
+
const parameters = [];
|
|
4076
|
+
for (const { name, value } of settings) {
|
|
4077
|
+
parameters.push(name, value);
|
|
4078
|
+
text += `${parameters.length > 2 ? "," : ""} set_config($${parameters.length - 1}, $${parameters.length}, true)`;
|
|
4079
|
+
}
|
|
4080
|
+
return createStatement(text, parameters);
|
|
4081
|
+
}
|
|
4082
|
+
// src/execution/transaction/level.ts
|
|
4083
|
+
/** Statement that starts the transaction of a level without a parent: a transaction of `transaction`, a test transaction, or the first test fixture. */
|
|
4084
|
+
const beginStatement = /* @__PURE__ */ createStatement("BEGIN");
|
|
4085
|
+
const commitStatement = /* @__PURE__ */ createStatement("COMMIT");
|
|
4086
|
+
const rollbackStatement = /* @__PURE__ */ createStatement("ROLLBACK");
|
|
4087
|
+
/**
|
|
4088
|
+
* Creates the state of a `starting` level on `connection`, nested in `parent` if given.
|
|
4089
|
+
*
|
|
4090
|
+
* It sends no SQL and does not reserve the level as the `child` of `parent`; the caller does both.
|
|
4091
|
+
* `transaction` tells whether the level is a transaction of `transaction` rather than a level of the test helpers.
|
|
4092
|
+
*/
|
|
4093
|
+
function createLevel(connection, parent, transaction) {
|
|
4094
|
+
return {
|
|
4095
|
+
connection,
|
|
4096
|
+
parent,
|
|
4097
|
+
depth: parent ? parent.depth + 1 : 0,
|
|
4098
|
+
inTransaction: transaction || (parent?.inTransaction ?? false),
|
|
4099
|
+
state: "starting",
|
|
4100
|
+
child: void 0,
|
|
4101
|
+
rollbackOnly: void 0,
|
|
4102
|
+
cleanup: void 0,
|
|
4103
|
+
endedBy: void 0,
|
|
4104
|
+
restore: void 0
|
|
4105
|
+
};
|
|
4106
|
+
}
|
|
4107
|
+
/**
|
|
4108
|
+
* Reserves a nested level of `parent`, sends its `SAVEPOINT`, and applies its `settings`, rejecting when one of them fails.
|
|
4109
|
+
*
|
|
4110
|
+
* `transaction` tells whether the level is a transaction of `transaction` rather than a level of the test helpers.
|
|
4111
|
+
* A level whose settings fail rolls back to its savepoint first.
|
|
4112
|
+
* The failure suppresses the reason of `signal` when the signal aborted before it.
|
|
4113
|
+
*/
|
|
4114
|
+
async function startNestedLevel(parent, transaction, signal, settings) {
|
|
4115
|
+
const level = createLevel(parent.connection, parent, transaction);
|
|
4116
|
+
parent.child = level;
|
|
4117
|
+
try {
|
|
4118
|
+
await level.connection.execute(createStatement(`SAVEPOINT ${getSavepointName(level)}`));
|
|
4119
|
+
} catch (error) {
|
|
4120
|
+
if (!level.cleanup) {
|
|
4121
|
+
closeStarting(level);
|
|
4122
|
+
throw suppressAbortReason(error, signal);
|
|
4123
|
+
}
|
|
4124
|
+
throw suppressAbortReason(combineRejections({ error }, await level.cleanup).error, signal);
|
|
4125
|
+
}
|
|
4126
|
+
if (settings) try {
|
|
4127
|
+
await applySettings(level, settings);
|
|
4128
|
+
} catch (error) {
|
|
4129
|
+
throw suppressAbortReason(combineRejections({ error }, await endLevel(level, false)).error, signal);
|
|
4130
|
+
}
|
|
4131
|
+
return level;
|
|
4132
|
+
}
|
|
4133
|
+
/**
|
|
4134
|
+
* Runs `callback` in the context of a started `level` in `storage`, then ends the level.
|
|
4135
|
+
*
|
|
4136
|
+
* A level that `commits` commits only when the callback resolves with no nested level running and no nested level that failed to end.
|
|
4137
|
+
* When `signal` aborts, the level ends at once without waiting for the callback, and its outcome is a rejection with the reason of the signal.
|
|
4138
|
+
*/
|
|
4139
|
+
async function runLevel(storage, level, callback, commits, signal) {
|
|
4140
|
+
if (level.cleanup) return getEndedOutcome(level.cleanup, createClosedError(level, void 0));
|
|
4141
|
+
let result;
|
|
4142
|
+
let rejection;
|
|
4143
|
+
if (signal?.aborted) endLevel(level, false, "abort");
|
|
4144
|
+
else {
|
|
4145
|
+
level.state = "open";
|
|
4146
|
+
try {
|
|
4147
|
+
result = await (signal ? settleUnlessAborted(() => storage.run(level, callback), signal, () => {
|
|
4148
|
+
endLevel(level, false, "abort");
|
|
4149
|
+
return true;
|
|
4150
|
+
}) : storage.run(level, callback));
|
|
4151
|
+
} catch (error) {
|
|
4152
|
+
rejection = { error };
|
|
4153
|
+
}
|
|
4154
|
+
}
|
|
4155
|
+
if (level.cleanup) return getEndedOutcome(level.cleanup, level.endedBy === "abort" ? signal?.reason : createClosedError(level, rejection));
|
|
4156
|
+
if (!rejection && level.child) rejection = { error: /* @__PURE__ */ new Error("Transaction was rolled back: a nested transaction was still running when its callback finished") };
|
|
4157
|
+
if (!rejection && level.rollbackOnly) rejection = { error: new Error("Transaction was rolled back: a nested transaction failed to end", { cause: level.rollbackOnly.error }) };
|
|
4158
|
+
const cleanup = await endLevel(level, commits && !rejection);
|
|
4159
|
+
return {
|
|
4160
|
+
result,
|
|
4161
|
+
rejection: combineRejections(rejection, cleanup),
|
|
4162
|
+
failure: cleanup.failure
|
|
4163
|
+
};
|
|
4164
|
+
}
|
|
4165
|
+
/**
|
|
4166
|
+
* Ends `level` once, whoever ends it: later calls return the cleanup already started.
|
|
4167
|
+
*
|
|
4168
|
+
* Statements of the level and of all levels nested in it fail from the start of the cleanup, and the nested levels end before it.
|
|
4169
|
+
*/
|
|
4170
|
+
function endLevel(level, commit, endedBy) {
|
|
4171
|
+
if (level.cleanup) return level.cleanup;
|
|
4172
|
+
level.endedBy = endedBy;
|
|
4173
|
+
level.state = "closing";
|
|
4174
|
+
level.cleanup = cleanUpLevel(level, commit, level.child && endLevel(level.child, false, "enclosing level"));
|
|
4175
|
+
return level.cleanup;
|
|
4176
|
+
}
|
|
4177
|
+
async function cleanUpLevel(level, commit, nested) {
|
|
4178
|
+
const nestedCleanup = await nested;
|
|
4179
|
+
const { parent } = level;
|
|
4180
|
+
const cleanup = parent ? await endSavepoint(level, commit && !level.rollbackOnly) : await endTransaction(level.connection, commit);
|
|
4181
|
+
level.state = "closed";
|
|
4182
|
+
if (parent) {
|
|
4183
|
+
if (parent.child === level) parent.child = void 0;
|
|
4184
|
+
parent.rollbackOnly ??= cleanup.rejection;
|
|
4185
|
+
}
|
|
4186
|
+
return {
|
|
4187
|
+
rejection: combineRejections(nestedCleanup?.rejection, cleanup),
|
|
4188
|
+
failure: cleanup.failure
|
|
4189
|
+
};
|
|
4190
|
+
}
|
|
4191
|
+
/** Ends a transaction with `COMMIT` or `ROLLBACK`. */
|
|
4192
|
+
async function endTransaction(connection, commit) {
|
|
4193
|
+
try {
|
|
4194
|
+
const { command } = await connection.execute(commit ? commitStatement : rollbackStatement);
|
|
4195
|
+
if (commit && command !== "COMMIT") return { rejection: { error: /* @__PURE__ */ new Error("Transaction was rolled back: a statement in it failed") } };
|
|
4196
|
+
return {};
|
|
4197
|
+
} catch (error) {
|
|
4198
|
+
return {
|
|
4199
|
+
rejection: { error },
|
|
4200
|
+
failure: { error }
|
|
4201
|
+
};
|
|
4202
|
+
}
|
|
4203
|
+
}
|
|
4204
|
+
/**
|
|
4205
|
+
* Ends the savepoint of a nested level, releasing it on commit and rolling back to it otherwise.
|
|
4206
|
+
*
|
|
4207
|
+
* Before a release, it restores the settings that the level changed; a rollback restores them itself.
|
|
4208
|
+
*/
|
|
4209
|
+
async function endSavepoint(level, commit) {
|
|
4210
|
+
const name = getSavepointName(level);
|
|
4211
|
+
try {
|
|
4212
|
+
if (!commit) await level.connection.execute(createStatement(`ROLLBACK TO SAVEPOINT ${name}`));
|
|
4213
|
+
else if (level.restore) await level.connection.execute(level.restore);
|
|
4214
|
+
await level.connection.execute(createStatement(`RELEASE SAVEPOINT ${name}`));
|
|
4215
|
+
return {};
|
|
4216
|
+
} catch (error) {
|
|
4217
|
+
return { rejection: { error } };
|
|
4218
|
+
}
|
|
4219
|
+
}
|
|
4220
|
+
/** Name of the savepoint of a nested level; a level has at most one nested level, so the depth makes it unique. */
|
|
4221
|
+
function getSavepointName(level) {
|
|
4222
|
+
return `kern_${level.depth}`;
|
|
4223
|
+
}
|
|
4224
|
+
/** Closes a nested level whose `SAVEPOINT` failed, freeing its parent for other statements. */
|
|
4225
|
+
function closeStarting(level) {
|
|
4226
|
+
level.state = "closed";
|
|
4227
|
+
if (level.parent?.child === level) level.parent.child = void 0;
|
|
4228
|
+
}
|
|
4229
|
+
/**
|
|
4230
|
+
* Creates the error of `operation` on a level that rejects statements and nested levels, or returns `undefined` when it accepts them.
|
|
4231
|
+
*
|
|
4232
|
+
* A level that can only roll back keeps the failure of its nested level as the cause.
|
|
4233
|
+
*/
|
|
4234
|
+
function createUnavailableError(level, operation) {
|
|
4235
|
+
if (level.state !== "open") return /* @__PURE__ */ new Error(`Cannot ${operation}: its transaction is already finished`);
|
|
4236
|
+
if (level.child) return /* @__PURE__ */ new Error(`Cannot ${operation}: a nested transaction is running; await it first`);
|
|
4237
|
+
if (level.rollbackOnly) return new Error(`Cannot ${operation}: a nested transaction failed to end, so the transaction can only roll back`, { cause: level.rollbackOnly.error });
|
|
4238
|
+
}
|
|
4239
|
+
/** Error of a level that another level ended, keeping the rejection of its callback as the cause. */
|
|
4240
|
+
function createClosedError(level, rejection) {
|
|
4241
|
+
return new Error(level.endedBy === "preemption" ? "Transaction was rolled back: its test fixture started another level before it finished" : "Transaction was rolled back: its enclosing transaction ended first", rejection && { cause: rejection.error });
|
|
4242
|
+
}
|
|
4243
|
+
/** Outcome of a level that something other than its callback ended: a rejection with `error`, which a failed cleanup suppresses. */
|
|
4244
|
+
async function getEndedOutcome(cleanup, error) {
|
|
4245
|
+
const ended = await cleanup;
|
|
4246
|
+
return {
|
|
4247
|
+
rejection: combineRejections({ error }, ended),
|
|
4248
|
+
failure: ended.failure
|
|
4249
|
+
};
|
|
4250
|
+
}
|
|
4251
|
+
/** Returns the connection of a transaction to the driver, keeping a failed release as a rejection that suppresses `rejection`. */
|
|
4252
|
+
async function releaseConnection(connection, failure, rejection) {
|
|
4253
|
+
try {
|
|
4254
|
+
await connection.release(failure);
|
|
4255
|
+
return rejection;
|
|
4256
|
+
} catch (error) {
|
|
4257
|
+
return suppress(error, rejection, "Releasing the transaction connection failed");
|
|
4258
|
+
}
|
|
4259
|
+
}
|
|
4260
|
+
/** Error of a failure to start a test transaction, which suppresses the reason of `signal` when the signal aborted before the failure. */
|
|
4261
|
+
function suppressAbortReason(error, signal) {
|
|
4262
|
+
return signal?.aborted ? suppress(error, { error: signal.reason }, "Starting the test transaction failed").error : error;
|
|
4263
|
+
}
|
|
4264
|
+
/** Rejection with the error of a cleanup, which suppresses the `earlier` rejection if there is one. */
|
|
4265
|
+
function combineRejections(earlier, cleanup) {
|
|
4266
|
+
return cleanup.rejection ? suppress(cleanup.rejection.error, earlier, "Transaction rollback failed") : earlier;
|
|
4267
|
+
}
|
|
4268
|
+
/** Rejection with `error`, which suppresses the `earlier` rejection if there is one. */
|
|
4269
|
+
function suppress(error, earlier, message) {
|
|
4270
|
+
return { error: earlier ? new SuppressedError(error, earlier.error, message) : error };
|
|
4271
|
+
}
|
|
4272
|
+
// src/execution/transaction/fixture-stack.ts
|
|
4273
|
+
/** Open test fixtures of a transaction coordinator and the queue of the changes of their stack. */
|
|
4274
|
+
var TestFixtureStack = class {
|
|
4275
|
+
#driver;
|
|
4276
|
+
/** Async context of the levels of the coordinator, which tells whether a call runs inside a level. */
|
|
4277
|
+
#storage;
|
|
4278
|
+
/** Open test fixtures, the innermost last. */
|
|
4279
|
+
#fixtures = [];
|
|
4280
|
+
/** Changes of the fixture stack, run one after another so that each one sees the stack the previous one left. */
|
|
4281
|
+
#transitions = Promise.resolve();
|
|
4282
|
+
/**
|
|
4283
|
+
* The `close` functions of the test fixtures that are still opening, from the call that starts the opening until the fixture enters the stack or the opening ends otherwise.
|
|
4284
|
+
*
|
|
4285
|
+
* An opening holds the queue of the fixture stack while its seed runs, so a closing of the stack queued behind it would wait for a seed that may never settle.
|
|
4286
|
+
* Closing the stack therefore calls these first: each one tells its opening to stop waiting for the seed.
|
|
4287
|
+
*/
|
|
4288
|
+
#openings = /* @__PURE__ */ new Set();
|
|
4289
|
+
/**
|
|
4290
|
+
* Outermost fixture in the stack whose closing is queued but has not finished.
|
|
4291
|
+
*
|
|
4292
|
+
* Openings that start after that closing is requested nest outside of the fixture once it closes, so a repeated closing of it, or a closing of a fixture nested in it, must not close them.
|
|
4293
|
+
*/
|
|
4294
|
+
#closing;
|
|
4295
|
+
constructor(driver, storage) {
|
|
4296
|
+
this.#driver = driver;
|
|
4297
|
+
this.#storage = storage;
|
|
4298
|
+
}
|
|
4299
|
+
/**
|
|
4300
|
+
* Starts opening a test fixture, see `startTestFixture` of the coordinator, or, given `refusal`, returns a fixture that rejects with it.
|
|
4301
|
+
*
|
|
4302
|
+
* The `close` of a refused fixture resolves once the earlier changes of the stack end.
|
|
4303
|
+
*/
|
|
4304
|
+
start(seed, refusal) {
|
|
4305
|
+
let level;
|
|
4306
|
+
let closeRequested = false;
|
|
4307
|
+
const closing = Promise.withResolvers();
|
|
4308
|
+
let closedRejection;
|
|
4309
|
+
const close = () => {
|
|
4310
|
+
if (this.#storage.getStore()) return Promise.reject(/* @__PURE__ */ new Error("Cannot close a test fixture inside a transaction"));
|
|
4311
|
+
closeRequested = true;
|
|
4312
|
+
closing.resolve();
|
|
4313
|
+
if (level && this.#fixtures.includes(level)) {
|
|
4314
|
+
const opened = level;
|
|
4315
|
+
if (this.#closing && this.#closing.depth <= opened.depth) return this.#enqueue(() => this.#closeFixture(opened));
|
|
4316
|
+
this.#closing = opened;
|
|
4317
|
+
return this.#closeAfterOpenings(() => this.#enqueue(async () => {
|
|
4318
|
+
try {
|
|
4319
|
+
await this.#closeFixture(opened);
|
|
4320
|
+
} finally {
|
|
4321
|
+
if (this.#closing === opened) this.#closing = void 0;
|
|
4322
|
+
}
|
|
4323
|
+
}));
|
|
4324
|
+
}
|
|
4325
|
+
return this.#enqueue(() => {
|
|
4326
|
+
const rejection = closedRejection;
|
|
4327
|
+
closedRejection = void 0;
|
|
4328
|
+
if (rejection) throw rejection.error;
|
|
4329
|
+
});
|
|
4330
|
+
};
|
|
4331
|
+
if (refusal) return {
|
|
4332
|
+
fixture: Promise.reject(refusal),
|
|
4333
|
+
close
|
|
4334
|
+
};
|
|
4335
|
+
/**
|
|
4336
|
+
* 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.
|
|
4337
|
+
*
|
|
4338
|
+
* 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`.
|
|
4339
|
+
*/
|
|
4340
|
+
const open = async () => {
|
|
4341
|
+
if (closeRequested) return;
|
|
4342
|
+
const parent = this.#fixtures.at(-1);
|
|
4343
|
+
const started = parent ? await this.#startInFixture(parent) : await this.#beginFixture();
|
|
4344
|
+
started.state = "open";
|
|
4345
|
+
const outcome = closeRequested ? void 0 : await Promise.race([this.#seedFixture(started, seed), closing.promise]);
|
|
4346
|
+
if (outcome && !outcome.rejection && !closeRequested) {
|
|
4347
|
+
this.#fixtures.push(started);
|
|
4348
|
+
level = started;
|
|
4349
|
+
this.#openings.delete(close);
|
|
4350
|
+
const { result } = outcome;
|
|
4351
|
+
return {
|
|
4352
|
+
get data() {
|
|
4353
|
+
if (started.state !== "open") throw new Error("Test fixture is closed");
|
|
4354
|
+
return result;
|
|
4355
|
+
},
|
|
4356
|
+
close,
|
|
4357
|
+
[Symbol.asyncDispose]: close
|
|
4358
|
+
};
|
|
4359
|
+
}
|
|
4360
|
+
const rejection = combineRejections(outcome?.rejection, { rejection: await this.#endFixture(started) });
|
|
4361
|
+
if (rejection) throw rejection.error;
|
|
4362
|
+
};
|
|
4363
|
+
this.#openings.add(close);
|
|
4364
|
+
return {
|
|
4365
|
+
fixture: this.#enqueue(async () => {
|
|
4366
|
+
let opened;
|
|
4367
|
+
try {
|
|
4368
|
+
opened = await open();
|
|
4369
|
+
} catch (error) {
|
|
4370
|
+
if (!closeRequested) throw error;
|
|
4371
|
+
closedRejection = { error };
|
|
4372
|
+
} finally {
|
|
4373
|
+
this.#openings.delete(close);
|
|
4374
|
+
}
|
|
4375
|
+
if (!opened) throw new Error("Test fixture was closed before it opened");
|
|
4376
|
+
return opened;
|
|
4377
|
+
}),
|
|
4378
|
+
close
|
|
4379
|
+
};
|
|
4380
|
+
}
|
|
4381
|
+
/**
|
|
4382
|
+
* Starts the level of a test transaction in the innermost test fixture as a change of the fixture stack, resolving to `undefined` when no fixture is open.
|
|
4383
|
+
*
|
|
4384
|
+
* Aborted while it waits for its turn, it rejects at once and its change starts nothing, so that a test that has already ended never preempts the active level of the fixture.
|
|
4385
|
+
* From its turn on, it settles with its change.
|
|
4386
|
+
*/
|
|
4387
|
+
startTestLevel(signal) {
|
|
4388
|
+
let waiting = true;
|
|
4389
|
+
const start = () => this.#enqueue(() => {
|
|
4390
|
+
if (signal?.aborted) return;
|
|
4391
|
+
waiting = false;
|
|
4392
|
+
const fixture = this.#fixtures.at(-1);
|
|
4393
|
+
return fixture && this.#startInFixture(fixture, signal);
|
|
4394
|
+
});
|
|
4395
|
+
return signal ? settleUnlessAborted(start, signal, () => waiting) : start();
|
|
4396
|
+
}
|
|
4397
|
+
/**
|
|
4398
|
+
* Closes every fixture, including those still opening, rejecting with the failures of all of them.
|
|
4399
|
+
*
|
|
4400
|
+
* Unlike closing a fixture, it closes every opening, including one started after a closing of the stack was requested, since nothing may stay open.
|
|
4401
|
+
*/
|
|
4402
|
+
close() {
|
|
4403
|
+
return this.#closeAfterOpenings(() => this.#enqueue(() => {
|
|
4404
|
+
const root = this.#fixtures[0];
|
|
4405
|
+
return root && this.#closeFixture(root);
|
|
4406
|
+
}));
|
|
4407
|
+
}
|
|
4408
|
+
/**
|
|
4409
|
+
* Closes the fixtures still opening and runs `closeStack`, rejecting with the failures of all of them.
|
|
4410
|
+
*
|
|
4411
|
+
* 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.
|
|
4412
|
+
*/
|
|
4413
|
+
async #closeAfterOpenings(closeStack) {
|
|
4414
|
+
const closings = [];
|
|
4415
|
+
for (const closeOpening of this.#openings) closings.push(closeOpening());
|
|
4416
|
+
closings.push(closeStack());
|
|
4417
|
+
let rejection;
|
|
4418
|
+
for (const closing of await Promise.allSettled(closings)) if (closing.status === "rejected") rejection = suppress(closing.reason, rejection, "Closing a test fixture failed");
|
|
4419
|
+
if (rejection) throw rejection.error;
|
|
4420
|
+
}
|
|
4421
|
+
/**
|
|
4422
|
+
* Runs `seed` in a savepoint of a fixture that is released when it resolves, returning its result or rejection.
|
|
4423
|
+
*
|
|
4424
|
+
* The savepoint has its own context, so late code of `seed` cannot reach the fixture after it ends.
|
|
4425
|
+
*/
|
|
4426
|
+
async #seedFixture(fixture, seed) {
|
|
4427
|
+
try {
|
|
4428
|
+
return await runLevel(this.#storage, await startNestedLevel(fixture, false), seed, true);
|
|
4429
|
+
} catch (error) {
|
|
4430
|
+
return { rejection: { error } };
|
|
4431
|
+
}
|
|
4432
|
+
}
|
|
4433
|
+
/** Closes an opened fixture as a change of the fixture stack. */
|
|
4434
|
+
async #closeFixture(fixture) {
|
|
4435
|
+
const index = this.#fixtures.indexOf(fixture);
|
|
4436
|
+
if (index < 0) return;
|
|
4437
|
+
let rejection;
|
|
4438
|
+
try {
|
|
4439
|
+
rejection = await this.#endFixture(fixture);
|
|
4440
|
+
} finally {
|
|
4441
|
+
this.#fixtures.length = index;
|
|
4442
|
+
}
|
|
4443
|
+
if (rejection) throw rejection.error;
|
|
4444
|
+
}
|
|
4445
|
+
/** Rolls back a fixture and releases the connection of the first one, returning the error to reject with. */
|
|
4446
|
+
async #endFixture(fixture) {
|
|
4447
|
+
const cleanup = await endLevel(fixture, false);
|
|
4448
|
+
return fixture.parent ? cleanup.rejection : releaseConnection(fixture.connection, cleanup.failure, cleanup.rejection);
|
|
4449
|
+
}
|
|
4450
|
+
/** Runs a change of the fixture stack after the earlier ones. */
|
|
4451
|
+
#enqueue(transition) {
|
|
4452
|
+
const result = this.#transitions.then(transition);
|
|
4453
|
+
this.#transitions = result.catch(() => {});
|
|
4454
|
+
return result;
|
|
4455
|
+
}
|
|
4456
|
+
/** Starts the first test fixture: a transaction on a reserved connection. */
|
|
4457
|
+
async #beginFixture() {
|
|
4458
|
+
const connection = await this.#driver.acquire();
|
|
4459
|
+
try {
|
|
4460
|
+
await connection.execute(beginStatement);
|
|
4461
|
+
} catch (error) {
|
|
4462
|
+
throw (await releaseConnection(connection, { error }, { error })).error;
|
|
4463
|
+
}
|
|
4464
|
+
return createLevel(connection, void 0, false);
|
|
4465
|
+
}
|
|
4466
|
+
/**
|
|
4467
|
+
* Starts a nested level of a test fixture, preempting its active one.
|
|
4468
|
+
*
|
|
4469
|
+
* A fixture runs one nested level at a time, so a new one ends the previous one, such as a test that timed out.
|
|
4470
|
+
* A level whose `signal` aborts while it preempts rejects with its reason instead of starting, and a failure to start after the abort suppresses the reason.
|
|
4471
|
+
*/
|
|
4472
|
+
async #startInFixture(fixture, signal) {
|
|
4473
|
+
if (fixture.child) {
|
|
4474
|
+
const cleanup = await endLevel(fixture.child, false, "preemption");
|
|
4475
|
+
if (cleanup.rejection) throw suppressAbortReason(new Error("Cannot start a level of the test fixture: ending its active level failed", { cause: cleanup.rejection.error }), signal);
|
|
4476
|
+
}
|
|
4477
|
+
const unavailable = createUnavailableError(fixture, "start a level of the test fixture");
|
|
4478
|
+
if (unavailable) throw suppressAbortReason(unavailable, signal);
|
|
4479
|
+
signal?.throwIfAborted();
|
|
4480
|
+
return startNestedLevel(fixture, false, signal);
|
|
4481
|
+
}
|
|
4482
|
+
};
|
|
4483
|
+
// src/execution/transaction/coordinator.ts
|
|
4484
|
+
/**
|
|
4485
|
+
* Routes statements and scripts to the ambient transaction of the current async context or to the pool.
|
|
4486
|
+
*
|
|
4487
|
+
* This is the only place that decides which connection executes a statement.
|
|
4488
|
+
*/
|
|
4489
|
+
var TransactionCoordinator = class {
|
|
4490
|
+
driver;
|
|
4491
|
+
test;
|
|
4492
|
+
#storage = new AsyncLocalStorage();
|
|
4493
|
+
#fixtures;
|
|
4494
|
+
/** Closing of the database, set by the first `close`; from then on, operations outside a transaction reject. */
|
|
4495
|
+
#closed;
|
|
4496
|
+
constructor(driver, test = false) {
|
|
4497
|
+
this.driver = driver;
|
|
4498
|
+
this.test = test;
|
|
4499
|
+
this.#fixtures = new TestFixtureStack(driver, this.#storage);
|
|
4500
|
+
}
|
|
4501
|
+
execute(statement) {
|
|
4502
|
+
const target = this.#route("execute a query");
|
|
4503
|
+
return target instanceof Error ? Promise.reject(target) : target.execute(statement);
|
|
4504
|
+
}
|
|
4505
|
+
/** Executes a script of statements without parameters where `execute` executes a statement. */
|
|
4506
|
+
executeScript(text) {
|
|
4507
|
+
const target = this.#route("execute a script");
|
|
4508
|
+
return target instanceof Error ? Promise.reject(target) : target.executeScript(text);
|
|
4509
|
+
}
|
|
4510
|
+
/** Returns the connection of the ambient transaction or the driver of the pool that runs `operation`, or the error that rejects it. */
|
|
4511
|
+
#route(operation) {
|
|
4512
|
+
const level = this.#storage.getStore();
|
|
4513
|
+
if (!level) {
|
|
4514
|
+
if (this.#closed) return createDatabaseClosedError(operation);
|
|
4515
|
+
return this.test ? new Error(describeOutsideTest(operation)) : this.driver;
|
|
4516
|
+
}
|
|
4517
|
+
return createUnavailableError(level, operation) ?? level.connection;
|
|
4518
|
+
}
|
|
4519
|
+
/**
|
|
4520
|
+
* Runs `callback` in a transaction that commits when it resolves and rolls back when it rejects, with the settings of `options`.
|
|
4521
|
+
*
|
|
4522
|
+
* Inside a transaction, it runs `callback` in a savepoint nested in it, which restores the settings it changed when it ends.
|
|
4523
|
+
* A failed cleanup after an error rejects with a `SuppressedError` that keeps the original error in its `suppressed` chain.
|
|
4524
|
+
*/
|
|
4525
|
+
transaction(callback, options) {
|
|
4526
|
+
const settings = getLevelSettings(options);
|
|
4527
|
+
const parent = this.#storage.getStore();
|
|
4528
|
+
if (parent) return this.#runNested(parent, callback, true, void 0, settings);
|
|
4529
|
+
if (this.#closed) return Promise.reject(createDatabaseClosedError("start a transaction"));
|
|
4530
|
+
return this.test ? Promise.reject(new Error(describeOutsideTest("start a transaction"))) : this.#runRoot(callback, true, void 0, settings);
|
|
4531
|
+
}
|
|
4532
|
+
/**
|
|
4533
|
+
* Runs `callback` in the current transaction, or in a new transaction outside of one.
|
|
4534
|
+
*
|
|
4535
|
+
* Joining starts no savepoint, so a rejection of `callback` does not undo its changes.
|
|
4536
|
+
* It rejects without calling `callback` when the current level accepts no statements, as a nested transaction would.
|
|
4537
|
+
*/
|
|
4538
|
+
async ensureTransaction(callback) {
|
|
4539
|
+
const level = this.#storage.getStore();
|
|
4540
|
+
if (!level?.inTransaction) return this.transaction(callback);
|
|
4541
|
+
const unavailable = createUnavailableError(level, "join the transaction");
|
|
4542
|
+
if (unavailable) throw unavailable;
|
|
4543
|
+
return callback();
|
|
4544
|
+
}
|
|
4545
|
+
/**
|
|
4546
|
+
* Tells whether the current async context runs in a transaction of `transaction`.
|
|
4547
|
+
*
|
|
4548
|
+
* A test transaction and the seed of a test fixture are not transactions, unless they run inside one, so that code under test behaves as in production.
|
|
4549
|
+
*/
|
|
4550
|
+
isInTransaction() {
|
|
4551
|
+
return this.#storage.getStore()?.inTransaction ?? false;
|
|
4552
|
+
}
|
|
4553
|
+
/**
|
|
4554
|
+
* Runs `callback` in a transaction that always rolls back, on a coordinator created for tests.
|
|
4555
|
+
*
|
|
4556
|
+
* Inside a transaction, it runs `callback` in a savepoint nested in it that always rolls back.
|
|
4557
|
+
* When `signal` aborts, the level stops accepting statements at once and ends without waiting for `callback`.
|
|
4558
|
+
* Once the level ends, the transaction rejects with the reason of the signal.
|
|
4559
|
+
* A failure to start or end the level after the abort suppresses the reason in a `SuppressedError`.
|
|
4560
|
+
* Aborted while it waits for its turn in the fixture stack or for a connection, it rejects at once; after the abort, it never calls `callback`.
|
|
4561
|
+
*/
|
|
4562
|
+
testTransaction(callback, { signal } = {}) {
|
|
4563
|
+
if (!this.test) return Promise.reject(/* @__PURE__ */ new Error("testTransaction requires a database created with test: true"));
|
|
4564
|
+
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
4565
|
+
const parent = this.#storage.getStore();
|
|
4566
|
+
if (parent) return this.#runNested(parent, callback, false, signal);
|
|
4567
|
+
if (this.#closed) return Promise.reject(createDatabaseClosedError("start a test transaction"));
|
|
4568
|
+
return this.#fixtures.startTestLevel(signal).then((level) => level ? this.#runStarted(level, callback, false, signal) : this.#runRoot(callback, false, signal));
|
|
4569
|
+
}
|
|
4570
|
+
/**
|
|
4571
|
+
* Opens a test fixture: a transaction on a reserved connection, or a savepoint in the innermost open fixture, and runs `seed` in it.
|
|
4572
|
+
*
|
|
4573
|
+
* Test transactions started outside any transaction run in the innermost fixture.
|
|
4574
|
+
* A fixture whose `seed` rejects rolls back and closes.
|
|
4575
|
+
*/
|
|
4576
|
+
createTestFixture(seed) {
|
|
4577
|
+
return this.startTestFixture(seed).fixture;
|
|
4578
|
+
}
|
|
4579
|
+
/**
|
|
4580
|
+
* Starts opening a test fixture, see `createTestFixture`, and returns it with a `close` that can be called before it opens.
|
|
4581
|
+
*
|
|
4582
|
+
* Closing before the fixture opens rejects the opening without waiting for `seed` and rolls the fixture back, so a fixture or test transaction started after `close` never nests in it, even when its `seed` never settles.
|
|
4583
|
+
* Closing an open fixture also closes the fixtures opening in it.
|
|
4584
|
+
*/
|
|
4585
|
+
startTestFixture(seed) {
|
|
4586
|
+
return this.#fixtures.start(seed, this.#getFixtureRefusal());
|
|
4587
|
+
}
|
|
4588
|
+
/** Returns the error that rejects a test fixture created now, or `undefined` when it can open. */
|
|
4589
|
+
#getFixtureRefusal() {
|
|
4590
|
+
if (!this.test) return /* @__PURE__ */ new Error("createTestFixture requires a database created with test: true");
|
|
4591
|
+
if (this.#storage.getStore()) return /* @__PURE__ */ new Error("Cannot create a test fixture inside a transaction");
|
|
4592
|
+
if (this.#closed) return createDatabaseClosedError("create a test fixture");
|
|
4593
|
+
}
|
|
4594
|
+
/**
|
|
4595
|
+
* Closes the test fixtures, including those still opening, and then the driver, which waits for the running transactions to end.
|
|
4596
|
+
*
|
|
4597
|
+
* A driver waits for every reserved connection, so closing it under an open fixture would wait forever.
|
|
4598
|
+
* A failed closing of the driver suppresses the failures of closing the fixtures.
|
|
4599
|
+
* From the first call, statements, transactions, and fixtures started outside a transaction reject, while the levels already running can still end; a repeated call returns the same closing.
|
|
4600
|
+
*/
|
|
4601
|
+
close() {
|
|
4602
|
+
if (this.#storage.getStore()) return Promise.reject(/* @__PURE__ */ new Error("Cannot close the database inside a transaction"));
|
|
4603
|
+
this.#closed ??= this.#close();
|
|
4604
|
+
return this.#closed;
|
|
4605
|
+
}
|
|
4606
|
+
/** Closes the test fixtures and then the driver, see `close`. */
|
|
4607
|
+
async #close() {
|
|
4608
|
+
let rejection;
|
|
4609
|
+
try {
|
|
4610
|
+
await this.#fixtures.close();
|
|
4611
|
+
} catch (error) {
|
|
4612
|
+
rejection = { error };
|
|
4613
|
+
}
|
|
4614
|
+
try {
|
|
4615
|
+
await this.driver.close();
|
|
4616
|
+
} catch (error) {
|
|
4617
|
+
rejection = suppress(error, rejection, "Closing the driver failed");
|
|
4618
|
+
}
|
|
4619
|
+
if (rejection) throw rejection.error;
|
|
4620
|
+
}
|
|
4621
|
+
async #runRoot(callback, commits, signal, settings) {
|
|
4622
|
+
const connection = await (signal ? acquireUnlessAborted(this.driver, signal) : this.driver.acquire());
|
|
4623
|
+
if (signal?.aborted) throw (await releaseConnection(connection, void 0, { error: signal.reason })).error;
|
|
4624
|
+
const level = createLevel(connection, void 0, commits);
|
|
4625
|
+
let outcome;
|
|
4626
|
+
try {
|
|
4627
|
+
await connection.execute(beginStatement);
|
|
4628
|
+
} catch (error) {
|
|
4629
|
+
level.state = "closed";
|
|
4630
|
+
outcome = {
|
|
4631
|
+
rejection: { error: suppressAbortReason(error, signal) },
|
|
4632
|
+
failure: { error }
|
|
4633
|
+
};
|
|
4634
|
+
}
|
|
4635
|
+
if (!outcome && settings) try {
|
|
4636
|
+
await applySettings(level, settings);
|
|
4637
|
+
} catch (error) {
|
|
4638
|
+
outcome = await getEndedOutcome(endLevel(level, false), error);
|
|
4639
|
+
}
|
|
4640
|
+
outcome ??= await runLevel(this.#storage, level, callback, commits, signal);
|
|
4641
|
+
const rejection = await releaseConnection(connection, outcome.failure, outcome.rejection);
|
|
4642
|
+
if (rejection) throw rejection.error;
|
|
4643
|
+
return outcome.result;
|
|
4644
|
+
}
|
|
4645
|
+
async #runNested(parent, callback, commits, signal, settings) {
|
|
4646
|
+
const unavailable = createUnavailableError(parent, "start a nested transaction");
|
|
4647
|
+
if (unavailable) throw unavailable;
|
|
4648
|
+
return this.#runStarted(await startNestedLevel(parent, commits, signal, settings), callback, commits, signal);
|
|
4649
|
+
}
|
|
4650
|
+
/** Runs `callback` in a started level, returning its result or throwing its rejection. */
|
|
4651
|
+
async #runStarted(level, callback, commits, signal) {
|
|
4652
|
+
const { result, rejection } = await runLevel(this.#storage, level, callback, commits, signal);
|
|
4653
|
+
if (rejection) throw rejection.error;
|
|
4654
|
+
return result;
|
|
4655
|
+
}
|
|
4656
|
+
};
|
|
4657
|
+
/** Error message of an operation outside a test transaction on a coordinator created for tests. */
|
|
4658
|
+
function describeOutsideTest(operation) {
|
|
4659
|
+
return `Cannot ${operation} outside a test transaction: the database was created with test: true, so wrap the test in testTransaction`;
|
|
4660
|
+
}
|
|
4661
|
+
/** Error of `operation` started outside a transaction after closing the database was requested. */
|
|
4662
|
+
function createDatabaseClosedError(operation) {
|
|
4663
|
+
return /* @__PURE__ */ new Error(`Cannot ${operation}: the database is closed`);
|
|
4664
|
+
}
|
|
4665
|
+
// src/execution/database.ts
|
|
4666
|
+
/** Creates a database over a driver; its transactions are shared by every schema bound to it. */
|
|
4667
|
+
function createDatabase({ driver, test }) {
|
|
4668
|
+
const coordinator = new TransactionCoordinator(driver, test);
|
|
4669
|
+
let tablelessDb;
|
|
4670
|
+
const getTablelessDb = () => tablelessDb ??= bindSchema(defineSchema(), database);
|
|
4671
|
+
const database = {
|
|
4672
|
+
coordinator,
|
|
4673
|
+
bind: (schema, options) => bindSchema(schema, database, options),
|
|
4674
|
+
query: (strings, ...values) => getTablelessDb().$query(strings, ...values),
|
|
4675
|
+
script: (script, ...values) => typeof script === "string" ? coordinator.executeScript(script) : getTablelessDb().$script(script, ...values),
|
|
4676
|
+
execute: (statement) => coordinator.execute(statement),
|
|
4677
|
+
transaction: (callback, options) => coordinator.transaction(callback, options),
|
|
4678
|
+
ensureTransaction: (callback) => coordinator.ensureTransaction(callback),
|
|
4679
|
+
isInTransaction: () => coordinator.isInTransaction(),
|
|
4680
|
+
async lock(key) {
|
|
4681
|
+
if (!coordinator.isInTransaction()) throw new Error("Cannot take an advisory lock outside a transaction, where it would end with its statement; a test transaction alone does not count");
|
|
4682
|
+
await coordinator.execute(createLockStatement(key));
|
|
4683
|
+
},
|
|
4684
|
+
close: () => coordinator.close(),
|
|
4685
|
+
[Symbol.asyncDispose]: () => coordinator.close()
|
|
4686
|
+
};
|
|
4687
|
+
return database;
|
|
4688
|
+
}
|
|
4689
|
+
/** Creates the statement that takes a transaction-level advisory lock on a 64-bit hash of `key`. */
|
|
4690
|
+
function createLockStatement(key) {
|
|
4691
|
+
return createStatement("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [key]);
|
|
4692
|
+
}
|
|
4693
|
+
export { not as A, countType as C, literal as D, toAggregateType as E, combineNodes as M, and as O, countProjection as S, createCountCall as T, createTableFactory as _, defineSchema as a, RequiredRelationError as b, requireDerived as c, desc as d, orderBy as f, createStatement as g, one as h, sql as i, or as j, isColumnValues as k, addTerms as l, many as m, identifier as n, SelectQuery as o, matchColumn as p, param as r, from as s, createDatabase as t, asc as u, defineTable as v, createAggregateCall as w, ResultDecodeError as x, NotFoundError as y };
|