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.
@@ -0,0 +1,2233 @@
1
+ import { a as containsBinding, r as QUERY_PLAN } from "./types-BavtzvoV.js";
2
+ //#region src/query/codecs/index.ts
3
+ /** Missing column codecs must never resolve to Object.prototype properties. */
4
+ const codecMap = (entries) => Object.setPrototypeOf(entries, null);
5
+ /** bigint columns also accept safe JavaScript integers on write. */
6
+ const bigintCodec = {
7
+ sqlType: "bigint",
8
+ encode: (value) => {
9
+ if (typeof value === "number" && !Number.isSafeInteger(value)) throw new Error("symmetria: bigint columns accept bigint values or safe integers");
10
+ return value.toString();
11
+ },
12
+ decode: (value) => BigInt(value)
13
+ };
14
+ /** Normalize boolean expressions returned by a query executor. */
15
+ const booleanCodec = {
16
+ sqlType: "boolean",
17
+ encode: (value) => value,
18
+ decode: (value) => value === true || value === 1 || value === 1n
19
+ };
20
+ /** COUNT and ranking results are safe integers in practice; decode them as numbers. */
21
+ const countCodec = {
22
+ encode: (value) => value,
23
+ decode: (value) => {
24
+ const count = Number(value);
25
+ if (!Number.isSafeInteger(count)) throw new Error(`symmetria: count ${String(value)} exceeds Number.MAX_SAFE_INTEGER`);
26
+ return count;
27
+ }
28
+ };
29
+ const numericCodec = {
30
+ encode: (value) => value,
31
+ decode: (value) => String(value)
32
+ };
33
+ /** Floats and smallint: drivers deliver numbers; JSON and text casts deliver strings such as "NaN". */
34
+ const numberCodec = (sqlType) => ({
35
+ sqlType,
36
+ encode: (value) => value,
37
+ decode: (value) => typeof value === "number" ? value : Number(value)
38
+ });
39
+ const pad = (value) => String(value).padStart(2, "0");
40
+ /** Calendar dates stay `YYYY-MM-DD` text; a driver Date is read in UTC (Bun) or local time (pg midnight). */
41
+ const dateCodec = {
42
+ sqlType: "date",
43
+ encode: (value) => value instanceof Date ? dateCodec.decode(value) : value,
44
+ decode: (value) => {
45
+ if (value instanceof Date) return value.getUTCHours() === 0 && value.getUTCMinutes() === 0 ? `${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}` : `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
46
+ return String(value);
47
+ }
48
+ };
49
+ /** Intervals stay PostgreSQL text; node-postgres interval objects print themselves back. */
50
+ const intervalCodec = {
51
+ sqlType: "interval",
52
+ encode: (value) => value,
53
+ decode: (value) => typeof value === "object" && value !== null && "toPostgres" in value && typeof value.toPostgres === "function" ? String(value.toPostgres()) : String(value)
54
+ };
55
+ /** Binary columns are `Uint8Array`; JSON and text casts deliver PostgreSQL's `\x…` hex form. */
56
+ const bytesCodec = {
57
+ sqlType: "bytea",
58
+ encode: (value) => {
59
+ if (!(value instanceof Uint8Array)) throw new Error("symmetria: bytea columns accept Uint8Array values");
60
+ return value;
61
+ },
62
+ decode: (value) => {
63
+ if (value instanceof Uint8Array) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
64
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
65
+ if (typeof value === "string" && value.startsWith("\\x")) return Uint8Array.from(Buffer.from(value.slice(2), "hex"));
66
+ throw new Error(`symmetria: cannot read bytea value ${JSON.stringify(value)}`);
67
+ }
68
+ };
69
+ /** Arrays travel as JavaScript arrays; the adapters bind them as PostgreSQL array parameters. */
70
+ const arrayCodec = (elementType, element) => ({
71
+ encode: (values) => {
72
+ if (!Array.isArray(values)) throw new Error("symmetria: array columns accept arrays");
73
+ return values.map((value) => encodeValue(value, element));
74
+ },
75
+ decode: (value) => {
76
+ const values = typeof value === "string" && value.startsWith("[") ? JSON.parse(value) : value;
77
+ if (!Array.isArray(values)) throw new Error("symmetria: expected an array value from the database");
78
+ return values.map((entry) => decodeValue(entry, element));
79
+ },
80
+ parameterCast: `${elementType}[]`,
81
+ ...element ? { element } : {}
82
+ });
83
+ const codecFor = (sqlType) => {
84
+ if (sqlType.endsWith("[]")) {
85
+ const elementType = sqlType.slice(0, -2);
86
+ return arrayCodec(elementType, codecFor(elementType));
87
+ }
88
+ if (sqlType === "bigint") return bigintCodec;
89
+ if (sqlType === "smallint" || sqlType === "real" || sqlType === "double precision") return numberCodec(sqlType);
90
+ if (sqlType === "date") return dateCodec;
91
+ if (sqlType === "interval") return intervalCodec;
92
+ if (sqlType === "bytea") return bytesCodec;
93
+ if (sqlType.startsWith("numeric")) return sqlType.includes(",") ? {
94
+ ...numericCodec,
95
+ sqlType
96
+ } : numericCodec;
97
+ if (sqlType === "jsonb" || sqlType === "json") return {
98
+ encode: (value) => JSON.stringify(value),
99
+ decode: (value) => value,
100
+ parameterCast: sqlType
101
+ };
102
+ if (sqlType === "timestamptz" || sqlType === "timestamp") return {
103
+ encode: (value) => value,
104
+ decode: (value) => {
105
+ if (value instanceof Date) return value;
106
+ const date = new Date(value);
107
+ if (Number.isNaN(date.getTime())) throw new Error(`symmetria: cannot represent ${sqlType} value ${JSON.stringify(typeof value === "number" ? String(value) : value)} as a Date; read it with sql.of(text)\`…\` instead`);
108
+ return date;
109
+ }
110
+ };
111
+ };
112
+ const encodeValue = (value, codec) => value === null || value === void 0 || !codec ? value : codec.encode(value);
113
+ const decodeValue = (value, codec) => value === null || value === void 0 || !codec ? value : codec.decode(value);
114
+ const createRowDecoder = (selection) => {
115
+ if (selection.some((expression) => expression.outputName === "__proto__")) return (row) => Object.fromEntries(selection.map((expression) => [expression.outputName, decodeValue(row[expression.outputName], expression.codec)]));
116
+ const codecs = [];
117
+ const fields = selection.map((expression) => {
118
+ const key = JSON.stringify(expression.outputName);
119
+ if (!expression.codec) return `${key}: row[${key}]`;
120
+ return `${key}: (v = row[${key}]) == null ? v : ${`c${codecs.push(expression.codec) - 1}`}.decode(v)`;
121
+ });
122
+ const source = `${codecs.map((_codec, index) => `const c${index} = codecs[${index}];`).join("\n")}
123
+ return (row) => { let v; return { ${fields.join(", ")} }; };`;
124
+ let factory = decoderFactories.get(source);
125
+ if (!factory) {
126
+ factory = new Function("codecs", source);
127
+ if (decoderFactories.size >= 256) decoderFactories.delete(decoderFactories.keys().next().value);
128
+ decoderFactories.set(source, factory);
129
+ }
130
+ return factory(codecs);
131
+ };
132
+ /** Generated code depends only on field names and codec positions, so factories are shared. */
133
+ const decoderFactories = /* @__PURE__ */ new Map();
134
+ /** Primitive parameter values can be reused; object-backed values are cloned defensively. */
135
+ const cloneParameter = (value) => {
136
+ if (value === null || typeof value !== "object") return typeof value === "function" || typeof value === "symbol" ? structuredClone(value) : value;
137
+ if (value instanceof Date) return new Date(value.getTime());
138
+ if (Array.isArray(value)) {
139
+ for (const entry of value) if (entry !== null && typeof entry === "object") return structuredClone(value);
140
+ return value.slice();
141
+ }
142
+ return structuredClone(value);
143
+ };
144
+ //#endregion
145
+ //#region src/schema/column.ts
146
+ /**
147
+ * Column builders. Property-access magic: `text.unique`, `uuid.v7`, `timestamptz.now`.
148
+ *
149
+ * Modifiers return new frozen column definitions. Runtime codecs live under a
150
+ * symbol; schema assembly normalizes defaults for serializable migration snapshots.
151
+ */
152
+ const COLUMN_CODEC = Symbol("symmetria.column.codec");
153
+ const defineGetter = (target, name, get) => {
154
+ Object.defineProperty(target, name, {
155
+ get,
156
+ enumerable: false,
157
+ configurable: false
158
+ });
159
+ };
160
+ /** Marks a column builder function so a schema can explain `price: jsonb` instead of `price: jsonb()`. */
161
+ const COLUMN_BUILDER = Symbol("symmetria.column.builder");
162
+ const markBuilder = (builder, example) => Object.defineProperty(builder, COLUMN_BUILDER, {
163
+ value: example,
164
+ enumerable: false
165
+ });
166
+ /** The usage example recorded on a marked builder, or undefined. */
167
+ const builderExample = (value) => typeof value === "function" && COLUMN_BUILDER in value ? String(value[COLUMN_BUILDER]) : void 0;
168
+ const makeColumn = (definition, extras = {}, codec, call) => {
169
+ const column = Object.assign(call ?? {}, {
170
+ kind: "column",
171
+ definition: Object.freeze({ ...definition }),
172
+ ...codec ? { [COLUMN_CODEC]: codec } : {},
173
+ brand: (name) => {
174
+ if (!name) throw new Error("symmetria: brand() requires a name");
175
+ return column;
176
+ }
177
+ });
178
+ const chain = (nextDefinition) => makeColumn(nextDefinition, extras, codec);
179
+ defineGetter(column, "nullable", () => chain({
180
+ ...definition,
181
+ notNull: false
182
+ }));
183
+ defineGetter(column, "unique", () => chain({
184
+ ...definition,
185
+ unique: true
186
+ }));
187
+ defineGetter(column, "index", () => chain({
188
+ ...definition,
189
+ index: true
190
+ }));
191
+ defineGetter(column, "primaryKey", () => chain({
192
+ ...definition,
193
+ primaryKey: true
194
+ }));
195
+ defineGetter(column, "array", () => {
196
+ if (definition.enumerationValues || definition.sqlType.endsWith("[]")) throw new Error("symmetria: arrays are available for scalar, non-enum column types");
197
+ if (/^vector(\(|$)/.test(definition.sqlType)) throw new Error("symmetria: vector columns cannot be arrays");
198
+ if (definition.default?.kind === "sql" && definition.default.sql === "identity") throw new Error("symmetria: identity columns cannot be arrays");
199
+ return makeColumn({
200
+ sqlType: `${definition.sqlType}[]`,
201
+ notNull: definition.notNull,
202
+ unique: false,
203
+ primaryKey: false
204
+ }, {}, arrayCodec(definition.sqlType, codec ?? codecFor(definition.sqlType)));
205
+ });
206
+ for (const [name, transform] of Object.entries(extras)) defineGetter(column, name, () => chain(transform(definition)));
207
+ Object.defineProperty(column, "default", {
208
+ value: (value) => {
209
+ const isSql = typeof value === "object" && value !== null && value.kind === "sql";
210
+ return chain({
211
+ ...definition,
212
+ default: isSql ? {
213
+ kind: "sql",
214
+ sql: value.sql
215
+ } : {
216
+ kind: "value",
217
+ value
218
+ }
219
+ });
220
+ },
221
+ enumerable: false
222
+ });
223
+ return Object.freeze(column);
224
+ };
225
+ const base = (sqlType, extras) => {
226
+ return makeColumn({
227
+ sqlType,
228
+ notNull: true,
229
+ unique: false,
230
+ primaryKey: false
231
+ }, extras);
232
+ };
233
+ const uuid = base("uuid", {
234
+ v4: (definition) => ({
235
+ ...definition,
236
+ default: {
237
+ kind: "sql",
238
+ sql: "gen_random_uuid()"
239
+ }
240
+ }),
241
+ v7: (definition) => ({
242
+ ...definition,
243
+ default: {
244
+ kind: "sql",
245
+ sql: "uuidv7()"
246
+ }
247
+ })
248
+ });
249
+ const text = base("text");
250
+ const int = base("integer", { auto: (definition) => ({
251
+ ...definition,
252
+ default: {
253
+ kind: "sql",
254
+ sql: "identity"
255
+ }
256
+ }) });
257
+ const bigint = base("bigint", { auto: (definition) => ({
258
+ ...definition,
259
+ default: {
260
+ kind: "sql",
261
+ sql: "identity"
262
+ }
263
+ }) });
264
+ const bool = base("boolean");
265
+ /** 16-bit integer; `smallint.auto` is an identity column like `int.auto`. */
266
+ const smallint = base("smallint", { auto: (definition) => ({
267
+ ...definition,
268
+ default: {
269
+ kind: "sql",
270
+ sql: "identity"
271
+ }
272
+ }) });
273
+ /** Single-precision float; `NaN` and `±Infinity` round-trip. */
274
+ const real = base("real");
275
+ /** Double-precision float; `NaN` and `±Infinity` round-trip. */
276
+ const doublePrecision = base("double precision");
277
+ /** Calendar date as `YYYY-MM-DD` text: no time zone shifts on either driver. */
278
+ const date = base("date");
279
+ /** Time of day as `HH:MM:SS[.ffffff]` text. */
280
+ const time = base("time");
281
+ /** Interval in PostgreSQL's text form, such as `1 day 02:00:00`. */
282
+ const interval = base("interval");
283
+ /** Binary data as `Uint8Array`. */
284
+ const bytea = base("bytea");
285
+ /** IPv4 or IPv6 address as text, such as `10.0.0.1` or `::1/128`. */
286
+ const inet = base("inet");
287
+ const timestamptz = base("timestamptz", { now: (definition) => ({
288
+ ...definition,
289
+ default: {
290
+ kind: "sql",
291
+ sql: "now()"
292
+ }
293
+ }) });
294
+ const varchar = makeColumn({
295
+ sqlType: "varchar",
296
+ notNull: true,
297
+ unique: false,
298
+ primaryKey: false
299
+ }, {}, void 0, (length) => {
300
+ if (!Number.isSafeInteger(length) || length <= 0) throw new Error("symmetria: varchar length must be a positive integer");
301
+ return base(`varchar(${length})`);
302
+ });
303
+ const formatIssue = (issue) => {
304
+ const path = (issue.path ?? []).map((segment) => String(typeof segment === "object" && segment !== null && "key" in segment ? segment.key : segment)).join(".");
305
+ return path ? `${path}: ${issue.message}` : issue.message;
306
+ };
307
+ /**
308
+ * `jsonb<Value>()` trusts the type; `jsonb(schema)` validates every written and
309
+ * read value with a Standard Schema and infers the value type from it.
310
+ */
311
+ const jsonb = (schema) => {
312
+ if (!schema) return base("jsonb");
313
+ if (typeof schema["~standard"]?.validate !== "function") throw new Error("symmetria: jsonb() expects a Standard Schema object");
314
+ const validate = (value) => {
315
+ const result = schema["~standard"].validate(value);
316
+ if (result instanceof Promise) throw new Error("symmetria: jsonb() schemas must validate synchronously");
317
+ if (result.issues) throw new Error(`symmetria: invalid jsonb value: ${result.issues.map(formatIssue).join("; ")}`);
318
+ return result.value;
319
+ };
320
+ return makeColumn({
321
+ sqlType: "jsonb",
322
+ notNull: true,
323
+ unique: false,
324
+ primaryKey: false
325
+ }, {}, Object.freeze({
326
+ encode: (value) => JSON.stringify(validate(value)),
327
+ decode: validate,
328
+ parameterCast: "jsonb"
329
+ }));
330
+ };
331
+ const oneOf = (...values) => {
332
+ return makeColumn({
333
+ sqlType: "enum",
334
+ notNull: true,
335
+ unique: false,
336
+ primaryKey: false,
337
+ enumerationValues: values
338
+ });
339
+ };
340
+ const isColumn = (value) => {
341
+ return (typeof value === "object" || typeof value === "function") && value !== null && value.kind === "column";
342
+ };
343
+ /** PostgreSQL numeric is lossless decimal text at the JavaScript boundary. */
344
+ const numeric = makeColumn({
345
+ sqlType: "numeric",
346
+ notNull: true,
347
+ unique: false,
348
+ primaryKey: false
349
+ }, {}, void 0, (precision, scale) => {
350
+ if (precision !== void 0 && (!Number.isInteger(precision) || precision < 1 || precision > 1e3)) throw new Error("symmetria: numeric precision must be between 1 and 1000");
351
+ if (scale !== void 0 && (precision === void 0 || !Number.isInteger(scale) || scale < 0 || scale > precision)) throw new Error("symmetria: numeric scale must be between zero and precision");
352
+ return base(precision === void 0 ? "numeric" : `numeric(${precision}${scale === void 0 ? "" : `,${scale}`})`);
353
+ });
354
+ const customType = (sqlType, codec) => makeColumn({
355
+ sqlType,
356
+ notNull: true,
357
+ unique: false,
358
+ primaryKey: false
359
+ }, {}, Object.freeze({
360
+ ...codec,
361
+ sqlType
362
+ }));
363
+ /**
364
+ * `tsvector` column. Write it with `sql.of(tsvector)\`to_tsvector('english', ${title})\``
365
+ * or keep it current with a trigger; read values are PostgreSQL's lexeme text.
366
+ */
367
+ const tsvector = customType("tsvector", {
368
+ encode: (value) => value,
369
+ decode: (value) => String(value)
370
+ });
371
+ /**
372
+ * A column whose codec also controls parameter casts; for package entries such as
373
+ * `symmetria/vector`. Not part of the public API.
374
+ * @internal
375
+ */
376
+ const typedColumn = (sqlType, codec) => makeColumn({
377
+ sqlType,
378
+ notNull: true,
379
+ unique: false,
380
+ primaryKey: false
381
+ }, {}, Object.freeze({
382
+ ...codec,
383
+ sqlType: codec.sqlType ?? sqlType
384
+ }));
385
+ markBuilder(jsonb, "jsonb<Value>() or jsonb(standardSchema)");
386
+ markBuilder(oneOf, "oneOf(\"draft\", \"published\")");
387
+ markBuilder(customType, "customType<Value>(\"sql_type\", { encode, decode })");
388
+ //#endregion
389
+ //#region src/query/plan/metadata.ts
390
+ const expressionSqlType = (expression) => {
391
+ const node = expression.node;
392
+ switch (node.kind) {
393
+ case "placeholder": return node.sqlType;
394
+ case "parameter": return node.sqlType ?? node.cast ?? expression.codec?.sqlType ?? "derived";
395
+ case "raw": return node.sqlType ?? expression.codec?.sqlType ?? expression.codec?.parameterCast ?? "derived";
396
+ case "column": {
397
+ const source = node.description.binding.projection?.[node.description.column.name];
398
+ return source ? expressionSqlType(source) : node.description.column.sqlType;
399
+ }
400
+ case "case": return node.sqlType;
401
+ case "arrayIndex": return node.elementType;
402
+ case "jsonPath": return node.scalarType ?? "jsonb";
403
+ case "jsonRows":
404
+ case "jsonObject": return "jsonb";
405
+ case "tsvector": return "tsvector";
406
+ case "searchHeadline": return "text";
407
+ case "window": return expressionSqlType({
408
+ ...expression,
409
+ node: node.expression
410
+ });
411
+ case "relativeWindow": return expressionSqlType({
412
+ ...expression,
413
+ node: node.value
414
+ });
415
+ case "coalesce": return node.values[0] ? expressionSqlType({
416
+ ...expression,
417
+ node: node.values[0]
418
+ }) : "derived";
419
+ case "binary": return node.sqlType ?? expressionSqlType({
420
+ ...expression,
421
+ node: node.left
422
+ });
423
+ case "aggregate": return node.numeric ? "numeric" : node.name === "COUNT" ? "bigint" : node.value ? expressionSqlType({
424
+ ...expression,
425
+ node: node.value
426
+ }) : "derived";
427
+ case "subquery": return node.query.selection[0] ? expressionSqlType(node.query.selection[0]) : "derived";
428
+ default: return expression.codec?.parameterCast ?? expression.codec?.sqlType ?? "derived";
429
+ }
430
+ };
431
+ /** Recover a projection's shape without changing the expression used in SQL. */
432
+ const expressionSource = (expression) => {
433
+ const node = expression.node;
434
+ const source = node.kind === "column" ? node.description.binding.projection?.[node.description.column.name] : node.kind === "jsonPath" ? node.target : node.kind === "subquery" ? node.query.selection[0] : void 0;
435
+ if (source) return expressionSource(source);
436
+ const value = node.kind === "window" ? node.expression : node.kind === "relativeWindow" ? node.value : node.kind === "coalesce" ? node.values[0] : void 0;
437
+ return value ? expressionSource({
438
+ ...expression,
439
+ node: value
440
+ }) : expression;
441
+ };
442
+ //#endregion
443
+ //#region src/query/codecs/json.ts
444
+ /** JSON field and row codecs, matching PostgreSQL JSON projections. */
445
+ const encodeJsonField = (value, codec) => {
446
+ if (value == null) return value;
447
+ if (codec?.parameterCast?.endsWith("[]")) {
448
+ if (!Array.isArray(value)) throw new Error("symmetria: array columns accept arrays");
449
+ return value.map((entry) => encodeJsonField(entry, codec.element));
450
+ }
451
+ const encoded = encodeValue(value, codec);
452
+ return (codec?.parameterCast === "json" || codec?.parameterCast === "jsonb") && typeof encoded === "string" ? JSON.parse(encoded) : encoded;
453
+ };
454
+ /** Composite parameters use the same encoded field values as SQL JSON projections. */
455
+ const jsonRowCodec = (selection, many = false) => {
456
+ let rowDecoder;
457
+ const decodeRow = (row) => (rowDecoder ??= createRowDecoder(selection))(row);
458
+ return Object.freeze({
459
+ parameterCast: "jsonb",
460
+ encode: (value) => {
461
+ const encodeRow = (row) => Object.fromEntries(selection.map((expression) => [expression.outputName, encodeJsonField(row[expression.outputName], expression.codec)]));
462
+ return JSON.stringify(many ? value.map(encodeRow) : encodeRow(value));
463
+ },
464
+ decode: (value) => many ? value.map(decodeRow) : decodeRow(value)
465
+ });
466
+ };
467
+ //#endregion
468
+ //#region src/query/expressions/json-path.ts
469
+ /**
470
+ * JSON path expressions: typed access into jsonb columns with the matching codecs.
471
+ */
472
+ const arrayElement = (expression, position) => {
473
+ const elementType = expressionSqlType(expression).slice(0, -2);
474
+ const codec = expression.codec?.element ?? (["boolean", "bool"].includes(elementType) ? booleanCodec : void 0);
475
+ return {
476
+ outputName: expression.outputName,
477
+ node: {
478
+ kind: "arrayIndex",
479
+ value: expression.node,
480
+ position,
481
+ elementType
482
+ },
483
+ ...codec ? { codec } : {}
484
+ };
485
+ };
486
+ const jsonPathTarget = (expression, key) => {
487
+ const source = expressionSource(expression);
488
+ const node = source.node;
489
+ if (node.kind === "jsonObject") return node.selection.find((field) => field.outputName === key);
490
+ if (node.kind === "jsonRows") return node.many ? typeof key === "number" ? {
491
+ outputName: source.outputName,
492
+ node: {
493
+ kind: "jsonObject",
494
+ selection: node.query.selection
495
+ },
496
+ codec: jsonRowCodec(node.query.selection)
497
+ } : void 0 : node.query.selection.find((field) => field.outputName === key);
498
+ return typeof key === "number" && expressionSqlType(source).endsWith("[]") ? arrayElement(source, key) : void 0;
499
+ };
500
+ const jsonValueCodec = (target) => ({
501
+ parameterCast: "jsonb",
502
+ encode: (value) => {
503
+ const encoded = encodeJsonField(value, target?.codec);
504
+ const type = target ? expressionSqlType(target) : "jsonb";
505
+ return JSON.stringify(encoded == null ? encoded : ["boolean", "bool"].includes(type) && target?.node.kind !== "arrayIndex" ? Boolean(encoded) : type === "bigint" || type.startsWith("numeric") && !type.endsWith("[]") ? String(encoded) : encoded);
506
+ },
507
+ decode: (value) => decodeValue(value, target?.codec)
508
+ });
509
+ const jsonPathDescription = (description, path) => {
510
+ let current = description;
511
+ for (const key of path) {
512
+ if (expressionSqlType(current).endsWith("[]") && typeof key === "number") {
513
+ current = arrayElement(current, key);
514
+ continue;
515
+ }
516
+ const target = jsonPathTarget(current, key);
517
+ const type = target ? expressionSqlType(target) : "jsonb";
518
+ const scalarType = type !== "derived" && type !== "json" && type !== "jsonb" && !type.endsWith("[]") ? type : void 0;
519
+ const codec = scalarType ? target?.codec : jsonValueCodec(target);
520
+ current = {
521
+ outputName: description.outputName,
522
+ node: Object.freeze({
523
+ kind: "jsonPath",
524
+ value: current.node,
525
+ path: Object.freeze([key]),
526
+ ...target ? { target } : {},
527
+ ...scalarType ? { scalarType } : {}
528
+ }),
529
+ ...codec ? { codec } : {}
530
+ };
531
+ }
532
+ return current;
533
+ };
534
+ //#endregion
535
+ //#region src/query/expressions/index.ts
536
+ /**
537
+ * Expression nodes and their fluent API: columns, predicates, orderings, parameters, window functions and raw SQL.
538
+ */
539
+ const COLUMN_EXPRESSION = Symbol("symmetria.query.expression");
540
+ const PREDICATE_EXPRESSION = Symbol("symmetria.query.predicate");
541
+ const ORDERING_EXPRESSION = Symbol("symmetria.query.ordering");
542
+ const NAMED_PARAMETER = Symbol("symmetria.query.parameter");
543
+ const over = (expression, options = {}) => {
544
+ const description = readColumn(expression);
545
+ const ordering = options.orderBy ? Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy] : [];
546
+ const boundary = (value) => {
547
+ if (typeof value === "string") {
548
+ if (![
549
+ "unbounded preceding",
550
+ "current row",
551
+ "unbounded following"
552
+ ].includes(value)) throw new Error("symmetria: invalid window frame boundary");
553
+ return value;
554
+ }
555
+ const names = Object.keys(value);
556
+ const offset = "preceding" in value ? value.preceding : value.following;
557
+ if (names.length !== 1 || !["preceding", "following"].includes(names[0]) || !Number.isSafeInteger(offset) || offset < 0) throw new Error("symmetria: window frame offsets must be nonnegative safe integers");
558
+ return Object.freeze({ ...value });
559
+ };
560
+ const rows = options.rows?.map(boundary);
561
+ if (rows && (rows.length !== 2 || rows[0] === "unbounded following" || rows[1] === "unbounded preceding")) throw new Error("symmetria: invalid window frame bounds");
562
+ return createExpression({
563
+ ...description,
564
+ outputName: expression[COLUMN_EXPRESSION].outputName,
565
+ node: Object.freeze({
566
+ kind: "window",
567
+ expression: description.node,
568
+ partitionBy: Object.freeze((options.partitionBy ?? []).map((column) => readColumn(column).node)),
569
+ orderBy: Object.freeze(ordering.map((entry) => {
570
+ if (!entry || !(ORDERING_EXPRESSION in entry)) throw new Error("symmetria: window orderBy requires ordering expressions");
571
+ return entry[ORDERING_EXPRESSION];
572
+ })),
573
+ ...rows ? { rows: Object.freeze(rows) } : {}
574
+ })
575
+ });
576
+ };
577
+ const windowFunction = (expression) => Object.freeze(Object.assign(Object.create(expression), { over: (options) => over(expression, options) }));
578
+ const rowNumber = () => windowFunction(createExpression({
579
+ node: {
580
+ kind: "raw",
581
+ parts: ["ROW_NUMBER()"]
582
+ },
583
+ outputName: "rowNumber",
584
+ codec: countCodec
585
+ }));
586
+ const rank = () => windowFunction(createExpression({
587
+ node: {
588
+ kind: "raw",
589
+ parts: ["RANK()"]
590
+ },
591
+ outputName: "rank",
592
+ codec: countCodec
593
+ }));
594
+ const denseRank = () => windowFunction(createExpression({
595
+ node: {
596
+ kind: "raw",
597
+ parts: ["DENSE_RANK()"]
598
+ },
599
+ outputName: "denseRank",
600
+ codec: countCodec
601
+ }));
602
+ const relativeWindow = (name, expression, offset, fallback) => {
603
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("symmetria: lag/lead offset must be a nonnegative safe integer");
604
+ const description = readColumn(expression);
605
+ return windowFunction(createExpression({
606
+ ...description,
607
+ outputName: name,
608
+ node: {
609
+ kind: "relativeWindow",
610
+ name,
611
+ value: description.node,
612
+ offset: valueNode(offset),
613
+ ...fallback === void 0 ? {} : { fallback: valueNode(fallback, description.codec) }
614
+ }
615
+ }));
616
+ };
617
+ const lag = (expression, offset = 1, fallback) => relativeWindow("lag", expression, offset, fallback);
618
+ const lead = (expression, offset = 1, fallback) => relativeWindow("lead", expression, offset, fallback);
619
+ const predicate = (description) => Object.freeze({ [PREDICATE_EXPRESSION]: Object.freeze(description) });
620
+ const readPredicate = (value) => {
621
+ if (!value || typeof value !== "object" || !(PREDICATE_EXPRESSION in value)) throw new Error("symmetria: expected a SQL predicate, such as column.is(value)");
622
+ return value[PREDICATE_EXPRESSION];
623
+ };
624
+ const readColumn = (value) => {
625
+ if (!value || typeof value !== "object" || !(COLUMN_EXPRESSION in value)) throw new Error("symmetria: expected a column or SQL expression");
626
+ return value[COLUMN_EXPRESSION];
627
+ };
628
+ const valueNode = (value, codec) => {
629
+ if (value && typeof value === "object" && COLUMN_EXPRESSION in value) {
630
+ const node = value[COLUMN_EXPRESSION].node;
631
+ return node.kind === "placeholder" && codec ? Object.freeze({
632
+ ...node,
633
+ codec
634
+ }) : node;
635
+ }
636
+ if (value === void 0) throw new Error("symmetria: undefined is not a SQL value");
637
+ return Object.freeze({
638
+ kind: "parameter",
639
+ value: cloneParameter(encodeValue(value, codec)),
640
+ ...codec?.parameterCast ? { cast: codec.parameterCast } : {},
641
+ ...codec?.sqlType ? { sqlType: codec.sqlType } : {}
642
+ });
643
+ };
644
+ const readQuery = (query) => {
645
+ if (!query || !(QUERY_PLAN in query) || !query[QUERY_PLAN].selection.length) throw new Error("symmetria: a subquery requires selected fields");
646
+ return query[QUERY_PLAN];
647
+ };
648
+ var OrderingHandle = class {
649
+ [ORDERING_EXPRESSION];
650
+ constructor(description) {
651
+ this[ORDERING_EXPRESSION] = Object.freeze(description);
652
+ }
653
+ get nullsFirst() {
654
+ return ordering({
655
+ ...this[ORDERING_EXPRESSION],
656
+ nulls: "FIRST"
657
+ });
658
+ }
659
+ get nullsLast() {
660
+ return ordering({
661
+ ...this[ORDERING_EXPRESSION],
662
+ nulls: "LAST"
663
+ });
664
+ }
665
+ };
666
+ const ordering = (description) => Object.freeze(new OrderingHandle(description));
667
+ const searchLanguage = (language = "simple") => {
668
+ if (!/^[a-z][a-z0-9_]*$/.test(language)) throw new Error("symmetria: search language must be a PostgreSQL text search configuration name");
669
+ return language;
670
+ };
671
+ const SEARCH_MODES = /* @__PURE__ */ new Set([
672
+ "websearch",
673
+ "plain",
674
+ "phrase",
675
+ "raw"
676
+ ]);
677
+ const searchMode = (mode = "websearch") => {
678
+ if (!SEARCH_MODES.has(mode)) throw new Error("symmetria: search mode must be websearch, plain, phrase or raw");
679
+ return mode;
680
+ };
681
+ const rankOptions = (options) => {
682
+ const { weights, normalization, coverDensity } = options;
683
+ if (weights !== void 0 && (!Array.isArray(weights) || weights.length !== 4 || weights.some((weight) => typeof weight !== "number" || !Number.isFinite(weight) || weight < 0))) throw new Error("symmetria: search weights must be four non-negative numbers in PostgreSQL's order (D, C, B, A)");
684
+ if (normalization !== void 0 && (!Number.isSafeInteger(normalization) || normalization < 0 || normalization > 63)) throw new Error("symmetria: search normalization must be an integer between 0 and 63");
685
+ return {
686
+ ...weights ? { weights: Object.freeze([...weights]) } : {},
687
+ ...normalization === void 0 ? {} : { normalization },
688
+ ...coverDensity ? { coverDensity: true } : {}
689
+ };
690
+ };
691
+ const HEADLINE_OPTIONS = {
692
+ startSel: "string",
693
+ stopSel: "string",
694
+ fragmentDelimiter: "string",
695
+ maxWords: "integer",
696
+ minWords: "integer",
697
+ shortWord: "integer",
698
+ maxFragments: "integer",
699
+ highlightAll: "boolean"
700
+ };
701
+ const headlineOptions = (options) => {
702
+ const result = {};
703
+ for (const [key, value] of Object.entries(options)) {
704
+ if (key === "language" || key === "mode" || value === void 0) continue;
705
+ const expected = HEADLINE_OPTIONS[key];
706
+ if (!expected) throw new Error(`symmetria: unknown headline option "${key}"`);
707
+ if (!(expected === "string" ? typeof value === "string" && !value.includes("\0") : expected === "integer" ? Number.isSafeInteger(value) && value >= 0 : typeof value === "boolean")) throw new Error(`symmetria: headline option "${key}" must be a ${expected === "integer" ? "non-negative integer" : expected}`);
708
+ result[key] = value;
709
+ }
710
+ return Object.freeze(result);
711
+ };
712
+ const matchExpression = (description, branches) => {
713
+ const source = expressionSource(description).node;
714
+ const enumeration = source.kind === "column" ? source.description.column.enumerationValues : void 0;
715
+ const entries = branches && typeof branches === "object" && !Array.isArray(branches) ? Object.entries(branches) : [];
716
+ if (!entries.length || enumeration && (entries.length !== enumeration.length || enumeration.some((name) => !Object.hasOwn(branches, name)))) throw new Error("symmetria: match() requires exactly one branch for every enum value");
717
+ const selected = entries.map(([, value]) => value).filter((value) => !!value && typeof value === "object" && COLUMN_EXPRESSION in value).map(readColumn);
718
+ const selectedDescription = selected.find((expression) => expressionSqlType(expression) !== "derived") ?? selected[0];
719
+ const literal = entries.find(([, value]) => value !== null && !(value && typeof value === "object" && COLUMN_EXPRESSION in value))?.[1];
720
+ const literalType = literal instanceof Date ? "timestamptz" : typeof literal === "bigint" ? "bigint" : typeof literal === "number" ? "double precision" : typeof literal === "boolean" ? "boolean" : "text";
721
+ const selectedType = selectedDescription ? expressionSqlType(selectedDescription) : "derived";
722
+ const sqlType = selectedType !== "derived" ? selectedType : literal !== void 0 || !selectedDescription ? literalType : "derived";
723
+ const codec = selectedDescription?.codec ?? (sqlType === "boolean" ? booleanCodec : codecFor(sqlType));
724
+ const parameterCodec = {
725
+ encode: (value) => {
726
+ const encoded = encodeValue(value, codec);
727
+ return encoded instanceof Date ? encoded.toISOString() : encoded;
728
+ },
729
+ decode: (value) => decodeValue(value, codec),
730
+ ...sqlType === "derived" || sqlType === "enum" ? {} : { parameterCast: sqlType }
731
+ };
732
+ const values = entries.map(([name, result]) => {
733
+ const expression = result && typeof result === "object" && COLUMN_EXPRESSION in result ? readColumn(result) : void 0;
734
+ if (expression && expressionSqlType(expression) !== "derived" && expressionSqlType(expression) !== sqlType) throw new Error("symmetria: match() branches require the same SQL type");
735
+ if (!expression && result !== null && (!selectedDescription && typeof result !== typeof literal || result === void 0)) throw new Error("symmetria: match() branches require compatible scalar values");
736
+ const node = valueNode(result, parameterCodec);
737
+ return Object.freeze({
738
+ when: valueNode(name, description.codec),
739
+ then: node.kind === "parameter" && sqlType !== "derived" && sqlType !== "enum" ? Object.freeze({
740
+ ...node,
741
+ cast: sqlType
742
+ }) : node
743
+ });
744
+ });
745
+ return createExpression({
746
+ outputName: description.outputName,
747
+ ...codec ? { codec } : {},
748
+ node: Object.freeze({
749
+ kind: "case",
750
+ value: description.node,
751
+ branches: Object.freeze(values),
752
+ sqlType
753
+ })
754
+ });
755
+ };
756
+ const compare = (description, operator, value) => {
757
+ if (value === null && operator !== "IS DISTINCT FROM" || value === void 0) throw new Error("symmetria: use is(null) or isNot(null) for NULL comparisons");
758
+ const right = valueNode(value, description.codec);
759
+ return predicate({
760
+ kind: "comparison",
761
+ left: description.node,
762
+ operator,
763
+ right,
764
+ ...right.kind === "placeholder" && right.nullable && (operator === "=" || operator === "<>") ? { nullableParameter: true } : {}
765
+ });
766
+ };
767
+ const membership = (description, values, negated) => {
768
+ if (!Array.isArray(values)) {
769
+ const query = readQuery(values);
770
+ if (query.selection.length !== 1) throw new Error("symmetria: IN requires a single-column subquery");
771
+ return predicate({
772
+ kind: "membership",
773
+ value: description.node,
774
+ values: query,
775
+ negated
776
+ });
777
+ }
778
+ return predicate({
779
+ kind: "membership",
780
+ value: description.node,
781
+ values: Object.freeze(values.map((value) => valueNode(value, description.codec))),
782
+ negated
783
+ });
784
+ };
785
+ const arithmetic = (description, operator, value) => createExpression({
786
+ ...description,
787
+ node: Object.freeze({
788
+ kind: "binary",
789
+ left: description.node,
790
+ operator,
791
+ right: valueNode(value, description.codec)
792
+ })
793
+ });
794
+ /** Callable equality whose string properties are enum-member predicates. */
795
+ const equality = (description, negated) => new Proxy((value) => value === null ? predicate({
796
+ kind: "nullCheck",
797
+ value: description.node,
798
+ negated
799
+ }) : compare(description, negated ? "<>" : "=", value), { get: (target, name) => typeof name === "string" ? compare(description, negated ? "<>" : "=", name) : Reflect.get(target, name) });
800
+ const HANDLE_MEMO = Symbol("symmetria.query.memo");
801
+ /**
802
+ * Column handles share one prototype; an instance owns only its description and
803
+ * a memo for the accessor results. Objects created from a handle inherit both.
804
+ */
805
+ var ColumnHandle = class {
806
+ [COLUMN_EXPRESSION];
807
+ [HANDLE_MEMO];
808
+ constructor(description) {
809
+ this[COLUMN_EXPRESSION] = Object.freeze(description);
810
+ this[HANDLE_MEMO] = {};
811
+ }
812
+ get is() {
813
+ return this[HANDLE_MEMO].is ??= equality(this[COLUMN_EXPRESSION], false);
814
+ }
815
+ get isNot() {
816
+ return this[HANDLE_MEMO].isNot ??= equality(this[COLUMN_EXPRESSION], true);
817
+ }
818
+ get ascending() {
819
+ return this[HANDLE_MEMO].ascending ??= ordering({
820
+ expression: this[COLUMN_EXPRESSION],
821
+ direction: "ASC"
822
+ });
823
+ }
824
+ get descending() {
825
+ return this[HANDLE_MEMO].descending ??= ordering({
826
+ expression: this[COLUMN_EXPRESSION],
827
+ direction: "DESC"
828
+ });
829
+ }
830
+ match(branches) {
831
+ return matchExpression(this[COLUMN_EXPRESSION], branches);
832
+ }
833
+ path(...path) {
834
+ if (!path.length || path.some((part) => typeof part !== "string" && !(typeof part === "number" && Number.isSafeInteger(part) && part >= 0))) throw new Error("symmetria: JSON paths require string keys or nonnegative integer positions");
835
+ return createExpression(jsonPathDescription(this[COLUMN_EXPRESSION], path));
836
+ }
837
+ contains(value) {
838
+ const description = this[COLUMN_EXPRESSION];
839
+ const sqlType = expressionSqlType(description);
840
+ return compare(sqlType === "json" || sqlType === "jsonb" ? {
841
+ ...description,
842
+ codec: codecFor(sqlType)
843
+ } : description, "@>", value);
844
+ }
845
+ overlaps(value) {
846
+ const description = this[COLUMN_EXPRESSION];
847
+ if (expressionSqlType(description).endsWith("[]")) return compare(description, "&&", value);
848
+ return predicate({
849
+ kind: "has",
850
+ value: description.node,
851
+ element: valueNode(value, description.codec),
852
+ json: true,
853
+ overlap: true
854
+ });
855
+ }
856
+ has(value) {
857
+ const description = this[COLUMN_EXPRESSION];
858
+ const json = !expressionSqlType(description).endsWith("[]");
859
+ return predicate({
860
+ kind: "has",
861
+ value: description.node,
862
+ element: valueNode(value, json ? jsonValueCodec(jsonPathTarget(description, 0)) : description.codec?.element),
863
+ ...json ? { json: true } : {}
864
+ });
865
+ }
866
+ length() {
867
+ const description = this[COLUMN_EXPRESSION];
868
+ return createExpression({
869
+ outputName: description.outputName,
870
+ node: Object.freeze({
871
+ kind: "arrayLength",
872
+ value: description.node,
873
+ ...!expressionSqlType(description).endsWith("[]") ? { json: true } : {}
874
+ })
875
+ });
876
+ }
877
+ /** A searchDocument() carries its own configuration; queries against it default to the same one. */
878
+ searchConfiguration(language) {
879
+ const node = this[COLUMN_EXPRESSION].node;
880
+ return searchLanguage(language ?? (node.kind === "tsvector" ? node.language : void 0));
881
+ }
882
+ search(query, options = {}) {
883
+ return predicate({
884
+ kind: "search",
885
+ value: this[COLUMN_EXPRESSION].node,
886
+ query: valueNode(query),
887
+ language: this.searchConfiguration(options.language),
888
+ mode: searchMode(options.mode)
889
+ });
890
+ }
891
+ searchRank(query, options = {}) {
892
+ return createExpression({
893
+ outputName: "searchRank",
894
+ node: Object.freeze({
895
+ kind: "searchRank",
896
+ value: this[COLUMN_EXPRESSION].node,
897
+ query: valueNode(query),
898
+ language: this.searchConfiguration(options.language),
899
+ mode: searchMode(options.mode),
900
+ ...rankOptions(options)
901
+ })
902
+ });
903
+ }
904
+ searchHeadline(query, options = {}) {
905
+ const description = this[COLUMN_EXPRESSION];
906
+ if (expressionSqlType(description) === "tsvector") throw new Error("symmetria: searchHeadline() highlights text; call it on the text column, not on a tsvector");
907
+ return createExpression({
908
+ outputName: "searchHeadline",
909
+ node: Object.freeze({
910
+ kind: "searchHeadline",
911
+ value: description.node,
912
+ query: valueNode(query),
913
+ language: searchLanguage(options.language),
914
+ mode: searchMode(options.mode),
915
+ options: headlineOptions(options)
916
+ })
917
+ });
918
+ }
919
+ distance(operator, name, query) {
920
+ const description = this[COLUMN_EXPRESSION];
921
+ if (!/^vector(\(|$)/.test(expressionSqlType(description))) throw new Error("symmetria: distance operators require a vector column or expression");
922
+ return createExpression({
923
+ outputName: name,
924
+ node: Object.freeze({
925
+ kind: "binary",
926
+ left: description.node,
927
+ operator,
928
+ right: valueNode(query, description.codec),
929
+ sqlType: "double precision"
930
+ })
931
+ });
932
+ }
933
+ l2Distance(query) {
934
+ return this.distance("<->", "l2Distance", query);
935
+ }
936
+ cosineDistance(query) {
937
+ return this.distance("<=>", "cosineDistance", query);
938
+ }
939
+ innerProduct(query) {
940
+ return this.distance("<#>", "innerProduct", query);
941
+ }
942
+ l1Distance(query) {
943
+ return this.distance("<+>", "l1Distance", query);
944
+ }
945
+ as(name) {
946
+ if (!name.length) throw new Error("symmetria: column aliases must be nonempty strings");
947
+ return createExpression({
948
+ ...this[COLUMN_EXPRESSION],
949
+ outputName: name
950
+ });
951
+ }
952
+ above(value) {
953
+ return compare(this[COLUMN_EXPRESSION], ">", value);
954
+ }
955
+ atLeast(value) {
956
+ return compare(this[COLUMN_EXPRESSION], ">=", value);
957
+ }
958
+ below(value) {
959
+ return compare(this[COLUMN_EXPRESSION], "<", value);
960
+ }
961
+ atMost(value) {
962
+ return compare(this[COLUMN_EXPRESSION], "<=", value);
963
+ }
964
+ isDistinctFrom(value) {
965
+ return compare(this[COLUMN_EXPRESSION], "IS DISTINCT FROM", value);
966
+ }
967
+ in(values) {
968
+ return membership(this[COLUMN_EXPRESSION], values, false);
969
+ }
970
+ notIn(values) {
971
+ return membership(this[COLUMN_EXPRESSION], values, true);
972
+ }
973
+ between(lower, upper) {
974
+ const description = this[COLUMN_EXPRESSION];
975
+ return predicate({
976
+ kind: "between",
977
+ value: description.node,
978
+ lower: valueNode(lower, description.codec),
979
+ upper: valueNode(upper, description.codec)
980
+ });
981
+ }
982
+ like(pattern) {
983
+ return compare(this[COLUMN_EXPRESSION], "LIKE", pattern);
984
+ }
985
+ ilike(pattern) {
986
+ return compare(this[COLUMN_EXPRESSION], "ILIKE", pattern);
987
+ }
988
+ plus(value) {
989
+ return arithmetic(this[COLUMN_EXPRESSION], "+", value);
990
+ }
991
+ minus(value) {
992
+ return arithmetic(this[COLUMN_EXPRESSION], "-", value);
993
+ }
994
+ multiply(value) {
995
+ return arithmetic(this[COLUMN_EXPRESSION], "*", value);
996
+ }
997
+ };
998
+ const createExpression = (description) => Object.freeze(new ColumnHandle(description));
999
+ const presentPredicates = (conditions) => Object.freeze(conditions.filter((condition) => condition !== void 0 && condition !== null && condition !== false).map(readPredicate));
1000
+ /** AND of the given predicates; `undefined`, `null` and `false` are skipped. Empty is TRUE. */
1001
+ const and = (...conditions) => predicate({
1002
+ kind: "group",
1003
+ operator: "AND",
1004
+ predicates: presentPredicates(conditions)
1005
+ });
1006
+ /** OR of the given predicates; `undefined`, `null` and `false` are skipped. Empty is FALSE. */
1007
+ const or = (...conditions) => predicate({
1008
+ kind: "group",
1009
+ operator: "OR",
1010
+ predicates: presentPredicates(conditions)
1011
+ });
1012
+ const when = (value, callback) => value === null || value === void 0 ? void 0 : callback(value);
1013
+ const not = (value) => predicate({
1014
+ kind: "not",
1015
+ predicate: readPredicate(value)
1016
+ });
1017
+ const exists = (query) => predicate({
1018
+ kind: "exists",
1019
+ query: readQuery(query),
1020
+ negated: false
1021
+ });
1022
+ const notExists = (query) => predicate({
1023
+ kind: "exists",
1024
+ query: readQuery(query),
1025
+ negated: true
1026
+ });
1027
+ const count = (expression) => createExpression({
1028
+ node: Object.freeze({
1029
+ kind: "aggregate",
1030
+ name: "COUNT",
1031
+ ...expression ? { value: readColumn(expression).node } : {}
1032
+ }),
1033
+ outputName: "count",
1034
+ codec: countCodec
1035
+ });
1036
+ const sum = (expression) => createExpression({
1037
+ node: Object.freeze({
1038
+ kind: "aggregate",
1039
+ name: "SUM",
1040
+ value: readColumn(expression).node,
1041
+ numeric: true
1042
+ }),
1043
+ outputName: "sum",
1044
+ codec: numericCodec
1045
+ });
1046
+ const average = (expression) => createExpression({
1047
+ node: Object.freeze({
1048
+ kind: "aggregate",
1049
+ name: "AVG",
1050
+ value: readColumn(expression).node,
1051
+ numeric: true
1052
+ }),
1053
+ outputName: "average",
1054
+ codec: numericCodec
1055
+ });
1056
+ const minimum = (expression) => {
1057
+ const description = readColumn(expression);
1058
+ return createExpression({
1059
+ ...description,
1060
+ node: Object.freeze({
1061
+ kind: "aggregate",
1062
+ name: "MIN",
1063
+ value: description.node
1064
+ }),
1065
+ outputName: "minimum"
1066
+ });
1067
+ };
1068
+ const maximum = (expression) => {
1069
+ const description = readColumn(expression);
1070
+ return createExpression({
1071
+ ...description,
1072
+ node: Object.freeze({
1073
+ kind: "aggregate",
1074
+ name: "MAX",
1075
+ value: description.node
1076
+ }),
1077
+ outputName: "maximum"
1078
+ });
1079
+ };
1080
+ const coalesce = (expression, fallback) => {
1081
+ const description = readColumn(expression);
1082
+ return createExpression({
1083
+ ...description,
1084
+ node: Object.freeze({
1085
+ kind: "coalesce",
1086
+ values: Object.freeze([description.node, valueNode(fallback, description.codec)])
1087
+ }),
1088
+ outputName: "coalesce"
1089
+ });
1090
+ };
1091
+ const SEARCH_WEIGHTS = /* @__PURE__ */ new Set([
1092
+ "A",
1093
+ "B",
1094
+ "C",
1095
+ "D"
1096
+ ]);
1097
+ /**
1098
+ * A full-text document built from one or more text expressions, optionally grouped by
1099
+ * weight: `searchDocument({ A: post.title, B: [post.body] }, { language: "english" })`.
1100
+ * Compiles to `setweight(to_tsvector(language, coalesce(expr, '')), 'A') || ...`; the
1101
+ * same expression declares a GIN index in `.indexes()`, so the planner can use it.
1102
+ */
1103
+ const searchDocument = (parts, options = {}) => {
1104
+ const collected = [];
1105
+ const add = (part, weight) => {
1106
+ for (const entry of Array.isArray(part) ? part : [part]) collected.push(Object.freeze({
1107
+ value: readColumn(entry).node,
1108
+ ...weight ? { weight } : {}
1109
+ }));
1110
+ };
1111
+ if (parts && typeof parts === "object" && COLUMN_EXPRESSION in parts) add(parts);
1112
+ else if (Array.isArray(parts)) add(parts);
1113
+ else if (parts && typeof parts === "object") for (const [weight, part] of Object.entries(parts)) {
1114
+ if (!SEARCH_WEIGHTS.has(weight)) throw new Error(`symmetria: search weights are A, B, C or D, not "${weight}"`);
1115
+ if (part !== void 0) add(part, weight);
1116
+ }
1117
+ if (!collected.length) throw new Error("symmetria: searchDocument() requires at least one text expression");
1118
+ return createExpression({
1119
+ outputName: "searchDocument",
1120
+ node: Object.freeze({
1121
+ kind: "tsvector",
1122
+ parts: Object.freeze(collected),
1123
+ language: searchLanguage(options.language)
1124
+ })
1125
+ });
1126
+ };
1127
+ const SQL_TEMPLATE = Symbol("symmetria.query.sql");
1128
+ var SqlHandle = class extends ColumnHandle {
1129
+ kind = "sql";
1130
+ [SQL_TEMPLATE];
1131
+ constructor(description, strings, interpolated) {
1132
+ super(description);
1133
+ this[SQL_TEMPLATE] = {
1134
+ strings,
1135
+ interpolated
1136
+ };
1137
+ }
1138
+ get sql() {
1139
+ if (this[SQL_TEMPLATE].interpolated) throw new Error("symmetria: SQL defaults cannot contain interpolations");
1140
+ return this[SQL_TEMPLATE].strings.join("");
1141
+ }
1142
+ };
1143
+ const sqlTemplate = (strings, values, codec, sqlType) => {
1144
+ const parts = [];
1145
+ strings.forEach((text, index) => {
1146
+ parts.push(text);
1147
+ if (index < values.length) parts.push(valueNode(values[index]));
1148
+ });
1149
+ return Object.freeze(new SqlHandle({
1150
+ node: Object.freeze({
1151
+ kind: "raw",
1152
+ parts: Object.freeze(parts),
1153
+ ...sqlType ? { sqlType } : {}
1154
+ }),
1155
+ outputName: "expression",
1156
+ ...codec ? { codec } : {}
1157
+ }, strings, values.length > 0));
1158
+ };
1159
+ /** Interpolations are parameters or expression nodes; only the template's literal text is SQL. */
1160
+ const sql = Object.assign((strings, ...values) => sqlTemplate(strings, values), {
1161
+ /**
1162
+ * A template typed and decoded like a column: `sql.of(bool)` returns booleans on every
1163
+ * driver, `sql.of(timestamptz)` returns Dates and `sql.of(bigint)` bigints.
1164
+ */
1165
+ of: (column) => (strings, ...values) => sqlTemplate(strings, values, column[COLUMN_CODEC] ?? (column.definition.sqlType === "boolean" ? booleanCodec : codecFor(column.definition.sqlType)), column.definition.sqlType) });
1166
+ //#endregion
1167
+ //#region src/schema/computed.ts
1168
+ /** Query-only expressions stay outside serializable migration snapshots. */
1169
+ const computedFields = /* @__PURE__ */ new WeakMap();
1170
+ //#endregion
1171
+ //#region src/query/compile/postgres/search.ts
1172
+ const sqlString = (text) => `'${text.replaceAll("'", "''")}'`;
1173
+ const TSQUERY_FUNCTIONS = {
1174
+ websearch: "websearch_to_tsquery",
1175
+ plain: "plainto_tsquery",
1176
+ phrase: "phraseto_tsquery",
1177
+ raw: "to_tsquery"
1178
+ };
1179
+ const tsquerySql = (query, language, mode) => `${TSQUERY_FUNCTIONS[mode]}(${sqlString(language)}, ${query})`;
1180
+ const searchVectorSql = (value, language, isVector) => isVector ? value : `to_tsvector(${sqlString(language)}, ${value})`;
1181
+ /** `setweight(to_tsvector(lang, coalesce(a, '')), 'A') || ...`; callers add parentheses when an operator follows. */
1182
+ const tsvectorSql = (parts, language) => parts.map(({ value, weight, isVector }) => {
1183
+ const vector = isVector ? value : `to_tsvector(${sqlString(language)}, coalesce(${value}, ''))`;
1184
+ return weight ? `setweight(${vector}, '${weight}')` : vector;
1185
+ }).join(" || ");
1186
+ const searchRankSql = (vector, query, options) => `${options.coverDensity ? "ts_rank_cd" : "ts_rank"}(${[
1187
+ ...options.weights ? [`'{${options.weights.join(",")}}'::real[]`] : [],
1188
+ vector,
1189
+ query,
1190
+ ...options.normalization === void 0 ? [] : [String(options.normalization)]
1191
+ ].join(", ")})`;
1192
+ const HEADLINE_KEYS = {
1193
+ startSel: "StartSel",
1194
+ stopSel: "StopSel",
1195
+ maxWords: "MaxWords",
1196
+ minWords: "MinWords",
1197
+ shortWord: "ShortWord",
1198
+ highlightAll: "HighlightAll",
1199
+ maxFragments: "MaxFragments",
1200
+ fragmentDelimiter: "FragmentDelimiter"
1201
+ };
1202
+ /** The ts_headline() options literal, or undefined when every option is default. */
1203
+ const headlineOptionsSql = (options) => {
1204
+ const entries = Object.keys(HEADLINE_KEYS).flatMap((key) => {
1205
+ const value = options[key];
1206
+ if (value === void 0) return [];
1207
+ const text = typeof value === "string" ? `"${value.replaceAll("\"", "\"\"")}"` : String(value);
1208
+ return [`${HEADLINE_KEYS[key]}=${text}`];
1209
+ });
1210
+ return entries.length ? sqlString(entries.join(", ")) : void 0;
1211
+ };
1212
+ const searchHeadlineSql = (language, text, query, options) => {
1213
+ const literal = headlineOptionsSql(options);
1214
+ return `ts_headline(${sqlString(language)}, ${text}, ${query}${literal ? `, ${literal}` : ""})`;
1215
+ };
1216
+ //#endregion
1217
+ //#region src/query/compile/state.ts
1218
+ const createCompilation = (plan, renderer, placeholder, selectSql) => ({
1219
+ plan,
1220
+ renderer,
1221
+ placeholder,
1222
+ parameters: [],
1223
+ commonTables: /* @__PURE__ */ new Map(),
1224
+ visiting: /* @__PURE__ */ new Set(),
1225
+ references: /* @__PURE__ */ new Map(),
1226
+ aliasNames: /* @__PURE__ */ new Map(),
1227
+ expressionCaches: void 0,
1228
+ aggregateReferences: void 0,
1229
+ selectSql
1230
+ });
1231
+ const quoteIdentifier = (identifier) => {
1232
+ if (identifier.length <= 63 && /^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) return `"${identifier}"`;
1233
+ if (!identifier.length || identifier.includes("\0")) throw new Error("symmetria: SQL identifiers must be nonempty and cannot contain null bytes");
1234
+ if (Buffer.byteLength(identifier) > 63) throw new Error(`symmetria: PostgreSQL identifiers cannot exceed 63 bytes: "${identifier}" has ${Buffer.byteLength(identifier)}; shorten the table, column or index name`);
1235
+ return `"${identifier.replaceAll("\"", "\"\"")}"`;
1236
+ };
1237
+ const aliasSql = (compilation, binding) => quoteIdentifier(compilation.aliasNames.get(binding) ?? binding.alias);
1238
+ const parameter = (compilation, value) => {
1239
+ compilation.parameters.push(value);
1240
+ return compilation.renderer.placeholder(compilation.parameters.length);
1241
+ };
1242
+ const nestedAlias = (compilation, prefix, bindings) => {
1243
+ const occupied = new Set(Object.values(bindings).map((binding) => compilation.aliasNames.get(binding) ?? binding.alias));
1244
+ let name = prefix;
1245
+ while (occupied.has(name)) name += "_";
1246
+ return quoteIdentifier(name);
1247
+ };
1248
+ /** Services handed to renderer methods that render within the given bindings. */
1249
+ const renderContext = (compilation, bindings) => ({
1250
+ parameter: (value) => parameter(compilation, value),
1251
+ nestedAlias: (prefix) => nestedAlias(compilation, prefix, bindings),
1252
+ quote: quoteIdentifier
1253
+ });
1254
+ //#endregion
1255
+ //#region src/query/select/scope.ts
1256
+ /** Runtime scopes and plan helpers shared by every query module. */
1257
+ const bindingColumns = /* @__PURE__ */ new WeakMap();
1258
+ const limitedPlans = /* @__PURE__ */ new WeakMap();
1259
+ const QUERY_STATE = Symbol("symmetria.query.state");
1260
+ /** one()/first() reuse one derived plan per query so compiled SQL and decoders stay cached. */
1261
+ const limitedPlan = (state, limit) => {
1262
+ let derived = limitedPlans.get(state);
1263
+ if (!derived) {
1264
+ derived = [];
1265
+ limitedPlans.set(state, derived);
1266
+ }
1267
+ return derived[limit] ??= Object.freeze({
1268
+ ...state,
1269
+ limit: typeof state.limit === "number" ? Math.min(state.limit, limit) : limit
1270
+ });
1271
+ };
1272
+ const resultRows = (result) => result.rows;
1273
+ /** The shape callback currently being evaluated: its merged bindings and nesting depth. */
1274
+ const shapeFrame = {
1275
+ bindings: void 0,
1276
+ depth: 0
1277
+ };
1278
+ /** Lazy column handles for one binding; computed fields are evaluated once per binding. */
1279
+ const bindingScope = (binding, bindings) => {
1280
+ const existing = bindingColumns.get(binding);
1281
+ if (existing) return existing;
1282
+ const columns = Object.defineProperties({}, Object.fromEntries(binding.table.columns.map((column) => {
1283
+ let expression;
1284
+ return [column.name, {
1285
+ enumerable: true,
1286
+ get: () => expression ??= createExpression({
1287
+ node: Object.freeze({
1288
+ kind: "column",
1289
+ description: Object.freeze({
1290
+ binding,
1291
+ column
1292
+ })
1293
+ }),
1294
+ outputName: column.name,
1295
+ ...binding.codecs[column.name] ? { codec: binding.codecs[column.name] } : {}
1296
+ })
1297
+ }];
1298
+ })));
1299
+ for (const callback of computedFields.get(binding.table) ?? []) for (const [name, selected] of Object.entries(callback(Object.freeze({ ...columns })))) {
1300
+ quoteIdentifier(name);
1301
+ if (Object.hasOwn(columns, name)) throw new Error(`symmetria: duplicate computed field "${name}"`);
1302
+ const description = readColumn(selected);
1303
+ validateNode(description.node, bindings);
1304
+ columns[name] = createExpression({
1305
+ ...description,
1306
+ outputName: name
1307
+ });
1308
+ }
1309
+ const result = Object.freeze(columns);
1310
+ bindingColumns.set(binding, result);
1311
+ return result;
1312
+ };
1313
+ const createScope = (bindings) => Object.freeze(Object.fromEntries(Object.entries(bindings).map(([aliasName, binding]) => [aliasName, bindingScope(binding, bindings)])));
1314
+ /** Every column inside a predicate must belong to the given bindings (subqueries are checked when built). */
1315
+ const validatePredicate = (description, bindings) => {
1316
+ switch (description.kind) {
1317
+ case "comparison":
1318
+ validateNode(description.left, bindings);
1319
+ validateNode(description.right, bindings);
1320
+ break;
1321
+ case "search":
1322
+ validateNode(description.value, bindings);
1323
+ validateNode(description.query, bindings);
1324
+ break;
1325
+ case "has":
1326
+ validateNode(description.value, bindings);
1327
+ validateNode(description.element, bindings);
1328
+ break;
1329
+ case "nullCheck":
1330
+ validateNode(description.value, bindings);
1331
+ break;
1332
+ case "group":
1333
+ description.predicates.forEach((predicate) => validatePredicate(predicate, bindings));
1334
+ break;
1335
+ case "not":
1336
+ case "notTrue":
1337
+ validatePredicate(description.predicate, bindings);
1338
+ break;
1339
+ case "membership":
1340
+ validateNode(description.value, bindings);
1341
+ if (Array.isArray(description.values)) description.values.forEach((value) => validateNode(value, bindings));
1342
+ break;
1343
+ case "between":
1344
+ validateNode(description.value, bindings);
1345
+ validateNode(description.lower, bindings);
1346
+ validateNode(description.upper, bindings);
1347
+ }
1348
+ };
1349
+ const validateNode = (node, bindings) => {
1350
+ if (node.kind === "column") {
1351
+ const { binding, column } = node.description;
1352
+ if (!containsBinding(bindings, binding)) throw new Error(`symmetria: column "${binding.alias}.${column.name}" belongs to another query scope`);
1353
+ } else if (node.kind === "raw") node.parts.forEach((part) => {
1354
+ if (typeof part !== "string") validateNode(part, bindings);
1355
+ });
1356
+ else if (node.kind === "binary") {
1357
+ validateNode(node.left, bindings);
1358
+ validateNode(node.right, bindings);
1359
+ } else if (node.kind === "aggregate" && node.value) validateNode(node.value, bindings);
1360
+ else if (node.kind === "case") {
1361
+ validateNode(node.value, bindings);
1362
+ node.branches.forEach((branch) => {
1363
+ validateNode(branch.when, bindings);
1364
+ validateNode(branch.then, bindings);
1365
+ });
1366
+ } else if (node.kind === "coalesce") node.values.forEach((value) => validateNode(value, bindings));
1367
+ else if (node.kind === "jsonObject") node.selection.forEach((expression) => validateNode(expression.node, bindings));
1368
+ else if (node.kind === "jsonPath" || node.kind === "arrayIndex" || node.kind === "arrayLength") validateNode(node.value, bindings);
1369
+ else if (node.kind === "window") {
1370
+ validateNode(node.expression, bindings);
1371
+ node.partitionBy.forEach((value) => validateNode(value, bindings));
1372
+ node.orderBy.forEach((ordering) => validateNode(ordering.expression.node, bindings));
1373
+ } else if (node.kind === "searchRank" || node.kind === "searchHeadline") {
1374
+ validateNode(node.value, bindings);
1375
+ validateNode(node.query, bindings);
1376
+ } else if (node.kind === "tsvector") node.parts.forEach((part) => validateNode(part.value, bindings));
1377
+ };
1378
+ const readSelection = (expressions, bindings) => {
1379
+ if (expressions && typeof expressions === "object" && !Array.isArray(expressions)) {
1380
+ const entries = Object.entries(expressions);
1381
+ if (!entries.length) throw new Error("symmetria: a projection requires at least one field");
1382
+ return Object.freeze(entries.map(([name, selected]) => {
1383
+ quoteIdentifier(name);
1384
+ if (!selected || typeof selected !== "object" && typeof selected !== "function") throw new Error("symmetria: selected fields must be SQL expressions, objects or selected queries");
1385
+ if (QUERY_PLAN in selected) {
1386
+ const query = selected[QUERY_PLAN];
1387
+ if (!query.selection.length) throw new Error("symmetria: nested queries require selected fields");
1388
+ if (Object.values(query.bindings).some((binding) => containsBinding(bindings, binding))) throw new Error("symmetria: nested queries require a distinct source occurrence");
1389
+ return Object.freeze({
1390
+ outputName: name,
1391
+ node: Object.freeze({
1392
+ kind: "jsonRows",
1393
+ query,
1394
+ many: true
1395
+ }),
1396
+ codec: jsonRowCodec(query.selection, true)
1397
+ });
1398
+ }
1399
+ if (COLUMN_EXPRESSION in selected) {
1400
+ const description = readColumn(selected);
1401
+ validateNode(description.node, bindings);
1402
+ return description.outputName === name && Object.isFrozen(description) ? description : Object.freeze({
1403
+ ...description,
1404
+ outputName: name
1405
+ });
1406
+ }
1407
+ const selection = readSelection(selected, bindings);
1408
+ return Object.freeze({
1409
+ outputName: name,
1410
+ node: Object.freeze({
1411
+ kind: "jsonObject",
1412
+ selection
1413
+ }),
1414
+ codec: jsonRowCodec(selection)
1415
+ });
1416
+ }));
1417
+ }
1418
+ if (!Array.isArray(expressions) || !expressions.length) throw new Error("symmetria: a projection requires at least one field");
1419
+ const names = /* @__PURE__ */ new Set();
1420
+ return Object.freeze(expressions.map((expression) => {
1421
+ const description = readColumn(expression);
1422
+ quoteIdentifier(description.outputName);
1423
+ validateNode(description.node, bindings);
1424
+ if (names.has(description.outputName)) throw new Error(`symmetria: duplicate selected name "${description.outputName}"; use .as()`);
1425
+ names.add(description.outputName);
1426
+ return description;
1427
+ }));
1428
+ };
1429
+ const countValue = (name, count) => {
1430
+ if (typeof count !== "number") {
1431
+ const node = readColumn(count).node;
1432
+ if (node.kind !== "placeholder") throw new Error(`symmetria: ${name} requires a number or prepared parameter`);
1433
+ return Object.freeze({
1434
+ ...node,
1435
+ count: true
1436
+ });
1437
+ }
1438
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error(`symmetria: ${name} must be a nonnegative safe integer`);
1439
+ return count;
1440
+ };
1441
+ const EMPTY = Object.freeze([]);
1442
+ const noBindings = Object.freeze({});
1443
+ const emptyBindings = () => noBindings;
1444
+ const initialPlan = (root) => Object.freeze({
1445
+ kind: "select",
1446
+ root,
1447
+ bindings: Object.freeze({ [root.alias]: root }),
1448
+ joins: EMPTY,
1449
+ selection: EMPTY,
1450
+ predicates: EMPTY,
1451
+ ordering: EMPTY,
1452
+ grouping: EMPTY,
1453
+ having: EMPTY,
1454
+ distinct: false
1455
+ });
1456
+ const evaluateContext = (context, callback) => {
1457
+ const previousBindings = shapeFrame.bindings;
1458
+ shapeFrame.bindings = context.bindings;
1459
+ shapeFrame.depth += 1;
1460
+ try {
1461
+ return callback();
1462
+ } finally {
1463
+ shapeFrame.bindings = previousBindings;
1464
+ shapeFrame.depth -= 1;
1465
+ }
1466
+ };
1467
+ const lockPlan = (state, mode, options = {}) => {
1468
+ if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((name) => ![
1469
+ "of",
1470
+ "noWait",
1471
+ "skipLocked"
1472
+ ].includes(name)) || options.noWait !== void 0 && typeof options.noWait !== "boolean" || options.skipLocked !== void 0 && typeof options.skipLocked !== "boolean") throw new Error("symmetria: invalid row lock options");
1473
+ if (options.noWait && options.skipLocked) throw new Error("symmetria: choose either NOWAIT or SKIP LOCKED");
1474
+ if (options.of !== void 0 && (!Array.isArray(options.of) || !options.of.length || options.of.some((alias) => typeof alias !== "string" || !Object.hasOwn(state.bindings, alias)))) throw new Error("symmetria: row locks require existing query aliases");
1475
+ return Object.freeze({
1476
+ ...state,
1477
+ locking: Object.freeze({
1478
+ ...options,
1479
+ mode,
1480
+ ...options.of ? { of: Object.freeze([...options.of]) } : {}
1481
+ })
1482
+ });
1483
+ };
1484
+ const readOrdering = (ordering, bindings) => {
1485
+ const descriptions = (Array.isArray(ordering) ? ordering : [ordering]).map((entry) => {
1486
+ if (!entry || !(ORDERING_EXPRESSION in entry)) throw new Error("symmetria: orderBy() expects ascending or descending expressions");
1487
+ validateNode(entry[ORDERING_EXPRESSION].expression.node, bindings);
1488
+ return entry[ORDERING_EXPRESSION];
1489
+ });
1490
+ if (!descriptions.length) throw new Error("symmetria: orderBy() requires expressions");
1491
+ return descriptions;
1492
+ };
1493
+ const presentSelection = Object.freeze([{
1494
+ outputName: "present",
1495
+ node: Object.freeze({
1496
+ kind: "raw",
1497
+ parts: Object.freeze(["1"])
1498
+ })
1499
+ }]);
1500
+ //#endregion
1501
+ //#region src/schema/table.ts
1502
+ /**
1503
+ * Anonymous tables. `table({...})` takes no name — tables are named by their key
1504
+ * in schema(). `table({...}).indexes((columns) => ({ ... }))` keeps indexes
1505
+ * alongside the column declaration; callbacks run when the schema is assembled.
1506
+ * `.relations((post, { to }) => ({ ... }))` declares condition relations: JOINs
1507
+ * by a predicate without a foreign key (see conditions.ts).
1508
+ *
1509
+ * A column value may be:
1510
+ * - a Column → scalar column
1511
+ * - a keyed schema link → FK + relation, including cyclic references
1512
+ * - another table → FK + relation (`author: users`)
1513
+ * - table.nullable/.unique/.onDelete.* → FK with flags
1514
+ * - a thunk `() => users` → lazy FK (cross-file cycles)
1515
+ * - `self` (with the same chain as tables, e.g. `self.nullable.inverse("children")`) → self-reference
1516
+ */
1517
+ const TABLE = Symbol("symmetria.table");
1518
+ const referenceChain = (target, flags) => {
1519
+ const reference = {
1520
+ kind: "reference",
1521
+ target,
1522
+ flags: Object.freeze({ ...flags })
1523
+ };
1524
+ const getter = (name, nextFlags) => Object.defineProperty(reference, name, {
1525
+ get: () => referenceChain(target, {
1526
+ ...flags,
1527
+ ...nextFlags
1528
+ }),
1529
+ enumerable: false
1530
+ });
1531
+ getter("nullable", { nullable: true });
1532
+ getter("unique", { unique: true });
1533
+ getter("index", { index: true });
1534
+ Object.defineProperty(reference, "onDelete", {
1535
+ get: () => onDeleteChain(target, flags),
1536
+ enumerable: false
1537
+ });
1538
+ Object.defineProperty(reference, "inverse", { value: (name) => referenceChain(target, {
1539
+ ...flags,
1540
+ inverse: name
1541
+ }) });
1542
+ Object.defineProperty(reference, "by", { value: (name) => referenceChain(target, {
1543
+ ...flags,
1544
+ by: name
1545
+ }) });
1546
+ Object.defineProperty(reference, "column", { value: (sqlName) => referenceChain(target, {
1547
+ ...flags,
1548
+ column: sqlName
1549
+ }) });
1550
+ return Object.freeze(reference);
1551
+ };
1552
+ const ON_DELETE_ACTIONS = /* @__PURE__ */ new Map([
1553
+ ["cascade", "cascade"],
1554
+ ["restrict", "restrict"],
1555
+ ["setNull", "set null"],
1556
+ ["noAction", "no action"]
1557
+ ]);
1558
+ const onDeleteChain = (target, flags) => {
1559
+ return new Proxy({}, { get: (_target, key) => {
1560
+ if (typeof key !== "string") return;
1561
+ const action = ON_DELETE_ACTIONS.get(key);
1562
+ if (!action) return;
1563
+ const extraFlags = key === "setNull" ? { nullable: true } : {};
1564
+ return referenceChain(target, {
1565
+ ...flags,
1566
+ ...extraFlags,
1567
+ onDelete: action
1568
+ });
1569
+ } });
1570
+ };
1571
+ /**
1572
+ * A binding over a table that is not assembled yet: references appear as
1573
+ * `${name}Id` columns. primaryKey() and relations() discovery run their
1574
+ * callbacks against it before the schema exists.
1575
+ */
1576
+ const draftBinding = (state) => ({
1577
+ table: {
1578
+ name: "table",
1579
+ sqlName: "table",
1580
+ junction: false,
1581
+ relations: [],
1582
+ columns: Object.entries(state.columns).map(([name, value]) => ({
1583
+ name: isColumn(value) ? name : `${name}Id`,
1584
+ sqlName: name,
1585
+ sqlType: isColumn(value) ? value.definition.sqlType : "reference",
1586
+ notNull: true,
1587
+ unique: false,
1588
+ primaryKey: false
1589
+ }))
1590
+ },
1591
+ alias: "table",
1592
+ codecs: Object.create(null)
1593
+ });
1594
+ const REFERENCE_MODIFIERS = /* @__PURE__ */ new Set([
1595
+ "nullable",
1596
+ "unique",
1597
+ "index",
1598
+ "onDelete",
1599
+ "inverse",
1600
+ "by",
1601
+ "column"
1602
+ ]);
1603
+ const createTable = (columns, indexCallbacks, checkCallbacks = [], primaryKey, computedCallbacks = [], junction = false, relationCallbacks = []) => {
1604
+ const state = {
1605
+ columns: Object.freeze({ ...columns }),
1606
+ indexCallbacks: Object.freeze([...indexCallbacks]),
1607
+ checkCallbacks: Object.freeze([...checkCallbacks]),
1608
+ computedCallbacks: Object.freeze([...computedCallbacks]),
1609
+ relationCallbacks: Object.freeze([...relationCallbacks]),
1610
+ junction,
1611
+ ...primaryKey ? { primaryKey: Object.freeze([...primaryKey]) } : {}
1612
+ };
1613
+ return new Proxy({ [TABLE]: state }, {
1614
+ get: (proxyTarget, key) => {
1615
+ if (key === TABLE) return state;
1616
+ if (typeof key !== "string") return Reflect.get(proxyTarget, key);
1617
+ if (key === "indexes") return (callback) => {
1618
+ if (typeof callback !== "function") throw new Error("symmetria: indexes() expects a callback");
1619
+ return createTable(state.columns, [...state.indexCallbacks, callback], state.checkCallbacks, state.primaryKey, state.computedCallbacks, state.junction, state.relationCallbacks);
1620
+ };
1621
+ if (key === "checks") return (callback) => {
1622
+ if (typeof callback !== "function") throw new Error("symmetria: checks() expects a callback");
1623
+ return createTable(state.columns, state.indexCallbacks, [...state.checkCallbacks, callback], state.primaryKey, state.computedCallbacks, state.junction, state.relationCallbacks);
1624
+ };
1625
+ if (key === "computed") return (callback) => {
1626
+ if (typeof callback !== "function") throw new Error("symmetria: computed() expects a callback");
1627
+ return createTable(state.columns, state.indexCallbacks, state.checkCallbacks, state.primaryKey, [...state.computedCallbacks, callback], state.junction, state.relationCallbacks);
1628
+ };
1629
+ if (key === "relations") return (callback) => {
1630
+ if (typeof callback !== "function") throw new Error("symmetria: relations() expects a callback");
1631
+ return createTable(state.columns, state.indexCallbacks, state.checkCallbacks, state.primaryKey, state.computedCallbacks, state.junction, [...state.relationCallbacks, callback]);
1632
+ };
1633
+ if (key === "primaryKey") return (callback) => {
1634
+ if (state.junction) throw new Error("symmetria: junction tables use both foreign keys as the primary key");
1635
+ if (state.primaryKey) throw new Error("symmetria: primaryKey() is already defined");
1636
+ const binding = draftBinding(state);
1637
+ const selection = callback(createScope({ table: binding }).table);
1638
+ if (!Array.isArray(selection) || !selection.length) throw new Error("symmetria: primaryKey() requires columns");
1639
+ const names = selection.map((selected) => {
1640
+ const expression = readColumn(selected);
1641
+ if (expression.node.kind !== "column" || expression.node.description.binding !== binding || expression.outputName !== expression.node.description.column.name) throw new Error("symmetria: primaryKey() requires plain columns from its callback");
1642
+ return expression.node.description.column.name;
1643
+ });
1644
+ if (new Set(names).size !== names.length) throw new Error("symmetria: duplicate primary-key column");
1645
+ return createTable(state.columns, state.indexCallbacks, state.checkCallbacks, names, state.computedCallbacks, state.junction, state.relationCallbacks);
1646
+ };
1647
+ if (REFERENCE_MODIFIERS.has(key)) {
1648
+ if (key === "onDelete") return onDeleteChain(state, {});
1649
+ if (key === "inverse") return (name) => referenceChain(state, { inverse: name });
1650
+ if (key === "by") return (name) => referenceChain(state, { by: name });
1651
+ if (key === "column") return (sqlName) => referenceChain(state, { column: sqlName });
1652
+ return referenceChain(state, { [key]: true });
1653
+ }
1654
+ if (key in state.columns) return {
1655
+ kind: "columnReference",
1656
+ table: state,
1657
+ key
1658
+ };
1659
+ },
1660
+ has: (proxyTarget, key) => {
1661
+ return key === TABLE || key === "indexes" || key === "checks" || key === "primaryKey" || key === "computed" || key === "relations" || typeof key === "string" && key in state.columns || Reflect.has(proxyTarget, key);
1662
+ }
1663
+ });
1664
+ };
1665
+ /** Names come from schema keys; index callbacks run after all references are resolved. */
1666
+ const table = (columns) => createTable(columns, []);
1667
+ /**
1668
+ * Explicit many-to-many link table: exactly two references form a composite primary
1669
+ * key and both sides receive through relations. Extra data columns are allowed.
1670
+ */
1671
+ const junction = (columns) => {
1672
+ const entries = Object.entries(columns);
1673
+ if (entries.filter(([, value]) => !isColumn(value)).length !== 2) throw new Error("symmetria: junction() requires exactly two table references");
1674
+ if (entries.some(([name, value]) => name === "id" || isColumn(value) && value.definition.primaryKey)) throw new Error("symmetria: junction tables use both foreign keys as the primary key; remove id and primaryKey columns");
1675
+ return createTable(columns, [], [], void 0, [], true, []);
1676
+ };
1677
+ /** Self-reference marker: `parent: self.nullable.onDelete.cascade.inverse("children")`. */
1678
+ const self = referenceChain("self", {});
1679
+ const isTable = (value) => {
1680
+ return (typeof value === "object" || typeof value === "function") && value !== null && TABLE in value;
1681
+ };
1682
+ const isReferenceInput = (value) => {
1683
+ return typeof value === "object" && value !== null && value.kind === "reference";
1684
+ };
1685
+ const isColumnReference = (value) => {
1686
+ return typeof value === "object" && value !== null && value.kind === "columnReference";
1687
+ };
1688
+ const tableState = (value) => {
1689
+ if (!isTable(value)) throw new Error("symmetria: expected a table");
1690
+ return value[TABLE];
1691
+ };
1692
+ //#endregion
1693
+ //#region src/schema/ddl-expressions.ts
1694
+ const literalSQL = (value) => {
1695
+ if (value === null) return "NULL";
1696
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
1697
+ if (typeof value === "bigint") return value.toString();
1698
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
1699
+ if (value instanceof Date) return `${literalSQL(value.toISOString())}::timestamptz`;
1700
+ if (value instanceof Uint8Array) return `'\\x${Buffer.from(value).toString("hex")}'::bytea`;
1701
+ if (typeof value === "string" && !value.includes("\0")) return `E'${value.replaceAll("\\", "\\\\").replaceAll("'", "''")}'`;
1702
+ throw new Error("symmetria: unsupported schema literal; use an encoded scalar or SQL expression");
1703
+ };
1704
+ /** Trusted schema expressions, with literal parameters and caller-owned column scope. */
1705
+ const ddlExpressions = (columnSQL) => {
1706
+ /** Raw SQL is opaque: parenthesize it wherever an operator could bind into it. */
1707
+ const operandSQL = (node) => node.kind === "raw" ? `(${valueSQL(node)})` : valueSQL(node);
1708
+ const valueSQL = (node) => {
1709
+ switch (node.kind) {
1710
+ case "column": return columnSQL(node);
1711
+ case "jsonPath": return `(${valueSQL(node.value)} ${node.scalarType ? "#>>" : "#>"} ARRAY[${node.path.map((part) => `${literalSQL(String(part))}::text`).join(", ")}])${node.scalarType ? `::${node.scalarType}` : ""}`;
1712
+ case "arrayIndex": return `(${valueSQL(node.value)})[(CASE WHEN ${node.position}::bigint < cardinality(${valueSQL(node.value)}) THEN array_lower(${valueSQL(node.value)}, 1)::bigint + ${node.position}::bigint END)::integer]`;
1713
+ case "parameter": return `${literalSQL(node.value)}${node.cast ? `::text::${node.cast}` : ""}`;
1714
+ case "raw": return node.parts.map((part) => typeof part === "string" ? part : operandSQL(part)).join("");
1715
+ case "binary": return `(${operandSQL(node.left)} ${node.operator} ${operandSQL(node.right)})`;
1716
+ case "case": return `(CASE ${valueSQL(node.value)} ${node.branches.map((branch) => `WHEN ${valueSQL(branch.when)} THEN ${valueSQL(branch.then)}`).join(" ")} END)`;
1717
+ case "coalesce": return `COALESCE(${node.values.map(valueSQL).join(", ")})`;
1718
+ case "tsvector": return tsvectorSql(node.parts.map((part) => ({
1719
+ value: valueSQL(part.value),
1720
+ ...part.weight ? { weight: part.weight } : {},
1721
+ isVector: part.value.kind === "column" && part.value.description.column.sqlType === "tsvector"
1722
+ })), node.language);
1723
+ default: throw new Error("symmetria: schema expressions cannot contain aggregates, subqueries or placeholders");
1724
+ }
1725
+ };
1726
+ const predicateSQL = (condition) => {
1727
+ switch (condition.kind) {
1728
+ case "comparison": return `${operandSQL(condition.left)} ${condition.operator} ${operandSQL(condition.right)}`;
1729
+ case "nullCheck": return `${operandSQL(condition.value)} IS ${condition.negated ? "NOT " : ""}NULL`;
1730
+ case "group":
1731
+ if (!condition.predicates.length) return condition.operator === "AND" ? "TRUE" : "FALSE";
1732
+ return `(${condition.predicates.map(predicateSQL).join(` ${condition.operator} `)})`;
1733
+ case "not": return `NOT (${predicateSQL(condition.predicate)})`;
1734
+ case "between": return `${operandSQL(condition.value)} BETWEEN ${operandSQL(condition.lower)} AND ${operandSQL(condition.upper)}`;
1735
+ case "membership":
1736
+ if (!Array.isArray(condition.values)) throw new Error("symmetria: schema expressions cannot contain subqueries");
1737
+ if (!condition.values.length) return condition.negated ? "TRUE" : "FALSE";
1738
+ return `${operandSQL(condition.value)} ${condition.negated ? "NOT " : ""}IN (${condition.values.map(valueSQL).join(", ")})`;
1739
+ case "search": throw new Error("symmetria: full-text predicates are not supported in schema expressions; index the document with searchDocument() instead");
1740
+ default: throw new Error("symmetria: schema expressions cannot contain subqueries");
1741
+ }
1742
+ };
1743
+ return {
1744
+ valueSQL,
1745
+ predicateSQL
1746
+ };
1747
+ };
1748
+ //#endregion
1749
+ //#region src/schema/indexes.ts
1750
+ /**
1751
+ * Index definitions: declaration, snapshot shape and CREATE INDEX generation including $createIndexes.
1752
+ */
1753
+ const INDEX_DEFINITION = Symbol("symmetria.index");
1754
+ const OPERATOR_CLASS = Symbol("symmetria.index.opclass");
1755
+ const INDEX_METHODS = Object.freeze([
1756
+ "btree",
1757
+ "hash",
1758
+ "gin",
1759
+ "gist",
1760
+ "spgist",
1761
+ "brin",
1762
+ "hnsw",
1763
+ "ivfflat"
1764
+ ]);
1765
+ /** Methods that index exactly one column without ordering or INCLUDE (pgvector). */
1766
+ const VECTOR_METHODS = Object.freeze(["hnsw", "ivfflat"]);
1767
+ const IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
1768
+ /** Attaches a PostgreSQL operator class to an index key (`text_pattern_ops`, `vector_cosine_ops`, ...). */
1769
+ const operatorClass = (key, name) => {
1770
+ if (!IDENTIFIER.test(name)) throw new Error(`symmetria: invalid operator class "${name}"`);
1771
+ return Object.freeze({ [OPERATOR_CLASS]: Object.freeze({
1772
+ key,
1773
+ name
1774
+ }) });
1775
+ };
1776
+ /** `WITH (m = 16, ef_construction = 64)` storage parameters, validated as identifiers and scalars. */
1777
+ const storageOptions = (options) => {
1778
+ const entries = Object.entries(options).filter(([, value]) => value !== void 0);
1779
+ if (!entries.length) throw new Error("symmetria: with() requires at least one storage option");
1780
+ for (const [name, value] of entries) {
1781
+ if (!IDENTIFIER.test(name)) throw new Error(`symmetria: invalid index storage option "${name}"`);
1782
+ if (!(typeof value === "number" && Number.isFinite(value) || typeof value === "string" && value.length && !/[\0']/.test(value))) throw new Error(`symmetria: index storage option "${name}" must be a finite number or a plain string`);
1783
+ }
1784
+ return Object.freeze(Object.fromEntries(entries.sort(([left], [right]) => left < right ? -1 : 1)));
1785
+ };
1786
+ const defineIndex = (description) => {
1787
+ const result = {
1788
+ [INDEX_DEFINITION]: Object.freeze(description),
1789
+ using: (method) => {
1790
+ if (!INDEX_METHODS.includes(method)) throw new Error(`symmetria: unsupported index method "${method}"`);
1791
+ return defineIndex({
1792
+ ...description,
1793
+ method
1794
+ });
1795
+ },
1796
+ with: (options) => defineIndex({
1797
+ ...description,
1798
+ with: storageOptions(options)
1799
+ }),
1800
+ include: (first, ...columns) => defineIndex({
1801
+ ...description,
1802
+ include: Object.freeze([first, ...columns])
1803
+ }),
1804
+ where: (condition) => defineIndex({
1805
+ ...description,
1806
+ where: readPredicate(condition)
1807
+ })
1808
+ };
1809
+ Object.defineProperty(result, "unique", { get: () => defineIndex({
1810
+ ...description,
1811
+ unique: true
1812
+ }) });
1813
+ return Object.freeze(result);
1814
+ };
1815
+ const index = (...[first, ...keys]) => {
1816
+ if (!first) throw new Error("symmetria: an index requires at least one key");
1817
+ return defineIndex({
1818
+ keys: Object.freeze([first, ...keys]),
1819
+ unique: false,
1820
+ method: "btree",
1821
+ include: Object.freeze([])
1822
+ });
1823
+ };
1824
+ const applyIndexes = (snapshot, codecs, callback, tableName) => {
1825
+ const bindings = Object.fromEntries(snapshot.tables.filter((table) => tableName === void 0 || table.name === tableName).map((table) => [table.name, Object.freeze({
1826
+ table,
1827
+ alias: table.name,
1828
+ codecs: Object.freeze(codecMap(Object.fromEntries(table.columns.flatMap((column) => {
1829
+ const codec = codecs[table.name]?.[column.name] ?? codecFor(column.sqlType);
1830
+ return codec ? [[column.name, codec]] : [];
1831
+ }))))
1832
+ })]));
1833
+ const definitions = callback(createScope(bindings));
1834
+ const names = new Set(snapshot.tables.flatMap((table) => [table.sqlName, ...(table.indexes ?? []).map((definition) => definition.sqlName)]));
1835
+ for (const [name, definition] of Object.entries(definitions)) {
1836
+ if (!definition || !(INDEX_DEFINITION in definition)) throw new Error(`symmetria: "${name}" is not an index definition`);
1837
+ quoteIdentifier(name);
1838
+ const sqlName = tableName === void 0 ? snakeCase(name) : `${bindings[tableName].table.sqlName}_${snakeCase(name)}_idx`;
1839
+ quoteIdentifier(sqlName);
1840
+ if (names.has(sqlName)) throw new Error(`symmetria: duplicate SQL index name "${sqlName}"`);
1841
+ names.add(sqlName);
1842
+ const description = definition[INDEX_DEFINITION];
1843
+ let owner;
1844
+ const columnSql = (node) => {
1845
+ if (node.kind !== "column") throw new Error("symmetria: INCLUDE requires plain columns");
1846
+ const { binding, column } = node.description;
1847
+ if (bindings[binding.alias] !== binding) throw new Error("symmetria: index columns must come from the indexes callback");
1848
+ if (owner && owner !== binding) throw new Error("symmetria: an index can reference only one table");
1849
+ owner = binding;
1850
+ return quoteIdentifier(column.sqlName);
1851
+ };
1852
+ const { valueSQL: valueSql, predicateSQL: predicateSql } = ddlExpressions(columnSql);
1853
+ if (description.unique && description.method !== "btree") throw new Error("symmetria: unique indexes require btree");
1854
+ if (["hash", "spgist"].includes(description.method) && description.keys.length !== 1) throw new Error(`symmetria: ${description.method} indexes require one key`);
1855
+ if (description.include.length && ![
1856
+ "btree",
1857
+ "gist",
1858
+ "spgist"
1859
+ ].includes(description.method)) throw new Error(`symmetria: ${description.method} does not support INCLUDE`);
1860
+ if (VECTOR_METHODS.includes(description.method) && description.keys.length !== 1) throw new Error(`symmetria: ${description.method} indexes require one key`);
1861
+ const keyColumns = /* @__PURE__ */ new Set();
1862
+ const opclasses = [];
1863
+ const keys = description.keys.map((entry) => {
1864
+ const operatorClassKey = entry && OPERATOR_CLASS in entry ? entry[OPERATOR_CLASS] : void 0;
1865
+ const key = operatorClassKey?.key ?? entry;
1866
+ opclasses.push(operatorClassKey?.name ?? null);
1867
+ const ordering = key && ORDERING_EXPRESSION in key ? key[ORDERING_EXPRESSION] : void 0;
1868
+ const expression = ordering?.expression ?? readColumn(key);
1869
+ if (ordering && description.method !== "btree") throw new Error("symmetria: ordered index keys require btree");
1870
+ const expressionSql = valueSql(expression.node);
1871
+ if (expression.node.kind === "column") keyColumns.add(expressionSql);
1872
+ return `${expression.node.kind === "column" ? expressionSql : `(${expressionSql})`}${ordering ? ` ${ordering.direction}${ordering.nulls ? ` NULLS ${ordering.nulls}` : ""}` : ""}`;
1873
+ });
1874
+ if (!owner) throw new Error("symmetria: index keys must reference a table column");
1875
+ const include = description.include.map((column) => columnSql(readColumn(column).node));
1876
+ if (new Set(include).size !== include.length || include.some((column) => keyColumns.has(column))) throw new Error("symmetria: duplicate INCLUDE column or key");
1877
+ const where = description.where ? predicateSql(description.where) : void 0;
1878
+ const indexSnapshot = Object.freeze({
1879
+ name,
1880
+ sqlName,
1881
+ unique: description.unique,
1882
+ method: description.method,
1883
+ keys: Object.freeze(keys),
1884
+ include: Object.freeze(include),
1885
+ ...where === void 0 ? {} : { where },
1886
+ ...opclasses.some(Boolean) ? { opclasses: Object.freeze(opclasses) } : {},
1887
+ ...description.with ? { with: description.with } : {}
1888
+ });
1889
+ owner.table.indexes = Object.freeze([...owner.table.indexes ?? [], indexSnapshot]);
1890
+ }
1891
+ };
1892
+ /** A snapshot key with its operator class inserted before any trailing ordering. */
1893
+ const indexKeySQL = (key, opclass) => {
1894
+ if (!opclass) return key;
1895
+ const ordering = /(?:\s+(?:ASC|DESC))?(?:\s+NULLS\s+(?:FIRST|LAST))?$/.exec(key);
1896
+ return `${key.slice(0, ordering.index)} ${opclass}${key.slice(ordering.index)}`;
1897
+ };
1898
+ /** The `(key opclass, ...)`, `INCLUDE`, `WITH` and `WHERE` clauses shared by every CREATE INDEX renderer. */
1899
+ const indexClausesSQL = (definition) => `(${definition.keys.map((key, position) => indexKeySQL(key, definition.opclasses?.[position] ?? null)).join(", ")})${definition.include.length ? ` INCLUDE (${definition.include.join(", ")})` : ""}${definition.with ? ` WITH (${Object.entries(definition.with).map(([name, value]) => `${name} = ${typeof value === "number" ? value : `'${value.replaceAll("'", "''")}'`}`).join(", ")})` : ""}${definition.where === void 0 ? "" : ` WHERE ${definition.where}`}`;
1900
+ const createIndexesSQL = (snapshot, options = {}) => snapshot.tables.flatMap((table) => (table.indexes ?? []).map((definition) => ({
1901
+ sql: `CREATE ${definition.unique ? "UNIQUE " : ""}INDEX ${options.concurrently ? "CONCURRENTLY " : ""}${options.ifNotExists ? "IF NOT EXISTS " : ""}${quoteIdentifier(definition.sqlName)} ON ${quoteIdentifier(table.sqlName)} USING ${definition.method} ${indexClausesSQL(definition)}`,
1902
+ parameters: []
1903
+ })));
1904
+ const createIndexQuery = (snapshot, executor, options = {}, transaction = false) => {
1905
+ if (transaction && options.concurrently) throw new Error("symmetria: CREATE INDEX CONCURRENTLY cannot run inside a transaction");
1906
+ const settings = Object.freeze({ ...options });
1907
+ return Object.freeze({
1908
+ toSQL: () => createIndexesSQL(snapshot, settings),
1909
+ execute: async () => {
1910
+ if (!executor) throw new Error("symmetria: configure a driver or executor before creating indexes");
1911
+ for (const query of createIndexesSQL(snapshot, settings)) await executor(query);
1912
+ }
1913
+ });
1914
+ };
1915
+ //#endregion
1916
+ //#region src/schema/checks.ts
1917
+ /**
1918
+ * CHECK constraints: declaration on tables and their snapshot/DDL representation.
1919
+ */
1920
+ const applyChecks = (snapshot, codecs, tableName, callback) => {
1921
+ const table = snapshot.tables.find((candidate) => candidate.name === tableName);
1922
+ const binding = {
1923
+ table,
1924
+ alias: tableName,
1925
+ codecs: codecMap(Object.fromEntries(table.columns.flatMap((column) => {
1926
+ const codec = codecs[tableName]?.[column.name] ?? codecFor(column.sqlType);
1927
+ return codec ? [[column.name, codec]] : [];
1928
+ })))
1929
+ };
1930
+ const expressions = ddlExpressions((node) => {
1931
+ if (node.description.binding !== binding) throw new Error("symmetria: checks require columns from their table callback");
1932
+ return quoteIdentifier(node.description.column.sqlName);
1933
+ });
1934
+ const names = new Set((table.checks ?? []).map((check) => check.sqlName));
1935
+ for (const [name, condition] of Object.entries(callback(createScope({ [tableName]: binding })[tableName]))) {
1936
+ quoteIdentifier(name);
1937
+ const sqlName = `${table.sqlName}_${snakeCase(name)}_check`;
1938
+ quoteIdentifier(sqlName);
1939
+ if (names.has(sqlName)) throw new Error(`symmetria: duplicate check constraint "${sqlName}"`);
1940
+ names.add(sqlName);
1941
+ table.checks = Object.freeze([...table.checks ?? [], Object.freeze({
1942
+ name,
1943
+ sqlName,
1944
+ expression: expressions.predicateSQL(readPredicate(condition))
1945
+ })]);
1946
+ }
1947
+ };
1948
+ //#endregion
1949
+ //#region src/schema/assembly.ts
1950
+ /**
1951
+ * Snapshot assembler. The public schema() in model.ts lowers reusable declarations
1952
+ * into fresh table handles before calling this.
1953
+ * Tables get their names from the object keys,
1954
+ * relations are derived from FK shape:
1955
+ * - `author: users` → posts.author + reverse users.posts
1956
+ * - `user: users.unique` → 1:1, reverse is a single object
1957
+ * - `junction({ post, tag })` → composite PK over both FKs and M:N through relations
1958
+ *
1959
+ * Colliding reverse names require overrides; self-reference reverses are created
1960
+ * only when explicitly named. Public schema() translates .inverse() modifiers
1961
+ * into overrides before assembly.
1962
+ */
1963
+ const snakeCase = (name) => {
1964
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
1965
+ };
1966
+ /** The column a reference points at: its `by()` column (unique or the key) or the target's primary key. */
1967
+ const referencedColumn = (table, reference) => {
1968
+ const { by } = reference.flags;
1969
+ if (by === void 0) {
1970
+ if (!reference.target.primaryKey) throw new Error(`symmetria: "${table.key}.${reference.key}" references "${reference.target.key}", which has no primary key`);
1971
+ return reference.target.primaryKey;
1972
+ }
1973
+ const scalar = reference.target.scalars.find((column) => column.key === by);
1974
+ if (!scalar) throw new Error(`symmetria: "${table.key}.${reference.key}" references unknown column "${reference.target.key}.${by}"`);
1975
+ if (!scalar.definition.unique && !(reference.target.keys.length === 1 && reference.target.keys[0] === by)) throw new Error(`symmetria: "${table.key}.${reference.key}" references "${reference.target.key}.${by}", which must be a unique column or the primary key`);
1976
+ return {
1977
+ key: scalar.key,
1978
+ sqlName: snakeCase(scalar.key),
1979
+ definition: scalar.definition
1980
+ };
1981
+ };
1982
+ const assembleSchema = (tables, overrides = {}, conditions = {}) => {
1983
+ const analyzedTables = [];
1984
+ const tablesByState = /* @__PURE__ */ new Map();
1985
+ for (const [key, handle] of Object.entries(tables)) {
1986
+ const state = tableState(handle);
1987
+ if (state.key !== void 0) throw new Error(`symmetria: table "${state.key}" is already part of a schema (passed as "${key}")`);
1988
+ state.key = key;
1989
+ state.sqlName = snakeCase(key);
1990
+ const analyzedTable = {
1991
+ key,
1992
+ state,
1993
+ scalars: [],
1994
+ references: [],
1995
+ isJunction: state.junction,
1996
+ keys: []
1997
+ };
1998
+ analyzedTables.push(analyzedTable);
1999
+ tablesByState.set(state, analyzedTable);
2000
+ }
2001
+ for (const analyzedTable of analyzedTables) {
2002
+ for (const [key, value] of Object.entries(analyzedTable.state.columns)) if (isColumn(value)) analyzedTable.scalars.push({
2003
+ key,
2004
+ definition: value.definition
2005
+ });
2006
+ else if (isTable(value)) analyzedTable.references.push({
2007
+ key,
2008
+ target: resolveTarget(tablesByState, value[TABLE], analyzedTable),
2009
+ flags: {},
2010
+ self: false
2011
+ });
2012
+ else if (isReferenceInput(value)) {
2013
+ const reference = value;
2014
+ if (reference.target === "self") analyzedTable.references.push({
2015
+ key,
2016
+ target: analyzedTable,
2017
+ flags: reference.flags,
2018
+ self: true
2019
+ });
2020
+ else if (typeof reference.target === "function") analyzedTable.references.push({
2021
+ key,
2022
+ target: resolveTarget(tablesByState, tableState(reference.target()), analyzedTable),
2023
+ flags: reference.flags,
2024
+ self: false
2025
+ });
2026
+ else analyzedTable.references.push({
2027
+ key,
2028
+ target: resolveTarget(tablesByState, reference.target, analyzedTable),
2029
+ flags: reference.flags,
2030
+ self: false
2031
+ });
2032
+ } else if (typeof value === "function") analyzedTable.references.push({
2033
+ key,
2034
+ target: resolveTarget(tablesByState, tableState(value()), analyzedTable),
2035
+ flags: {},
2036
+ self: false
2037
+ });
2038
+ else throw new Error(`symmetria: "${analyzedTable.key}.${key}" is not a column, table reference or thunk (got ${value === null ? "null" : typeof value})`);
2039
+ if (analyzedTable.isJunction && analyzedTable.references.length !== 2) throw new Error(`symmetria: junction "${analyzedTable.key}" requires exactly two table references`);
2040
+ const marked = analyzedTable.scalars.filter((column) => column.definition.primaryKey).map((column) => column.key);
2041
+ const keys = analyzedTable.state.primaryKey ?? (analyzedTable.isJunction ? analyzedTable.references.map((reference) => `${reference.key}Id`) : marked.length ? marked : analyzedTable.scalars.some((column) => column.key === "id") ? ["id"] : []);
2042
+ analyzedTable.keys = keys;
2043
+ if (analyzedTable.state.primaryKey && marked.some((name) => !keys.includes(name))) throw new Error("symmetria: conflicting primary-key declarations");
2044
+ for (const name of keys) {
2045
+ const scalar = analyzedTable.scalars.find((column) => column.key === name);
2046
+ const reference = analyzedTable.references.find((column) => `${column.key}Id` === name);
2047
+ if (!scalar && !reference) throw new Error(`symmetria: unknown primary-key column "${name}"`);
2048
+ if (scalar && !scalar.definition.notNull || reference?.flags.nullable) throw new Error("symmetria: primary-key columns cannot be nullable");
2049
+ }
2050
+ for (const scalar of analyzedTable.scalars) scalar.definition = {
2051
+ ...scalar.definition,
2052
+ primaryKey: keys.includes(scalar.key)
2053
+ };
2054
+ const primaryKeyColumn = keys.length === 1 ? analyzedTable.scalars.find((column) => column.key === keys[0]) : void 0;
2055
+ if (primaryKeyColumn) analyzedTable.primaryKey = {
2056
+ key: primaryKeyColumn.key,
2057
+ sqlName: snakeCase(primaryKeyColumn.key),
2058
+ definition: primaryKeyColumn.definition
2059
+ };
2060
+ }
2061
+ const relations = new Map(analyzedTables.map((analyzedTable) => [analyzedTable.key, []]));
2062
+ const namedRelations = /* @__PURE__ */ new Set();
2063
+ const addRelation = (tableKey, relation) => {
2064
+ const list = relations.get(tableKey);
2065
+ const clash = list.find((existingRelation) => existingRelation.name === relation.name);
2066
+ if (clash) {
2067
+ const advice = clash.kind === "condition" || relation.kind === "condition" ? "Rename the condition relation in relations()." : `Name it explicitly in schema overrides: schema({...}, { ${tableKey}: { <name>: <table>.<foreignKeyColumn> } })`;
2068
+ throw new Error(`symmetria: relation name "${relation.name}" on "${tableKey}" is ambiguous (${clash.origin} vs ${relation.origin}). ${advice}`);
2069
+ }
2070
+ list.push(relation);
2071
+ };
2072
+ for (const analyzedTable of analyzedTables) for (const reference of analyzedTable.references) addRelation(analyzedTable.key, {
2073
+ name: reference.key,
2074
+ kind: "one",
2075
+ target: reference.target.key,
2076
+ foreignKey: `${reference.key}Id`,
2077
+ nullable: reference.flags.nullable === true,
2078
+ origin: `${analyzedTable.key}.${reference.key}`
2079
+ });
2080
+ for (const [tableKey, definitions] of Object.entries(overrides)) {
2081
+ if (!relations.has(tableKey)) throw new Error(`symmetria: overrides refer to unknown table "${tableKey}"`);
2082
+ for (const [relationName, columnReference] of Object.entries(definitions)) {
2083
+ if (!isColumnReference(columnReference)) throw new Error(`symmetria: override "${tableKey}.${relationName}" must be a column reference`);
2084
+ const source = tablesByState.get(columnReference.table);
2085
+ if (!source) throw new Error(`symmetria: override "${tableKey}.${relationName}" points outside this schema`);
2086
+ const reference = source.references.find((candidate) => candidate.key === columnReference.key);
2087
+ if (!reference) throw new Error(`symmetria: override "${tableKey}.${relationName}": "${source.key}.${columnReference.key}" is not a reference column`);
2088
+ if (source.isJunction) {
2089
+ const other = source.references.find((candidate) => candidate !== reference);
2090
+ if (!other) throw new Error(`symmetria: junction "${source.key}" needs two reference columns`);
2091
+ if (reference.target.key !== tableKey && other.target.key !== tableKey) throw new Error(`symmetria: override "${tableKey}.${relationName}": junction "${source.key}" does not touch "${tableKey}"`);
2092
+ const [sourceReference, targetReference] = reference.target.key === tableKey ? [reference, other] : [other, reference];
2093
+ addRelation(tableKey, {
2094
+ name: relationName,
2095
+ kind: "through",
2096
+ target: targetReference.target.key,
2097
+ junction: source.key,
2098
+ sourceForeignKey: `${sourceReference.key}Id`,
2099
+ targetForeignKey: `${targetReference.key}Id`,
2100
+ origin: `override through ${source.key}`
2101
+ });
2102
+ namedRelations.add(`${source.key}.${sourceReference.key}:through`);
2103
+ } else {
2104
+ if (reference.target.key !== tableKey) throw new Error(`symmetria: override "${tableKey}.${relationName}": "${source.key}.${columnReference.key}" references "${reference.target.key}", not "${tableKey}"`);
2105
+ addRelation(tableKey, {
2106
+ name: relationName,
2107
+ kind: reference.flags.unique ? "one" : "many",
2108
+ target: source.key,
2109
+ foreignKey: `${reference.key}Id`,
2110
+ reverse: true,
2111
+ origin: `override reverse of ${source.key}.${reference.key}`
2112
+ });
2113
+ namedRelations.add(`${source.key}.${reference.key}:reverse`);
2114
+ }
2115
+ }
2116
+ }
2117
+ for (const [tableKey, entries] of Object.entries(conditions)) {
2118
+ if (!relations.has(tableKey)) throw new Error(`symmetria: condition relations refer to unknown table "${tableKey}"`);
2119
+ for (const entry of entries ?? []) {
2120
+ if (!relations.has(entry.target)) throw new Error(`symmetria: relation "${tableKey}.${entry.name}" points to unknown table "${entry.target}"`);
2121
+ addRelation(tableKey, {
2122
+ name: entry.name,
2123
+ kind: "condition",
2124
+ target: entry.target,
2125
+ many: entry.many,
2126
+ nullable: true,
2127
+ origin: `condition ${tableKey}.${entry.name}`
2128
+ });
2129
+ if (entry.inverse !== void 0) addRelation(entry.target, {
2130
+ name: entry.inverse,
2131
+ kind: "condition",
2132
+ target: tableKey,
2133
+ many: true,
2134
+ nullable: true,
2135
+ reverse: true,
2136
+ inverseOf: entry.name,
2137
+ origin: `inverse of condition ${tableKey}.${entry.name}`
2138
+ });
2139
+ }
2140
+ }
2141
+ for (const analyzedTable of analyzedTables) {
2142
+ for (const reference of analyzedTable.references) {
2143
+ if (reference.self) continue;
2144
+ if (namedRelations.has(`${analyzedTable.key}.${reference.key}:reverse`)) continue;
2145
+ addRelation(reference.target.key, {
2146
+ name: analyzedTable.key,
2147
+ kind: reference.flags.unique ? "one" : "many",
2148
+ target: analyzedTable.key,
2149
+ foreignKey: `${reference.key}Id`,
2150
+ reverse: true,
2151
+ origin: `reverse of ${analyzedTable.key}.${reference.key}`
2152
+ });
2153
+ }
2154
+ if (analyzedTable.isJunction) {
2155
+ const [firstReference, secondReference] = analyzedTable.references;
2156
+ for (const [sourceReference, targetReference] of [[firstReference, secondReference], [secondReference, firstReference]]) {
2157
+ if (namedRelations.has(`${analyzedTable.key}.${sourceReference.key}:through`)) continue;
2158
+ addRelation(sourceReference.target.key, {
2159
+ name: targetReference.target.key,
2160
+ kind: "through",
2161
+ target: targetReference.target.key,
2162
+ junction: analyzedTable.key,
2163
+ sourceForeignKey: `${sourceReference.key}Id`,
2164
+ targetForeignKey: `${targetReference.key}Id`,
2165
+ origin: `M:N through ${analyzedTable.key}`
2166
+ });
2167
+ }
2168
+ }
2169
+ }
2170
+ const snapshot = { tables: [...analyzedTables.map((analyzedTable) => {
2171
+ const columns = analyzedTable.scalars.map((column) => ({
2172
+ name: column.key,
2173
+ sqlName: snakeCase(column.key),
2174
+ sqlType: column.definition.sqlType,
2175
+ notNull: column.definition.notNull,
2176
+ unique: column.definition.unique,
2177
+ primaryKey: column.definition.primaryKey,
2178
+ ...column.definition.default !== void 0 ? { default: column.definition.default } : {},
2179
+ ...column.definition.enumerationValues !== void 0 ? { enumerationValues: column.definition.enumerationValues } : {}
2180
+ }));
2181
+ for (const reference of analyzedTable.references) {
2182
+ const targetColumn = referencedColumn(analyzedTable, reference);
2183
+ reference.targetColumn = targetColumn;
2184
+ const sqlName = reference.flags.column ?? `${snakeCase(reference.key)}_id`;
2185
+ if (!/^[a-z_][a-z0-9_]*$/.test(sqlName)) throw new Error(`symmetria: "${analyzedTable.key}.${reference.key}" column name "${sqlName}" must be a lowercase identifier`);
2186
+ columns.push({
2187
+ name: `${reference.key}Id`,
2188
+ sqlName,
2189
+ sqlType: targetColumn.definition.sqlType,
2190
+ notNull: reference.flags.nullable !== true,
2191
+ unique: reference.flags.unique === true,
2192
+ primaryKey: analyzedTable.keys.includes(`${reference.key}Id`),
2193
+ references: {
2194
+ table: reference.target.state.sqlName,
2195
+ column: targetColumn.sqlName,
2196
+ onDelete: reference.flags.onDelete ?? "restrict"
2197
+ }
2198
+ });
2199
+ }
2200
+ const sqlNames = /* @__PURE__ */ new Set();
2201
+ for (const column of columns) {
2202
+ if (sqlNames.has(column.sqlName)) throw new Error(`symmetria: "${analyzedTable.key}" declares two columns named "${column.sqlName}"`);
2203
+ sqlNames.add(column.sqlName);
2204
+ }
2205
+ const tableRelations = relations.get(analyzedTable.key).map(({ origin: _origin, ...relation }) => relation);
2206
+ return {
2207
+ name: analyzedTable.key,
2208
+ sqlName: analyzedTable.state.sqlName,
2209
+ junction: analyzedTable.isJunction,
2210
+ columns,
2211
+ relations: tableRelations,
2212
+ ...analyzedTable.state.primaryKey ? { primaryKey: analyzedTable.state.primaryKey.map((name) => columns.find((column) => column.name === name)?.sqlName ?? snakeCase(name)) } : {}
2213
+ };
2214
+ })].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0) };
2215
+ for (const analyzedTable of analyzedTables) {
2216
+ const indexedColumns = [...analyzedTable.scalars.filter((column) => column.definition.index && !column.definition.unique && !(column.definition.primaryKey && analyzedTable.primaryKey)).map((column) => column.key), ...analyzedTable.references.filter((reference, position) => reference.flags.index && !reference.flags.unique && !(analyzedTable.state.primaryKey?.length === 1 && analyzedTable.state.primaryKey[0] === `${reference.key}Id`) && !(analyzedTable.isJunction && position === 0)).map((reference) => `${reference.key}Id`)];
2217
+ if (!analyzedTable.state.indexCallbacks.length && !analyzedTable.state.checkCallbacks.length && !indexedColumns.length) continue;
2218
+ const codecs = Object.fromEntries([...analyzedTable.scalars.map((column) => [column.key, analyzedTable.state.columns[column.key]]), ...analyzedTable.references.map((reference) => [`${reference.key}Id`, reference.target.state.columns[reference.targetColumn.key]])].flatMap(([name, column]) => isColumn(column) && column[COLUMN_CODEC] ? [[name, column[COLUMN_CODEC]]] : []));
2219
+ for (const callback of analyzedTable.state.indexCallbacks) applyIndexes(snapshot, { [analyzedTable.key]: codecs }, (scope) => callback(scope[analyzedTable.key]), analyzedTable.key);
2220
+ if (indexedColumns.length) applyIndexes(snapshot, { [analyzedTable.key]: codecs }, (scope) => Object.fromEntries(indexedColumns.map((name) => [name, index(scope[analyzedTable.key][name])])), analyzedTable.key);
2221
+ for (const callback of analyzedTable.state.checkCallbacks) applyChecks(snapshot, { [analyzedTable.key]: codecs }, analyzedTable.key, callback);
2222
+ }
2223
+ return snapshot;
2224
+ };
2225
+ const resolveTarget = (tablesByState, state, source) => {
2226
+ const found = tablesByState.get(state);
2227
+ if (!found) throw new Error(`symmetria: "${source.key}" references a table that is not part of this schema() call`);
2228
+ return found;
2229
+ };
2230
+ //#endregion
2231
+ export { count as $, createRowDecoder as $t, readOrdering as A, date as At, renderContext as B, smallint as Bt, createScope as C, COLUMN_BUILDER as Ct, limitedPlan as D, builderExample as Dt, initialPlan as E, bool as Et, validatePredicate as F, isColumn as Ft, tsquerySql as G, typedColumn as Gt, searchRankSql as H, time as Ht, aliasSql as I, jsonb as It, COLUMN_EXPRESSION as J, bigintCodec as Jt, tsvectorSql as K, uuid as Kt, createCompilation as L, numeric as Lt, resultRows as M, inet as Mt, shapeFrame as N, int as Nt, lockPlan as O, bytea as Ot, validateNode as P, interval as Pt, coalesce as Q, codecMap as Qt, parameter as R, oneOf as Rt, countValue as S, expressionSqlType as St, evaluateContext as T, bigint as Tt, searchVectorSql as U, timestamptz as Ut, searchHeadlineSql as V, text as Vt, sqlString as W, tsvector as Wt, and as X, cloneParameter as Xt, NAMED_PARAMETER as Y, booleanCodec as Yt, average as Z, codecFor as Zt, table as _, sql as _t, applyIndexes as a, maximum as at, QUERY_STATE as b, when as bt, index as c, notExists as ct, TABLE as d, predicate as dt, encodeValue as en, createExpression as et, draftBinding as f, rank as ft, self as g, searchDocument as gt, junction as h, rowNumber as ht, INDEX_METHODS as i, lead as it, readSelection as j, doublePrecision as jt, presentSelection as k, customType as kt, indexClausesSQL as l, or as lt, isTable as m, readPredicate as mt, snakeCase as n, exists as nt, createIndexQuery as o, minimum as ot, isReferenceInput as p, readColumn as pt, computedFields as q, varchar as qt, applyChecks as r, lag as rt, createIndexesSQL as s, not as st, assembleSchema as t, numericCodec as tn, denseRank as tt, operatorClass as u, over as ut, tableState as v, sum as vt, emptyBindings as w, COLUMN_CODEC as wt, bindingScope as x, jsonRowCodec as xt, EMPTY as y, valueNode as yt, quoteIdentifier as z, real as zt };
2232
+
2233
+ //# sourceMappingURL=assembly-B-tpaqlp.js.map