@aeye/query 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -25
- package/aeye-query.md +48 -58
- package/dist/index.d.ts +6632 -6552
- package/dist/index.js +1249 -1708
- package/package.json +11 -8
package/dist/index.js
CHANGED
|
@@ -75,12 +75,6 @@ var QueryTypeError = class extends Error {
|
|
|
75
75
|
};
|
|
76
76
|
|
|
77
77
|
// src/aids.ts
|
|
78
|
-
import { z } from "zod";
|
|
79
|
-
var sharedIdRegistry = z.registry();
|
|
80
|
-
function withSharedId(schema, id) {
|
|
81
|
-
sharedIdRegistry.add(schema, { id });
|
|
82
|
-
return schema;
|
|
83
|
-
}
|
|
84
78
|
var AID_REGISTRY = {
|
|
85
79
|
// ── The recursive unions ──────────────────────────────────────────────────
|
|
86
80
|
Expr: { label: "an expression", noun: "expression" },
|
|
@@ -171,9 +165,6 @@ var AID_REGISTRY = {
|
|
|
171
165
|
function aidInfo(aid) {
|
|
172
166
|
return AID_REGISTRY[aid] ?? { label: `a \`${aid}\` value` };
|
|
173
167
|
}
|
|
174
|
-
function isRecord(value2) {
|
|
175
|
-
return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
176
|
-
}
|
|
177
168
|
function describeInput(input) {
|
|
178
169
|
if (input === void 0) return void 0;
|
|
179
170
|
if (input === null) return "null";
|
|
@@ -191,15 +182,15 @@ function describeInput(input) {
|
|
|
191
182
|
return void 0;
|
|
192
183
|
}
|
|
193
184
|
}
|
|
194
|
-
function editDistance(
|
|
185
|
+
function editDistance(a13, b) {
|
|
195
186
|
const prev = [];
|
|
196
187
|
for (let j = 0; j <= b.length; j++) prev[j] = j;
|
|
197
|
-
for (let i = 1; i <=
|
|
188
|
+
for (let i = 1; i <= a13.length; i++) {
|
|
198
189
|
let diag = prev[0];
|
|
199
190
|
prev[0] = i;
|
|
200
191
|
for (let j = 1; j <= b.length; j++) {
|
|
201
192
|
const tmp = prev[j];
|
|
202
|
-
const cost =
|
|
193
|
+
const cost = a13[i - 1] === b[j - 1] ? 0 : 1;
|
|
203
194
|
prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + cost);
|
|
204
195
|
diag = tmp;
|
|
205
196
|
}
|
|
@@ -217,7 +208,7 @@ function rankNear(input, candidates, budget) {
|
|
|
217
208
|
ci: editDistance(lower3, candidate.toLowerCase()),
|
|
218
209
|
exact: editDistance(input, candidate)
|
|
219
210
|
})).filter((s) => s.ci <= budget);
|
|
220
|
-
scored.sort((
|
|
211
|
+
scored.sort((a13, b) => a13.ci - b.ci || a13.exact - b.exact || a13.index - b.index);
|
|
221
212
|
return scored.map((s) => s.candidate);
|
|
222
213
|
}
|
|
223
214
|
function nearest(input, candidates, budget = suggestionBudget(input.length)) {
|
|
@@ -238,46 +229,9 @@ function orList(items) {
|
|
|
238
229
|
function nearestKind(kind, kinds) {
|
|
239
230
|
return nearest(kind, kinds);
|
|
240
231
|
}
|
|
241
|
-
function unknownKindMessage(input, kinds, info) {
|
|
242
|
-
if (!kinds || kinds.length === 0) return void 0;
|
|
243
|
-
if (!isRecord(input)) return void 0;
|
|
244
|
-
const kind = input["kind"];
|
|
245
|
-
if (typeof kind !== "string") return void 0;
|
|
246
|
-
const noun = info.noun ?? "value";
|
|
247
|
-
const nearest2 = nearestKind(kind, kinds);
|
|
248
|
-
const suggestion = nearest2 !== void 0 ? ` \u2014 did you mean \`${nearest2}\`?` : "";
|
|
249
|
-
return `unknown ${noun} kind \`${kind}\`${suggestion} (available: ${kinds.join(", ")})`;
|
|
250
|
-
}
|
|
251
|
-
function directedMessage(issue, aid, kinds) {
|
|
252
|
-
const info = aidInfo(aid);
|
|
253
|
-
switch (issue.code) {
|
|
254
|
-
case "invalid_type": {
|
|
255
|
-
const got = describeInput(issue.input);
|
|
256
|
-
return got !== void 0 ? `expected ${info.label}, got ${got}` : `expected ${info.label}`;
|
|
257
|
-
}
|
|
258
|
-
case "invalid_value": {
|
|
259
|
-
const values = issue.values.map((v) => String(v));
|
|
260
|
-
const allowed = values.join(", ");
|
|
261
|
-
const suggestion = typeof issue.input === "string" ? didYouMean(issue.input, values) : "";
|
|
262
|
-
return `expected ${info.label}: ${allowed}${suggestion}`;
|
|
263
|
-
}
|
|
264
|
-
case "invalid_union": {
|
|
265
|
-
return unknownKindMessage(issue.input, kinds, info) ?? `expected ${info.label}`;
|
|
266
|
-
}
|
|
267
|
-
default:
|
|
268
|
-
return `expected ${info.label}`;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
function makeAidError(aid, kinds) {
|
|
272
|
-
return (issue) => directedMessage(issue, aid, kinds);
|
|
273
|
-
}
|
|
274
|
-
function withAid(schema, aid, opts = {}) {
|
|
275
|
-
const cloned = schema.clone({ ...schema.def, error: makeAidError(aid, opts.kinds) }).meta({ aid });
|
|
276
|
-
return opts.id !== void 0 ? withSharedId(cloned, opts.id) : cloned;
|
|
277
|
-
}
|
|
278
232
|
|
|
279
233
|
// src/json-source.ts
|
|
280
|
-
function
|
|
234
|
+
function isRecord(value2) {
|
|
281
235
|
return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
282
236
|
}
|
|
283
237
|
function isArray(value2) {
|
|
@@ -304,7 +258,7 @@ function jsonSource(value2) {
|
|
|
304
258
|
const start = text.length;
|
|
305
259
|
if (isArray(node)) {
|
|
306
260
|
emitArray(node, path, level);
|
|
307
|
-
} else if (
|
|
261
|
+
} else if (isRecord(node)) {
|
|
308
262
|
emitObject(node, path, level);
|
|
309
263
|
} else {
|
|
310
264
|
text += serializeLeaf(node);
|
|
@@ -647,7 +601,7 @@ function resolveProblem(codeValue, lines, problem) {
|
|
|
647
601
|
}
|
|
648
602
|
function mergeSections(resolved, totalLines, contextLines) {
|
|
649
603
|
if (resolved.length === 0) return [];
|
|
650
|
-
const sorted = [...resolved].sort((
|
|
604
|
+
const sorted = [...resolved].sort((a13, b) => a13.firstLine - b.firstLine);
|
|
651
605
|
const sections = [];
|
|
652
606
|
for (const r of sorted) {
|
|
653
607
|
const start = Math.max(0, r.firstLine - contextLines);
|
|
@@ -722,8 +676,8 @@ function casingRank(casing) {
|
|
|
722
676
|
return 2;
|
|
723
677
|
}
|
|
724
678
|
}
|
|
725
|
-
function strictestCasing(
|
|
726
|
-
return casingRank(b) > casingRank(
|
|
679
|
+
function strictestCasing(a13, b) {
|
|
680
|
+
return casingRank(b) > casingRank(a13) ? b : a13;
|
|
727
681
|
}
|
|
728
682
|
function effectiveCasing(left, right, fallback) {
|
|
729
683
|
if (left === void 0) return right ?? fallback;
|
|
@@ -738,52 +692,53 @@ function foldsAtRuntime(casing) {
|
|
|
738
692
|
}
|
|
739
693
|
|
|
740
694
|
// src/field-type.ts
|
|
741
|
-
import { z as
|
|
695
|
+
import { z as z2 } from "zod";
|
|
742
696
|
|
|
743
697
|
// src/field-types/_values.ts
|
|
744
|
-
import { z
|
|
698
|
+
import { z } from "zod";
|
|
699
|
+
import { a } from "@aeye/schema";
|
|
745
700
|
|
|
746
701
|
// src/field-types/_meet.ts
|
|
747
702
|
function met(value2) {
|
|
748
703
|
return { ok: true, value: value2 };
|
|
749
704
|
}
|
|
750
705
|
var MEET_CONFLICT = { ok: false };
|
|
751
|
-
function meetExact(
|
|
752
|
-
if (
|
|
753
|
-
if (b === void 0) return met(
|
|
754
|
-
return eq4(
|
|
706
|
+
function meetExact(a13, b, eq4 = Object.is) {
|
|
707
|
+
if (a13 === void 0) return met(b);
|
|
708
|
+
if (b === void 0) return met(a13);
|
|
709
|
+
return eq4(a13, b) ? met(a13) : MEET_CONFLICT;
|
|
755
710
|
}
|
|
756
|
-
function meetLower(
|
|
757
|
-
if (
|
|
758
|
-
if (b === void 0) return
|
|
759
|
-
return Math.max(
|
|
711
|
+
function meetLower(a13, b) {
|
|
712
|
+
if (a13 === void 0) return b;
|
|
713
|
+
if (b === void 0) return a13;
|
|
714
|
+
return Math.max(a13, b);
|
|
760
715
|
}
|
|
761
|
-
function meetUpper(
|
|
762
|
-
if (
|
|
763
|
-
if (b === void 0) return
|
|
764
|
-
return Math.min(
|
|
716
|
+
function meetUpper(a13, b) {
|
|
717
|
+
if (a13 === void 0) return b;
|
|
718
|
+
if (b === void 0) return a13;
|
|
719
|
+
return Math.min(a13, b);
|
|
765
720
|
}
|
|
766
721
|
function emptyRange(lower3, upper) {
|
|
767
722
|
return lower3 !== void 0 && upper !== void 0 && lower3 > upper;
|
|
768
723
|
}
|
|
769
|
-
function meetFlag(
|
|
770
|
-
if (
|
|
771
|
-
return
|
|
724
|
+
function meetFlag(a13, b) {
|
|
725
|
+
if (a13 === void 0 && b === void 0) return void 0;
|
|
726
|
+
return a13 === true || b === true;
|
|
772
727
|
}
|
|
773
|
-
function meetRanked(
|
|
774
|
-
if (
|
|
775
|
-
if (b === void 0) return
|
|
776
|
-
return rank(b) > rank(
|
|
728
|
+
function meetRanked(a13, b, rank) {
|
|
729
|
+
if (a13 === void 0) return b;
|
|
730
|
+
if (b === void 0) return a13;
|
|
731
|
+
return rank(b) > rank(a13) ? b : a13;
|
|
777
732
|
}
|
|
778
|
-
function sameJson(
|
|
779
|
-
return JSON.stringify(
|
|
733
|
+
function sameJson(a13, b) {
|
|
734
|
+
return JSON.stringify(a13) === JSON.stringify(b);
|
|
780
735
|
}
|
|
781
|
-
function meetRefinementOptions(
|
|
782
|
-
if (
|
|
783
|
-
if (b === void 0) return met(
|
|
736
|
+
function meetRefinementOptions(a13, b) {
|
|
737
|
+
if (a13 === void 0) return met(b);
|
|
738
|
+
if (b === void 0) return met(a13);
|
|
784
739
|
const merged = {};
|
|
785
|
-
for (const key of [.../* @__PURE__ */ new Set([...Object.keys(
|
|
786
|
-
const value2 = meetExact(
|
|
740
|
+
for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a13), ...Object.keys(b)])].sort()) {
|
|
741
|
+
const value2 = meetExact(a13[key], b[key], sameJson);
|
|
787
742
|
if (!value2.ok) return MEET_CONFLICT;
|
|
788
743
|
if (value2.value !== void 0) merged[key] = value2.value;
|
|
789
744
|
}
|
|
@@ -792,10 +747,10 @@ function meetRefinementOptions(a, b) {
|
|
|
792
747
|
|
|
793
748
|
// src/field-types/_values.ts
|
|
794
749
|
function fieldValuesSchema(member) {
|
|
795
|
-
return
|
|
796
|
-
|
|
750
|
+
return z.array(
|
|
751
|
+
z.object({
|
|
797
752
|
value: member.describe("The stored value \u2014 one member of the closed set."),
|
|
798
|
-
label:
|
|
753
|
+
label: z.string().optional().describe("Human-facing name for this member (defaults to the value).")
|
|
799
754
|
})
|
|
800
755
|
).optional().describe("Closed set of values this field may hold. Declare only a genuinely fixed set.");
|
|
801
756
|
}
|
|
@@ -810,19 +765,23 @@ function compactFieldValues(values) {
|
|
|
810
765
|
}
|
|
811
766
|
return out;
|
|
812
767
|
}
|
|
768
|
+
function closedSetA(values) {
|
|
769
|
+
if (!values || values.length === 0) return void 0;
|
|
770
|
+
return values.length === 1 ? a.literal(values[0].value) : a.union(values.map((v) => a.literal(v.value)));
|
|
771
|
+
}
|
|
813
772
|
function closedSetValueSchema(values) {
|
|
814
773
|
if (!values || values.length === 0) return void 0;
|
|
815
774
|
const first = values[0];
|
|
816
|
-
if (values.length === 1) return
|
|
817
|
-
return
|
|
775
|
+
if (values.length === 1) return z.literal(first.value);
|
|
776
|
+
return z.union(values.map((v) => z.literal(v.value)));
|
|
818
777
|
}
|
|
819
778
|
function isClosedSetMember(values, raw2) {
|
|
820
779
|
if (!values || values.length === 0) return true;
|
|
821
780
|
if (typeof raw2 !== "string" && typeof raw2 !== "number") return false;
|
|
822
781
|
return values.some((v) => v.value === raw2 || v.value !== v.value && raw2 !== raw2);
|
|
823
782
|
}
|
|
824
|
-
function meetFieldValues(
|
|
825
|
-
const left = compactFieldValues(
|
|
783
|
+
function meetFieldValues(a13, b) {
|
|
784
|
+
const left = compactFieldValues(a13);
|
|
826
785
|
const right = compactFieldValues(b);
|
|
827
786
|
if (!left) return met(right);
|
|
828
787
|
if (!right) return met(left);
|
|
@@ -838,19 +797,19 @@ function meetFieldValues(a, b) {
|
|
|
838
797
|
if (shared.length === 0) return MEET_CONFLICT;
|
|
839
798
|
return met(shared.sort(compareMembers));
|
|
840
799
|
}
|
|
841
|
-
function sameValueList(
|
|
842
|
-
return
|
|
800
|
+
function sameValueList(a13, b) {
|
|
801
|
+
return a13.length === b.length && a13.every((v, i) => v.value === b[i].value && v.label === b[i].label);
|
|
843
802
|
}
|
|
844
|
-
function minLabel(
|
|
845
|
-
if (
|
|
846
|
-
if (b === void 0) return
|
|
847
|
-
return
|
|
803
|
+
function minLabel(a13, b) {
|
|
804
|
+
if (a13 === void 0) return b;
|
|
805
|
+
if (b === void 0) return a13;
|
|
806
|
+
return a13 <= b ? a13 : b;
|
|
848
807
|
}
|
|
849
|
-
function compareMembers(
|
|
850
|
-
if (typeof
|
|
851
|
-
if (typeof
|
|
808
|
+
function compareMembers(a13, b) {
|
|
809
|
+
if (typeof a13.value === "number" && typeof b.value === "number") return a13.value - b.value;
|
|
810
|
+
if (typeof a13.value === "number") return -1;
|
|
852
811
|
if (typeof b.value === "number") return 1;
|
|
853
|
-
return
|
|
812
|
+
return a13.value < b.value ? -1 : 1;
|
|
854
813
|
}
|
|
855
814
|
function narrowFieldValues(values, admits) {
|
|
856
815
|
return values.filter((v) => admits(v.value));
|
|
@@ -1055,9 +1014,9 @@ var FieldType = class {
|
|
|
1055
1014
|
*/
|
|
1056
1015
|
comparableWith(other) {
|
|
1057
1016
|
if (this.builtinComparableWith(other)) return true;
|
|
1058
|
-
const
|
|
1017
|
+
const a13 = this.declaredRefinement;
|
|
1059
1018
|
const b = other.declaredRefinement;
|
|
1060
|
-
return
|
|
1019
|
+
return a13 !== void 0 && b !== void 0 && a13.comparableTo(b.name);
|
|
1061
1020
|
}
|
|
1062
1021
|
/**
|
|
1063
1022
|
* The BUILTIN comparability rule: same category, with number/money and
|
|
@@ -1065,11 +1024,11 @@ var FieldType = class {
|
|
|
1065
1024
|
* for stricter or looser rules.
|
|
1066
1025
|
*/
|
|
1067
1026
|
builtinComparableWith(other) {
|
|
1068
|
-
const
|
|
1027
|
+
const a13 = this.resolve();
|
|
1069
1028
|
const b = other.resolve();
|
|
1070
|
-
if (
|
|
1071
|
-
if (NUMERIC_KINDS.has(
|
|
1072
|
-
if (TEMPORAL_KINDS.has(
|
|
1029
|
+
if (a13 === b) return true;
|
|
1030
|
+
if (NUMERIC_KINDS.has(a13) && NUMERIC_KINDS.has(b)) return true;
|
|
1031
|
+
if (TEMPORAL_KINDS.has(a13) && TEMPORAL_KINDS.has(b)) return true;
|
|
1073
1032
|
return false;
|
|
1074
1033
|
}
|
|
1075
1034
|
/**
|
|
@@ -1335,7 +1294,21 @@ var FieldType = class {
|
|
|
1335
1294
|
toValueSchema(opts) {
|
|
1336
1295
|
const builtin = this.builtinValueSchema(opts);
|
|
1337
1296
|
const declared = this.declaredRefinement?.value;
|
|
1338
|
-
return declared === void 0 ? builtin :
|
|
1297
|
+
return declared === void 0 ? builtin : z2.intersection(builtin, declared);
|
|
1298
|
+
}
|
|
1299
|
+
/**
|
|
1300
|
+
* The model-facing `@aeye/schema` form of a VALUE of this field type — what a
|
|
1301
|
+
* model writes for this field in a typed INSERT row / UPDATE SET. Mirrors
|
|
1302
|
+
* `toValueSchema` (which stays query's own value gate): bounds, patterns and
|
|
1303
|
+
* closed sets are shown to the model; a refinement's declared value gate is
|
|
1304
|
+
* checked on decode too (named in the message).
|
|
1305
|
+
*/
|
|
1306
|
+
toA() {
|
|
1307
|
+
const builtin = this.builtinA();
|
|
1308
|
+
const declared = this.declaredRefinement;
|
|
1309
|
+
const gate = declared?.value;
|
|
1310
|
+
if (!declared || gate === void 0) return builtin;
|
|
1311
|
+
return builtin.refine((v) => gate.safeParse(v).success || `Not a valid \`${declared.name}\` value.`);
|
|
1339
1312
|
}
|
|
1340
1313
|
/**
|
|
1341
1314
|
* Whether `raw` is a valid value of this type. Default: delegate to
|
|
@@ -1361,13 +1334,14 @@ var FieldType = class {
|
|
|
1361
1334
|
};
|
|
1362
1335
|
|
|
1363
1336
|
// src/field-types/index.ts
|
|
1364
|
-
import { z as
|
|
1337
|
+
import { z as z13 } from "zod";
|
|
1365
1338
|
|
|
1366
1339
|
// src/field-types/number.ts
|
|
1367
|
-
import { z as
|
|
1340
|
+
import { z as z4 } from "zod";
|
|
1341
|
+
import { a as a2 } from "@aeye/schema";
|
|
1368
1342
|
|
|
1369
1343
|
// src/refinement.ts
|
|
1370
|
-
import { z as
|
|
1344
|
+
import { z as z3 } from "zod";
|
|
1371
1345
|
|
|
1372
1346
|
// src/sql-template.ts
|
|
1373
1347
|
var TEMPLATE_SLOT = /\{([^{}]*)\}/g;
|
|
@@ -1875,7 +1849,7 @@ var FieldTypeRefinement = class _FieldTypeRefinement {
|
|
|
1875
1849
|
const entries = Object.entries(withOptions ?? {}).filter(([, value2]) => value2 !== void 0);
|
|
1876
1850
|
if (entries.length === 0) return void 0;
|
|
1877
1851
|
const bag = {};
|
|
1878
|
-
for (const [key, value2] of entries.sort(([
|
|
1852
|
+
for (const [key, value2] of entries.sort(([a13], [b]) => a13 < b ? -1 : a13 > b ? 1 : 0)) {
|
|
1879
1853
|
const option = this.ownOptions.get(key);
|
|
1880
1854
|
if (!option) {
|
|
1881
1855
|
const names = this.ownOptionNames();
|
|
@@ -1980,21 +1954,21 @@ var FieldTypeRefinement = class _FieldTypeRefinement {
|
|
|
1980
1954
|
function refinementKeySchema(base, opts) {
|
|
1981
1955
|
if (!REFINABLE_BASE_SET.has(base)) {
|
|
1982
1956
|
return {
|
|
1983
|
-
as:
|
|
1984
|
-
with:
|
|
1957
|
+
as: z3.never().optional().describe(`A ${base} cannot be refined \u2014 omit \`as\`.`),
|
|
1958
|
+
with: z3.never().optional().describe(`A ${base} cannot be refined \u2014 omit \`with\`.`)
|
|
1985
1959
|
};
|
|
1986
1960
|
}
|
|
1987
1961
|
const registered = (opts?.registry?.fieldTypeRefinementList() ?? []).filter((r) => r.base === base);
|
|
1988
1962
|
const [first, ...rest] = registered.map((r) => r.name);
|
|
1989
1963
|
if (first === void 0) {
|
|
1990
1964
|
return {
|
|
1991
|
-
as:
|
|
1992
|
-
with:
|
|
1965
|
+
as: z3.never().optional().describe(`No registered type refines a ${base} here \u2014 omit \`as\`.`),
|
|
1966
|
+
with: z3.never().optional().describe(`No registered type refines a ${base} here \u2014 omit \`with\`.`)
|
|
1993
1967
|
};
|
|
1994
1968
|
}
|
|
1995
1969
|
const glossary = registered.map((r) => `${r.name} \u2014 ${r.instructions}${refusedArmsNote(r)}`).join(" ");
|
|
1996
1970
|
return {
|
|
1997
|
-
as:
|
|
1971
|
+
as: z3.enum([first, ...rest]).optional().describe(
|
|
1998
1972
|
`Narrow this ${base} to a registered type. It carries that type's own constraints; you may constrain further here, never loosen. ${glossary}`
|
|
1999
1973
|
),
|
|
2000
1974
|
with: refinementOptionsSchema(base, registered, opts)
|
|
@@ -2011,31 +1985,31 @@ function refinementOptionsSchema(base, registered, opts) {
|
|
|
2011
1985
|
for (const option of refinement.ownOptions.values()) {
|
|
2012
1986
|
const existing = shape[option.name];
|
|
2013
1987
|
const schema = option.type.toValueSchema(opts);
|
|
2014
|
-
shape[option.name] = (existing === void 0 ? schema :
|
|
1988
|
+
shape[option.name] = (existing === void 0 ? schema : z3.union([existing, schema])).optional();
|
|
2015
1989
|
glossary.push(
|
|
2016
1990
|
`${refinement.name}.${option.name}: ${option.type.toCode()}${option.default === void 0 ? "" : ` (default ${JSON.stringify(option.default)})`}${option.docs === void 0 ? "" : ` \u2014 ${option.docs}`}`
|
|
2017
1991
|
);
|
|
2018
1992
|
}
|
|
2019
1993
|
}
|
|
2020
1994
|
if (glossary.length === 0) {
|
|
2021
|
-
return
|
|
1995
|
+
return z3.never().optional().describe(`No registered type refining a ${base} declares options of its own \u2014 omit \`with\`.`);
|
|
2022
1996
|
}
|
|
2023
|
-
return
|
|
1997
|
+
return z3.strictObject(shape).optional().describe(
|
|
2024
1998
|
`Values for the options the type named in \`as\` declares for itself. Omit an option to take its declared default. ${glossary.join("; ")}`
|
|
2025
1999
|
);
|
|
2026
2000
|
}
|
|
2027
2001
|
|
|
2028
2002
|
// src/field-types/number.ts
|
|
2029
2003
|
function numberOptionsSchema() {
|
|
2030
|
-
return
|
|
2031
|
-
min:
|
|
2032
|
-
max:
|
|
2033
|
-
whole:
|
|
2034
|
-
minPlaces:
|
|
2035
|
-
maxPlaces:
|
|
2004
|
+
return z4.object({
|
|
2005
|
+
min: z4.number().optional().describe("Real lower bound only (e.g. age \u2192 0). Do not add 0 reflexively."),
|
|
2006
|
+
max: z4.number().optional().describe("Real upper bound only (e.g. percentage \u2192 100)."),
|
|
2007
|
+
whole: z4.boolean().optional().describe("True only when genuinely integral (counts, ids)."),
|
|
2008
|
+
minPlaces: z4.number().int().optional().describe("Decimal-place floor; omit unless required."),
|
|
2009
|
+
maxPlaces: z4.number().int().optional().describe("Decimal-place ceiling; omit unless required."),
|
|
2036
2010
|
// A numeric member is a NUMBER — the owning kind decides the member type
|
|
2037
2011
|
// (see `fieldValuesSchema`), and `money` inherits that through this bag.
|
|
2038
|
-
values: fieldValuesSchema(
|
|
2012
|
+
values: fieldValuesSchema(z4.number())
|
|
2039
2013
|
});
|
|
2040
2014
|
}
|
|
2041
2015
|
function compactNumberOptions(o) {
|
|
@@ -2050,7 +2024,7 @@ function compactNumberOptions(o) {
|
|
|
2050
2024
|
return out;
|
|
2051
2025
|
}
|
|
2052
2026
|
function numberConstraintSchema(o) {
|
|
2053
|
-
let s = o.whole ?
|
|
2027
|
+
let s = o.whole ? z4.number().int() : z4.number();
|
|
2054
2028
|
if (o.min !== void 0) s = s.min(o.min);
|
|
2055
2029
|
if (o.max !== void 0) s = s.max(o.max);
|
|
2056
2030
|
return s;
|
|
@@ -2058,22 +2032,30 @@ function numberConstraintSchema(o) {
|
|
|
2058
2032
|
function checkNumberValues(kind, path, o) {
|
|
2059
2033
|
checkFieldValues(kind, path, o.values, numberConstraintSchema(o));
|
|
2060
2034
|
}
|
|
2035
|
+
function numberA(o) {
|
|
2036
|
+
const set = closedSetA(o.values);
|
|
2037
|
+
if (set) return set;
|
|
2038
|
+
let s = o.whole ? a2.int() : a2.number();
|
|
2039
|
+
if (o.min !== void 0) s = s.min(o.min);
|
|
2040
|
+
if (o.max !== void 0) s = s.max(o.max);
|
|
2041
|
+
return s;
|
|
2042
|
+
}
|
|
2061
2043
|
function numberValueSchema(o) {
|
|
2062
2044
|
return closedSetValueSchema(o.values) ?? numberConstraintSchema(o);
|
|
2063
2045
|
}
|
|
2064
|
-
function meetNumberOptions(
|
|
2065
|
-
const min2 = meetLower(
|
|
2066
|
-
const max2 = meetUpper(
|
|
2046
|
+
function meetNumberOptions(a13, b) {
|
|
2047
|
+
const min2 = meetLower(a13.min, b.min);
|
|
2048
|
+
const max2 = meetUpper(a13.max, b.max);
|
|
2067
2049
|
if (emptyRange(min2, max2)) return void 0;
|
|
2068
|
-
const minPlaces = meetLower(
|
|
2069
|
-
const maxPlaces = meetUpper(
|
|
2050
|
+
const minPlaces = meetLower(a13.minPlaces, b.minPlaces);
|
|
2051
|
+
const maxPlaces = meetUpper(a13.maxPlaces, b.maxPlaces);
|
|
2070
2052
|
if (emptyRange(minPlaces, maxPlaces)) return void 0;
|
|
2071
|
-
const values = meetFieldValues(
|
|
2053
|
+
const values = meetFieldValues(a13.values, b.values);
|
|
2072
2054
|
if (!values.ok) return void 0;
|
|
2073
2055
|
const merged = compactNumberOptions({
|
|
2074
2056
|
min: min2,
|
|
2075
2057
|
max: max2,
|
|
2076
|
-
whole: meetFlag(
|
|
2058
|
+
whole: meetFlag(a13.whole, b.whole),
|
|
2077
2059
|
minPlaces,
|
|
2078
2060
|
maxPlaces,
|
|
2079
2061
|
values: values.value
|
|
@@ -2118,15 +2100,15 @@ var NumberFieldType = class _NumberFieldType extends FieldType {
|
|
|
2118
2100
|
}
|
|
2119
2101
|
/** The Zod schema for this field type's JSON def. */
|
|
2120
2102
|
static toSchema(opts) {
|
|
2121
|
-
return
|
|
2122
|
-
kind:
|
|
2103
|
+
return z4.object({
|
|
2104
|
+
kind: z4.literal("number"),
|
|
2123
2105
|
...refinementKeySchema("number", opts),
|
|
2124
|
-
min:
|
|
2125
|
-
max:
|
|
2126
|
-
whole:
|
|
2127
|
-
minPlaces:
|
|
2128
|
-
maxPlaces:
|
|
2129
|
-
values: fieldValuesSchema(
|
|
2106
|
+
min: z4.number().optional().describe("Real lower bound only (e.g. age \u2192 0). Do not add 0 reflexively."),
|
|
2107
|
+
max: z4.number().optional().describe("Real upper bound only (e.g. percentage \u2192 100)."),
|
|
2108
|
+
whole: z4.boolean().optional().describe("True only when genuinely integral (counts, ids)."),
|
|
2109
|
+
minPlaces: z4.number().int().optional().describe("Decimal-place floor; omit unless required."),
|
|
2110
|
+
maxPlaces: z4.number().int().optional().describe("Decimal-place ceiling; omit unless required."),
|
|
2111
|
+
values: fieldValuesSchema(z4.number())
|
|
2130
2112
|
}).meta({ aid: "FieldType_number" }).describe("Numeric field type.");
|
|
2131
2113
|
}
|
|
2132
2114
|
/** Resolve to the `number` scalar comparison category. */
|
|
@@ -2184,6 +2166,9 @@ var NumberFieldType = class _NumberFieldType extends FieldType {
|
|
|
2184
2166
|
return this.options.whole ? "integer" : "numeric";
|
|
2185
2167
|
}
|
|
2186
2168
|
/** Zod schema validating a number value, honoring the options. */
|
|
2169
|
+
builtinA() {
|
|
2170
|
+
return numberA(this.options);
|
|
2171
|
+
}
|
|
2187
2172
|
builtinValueSchema(_opts) {
|
|
2188
2173
|
return numberValueSchema(this.options);
|
|
2189
2174
|
}
|
|
@@ -2206,7 +2191,8 @@ var NumberFieldType = class _NumberFieldType extends FieldType {
|
|
|
2206
2191
|
};
|
|
2207
2192
|
|
|
2208
2193
|
// src/field-types/text.ts
|
|
2209
|
-
import { z as
|
|
2194
|
+
import { z as z5 } from "zod";
|
|
2195
|
+
import { a as a3 } from "@aeye/schema";
|
|
2210
2196
|
function checkPattern(pattern) {
|
|
2211
2197
|
try {
|
|
2212
2198
|
new RegExp(pattern);
|
|
@@ -2230,7 +2216,7 @@ function checkLegacySensitive(json2) {
|
|
|
2230
2216
|
});
|
|
2231
2217
|
}
|
|
2232
2218
|
function textConstraintSchema(o) {
|
|
2233
|
-
let s =
|
|
2219
|
+
let s = z5.string();
|
|
2234
2220
|
if (o.minLength !== void 0) s = s.min(o.minLength);
|
|
2235
2221
|
if (o.maxLength !== void 0) s = s.max(o.maxLength);
|
|
2236
2222
|
if (o.pattern !== void 0) s = s.regex(new RegExp(o.pattern));
|
|
@@ -2287,20 +2273,20 @@ var TextFieldType = class _TextFieldType extends FieldType {
|
|
|
2287
2273
|
}
|
|
2288
2274
|
/** The Zod schema for this field type's JSON def. */
|
|
2289
2275
|
static toSchema(opts) {
|
|
2290
|
-
return
|
|
2291
|
-
kind:
|
|
2276
|
+
return z5.object({
|
|
2277
|
+
kind: z5.literal("text"),
|
|
2292
2278
|
...refinementKeySchema("text", opts),
|
|
2293
|
-
minLength:
|
|
2294
|
-
maxLength:
|
|
2295
|
-
pattern:
|
|
2296
|
-
semantic:
|
|
2297
|
-
search:
|
|
2298
|
-
casing:
|
|
2279
|
+
minLength: z5.number().int().optional().describe("Real lower bound (e.g. non-empty \u2192 1)."),
|
|
2280
|
+
maxLength: z5.number().int().optional().describe("Real upper bound (field width / API limit)."),
|
|
2281
|
+
pattern: z5.string().optional().describe("Format regex (UUID, slug, \u2026); not accept-anything."),
|
|
2282
|
+
semantic: z5.boolean().optional().describe("Eligible for embedding-based semantic similarity."),
|
|
2283
|
+
search: z5.boolean().optional().describe("Eligible for full-text search."),
|
|
2284
|
+
casing: z5.enum(TEXT_CASINGS).optional().describe(
|
|
2299
2285
|
"How text matching treats letter case. 'fold' (the usual default) = case-INSENSITIVE, folded by the query (SQL wraps both sides in LOWER(...)); 'exact' = case-SENSITIVE \u2014 use it for identifiers, codes and uuids, where folding is wrong and defeats the index; 'collated' = case-INSENSITIVE because the COLUMN's own collation folds (citext / a non-deterministic collation), so no LOWER(...) is emitted. Omit to inherit the engine's default."
|
|
2300
2286
|
),
|
|
2301
2287
|
// A `text` member is a STRING — the owning kind decides the member type
|
|
2302
2288
|
// (see `fieldValuesSchema`), so this schema cannot offer a numeric one.
|
|
2303
|
-
values: fieldValuesSchema(
|
|
2289
|
+
values: fieldValuesSchema(z5.string())
|
|
2304
2290
|
}).meta({ aid: "FieldType_text" }).describe("String field type.");
|
|
2305
2291
|
}
|
|
2306
2292
|
/** Resolve to the `text` scalar comparison category. */
|
|
@@ -2342,22 +2328,22 @@ var TextFieldType = class _TextFieldType extends FieldType {
|
|
|
2342
2328
|
*/
|
|
2343
2329
|
meetWith(other) {
|
|
2344
2330
|
if (!(other instanceof _TextFieldType)) return void 0;
|
|
2345
|
-
const
|
|
2331
|
+
const a13 = this.options;
|
|
2346
2332
|
const b = other.options;
|
|
2347
|
-
const pattern = meetExact(
|
|
2333
|
+
const pattern = meetExact(a13.pattern, b.pattern);
|
|
2348
2334
|
if (!pattern.ok) return void 0;
|
|
2349
|
-
const minLength = meetLower(
|
|
2350
|
-
const maxLength = meetUpper(
|
|
2335
|
+
const minLength = meetLower(a13.minLength, b.minLength);
|
|
2336
|
+
const maxLength = meetUpper(a13.maxLength, b.maxLength);
|
|
2351
2337
|
if (emptyRange(minLength, maxLength)) return void 0;
|
|
2352
|
-
const values = meetFieldValues(
|
|
2338
|
+
const values = meetFieldValues(a13.values, b.values);
|
|
2353
2339
|
if (!values.ok) return void 0;
|
|
2354
2340
|
const merged = compact({
|
|
2355
2341
|
minLength,
|
|
2356
2342
|
maxLength,
|
|
2357
2343
|
pattern: pattern.value,
|
|
2358
|
-
semantic: meetFlag(
|
|
2359
|
-
search: meetFlag(
|
|
2360
|
-
casing: meetRanked(
|
|
2344
|
+
semantic: meetFlag(a13.semantic, b.semantic),
|
|
2345
|
+
search: meetFlag(a13.search, b.search),
|
|
2346
|
+
casing: meetRanked(a13.casing, b.casing, casingRank),
|
|
2361
2347
|
values: values.value
|
|
2362
2348
|
});
|
|
2363
2349
|
if (merged.values) {
|
|
@@ -2380,6 +2366,14 @@ var TextFieldType = class _TextFieldType extends FieldType {
|
|
|
2380
2366
|
return this.options.maxLength !== void 0 ? `varchar(${this.options.maxLength})` : "text";
|
|
2381
2367
|
}
|
|
2382
2368
|
/** Zod schema validating a string, honoring the closed value set else length / pattern options. */
|
|
2369
|
+
builtinA() {
|
|
2370
|
+
if (this.options.values?.length) return closedSetA(this.options.values);
|
|
2371
|
+
let s = a3.string();
|
|
2372
|
+
if (this.options.minLength !== void 0) s = s.min(this.options.minLength);
|
|
2373
|
+
if (this.options.maxLength !== void 0) s = s.max(this.options.maxLength);
|
|
2374
|
+
if (this.options.pattern !== void 0) s = s.pattern(this.options.pattern);
|
|
2375
|
+
return s;
|
|
2376
|
+
}
|
|
2383
2377
|
builtinValueSchema(_opts) {
|
|
2384
2378
|
return closedSetValueSchema(this.options.values) ?? textConstraintSchema(this.options);
|
|
2385
2379
|
}
|
|
@@ -2402,7 +2396,7 @@ var TextFieldType = class _TextFieldType extends FieldType {
|
|
|
2402
2396
|
};
|
|
2403
2397
|
|
|
2404
2398
|
// src/field-types/money.ts
|
|
2405
|
-
import { z as
|
|
2399
|
+
import { z as z6 } from "zod";
|
|
2406
2400
|
function compact2(o) {
|
|
2407
2401
|
const out = {};
|
|
2408
2402
|
const num2 = o.number ? compactNumberOptions(o.number) : void 0;
|
|
@@ -2441,11 +2435,11 @@ var MoneyFieldType = class _MoneyFieldType extends FieldType {
|
|
|
2441
2435
|
}
|
|
2442
2436
|
/** The Zod schema for this field type's JSON def. */
|
|
2443
2437
|
static toSchema(opts) {
|
|
2444
|
-
return
|
|
2445
|
-
kind:
|
|
2438
|
+
return z6.object({
|
|
2439
|
+
kind: z6.literal("money"),
|
|
2446
2440
|
...refinementKeySchema("money", opts),
|
|
2447
2441
|
number: numberOptionsSchema().optional().describe("Numeric constraints on the amount."),
|
|
2448
|
-
currency:
|
|
2442
|
+
currency: z6.string().optional().describe('ISO 4217 currency code (e.g. "USD").')
|
|
2449
2443
|
}).meta({ aid: "FieldType_money" }).describe("Monetary amount field type.");
|
|
2450
2444
|
}
|
|
2451
2445
|
/** Resolve to the `money` scalar comparison category. */
|
|
@@ -2488,6 +2482,9 @@ var MoneyFieldType = class _MoneyFieldType extends FieldType {
|
|
|
2488
2482
|
return "numeric";
|
|
2489
2483
|
}
|
|
2490
2484
|
/** Zod schema validating the amount, honoring the inner number options. */
|
|
2485
|
+
builtinA() {
|
|
2486
|
+
return numberA(this.options.number ?? {});
|
|
2487
|
+
}
|
|
2491
2488
|
builtinValueSchema(_opts) {
|
|
2492
2489
|
return numberValueSchema(this.options.number ?? {});
|
|
2493
2490
|
}
|
|
@@ -2513,7 +2510,8 @@ var MoneyFieldType = class _MoneyFieldType extends FieldType {
|
|
|
2513
2510
|
};
|
|
2514
2511
|
|
|
2515
2512
|
// src/field-types/bool.ts
|
|
2516
|
-
import { z as
|
|
2513
|
+
import { z as z7 } from "zod";
|
|
2514
|
+
import { a as a4 } from "@aeye/schema";
|
|
2517
2515
|
var BoolFieldType = class _BoolFieldType extends FieldType {
|
|
2518
2516
|
/** Discriminant kind tag (`'bool'`) shared by all instances. */
|
|
2519
2517
|
static NAME = "bool";
|
|
@@ -2533,7 +2531,7 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
|
|
|
2533
2531
|
}
|
|
2534
2532
|
/** The Zod schema for this field type's JSON def. */
|
|
2535
2533
|
static toSchema(opts) {
|
|
2536
|
-
return
|
|
2534
|
+
return z7.object({ kind: z7.literal("bool"), ...refinementKeySchema("bool", opts) }).meta({ aid: "FieldType_bool" }).describe("Boolean field type.");
|
|
2537
2535
|
}
|
|
2538
2536
|
/** Resolve to the `bool` scalar comparison category. */
|
|
2539
2537
|
resolve() {
|
|
@@ -2557,8 +2555,11 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
|
|
|
2557
2555
|
return "boolean";
|
|
2558
2556
|
}
|
|
2559
2557
|
/** Zod schema validating a boolean value. */
|
|
2558
|
+
builtinA() {
|
|
2559
|
+
return a4.boolean();
|
|
2560
|
+
}
|
|
2560
2561
|
builtinValueSchema(_opts) {
|
|
2561
|
-
return
|
|
2562
|
+
return z7.boolean();
|
|
2562
2563
|
}
|
|
2563
2564
|
/** Serialize to its JSON def. */
|
|
2564
2565
|
/** Serialize to its JSON def, carrying any `as` refinement (see `FieldType.toJSON`). */
|
|
@@ -2579,7 +2580,8 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
|
|
|
2579
2580
|
};
|
|
2580
2581
|
|
|
2581
2582
|
// src/field-types/relation.ts
|
|
2582
|
-
import { z as
|
|
2583
|
+
import { z as z8 } from "zod";
|
|
2584
|
+
import { a as a5 } from "@aeye/schema";
|
|
2583
2585
|
|
|
2584
2586
|
// src/backing.ts
|
|
2585
2587
|
function joinAlias(sourceAlias, name) {
|
|
@@ -2817,12 +2819,12 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
|
|
|
2817
2819
|
}
|
|
2818
2820
|
/** The Zod schema for this field type's JSON def. */
|
|
2819
2821
|
static toSchema(opts) {
|
|
2820
|
-
return
|
|
2821
|
-
kind:
|
|
2822
|
+
return z8.object({
|
|
2823
|
+
kind: z8.literal("relation"),
|
|
2822
2824
|
...refinementKeySchema("relation", opts),
|
|
2823
|
-
to:
|
|
2824
|
-
count:
|
|
2825
|
-
inverseRelation:
|
|
2825
|
+
to: z8.string().describe("Name of the target Type this relation points to."),
|
|
2826
|
+
count: z8.number().describe("Expected related-row cardinality; 1 = belongs-to, >1 = has-many."),
|
|
2827
|
+
inverseRelation: z8.string().optional().describe("If set, the target Type gains a one-to-many relation of this name pointing back.")
|
|
2826
2828
|
}).meta({ aid: "FieldType_relation" }).describe("Relation (foreign-key) field type.");
|
|
2827
2829
|
}
|
|
2828
2830
|
/**
|
|
@@ -2965,8 +2967,11 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
|
|
|
2965
2967
|
return "text";
|
|
2966
2968
|
}
|
|
2967
2969
|
/** Zod schema validating a relation value (the related row's identifier). */
|
|
2970
|
+
builtinA() {
|
|
2971
|
+
return a5.string();
|
|
2972
|
+
}
|
|
2968
2973
|
builtinValueSchema(_opts) {
|
|
2969
|
-
return
|
|
2974
|
+
return z8.string();
|
|
2970
2975
|
}
|
|
2971
2976
|
/** Serialize to its JSON def (`inverseVia` is internal, never emitted). */
|
|
2972
2977
|
/** Serialize to its JSON def, carrying any `as` refinement (see `FieldType.toJSON`). */
|
|
@@ -2989,15 +2994,17 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
|
|
|
2989
2994
|
};
|
|
2990
2995
|
|
|
2991
2996
|
// src/field-types/date.ts
|
|
2992
|
-
import { z as
|
|
2997
|
+
import { z as z10 } from "zod";
|
|
2998
|
+
import { a as a7 } from "@aeye/schema";
|
|
2993
2999
|
|
|
2994
3000
|
// src/field-types/timestamp.ts
|
|
2995
|
-
import { z as
|
|
3001
|
+
import { z as z9 } from "zod";
|
|
3002
|
+
import { a as a6 } from "@aeye/schema";
|
|
2996
3003
|
var ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
|
|
2997
3004
|
function timezoneSchema() {
|
|
2998
|
-
return
|
|
2999
|
-
|
|
3000
|
-
|
|
3005
|
+
return z9.union([
|
|
3006
|
+
z9.string().describe('Fixed IANA timezone name (e.g. "America/New_York").'),
|
|
3007
|
+
z9.boolean().describe("true = tz-aware, false = naive/local.")
|
|
3001
3008
|
]).describe("Timezone policy.");
|
|
3002
3009
|
}
|
|
3003
3010
|
var TimestampFieldType = class _TimestampFieldType extends FieldType {
|
|
@@ -3024,8 +3031,8 @@ var TimestampFieldType = class _TimestampFieldType extends FieldType {
|
|
|
3024
3031
|
}
|
|
3025
3032
|
/** The Zod schema for this field type's JSON def. */
|
|
3026
3033
|
static toSchema(opts) {
|
|
3027
|
-
return
|
|
3028
|
-
kind:
|
|
3034
|
+
return z9.object({
|
|
3035
|
+
kind: z9.literal("timestamp"),
|
|
3029
3036
|
...refinementKeySchema("timestamp", opts),
|
|
3030
3037
|
timezone: timezoneSchema().optional()
|
|
3031
3038
|
}).meta({ aid: "FieldType_timestamp" }).describe("Timestamp (date + time) field type.");
|
|
@@ -3062,8 +3069,11 @@ var TimestampFieldType = class _TimestampFieldType extends FieldType {
|
|
|
3062
3069
|
return this.timezone === false ? "timestamp" : "timestamptz";
|
|
3063
3070
|
}
|
|
3064
3071
|
/** Zod schema validating an ISO timestamp (`YYYY-MM-DD HH:MM`) value. */
|
|
3072
|
+
builtinA() {
|
|
3073
|
+
return a6.string().pattern(ISO_TIMESTAMP.source).describe("An ISO timestamp (YYYY-MM-DD HH:MM\u2026).");
|
|
3074
|
+
}
|
|
3065
3075
|
builtinValueSchema(_opts) {
|
|
3066
|
-
return
|
|
3076
|
+
return z9.string().regex(ISO_TIMESTAMP, "expected ISO timestamp (YYYY-MM-DD HH:MM)");
|
|
3067
3077
|
}
|
|
3068
3078
|
/** Serialize to its JSON def (omitting `timezone` when unset). */
|
|
3069
3079
|
/** Serialize to its JSON def, carrying any `as` refinement (see `FieldType.toJSON`). */
|
|
@@ -3109,8 +3119,8 @@ var DateFieldType = class _DateFieldType extends FieldType {
|
|
|
3109
3119
|
}
|
|
3110
3120
|
/** The Zod schema for this field type's JSON def. */
|
|
3111
3121
|
static toSchema(opts) {
|
|
3112
|
-
return
|
|
3113
|
-
kind:
|
|
3122
|
+
return z10.object({
|
|
3123
|
+
kind: z10.literal("date"),
|
|
3114
3124
|
...refinementKeySchema("date", opts),
|
|
3115
3125
|
timezone: timezoneSchema().optional()
|
|
3116
3126
|
}).meta({ aid: "FieldType_date" }).describe("Calendar-date field type.");
|
|
@@ -3141,8 +3151,11 @@ var DateFieldType = class _DateFieldType extends FieldType {
|
|
|
3141
3151
|
return "date";
|
|
3142
3152
|
}
|
|
3143
3153
|
/** Zod schema validating an ISO date (`YYYY-MM-DD`) value. */
|
|
3154
|
+
builtinA() {
|
|
3155
|
+
return a7.string().pattern(ISO_DATE.source).describe("An ISO date (YYYY-MM-DD).");
|
|
3156
|
+
}
|
|
3144
3157
|
builtinValueSchema(_opts) {
|
|
3145
|
-
return
|
|
3158
|
+
return z10.string().regex(ISO_DATE, "expected ISO date (YYYY-MM-DD)");
|
|
3146
3159
|
}
|
|
3147
3160
|
/** Serialize to its JSON def (omitting `timezone` when unset). */
|
|
3148
3161
|
/** Serialize to its JSON def, carrying any `as` refinement (see `FieldType.toJSON`). */
|
|
@@ -3163,16 +3176,17 @@ var DateFieldType = class _DateFieldType extends FieldType {
|
|
|
3163
3176
|
};
|
|
3164
3177
|
|
|
3165
3178
|
// src/field-types/json.ts
|
|
3166
|
-
import { z as
|
|
3179
|
+
import { z as z11 } from "zod";
|
|
3180
|
+
import { a as a8 } from "@aeye/schema";
|
|
3167
3181
|
function jsonValueSchema() {
|
|
3168
|
-
const schema =
|
|
3169
|
-
() =>
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3182
|
+
const schema = z11.lazy(
|
|
3183
|
+
() => z11.union([
|
|
3184
|
+
z11.string(),
|
|
3185
|
+
z11.number(),
|
|
3186
|
+
z11.boolean(),
|
|
3187
|
+
z11.null(),
|
|
3188
|
+
z11.array(schema),
|
|
3189
|
+
z11.record(z11.string(), schema)
|
|
3176
3190
|
])
|
|
3177
3191
|
);
|
|
3178
3192
|
return schema;
|
|
@@ -3201,8 +3215,8 @@ var JsonFieldType = class _JsonFieldType extends FieldType {
|
|
|
3201
3215
|
}
|
|
3202
3216
|
/** The Zod schema for this field type's JSON def. */
|
|
3203
3217
|
static toSchema(opts) {
|
|
3204
|
-
return
|
|
3205
|
-
kind:
|
|
3218
|
+
return z11.object({
|
|
3219
|
+
kind: z11.literal("json"),
|
|
3206
3220
|
...refinementKeySchema("json", opts),
|
|
3207
3221
|
schema: jsonValueSchema().optional().describe("Optional JSON-Schema-shaped constraint.")
|
|
3208
3222
|
}).meta({ aid: "FieldType_json" }).describe("JSON-document field type.");
|
|
@@ -3235,6 +3249,9 @@ var JsonFieldType = class _JsonFieldType extends FieldType {
|
|
|
3235
3249
|
return "jsonb";
|
|
3236
3250
|
}
|
|
3237
3251
|
/** Zod schema validating any JSON value. */
|
|
3252
|
+
builtinA() {
|
|
3253
|
+
return a8.json();
|
|
3254
|
+
}
|
|
3238
3255
|
builtinValueSchema(_opts) {
|
|
3239
3256
|
return jsonValueSchema();
|
|
3240
3257
|
}
|
|
@@ -3258,7 +3275,8 @@ var JsonFieldType = class _JsonFieldType extends FieldType {
|
|
|
3258
3275
|
};
|
|
3259
3276
|
|
|
3260
3277
|
// src/field-types/array.ts
|
|
3261
|
-
import { z as
|
|
3278
|
+
import { z as z12 } from "zod";
|
|
3279
|
+
import { a as a9 } from "@aeye/schema";
|
|
3262
3280
|
var DEFAULT_AVG_ITEMS = 4;
|
|
3263
3281
|
var UNKNOWN_ITEM_BYTES = 16;
|
|
3264
3282
|
var ArrayFieldType = class _ArrayFieldType extends FieldType {
|
|
@@ -3290,12 +3308,12 @@ var ArrayFieldType = class _ArrayFieldType extends FieldType {
|
|
|
3290
3308
|
}
|
|
3291
3309
|
/** The Zod schema for this field type's JSON def. */
|
|
3292
3310
|
static toSchema(opts) {
|
|
3293
|
-
const item =
|
|
3294
|
-
return
|
|
3295
|
-
kind:
|
|
3311
|
+
const item = z12.lazy(() => fieldTypeDefSchema(opts));
|
|
3312
|
+
return z12.object({
|
|
3313
|
+
kind: z12.literal("array"),
|
|
3296
3314
|
...refinementKeySchema("array", opts),
|
|
3297
|
-
minItems:
|
|
3298
|
-
maxItems:
|
|
3315
|
+
minItems: z12.number().int().optional().describe("Minimum element count (e.g. non-empty \u2192 1)."),
|
|
3316
|
+
maxItems: z12.number().int().optional().describe("Maximum element count; omit when unbounded."),
|
|
3299
3317
|
item: item.optional().describe("Element field type; omit for heterogeneous / unknown elements.")
|
|
3300
3318
|
}).meta({ aid: "FieldType_array" }).describe("Ordered collection (array) field type.");
|
|
3301
3319
|
}
|
|
@@ -3368,8 +3386,14 @@ var ArrayFieldType = class _ArrayFieldType extends FieldType {
|
|
|
3368
3386
|
return "json";
|
|
3369
3387
|
}
|
|
3370
3388
|
/** Zod schema validating an array value, honoring element type and bounds. */
|
|
3389
|
+
builtinA() {
|
|
3390
|
+
let s = a9.array(this.item ? this.item.toA() : a9.json());
|
|
3391
|
+
if (this.minItems !== void 0) s = s.min(this.minItems);
|
|
3392
|
+
if (this.maxItems !== void 0) s = s.max(this.maxItems);
|
|
3393
|
+
return s;
|
|
3394
|
+
}
|
|
3371
3395
|
builtinValueSchema(opts) {
|
|
3372
|
-
let s =
|
|
3396
|
+
let s = z12.array(this.item ? this.item.toValueSchema(opts) : jsonValueSchema());
|
|
3373
3397
|
if (this.minItems !== void 0) s = s.min(this.minItems);
|
|
3374
3398
|
if (this.maxItems !== void 0) s = s.max(this.maxItems);
|
|
3375
3399
|
return s;
|
|
@@ -3416,7 +3440,7 @@ function fieldTypeDefSchema(opts) {
|
|
|
3416
3440
|
const classes = opts?.registry?.fieldTypeClassList() ?? BUILTIN_FIELD_TYPES;
|
|
3417
3441
|
const branches = classes.map((c) => c.toSchema(opts));
|
|
3418
3442
|
const first = branches[0];
|
|
3419
|
-
if (!first) return
|
|
3443
|
+
if (!first) return z13.never();
|
|
3420
3444
|
return branches.slice(1).reduce((acc, s) => acc.or(s), first).describe(`Field type definition (one of the ${branches.length} registered kinds).`);
|
|
3421
3445
|
}
|
|
3422
3446
|
|
|
@@ -3491,11 +3515,11 @@ function affectedOne(type, rows) {
|
|
|
3491
3515
|
var ZERO_COST = { rows: 0, bytes: 0 };
|
|
3492
3516
|
var ALWAYS_CHANGES = 0;
|
|
3493
3517
|
var NEVER_CHANGES = -1;
|
|
3494
|
-
function foldChanges(
|
|
3495
|
-
if (
|
|
3496
|
-
if (
|
|
3497
|
-
if (b < 0) return
|
|
3498
|
-
return Math.min(
|
|
3518
|
+
function foldChanges(a13, b) {
|
|
3519
|
+
if (a13 === ALWAYS_CHANGES || b === ALWAYS_CHANGES) return ALWAYS_CHANGES;
|
|
3520
|
+
if (a13 < 0) return b;
|
|
3521
|
+
if (b < 0) return a13;
|
|
3522
|
+
return Math.min(a13, b);
|
|
3499
3523
|
}
|
|
3500
3524
|
var EQ_SELECTIVITY = 0.33;
|
|
3501
3525
|
var RANGE_SELECTIVITY = 0.5;
|
|
@@ -3503,11 +3527,11 @@ var IN_SELECTIVITY = 0.5;
|
|
|
3503
3527
|
var RECURSIVE_CTE_LEVELS = 4;
|
|
3504
3528
|
var SEMANTIC_ROW_PENALTY = 1e3;
|
|
3505
3529
|
var TEXT_SEARCH_ROW_PENALTY = 100;
|
|
3506
|
-
function addCost(
|
|
3507
|
-
return { rows:
|
|
3530
|
+
function addCost(a13, b) {
|
|
3531
|
+
return { rows: a13.rows + b.rows, bytes: a13.bytes + b.bytes };
|
|
3508
3532
|
}
|
|
3509
|
-
function maxCost(
|
|
3510
|
-
return { rows: Math.max(
|
|
3533
|
+
function maxCost(a13, b) {
|
|
3534
|
+
return { rows: Math.max(a13.rows, b.rows), bytes: Math.max(a13.bytes, b.bytes) };
|
|
3511
3535
|
}
|
|
3512
3536
|
function scaleRows(cost, factor) {
|
|
3513
3537
|
const rows = Math.max(1, cost.rows * factor);
|
|
@@ -3709,8 +3733,8 @@ var QueryFunction = class _QueryFunction {
|
|
|
3709
3733
|
orderedArgs(namedArgs) {
|
|
3710
3734
|
const out = [];
|
|
3711
3735
|
for (const param4 of this.params) {
|
|
3712
|
-
const
|
|
3713
|
-
if (
|
|
3736
|
+
const a13 = namedArgs.get(param4.name);
|
|
3737
|
+
if (a13) out.push(a13);
|
|
3714
3738
|
}
|
|
3715
3739
|
return out;
|
|
3716
3740
|
}
|
|
@@ -3737,17 +3761,17 @@ var QueryFunction = class _QueryFunction {
|
|
|
3737
3761
|
const argTypes = this.orderedArgs(namedArgs);
|
|
3738
3762
|
const sources = [];
|
|
3739
3763
|
let nullable = false;
|
|
3740
|
-
for (const
|
|
3741
|
-
sources.push(...sourcesOf(
|
|
3742
|
-
if (
|
|
3764
|
+
for (const a13 of argTypes) {
|
|
3765
|
+
sources.push(...sourcesOf(a13));
|
|
3766
|
+
if (a13.kind !== "type" && a13.nullable) nullable = true;
|
|
3743
3767
|
}
|
|
3744
|
-
const aggregate2 = this.shape === "aggregate" || argTypes.some((
|
|
3768
|
+
const aggregate2 = this.shape === "aggregate" || argTypes.some((a13) => a13.kind === "computed" && a13.aggregate);
|
|
3745
3769
|
let fieldType;
|
|
3746
3770
|
if (this.output.tag === "field") {
|
|
3747
3771
|
fieldType = this.output.fieldType;
|
|
3748
3772
|
} else {
|
|
3749
|
-
for (const
|
|
3750
|
-
const ft = asFieldType(
|
|
3773
|
+
for (const a13 of argTypes) {
|
|
3774
|
+
const ft = asFieldType(a13);
|
|
3751
3775
|
if (ft) {
|
|
3752
3776
|
fieldType = ft;
|
|
3753
3777
|
break;
|
|
@@ -4179,9 +4203,6 @@ function parenthesized(template) {
|
|
|
4179
4203
|
return depth === 0;
|
|
4180
4204
|
}
|
|
4181
4205
|
|
|
4182
|
-
// src/exprs/literal.ts
|
|
4183
|
-
import { z as z16 } from "zod";
|
|
4184
|
-
|
|
4185
4206
|
// src/index-spec.ts
|
|
4186
4207
|
var NON_FIELD_PART_BYTES = 8;
|
|
4187
4208
|
function stableStringify(value2) {
|
|
@@ -4424,10 +4445,10 @@ var Value = class _Value {
|
|
|
4424
4445
|
if (this.raw === other.raw) return 0;
|
|
4425
4446
|
return this.raw ? 1 : -1;
|
|
4426
4447
|
}
|
|
4427
|
-
const
|
|
4448
|
+
const a13 = this.toText();
|
|
4428
4449
|
const b = other.toText();
|
|
4429
|
-
if (
|
|
4430
|
-
return
|
|
4450
|
+
if (a13 === b) return 0;
|
|
4451
|
+
return a13 < b ? -1 : 1;
|
|
4431
4452
|
}
|
|
4432
4453
|
/**
|
|
4433
4454
|
* The {@link TextCasing} this value's originating field type DECLARES, or
|
|
@@ -4466,10 +4487,10 @@ var Value = class _Value {
|
|
|
4466
4487
|
compareToCase(other, sensitive) {
|
|
4467
4488
|
const folds = !sensitive && typeof this.raw === "string" && typeof other.raw === "string";
|
|
4468
4489
|
if (folds && effectiveComparator(this.comparator(), other.comparator()) === void 0) {
|
|
4469
|
-
const
|
|
4490
|
+
const a13 = this.raw.toLowerCase();
|
|
4470
4491
|
const b = other.raw.toLowerCase();
|
|
4471
|
-
if (
|
|
4472
|
-
return
|
|
4492
|
+
if (a13 === b) return 0;
|
|
4493
|
+
return a13 < b ? -1 : 1;
|
|
4473
4494
|
}
|
|
4474
4495
|
return this.compareTo(other);
|
|
4475
4496
|
}
|
|
@@ -4748,7 +4769,6 @@ function canonicalize(expr) {
|
|
|
4748
4769
|
}
|
|
4749
4770
|
|
|
4750
4771
|
// src/exprs/_shared.ts
|
|
4751
|
-
import { z as z15 } from "zod";
|
|
4752
4772
|
function computed(fieldType, sources, nullable, aggregate2, applied) {
|
|
4753
4773
|
const rt = { kind: "computed", fieldType, sources, nullable, aggregate: aggregate2 };
|
|
4754
4774
|
if (!applied) return rt;
|
|
@@ -4792,8 +4812,8 @@ function hasManyValueMessage(rel) {
|
|
|
4792
4812
|
function relationAggregateMessage(rel) {
|
|
4793
4813
|
return `'${rel.source}.${rel.field}' is a relation: its value is an IDENTITY, which cannot be aggregated. Group BY it (or order by it) instead, aggregate one of the joined target's scalar fields, or count rows.`;
|
|
4794
4814
|
}
|
|
4795
|
-
function relationValueProblem(
|
|
4796
|
-
const ra = relationOf(
|
|
4815
|
+
function relationValueProblem(a13, b) {
|
|
4816
|
+
const ra = relationOf(a13);
|
|
4797
4817
|
const rb = relationOf(b);
|
|
4798
4818
|
if (!ra && !rb) return void 0;
|
|
4799
4819
|
if (ra && rb) {
|
|
@@ -4807,15 +4827,6 @@ function relationValueProblem(a, b) {
|
|
|
4807
4827
|
if (!rel) return void 0;
|
|
4808
4828
|
return relationAsValueMessage(rel);
|
|
4809
4829
|
}
|
|
4810
|
-
function looseExprSchema() {
|
|
4811
|
-
return z15.looseObject({ kind: z15.string() });
|
|
4812
|
-
}
|
|
4813
|
-
function childExprSchema(Expr9) {
|
|
4814
|
-
return Expr9 ?? looseExprSchema();
|
|
4815
|
-
}
|
|
4816
|
-
function childQuerySchema(Query2) {
|
|
4817
|
-
return Query2 ?? looseExprSchema();
|
|
4818
|
-
}
|
|
4819
4830
|
function emitSubquerySQL(dialect, ctx, def) {
|
|
4820
4831
|
return ctx.engine.parseQuery(def).toSQL(dialect, ctx).parens();
|
|
4821
4832
|
}
|
|
@@ -4845,7 +4856,7 @@ __export(shape_exports, {
|
|
|
4845
4856
|
exprRef: () => exprRef,
|
|
4846
4857
|
int: () => int,
|
|
4847
4858
|
isJsonValue: () => isJsonValue,
|
|
4848
|
-
isRecord: () =>
|
|
4859
|
+
isRecord: () => isRecord2,
|
|
4849
4860
|
json: () => json,
|
|
4850
4861
|
list: () => list,
|
|
4851
4862
|
lit: () => lit,
|
|
@@ -4862,7 +4873,7 @@ __export(shape_exports, {
|
|
|
4862
4873
|
|
|
4863
4874
|
// src/shape/shape.ts
|
|
4864
4875
|
var INVALID = /* @__PURE__ */ Symbol("invalid");
|
|
4865
|
-
function
|
|
4876
|
+
function isRecord2(value2) {
|
|
4866
4877
|
return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
4867
4878
|
}
|
|
4868
4879
|
function gotTail(json2) {
|
|
@@ -4996,7 +5007,7 @@ function list(shape, opts = {}) {
|
|
|
4996
5007
|
function record(shape, aid) {
|
|
4997
5008
|
return {
|
|
4998
5009
|
check(json2, ctx) {
|
|
4999
|
-
if (!
|
|
5010
|
+
if (!isRecord2(json2)) {
|
|
5000
5011
|
ctx.problems.error("shape.not-object", expected(aid, json2));
|
|
5001
5012
|
return INVALID;
|
|
5002
5013
|
}
|
|
@@ -5052,7 +5063,7 @@ function obj(fields, build, opts = {}) {
|
|
|
5052
5063
|
const required = keys.filter((key) => !optionalKeys.has(key));
|
|
5053
5064
|
return {
|
|
5054
5065
|
check(json2, ctx) {
|
|
5055
|
-
if (!
|
|
5066
|
+
if (!isRecord2(json2)) {
|
|
5056
5067
|
ctx.problems.error("shape.not-object", expected(opts.aid ?? "Expr", json2));
|
|
5057
5068
|
return INVALID;
|
|
5058
5069
|
}
|
|
@@ -5233,16 +5244,6 @@ var LiteralExpr = class _LiteralExpr extends Expr {
|
|
|
5233
5244
|
(v) => new _LiteralExpr(v.value),
|
|
5234
5245
|
{ aid: "Expr_literal" }
|
|
5235
5246
|
);
|
|
5236
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
5237
|
-
static toSchema(_opts) {
|
|
5238
|
-
return withAid(
|
|
5239
|
-
z16.object({
|
|
5240
|
-
kind: z16.literal("literal"),
|
|
5241
|
-
value: withAid(jsonValueSchema(), "LiteralValue")
|
|
5242
|
-
}),
|
|
5243
|
-
"Expr_literal"
|
|
5244
|
-
).describe("A constant value: a scalar, or a whole JSON document for a json / array field.");
|
|
5245
|
-
}
|
|
5246
5247
|
/** Whether this is the SQL `NULL` literal. */
|
|
5247
5248
|
isNullLiteral() {
|
|
5248
5249
|
return this.value === null;
|
|
@@ -5307,7 +5308,6 @@ var LiteralExpr = class _LiteralExpr extends Expr {
|
|
|
5307
5308
|
};
|
|
5308
5309
|
|
|
5309
5310
|
// src/exprs/param.ts
|
|
5310
|
-
import { z as z17 } from "zod";
|
|
5311
5311
|
var ParamExpr = class _ParamExpr extends Expr {
|
|
5312
5312
|
/** Wrap a named bind parameter (its type is inferred from usage). */
|
|
5313
5313
|
constructor(name) {
|
|
@@ -5339,16 +5339,6 @@ var ParamExpr = class _ParamExpr extends Expr {
|
|
|
5339
5339
|
(v) => new _ParamExpr(v.name),
|
|
5340
5340
|
{ aid: "Expr_param" }
|
|
5341
5341
|
);
|
|
5342
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
5343
|
-
static toSchema(_opts) {
|
|
5344
|
-
return withAid(
|
|
5345
|
-
z17.object({
|
|
5346
|
-
kind: z17.literal("param"),
|
|
5347
|
-
name: z17.string().describe("Parameter name; its type is inferred from usage.")
|
|
5348
|
-
}),
|
|
5349
|
-
"Expr_param"
|
|
5350
|
-
).describe("A named bind parameter (contextually typed).");
|
|
5351
|
-
}
|
|
5352
5342
|
contributeParams(params) {
|
|
5353
5343
|
params.reference(this.name);
|
|
5354
5344
|
}
|
|
@@ -5423,12 +5413,6 @@ function typedValueSql(expr, target, dialect, ctx, site) {
|
|
|
5423
5413
|
return expr.toSQL(dialect, ctx);
|
|
5424
5414
|
}
|
|
5425
5415
|
|
|
5426
|
-
// src/exprs/comparison.ts
|
|
5427
|
-
import { z as z20 } from "zod";
|
|
5428
|
-
|
|
5429
|
-
// src/schema-build.ts
|
|
5430
|
-
import { z as z18 } from "zod";
|
|
5431
|
-
|
|
5432
5416
|
// src/write-model.ts
|
|
5433
5417
|
function requiredOnInsert(field, fb) {
|
|
5434
5418
|
if (!field.insertableFor(fb)) return false;
|
|
@@ -5449,465 +5433,7 @@ function checkFieldExpr(kind, field, source, p) {
|
|
|
5449
5433
|
}
|
|
5450
5434
|
}
|
|
5451
5435
|
|
|
5452
|
-
// src/schema-build.ts
|
|
5453
|
-
function enumOf2(values) {
|
|
5454
|
-
const unique = Array.from(new Set(values));
|
|
5455
|
-
const first = unique[0];
|
|
5456
|
-
if (first === void 0) return z18.never();
|
|
5457
|
-
return unique.slice(1).reduce((acc, v) => acc.or(z18.literal(v)), z18.literal(first));
|
|
5458
|
-
}
|
|
5459
|
-
function orFold(branches) {
|
|
5460
|
-
const first = branches[0];
|
|
5461
|
-
if (!first) return z18.never();
|
|
5462
|
-
return branches.slice(1).reduce((acc, s) => acc.or(s), first);
|
|
5463
|
-
}
|
|
5464
|
-
function paramSchema() {
|
|
5465
|
-
return z18.object({ kind: z18.literal("param"), name: z18.string() }).describe("A named bind parameter.");
|
|
5466
|
-
}
|
|
5467
|
-
var cacheGeneration = 0;
|
|
5468
|
-
var SchemaCache = class {
|
|
5469
|
-
/** This cache's generation, salting its ids to stay unique in `sharedIdRegistry`. */
|
|
5470
|
-
generation = ++cacheGeneration;
|
|
5471
|
-
/** content-key → the built, id-tagged instance. */
|
|
5472
|
-
byKey = /* @__PURE__ */ new Map();
|
|
5473
|
-
/** id base → how many distinct fragments have claimed it (for `_2` suffixes). */
|
|
5474
|
-
baseUses = /* @__PURE__ */ new Map();
|
|
5475
|
-
/**
|
|
5476
|
-
* A process-unique, mostly-readable `$def` id for `idBase`: disambiguated to
|
|
5477
|
-
* `idBase_2`, `idBase_3`, … when a DIFFERENT fragment in THIS cache already
|
|
5478
|
-
* claimed the base, then salted with `_g<generation>` for every cache after
|
|
5479
|
-
* the first so ids never collide in the process-local `sharedIdRegistry`.
|
|
5480
|
-
*/
|
|
5481
|
-
defId(idBase) {
|
|
5482
|
-
const used = this.baseUses.get(idBase) ?? 0;
|
|
5483
|
-
this.baseUses.set(idBase, used + 1);
|
|
5484
|
-
const local = used === 0 ? idBase : `${idBase}_${used + 1}`;
|
|
5485
|
-
return this.generation === 1 ? local : `${local}_g${this.generation}`;
|
|
5486
|
-
}
|
|
5487
|
-
/**
|
|
5488
|
-
* Return the shared instance for `contentKey`, building (and id-tagging) it on
|
|
5489
|
-
* first request via {@link defId}. Two positions producing the identical
|
|
5490
|
-
* fragment (same `contentKey`) share ONE instance ⇒ one `$def` + `$ref`s.
|
|
5491
|
-
*/
|
|
5492
|
-
shared(contentKey, idBase, build) {
|
|
5493
|
-
const cached = this.byKey.get(contentKey);
|
|
5494
|
-
if (cached) return cached;
|
|
5495
|
-
const instance = build(this.defId(idBase));
|
|
5496
|
-
this.byKey.set(contentKey, instance);
|
|
5497
|
-
return instance;
|
|
5498
|
-
}
|
|
5499
|
-
/**
|
|
5500
|
-
* A shared `FieldName` enum over `names` (a Type's eligible fields), id
|
|
5501
|
-
* `Fields_<typeHint>`. Reused across every reference position that enumerates
|
|
5502
|
-
* the same field set.
|
|
5503
|
-
*/
|
|
5504
|
-
fieldEnum(names, typeHint) {
|
|
5505
|
-
const key = `fields\0${names.join("\0")}`;
|
|
5506
|
-
return this.shared(key, `Fields_${typeHint}`, (id) => withAid(enumOf2(names), "FieldName", { id }));
|
|
5507
|
-
}
|
|
5508
|
-
/** The shared `param` expr fragment (id `param`). */
|
|
5509
|
-
param() {
|
|
5510
|
-
return this.shared(
|
|
5511
|
-
"param",
|
|
5512
|
-
"param",
|
|
5513
|
-
(id) => withSharedId(
|
|
5514
|
-
z18.object({ kind: z18.literal("param"), name: z18.string() }).describe("A named bind parameter."),
|
|
5515
|
-
id
|
|
5516
|
-
)
|
|
5517
|
-
);
|
|
5518
|
-
}
|
|
5519
|
-
/**
|
|
5520
|
-
* A shared typed-args `strictObject` for a function, keyed by its argument
|
|
5521
|
-
* SIGNATURE (param names + optionality) — NOT its name. The 100+ registered
|
|
5522
|
-
* functions collapse to a few dozen distinct signatures (e.g. dozens share a
|
|
5523
|
-
* lone `value` argument), so this is the single biggest paired-schema win.
|
|
5524
|
-
* The `child` (any-`Expr`) is the SAME shared instance for every function, so
|
|
5525
|
-
* the signature fully determines the shape; the describe names the signature's
|
|
5526
|
-
* params rather than the function, keeping it accurate for every sharer.
|
|
5527
|
-
*/
|
|
5528
|
-
typedArgs(fn2, child) {
|
|
5529
|
-
const params = fn2.params.map((p) => `${p.name}${p.optional ? "?" : ""}`);
|
|
5530
|
-
return this.shared(`args ${params.join(",")}`, "Args", (id) => {
|
|
5531
|
-
const shape = {};
|
|
5532
|
-
for (const param4 of fn2.params) shape[param4.name] = param4.optional ? child.optional() : child;
|
|
5533
|
-
const named = params.length ? params.join(", ") : "none";
|
|
5534
|
-
return withSharedId(z18.strictObject(shape).describe(`Named arguments: ${named}.`), id);
|
|
5535
|
-
});
|
|
5536
|
-
}
|
|
5537
|
-
};
|
|
5538
|
-
var allFields = (t) => t.fields;
|
|
5539
|
-
var relationFieldsOf = (t) => t.relationFields();
|
|
5540
|
-
var semanticFieldsOf = (t) => t.semanticFields();
|
|
5541
|
-
var textFieldsOf = (t) => t.textFields();
|
|
5542
|
-
function allowingExpr(base, kind) {
|
|
5543
|
-
return (t) => base(t).filter((f) => f.allowsExpr(kind));
|
|
5544
|
-
}
|
|
5545
|
-
function eligibleFieldNames(types, eligible) {
|
|
5546
|
-
const seen = /* @__PURE__ */ new Set();
|
|
5547
|
-
for (const t of types) for (const f of eligible(t)) seen.add(f.name);
|
|
5548
|
-
return Array.from(seen);
|
|
5549
|
-
}
|
|
5550
|
-
function fieldProperty(mode, fieldValue) {
|
|
5551
|
-
switch (mode) {
|
|
5552
|
-
case "none":
|
|
5553
|
-
return {};
|
|
5554
|
-
case "one":
|
|
5555
|
-
return { field: fieldValue.describe("A field of the referenced source.") };
|
|
5556
|
-
case "optional":
|
|
5557
|
-
return { field: fieldValue.optional().describe("A field to narrow to (omit for the whole source).") };
|
|
5558
|
-
case "list":
|
|
5559
|
-
return { fields: z18.array(fieldValue).optional().describe("Optional allowlist of fields the reference may touch.") };
|
|
5560
|
-
/* v8 ignore next 2 -- unreachable: `mode` exhaustively covers RefFieldMode (compile-time guard) */
|
|
5561
|
-
default:
|
|
5562
|
-
return assertNeverFieldMode(mode);
|
|
5563
|
-
}
|
|
5564
|
-
}
|
|
5565
|
-
function refObject(keyName, keyValue, fieldProps, extras, aid, describe) {
|
|
5566
|
-
const shape = { [keyName]: keyValue, ...fieldProps, ...extras };
|
|
5567
|
-
const obj2 = z18.object(shape);
|
|
5568
|
-
return (aid ? withAid(obj2, aid) : obj2).describe(describe);
|
|
5569
|
-
}
|
|
5570
|
-
function refSchema(types, depth, opts, cache) {
|
|
5571
|
-
const keyNoun = opts.keyName === "type" ? "a registered Type name" : "a bound source name";
|
|
5572
|
-
const fieldEnum = (names, typeHint) => cache ? cache.fieldEnum(names, typeHint) : withAid(enumOf2(names), "FieldName");
|
|
5573
|
-
if (depth === "paired") {
|
|
5574
|
-
const branches = types.map((t) => {
|
|
5575
|
-
const names = opts.eligible(t).map((f) => f.name);
|
|
5576
|
-
const fieldValue2 = names.length ? fieldEnum(names, t.name) : z18.string();
|
|
5577
|
-
const keyValue2 = z18.literal(t.name).describe(`The \`${t.name}\` ${opts.keyName} (its Type name).`);
|
|
5578
|
-
const fieldProps2 = fieldProperty(opts.fieldMode, fieldValue2);
|
|
5579
|
-
return refObject(
|
|
5580
|
-
opts.keyName,
|
|
5581
|
-
keyValue2,
|
|
5582
|
-
fieldProps2,
|
|
5583
|
-
opts.extras,
|
|
5584
|
-
opts.aid ? `${opts.aid}_${t.name}` : void 0,
|
|
5585
|
-
`A reference into \`${t.name}\`.`
|
|
5586
|
-
);
|
|
5587
|
-
});
|
|
5588
|
-
return orFold(branches).describe(opts.describe);
|
|
5589
|
-
}
|
|
5590
|
-
const enumKey = depth === "types" || depth === "both";
|
|
5591
|
-
const enumField = depth === "fields" || depth === "both";
|
|
5592
|
-
const keyBase = enumKey ? enumOf2(types.map((t) => t.name)) : z18.string();
|
|
5593
|
-
const keyTagged = enumKey && opts.keyName === "type" ? withAid(keyBase, "TypeName") : keyBase;
|
|
5594
|
-
const keyValue = keyTagged.describe(
|
|
5595
|
-
enumKey ? `${keyNoun[0].toUpperCase()}${keyNoun.slice(1)}.` : `A ${opts.keyName} name.`
|
|
5596
|
-
);
|
|
5597
|
-
const fieldNames = eligibleFieldNames(types, opts.eligible);
|
|
5598
|
-
const fieldValue = enumField && fieldNames.length ? fieldEnum(fieldNames, "any") : z18.string();
|
|
5599
|
-
const fieldProps = fieldProperty(opts.fieldMode, fieldValue);
|
|
5600
|
-
return refObject(opts.keyName, keyValue, fieldProps, opts.extras, opts.aid, opts.describe);
|
|
5601
|
-
}
|
|
5602
|
-
function fieldRefSchema(types, depth, cache) {
|
|
5603
|
-
return refSchema(types, depth, {
|
|
5604
|
-
keyName: "source",
|
|
5605
|
-
fieldMode: "one",
|
|
5606
|
-
eligible: allowingExpr(allFields, "field-ref"),
|
|
5607
|
-
extras: { kind: z18.literal("field-ref") },
|
|
5608
|
-
aid: "Expr_field-ref",
|
|
5609
|
-
describe: "A direct field reference."
|
|
5610
|
-
}, cache);
|
|
5611
|
-
}
|
|
5612
|
-
function paramFragment(cache) {
|
|
5613
|
-
return cache ? cache.param() : paramSchema();
|
|
5614
|
-
}
|
|
5615
|
-
function semanticQuerySchema(types, depth, cache) {
|
|
5616
|
-
const sourceField = refSchema(types, depth, {
|
|
5617
|
-
keyName: "source",
|
|
5618
|
-
fieldMode: "one",
|
|
5619
|
-
eligible: semanticFieldsOf,
|
|
5620
|
-
describe: "Another BOUND source + semantic field whose embedding is the query vector (cross-source pairing)."
|
|
5621
|
-
}, cache);
|
|
5622
|
-
const typeField = refSchema(types, depth, {
|
|
5623
|
-
keyName: "type",
|
|
5624
|
-
fieldMode: "one",
|
|
5625
|
-
eligible: semanticFieldsOf,
|
|
5626
|
-
describe: "A semantic Type + field, resolved to that Type's single bound source, whose embedding is the query vector."
|
|
5627
|
-
}, cache);
|
|
5628
|
-
return orFold([
|
|
5629
|
-
z18.string().describe("A literal natural-language query."),
|
|
5630
|
-
paramFragment(cache),
|
|
5631
|
-
sourceField,
|
|
5632
|
-
typeField
|
|
5633
|
-
]).describe("The query: text, a param, a bound source+field, or a semantic Type+field.");
|
|
5634
|
-
}
|
|
5635
|
-
function semanticSchema(types, depth, cache) {
|
|
5636
|
-
return refSchema(types, depth, {
|
|
5637
|
-
keyName: "source",
|
|
5638
|
-
fieldMode: "optional",
|
|
5639
|
-
eligible: allowingExpr(semanticFieldsOf, "semantic"),
|
|
5640
|
-
extras: { kind: z18.literal("semantic"), query: semanticQuerySchema(types, depth, cache) },
|
|
5641
|
-
aid: "Expr_semantic",
|
|
5642
|
-
describe: "Semantic-similarity score (requires an embedder)."
|
|
5643
|
-
}, cache);
|
|
5644
|
-
}
|
|
5645
|
-
function textSearchSchema(types, depth, cache) {
|
|
5646
|
-
return refSchema(types, depth, {
|
|
5647
|
-
keyName: "source",
|
|
5648
|
-
fieldMode: "optional",
|
|
5649
|
-
eligible: allowingExpr(textFieldsOf, "text-search"),
|
|
5650
|
-
extras: {
|
|
5651
|
-
kind: z18.literal("text-search"),
|
|
5652
|
-
query: z18.string().or(paramFragment(cache)).describe("Search query: a literal string or a param.")
|
|
5653
|
-
},
|
|
5654
|
-
aid: "Expr_text-search",
|
|
5655
|
-
describe: "Full-text search predicate."
|
|
5656
|
-
}, cache);
|
|
5657
|
-
}
|
|
5658
|
-
function textScoreSchema(types, depth, cache) {
|
|
5659
|
-
return refSchema(types, depth, {
|
|
5660
|
-
keyName: "source",
|
|
5661
|
-
fieldMode: "optional",
|
|
5662
|
-
eligible: allowingExpr(textFieldsOf, "text-score"),
|
|
5663
|
-
extras: {
|
|
5664
|
-
kind: z18.literal("text-score"),
|
|
5665
|
-
query: z18.string().or(paramFragment(cache)).describe("Search query: a literal string or a param.")
|
|
5666
|
-
},
|
|
5667
|
-
aid: "Expr_text-score",
|
|
5668
|
-
describe: "Numeric full-text relevance score (usable in SELECT / ORDER BY)."
|
|
5669
|
-
}, cache);
|
|
5670
|
-
}
|
|
5671
|
-
function filtersSchema(types, depth, cache) {
|
|
5672
|
-
return refSchema(types, depth, {
|
|
5673
|
-
keyName: "source",
|
|
5674
|
-
fieldMode: "list",
|
|
5675
|
-
eligible: allowingExpr(allFields, "filters"),
|
|
5676
|
-
extras: { kind: z18.literal("filters") },
|
|
5677
|
-
aid: "Expr_filters",
|
|
5678
|
-
describe: "A structured filter placeholder; clauses are supplied at execution time."
|
|
5679
|
-
}, cache);
|
|
5680
|
-
}
|
|
5681
|
-
function sorterSchema(childExpr) {
|
|
5682
|
-
const entry = z18.object({
|
|
5683
|
-
sort: z18.string().describe("A declared sort name (a key of `sorts`)."),
|
|
5684
|
-
dir: withAid(enumOf2(["asc", "desc"]), "OrderDir")
|
|
5685
|
-
});
|
|
5686
|
-
return withAid(
|
|
5687
|
-
z18.object({
|
|
5688
|
-
kind: z18.literal("sorter"),
|
|
5689
|
-
sorts: z18.record(z18.string(), childExpr).describe("Named sortable expressions (sort name \u2192 expr); the caller selects by name at run time."),
|
|
5690
|
-
defaultSort: z18.array(entry).optional().describe("Default multi-key sort (each `{ sort, dir }`) applied when the caller selects none.")
|
|
5691
|
-
}),
|
|
5692
|
-
"Expr_sorter"
|
|
5693
|
-
).describe("A dynamic-sort catalog (valid only in a SELECT `order`); the selection is supplied at execution time.");
|
|
5694
|
-
}
|
|
5695
|
-
function writeValueSchema(field, writes, Expr9) {
|
|
5696
|
-
if (writes === "typed") {
|
|
5697
|
-
return field.fieldType.toValueSchema().or(Expr9).describe(`A ${field.fieldType.kind} value, or an expression.`);
|
|
5698
|
-
}
|
|
5699
|
-
return Expr9;
|
|
5700
|
-
}
|
|
5701
|
-
function insertRowSchema(type, fbOf, writes, Expr9) {
|
|
5702
|
-
const shape = {};
|
|
5703
|
-
for (const f of type.fields) {
|
|
5704
|
-
const fb = fbOf(type.name, f.name);
|
|
5705
|
-
if (!f.insertableFor(fb)) continue;
|
|
5706
|
-
const value2 = writeValueSchema(f, writes, Expr9);
|
|
5707
|
-
const required = writes === "typed" && requiredOnInsert(f, fb);
|
|
5708
|
-
shape[f.name] = required ? value2 : value2.optional();
|
|
5709
|
-
}
|
|
5710
|
-
return z18.strictObject(shape).describe(`A row to insert into ${type.name} (field \u2192 value).`);
|
|
5711
|
-
}
|
|
5712
|
-
function updateSetSchema(type, fbOf, writes, Expr9) {
|
|
5713
|
-
const shape = {};
|
|
5714
|
-
for (const f of type.fields) {
|
|
5715
|
-
const fb = fbOf(type.name, f.name);
|
|
5716
|
-
if (!f.updatableFor(fb)) continue;
|
|
5717
|
-
shape[f.name] = writeValueSchema(f, writes, Expr9).optional();
|
|
5718
|
-
}
|
|
5719
|
-
return z18.strictObject(shape).describe(`Fields to set on ${type.name} (field \u2192 value).`);
|
|
5720
|
-
}
|
|
5721
|
-
function pickByNames(available, sel) {
|
|
5722
|
-
if (sel === "none") return [];
|
|
5723
|
-
if (sel === "all") return [...available];
|
|
5724
|
-
const names = new Set(sel);
|
|
5725
|
-
return available.filter((f) => names.has(f.name));
|
|
5726
|
-
}
|
|
5727
|
-
function selectFunctions(registry, selector = "all") {
|
|
5728
|
-
const all = registry.functionList();
|
|
5729
|
-
const byShape = (shape) => all.filter((f) => f.shape === shape);
|
|
5730
|
-
if (selector === "all" || selector === "none") {
|
|
5731
|
-
const sel = selector;
|
|
5732
|
-
return {
|
|
5733
|
-
scalar: pickByNames(byShape("scalar"), sel),
|
|
5734
|
-
tabular: pickByNames(byShape("tabular"), sel),
|
|
5735
|
-
window: pickByNames(byShape("window"), sel),
|
|
5736
|
-
aggregate: pickByNames(byShape("aggregate"), sel)
|
|
5737
|
-
};
|
|
5738
|
-
}
|
|
5739
|
-
if (Array.isArray(selector)) {
|
|
5740
|
-
const names = new Set(selector);
|
|
5741
|
-
const keep = (shape) => byShape(shape).filter((f) => names.has(f.name));
|
|
5742
|
-
return { scalar: keep("scalar"), tabular: keep("tabular"), window: keep("window"), aggregate: keep("aggregate") };
|
|
5743
|
-
}
|
|
5744
|
-
return {
|
|
5745
|
-
scalar: pickByNames(byShape("scalar"), selector.scalar ?? "all"),
|
|
5746
|
-
tabular: pickByNames(byShape("tabular"), selector.tabular ?? "all"),
|
|
5747
|
-
window: pickByNames(byShape("window"), selector.window ?? "all"),
|
|
5748
|
-
aggregate: pickByNames(byShape("aggregate"), selector.aggregate ?? "all")
|
|
5749
|
-
};
|
|
5750
|
-
}
|
|
5751
|
-
function functionsForShape(s, shape) {
|
|
5752
|
-
switch (shape) {
|
|
5753
|
-
case "scalar":
|
|
5754
|
-
return s.scalar;
|
|
5755
|
-
case "tabular":
|
|
5756
|
-
return s.tabular;
|
|
5757
|
-
case "window":
|
|
5758
|
-
return s.window;
|
|
5759
|
-
case "aggregate":
|
|
5760
|
-
return s.aggregate;
|
|
5761
|
-
/* v8 ignore next 2 -- unreachable: `shape` exhaustively covers FunctionShape (compile-time guard) */
|
|
5762
|
-
default:
|
|
5763
|
-
return assertNeverShape(shape);
|
|
5764
|
-
}
|
|
5765
|
-
}
|
|
5766
|
-
function shapeForKind(kind) {
|
|
5767
|
-
switch (kind) {
|
|
5768
|
-
case "function-call":
|
|
5769
|
-
return "scalar";
|
|
5770
|
-
case "tabular-function-call":
|
|
5771
|
-
return "tabular";
|
|
5772
|
-
case "aggregate":
|
|
5773
|
-
return "aggregate";
|
|
5774
|
-
case "window":
|
|
5775
|
-
return "window";
|
|
5776
|
-
/* v8 ignore next 2 -- unreachable: `kind` exhaustively covers FnExprKind (compile-time guard) */
|
|
5777
|
-
default:
|
|
5778
|
-
return assertNeverKind(kind);
|
|
5779
|
-
}
|
|
5780
|
-
}
|
|
5781
|
-
function windowOrderSchema(child) {
|
|
5782
|
-
return z18.array(
|
|
5783
|
-
z18.object({
|
|
5784
|
-
expr: child,
|
|
5785
|
-
dir: z18.enum(["asc", "desc"]),
|
|
5786
|
-
nulls: z18.enum(["first", "last"]).optional()
|
|
5787
|
-
})
|
|
5788
|
-
);
|
|
5789
|
-
}
|
|
5790
|
-
function functionObject(kind, functionField, argsField, child) {
|
|
5791
|
-
switch (kind) {
|
|
5792
|
-
case "function-call":
|
|
5793
|
-
return withAid(
|
|
5794
|
-
z18.object({ kind: z18.literal("function-call"), function: functionField, args: argsField }),
|
|
5795
|
-
"Expr_function-call"
|
|
5796
|
-
).describe("A scalar function call with named arguments.");
|
|
5797
|
-
case "tabular-function-call":
|
|
5798
|
-
return withAid(
|
|
5799
|
-
z18.object({ kind: z18.literal("tabular-function-call"), function: functionField, args: argsField }),
|
|
5800
|
-
"Expr_tabular-function-call"
|
|
5801
|
-
).describe("A type-valued function call (produces rows).");
|
|
5802
|
-
case "aggregate":
|
|
5803
|
-
return withAid(
|
|
5804
|
-
z18.object({
|
|
5805
|
-
kind: z18.literal("aggregate"),
|
|
5806
|
-
function: functionField,
|
|
5807
|
-
args: argsField,
|
|
5808
|
-
distinct: z18.boolean().optional()
|
|
5809
|
-
}),
|
|
5810
|
-
"Expr_aggregate"
|
|
5811
|
-
).describe("Aggregate function over named args (count with empty args = count(*)).");
|
|
5812
|
-
case "window":
|
|
5813
|
-
return withAid(
|
|
5814
|
-
z18.object({
|
|
5815
|
-
kind: z18.literal("window"),
|
|
5816
|
-
function: functionField,
|
|
5817
|
-
args: argsField,
|
|
5818
|
-
partitionBy: z18.array(child).optional(),
|
|
5819
|
-
orderBy: windowOrderSchema(child).optional()
|
|
5820
|
-
}),
|
|
5821
|
-
"Expr_window"
|
|
5822
|
-
).describe("Window function over a partition / ordering, with named args.");
|
|
5823
|
-
/* v8 ignore next 2 -- unreachable: `kind` exhaustively covers FnExprKind (compile-time guard) */
|
|
5824
|
-
default:
|
|
5825
|
-
return assertNeverKind(kind);
|
|
5826
|
-
}
|
|
5827
|
-
}
|
|
5828
|
-
function typedArgsSchema(fn2, child, cache) {
|
|
5829
|
-
if (cache) return cache.typedArgs(fn2, child);
|
|
5830
|
-
const shape = {};
|
|
5831
|
-
for (const param4 of fn2.params) {
|
|
5832
|
-
shape[param4.name] = param4.optional ? child.optional() : child;
|
|
5833
|
-
}
|
|
5834
|
-
return z18.strictObject(shape).describe(`Named arguments for \`${fn2.name}\`.`);
|
|
5835
|
-
}
|
|
5836
|
-
function functionExprSchema(kind, openSchema, selected, depth, child, cache) {
|
|
5837
|
-
if (depth === "open" || !selected) return openSchema;
|
|
5838
|
-
const fns = functionsForShape(selected, shapeForKind(kind));
|
|
5839
|
-
if (depth === "names") {
|
|
5840
|
-
const functionField = withAid(enumOf2(fns.map((f) => f.name)), "FunctionName").describe(
|
|
5841
|
-
"A selected function name."
|
|
5842
|
-
);
|
|
5843
|
-
const argsField = withAid(z18.record(z18.string(), child), "FunctionArgs").describe(
|
|
5844
|
-
"Arguments keyed by declared parameter name."
|
|
5845
|
-
);
|
|
5846
|
-
return functionObject(kind, functionField, argsField, child);
|
|
5847
|
-
}
|
|
5848
|
-
const branches = fns.map((fn2) => {
|
|
5849
|
-
const hasRequired = fn2.params.some((p) => !(p.optional ?? false));
|
|
5850
|
-
const argsObj = typedArgsSchema(fn2, child, cache);
|
|
5851
|
-
return functionObject(
|
|
5852
|
-
kind,
|
|
5853
|
-
z18.literal(fn2.name).describe(`The \`${fn2.name}\` function.`),
|
|
5854
|
-
hasRequired ? argsObj : argsObj.optional(),
|
|
5855
|
-
child
|
|
5856
|
-
);
|
|
5857
|
-
});
|
|
5858
|
-
return branches.length > 0 ? orFold(branches) : z18.never();
|
|
5859
|
-
}
|
|
5860
|
-
function exprKindApplicable(kind, types, selected, registry) {
|
|
5861
|
-
switch (kind) {
|
|
5862
|
-
case "operator":
|
|
5863
|
-
return registry.operatorList().some((op) => operatorReachable(op, types));
|
|
5864
|
-
case "semantic":
|
|
5865
|
-
return types.some((t) => t.isSemantic());
|
|
5866
|
-
case "text-search":
|
|
5867
|
-
return types.some((t) => t.isSearchable());
|
|
5868
|
-
case "text-score":
|
|
5869
|
-
return types.some((t) => t.isSearchable());
|
|
5870
|
-
case "array-op":
|
|
5871
|
-
return types.some((t) => t.fields.some((f) => f.allowsExpr("array-op")));
|
|
5872
|
-
case "tabular-function-call":
|
|
5873
|
-
return selected.tabular.length > 0;
|
|
5874
|
-
case "aggregate":
|
|
5875
|
-
return selected.aggregate.length > 0;
|
|
5876
|
-
case "window":
|
|
5877
|
-
return selected.window.length > 0;
|
|
5878
|
-
case "function-call":
|
|
5879
|
-
return selected.scalar.length > 0;
|
|
5880
|
-
case "filters":
|
|
5881
|
-
return types.some((t) => t.fields.length > 0);
|
|
5882
|
-
case "excluded":
|
|
5883
|
-
return false;
|
|
5884
|
-
case "output":
|
|
5885
|
-
return false;
|
|
5886
|
-
case "sorter":
|
|
5887
|
-
return false;
|
|
5888
|
-
default:
|
|
5889
|
-
return true;
|
|
5890
|
-
}
|
|
5891
|
-
}
|
|
5892
|
-
function operatorReachable(operator, types) {
|
|
5893
|
-
return operator.operands.some(
|
|
5894
|
-
(operand) => types.some(
|
|
5895
|
-
(t) => t.fields.some((f) => operand.fieldType === void 0 || operand.fieldType.comparableWith(f.fieldType))
|
|
5896
|
-
)
|
|
5897
|
-
);
|
|
5898
|
-
}
|
|
5899
|
-
function assertNeverShape(value2) {
|
|
5900
|
-
throw new Error(`schema-build: unhandled function shape ${JSON.stringify(value2)}`);
|
|
5901
|
-
}
|
|
5902
|
-
function assertNeverKind(value2) {
|
|
5903
|
-
throw new Error(`schema-build: unhandled function-call kind ${JSON.stringify(value2)}`);
|
|
5904
|
-
}
|
|
5905
|
-
function assertNeverFieldMode(value2) {
|
|
5906
|
-
throw new Error(`schema-build: unhandled ref field mode ${JSON.stringify(value2)}`);
|
|
5907
|
-
}
|
|
5908
|
-
|
|
5909
5436
|
// src/exprs/output-ref.ts
|
|
5910
|
-
import { z as z19 } from "zod";
|
|
5911
5437
|
var OutputRefExpr = class _OutputRefExpr extends Expr {
|
|
5912
5438
|
/** Wrap the referenced output field name. */
|
|
5913
5439
|
constructor(name) {
|
|
@@ -5940,16 +5466,6 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
|
|
|
5940
5466
|
(v) => new _OutputRefExpr(v.name),
|
|
5941
5467
|
{ aid: "Expr_output" }
|
|
5942
5468
|
);
|
|
5943
|
-
/** Zod schema for this expr kind's JSON shape (name is query-local ⇒ a plain string). */
|
|
5944
|
-
static toSchema(_opts) {
|
|
5945
|
-
return withAid(
|
|
5946
|
-
z19.object({
|
|
5947
|
-
kind: z19.literal("output"),
|
|
5948
|
-
name: z19.string().describe("A SELECT output field name (its `as`, or the natural derived name).")
|
|
5949
|
-
}),
|
|
5950
|
-
"Expr_output"
|
|
5951
|
-
).describe("A reference to a SELECT output field by name (valid in groupBy / orderBy / having).");
|
|
5952
|
-
}
|
|
5953
5469
|
/** Resolve to the referenced output field's type (delegates; text fallback when unbound). */
|
|
5954
5470
|
resolve(engine, scope) {
|
|
5955
5471
|
const target = scope.output(this.name);
|
|
@@ -6101,10 +5617,6 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
|
|
|
6101
5617
|
(v) => new _FieldRefExpr(v.source, v.field),
|
|
6102
5618
|
{ aid: "Expr_field-ref" }
|
|
6103
5619
|
);
|
|
6104
|
-
/** Depth-aware Zod schema for this expr kind's JSON shape (per `opts.depth.refs`). */
|
|
6105
|
-
static toSchema(opts) {
|
|
6106
|
-
return fieldRefSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
|
|
6107
|
-
}
|
|
6108
5620
|
/** Resolve to the named field on the bound source, widening nullability by the source's. */
|
|
6109
5621
|
resolve(engine, scope) {
|
|
6110
5622
|
const bound = scope.lookup(this.source);
|
|
@@ -6552,17 +6064,17 @@ function assertNeverJoinSpec(value2) {
|
|
|
6552
6064
|
}
|
|
6553
6065
|
|
|
6554
6066
|
// src/runtime/tri.ts
|
|
6555
|
-
function not3(
|
|
6556
|
-
return
|
|
6067
|
+
function not3(a13) {
|
|
6068
|
+
return a13 === void 0 ? void 0 : !a13;
|
|
6557
6069
|
}
|
|
6558
|
-
function and3(
|
|
6559
|
-
if (
|
|
6560
|
-
if (
|
|
6070
|
+
function and3(a13, b) {
|
|
6071
|
+
if (a13 === false || b === false) return false;
|
|
6072
|
+
if (a13 === void 0 || b === void 0) return void 0;
|
|
6561
6073
|
return true;
|
|
6562
6074
|
}
|
|
6563
|
-
function or3(
|
|
6564
|
-
if (
|
|
6565
|
-
if (
|
|
6075
|
+
function or3(a13, b) {
|
|
6076
|
+
if (a13 === true || b === true) return true;
|
|
6077
|
+
if (a13 === void 0 || b === void 0) return void 0;
|
|
6566
6078
|
return false;
|
|
6567
6079
|
}
|
|
6568
6080
|
function triOf(v) {
|
|
@@ -6613,9 +6125,9 @@ async function tuple(operand, rel, keys, row, ctx, group) {
|
|
|
6613
6125
|
}
|
|
6614
6126
|
return [v];
|
|
6615
6127
|
}
|
|
6616
|
-
function eq3(
|
|
6617
|
-
if (
|
|
6618
|
-
return
|
|
6128
|
+
function eq3(a13, b) {
|
|
6129
|
+
if (a13.isNull() || b.isNull()) return void 0;
|
|
6130
|
+
return a13.compareTo(b) === 0;
|
|
6619
6131
|
}
|
|
6620
6132
|
function cell(rec, name) {
|
|
6621
6133
|
return Value.of(rec[name] ?? null);
|
|
@@ -6814,19 +6326,6 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
6814
6326
|
(v) => new _ComparisonExpr(v.op, v.left, v.right),
|
|
6815
6327
|
{ aid: "Expr_comparison" }
|
|
6816
6328
|
);
|
|
6817
|
-
/** Zod schema for this expr kind's JSON shape (left/right are child Expr slots). */
|
|
6818
|
-
static toSchema(opts) {
|
|
6819
|
-
const child = childExprSchema(opts.Expr);
|
|
6820
|
-
return withAid(
|
|
6821
|
-
z20.object({
|
|
6822
|
-
kind: z20.literal("comparison"),
|
|
6823
|
-
op: withAid(z20.enum(["=", "<>", "<", "<=", ">", ">=", "like", "notLike", "ilike"]), "ComparisonOp"),
|
|
6824
|
-
left: child,
|
|
6825
|
-
right: child
|
|
6826
|
-
}),
|
|
6827
|
-
"Expr_comparison"
|
|
6828
|
-
).describe("Scalar comparison predicate.");
|
|
6829
|
-
}
|
|
6830
6329
|
forEachChild(visit) {
|
|
6831
6330
|
visit(this.left);
|
|
6832
6331
|
visit(this.right);
|
|
@@ -7023,9 +6522,6 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
7023
6522
|
}
|
|
7024
6523
|
};
|
|
7025
6524
|
|
|
7026
|
-
// src/exprs/operator.ts
|
|
7027
|
-
import { z as z22 } from "zod";
|
|
7028
|
-
|
|
7029
6525
|
// src/runtime/functions.ts
|
|
7030
6526
|
var WINDOW_ORDER_ARG = "$order";
|
|
7031
6527
|
function declaredOutput(engine, name) {
|
|
@@ -7068,17 +6564,11 @@ async function runWindowFunction(engine, name, partition, index, ctx) {
|
|
|
7068
6564
|
}
|
|
7069
6565
|
|
|
7070
6566
|
// src/exprs/_function-args.ts
|
|
7071
|
-
import { z as z21 } from "zod";
|
|
7072
6567
|
function parseNamedArgs(json2, registry) {
|
|
7073
6568
|
const out = /* @__PURE__ */ new Map();
|
|
7074
6569
|
for (const [name, def] of Object.entries(json2)) out.set(name, registry.parseExpr(def));
|
|
7075
6570
|
return out;
|
|
7076
6571
|
}
|
|
7077
|
-
function namedArgSchema(child) {
|
|
7078
|
-
return withAid(z21.record(z21.string(), child), "FunctionArgs").describe(
|
|
7079
|
-
"Arguments keyed by declared parameter name."
|
|
7080
|
-
);
|
|
7081
|
-
}
|
|
7082
6572
|
function resolveNamedArgs(args, engine, scope) {
|
|
7083
6573
|
const out = /* @__PURE__ */ new Map();
|
|
7084
6574
|
for (const [name, e2] of args) out.set(name, e2.resolve(engine, scope));
|
|
@@ -7212,63 +6702,8 @@ var OperatorExpr = class _OperatorExpr extends Expr {
|
|
|
7212
6702
|
(v) => new _OperatorExpr(v.op, v.args),
|
|
7213
6703
|
{ aid: "Expr_operator" }
|
|
7214
6704
|
);
|
|
7215
|
-
/**
|
|
7216
|
-
* Zod schema for this expr kind's JSON shape.
|
|
7217
|
-
*
|
|
7218
|
-
* `op` is ENUM-LOCKED to the registered operator names whenever a registry is
|
|
7219
|
-
* supplied and the `functions` depth axis asks for more than `open` — the same
|
|
7220
|
-
* argument that made a refinement's `as` an enum rather than a string: a model
|
|
7221
|
-
* free to write `op: '&&'` into a registry that has no `&&` finds out at
|
|
7222
|
-
* validate, one whole round trip later. The glossary carries each operator's
|
|
7223
|
-
* signature and `instructions` inline, because a bare list of glyphs tells a
|
|
7224
|
-
* model what it may write and not what any of them mean.
|
|
7225
|
-
*
|
|
7226
|
-
* At `typed` depth each operator additionally gets its own STRICT operand
|
|
7227
|
-
* object, so a misspelled operand name is refused by the schema rather than by
|
|
7228
|
-
* validation. The axis is `functions` rather than an axis of its own: an
|
|
7229
|
-
* operator IS a named-argument call, and a caller who asked for loose function
|
|
7230
|
-
* calls did not ask for strict operator ones.
|
|
7231
|
-
*/
|
|
7232
|
-
static toSchema(opts) {
|
|
7233
|
-
const child = childExprSchema(opts.Expr);
|
|
7234
|
-
const registered = opts.registry?.operatorList() ?? [];
|
|
7235
|
-
const depth = opts.depth?.functions ?? "open";
|
|
7236
|
-
const [first, ...rest] = registered.map((o) => o.name);
|
|
7237
|
-
if (depth === "open" || first === void 0) {
|
|
7238
|
-
return withAid(
|
|
7239
|
-
z22.object({
|
|
7240
|
-
kind: z22.literal("operator"),
|
|
7241
|
-
op: z22.string().describe("Registered operator name."),
|
|
7242
|
-
args: namedArgSchema(child)
|
|
7243
|
-
}),
|
|
7244
|
-
"Expr_operator"
|
|
7245
|
-
).describe("A registered operator applied to named operands.");
|
|
7246
|
-
}
|
|
7247
|
-
const glossary = registered.map((o) => `${signatureOf(o)} \u2014 ${o.instructions}`).join(" ");
|
|
7248
|
-
if (depth === "names") {
|
|
7249
|
-
return withAid(
|
|
7250
|
-
z22.object({
|
|
7251
|
-
kind: z22.literal("operator"),
|
|
7252
|
-
op: withAid(z22.enum([first, ...rest]), "OperatorName").describe(`A registered operator. ${glossary}`),
|
|
7253
|
-
args: namedArgSchema(child)
|
|
7254
|
-
}),
|
|
7255
|
-
"Expr_operator"
|
|
7256
|
-
).describe("A registered operator applied to named operands.");
|
|
7257
|
-
}
|
|
7258
|
-
const branches = registered.map(
|
|
7259
|
-
(operator) => withAid(
|
|
7260
|
-
z22.object({
|
|
7261
|
-
kind: z22.literal("operator"),
|
|
7262
|
-
op: z22.literal(operator.name).describe(`${signatureOf(operator)} \u2014 ${operator.instructions}`),
|
|
7263
|
-
args: z22.strictObject(Object.fromEntries(operator.operands.map((o) => [o.name, child]))).describe(`Operands for \`${operator.name}\`.`)
|
|
7264
|
-
}),
|
|
7265
|
-
"Expr_operator"
|
|
7266
|
-
)
|
|
7267
|
-
);
|
|
7268
|
-
return orFold(branches).describe("A registered operator applied to named operands.");
|
|
7269
|
-
}
|
|
7270
6705
|
forEachChild(visit) {
|
|
7271
|
-
for (const
|
|
6706
|
+
for (const a13 of this.args.values()) visit(a13);
|
|
7272
6707
|
}
|
|
7273
6708
|
aggregateHere() {
|
|
7274
6709
|
return false;
|
|
@@ -7425,10 +6860,10 @@ function describeRegistered(engine) {
|
|
|
7425
6860
|
}
|
|
7426
6861
|
|
|
7427
6862
|
// src/registry.ts
|
|
7428
|
-
import { z as
|
|
6863
|
+
import { z as z17 } from "zod";
|
|
7429
6864
|
|
|
7430
6865
|
// src/type.ts
|
|
7431
|
-
import { z as
|
|
6866
|
+
import { z as z14 } from "zod";
|
|
7432
6867
|
|
|
7433
6868
|
// src/field.ts
|
|
7434
6869
|
var Field = class _Field {
|
|
@@ -7846,51 +7281,51 @@ var Type = class _Type {
|
|
|
7846
7281
|
}
|
|
7847
7282
|
/** Zod schema for the `TypeDef` JSON shape. */
|
|
7848
7283
|
static toSchema(opts) {
|
|
7849
|
-
const exprKindSchema =
|
|
7850
|
-
const fieldExprsSchema =
|
|
7851
|
-
|
|
7852
|
-
|
|
7284
|
+
const exprKindSchema = z14.string().describe("An expression kind (e.g. `comparison`, `array-op`).");
|
|
7285
|
+
const fieldExprsSchema = z14.union([
|
|
7286
|
+
z14.object({ not: z14.array(exprKindSchema).describe("Expr kinds to EXCLUDE for this field.") }),
|
|
7287
|
+
z14.object({ only: z14.array(exprKindSchema).describe("The ONLY expr kinds allowed for this field.") })
|
|
7853
7288
|
]).describe("Restrict which expr kinds may target this field (narrows the type's set).");
|
|
7854
|
-
const fieldDefSchema =
|
|
7855
|
-
name:
|
|
7856
|
-
label:
|
|
7857
|
-
description:
|
|
7289
|
+
const fieldDefSchema = z14.object({
|
|
7290
|
+
name: z14.string(),
|
|
7291
|
+
label: z14.string().optional(),
|
|
7292
|
+
description: z14.string().optional(),
|
|
7858
7293
|
// `opts` carries the registry, so a field's type offers the `as`
|
|
7859
7294
|
// refinement vocabulary THIS registry actually has (see `refinement.ts`).
|
|
7860
7295
|
type: fieldTypeDefSchema(opts),
|
|
7861
|
-
bytes:
|
|
7862
|
-
changes:
|
|
7863
|
-
nullable:
|
|
7864
|
-
insertable:
|
|
7865
|
-
updatable:
|
|
7296
|
+
bytes: z14.number().optional().describe("Estimated average stored bytes for this field (overrides the field type default)."),
|
|
7297
|
+
changes: z14.number().optional().describe("Ms between changes to this field (overrides the Type; 0 = always, -1 = never)."),
|
|
7298
|
+
nullable: z14.boolean().optional(),
|
|
7299
|
+
insertable: z14.boolean().optional().describe("Whether the field may be supplied on INSERT (default true)."),
|
|
7300
|
+
updatable: z14.boolean().optional().describe("Whether the field may be assigned on UPDATE (default true)."),
|
|
7866
7301
|
exprs: fieldExprsSchema.optional()
|
|
7867
7302
|
}).meta({ aid: "FieldDef" }).describe("A field (field) definition.");
|
|
7868
|
-
const exprSchema = opts?.Expr ??
|
|
7869
|
-
const indexPartDefSchema =
|
|
7303
|
+
const exprSchema = opts?.Expr ?? z14.object({ kind: z14.string() }).loose();
|
|
7304
|
+
const indexPartDefSchema = z14.object({
|
|
7870
7305
|
expr: exprSchema,
|
|
7871
|
-
count:
|
|
7306
|
+
count: z14.number().describe("Prefix distinct rows up to & including this part; last part 1 \u21D2 unique.")
|
|
7872
7307
|
}).meta({ aid: "IndexPartDef" }).describe("One ordered part of a composite index.");
|
|
7873
|
-
const indexDefSchema =
|
|
7874
|
-
exprs:
|
|
7875
|
-
bytes:
|
|
7308
|
+
const indexDefSchema = z14.object({
|
|
7309
|
+
exprs: z14.array(indexPartDefSchema).describe("Ordered composite-index parts."),
|
|
7310
|
+
bytes: z14.number().optional().describe("Estimated average bytes per index entry (else derived from the parts).")
|
|
7876
7311
|
}).meta({ aid: "IndexDef" }).describe("A composite index definition.");
|
|
7877
|
-
return
|
|
7878
|
-
name:
|
|
7879
|
-
label:
|
|
7880
|
-
description:
|
|
7881
|
-
fields:
|
|
7882
|
-
indexes:
|
|
7883
|
-
identity:
|
|
7312
|
+
return z14.object({
|
|
7313
|
+
name: z14.string(),
|
|
7314
|
+
label: z14.string().optional(),
|
|
7315
|
+
description: z14.string().optional(),
|
|
7316
|
+
fields: z14.array(fieldDefSchema),
|
|
7317
|
+
indexes: z14.array(indexDefSchema).optional(),
|
|
7318
|
+
identity: z14.union([z14.string(), z14.array(z14.string())]).optional().describe(
|
|
7884
7319
|
"The field (or ordered fields) that IDENTIFY a row. Declare it and index order stops deciding identity."
|
|
7885
7320
|
),
|
|
7886
|
-
count:
|
|
7887
|
-
bytes:
|
|
7888
|
-
changes:
|
|
7889
|
-
semantic:
|
|
7890
|
-
search:
|
|
7891
|
-
insertable:
|
|
7892
|
-
updatable:
|
|
7893
|
-
deletable:
|
|
7321
|
+
count: z14.number().describe("Estimated total row count."),
|
|
7322
|
+
bytes: z14.number().optional().describe("Estimated average bytes per row (else derived as the sum of the fields' bytes)."),
|
|
7323
|
+
changes: z14.number().optional().describe("Ms between changes to this Type's data (0 = always changing, -1 = never)."),
|
|
7324
|
+
semantic: z14.boolean().optional().describe("Eligible for semantic similarity across the type."),
|
|
7325
|
+
search: z14.boolean().optional().describe("Eligible for full-text search across the type."),
|
|
7326
|
+
insertable: z14.boolean().optional().describe("Whether rows may be INSERTed (default true)."),
|
|
7327
|
+
updatable: z14.boolean().optional().describe("Whether rows may be UPDATEd (default true)."),
|
|
7328
|
+
deletable: z14.boolean().optional().describe("Whether rows may be DELETEd (default true).")
|
|
7894
7329
|
}).meta({ aid: "TypeDef" }).describe("A type-like Type definition.");
|
|
7895
7330
|
}
|
|
7896
7331
|
/** Serialize to its `TypeDef` JSON shape (omits synthetic fields and false flags). */
|
|
@@ -7946,16 +7381,13 @@ ${fieldList}
|
|
|
7946
7381
|
}
|
|
7947
7382
|
};
|
|
7948
7383
|
|
|
7949
|
-
// src/exprs/index.ts
|
|
7950
|
-
import { z as z39 } from "zod";
|
|
7951
|
-
|
|
7952
7384
|
// src/queries/order.ts
|
|
7953
7385
|
var QueryOrder = class _QueryOrder {
|
|
7954
7386
|
/** Construct an ORDER BY term from its expr, direction, and optional nulls placement. */
|
|
7955
|
-
constructor(expr,
|
|
7387
|
+
constructor(expr, dir2, nulls2) {
|
|
7956
7388
|
this.expr = expr;
|
|
7957
|
-
this.dir =
|
|
7958
|
-
this.nulls =
|
|
7389
|
+
this.dir = dir2;
|
|
7390
|
+
this.nulls = nulls2;
|
|
7959
7391
|
}
|
|
7960
7392
|
expr;
|
|
7961
7393
|
dir;
|
|
@@ -8003,9 +7435,9 @@ var QueryOrder = class _QueryOrder {
|
|
|
8003
7435
|
};
|
|
8004
7436
|
function sortByKeys(entries, terms) {
|
|
8005
7437
|
const decorated = [...entries];
|
|
8006
|
-
decorated.sort((
|
|
7438
|
+
decorated.sort((a13, b) => {
|
|
8007
7439
|
for (let i = 0; i < terms.length; i++) {
|
|
8008
|
-
const cmp2 = compareWithNulls(
|
|
7440
|
+
const cmp2 = compareWithNulls(a13.keys[i], b.keys[i], terms[i]);
|
|
8009
7441
|
if (cmp2 !== 0) return cmp2;
|
|
8010
7442
|
}
|
|
8011
7443
|
return 0;
|
|
@@ -8036,8 +7468,8 @@ async function sortEntries(entries, terms, ctx) {
|
|
|
8036
7468
|
);
|
|
8037
7469
|
return sortByKeys(decorated, expanded);
|
|
8038
7470
|
}
|
|
8039
|
-
function compareWithNulls(
|
|
8040
|
-
const aNull =
|
|
7471
|
+
function compareWithNulls(a13, b, term) {
|
|
7472
|
+
const aNull = a13.isNull();
|
|
8041
7473
|
const bNull = b.isNull();
|
|
8042
7474
|
if (aNull || bNull) {
|
|
8043
7475
|
if (aNull && bNull) return 0;
|
|
@@ -8045,7 +7477,7 @@ function compareWithNulls(a, b, term) {
|
|
|
8045
7477
|
const nullIsA = aNull ? -1 : 1;
|
|
8046
7478
|
return nullsFirst ? nullIsA : -nullIsA;
|
|
8047
7479
|
}
|
|
8048
|
-
const cmp2 =
|
|
7480
|
+
const cmp2 = a13.compareTo(b);
|
|
8049
7481
|
return term.dir === "desc" ? -cmp2 : cmp2;
|
|
8050
7482
|
}
|
|
8051
7483
|
|
|
@@ -8098,10 +7530,6 @@ var SorterExpr = class _SorterExpr extends Expr {
|
|
|
8098
7530
|
(v) => new _SorterExpr(v.sorts, v.defaultSort),
|
|
8099
7531
|
{ optional: ["defaultSort"], aid: "Expr_sorter" }
|
|
8100
7532
|
);
|
|
8101
|
-
/** Zod schema for this expr kind's JSON shape (its `sorts` values are child exprs). */
|
|
8102
|
-
static toSchema(opts) {
|
|
8103
|
-
return sorterSchema(childExprSchema(opts.Expr));
|
|
8104
|
-
}
|
|
8105
7533
|
// ─── Resolution / validation ─────────────────────────────────────────────
|
|
8106
7534
|
/**
|
|
8107
7535
|
* A sorter is never a VALUE, so this is only reached when one is (invalidly)
|
|
@@ -8167,14 +7595,14 @@ var SorterExpr = class _SorterExpr extends Expr {
|
|
|
8167
7595
|
*/
|
|
8168
7596
|
expand(spec) {
|
|
8169
7597
|
const chosen = spec && spec.length > 0 ? spec.map((s) => ({ sort: s.sort, dir: s.dir ?? "asc" })) : this.defaultSort ?? [];
|
|
8170
|
-
return chosen.map(({ sort, dir }) => {
|
|
7598
|
+
return chosen.map(({ sort, dir: dir2 }) => {
|
|
8171
7599
|
const expr = this.sorts.get(sort);
|
|
8172
7600
|
if (!expr) {
|
|
8173
7601
|
throw new Error(
|
|
8174
7602
|
`sort.unknown-name: unknown sort '${sort}'. Declared sorts: ${[...this.sorts.keys()].join(", ")}.`
|
|
8175
7603
|
);
|
|
8176
7604
|
}
|
|
8177
|
-
return new QueryOrder(expr,
|
|
7605
|
+
return new QueryOrder(expr, dir2, void 0);
|
|
8178
7606
|
});
|
|
8179
7607
|
}
|
|
8180
7608
|
// ─── Evaluation / cost / SQL (never reached for a well-placed sorter) ──────
|
|
@@ -8256,7 +7684,6 @@ var SorterExpr = class _SorterExpr extends Expr {
|
|
|
8256
7684
|
};
|
|
8257
7685
|
|
|
8258
7686
|
// src/exprs/binary.ts
|
|
8259
|
-
import { z as z24 } from "zod";
|
|
8260
7687
|
var NUMERIC = /* @__PURE__ */ new Set(["number", "money"]);
|
|
8261
7688
|
var BINARY_OPS = ["+", "-", "*", "/", "%"];
|
|
8262
7689
|
function exempt2(e2) {
|
|
@@ -8303,19 +7730,6 @@ var BinaryExpr = class _BinaryExpr extends Expr {
|
|
|
8303
7730
|
(v) => new _BinaryExpr(v.op, v.left, v.right),
|
|
8304
7731
|
{ aid: "Expr_binary" }
|
|
8305
7732
|
);
|
|
8306
|
-
/** Zod schema for this expr kind's JSON shape (operands use the shared child Expr schema). */
|
|
8307
|
-
static toSchema(opts) {
|
|
8308
|
-
const child = childExprSchema(opts.Expr);
|
|
8309
|
-
return withAid(
|
|
8310
|
-
z24.object({
|
|
8311
|
-
kind: z24.literal("binary"),
|
|
8312
|
-
op: withAid(z24.enum(["+", "-", "*", "/", "%"]), "BinaryOp"),
|
|
8313
|
-
left: child,
|
|
8314
|
-
right: child
|
|
8315
|
-
}),
|
|
8316
|
-
"Expr_binary"
|
|
8317
|
-
).describe("Arithmetic binary operation.");
|
|
8318
|
-
}
|
|
8319
7733
|
forEachChild(visit) {
|
|
8320
7734
|
visit(this.left);
|
|
8321
7735
|
visit(this.right);
|
|
@@ -8430,7 +7844,6 @@ function assertNeverOp2(op) {
|
|
|
8430
7844
|
}
|
|
8431
7845
|
|
|
8432
7846
|
// src/exprs/unary.ts
|
|
8433
|
-
import { z as z25 } from "zod";
|
|
8434
7847
|
var UNARY_OPS = ["-", "+"];
|
|
8435
7848
|
var UnaryExpr = class _UnaryExpr extends Expr {
|
|
8436
7849
|
/** Wrap a unary operation over its operator and operand expr. */
|
|
@@ -8466,17 +7879,6 @@ var UnaryExpr = class _UnaryExpr extends Expr {
|
|
|
8466
7879
|
(v) => new _UnaryExpr(v.op, v.operand),
|
|
8467
7880
|
{ aid: "Expr_unary" }
|
|
8468
7881
|
);
|
|
8469
|
-
/** Zod schema for this expr kind's JSON shape (operand uses the shared child Expr schema). */
|
|
8470
|
-
static toSchema(opts) {
|
|
8471
|
-
return withAid(
|
|
8472
|
-
z25.object({
|
|
8473
|
-
kind: z25.literal("unary"),
|
|
8474
|
-
op: withAid(z25.enum(["-", "+"]), "UnaryOp"),
|
|
8475
|
-
operand: childExprSchema(opts.Expr)
|
|
8476
|
-
}),
|
|
8477
|
-
"Expr_unary"
|
|
8478
|
-
).describe("Unary arithmetic operation.");
|
|
8479
|
-
}
|
|
8480
7882
|
forEachChild(visit) {
|
|
8481
7883
|
visit(this.operand);
|
|
8482
7884
|
}
|
|
@@ -8537,7 +7939,6 @@ var UnaryExpr = class _UnaryExpr extends Expr {
|
|
|
8537
7939
|
};
|
|
8538
7940
|
|
|
8539
7941
|
// src/exprs/logical.ts
|
|
8540
|
-
import { z as z26 } from "zod";
|
|
8541
7942
|
var LOGICAL_OPS = ["and", "or", "not"];
|
|
8542
7943
|
var LogicalExpr = class _LogicalExpr extends BoolExpr {
|
|
8543
7944
|
/** Wrap a boolean connective (`and` / `or` / `not`) over its operands. */
|
|
@@ -8592,17 +7993,6 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
|
|
|
8592
7993
|
(v) => new _LogicalExpr(v.op, v.operands),
|
|
8593
7994
|
{ aid: "Expr_logical" }
|
|
8594
7995
|
);
|
|
8595
|
-
/** Zod schema for this expr kind's JSON shape (operands are child Expr slots). */
|
|
8596
|
-
static toSchema(opts) {
|
|
8597
|
-
return withAid(
|
|
8598
|
-
z26.object({
|
|
8599
|
-
kind: z26.literal("logical"),
|
|
8600
|
-
op: withAid(z26.enum(["and", "or", "not"]), "LogicalOp"),
|
|
8601
|
-
operands: z26.array(childExprSchema(opts.Expr))
|
|
8602
|
-
}),
|
|
8603
|
-
"Expr_logical"
|
|
8604
|
-
).describe("Boolean connective (and / or / not).");
|
|
8605
|
-
}
|
|
8606
7996
|
forEachChild(visit) {
|
|
8607
7997
|
for (const o of this.operands) visit(o);
|
|
8608
7998
|
}
|
|
@@ -8701,9 +8091,6 @@ function assertNeverOp3(op) {
|
|
|
8701
8091
|
throw new Error(`LogicalExpr: unhandled op ${JSON.stringify(op)}`);
|
|
8702
8092
|
}
|
|
8703
8093
|
|
|
8704
|
-
// src/exprs/in.ts
|
|
8705
|
-
import { z as z27 } from "zod";
|
|
8706
|
-
|
|
8707
8094
|
// src/exprs/_subquery.ts
|
|
8708
8095
|
function inferSubqueryOutput(engine, scope, def) {
|
|
8709
8096
|
return engine.parseQuery(def).resolve(engine, scope);
|
|
@@ -8810,7 +8197,7 @@ var InExpr = class _InExpr extends BoolExpr {
|
|
|
8810
8197
|
*/
|
|
8811
8198
|
static SHAPE = {
|
|
8812
8199
|
check(json2, ctx) {
|
|
8813
|
-
if (
|
|
8200
|
+
if (isRecord2(json2) && isRecord2(json2["in"])) {
|
|
8814
8201
|
return _InExpr.SHAPE_SUBQUERY.check(json2, ctx);
|
|
8815
8202
|
}
|
|
8816
8203
|
return _InExpr.SHAPE_LIST.check(json2, ctx);
|
|
@@ -8838,18 +8225,6 @@ var InExpr = class _InExpr extends BoolExpr {
|
|
|
8838
8225
|
(v) => new _InExpr(v.value, void 0, v.in, v.not ?? false),
|
|
8839
8226
|
{ optional: ["not"], aid: "Expr_in" }
|
|
8840
8227
|
);
|
|
8841
|
-
/** Zod schema for this expr kind's JSON shape (`in` is a child Expr list or a child Query slot). */
|
|
8842
|
-
static toSchema(opts) {
|
|
8843
|
-
return withAid(
|
|
8844
|
-
z27.object({
|
|
8845
|
-
kind: z27.literal("in"),
|
|
8846
|
-
value: childExprSchema(opts.Expr),
|
|
8847
|
-
in: z27.union([z27.array(childExprSchema(opts.Expr)), childQuerySchema(opts.Query)]),
|
|
8848
|
-
not: z27.boolean().optional()
|
|
8849
|
-
}),
|
|
8850
|
-
"Expr_in"
|
|
8851
|
-
).describe("Membership predicate (value IN list / subquery).");
|
|
8852
|
-
}
|
|
8853
8228
|
forEachChild(visit) {
|
|
8854
8229
|
visit(this.value);
|
|
8855
8230
|
if (this.list) for (const e2 of this.list) visit(e2);
|
|
@@ -9032,7 +8407,6 @@ var InExpr = class _InExpr extends BoolExpr {
|
|
|
9032
8407
|
};
|
|
9033
8408
|
|
|
9034
8409
|
// src/exprs/between.ts
|
|
9035
|
-
import { z as z28 } from "zod";
|
|
9036
8410
|
var BetweenExpr = class _BetweenExpr extends BoolExpr {
|
|
9037
8411
|
/** Wrap `value [NOT] BETWEEN lower AND upper` as a range predicate. */
|
|
9038
8412
|
constructor(value2, lower3, upper, not2) {
|
|
@@ -9079,20 +8453,6 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
|
|
|
9079
8453
|
(v) => new _BetweenExpr(v.value, v.lower, v.upper, v.not ?? false),
|
|
9080
8454
|
{ optional: ["not"], aid: "Expr_between" }
|
|
9081
8455
|
);
|
|
9082
|
-
/** Zod schema for this expr kind's JSON shape (value/lower/upper are child Expr slots). */
|
|
9083
|
-
static toSchema(opts) {
|
|
9084
|
-
const child = childExprSchema(opts.Expr);
|
|
9085
|
-
return withAid(
|
|
9086
|
-
z28.object({
|
|
9087
|
-
kind: z28.literal("between"),
|
|
9088
|
-
value: child,
|
|
9089
|
-
lower: child,
|
|
9090
|
-
upper: child,
|
|
9091
|
-
not: z28.boolean().optional()
|
|
9092
|
-
}),
|
|
9093
|
-
"Expr_between"
|
|
9094
|
-
).describe("Range predicate (value BETWEEN lower AND upper).");
|
|
9095
|
-
}
|
|
9096
8456
|
forEachChild(visit) {
|
|
9097
8457
|
visit(this.value);
|
|
9098
8458
|
visit(this.lower);
|
|
@@ -9191,7 +8551,6 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
|
|
|
9191
8551
|
};
|
|
9192
8552
|
|
|
9193
8553
|
// src/exprs/is-null.ts
|
|
9194
|
-
import { z as z29 } from "zod";
|
|
9195
8554
|
var IsNullExpr = class _IsNullExpr extends BoolExpr {
|
|
9196
8555
|
/** Wrap `value IS [NOT] NULL` as a null test. */
|
|
9197
8556
|
constructor(value2, not2) {
|
|
@@ -9227,17 +8586,6 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
|
|
|
9227
8586
|
(v) => new _IsNullExpr(v.value, v.not ?? false),
|
|
9228
8587
|
{ optional: ["not"], aid: "Expr_is-null" }
|
|
9229
8588
|
);
|
|
9230
|
-
/** Zod schema for this expr kind's JSON shape (value is a child Expr slot). */
|
|
9231
|
-
static toSchema(opts) {
|
|
9232
|
-
return withAid(
|
|
9233
|
-
z29.object({
|
|
9234
|
-
kind: z29.literal("is-null"),
|
|
9235
|
-
value: childExprSchema(opts.Expr),
|
|
9236
|
-
not: z29.boolean().optional()
|
|
9237
|
-
}),
|
|
9238
|
-
"Expr_is-null"
|
|
9239
|
-
).describe("Null test (value IS [NOT] NULL).");
|
|
9240
|
-
}
|
|
9241
8589
|
forEachChild(visit) {
|
|
9242
8590
|
visit(this.value);
|
|
9243
8591
|
}
|
|
@@ -9299,7 +8647,6 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
|
|
|
9299
8647
|
};
|
|
9300
8648
|
|
|
9301
8649
|
// src/exprs/exists.ts
|
|
9302
|
-
import { z as z30 } from "zod";
|
|
9303
8650
|
var ExistsExpr = class _ExistsExpr extends BoolExpr {
|
|
9304
8651
|
/** Wrap `[NOT] EXISTS (query)` as an existence predicate over a subquery. */
|
|
9305
8652
|
constructor(query, not2) {
|
|
@@ -9396,17 +8743,6 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
|
|
|
9396
8743
|
(v) => new _ExistsExpr(v.query, v.not ?? false),
|
|
9397
8744
|
{ optional: ["not"], aid: "Expr_exists" }
|
|
9398
8745
|
);
|
|
9399
|
-
/** Zod schema for this expr kind's JSON shape (uses a child Query slot for the subquery). */
|
|
9400
|
-
static toSchema(opts) {
|
|
9401
|
-
return withAid(
|
|
9402
|
-
z30.object({
|
|
9403
|
-
kind: z30.literal("exists"),
|
|
9404
|
-
query: childQuerySchema(opts.Query),
|
|
9405
|
-
not: z30.boolean().optional()
|
|
9406
|
-
}),
|
|
9407
|
-
"Expr_exists"
|
|
9408
|
-
).describe("Existence predicate over a subquery.");
|
|
9409
|
-
}
|
|
9410
8746
|
/** Resolve to a non-nullable bool (EXISTS yields a definite boolean). */
|
|
9411
8747
|
resolve(_engine, _scope) {
|
|
9412
8748
|
return boolResult([], false, false);
|
|
@@ -9456,7 +8792,6 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
|
|
|
9456
8792
|
};
|
|
9457
8793
|
|
|
9458
8794
|
// src/exprs/array-op.ts
|
|
9459
|
-
import { z as z31 } from "zod";
|
|
9460
8795
|
var NO_VALUE_OPS = /* @__PURE__ */ new Set(["isEmpty", "notEmpty"]);
|
|
9461
8796
|
var SINGLE_VALUE_OPS = /* @__PURE__ */ new Set(["contains"]);
|
|
9462
8797
|
var LIST_VALUE_OPS = /* @__PURE__ */ new Set(["containsAny", "containsAll"]);
|
|
@@ -9515,30 +8850,6 @@ var ArrayOpExpr = class _ArrayOpExpr extends BoolExpr {
|
|
|
9515
8850
|
(v) => new _ArrayOpExpr(v.op, v.target, v.value ?? []),
|
|
9516
8851
|
{ optional: ["value"], aid: "Expr_array-op" }
|
|
9517
8852
|
);
|
|
9518
|
-
/** Zod schema for this expr kind's JSON shape (target plus a single/list/omitted value child). */
|
|
9519
|
-
static toSchema(opts) {
|
|
9520
|
-
const child = childExprSchema(opts.Expr);
|
|
9521
|
-
return withAid(
|
|
9522
|
-
z31.object({
|
|
9523
|
-
kind: z31.literal("array-op"),
|
|
9524
|
-
op: withAid(z31.enum(["contains", "containsAny", "containsAll", "isEmpty", "notEmpty"]), "ArrayOp").describe(
|
|
9525
|
-
"Array predicate: element membership / overlap / emptiness."
|
|
9526
|
-
),
|
|
9527
|
-
// The target is the recursive `Expr` union (`opts.Expr` is a shared
|
|
9528
|
-
// `z.lazy`). Use it DIRECTLY — never `.describe()` it here. `.describe()`
|
|
9529
|
-
// CLONES the lazy into a fresh, aid-less wrapper whose new identity
|
|
9530
|
-
// defeats BOTH of the converter's recursion cache keys (instance identity
|
|
9531
|
-
// AND the lazy's `aid`), so `toJSONSchema` re-evaluates the getter on every
|
|
9532
|
-
// encounter and recurses until the stack overflows. (The description is
|
|
9533
|
-
// dropped at a recursive `$ref` position anyway, which is why every other
|
|
9534
|
-
// expr class threads `childExprSchema(opts.Expr)` in bare — see #array-op
|
|
9535
|
-
// overflow.) The wrapping object's own `.describe` still documents the kind.
|
|
9536
|
-
target: child,
|
|
9537
|
-
value: z31.union([child, z31.array(child)]).optional().describe("Single element (contains), element list (containsAny/All), or omitted (isEmpty/notEmpty).")
|
|
9538
|
-
}),
|
|
9539
|
-
"Expr_array-op"
|
|
9540
|
-
).describe("Array containment / emptiness predicate.");
|
|
9541
|
-
}
|
|
9542
8853
|
forEachChild(visit) {
|
|
9543
8854
|
visit(this.target);
|
|
9544
8855
|
for (const v of this.values) visit(v);
|
|
@@ -9699,7 +9010,6 @@ function assertNever3(value2) {
|
|
|
9699
9010
|
}
|
|
9700
9011
|
|
|
9701
9012
|
// src/exprs/case.ts
|
|
9702
|
-
import { z as z32 } from "zod";
|
|
9703
9013
|
var BRANCH_SHAPE = obj(
|
|
9704
9014
|
{ when: exprRef(), then: exprRef() },
|
|
9705
9015
|
(v) => ({ when: v.when, then: v.then }),
|
|
@@ -9745,18 +9055,6 @@ var CaseExpr = class _CaseExpr extends Expr {
|
|
|
9745
9055
|
(v) => new _CaseExpr(v.branches, v.else),
|
|
9746
9056
|
{ optional: ["else"], aid: "Expr_case" }
|
|
9747
9057
|
);
|
|
9748
|
-
/** Zod schema for this expr kind's JSON shape (when/then branch slots and an optional else). */
|
|
9749
|
-
static toSchema(opts) {
|
|
9750
|
-
const child = childExprSchema(opts.Expr);
|
|
9751
|
-
return withAid(
|
|
9752
|
-
z32.object({
|
|
9753
|
-
kind: z32.literal("case"),
|
|
9754
|
-
branches: z32.array(z32.object({ when: child, then: child })),
|
|
9755
|
-
else: child.optional()
|
|
9756
|
-
}),
|
|
9757
|
-
"Expr_case"
|
|
9758
|
-
).describe("Conditional CASE expression.");
|
|
9759
|
-
}
|
|
9760
9058
|
forEachChild(visit) {
|
|
9761
9059
|
for (const b of this.branches) {
|
|
9762
9060
|
visit(b.when);
|
|
@@ -9866,7 +9164,6 @@ var CaseExpr = class _CaseExpr extends Expr {
|
|
|
9866
9164
|
};
|
|
9867
9165
|
|
|
9868
9166
|
// src/exprs/aggregate.ts
|
|
9869
|
-
import { z as z33 } from "zod";
|
|
9870
9167
|
var AggregateExpr = class _AggregateExpr extends Expr {
|
|
9871
9168
|
/** Wrap a registered aggregate `fn` with its named `args` and a DISTINCT flag. */
|
|
9872
9169
|
constructor(fn2, args, distinct) {
|
|
@@ -9928,25 +9225,11 @@ var AggregateExpr = class _AggregateExpr extends Expr {
|
|
|
9928
9225
|
(v) => new _AggregateExpr(v.function, v.args, v.distinct ?? false),
|
|
9929
9226
|
{ optional: ["distinct"], aid: "Expr_aggregate" }
|
|
9930
9227
|
);
|
|
9931
|
-
/** Zod schema for this expr kind's JSON shape (named-arg map plus distinct), layered by `functionExprSchema`. */
|
|
9932
|
-
static toSchema(opts) {
|
|
9933
|
-
const child = childExprSchema(opts.Expr);
|
|
9934
|
-
const open = withAid(
|
|
9935
|
-
z33.object({
|
|
9936
|
-
kind: z33.literal("aggregate"),
|
|
9937
|
-
function: z33.string().describe("Registered aggregate function name (count for count(*))."),
|
|
9938
|
-
args: namedArgSchema(child),
|
|
9939
|
-
distinct: z33.boolean().optional()
|
|
9940
|
-
}),
|
|
9941
|
-
"Expr_aggregate"
|
|
9942
|
-
).describe("Aggregate function over named args (count with empty args = count(*)).");
|
|
9943
|
-
return functionExprSchema("aggregate", open, opts.functions, opts.depth?.functions ?? "open", child, opts.cache);
|
|
9944
|
-
}
|
|
9945
9228
|
aggregateHere() {
|
|
9946
9229
|
return true;
|
|
9947
9230
|
}
|
|
9948
9231
|
forEachChild(visit) {
|
|
9949
|
-
for (const
|
|
9232
|
+
for (const a13 of this.args.values()) visit(a13);
|
|
9950
9233
|
}
|
|
9951
9234
|
/**
|
|
9952
9235
|
* The APPLIED-aggregate facts this call stamps onto its resolution: the
|
|
@@ -10059,7 +9342,7 @@ var AggregateExpr = class _AggregateExpr extends Expr {
|
|
|
10059
9342
|
if (this.args.size === 0) {
|
|
10060
9343
|
return SqlText.concat([SqlText.raw(`${this.fn}(`), SqlText.raw("*"), SqlText.raw(")")]);
|
|
10061
9344
|
}
|
|
10062
|
-
const argSql = [...this.args.values()].map((
|
|
9345
|
+
const argSql = [...this.args.values()].map((a13) => a13.toSQL(dialect, ctx.asAggregate(true)));
|
|
10063
9346
|
const override = dialect.emitBuiltinCall(this.fn, argSql);
|
|
10064
9347
|
if (override) return override;
|
|
10065
9348
|
const name = ctx.engine.lookupFunction(this.fn)?.sql ?? this.fn;
|
|
@@ -10128,7 +9411,6 @@ function substituteArgs(template, args) {
|
|
|
10128
9411
|
}
|
|
10129
9412
|
|
|
10130
9413
|
// src/exprs/window.ts
|
|
10131
|
-
import { z as z34 } from "zod";
|
|
10132
9414
|
var ORDER_SHAPE = obj(
|
|
10133
9415
|
{
|
|
10134
9416
|
expr: exprRef(),
|
|
@@ -10209,32 +9491,11 @@ var WindowExpr = class _WindowExpr extends Expr {
|
|
|
10209
9491
|
(v) => new _WindowExpr(v.function, v.args, v.partitionBy ?? [], v.orderBy ?? []),
|
|
10210
9492
|
{ optional: ["partitionBy", "orderBy"], aid: "Expr_window" }
|
|
10211
9493
|
);
|
|
10212
|
-
/** Zod schema for this expr kind's JSON shape (named args plus partitionBy/orderBy slots), layered by `functionExprSchema`. */
|
|
10213
|
-
static toSchema(opts) {
|
|
10214
|
-
const child = childExprSchema(opts.Expr);
|
|
10215
|
-
const open = withAid(
|
|
10216
|
-
z34.object({
|
|
10217
|
-
kind: z34.literal("window"),
|
|
10218
|
-
function: z34.string().describe("Registered window (or aggregate) function name."),
|
|
10219
|
-
args: namedArgSchema(child),
|
|
10220
|
-
partitionBy: z34.array(child).optional(),
|
|
10221
|
-
orderBy: z34.array(
|
|
10222
|
-
z34.object({
|
|
10223
|
-
expr: child,
|
|
10224
|
-
dir: withAid(z34.enum(["asc", "desc"]), "OrderDir"),
|
|
10225
|
-
nulls: withAid(z34.enum(["first", "last"]), "OrderNulls").optional()
|
|
10226
|
-
})
|
|
10227
|
-
).optional()
|
|
10228
|
-
}),
|
|
10229
|
-
"Expr_window"
|
|
10230
|
-
).describe("Window function over a partition / ordering, with named args.");
|
|
10231
|
-
return functionExprSchema("window", open, opts.functions, opts.depth?.functions ?? "open", child, opts.cache);
|
|
10232
|
-
}
|
|
10233
9494
|
windowHere() {
|
|
10234
9495
|
return true;
|
|
10235
9496
|
}
|
|
10236
9497
|
forEachChild(visit) {
|
|
10237
|
-
for (const
|
|
9498
|
+
for (const a13 of this.args.values()) visit(a13);
|
|
10238
9499
|
for (const e2 of this.partitionBy) visit(e2);
|
|
10239
9500
|
for (const o of this.orderBy) visit(o.expr);
|
|
10240
9501
|
}
|
|
@@ -10302,9 +9563,9 @@ var WindowExpr = class _WindowExpr extends Expr {
|
|
|
10302
9563
|
return out;
|
|
10303
9564
|
}
|
|
10304
9565
|
/** Compare two rows by the ORDER BY clause. */
|
|
10305
|
-
compareByOrder(
|
|
9566
|
+
compareByOrder(a13, b) {
|
|
10306
9567
|
for (let i = 0; i < this.orderBy.length; i++) {
|
|
10307
|
-
const cmp2 =
|
|
9568
|
+
const cmp2 = a13[i].compareTo(b[i]);
|
|
10308
9569
|
if (cmp2 !== 0) return this.orderBy[i].dir === "desc" ? -cmp2 : cmp2;
|
|
10309
9570
|
}
|
|
10310
9571
|
return 0;
|
|
@@ -10347,7 +9608,7 @@ var WindowExpr = class _WindowExpr extends Expr {
|
|
|
10347
9608
|
}
|
|
10348
9609
|
/** Emit `fn(args) OVER (PARTITION BY … ORDER BY …)`. */
|
|
10349
9610
|
toSQL(dialect, ctx) {
|
|
10350
|
-
const argSql = [...this.args.values()].map((
|
|
9611
|
+
const argSql = [...this.args.values()].map((a13) => a13.toSQL(dialect, ctx));
|
|
10351
9612
|
const name = ctx.engine.lookupFunction(this.fn)?.sql ?? this.fn;
|
|
10352
9613
|
const call = dialect.emitBuiltinCall(this.fn, argSql) ?? SqlText.concat([SqlText.raw(`${name}(`), SqlText.join(argSql, ", "), SqlText.raw(")")]);
|
|
10353
9614
|
const over = [];
|
|
@@ -10411,7 +9672,6 @@ var WindowExpr = class _WindowExpr extends Expr {
|
|
|
10411
9672
|
};
|
|
10412
9673
|
|
|
10413
9674
|
// src/exprs/function-call.ts
|
|
10414
|
-
import { z as z35 } from "zod";
|
|
10415
9675
|
var FunctionCallExpr = class _FunctionCallExpr extends Expr {
|
|
10416
9676
|
/** Wrap a registered scalar `fn` with its named `args`. */
|
|
10417
9677
|
constructor(fn2, args) {
|
|
@@ -10458,21 +9718,8 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
|
|
|
10458
9718
|
(v) => new _FunctionCallExpr(v.function, v.args),
|
|
10459
9719
|
{ aid: "Expr_function-call" }
|
|
10460
9720
|
);
|
|
10461
|
-
/** Zod schema for this expr kind's JSON shape (named-arg map), layered by `functionExprSchema`. */
|
|
10462
|
-
static toSchema(opts) {
|
|
10463
|
-
const child = childExprSchema(opts.Expr);
|
|
10464
|
-
const open = withAid(
|
|
10465
|
-
z35.object({
|
|
10466
|
-
kind: z35.literal("function-call"),
|
|
10467
|
-
function: z35.string().describe("Registered scalar function name."),
|
|
10468
|
-
args: namedArgSchema(child)
|
|
10469
|
-
}),
|
|
10470
|
-
"Expr_function-call"
|
|
10471
|
-
).describe("A scalar function call with named arguments.");
|
|
10472
|
-
return functionExprSchema("function-call", open, opts.functions, opts.depth?.functions ?? "open", child, opts.cache);
|
|
10473
|
-
}
|
|
10474
9721
|
forEachChild(visit) {
|
|
10475
|
-
for (const
|
|
9722
|
+
for (const a13 of this.args.values()) visit(a13);
|
|
10476
9723
|
}
|
|
10477
9724
|
aggregateHere() {
|
|
10478
9725
|
return false;
|
|
@@ -10551,7 +9798,6 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
|
|
|
10551
9798
|
};
|
|
10552
9799
|
|
|
10553
9800
|
// src/exprs/tabular-function-call.ts
|
|
10554
|
-
import { z as z36 } from "zod";
|
|
10555
9801
|
var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
|
|
10556
9802
|
/** Wrap a registered tabular `fn` with its named `args`. */
|
|
10557
9803
|
constructor(fn2, args) {
|
|
@@ -10587,21 +9833,8 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
|
|
|
10587
9833
|
(v) => new _TabularFunctionCallExpr(v.function, v.args),
|
|
10588
9834
|
{ aid: "Expr_tabular-function-call" }
|
|
10589
9835
|
);
|
|
10590
|
-
/** Zod schema for this expr kind's JSON shape (named-arg map), layered by `functionExprSchema`. */
|
|
10591
|
-
static toSchema(opts) {
|
|
10592
|
-
const child = childExprSchema(opts.Expr);
|
|
10593
|
-
const open = withAid(
|
|
10594
|
-
z36.object({
|
|
10595
|
-
kind: z36.literal("tabular-function-call"),
|
|
10596
|
-
function: z36.string().describe("Registered tabular function name."),
|
|
10597
|
-
args: namedArgSchema(child)
|
|
10598
|
-
}),
|
|
10599
|
-
"Expr_tabular-function-call"
|
|
10600
|
-
).describe("A type-valued function call (produces rows).");
|
|
10601
|
-
return functionExprSchema("tabular-function-call", open, opts.functions, opts.depth?.functions ?? "open", child, opts.cache);
|
|
10602
|
-
}
|
|
10603
9836
|
forEachChild(visit) {
|
|
10604
|
-
for (const
|
|
9837
|
+
for (const a13 of this.args.values()) visit(a13);
|
|
10605
9838
|
}
|
|
10606
9839
|
/** Resolve to the function's declared output Type, or a synthetic field-less type when unavailable. */
|
|
10607
9840
|
resolve(engine, _scope) {
|
|
@@ -10709,14 +9942,14 @@ function parseVectorText(text) {
|
|
|
10709
9942
|
}
|
|
10710
9943
|
|
|
10711
9944
|
// src/exprs/semantic.ts
|
|
10712
|
-
function cosine(
|
|
10713
|
-
const n = Math.min(
|
|
9945
|
+
function cosine(a13, b) {
|
|
9946
|
+
const n = Math.min(a13.length, b.length);
|
|
10714
9947
|
let dot = 0;
|
|
10715
9948
|
let na = 0;
|
|
10716
9949
|
let nb = 0;
|
|
10717
9950
|
for (let i = 0; i < n; i++) {
|
|
10718
|
-
dot +=
|
|
10719
|
-
na +=
|
|
9951
|
+
dot += a13[i] * b[i];
|
|
9952
|
+
na += a13[i] * a13[i];
|
|
10720
9953
|
nb += b[i] * b[i];
|
|
10721
9954
|
}
|
|
10722
9955
|
if (na === 0 || nb === 0) return 0;
|
|
@@ -10771,7 +10004,7 @@ var SEMANTIC_TYPE_FIELD_SHAPE = obj(
|
|
|
10771
10004
|
var semanticQueryShape = {
|
|
10772
10005
|
check(json2, ctx) {
|
|
10773
10006
|
if (typeof json2 === "string") return { kind: "text", text: json2 };
|
|
10774
|
-
if (
|
|
10007
|
+
if (isRecord2(json2)) {
|
|
10775
10008
|
if (json2["kind"] === "param") {
|
|
10776
10009
|
const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
|
|
10777
10010
|
if (built instanceof ParamExpr) return { kind: "param", param: built };
|
|
@@ -10837,10 +10070,6 @@ var SemanticExpr = class _SemanticExpr extends Expr {
|
|
|
10837
10070
|
(v) => new _SemanticExpr(v.source, v.field, v.query),
|
|
10838
10071
|
{ optional: ["field"], aid: "Expr_semantic" }
|
|
10839
10072
|
);
|
|
10840
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
10841
|
-
static toSchema(opts) {
|
|
10842
|
-
return semanticSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
|
|
10843
|
-
}
|
|
10844
10073
|
forEachChild(visit) {
|
|
10845
10074
|
if (this.query.kind === "param") visit(this.query.param);
|
|
10846
10075
|
}
|
|
@@ -11317,10 +10546,6 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
|
|
|
11317
10546
|
(v) => new _TextSearchExpr(v.source, v.field, v.query),
|
|
11318
10547
|
{ optional: ["field"], aid: "Expr_text-search" }
|
|
11319
10548
|
);
|
|
11320
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
11321
|
-
static toSchema(opts) {
|
|
11322
|
-
return textSearchSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
|
|
11323
|
-
}
|
|
11324
10549
|
forEachChild(visit) {
|
|
11325
10550
|
if (this.query.kind === "param") visit(this.query.param);
|
|
11326
10551
|
}
|
|
@@ -11476,10 +10701,6 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
|
|
|
11476
10701
|
(v) => new _TextScoreExpr(v.source, v.field, v.query),
|
|
11477
10702
|
{ optional: ["field"], aid: "Expr_text-score" }
|
|
11478
10703
|
);
|
|
11479
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
11480
|
-
static toSchema(opts) {
|
|
11481
|
-
return textScoreSchema(opts.types ?? [], opts.depth?.refs ?? "open", opts.cache);
|
|
11482
|
-
}
|
|
11483
10704
|
forEachChild(visit) {
|
|
11484
10705
|
if (this.query.kind === "param") visit(this.query.param);
|
|
11485
10706
|
}
|
|
@@ -11638,10 +10859,6 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
|
|
|
11638
10859
|
(v) => new _FiltersExpr(v.source, v.fields),
|
|
11639
10860
|
{ optional: ["fields"], aid: "Expr_filters" }
|
|
11640
10861
|
);
|
|
11641
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
11642
|
-
static toSchema(opts) {
|
|
11643
|
-
return filtersSchema(opts.types ?? [], opts.depth?.filters ?? "open", opts.cache);
|
|
11644
|
-
}
|
|
11645
10862
|
// ─── Resolution / validation ─────────────────────────────────────────────
|
|
11646
10863
|
resolve(_engine, _scope) {
|
|
11647
10864
|
return boolResult([], false, false);
|
|
@@ -11728,7 +10945,6 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
|
|
|
11728
10945
|
};
|
|
11729
10946
|
|
|
11730
10947
|
// src/exprs/subquery.ts
|
|
11731
|
-
import { z as z37 } from "zod";
|
|
11732
10948
|
var SubqueryExpr = class _SubqueryExpr extends Expr {
|
|
11733
10949
|
/** Wrap the inner query def evaluated in value position. */
|
|
11734
10950
|
constructor(query) {
|
|
@@ -11813,16 +11029,6 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
|
|
|
11813
11029
|
(v) => new _SubqueryExpr(v.query),
|
|
11814
11030
|
{ aid: "Expr_subquery" }
|
|
11815
11031
|
);
|
|
11816
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
11817
|
-
static toSchema(opts) {
|
|
11818
|
-
return withAid(
|
|
11819
|
-
z37.object({
|
|
11820
|
-
kind: z37.literal("subquery"),
|
|
11821
|
-
query: childQuerySchema(opts.Query)
|
|
11822
|
-
}),
|
|
11823
|
-
"Expr_subquery"
|
|
11824
|
-
).describe("A subquery used in value position.");
|
|
11825
|
-
}
|
|
11826
11032
|
/** Infer the subquery's output type via the structural seam. */
|
|
11827
11033
|
resolve(engine, scope) {
|
|
11828
11034
|
return inferSubqueryOutput(engine, scope, this.query);
|
|
@@ -11867,7 +11073,6 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
|
|
|
11867
11073
|
};
|
|
11868
11074
|
|
|
11869
11075
|
// src/exprs/excluded.ts
|
|
11870
|
-
import { z as z38 } from "zod";
|
|
11871
11076
|
var EXCLUDED_SOURCE = "excluded";
|
|
11872
11077
|
var ExcludedExpr = class _ExcludedExpr extends Expr {
|
|
11873
11078
|
/** Wrap the proposed-row column name this reference reads. */
|
|
@@ -11901,16 +11106,6 @@ var ExcludedExpr = class _ExcludedExpr extends Expr {
|
|
|
11901
11106
|
(v) => new _ExcludedExpr(v.field),
|
|
11902
11107
|
{ aid: "Expr_excluded" }
|
|
11903
11108
|
);
|
|
11904
|
-
/** Zod schema for this expr kind's JSON shape. */
|
|
11905
|
-
static toSchema(_opts) {
|
|
11906
|
-
return withAid(
|
|
11907
|
-
z38.object({
|
|
11908
|
-
kind: z38.literal("excluded"),
|
|
11909
|
-
field: z38.string().describe("A column of the proposed (excluded) row.")
|
|
11910
|
-
}),
|
|
11911
|
-
"Expr_excluded"
|
|
11912
|
-
).describe("The proposed row inside an INSERT ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
|
|
11913
|
-
}
|
|
11914
11109
|
/** Resolve to the referenced field's type (text fallback when out of scope). */
|
|
11915
11110
|
resolve(_engine, scope) {
|
|
11916
11111
|
const bound = scope.lookup(EXCLUDED_SOURCE);
|
|
@@ -11996,12 +11191,6 @@ var BUILTIN_EXPRS = [
|
|
|
11996
11191
|
SubqueryExpr,
|
|
11997
11192
|
ExcludedExpr
|
|
11998
11193
|
];
|
|
11999
|
-
function exprDefSchema(opts = {}) {
|
|
12000
|
-
const branches = BUILTIN_EXPRS.map((c) => c.toSchema(opts));
|
|
12001
|
-
const first = branches[0];
|
|
12002
|
-
if (!first) return z39.never();
|
|
12003
|
-
return branches.slice(1).reduce((acc, s) => acc.or(s), first).describe("Expression definition (one of the built-in expression kinds).");
|
|
12004
|
-
}
|
|
12005
11194
|
|
|
12006
11195
|
// src/queries/query.ts
|
|
12007
11196
|
function mergeReferences(parts) {
|
|
@@ -12636,7 +11825,7 @@ var RELATION_ON_SHAPE = obj(
|
|
|
12636
11825
|
);
|
|
12637
11826
|
var JOIN_ON_SHAPE = {
|
|
12638
11827
|
check(json2, ctx) {
|
|
12639
|
-
if (
|
|
11828
|
+
if (isRecord2(json2) && json2["kind"] === "relation") {
|
|
12640
11829
|
return RELATION_ON_SHAPE.check(json2, ctx);
|
|
12641
11830
|
}
|
|
12642
11831
|
const src = sourceRef().check(json2, ctx);
|
|
@@ -12917,7 +12106,7 @@ function reportDuplicateSources(p, sources) {
|
|
|
12917
12106
|
|
|
12918
12107
|
// src/queries/_write.ts
|
|
12919
12108
|
function isExprValue(v, registry) {
|
|
12920
|
-
if (!
|
|
12109
|
+
if (!isRecord2(v) || typeof v["kind"] !== "string") return false;
|
|
12921
12110
|
return registry === void 0 || registry.exprClass(v["kind"]) !== void 0;
|
|
12922
12111
|
}
|
|
12923
12112
|
function writeValueToExpr(v, registry) {
|
|
@@ -13005,7 +12194,7 @@ function writeRecordShape(aid) {
|
|
|
13005
12194
|
const value2 = writeValueShape();
|
|
13006
12195
|
return {
|
|
13007
12196
|
check(json2, ctx) {
|
|
13008
|
-
if (!
|
|
12197
|
+
if (!isRecord2(json2)) {
|
|
13009
12198
|
ctx.problems.error("shape.not-object", expected(aid, json2));
|
|
13010
12199
|
return INVALID;
|
|
13011
12200
|
}
|
|
@@ -13024,7 +12213,7 @@ function boundShape() {
|
|
|
13024
12213
|
return {
|
|
13025
12214
|
check(json2, ctx) {
|
|
13026
12215
|
if (typeof json2 === "number") return json2;
|
|
13027
|
-
if (
|
|
12216
|
+
if (isRecord2(json2) && json2["kind"] === "param") {
|
|
13028
12217
|
const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
|
|
13029
12218
|
if (built instanceof ParamExpr) return built.toJSON();
|
|
13030
12219
|
return INVALID;
|
|
@@ -13826,7 +13015,7 @@ async function rowPassesDefaultConditions(active, row, ctx) {
|
|
|
13826
13015
|
// src/queries/select.ts
|
|
13827
13016
|
var orderItemShape = {
|
|
13828
13017
|
check(json2, ctx) {
|
|
13829
|
-
return
|
|
13018
|
+
return isRecord2(json2) && json2["kind"] === "sorter" ? SorterExpr.SHAPE.check(json2, ctx) : QueryOrder.SHAPE.check(json2, ctx);
|
|
13830
13019
|
}
|
|
13831
13020
|
};
|
|
13832
13021
|
function parseOrderItem(def, registry) {
|
|
@@ -15249,7 +14438,7 @@ var InsertQuery = class _InsertQuery extends Query {
|
|
|
15249
14438
|
walkExprs(visit) {
|
|
15250
14439
|
for (const row of this.rows ?? []) for (const e2 of row.values()) e2.walk(visit);
|
|
15251
14440
|
for (const r of this.returning) r.expr.walk(visit);
|
|
15252
|
-
for (const
|
|
14441
|
+
for (const a13 of this.onConflict?.update ?? []) a13.expr.walk(visit);
|
|
15253
14442
|
}
|
|
15254
14443
|
/** The statements this INSERT nests: its clause exprs' plus the source SELECT. */
|
|
15255
14444
|
forEachNestedQuery(ctx, scope, visit) {
|
|
@@ -16551,7 +15740,7 @@ var RECURSIVE_ENTRY_SHAPE = obj(
|
|
|
16551
15740
|
);
|
|
16552
15741
|
var cteEntryShape = {
|
|
16553
15742
|
check(json2, ctx) {
|
|
16554
|
-
if (
|
|
15743
|
+
if (isRecord2(json2) && "base" in json2 && "recursive" in json2) {
|
|
16555
15744
|
return RECURSIVE_ENTRY_SHAPE.check(json2, ctx);
|
|
16556
15745
|
}
|
|
16557
15746
|
return PLAIN_ENTRY_SHAPE.check(json2, ctx);
|
|
@@ -16807,9 +15996,9 @@ var CTEStatementQuery = class _CTEStatementQuery extends Query {
|
|
|
16807
15996
|
*/
|
|
16808
15997
|
emitWith(dialect, ctx) {
|
|
16809
15998
|
const inner = ctx.withScope(this.bind(ctx.engine, ctx.scope));
|
|
16810
|
-
const
|
|
15999
|
+
const named2 = this.ctes.map((cte) => cte.toSQL(dialect, inner));
|
|
16811
16000
|
const finalParts = this.final.emitWith(dialect, inner);
|
|
16812
|
-
return { ctes: [...
|
|
16001
|
+
return { ctes: [...named2, ...finalParts.ctes], body: finalParts.body };
|
|
16813
16002
|
}
|
|
16814
16003
|
/** Serialize back to a `CTEStatementDef`. */
|
|
16815
16004
|
toJSON() {
|
|
@@ -16920,70 +16109,70 @@ var BUILTIN_QUERIES = [
|
|
|
16920
16109
|
];
|
|
16921
16110
|
|
|
16922
16111
|
// src/ddl/writer.ts
|
|
16923
|
-
import { z as
|
|
16112
|
+
import { z as z16 } from "zod";
|
|
16924
16113
|
|
|
16925
16114
|
// src/ddl/table.ts
|
|
16926
|
-
import { z as
|
|
16927
|
-
var ColumnType =
|
|
16928
|
-
|
|
16929
|
-
|
|
16930
|
-
|
|
16931
|
-
kind:
|
|
16932
|
-
precision:
|
|
16933
|
-
scale:
|
|
16115
|
+
import { z as z15 } from "zod";
|
|
16116
|
+
var ColumnType = z15.discriminatedUnion("kind", [
|
|
16117
|
+
z15.object({ kind: z15.literal("text"), maxLength: z15.number().int().positive().optional() }),
|
|
16118
|
+
z15.object({ kind: z15.literal("integer"), big: z15.boolean().optional() }),
|
|
16119
|
+
z15.object({
|
|
16120
|
+
kind: z15.literal("decimal"),
|
|
16121
|
+
precision: z15.number().int().positive().optional(),
|
|
16122
|
+
scale: z15.number().int().nonnegative().optional()
|
|
16934
16123
|
}),
|
|
16935
|
-
|
|
16936
|
-
|
|
16937
|
-
|
|
16938
|
-
|
|
16939
|
-
|
|
16940
|
-
|
|
16941
|
-
|
|
16124
|
+
z15.object({ kind: z15.literal("float") }),
|
|
16125
|
+
z15.object({ kind: z15.literal("bool") }),
|
|
16126
|
+
z15.object({ kind: z15.literal("date") }),
|
|
16127
|
+
z15.object({ kind: z15.literal("timestamp"), timezone: z15.boolean().optional() }),
|
|
16128
|
+
z15.object({ kind: z15.literal("uuid") }),
|
|
16129
|
+
z15.object({ kind: z15.literal("json") }),
|
|
16130
|
+
z15.object({ kind: z15.literal("bytes") }),
|
|
16942
16131
|
/** A native type with no portable equivalent, kept by name so it survives a round trip. */
|
|
16943
|
-
|
|
16132
|
+
z15.object({ kind: z15.literal("other"), native: z15.string().min(1) })
|
|
16944
16133
|
]);
|
|
16945
|
-
var ColumnDefault =
|
|
16946
|
-
|
|
16947
|
-
|
|
16948
|
-
|
|
16134
|
+
var ColumnDefault = z15.discriminatedUnion("kind", [
|
|
16135
|
+
z15.object({ kind: z15.literal("value"), value: z15.union([z15.string(), z15.number(), z15.boolean(), z15.null()]) }),
|
|
16136
|
+
z15.object({ kind: z15.literal("now") }),
|
|
16137
|
+
z15.object({ kind: z15.literal("sql"), sql: z15.string().min(1) })
|
|
16949
16138
|
]);
|
|
16950
|
-
var ColumnSpec =
|
|
16951
|
-
name:
|
|
16139
|
+
var ColumnSpec = z15.object({
|
|
16140
|
+
name: z15.string().min(1),
|
|
16952
16141
|
type: ColumnType,
|
|
16953
|
-
nullable:
|
|
16142
|
+
nullable: z15.boolean(),
|
|
16954
16143
|
default: ColumnDefault.optional(),
|
|
16955
16144
|
/** The database assigns the value (an identity / autoincrement key). */
|
|
16956
|
-
generated:
|
|
16145
|
+
generated: z15.boolean().optional(),
|
|
16957
16146
|
/** The closed set of values the column may hold (a `CHECK (… IN …)` constraint). */
|
|
16958
|
-
values:
|
|
16147
|
+
values: z15.array(z15.union([z15.string(), z15.number()])).min(1).optional(),
|
|
16959
16148
|
/** The name of that check constraint, when read from a database. */
|
|
16960
|
-
checkName:
|
|
16149
|
+
checkName: z15.string().optional(),
|
|
16961
16150
|
/** The name of the default constraint (SQL Server), when read from a database. */
|
|
16962
|
-
defaultName:
|
|
16151
|
+
defaultName: z15.string().optional(),
|
|
16963
16152
|
/** A comment or description, when the database has one. */
|
|
16964
|
-
comment:
|
|
16153
|
+
comment: z15.string().optional()
|
|
16965
16154
|
});
|
|
16966
|
-
var ForeignKeySpec =
|
|
16967
|
-
name:
|
|
16968
|
-
columns:
|
|
16969
|
-
table:
|
|
16970
|
-
references:
|
|
16971
|
-
onDelete:
|
|
16155
|
+
var ForeignKeySpec = z15.object({
|
|
16156
|
+
name: z15.string().optional(),
|
|
16157
|
+
columns: z15.array(z15.string().min(1)).min(1),
|
|
16158
|
+
table: z15.string().min(1),
|
|
16159
|
+
references: z15.array(z15.string().min(1)).min(1),
|
|
16160
|
+
onDelete: z15.enum(["no-action", "cascade", "set-null", "restrict"]).optional()
|
|
16972
16161
|
});
|
|
16973
|
-
var UniqueSpec =
|
|
16974
|
-
var TableSpec =
|
|
16975
|
-
name:
|
|
16162
|
+
var UniqueSpec = z15.object({ name: z15.string().optional(), columns: z15.array(z15.string().min(1)).min(1) });
|
|
16163
|
+
var TableSpec = z15.object({
|
|
16164
|
+
name: z15.string().min(1),
|
|
16976
16165
|
/** The schema (namespace) it lives in, when the database has them (`public`, `dbo`). */
|
|
16977
|
-
schema:
|
|
16978
|
-
columns:
|
|
16979
|
-
primaryKey:
|
|
16980
|
-
primaryKeyName:
|
|
16981
|
-
foreignKeys:
|
|
16982
|
-
unique:
|
|
16983
|
-
comment:
|
|
16166
|
+
schema: z15.string().optional(),
|
|
16167
|
+
columns: z15.array(ColumnSpec).min(1),
|
|
16168
|
+
primaryKey: z15.array(z15.string().min(1)),
|
|
16169
|
+
primaryKeyName: z15.string().optional(),
|
|
16170
|
+
foreignKeys: z15.array(ForeignKeySpec),
|
|
16171
|
+
unique: z15.array(UniqueSpec),
|
|
16172
|
+
comment: z15.string().optional()
|
|
16984
16173
|
});
|
|
16985
|
-
function sameColumnType(
|
|
16986
|
-
return JSON.stringify(normalizeColumnType(
|
|
16174
|
+
function sameColumnType(a13, b) {
|
|
16175
|
+
return JSON.stringify(normalizeColumnType(a13)) === JSON.stringify(normalizeColumnType(b));
|
|
16987
16176
|
}
|
|
16988
16177
|
function normalizeColumnType(t) {
|
|
16989
16178
|
switch (t.kind) {
|
|
@@ -17021,7 +16210,7 @@ function columnTypeWidens(from, to) {
|
|
|
17021
16210
|
}
|
|
17022
16211
|
|
|
17023
16212
|
// src/ddl/writer.ts
|
|
17024
|
-
var DdlAction =
|
|
16213
|
+
var DdlAction = z16.enum([
|
|
17025
16214
|
"create-table",
|
|
17026
16215
|
"drop-table",
|
|
17027
16216
|
"rebuild-table",
|
|
@@ -17031,17 +16220,17 @@ var DdlAction = z41.enum([
|
|
|
17031
16220
|
"add-constraint",
|
|
17032
16221
|
"drop-constraint"
|
|
17033
16222
|
]);
|
|
17034
|
-
var DdlStep =
|
|
16223
|
+
var DdlStep = z16.object({
|
|
17035
16224
|
action: DdlAction,
|
|
17036
|
-
table:
|
|
16225
|
+
table: z16.string(),
|
|
17037
16226
|
/** The column or constraint the step is about, when it is about one. */
|
|
17038
|
-
target:
|
|
16227
|
+
target: z16.string().optional(),
|
|
17039
16228
|
/** The statements to run, in order. */
|
|
17040
|
-
sql:
|
|
16229
|
+
sql: z16.array(z16.string()).min(1),
|
|
17041
16230
|
/** True when the step can lose data: a drop, or a type change that narrows. */
|
|
17042
|
-
irreversible:
|
|
16231
|
+
irreversible: z16.boolean(),
|
|
17043
16232
|
/** One plain sentence saying what the step does. */
|
|
17044
|
-
summary:
|
|
16233
|
+
summary: z16.string()
|
|
17045
16234
|
});
|
|
17046
16235
|
var DdlError = class extends Error {
|
|
17047
16236
|
name = "DdlError";
|
|
@@ -17340,8 +16529,8 @@ function decimalSpelling(word, type) {
|
|
|
17340
16529
|
function splitNative(native) {
|
|
17341
16530
|
const m = /^\s*([^(]+?)\s*(?:\(([^)]*)\))?\s*(\[\])?\s*$/u.exec(native);
|
|
17342
16531
|
const name = (m?.[1] ?? native).trim().toLowerCase().replace(/\s+/g, " ");
|
|
17343
|
-
const raw2 = (m?.[2] ?? "").split(",").map((
|
|
17344
|
-
return { name, args: raw2.map(Number).filter((n) => Number.isFinite(n)), max: raw2.some((
|
|
16532
|
+
const raw2 = (m?.[2] ?? "").split(",").map((a13) => a13.trim()).filter((a13) => a13 !== "");
|
|
16533
|
+
return { name, args: raw2.map(Number).filter((n) => Number.isFinite(n)), max: raw2.some((a13) => a13.toLowerCase() === "max") };
|
|
17345
16534
|
}
|
|
17346
16535
|
function readCommonType(native) {
|
|
17347
16536
|
const { name, args } = splitNative(native);
|
|
@@ -17475,11 +16664,11 @@ var Dialect = class {
|
|
|
17475
16664
|
* One `ORDER BY` term: `<key> ASC|DESC [NULLS FIRST|LAST]`. A dialect with no
|
|
17476
16665
|
* `NULLS` clause (SQL Server) overrides to order by a null flag first.
|
|
17477
16666
|
*/
|
|
17478
|
-
orderTerm(key,
|
|
16667
|
+
orderTerm(key, dir2, nulls2) {
|
|
17479
16668
|
return SqlText.concat([
|
|
17480
16669
|
key,
|
|
17481
|
-
SqlText.raw(` ${
|
|
17482
|
-
|
|
16670
|
+
SqlText.raw(` ${dir2.toUpperCase()}`),
|
|
16671
|
+
nulls2 ? SqlText.raw(` NULLS ${nulls2.toUpperCase()}`) : SqlText.empty()
|
|
17483
16672
|
]);
|
|
17484
16673
|
}
|
|
17485
16674
|
/** A predicate that is always true (`TRUE`; SQL Server has no boolean literal). */
|
|
@@ -18055,7 +17244,7 @@ var SqliteDdl = class extends SqlDdl {
|
|
|
18055
17244
|
planAlter(current, wanted, diff) {
|
|
18056
17245
|
const keyed = /* @__PURE__ */ new Set([...wanted.primaryKey, ...current.primaryKey, ...wanted.unique.flatMap((u) => u.columns), ...current.unique.flatMap((u) => u.columns)]);
|
|
18057
17246
|
const fkColumns = new Set([...current.foreignKeys, ...wanted.foreignKeys].flatMap((f) => f.columns));
|
|
18058
|
-
const constraintsSame = !diff.primaryKey && diff.changed.length === 0 && diff.foreignKeysDropped.length === 0 && diff.uniqueAdded.length === 0 && diff.uniqueDropped.length === 0 && diff.foreignKeysAdded.every((f) => f.columns.every((col) => diff.added.some((
|
|
17247
|
+
const constraintsSame = !diff.primaryKey && diff.changed.length === 0 && diff.foreignKeysDropped.length === 0 && diff.uniqueAdded.length === 0 && diff.uniqueDropped.length === 0 && diff.foreignKeysAdded.every((f) => f.columns.every((col) => diff.added.some((a13) => a13.name === col)) && f.columns.length === 1);
|
|
18059
17248
|
const plainAdds = diff.added.every((c) => !keyed.has(c.name) && !c.generated && (c.nullable || c.default !== void 0) && (c.default?.kind ?? "value") !== "now");
|
|
18060
17249
|
const plainDrops = diff.dropped.every((c) => !keyed.has(c.name) && !fkColumns.has(c.name) && !c.values);
|
|
18061
17250
|
if (constraintsSame && plainAdds && plainDrops) {
|
|
@@ -18154,8 +17343,8 @@ var PostgresDialect = class extends BaseDialect {
|
|
|
18154
17343
|
);
|
|
18155
17344
|
}
|
|
18156
17345
|
/** Cosine similarity over a pgvector embedding field (`<=>` = distance). */
|
|
18157
|
-
similarity(
|
|
18158
|
-
return SqlText.concat([SqlText.raw("(1 - ("),
|
|
17346
|
+
similarity(a13, b) {
|
|
17347
|
+
return SqlText.concat([SqlText.raw("(1 - ("), a13, SqlText.raw(" <=> "), b, SqlText.raw("))")]);
|
|
18159
17348
|
}
|
|
18160
17349
|
/**
|
|
18161
17350
|
* A precomputed-tsvector field matched directly (NOT re-wrapped in
|
|
@@ -18609,10 +17798,10 @@ var SqlServerDialect = class extends BaseDialect {
|
|
|
18609
17798
|
]);
|
|
18610
17799
|
}
|
|
18611
17800
|
/** No `NULLS FIRST|LAST`: order by a null flag first, then the key. */
|
|
18612
|
-
orderTerm(key,
|
|
18613
|
-
const plain2 = SqlText.concat([key, SqlText.raw(` ${
|
|
18614
|
-
if (!
|
|
18615
|
-
const [isNull3, notNull2] =
|
|
17801
|
+
orderTerm(key, dir2, nulls2) {
|
|
17802
|
+
const plain2 = SqlText.concat([key, SqlText.raw(` ${dir2.toUpperCase()}`)]);
|
|
17803
|
+
if (!nulls2) return plain2;
|
|
17804
|
+
const [isNull3, notNull2] = nulls2 === "first" ? ["0", "1"] : ["1", "0"];
|
|
18616
17805
|
return SqlText.concat([SqlText.raw("CASE WHEN "), key, SqlText.raw(` IS NULL THEN ${isNull3} ELSE ${notNull2} END, `), plain2]);
|
|
18617
17806
|
}
|
|
18618
17807
|
trueSql() {
|
|
@@ -18754,9 +17943,9 @@ function numeric(v, fn2) {
|
|
|
18754
17943
|
const r = fn2(n);
|
|
18755
17944
|
return Number.isFinite(r) ? Value.of(r) : Value.null();
|
|
18756
17945
|
}
|
|
18757
|
-
function numeric2(
|
|
18758
|
-
if (
|
|
18759
|
-
const x =
|
|
17946
|
+
function numeric2(a13, b, fn2) {
|
|
17947
|
+
if (a13.isNull() || b.isNull()) return Value.null();
|
|
17948
|
+
const x = a13.toNumber();
|
|
18760
17949
|
const y = b.toNumber();
|
|
18761
17950
|
if (Number.isNaN(x) || Number.isNaN(y)) return Value.null();
|
|
18762
17951
|
const r = fn2(x, y);
|
|
@@ -18768,10 +17957,10 @@ function intArg(args, name, dflt) {
|
|
|
18768
17957
|
const n = v.toNumber();
|
|
18769
17958
|
return Number.isNaN(n) ? dflt : Math.trunc(n);
|
|
18770
17959
|
}
|
|
18771
|
-
function extremum(values,
|
|
17960
|
+
function extremum(values, dir2) {
|
|
18772
17961
|
const present = values.filter((v) => !v.isNull());
|
|
18773
17962
|
if (present.length === 0) return Value.null();
|
|
18774
|
-
return present.reduce((best, v) => v.compareTo(best) *
|
|
17963
|
+
return present.reduce((best, v) => v.compareTo(best) * dir2 > 0 ? v : best);
|
|
18775
17964
|
}
|
|
18776
17965
|
function toDate(v) {
|
|
18777
17966
|
if (v.isNull()) return null;
|
|
@@ -18897,8 +18086,8 @@ function formatDate(d, fmt) {
|
|
|
18897
18086
|
};
|
|
18898
18087
|
return fmt.replace(/YYYY|HH24|HH|MM|DD|MI|SS/g, (t) => map[t]);
|
|
18899
18088
|
}
|
|
18900
|
-
function dateComponent(
|
|
18901
|
-
const d = toDate(arg(
|
|
18089
|
+
function dateComponent(a13, name, fn2) {
|
|
18090
|
+
const d = toDate(arg(a13, name));
|
|
18902
18091
|
return d ? Value.of(fn2(d)) : Value.null();
|
|
18903
18092
|
}
|
|
18904
18093
|
function scalar2(name, instructions, params, output2, run, sql, rawArgs, examples) {
|
|
@@ -18926,35 +18115,35 @@ var SCALARS = [
|
|
|
18926
18115
|
"Concatenate the array elements into one string (NULLs become empty).",
|
|
18927
18116
|
[{ name: "values", type: ARRAY }],
|
|
18928
18117
|
TEXT,
|
|
18929
|
-
(
|
|
18118
|
+
(a13) => Value.of(elements(a13, "values").map((e2) => Value.of(e2).toText()).join(""))
|
|
18930
18119
|
),
|
|
18931
18120
|
scalar2(
|
|
18932
18121
|
"lower",
|
|
18933
18122
|
"Lower-case the text.",
|
|
18934
18123
|
[{ name: "value", type: TEXT }],
|
|
18935
18124
|
TEXT,
|
|
18936
|
-
(
|
|
18125
|
+
(a13) => Value.of(arg(a13, "value").toText().toLowerCase())
|
|
18937
18126
|
),
|
|
18938
18127
|
scalar2(
|
|
18939
18128
|
"upper",
|
|
18940
18129
|
"Upper-case the text.",
|
|
18941
18130
|
[{ name: "value", type: TEXT }],
|
|
18942
18131
|
TEXT,
|
|
18943
|
-
(
|
|
18132
|
+
(a13) => Value.of(arg(a13, "value").toText().toUpperCase())
|
|
18944
18133
|
),
|
|
18945
18134
|
scalar2(
|
|
18946
18135
|
"trim",
|
|
18947
18136
|
"Strip leading and trailing whitespace.",
|
|
18948
18137
|
[{ name: "value", type: TEXT }],
|
|
18949
18138
|
TEXT,
|
|
18950
|
-
(
|
|
18139
|
+
(a13) => Value.of(arg(a13, "value").toText().trim())
|
|
18951
18140
|
),
|
|
18952
18141
|
scalar2(
|
|
18953
18142
|
"length",
|
|
18954
18143
|
"Character length of the text.",
|
|
18955
18144
|
[{ name: "value", type: TEXT }],
|
|
18956
18145
|
WHOLE,
|
|
18957
|
-
(
|
|
18146
|
+
(a13) => Value.of(arg(a13, "value").toText().length)
|
|
18958
18147
|
),
|
|
18959
18148
|
scalar2(
|
|
18960
18149
|
"substring",
|
|
@@ -18965,10 +18154,10 @@ var SCALARS = [
|
|
|
18965
18154
|
{ name: "length", type: NUMBER, optional: true }
|
|
18966
18155
|
],
|
|
18967
18156
|
TEXT,
|
|
18968
|
-
(
|
|
18969
|
-
const str2 = arg(
|
|
18970
|
-
const start = arg(
|
|
18971
|
-
const len =
|
|
18157
|
+
(a13) => {
|
|
18158
|
+
const str2 = arg(a13, "value").toText();
|
|
18159
|
+
const start = arg(a13, "start").toNumber();
|
|
18160
|
+
const len = a13["length"] ? a13["length"].toNumber() : void 0;
|
|
18972
18161
|
return Value.of(len !== void 0 ? str2.substring(start, start + len) : str2.substring(start));
|
|
18973
18162
|
}
|
|
18974
18163
|
),
|
|
@@ -18981,18 +18170,18 @@ var SCALARS = [
|
|
|
18981
18170
|
{ name: "replacement", type: TEXT }
|
|
18982
18171
|
],
|
|
18983
18172
|
TEXT,
|
|
18984
|
-
(
|
|
18985
|
-
arg(
|
|
18173
|
+
(a13) => Value.of(
|
|
18174
|
+
arg(a13, "value").toText().split(arg(a13, "search").toText()).join(arg(a13, "replacement").toText())
|
|
18986
18175
|
),
|
|
18987
18176
|
void 0,
|
|
18988
18177
|
void 0,
|
|
18989
18178
|
[callExample("replace", { value: ref("event", "code"), search: litExpr("-"), replacement: litExpr("") })]
|
|
18990
18179
|
),
|
|
18991
|
-
scalar2("abs", "Absolute value.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18992
|
-
scalar2("ceil", "Round up to the next whole number.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18993
|
-
scalar2("floor", "Round down to the previous whole number.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18994
|
-
scalar2("round", "Round to the nearest whole number.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18995
|
-
scalar2("sqrt", "Square root (NULL for negatives).", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18180
|
+
scalar2("abs", "Absolute value.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.abs)),
|
|
18181
|
+
scalar2("ceil", "Round up to the next whole number.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.ceil)),
|
|
18182
|
+
scalar2("floor", "Round down to the previous whole number.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.floor)),
|
|
18183
|
+
scalar2("round", "Round to the nearest whole number.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.round)),
|
|
18184
|
+
scalar2("sqrt", "Square root (NULL for negatives).", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.sqrt)),
|
|
18996
18185
|
scalar2(
|
|
18997
18186
|
"power",
|
|
18998
18187
|
"`base` raised to `exponent`.",
|
|
@@ -19001,15 +18190,15 @@ var SCALARS = [
|
|
|
19001
18190
|
{ name: "exponent", type: NUMBER }
|
|
19002
18191
|
],
|
|
19003
18192
|
NUMBER,
|
|
19004
|
-
(
|
|
19005
|
-
const base = arg(
|
|
19006
|
-
const exp = arg(
|
|
18193
|
+
(a13) => {
|
|
18194
|
+
const base = arg(a13, "base").toNumber();
|
|
18195
|
+
const exp = arg(a13, "exponent").toNumber();
|
|
19007
18196
|
if (Number.isNaN(base) || Number.isNaN(exp)) return Value.null();
|
|
19008
18197
|
return Value.of(Math.pow(base, exp));
|
|
19009
18198
|
}
|
|
19010
18199
|
),
|
|
19011
|
-
scalar2("coalesce", "First non-null element of the array.", [{ name: "values", type: ARRAY }], "inferred", (
|
|
19012
|
-
for (const e2 of elements(
|
|
18200
|
+
scalar2("coalesce", "First non-null element of the array.", [{ name: "values", type: ARRAY }], "inferred", (a13) => {
|
|
18201
|
+
for (const e2 of elements(a13, "values")) {
|
|
19013
18202
|
if (e2 !== null) return Value.of(e2);
|
|
19014
18203
|
}
|
|
19015
18204
|
return Value.null();
|
|
@@ -19022,41 +18211,41 @@ var SCALARS = [
|
|
|
19022
18211
|
{ name: "other", type: ANY }
|
|
19023
18212
|
],
|
|
19024
18213
|
"inferred",
|
|
19025
|
-
(
|
|
18214
|
+
(a13) => arg(a13, "value").equals(arg(a13, "other")) ? Value.null() : arg(a13, "value")
|
|
19026
18215
|
),
|
|
19027
18216
|
scalar2(
|
|
19028
18217
|
"greatest",
|
|
19029
18218
|
"Largest non-null element of the array.",
|
|
19030
18219
|
[{ name: "values", type: ARRAY }],
|
|
19031
18220
|
"inferred",
|
|
19032
|
-
(
|
|
18221
|
+
(a13) => extremum(elements(a13, "values").map((e2) => Value.of(e2)), 1)
|
|
19033
18222
|
),
|
|
19034
18223
|
scalar2(
|
|
19035
18224
|
"least",
|
|
19036
18225
|
"Smallest non-null element of the array.",
|
|
19037
18226
|
[{ name: "values", type: ARRAY }],
|
|
19038
18227
|
"inferred",
|
|
19039
|
-
(
|
|
18228
|
+
(a13) => extremum(elements(a13, "values").map((e2) => Value.of(e2)), -1)
|
|
19040
18229
|
),
|
|
19041
18230
|
scalar2(
|
|
19042
18231
|
"arrayLength",
|
|
19043
18232
|
"Number of elements in the array.",
|
|
19044
18233
|
[{ name: "arr", type: ARRAY }],
|
|
19045
18234
|
WHOLE,
|
|
19046
|
-
(
|
|
18235
|
+
(a13) => Value.of(elements(a13, "arr").length)
|
|
19047
18236
|
),
|
|
19048
18237
|
// ─── Group 2c: common scalars (string) ─────────────────────────────────────
|
|
19049
18238
|
// Most emit the portable `name(args)` form; a `sql` override supplies the
|
|
19050
18239
|
// postgres/common function name where it differs from the camelCase name.
|
|
19051
|
-
scalar2("trimLeft", "Strip leading whitespace.", [{ name: "value", type: TEXT }], TEXT, (
|
|
19052
|
-
scalar2("trimRight", "Strip trailing whitespace.", [{ name: "value", type: TEXT }], TEXT, (
|
|
18240
|
+
scalar2("trimLeft", "Strip leading whitespace.", [{ name: "value", type: TEXT }], TEXT, (a13) => Value.of(arg(a13, "value").toText().trimStart()), "ltrim"),
|
|
18241
|
+
scalar2("trimRight", "Strip trailing whitespace.", [{ name: "value", type: TEXT }], TEXT, (a13) => Value.of(arg(a13, "value").toText().trimEnd()), "rtrim"),
|
|
19053
18242
|
scalar2(
|
|
19054
18243
|
"left",
|
|
19055
18244
|
"First `count` characters (negative drops the last |count|).",
|
|
19056
18245
|
[{ name: "value", type: TEXT }, { name: "count", type: NUMBER }],
|
|
19057
18246
|
TEXT,
|
|
19058
18247
|
// `left(s, n)`: first n chars; a negative n drops the last |n| (pg semantics).
|
|
19059
|
-
(
|
|
18248
|
+
(a13) => Value.of(arg(a13, "value").toText().slice(0, intArg(a13, "count", 0)))
|
|
19060
18249
|
),
|
|
19061
18250
|
scalar2(
|
|
19062
18251
|
"right",
|
|
@@ -19064,9 +18253,9 @@ var SCALARS = [
|
|
|
19064
18253
|
[{ name: "value", type: TEXT }, { name: "count", type: NUMBER }],
|
|
19065
18254
|
TEXT,
|
|
19066
18255
|
// `right(s, n)`: last n chars; n = 0 → '' ; a negative n drops the first |n|.
|
|
19067
|
-
(
|
|
19068
|
-
const s = arg(
|
|
19069
|
-
const n = intArg(
|
|
18256
|
+
(a13) => {
|
|
18257
|
+
const s = arg(a13, "value").toText();
|
|
18258
|
+
const n = intArg(a13, "count", 0);
|
|
19070
18259
|
return Value.of(n === 0 ? "" : s.slice(-n));
|
|
19071
18260
|
}
|
|
19072
18261
|
),
|
|
@@ -19080,10 +18269,10 @@ var SCALARS = [
|
|
|
19080
18269
|
],
|
|
19081
18270
|
TEXT,
|
|
19082
18271
|
// `lpad`: truncate to `length` when shorter, else left-pad with `fill` (space).
|
|
19083
|
-
(
|
|
19084
|
-
const s = arg(
|
|
19085
|
-
const len = intArg(
|
|
19086
|
-
const fill =
|
|
18272
|
+
(a13) => {
|
|
18273
|
+
const s = arg(a13, "value").toText();
|
|
18274
|
+
const len = intArg(a13, "length", 0);
|
|
18275
|
+
const fill = a13["fill"] ? arg(a13, "fill").toText() : " ";
|
|
19087
18276
|
return Value.of(len < s.length ? s.slice(0, Math.max(len, 0)) : s.padStart(len, fill));
|
|
19088
18277
|
},
|
|
19089
18278
|
"lpad"
|
|
@@ -19098,10 +18287,10 @@ var SCALARS = [
|
|
|
19098
18287
|
],
|
|
19099
18288
|
TEXT,
|
|
19100
18289
|
// `rpad`: truncate to `length` when shorter, else right-pad with `fill` (space).
|
|
19101
|
-
(
|
|
19102
|
-
const s = arg(
|
|
19103
|
-
const len = intArg(
|
|
19104
|
-
const fill =
|
|
18290
|
+
(a13) => {
|
|
18291
|
+
const s = arg(a13, "value").toText();
|
|
18292
|
+
const len = intArg(a13, "length", 0);
|
|
18293
|
+
const fill = a13["fill"] ? arg(a13, "fill").toText() : " ";
|
|
19105
18294
|
return Value.of(len < s.length ? s.slice(0, Math.max(len, 0)) : s.padEnd(len, fill));
|
|
19106
18295
|
},
|
|
19107
18296
|
"rpad"
|
|
@@ -19111,14 +18300,14 @@ var SCALARS = [
|
|
|
19111
18300
|
"Repeat the text `count` times.",
|
|
19112
18301
|
[{ name: "value", type: TEXT }, { name: "count", type: NUMBER }],
|
|
19113
18302
|
TEXT,
|
|
19114
|
-
(
|
|
18303
|
+
(a13) => Value.of(arg(a13, "value").toText().repeat(Math.max(0, intArg(a13, "count", 0))))
|
|
19115
18304
|
),
|
|
19116
18305
|
scalar2(
|
|
19117
18306
|
"reverse",
|
|
19118
18307
|
"Reverse the characters.",
|
|
19119
18308
|
[{ name: "value", type: TEXT }],
|
|
19120
18309
|
TEXT,
|
|
19121
|
-
(
|
|
18310
|
+
(a13) => Value.of([...arg(a13, "value").toText()].reverse().join(""))
|
|
19122
18311
|
),
|
|
19123
18312
|
scalar2(
|
|
19124
18313
|
"indexOf",
|
|
@@ -19126,7 +18315,7 @@ var SCALARS = [
|
|
|
19126
18315
|
[{ name: "value", type: TEXT }, { name: "search", type: TEXT }],
|
|
19127
18316
|
// 1-based position of `search` in `value`, 0 when absent (pg `strpos`).
|
|
19128
18317
|
WHOLE,
|
|
19129
|
-
(
|
|
18318
|
+
(a13) => Value.of(arg(a13, "value").toText().indexOf(arg(a13, "search").toText()) + 1),
|
|
19130
18319
|
"strpos"
|
|
19131
18320
|
),
|
|
19132
18321
|
scalar2(
|
|
@@ -19134,7 +18323,7 @@ var SCALARS = [
|
|
|
19134
18323
|
"True if the text begins with `search`.",
|
|
19135
18324
|
[{ name: "value", type: TEXT }, { name: "search", type: TEXT }],
|
|
19136
18325
|
BOOL,
|
|
19137
|
-
(
|
|
18326
|
+
(a13) => Value.of(arg(a13, "value").toText().startsWith(arg(a13, "search").toText())),
|
|
19138
18327
|
// pg `starts_with(value, search)`; base uses the same builtin name.
|
|
19139
18328
|
"starts_with"
|
|
19140
18329
|
),
|
|
@@ -19148,9 +18337,9 @@ var SCALARS = [
|
|
|
19148
18337
|
],
|
|
19149
18338
|
TEXT,
|
|
19150
18339
|
// `split_part(s, delim, n)`: the 1-based n-th field, '' when out of range.
|
|
19151
|
-
(
|
|
19152
|
-
const parts = arg(
|
|
19153
|
-
return Value.of(parts[intArg(
|
|
18340
|
+
(a13) => {
|
|
18341
|
+
const parts = arg(a13, "value").toText().split(arg(a13, "delimiter").toText());
|
|
18342
|
+
return Value.of(parts[intArg(a13, "index", 1) - 1] ?? "");
|
|
19154
18343
|
},
|
|
19155
18344
|
"split_part"
|
|
19156
18345
|
),
|
|
@@ -19161,8 +18350,8 @@ var SCALARS = [
|
|
|
19161
18350
|
TEXT,
|
|
19162
18351
|
// Like `concat`, `values` is ONE array arg (the variadic operands); non-null
|
|
19163
18352
|
// elements are joined by `separator` (pg `concat_ws(sep, …)`).
|
|
19164
|
-
(
|
|
19165
|
-
elements(
|
|
18353
|
+
(a13) => Value.of(
|
|
18354
|
+
elements(a13, "values").filter((e2) => e2 !== null).map((e2) => Value.of(e2).toText()).join(arg(a13, "separator").toText())
|
|
19166
18355
|
),
|
|
19167
18356
|
"concat_ws"
|
|
19168
18357
|
),
|
|
@@ -19172,38 +18361,38 @@ var SCALARS = [
|
|
|
19172
18361
|
"Remainder of `value` divided by `divisor`.",
|
|
19173
18362
|
[{ name: "value", type: NUMBER }, { name: "divisor", type: NUMBER }],
|
|
19174
18363
|
NUMBER,
|
|
19175
|
-
(
|
|
18364
|
+
(a13) => numeric2(arg(a13, "value"), arg(a13, "divisor"), (x, y) => x % y)
|
|
19176
18365
|
),
|
|
19177
|
-
scalar2("sign", "-1, 0, or 1 for the number\u2019s sign.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19178
|
-
scalar2("exp", "e raised to `value`.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19179
|
-
scalar2("ln", "Natural logarithm (NULL for value \u2264 0).", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18366
|
+
scalar2("sign", "-1, 0, or 1 for the number\u2019s sign.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.sign)),
|
|
18367
|
+
scalar2("exp", "e raised to `value`.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.exp)),
|
|
18368
|
+
scalar2("ln", "Natural logarithm (NULL for value \u2264 0).", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.log)),
|
|
19180
18369
|
scalar2(
|
|
19181
18370
|
"log",
|
|
19182
18371
|
"Logarithm of `value` in `base`.",
|
|
19183
18372
|
[{ name: "base", type: NUMBER }, { name: "value", type: NUMBER }],
|
|
19184
18373
|
// `log(base, value)` = log of `value` in `base` (pg `log(b, x)`).
|
|
19185
18374
|
NUMBER,
|
|
19186
|
-
(
|
|
18375
|
+
(a13) => numeric2(arg(a13, "base"), arg(a13, "value"), (b, x) => Math.log(x) / Math.log(b))
|
|
19187
18376
|
),
|
|
19188
18377
|
// base-10 log; pg spells single-arg `log(x)` as base-10, so emit `log`.
|
|
19189
|
-
scalar2("log10", "Base-10 logarithm.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19190
|
-
scalar2("trunc", "Truncate toward zero to a whole number.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18378
|
+
scalar2("log10", "Base-10 logarithm.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.log10), "log"),
|
|
18379
|
+
scalar2("trunc", "Truncate toward zero to a whole number.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.trunc)),
|
|
19191
18380
|
scalar2("pi", "The constant \u03C0.", [], NUMBER, () => Value.of(Math.PI)),
|
|
19192
|
-
scalar2("degrees", "Convert radians to degrees.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19193
|
-
scalar2("radians", "Convert degrees to radians.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18381
|
+
scalar2("degrees", "Convert radians to degrees.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), (n) => n * 180 / Math.PI)),
|
|
18382
|
+
scalar2("radians", "Convert degrees to radians.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), (n) => n * Math.PI / 180)),
|
|
19194
18383
|
withChanges(scalar2("random", "Random number in [0, 1).", [], NUMBER, () => Value.of(Math.random())), 0),
|
|
19195
|
-
scalar2("sin", "Sine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19196
|
-
scalar2("cos", "Cosine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19197
|
-
scalar2("tan", "Tangent (radians).", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19198
|
-
scalar2("asin", "Arc-sine in radians (NULL outside [-1, 1]).", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19199
|
-
scalar2("acos", "Arc-cosine in radians (NULL outside [-1, 1]).", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
19200
|
-
scalar2("atan", "Arc-tangent in radians.", [{ name: "value", type: NUMBER }], NUMBER, (
|
|
18384
|
+
scalar2("sin", "Sine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.sin)),
|
|
18385
|
+
scalar2("cos", "Cosine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.cos)),
|
|
18386
|
+
scalar2("tan", "Tangent (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.tan)),
|
|
18387
|
+
scalar2("asin", "Arc-sine in radians (NULL outside [-1, 1]).", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.asin)),
|
|
18388
|
+
scalar2("acos", "Arc-cosine in radians (NULL outside [-1, 1]).", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.acos)),
|
|
18389
|
+
scalar2("atan", "Arc-tangent in radians.", [{ name: "value", type: NUMBER }], NUMBER, (a13) => numeric(arg(a13, "value"), Math.atan)),
|
|
19201
18390
|
scalar2(
|
|
19202
18391
|
"atan2",
|
|
19203
18392
|
"Angle in radians of the point (x, y).",
|
|
19204
18393
|
[{ name: "y", type: NUMBER }, { name: "x", type: NUMBER }],
|
|
19205
18394
|
NUMBER,
|
|
19206
|
-
(
|
|
18395
|
+
(a13) => numeric2(arg(a13, "y"), arg(a13, "x"), (y, x) => Math.atan2(y, x))
|
|
19207
18396
|
),
|
|
19208
18397
|
// ─── Group 2c: conditional ─────────────────────────────────────────────────
|
|
19209
18398
|
scalar2(
|
|
@@ -19216,7 +18405,7 @@ var SCALARS = [
|
|
|
19216
18405
|
],
|
|
19217
18406
|
"inferred",
|
|
19218
18407
|
// Emitted (both dialects) as `(CASE WHEN condition THEN then ELSE else END)`.
|
|
19219
|
-
(
|
|
18408
|
+
(a13) => arg(a13, "condition").toBoolean() ? arg(a13, "then") : arg(a13, "else")
|
|
19220
18409
|
),
|
|
19221
18410
|
withChanges(scalar2("now", "Current timestamp.", [], { kind: "timestamp" }, () => Value.of((/* @__PURE__ */ new Date()).toISOString())), 0),
|
|
19222
18411
|
withChanges(scalar2("currentDate", "Today\u2019s date.", [], { kind: "date" }, () => {
|
|
@@ -19237,34 +18426,34 @@ var SCALARS = [
|
|
|
19237
18426
|
[{ name: "field", type: TEXT }, { name: "d", type: ANY }],
|
|
19238
18427
|
// Numeric component named by `field` (year/month/day/dow/doy/week/…).
|
|
19239
18428
|
NUMBER,
|
|
19240
|
-
(
|
|
19241
|
-
const d = toDate(arg(
|
|
18429
|
+
(a13) => {
|
|
18430
|
+
const d = toDate(arg(a13, "d"));
|
|
19242
18431
|
if (!d) return Value.null();
|
|
19243
|
-
const n = datePartOf(arg(
|
|
18432
|
+
const n = datePartOf(arg(a13, "field").toText(), d);
|
|
19244
18433
|
return n === null ? Value.null() : Value.of(n);
|
|
19245
18434
|
},
|
|
19246
18435
|
void 0,
|
|
19247
18436
|
[0]
|
|
19248
18437
|
),
|
|
19249
|
-
scalar2("year", "Year component of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
19250
|
-
scalar2("month", "Month component (1-12) of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
19251
|
-
scalar2("day", "Day-of-month (1-31) of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
19252
|
-
scalar2("hour", "Hour (0-23) of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
19253
|
-
scalar2("minute", "Minute (0-59) of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
19254
|
-
scalar2("second", "Second (0-59) of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
18438
|
+
scalar2("year", "Year component of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", (x) => x.getUTCFullYear())),
|
|
18439
|
+
scalar2("month", "Month component (1-12) of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", (x) => x.getUTCMonth() + 1)),
|
|
18440
|
+
scalar2("day", "Day-of-month (1-31) of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", (x) => x.getUTCDate())),
|
|
18441
|
+
scalar2("hour", "Hour (0-23) of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", (x) => x.getUTCHours())),
|
|
18442
|
+
scalar2("minute", "Minute (0-59) of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", (x) => x.getUTCMinutes())),
|
|
18443
|
+
scalar2("second", "Second (0-59) of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", (x) => x.getUTCSeconds())),
|
|
19255
18444
|
// `dayOfWeek` = 0(Sun)..6(Sat) (matches pg `EXTRACT(DOW …)`); `week` = ISO week.
|
|
19256
|
-
scalar2("dayOfWeek", "Day of week of `d` (0=Sun \u2026 6=Sat).", [{ name: "d", type: ANY }], WHOLE, (
|
|
19257
|
-
scalar2("dayOfYear", "1-based day of year of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
19258
|
-
scalar2("week", "ISO week number of `d`.", [{ name: "d", type: ANY }], WHOLE, (
|
|
18445
|
+
scalar2("dayOfWeek", "Day of week of `d` (0=Sun \u2026 6=Sat).", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", (x) => x.getUTCDay())),
|
|
18446
|
+
scalar2("dayOfYear", "1-based day of year of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", dayOfYearOf)),
|
|
18447
|
+
scalar2("week", "ISO week number of `d`.", [{ name: "d", type: ANY }], WHOLE, (a13) => dateComponent(a13, "d", isoWeekOf)),
|
|
19259
18448
|
scalar2(
|
|
19260
18449
|
"dateAdd",
|
|
19261
18450
|
"`d` plus `n` whole units of `field` (year/month/day/\u2026).",
|
|
19262
18451
|
[{ name: "field", type: TEXT }, { name: "n", type: NUMBER }, { name: "d", type: ANY }],
|
|
19263
18452
|
TIMESTAMP,
|
|
19264
|
-
(
|
|
19265
|
-
const d = toDate(arg(
|
|
18453
|
+
(a13) => {
|
|
18454
|
+
const d = toDate(arg(a13, "d"));
|
|
19266
18455
|
if (!d) return Value.null();
|
|
19267
|
-
const r = addToDate(d, arg(
|
|
18456
|
+
const r = addToDate(d, arg(a13, "field").toText(), intArg(a13, "n", 0));
|
|
19268
18457
|
return r ? Value.of(r.toISOString()) : Value.null();
|
|
19269
18458
|
},
|
|
19270
18459
|
void 0,
|
|
@@ -19277,11 +18466,11 @@ var SCALARS = [
|
|
|
19277
18466
|
// The DIFFERENCE of the two extracted `field` components (`part(b) - part(a)`),
|
|
19278
18467
|
// NOT a true calendar span — matches the emitted pg/base SQL semantics.
|
|
19279
18468
|
NUMBER,
|
|
19280
|
-
(
|
|
19281
|
-
const da = toDate(arg(
|
|
19282
|
-
const db = toDate(arg(
|
|
18469
|
+
(a13) => {
|
|
18470
|
+
const da = toDate(arg(a13, "a"));
|
|
18471
|
+
const db = toDate(arg(a13, "b"));
|
|
19283
18472
|
if (!da || !db) return Value.null();
|
|
19284
|
-
const token = arg(
|
|
18473
|
+
const token = arg(a13, "field").toText();
|
|
19285
18474
|
const pa = datePartOf(token, da);
|
|
19286
18475
|
const pb = datePartOf(token, db);
|
|
19287
18476
|
return pa === null || pb === null ? Value.null() : Value.of(pb - pa);
|
|
@@ -19294,10 +18483,10 @@ var SCALARS = [
|
|
|
19294
18483
|
"Truncate `d` DOWN to `field` precision (zeroes lower components) \u2014 e.g. `field:'month'` maps any day to the 1st. `field` is a literal token (year/quarter/month/week/day/hour/minute/second).",
|
|
19295
18484
|
[{ name: "field", type: TEXT }, { name: "d", type: ANY }],
|
|
19296
18485
|
TIMESTAMP,
|
|
19297
|
-
(
|
|
19298
|
-
const d = toDate(arg(
|
|
18486
|
+
(a13) => {
|
|
18487
|
+
const d = toDate(arg(a13, "d"));
|
|
19299
18488
|
if (!d) return Value.null();
|
|
19300
|
-
const r = truncToDate(arg(
|
|
18489
|
+
const r = truncToDate(arg(a13, "field").toText(), d);
|
|
19301
18490
|
return r ? Value.of(r.toISOString()) : Value.null();
|
|
19302
18491
|
},
|
|
19303
18492
|
void 0,
|
|
@@ -19310,8 +18499,8 @@ var SCALARS = [
|
|
|
19310
18499
|
[{ name: "year", type: NUMBER }, { name: "month", type: NUMBER }, { name: "day", type: NUMBER }],
|
|
19311
18500
|
DATE,
|
|
19312
18501
|
// ISO `YYYY-MM-DD` from the numeric parts (zero-padded).
|
|
19313
|
-
(
|
|
19314
|
-
`${String(intArg(
|
|
18502
|
+
(a13) => Value.of(
|
|
18503
|
+
`${String(intArg(a13, "year", 0)).padStart(4, "0")}-${pad2(intArg(a13, "month", 1))}-${pad2(intArg(a13, "day", 1))}`
|
|
19315
18504
|
),
|
|
19316
18505
|
"make_date"
|
|
19317
18506
|
),
|
|
@@ -19321,15 +18510,15 @@ var SCALARS = [
|
|
|
19321
18510
|
[{ name: "d", type: ANY }, { name: "format", type: TEXT }],
|
|
19322
18511
|
TEXT,
|
|
19323
18512
|
// pg `to_char(d, fmt)`; supported tokens: YYYY/MM/DD/HH24/HH/MI/SS.
|
|
19324
|
-
(
|
|
19325
|
-
const d = toDate(arg(
|
|
19326
|
-
return d ? Value.of(formatDate(d, arg(
|
|
18513
|
+
(a13) => {
|
|
18514
|
+
const d = toDate(arg(a13, "d"));
|
|
18515
|
+
return d ? Value.of(formatDate(d, arg(a13, "format").toText())) : Value.null();
|
|
19327
18516
|
},
|
|
19328
18517
|
"to_char"
|
|
19329
18518
|
),
|
|
19330
18519
|
// `epoch` emits `EXTRACT(EPOCH FROM ts)` (both dialects, via the dialect).
|
|
19331
|
-
scalar2("epoch", "Unix seconds since 1970 for `ts`.", [{ name: "ts", type: ANY }], NUMBER, (
|
|
19332
|
-
const d = toDate(arg(
|
|
18520
|
+
scalar2("epoch", "Unix seconds since 1970 for `ts`.", [{ name: "ts", type: ANY }], NUMBER, (a13) => {
|
|
18521
|
+
const d = toDate(arg(a13, "ts"));
|
|
19333
18522
|
return d ? Value.of(Math.floor(d.getTime() / 1e3)) : Value.null();
|
|
19334
18523
|
}),
|
|
19335
18524
|
scalar2(
|
|
@@ -19338,8 +18527,8 @@ var SCALARS = [
|
|
|
19338
18527
|
[{ name: "value", type: NUMBER }],
|
|
19339
18528
|
TIMESTAMP,
|
|
19340
18529
|
// Seconds since the epoch → an ISO timestamp; pg `to_timestamp(n)`.
|
|
19341
|
-
(
|
|
19342
|
-
const v = arg(
|
|
18530
|
+
(a13) => {
|
|
18531
|
+
const v = arg(a13, "value");
|
|
19343
18532
|
if (v.isNull()) return Value.null();
|
|
19344
18533
|
const n = v.toNumber();
|
|
19345
18534
|
return Number.isNaN(n) ? Value.null() : Value.of(new Date(n * 1e3).toISOString());
|
|
@@ -19353,9 +18542,9 @@ var SCALARS = [
|
|
|
19353
18542
|
// Whole-day span `a - b`. pg `age(a, b)` yields a symbolic interval; our
|
|
19354
18543
|
// runtime returns the integer day difference (documented divergence).
|
|
19355
18544
|
WHOLE,
|
|
19356
|
-
(
|
|
19357
|
-
const da = toDate(arg(
|
|
19358
|
-
const db = toDate(arg(
|
|
18545
|
+
(a13) => {
|
|
18546
|
+
const da = toDate(arg(a13, "a"));
|
|
18547
|
+
const db = toDate(arg(a13, "b"));
|
|
19359
18548
|
if (!da || !db) return Value.null();
|
|
19360
18549
|
return Value.of(Math.trunc((da.getTime() - db.getTime()) / 864e5));
|
|
19361
18550
|
},
|
|
@@ -19373,9 +18562,9 @@ var SCALARS = [
|
|
|
19373
18562
|
"True if the array contains the element.",
|
|
19374
18563
|
[{ name: "arr", type: ARRAY }, { name: "value", type: ANY }],
|
|
19375
18564
|
BOOL,
|
|
19376
|
-
(
|
|
19377
|
-
const target = arg(
|
|
19378
|
-
return Value.of(elements(
|
|
18565
|
+
(a13) => {
|
|
18566
|
+
const target = arg(a13, "value");
|
|
18567
|
+
return Value.of(elements(a13, "arr").some((el) => Value.of(el).identical(target)));
|
|
19379
18568
|
}
|
|
19380
18569
|
),
|
|
19381
18570
|
scalar2(
|
|
@@ -19383,21 +18572,21 @@ var SCALARS = [
|
|
|
19383
18572
|
"Array with `value` added at the end.",
|
|
19384
18573
|
[{ name: "arr", type: ARRAY }, { name: "value", type: ANY }],
|
|
19385
18574
|
ARRAY,
|
|
19386
|
-
(
|
|
18575
|
+
(a13) => Value.of([...elements(a13, "arr"), arg(a13, "value").raw])
|
|
19387
18576
|
),
|
|
19388
18577
|
scalar2(
|
|
19389
18578
|
"arrayPrepend",
|
|
19390
18579
|
"Array with `value` added at the front.",
|
|
19391
18580
|
[{ name: "arr", type: ARRAY }, { name: "value", type: ANY }],
|
|
19392
18581
|
ARRAY,
|
|
19393
|
-
(
|
|
18582
|
+
(a13) => Value.of([arg(a13, "value").raw, ...elements(a13, "arr")])
|
|
19394
18583
|
),
|
|
19395
18584
|
scalar2(
|
|
19396
18585
|
"arrayConcat",
|
|
19397
18586
|
"Concatenate arrays `a` and `b`.",
|
|
19398
18587
|
[{ name: "a", type: ARRAY }, { name: "b", type: ARRAY }],
|
|
19399
18588
|
ARRAY,
|
|
19400
|
-
(
|
|
18589
|
+
(a13) => Value.of([...elements(a13, "a"), ...elements(a13, "b")])
|
|
19401
18590
|
),
|
|
19402
18591
|
scalar2(
|
|
19403
18592
|
"arrayIndexOf",
|
|
@@ -19405,9 +18594,9 @@ var SCALARS = [
|
|
|
19405
18594
|
[{ name: "arr", type: ARRAY }, { name: "value", type: ANY }],
|
|
19406
18595
|
// 1-based position of `value`, NULL when absent (pg `array_position`).
|
|
19407
18596
|
WHOLE,
|
|
19408
|
-
(
|
|
19409
|
-
const target = arg(
|
|
19410
|
-
const idx = elements(
|
|
18597
|
+
(a13) => {
|
|
18598
|
+
const target = arg(a13, "value");
|
|
18599
|
+
const idx = elements(a13, "arr").findIndex((el) => Value.of(el).identical(target));
|
|
19411
18600
|
return idx < 0 ? Value.null() : Value.of(idx + 1);
|
|
19412
18601
|
}
|
|
19413
18602
|
),
|
|
@@ -19417,21 +18606,21 @@ var SCALARS = [
|
|
|
19417
18606
|
[{ name: "arr", type: ARRAY }, { name: "lo", type: NUMBER }, { name: "hi", type: NUMBER }],
|
|
19418
18607
|
// 1-based inclusive slice `arr[lo:hi]` (pg array slice semantics).
|
|
19419
18608
|
ARRAY,
|
|
19420
|
-
(
|
|
19421
|
-
const arr = elements(
|
|
19422
|
-
const lo = intArg(
|
|
19423
|
-
const hi = intArg(
|
|
18609
|
+
(a13) => {
|
|
18610
|
+
const arr = elements(a13, "arr");
|
|
18611
|
+
const lo = intArg(a13, "lo", 1);
|
|
18612
|
+
const hi = intArg(a13, "hi", arr.length);
|
|
19424
18613
|
return Value.of(arr.slice(Math.max(0, lo - 1), hi));
|
|
19425
18614
|
}
|
|
19426
18615
|
),
|
|
19427
|
-
scalar2("arrayRemove", "Array with every occurrence of `value` removed.", [{ name: "arr", type: ARRAY }, { name: "value", type: ANY }], ARRAY, (
|
|
19428
|
-
const target = arg(
|
|
19429
|
-
return Value.of(elements(
|
|
18616
|
+
scalar2("arrayRemove", "Array with every occurrence of `value` removed.", [{ name: "arr", type: ARRAY }, { name: "value", type: ANY }], ARRAY, (a13) => {
|
|
18617
|
+
const target = arg(a13, "value");
|
|
18618
|
+
return Value.of(elements(a13, "arr").filter((el) => !Value.of(el).identical(target)));
|
|
19430
18619
|
}),
|
|
19431
|
-
scalar2("arrayDistinct", "Array with duplicate elements removed.", [{ name: "arr", type: ARRAY }], ARRAY, (
|
|
18620
|
+
scalar2("arrayDistinct", "Array with duplicate elements removed.", [{ name: "arr", type: ARRAY }], ARRAY, (a13) => {
|
|
19432
18621
|
const seen = /* @__PURE__ */ new Set();
|
|
19433
18622
|
const out = [];
|
|
19434
|
-
for (const el of elements(
|
|
18623
|
+
for (const el of elements(a13, "arr")) {
|
|
19435
18624
|
const key = JSON.stringify(el);
|
|
19436
18625
|
if (seen.has(key)) continue;
|
|
19437
18626
|
seen.add(key);
|
|
@@ -19445,8 +18634,8 @@ var SCALARS = [
|
|
|
19445
18634
|
[{ name: "arr", type: ARRAY }, { name: "sep", type: TEXT }],
|
|
19446
18635
|
TEXT,
|
|
19447
18636
|
// Non-null elements joined by `sep` (pg `array_to_string` drops NULLs).
|
|
19448
|
-
(
|
|
19449
|
-
elements(
|
|
18637
|
+
(a13) => Value.of(
|
|
18638
|
+
elements(a13, "arr").filter((el) => el !== null).map((el) => Value.of(el).toText()).join(arg(a13, "sep").toText())
|
|
19450
18639
|
)
|
|
19451
18640
|
),
|
|
19452
18641
|
scalar2(
|
|
@@ -19455,7 +18644,7 @@ var SCALARS = [
|
|
|
19455
18644
|
[{ name: "str", type: TEXT }, { name: "sep", type: TEXT }],
|
|
19456
18645
|
ARRAY,
|
|
19457
18646
|
// Split `str` on `sep` (pg `string_to_array`).
|
|
19458
|
-
(
|
|
18647
|
+
(a13) => Value.of(arg(a13, "str").toText().split(arg(a13, "sep").toText()))
|
|
19459
18648
|
)
|
|
19460
18649
|
];
|
|
19461
18650
|
function aggValues(rows) {
|
|
@@ -19522,11 +18711,11 @@ var arrayAggRun = (rows) => {
|
|
|
19522
18711
|
if (rows.length === 0) return Value.null();
|
|
19523
18712
|
return Value.of(rows.map((r) => r["value"] ? r["value"].raw : null));
|
|
19524
18713
|
};
|
|
19525
|
-
function boolAggRun(
|
|
18714
|
+
function boolAggRun(dir2) {
|
|
19526
18715
|
return (rows) => {
|
|
19527
18716
|
const vals = aggValues(rows);
|
|
19528
18717
|
if (vals.length === 0) return Value.null();
|
|
19529
|
-
return Value.of(
|
|
18718
|
+
return Value.of(dir2 === "and" ? vals.every((v) => v.toBoolean()) : vals.some((v) => v.toBoolean()));
|
|
19530
18719
|
};
|
|
19531
18720
|
}
|
|
19532
18721
|
var countIfRun = (rows) => {
|
|
@@ -19610,11 +18799,11 @@ var denseRankRun = (partition, index) => {
|
|
|
19610
18799
|
for (let i = 0; i <= index; i++) distinct.add(orderSig(partition[i] ?? {}));
|
|
19611
18800
|
return Value.of(distinct.size);
|
|
19612
18801
|
};
|
|
19613
|
-
function offsetRun(
|
|
18802
|
+
function offsetRun(dir2) {
|
|
19614
18803
|
return (partition, index) => {
|
|
19615
18804
|
const cur = partition[index] ?? {};
|
|
19616
18805
|
const offset = cur["offset"] ? Math.trunc(cur["offset"].toNumber()) : 1;
|
|
19617
|
-
const target = partition[index +
|
|
18806
|
+
const target = partition[index + dir2 * offset];
|
|
19618
18807
|
const value2 = target?.["value"];
|
|
19619
18808
|
if (value2 && !value2.isNull()) return value2;
|
|
19620
18809
|
return cur["default"] ?? Value.null();
|
|
@@ -19774,6 +18963,19 @@ function validateDefaultConditions(type, conditions) {
|
|
|
19774
18963
|
}
|
|
19775
18964
|
}
|
|
19776
18965
|
var Registry = class {
|
|
18966
|
+
/**
|
|
18967
|
+
* Bumped by every registration (types, field types, refinements, functions,
|
|
18968
|
+
* operators, expr / query classes): what a cached grammar bind is keyed by
|
|
18969
|
+
* (`buildSchemas`), so a registry that changed is never served a stale grammar.
|
|
18970
|
+
*/
|
|
18971
|
+
get version() {
|
|
18972
|
+
return this._version;
|
|
18973
|
+
}
|
|
18974
|
+
_version = 0;
|
|
18975
|
+
/** Record a registration (see `version`). */
|
|
18976
|
+
touch() {
|
|
18977
|
+
this._version++;
|
|
18978
|
+
}
|
|
19777
18979
|
// ─── Wired this phase ───────────────────────────────────────────────────
|
|
19778
18980
|
fieldTypeClasses = /* @__PURE__ */ new Map();
|
|
19779
18981
|
namedTypes = /* @__PURE__ */ new Map();
|
|
@@ -19792,6 +18994,7 @@ var Registry = class {
|
|
|
19792
18994
|
// ─── Field-type registration / dispatch ──────────────────────────────────
|
|
19793
18995
|
/** Register a built-in FieldType class for JSON parse dispatch. */
|
|
19794
18996
|
defineFieldType(cls) {
|
|
18997
|
+
this.touch();
|
|
19795
18998
|
this.fieldTypeClasses.set(cls.NAME, cls);
|
|
19796
18999
|
return this;
|
|
19797
19000
|
}
|
|
@@ -19835,6 +19038,7 @@ var Registry = class {
|
|
|
19835
19038
|
* loudly, rather than silently degrading to the bare base).
|
|
19836
19039
|
*/
|
|
19837
19040
|
registerFieldType(def) {
|
|
19041
|
+
this.touch();
|
|
19838
19042
|
this.refuseLateRegistration("registerFieldType", def.name);
|
|
19839
19043
|
const refinement = FieldTypeRefinement.compile(def, this, (json2) => this.parseFieldTypeUnflagged(json2));
|
|
19840
19044
|
this.fieldTypeRefinements.set(refinement.name, refinement);
|
|
@@ -19907,6 +19111,7 @@ var Registry = class {
|
|
|
19907
19111
|
* as the declaration does.
|
|
19908
19112
|
*/
|
|
19909
19113
|
registerFieldTypeImpl(name, impl) {
|
|
19114
|
+
this.touch();
|
|
19910
19115
|
this.refuseLateRegistration("registerFieldTypeImpl", name);
|
|
19911
19116
|
const refinement = this.fieldTypeRefinements.get(name);
|
|
19912
19117
|
if (!refinement) {
|
|
@@ -19926,7 +19131,7 @@ var Registry = class {
|
|
|
19926
19131
|
message: `\`${name}\` already has an implementation. A second one is refused for the same reason a second DECLARATION is: every column naming it shares one compiled refinement, so the last registration would silently decide what all of them validate against.`
|
|
19927
19132
|
});
|
|
19928
19133
|
}
|
|
19929
|
-
if (impl.value !== void 0 && !(impl.value instanceof
|
|
19134
|
+
if (impl.value !== void 0 && !(impl.value instanceof z17.ZodType)) {
|
|
19930
19135
|
throw new QueryTypeError({
|
|
19931
19136
|
path: ["registerFieldTypeImpl", name, "value"],
|
|
19932
19137
|
code: "field-type.bad-refinement",
|
|
@@ -20086,6 +19291,7 @@ var Registry = class {
|
|
|
20086
19291
|
* Back-compatible: `registerType(type)` (no backing) keeps working.
|
|
20087
19292
|
*/
|
|
20088
19293
|
registerType(type, backing) {
|
|
19294
|
+
this.touch();
|
|
20089
19295
|
if (backing?.defaultConditions) validateDefaultConditions(type, backing.defaultConditions);
|
|
20090
19296
|
this.catalogBuilt = true;
|
|
20091
19297
|
this.namedTypes.set(type.name, type);
|
|
@@ -20176,6 +19382,7 @@ var Registry = class {
|
|
|
20176
19382
|
* replace the checked one.
|
|
20177
19383
|
*/
|
|
20178
19384
|
registerFunction(fn2) {
|
|
19385
|
+
this.touch();
|
|
20179
19386
|
for (const [what, value2] of [["name", fn2.name], ["sql", fn2.sql]]) {
|
|
20180
19387
|
if (value2 !== void 0 && !FUNCTION_NAME_PATTERN.test(value2)) {
|
|
20181
19388
|
throw new Error(
|
|
@@ -20200,6 +19407,7 @@ var Registry = class {
|
|
|
20200
19407
|
* match the run's `shape` (so an aggregate def can't be given a scalar run).
|
|
20201
19408
|
*/
|
|
20202
19409
|
registerFunctionRun(name, run) {
|
|
19410
|
+
this.touch();
|
|
20203
19411
|
const def = this.functions.get(name);
|
|
20204
19412
|
if (def && def.shape !== run.shape) {
|
|
20205
19413
|
throw new Error(
|
|
@@ -20235,6 +19443,7 @@ var Registry = class {
|
|
|
20235
19443
|
* parse through the unflagged road for exactly that reason.
|
|
20236
19444
|
*/
|
|
20237
19445
|
registerOperator(def) {
|
|
19446
|
+
this.touch();
|
|
20238
19447
|
const operator = QueryOperator.compile(def, this, (json2) => this.parseFieldTypeUnflagged(json2));
|
|
20239
19448
|
this.operators.set(operator.name, operator);
|
|
20240
19449
|
return this;
|
|
@@ -20286,6 +19495,7 @@ var Registry = class {
|
|
|
20286
19495
|
// ─── Expr / Query / Dialect registration (later phases) ───────────────────
|
|
20287
19496
|
/** Register an Expr class so `parseExpr` can dispatch JSON by `kind`. */
|
|
20288
19497
|
defineExpr(cls) {
|
|
19498
|
+
this.touch();
|
|
20289
19499
|
this.exprClasses.set(cls.KIND, cls);
|
|
20290
19500
|
return this;
|
|
20291
19501
|
}
|
|
@@ -20299,6 +19509,7 @@ var Registry = class {
|
|
|
20299
19509
|
}
|
|
20300
19510
|
/** Register a Query class (Phase 3). */
|
|
20301
19511
|
defineQuery(cls) {
|
|
19512
|
+
this.touch();
|
|
20302
19513
|
this.queryClasses.set(cls.KIND, cls);
|
|
20303
19514
|
return this;
|
|
20304
19515
|
}
|
|
@@ -20361,7 +19572,7 @@ var Registry = class {
|
|
|
20361
19572
|
*/
|
|
20362
19573
|
parseCheckedExpr(json2, problems) {
|
|
20363
19574
|
if (json2 instanceof Expr) return json2;
|
|
20364
|
-
if (!
|
|
19575
|
+
if (!isRecord2(json2)) {
|
|
20365
19576
|
const got = describeInput(json2);
|
|
20366
19577
|
problems.error(
|
|
20367
19578
|
"shape.not-object",
|
|
@@ -20416,7 +19627,7 @@ var Registry = class {
|
|
|
20416
19627
|
* in a single pass. Only query kinds that declare a `static SHAPE` participate.
|
|
20417
19628
|
*/
|
|
20418
19629
|
parseCheckedQuery(json2, problems) {
|
|
20419
|
-
if (!
|
|
19630
|
+
if (!isRecord2(json2)) {
|
|
20420
19631
|
const got = describeInput(json2);
|
|
20421
19632
|
problems.error(
|
|
20422
19633
|
"shape.not-object",
|
|
@@ -20449,7 +19660,7 @@ var Registry = class {
|
|
|
20449
19660
|
* `undefined`. Dispatches on the source `kind` over `QuerySource.SHAPES`.
|
|
20450
19661
|
*/
|
|
20451
19662
|
parseCheckedSource(json2, problems) {
|
|
20452
|
-
if (!
|
|
19663
|
+
if (!isRecord2(json2)) {
|
|
20453
19664
|
const got = describeInput(json2);
|
|
20454
19665
|
problems.error(
|
|
20455
19666
|
"shape.not-object",
|
|
@@ -20565,7 +19776,7 @@ function checkLatticeLaws(types, opts) {
|
|
|
20565
19776
|
};
|
|
20566
19777
|
const kindOf = (ft) => attempt("FieldType.kind", () => ft.kind);
|
|
20567
19778
|
const refinementOf = (ft) => attempt("FieldType.refinement", () => ft.refinement);
|
|
20568
|
-
const metKey = (
|
|
19779
|
+
const metKey = (a13, b) => key(a13 && b ? attempt(MEET, () => a13.meet(b), `${key(a13)} \u2227 ${key(b)}`) : void 0);
|
|
20569
19780
|
const asymmetric = [];
|
|
20570
19781
|
for (const x of names) {
|
|
20571
19782
|
for (const y of names) {
|
|
@@ -20586,10 +19797,10 @@ function checkLatticeLaws(types, opts) {
|
|
|
20586
19797
|
const notAssociative = [];
|
|
20587
19798
|
for (const x of names) {
|
|
20588
19799
|
for (const y of names) {
|
|
20589
|
-
for (const
|
|
20590
|
-
const left = metKey(pair(x, y), at(
|
|
20591
|
-
const right = metKey(at(x), pair(y,
|
|
20592
|
-
if (left !== right) notAssociative.push(`${x} \u2227 ${y} \u2227 ${
|
|
19800
|
+
for (const z18 of names) {
|
|
19801
|
+
const left = metKey(pair(x, y), at(z18));
|
|
19802
|
+
const right = metKey(at(x), pair(y, z18));
|
|
19803
|
+
if (left !== right) notAssociative.push(`${x} \u2227 ${y} \u2227 ${z18}: ${left} vs ${right}`);
|
|
20593
19804
|
}
|
|
20594
19805
|
}
|
|
20595
19806
|
}
|
|
@@ -20784,20 +19995,20 @@ function checkComparator(refinement, impl, samples) {
|
|
|
20784
19995
|
};
|
|
20785
19996
|
const threw = [];
|
|
20786
19997
|
const answered = /* @__PURE__ */ new Map();
|
|
20787
|
-
const call = (
|
|
20788
|
-
const key = safeJson([
|
|
19998
|
+
const call = (a13, b) => {
|
|
19999
|
+
const key = safeJson([a13, b]);
|
|
20789
20000
|
const cached = answered.get(key);
|
|
20790
20001
|
if (cached !== void 0) return cached;
|
|
20791
20002
|
let answer;
|
|
20792
20003
|
try {
|
|
20793
|
-
answer = compare(
|
|
20004
|
+
answer = compare(a13, b);
|
|
20794
20005
|
} catch (err) {
|
|
20795
|
-
const line = `compareValues(${safeJson(
|
|
20006
|
+
const line = `compareValues(${safeJson(a13)}, ${safeJson(b)}): ${err instanceof Error ? err.message : String(err)}`;
|
|
20796
20007
|
if (!threw.includes(line)) threw.push(line);
|
|
20797
20008
|
return void 0;
|
|
20798
20009
|
}
|
|
20799
20010
|
if (typeof answer !== "number" || Number.isNaN(answer)) {
|
|
20800
|
-
const line = `compareValues(${safeJson(
|
|
20011
|
+
const line = `compareValues(${safeJson(a13)}, ${safeJson(b)}) answered ${safeJson(answer)}`;
|
|
20801
20012
|
if (!threw.includes(line)) threw.push(line);
|
|
20802
20013
|
return void 0;
|
|
20803
20014
|
}
|
|
@@ -20805,33 +20016,33 @@ function checkComparator(refinement, impl, samples) {
|
|
|
20805
20016
|
return answer;
|
|
20806
20017
|
};
|
|
20807
20018
|
const notOrder = [];
|
|
20808
|
-
for (const
|
|
20809
|
-
const self = call(
|
|
20810
|
-
if (self !== void 0 && self !== 0) notOrder.push(`compareValues(x, x) = ${self} for x = ${safeJson(
|
|
20019
|
+
for (const a13 of corpus) {
|
|
20020
|
+
const self = call(a13, a13);
|
|
20021
|
+
if (self !== void 0 && self !== 0) notOrder.push(`compareValues(x, x) = ${self} for x = ${safeJson(a13)}`);
|
|
20811
20022
|
for (const b of corpus) {
|
|
20812
|
-
const ab = call(
|
|
20813
|
-
const ba = call(b,
|
|
20023
|
+
const ab = call(a13, b);
|
|
20024
|
+
const ba = call(b, a13);
|
|
20814
20025
|
if (ab === void 0 || ba === void 0) continue;
|
|
20815
20026
|
if (Math.sign(ab) !== -Math.sign(ba)) {
|
|
20816
20027
|
notOrder.push(
|
|
20817
|
-
`compareValues(${safeJson(
|
|
20028
|
+
`compareValues(${safeJson(a13)}, ${safeJson(b)}) = ${ab} but the reverse = ${ba}`
|
|
20818
20029
|
);
|
|
20819
20030
|
}
|
|
20820
20031
|
}
|
|
20821
20032
|
}
|
|
20822
20033
|
const declared = Array.isArray(impl?.samples) ? impl.samples.filter((v) => v !== null) : [];
|
|
20823
20034
|
const triples = [.../* @__PURE__ */ new Set([...declared, ...corpus])].slice(0, MAX_COMPARATOR_SAMPLES);
|
|
20824
|
-
for (const
|
|
20035
|
+
for (const a13 of triples) {
|
|
20825
20036
|
for (const b of triples) {
|
|
20826
|
-
const ab = call(
|
|
20037
|
+
const ab = call(a13, b);
|
|
20827
20038
|
if (ab === void 0 || ab > 0) continue;
|
|
20828
20039
|
for (const c of triples) {
|
|
20829
20040
|
const bc = call(b, c);
|
|
20830
|
-
const ac = call(
|
|
20041
|
+
const ac = call(a13, c);
|
|
20831
20042
|
if (bc === void 0 || ac === void 0 || bc > 0) continue;
|
|
20832
20043
|
if (ac > 0) {
|
|
20833
20044
|
notOrder.push(
|
|
20834
|
-
`${safeJson(
|
|
20045
|
+
`${safeJson(a13)} \u2264 ${safeJson(b)} \u2264 ${safeJson(c)}, but compareValues(${safeJson(a13)}, ${safeJson(c)}) = ${ac}`
|
|
20835
20046
|
);
|
|
20836
20047
|
}
|
|
20837
20048
|
}
|
|
@@ -20847,10 +20058,10 @@ function checkComparator(refinement, impl, samples) {
|
|
|
20847
20058
|
}
|
|
20848
20059
|
const storable = corpus.filter((v) => refinement.declared.validValue(v));
|
|
20849
20060
|
const merged = [];
|
|
20850
|
-
for (const [i,
|
|
20061
|
+
for (const [i, a13] of storable.entries()) {
|
|
20851
20062
|
for (const b of storable.slice(i + 1)) {
|
|
20852
|
-
if (safeJson(
|
|
20853
|
-
if (call(
|
|
20063
|
+
if (safeJson(a13) === safeJson(b)) continue;
|
|
20064
|
+
if (call(a13, b) === 0) merged.push(`${safeJson(a13)} and ${safeJson(b)}`);
|
|
20854
20065
|
}
|
|
20855
20066
|
}
|
|
20856
20067
|
if (merged.length > 0) {
|
|
@@ -21150,8 +20361,8 @@ async function differentialCheck(opts) {
|
|
|
21150
20361
|
message: `\`${label}\` answers differently in memory and at the database. \`engine.run\` gave ${safeJson(runValues)}; \`${dialect}\` gave ${safeJson(sqlValues)}. SQL: ${sql}. One query, two answers: reconcile the type's SQL half (\`sql\` / \`cast\`) with its in-memory half (\`registerFieldTypeImpl\`'s \`compareValues\`) \u2014 whichever of the two is not what you meant. If the two look the same, check what your driver deserialises this column to (see \`DifferentialRow\`): a \`numeric\` arrives as the string "1.5" and a \`bytea\` as a \`Buffer\`, neither of which renders as what \`engine.run\` produced.`
|
|
21151
20362
|
});
|
|
21152
20363
|
};
|
|
21153
|
-
for (const
|
|
21154
|
-
await probe(`order ${
|
|
20364
|
+
for (const dir2 of ["asc", "desc"]) {
|
|
20365
|
+
await probe(`order ${dir2}`, orderProbe(columns.type, columns.field, dir2), "sequence");
|
|
21155
20366
|
}
|
|
21156
20367
|
await probe("distinct", distinctProbe(columns.type, columns.field), "multiset");
|
|
21157
20368
|
await probe("group by", groupProbe(columns.type, columns.field), "multiset");
|
|
@@ -21261,12 +20472,12 @@ function spreadArgs(names, source, field, other) {
|
|
|
21261
20472
|
});
|
|
21262
20473
|
return args;
|
|
21263
20474
|
}
|
|
21264
|
-
function orderProbe(type, field,
|
|
20475
|
+
function orderProbe(type, field, dir2) {
|
|
21265
20476
|
return {
|
|
21266
20477
|
kind: "select",
|
|
21267
20478
|
fields: [{ expr: fieldRef(type, field), as: PROBE_COLUMN }],
|
|
21268
20479
|
from: { kind: "type", type },
|
|
21269
|
-
order: [{ expr: fieldRef(type, field), dir }]
|
|
20480
|
+
order: [{ expr: fieldRef(type, field), dir: dir2 }]
|
|
21270
20481
|
};
|
|
21271
20482
|
}
|
|
21272
20483
|
function distinctProbe(type, field) {
|
|
@@ -21526,8 +20737,8 @@ function week(d) {
|
|
|
21526
20737
|
function dateAdd(field, n, d) {
|
|
21527
20738
|
return fn("dateAdd", { field: new LiteralExpr(field), n, d });
|
|
21528
20739
|
}
|
|
21529
|
-
function dateDiff(field,
|
|
21530
|
-
return fn("dateDiff", { field: new LiteralExpr(field), a, b });
|
|
20740
|
+
function dateDiff(field, a13, b) {
|
|
20741
|
+
return fn("dateDiff", { field: new LiteralExpr(field), a: a13, b });
|
|
21531
20742
|
}
|
|
21532
20743
|
function dateTrunc2(field, d) {
|
|
21533
20744
|
return fn("dateTrunc", { field: new LiteralExpr(field), d });
|
|
@@ -21544,8 +20755,8 @@ function epoch(ts) {
|
|
|
21544
20755
|
function fromEpoch(value2) {
|
|
21545
20756
|
return fn("fromEpoch", { value: value2 });
|
|
21546
20757
|
}
|
|
21547
|
-
function age(
|
|
21548
|
-
return fn("age", { a, b });
|
|
20758
|
+
function age(a13, b) {
|
|
20759
|
+
return fn("age", { a: a13, b });
|
|
21549
20760
|
}
|
|
21550
20761
|
function arrayContains(arr, value2) {
|
|
21551
20762
|
return fn("arrayContains", { arr, value: value2 });
|
|
@@ -21556,8 +20767,8 @@ function arrayAppend(arr, value2) {
|
|
|
21556
20767
|
function arrayPrepend(arr, value2) {
|
|
21557
20768
|
return fn("arrayPrepend", { arr, value: value2 });
|
|
21558
20769
|
}
|
|
21559
|
-
function arrayConcat(
|
|
21560
|
-
return fn("arrayConcat", { a, b });
|
|
20770
|
+
function arrayConcat(a13, b) {
|
|
20771
|
+
return fn("arrayConcat", { a: a13, b });
|
|
21561
20772
|
}
|
|
21562
20773
|
function arrayIndexOf(arr, value2) {
|
|
21563
20774
|
return fn("arrayIndexOf", { arr, value: value2 });
|
|
@@ -22448,7 +21659,7 @@ var BUILTIN_NAMES = /* @__PURE__ */ new Set([
|
|
|
22448
21659
|
"color"
|
|
22449
21660
|
]);
|
|
22450
21661
|
function ginToColumnType(type) {
|
|
22451
|
-
const o =
|
|
21662
|
+
const o = isRecord3(type.options) ? type.options : {};
|
|
22452
21663
|
switch (type.name) {
|
|
22453
21664
|
case "text":
|
|
22454
21665
|
if (o["pattern"] === UUID_PATTERN) return { kind: "uuid" };
|
|
@@ -22473,13 +21684,13 @@ function ginToColumnType(type) {
|
|
|
22473
21684
|
}
|
|
22474
21685
|
}
|
|
22475
21686
|
function storage(type) {
|
|
22476
|
-
const o =
|
|
21687
|
+
const o = isRecord3(type.options) ? type.options : {};
|
|
22477
21688
|
return { name: type.name, maxLength: o["maxLength"], whole: o["whole"], maxPrecision: o["maxPrecision"], uuid: o["pattern"] === UUID_PATTERN };
|
|
22478
21689
|
}
|
|
22479
21690
|
function enumValues(type) {
|
|
22480
|
-
const o =
|
|
21691
|
+
const o = isRecord3(type.options) ? type.options : {};
|
|
22481
21692
|
const values = o["values"];
|
|
22482
|
-
if (!
|
|
21693
|
+
if (!isRecord3(values)) return void 0;
|
|
22483
21694
|
const out = Object.values(values).filter((v) => typeof v === "string" || typeof v === "number");
|
|
22484
21695
|
return out.length > 0 ? out : void 0;
|
|
22485
21696
|
}
|
|
@@ -22489,7 +21700,7 @@ function defaultOf(expr) {
|
|
|
22489
21700
|
if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") return { kind: "value", value: value2 };
|
|
22490
21701
|
return void 0;
|
|
22491
21702
|
}
|
|
22492
|
-
function
|
|
21703
|
+
function isRecord3(value2) {
|
|
22493
21704
|
return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
22494
21705
|
}
|
|
22495
21706
|
|
|
@@ -22563,7 +21774,7 @@ function fieldTypeToGin(def) {
|
|
|
22563
21774
|
case "number":
|
|
22564
21775
|
case "money": {
|
|
22565
21776
|
const options = def.kind === "number" ? def : def.number ?? {};
|
|
22566
|
-
if (options.values !== void 0) return
|
|
21777
|
+
if (options.values !== void 0) return enumOf2(options.values.map((v) => v.value), { name: "num" });
|
|
22567
21778
|
const bounds = {
|
|
22568
21779
|
...options.min === void 0 ? {} : { min: options.min },
|
|
22569
21780
|
...options.max === void 0 ? {} : { max: options.max },
|
|
@@ -22572,7 +21783,7 @@ function fieldTypeToGin(def) {
|
|
|
22572
21783
|
return Object.keys(bounds).length === 0 ? { name: "num" } : { name: "num", options: bounds };
|
|
22573
21784
|
}
|
|
22574
21785
|
case "text": {
|
|
22575
|
-
if (def.values !== void 0) return
|
|
21786
|
+
if (def.values !== void 0) return enumOf2(def.values.map((v) => v.value), { name: "text" });
|
|
22576
21787
|
const bounds = {
|
|
22577
21788
|
...def.minLength === void 0 ? {} : { minLength: def.minLength },
|
|
22578
21789
|
...def.maxLength === void 0 ? {} : { maxLength: def.maxLength },
|
|
@@ -22593,7 +21804,7 @@ function fieldTypeToGin(def) {
|
|
|
22593
21804
|
return { name: "any" };
|
|
22594
21805
|
}
|
|
22595
21806
|
}
|
|
22596
|
-
function
|
|
21807
|
+
function enumOf2(values, scalar3) {
|
|
22597
21808
|
const members = {};
|
|
22598
21809
|
for (const value2 of values) members[String(value2)] = value2;
|
|
22599
21810
|
return { name: "enum", generic: { V: scalar3 }, options: { values: members } };
|
|
@@ -22619,7 +21830,7 @@ function queryArgsType(params, options = {}) {
|
|
|
22619
21830
|
}
|
|
22620
21831
|
const sorters = options.sorters ?? [];
|
|
22621
21832
|
if (sorters.length > 0 && props["sort"] === void 0) {
|
|
22622
|
-
const entry = { name: "obj", props: { column: { type:
|
|
21833
|
+
const entry = { name: "obj", props: { column: { type: enumOf2(sorters, { name: "text" }) }, dir: { type: enumOf2(["asc", "desc"], { name: "text" }) } } };
|
|
22623
21834
|
props["sort"] = { type: optional2({ name: "list", generic: { V: entry } }), docs: "Sort by these columns, in order (the query's own order when empty)." };
|
|
22624
21835
|
}
|
|
22625
21836
|
return { name: "obj", props };
|
|
@@ -22694,7 +21905,7 @@ function tableSchemaHash(table, tables) {
|
|
|
22694
21905
|
const own = tables.find((t) => t.name === table);
|
|
22695
21906
|
if (!own) throw new TableFnError(`There is no table ${table}.`);
|
|
22696
21907
|
const related = tables.filter((t) => t.name === table || own.foreignKeys.some((f) => f.table === t.name) || t.foreignKeys.some((f) => f.table === table));
|
|
22697
|
-
const text = stableJson([...related].sort((
|
|
21908
|
+
const text = stableJson([...related].sort((a13, b) => a13.name < b.name ? -1 : 1));
|
|
22698
21909
|
let hash = 0xcbf29ce484222325n;
|
|
22699
21910
|
for (let i = 0; i < text.length; i++) {
|
|
22700
21911
|
hash ^= BigInt(text.charCodeAt(i));
|
|
@@ -22705,7 +21916,7 @@ function tableSchemaHash(table, tables) {
|
|
|
22705
21916
|
function stableJson(value2) {
|
|
22706
21917
|
if (Array.isArray(value2)) return `[${value2.map(stableJson).join(",")}]`;
|
|
22707
21918
|
if (typeof value2 !== "object" || value2 === null) return JSON.stringify(value2) ?? "null";
|
|
22708
|
-
const entries = Object.entries(value2).filter(([, v]) => v !== void 0).sort(([
|
|
21919
|
+
const entries = Object.entries(value2).filter(([, v]) => v !== void 0).sort(([a13], [b]) => a13 < b ? -1 : 1);
|
|
22709
21920
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(",")}}`;
|
|
22710
21921
|
}
|
|
22711
21922
|
var ref3 = (source, field) => ({ kind: "field-ref", source, field });
|
|
@@ -22723,12 +21934,12 @@ var win = (fn2, value2, partitionBy, orderBy) => ({
|
|
|
22723
21934
|
...partitionBy.length > 0 ? { partitionBy } : {},
|
|
22724
21935
|
...orderBy === void 0 ? {} : { orderBy: [{ expr: orderBy, dir: "desc", nulls: "last" }] }
|
|
22725
21936
|
});
|
|
22726
|
-
var sub2 = (
|
|
22727
|
-
function div2(
|
|
21937
|
+
var sub2 = (a13, b) => ({ kind: "binary", op: "-", left: a13, right: b });
|
|
21938
|
+
function div2(a13, b) {
|
|
22728
21939
|
return {
|
|
22729
21940
|
kind: "binary",
|
|
22730
21941
|
op: "/",
|
|
22731
|
-
left: { kind: "binary", op: "*", left:
|
|
21942
|
+
left: { kind: "binary", op: "*", left: a13, right: lit3(1) },
|
|
22732
21943
|
right: { kind: "function-call", function: "nullif", args: { value: b, other: lit3(0) } }
|
|
22733
21944
|
};
|
|
22734
21945
|
}
|
|
@@ -22936,7 +22147,7 @@ var TableFnSchema = class {
|
|
|
22936
22147
|
/** The table's fns, most useful first, capped. */
|
|
22937
22148
|
list(table) {
|
|
22938
22149
|
const t = this.table(table);
|
|
22939
|
-
const fns = this.#ops(t).map((op) => this.fn(op)).sort((
|
|
22150
|
+
const fns = this.#ops(t).map((op) => this.fn(op)).sort((a13, b) => a13.rank - b.rank || a13.group.localeCompare(b.group) || a13.name.localeCompare(b.name));
|
|
22940
22151
|
return { table, hash: tableSchemaHash(table, [...this.#tables.values()]), fns: fns.slice(0, this.#cap), more: Math.max(0, fns.length - this.#cap) };
|
|
22941
22152
|
}
|
|
22942
22153
|
#ops(t) {
|
|
@@ -23901,7 +23112,90 @@ function drillDownInto(select, groupRow, engine) {
|
|
|
23901
23112
|
}
|
|
23902
23113
|
|
|
23903
23114
|
// src/llm/schemas.ts
|
|
23904
|
-
import {
|
|
23115
|
+
import { a as a11 } from "@aeye/schema";
|
|
23116
|
+
|
|
23117
|
+
// src/llm/grammar.ts
|
|
23118
|
+
import { a as a10 } from "@aeye/schema";
|
|
23119
|
+
|
|
23120
|
+
// src/schema-build.ts
|
|
23121
|
+
var allFields = (t) => t.fields;
|
|
23122
|
+
var relationFieldsOf = (t) => t.relationFields();
|
|
23123
|
+
var semanticFieldsOf = (t) => t.semanticFields();
|
|
23124
|
+
var textFieldsOf = (t) => t.textFields();
|
|
23125
|
+
function allowingExpr(base, kind) {
|
|
23126
|
+
return (t) => base(t).filter((f) => f.allowsExpr(kind));
|
|
23127
|
+
}
|
|
23128
|
+
function pickByNames(available, sel) {
|
|
23129
|
+
if (sel === "none") return [];
|
|
23130
|
+
if (sel === "all") return [...available];
|
|
23131
|
+
const names = new Set(sel);
|
|
23132
|
+
return available.filter((f) => names.has(f.name));
|
|
23133
|
+
}
|
|
23134
|
+
function selectFunctions(registry, selector = "all") {
|
|
23135
|
+
const all = registry.functionList();
|
|
23136
|
+
const byShape = (shape) => all.filter((f) => f.shape === shape);
|
|
23137
|
+
if (selector === "all" || selector === "none") {
|
|
23138
|
+
const sel = selector;
|
|
23139
|
+
return {
|
|
23140
|
+
scalar: pickByNames(byShape("scalar"), sel),
|
|
23141
|
+
tabular: pickByNames(byShape("tabular"), sel),
|
|
23142
|
+
window: pickByNames(byShape("window"), sel),
|
|
23143
|
+
aggregate: pickByNames(byShape("aggregate"), sel)
|
|
23144
|
+
};
|
|
23145
|
+
}
|
|
23146
|
+
if (Array.isArray(selector)) {
|
|
23147
|
+
const names = new Set(selector);
|
|
23148
|
+
const keep = (shape) => byShape(shape).filter((f) => names.has(f.name));
|
|
23149
|
+
return { scalar: keep("scalar"), tabular: keep("tabular"), window: keep("window"), aggregate: keep("aggregate") };
|
|
23150
|
+
}
|
|
23151
|
+
return {
|
|
23152
|
+
scalar: pickByNames(byShape("scalar"), selector.scalar ?? "all"),
|
|
23153
|
+
tabular: pickByNames(byShape("tabular"), selector.tabular ?? "all"),
|
|
23154
|
+
window: pickByNames(byShape("window"), selector.window ?? "all"),
|
|
23155
|
+
aggregate: pickByNames(byShape("aggregate"), selector.aggregate ?? "all")
|
|
23156
|
+
};
|
|
23157
|
+
}
|
|
23158
|
+
function exprKindApplicable(kind, types, selected, registry) {
|
|
23159
|
+
switch (kind) {
|
|
23160
|
+
case "operator":
|
|
23161
|
+
return registry.operatorList().some((op) => operatorReachable(op, types));
|
|
23162
|
+
case "semantic":
|
|
23163
|
+
return types.some((t) => t.isSemantic());
|
|
23164
|
+
case "text-search":
|
|
23165
|
+
return types.some((t) => t.isSearchable());
|
|
23166
|
+
case "text-score":
|
|
23167
|
+
return types.some((t) => t.isSearchable());
|
|
23168
|
+
case "array-op":
|
|
23169
|
+
return types.some((t) => t.fields.some((f) => f.allowsExpr("array-op")));
|
|
23170
|
+
case "tabular-function-call":
|
|
23171
|
+
return selected.tabular.length > 0;
|
|
23172
|
+
case "aggregate":
|
|
23173
|
+
return selected.aggregate.length > 0;
|
|
23174
|
+
case "window":
|
|
23175
|
+
return selected.window.length > 0;
|
|
23176
|
+
case "function-call":
|
|
23177
|
+
return selected.scalar.length > 0;
|
|
23178
|
+
case "filters":
|
|
23179
|
+
return types.some((t) => t.fields.length > 0);
|
|
23180
|
+
case "excluded":
|
|
23181
|
+
return false;
|
|
23182
|
+
case "output":
|
|
23183
|
+
return false;
|
|
23184
|
+
case "sorter":
|
|
23185
|
+
return false;
|
|
23186
|
+
default:
|
|
23187
|
+
return true;
|
|
23188
|
+
}
|
|
23189
|
+
}
|
|
23190
|
+
function operatorReachable(operator, types) {
|
|
23191
|
+
return operator.operands.some(
|
|
23192
|
+
(operand) => types.some(
|
|
23193
|
+
(t) => t.fields.some((f) => operand.fieldType === void 0 || operand.fieldType.comparableWith(f.fieldType))
|
|
23194
|
+
)
|
|
23195
|
+
);
|
|
23196
|
+
}
|
|
23197
|
+
|
|
23198
|
+
// src/llm/depth.ts
|
|
23905
23199
|
var DEFAULT_MAX_QUERY_SCHEMA_TYPES = 5;
|
|
23906
23200
|
function toRegistry(engineOrRegistry) {
|
|
23907
23201
|
return "registry" in engineOrRegistry ? engineOrRegistry.registry : engineOrRegistry;
|
|
@@ -23973,293 +23267,9 @@ function resolveDepth(options, counts) {
|
|
|
23973
23267
|
writes: degradeWrites(d.writes, counts.fieldCount, max2)
|
|
23974
23268
|
};
|
|
23975
23269
|
}
|
|
23976
|
-
function relationOnSchema(types, depth, cache) {
|
|
23977
|
-
return refSchema(types, depth, {
|
|
23978
|
-
keyName: "source",
|
|
23979
|
-
fieldMode: "one",
|
|
23980
|
-
eligible: relationFieldsOf,
|
|
23981
|
-
extras: {
|
|
23982
|
-
kind: z43.literal("relation"),
|
|
23983
|
-
as: z43.string().describe("Required alias the joined target binds under.")
|
|
23984
|
-
},
|
|
23985
|
-
aid: "JoinOn",
|
|
23986
|
-
describe: "Cross a relation field of a bound source (key synthesized from the relation)."
|
|
23987
|
-
}, cache);
|
|
23988
|
-
}
|
|
23989
|
-
function buildExprUnion(registry, inner, types, selected) {
|
|
23990
|
-
const applicable = registry.exprClassList().filter((c) => exprKindApplicable(c.KIND, types, selected, registry));
|
|
23991
|
-
return withAid(orFold(applicable.map((c) => c.toSchema(inner))), "Expr", {
|
|
23992
|
-
kinds: applicable.map((c) => c.KIND)
|
|
23993
|
-
});
|
|
23994
|
-
}
|
|
23995
|
-
function buildSchemas(engineOrRegistry, options = {}) {
|
|
23996
|
-
const registry = toRegistry(engineOrRegistry);
|
|
23997
|
-
const types = options.types ?? registry.typeList();
|
|
23998
|
-
const typeNames = types.map((t) => t.name);
|
|
23999
|
-
const selected = selectFunctions(registry, options.functions);
|
|
24000
|
-
const depth = resolveDepth(options, {
|
|
24001
|
-
typeCount: types.length,
|
|
24002
|
-
fieldCount: uniqueFieldNames(types).length,
|
|
24003
|
-
fnCount: maxFunctionGroup(selected)
|
|
24004
|
-
});
|
|
24005
|
-
const cache = new SchemaCache();
|
|
24006
|
-
const inner = {
|
|
24007
|
-
registry,
|
|
24008
|
-
types: [...types],
|
|
24009
|
-
depth,
|
|
24010
|
-
functions: selected,
|
|
24011
|
-
includeDocs: options.includeDocs,
|
|
24012
|
-
cache,
|
|
24013
|
-
Expr: z43.never(),
|
|
24014
|
-
Query: z43.never()
|
|
24015
|
-
};
|
|
24016
|
-
inner.Expr = z43.lazy(() => buildExprUnion(registry, inner, types, selected));
|
|
24017
|
-
const typeRef = depth.typeNames === "enum" ? withAid(enumOf2(typeNames), "TypeName").describe("A registered Type name.") : z43.string().describe("A Type name.");
|
|
24018
|
-
const Expr9 = inner.Expr;
|
|
24019
|
-
const Query2 = z43.lazy(() => QueryUnion);
|
|
24020
|
-
inner.Query = Query2;
|
|
24021
|
-
const sourceBranches = [
|
|
24022
|
-
z43.object({ kind: z43.literal("type"), type: typeRef }).describe("A type source, bound under (and referenced by) its type name."),
|
|
24023
|
-
z43.object({
|
|
24024
|
-
kind: z43.literal("aliased"),
|
|
24025
|
-
type: typeRef,
|
|
24026
|
-
as: z43.string().describe("Custom source name (self-join / collision break).")
|
|
24027
|
-
}).describe("An explicitly-aliased type source (the discouraged escape hatch)."),
|
|
24028
|
-
z43.object({
|
|
24029
|
-
kind: z43.literal("subquery"),
|
|
24030
|
-
query: Query2,
|
|
24031
|
-
as: z43.string().describe("Required alias for the derived source.")
|
|
24032
|
-
}).describe("A derived (subquery) source.")
|
|
24033
|
-
];
|
|
24034
|
-
if (selected.tabular.length > 0) {
|
|
24035
|
-
const fnName = depth.functions === "open" ? z43.string().describe("A registered tabular function name.") : withAid(enumOf2(selected.tabular.map((f) => f.name)), "FunctionName").describe(
|
|
24036
|
-
"A registered tabular function name."
|
|
24037
|
-
);
|
|
24038
|
-
sourceBranches.push(
|
|
24039
|
-
z43.object({
|
|
24040
|
-
kind: z43.literal("function"),
|
|
24041
|
-
function: fnName,
|
|
24042
|
-
args: z43.record(z43.string(), Expr9).describe("Arguments keyed by declared parameter name."),
|
|
24043
|
-
as: z43.string().describe("Required alias the produced rows bind under.")
|
|
24044
|
-
}).describe("A table-valued function source: FROM fn(args) AS alias.")
|
|
24045
|
-
);
|
|
24046
|
-
}
|
|
24047
|
-
const sourceKinds = selected.tabular.length > 0 ? ["type", "aliased", "subquery", "function"] : ["type", "aliased", "subquery"];
|
|
24048
|
-
const Source = withAid(orFold(sourceBranches), "Source", {
|
|
24049
|
-
kinds: sourceKinds
|
|
24050
|
-
}).describe(
|
|
24051
|
-
"A FROM / JOIN source: a type, an aliased type, a subquery, or a table-valued function."
|
|
24052
|
-
);
|
|
24053
|
-
const hasRelations = types.some((t) => t.relationFields().length > 0);
|
|
24054
|
-
const relationOn = relationOnSchema(types, depth.refs, cache);
|
|
24055
|
-
const JoinOn = withAid(
|
|
24056
|
-
hasRelations ? orFold([relationOn, Source]) : Source,
|
|
24057
|
-
"JoinOn",
|
|
24058
|
-
{ kinds: ["relation", ...sourceKinds] }
|
|
24059
|
-
).describe("A join target: a relation crossing or a manually-joined source.");
|
|
24060
|
-
const Join = withAid(
|
|
24061
|
-
z43.object({
|
|
24062
|
-
on: JoinOn,
|
|
24063
|
-
and: Expr9.optional(),
|
|
24064
|
-
joinType: withAid(enumOf2(["inner", "left", "right", "full"]), "JoinType").optional()
|
|
24065
|
-
}),
|
|
24066
|
-
"Join"
|
|
24067
|
-
).describe("A JOIN: a relation crossing (key synthesized) or a manual source-def join with `and` as its ON.");
|
|
24068
|
-
const joinsField = hasRelations ? z43.array(Join).optional() : z43.array(z43.never()).optional();
|
|
24069
|
-
const Order = z43.object({
|
|
24070
|
-
expr: Expr9,
|
|
24071
|
-
dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
|
|
24072
|
-
nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
|
|
24073
|
-
}).describe("An ORDER BY entry.");
|
|
24074
|
-
const OutputRef = z43.object({ kind: z43.literal("output"), name: z43.string() }).describe("A reference to a SELECT output field by name (its `as`, or the natural derived name).");
|
|
24075
|
-
const GroupExpr = Expr9.or(OutputRef);
|
|
24076
|
-
const SelectOrder = z43.object({
|
|
24077
|
-
expr: GroupExpr,
|
|
24078
|
-
dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
|
|
24079
|
-
nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
|
|
24080
|
-
}).describe("An ORDER BY entry (its `expr` may reference a SELECT output field by name).");
|
|
24081
|
-
const Sorter = sorterSchema(GroupExpr);
|
|
24082
|
-
const SelectOrderEntry = SelectOrder.or(Sorter).describe(
|
|
24083
|
-
"A SELECT ORDER BY entry: a term, or a dynamic-sort `sorter` catalog (selection supplied at run time)."
|
|
24084
|
-
);
|
|
24085
|
-
const SelectField = z43.object({ expr: Expr9, as: z43.string().optional() }).describe("A selected output field.");
|
|
24086
|
-
const limitOffset = withAid(z43.number().or(cache.param()), "Limit", { id: cache.defId("Limit") });
|
|
24087
|
-
const Select = withAid(
|
|
24088
|
-
z43.object({
|
|
24089
|
-
kind: z43.literal("select"),
|
|
24090
|
-
distinct: z43.boolean().optional(),
|
|
24091
|
-
fields: z43.array(SelectField),
|
|
24092
|
-
from: Source,
|
|
24093
|
-
joins: joinsField,
|
|
24094
|
-
where: z43.array(Expr9).optional(),
|
|
24095
|
-
groupBy: z43.array(GroupExpr).optional(),
|
|
24096
|
-
having: z43.array(GroupExpr).optional(),
|
|
24097
|
-
order: z43.array(SelectOrderEntry).optional(),
|
|
24098
|
-
limit: limitOffset.optional(),
|
|
24099
|
-
offset: limitOffset.optional()
|
|
24100
|
-
// `includeTotal` is an EXECUTION-time option (engine.run / engine.toSQL),
|
|
24101
|
-
// not a SELECT field — so it is intentionally absent here.
|
|
24102
|
-
}),
|
|
24103
|
-
"Query_select"
|
|
24104
|
-
).describe("A SELECT statement.");
|
|
24105
|
-
const insertableTypes = types.filter((t) => t.insertable);
|
|
24106
|
-
const updatableTypes = types.filter((t) => t.updatable);
|
|
24107
|
-
const deletableTypes = types.filter((t) => t.deletable);
|
|
24108
|
-
const fbOf = (typeName, field) => registry.backing(typeName)?.fields?.[field];
|
|
24109
|
-
const dmlTypeRef = (subset) => depth.typeNames === "enum" ? enumOf2(subset.map((t) => t.name)).describe("A permitted target Type name.") : z43.string().describe("A Type name.");
|
|
24110
|
-
const ExcludedExprSchema = z43.object({ kind: z43.literal("excluded"), field: z43.string() }).describe("The proposed row inside ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
|
|
24111
|
-
const ConflictExpr = Expr9.or(ExcludedExprSchema);
|
|
24112
|
-
const onConflictSchema = (t) => {
|
|
24113
|
-
const update = depth.writes !== "open" && t ? updateSetSchema(t, fbOf, depth.writes, ConflictExpr) : z43.record(z43.string(), ConflictExpr).describe("DO UPDATE SET assignments (field \u2192 value).");
|
|
24114
|
-
return z43.object({
|
|
24115
|
-
fields: z43.array(z43.string()),
|
|
24116
|
-
doNothing: z43.boolean().optional(),
|
|
24117
|
-
update: update.optional()
|
|
24118
|
-
});
|
|
24119
|
-
};
|
|
24120
|
-
const openInsert = () => withAid(
|
|
24121
|
-
z43.object({
|
|
24122
|
-
kind: z43.literal("insert"),
|
|
24123
|
-
into: dmlTypeRef(insertableTypes),
|
|
24124
|
-
rows: z43.array(z43.record(z43.string(), Expr9)).optional().describe("Rows to insert (each a field \u2192 value map)."),
|
|
24125
|
-
select: Query2.optional(),
|
|
24126
|
-
returning: z43.array(SelectField).optional(),
|
|
24127
|
-
onConflict: onConflictSchema().optional()
|
|
24128
|
-
}),
|
|
24129
|
-
"Query_insert"
|
|
24130
|
-
).describe("An INSERT statement.");
|
|
24131
|
-
const namedInsert = (writes) => orFold(
|
|
24132
|
-
insertableTypes.map(
|
|
24133
|
-
(t) => z43.object({
|
|
24134
|
-
kind: z43.literal("insert"),
|
|
24135
|
-
into: z43.literal(t.name),
|
|
24136
|
-
rows: z43.array(insertRowSchema(t, fbOf, writes, Expr9)).optional(),
|
|
24137
|
-
select: Query2.optional(),
|
|
24138
|
-
returning: z43.array(SelectField).optional(),
|
|
24139
|
-
onConflict: onConflictSchema(t).optional()
|
|
24140
|
-
}).describe(`An INSERT into ${t.name}.`)
|
|
24141
|
-
)
|
|
24142
|
-
).describe("An INSERT statement.");
|
|
24143
|
-
const Insert = depth.writes === "open" ? openInsert() : namedInsert(depth.writes);
|
|
24144
|
-
const openUpdate = () => withAid(
|
|
24145
|
-
z43.object({
|
|
24146
|
-
kind: z43.literal("update"),
|
|
24147
|
-
type: dmlTypeRef(updatableTypes),
|
|
24148
|
-
set: z43.record(z43.string(), Expr9).describe("Fields to set (field \u2192 value)."),
|
|
24149
|
-
joins: joinsField,
|
|
24150
|
-
where: z43.array(Expr9).optional(),
|
|
24151
|
-
returning: z43.array(SelectField).optional()
|
|
24152
|
-
}),
|
|
24153
|
-
"Query_update"
|
|
24154
|
-
).describe("An UPDATE statement.");
|
|
24155
|
-
const namedUpdate = (writes) => orFold(
|
|
24156
|
-
updatableTypes.map(
|
|
24157
|
-
(t) => z43.object({
|
|
24158
|
-
kind: z43.literal("update"),
|
|
24159
|
-
type: z43.literal(t.name),
|
|
24160
|
-
set: updateSetSchema(t, fbOf, writes, Expr9),
|
|
24161
|
-
joins: joinsField,
|
|
24162
|
-
where: z43.array(Expr9).optional(),
|
|
24163
|
-
returning: z43.array(SelectField).optional()
|
|
24164
|
-
}).describe(`An UPDATE of ${t.name}.`)
|
|
24165
|
-
)
|
|
24166
|
-
).describe("An UPDATE statement.");
|
|
24167
|
-
const Update = depth.writes === "open" ? openUpdate() : namedUpdate(depth.writes);
|
|
24168
|
-
const Delete = withAid(
|
|
24169
|
-
z43.object({
|
|
24170
|
-
kind: z43.literal("delete"),
|
|
24171
|
-
from: dmlTypeRef(deletableTypes),
|
|
24172
|
-
joins: joinsField,
|
|
24173
|
-
where: z43.array(Expr9).optional(),
|
|
24174
|
-
returning: z43.array(SelectField).optional()
|
|
24175
|
-
}),
|
|
24176
|
-
"Query_delete"
|
|
24177
|
-
).describe("A DELETE statement.");
|
|
24178
|
-
const SetOperation = withAid(
|
|
24179
|
-
z43.object({
|
|
24180
|
-
kind: withAid(enumOf2(["union", "intersect", "except"]), "SetOpKind"),
|
|
24181
|
-
left: Query2,
|
|
24182
|
-
right: Query2,
|
|
24183
|
-
all: z43.boolean().optional(),
|
|
24184
|
-
// SET-LEVEL ordering / pagination applied AFTER the set op; ORDER BY terms
|
|
24185
|
-
// reference OUTPUT COLUMN names (a set op has no table to qualify).
|
|
24186
|
-
order: z43.array(Order).optional(),
|
|
24187
|
-
limit: limitOffset.optional(),
|
|
24188
|
-
offset: limitOffset.optional()
|
|
24189
|
-
}),
|
|
24190
|
-
"Query_set-operation"
|
|
24191
|
-
).describe("A UNION / INTERSECT / EXCEPT set operation.");
|
|
24192
|
-
const CteEntry = orFold([
|
|
24193
|
-
z43.object({ name: z43.string(), query: Query2 }).describe("A non-recursive CTE."),
|
|
24194
|
-
z43.object({ name: z43.string(), base: Query2, recursive: Query2 }).describe("A recursive CTE: a base seed UNION-ed with a recursive arm.")
|
|
24195
|
-
]);
|
|
24196
|
-
const CTE = withAid(
|
|
24197
|
-
z43.object({
|
|
24198
|
-
kind: z43.literal("cte"),
|
|
24199
|
-
ctes: z43.array(CteEntry),
|
|
24200
|
-
final: Query2
|
|
24201
|
-
}),
|
|
24202
|
-
"Query_cte"
|
|
24203
|
-
).describe("A WITH (CTE) statement.");
|
|
24204
|
-
const ExprQuery2 = withAid(
|
|
24205
|
-
z43.object({ kind: z43.literal("expr"), expr: Expr9 }),
|
|
24206
|
-
"Query_expr"
|
|
24207
|
-
).describe("A single-expression query.");
|
|
24208
|
-
const queryBranches = [Select];
|
|
24209
|
-
const queryKinds = ["select"];
|
|
24210
|
-
if (insertableTypes.length > 0) {
|
|
24211
|
-
queryBranches.push(Insert);
|
|
24212
|
-
queryKinds.push("insert");
|
|
24213
|
-
}
|
|
24214
|
-
if (updatableTypes.length > 0) {
|
|
24215
|
-
queryBranches.push(Update);
|
|
24216
|
-
queryKinds.push("update");
|
|
24217
|
-
}
|
|
24218
|
-
if (deletableTypes.length > 0) {
|
|
24219
|
-
queryBranches.push(Delete);
|
|
24220
|
-
queryKinds.push("delete");
|
|
24221
|
-
}
|
|
24222
|
-
queryBranches.push(SetOperation, CTE, ExprQuery2);
|
|
24223
|
-
queryKinds.push("union", "intersect", "except", "cte", "expr");
|
|
24224
|
-
const QueryUnion = withAid(orFold(queryBranches), "Query", {
|
|
24225
|
-
kinds: queryKinds
|
|
24226
|
-
}).describe("Any query: select / insert / update / delete / set-op / cte / expr.");
|
|
24227
|
-
return {
|
|
24228
|
-
Type: typeRef,
|
|
24229
|
-
Expr: Expr9,
|
|
24230
|
-
Source,
|
|
24231
|
-
Join,
|
|
24232
|
-
Order,
|
|
24233
|
-
SelectField,
|
|
24234
|
-
Select,
|
|
24235
|
-
Insert,
|
|
24236
|
-
Update,
|
|
24237
|
-
Delete,
|
|
24238
|
-
SetOperation,
|
|
24239
|
-
CTE,
|
|
24240
|
-
ExprQuery: ExprQuery2,
|
|
24241
|
-
Query: QueryUnion
|
|
24242
|
-
};
|
|
24243
|
-
}
|
|
24244
23270
|
function shouldUseStringSchema(types, max2 = DEFAULT_MAX_QUERY_SCHEMA_TYPES) {
|
|
24245
23271
|
return types.length > max2;
|
|
24246
23272
|
}
|
|
24247
|
-
function querySchema(engine, options = {}) {
|
|
24248
|
-
const registry = toRegistry(engine);
|
|
24249
|
-
const types = options.types ?? registry.typeList();
|
|
24250
|
-
const max2 = options.max ?? DEFAULT_MAX_QUERY_SCHEMA_TYPES;
|
|
24251
|
-
if (shouldUseStringSchema(types, max2)) {
|
|
24252
|
-
return z43.object({
|
|
24253
|
-
query: z43.string().describe(
|
|
24254
|
-
"A detailed natural-language description of the query: which Types are involved, filter conditions, known record IDs, and the precise outcome desired. Do not emit a structured query \u2014 there are too many Types to enumerate."
|
|
24255
|
-
)
|
|
24256
|
-
});
|
|
24257
|
-
}
|
|
24258
|
-
const schemas = buildSchemas(registry, options);
|
|
24259
|
-
return z43.object({
|
|
24260
|
-
query: schemas.Query.describe("The query to execute as a structured Query object.")
|
|
24261
|
-
});
|
|
24262
|
-
}
|
|
24263
23273
|
function resolveSchemaDepth(engine, options = {}) {
|
|
24264
23274
|
const registry = toRegistry(engine);
|
|
24265
23275
|
const types = options.types ?? registry.typeList();
|
|
@@ -24325,6 +23335,517 @@ function depthInstructions(engine, options = {}) {
|
|
|
24325
23335
|
}
|
|
24326
23336
|
return notes.join("\n");
|
|
24327
23337
|
}
|
|
23338
|
+
function resolveDepthFor(types, selected, options = {}) {
|
|
23339
|
+
return resolveDepth(options, {
|
|
23340
|
+
typeCount: types.length,
|
|
23341
|
+
fieldCount: uniqueFieldNames(types).length,
|
|
23342
|
+
fnCount: maxFunctionGroup(selected)
|
|
23343
|
+
});
|
|
23344
|
+
}
|
|
23345
|
+
|
|
23346
|
+
// src/llm/grammar.ts
|
|
23347
|
+
var Expr9 = a10.ref("Expr");
|
|
23348
|
+
var Query2 = a10.ref("Query");
|
|
23349
|
+
var dir = a10.enum(["asc", "desc"]);
|
|
23350
|
+
var nulls = a10.enum(["first", "last"]);
|
|
23351
|
+
var grammar = {
|
|
23352
|
+
Expr_literal: a10.object({ kind: a10.literal("literal"), value: a10.json() }).describe("A constant value: a scalar, or a whole JSON document for a json / array field."),
|
|
23353
|
+
Expr_param: a10.object({ kind: a10.literal("param"), name: a10.string().describe("Parameter name; its type is inferred from usage.") }).describe("A named bind parameter (contextually typed)."),
|
|
23354
|
+
// The shared `param` fragment (limits, text-search queries).
|
|
23355
|
+
param: a10.object({ kind: a10.literal("param"), name: a10.string() }).describe("A named bind parameter."),
|
|
23356
|
+
Expr_binary: a10.object({ kind: a10.literal("binary"), op: a10.enum(["+", "-", "*", "/", "%"]), left: Expr9, right: Expr9 }).describe("Arithmetic binary operation."),
|
|
23357
|
+
Expr_unary: a10.object({ kind: a10.literal("unary"), op: a10.enum(["-", "+"]), operand: Expr9 }).describe("Unary arithmetic operation."),
|
|
23358
|
+
Expr_comparison: a10.object({
|
|
23359
|
+
kind: a10.literal("comparison"),
|
|
23360
|
+
op: a10.enum(["=", "<>", "<", "<=", ">", ">=", "like", "notLike", "ilike"]),
|
|
23361
|
+
left: Expr9,
|
|
23362
|
+
right: Expr9
|
|
23363
|
+
}).describe("Scalar comparison predicate."),
|
|
23364
|
+
Expr_logical: a10.object({ kind: a10.literal("logical"), op: a10.enum(["and", "or", "not"]), operands: a10.array(Expr9) }).describe("Boolean connective (and / or / not)."),
|
|
23365
|
+
Expr_in: a10.object({ kind: a10.literal("in"), value: Expr9, in: a10.union([a10.array(Expr9), Query2]), not: a10.boolean().optional() }).describe("Membership predicate (value IN list / subquery)."),
|
|
23366
|
+
Expr_between: a10.object({ kind: a10.literal("between"), value: Expr9, lower: Expr9, upper: Expr9, not: a10.boolean().optional() }).describe("Range predicate (value BETWEEN lower AND upper)."),
|
|
23367
|
+
"Expr_is-null": a10.object({ kind: a10.literal("is-null"), value: Expr9, not: a10.boolean().optional() }).describe("Null test (value IS [NOT] NULL)."),
|
|
23368
|
+
Expr_exists: a10.object({ kind: a10.literal("exists"), query: Query2, not: a10.boolean().optional() }).describe("Existence predicate over a subquery."),
|
|
23369
|
+
Expr_case: a10.object({ kind: a10.literal("case"), branches: a10.array(a10.object({ when: Expr9, then: Expr9 })), else: Expr9.optional() }).describe("Conditional CASE expression."),
|
|
23370
|
+
Expr_subquery: a10.object({ kind: a10.literal("subquery"), query: Query2 }).describe("A subquery used in value position."),
|
|
23371
|
+
"Expr_array-op": a10.object({
|
|
23372
|
+
kind: a10.literal("array-op"),
|
|
23373
|
+
op: a10.enum(["contains", "containsAny", "containsAll", "isEmpty", "notEmpty"]).describe("Array predicate: element membership / overlap / emptiness."),
|
|
23374
|
+
target: Expr9,
|
|
23375
|
+
value: a10.union([Expr9, a10.array(Expr9)]).optional().describe("Single element (contains), element list (containsAny/All), or omitted (isEmpty/notEmpty).")
|
|
23376
|
+
}).describe("Array containment / emptiness predicate."),
|
|
23377
|
+
// ORDER BY, output refs, the sorter
|
|
23378
|
+
Order: a10.object({ expr: Expr9, dir, nulls: nulls.optional() }).describe("An ORDER BY entry."),
|
|
23379
|
+
Expr_output: a10.object({ kind: a10.literal("output"), name: a10.string() }).describe("A reference to a SELECT output field by name (its `as`, or the natural derived name)."),
|
|
23380
|
+
GroupExpr: a10.union([Expr9, a10.ref("Expr_output")]),
|
|
23381
|
+
SelectOrder: a10.object({ expr: a10.ref("GroupExpr"), dir, nulls: nulls.optional() }).describe("An ORDER BY entry (its `expr` may reference a SELECT output field by name)."),
|
|
23382
|
+
Expr_sorter: a10.object({
|
|
23383
|
+
kind: a10.literal("sorter"),
|
|
23384
|
+
sorts: a10.record(a10.ref("GroupExpr")).describe("Named sortable expressions (sort name \u2192 expr); the caller selects by name at run time."),
|
|
23385
|
+
defaultSort: a10.array(a10.object({ sort: a10.string().describe("A declared sort name (a key of `sorts`)."), dir })).optional().describe("Default multi-key sort (each `{ sort, dir }`) applied when the caller selects none.")
|
|
23386
|
+
}).describe("A dynamic-sort catalog (valid only in a SELECT `order`); the selection is supplied at execution time."),
|
|
23387
|
+
SelectOrderEntry: a10.union([a10.ref("SelectOrder"), a10.ref("Expr_sorter")]).describe("A SELECT ORDER BY entry: a term, or a dynamic-sort `sorter` catalog (selection supplied at run time)."),
|
|
23388
|
+
SelectField: a10.object({ expr: Expr9, as: a10.string().optional() }).describe("A selected output field."),
|
|
23389
|
+
Limit: a10.union([a10.number(), a10.ref("param")]),
|
|
23390
|
+
Join: a10.object({ on: a10.ref("JoinOn"), and: Expr9.optional(), joinType: a10.enum(["inner", "left", "right", "full"]).optional() }).describe("A JOIN: a relation crossing (key synthesized) or a manual source-def join with `and` as its ON."),
|
|
23391
|
+
Query_select: a10.object({
|
|
23392
|
+
kind: a10.literal("select"),
|
|
23393
|
+
distinct: a10.boolean().optional(),
|
|
23394
|
+
fields: a10.array(a10.ref("SelectField")),
|
|
23395
|
+
from: a10.ref("Source"),
|
|
23396
|
+
joins: a10.ref("Joins").optional(),
|
|
23397
|
+
where: a10.array(Expr9).optional(),
|
|
23398
|
+
groupBy: a10.array(a10.ref("GroupExpr")).optional(),
|
|
23399
|
+
having: a10.array(a10.ref("GroupExpr")).optional(),
|
|
23400
|
+
order: a10.array(a10.ref("SelectOrderEntry")).optional(),
|
|
23401
|
+
limit: a10.ref("Limit").optional(),
|
|
23402
|
+
offset: a10.ref("Limit").optional()
|
|
23403
|
+
}).describe("A SELECT statement."),
|
|
23404
|
+
"Query_set-operation": a10.object({
|
|
23405
|
+
kind: a10.enum(["union", "intersect", "except"]),
|
|
23406
|
+
left: Query2,
|
|
23407
|
+
right: Query2,
|
|
23408
|
+
all: a10.boolean().optional(),
|
|
23409
|
+
order: a10.array(a10.ref("Order")).optional(),
|
|
23410
|
+
limit: a10.ref("Limit").optional(),
|
|
23411
|
+
offset: a10.ref("Limit").optional()
|
|
23412
|
+
}).describe("A UNION / INTERSECT / EXCEPT set operation."),
|
|
23413
|
+
Query_cte: a10.object({
|
|
23414
|
+
kind: a10.literal("cte"),
|
|
23415
|
+
ctes: a10.array(a10.union([
|
|
23416
|
+
a10.object({ name: a10.string(), query: Query2 }).describe("A non-recursive CTE."),
|
|
23417
|
+
a10.object({ name: a10.string(), base: Query2, recursive: Query2 }).describe("A recursive CTE: a base seed UNION-ed with a recursive arm.")
|
|
23418
|
+
])),
|
|
23419
|
+
final: Query2
|
|
23420
|
+
}).describe("A WITH (CTE) statement."),
|
|
23421
|
+
Query_expr: a10.object({ kind: a10.literal("expr"), expr: Expr9 }).describe("A single-expression query."),
|
|
23422
|
+
// INSERT ON CONFLICT DO UPDATE may also name the proposed row.
|
|
23423
|
+
Expr_excluded: a10.object({ kind: a10.literal("excluded"), field: a10.string() }).describe("The proposed row inside ON CONFLICT DO UPDATE (EXCLUDED.<field>)."),
|
|
23424
|
+
ConflictExpr: a10.union([Expr9, a10.ref("Expr_excluded")])
|
|
23425
|
+
};
|
|
23426
|
+
var QueryGrammarBuild = class {
|
|
23427
|
+
constructor(registry, types, depth, selected) {
|
|
23428
|
+
this.registry = registry;
|
|
23429
|
+
this.types = types;
|
|
23430
|
+
this.depth = depth;
|
|
23431
|
+
this.selected = selected;
|
|
23432
|
+
}
|
|
23433
|
+
registry;
|
|
23434
|
+
types;
|
|
23435
|
+
depth;
|
|
23436
|
+
selected;
|
|
23437
|
+
/** The shared named fragments built so far (they join the module's named types). */
|
|
23438
|
+
defs = {};
|
|
23439
|
+
byKey = /* @__PURE__ */ new Map();
|
|
23440
|
+
baseUses = /* @__PURE__ */ new Map();
|
|
23441
|
+
/** `a.ref('Expr')`: any expression. */
|
|
23442
|
+
get Expr() {
|
|
23443
|
+
return Expr9;
|
|
23444
|
+
}
|
|
23445
|
+
/** `a.ref('Query')`: any query. */
|
|
23446
|
+
get Query() {
|
|
23447
|
+
return Query2;
|
|
23448
|
+
}
|
|
23449
|
+
/** One named type per distinct content (`Fields_user`, `Args_2`…); its ref. */
|
|
23450
|
+
shared(contentKey, idBase, build) {
|
|
23451
|
+
let id = this.byKey.get(contentKey);
|
|
23452
|
+
if (!id) {
|
|
23453
|
+
const used = this.baseUses.get(idBase) ?? 0;
|
|
23454
|
+
this.baseUses.set(idBase, used + 1);
|
|
23455
|
+
id = used === 0 ? idBase : `${idBase}_${used + 1}`;
|
|
23456
|
+
this.byKey.set(contentKey, id);
|
|
23457
|
+
this.defs[id] = build();
|
|
23458
|
+
}
|
|
23459
|
+
return a10.refOf(id);
|
|
23460
|
+
}
|
|
23461
|
+
/** A shared `Fields_<Type>` enum over these field names. */
|
|
23462
|
+
fieldEnum(names, hint) {
|
|
23463
|
+
return this.shared(`fields\0${names.join("\0")}`, `Fields_${hint}`, () => a10.enum(names));
|
|
23464
|
+
}
|
|
23465
|
+
/** A shared strict args object per argument signature (not per function). */
|
|
23466
|
+
typedArgs(fn2) {
|
|
23467
|
+
const params = fn2.params.map((p) => `${p.name}${p.optional ? "?" : ""}`);
|
|
23468
|
+
return this.shared(`args ${params.join(",")}`, "Args", () => {
|
|
23469
|
+
const shape = {};
|
|
23470
|
+
for (const p of fn2.params) shape[p.name] = p.optional ? Expr9.optional() : Expr9;
|
|
23471
|
+
return a10.object(shape).strict().describe(`Named arguments: ${params.length ? params.join(", ") : "none"}.`);
|
|
23472
|
+
});
|
|
23473
|
+
}
|
|
23474
|
+
/**
|
|
23475
|
+
* A `{ key, field(s) }` reference at a `RefDepth`: free strings (`open`),
|
|
23476
|
+
* the key or the field (or both) enumerated (`types` / `fields` / `both`),
|
|
23477
|
+
* or one branch per Type pairing its name with only its fields (`paired`).
|
|
23478
|
+
*/
|
|
23479
|
+
ref(depth, o) {
|
|
23480
|
+
const fieldProp = (value2) => {
|
|
23481
|
+
switch (o.fieldMode) {
|
|
23482
|
+
case "none":
|
|
23483
|
+
return {};
|
|
23484
|
+
case "one":
|
|
23485
|
+
return { field: value2.describe("A field of the referenced source.") };
|
|
23486
|
+
case "optional":
|
|
23487
|
+
return { field: a10.optional(value2).describe("A field to narrow to (omit for the whole source).") };
|
|
23488
|
+
case "list":
|
|
23489
|
+
return { fields: a10.array(value2).optional().describe("Optional allowlist of fields the reference may touch.") };
|
|
23490
|
+
}
|
|
23491
|
+
};
|
|
23492
|
+
if (depth === "paired") {
|
|
23493
|
+
return a10.union(this.types.map((t) => {
|
|
23494
|
+
const names2 = o.eligible(t).map((f) => f.name);
|
|
23495
|
+
const field2 = names2.length ? this.fieldEnum(names2, t.name) : a10.string();
|
|
23496
|
+
const key2 = a10.literal(t.name).describe(`The \`${t.name}\` ${o.keyName} (its Type name).`);
|
|
23497
|
+
return a10.object({ [o.keyName]: key2, ...fieldProp(field2), ...o.extras }).describe(`A reference into \`${t.name}\`.`);
|
|
23498
|
+
})).describe(o.describe);
|
|
23499
|
+
}
|
|
23500
|
+
const enumKey = depth === "types" || depth === "both";
|
|
23501
|
+
const enumField = depth === "fields" || depth === "both";
|
|
23502
|
+
const noun = o.keyName === "type" ? "a registered Type name" : "a bound source name";
|
|
23503
|
+
const key = (enumKey ? a10.enum(this.types.map((t) => t.name)) : a10.string()).describe(enumKey ? `${noun[0].toUpperCase()}${noun.slice(1)}.` : `A ${o.keyName} name.`);
|
|
23504
|
+
const names = [...new Set(this.types.flatMap((t) => o.eligible(t).map((f) => f.name)))];
|
|
23505
|
+
const field = enumField && names.length ? this.fieldEnum(names, "any") : a10.string();
|
|
23506
|
+
return a10.object({ [o.keyName]: key, ...fieldProp(field), ...o.extras }).describe(o.describe);
|
|
23507
|
+
}
|
|
23508
|
+
/** A function-call kind at the `functions` depth: `open` as given, `names` (an enum), `typed` (a branch per function). */
|
|
23509
|
+
fn(kind, open) {
|
|
23510
|
+
const depth = this.depth.functions;
|
|
23511
|
+
if (depth === "open") return open;
|
|
23512
|
+
const shape = kind === "function-call" ? "scalar" : kind === "tabular-function-call" ? "tabular" : kind;
|
|
23513
|
+
const fns = this.selected[shape];
|
|
23514
|
+
const object = (fnField, args) => {
|
|
23515
|
+
const k = a10.literal(kind);
|
|
23516
|
+
switch (kind) {
|
|
23517
|
+
case "function-call":
|
|
23518
|
+
return a10.object({ kind: k, function: fnField, args }).describe("A scalar function call with named arguments.");
|
|
23519
|
+
case "tabular-function-call":
|
|
23520
|
+
return a10.object({ kind: k, function: fnField, args }).describe("A type-valued function call (produces rows).");
|
|
23521
|
+
case "aggregate":
|
|
23522
|
+
return a10.object({ kind: k, function: fnField, args, distinct: a10.boolean().optional() }).describe("Aggregate function over named args (count with empty args = count(*)).");
|
|
23523
|
+
case "window":
|
|
23524
|
+
return a10.object({
|
|
23525
|
+
kind: k,
|
|
23526
|
+
function: fnField,
|
|
23527
|
+
args,
|
|
23528
|
+
partitionBy: a10.array(Expr9).optional(),
|
|
23529
|
+
orderBy: a10.array(a10.object({ expr: Expr9, dir, nulls: nulls.optional() })).optional()
|
|
23530
|
+
}).describe("Window function over a partition / ordering, with named args.");
|
|
23531
|
+
}
|
|
23532
|
+
};
|
|
23533
|
+
if (depth === "names") {
|
|
23534
|
+
return object(a10.enum(fns.map((f) => f.name)).describe("A selected function name."), a10.record(Expr9).describe("Arguments keyed by declared parameter name."));
|
|
23535
|
+
}
|
|
23536
|
+
return a10.union(fns.map((f) => {
|
|
23537
|
+
const args = this.typedArgs(f);
|
|
23538
|
+
const required = f.params.some((p) => !p.optional);
|
|
23539
|
+
return object(a10.literal(f.name).describe(`The \`${f.name}\` function.`), required ? args : a10.default(args, {}));
|
|
23540
|
+
}));
|
|
23541
|
+
}
|
|
23542
|
+
/** A Type-name position: an enum over `subset` when `typeNames: 'enum'`, else a string. */
|
|
23543
|
+
typeName(subset, describe) {
|
|
23544
|
+
return this.depth.typeNames === "enum" ? a10.enum(subset.map((t) => t.name)).describe(describe) : a10.string().describe("A Type name.");
|
|
23545
|
+
}
|
|
23546
|
+
/** The backing of `type.field`, for the write model. */
|
|
23547
|
+
backing(type, field) {
|
|
23548
|
+
return this.registry.backing(type.name)?.fields?.[field.name];
|
|
23549
|
+
}
|
|
23550
|
+
/** A field's write value: its typed value or an expression (`typed`), an expression (`names`). */
|
|
23551
|
+
writeValue(field, writes, expr) {
|
|
23552
|
+
return writes === "typed" ? a10.union([field.fieldType.toA(), expr]).describe(`A ${field.fieldType.kind} value, or an expression.`) : expr;
|
|
23553
|
+
}
|
|
23554
|
+
/** A strict INSERT row: insertable fields only; at `typed`, the required-on-insert ones required. */
|
|
23555
|
+
insertRow(t, writes, expr) {
|
|
23556
|
+
const shape = {};
|
|
23557
|
+
for (const f of t.fields) {
|
|
23558
|
+
const fb = this.backing(t, f);
|
|
23559
|
+
if (!f.insertableFor(fb)) continue;
|
|
23560
|
+
const v = this.writeValue(f, writes, expr);
|
|
23561
|
+
shape[f.name] = writes === "typed" && requiredOnInsert(f, fb) ? v : a10.optional(v);
|
|
23562
|
+
}
|
|
23563
|
+
return a10.object(shape).strict().describe(`A row to insert into ${t.name} (field \u2192 value).`);
|
|
23564
|
+
}
|
|
23565
|
+
/** A strict UPDATE SET: updatable fields only, every key optional. */
|
|
23566
|
+
updateSet(t, writes, expr) {
|
|
23567
|
+
const shape = {};
|
|
23568
|
+
for (const f of t.fields) if (f.updatableFor(this.backing(t, f))) shape[f.name] = a10.optional(this.writeValue(f, writes, expr));
|
|
23569
|
+
return a10.object(shape).strict().describe(`Fields to set on ${t.name} (field \u2192 value).`);
|
|
23570
|
+
}
|
|
23571
|
+
};
|
|
23572
|
+
var named = (args) => args.describe("Arguments keyed by declared parameter name.");
|
|
23573
|
+
var BUILTIN_BRANCHES = {
|
|
23574
|
+
literal: () => a10.ref("Expr_literal"),
|
|
23575
|
+
"field-ref": (b) => b.ref(b.depth.refs, {
|
|
23576
|
+
keyName: "source",
|
|
23577
|
+
fieldMode: "one",
|
|
23578
|
+
eligible: allowingExpr(allFields, "field-ref"),
|
|
23579
|
+
extras: { kind: a10.literal("field-ref") },
|
|
23580
|
+
describe: "A direct field reference."
|
|
23581
|
+
}),
|
|
23582
|
+
param: () => a10.ref("Expr_param"),
|
|
23583
|
+
binary: () => a10.ref("Expr_binary"),
|
|
23584
|
+
unary: () => a10.ref("Expr_unary"),
|
|
23585
|
+
comparison: () => a10.ref("Expr_comparison"),
|
|
23586
|
+
logical: () => a10.ref("Expr_logical"),
|
|
23587
|
+
in: () => a10.ref("Expr_in"),
|
|
23588
|
+
between: () => a10.ref("Expr_between"),
|
|
23589
|
+
"is-null": () => a10.ref("Expr_is-null"),
|
|
23590
|
+
exists: () => a10.ref("Expr_exists"),
|
|
23591
|
+
"array-op": () => a10.ref("Expr_array-op"),
|
|
23592
|
+
case: () => a10.ref("Expr_case"),
|
|
23593
|
+
aggregate: (b) => b.fn("aggregate", a10.object({
|
|
23594
|
+
kind: a10.literal("aggregate"),
|
|
23595
|
+
function: a10.string().describe("Registered aggregate function name (count for count(*))."),
|
|
23596
|
+
args: named(a10.record(Expr9)),
|
|
23597
|
+
distinct: a10.boolean().optional()
|
|
23598
|
+
}).describe("Aggregate function over named args (count with empty args = count(*)).")),
|
|
23599
|
+
window: (b) => b.fn("window", a10.object({
|
|
23600
|
+
kind: a10.literal("window"),
|
|
23601
|
+
function: a10.string().describe("Registered window (or aggregate) function name."),
|
|
23602
|
+
args: named(a10.record(Expr9)),
|
|
23603
|
+
partitionBy: a10.array(Expr9).optional(),
|
|
23604
|
+
orderBy: a10.array(a10.object({ expr: Expr9, dir, nulls: nulls.optional() })).optional()
|
|
23605
|
+
}).describe("Window function over a partition / ordering, with named args.")),
|
|
23606
|
+
"function-call": (b) => b.fn("function-call", a10.object({
|
|
23607
|
+
kind: a10.literal("function-call"),
|
|
23608
|
+
function: a10.string().describe("Registered scalar function name."),
|
|
23609
|
+
args: named(a10.record(Expr9))
|
|
23610
|
+
}).describe("A scalar function call with named arguments.")),
|
|
23611
|
+
"tabular-function-call": (b) => b.fn("tabular-function-call", a10.object({
|
|
23612
|
+
kind: a10.literal("tabular-function-call"),
|
|
23613
|
+
function: a10.string().describe("Registered tabular function name."),
|
|
23614
|
+
args: named(a10.record(Expr9))
|
|
23615
|
+
}).describe("A type-valued function call (produces rows).")),
|
|
23616
|
+
// `op` enum-locked past `open`, with each operator's signature and instructions; strict operands at `typed`.
|
|
23617
|
+
operator: (b) => {
|
|
23618
|
+
const ops = b.registry.operatorList();
|
|
23619
|
+
if (b.depth.functions === "open" || !ops.length) {
|
|
23620
|
+
return a10.object({ kind: a10.literal("operator"), op: a10.string().describe("Registered operator name."), args: named(a10.record(Expr9)) }).describe("A registered operator applied to named operands.");
|
|
23621
|
+
}
|
|
23622
|
+
const glossary = ops.map((o) => `${signatureOf(o)} \u2014 ${o.instructions}`).join(" ");
|
|
23623
|
+
if (b.depth.functions === "names") {
|
|
23624
|
+
return a10.object({ kind: a10.literal("operator"), op: a10.enum(ops.map((o) => o.name)).describe(`A registered operator. ${glossary}`), args: named(a10.record(Expr9)) }).describe("A registered operator applied to named operands.");
|
|
23625
|
+
}
|
|
23626
|
+
return a10.union(ops.map((o) => a10.object({
|
|
23627
|
+
kind: a10.literal("operator"),
|
|
23628
|
+
op: a10.literal(o.name).describe(`${signatureOf(o)} \u2014 ${o.instructions}`),
|
|
23629
|
+
args: a10.object(Object.fromEntries(o.operands.map((n) => [n.name, Expr9]))).strict().describe(`Operands for \`${o.name}\`.`)
|
|
23630
|
+
}))).describe("A registered operator applied to named operands.");
|
|
23631
|
+
},
|
|
23632
|
+
semantic: (b) => b.ref(b.depth.refs, {
|
|
23633
|
+
keyName: "source",
|
|
23634
|
+
fieldMode: "optional",
|
|
23635
|
+
eligible: allowingExpr(semanticFieldsOf, "semantic"),
|
|
23636
|
+
extras: {
|
|
23637
|
+
kind: a10.literal("semantic"),
|
|
23638
|
+
query: a10.union([
|
|
23639
|
+
a10.string().describe("A literal natural-language query."),
|
|
23640
|
+
a10.ref("param"),
|
|
23641
|
+
b.ref(b.depth.refs, { keyName: "source", fieldMode: "one", eligible: semanticFieldsOf, describe: "Another BOUND source + semantic field whose embedding is the query vector (cross-source pairing)." }),
|
|
23642
|
+
b.ref(b.depth.refs, { keyName: "type", fieldMode: "one", eligible: semanticFieldsOf, describe: "A semantic Type + field, resolved to that Type's single bound source, whose embedding is the query vector." })
|
|
23643
|
+
]).describe("The query: text, a param, a bound source+field, or a semantic Type+field.")
|
|
23644
|
+
},
|
|
23645
|
+
describe: "Semantic-similarity score (requires an embedder)."
|
|
23646
|
+
}),
|
|
23647
|
+
"text-search": (b) => b.ref(b.depth.refs, {
|
|
23648
|
+
keyName: "source",
|
|
23649
|
+
fieldMode: "optional",
|
|
23650
|
+
eligible: allowingExpr(textFieldsOf, "text-search"),
|
|
23651
|
+
extras: { kind: a10.literal("text-search"), query: a10.union([a10.string(), a10.ref("param")]).describe("Search query: a literal string or a param.") },
|
|
23652
|
+
describe: "Full-text search predicate."
|
|
23653
|
+
}),
|
|
23654
|
+
"text-score": (b) => b.ref(b.depth.refs, {
|
|
23655
|
+
keyName: "source",
|
|
23656
|
+
fieldMode: "optional",
|
|
23657
|
+
eligible: allowingExpr(textFieldsOf, "text-score"),
|
|
23658
|
+
extras: { kind: a10.literal("text-score"), query: a10.union([a10.string(), a10.ref("param")]).describe("Search query: a literal string or a param.") },
|
|
23659
|
+
describe: "Numeric full-text relevance score (usable in SELECT / ORDER BY)."
|
|
23660
|
+
}),
|
|
23661
|
+
filters: (b) => b.ref(b.depth.filters, {
|
|
23662
|
+
keyName: "source",
|
|
23663
|
+
fieldMode: "list",
|
|
23664
|
+
eligible: allowingExpr(allFields, "filters"),
|
|
23665
|
+
extras: { kind: a10.literal("filters") },
|
|
23666
|
+
describe: "A structured filter placeholder; clauses are supplied at execution time."
|
|
23667
|
+
}),
|
|
23668
|
+
subquery: () => a10.ref("Expr_subquery")
|
|
23669
|
+
};
|
|
23670
|
+
var typesOf = (registry, o) => o.types ?? registry.typeList();
|
|
23671
|
+
function grammarDefs(registry, options) {
|
|
23672
|
+
registry.finalize();
|
|
23673
|
+
const types = typesOf(registry, options);
|
|
23674
|
+
const selected = selectFunctions(registry, options.functions);
|
|
23675
|
+
const depth = resolveDepthFor(types, selected, options);
|
|
23676
|
+
const b = new QueryGrammarBuild(registry, types, depth, selected);
|
|
23677
|
+
const exprOptions = [];
|
|
23678
|
+
for (const cls of registry.exprClassList()) {
|
|
23679
|
+
if (!exprKindApplicable(cls.KIND, types, selected, registry)) continue;
|
|
23680
|
+
const builtin = BUILTIN_BRANCHES[cls.KIND];
|
|
23681
|
+
const branch = builtin ? builtin(b) : cls.toA?.(b);
|
|
23682
|
+
if (branch) exprOptions.push(branch);
|
|
23683
|
+
}
|
|
23684
|
+
const typeRef = b.typeName(types, "A registered Type name.");
|
|
23685
|
+
const sources = [
|
|
23686
|
+
a10.object({ kind: a10.literal("type"), type: typeRef }).describe("A type source, bound under (and referenced by) its type name."),
|
|
23687
|
+
a10.object({ kind: a10.literal("aliased"), type: typeRef, as: a10.string().describe("Custom source name (self-join / collision break).") }).describe("An explicitly-aliased type source (the discouraged escape hatch)."),
|
|
23688
|
+
a10.object({ kind: a10.literal("subquery"), query: Query2, as: a10.string().describe("Required alias for the derived source.") }).describe("A derived (subquery) source.")
|
|
23689
|
+
];
|
|
23690
|
+
if (selected.tabular.length) {
|
|
23691
|
+
const fnName = depth.functions === "open" ? a10.string().describe("A registered tabular function name.") : a10.enum(selected.tabular.map((f) => f.name)).describe("A registered tabular function name.");
|
|
23692
|
+
sources.push(a10.object({
|
|
23693
|
+
kind: a10.literal("function"),
|
|
23694
|
+
function: fnName,
|
|
23695
|
+
args: a10.record(Expr9).describe("Arguments keyed by declared parameter name."),
|
|
23696
|
+
as: a10.string().describe("Required alias the produced rows bind under.")
|
|
23697
|
+
}).describe("A table-valued function source: FROM fn(args) AS alias."));
|
|
23698
|
+
}
|
|
23699
|
+
const Source = a10.union(sources).describe("A FROM / JOIN source: a type, an aliased type, a subquery, or a table-valued function.");
|
|
23700
|
+
const hasRelations = types.some((t) => t.relationFields().length > 0);
|
|
23701
|
+
const relationOn = b.ref(depth.refs, {
|
|
23702
|
+
keyName: "source",
|
|
23703
|
+
fieldMode: "one",
|
|
23704
|
+
eligible: relationFieldsOf,
|
|
23705
|
+
extras: { kind: a10.literal("relation"), as: a10.string().describe("Required alias the joined target binds under.") },
|
|
23706
|
+
describe: "Cross a relation field of a bound source (key synthesized from the relation)."
|
|
23707
|
+
});
|
|
23708
|
+
const JoinOn = (hasRelations ? a10.union([relationOn, a10.ref("Source")]) : a10.ref("Source")).describe("A join target: a relation crossing or a manually-joined source.");
|
|
23709
|
+
const Joins = hasRelations ? a10.array(a10.ref("Join")) : a10.array(a10.never());
|
|
23710
|
+
const insertable = types.filter((t) => t.insertable);
|
|
23711
|
+
const updatable = types.filter((t) => t.updatable);
|
|
23712
|
+
const deletable = types.filter((t) => t.deletable);
|
|
23713
|
+
const writes = depth.writes;
|
|
23714
|
+
const conflict = (t) => a10.object({
|
|
23715
|
+
fields: a10.array(a10.string()),
|
|
23716
|
+
doNothing: a10.boolean().optional(),
|
|
23717
|
+
update: a10.optional(writes !== "open" && t ? b.updateSet(t, writes, a10.ref("ConflictExpr")) : a10.record(a10.ref("ConflictExpr")).describe("DO UPDATE SET assignments (field \u2192 value)."))
|
|
23718
|
+
});
|
|
23719
|
+
const returning = a10.array(a10.ref("SelectField")).optional();
|
|
23720
|
+
const Insert = writes === "open" ? a10.object({
|
|
23721
|
+
kind: a10.literal("insert"),
|
|
23722
|
+
into: b.typeName(insertable, "A permitted target Type name."),
|
|
23723
|
+
rows: a10.array(a10.record(Expr9)).optional().describe("Rows to insert (each a field \u2192 value map)."),
|
|
23724
|
+
select: Query2.optional(),
|
|
23725
|
+
returning,
|
|
23726
|
+
onConflict: conflict().optional()
|
|
23727
|
+
}).describe("An INSERT statement.") : a10.union(insertable.map((t) => a10.object({
|
|
23728
|
+
kind: a10.literal("insert"),
|
|
23729
|
+
into: a10.literal(t.name),
|
|
23730
|
+
rows: a10.array(b.insertRow(t, writes, Expr9)).optional(),
|
|
23731
|
+
select: Query2.optional(),
|
|
23732
|
+
returning,
|
|
23733
|
+
onConflict: conflict(t).optional()
|
|
23734
|
+
}).describe(`An INSERT into ${t.name}.`))).describe("An INSERT statement.");
|
|
23735
|
+
const Update = writes === "open" ? a10.object({
|
|
23736
|
+
kind: a10.literal("update"),
|
|
23737
|
+
type: b.typeName(updatable, "A permitted target Type name."),
|
|
23738
|
+
set: a10.record(Expr9).describe("Fields to set (field \u2192 value)."),
|
|
23739
|
+
joins: a10.ref("Joins").optional(),
|
|
23740
|
+
where: a10.array(Expr9).optional(),
|
|
23741
|
+
returning
|
|
23742
|
+
}).describe("An UPDATE statement.") : a10.union(updatable.map((t) => a10.object({
|
|
23743
|
+
kind: a10.literal("update"),
|
|
23744
|
+
type: a10.literal(t.name),
|
|
23745
|
+
set: b.updateSet(t, writes, Expr9),
|
|
23746
|
+
joins: a10.ref("Joins").optional(),
|
|
23747
|
+
where: a10.array(Expr9).optional(),
|
|
23748
|
+
returning
|
|
23749
|
+
}).describe(`An UPDATE of ${t.name}.`))).describe("An UPDATE statement.");
|
|
23750
|
+
const Delete = a10.object({
|
|
23751
|
+
kind: a10.literal("delete"),
|
|
23752
|
+
from: b.typeName(deletable, "A permitted target Type name."),
|
|
23753
|
+
joins: a10.ref("Joins").optional(),
|
|
23754
|
+
where: a10.array(Expr9).optional(),
|
|
23755
|
+
returning
|
|
23756
|
+
}).describe("A DELETE statement.");
|
|
23757
|
+
const queries = [a10.ref("Query_select")];
|
|
23758
|
+
if (insertable.length) queries.push(a10.ref("Query_insert"));
|
|
23759
|
+
if (updatable.length) queries.push(a10.ref("Query_update"));
|
|
23760
|
+
if (deletable.length) queries.push(a10.ref("Query_delete"));
|
|
23761
|
+
queries.push(a10.ref("Query_set-operation"), a10.ref("Query_cte"), a10.ref("Query_expr"));
|
|
23762
|
+
return {
|
|
23763
|
+
...b.defs,
|
|
23764
|
+
TypeName: typeRef,
|
|
23765
|
+
Expr: a10.union(exprOptions),
|
|
23766
|
+
Query: a10.union(queries).describe("Any query: select / insert / update / delete / set-op / cte / expr."),
|
|
23767
|
+
Source,
|
|
23768
|
+
JoinOn,
|
|
23769
|
+
Joins,
|
|
23770
|
+
Query_insert: Insert,
|
|
23771
|
+
Query_update: Update,
|
|
23772
|
+
Query_delete: Delete
|
|
23773
|
+
};
|
|
23774
|
+
}
|
|
23775
|
+
var QUERY_BIND_CACHE_SIZE = 4;
|
|
23776
|
+
var nextRegistryId = 0;
|
|
23777
|
+
var registryIds = /* @__PURE__ */ new WeakMap();
|
|
23778
|
+
var idOf = (r) => {
|
|
23779
|
+
let id = registryIds.get(r);
|
|
23780
|
+
if (id === void 0) registryIds.set(r, id = ++nextRegistryId);
|
|
23781
|
+
return id;
|
|
23782
|
+
};
|
|
23783
|
+
function optionsKey(o = {}) {
|
|
23784
|
+
return JSON.stringify([o.depth ?? null, o.functions ?? null, o.maxEnumSize ?? null, o.strict ?? null, o.types?.map((t) => t.name) ?? null]);
|
|
23785
|
+
}
|
|
23786
|
+
var grammarKey = (registry, options = {}) => `${idOf(registry)}.${registry.version}|${optionsKey(options)}`;
|
|
23787
|
+
var defsMemo = /* @__PURE__ */ new WeakMap();
|
|
23788
|
+
function memoDefs(registry, options = {}) {
|
|
23789
|
+
let byKey = defsMemo.get(registry);
|
|
23790
|
+
if (!byKey) defsMemo.set(registry, byKey = /* @__PURE__ */ new Map());
|
|
23791
|
+
const key = grammarKey(registry, options);
|
|
23792
|
+
let defs = byKey.get(key);
|
|
23793
|
+
if (defs) {
|
|
23794
|
+
byKey.delete(key);
|
|
23795
|
+
byKey.set(key, defs);
|
|
23796
|
+
return defs;
|
|
23797
|
+
}
|
|
23798
|
+
defs = grammarDefs(registry, options);
|
|
23799
|
+
byKey.set(key, defs);
|
|
23800
|
+
while (byKey.size > QUERY_BIND_CACHE_SIZE) byKey.delete(byKey.keys().next().value);
|
|
23801
|
+
return defs;
|
|
23802
|
+
}
|
|
23803
|
+
var QueryGrammar = a10.define(grammar).declare().dynamic((registry, options) => memoDefs(registry, options), { key: grammarKey, cacheSize: QUERY_BIND_CACHE_SIZE });
|
|
23804
|
+
var QueryResult = QueryGrammar.result("Query");
|
|
23805
|
+
var ExprResult = QueryGrammar.result("Expr");
|
|
23806
|
+
var QUERY_RESULTS = {
|
|
23807
|
+
Type: QueryGrammar.result("TypeName"),
|
|
23808
|
+
Expr: ExprResult,
|
|
23809
|
+
Source: QueryGrammar.result("Source"),
|
|
23810
|
+
Join: QueryGrammar.result("Join"),
|
|
23811
|
+
Order: QueryGrammar.result("Order"),
|
|
23812
|
+
SelectField: QueryGrammar.result("SelectField"),
|
|
23813
|
+
Select: QueryGrammar.result("Query_select"),
|
|
23814
|
+
Insert: QueryGrammar.result("Query_insert"),
|
|
23815
|
+
Update: QueryGrammar.result("Query_update"),
|
|
23816
|
+
Delete: QueryGrammar.result("Query_delete"),
|
|
23817
|
+
SetOperation: QueryGrammar.result("Query_set-operation"),
|
|
23818
|
+
CTE: QueryGrammar.result("Query_cte"),
|
|
23819
|
+
ExprQuery: QueryGrammar.result("Query_expr"),
|
|
23820
|
+
Query: QueryResult
|
|
23821
|
+
};
|
|
23822
|
+
|
|
23823
|
+
// src/llm/schemas.ts
|
|
23824
|
+
function buildSchemas(engineOrRegistry, options = {}) {
|
|
23825
|
+
const registry = toRegistry(engineOrRegistry);
|
|
23826
|
+
const out = {};
|
|
23827
|
+
for (const key of Object.keys(QUERY_RESULTS)) {
|
|
23828
|
+
let bound;
|
|
23829
|
+
Object.defineProperty(out, key, {
|
|
23830
|
+
enumerable: true,
|
|
23831
|
+
get: () => bound ??= QUERY_RESULTS[key].bind(registry, options)
|
|
23832
|
+
});
|
|
23833
|
+
}
|
|
23834
|
+
return out;
|
|
23835
|
+
}
|
|
23836
|
+
var QueryArgs = QueryGrammar.result(a11.object({ query: a11.ref("Query").describe("The query to execute as a structured Query object.") }));
|
|
23837
|
+
var QueryProseArgs = a11.object({
|
|
23838
|
+
query: a11.string().describe(
|
|
23839
|
+
"A detailed natural-language description of the query: which Types are involved, filter conditions, known record IDs, and the precise outcome desired. Do not emit a structured query \u2014 there are too many Types to enumerate."
|
|
23840
|
+
)
|
|
23841
|
+
});
|
|
23842
|
+
function querySchema(engine, options = {}) {
|
|
23843
|
+
const registry = toRegistry(engine);
|
|
23844
|
+
const types = options.types ?? registry.typeList();
|
|
23845
|
+
if (shouldUseStringSchema(types, options.max ?? DEFAULT_MAX_QUERY_SCHEMA_TYPES)) return QueryProseArgs;
|
|
23846
|
+
const args = QueryArgs;
|
|
23847
|
+
return args.adapt(() => [registry, options]);
|
|
23848
|
+
}
|
|
24328
23849
|
|
|
24329
23850
|
// src/llm/describe-generate.ts
|
|
24330
23851
|
function humanize(name) {
|
|
@@ -24646,14 +24167,14 @@ function describeEngine(engine, options = {}) {
|
|
|
24646
24167
|
}
|
|
24647
24168
|
|
|
24648
24169
|
// src/llm/select-types.ts
|
|
24649
|
-
function cosine2(
|
|
24650
|
-
const n = Math.min(
|
|
24170
|
+
function cosine2(a13, b) {
|
|
24171
|
+
const n = Math.min(a13.length, b.length);
|
|
24651
24172
|
if (n === 0) return 0;
|
|
24652
24173
|
let dot = 0;
|
|
24653
24174
|
let magA = 0;
|
|
24654
24175
|
let magB = 0;
|
|
24655
24176
|
for (let i = 0; i < n; i++) {
|
|
24656
|
-
const x =
|
|
24177
|
+
const x = a13[i] ?? 0;
|
|
24657
24178
|
const y = b[i] ?? 0;
|
|
24658
24179
|
dot += x * y;
|
|
24659
24180
|
magA += x * x;
|
|
@@ -24684,12 +24205,13 @@ async function selectTypes(engine, request, options = {}) {
|
|
|
24684
24205
|
score: cosine2(requestVec, await embedder.embed(typeText(type)))
|
|
24685
24206
|
}))
|
|
24686
24207
|
);
|
|
24687
|
-
scored.sort((
|
|
24208
|
+
scored.sort((a13, b) => b.score - a13.score);
|
|
24688
24209
|
return scored.slice(0, topN).map((s) => s.type);
|
|
24689
24210
|
}
|
|
24690
24211
|
|
|
24691
24212
|
// src/llm/tool.ts
|
|
24692
24213
|
import { Tool } from "@aeye/core";
|
|
24214
|
+
import { a as a12, Rejection } from "@aeye/schema";
|
|
24693
24215
|
var QueryToolError = class extends Error {
|
|
24694
24216
|
constructor(problems, report) {
|
|
24695
24217
|
super(report);
|
|
@@ -24704,8 +24226,9 @@ function reportFor(value2, problems, opts) {
|
|
|
24704
24226
|
if (problems.list.length === 0) return "";
|
|
24705
24227
|
return Code.fromJson(value2).formatProblems(problems, opts);
|
|
24706
24228
|
}
|
|
24229
|
+
var NEEDS_STRUCTURING = "Received a prose query; it must be converted to a structured query before it can run.";
|
|
24707
24230
|
function parseQueryInput(engine, useString, raw2, reportOpts) {
|
|
24708
|
-
if (!
|
|
24231
|
+
if (!isRecord2(raw2)) {
|
|
24709
24232
|
const problems2 = new Problems();
|
|
24710
24233
|
problems2.error("shape.not-object", expected("QueryRequest", raw2));
|
|
24711
24234
|
return { query: null, problems: problems2, report: reportFor(raw2, problems2, reportOpts) };
|
|
@@ -24718,10 +24241,7 @@ function parseQueryInput(engine, useString, raw2, reportOpts) {
|
|
|
24718
24241
|
const queryValue = raw2["query"];
|
|
24719
24242
|
if (useString || typeof queryValue === "string") {
|
|
24720
24243
|
const problems2 = new Problems();
|
|
24721
|
-
problems2.info(
|
|
24722
|
-
"query.needs-structuring",
|
|
24723
|
-
"Received a prose query; it must be converted to a structured query before it can run."
|
|
24724
|
-
);
|
|
24244
|
+
problems2.info("query.needs-structuring", NEEDS_STRUCTURING);
|
|
24725
24245
|
return { query: null, problems: problems2, report: reportFor(queryValue, problems2, reportOpts) };
|
|
24726
24246
|
}
|
|
24727
24247
|
const problems = new Problems();
|
|
@@ -24741,11 +24261,35 @@ function parseQueryTool(engine, raw2, options = {}) {
|
|
|
24741
24261
|
const { query, problems, report } = parseQueryRequest(engine, raw2, options);
|
|
24742
24262
|
return query && !problems.hasErrors ? query : new QueryToolError(problems, report);
|
|
24743
24263
|
}
|
|
24264
|
+
function issuesOf(problems) {
|
|
24265
|
+
return problems.list.filter((p) => p.severity === "error").map((p) => ({ path: ["query", ...p.path], message: p.message }));
|
|
24266
|
+
}
|
|
24267
|
+
function queryToolSchema(engine, options = {}) {
|
|
24268
|
+
const types = options.types ?? engine.registry.typeList();
|
|
24269
|
+
if (shouldUseStringSchema(types, options.max)) {
|
|
24270
|
+
const prose = a12.codec(QueryProseArgs, {
|
|
24271
|
+
decode: () => new Rejection([{ path: ["query"], message: NEEDS_STRUCTURING }]),
|
|
24272
|
+
encode: (q) => ({ query: JSON.stringify(q.toJSON()) })
|
|
24273
|
+
});
|
|
24274
|
+
return prose;
|
|
24275
|
+
}
|
|
24276
|
+
const args = a12.codec(a12.object({ query: a12.refOf("Query").describe("The query to execute as a structured Query object.") }), {
|
|
24277
|
+
decode: (v) => {
|
|
24278
|
+
const problems = new Problems();
|
|
24279
|
+
const query = engine.registry.parseCheckedQuery(v.query, problems);
|
|
24280
|
+
if (query === void 0 || problems.hasErrors) return new Rejection(issuesOf(problems));
|
|
24281
|
+
const semantic2 = engine.validateQuery(query);
|
|
24282
|
+
return semantic2.hasErrors ? new Rejection(issuesOf(semantic2)) : query;
|
|
24283
|
+
},
|
|
24284
|
+
encode: (q) => ({ query: q.toJSON() })
|
|
24285
|
+
});
|
|
24286
|
+
const build = options;
|
|
24287
|
+
const bundle = QueryGrammar.result(args);
|
|
24288
|
+
return bundle.adapt(() => [engine.registry, build]);
|
|
24289
|
+
}
|
|
24744
24290
|
function buildQueryTool(engine, options = {}) {
|
|
24745
24291
|
const types = options.types ?? engine.registry.typeList();
|
|
24746
|
-
const
|
|
24747
|
-
const useString = shouldUseStringSchema(types, max2);
|
|
24748
|
-
const schema = querySchema(engine, options);
|
|
24292
|
+
const useString = shouldUseStringSchema(types, options.max);
|
|
24749
24293
|
const depthNote = useString ? "" : depthInstructions(engine, options);
|
|
24750
24294
|
const gatingNote = useString ? "" : "Only expression kinds the available Types and functions can use are offered \u2014 e.g. semantic / text-search / array / join appear ONLY when a Type supports them. Do not invent an unavailable kind.";
|
|
24751
24295
|
const instructions = [
|
|
@@ -24757,21 +24301,14 @@ ${depthNote}` : "",
|
|
|
24757
24301
|
gatingNote ? `
|
|
24758
24302
|
${gatingNote}` : "",
|
|
24759
24303
|
"",
|
|
24760
|
-
// Forward the function selection so the listed functions match the schema.
|
|
24761
|
-
// `describeEngine` now folds in worked examples (per expr kind, function, and
|
|
24762
|
-
// query kind) from the nodes' own `EXAMPLES` — the one source of truth.
|
|
24763
24304
|
describeEngine(engine, { types, functions: options.functions })
|
|
24764
24305
|
].join("\n");
|
|
24765
24306
|
return new Tool({
|
|
24766
24307
|
name: options.name ?? "query",
|
|
24767
24308
|
description: options.description ?? "Execute a structured query (select / insert / update / delete / set-op / cte) over the available Types.",
|
|
24768
24309
|
instructions,
|
|
24769
|
-
schema,
|
|
24770
|
-
|
|
24771
|
-
// SEMANTICALLY validate the query, then return the runnable `Query` (clean)
|
|
24772
|
-
// or a rich `QueryToolError` (problems). Delegates to the STANDALONE
|
|
24773
|
-
// `parseQueryTool` — ONE parse implementation shared with direct callers.
|
|
24774
|
-
parse: (raw2, _ctx) => parseQueryTool(engine, raw2, options),
|
|
24310
|
+
schema: queryToolSchema(engine, options),
|
|
24311
|
+
...options.errorFormat !== void 0 ? { errorFormat: options.errorFormat } : {},
|
|
24775
24312
|
// The handler RUNS the (already-validated) query in-memory.
|
|
24776
24313
|
call: (query, _refs, _ctx) => engine.run(query, options.runtime)
|
|
24777
24314
|
});
|
|
@@ -24843,12 +24380,18 @@ export {
|
|
|
24843
24380
|
PostgresDdl,
|
|
24844
24381
|
PostgresDialect,
|
|
24845
24382
|
Problems,
|
|
24383
|
+
QUERY_BIND_CACHE_SIZE,
|
|
24384
|
+
QUERY_RESULTS,
|
|
24846
24385
|
Query,
|
|
24386
|
+
QueryArgs,
|
|
24847
24387
|
QueryEngine,
|
|
24848
24388
|
QueryFunction,
|
|
24389
|
+
QueryGrammar,
|
|
24390
|
+
QueryGrammarBuild,
|
|
24849
24391
|
QueryJoin,
|
|
24850
24392
|
QueryOperator,
|
|
24851
24393
|
QueryOrder,
|
|
24394
|
+
QueryProseArgs,
|
|
24852
24395
|
QueryScope,
|
|
24853
24396
|
QuerySource,
|
|
24854
24397
|
QueryToolError,
|
|
@@ -24968,7 +24511,6 @@ export {
|
|
|
24968
24511
|
describeTypes,
|
|
24969
24512
|
didYouMean,
|
|
24970
24513
|
differentialCheck,
|
|
24971
|
-
directedMessage,
|
|
24972
24514
|
div,
|
|
24973
24515
|
drillDown,
|
|
24974
24516
|
drillDownInto,
|
|
@@ -24980,7 +24522,6 @@ export {
|
|
|
24980
24522
|
eq,
|
|
24981
24523
|
excluded,
|
|
24982
24524
|
exists,
|
|
24983
|
-
exprDefSchema,
|
|
24984
24525
|
exprDigest,
|
|
24985
24526
|
fieldMeta,
|
|
24986
24527
|
fieldNameOf,
|
|
@@ -25059,6 +24600,7 @@ export {
|
|
|
25059
24600
|
queryArgProblems,
|
|
25060
24601
|
queryArgsType,
|
|
25061
24602
|
querySchema,
|
|
24603
|
+
queryToolSchema,
|
|
25062
24604
|
ratio,
|
|
25063
24605
|
raw,
|
|
25064
24606
|
readCommonType,
|
|
@@ -25140,7 +24682,6 @@ export {
|
|
|
25140
24682
|
when,
|
|
25141
24683
|
widenNullable,
|
|
25142
24684
|
window2 as window,
|
|
25143
|
-
withAid,
|
|
25144
24685
|
withArgDefaults,
|
|
25145
24686
|
year
|
|
25146
24687
|
};
|