@prisma-next/sql-relational-core 0.5.0-dev.8 → 0.5.0-dev.81

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