@prisma-next/sql-relational-core 0.5.0-dev.7 → 0.5.0-dev.71

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.
Files changed (72) hide show
  1. package/README.md +65 -1
  2. package/dist/{errors-D3xmG4h-.mjs → errors-Cb03_kgU.mjs} +2 -2
  3. package/dist/{errors-D3xmG4h-.mjs.map → errors-Cb03_kgU.mjs.map} +1 -1
  4. package/dist/{errors-ChY_dHam.d.mts → errors-DCg-36g-.d.mts} +2 -2
  5. package/dist/errors-DCg-36g-.d.mts.map +1 -0
  6. package/dist/exports/ast.d.mts +154 -85
  7. package/dist/exports/ast.d.mts.map +1 -1
  8. package/dist/exports/ast.mjs +229 -1289
  9. package/dist/exports/ast.mjs.map +1 -1
  10. package/dist/exports/codec-descriptor-registry.d.mts +17 -0
  11. package/dist/exports/codec-descriptor-registry.d.mts.map +1 -0
  12. package/dist/exports/codec-descriptor-registry.mjs +40 -0
  13. package/dist/exports/codec-descriptor-registry.mjs.map +1 -0
  14. package/dist/exports/errors.d.mts +1 -4
  15. package/dist/exports/errors.mjs +2 -3
  16. package/dist/exports/expression.d.mts +84 -0
  17. package/dist/exports/expression.d.mts.map +1 -0
  18. package/dist/exports/expression.mjs +62 -0
  19. package/dist/exports/expression.mjs.map +1 -0
  20. package/dist/exports/plan.d.mts +3 -2
  21. package/dist/exports/plan.mjs +1 -17
  22. package/dist/exports/query-lane-context.d.mts +2 -3
  23. package/dist/exports/query-lane-context.mjs +1 -1
  24. package/dist/exports/types.d.mts +3 -4
  25. package/dist/exports/types.mjs +1 -1
  26. package/dist/index.d.mts +10 -11
  27. package/dist/index.mjs +6 -5
  28. package/dist/plan-CZ6CFuSX.d.mts +24 -0
  29. package/dist/plan-CZ6CFuSX.d.mts.map +1 -0
  30. package/dist/query-lane-context-DaimN0zf.d.mts +174 -0
  31. package/dist/query-lane-context-DaimN0zf.d.mts.map +1 -0
  32. package/dist/sql-execution-plan-DgcD75jn.d.mts +32 -0
  33. package/dist/sql-execution-plan-DgcD75jn.d.mts.map +1 -0
  34. package/dist/types-BnLrX_Vr.d.mts +23 -0
  35. package/dist/types-BnLrX_Vr.d.mts.map +1 -0
  36. package/dist/{types-k9pir8XY.d.mts → types-Czw4j_wY.d.mts} +18 -25
  37. package/dist/types-Czw4j_wY.d.mts.map +1 -0
  38. package/dist/{types-C3Hg-CVz.d.mts → types-hwPoFZX2.d.mts} +36 -23
  39. package/dist/types-hwPoFZX2.d.mts.map +1 -0
  40. package/dist/types-vA5134SY.mjs +1072 -0
  41. package/dist/types-vA5134SY.mjs.map +1 -0
  42. package/package.json +16 -12
  43. package/src/ast/adapter-types.ts +6 -14
  44. package/src/ast/codec-types.ts +90 -372
  45. package/src/ast/sql-codec-helpers.ts +79 -0
  46. package/src/ast/sql-codecs.ts +285 -125
  47. package/src/ast/types.ts +170 -175
  48. package/src/ast/util.ts +23 -0
  49. package/src/ast/validate-param-refs.ts +39 -0
  50. package/src/codec-descriptor-registry.ts +52 -0
  51. package/src/exports/ast.ts +2 -0
  52. package/src/exports/codec-descriptor-registry.ts +1 -0
  53. package/src/exports/expression.ts +1 -0
  54. package/src/exports/plan.ts +1 -0
  55. package/src/exports/types.ts +1 -0
  56. package/src/expression.ts +134 -0
  57. package/src/index.ts +1 -0
  58. package/src/plan.ts +11 -30
  59. package/src/query-lane-context.ts +35 -55
  60. package/src/runtime-scope.ts +20 -0
  61. package/src/sql-execution-plan.ts +28 -0
  62. package/src/types.ts +9 -22
  63. package/dist/codec-types-DcEITed4.d.mts +0 -144
  64. package/dist/codec-types-DcEITed4.d.mts.map +0 -1
  65. package/dist/errors-ChY_dHam.d.mts.map +0 -1
  66. package/dist/exports/plan.mjs.map +0 -1
  67. package/dist/plan-Cs65hb-E.d.mts +0 -28
  68. package/dist/plan-Cs65hb-E.d.mts.map +0 -1
  69. package/dist/query-lane-context-UlR8vOkd.d.mts +0 -89
  70. package/dist/query-lane-context-UlR8vOkd.d.mts.map +0 -1
  71. package/dist/types-C3Hg-CVz.d.mts.map +0 -1
  72. package/dist/types-k9pir8XY.d.mts.map +0 -1
@@ -1,1343 +1,234 @@
1
- import { ifDefined } from "@prisma-next/utils/defined";
1
+ import { A as UpdateAst, C as OrExpr, D as SelectAst, E as ProjectionItem, M as isWhereExpr, N as queryAstKinds, O as SubqueryExpr, P as whereExprKinds, S as OperationExpr, T as ParamRef, _ as JsonObjectExpr, a as DefaultValueExpr, b as NotExpr, c as DoNothingConflictAction, d as ExistsExpr, f as IdentifierRef, g as JsonArrayAggExpr, h as JoinAst, i as ColumnRef, j as isQueryAst, k as TableSource, l as DoUpdateSetConflictAction, m as InsertOnConflict, n as AndExpr, o as DeleteAst, p as InsertAst, r as BinaryExpr, s as DerivedTableSource, t as AggregateExpr, u as EqColJoinOn, v as ListExpression, w as OrderByItem, x as NullCheckExpr, y as LiteralExpr } from "../types-vA5134SY.mjs";
2
+ import { CodecDescriptorImpl, CodecImpl, column, voidParamsSchema } from "@prisma-next/framework-components/codec";
2
3
  import { type } from "arktype";
3
-
4
- //#region src/ast/codec-types.ts
5
- /**
6
- * Implementation of CodecRegistry.
7
- */
8
- var CodecRegistryImpl = class {
9
- _byId = /* @__PURE__ */ new Map();
10
- _byScalar = /* @__PURE__ */ new Map();
11
- /**
12
- * Map-like interface for codec lookup by ID.
13
- * Example: registry.get('pg/text@1')
14
- */
15
- get(id) {
16
- return this._byId.get(id);
17
- }
18
- /**
19
- * Check if a codec with the given ID is registered.
20
- */
21
- has(id) {
22
- return this._byId.has(id);
23
- }
24
- /**
25
- * Get all codecs that handle a given scalar type.
26
- * Returns an empty frozen array if no codecs are found.
27
- * Example: registry.getByScalar('text') → [codec1, codec2, ...]
28
- */
29
- getByScalar(scalar) {
30
- return this._byScalar.get(scalar) ?? Object.freeze([]);
31
- }
32
- /**
33
- * Get the default codec for a scalar type (first registered codec).
34
- * Returns undefined if no codec handles this scalar type.
35
- */
36
- getDefaultCodec(scalar) {
37
- return this._byScalar.get(scalar)?.[0];
38
- }
39
- /**
40
- * Register a codec in the registry.
41
- * Throws an error if a codec with the same ID is already registered.
42
- *
43
- * @param codec - The codec to register
44
- * @throws Error if a codec with the same ID already exists
45
- */
46
- register(codec$1) {
47
- if (this._byId.has(codec$1.id)) throw new Error(`Codec with ID '${codec$1.id}' is already registered`);
48
- this._byId.set(codec$1.id, codec$1);
49
- for (const scalarType of codec$1.targetTypes) {
50
- const existing = this._byScalar.get(scalarType);
51
- if (existing) existing.push(codec$1);
52
- else this._byScalar.set(scalarType, [codec$1]);
53
- }
54
- }
55
- hasTrait(codecId, trait) {
56
- return this._byId.get(codecId)?.traits?.includes(trait) ?? false;
57
- }
58
- traitsOf(codecId) {
59
- return this._byId.get(codecId)?.traits ?? [];
60
- }
61
- /**
62
- * Returns an iterator over all registered codecs.
63
- * Useful for iterating through codecs from another registry.
64
- */
65
- *[Symbol.iterator]() {
66
- for (const codec$1 of this._byId.values()) yield codec$1;
67
- }
68
- /**
69
- * Returns an iterable of all registered codecs.
70
- */
71
- values() {
72
- return this._byId.values();
73
- }
74
- };
75
- /**
76
- * Codec factory - creates a codec with typeId and encode/decode functions.
77
- * Provides identity defaults for encodeJson/decodeJson when not supplied.
78
- */
79
- function codec(config) {
80
- const identity = (v) => v;
81
- return {
82
- id: config.typeId,
83
- targetTypes: config.targetTypes,
84
- ...ifDefined("meta", config.meta),
85
- ...ifDefined("paramsSchema", config.paramsSchema),
86
- ...ifDefined("init", config.init),
87
- ...ifDefined("traits", config.traits ? Object.freeze([...config.traits]) : void 0),
88
- ...ifDefined("renderOutputType", config.renderOutputType),
89
- encode: config.encode,
90
- decode: config.decode,
91
- encodeJson: config.encodeJson ?? identity,
92
- decodeJson: config.decodeJson ?? identity
93
- };
94
- }
95
- /**
96
- * Implementation of CodecDefBuilder.
97
- */
98
- var CodecDefBuilderImpl = class CodecDefBuilderImpl {
99
- _codecs;
100
- CodecTypes;
101
- dataTypes;
102
- constructor(codecs$1) {
103
- this._codecs = codecs$1;
104
- const codecTypes = {};
105
- for (const [, codecImpl] of Object.entries(this._codecs)) {
106
- const codecImplTyped = codecImpl;
107
- codecTypes[codecImplTyped.id] = {
108
- input: void 0,
109
- output: void 0,
110
- traits: void 0
111
- };
112
- }
113
- this.CodecTypes = codecTypes;
114
- const dataTypes = {};
115
- for (const key in this._codecs) if (Object.hasOwn(this._codecs, key)) dataTypes[key] = this._codecs[key].id;
116
- this.dataTypes = dataTypes;
117
- }
118
- add(scalarName, codecImpl) {
119
- return new CodecDefBuilderImpl({
120
- ...this._codecs,
121
- [scalarName]: codecImpl
122
- });
123
- }
124
- /**
125
- * Derive codecDefinitions structure.
126
- */
127
- get codecDefinitions() {
128
- const result = {};
129
- for (const [scalarName, codecImpl] of Object.entries(this._codecs)) {
130
- const codec$1 = codecImpl;
131
- result[scalarName] = {
132
- typeId: codec$1.id,
133
- scalar: scalarName,
134
- codec: codec$1,
135
- input: void 0,
136
- output: void 0,
137
- jsType: void 0
138
- };
139
- }
140
- return result;
141
- }
142
- };
143
- /**
144
- * Create a new codec registry.
145
- */
146
- function createCodecRegistry() {
147
- return new CodecRegistryImpl();
148
- }
149
- /**
150
- * Create a new codec definition builder.
151
- */
152
- function defineCodecs() {
153
- return new CodecDefBuilderImpl({});
154
- }
155
-
156
- //#endregion
157
- //#region src/ast/sql-codecs.ts
4
+ import { runtimeError } from "@prisma-next/framework-components/runtime";
5
+ //#region src/ast/sql-codec-helpers.ts
158
6
  const SQL_CHAR_CODEC_ID = "sql/char@1";
159
7
  const SQL_VARCHAR_CODEC_ID = "sql/varchar@1";
160
8
  const SQL_INT_CODEC_ID = "sql/int@1";
161
9
  const SQL_FLOAT_CODEC_ID = "sql/float@1";
162
10
  const SQL_TEXT_CODEC_ID = "sql/text@1";
163
11
  const SQL_TIMESTAMP_CODEC_ID = "sql/timestamp@1";
164
- const lengthParamsSchema = type({ length: "number.integer > 0" });
165
- const precisionParamsSchema = type({ "precision?": "number.integer >= 0 & number.integer <= 6" });
166
- function createLengthTypeHelper(kind) {
167
- return (params) => ({
168
- kind,
169
- maxLength: params["length"]
170
- });
171
- }
172
- const sqlCharCodec = codec({
173
- typeId: SQL_CHAR_CODEC_ID,
174
- targetTypes: ["char"],
175
- traits: [
176
- "equality",
177
- "order",
178
- "textual"
179
- ],
180
- encode: (value) => value,
181
- decode: (wire) => wire.trimEnd(),
182
- paramsSchema: lengthParamsSchema,
183
- init: createLengthTypeHelper("fixed"),
184
- renderOutputType: (typeParams) => {
185
- const length = typeParams["length"];
186
- if (length === void 0) return void 0;
187
- if (typeof length !== "number" || !Number.isFinite(length) || !Number.isInteger(length)) throw new Error(`renderOutputType: expected integer "length" in typeParams for Char, got ${String(length)}`);
188
- return `Char<${length}>`;
189
- }
190
- });
191
- const sqlVarcharCodec = codec({
192
- typeId: SQL_VARCHAR_CODEC_ID,
193
- targetTypes: ["varchar"],
194
- traits: [
195
- "equality",
196
- "order",
197
- "textual"
198
- ],
199
- encode: (value) => value,
200
- decode: (wire) => wire,
201
- paramsSchema: lengthParamsSchema,
202
- init: createLengthTypeHelper("variable"),
203
- renderOutputType: (typeParams) => {
204
- const length = typeParams["length"];
205
- if (length === void 0) return void 0;
206
- if (typeof length !== "number" || !Number.isFinite(length) || !Number.isInteger(length)) throw new Error(`renderOutputType: expected integer "length" in typeParams for Varchar, got ${String(length)}`);
207
- return `Varchar<${length}>`;
208
- }
209
- });
210
- const sqlIntCodec = codec({
211
- typeId: SQL_INT_CODEC_ID,
212
- targetTypes: ["int"],
213
- traits: [
214
- "equality",
215
- "order",
216
- "numeric"
217
- ],
218
- encode: (value) => value,
219
- decode: (wire) => wire
220
- });
221
- const sqlFloatCodec = codec({
222
- typeId: SQL_FLOAT_CODEC_ID,
223
- targetTypes: ["float"],
224
- traits: [
225
- "equality",
226
- "order",
227
- "numeric"
228
- ],
229
- encode: (value) => value,
230
- decode: (wire) => wire
231
- });
232
- const sqlTextCodec = codec({
233
- typeId: SQL_TEXT_CODEC_ID,
234
- targetTypes: ["text"],
235
- traits: [
236
- "equality",
237
- "order",
238
- "textual"
239
- ],
240
- encode: (value) => value,
241
- decode: (wire) => wire
242
- });
243
- const sqlTimestampCodec = codec({
244
- typeId: SQL_TIMESTAMP_CODEC_ID,
245
- targetTypes: ["timestamp"],
246
- traits: ["equality", "order"],
247
- encode: (value) => value instanceof Date ? value.toISOString() : value,
248
- decode: (wire) => wire instanceof Date ? wire.toISOString() : wire,
249
- paramsSchema: precisionParamsSchema,
250
- renderOutputType: (typeParams) => {
251
- const precision = typeParams["precision"];
252
- if (precision === void 0) return "Timestamp";
253
- if (typeof precision !== "number" || !Number.isFinite(precision) || !Number.isInteger(precision)) throw new Error(`renderOutputType: expected integer "precision" in typeParams for Timestamp, got ${String(precision)}`);
254
- return `Timestamp<${precision}>`;
255
- }
256
- });
257
- const codecs = defineCodecs().add("char", sqlCharCodec).add("varchar", sqlVarcharCodec).add("int", sqlIntCodec).add("float", sqlFloatCodec).add("text", sqlTextCodec).add("timestamp", sqlTimestampCodec);
258
- const sqlCodecDefinitions = codecs.codecDefinitions;
259
- const sqlDataTypes = codecs.dataTypes;
260
-
261
- //#endregion
262
- //#region src/ast/types.ts
263
- function frozenArrayCopy(values) {
264
- return Object.freeze([...values]);
265
- }
266
- function frozenOptionalRecordCopy(value) {
267
- return value === void 0 ? void 0 : Object.freeze({ ...value });
268
- }
269
- function frozenRecordCopy(record) {
270
- return Object.freeze({ ...record });
271
- }
272
- function freezeRows(rows) {
273
- return Object.freeze(rows.map((row) => Object.freeze({ ...row })));
274
- }
275
- function combineAll(folder, thunks) {
276
- let result = folder.empty;
277
- for (const thunk of thunks) {
278
- if (folder.isAbsorbing?.(result)) return result;
279
- result = folder.combine(result, thunk());
280
- }
281
- return result;
282
- }
283
- function rewriteComparable(value, rewriter) {
284
- switch (value.kind) {
285
- case "param-ref": return rewriter.paramRef ? rewriter.paramRef(value) : value;
286
- case "literal": return rewriter.literal ? rewriter.literal(value) : value;
287
- case "list":
288
- if (rewriter.list) return rewriter.list(value);
289
- return value.rewrite(rewriter);
290
- default: return value.rewrite(rewriter);
291
- }
292
- }
293
- function foldComparable(value, folder) {
294
- switch (value.kind) {
295
- case "param-ref": return folder.paramRef ? folder.paramRef(value) : folder.empty;
296
- case "literal": return folder.literal ? folder.literal(value) : folder.empty;
297
- case "list": return value.fold(folder);
298
- default: return value.fold(folder);
299
- }
300
- }
301
- function collectColumnRefsWith(node) {
302
- return node.fold({
303
- empty: [],
304
- combine: (a, b) => [...a, ...b],
305
- columnRef: (columnRef) => [columnRef],
306
- select: (ast) => ast.collectColumnRefs()
307
- });
308
- }
309
- function collectParamRefsWith(node) {
310
- return node.fold({
311
- empty: [],
312
- combine: (a, b) => [...a, ...b],
313
- paramRef: (paramRef) => [paramRef],
314
- select: (ast) => ast.collectParamRefs()
315
- });
316
- }
317
- function sortRefs(tables, columns) {
318
- return {
319
- tables: [...tables].sort((a, b) => a.localeCompare(b)),
320
- columns: [...columns.values()].sort((a, b) => {
321
- const tableCompare = a.table.localeCompare(b.table);
322
- if (tableCompare !== 0) return tableCompare;
323
- return a.column.localeCompare(b.column);
324
- })
325
- };
326
- }
327
- function addColumnRefToRefSets(columnRef, tables, columns) {
328
- if (columnRef.table === "excluded") return;
329
- tables.add(columnRef.table);
330
- const key = `${columnRef.table}.${columnRef.column}`;
331
- if (!columns.has(key)) columns.set(key, {
332
- table: columnRef.table,
333
- column: columnRef.column
334
- });
335
- }
336
- function mergeRefsInto(refs, tables, columns) {
337
- for (const table of refs.tables ?? []) tables.add(table);
338
- for (const column of refs.columns ?? []) addColumnRefToRefSets(new ColumnRef(column.table, column.column), tables, columns);
339
- }
340
- var AstNode = class {
341
- freeze() {
342
- Object.freeze(this);
343
- }
344
- };
345
- var QueryAst = class extends AstNode {
346
- collectColumnRefs() {
347
- return (this.collectRefs().columns ?? []).map((ref) => new ColumnRef(ref.table, ref.column));
348
- }
349
- };
350
- var FromSource = class extends AstNode {};
351
- var Expression = class extends AstNode {
352
- collectColumnRefs() {
353
- return collectColumnRefsWith(this);
354
- }
355
- collectParamRefs() {
356
- return collectParamRefsWith(this);
357
- }
358
- baseColumnRef() {
359
- throw new Error(`${this.constructor.name} does not expose a base column reference`);
360
- }
361
- toExpr() {
362
- return this;
363
- }
364
- not() {
365
- return new NotExpr(this);
366
- }
12
+ const sqlCharEncode = (value) => value;
13
+ const sqlCharDecode = (wire) => wire.trimEnd();
14
+ const sqlCharRenderOutputType = (typeParams) => {
15
+ const length = typeParams.length;
16
+ if (length === void 0) return void 0;
17
+ if (typeof length !== "number" || !Number.isFinite(length) || !Number.isInteger(length)) throw new Error(`renderOutputType: expected integer "length" in typeParams for Char, got ${String(length)}`);
18
+ return `Char<${length}>`;
19
+ };
20
+ const sqlVarcharEncode = (value) => value;
21
+ const sqlVarcharDecode = (wire) => wire;
22
+ const sqlVarcharRenderOutputType = (typeParams) => {
23
+ const length = typeParams.length;
24
+ if (length === void 0) return void 0;
25
+ if (typeof length !== "number" || !Number.isFinite(length) || !Number.isInteger(length)) throw new Error(`renderOutputType: expected integer "length" in typeParams for Varchar, got ${String(length)}`);
26
+ return `Varchar<${length}>`;
27
+ };
28
+ const sqlIntEncode = (value) => value;
29
+ const sqlIntDecode = (wire) => wire;
30
+ const sqlFloatEncode = (value) => value;
31
+ const sqlFloatDecode = (wire) => wire;
32
+ const sqlTextEncode = (value) => value;
33
+ const sqlTextDecode = (wire) => wire;
34
+ const sqlTimestampEncode = (value) => value;
35
+ const sqlTimestampDecode = (wire) => wire;
36
+ const sqlTimestampEncodeJson = (value) => value.toISOString();
37
+ const sqlTimestampDecodeJson = (json) => {
38
+ if (typeof json !== "string") throw new Error(`Expected ISO date string for sql/timestamp@1, got ${typeof json}`);
39
+ const date = new Date(json);
40
+ if (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date string for sql/timestamp@1: ${json}`);
41
+ return date;
42
+ };
43
+ const sqlTimestampRenderOutputType = (typeParams) => {
44
+ const precision = typeParams.precision;
45
+ if (precision === void 0) return "Timestamp";
46
+ if (typeof precision !== "number" || !Number.isFinite(precision) || !Number.isInteger(precision)) throw new Error(`renderOutputType: expected integer "precision" in typeParams for Timestamp, got ${String(precision)}`);
47
+ return `Timestamp<${precision}>`;
367
48
  };
368
- var TableSource = class TableSource extends FromSource {
369
- kind = "table-source";
370
- name;
371
- alias;
372
- constructor(name, alias) {
373
- super();
374
- this.name = name;
375
- this.alias = alias;
376
- this.freeze();
377
- }
378
- static named(name, alias) {
379
- return new TableSource(name, alias);
380
- }
381
- rewrite(rewriter) {
382
- return rewriter.tableSource ? rewriter.tableSource(this) : this;
383
- }
384
- toFromSource() {
385
- return this;
386
- }
387
- collectRefs() {
388
- return {
389
- tables: [this.name],
390
- columns: []
391
- };
392
- }
393
- };
394
- var DerivedTableSource = class DerivedTableSource extends FromSource {
395
- kind = "derived-table-source";
396
- alias;
397
- query;
398
- constructor(alias, query) {
399
- super();
400
- this.alias = alias;
401
- this.query = query;
402
- this.freeze();
403
- }
404
- static as(alias, query) {
405
- return new DerivedTableSource(alias, query);
406
- }
407
- rewrite(rewriter) {
408
- return new DerivedTableSource(this.alias, this.query.rewrite(rewriter));
409
- }
410
- toFromSource() {
411
- return this;
412
- }
413
- collectRefs() {
414
- return this.query.collectRefs();
415
- }
416
- };
417
- var ColumnRef = class ColumnRef extends Expression {
418
- kind = "column-ref";
419
- table;
420
- column;
421
- constructor(table, column) {
422
- super();
423
- this.table = table;
424
- this.column = column;
425
- this.freeze();
426
- }
427
- static of(table, column) {
428
- return new ColumnRef(table, column);
429
- }
430
- accept(visitor) {
431
- return visitor.columnRef(this);
432
- }
433
- rewrite(rewriter) {
434
- return rewriter.columnRef ? rewriter.columnRef(this) : this;
435
- }
436
- fold(folder) {
437
- return folder.columnRef ? folder.columnRef(this) : folder.empty;
438
- }
439
- baseColumnRef() {
440
- return this;
441
- }
442
- };
443
- var IdentifierRef = class IdentifierRef extends Expression {
444
- kind = "identifier-ref";
445
- name;
446
- constructor(name) {
447
- super();
448
- this.name = name;
449
- this.freeze();
450
- }
451
- static of(name) {
452
- return new IdentifierRef(name);
453
- }
454
- accept(visitor) {
455
- return visitor.identifierRef(this);
456
- }
457
- rewrite(rewriter) {
458
- return rewriter.identifierRef ? rewriter.identifierRef(this) : this;
459
- }
460
- fold(folder) {
461
- return folder.identifierRef ? folder.identifierRef(this) : folder.empty;
462
- }
463
- };
464
- var ParamRef = class ParamRef extends Expression {
465
- kind = "param-ref";
466
- value;
467
- name;
468
- codecId;
469
- constructor(value, options) {
470
- super();
471
- this.value = value;
472
- this.name = options?.name;
473
- this.codecId = options?.codecId;
474
- this.freeze();
475
- }
476
- static of(value, options) {
477
- return new ParamRef(value, options);
478
- }
479
- accept(visitor) {
480
- return visitor.param(this);
481
- }
482
- rewrite(rewriter) {
483
- return rewriter.paramRef ? rewriter.paramRef(this) : this;
484
- }
485
- fold(folder) {
486
- return folder.paramRef ? folder.paramRef(this) : folder.empty;
487
- }
488
- };
489
- var DefaultValueExpr = class extends AstNode {
490
- kind = "default-value";
491
- constructor() {
492
- super();
493
- this.freeze();
494
- }
495
- };
496
- var LiteralExpr = class LiteralExpr extends Expression {
497
- kind = "literal";
498
- value;
499
- constructor(value) {
500
- super();
501
- this.value = value;
502
- this.freeze();
503
- }
504
- static of(value) {
505
- return new LiteralExpr(value);
506
- }
507
- accept(visitor) {
508
- return visitor.literal(this);
509
- }
510
- rewrite(rewriter) {
511
- return rewriter.literal ? rewriter.literal(this) : this;
512
- }
513
- fold(folder) {
514
- return folder.literal ? folder.literal(this) : folder.empty;
515
- }
516
- };
517
- var SubqueryExpr = class SubqueryExpr extends Expression {
518
- kind = "subquery";
519
- query;
520
- constructor(query) {
521
- super();
522
- this.query = query;
523
- this.freeze();
524
- }
525
- static of(query) {
526
- return new SubqueryExpr(query);
527
- }
528
- accept(visitor) {
529
- return visitor.subquery(this);
530
- }
531
- rewrite(rewriter) {
532
- return new SubqueryExpr(this.query.rewrite(rewriter));
533
- }
534
- fold(folder) {
535
- return folder.select ? folder.select(this.query) : folder.empty;
536
- }
537
- };
538
- var OperationExpr = class OperationExpr extends Expression {
539
- kind = "operation";
540
- method;
541
- self;
542
- args;
543
- returns;
544
- lowering;
545
- constructor(options) {
546
- super();
547
- this.method = options.method;
548
- this.self = options.self;
549
- this.args = frozenArrayCopy(options.args ?? []);
550
- this.returns = options.returns;
551
- this.lowering = options.lowering;
552
- this.freeze();
553
- }
554
- accept(visitor) {
555
- return visitor.operation(this);
556
- }
557
- rewrite(rewriter) {
558
- return new OperationExpr({
559
- method: this.method,
560
- self: this.self.rewrite(rewriter),
561
- args: this.args.map((arg) => rewriteComparable(arg, rewriter)),
562
- returns: this.returns,
563
- lowering: this.lowering
564
- });
565
- }
566
- fold(folder) {
567
- return combineAll(folder, [() => this.self.fold(folder), ...this.args.map((arg) => () => foldComparable(arg, folder))]);
568
- }
569
- baseColumnRef() {
570
- return this.self.baseColumnRef();
571
- }
572
- };
573
- var AggregateExpr = class AggregateExpr extends Expression {
574
- kind = "aggregate";
575
- fn;
576
- expr;
577
- constructor(fn, expr) {
578
- super();
579
- if (fn !== "count" && expr === void 0) throw new Error(`Aggregate function "${fn}" requires an expression`);
580
- this.fn = fn;
581
- this.expr = expr;
582
- this.freeze();
583
- }
584
- static count(expr) {
585
- return new AggregateExpr("count", expr);
586
- }
587
- static sum(expr) {
588
- return new AggregateExpr("sum", expr);
589
- }
590
- static avg(expr) {
591
- return new AggregateExpr("avg", expr);
592
- }
593
- static min(expr) {
594
- return new AggregateExpr("min", expr);
595
- }
596
- static max(expr) {
597
- return new AggregateExpr("max", expr);
598
- }
599
- accept(visitor) {
600
- return visitor.aggregate(this);
601
- }
602
- rewrite(rewriter) {
603
- return this.expr === void 0 ? this : new AggregateExpr(this.fn, this.expr.rewrite(rewriter));
604
- }
605
- fold(folder) {
606
- return this.expr ? this.expr.fold(folder) : folder.empty;
607
- }
608
- };
609
- var JsonObjectExpr = class JsonObjectExpr extends Expression {
610
- kind = "json-object";
611
- entries;
612
- constructor(entries) {
613
- super();
614
- this.entries = frozenArrayCopy(entries.map((entry) => Object.freeze({ ...entry })));
615
- this.freeze();
616
- }
617
- static entry(key, value) {
618
- return {
619
- key,
620
- value
621
- };
622
- }
623
- static fromEntries(entries) {
624
- return new JsonObjectExpr(entries);
625
- }
626
- accept(visitor) {
627
- return visitor.jsonObject(this);
628
- }
629
- rewrite(rewriter) {
630
- return new JsonObjectExpr(this.entries.map((entry) => ({
631
- key: entry.key,
632
- value: entry.value.kind === "literal" ? rewriter.literal ? rewriter.literal(entry.value) : entry.value : entry.value.rewrite(rewriter)
633
- })));
634
- }
635
- fold(folder) {
636
- return combineAll(folder, this.entries.map((entry) => () => entry.value.kind === "literal" ? folder.literal ? folder.literal(entry.value) : folder.empty : entry.value.fold(folder)));
637
- }
638
- };
639
- var OrderByItem = class OrderByItem extends AstNode {
640
- kind = "order-by-item";
641
- expr;
642
- dir;
643
- constructor(expr, dir) {
644
- super();
645
- this.expr = expr;
646
- this.dir = dir;
647
- this.freeze();
648
- }
649
- static asc(expr) {
650
- return new OrderByItem(expr, "asc");
651
- }
652
- static desc(expr) {
653
- return new OrderByItem(expr, "desc");
654
- }
655
- rewrite(rewriter) {
656
- return new OrderByItem(this.expr.rewrite(rewriter), this.dir);
657
- }
658
- };
659
- var JsonArrayAggExpr = class JsonArrayAggExpr extends Expression {
660
- kind = "json-array-agg";
661
- expr;
662
- onEmpty;
663
- orderBy;
664
- constructor(expr, onEmpty = "null", orderBy) {
665
- super();
666
- this.expr = expr;
667
- this.onEmpty = onEmpty;
668
- this.orderBy = orderBy && orderBy.length > 0 ? frozenArrayCopy(orderBy) : void 0;
669
- this.freeze();
670
- }
671
- static of(expr, onEmpty = "null", orderBy) {
672
- return new JsonArrayAggExpr(expr, onEmpty, orderBy);
673
- }
674
- accept(visitor) {
675
- return visitor.jsonArrayAgg(this);
676
- }
677
- rewrite(rewriter) {
678
- return new JsonArrayAggExpr(this.expr.rewrite(rewriter), this.onEmpty, this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)));
679
- }
680
- fold(folder) {
681
- return combineAll(folder, [() => this.expr.fold(folder), ...(this.orderBy ?? []).map((orderItem) => () => orderItem.expr.fold(folder))]);
682
- }
683
- };
684
- var ListExpression = class ListExpression extends Expression {
685
- kind = "list";
686
- values;
687
- constructor(values) {
688
- super();
689
- this.values = frozenArrayCopy(values);
690
- this.freeze();
691
- }
692
- static of(values) {
693
- return new ListExpression(values);
694
- }
695
- static fromValues(values) {
696
- return new ListExpression(values.map((value) => new LiteralExpr(value)));
697
- }
698
- accept(visitor) {
699
- return visitor.list(this);
700
- }
701
- rewrite(rewriter) {
702
- if (rewriter.list) return rewriter.list(this);
703
- return new ListExpression(this.values.map((value) => value.rewrite(rewriter)));
704
- }
705
- fold(folder) {
706
- if (folder.list) return folder.list(this);
707
- return combineAll(folder, this.values.map((value) => () => value.fold(folder)));
708
- }
709
- };
710
- var BinaryExpr = class BinaryExpr extends Expression {
711
- kind = "binary";
712
- op;
713
- left;
714
- right;
715
- constructor(op, left, right) {
716
- super();
717
- this.op = op;
718
- this.left = left;
719
- this.right = right;
720
- this.freeze();
721
- }
722
- static eq(left, right) {
723
- return new BinaryExpr("eq", left, right);
724
- }
725
- static neq(left, right) {
726
- return new BinaryExpr("neq", left, right);
727
- }
728
- static gt(left, right) {
729
- return new BinaryExpr("gt", left, right);
730
- }
731
- static lt(left, right) {
732
- return new BinaryExpr("lt", left, right);
733
- }
734
- static gte(left, right) {
735
- return new BinaryExpr("gte", left, right);
736
- }
737
- static lte(left, right) {
738
- return new BinaryExpr("lte", left, right);
739
- }
740
- static like(left, right) {
741
- return new BinaryExpr("like", left, right);
742
- }
743
- static in(left, right) {
744
- return new BinaryExpr("in", left, right);
745
- }
746
- static notIn(left, right) {
747
- return new BinaryExpr("notIn", left, right);
748
- }
749
- accept(visitor) {
750
- return visitor.binary(this);
751
- }
752
- rewrite(rewriter) {
753
- return new BinaryExpr(this.op, rewriteComparable(this.left, rewriter), rewriteComparable(this.right, rewriter));
754
- }
755
- fold(folder) {
756
- return combineAll(folder, [() => foldComparable(this.left, folder), () => foldComparable(this.right, folder)]);
757
- }
758
- };
759
- var AndExpr = class AndExpr extends Expression {
760
- kind = "and";
761
- exprs;
762
- constructor(exprs) {
763
- super();
764
- this.exprs = frozenArrayCopy(exprs);
765
- this.freeze();
766
- }
767
- static of(exprs) {
768
- return new AndExpr(exprs);
769
- }
770
- static true() {
771
- return new AndExpr([]);
772
- }
773
- accept(visitor) {
774
- return visitor.and(this);
775
- }
776
- rewrite(rewriter) {
777
- return new AndExpr(this.exprs.map((expr) => expr.rewrite(rewriter)));
778
- }
779
- fold(folder) {
780
- return combineAll(folder, this.exprs.map((expr) => () => expr.fold(folder)));
781
- }
782
- };
783
- var OrExpr = class OrExpr extends Expression {
784
- kind = "or";
785
- exprs;
786
- constructor(exprs) {
787
- super();
788
- this.exprs = frozenArrayCopy(exprs);
789
- this.freeze();
790
- }
791
- static of(exprs) {
792
- return new OrExpr(exprs);
793
- }
794
- static false() {
795
- return new OrExpr([]);
796
- }
797
- accept(visitor) {
798
- return visitor.or(this);
799
- }
800
- rewrite(rewriter) {
801
- return new OrExpr(this.exprs.map((expr) => expr.rewrite(rewriter)));
802
- }
803
- fold(folder) {
804
- return combineAll(folder, this.exprs.map((expr) => () => expr.fold(folder)));
805
- }
806
- };
807
- var ExistsExpr = class ExistsExpr extends Expression {
808
- kind = "exists";
809
- notExists;
810
- subquery;
811
- constructor(subquery, notExists = false) {
812
- super();
813
- this.notExists = notExists;
814
- this.subquery = subquery;
815
- this.freeze();
816
- }
817
- static exists(subquery) {
818
- return new ExistsExpr(subquery, false);
819
- }
820
- static notExists(subquery) {
821
- return new ExistsExpr(subquery, true);
49
+ //#endregion
50
+ //#region src/ast/sql-codecs.ts
51
+ const lengthParamsSchema = type({ "length?": "number.integer > 0" });
52
+ const precisionParamsSchema = type({ "precision?": "number.integer >= 0 & number.integer <= 6" });
53
+ var SqlTextCodec = class extends CodecImpl {
54
+ async encode(value, _ctx) {
55
+ return sqlTextEncode(value);
822
56
  }
823
- accept(visitor) {
824
- return visitor.exists(this);
57
+ async decode(wire, _ctx) {
58
+ return sqlTextDecode(wire);
825
59
  }
826
- rewrite(rewriter) {
827
- return new ExistsExpr(this.subquery.rewrite(rewriter), this.notExists);
60
+ encodeJson(value) {
61
+ return value;
828
62
  }
829
- fold(folder) {
830
- return folder.select ? folder.select(this.subquery) : folder.empty;
63
+ decodeJson(json) {
64
+ return json;
831
65
  }
832
66
  };
833
- var NullCheckExpr = class NullCheckExpr extends Expression {
834
- kind = "null-check";
835
- expr;
836
- isNull;
837
- constructor(expr, isNull) {
838
- super();
839
- this.expr = expr;
840
- this.isNull = isNull;
841
- this.freeze();
842
- }
843
- static isNull(expr) {
844
- return new NullCheckExpr(expr, true);
845
- }
846
- static isNotNull(expr) {
847
- return new NullCheckExpr(expr, false);
848
- }
849
- accept(visitor) {
850
- return visitor.nullCheck(this);
851
- }
852
- rewrite(rewriter) {
853
- return new NullCheckExpr(this.expr.rewrite(rewriter), this.isNull);
854
- }
855
- fold(folder) {
856
- return this.expr.fold(folder);
67
+ var SqlTextDescriptor = class extends CodecDescriptorImpl {
68
+ codecId = SQL_TEXT_CODEC_ID;
69
+ traits = [
70
+ "equality",
71
+ "order",
72
+ "textual"
73
+ ];
74
+ targetTypes = ["text"];
75
+ paramsSchema = voidParamsSchema;
76
+ factory() {
77
+ return () => new SqlTextCodec(this);
857
78
  }
858
79
  };
859
- var NotExpr = class NotExpr extends Expression {
860
- kind = "not";
861
- expr;
862
- constructor(expr) {
863
- super();
864
- this.expr = expr;
865
- this.freeze();
80
+ const sqlTextDescriptor = new SqlTextDescriptor();
81
+ const sqlTextColumn = () => column(sqlTextDescriptor.factory(), sqlTextDescriptor.codecId, void 0, "text");
82
+ var SqlIntCodec = class extends CodecImpl {
83
+ async encode(value, _ctx) {
84
+ return sqlIntEncode(value);
866
85
  }
867
- toWhereExpr() {
868
- return this;
86
+ async decode(wire, _ctx) {
87
+ return sqlIntDecode(wire);
869
88
  }
870
- accept(visitor) {
871
- return visitor.not(this);
89
+ encodeJson(value) {
90
+ return value;
872
91
  }
873
- rewrite(rewriter) {
874
- return new NotExpr(this.expr.rewrite(rewriter));
875
- }
876
- fold(folder) {
877
- return this.expr.fold(folder);
92
+ decodeJson(json) {
93
+ return json;
878
94
  }
879
95
  };
880
- var EqColJoinOn = class EqColJoinOn extends AstNode {
881
- kind = "eq-col-join-on";
882
- left;
883
- right;
884
- constructor(left, right) {
885
- super();
886
- this.left = left;
887
- this.right = right;
888
- this.freeze();
889
- }
890
- static of(left, right) {
891
- return new EqColJoinOn(left, right);
892
- }
893
- rewrite(rewriter) {
894
- return rewriter.eqColJoinOn ? rewriter.eqColJoinOn(this) : this;
96
+ var SqlIntDescriptor = class extends CodecDescriptorImpl {
97
+ codecId = SQL_INT_CODEC_ID;
98
+ traits = [
99
+ "equality",
100
+ "order",
101
+ "numeric"
102
+ ];
103
+ targetTypes = ["int"];
104
+ paramsSchema = voidParamsSchema;
105
+ factory() {
106
+ return () => new SqlIntCodec(this);
895
107
  }
896
108
  };
897
- var JoinAst = class JoinAst extends AstNode {
898
- kind = "join";
899
- joinType;
900
- source;
901
- lateral;
902
- on;
903
- constructor(joinType, source, on, lateral = false) {
904
- super();
905
- this.joinType = joinType;
906
- this.source = source;
907
- this.lateral = lateral;
908
- this.on = on;
909
- this.freeze();
910
- }
911
- static inner(source, on, lateral = false) {
912
- return new JoinAst("inner", source, on, lateral);
109
+ const sqlIntDescriptor = new SqlIntDescriptor();
110
+ const sqlIntColumn = () => column(sqlIntDescriptor.factory(), sqlIntDescriptor.codecId, void 0, "int");
111
+ var SqlFloatCodec = class extends CodecImpl {
112
+ async encode(value, _ctx) {
113
+ return sqlFloatEncode(value);
913
114
  }
914
- static left(source, on, lateral = false) {
915
- return new JoinAst("left", source, on, lateral);
115
+ async decode(wire, _ctx) {
116
+ return sqlFloatDecode(wire);
916
117
  }
917
- static right(source, on, lateral = false) {
918
- return new JoinAst("right", source, on, lateral);
118
+ encodeJson(value) {
119
+ return value;
919
120
  }
920
- static full(source, on, lateral = false) {
921
- return new JoinAst("full", source, on, lateral);
922
- }
923
- rewrite(rewriter) {
924
- return new JoinAst(this.joinType, this.source.rewrite(rewriter), this.on.kind === "eq-col-join-on" ? this.on.rewrite(rewriter) : this.on.rewrite(rewriter), this.lateral);
121
+ decodeJson(json) {
122
+ return json;
925
123
  }
926
124
  };
927
- var ProjectionItem = class ProjectionItem extends AstNode {
928
- kind = "projection-item";
929
- alias;
930
- expr;
931
- constructor(alias, expr) {
932
- super();
933
- this.alias = alias;
934
- this.expr = expr;
935
- this.freeze();
936
- }
937
- static of(alias, expr) {
938
- return new ProjectionItem(alias, expr);
125
+ var SqlFloatDescriptor = class extends CodecDescriptorImpl {
126
+ codecId = SQL_FLOAT_CODEC_ID;
127
+ traits = [
128
+ "equality",
129
+ "order",
130
+ "numeric"
131
+ ];
132
+ targetTypes = ["float"];
133
+ paramsSchema = voidParamsSchema;
134
+ factory() {
135
+ return () => new SqlFloatCodec(this);
939
136
  }
940
137
  };
941
- var SelectAst = class SelectAst extends QueryAst {
942
- kind = "select";
943
- from;
944
- joins;
945
- projection;
946
- where;
947
- orderBy;
948
- distinct;
949
- distinctOn;
950
- groupBy;
951
- having;
952
- limit;
953
- offset;
954
- selectAllIntent;
955
- constructor(options) {
956
- super();
957
- this.from = options.from;
958
- this.joins = options.joins && options.joins.length > 0 ? frozenArrayCopy(options.joins) : void 0;
959
- this.projection = frozenArrayCopy(options.projection);
960
- this.where = options.where;
961
- this.orderBy = options.orderBy && options.orderBy.length > 0 ? frozenArrayCopy(options.orderBy) : void 0;
962
- this.distinct = options.distinct;
963
- this.distinctOn = options.distinctOn && options.distinctOn.length > 0 ? frozenArrayCopy(options.distinctOn) : void 0;
964
- this.groupBy = options.groupBy && options.groupBy.length > 0 ? frozenArrayCopy(options.groupBy) : void 0;
965
- this.having = options.having;
966
- this.limit = options.limit;
967
- this.offset = options.offset;
968
- this.selectAllIntent = frozenOptionalRecordCopy(options.selectAllIntent);
969
- this.freeze();
970
- }
971
- static from(from) {
972
- return new SelectAst({
973
- from,
974
- joins: void 0,
975
- projection: [],
976
- where: void 0,
977
- orderBy: void 0,
978
- distinct: void 0,
979
- distinctOn: void 0,
980
- groupBy: void 0,
981
- having: void 0,
982
- limit: void 0,
983
- offset: void 0,
984
- selectAllIntent: void 0
985
- });
986
- }
987
- withFrom(from) {
988
- return new SelectAst({
989
- ...this,
990
- from
991
- });
992
- }
993
- withJoins(joins) {
994
- return new SelectAst({
995
- ...this,
996
- joins: joins.length > 0 ? joins : void 0
997
- });
998
- }
999
- withProjection(projection) {
1000
- return new SelectAst({
1001
- ...this,
1002
- projection
1003
- });
1004
- }
1005
- addProjection(alias, expr) {
1006
- return new SelectAst({
1007
- ...this,
1008
- projection: [...this.projection, new ProjectionItem(alias, expr)]
1009
- });
1010
- }
1011
- withWhere(where) {
1012
- return new SelectAst({
1013
- ...this,
1014
- where
1015
- });
138
+ const sqlFloatDescriptor = new SqlFloatDescriptor();
139
+ const sqlFloatColumn = () => column(sqlFloatDescriptor.factory(), sqlFloatDescriptor.codecId, void 0, "float");
140
+ var SqlCharCodec = class extends CodecImpl {
141
+ async encode(value, _ctx) {
142
+ return sqlCharEncode(value);
1016
143
  }
1017
- withOrderBy(orderBy) {
1018
- return new SelectAst({
1019
- ...this,
1020
- orderBy: orderBy.length > 0 ? orderBy : void 0
1021
- });
144
+ async decode(wire, _ctx) {
145
+ return sqlCharDecode(wire);
1022
146
  }
1023
- withDistinct(enabled = true) {
1024
- return new SelectAst({
1025
- ...this,
1026
- distinct: enabled ? true : void 0
1027
- });
147
+ encodeJson(value) {
148
+ return value;
1028
149
  }
1029
- withDistinctOn(distinctOn) {
1030
- return new SelectAst({
1031
- ...this,
1032
- distinctOn: distinctOn.length > 0 ? distinctOn : void 0
1033
- });
1034
- }
1035
- withGroupBy(groupBy) {
1036
- return new SelectAst({
1037
- ...this,
1038
- groupBy: groupBy.length > 0 ? groupBy : void 0
1039
- });
1040
- }
1041
- withHaving(having) {
1042
- return new SelectAst({
1043
- ...this,
1044
- having
1045
- });
1046
- }
1047
- withLimit(limit) {
1048
- return new SelectAst({
1049
- ...this,
1050
- limit
1051
- });
1052
- }
1053
- withOffset(offset) {
1054
- return new SelectAst({
1055
- ...this,
1056
- offset
1057
- });
1058
- }
1059
- withSelectAllIntent(selectAllIntent) {
1060
- return new SelectAst({
1061
- ...this,
1062
- selectAllIntent
1063
- });
1064
- }
1065
- rewrite(rewriter) {
1066
- const rewritten = new SelectAst({
1067
- from: this.from.rewrite(rewriter),
1068
- joins: this.joins?.map((join) => join.rewrite(rewriter)),
1069
- projection: this.projection.map((projection) => new ProjectionItem(projection.alias, projection.expr.kind === "literal" ? rewriter.literal ? rewriter.literal(projection.expr) : projection.expr : projection.expr.rewrite(rewriter))),
1070
- where: this.where?.rewrite(rewriter),
1071
- orderBy: this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)),
1072
- distinct: this.distinct,
1073
- distinctOn: this.distinctOn?.map((expr) => expr.rewrite(rewriter)),
1074
- groupBy: this.groupBy?.map((expr) => expr.rewrite(rewriter)),
1075
- having: this.having?.rewrite(rewriter),
1076
- limit: this.limit,
1077
- offset: this.offset,
1078
- selectAllIntent: this.selectAllIntent
1079
- });
1080
- return rewriter.select ? rewriter.select(rewritten) : rewritten;
1081
- }
1082
- collectColumnRefs() {
1083
- const refs = [];
1084
- const pushRefs = (columns) => {
1085
- refs.push(...columns);
1086
- };
1087
- if (this.from.kind === "derived-table-source") pushRefs(this.from.query.collectColumnRefs());
1088
- for (const projection of this.projection) if (!(projection.expr.kind === "literal")) pushRefs(projection.expr.collectColumnRefs());
1089
- if (this.where) pushRefs(this.where.collectColumnRefs());
1090
- if (this.having) pushRefs(this.having.collectColumnRefs());
1091
- for (const orderItem of this.orderBy ?? []) pushRefs(orderItem.expr.collectColumnRefs());
1092
- for (const expr of this.distinctOn ?? []) pushRefs(expr.collectColumnRefs());
1093
- for (const expr of this.groupBy ?? []) pushRefs(expr.collectColumnRefs());
1094
- for (const join of this.joins ?? []) {
1095
- if (join.source.kind === "derived-table-source") pushRefs(join.source.query.collectColumnRefs());
1096
- if (join.on.kind === "eq-col-join-on") refs.push(join.on.left, join.on.right);
1097
- else pushRefs(join.on.collectColumnRefs());
1098
- }
1099
- return refs;
1100
- }
1101
- collectParamRefs() {
1102
- const refs = [];
1103
- const pushRefs = (params) => {
1104
- refs.push(...params);
1105
- };
1106
- if (this.from.kind === "derived-table-source") pushRefs(this.from.query.collectParamRefs());
1107
- for (const projection of this.projection) if (!(projection.expr.kind === "literal")) pushRefs(projection.expr.collectParamRefs());
1108
- if (this.where) pushRefs(this.where.collectParamRefs());
1109
- if (this.having) pushRefs(this.having.collectParamRefs());
1110
- for (const orderItem of this.orderBy ?? []) pushRefs(orderItem.expr.collectParamRefs());
1111
- for (const expr of this.distinctOn ?? []) pushRefs(expr.collectParamRefs());
1112
- for (const expr of this.groupBy ?? []) pushRefs(expr.collectParamRefs());
1113
- for (const join of this.joins ?? []) {
1114
- if (join.source.kind === "derived-table-source") pushRefs(join.source.query.collectParamRefs());
1115
- if (!(join.on.kind === "eq-col-join-on")) pushRefs(join.on.collectParamRefs());
1116
- }
1117
- return refs;
1118
- }
1119
- collectRefs() {
1120
- const tables = /* @__PURE__ */ new Set();
1121
- const columns = /* @__PURE__ */ new Map();
1122
- const addSource = (source) => {
1123
- mergeRefsInto(source.collectRefs(), tables, columns);
1124
- };
1125
- addSource(this.from);
1126
- for (const join of this.joins ?? []) {
1127
- addSource(join.source);
1128
- if (join.on.kind === "eq-col-join-on") {
1129
- addColumnRefToRefSets(join.on.left, tables, columns);
1130
- addColumnRefToRefSets(join.on.right, tables, columns);
1131
- } else for (const columnRef of join.on.collectColumnRefs()) addColumnRefToRefSets(columnRef, tables, columns);
1132
- }
1133
- for (const columnRef of this.collectColumnRefs()) addColumnRefToRefSets(columnRef, tables, columns);
1134
- return sortRefs(tables, columns);
1135
- }
1136
- toQueryAst() {
1137
- return this;
1138
- }
1139
- };
1140
- var InsertOnConflictAction = class extends AstNode {};
1141
- var DoNothingConflictAction = class extends InsertOnConflictAction {
1142
- kind = "do-nothing";
1143
- constructor() {
1144
- super();
1145
- this.freeze();
1146
- }
1147
- toInsertOnConflictAction() {
1148
- return this;
150
+ decodeJson(json) {
151
+ return json;
1149
152
  }
1150
153
  };
1151
- var DoUpdateSetConflictAction = class extends InsertOnConflictAction {
1152
- kind = "do-update-set";
1153
- set;
1154
- constructor(set) {
1155
- super();
1156
- this.set = frozenRecordCopy(set);
1157
- this.freeze();
154
+ var SqlCharDescriptor = class extends CodecDescriptorImpl {
155
+ codecId = SQL_CHAR_CODEC_ID;
156
+ traits = [
157
+ "equality",
158
+ "order",
159
+ "textual"
160
+ ];
161
+ targetTypes = ["char"];
162
+ paramsSchema = lengthParamsSchema;
163
+ renderOutputType(params) {
164
+ return sqlCharRenderOutputType(params);
1158
165
  }
1159
- toInsertOnConflictAction() {
1160
- return this;
166
+ factory(_params) {
167
+ return () => new SqlCharCodec(this);
1161
168
  }
1162
169
  };
1163
- var InsertOnConflict = class InsertOnConflict extends AstNode {
1164
- kind = "insert-on-conflict";
1165
- columns;
1166
- action;
1167
- constructor(columns, action) {
1168
- super();
1169
- this.columns = frozenArrayCopy(columns);
1170
- this.action = action;
1171
- this.freeze();
170
+ const sqlCharDescriptor = new SqlCharDescriptor();
171
+ const sqlCharColumn = (params = {}) => column(sqlCharDescriptor.factory(params), sqlCharDescriptor.codecId, params, "char");
172
+ var SqlVarcharCodec = class extends CodecImpl {
173
+ async encode(value, _ctx) {
174
+ return sqlVarcharEncode(value);
1172
175
  }
1173
- static on(columns) {
1174
- return new InsertOnConflict(columns, new DoNothingConflictAction());
176
+ async decode(wire, _ctx) {
177
+ return sqlVarcharDecode(wire);
1175
178
  }
1176
- doNothing() {
1177
- return new InsertOnConflict(this.columns, new DoNothingConflictAction());
179
+ encodeJson(value) {
180
+ return value;
1178
181
  }
1179
- doUpdateSet(set) {
1180
- return new InsertOnConflict(this.columns, new DoUpdateSetConflictAction(set));
182
+ decodeJson(json) {
183
+ return json;
1181
184
  }
1182
185
  };
1183
- var InsertAst = class InsertAst extends QueryAst {
1184
- kind = "insert";
1185
- table;
1186
- rows;
1187
- onConflict;
1188
- returning;
1189
- constructor(table, rows = [{}], onConflict, returning) {
1190
- super();
1191
- this.table = table;
1192
- this.rows = freezeRows(rows);
1193
- this.onConflict = onConflict;
1194
- this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
1195
- this.freeze();
1196
- }
1197
- static into(table) {
1198
- return new InsertAst(table);
1199
- }
1200
- withValues(values) {
1201
- return new InsertAst(this.table, [{ ...values }], this.onConflict, this.returning);
1202
- }
1203
- withRows(rows) {
1204
- return new InsertAst(this.table, rows.map((row) => ({ ...row })), this.onConflict, this.returning);
1205
- }
1206
- withReturning(returning) {
1207
- return new InsertAst(this.table, this.rows.map((row) => ({ ...row })), this.onConflict, returning);
1208
- }
1209
- withOnConflict(onConflict) {
1210
- return new InsertAst(this.table, this.rows.map((row) => ({ ...row })), onConflict, this.returning);
1211
- }
1212
- collectParamRefs() {
1213
- const refs = [];
1214
- for (const row of this.rows) for (const value of Object.values(row)) if (value.kind === "param-ref") refs.push(value);
1215
- if (this.onConflict?.action.kind === "do-update-set") {
1216
- for (const value of Object.values(this.onConflict.action.set)) if (value.kind === "param-ref") refs.push(value);
1217
- }
1218
- return refs;
1219
- }
1220
- collectRefs() {
1221
- const tables = new Set([this.table.name]);
1222
- const columns = /* @__PURE__ */ new Map();
1223
- const addColumn = (columnRef) => addColumnRefToRefSets(columnRef, tables, columns);
1224
- const addValue = (value) => {
1225
- if (value.kind === "column-ref") addColumn(value);
1226
- };
1227
- for (const row of this.rows) for (const value of Object.values(row)) addValue(value);
1228
- for (const columnRef of this.returning ?? []) addColumn(columnRef);
1229
- if (this.onConflict) {
1230
- for (const columnRef of this.onConflict.columns) addColumn(columnRef);
1231
- if (this.onConflict.action.kind === "do-update-set") {
1232
- for (const value of Object.values(this.onConflict.action.set)) if (value.kind === "column-ref") addColumn(value);
1233
- }
1234
- }
1235
- return sortRefs(tables, columns);
186
+ var SqlVarcharDescriptor = class extends CodecDescriptorImpl {
187
+ codecId = SQL_VARCHAR_CODEC_ID;
188
+ traits = [
189
+ "equality",
190
+ "order",
191
+ "textual"
192
+ ];
193
+ targetTypes = ["varchar"];
194
+ paramsSchema = lengthParamsSchema;
195
+ renderOutputType(params) {
196
+ return sqlVarcharRenderOutputType(params);
1236
197
  }
1237
- toQueryAst() {
1238
- return this;
198
+ factory(_params) {
199
+ return () => new SqlVarcharCodec(this);
1239
200
  }
1240
201
  };
1241
- var UpdateAst = class UpdateAst extends QueryAst {
1242
- kind = "update";
1243
- table;
1244
- set;
1245
- where;
1246
- returning;
1247
- constructor(table, set = {}, where, returning) {
1248
- super();
1249
- this.table = table;
1250
- this.set = frozenRecordCopy(set);
1251
- this.where = where;
1252
- this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
1253
- this.freeze();
202
+ const sqlVarcharDescriptor = new SqlVarcharDescriptor();
203
+ const sqlVarcharColumn = (params = {}) => column(sqlVarcharDescriptor.factory(params), sqlVarcharDescriptor.codecId, params, "varchar");
204
+ var SqlTimestampCodec = class extends CodecImpl {
205
+ async encode(value, _ctx) {
206
+ return sqlTimestampEncode(value);
1254
207
  }
1255
- static table(table) {
1256
- return new UpdateAst(table);
208
+ async decode(wire, _ctx) {
209
+ return sqlTimestampDecode(wire);
1257
210
  }
1258
- withSet(set) {
1259
- return new UpdateAst(this.table, set, this.where, this.returning);
211
+ encodeJson(value) {
212
+ return sqlTimestampEncodeJson(value);
1260
213
  }
1261
- withWhere(where) {
1262
- return new UpdateAst(this.table, this.set, where, this.returning);
1263
- }
1264
- withReturning(returning) {
1265
- return new UpdateAst(this.table, this.set, this.where, returning);
1266
- }
1267
- collectParamRefs() {
1268
- const refs = [];
1269
- for (const value of Object.values(this.set)) if (value.kind === "param-ref") refs.push(value);
1270
- if (this.where) refs.push(...this.where.collectParamRefs());
1271
- return refs;
1272
- }
1273
- collectRefs() {
1274
- const tables = new Set([this.table.name]);
1275
- const columns = /* @__PURE__ */ new Map();
1276
- for (const value of Object.values(this.set)) if (value.kind === "column-ref") addColumnRefToRefSets(value, tables, columns);
1277
- for (const columnRef of this.where?.collectColumnRefs() ?? []) addColumnRefToRefSets(columnRef, tables, columns);
1278
- for (const columnRef of this.returning ?? []) addColumnRefToRefSets(columnRef, tables, columns);
1279
- return sortRefs(tables, columns);
1280
- }
1281
- toQueryAst() {
1282
- return this;
214
+ decodeJson(json) {
215
+ return sqlTimestampDecodeJson(json);
1283
216
  }
1284
217
  };
1285
- var DeleteAst = class DeleteAst extends QueryAst {
1286
- kind = "delete";
1287
- table;
1288
- where;
1289
- returning;
1290
- constructor(table, where, returning) {
1291
- super();
1292
- this.table = table;
1293
- this.where = where;
1294
- this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
1295
- this.freeze();
1296
- }
1297
- static from(table) {
1298
- return new DeleteAst(table);
1299
- }
1300
- withWhere(where) {
1301
- return new DeleteAst(this.table, where, this.returning);
1302
- }
1303
- withReturning(returning) {
1304
- return new DeleteAst(this.table, this.where, returning);
1305
- }
1306
- collectParamRefs() {
1307
- return this.where?.collectParamRefs() ?? [];
218
+ var SqlTimestampDescriptor = class extends CodecDescriptorImpl {
219
+ codecId = SQL_TIMESTAMP_CODEC_ID;
220
+ traits = ["equality", "order"];
221
+ targetTypes = ["timestamp"];
222
+ paramsSchema = precisionParamsSchema;
223
+ renderOutputType(params) {
224
+ return sqlTimestampRenderOutputType(params);
1308
225
  }
1309
- collectRefs() {
1310
- const tables = new Set([this.table.name]);
1311
- const columns = /* @__PURE__ */ new Map();
1312
- for (const columnRef of this.where?.collectColumnRefs() ?? []) addColumnRefToRefSets(columnRef, tables, columns);
1313
- for (const columnRef of this.returning ?? []) addColumnRefToRefSets(columnRef, tables, columns);
1314
- return sortRefs(tables, columns);
1315
- }
1316
- toQueryAst() {
1317
- return this;
226
+ factory(_params) {
227
+ return () => new SqlTimestampCodec(this);
1318
228
  }
1319
229
  };
1320
- const queryAstKinds = new Set([
1321
- "select",
1322
- "insert",
1323
- "update",
1324
- "delete"
1325
- ]);
1326
- const whereExprKinds = new Set([
1327
- "binary",
1328
- "and",
1329
- "or",
1330
- "exists",
1331
- "null-check",
1332
- "not"
1333
- ]);
1334
- function isQueryAst(value) {
1335
- return typeof value === "object" && value !== null && "kind" in value && queryAstKinds.has(value.kind);
1336
- }
1337
- function isWhereExpr(value) {
1338
- return typeof value === "object" && value !== null && "kind" in value && whereExprKinds.has(value.kind);
1339
- }
1340
-
230
+ const sqlTimestampDescriptor = new SqlTimestampDescriptor();
231
+ const sqlTimestampColumn = (params = {}) => column(sqlTimestampDescriptor.factory(params), sqlTimestampDescriptor.codecId, params, "timestamp");
1341
232
  //#endregion
1342
233
  //#region src/ast/util.ts
1343
234
  function compact(o) {
@@ -1349,7 +240,56 @@ function compact(o) {
1349
240
  }
1350
241
  return out;
1351
242
  }
1352
-
243
+ /**
244
+ * Walks an AST's parameter references in first-encounter order and dedupes
245
+ * by ParamRef identity. The single canonical helper used by every consumer
246
+ * that aligns `plan.params` with metadata-by-index — the SQL builder lane,
247
+ * the SQL ORM client, the SQL runtime encoder, and the Postgres renderer's
248
+ * `$N` index map — so the four walks cannot drift in dedupe semantics.
249
+ *
250
+ * SQLite's `?`-placeholder renderer intentionally does NOT use this helper
251
+ * because it needs one params entry per occurrence in the SQL.
252
+ */
253
+ function collectOrderedParamRefs(ast) {
254
+ const seen = /* @__PURE__ */ new Set();
255
+ const ordered = [];
256
+ for (const ref of ast.collectParamRefs()) {
257
+ if (seen.has(ref)) continue;
258
+ seen.add(ref);
259
+ ordered.push(ref);
260
+ }
261
+ return Object.freeze(ordered);
262
+ }
1353
263
  //#endregion
1354
- export { AggregateExpr, AndExpr, BinaryExpr, ColumnRef, DefaultValueExpr, DeleteAst, DerivedTableSource, DoNothingConflictAction, DoUpdateSetConflictAction, EqColJoinOn, ExistsExpr, IdentifierRef, InsertAst, InsertOnConflict, JoinAst, JsonArrayAggExpr, JsonObjectExpr, ListExpression, LiteralExpr, NotExpr, NullCheckExpr, OperationExpr, OrExpr, OrderByItem, ParamRef, ProjectionItem, SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_TEXT_CODEC_ID, SQL_TIMESTAMP_CODEC_ID, SQL_VARCHAR_CODEC_ID, SelectAst, SubqueryExpr, TableSource, UpdateAst, codec, compact, createCodecRegistry, defineCodecs, isQueryAst, isWhereExpr, queryAstKinds, sqlCodecDefinitions, sqlDataTypes, whereExprKinds };
264
+ //#region src/ast/validate-param-refs.ts
265
+ /**
266
+ * Builder-pipeline validator pass: every {@link ParamRef} whose `codecId` resolves to a *parameterized* descriptor must carry `refs: { table, column }` so encode-side dispatch can call `contractCodecs.forColumn(table, column)`. Refs-less parameterized `ParamRef`s are a hard error — the codec-id-keyed `forCodecId` fallback cannot disambiguate per-instance codecs (e.g. `vector(1024)` vs. `vector(1536)`), so the dispatch
267
+ * path must reject them at validation time rather than silently bind to the wrong instance.
268
+ *
269
+ * Non-parameterized codec ids (the `voidParamsSchema` case) are always dispatch-safe via codec id alone, so refs-less ParamRefs for those ids are accepted unchanged.
270
+ *
271
+ * The pass runs post-build / pre-execute — the natural location is the SQL runtime's `lower()` step, between any `beforeCompile` rewrites and `encodeParams`. See AC-5 in the codec-registry-unification spec.
272
+ */
273
+ /**
274
+ * Validate that every parameterized-codec `ParamRef` in `plan` carries `refs`. Throws `RUNTIME.PARAM_REF_REFS_REQUIRED` (a runtime envelope) naming the codec id and the binding label when the invariant is violated. Returns the plan unchanged on success — callers that prefer a side-effecting assertion can ignore the return value.
275
+ *
276
+ * The `registry` is consulted via `descriptorFor(codecId).isParameterized` — `true` whenever the descriptor's `paramsSchema` is not the singleton `voidParamsSchema`.
277
+ */
278
+ function validateParamRefRefs(plan, registry) {
279
+ for (const ref of collectOrderedParamRefs(plan)) diagnoseRef(ref, registry);
280
+ }
281
+ function diagnoseRef(ref, registry) {
282
+ if (!ref.codecId) return;
283
+ const descriptor = registry.descriptorFor(ref.codecId);
284
+ if (descriptor === void 0) return;
285
+ if (!descriptor.isParameterized) return;
286
+ if (ref.refs) return;
287
+ throw runtimeError("RUNTIME.PARAM_REF_REFS_REQUIRED", `ParamRef '${ref.name ?? "<anonymous>"}' for parameterized codec '${ref.codecId}' is missing column refs; column-aware dispatch requires { table, column } at the binding site.`, {
288
+ codecId: ref.codecId,
289
+ paramName: ref.name
290
+ });
291
+ }
292
+ //#endregion
293
+ export { AggregateExpr, AndExpr, BinaryExpr, ColumnRef, DefaultValueExpr, DeleteAst, DerivedTableSource, DoNothingConflictAction, DoUpdateSetConflictAction, EqColJoinOn, ExistsExpr, IdentifierRef, InsertAst, InsertOnConflict, JoinAst, JsonArrayAggExpr, JsonObjectExpr, ListExpression, LiteralExpr, NotExpr, NullCheckExpr, OperationExpr, OrExpr, OrderByItem, ParamRef, ProjectionItem, SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_TEXT_CODEC_ID, SQL_TIMESTAMP_CODEC_ID, SQL_VARCHAR_CODEC_ID, SelectAst, SqlCharCodec, SqlCharDescriptor, SqlFloatCodec, SqlFloatDescriptor, SqlIntCodec, SqlIntDescriptor, SqlTextCodec, SqlTextDescriptor, SqlTimestampCodec, SqlTimestampDescriptor, SqlVarcharCodec, SqlVarcharDescriptor, SubqueryExpr, TableSource, UpdateAst, collectOrderedParamRefs, compact, isQueryAst, isWhereExpr, queryAstKinds, sqlCharColumn, sqlCharDecode, sqlCharDescriptor, sqlCharEncode, sqlCharRenderOutputType, sqlFloatColumn, sqlFloatDecode, sqlFloatDescriptor, sqlFloatEncode, sqlIntColumn, sqlIntDecode, sqlIntDescriptor, sqlIntEncode, sqlTextColumn, sqlTextDecode, sqlTextDescriptor, sqlTextEncode, sqlTimestampColumn, sqlTimestampDecode, sqlTimestampDecodeJson, sqlTimestampDescriptor, sqlTimestampEncode, sqlTimestampEncodeJson, sqlTimestampRenderOutputType, sqlVarcharColumn, sqlVarcharDecode, sqlVarcharDescriptor, sqlVarcharEncode, sqlVarcharRenderOutputType, validateParamRefRefs, whereExprKinds };
294
+
1355
295
  //# sourceMappingURL=ast.mjs.map