symmetria 1.0.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/LICENSE +21 -0
- package/README.md +350 -0
- package/dist/assembly-B-tpaqlp.js +2233 -0
- package/dist/assembly-B-tpaqlp.js.map +1 -0
- package/dist/binding-CD-0xNaB.js +12 -0
- package/dist/binding-CD-0xNaB.js.map +1 -0
- package/dist/bun.d.ts +12 -0
- package/dist/bun.js +64 -0
- package/dist/bun.js.map +1 -0
- package/dist/compile-aiRi8O7q.js +1177 -0
- package/dist/compile-aiRi8O7q.js.map +1 -0
- package/dist/driver.d.ts +4 -0
- package/dist/driver.js +3 -0
- package/dist/index-DNCu4XEk.d.ts +10 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2636 -0
- package/dist/index.js.map +1 -0
- package/dist/inspection-CXnLd3MA.js +65 -0
- package/dist/inspection-CXnLd3MA.js.map +1 -0
- package/dist/internal.d.ts +10 -0
- package/dist/internal.js +4 -0
- package/dist/pg-B7PQlBHz.d.ts +12 -0
- package/dist/pg-BzycsnK9.js +84 -0
- package/dist/pg-BzycsnK9.js.map +1 -0
- package/dist/pg.d.ts +4 -0
- package/dist/pg.js +3 -0
- package/dist/pool-OKiwLiBZ.js +240 -0
- package/dist/pool-OKiwLiBZ.js.map +1 -0
- package/dist/pool-UBdmZPmu.d.ts +14 -0
- package/dist/profiling-CRd3epfk.d.ts +56 -0
- package/dist/types-BNSyrEFw.d.ts +1829 -0
- package/dist/types-BavtzvoV.js +35 -0
- package/dist/types-BavtzvoV.js.map +1 -0
- package/dist/values-BhrNtVaY.js +11 -0
- package/dist/values-BhrNtVaY.js.map +1 -0
- package/dist/vector.d.ts +16 -0
- package/dist/vector.js +34 -0
- package/dist/vector.js.map +1 -0
- package/package.json +79 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2636 @@
|
|
|
1
|
+
import { $ as count, A as readOrdering, At as date, Bt as smallint, C as createScope, D as limitedPlan, Dt as builderExample, E as initialPlan, Et as bool, F as validatePredicate, Ft as isColumn, Ht as time, It as jsonb, J as COLUMN_EXPRESSION, Kt as uuid, Lt as numeric, M as resultRows, Mt as inet, N as shapeFrame, Nt as int, O as lockPlan, Ot as bytea, P as validateNode, Pt as interval, Q as coalesce, Qt as codecMap, Rt as oneOf, S as countValue, St as expressionSqlType, T as evaluateContext, Tt as bigint, Ut as timestamptz, Vt as text, Wt as tsvector, X as and, Xt as cloneParameter, Y as NAMED_PARAMETER, Yt as booleanCodec, Z as average, Zt as codecFor, _ as table, _t as sql, a as applyIndexes, at as maximum, b as QUERY_STATE, bt as when, c as index, ct as notExists, d as TABLE, dt as predicate, en as encodeValue, et as createExpression, f as draftBinding, ft as rank, g as self, gt as searchDocument, h as junction, ht as rowNumber, it as lead, j as readSelection, jt as doublePrecision, k as presentSelection, kt as customType, lt as or, m as isTable, mt as readPredicate, n as snakeCase, nt as exists, o as createIndexQuery, ot as minimum, p as isReferenceInput, pt as readColumn, q as computedFields, qt as varchar, r as applyChecks, rt as lag, s as createIndexesSQL, st as not, t as assembleSchema, tt as denseRank, u as operatorClass, ut as over, v as tableState, vt as sum, w as emptyBindings, wt as COLUMN_CODEC, x as bindingScope, xt as jsonRowCodec, y as EMPTY, yt as valueNode, z as quoteIdentifier, zt as real } from "./assembly-B-tpaqlp.js";
|
|
2
|
+
import { a as containsBinding, c as numberedAlias, i as TABLE_SOURCE, n as IsolationLevel, o as mergeBindings, r as QUERY_PLAN, s as normalizeResult, t as DEFAULT_VALUE } from "./types-BavtzvoV.js";
|
|
3
|
+
import { a as rowDecoder, c as postgresRenderer, i as executePlan, n as compileQuery, o as createProfiler, r as executeCompiled, s as executorProfiling, t as compilePlan } from "./compile-aiRi8O7q.js";
|
|
4
|
+
import { n as createDatabase, t as SCHEMA_BIND } from "./binding-CD-0xNaB.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
//#region src/driver/errors.ts
|
|
7
|
+
/**
|
|
8
|
+
* PostgreSQL error inspection shared by the adapters: SQLSTATE lookup and the
|
|
9
|
+
* conflict classes a transaction may retry.
|
|
10
|
+
*/
|
|
11
|
+
/** The five-character SQLSTATE of a server error (`code` on pg, `errno` on Bun). */
|
|
12
|
+
const sqlState = (error) => {
|
|
13
|
+
if (!error || typeof error !== "object") return;
|
|
14
|
+
const value = error;
|
|
15
|
+
return [value.code, value.errno].find((code) => typeof code === "string" && /^[0-9A-Z]{5}$/.test(code));
|
|
16
|
+
};
|
|
17
|
+
/** serialization_failure and deadlock_detected: the transaction can be re-run from the start. */
|
|
18
|
+
const isRetryableTransactionError = (error) => {
|
|
19
|
+
const state = sqlState(error);
|
|
20
|
+
return state === "40001" || state === "40P01";
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/query/select/projections.ts
|
|
24
|
+
/**
|
|
25
|
+
* Reusable RETURNING projections shared between read queries and writes.
|
|
26
|
+
*/
|
|
27
|
+
const SHAPE_SOURCE = Symbol("symmetria.query.shape");
|
|
28
|
+
const shapeExpressions = Object.freeze({
|
|
29
|
+
and,
|
|
30
|
+
or,
|
|
31
|
+
not,
|
|
32
|
+
when,
|
|
33
|
+
exists,
|
|
34
|
+
notExists,
|
|
35
|
+
count,
|
|
36
|
+
sum,
|
|
37
|
+
average,
|
|
38
|
+
minimum,
|
|
39
|
+
maximum,
|
|
40
|
+
coalesce,
|
|
41
|
+
sql,
|
|
42
|
+
rowNumber,
|
|
43
|
+
rank,
|
|
44
|
+
denseRank,
|
|
45
|
+
lag,
|
|
46
|
+
lead,
|
|
47
|
+
over
|
|
48
|
+
});
|
|
49
|
+
/** The scalar tools a RETURNING callback receives: aggregates, windows and subqueries cannot appear there. */
|
|
50
|
+
const returningTools = Object.freeze({
|
|
51
|
+
and,
|
|
52
|
+
or,
|
|
53
|
+
not,
|
|
54
|
+
when,
|
|
55
|
+
coalesce,
|
|
56
|
+
sql
|
|
57
|
+
});
|
|
58
|
+
/** Reusable write projections share scalar SQL tools, table identity and codecs. */
|
|
59
|
+
const returningProjection = (selector, row, table) => {
|
|
60
|
+
if (!(SHAPE_SOURCE in selector)) return selector(row, returningTools);
|
|
61
|
+
if (selector[SHAPE_SOURCE] !== table) throw new Error("symmetria: reusable shape belongs to another table");
|
|
62
|
+
const unsupported = () => {
|
|
63
|
+
throw new Error("symmetria: RETURNING shapes require row-local expressions without relations, aggregates, windows or query options");
|
|
64
|
+
};
|
|
65
|
+
const result = selector(new Proxy(row, { get: (target, name) => {
|
|
66
|
+
if (!Object.hasOwn(target, name) && table.relations.some((relation) => relation.name === name)) return unsupported();
|
|
67
|
+
return Reflect.get(target, name);
|
|
68
|
+
} }), {
|
|
69
|
+
...shapeExpressions,
|
|
70
|
+
join: unsupported,
|
|
71
|
+
innerJoin: unsupported,
|
|
72
|
+
leftJoin: unsupported,
|
|
73
|
+
crossJoin: unsupported,
|
|
74
|
+
whereNotNull: unsupported
|
|
75
|
+
});
|
|
76
|
+
if (!result || typeof result !== "object" || Array.isArray(result) || "then" in result && typeof result.then === "function" || !Object.keys(result).length) throw new Error("symmetria: shape() requires a synchronous object projection");
|
|
77
|
+
const validateNode = (value) => {
|
|
78
|
+
if (!value || typeof value !== "object") return;
|
|
79
|
+
if ("kind" in value) {
|
|
80
|
+
if ([
|
|
81
|
+
"column",
|
|
82
|
+
"parameter",
|
|
83
|
+
"placeholder"
|
|
84
|
+
].includes(String(value.kind))) return;
|
|
85
|
+
if ([
|
|
86
|
+
"aggregate",
|
|
87
|
+
"window",
|
|
88
|
+
"relativeWindow",
|
|
89
|
+
"subquery",
|
|
90
|
+
"rowCount",
|
|
91
|
+
"jsonRows",
|
|
92
|
+
"exists"
|
|
93
|
+
].includes(String(value.kind))) unsupported();
|
|
94
|
+
}
|
|
95
|
+
for (const [key, child] of Object.entries(value)) if (key !== "codec") validateNode(child);
|
|
96
|
+
};
|
|
97
|
+
const validateFields = (value) => {
|
|
98
|
+
if (!value || typeof value !== "object") return;
|
|
99
|
+
if (COLUMN_EXPRESSION in value) {
|
|
100
|
+
validateNode(readColumn(value).node);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
for (const [key, child] of Object.entries(value)) {
|
|
104
|
+
if (key.startsWith("$")) unsupported();
|
|
105
|
+
validateFields(child);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
validateFields(result);
|
|
109
|
+
return result;
|
|
110
|
+
};
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region src/query/plan/derived.ts
|
|
113
|
+
/**
|
|
114
|
+
* Builds the table binding for a derived source (subquery or CTE) from its plan.
|
|
115
|
+
*/
|
|
116
|
+
const derivedBinding = (plan, alias) => Object.freeze({
|
|
117
|
+
table: {
|
|
118
|
+
name: alias,
|
|
119
|
+
sqlName: alias,
|
|
120
|
+
junction: false,
|
|
121
|
+
relations: [],
|
|
122
|
+
columns: plan.selection.map((expression) => ({
|
|
123
|
+
name: expression.outputName,
|
|
124
|
+
sqlName: expression.outputName,
|
|
125
|
+
sqlType: expressionSqlType(expression),
|
|
126
|
+
notNull: false,
|
|
127
|
+
unique: false,
|
|
128
|
+
primaryKey: false
|
|
129
|
+
}))
|
|
130
|
+
},
|
|
131
|
+
alias,
|
|
132
|
+
derived: plan,
|
|
133
|
+
projection: Object.freeze(Object.fromEntries(plan.selection.map((expression) => [expression.outputName, expression]))),
|
|
134
|
+
codecs: Object.freeze(codecMap(Object.fromEntries(plan.selection.flatMap((expression) => expression.codec ? [[expression.outputName, expression.codec]] : []))))
|
|
135
|
+
});
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region src/query/select/terminal.ts
|
|
138
|
+
/**
|
|
139
|
+
* Terminal plans shared by query handles and prepared queries: `count()` and
|
|
140
|
+
* `exists()` over any SELECT plan, selected or not. Derived plans are cached per
|
|
141
|
+
* source plan so compiled SQL and row decoders stay cached too.
|
|
142
|
+
*/
|
|
143
|
+
const countPlans = /* @__PURE__ */ new WeakMap();
|
|
144
|
+
const existsPlans = /* @__PURE__ */ new WeakMap();
|
|
145
|
+
const withoutLocking = (plan) => {
|
|
146
|
+
const { locking: _locking, ...rest } = plan;
|
|
147
|
+
return rest;
|
|
148
|
+
};
|
|
149
|
+
/** The selection a wrapped plan keeps so its row count matches the user's query. */
|
|
150
|
+
const innerSelection = (plan) => {
|
|
151
|
+
if (!plan.distinct) return presentSelection;
|
|
152
|
+
if (plan.selection.length) return plan.selection;
|
|
153
|
+
return plan.grouping.length ? plan.grouping : readSelection(createScope({ [plan.root.alias]: plan.root })[plan.root.alias], plan.bindings);
|
|
154
|
+
};
|
|
155
|
+
/** A plan whose single row carries `count`, decoded as a number. */
|
|
156
|
+
const countPlan = (plan) => {
|
|
157
|
+
let derived = countPlans.get(plan);
|
|
158
|
+
if (derived) return derived;
|
|
159
|
+
derived = plan.limit !== void 0 || plan.offset !== void 0 || plan.grouping.length > 0 || plan.having.length > 0 || plan.distinct ? Object.freeze({
|
|
160
|
+
...initialPlan(derivedBinding(Object.freeze({
|
|
161
|
+
...plan,
|
|
162
|
+
selection: innerSelection(plan)
|
|
163
|
+
}), "__symmetria_count")),
|
|
164
|
+
selection: Object.freeze([readColumn(count())])
|
|
165
|
+
}) : Object.freeze({
|
|
166
|
+
...withoutLocking(plan),
|
|
167
|
+
selection: Object.freeze([readColumn(count())]),
|
|
168
|
+
ordering: EMPTY
|
|
169
|
+
});
|
|
170
|
+
countPlans.set(plan, derived);
|
|
171
|
+
return derived;
|
|
172
|
+
};
|
|
173
|
+
/**
|
|
174
|
+
* A plan returning at most one `present` row. A parameterized LIMIT is refused
|
|
175
|
+
* unless `allowPlaceholderLimit` (prepared queries), which wraps the plan instead.
|
|
176
|
+
*/
|
|
177
|
+
const existsPlan = (plan, allowPlaceholderLimit) => {
|
|
178
|
+
const parameterized = typeof plan.limit === "object" || typeof plan.offset === "object";
|
|
179
|
+
if (parameterized && !allowPlaceholderLimit) throw new Error("symmetria: bind a parameterized LIMIT with prepare()");
|
|
180
|
+
let variants = existsPlans.get(plan);
|
|
181
|
+
if (!variants) {
|
|
182
|
+
variants = [];
|
|
183
|
+
existsPlans.set(plan, variants);
|
|
184
|
+
}
|
|
185
|
+
return variants[allowPlaceholderLimit ? 1 : 0] ??= Object.freeze(parameterized ? {
|
|
186
|
+
...initialPlan(derivedBinding(Object.freeze({
|
|
187
|
+
...withoutLocking(plan),
|
|
188
|
+
selection: innerSelection(plan)
|
|
189
|
+
}), "__symmetria_exists")),
|
|
190
|
+
selection: presentSelection,
|
|
191
|
+
limit: 1
|
|
192
|
+
} : {
|
|
193
|
+
...withoutLocking(plan),
|
|
194
|
+
selection: innerSelection(plan),
|
|
195
|
+
ordering: EMPTY,
|
|
196
|
+
limit: typeof plan.limit === "number" ? Math.min(plan.limit, 1) : 1
|
|
197
|
+
});
|
|
198
|
+
};
|
|
199
|
+
const readCount = (rows) => rows[0].count;
|
|
200
|
+
const readExists = (rows) => rows.length > 0;
|
|
201
|
+
//#endregion
|
|
202
|
+
//#region src/query/select/prepared.ts
|
|
203
|
+
/**
|
|
204
|
+
* `prepare()`: named-parameter queries compiled once and executed with typed values.
|
|
205
|
+
*/
|
|
206
|
+
const PREPARE_QUERY = Symbol("symmetria.query.prepare");
|
|
207
|
+
/** Construct a query once; only encoded parameter values change between executions. */
|
|
208
|
+
const prepare = (definitions, factory) => {
|
|
209
|
+
const scope = {};
|
|
210
|
+
const parameters = Object.fromEntries(Object.entries(definitions).map(([name, column]) => {
|
|
211
|
+
if (!name || !isColumn(column)) throw new Error("symmetria: prepared parameters require named column types");
|
|
212
|
+
const codec = column[COLUMN_CODEC] ?? codecFor(column.definition.sqlType);
|
|
213
|
+
const expression = createExpression({
|
|
214
|
+
outputName: name,
|
|
215
|
+
node: Object.freeze({
|
|
216
|
+
kind: "placeholder",
|
|
217
|
+
name,
|
|
218
|
+
scope,
|
|
219
|
+
nullable: !column.definition.notNull,
|
|
220
|
+
sqlType: column.definition.sqlType,
|
|
221
|
+
...codec ? { codec } : {}
|
|
222
|
+
}),
|
|
223
|
+
...codec ? { codec } : {}
|
|
224
|
+
});
|
|
225
|
+
return [name, Object.freeze(Object.defineProperty(Object.create(expression), NAMED_PARAMETER, { value: true }))];
|
|
226
|
+
}));
|
|
227
|
+
const query = factory(Object.freeze(parameters));
|
|
228
|
+
if (!query || !(PREPARE_QUERY in query)) throw new Error("symmetria: prepare() expects a query or mutation");
|
|
229
|
+
return query[PREPARE_QUERY](scope, Object.keys(definitions));
|
|
230
|
+
};
|
|
231
|
+
const preparePlan = (plan, executor, scope, names = [], run) => {
|
|
232
|
+
const slots = /* @__PURE__ */ new Set();
|
|
233
|
+
const placeholder = (node) => {
|
|
234
|
+
if (node.scope !== scope) throw new Error(`symmetria: parameter "${node.name}" belongs to another prepare() callback`);
|
|
235
|
+
slots.add(node);
|
|
236
|
+
return node;
|
|
237
|
+
};
|
|
238
|
+
const templates = /* @__PURE__ */ new WeakMap();
|
|
239
|
+
const template = (state) => {
|
|
240
|
+
let compiled = templates.get(state);
|
|
241
|
+
if (!compiled) {
|
|
242
|
+
compiled = compileQuery(state, placeholder);
|
|
243
|
+
templates.set(state, compiled);
|
|
244
|
+
}
|
|
245
|
+
return compiled;
|
|
246
|
+
};
|
|
247
|
+
const primary = plan.kind !== "insert" || plan.values.length ? template(plan) : void 0;
|
|
248
|
+
const validate = (values) => {
|
|
249
|
+
if (!values || typeof values !== "object" || Array.isArray(values) || Object.keys(values).length !== names.length || names.some((name) => !Object.hasOwn(values, name))) throw new Error("symmetria: prepared query requires exactly its declared parameters");
|
|
250
|
+
for (const name of names) if (values[name] === void 0) throw new Error(`symmetria: parameter "${name}" cannot be undefined`);
|
|
251
|
+
};
|
|
252
|
+
const bind = (state, values) => {
|
|
253
|
+
const compiled = state === plan && primary ? primary : template(state);
|
|
254
|
+
return {
|
|
255
|
+
sql: compiled.sql,
|
|
256
|
+
parameters: compiled.parameters.map((value) => {
|
|
257
|
+
if (!slots.has(value)) return cloneParameter(value);
|
|
258
|
+
const node = value;
|
|
259
|
+
const bound = values[node.name];
|
|
260
|
+
if (bound === null && !node.nullable) throw new Error(`symmetria: parameter "${node.name}" cannot be null`);
|
|
261
|
+
if (node.count && (typeof bound !== "number" || !Number.isSafeInteger(bound) || bound < 0)) throw new Error(`symmetria: parameter "${node.name}" must be a nonnegative safe integer`);
|
|
262
|
+
return cloneParameter(encodeValue(bound, node.codec));
|
|
263
|
+
})
|
|
264
|
+
};
|
|
265
|
+
};
|
|
266
|
+
const execute = async (values = {}) => {
|
|
267
|
+
validate(values);
|
|
268
|
+
if (run) return run((state) => bind(state, values));
|
|
269
|
+
const result = await executeCompiled(plan, bind(plan, values), executor);
|
|
270
|
+
if (plan.kind === "select") return result.rows;
|
|
271
|
+
if (!plan.selection.length) return { affectedRows: result.affectedRows };
|
|
272
|
+
return plan.single ? result.rows[0] ?? null : result.rows;
|
|
273
|
+
};
|
|
274
|
+
const toSQL = (values = {}) => {
|
|
275
|
+
validate(values);
|
|
276
|
+
return bind(plan, values);
|
|
277
|
+
};
|
|
278
|
+
if (plan.kind !== "select" || run) return Object.freeze(Object.assign(execute, {
|
|
279
|
+
execute,
|
|
280
|
+
toSQL
|
|
281
|
+
}));
|
|
282
|
+
const rowsOf = async (state, values) => {
|
|
283
|
+
validate(values);
|
|
284
|
+
return (await executeCompiled(state, bind(state, values), executor)).rows;
|
|
285
|
+
};
|
|
286
|
+
const limited = (limit) => {
|
|
287
|
+
if (typeof plan.limit === "object") throw new Error("symmetria: bind a parameterized LIMIT with prepare()");
|
|
288
|
+
return limitedPlan(plan, limit);
|
|
289
|
+
};
|
|
290
|
+
const single = async (values, required) => {
|
|
291
|
+
const rows = await rowsOf(limited(2), values);
|
|
292
|
+
if (rows.length > 1 || required && !rows.length) throw new Error(`symmetria: expected ${required ? "exactly one" : "at most one"} row, received ${rows.length}`);
|
|
293
|
+
return rows[0] ?? null;
|
|
294
|
+
};
|
|
295
|
+
return Object.freeze(Object.assign(execute, {
|
|
296
|
+
execute,
|
|
297
|
+
toSQL,
|
|
298
|
+
one: (values = {}) => single(values, true),
|
|
299
|
+
maybeOne: (values = {}) => single(values, false),
|
|
300
|
+
first: async (values = {}) => (await rowsOf(limited(1), values))[0] ?? null,
|
|
301
|
+
count: async (values = {}) => readCount(await rowsOf(countPlan(plan), values)),
|
|
302
|
+
exists: async (values = {}) => readExists(await rowsOf(existsPlan(plan, true), values)),
|
|
303
|
+
inspect: async (...argumentsList) => {
|
|
304
|
+
const [values, options] = names.length ? [argumentsList[0], argumentsList[1]] : [{}, argumentsList[0]];
|
|
305
|
+
validate(values ?? {});
|
|
306
|
+
return (await import("./inspection-CXnLd3MA.js")).inspectQuery(plan, executor, options, bind(plan, values ?? {}));
|
|
307
|
+
}
|
|
308
|
+
}));
|
|
309
|
+
};
|
|
310
|
+
//#endregion
|
|
311
|
+
//#region src/query/write/mutations.ts
|
|
312
|
+
/** PostgreSQL's wire-protocol bind-parameter limit; larger multi-row INSERTs are split into atomic chunks. */
|
|
313
|
+
const PARAMETER_LIMIT = 65535;
|
|
314
|
+
const createMutation = (kind, root, input, executor, options = {}) => {
|
|
315
|
+
const profile = executorProfiling(executor);
|
|
316
|
+
const bindings = Object.freeze({ [root.alias]: root });
|
|
317
|
+
const scope = createScope(bindings);
|
|
318
|
+
const columnNode = (column) => Object.freeze({
|
|
319
|
+
kind: "column",
|
|
320
|
+
description: Object.freeze({
|
|
321
|
+
binding: root,
|
|
322
|
+
column
|
|
323
|
+
})
|
|
324
|
+
});
|
|
325
|
+
/**
|
|
326
|
+
* Predicates may follow relation paths; the resulting JOINs cannot live in an
|
|
327
|
+
* UPDATE or DELETE, so they move into a primary-key subquery.
|
|
328
|
+
*/
|
|
329
|
+
const wherePredicate = (callback) => {
|
|
330
|
+
const evaluate = (row) => {
|
|
331
|
+
const result = callback(row);
|
|
332
|
+
return Array.isArray(result) ? and(...result) : result;
|
|
333
|
+
};
|
|
334
|
+
if (!options.context) return readPredicate(evaluate(scope[root.alias]));
|
|
335
|
+
const context = options.context(initialPlan(root));
|
|
336
|
+
const description = readPredicate(evaluate(context.scope()[root.alias]));
|
|
337
|
+
if (!context.plan.joins.length) return description;
|
|
338
|
+
const keys = root.table.columns.filter((column) => column.primaryKey);
|
|
339
|
+
if (!keys.length) throw new Error(`symmetria: relation paths in ${kind}().where() require a primary key on "${root.alias}"`);
|
|
340
|
+
const subquery = Object.freeze({
|
|
341
|
+
...context.plan,
|
|
342
|
+
selection: Object.freeze(keys.map((column) => Object.freeze({
|
|
343
|
+
outputName: column.name,
|
|
344
|
+
node: columnNode(column)
|
|
345
|
+
}))),
|
|
346
|
+
predicates: Object.freeze([...context.plan.predicates, description])
|
|
347
|
+
});
|
|
348
|
+
const value = keys.length === 1 ? columnNode(keys[0]) : Object.freeze({
|
|
349
|
+
kind: "tuple",
|
|
350
|
+
values: Object.freeze(keys.map(columnNode))
|
|
351
|
+
});
|
|
352
|
+
return Object.freeze({
|
|
353
|
+
kind: "membership",
|
|
354
|
+
value,
|
|
355
|
+
values: subquery,
|
|
356
|
+
negated: false
|
|
357
|
+
});
|
|
358
|
+
};
|
|
359
|
+
let atomicValues = true;
|
|
360
|
+
const readValues = (values, insert = false) => {
|
|
361
|
+
if (!values || typeof values !== "object" || Array.isArray(values)) throw new Error("symmetria: values must be an object");
|
|
362
|
+
const result = Object.create(null);
|
|
363
|
+
let assigned = 0;
|
|
364
|
+
for (const name of Object.keys(values)) {
|
|
365
|
+
const value = values[name];
|
|
366
|
+
const column = root.table.columns.find((column) => column.name === name);
|
|
367
|
+
if (!column) throw new Error(`symmetria: unknown column "${root.alias}.${name}"`);
|
|
368
|
+
if (value === void 0) continue;
|
|
369
|
+
if (value === null && column.notNull) throw new Error(`symmetria: "${root.alias}.${name}" cannot be null`);
|
|
370
|
+
if (value === DEFAULT_VALUE && !column.default && column.notNull) throw new Error(`symmetria: "${root.alias}.${name}" has no default`);
|
|
371
|
+
if (column.default?.kind === "sql" && column.default.sql === "identity" && value !== DEFAULT_VALUE) throw new Error(`symmetria: "${root.alias}.${name}" is generated always; use defaultValue`);
|
|
372
|
+
const node = value === DEFAULT_VALUE ? DEFAULT_VALUE : valueNode(value, root.codecs[name]);
|
|
373
|
+
if (node !== DEFAULT_VALUE && node.kind !== "parameter" && node.kind !== "placeholder" && node.kind !== "column") atomicValues = false;
|
|
374
|
+
result[name] = node;
|
|
375
|
+
assigned += 1;
|
|
376
|
+
}
|
|
377
|
+
if (insert) {
|
|
378
|
+
for (const column of root.table.columns) if (column.notNull && !column.default && values[column.name] === void 0) throw new Error(`symmetria: missing required column "${root.alias}.${column.name}"`);
|
|
379
|
+
}
|
|
380
|
+
if (!insert && !assigned) throw new Error("symmetria: update() requires at least one value");
|
|
381
|
+
return Object.freeze(result);
|
|
382
|
+
};
|
|
383
|
+
const resolved = typeof input === "function" ? input(scope[root.alias]) : input;
|
|
384
|
+
const rows = Array.isArray(resolved) ? resolved : [resolved];
|
|
385
|
+
const single = kind === "insert" && !Array.isArray(resolved);
|
|
386
|
+
if (kind === "update" && !rows.length) throw new Error("symmetria: update() requires at least one value");
|
|
387
|
+
const initial = Object.freeze({
|
|
388
|
+
kind,
|
|
389
|
+
root,
|
|
390
|
+
bindings,
|
|
391
|
+
values: Object.freeze(kind === "delete" ? [] : rows.map((row) => readValues(row, kind === "insert"))),
|
|
392
|
+
atomicValues,
|
|
393
|
+
predicates: Object.freeze(kind === "insert" ? [] : [...options.scope ?? []]),
|
|
394
|
+
selection: Object.freeze([]),
|
|
395
|
+
...single ? { single: true } : {}
|
|
396
|
+
});
|
|
397
|
+
const chunkPlans = /* @__PURE__ */ new WeakMap();
|
|
398
|
+
const executeChunked = async (state, runner = executor, compile, insideAtomic = false) => {
|
|
399
|
+
const limit = PARAMETER_LIMIT;
|
|
400
|
+
const compiled = compile ?? compilePlan;
|
|
401
|
+
let chunks = chunkPlans.get(state);
|
|
402
|
+
const run = (plan, execute) => compile ? executeCompiled(plan, compile(plan), execute) : executePlan(plan, execute);
|
|
403
|
+
if (state.kind !== "insert" || state.values.length < 2 || !options.atomic || state.atomicValues && state.values.length * root.table.columns.length + 1e3 <= limit || !chunks && compiled(state).parameters.length <= limit) return run(state, runner);
|
|
404
|
+
if (!chunks) {
|
|
405
|
+
const plans = [];
|
|
406
|
+
const split = (values) => {
|
|
407
|
+
const chunk = Object.freeze({
|
|
408
|
+
...state,
|
|
409
|
+
values
|
|
410
|
+
});
|
|
411
|
+
if (values.length > 1 && compiled(chunk).parameters.length > limit) {
|
|
412
|
+
const middle = Math.ceil(values.length / 2);
|
|
413
|
+
split(values.slice(0, middle));
|
|
414
|
+
split(values.slice(middle));
|
|
415
|
+
} else plans.push(chunk);
|
|
416
|
+
};
|
|
417
|
+
split(state.values);
|
|
418
|
+
chunks = plans;
|
|
419
|
+
chunkPlans.set(state, chunks);
|
|
420
|
+
}
|
|
421
|
+
const runChunks = async (atomicExecutor) => {
|
|
422
|
+
const rows = [];
|
|
423
|
+
let affectedRows = 0;
|
|
424
|
+
for (const chunk of chunks) {
|
|
425
|
+
const result = await run(chunk, atomicExecutor);
|
|
426
|
+
rows.push(...result.rows);
|
|
427
|
+
affectedRows += result.affectedRows;
|
|
428
|
+
}
|
|
429
|
+
return {
|
|
430
|
+
rows,
|
|
431
|
+
affectedRows
|
|
432
|
+
};
|
|
433
|
+
};
|
|
434
|
+
return insideAtomic ? runChunks(runner) : options.atomic(runChunks);
|
|
435
|
+
};
|
|
436
|
+
const build = (state) => {
|
|
437
|
+
const executeUsing = async (compile) => {
|
|
438
|
+
const inScope = (result) => {
|
|
439
|
+
if (state.conflict?.predicates?.length && !state.conflict.condition && result.affectedRows < state.values.length) throw Object.assign(/* @__PURE__ */ new Error(`symmetria: upsert on "${root.table.name}" conflicted with a row outside the database scope`), { code: "SYMMETRIA_OUT_OF_SCOPE" });
|
|
440
|
+
return result;
|
|
441
|
+
};
|
|
442
|
+
const result = state.kind === "insert" && !state.values.length ? {
|
|
443
|
+
rows: [],
|
|
444
|
+
affectedRows: 0
|
|
445
|
+
} : state.conflict?.predicates?.length && state.values.length > 1 && options.atomic ? await options.atomic((atomicExecutor) => executeChunked(state, atomicExecutor, compile, true).then(inScope)) : inScope(await executeChunked(state, executor, compile));
|
|
446
|
+
if (!state.selection.length) return { affectedRows: result.affectedRows };
|
|
447
|
+
return state.single ? result.rows[0] ?? null : result.rows;
|
|
448
|
+
};
|
|
449
|
+
const execute = () => executeUsing();
|
|
450
|
+
const builder = Object.freeze({
|
|
451
|
+
returning: (selector) => build(Object.freeze({
|
|
452
|
+
...state,
|
|
453
|
+
selection: readSelection(returningProjection(selector, scope[root.alias], root.table), bindings)
|
|
454
|
+
})),
|
|
455
|
+
where: (callback) => {
|
|
456
|
+
if (kind === "insert") throw new Error("symmetria: INSERT has no WHERE clause");
|
|
457
|
+
return build(Object.freeze({
|
|
458
|
+
...state,
|
|
459
|
+
predicates: Object.freeze([...state.predicates, wherePredicate(callback)])
|
|
460
|
+
}));
|
|
461
|
+
},
|
|
462
|
+
all: () => {
|
|
463
|
+
if (kind === "insert") throw new Error("symmetria: all() applies to UPDATE and DELETE");
|
|
464
|
+
return build(Object.freeze({
|
|
465
|
+
...state,
|
|
466
|
+
unrestricted: true
|
|
467
|
+
}));
|
|
468
|
+
},
|
|
469
|
+
onConflict: (...names) => {
|
|
470
|
+
if (kind !== "insert") throw new Error("symmetria: ON CONFLICT is only available for INSERT");
|
|
471
|
+
const columns = names.map((name) => {
|
|
472
|
+
const column = root.table.columns.find((column) => column.name === name);
|
|
473
|
+
if (!column) throw new Error(`symmetria: unknown conflict column "${name}"`);
|
|
474
|
+
return column;
|
|
475
|
+
});
|
|
476
|
+
if (new Set(names).size !== names.length) throw new Error("symmetria: duplicate conflict columns");
|
|
477
|
+
return Object.freeze({
|
|
478
|
+
doNothing: () => build(Object.freeze({
|
|
479
|
+
...state,
|
|
480
|
+
conflict: Object.freeze({
|
|
481
|
+
columns: Object.freeze(columns),
|
|
482
|
+
action: "nothing",
|
|
483
|
+
values: Object.freeze({})
|
|
484
|
+
})
|
|
485
|
+
})),
|
|
486
|
+
doUpdate: (values, ...rest) => {
|
|
487
|
+
if (!columns.length) throw new Error("symmetria: DO UPDATE requires conflict columns");
|
|
488
|
+
const conditional = typeof values !== "string" && rest.length === 1 && rest[0] !== null && typeof rest[0] === "object";
|
|
489
|
+
const names = conditional ? [] : rest;
|
|
490
|
+
const where = conditional ? rest[0].where : void 0;
|
|
491
|
+
if (conditional && (typeof where !== "function" || Object.keys(rest[0]).some((key) => key !== "where"))) throw new Error("symmetria: doUpdate() options accept a where callback only");
|
|
492
|
+
if (typeof values === "string" ? (/* @__PURE__ */ new Set([values, ...names])).size !== names.length + 1 : names.some((name) => typeof name !== "string") || names.length > 0 && !conditional) throw new Error("symmetria: doUpdate() requires distinct column names or a single values object/callback");
|
|
493
|
+
if (root.alias === "excluded") throw new Error("symmetria: the table alias 'excluded' conflicts with PostgreSQL's upsert row");
|
|
494
|
+
const excluded = Object.freeze({
|
|
495
|
+
...root,
|
|
496
|
+
alias: "excluded"
|
|
497
|
+
});
|
|
498
|
+
const conflictScope = createScope({
|
|
499
|
+
...bindings,
|
|
500
|
+
excluded
|
|
501
|
+
});
|
|
502
|
+
const condition = where ? (() => {
|
|
503
|
+
const result = where(conflictScope[root.alias], conflictScope.excluded);
|
|
504
|
+
const description = readPredicate(Array.isArray(result) ? and(...result) : result);
|
|
505
|
+
validatePredicate(description, {
|
|
506
|
+
...bindings,
|
|
507
|
+
excluded
|
|
508
|
+
});
|
|
509
|
+
return description;
|
|
510
|
+
})() : void 0;
|
|
511
|
+
return build(Object.freeze({
|
|
512
|
+
...state,
|
|
513
|
+
conflict: Object.freeze({
|
|
514
|
+
columns: Object.freeze(columns),
|
|
515
|
+
action: "update",
|
|
516
|
+
excluded,
|
|
517
|
+
...condition ? { condition } : {},
|
|
518
|
+
...options.scope?.length ? { predicates: Object.freeze([...options.scope]) } : {},
|
|
519
|
+
values: readValues(typeof values === "string" ? Object.fromEntries([values, ...names].map((name) => [name, conflictScope.excluded[name]])) : typeof values === "function" ? values(conflictScope[root.alias], conflictScope.excluded) : values)
|
|
520
|
+
})
|
|
521
|
+
}));
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
},
|
|
525
|
+
toSQL: () => compileQuery(state),
|
|
526
|
+
prepare: () => preparePlan(state, executor, void 0, [], executeUsing),
|
|
527
|
+
[PREPARE_QUERY]: (scope, names) => preparePlan(state, executor, scope, names, executeUsing),
|
|
528
|
+
execute,
|
|
529
|
+
then: (onFulfilled, onRejected) => execute().then(onFulfilled, onRejected)
|
|
530
|
+
});
|
|
531
|
+
return profile ? profile.trackBuilder(builder) : builder;
|
|
532
|
+
};
|
|
533
|
+
return build(initial);
|
|
534
|
+
};
|
|
535
|
+
//#endregion
|
|
536
|
+
//#region src/query/expressions/callable.ts
|
|
537
|
+
/**
|
|
538
|
+
* Relation handles live only inside one shape callback, so they are not frozen:
|
|
539
|
+
* freezing a function with many properties costs more than building it.
|
|
540
|
+
*/
|
|
541
|
+
const callable = (invoke, properties, relatedColumns = false) => {
|
|
542
|
+
if (relatedColumns) Object.defineProperties(invoke, {
|
|
543
|
+
name: { get: () => void 0 },
|
|
544
|
+
length: { get: () => void 0 }
|
|
545
|
+
});
|
|
546
|
+
return Object.assign(invoke, properties);
|
|
547
|
+
};
|
|
548
|
+
/** Lazy binding preserves detached calls without allocating every method per query. */
|
|
549
|
+
const boundMethodDescriptors = (methods) => {
|
|
550
|
+
const descriptors = Object.getOwnPropertyDescriptors(methods);
|
|
551
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
552
|
+
const descriptor = descriptors[key];
|
|
553
|
+
if (typeof descriptor.value !== "function") continue;
|
|
554
|
+
const method = descriptor.value;
|
|
555
|
+
const bound = /* @__PURE__ */ new WeakMap();
|
|
556
|
+
descriptors[key] = {
|
|
557
|
+
enumerable: !!descriptor.enumerable,
|
|
558
|
+
configurable: !!descriptor.configurable,
|
|
559
|
+
get() {
|
|
560
|
+
let value = bound.get(this);
|
|
561
|
+
if (!value) {
|
|
562
|
+
value = method.bind(this);
|
|
563
|
+
bound.set(this, value);
|
|
564
|
+
}
|
|
565
|
+
return value;
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
return descriptors;
|
|
570
|
+
};
|
|
571
|
+
const extendBuilder = (builder, properties) => {
|
|
572
|
+
if (typeof builder === "function") {
|
|
573
|
+
const extended = (...argumentsList) => Reflect.apply(builder, void 0, argumentsList);
|
|
574
|
+
Object.setPrototypeOf(extended, Object.getPrototypeOf(builder));
|
|
575
|
+
for (const key of Reflect.ownKeys(builder)) if (key !== "length" && key !== "name") Object.defineProperty(extended, key, {
|
|
576
|
+
...Object.getOwnPropertyDescriptor(builder, key),
|
|
577
|
+
configurable: true
|
|
578
|
+
});
|
|
579
|
+
for (const key of Reflect.ownKeys(properties)) Object.defineProperty(extended, key, {
|
|
580
|
+
value: properties[key],
|
|
581
|
+
enumerable: true,
|
|
582
|
+
configurable: true
|
|
583
|
+
});
|
|
584
|
+
return Object.freeze(extended);
|
|
585
|
+
}
|
|
586
|
+
return Object.freeze({
|
|
587
|
+
...builder,
|
|
588
|
+
...properties
|
|
589
|
+
});
|
|
590
|
+
};
|
|
591
|
+
//#endregion
|
|
592
|
+
//#region src/query/select/suggest.ts
|
|
593
|
+
/** Property reads that generic code performs on any object and must stay silent. */
|
|
594
|
+
const PASSTHROUGH_MEMBERS = /* @__PURE__ */ new Set(["then", "toJSON"]);
|
|
595
|
+
const distance = (left, right) => {
|
|
596
|
+
const previous = Array.from({ length: right.length + 1 }, (_, i) => i);
|
|
597
|
+
for (let i = 1; i <= left.length; i += 1) {
|
|
598
|
+
let diagonal = previous[0];
|
|
599
|
+
previous[0] = i;
|
|
600
|
+
for (let j = 1; j <= right.length; j += 1) {
|
|
601
|
+
const above = previous[j];
|
|
602
|
+
previous[j] = Math.min(above + 1, previous[j - 1] + 1, diagonal + (left[i - 1] === right[j - 1] ? 0 : 1));
|
|
603
|
+
diagonal = above;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return previous[right.length];
|
|
607
|
+
};
|
|
608
|
+
/** The closest known name: a case-insensitive match, or within two edits. */
|
|
609
|
+
const closestName = (name, candidates) => {
|
|
610
|
+
const exact = candidates.find((candidate) => candidate.toLowerCase() === name.toLowerCase());
|
|
611
|
+
if (exact) return exact;
|
|
612
|
+
let best;
|
|
613
|
+
for (const candidate of candidates) {
|
|
614
|
+
const score = distance(name.toLowerCase(), candidate.toLowerCase());
|
|
615
|
+
if (score <= 2 && (!best || score < best.score)) best = {
|
|
616
|
+
candidate,
|
|
617
|
+
score
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
return best?.candidate;
|
|
621
|
+
};
|
|
622
|
+
/** Whether a property read on a shape view should be reported as a mistake. */
|
|
623
|
+
const isSilentMember = (property) => PASSTHROUGH_MEMBERS.has(property) || property in Object.prototype;
|
|
624
|
+
const unknownMember = (table, property, columnNames) => {
|
|
625
|
+
const relations = table.relations.map((relation) => relation.name);
|
|
626
|
+
const suggestion = closestName(property, [...columnNames, ...relations]);
|
|
627
|
+
const available = [...columnNames.length ? [`columns: ${columnNames.join(", ")}`] : [], ...relations.length ? [`relations: ${relations.join(", ")}`] : []].join("; ");
|
|
628
|
+
return /* @__PURE__ */ new Error(`symmetria: "${table.name}.${property}" is not a column or relation of "${table.name}"${suggestion ? ` (did you mean "${suggestion}"?)` : ""}. Available ${available}`);
|
|
629
|
+
};
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region src/query/plan/occurrence.ts
|
|
632
|
+
const remap = (values, visit) => values.length ? Object.freeze(values.map(visit)) : values;
|
|
633
|
+
/** Give a reusable query new local sources, retaining its correlated ancestors. */
|
|
634
|
+
const queryOccurrence = (source) => {
|
|
635
|
+
const replacements = new Map([source.root, ...source.joins.map((join) => join.binding)].map((binding) => [binding, Object.freeze({ ...binding })]));
|
|
636
|
+
const derivedBindings = /* @__PURE__ */ new Map();
|
|
637
|
+
const binding = (original) => {
|
|
638
|
+
if (!original.derived) return replacements.get(original) ?? original;
|
|
639
|
+
const existing = derivedBindings.get(original);
|
|
640
|
+
if (existing) return existing;
|
|
641
|
+
const rebound = Object.freeze({
|
|
642
|
+
...original,
|
|
643
|
+
derived: query(original.derived),
|
|
644
|
+
...original.projection ? { projection: Object.freeze(Object.fromEntries(Object.entries(original.projection).map(([name, selected]) => [name, expression(selected)]))) } : {}
|
|
645
|
+
});
|
|
646
|
+
derivedBindings.set(original, rebound);
|
|
647
|
+
return rebound;
|
|
648
|
+
};
|
|
649
|
+
const expression = (original) => {
|
|
650
|
+
const node = value(original.node);
|
|
651
|
+
return node === original.node ? original : Object.freeze({
|
|
652
|
+
...original,
|
|
653
|
+
node
|
|
654
|
+
});
|
|
655
|
+
};
|
|
656
|
+
const ordering = (original) => Object.freeze({
|
|
657
|
+
...original,
|
|
658
|
+
expression: expression(original.expression)
|
|
659
|
+
});
|
|
660
|
+
const value = (original) => {
|
|
661
|
+
switch (original.kind) {
|
|
662
|
+
case "column": {
|
|
663
|
+
const rebound = binding(original.description.binding);
|
|
664
|
+
if (rebound === original.description.binding) return original;
|
|
665
|
+
return Object.freeze({
|
|
666
|
+
...original,
|
|
667
|
+
description: Object.freeze({
|
|
668
|
+
...original.description,
|
|
669
|
+
binding: rebound
|
|
670
|
+
})
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
case "parameter":
|
|
674
|
+
case "placeholder": return original;
|
|
675
|
+
case "raw": return Object.freeze({
|
|
676
|
+
...original,
|
|
677
|
+
parts: Object.freeze(original.parts.map((part) => typeof part === "string" ? part : value(part)))
|
|
678
|
+
});
|
|
679
|
+
case "binary": return Object.freeze({
|
|
680
|
+
...original,
|
|
681
|
+
left: value(original.left),
|
|
682
|
+
right: value(original.right)
|
|
683
|
+
});
|
|
684
|
+
case "aggregate": return original.value ? Object.freeze({
|
|
685
|
+
...original,
|
|
686
|
+
value: value(original.value)
|
|
687
|
+
}) : original;
|
|
688
|
+
case "case": return Object.freeze({
|
|
689
|
+
...original,
|
|
690
|
+
value: value(original.value),
|
|
691
|
+
branches: Object.freeze(original.branches.map((branch) => Object.freeze({
|
|
692
|
+
when: value(branch.when),
|
|
693
|
+
then: value(branch.then)
|
|
694
|
+
})))
|
|
695
|
+
});
|
|
696
|
+
case "coalesce":
|
|
697
|
+
case "tuple": return Object.freeze({
|
|
698
|
+
...original,
|
|
699
|
+
values: Object.freeze(original.values.map(value))
|
|
700
|
+
});
|
|
701
|
+
case "relativeWindow": return Object.freeze({
|
|
702
|
+
...original,
|
|
703
|
+
value: value(original.value),
|
|
704
|
+
offset: value(original.offset),
|
|
705
|
+
...original.fallback ? { fallback: value(original.fallback) } : {}
|
|
706
|
+
});
|
|
707
|
+
case "window": return Object.freeze({
|
|
708
|
+
...original,
|
|
709
|
+
expression: value(original.expression),
|
|
710
|
+
partitionBy: Object.freeze(original.partitionBy.map(value)),
|
|
711
|
+
orderBy: Object.freeze(original.orderBy.map(ordering))
|
|
712
|
+
});
|
|
713
|
+
case "subquery":
|
|
714
|
+
case "rowCount":
|
|
715
|
+
case "jsonRows": return Object.freeze({
|
|
716
|
+
...original,
|
|
717
|
+
query: query(original.query)
|
|
718
|
+
});
|
|
719
|
+
case "jsonObject": return Object.freeze({
|
|
720
|
+
...original,
|
|
721
|
+
selection: Object.freeze(original.selection.map(expression))
|
|
722
|
+
});
|
|
723
|
+
case "jsonPath":
|
|
724
|
+
case "arrayLength":
|
|
725
|
+
case "arrayIndex": return Object.freeze({
|
|
726
|
+
...original,
|
|
727
|
+
value: value(original.value)
|
|
728
|
+
});
|
|
729
|
+
case "searchRank":
|
|
730
|
+
case "searchHeadline": return Object.freeze({
|
|
731
|
+
...original,
|
|
732
|
+
value: value(original.value),
|
|
733
|
+
query: value(original.query)
|
|
734
|
+
});
|
|
735
|
+
case "tsvector": return Object.freeze({
|
|
736
|
+
...original,
|
|
737
|
+
parts: Object.freeze(original.parts.map((part) => Object.freeze({
|
|
738
|
+
...part,
|
|
739
|
+
value: value(part.value)
|
|
740
|
+
})))
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
const predicate = (original) => {
|
|
745
|
+
switch (original.kind) {
|
|
746
|
+
case "comparison": return Object.freeze({
|
|
747
|
+
...original,
|
|
748
|
+
left: value(original.left),
|
|
749
|
+
right: value(original.right)
|
|
750
|
+
});
|
|
751
|
+
case "search": return Object.freeze({
|
|
752
|
+
...original,
|
|
753
|
+
value: value(original.value),
|
|
754
|
+
query: value(original.query)
|
|
755
|
+
});
|
|
756
|
+
case "has": return Object.freeze({
|
|
757
|
+
...original,
|
|
758
|
+
value: value(original.value),
|
|
759
|
+
element: value(original.element)
|
|
760
|
+
});
|
|
761
|
+
case "nullCheck": return Object.freeze({
|
|
762
|
+
...original,
|
|
763
|
+
value: value(original.value)
|
|
764
|
+
});
|
|
765
|
+
case "group": return Object.freeze({
|
|
766
|
+
...original,
|
|
767
|
+
predicates: Object.freeze(original.predicates.map(predicate))
|
|
768
|
+
});
|
|
769
|
+
case "not":
|
|
770
|
+
case "notTrue": return Object.freeze({
|
|
771
|
+
...original,
|
|
772
|
+
predicate: predicate(original.predicate)
|
|
773
|
+
});
|
|
774
|
+
case "membership": return Object.freeze({
|
|
775
|
+
...original,
|
|
776
|
+
value: value(original.value),
|
|
777
|
+
values: Array.isArray(original.values) ? Object.freeze(original.values.map(value)) : query(original.values)
|
|
778
|
+
});
|
|
779
|
+
case "between": return Object.freeze({
|
|
780
|
+
...original,
|
|
781
|
+
value: value(original.value),
|
|
782
|
+
lower: value(original.lower),
|
|
783
|
+
upper: value(original.upper)
|
|
784
|
+
});
|
|
785
|
+
case "exists": return Object.freeze({
|
|
786
|
+
...original,
|
|
787
|
+
query: query(original.query)
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
};
|
|
791
|
+
const query = (original) => Object.freeze({
|
|
792
|
+
...original,
|
|
793
|
+
root: binding(original.root),
|
|
794
|
+
bindings: Object.freeze(Object.fromEntries(Object.entries(original.bindings).map(([name, original]) => [name, binding(original)]))),
|
|
795
|
+
joins: remap(original.joins, (join) => Object.freeze({
|
|
796
|
+
...join,
|
|
797
|
+
binding: binding(join.binding),
|
|
798
|
+
...join.condition ? { condition: predicate(join.condition) } : {},
|
|
799
|
+
...join.relation ? { relation: Object.freeze({
|
|
800
|
+
...join.relation,
|
|
801
|
+
from: binding(join.relation.from)
|
|
802
|
+
}) } : {}
|
|
803
|
+
})),
|
|
804
|
+
selection: remap(original.selection, expression),
|
|
805
|
+
predicates: remap(original.predicates, predicate),
|
|
806
|
+
grouping: remap(original.grouping, expression),
|
|
807
|
+
having: remap(original.having, predicate),
|
|
808
|
+
ordering: remap(original.ordering, ordering)
|
|
809
|
+
});
|
|
810
|
+
return query(source);
|
|
811
|
+
};
|
|
812
|
+
//#endregion
|
|
813
|
+
//#region src/schema/conditions.ts
|
|
814
|
+
const CONDITION = Symbol("symmetria.relation.condition");
|
|
815
|
+
const declaration = (state) => Object.freeze({
|
|
816
|
+
[CONDITION]: Object.freeze(state),
|
|
817
|
+
inverse: (name) => {
|
|
818
|
+
if (typeof name !== "string" || !name) throw new Error("symmetria: inverse() expects a relation name");
|
|
819
|
+
return declaration({
|
|
820
|
+
...state,
|
|
821
|
+
inverse: name
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
const relationTools = Object.freeze({ to: (target) => {
|
|
826
|
+
if (target === null || target === void 0) throw new Error("symmetria: to() expects a table, a thunk returning one or a schema reference");
|
|
827
|
+
const build = (many) => (predicate) => {
|
|
828
|
+
if (typeof predicate !== "function") throw new Error(`symmetria: ${many ? "many" : "one"}() expects a predicate callback`);
|
|
829
|
+
return declaration({
|
|
830
|
+
target,
|
|
831
|
+
many,
|
|
832
|
+
predicate
|
|
833
|
+
});
|
|
834
|
+
};
|
|
835
|
+
return Object.freeze({
|
|
836
|
+
one: build(false),
|
|
837
|
+
many: build(true)
|
|
838
|
+
});
|
|
839
|
+
} });
|
|
840
|
+
const isConditionDeclaration = (value) => typeof value === "object" && value !== null && CONDITION in value;
|
|
841
|
+
/** Relation callbacks per table snapshot; they never enter the snapshot itself. */
|
|
842
|
+
const conditionRelations = /* @__PURE__ */ new WeakMap();
|
|
843
|
+
/** Runs a table's relation callbacks against a scope and collects the declarations by name. */
|
|
844
|
+
const declaredConditions = (callbacks, columns, tableName) => {
|
|
845
|
+
const result = {};
|
|
846
|
+
for (const callback of callbacks) {
|
|
847
|
+
const declared = callback(columns, relationTools);
|
|
848
|
+
if (!declared || typeof declared !== "object" || Array.isArray(declared)) throw new Error(`symmetria: relations() of "${tableName}" must return an object of to(...) declarations`);
|
|
849
|
+
for (const [name, entry] of Object.entries(declared)) {
|
|
850
|
+
if (!isConditionDeclaration(entry)) throw new Error(`symmetria: relation "${tableName}.${name}" must be declared with to(<table>).one(...) or to(<table>).many(...)`);
|
|
851
|
+
if (Object.hasOwn(result, name)) throw new Error(`symmetria: relation "${tableName}.${name}" is declared twice in relations()`);
|
|
852
|
+
result[name] = entry;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return result;
|
|
856
|
+
};
|
|
857
|
+
//#endregion
|
|
858
|
+
//#region src/query/select/types.ts
|
|
859
|
+
const RELATION_SOURCE = Symbol("symmetria.query.relation");
|
|
860
|
+
//#endregion
|
|
861
|
+
//#region src/query/select/joins.ts
|
|
862
|
+
const columnNode = (binding, name, sqlName = false) => {
|
|
863
|
+
const column = binding.table.columns.find((candidate) => (sqlName ? candidate.sqlName : candidate.name) === name);
|
|
864
|
+
if (!column) throw new Error(`symmetria: unknown join column "${binding.alias}.${name}"`);
|
|
865
|
+
return Object.freeze({
|
|
866
|
+
kind: "column",
|
|
867
|
+
description: Object.freeze({
|
|
868
|
+
binding,
|
|
869
|
+
column
|
|
870
|
+
})
|
|
871
|
+
});
|
|
872
|
+
};
|
|
873
|
+
const joinRelation = (registry, state, kind, from, relationName, alias, outerAliases = []) => {
|
|
874
|
+
if (state.joins.some((join) => join.binding.alias === alias) || Object.hasOwn(state.bindings, alias)) throw new Error(`symmetria: duplicate query alias "${alias}"`);
|
|
875
|
+
const source = state.bindings[from];
|
|
876
|
+
if (!source) throw new Error(`symmetria: unknown query alias "${from}"`);
|
|
877
|
+
const relation = source.table.relations.find((candidate) => candidate.name === relationName);
|
|
878
|
+
if (!relation) throw new Error(`symmetria: unknown relation "${source.alias}.${relationName}"`);
|
|
879
|
+
const target = registry.bindingFor(relation.target, alias);
|
|
880
|
+
const joins = [...state.joins];
|
|
881
|
+
const equals = (left, right) => Object.freeze({
|
|
882
|
+
kind: "comparison",
|
|
883
|
+
left,
|
|
884
|
+
operator: "=",
|
|
885
|
+
right
|
|
886
|
+
});
|
|
887
|
+
const addJoin = (binding, comparison) => {
|
|
888
|
+
const scope = registry.scopePredicates(binding);
|
|
889
|
+
joins.push(Object.freeze({
|
|
890
|
+
kind,
|
|
891
|
+
binding,
|
|
892
|
+
...binding === target ? { relation: Object.freeze({
|
|
893
|
+
from: source,
|
|
894
|
+
name: relationName
|
|
895
|
+
}) } : {},
|
|
896
|
+
condition: scope.length ? Object.freeze({
|
|
897
|
+
kind: "group",
|
|
898
|
+
operator: "AND",
|
|
899
|
+
predicates: Object.freeze([comparison, ...scope])
|
|
900
|
+
}) : comparison
|
|
901
|
+
}));
|
|
902
|
+
};
|
|
903
|
+
const reference = (foreignKey, binding) => {
|
|
904
|
+
if (foreignKey.kind !== "column" || !foreignKey.description.column.references) throw new Error("symmetria: missing foreign key metadata");
|
|
905
|
+
return columnNode(binding, foreignKey.description.column.references.column, true);
|
|
906
|
+
};
|
|
907
|
+
if (relation.kind === "condition") {
|
|
908
|
+
const declaring = relation.reverse === true ? target : source;
|
|
909
|
+
const other = relation.reverse === true ? source : target;
|
|
910
|
+
const name = relation.reverse === true ? relation.inverseOf : relation.name;
|
|
911
|
+
const scope = createScope({
|
|
912
|
+
[declaring.alias]: declaring,
|
|
913
|
+
[other.alias]: other
|
|
914
|
+
});
|
|
915
|
+
const entry = declaredConditions(conditionRelations.get(declaring.table) ?? [], scope[declaring.alias], declaring.table.name)[name];
|
|
916
|
+
if (!entry) throw new Error(`symmetria: condition relation "${declaring.table.name}.${name}" is not declared by relations()`);
|
|
917
|
+
const condition = readPredicate(entry[CONDITION].predicate(scope[other.alias]));
|
|
918
|
+
validatePredicate(condition, {
|
|
919
|
+
[source.alias]: source,
|
|
920
|
+
[target.alias]: target
|
|
921
|
+
});
|
|
922
|
+
addJoin(target, condition);
|
|
923
|
+
} else if (relation.kind === "through") {
|
|
924
|
+
const reservedAliases = /* @__PURE__ */ new Set([
|
|
925
|
+
...outerAliases,
|
|
926
|
+
...Object.keys(state.bindings),
|
|
927
|
+
...joins.map((join) => join.binding.alias),
|
|
928
|
+
alias,
|
|
929
|
+
...registry.snapshot.tables.flatMap((table) => table.relations.map((relation) => relation.name))
|
|
930
|
+
]);
|
|
931
|
+
let junctionNumber = 0;
|
|
932
|
+
while (reservedAliases.has(`__symmetria_junction_${junctionNumber}`)) junctionNumber += 1;
|
|
933
|
+
const junction = registry.bindingFor(relation.junction, `__symmetria_junction_${junctionNumber}`);
|
|
934
|
+
const sourceForeignKey = columnNode(junction, relation.sourceForeignKey);
|
|
935
|
+
const targetForeignKey = columnNode(junction, relation.targetForeignKey);
|
|
936
|
+
addJoin(junction, equals(reference(sourceForeignKey, source), sourceForeignKey));
|
|
937
|
+
addJoin(target, equals(targetForeignKey, reference(targetForeignKey, target)));
|
|
938
|
+
} else if (relation.reverse === true) {
|
|
939
|
+
const foreignKey = columnNode(target, relation.foreignKey);
|
|
940
|
+
addJoin(target, equals(reference(foreignKey, source), foreignKey));
|
|
941
|
+
} else {
|
|
942
|
+
const foreignKey = columnNode(source, relation.foreignKey);
|
|
943
|
+
addJoin(target, equals(foreignKey, reference(foreignKey, target)));
|
|
944
|
+
}
|
|
945
|
+
return Object.freeze({
|
|
946
|
+
...state,
|
|
947
|
+
joins: Object.freeze(joins),
|
|
948
|
+
bindings: Object.freeze({
|
|
949
|
+
...state.bindings,
|
|
950
|
+
[alias]: target
|
|
951
|
+
})
|
|
952
|
+
});
|
|
953
|
+
};
|
|
954
|
+
const joinSource = (registry, state, kind, input, condition, context, occurrence) => {
|
|
955
|
+
if (input[TABLE_SOURCE].schema !== registry.snapshot) throw new Error("symmetria: cannot join a table from another schema");
|
|
956
|
+
const source = occurrence ?? input[TABLE_SOURCE].binding;
|
|
957
|
+
if (Object.hasOwn(state.bindings, source.alias) || state.joins.some((join) => join.binding.alias === source.alias)) throw new Error(`symmetria: duplicate query alias "${source.alias}"`);
|
|
958
|
+
if (kind !== "CROSS" && !condition) throw new Error("symmetria: an explicit join requires an ON callback");
|
|
959
|
+
const binding = Object.freeze({ ...source });
|
|
960
|
+
const scope = registry.scopePredicates(binding);
|
|
961
|
+
const joinCondition = condition ? readPredicate(condition(createScope({
|
|
962
|
+
...state.bindings,
|
|
963
|
+
[binding.alias]: binding
|
|
964
|
+
}))) : void 0;
|
|
965
|
+
const current = context?.plan ?? state;
|
|
966
|
+
if (Object.hasOwn(current.bindings, source.alias) || current.joins.some((join) => join.binding.alias === source.alias)) throw new Error(`symmetria: duplicate query alias "${source.alias}"`);
|
|
967
|
+
const bindings = Object.freeze({
|
|
968
|
+
...current.bindings,
|
|
969
|
+
[binding.alias]: binding
|
|
970
|
+
});
|
|
971
|
+
const description = Object.freeze({
|
|
972
|
+
kind,
|
|
973
|
+
binding,
|
|
974
|
+
...joinCondition ? { condition: scope.length ? Object.freeze({
|
|
975
|
+
kind: "group",
|
|
976
|
+
operator: "AND",
|
|
977
|
+
predicates: Object.freeze([joinCondition, ...scope])
|
|
978
|
+
}) : joinCondition } : {}
|
|
979
|
+
});
|
|
980
|
+
return Object.freeze({
|
|
981
|
+
...current,
|
|
982
|
+
bindings,
|
|
983
|
+
joins: Object.freeze([...current.joins, description]),
|
|
984
|
+
predicates: joinCondition || !scope.length ? current.predicates : Object.freeze([...current.predicates, ...scope])
|
|
985
|
+
});
|
|
986
|
+
};
|
|
987
|
+
/** Reads one predicate or a list; `undefined`, `null` and `false` entries are skipped. */
|
|
988
|
+
const readShapePredicates = (value) => Object.freeze((Array.isArray(value) ? value : [value]).filter((entry) => entry !== void 0 && entry !== null && entry !== false).map(readPredicate));
|
|
989
|
+
const joinReference = (context, input) => {
|
|
990
|
+
if (!input || typeof input !== "object" && typeof input !== "function") throw new Error("symmetria: JOIN requires a foreign-key column or an unfiltered relation");
|
|
991
|
+
if (COLUMN_EXPRESSION in input) {
|
|
992
|
+
const node = readColumn(input).node;
|
|
993
|
+
if (node.kind !== "column" || !node.description.column.references) throw new Error("symmetria: JOIN requires a foreign-key column or an unfiltered relation");
|
|
994
|
+
const { binding, column } = node.description;
|
|
995
|
+
const relation = binding.table.relations.find((relation) => relation.kind === "one" && !relation.reverse && relation.foreignKey === column.name);
|
|
996
|
+
if (context.plan.bindings[binding.alias] !== binding || !relation) throw new Error("symmetria: JOIN foreign-key column belongs to another query scope");
|
|
997
|
+
return {
|
|
998
|
+
from: binding.alias,
|
|
999
|
+
relation: relation.name,
|
|
1000
|
+
target: relation.target,
|
|
1001
|
+
alias: relation.name,
|
|
1002
|
+
owner: binding,
|
|
1003
|
+
nullable: !column.notNull || context.plan.joins.some((join) => join.binding === binding && join.kind === "LEFT")
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
const relation = input?.[RELATION_SOURCE];
|
|
1007
|
+
if (!relation || context.plan.bindings[relation.from] !== relation.owner) throw new Error("symmetria: JOIN expects an unfiltered relation from its query scope");
|
|
1008
|
+
return relation;
|
|
1009
|
+
};
|
|
1010
|
+
const joinAlias = (context, preferred, explicit = false) => {
|
|
1011
|
+
let alias = preferred;
|
|
1012
|
+
let ordinal = 2;
|
|
1013
|
+
while (Object.hasOwn(context.plan.bindings, alias) || context.plan.joins.some((join) => join.binding.alias === alias) || context.reservedAliases.has(alias)) {
|
|
1014
|
+
if (explicit) throw new Error(`symmetria: duplicate query alias "${preferred}"`);
|
|
1015
|
+
alias = numberedAlias(preferred, ordinal++);
|
|
1016
|
+
}
|
|
1017
|
+
return alias;
|
|
1018
|
+
};
|
|
1019
|
+
const localJoin = (context, kind, input, condition) => {
|
|
1020
|
+
if (!input || typeof input !== "object" && typeof input !== "function") throw new Error("symmetria: local JOIN expects a foreign-key column, relation or table source");
|
|
1021
|
+
if (TABLE_SOURCE in input) {
|
|
1022
|
+
if (kind === "AUTO" || kind === "CROSS" && condition) throw new Error("symmetria: join() requires a relation; crossJoin() accepts a source without ON");
|
|
1023
|
+
const source = input[TABLE_SOURCE].binding;
|
|
1024
|
+
if (!condition && (kind !== "CROSS" || source.explicitAlias)) {
|
|
1025
|
+
const matches = context.plan.joins.filter((join) => source.explicitAlias ? join.binding.alias === source.alias : join.binding.table === source.table && join.binding.derived === source.derived && join.binding.cteReference?.identity === source.cteReference?.identity);
|
|
1026
|
+
if (matches.length === 1) return context.columns(matches[0].binding);
|
|
1027
|
+
if (matches.length > 1) throw new Error(`symmetria: "${source.alias}" is joined more than once; name the JOIN with .as() to refer to it`);
|
|
1028
|
+
}
|
|
1029
|
+
const alias = joinAlias(context, source.alias, source.explicitAlias);
|
|
1030
|
+
context.reservedAliases.add(alias);
|
|
1031
|
+
try {
|
|
1032
|
+
context.plan = joinSource(context.registry, context.plan, kind, input, condition ? (scope) => predicate({
|
|
1033
|
+
kind: "group",
|
|
1034
|
+
operator: "AND",
|
|
1035
|
+
predicates: readShapePredicates(condition(scope[alias]))
|
|
1036
|
+
}) : void 0, context, Object.freeze({
|
|
1037
|
+
...source,
|
|
1038
|
+
alias
|
|
1039
|
+
}));
|
|
1040
|
+
} finally {
|
|
1041
|
+
context.reservedAliases.delete(alias);
|
|
1042
|
+
}
|
|
1043
|
+
return context.columns(context.plan.bindings[alias]);
|
|
1044
|
+
}
|
|
1045
|
+
const relation = joinReference(context, input);
|
|
1046
|
+
if (condition) throw new Error("symmetria: inferred JOIN sources do not take an ON callback");
|
|
1047
|
+
if (relation.explicitAlias) {
|
|
1048
|
+
const existing = context.plan.joins.find((join) => join.binding.alias === relation.alias && join.relation?.from === relation.owner && join.relation.name === relation.relation);
|
|
1049
|
+
if (existing) return context.columns(existing.binding);
|
|
1050
|
+
}
|
|
1051
|
+
const alias = joinAlias(context, relation.alias, relation.explicitAlias);
|
|
1052
|
+
if (kind === "CROSS") {
|
|
1053
|
+
const joined = joinSource(context.registry, context.plan, kind, { [TABLE_SOURCE]: {
|
|
1054
|
+
binding: context.registry.bindingFor(relation.target, alias),
|
|
1055
|
+
schema: context.registry.snapshot
|
|
1056
|
+
} });
|
|
1057
|
+
const last = joined.joins.at(-1);
|
|
1058
|
+
context.plan = Object.freeze({
|
|
1059
|
+
...joined,
|
|
1060
|
+
joins: Object.freeze([...joined.joins.slice(0, -1), Object.freeze({
|
|
1061
|
+
...last,
|
|
1062
|
+
relation: Object.freeze({
|
|
1063
|
+
from: relation.owner,
|
|
1064
|
+
name: relation.relation
|
|
1065
|
+
})
|
|
1066
|
+
})])
|
|
1067
|
+
});
|
|
1068
|
+
return context.columns(context.plan.bindings[alias]);
|
|
1069
|
+
}
|
|
1070
|
+
context.plan = joinRelation(context.registry, context.plan, kind === "AUTO" ? relation.nullable ? "LEFT" : "INNER" : kind, relation.from, relation.relation, alias, Object.keys(context.bindings()));
|
|
1071
|
+
return context.columns(context.plan.bindings[alias]);
|
|
1072
|
+
};
|
|
1073
|
+
//#endregion
|
|
1074
|
+
//#region src/query/select/shape.ts
|
|
1075
|
+
/** applyShape(): evaluates one projection callback with its options into a plan. */
|
|
1076
|
+
const emptyShape = () => ({});
|
|
1077
|
+
const queryOptionNames = /* @__PURE__ */ new Set([
|
|
1078
|
+
"where",
|
|
1079
|
+
"orderBy",
|
|
1080
|
+
"limit",
|
|
1081
|
+
"offset",
|
|
1082
|
+
"groupBy",
|
|
1083
|
+
"having",
|
|
1084
|
+
"distinct",
|
|
1085
|
+
"forUpdate",
|
|
1086
|
+
"forShare"
|
|
1087
|
+
]);
|
|
1088
|
+
const applyShape = (context, binding, callback, options) => {
|
|
1089
|
+
if (typeof callback === "object" && options === void 0) {
|
|
1090
|
+
options = callback;
|
|
1091
|
+
callback = emptyShape;
|
|
1092
|
+
}
|
|
1093
|
+
if (typeof callback !== "function") throw new Error("symmetria: a shape requires a synchronous callback");
|
|
1094
|
+
if (SHAPE_SOURCE in callback && callback[SHAPE_SOURCE] !== binding.table) throw new Error("symmetria: reusable shape belongs to another table");
|
|
1095
|
+
if (options !== void 0 && (!options || typeof options !== "object" || Array.isArray(options))) throw new Error("symmetria: query options must be an object");
|
|
1096
|
+
const initialJoinCount = context.plan.joins.length;
|
|
1097
|
+
const ancestors = shapeFrame.bindings?.();
|
|
1098
|
+
if (ancestors && Object.values(context.plan.bindings).some((binding) => containsBinding(ancestors, binding))) throw new Error("symmetria: nested queries require a distinct source occurrence");
|
|
1099
|
+
let active = true;
|
|
1100
|
+
const assertActive = () => {
|
|
1101
|
+
if (!active || shapeFrame.bindings !== context.bindings) throw new Error("symmetria: local JOIN helpers and whereNotNull can only be used inside their shape callback");
|
|
1102
|
+
};
|
|
1103
|
+
const join = (kind) => (input, condition) => {
|
|
1104
|
+
assertActive();
|
|
1105
|
+
return localJoin(context, kind, input, condition);
|
|
1106
|
+
};
|
|
1107
|
+
const whereNotNull = (column) => {
|
|
1108
|
+
assertActive();
|
|
1109
|
+
const expression = readColumn(column);
|
|
1110
|
+
validateNode(expression.node, context.bindings());
|
|
1111
|
+
context.plan = Object.freeze({
|
|
1112
|
+
...context.plan,
|
|
1113
|
+
predicates: Object.freeze([...context.plan.predicates, Object.freeze({
|
|
1114
|
+
kind: "nullCheck",
|
|
1115
|
+
value: expression.node,
|
|
1116
|
+
negated: true
|
|
1117
|
+
})])
|
|
1118
|
+
});
|
|
1119
|
+
return column;
|
|
1120
|
+
};
|
|
1121
|
+
let result;
|
|
1122
|
+
let controls;
|
|
1123
|
+
try {
|
|
1124
|
+
result = evaluateContext(context, () => {
|
|
1125
|
+
const columns = context.columns(binding);
|
|
1126
|
+
const tools = Object.assign(Object.create(shapeExpressions), {
|
|
1127
|
+
join: join("AUTO"),
|
|
1128
|
+
innerJoin: join("INNER"),
|
|
1129
|
+
leftJoin: join("LEFT"),
|
|
1130
|
+
crossJoin: join("CROSS"),
|
|
1131
|
+
whereNotNull
|
|
1132
|
+
});
|
|
1133
|
+
const projection = callback(columns, tools);
|
|
1134
|
+
if (options !== void 0) controls = Object.entries(options).map(([name, value]) => {
|
|
1135
|
+
if (!queryOptionNames.has(name)) throw new Error(`symmetria: unknown query option "${name}"`);
|
|
1136
|
+
return [name, typeof value === "function" ? value(columns, tools) : value];
|
|
1137
|
+
});
|
|
1138
|
+
return projection;
|
|
1139
|
+
});
|
|
1140
|
+
} finally {
|
|
1141
|
+
active = false;
|
|
1142
|
+
}
|
|
1143
|
+
if (!result || typeof result !== "object" || Array.isArray(result) || typeof result.then === "function" && !(QUERY_PLAN in result.then)) throw new Error("symmetria: a shape callback must synchronously return an object");
|
|
1144
|
+
const fields = Object.create(null);
|
|
1145
|
+
const entries = Object.entries(result);
|
|
1146
|
+
for (const [name] of entries) if (name.startsWith("$")) throw new Error(`symmetria: "${name}" is not a field; query options such as ${name.slice(1)} belong to the second argument: posts(shape, { ${name.slice(1)}: … })`);
|
|
1147
|
+
if (SHAPE_SOURCE in callback && !entries.length) throw new Error("symmetria: shape() requires projected fields");
|
|
1148
|
+
const settings = controls ?? [];
|
|
1149
|
+
let plan = { ...context.plan };
|
|
1150
|
+
if (settings.some(([name, value]) => name === "forUpdate" && value) && settings.some(([name, value]) => name === "forShare" && value)) throw new Error("symmetria: choose either forUpdate or forShare");
|
|
1151
|
+
for (const [name, value] of settings) switch (name) {
|
|
1152
|
+
case "distinct":
|
|
1153
|
+
if (value !== void 0) {
|
|
1154
|
+
if (typeof value !== "boolean") throw new Error("symmetria: distinct requires a boolean");
|
|
1155
|
+
plan.distinct = value;
|
|
1156
|
+
}
|
|
1157
|
+
break;
|
|
1158
|
+
case "forUpdate":
|
|
1159
|
+
case "forShare":
|
|
1160
|
+
if (value !== void 0 && value !== false) plan = { ...lockPlan(plan, name === "forUpdate" ? "UPDATE" : "SHARE", value === true ? {} : value) };
|
|
1161
|
+
break;
|
|
1162
|
+
case "where":
|
|
1163
|
+
case "having": {
|
|
1164
|
+
const clause = name === "where" ? "predicates" : "having";
|
|
1165
|
+
if (value !== void 0 && value !== null && value !== false) plan[clause] = Object.freeze([...plan[clause], ...readShapePredicates(value)]);
|
|
1166
|
+
break;
|
|
1167
|
+
}
|
|
1168
|
+
case "orderBy":
|
|
1169
|
+
if (value !== void 0) plan.ordering = Object.freeze([...plan.ordering, ...readOrdering(value, context.bindings())]);
|
|
1170
|
+
break;
|
|
1171
|
+
case "groupBy":
|
|
1172
|
+
if (value !== void 0) {
|
|
1173
|
+
if (!Array.isArray(value) || !value.length) throw new Error("symmetria: groupBy requires expressions");
|
|
1174
|
+
const grouping = value.map(readColumn);
|
|
1175
|
+
grouping.forEach((expression) => validateNode(expression.node, context.bindings()));
|
|
1176
|
+
plan.grouping = Object.freeze([...plan.grouping, ...grouping]);
|
|
1177
|
+
}
|
|
1178
|
+
break;
|
|
1179
|
+
case "limit":
|
|
1180
|
+
case "offset":
|
|
1181
|
+
if (value !== void 0) plan[name === "limit" ? "limit" : "offset"] = countValue(name, value);
|
|
1182
|
+
break;
|
|
1183
|
+
default: throw new Error(`symmetria: unknown query option "${name}"`);
|
|
1184
|
+
}
|
|
1185
|
+
for (const [name, value] of entries) fields[name] = value;
|
|
1186
|
+
if (!entries.length && !settings.length && context.plan.joins.length === initialJoinCount) throw new Error("symmetria: a shape requires at least one field or query option");
|
|
1187
|
+
if (Object.keys(fields).length) plan.selection = readSelection(fields, context.bindings());
|
|
1188
|
+
return Object.freeze(plan);
|
|
1189
|
+
};
|
|
1190
|
+
//#endregion
|
|
1191
|
+
//#region src/query/select/context.ts
|
|
1192
|
+
const memberNameCache = /* @__PURE__ */ new WeakMap();
|
|
1193
|
+
const aggregatePrototypes = /* @__PURE__ */ new WeakMap();
|
|
1194
|
+
const createContext = (registry, state, ancestors = shapeFrame.bindings ?? emptyBindings, depth = shapeFrame.depth) => {
|
|
1195
|
+
let previousOuter;
|
|
1196
|
+
let previousLocal;
|
|
1197
|
+
let merged;
|
|
1198
|
+
const context = {
|
|
1199
|
+
registry,
|
|
1200
|
+
plan: state,
|
|
1201
|
+
scope: () => {
|
|
1202
|
+
const bindings = Object.entries(state.bindings);
|
|
1203
|
+
if (bindings.length === 1) {
|
|
1204
|
+
const [name, binding] = bindings[0];
|
|
1205
|
+
return Object.freeze({ [name]: columnsFor(binding) });
|
|
1206
|
+
}
|
|
1207
|
+
return Object.freeze(Object.defineProperties({}, Object.fromEntries(bindings.map(([name, binding]) => [name, {
|
|
1208
|
+
enumerable: true,
|
|
1209
|
+
get: () => columnsFor(binding)
|
|
1210
|
+
}]))));
|
|
1211
|
+
},
|
|
1212
|
+
columns: (binding) => columnsFor(binding),
|
|
1213
|
+
bindings: () => {
|
|
1214
|
+
const outer = ancestors();
|
|
1215
|
+
const local = context.plan.bindings;
|
|
1216
|
+
if (outer !== previousOuter || local !== previousLocal) {
|
|
1217
|
+
previousOuter = outer;
|
|
1218
|
+
previousLocal = local;
|
|
1219
|
+
merged = Object.keys(outer).length ? Object.freeze(mergeBindings(outer, local)) : local;
|
|
1220
|
+
}
|
|
1221
|
+
return merged;
|
|
1222
|
+
},
|
|
1223
|
+
reservedAliases: /* @__PURE__ */ new Set()
|
|
1224
|
+
};
|
|
1225
|
+
const views = /* @__PURE__ */ new Map();
|
|
1226
|
+
const uniqueAlias = (prefix) => {
|
|
1227
|
+
const bindings = context.bindings();
|
|
1228
|
+
let ordinal = 0;
|
|
1229
|
+
let alias;
|
|
1230
|
+
do
|
|
1231
|
+
alias = `${prefix}${ordinal++}`;
|
|
1232
|
+
while (Object.hasOwn(bindings, alias) || context.reservedAliases.has(alias) || context.plan.joins.some((join) => join.binding.alias === alias));
|
|
1233
|
+
return alias;
|
|
1234
|
+
};
|
|
1235
|
+
/** Column and computed-field keys of a table, for membership checks and hints. */
|
|
1236
|
+
const memberNames = (table) => {
|
|
1237
|
+
let names = memberNameCache.get(table);
|
|
1238
|
+
if (!names) {
|
|
1239
|
+
const source = registry.bindingFor(table.name, table.name);
|
|
1240
|
+
names = Object.freeze(Object.keys(createScope({ [source.alias]: source })[source.alias]));
|
|
1241
|
+
memberNameCache.set(table, names);
|
|
1242
|
+
}
|
|
1243
|
+
return names;
|
|
1244
|
+
};
|
|
1245
|
+
const columnsFor = (binding) => {
|
|
1246
|
+
const existing = views.get(binding);
|
|
1247
|
+
if (existing) return existing;
|
|
1248
|
+
const columns = bindingScope(binding, { [binding.alias]: binding });
|
|
1249
|
+
const relationships = /* @__PURE__ */ new Map();
|
|
1250
|
+
const view = new Proxy(columns, { get: (target, property) => {
|
|
1251
|
+
if (typeof property !== "string" || Object.hasOwn(target, property)) return Reflect.get(target, property);
|
|
1252
|
+
if (relationships.has(property)) return relationships.get(property);
|
|
1253
|
+
const relation = binding.table.relations.find((relation) => relation.name === property);
|
|
1254
|
+
if (!relation) {
|
|
1255
|
+
if (isSilentMember(property)) return;
|
|
1256
|
+
throw unknownMember(binding.table, property, Object.keys(target));
|
|
1257
|
+
}
|
|
1258
|
+
const many = relation.kind === "many" || relation.kind === "through" || relation.kind === "condition" && relation.many;
|
|
1259
|
+
const nullable = context.plan.joins.some((join) => join.binding === binding && join.kind === "LEFT") || relation.kind !== "one" || relation.reverse === true || relation.nullable;
|
|
1260
|
+
let base;
|
|
1261
|
+
let related;
|
|
1262
|
+
const nestedPlan = () => {
|
|
1263
|
+
if (base) return base;
|
|
1264
|
+
const alias = uniqueAlias("__symmetria_aggregate_");
|
|
1265
|
+
const joined = joinRelation(registry, initialPlan(binding), "INNER", binding.alias, property, alias, Object.keys(context.bindings()));
|
|
1266
|
+
const first = joined.joins[0];
|
|
1267
|
+
related = joined.bindings[alias];
|
|
1268
|
+
base = Object.freeze({
|
|
1269
|
+
...initialPlan(first.binding),
|
|
1270
|
+
bindings: Object.freeze(Object.fromEntries(joined.joins.map((join) => [join.binding.alias, join.binding]))),
|
|
1271
|
+
joins: Object.freeze(joined.joins.slice(1)),
|
|
1272
|
+
predicates: Object.freeze([first.condition])
|
|
1273
|
+
});
|
|
1274
|
+
return base;
|
|
1275
|
+
};
|
|
1276
|
+
const pathColumns = (selectedAlias, customAlias) => {
|
|
1277
|
+
const previous = context.plan.joins.find((join) => join.relation?.from === binding && join.relation.name === property && (!customAlias || join.binding.alias === selectedAlias));
|
|
1278
|
+
if (previous) return columnsFor(previous.binding);
|
|
1279
|
+
const alias = customAlias ? selectedAlias : uniqueAlias(depth ? `__symmetria_path_${depth}_` : "__symmetria_path_");
|
|
1280
|
+
context.plan = joinRelation(registry, context.plan, nullable ? "LEFT" : "INNER", binding.alias, property, alias);
|
|
1281
|
+
return columnsFor(context.plan.bindings[alias]);
|
|
1282
|
+
};
|
|
1283
|
+
const build = (plan, selectedAlias = property, filtered = false, customAlias = false) => {
|
|
1284
|
+
const current = () => plan ?? nestedPlan();
|
|
1285
|
+
const evaluate = (callback) => {
|
|
1286
|
+
const nested = createContext(registry, current(), context.bindings, depth + 1);
|
|
1287
|
+
return {
|
|
1288
|
+
nested,
|
|
1289
|
+
result: evaluateContext(nested, () => callback(nested.columns(nested.plan.bindings[related.alias])))
|
|
1290
|
+
};
|
|
1291
|
+
};
|
|
1292
|
+
const quantified = (mode, callback) => {
|
|
1293
|
+
let query = current();
|
|
1294
|
+
if (query.limit !== void 0 || query.offset !== void 0) throw new Error("symmetria: relation quantifiers must precede limit()/offset()");
|
|
1295
|
+
if (mode === "every" && !callback) throw new Error("symmetria: every() requires a predicate");
|
|
1296
|
+
if (callback) {
|
|
1297
|
+
const { nested, result } = evaluate(callback);
|
|
1298
|
+
const description = readPredicate(result);
|
|
1299
|
+
query = Object.freeze({
|
|
1300
|
+
...nested.plan,
|
|
1301
|
+
predicates: Object.freeze([...nested.plan.predicates, mode === "every" ? {
|
|
1302
|
+
kind: "notTrue",
|
|
1303
|
+
predicate: description
|
|
1304
|
+
} : description])
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
return predicate({
|
|
1308
|
+
kind: "exists",
|
|
1309
|
+
query: Object.freeze({
|
|
1310
|
+
...query,
|
|
1311
|
+
ordering: Object.freeze([]),
|
|
1312
|
+
selection: presentSelection
|
|
1313
|
+
}),
|
|
1314
|
+
negated: mode !== "some"
|
|
1315
|
+
});
|
|
1316
|
+
};
|
|
1317
|
+
const aggregate = (operation, callback) => {
|
|
1318
|
+
const { nested, result } = evaluate(callback);
|
|
1319
|
+
const expression = readColumn(result);
|
|
1320
|
+
const query = nested.plan;
|
|
1321
|
+
const source = query.limit !== void 0 || query.offset !== void 0 || query.grouping.length > 0 || query.distinct ? derivedBinding(Object.freeze({
|
|
1322
|
+
...query,
|
|
1323
|
+
selection: Object.freeze([{
|
|
1324
|
+
...expression,
|
|
1325
|
+
outputName: "value"
|
|
1326
|
+
}])
|
|
1327
|
+
}), "__symmetria_aggregate") : void 0;
|
|
1328
|
+
const selected = readColumn(operation(source ? createScope({ [source.alias]: source })[source.alias].value : result));
|
|
1329
|
+
return createExpression({
|
|
1330
|
+
...selected,
|
|
1331
|
+
node: Object.freeze({
|
|
1332
|
+
kind: "subquery",
|
|
1333
|
+
query: Object.freeze({
|
|
1334
|
+
...source ? initialPlan(source) : query,
|
|
1335
|
+
ordering: Object.freeze([]),
|
|
1336
|
+
selection: Object.freeze([selected])
|
|
1337
|
+
})
|
|
1338
|
+
})
|
|
1339
|
+
});
|
|
1340
|
+
};
|
|
1341
|
+
const aggregateMethod = (invoke) => {
|
|
1342
|
+
const target = registry.tablesByName.get(relation.target);
|
|
1343
|
+
let prototype = aggregatePrototypes.get(target);
|
|
1344
|
+
if (!prototype) {
|
|
1345
|
+
const source = registry.bindingFor(target.name, target.name);
|
|
1346
|
+
const names = Object.keys(createScope({ [source.alias]: source })[source.alias]);
|
|
1347
|
+
prototype = Object.freeze(Object.create(Function.prototype, Object.fromEntries(names.map((name) => [name, { get() {
|
|
1348
|
+
return this((columns) => columns[name]);
|
|
1349
|
+
} }]))));
|
|
1350
|
+
aggregatePrototypes.set(target, prototype);
|
|
1351
|
+
}
|
|
1352
|
+
Object.setPrototypeOf(invoke, prototype);
|
|
1353
|
+
for (const name of ["name", "length"]) {
|
|
1354
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
|
|
1355
|
+
if (descriptor) Object.defineProperty(invoke, name, descriptor);
|
|
1356
|
+
}
|
|
1357
|
+
return invoke;
|
|
1358
|
+
};
|
|
1359
|
+
const methods = callable((callback, options) => {
|
|
1360
|
+
const occurrence = queryOccurrence(current());
|
|
1361
|
+
const nested = createContext(registry, occurrence, context.bindings, depth + 1);
|
|
1362
|
+
const query = applyShape(nested, occurrence.bindings[related.alias], callback, options);
|
|
1363
|
+
if (!query.selection.length) return build(query, selectedAlias, true);
|
|
1364
|
+
return createExpression({
|
|
1365
|
+
outputName: selectedAlias,
|
|
1366
|
+
node: Object.freeze({
|
|
1367
|
+
kind: "jsonRows",
|
|
1368
|
+
query,
|
|
1369
|
+
many
|
|
1370
|
+
}),
|
|
1371
|
+
codec: jsonRowCodec(query.selection, many)
|
|
1372
|
+
});
|
|
1373
|
+
}, {
|
|
1374
|
+
...!filtered ? {
|
|
1375
|
+
[RELATION_SOURCE]: Object.freeze({
|
|
1376
|
+
from: binding.alias,
|
|
1377
|
+
relation: property,
|
|
1378
|
+
target: relation.target,
|
|
1379
|
+
alias: selectedAlias,
|
|
1380
|
+
owner: binding,
|
|
1381
|
+
nullable,
|
|
1382
|
+
explicitAlias: customAlias
|
|
1383
|
+
}),
|
|
1384
|
+
as: (alias) => {
|
|
1385
|
+
quoteIdentifier(alias);
|
|
1386
|
+
return build(plan, alias, false, true);
|
|
1387
|
+
}
|
|
1388
|
+
} : {},
|
|
1389
|
+
count: () => {
|
|
1390
|
+
const query = current();
|
|
1391
|
+
const counted = query.limit !== void 0 || query.offset !== void 0 || query.grouping.length > 0 || query.having.length > 0 || query.distinct;
|
|
1392
|
+
return createExpression({
|
|
1393
|
+
...readColumn(count()),
|
|
1394
|
+
node: Object.freeze({
|
|
1395
|
+
kind: counted ? "rowCount" : "subquery",
|
|
1396
|
+
query: Object.freeze({
|
|
1397
|
+
...query,
|
|
1398
|
+
...counted ? {} : { ordering: Object.freeze([]) },
|
|
1399
|
+
selection: counted ? query.distinct ? query.grouping.length ? query.grouping : readSelection(createScope({ [query.root.alias]: query.root })[query.root.alias], query.bindings) : presentSelection : Object.freeze([readColumn(count())])
|
|
1400
|
+
})
|
|
1401
|
+
})
|
|
1402
|
+
});
|
|
1403
|
+
},
|
|
1404
|
+
sum: aggregateMethod((callback) => aggregate(sum, callback)),
|
|
1405
|
+
average: aggregateMethod((callback) => aggregate(average, callback)),
|
|
1406
|
+
minimum: aggregateMethod((callback) => aggregate(minimum, callback)),
|
|
1407
|
+
maximum: aggregateMethod((callback) => aggregate(maximum, callback)),
|
|
1408
|
+
exists: () => createExpression({
|
|
1409
|
+
outputName: "exists",
|
|
1410
|
+
codec: booleanCodec,
|
|
1411
|
+
node: Object.freeze({
|
|
1412
|
+
kind: "raw",
|
|
1413
|
+
sqlType: "boolean",
|
|
1414
|
+
parts: Object.freeze(["EXISTS ", {
|
|
1415
|
+
kind: "subquery",
|
|
1416
|
+
query: Object.freeze({
|
|
1417
|
+
...current(),
|
|
1418
|
+
selection: presentSelection
|
|
1419
|
+
})
|
|
1420
|
+
}])
|
|
1421
|
+
})
|
|
1422
|
+
}),
|
|
1423
|
+
some: (callback) => quantified("some", callback),
|
|
1424
|
+
none: (callback) => quantified("none", callback),
|
|
1425
|
+
every: (callback) => quantified("every", callback)
|
|
1426
|
+
}, true);
|
|
1427
|
+
if (filtered || many) return methods;
|
|
1428
|
+
return new Proxy(methods, { get: (target, name) => {
|
|
1429
|
+
if (typeof name !== "string" || name !== "name" && name !== "length" && Object.hasOwn(target, name)) return Reflect.get(target, name);
|
|
1430
|
+
const table = registry.tablesByName.get(relation.target);
|
|
1431
|
+
const members = memberNames(table);
|
|
1432
|
+
if (!members.includes(name) && !table.relations.some((relation) => relation.name === name)) {
|
|
1433
|
+
if (isSilentMember(name)) return;
|
|
1434
|
+
throw unknownMember(table, name, members);
|
|
1435
|
+
}
|
|
1436
|
+
return pathColumns(selectedAlias, customAlias)[name];
|
|
1437
|
+
} });
|
|
1438
|
+
};
|
|
1439
|
+
const result = build();
|
|
1440
|
+
relationships.set(property, result);
|
|
1441
|
+
return result;
|
|
1442
|
+
} });
|
|
1443
|
+
views.set(binding, view);
|
|
1444
|
+
return view;
|
|
1445
|
+
};
|
|
1446
|
+
return context;
|
|
1447
|
+
};
|
|
1448
|
+
//#endregion
|
|
1449
|
+
//#region src/query/select/pagination.ts
|
|
1450
|
+
/** True when the expression reads root columns only: it can be re-evaluated per row by the cursor predicate. */
|
|
1451
|
+
const rootExpression = (node, root) => {
|
|
1452
|
+
switch (node.kind) {
|
|
1453
|
+
case "column": return node.description.binding === root;
|
|
1454
|
+
case "parameter":
|
|
1455
|
+
case "placeholder": return true;
|
|
1456
|
+
case "case": return rootExpression(node.value, root) && node.branches.every((branch) => rootExpression(branch.when, root) && rootExpression(branch.then, root));
|
|
1457
|
+
case "coalesce":
|
|
1458
|
+
case "tuple": return node.values.every((value) => rootExpression(value, root));
|
|
1459
|
+
case "binary": return rootExpression(node.left, root) && rootExpression(node.right, root);
|
|
1460
|
+
case "raw": return node.parts.every((part) => typeof part === "string" || rootExpression(part, root));
|
|
1461
|
+
case "jsonPath":
|
|
1462
|
+
case "arrayIndex":
|
|
1463
|
+
case "arrayLength": return rootExpression(node.value, root);
|
|
1464
|
+
default: return false;
|
|
1465
|
+
}
|
|
1466
|
+
};
|
|
1467
|
+
const containsWindow = (node) => {
|
|
1468
|
+
switch (node.kind) {
|
|
1469
|
+
case "window": return true;
|
|
1470
|
+
case "jsonObject": return node.selection.some((expression) => containsWindow(expression.node));
|
|
1471
|
+
case "case": return containsWindow(node.value) || node.branches.some((branch) => containsWindow(branch.when) || containsWindow(branch.then));
|
|
1472
|
+
case "coalesce":
|
|
1473
|
+
case "tuple": return node.values.some(containsWindow);
|
|
1474
|
+
case "binary": return containsWindow(node.left) || containsWindow(node.right);
|
|
1475
|
+
case "raw": return node.parts.some((part) => typeof part !== "string" && containsWindow(part));
|
|
1476
|
+
case "jsonPath":
|
|
1477
|
+
case "arrayIndex":
|
|
1478
|
+
case "arrayLength": return containsWindow(node.value);
|
|
1479
|
+
default: return false;
|
|
1480
|
+
}
|
|
1481
|
+
};
|
|
1482
|
+
/** Apply keyset predicates after windows have seen the complete filtered input. */
|
|
1483
|
+
const windowPagePlan = (plan) => {
|
|
1484
|
+
const occupied = new Set(plan.selection.map((expression) => expression.outputName));
|
|
1485
|
+
const keys = plan.ordering.map((ordering, position) => {
|
|
1486
|
+
let name = `__symmetria_order_${position}`;
|
|
1487
|
+
while (occupied.has(name)) name += "_";
|
|
1488
|
+
occupied.add(name);
|
|
1489
|
+
return {
|
|
1490
|
+
...ordering.expression,
|
|
1491
|
+
outputName: name
|
|
1492
|
+
};
|
|
1493
|
+
});
|
|
1494
|
+
const root = derivedBinding({
|
|
1495
|
+
...plan,
|
|
1496
|
+
selection: [...plan.selection, ...keys],
|
|
1497
|
+
ordering: []
|
|
1498
|
+
}, "__symmetria_page");
|
|
1499
|
+
const column = (name) => ({
|
|
1500
|
+
kind: "column",
|
|
1501
|
+
description: {
|
|
1502
|
+
binding: root,
|
|
1503
|
+
column: root.table.columns.find((column) => column.name === name)
|
|
1504
|
+
}
|
|
1505
|
+
});
|
|
1506
|
+
return {
|
|
1507
|
+
...plan,
|
|
1508
|
+
root,
|
|
1509
|
+
bindings: { [root.alias]: root },
|
|
1510
|
+
predicates: [],
|
|
1511
|
+
selection: plan.selection.map((expression) => ({
|
|
1512
|
+
...expression,
|
|
1513
|
+
node: column(expression.outputName)
|
|
1514
|
+
})),
|
|
1515
|
+
ordering: plan.ordering.map((ordering, position) => ({
|
|
1516
|
+
...ordering,
|
|
1517
|
+
expression: {
|
|
1518
|
+
...ordering.expression,
|
|
1519
|
+
node: column(keys[position].outputName)
|
|
1520
|
+
}
|
|
1521
|
+
}))
|
|
1522
|
+
};
|
|
1523
|
+
};
|
|
1524
|
+
const TIMESTAMP = /^(\d{4,})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}(?::?\d{2}){0,2})?(?: BC)?$/;
|
|
1525
|
+
const fingerprints = /* @__PURE__ */ new WeakMap();
|
|
1526
|
+
/** Cursor values are text renderings of the ordering columns; reject ones PostgreSQL could not cast back. */
|
|
1527
|
+
const cursorValueMatches = (sqlType, value) => {
|
|
1528
|
+
const type = sqlType.toLowerCase();
|
|
1529
|
+
if (/^(?:smallint|integer|int|bigint|int[248])$/.test(type)) return /^-?\d{1,19}$/.test(value);
|
|
1530
|
+
if (/^(?:numeric|decimal)/.test(type) || /^(?:real|double precision)$/.test(type)) return /^(?:NaN|-?Infinity|-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)$/i.test(value);
|
|
1531
|
+
if (/^(?:timestamptz|timestamp|date)/.test(type)) {
|
|
1532
|
+
if (value === "infinity" || value === "-infinity") return true;
|
|
1533
|
+
const parts = TIMESTAMP.exec(value);
|
|
1534
|
+
return !!parts && Number(parts[2]) >= 1 && Number(parts[2]) <= 12 && Number(parts[3]) >= 1 && Number(parts[3]) <= 31 && Number(parts[4] ?? 0) <= 23 && Number(parts[5] ?? 0) <= 59 && Number(parts[6] ?? 0) <= 60;
|
|
1535
|
+
}
|
|
1536
|
+
if (type === "uuid") return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
|
|
1537
|
+
if (type === "boolean" || type === "bool") return /^(?:t|f|true|false|0|1)$/.test(value);
|
|
1538
|
+
return true;
|
|
1539
|
+
};
|
|
1540
|
+
/** The reverse of an ORDER BY entry; an implicit NULLS placement is made explicit first so it flips too. */
|
|
1541
|
+
const reversed = (ordering) => {
|
|
1542
|
+
const nulls = ordering.nulls ?? postgresRenderer.nullsDefault(ordering.direction);
|
|
1543
|
+
return {
|
|
1544
|
+
...ordering,
|
|
1545
|
+
direction: ordering.direction === "ASC" ? "DESC" : "ASC",
|
|
1546
|
+
nulls: nulls === "FIRST" ? "LAST" : "FIRST"
|
|
1547
|
+
};
|
|
1548
|
+
};
|
|
1549
|
+
const executePage = async (plan, options, executor) => {
|
|
1550
|
+
if (!Number.isSafeInteger(options.size) || options.size < 1 || options.size >= Number.MAX_SAFE_INTEGER) throw new Error("symmetria: page size must be a positive safe integer");
|
|
1551
|
+
if (options.after != null && options.before != null) throw new Error("symmetria: page() accepts either after or before, not both");
|
|
1552
|
+
const backward = options.before != null;
|
|
1553
|
+
const cursor = backward ? options.before : options.after;
|
|
1554
|
+
if (plan.joins.length || plan.grouping.length || plan.having.length || plan.distinct || plan.root.derived || plan.offset !== void 0 || plan.limit !== void 0) throw new Error("symmetria: page() requires an ungrouped root-table query without joins, LIMIT or OFFSET");
|
|
1555
|
+
const columns = plan.ordering.map((ordering, position) => {
|
|
1556
|
+
const node = ordering.expression.node;
|
|
1557
|
+
if (node.kind === "column" && node.description.binding === plan.root) return node.description.column;
|
|
1558
|
+
if (!rootExpression(node, plan.root)) throw new Error("symmetria: page() ORDER BY accepts root columns and expressions over them only");
|
|
1559
|
+
return {
|
|
1560
|
+
name: `__symmetria_expression_${position}`,
|
|
1561
|
+
sqlType: expressionSqlType(ordering.expression),
|
|
1562
|
+
notNull: false,
|
|
1563
|
+
unique: false,
|
|
1564
|
+
expression: true
|
|
1565
|
+
};
|
|
1566
|
+
});
|
|
1567
|
+
const names = columns.map((column) => column.name);
|
|
1568
|
+
const keys = plan.root.table.columns.filter((column) => column.primaryKey);
|
|
1569
|
+
if (!names.length || new Set(names).size !== names.length || !(keys.length && keys.every((column) => names.includes(column.name)) || columns.some((column) => column.unique && column.notNull))) throw new Error("symmetria: page() ORDER BY must include a complete primary key or a non-null unique column");
|
|
1570
|
+
let fingerprint = fingerprints.get(plan);
|
|
1571
|
+
if (!fingerprint) {
|
|
1572
|
+
fingerprint = createHash("sha256").update(JSON.stringify(compilePlan(plan), (_name, value) => typeof value === "bigint" ? { bigint: String(value) } : value)).digest("hex");
|
|
1573
|
+
fingerprints.set(plan, fingerprint);
|
|
1574
|
+
}
|
|
1575
|
+
const declaredPlan = plan.selection.some((expression) => containsWindow(expression.node)) ? windowPagePlan(plan) : plan;
|
|
1576
|
+
const pagePlan = backward ? {
|
|
1577
|
+
...declaredPlan,
|
|
1578
|
+
ordering: declaredPlan.ordering.map(reversed)
|
|
1579
|
+
} : declaredPlan;
|
|
1580
|
+
const predicates = [...pagePlan.predicates];
|
|
1581
|
+
const cursorValue = (value, position) => {
|
|
1582
|
+
const column = columns[position];
|
|
1583
|
+
return {
|
|
1584
|
+
kind: "parameter",
|
|
1585
|
+
value,
|
|
1586
|
+
...["json", "jsonb"].includes(column.sqlType) ? { cast: column.sqlType } : {}
|
|
1587
|
+
};
|
|
1588
|
+
};
|
|
1589
|
+
if (cursor != null) {
|
|
1590
|
+
let values;
|
|
1591
|
+
try {
|
|
1592
|
+
if (typeof cursor !== "string" || cursor.length > 65536 || !/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error();
|
|
1593
|
+
const decoded = JSON.parse(Buffer.from(cursor, "base64url").toString());
|
|
1594
|
+
if (decoded.version !== 1 || decoded.query !== fingerprint || !Array.isArray(decoded.values) || decoded.values.length !== columns.length || decoded.values.some((value, position) => value === null ? columns[position].notNull : typeof value !== "string" || !cursorValueMatches(columns[position].sqlType, value))) throw new Error();
|
|
1595
|
+
values = decoded.values;
|
|
1596
|
+
} catch {
|
|
1597
|
+
throw new Error("symmetria: invalid page cursor or cursor from another query");
|
|
1598
|
+
}
|
|
1599
|
+
if (columns.every((column) => column.notNull) && pagePlan.ordering.every((ordering) => ordering.direction === pagePlan.ordering[0].direction)) {
|
|
1600
|
+
const tuple = (nodes) => nodes.length === 1 ? nodes[0] : {
|
|
1601
|
+
kind: "tuple",
|
|
1602
|
+
values: nodes
|
|
1603
|
+
};
|
|
1604
|
+
predicates.push({
|
|
1605
|
+
kind: "comparison",
|
|
1606
|
+
left: tuple(pagePlan.ordering.map((ordering) => ordering.expression.node)),
|
|
1607
|
+
operator: pagePlan.ordering[0].direction === "ASC" ? ">" : "<",
|
|
1608
|
+
right: tuple(values.map(cursorValue))
|
|
1609
|
+
});
|
|
1610
|
+
} else {
|
|
1611
|
+
const branches = [];
|
|
1612
|
+
const prefix = [];
|
|
1613
|
+
pagePlan.ordering.forEach((ordering, position) => {
|
|
1614
|
+
const expression = ordering.expression;
|
|
1615
|
+
const value = values[position];
|
|
1616
|
+
const nullsFirst = (ordering.nulls ?? postgresRenderer.nullsDefault(ordering.direction)) === "FIRST";
|
|
1617
|
+
const following = value === null ? nullsFirst ? {
|
|
1618
|
+
kind: "nullCheck",
|
|
1619
|
+
value: expression.node,
|
|
1620
|
+
negated: true
|
|
1621
|
+
} : {
|
|
1622
|
+
kind: "group",
|
|
1623
|
+
operator: "OR",
|
|
1624
|
+
predicates: []
|
|
1625
|
+
} : {
|
|
1626
|
+
kind: "group",
|
|
1627
|
+
operator: "OR",
|
|
1628
|
+
predicates: [{
|
|
1629
|
+
kind: "comparison",
|
|
1630
|
+
left: expression.node,
|
|
1631
|
+
operator: ordering.direction === "ASC" ? ">" : "<",
|
|
1632
|
+
right: cursorValue(value, position)
|
|
1633
|
+
}, ...!nullsFirst && !columns[position].notNull ? [{
|
|
1634
|
+
kind: "nullCheck",
|
|
1635
|
+
value: expression.node,
|
|
1636
|
+
negated: false
|
|
1637
|
+
}] : []]
|
|
1638
|
+
};
|
|
1639
|
+
branches.push({
|
|
1640
|
+
kind: "group",
|
|
1641
|
+
operator: "AND",
|
|
1642
|
+
predicates: [...prefix, following]
|
|
1643
|
+
});
|
|
1644
|
+
prefix.push({
|
|
1645
|
+
kind: "comparison",
|
|
1646
|
+
left: expression.node,
|
|
1647
|
+
operator: "IS NOT DISTINCT FROM",
|
|
1648
|
+
right: cursorValue(value, position)
|
|
1649
|
+
});
|
|
1650
|
+
});
|
|
1651
|
+
predicates.push({
|
|
1652
|
+
kind: "group",
|
|
1653
|
+
operator: "OR",
|
|
1654
|
+
predicates: branches
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
const occupied = new Set(plan.selection.map((expression) => expression.outputName));
|
|
1659
|
+
const textCast = postgresRenderer.textCast;
|
|
1660
|
+
const hidden = pagePlan.ordering.map((ordering, position) => {
|
|
1661
|
+
let name = `__symmetria_cursor_${position}`;
|
|
1662
|
+
while (occupied.has(name)) name += "_";
|
|
1663
|
+
occupied.add(name);
|
|
1664
|
+
return {
|
|
1665
|
+
outputName: name,
|
|
1666
|
+
node: {
|
|
1667
|
+
kind: "raw",
|
|
1668
|
+
parts: [
|
|
1669
|
+
...textCast.prefix ? [textCast.prefix] : [],
|
|
1670
|
+
ordering.expression.node,
|
|
1671
|
+
textCast.suffix
|
|
1672
|
+
]
|
|
1673
|
+
}
|
|
1674
|
+
};
|
|
1675
|
+
});
|
|
1676
|
+
const result = await executePlan({
|
|
1677
|
+
...pagePlan,
|
|
1678
|
+
selection: [...pagePlan.selection, ...hidden],
|
|
1679
|
+
predicates,
|
|
1680
|
+
limit: options.size + 1
|
|
1681
|
+
}, executor);
|
|
1682
|
+
const fetched = result.rows.slice(0, options.size);
|
|
1683
|
+
const more = result.rows.length > options.size;
|
|
1684
|
+
const rows = backward ? fetched.reverse() : fetched;
|
|
1685
|
+
const encode = (row) => Buffer.from(JSON.stringify({
|
|
1686
|
+
version: 1,
|
|
1687
|
+
query: fingerprint,
|
|
1688
|
+
values: hidden.map((expression) => row[expression.outputName])
|
|
1689
|
+
})).toString("base64url");
|
|
1690
|
+
const first = rows[0];
|
|
1691
|
+
const last = rows.at(-1);
|
|
1692
|
+
const nextCursor = last && (backward || more) ? encode(last) : null;
|
|
1693
|
+
const previousCursor = first && (backward ? more : options.after != null) ? encode(first) : null;
|
|
1694
|
+
return {
|
|
1695
|
+
items: rows.map((row) => Object.fromEntries(plan.selection.map((expression) => [expression.outputName, row[expression.outputName]]))),
|
|
1696
|
+
nextCursor,
|
|
1697
|
+
previousCursor
|
|
1698
|
+
};
|
|
1699
|
+
};
|
|
1700
|
+
//#endregion
|
|
1701
|
+
//#region src/query/select/query.ts
|
|
1702
|
+
/** Query handles: the shared prototype of every query and the callable that extends it. */
|
|
1703
|
+
/** Query handles share one prototype per database so methods stay cached. */
|
|
1704
|
+
let streamOrdinal = 0;
|
|
1705
|
+
/**
|
|
1706
|
+
* Rows through a server-side cursor on a reserved connection. The hold callback
|
|
1707
|
+
* publishes the connection's executor and stays open until iteration finishes,
|
|
1708
|
+
* so an early `break` or an error ends the transaction and frees the connection.
|
|
1709
|
+
*/
|
|
1710
|
+
async function* streamRows(hold, plan, size) {
|
|
1711
|
+
const compiled = compilePlan(plan);
|
|
1712
|
+
const decode = rowDecoder(plan);
|
|
1713
|
+
const cursor = quoteIdentifier(`__symmetria_stream_${++streamOrdinal}`);
|
|
1714
|
+
const ready = Promise.withResolvers();
|
|
1715
|
+
const finished = Promise.withResolvers();
|
|
1716
|
+
const held = hold(async (execute) => {
|
|
1717
|
+
ready.resolve(execute);
|
|
1718
|
+
await finished.promise;
|
|
1719
|
+
});
|
|
1720
|
+
held.catch(() => {});
|
|
1721
|
+
let failure;
|
|
1722
|
+
let failed = false;
|
|
1723
|
+
let execute;
|
|
1724
|
+
let declared = false;
|
|
1725
|
+
try {
|
|
1726
|
+
execute = await Promise.race([ready.promise, held.then(() => {
|
|
1727
|
+
throw new Error("symmetria: the stream connection closed early");
|
|
1728
|
+
})]);
|
|
1729
|
+
await execute({
|
|
1730
|
+
sql: `DECLARE ${cursor} NO SCROLL CURSOR FOR ${compiled.sql}`,
|
|
1731
|
+
parameters: compiled.parameters
|
|
1732
|
+
});
|
|
1733
|
+
declared = true;
|
|
1734
|
+
while (true) {
|
|
1735
|
+
const { rows } = normalizeResult(await execute({
|
|
1736
|
+
sql: `FETCH FORWARD ${size} FROM ${cursor}`,
|
|
1737
|
+
parameters: []
|
|
1738
|
+
}));
|
|
1739
|
+
for (const row of rows) yield decode(row);
|
|
1740
|
+
if (rows.length < size) break;
|
|
1741
|
+
}
|
|
1742
|
+
} catch (error) {
|
|
1743
|
+
failure = error;
|
|
1744
|
+
failed = true;
|
|
1745
|
+
throw error;
|
|
1746
|
+
} finally {
|
|
1747
|
+
if (!failed && declared && execute) try {
|
|
1748
|
+
await execute({
|
|
1749
|
+
sql: `CLOSE ${cursor}`,
|
|
1750
|
+
parameters: []
|
|
1751
|
+
});
|
|
1752
|
+
} catch (error) {
|
|
1753
|
+
failure = error;
|
|
1754
|
+
failed = true;
|
|
1755
|
+
}
|
|
1756
|
+
if (failed) finished.reject(failure);
|
|
1757
|
+
else finished.resolve();
|
|
1758
|
+
await held.catch(() => {});
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
const createQueryFactory = (registry, executor, profile, hold) => {
|
|
1762
|
+
const startPlan = (state, allowScopedAlias, freshSource) => {
|
|
1763
|
+
if (!freshSource) return state;
|
|
1764
|
+
const root = Object.freeze({ ...state.root });
|
|
1765
|
+
return allowScopedAlias ? registry.scopedPlan(root) : initialPlan(root);
|
|
1766
|
+
};
|
|
1767
|
+
const single = async (state, required) => {
|
|
1768
|
+
if (typeof state.limit === "object") throw new Error("symmetria: bind a parameterized LIMIT with prepare()");
|
|
1769
|
+
const rows = (await executePlan(limitedPlan(state, 2), executor)).rows;
|
|
1770
|
+
if (rows.length > 1 || required && !rows.length) throw new Error(`symmetria: expected ${required ? "exactly one" : "at most one"} row, received ${rows.length}`);
|
|
1771
|
+
return rows[0] ?? null;
|
|
1772
|
+
};
|
|
1773
|
+
/** Every query is a callable whose methods live on one shared prototype. */
|
|
1774
|
+
const queryPrototype = Object.freeze(Object.create(Function.prototype, boundMethodDescriptors({
|
|
1775
|
+
get [QUERY_PLAN]() {
|
|
1776
|
+
return this[QUERY_STATE].plan;
|
|
1777
|
+
},
|
|
1778
|
+
get [TABLE_SOURCE]() {
|
|
1779
|
+
const state = this[QUERY_STATE];
|
|
1780
|
+
return state.source ??= Object.freeze({
|
|
1781
|
+
binding: state.plan.root,
|
|
1782
|
+
schema: registry.snapshot
|
|
1783
|
+
});
|
|
1784
|
+
},
|
|
1785
|
+
cte(name, options = {}) {
|
|
1786
|
+
const state = this[QUERY_STATE].plan;
|
|
1787
|
+
if (!state.selection.length) throw new Error("symmetria: a CTE requires selected fields");
|
|
1788
|
+
if (options.materialized !== void 0 && typeof options.materialized !== "boolean") throw new Error("symmetria: materialized must be a boolean");
|
|
1789
|
+
const { derived: _query, ...binding } = derivedBinding(state, name);
|
|
1790
|
+
const identity = Object.freeze({});
|
|
1791
|
+
const definition = Object.freeze({
|
|
1792
|
+
name,
|
|
1793
|
+
identity,
|
|
1794
|
+
query: state,
|
|
1795
|
+
...options.materialized === void 0 ? {} : { materialized: options.materialized }
|
|
1796
|
+
});
|
|
1797
|
+
return createQuery(initialPlan(Object.freeze({
|
|
1798
|
+
...binding,
|
|
1799
|
+
cte: definition,
|
|
1800
|
+
cteReference: {
|
|
1801
|
+
name,
|
|
1802
|
+
identity
|
|
1803
|
+
}
|
|
1804
|
+
})), false, true);
|
|
1805
|
+
},
|
|
1806
|
+
recursive(name, step, options = {}) {
|
|
1807
|
+
const state = this[QUERY_STATE].plan;
|
|
1808
|
+
if (!state.selection.length) throw new Error("symmetria: a recursive CTE requires a selected anchor");
|
|
1809
|
+
if (options.unionAll !== void 0 && typeof options.unionAll !== "boolean") throw new Error("symmetria: unionAll must be a boolean");
|
|
1810
|
+
const { derived: _query, ...binding } = derivedBinding(state, name);
|
|
1811
|
+
const identity = Object.freeze({});
|
|
1812
|
+
const reference = Object.freeze({
|
|
1813
|
+
...binding,
|
|
1814
|
+
cteReference: {
|
|
1815
|
+
name,
|
|
1816
|
+
identity
|
|
1817
|
+
}
|
|
1818
|
+
});
|
|
1819
|
+
const recursive = step(createQuery(initialPlan(reference), false, true))?.[QUERY_PLAN];
|
|
1820
|
+
if (!recursive || recursive.selection.length !== state.selection.length || recursive.selection.some((expression, position) => expression.outputName !== state.selection[position].outputName)) throw new Error("symmetria: recursive term must select the same fields in the same order as its anchor");
|
|
1821
|
+
const definition = Object.freeze({
|
|
1822
|
+
name,
|
|
1823
|
+
identity,
|
|
1824
|
+
query: state,
|
|
1825
|
+
recursive,
|
|
1826
|
+
unionAll: options.unionAll ?? true
|
|
1827
|
+
});
|
|
1828
|
+
return createQuery(initialPlan(Object.freeze({
|
|
1829
|
+
...reference,
|
|
1830
|
+
cte: definition
|
|
1831
|
+
})), false, true);
|
|
1832
|
+
},
|
|
1833
|
+
as(name) {
|
|
1834
|
+
const { plan: state, allowScopedAlias } = this[QUERY_STATE];
|
|
1835
|
+
quoteIdentifier(name);
|
|
1836
|
+
if (state.selection.length) return createQuery(initialPlan(derivedBinding(state, name)), false, true);
|
|
1837
|
+
if (state.joins.length || state.predicates.length && !allowScopedAlias || state.grouping.length || state.ordering.length || state.having.length || state.limit !== void 0 || state.offset !== void 0 || state.distinct || state.locking) throw new Error("symmetria: alias the table before building the query, or select fields before creating a derived table");
|
|
1838
|
+
const binding = Object.freeze({
|
|
1839
|
+
...state.root,
|
|
1840
|
+
alias: name,
|
|
1841
|
+
explicitAlias: true
|
|
1842
|
+
});
|
|
1843
|
+
return createQuery(allowScopedAlias ? registry.scopedPlan(binding) : initialPlan(binding), allowScopedAlias, true);
|
|
1844
|
+
},
|
|
1845
|
+
scalar() {
|
|
1846
|
+
const state = this[QUERY_STATE].plan;
|
|
1847
|
+
if (state.selection.length !== 1) throw new Error("symmetria: scalar() requires one selected column");
|
|
1848
|
+
return createExpression({
|
|
1849
|
+
...state.selection[0],
|
|
1850
|
+
node: Object.freeze({
|
|
1851
|
+
kind: "subquery",
|
|
1852
|
+
query: state
|
|
1853
|
+
}),
|
|
1854
|
+
outputName: "scalar"
|
|
1855
|
+
});
|
|
1856
|
+
},
|
|
1857
|
+
toSQL() {
|
|
1858
|
+
return compilePlan(this[QUERY_STATE].plan);
|
|
1859
|
+
},
|
|
1860
|
+
prepare() {
|
|
1861
|
+
return preparePlan(this[QUERY_STATE].plan, executor);
|
|
1862
|
+
},
|
|
1863
|
+
[PREPARE_QUERY](scope, names) {
|
|
1864
|
+
return preparePlan(this[QUERY_STATE].plan, executor, scope, names);
|
|
1865
|
+
},
|
|
1866
|
+
async execute() {
|
|
1867
|
+
return (await executePlan(this[QUERY_STATE].plan, executor)).rows;
|
|
1868
|
+
},
|
|
1869
|
+
then(onFulfilled, onRejected) {
|
|
1870
|
+
return executePlan(this[QUERY_STATE].plan, executor).then(onFulfilled ? (result) => onFulfilled(result.rows) : resultRows, onRejected);
|
|
1871
|
+
},
|
|
1872
|
+
async inspect(options) {
|
|
1873
|
+
return (await import("./inspection-CXnLd3MA.js")).inspectQuery(this[QUERY_STATE].plan, executor, options);
|
|
1874
|
+
},
|
|
1875
|
+
one() {
|
|
1876
|
+
return single(this[QUERY_STATE].plan, true);
|
|
1877
|
+
},
|
|
1878
|
+
maybeOne() {
|
|
1879
|
+
return single(this[QUERY_STATE].plan, false);
|
|
1880
|
+
},
|
|
1881
|
+
page(options) {
|
|
1882
|
+
return executePage(this[QUERY_STATE].plan, options, executor);
|
|
1883
|
+
},
|
|
1884
|
+
pages(options) {
|
|
1885
|
+
const state = this[QUERY_STATE].plan;
|
|
1886
|
+
return { [Symbol.asyncIterator]: () => {
|
|
1887
|
+
let after = options.after ?? null;
|
|
1888
|
+
return { next: async () => {
|
|
1889
|
+
if (after === void 0) return {
|
|
1890
|
+
done: true,
|
|
1891
|
+
value: void 0
|
|
1892
|
+
};
|
|
1893
|
+
const page = await executePage(state, {
|
|
1894
|
+
size: options.size,
|
|
1895
|
+
after
|
|
1896
|
+
}, executor);
|
|
1897
|
+
after = page.nextCursor ?? void 0;
|
|
1898
|
+
return {
|
|
1899
|
+
done: false,
|
|
1900
|
+
value: page
|
|
1901
|
+
};
|
|
1902
|
+
} };
|
|
1903
|
+
} };
|
|
1904
|
+
},
|
|
1905
|
+
stream(options = {}) {
|
|
1906
|
+
const plan = this[QUERY_STATE].plan;
|
|
1907
|
+
const size = options.size ?? 1e3;
|
|
1908
|
+
if (!Number.isSafeInteger(size) || size < 1) throw new Error("symmetria: stream size must be a positive integer");
|
|
1909
|
+
if (!hold) throw new Error("symmetria: stream() requires a driver with transaction support");
|
|
1910
|
+
return { [Symbol.asyncIterator]: () => streamRows(hold, plan, size) };
|
|
1911
|
+
},
|
|
1912
|
+
async first() {
|
|
1913
|
+
const state = this[QUERY_STATE].plan;
|
|
1914
|
+
if (typeof state.limit === "object") throw new Error("symmetria: bind a parameterized LIMIT with prepare()");
|
|
1915
|
+
return (await executePlan(limitedPlan(state, 1), executor)).rows[0] ?? null;
|
|
1916
|
+
},
|
|
1917
|
+
async count() {
|
|
1918
|
+
return readCount((await executePlan(countPlan(this[QUERY_STATE].plan), executor)).rows);
|
|
1919
|
+
},
|
|
1920
|
+
async exists() {
|
|
1921
|
+
return readExists((await executePlan(existsPlan(this[QUERY_STATE].plan, false), executor)).rows);
|
|
1922
|
+
}
|
|
1923
|
+
})));
|
|
1924
|
+
const createQuery = (state, allowScopedAlias = false, freshSource = false, prototype = queryPrototype) => {
|
|
1925
|
+
const query = ((callback, options) => {
|
|
1926
|
+
const current = freshSource ? startPlan(state, allowScopedAlias, freshSource) : queryOccurrence(state);
|
|
1927
|
+
return createQuery(applyShape(createContext(registry, current), current.root, callback, options));
|
|
1928
|
+
});
|
|
1929
|
+
Object.setPrototypeOf(query, prototype);
|
|
1930
|
+
Object.defineProperty(query, QUERY_STATE, { value: {
|
|
1931
|
+
plan: state,
|
|
1932
|
+
allowScopedAlias,
|
|
1933
|
+
freshSource
|
|
1934
|
+
} });
|
|
1935
|
+
Object.freeze(query);
|
|
1936
|
+
return profile ? profile.trackBuilder(query) : query;
|
|
1937
|
+
};
|
|
1938
|
+
return {
|
|
1939
|
+
createQuery,
|
|
1940
|
+
queryPrototype
|
|
1941
|
+
};
|
|
1942
|
+
};
|
|
1943
|
+
//#endregion
|
|
1944
|
+
//#region src/query/select/registry.ts
|
|
1945
|
+
const createTableRegistry = (snapshot, codecs = {}, scopes = {}) => {
|
|
1946
|
+
const tablesByName = new Map(snapshot.tables.map((table) => [table.name, table]));
|
|
1947
|
+
const tableCodecs = /* @__PURE__ */ new Map();
|
|
1948
|
+
/** $scope() predicates apply wherever a scoped table enters a plan. */
|
|
1949
|
+
const scopePredicates = (binding) => {
|
|
1950
|
+
const scope = scopes[binding.table.name];
|
|
1951
|
+
if (!scope) return EMPTY;
|
|
1952
|
+
const columns = createScope({ [binding.alias]: binding })[binding.alias];
|
|
1953
|
+
return [readPredicate(scope(columns))];
|
|
1954
|
+
};
|
|
1955
|
+
const scopedPlan = (binding) => {
|
|
1956
|
+
const plan = initialPlan(binding);
|
|
1957
|
+
const predicates = scopePredicates(binding);
|
|
1958
|
+
return predicates.length ? Object.freeze({
|
|
1959
|
+
...plan,
|
|
1960
|
+
predicates: Object.freeze(predicates)
|
|
1961
|
+
}) : plan;
|
|
1962
|
+
};
|
|
1963
|
+
const bindingFor = (tableName, alias) => {
|
|
1964
|
+
quoteIdentifier(alias);
|
|
1965
|
+
const table = tablesByName.get(tableName);
|
|
1966
|
+
if (!table) throw new Error(`symmetria: unknown table "${tableName}"`);
|
|
1967
|
+
let resolvedCodecs = tableCodecs.get(tableName);
|
|
1968
|
+
if (!resolvedCodecs) {
|
|
1969
|
+
resolvedCodecs = Object.freeze(codecMap(Object.fromEntries(table.columns.flatMap((column) => {
|
|
1970
|
+
const codec = codecs[tableName]?.[column.name] ?? codecFor(column.sqlType);
|
|
1971
|
+
return codec ? [[column.name, codec]] : [];
|
|
1972
|
+
}))));
|
|
1973
|
+
tableCodecs.set(tableName, resolvedCodecs);
|
|
1974
|
+
}
|
|
1975
|
+
return Object.freeze({
|
|
1976
|
+
table,
|
|
1977
|
+
alias,
|
|
1978
|
+
codecs: resolvedCodecs
|
|
1979
|
+
});
|
|
1980
|
+
};
|
|
1981
|
+
return Object.freeze({
|
|
1982
|
+
snapshot,
|
|
1983
|
+
tablesByName,
|
|
1984
|
+
scopes,
|
|
1985
|
+
bindingFor,
|
|
1986
|
+
scopePredicates,
|
|
1987
|
+
scopedPlan
|
|
1988
|
+
});
|
|
1989
|
+
};
|
|
1990
|
+
//#endregion
|
|
1991
|
+
//#region src/query/select/tables.ts
|
|
1992
|
+
const createQueryTables = (snapshot, executor, codecs = {}, scopes = {}, atomic, hold) => {
|
|
1993
|
+
const profile = executorProfiling(executor);
|
|
1994
|
+
const registry = createTableRegistry(snapshot, codecs, scopes);
|
|
1995
|
+
const { createQuery, queryPrototype } = createQueryFactory(registry, executor, profile, hold);
|
|
1996
|
+
return Object.fromEntries(snapshot.tables.map((table) => {
|
|
1997
|
+
const root = registry.bindingFor(table.name, table.name);
|
|
1998
|
+
const mutationOptions = Object.freeze({
|
|
1999
|
+
...atomic ? { atomic } : {},
|
|
2000
|
+
scope: registry.scopePredicates(root),
|
|
2001
|
+
context: (plan) => createContext(registry, plan)
|
|
2002
|
+
});
|
|
2003
|
+
const lookupPrototype = Object.freeze(Object.create(queryPrototype, boundMethodDescriptors({
|
|
2004
|
+
update(values) {
|
|
2005
|
+
const plan = this[QUERY_STATE].plan;
|
|
2006
|
+
return createMutation("update", plan.root, values, executor, {
|
|
2007
|
+
...mutationOptions,
|
|
2008
|
+
scope: plan.predicates
|
|
2009
|
+
});
|
|
2010
|
+
},
|
|
2011
|
+
delete() {
|
|
2012
|
+
const plan = this[QUERY_STATE].plan;
|
|
2013
|
+
return createMutation("delete", plan.root, {}, executor, {
|
|
2014
|
+
...mutationOptions,
|
|
2015
|
+
scope: plan.predicates
|
|
2016
|
+
});
|
|
2017
|
+
}
|
|
2018
|
+
})));
|
|
2019
|
+
/**
|
|
2020
|
+
* Key lookups build their plan directly instead of materializing a column
|
|
2021
|
+
* scope; scoped tables and computed fields still need the full scope.
|
|
2022
|
+
*/
|
|
2023
|
+
const keyLookup = (keys, values) => {
|
|
2024
|
+
const binding = Object.freeze({ ...root });
|
|
2025
|
+
if (registry.scopes[table.name] || computedFields.get(table)?.length) {
|
|
2026
|
+
const columns = createScope({ [binding.alias]: binding })[binding.alias];
|
|
2027
|
+
return createQuery(Object.freeze({
|
|
2028
|
+
...initialPlan(binding),
|
|
2029
|
+
predicates: Object.freeze([...registry.scopePredicates(binding), ...keys.map((column, position) => readPredicate(columns[column.name].is(values[position])))]),
|
|
2030
|
+
selection: Object.freeze(Object.values(columns).map(readColumn))
|
|
2031
|
+
}), false, false, lookupPrototype);
|
|
2032
|
+
}
|
|
2033
|
+
const columnNode = (column) => Object.freeze({
|
|
2034
|
+
kind: "column",
|
|
2035
|
+
description: Object.freeze({
|
|
2036
|
+
binding,
|
|
2037
|
+
column
|
|
2038
|
+
})
|
|
2039
|
+
});
|
|
2040
|
+
const predicates = keys.map((column, position) => {
|
|
2041
|
+
const right = valueNode(values[position], binding.codecs[column.name]);
|
|
2042
|
+
return Object.freeze({
|
|
2043
|
+
kind: "comparison",
|
|
2044
|
+
left: columnNode(column),
|
|
2045
|
+
operator: "=",
|
|
2046
|
+
right,
|
|
2047
|
+
...right.kind === "placeholder" && right.nullable ? { nullableParameter: true } : {}
|
|
2048
|
+
});
|
|
2049
|
+
});
|
|
2050
|
+
const selection = table.columns.map((column) => {
|
|
2051
|
+
const codec = binding.codecs[column.name];
|
|
2052
|
+
return Object.freeze({
|
|
2053
|
+
node: columnNode(column),
|
|
2054
|
+
outputName: column.name,
|
|
2055
|
+
...codec ? { codec } : {}
|
|
2056
|
+
});
|
|
2057
|
+
});
|
|
2058
|
+
return createQuery(Object.freeze({
|
|
2059
|
+
...initialPlan(binding),
|
|
2060
|
+
predicates: Object.freeze(predicates),
|
|
2061
|
+
selection: Object.freeze(selection)
|
|
2062
|
+
}), false, false, lookupPrototype);
|
|
2063
|
+
};
|
|
2064
|
+
const uniqueLookup = (names, value) => {
|
|
2065
|
+
if (!names.length || names.length > 1 && (!value || typeof value !== "object" || Object.keys(value).length !== names.length || names.some((name) => !Object.hasOwn(value, name)))) throw new Error(`symmetria: unique lookup requires exactly these key fields: ${names.join(", ")}`);
|
|
2066
|
+
const values = names.map((name) => {
|
|
2067
|
+
const selected = names.length === 1 ? value : value[name];
|
|
2068
|
+
if (selected === null || selected === void 0) throw new Error(`symmetria: unique key "${name}" cannot be null or undefined`);
|
|
2069
|
+
return selected;
|
|
2070
|
+
});
|
|
2071
|
+
return keyLookup(names.map((name) => table.columns.find((column) => column.name === name)), values);
|
|
2072
|
+
};
|
|
2073
|
+
const uniqueKeys = new Map(table.columns.filter((column) => column.unique).map((column) => [column.name, [column.name]]));
|
|
2074
|
+
for (const definition of table.indexes ?? []) {
|
|
2075
|
+
if (!definition.unique || definition.where) continue;
|
|
2076
|
+
const columns = definition.keys.map((key) => table.columns.find((column) => quoteIdentifier(column.sqlName) === key)?.name);
|
|
2077
|
+
if (columns.every((name) => name !== void 0)) {
|
|
2078
|
+
if (uniqueKeys.has(definition.name)) throw new Error(`symmetria: duplicate unique lookup "${table.name}.${definition.name}"`);
|
|
2079
|
+
uniqueKeys.set(definition.name, columns);
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
return [table.name, extendBuilder(createQuery(registry.scopedPlan(root), true, true), {
|
|
2083
|
+
shape: (callback) => {
|
|
2084
|
+
if (typeof callback !== "function") throw new Error("symmetria: shape() requires a synchronous callback");
|
|
2085
|
+
return Object.freeze(Object.assign((columns, tools) => callback(columns, tools), { [SHAPE_SOURCE]: table }));
|
|
2086
|
+
},
|
|
2087
|
+
by: Object.freeze(Object.fromEntries([...uniqueKeys].map(([name, columns]) => [name, (value) => uniqueLookup(columns, value)]))),
|
|
2088
|
+
byId: (value) => {
|
|
2089
|
+
const keys = table.primaryKey ? table.primaryKey.map((name) => table.columns.find((column) => column.sqlName === name)) : table.columns.filter((column) => column.primaryKey);
|
|
2090
|
+
if (!keys.length) throw new Error(`symmetria: byId() requires a primary key on "${table.name}"`);
|
|
2091
|
+
if (keys.length > 1 && (!value || typeof value !== "object" || Object.keys(value).length !== keys.length || keys.some((column) => !Object.hasOwn(value, column.name)))) throw new Error(`symmetria: byId() requires exactly these key fields: ${keys.map((column) => column.name).join(", ")}`);
|
|
2092
|
+
const values = keys.map((column) => {
|
|
2093
|
+
const selected = keys.length === 1 ? value : value[column.name];
|
|
2094
|
+
if (selected === null || selected === void 0) throw new Error(`symmetria: primary key "${column.name}" cannot be null or undefined`);
|
|
2095
|
+
return selected;
|
|
2096
|
+
});
|
|
2097
|
+
return keyLookup(keys, values);
|
|
2098
|
+
},
|
|
2099
|
+
insert: (values) => createMutation("insert", root, values, executor, mutationOptions),
|
|
2100
|
+
update: (values) => createMutation("update", root, values, executor, mutationOptions),
|
|
2101
|
+
delete: () => createMutation("delete", root, {}, executor, mutationOptions)
|
|
2102
|
+
})];
|
|
2103
|
+
}));
|
|
2104
|
+
};
|
|
2105
|
+
//#endregion
|
|
2106
|
+
//#region src/query/write/nested-inserts.ts
|
|
2107
|
+
/**
|
|
2108
|
+
* Nested inserts: writes a parent row and its related rows in one transaction, resolving generated keys.
|
|
2109
|
+
*/
|
|
2110
|
+
const uniqueKeys = (table) => {
|
|
2111
|
+
const primary = table.columns.filter((column) => column.primaryKey).map((column) => column.name);
|
|
2112
|
+
const keys = primary.length ? [primary] : [];
|
|
2113
|
+
keys.push(...table.columns.filter((column) => column.unique).map((column) => [column.name]));
|
|
2114
|
+
for (const definition of table.indexes ?? []) {
|
|
2115
|
+
if (!definition.unique || definition.where) continue;
|
|
2116
|
+
const names = definition.keys.map((key) => table.columns.find((column) => quoteIdentifier(column.sqlName) === key)?.name);
|
|
2117
|
+
if (names.every((name) => name !== void 0)) keys.push(names);
|
|
2118
|
+
}
|
|
2119
|
+
return keys;
|
|
2120
|
+
};
|
|
2121
|
+
const copyInput = (value, ancestors = /* @__PURE__ */ new Set()) => {
|
|
2122
|
+
if (!value || typeof value !== "object" || COLUMN_EXPRESSION in value) return value;
|
|
2123
|
+
if (value instanceof Date || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return cloneParameter(value);
|
|
2124
|
+
if (ancestors.has(value)) throw new Error("symmetria: cyclic nested insert input");
|
|
2125
|
+
ancestors.add(value);
|
|
2126
|
+
const result = Array.isArray(value) ? value.map((entry) => copyInput(entry, ancestors)) : Object.fromEntries(Object.entries(value).map(([name, entry]) => [name, copyInput(entry, ancestors)]));
|
|
2127
|
+
ancestors.delete(value);
|
|
2128
|
+
return Object.freeze(result);
|
|
2129
|
+
};
|
|
2130
|
+
/** Write payloads treat `undefined` as an omitted field or operation. */
|
|
2131
|
+
const definedEntries = (value) => Object.entries(value).filter(([, entry]) => entry !== void 0);
|
|
2132
|
+
/** Relational inserts are multi-statement operations and execute atomically. */
|
|
2133
|
+
/** Condition relations have no foreign key, so nested writes cannot target them. */
|
|
2134
|
+
const conditionWrite = (table, field) => /* @__PURE__ */ new Error(`symmetria: "${table}.${field}" is a condition relation; it has no foreign key to write`);
|
|
2135
|
+
const createNestedInsert = (snapshot, tableName, input, transaction, codecs) => {
|
|
2136
|
+
const tableByName = new Map(snapshot.tables.map((table) => [table.name, table]));
|
|
2137
|
+
const scalar = (name, column, value) => {
|
|
2138
|
+
const codec = codecs[name]?.[column];
|
|
2139
|
+
if (!codec || value === null || value === void 0 || typeof value === "symbol") return copyInput(value);
|
|
2140
|
+
return createExpression({
|
|
2141
|
+
outputName: column,
|
|
2142
|
+
node: valueNode(value, codec)
|
|
2143
|
+
});
|
|
2144
|
+
};
|
|
2145
|
+
/** The target column a foreign key points at, by TypeScript name. */
|
|
2146
|
+
const referencedName = (sourceName, foreignKey, targetName) => {
|
|
2147
|
+
const column = tableByName.get(sourceName).columns.find((entry) => entry.name === foreignKey);
|
|
2148
|
+
const target = tableByName.get(targetName).columns.find((entry) => entry.sqlName === column?.references?.column);
|
|
2149
|
+
if (!target) throw new Error(`symmetria: missing foreign key metadata for "${sourceName}.${foreignKey}"`);
|
|
2150
|
+
return target.name;
|
|
2151
|
+
};
|
|
2152
|
+
/**
|
|
2153
|
+
* The column a scalar connect value names: the referenced column of a forward
|
|
2154
|
+
* reference or of the junction's target key; children of reverse relations
|
|
2155
|
+
* connect by their primary key.
|
|
2156
|
+
*/
|
|
2157
|
+
const scalarKey = (sourceName, relation) => relation.kind === "through" ? referencedName(relation.junction, relation.targetForeignKey, relation.target) : relation.kind === "one" && !relation.reverse ? referencedName(sourceName, relation.foreignKey, relation.target) : void 0;
|
|
2158
|
+
const connect = (name, value, scalarColumn) => {
|
|
2159
|
+
const table = tableByName.get(name);
|
|
2160
|
+
if (value && typeof value === "object" && !(COLUMN_EXPRESSION in value) && uniqueKeys(table).some((key) => key.length === definedEntries(value).length && key.every((column) => value[column] !== void 0))) return Object.fromEntries(definedEntries(value).map(([column, entry]) => [column, scalar(name, column, entry)]));
|
|
2161
|
+
const primary = table.columns.filter((column) => column.primaryKey);
|
|
2162
|
+
if (scalarColumn !== void 0) return scalar(name, scalarColumn, value);
|
|
2163
|
+
return primary.length === 1 ? scalar(name, primary[0].name, value) : copyInput(value);
|
|
2164
|
+
};
|
|
2165
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
2166
|
+
const capture = (name, value) => {
|
|
2167
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return copyInput(value);
|
|
2168
|
+
if (ancestors.has(value)) throw new Error("symmetria: cyclic nested insert input");
|
|
2169
|
+
ancestors.add(value);
|
|
2170
|
+
const table = tableByName.get(name);
|
|
2171
|
+
const result = Object.fromEntries(definedEntries(value).map(([field, entry]) => {
|
|
2172
|
+
const relation = table.relations.find((relation) => relation.name === field);
|
|
2173
|
+
if (relation?.kind === "condition") throw conditionWrite(name, field);
|
|
2174
|
+
if (!relation || !entry || typeof entry !== "object" || Array.isArray(entry)) return [field, scalar(name, field, entry)];
|
|
2175
|
+
return [field, Object.fromEntries(definedEntries(entry).map(([operation, payload]) => {
|
|
2176
|
+
const target = (row) => operation === "connect" ? connect(relation.target, row, scalarKey(name, relation)) : capture(relation.target, row);
|
|
2177
|
+
return [operation, relation.kind === "one" || !Array.isArray(payload) ? target(payload) : payload.map(target)];
|
|
2178
|
+
}))];
|
|
2179
|
+
}));
|
|
2180
|
+
ancestors.delete(value);
|
|
2181
|
+
return Object.freeze(result);
|
|
2182
|
+
};
|
|
2183
|
+
const values = (Array.isArray(input) ? input : [input]).map((row) => capture(tableName, row));
|
|
2184
|
+
const build = (selector) => {
|
|
2185
|
+
const execute = () => transaction(async (database) => {
|
|
2186
|
+
const mutate = (name, kind, data) => {
|
|
2187
|
+
return database[name][kind](data);
|
|
2188
|
+
};
|
|
2189
|
+
const find = async (name, selection, scalarColumn) => {
|
|
2190
|
+
const table = tableByName.get(name);
|
|
2191
|
+
const primary = table.columns.filter((column) => column.primaryKey);
|
|
2192
|
+
const fields = selection !== null && typeof selection === "object" && !(COLUMN_EXPRESSION in selection) && !Array.isArray(selection) ? selection : scalarColumn !== void 0 ? { [scalarColumn]: selection } : primary.length === 1 ? { [primary[0].name]: selection } : {};
|
|
2193
|
+
const names = Object.keys(fields);
|
|
2194
|
+
if (!uniqueKeys(table).some((key) => key.length === names.length && key.every((column) => names.includes(column))) || names.some((column) => fields[column] === null || fields[column] === void 0)) throw new Error(`symmetria: connect on "${name}" requires a complete non-null unique key`);
|
|
2195
|
+
const rows = await database[name]((columns) => ({ ...columns }), {
|
|
2196
|
+
where: (columns) => and(...names.map((column) => columns[column].is(fields[column]))),
|
|
2197
|
+
limit: 2
|
|
2198
|
+
}).execute();
|
|
2199
|
+
if (rows.length !== 1) throw Object.assign(/* @__PURE__ */ new Error(`symmetria: connect on "${name}" expected one existing row`), { code: "SYMMETRIA_RECORD_NOT_FOUND" });
|
|
2200
|
+
return rows[0];
|
|
2201
|
+
};
|
|
2202
|
+
const attach = async (name, row, foreignKey, value) => {
|
|
2203
|
+
const primary = tableByName.get(name).columns.filter((column) => column.primaryKey);
|
|
2204
|
+
if (!primary.length) throw new Error(`symmetria: connect on "${name}" requires a primary key`);
|
|
2205
|
+
await mutate(name, "update", { [foreignKey]: value }).where((rowColumns) => and(...primary.map((column) => rowColumns[column.name].is(row[column.name])))).execute();
|
|
2206
|
+
};
|
|
2207
|
+
const insertRow = async (name, data, returning) => {
|
|
2208
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("symmetria: nested create requires a row object");
|
|
2209
|
+
const table = tableByName.get(name);
|
|
2210
|
+
const scalars = Object.create(null);
|
|
2211
|
+
const relations = [];
|
|
2212
|
+
for (const [field, value] of Object.entries(data)) {
|
|
2213
|
+
const relation = table.relations.find((entry) => entry.name === field);
|
|
2214
|
+
if (!relation) {
|
|
2215
|
+
scalars[field] = value;
|
|
2216
|
+
continue;
|
|
2217
|
+
}
|
|
2218
|
+
if (relation.kind === "condition") throw conditionWrite(name, field);
|
|
2219
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((operation) => ![
|
|
2220
|
+
"connect",
|
|
2221
|
+
"create",
|
|
2222
|
+
"connectOrCreate"
|
|
2223
|
+
].includes(operation))) throw new Error(`symmetria: invalid nested operation "${name}.${field}"`);
|
|
2224
|
+
const operations = value;
|
|
2225
|
+
if (relation.kind === "one" && Object.keys(operations).length !== 1) throw new Error(`symmetria: "${name}.${field}" requires exactly one nested operation`);
|
|
2226
|
+
relations.push([relation, operations]);
|
|
2227
|
+
}
|
|
2228
|
+
const resolveRow = async (target, operation, value, extra = {}, scalarColumn) => {
|
|
2229
|
+
if (operation === "connect") return find(target, value, scalarColumn);
|
|
2230
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`symmetria: ${operation} requires a row object`);
|
|
2231
|
+
if (Object.keys(extra).some((field) => Object.hasOwn(value, field))) throw new Error("symmetria: nested reverse create cannot supply its parent foreign key");
|
|
2232
|
+
const payload = {
|
|
2233
|
+
...value,
|
|
2234
|
+
...extra
|
|
2235
|
+
};
|
|
2236
|
+
if (operation === "create") return (await insertRow(target, payload)).row;
|
|
2237
|
+
const key = uniqueKeys(tableByName.get(target)).find((names) => names.every((field) => payload[field] !== null && payload[field] !== void 0));
|
|
2238
|
+
if (!key) throw new Error(`symmetria: connectOrCreate on "${target}" requires a non-null unique key`);
|
|
2239
|
+
return mutate(target, "insert", payload).onConflict(...key).doUpdate(...key).returning((row) => row).execute();
|
|
2240
|
+
};
|
|
2241
|
+
for (const [relation, operations] of relations) {
|
|
2242
|
+
if (relation.kind !== "one" || relation.reverse) continue;
|
|
2243
|
+
if (Object.hasOwn(data, relation.foreignKey)) throw new Error(`symmetria: supply either "${relation.name}" or "${relation.foreignKey}"`);
|
|
2244
|
+
const [operation, value] = Object.entries(operations)[0];
|
|
2245
|
+
const referenced = referencedName(name, relation.foreignKey, relation.target);
|
|
2246
|
+
const row = await resolveRow(relation.target, operation, value, {}, referenced);
|
|
2247
|
+
scalars[relation.foreignKey] = row[referenced];
|
|
2248
|
+
}
|
|
2249
|
+
const inserted = await mutate(name, "insert", scalars).returning((row) => {
|
|
2250
|
+
const selection = returning ? returningProjection(returning, row, table) : void 0;
|
|
2251
|
+
const result = Array.isArray(selection) ? Object.fromEntries(selection.map((column) => [readColumn(column).outputName, column])) : selection;
|
|
2252
|
+
return {
|
|
2253
|
+
row,
|
|
2254
|
+
...result ? { result } : {}
|
|
2255
|
+
};
|
|
2256
|
+
}).execute();
|
|
2257
|
+
const row = inserted.row;
|
|
2258
|
+
for (const [relation, operations] of relations) {
|
|
2259
|
+
if (relation.kind === "one" && !relation.reverse) continue;
|
|
2260
|
+
const parentKey = row[relation.kind === "through" ? referencedName(relation.junction, relation.sourceForeignKey, name) : referencedName(relation.target, relation.foreignKey, name)];
|
|
2261
|
+
for (const [operation, value] of Object.entries(operations)) {
|
|
2262
|
+
const entries = relation.kind === "one" ? [value] : value;
|
|
2263
|
+
if (!Array.isArray(entries)) throw new Error(`symmetria: collection "${name}.${relation.name}" requires arrays`);
|
|
2264
|
+
for (const entry of entries) {
|
|
2265
|
+
const extra = relation.kind === "through" ? {} : { [relation.foreignKey]: parentKey };
|
|
2266
|
+
const target = await resolveRow(relation.target, operation, entry, operation === "connect" ? {} : extra, scalarKey(name, relation));
|
|
2267
|
+
if (relation.kind === "through") await mutate(relation.junction, "insert", {
|
|
2268
|
+
[relation.sourceForeignKey]: parentKey,
|
|
2269
|
+
[relation.targetForeignKey]: target[referencedName(relation.junction, relation.targetForeignKey, relation.target)]
|
|
2270
|
+
}).onConflict(relation.sourceForeignKey, relation.targetForeignKey).doNothing().execute();
|
|
2271
|
+
else if (operation !== "create") await attach(relation.target, target, relation.foreignKey, parentKey);
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
return {
|
|
2276
|
+
row,
|
|
2277
|
+
...returning ? { result: inserted.result } : {}
|
|
2278
|
+
};
|
|
2279
|
+
};
|
|
2280
|
+
const results = [];
|
|
2281
|
+
for (const value of values) {
|
|
2282
|
+
const inserted = await insertRow(tableName, value, selector);
|
|
2283
|
+
if (selector) results.push(inserted.result);
|
|
2284
|
+
}
|
|
2285
|
+
if (!selector) return { affectedRows: values.length };
|
|
2286
|
+
return Array.isArray(input) ? results : results[0];
|
|
2287
|
+
});
|
|
2288
|
+
return Object.freeze({
|
|
2289
|
+
returning: (next) => build(next),
|
|
2290
|
+
execute,
|
|
2291
|
+
then: (onFulfilled, onRejected) => execute().then(onFulfilled, onRejected)
|
|
2292
|
+
});
|
|
2293
|
+
};
|
|
2294
|
+
return build();
|
|
2295
|
+
};
|
|
2296
|
+
//#endregion
|
|
2297
|
+
//#region src/schema/model.ts
|
|
2298
|
+
/**
|
|
2299
|
+
* Table identity comes from object keys. References carry
|
|
2300
|
+
* only that key, so contextual typing does not depend on another table's body.
|
|
2301
|
+
* Runtime lowering reuses the snapshot assembler; queries use the typed graph.
|
|
2302
|
+
*/
|
|
2303
|
+
const LINK = Symbol("symmetria.schema.link");
|
|
2304
|
+
const createLink = (target, flags) => {
|
|
2305
|
+
const withOptions = (options) => createLink(target, {
|
|
2306
|
+
...flags,
|
|
2307
|
+
...options
|
|
2308
|
+
});
|
|
2309
|
+
const link = {
|
|
2310
|
+
[LINK]: Object.freeze({
|
|
2311
|
+
target,
|
|
2312
|
+
flags: Object.freeze({
|
|
2313
|
+
nullable: false,
|
|
2314
|
+
unique: false,
|
|
2315
|
+
inverse: void 0,
|
|
2316
|
+
...flags
|
|
2317
|
+
})
|
|
2318
|
+
}),
|
|
2319
|
+
inverse: (name) => withOptions({ inverse: name }),
|
|
2320
|
+
by: (name) => withOptions({ by: name }),
|
|
2321
|
+
column: (sqlName) => withOptions({ column: sqlName })
|
|
2322
|
+
};
|
|
2323
|
+
Object.defineProperties(link, {
|
|
2324
|
+
nullable: {
|
|
2325
|
+
enumerable: true,
|
|
2326
|
+
get: () => withOptions({ nullable: true })
|
|
2327
|
+
},
|
|
2328
|
+
unique: {
|
|
2329
|
+
enumerable: true,
|
|
2330
|
+
get: () => withOptions({ unique: true })
|
|
2331
|
+
},
|
|
2332
|
+
index: {
|
|
2333
|
+
enumerable: true,
|
|
2334
|
+
get: () => withOptions({ index: true })
|
|
2335
|
+
},
|
|
2336
|
+
onDelete: {
|
|
2337
|
+
enumerable: true,
|
|
2338
|
+
get: () => Object.freeze(Object.defineProperties({}, {
|
|
2339
|
+
cascade: {
|
|
2340
|
+
enumerable: true,
|
|
2341
|
+
get: () => withOptions({ onDelete: "cascade" })
|
|
2342
|
+
},
|
|
2343
|
+
restrict: {
|
|
2344
|
+
enumerable: true,
|
|
2345
|
+
get: () => withOptions({ onDelete: "restrict" })
|
|
2346
|
+
},
|
|
2347
|
+
noAction: {
|
|
2348
|
+
enumerable: true,
|
|
2349
|
+
get: () => withOptions({ onDelete: "no action" })
|
|
2350
|
+
},
|
|
2351
|
+
setNull: {
|
|
2352
|
+
enumerable: true,
|
|
2353
|
+
get: () => withOptions({
|
|
2354
|
+
onDelete: "set null",
|
|
2355
|
+
nullable: true
|
|
2356
|
+
})
|
|
2357
|
+
}
|
|
2358
|
+
}))
|
|
2359
|
+
}
|
|
2360
|
+
});
|
|
2361
|
+
return Object.freeze(link);
|
|
2362
|
+
};
|
|
2363
|
+
const isLink = (value) => {
|
|
2364
|
+
return typeof value === "object" && value !== null && LINK in value;
|
|
2365
|
+
};
|
|
2366
|
+
/**
|
|
2367
|
+
* Infer key values and complete definitions through separate reverse maps.
|
|
2368
|
+
* Callback references can then carry scalar types without a circular dependency
|
|
2369
|
+
* on the complete relation graph.
|
|
2370
|
+
*/
|
|
2371
|
+
/** A thunk in a table body must yield a table; columns are declared directly. */
|
|
2372
|
+
const resolveThunk = (tableName, name, thunk) => {
|
|
2373
|
+
const result = thunk();
|
|
2374
|
+
if (isColumn(result)) throw new Error(`symmetria: "${tableName}.${name}": a thunk must return a table; declare the column directly (${name}: ${describeValue(result)})`);
|
|
2375
|
+
if (!isTable(result)) throw new Error(`symmetria: "${tableName}.${name}": a thunk must return a table (got ${describeValue(result)})`);
|
|
2376
|
+
return result;
|
|
2377
|
+
};
|
|
2378
|
+
const describeValue = (value) => {
|
|
2379
|
+
if (value === null) return "null";
|
|
2380
|
+
if (isColumn(value)) return `a ${value.definition.sqlType} column`;
|
|
2381
|
+
if (typeof value === "function") return `function ${value.name || "(anonymous)"}`;
|
|
2382
|
+
if (typeof value === "object") {
|
|
2383
|
+
const constructor = value.constructor?.name;
|
|
2384
|
+
return constructor && constructor !== "Object" ? `an instance of ${constructor}` : "a plain object";
|
|
2385
|
+
}
|
|
2386
|
+
return typeof value;
|
|
2387
|
+
};
|
|
2388
|
+
const createSchema = (definitions, options = {}) => {
|
|
2389
|
+
const tableNames = Object.keys(definitions);
|
|
2390
|
+
const references = Object.freeze(Object.fromEntries(tableNames.map((tableName) => [tableName, createLink(tableName, {})])));
|
|
2391
|
+
const tableIndexes = /* @__PURE__ */ new Map();
|
|
2392
|
+
const tableChecks = /* @__PURE__ */ new Map();
|
|
2393
|
+
const tableComputed = /* @__PURE__ */ new Map();
|
|
2394
|
+
const tableRelations = /* @__PURE__ */ new Map();
|
|
2395
|
+
const primaryKeys = /* @__PURE__ */ new Map();
|
|
2396
|
+
const junctionTables = /* @__PURE__ */ new Set();
|
|
2397
|
+
const tableNamesByState = /* @__PURE__ */ new Map();
|
|
2398
|
+
const tableNamesByRecord = /* @__PURE__ */ new Map();
|
|
2399
|
+
const rawDefinitions = Object.fromEntries(Object.entries(definitions).map(([tableName, definition]) => {
|
|
2400
|
+
const resolved = typeof definition === "function" ? definition(references) : definition;
|
|
2401
|
+
if (!isTable(resolved)) {
|
|
2402
|
+
if (resolved && typeof resolved === "object") tableNamesByRecord.set(resolved, [...tableNamesByRecord.get(resolved) ?? [], tableName]);
|
|
2403
|
+
return [tableName, resolved];
|
|
2404
|
+
}
|
|
2405
|
+
const state = tableState(resolved);
|
|
2406
|
+
tableNamesByState.set(state, [...tableNamesByState.get(state) ?? [], tableName]);
|
|
2407
|
+
tableIndexes.set(tableName, state.indexCallbacks);
|
|
2408
|
+
tableChecks.set(tableName, state.checkCallbacks);
|
|
2409
|
+
tableComputed.set(tableName, state.computedCallbacks);
|
|
2410
|
+
tableRelations.set(tableName, state.relationCallbacks);
|
|
2411
|
+
if (state.primaryKey) primaryKeys.set(tableName, state.primaryKey);
|
|
2412
|
+
if (state.junction) junctionTables.add(tableName);
|
|
2413
|
+
return [tableName, state.columns];
|
|
2414
|
+
}));
|
|
2415
|
+
const tableDefinitions = {};
|
|
2416
|
+
for (const [tableName, columns] of Object.entries(rawDefinitions)) tableDefinitions[tableName] = Object.fromEntries(Object.entries(columns).map(([name, value]) => {
|
|
2417
|
+
if (isColumn(value) || isLink(value)) return [name, value];
|
|
2418
|
+
const example = builderExample(value);
|
|
2419
|
+
if (example) throw new Error(`symmetria: "${tableName}.${name}" is the ${value.name || "column"}() builder itself; call it: ${name}: ${example}`);
|
|
2420
|
+
const input = isReferenceInput(value) ? value : void 0;
|
|
2421
|
+
const target = input?.target ?? value;
|
|
2422
|
+
const state = target === "self" ? void 0 : typeof target === "function" ? tableState(resolveThunk(tableName, name, target)) : isTable(target) ? tableState(target) : target;
|
|
2423
|
+
const targets = tableNamesByState.get(state);
|
|
2424
|
+
if (targets && targets.length > 1) throw new Error(`symmetria: ambiguous table reference "${tableName}.${name}"; use a keyed callback`);
|
|
2425
|
+
const targetName = target === "self" ? tableName : targets?.[0];
|
|
2426
|
+
if (!targetName) {
|
|
2427
|
+
if (!isTable(target)) throw new Error(`symmetria: "${tableName}.${name}" is not a column, table or reference (got ${describeValue(target)})`);
|
|
2428
|
+
throw new Error(`symmetria: reference "${tableName}.${name}" points to a table outside this schema`);
|
|
2429
|
+
}
|
|
2430
|
+
return [name, createLink(targetName, input?.flags ?? {})];
|
|
2431
|
+
}));
|
|
2432
|
+
for (const [tableName, definition] of Object.entries(tableDefinitions)) if (!primaryKeys.has(tableName)) {
|
|
2433
|
+
const explicit = Object.entries(definition).filter(([, column]) => isColumn(column) && column.definition.primaryKey).map(([name]) => name);
|
|
2434
|
+
primaryKeys.set(tableName, junctionTables.has(tableName) ? Object.entries(definition).filter(([, column]) => isLink(column)).map(([name]) => `${name}Id`) : explicit.length ? explicit : isColumn(definition.id) ? ["id"] : []);
|
|
2435
|
+
}
|
|
2436
|
+
const tableHandles = Object.create(null);
|
|
2437
|
+
const inverseRelations = [];
|
|
2438
|
+
for (const [tableName, tableDefinition] of Object.entries(tableDefinitions)) {
|
|
2439
|
+
if ([
|
|
2440
|
+
"$snapshot",
|
|
2441
|
+
"$close",
|
|
2442
|
+
"$transaction",
|
|
2443
|
+
"$createIndexes",
|
|
2444
|
+
"__proto__",
|
|
2445
|
+
"constructor",
|
|
2446
|
+
"prototype"
|
|
2447
|
+
].includes(tableName)) throw new Error(`symmetria experiment: reserved table name "${tableName}"`);
|
|
2448
|
+
const columns = Object.create(null);
|
|
2449
|
+
const columnEntries = Object.entries(tableDefinition);
|
|
2450
|
+
const isJunction = junctionTables.has(tableName);
|
|
2451
|
+
for (const [columnName, value] of columnEntries) {
|
|
2452
|
+
if (isColumn(value)) {
|
|
2453
|
+
if (primaryKeys.get(tableName).includes(columnName) && !value.definition.notNull) throw new Error(`symmetria: primary key "${tableName}.${columnName}" cannot be nullable`);
|
|
2454
|
+
columns[columnName] = value;
|
|
2455
|
+
continue;
|
|
2456
|
+
}
|
|
2457
|
+
if (!isLink(value)) throw new Error(`symmetria experiment: invalid column "${tableName}.${columnName}"`);
|
|
2458
|
+
const { target, flags } = value[LINK];
|
|
2459
|
+
const targetDefinition = tableDefinitions[target];
|
|
2460
|
+
const targetKeys = primaryKeys.get(target) ?? [];
|
|
2461
|
+
if (!targetDefinition) throw new Error(`symmetria: "${tableName}.${columnName}" references unknown table "${target}"`);
|
|
2462
|
+
if (flags.by !== void 0) {
|
|
2463
|
+
const referenced = targetDefinition[flags.by];
|
|
2464
|
+
if (!isColumn(referenced) || !(referenced.definition.unique || targetKeys.length === 1 && targetKeys[0] === flags.by)) throw new Error(`symmetria: "${tableName}.${columnName}" references "${target}.${flags.by}", which must be a unique column or the primary key`);
|
|
2465
|
+
} else if (targetKeys.length !== 1 || !isColumn(targetDefinition[targetKeys[0]])) throw new Error(`symmetria: "${tableName}.${columnName}" must reference a table with a single scalar primary key`);
|
|
2466
|
+
if (flags.inverse !== void 0) {
|
|
2467
|
+
if (isJunction) throw new Error("symmetria experiment: junction inverse renaming is not implemented");
|
|
2468
|
+
inverseRelations.push({
|
|
2469
|
+
target,
|
|
2470
|
+
name: flags.inverse,
|
|
2471
|
+
source: tableName,
|
|
2472
|
+
column: columnName
|
|
2473
|
+
});
|
|
2474
|
+
}
|
|
2475
|
+
columns[columnName] = Object.freeze({
|
|
2476
|
+
kind: "reference",
|
|
2477
|
+
target: target === tableName ? "self" : () => tableHandles[target],
|
|
2478
|
+
flags: Object.freeze({ ...flags })
|
|
2479
|
+
});
|
|
2480
|
+
}
|
|
2481
|
+
tableHandles[tableName] = isJunction ? junction(columns) : table(columns);
|
|
2482
|
+
const explicitKeys = primaryKeys.get(tableName);
|
|
2483
|
+
if (!isJunction && explicitKeys.length) tableHandles[tableName] = tableHandles[tableName].primaryKey((columns) => {
|
|
2484
|
+
const scope = columns;
|
|
2485
|
+
return [scope[explicitKeys[0]], ...explicitKeys.slice(1).map((name) => scope[name])];
|
|
2486
|
+
});
|
|
2487
|
+
}
|
|
2488
|
+
const overrides = Object.create(null);
|
|
2489
|
+
for (const inverseRelation of inverseRelations) {
|
|
2490
|
+
const tableOverrides = overrides[inverseRelation.target] ??= Object.create(null);
|
|
2491
|
+
if (Object.hasOwn(tableOverrides, inverseRelation.name)) throw new Error(`symmetria experiment: duplicate inverse "${inverseRelation.target}.${inverseRelation.name}"`);
|
|
2492
|
+
tableOverrides[inverseRelation.name] = tableHandles[inverseRelation.source][inverseRelation.column];
|
|
2493
|
+
}
|
|
2494
|
+
const conditionTargetName = (tableName, relationName, target) => {
|
|
2495
|
+
if (isLink(target)) return target[LINK].target;
|
|
2496
|
+
const resolved = typeof target === "function" ? resolveThunk(tableName, relationName, target) : target;
|
|
2497
|
+
const names = isTable(resolved) ? tableNamesByState.get(tableState(resolved)) : resolved && typeof resolved === "object" ? tableNamesByRecord.get(resolved) : void 0;
|
|
2498
|
+
if (names && names.length > 1) throw new Error(`symmetria: ambiguous table reference in relation "${tableName}.${relationName}"; use a keyed callback`);
|
|
2499
|
+
if (!names?.[0]) throw new Error(`symmetria: relation "${tableName}.${relationName}" points to a table outside this schema (got ${describeValue(target)})`);
|
|
2500
|
+
return names[0];
|
|
2501
|
+
};
|
|
2502
|
+
const conditions = Object.create(null);
|
|
2503
|
+
for (const [tableName, callbacks] of tableRelations) {
|
|
2504
|
+
if (!callbacks.length) continue;
|
|
2505
|
+
const draft = draftBinding(tableState(tableHandles[tableName]));
|
|
2506
|
+
const declared = declaredConditions(callbacks, createScope({ [draft.alias]: draft })[draft.alias], tableName);
|
|
2507
|
+
const definition = tableDefinitions[tableName];
|
|
2508
|
+
conditions[tableName] = Object.entries(declared).map(([name, entry]) => {
|
|
2509
|
+
const state = entry[CONDITION];
|
|
2510
|
+
if (Object.hasOwn(definition, name) || Object.keys(definition).some((column) => `${column}Id` === name)) throw new Error(`symmetria: relation "${tableName}.${name}" clashes with a column of the same name`);
|
|
2511
|
+
return {
|
|
2512
|
+
name,
|
|
2513
|
+
target: conditionTargetName(tableName, name, state.target),
|
|
2514
|
+
many: state.many,
|
|
2515
|
+
...state.inverse !== void 0 ? { inverse: state.inverse } : {}
|
|
2516
|
+
};
|
|
2517
|
+
});
|
|
2518
|
+
}
|
|
2519
|
+
const snapshot = assembleSchema(tableHandles, overrides, conditions);
|
|
2520
|
+
if (options.extensions?.length) {
|
|
2521
|
+
for (const extension of options.extensions) if (!/^[a-z_][a-z0-9_]*$/.test(extension)) throw new Error(`symmetria: extension names are lowercase identifiers, not "${extension}"`);
|
|
2522
|
+
snapshot.extensions = Object.freeze([...new Set(options.extensions)].sort());
|
|
2523
|
+
}
|
|
2524
|
+
for (const table of snapshot.tables) {
|
|
2525
|
+
computedFields.set(table, tableComputed.get(table.name) ?? []);
|
|
2526
|
+
conditionRelations.set(table, tableRelations.get(table.name) ?? []);
|
|
2527
|
+
}
|
|
2528
|
+
if (options.executor && options.driver) throw new Error("symmetria: supply either driver or executor");
|
|
2529
|
+
const codecs = Object.fromEntries(Object.entries(tableDefinitions).map(([tableName, definition]) => [tableName, codecMap(Object.fromEntries(Object.entries(definition).flatMap(([columnName, value]) => {
|
|
2530
|
+
const column = isColumn(value) ? value : tableDefinitions[value[LINK].target]?.[value[LINK].flags.by ?? primaryKeys.get(value[LINK].target)?.[0] ?? "id"];
|
|
2531
|
+
const codec = column && isColumn(column) ? column[COLUMN_CODEC] : void 0;
|
|
2532
|
+
return codec ? [[isColumn(value) ? columnName : `${columnName}Id`, codec]] : [];
|
|
2533
|
+
})))]));
|
|
2534
|
+
for (const table of snapshot.tables) for (const column of table.columns) {
|
|
2535
|
+
const codec = codecs[table.name]?.[column.name];
|
|
2536
|
+
if (codec && column.default?.kind === "value") {
|
|
2537
|
+
const encoded = encodeValue(column.default.value, codec);
|
|
2538
|
+
column.default = {
|
|
2539
|
+
kind: "value",
|
|
2540
|
+
value: ["json", "jsonb"].includes(column.sqlType) && typeof encoded === "string" ? JSON.parse(encoded) : encoded
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
for (const [tableName, callbacks] of tableIndexes) for (const callback of callbacks) applyIndexes(snapshot, codecs, (scope) => callback(scope[tableName]), tableName);
|
|
2545
|
+
for (const [tableName, callbacks] of tableChecks) for (const callback of callbacks) applyChecks(snapshot, codecs, tableName, callback);
|
|
2546
|
+
if (options.indexes) applyIndexes(snapshot, codecs, options.indexes);
|
|
2547
|
+
for (const table of snapshot.tables) {
|
|
2548
|
+
const second = table.junction ? (table.primaryKey ?? table.columns.filter((column) => column.primaryKey).map((column) => column.name))[1] : void 0;
|
|
2549
|
+
const column = table.columns.find((column) => column.name === second);
|
|
2550
|
+
if (!second || !column) continue;
|
|
2551
|
+
const leading = quoteIdentifier(column.sqlName);
|
|
2552
|
+
if (!table.indexes?.some(({ keys: [first] }) => first === leading || first?.startsWith(`${leading} `))) applyIndexes(snapshot, codecs, (scope) => ({ [second]: index(scope[table.name][second]) }), table.name);
|
|
2553
|
+
}
|
|
2554
|
+
const bindDatabase = (executor, transactionDriver, driver = options.driver, scopes = {}) => {
|
|
2555
|
+
const atomicDriver = transactionDriver ?? driver;
|
|
2556
|
+
const hold = transactionDriver ? (run) => run(transactionDriver.execute) : driver?.transaction ? (run) => driver.transaction((connection) => run(connection.execute)) : void 0;
|
|
2557
|
+
const queryTables = createQueryTables(snapshot, executor, codecs, scopes, atomicDriver?.transaction ? (run) => atomicDriver.transaction((connection) => run(connection.execute)) : void 0, hold);
|
|
2558
|
+
const profile = executorProfiling(executor);
|
|
2559
|
+
const runTransaction = async (callback, options) => {
|
|
2560
|
+
const run = async (connection) => callback(bindDatabase(connection.execute, connection, driver, scopes));
|
|
2561
|
+
if (transactionDriver) {
|
|
2562
|
+
if (options !== void 0) throw new Error("symmetria: transaction options cannot be changed inside a savepoint");
|
|
2563
|
+
return transactionDriver.transaction(run);
|
|
2564
|
+
}
|
|
2565
|
+
if (!driver?.transaction) throw new Error("symmetria: the configured driver does not support transactions");
|
|
2566
|
+
const { retries = 0, retryDelayMs = 10, ...settings } = options ?? {};
|
|
2567
|
+
if (!Number.isSafeInteger(retries) || retries < 0 || retries > 20) throw new Error("symmetria: retries must be an integer between 0 and 20");
|
|
2568
|
+
if (!Number.isFinite(retryDelayMs) || retryDelayMs < 0) throw new Error("symmetria: retryDelayMs must be a non-negative number");
|
|
2569
|
+
for (let attempt = 0;; attempt += 1) try {
|
|
2570
|
+
return await driver.transaction(run, options === void 0 ? void 0 : settings);
|
|
2571
|
+
} catch (error) {
|
|
2572
|
+
if (attempt >= retries || !isRetryableTransactionError(error)) throw error;
|
|
2573
|
+
const delay = Math.random() * retryDelayMs * 2 ** attempt;
|
|
2574
|
+
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2575
|
+
}
|
|
2576
|
+
};
|
|
2577
|
+
const databaseTables = Object.fromEntries(snapshot.tables.map((tableSnapshot) => {
|
|
2578
|
+
const relationNames = tableSnapshot.relations.map((relation) => relation.name);
|
|
2579
|
+
const table = extendBuilder(queryTables[tableSnapshot.name], {
|
|
2580
|
+
$name: tableSnapshot.sqlName,
|
|
2581
|
+
insert: (values) => {
|
|
2582
|
+
const rows = Array.isArray(values) ? values : [values];
|
|
2583
|
+
if (rows.some((row) => row && relationNames.some((name) => row[name] !== void 0))) return createNestedInsert(snapshot, tableSnapshot.name, values, runTransaction, codecs);
|
|
2584
|
+
const flat = (row) => row && relationNames.some((name) => name in row) ? Object.fromEntries(Object.entries(row).filter(([name]) => !relationNames.includes(name))) : row;
|
|
2585
|
+
return queryTables[tableSnapshot.name].insert(Array.isArray(values) ? rows.map(flat) : flat(values));
|
|
2586
|
+
}
|
|
2587
|
+
});
|
|
2588
|
+
return [tableSnapshot.name, profile ? profile.trackBuilder(table) : table];
|
|
2589
|
+
}));
|
|
2590
|
+
const mergeScopes = (next) => Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(scopes), ...Object.keys(next)])].map((tableName) => {
|
|
2591
|
+
if (!snapshot.tables.some((table) => table.name === tableName)) throw new Error(`symmetria: $scope() received unknown table "${tableName}"`);
|
|
2592
|
+
const previous = scopes[tableName];
|
|
2593
|
+
const added = next[tableName];
|
|
2594
|
+
if (added !== void 0 && typeof added !== "function") throw new Error(`symmetria: $scope() expects a predicate callback for "${tableName}"`);
|
|
2595
|
+
return [tableName, previous && added ? (columns) => and(previous(columns), added(columns)) : previous ?? added];
|
|
2596
|
+
}));
|
|
2597
|
+
return Object.freeze({
|
|
2598
|
+
...databaseTables,
|
|
2599
|
+
...!transactionDriver ? { [SCHEMA_BIND]: (connection) => bindDatabase(connection.execute, void 0, connection, scopes) } : {},
|
|
2600
|
+
$scope: (next) => bindDatabase(executor, transactionDriver, driver, mergeScopes(next)),
|
|
2601
|
+
$snapshot: () => structuredClone(snapshot),
|
|
2602
|
+
$createIndexes: (settings) => createIndexQuery(snapshot, executor, settings, !!transactionDriver),
|
|
2603
|
+
$transaction: runTransaction,
|
|
2604
|
+
...transactionDriver ? {} : { $close: async () => {
|
|
2605
|
+
await driver?.close();
|
|
2606
|
+
} }
|
|
2607
|
+
});
|
|
2608
|
+
};
|
|
2609
|
+
return bindDatabase(options.executor ?? options.driver?.execute);
|
|
2610
|
+
};
|
|
2611
|
+
/** Anchor key types before checking mutually recursive table callbacks. */
|
|
2612
|
+
const withKeys = (keys) => (definitions, options = {}) => {
|
|
2613
|
+
for (const [name, key] of Object.entries(keys)) {
|
|
2614
|
+
if (!isColumn(key)) throw new Error("symmetria: schema.keys() expects primary-key column types");
|
|
2615
|
+
if (!Object.hasOwn(definitions, name)) throw new Error(`symmetria: unknown schema.keys() table "${name}"`);
|
|
2616
|
+
}
|
|
2617
|
+
const anchored = Object.fromEntries(Object.entries(definitions).map(([name, definition]) => [name, (references) => {
|
|
2618
|
+
const resolved = typeof definition === "function" ? definition(references) : definition;
|
|
2619
|
+
const key = keys[name];
|
|
2620
|
+
if (key) {
|
|
2621
|
+
const state = isTable(resolved) ? tableState(resolved) : void 0;
|
|
2622
|
+
const columns = state?.columns ?? resolved;
|
|
2623
|
+
const marked = Object.entries(columns).filter(([, column]) => isColumn(column) && column.definition.primaryKey).map(([name]) => name);
|
|
2624
|
+
const names = state?.primaryKey ?? (marked.length ? marked : ["id"]);
|
|
2625
|
+
const primary = names.length === 1 ? columns[names[0]] : void 0;
|
|
2626
|
+
if (!isColumn(primary) || primary.definition.sqlType !== key.definition.sqlType || primary[COLUMN_CODEC] !== key[COLUMN_CODEC] || JSON.stringify(primary.definition.enumerationValues) !== JSON.stringify(key.definition.enumerationValues)) throw new Error(`symmetria: primary key for "${name}" does not match schema.keys()`);
|
|
2627
|
+
}
|
|
2628
|
+
return resolved;
|
|
2629
|
+
}]));
|
|
2630
|
+
return createSchema(anchored, options);
|
|
2631
|
+
};
|
|
2632
|
+
const schema = Object.assign(createSchema, { keys: withKeys });
|
|
2633
|
+
//#endregion
|
|
2634
|
+
export { IsolationLevel, TABLE, and, average, bigint, bool, bytea, coalesce, count, createDatabase, createIndexesSQL, createProfiler, customType, date, DEFAULT_VALUE as defaultValue, denseRank, doublePrecision, exists, index, inet, int, interval, isColumn, isTable, jsonb, junction, lag, lead, maximum, minimum, not, notExists, numeric, oneOf, operatorClass, or, over, prepare, rank, real, rowNumber, schema, searchDocument, self, smallint, snakeCase, sql, sqlState, sum, table, text, time, timestamptz, tsvector, uuid, varchar, when };
|
|
2635
|
+
|
|
2636
|
+
//# sourceMappingURL=index.js.map
|