@query-farm/vgi 0.47.1 → 0.47.2
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/dist/catalog/column-expressions.d.ts +22 -1
- package/dist/catalog/column-metadata.d.ts +7 -0
- package/dist/catalog/column-types.d.ts +15 -0
- package/dist/catalog/composite.d.ts +2 -0
- package/dist/catalog/constraints.d.ts +110 -12
- package/dist/catalog/descriptors.d.ts +19 -1
- package/dist/catalog/indexes.d.ts +29 -0
- package/dist/catalog/interface.d.ts +41 -0
- package/dist/catalog/public-codecs.d.ts +6 -0
- package/dist/catalog/read-only.d.ts +3 -0
- package/dist/catalog/sql-grammar.d.ts +53 -0
- package/dist/catalog/unconstrained-columns.d.ts +8 -0
- package/dist/client/types.d.ts +5 -1
- package/dist/client-entry.d.ts +1 -0
- package/dist/client-entry.js +1410 -152
- package/dist/client-entry.js.map +12 -8
- package/dist/index.core.d.ts +1 -1
- package/dist/index.js +1681 -411
- package/dist/index.js.map +19 -16
- package/dist/serve-entry.js +1095 -49
- package/dist/serve-entry.js.map +13 -11
- package/dist/worker-cf-entry.d.ts +2 -1
- package/dist/worker-cf-entry.js +1459 -182
- package/dist/worker-cf-entry.js.map +19 -16
- package/package.json +1 -1
- package/src/catalog/column-expressions.ts +85 -7
- package/src/catalog/column-metadata.ts +20 -2
- package/src/catalog/column-types.ts +50 -0
- package/src/catalog/composite.ts +10 -0
- package/src/catalog/constraints.ts +496 -58
- package/src/catalog/contents-codec.ts +3 -3
- package/src/catalog/descriptors.ts +19 -1
- package/src/catalog/indexes.ts +59 -0
- package/src/catalog/interface.ts +103 -1
- package/src/catalog/public-codecs.ts +36 -0
- package/src/catalog/read-only.ts +92 -36
- package/src/catalog/sql-grammar.ts +476 -0
- package/src/catalog/unconstrained-columns.ts +34 -8
- package/src/client/client.ts +6 -3
- package/src/client/types.ts +5 -1
- package/src/client-entry.ts +4 -0
- package/src/index.core.ts +2 -1
- package/src/protocol/handlers/catalog/admin.ts +14 -13
- package/src/protocol/handlers/catalog/table.ts +58 -11
- package/src/worker-cf-entry.ts +2 -4
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
// Copyright 2026 Query Farm LLC - https://query.farm
|
|
2
|
+
// The bounded DuckDB scalar grammars the vgi extension accepts for column
|
|
3
|
+
// expressions (vgi_column_expression.cpp: Parse/Scalar) and native CHECK
|
|
4
|
+
// constraints (vgi_constraint_contract.cpp: ParseNumericCheck). A worker that
|
|
5
|
+
// states something outside them fails ATTACH; checking here names the table and
|
|
6
|
+
// column in the worker's own tests instead. This is a conservative recognizer,
|
|
7
|
+
// not a DuckDB parser: anything it does not understand is refused.
|
|
8
|
+
|
|
9
|
+
export type LiteralType = "NULL" | "BOOLEAN" | "INTEGER" | "BIGINT" | "HUGEINT" | "DECIMAL" | "DOUBLE" | "VARCHAR";
|
|
10
|
+
|
|
11
|
+
export type ScalarNode =
|
|
12
|
+
| { kind: "constant"; type: LiteralType }
|
|
13
|
+
| { kind: "column"; names: string[] }
|
|
14
|
+
| { kind: "cast"; type: string | null; qualified: boolean; child: ScalarNode }
|
|
15
|
+
| { kind: "comparison"; op: string; left: ScalarNode; right: ScalarNode }
|
|
16
|
+
| { kind: "conjunction"; op: "AND" | "OR"; children: ScalarNode[] }
|
|
17
|
+
| { kind: "operator"; op: "NOT" | "IS_NULL" | "IS_NOT_NULL" | "COALESCE"; children: ScalarNode[] }
|
|
18
|
+
| { kind: "function"; name: string; qualified: boolean; children: ScalarNode[] };
|
|
19
|
+
|
|
20
|
+
type Token =
|
|
21
|
+
| { t: "num"; v: string }
|
|
22
|
+
| { t: "str"; v: string }
|
|
23
|
+
| { t: "ident"; v: string; quoted: boolean }
|
|
24
|
+
| { t: "op"; v: string }
|
|
25
|
+
| { t: "end" };
|
|
26
|
+
|
|
27
|
+
class GrammarError extends Error {}
|
|
28
|
+
const fail = (message: string): never => {
|
|
29
|
+
throw new GrammarError(message);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// Words the DuckDB grammar never reads as a bare column reference here.
|
|
33
|
+
const RESERVED = new Set([
|
|
34
|
+
"all", "and", "any", "array", "as", "asc", "between", "both", "case", "cast", "check", "collate", "column",
|
|
35
|
+
"constraint", "create", "default", "desc", "distinct", "do", "else", "end", "except", "false", "fetch", "for",
|
|
36
|
+
"foreign", "from", "glob", "grant", "group", "having", "ilike", "in", "intersect", "interval", "into", "is",
|
|
37
|
+
"isnull", "like", "limit", "not", "notnull", "null", "offset", "on", "or", "order", "primary", "references",
|
|
38
|
+
"returning", "select", "similar", "some", "table", "then", "to", "true", "try_cast", "union", "unique", "using",
|
|
39
|
+
"when", "where", "window", "with",
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
const OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
|
|
43
|
+
|
|
44
|
+
function tokenize(sql: string): Token[] {
|
|
45
|
+
const out: Token[] = [];
|
|
46
|
+
let i = 0;
|
|
47
|
+
while (i < sql.length) {
|
|
48
|
+
const c = sql[i];
|
|
49
|
+
if (/\s/.test(c)) { i++; continue; }
|
|
50
|
+
if (sql.startsWith("--", i)) {
|
|
51
|
+
while (i < sql.length && sql[i] !== "\n") i++;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (sql.startsWith("/*", i)) {
|
|
55
|
+
const close = sql.indexOf("*/", i + 2);
|
|
56
|
+
if (close < 0) fail("unterminated comment");
|
|
57
|
+
i = close + 2;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (/[0-9]/.test(c) || (c === "." && /[0-9]/.test(sql[i + 1] ?? ""))) {
|
|
61
|
+
const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i))!;
|
|
62
|
+
if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? "")) fail("unsupported numeric literal");
|
|
63
|
+
out.push({ t: "num", v: m[0] });
|
|
64
|
+
i += m[0].length;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (c === "'" || c === '"') {
|
|
68
|
+
let j = i + 1, text = "";
|
|
69
|
+
for (;;) {
|
|
70
|
+
if (j >= sql.length) fail("unterminated quoted text");
|
|
71
|
+
if (sql[j] === c) {
|
|
72
|
+
if (sql[j + 1] === c) { text += c; j += 2; continue; }
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
text += sql[j++];
|
|
76
|
+
}
|
|
77
|
+
out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
|
|
78
|
+
i = j + 1;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (/[A-Za-z_\u0080-]/.test(c)) {
|
|
82
|
+
const m = /^[A-Za-z_\u0080-][A-Za-z0-9_$\u0080-]*/.exec(sql.slice(i))!;
|
|
83
|
+
out.push({ t: "ident", v: m[0], quoted: false });
|
|
84
|
+
i += m[0].length;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const op = OPERATORS.find((o) => sql.startsWith(o, i));
|
|
88
|
+
if (!op) fail(`unsupported character '${c}'`);
|
|
89
|
+
out.push({ t: "op", v: op! });
|
|
90
|
+
i += op!.length;
|
|
91
|
+
}
|
|
92
|
+
out.push({ t: "end" });
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// DuckDB's default binding of a cast target, restricted to the types any of the
|
|
97
|
+
// grammars can accept; every other type maps to null (refused).
|
|
98
|
+
const CAST_TYPES: Record<string, string> = {
|
|
99
|
+
boolean: "BOOLEAN", bool: "BOOLEAN", logical: "BOOLEAN",
|
|
100
|
+
tinyint: "TINYINT", int1: "TINYINT",
|
|
101
|
+
smallint: "SMALLINT", int2: "SMALLINT", short: "SMALLINT",
|
|
102
|
+
integer: "INTEGER", int: "INTEGER", int4: "INTEGER", signed: "INTEGER",
|
|
103
|
+
bigint: "BIGINT", int8: "BIGINT", long: "BIGINT",
|
|
104
|
+
float: "FLOAT", real: "FLOAT", float4: "FLOAT",
|
|
105
|
+
double: "DOUBLE", float8: "DOUBLE",
|
|
106
|
+
decimal: "DECIMAL", numeric: "DECIMAL",
|
|
107
|
+
varchar: "VARCHAR", text: "VARCHAR", string: "VARCHAR", char: "VARCHAR", bpchar: "VARCHAR",
|
|
108
|
+
nvarchar: "VARCHAR", character: "VARCHAR",
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const INT64_MAX = (1n << 63n) - 1n;
|
|
112
|
+
|
|
113
|
+
function literalNumber(text: string, negative: boolean): ScalarNode {
|
|
114
|
+
if (/^[0-9]+$/.test(text)) {
|
|
115
|
+
const value = BigInt(text) * (negative ? -1n : 1n);
|
|
116
|
+
const type: LiteralType = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER"
|
|
117
|
+
: value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
|
|
118
|
+
return { kind: "constant", type };
|
|
119
|
+
}
|
|
120
|
+
// A decimal point without an exponent is a DECIMAL literal while it fits.
|
|
121
|
+
if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38) return { kind: "constant", type: "DECIMAL" };
|
|
122
|
+
return { kind: "constant", type: "DOUBLE" };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
class Parser {
|
|
126
|
+
private pos = 0;
|
|
127
|
+
constructor(private readonly tokens: Token[]) {}
|
|
128
|
+
|
|
129
|
+
private peek(offset = 0): Token { return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)]; }
|
|
130
|
+
private next(): Token { return this.tokens[this.pos++]; }
|
|
131
|
+
private isOp(v: string, offset = 0): boolean {
|
|
132
|
+
const t = this.peek(offset);
|
|
133
|
+
return t.t === "op" && t.v === v;
|
|
134
|
+
}
|
|
135
|
+
private isWord(word: string, offset = 0): boolean {
|
|
136
|
+
const t = this.peek(offset);
|
|
137
|
+
return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
|
|
138
|
+
}
|
|
139
|
+
private expectOp(v: string): void {
|
|
140
|
+
if (!this.isOp(v)) fail(`expected '${v}'`);
|
|
141
|
+
this.pos++;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
parseAll(): ScalarNode {
|
|
145
|
+
const node = this.expr();
|
|
146
|
+
if (this.peek().t !== "end") fail("unexpected text after the expression");
|
|
147
|
+
return node;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private expr(): ScalarNode { return this.or(); }
|
|
151
|
+
|
|
152
|
+
private or(): ScalarNode {
|
|
153
|
+
let left = this.and();
|
|
154
|
+
while (this.isWord("or")) {
|
|
155
|
+
this.pos++;
|
|
156
|
+
left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
|
|
157
|
+
}
|
|
158
|
+
return left;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private and(): ScalarNode {
|
|
162
|
+
let left = this.not();
|
|
163
|
+
while (this.isWord("and")) {
|
|
164
|
+
this.pos++;
|
|
165
|
+
left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
|
|
166
|
+
}
|
|
167
|
+
return left;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private not(): ScalarNode {
|
|
171
|
+
if (this.isWord("not")) {
|
|
172
|
+
this.pos++;
|
|
173
|
+
return { kind: "operator", op: "NOT", children: [this.not()] };
|
|
174
|
+
}
|
|
175
|
+
return this.is();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private is(): ScalarNode {
|
|
179
|
+
let left = this.comparison();
|
|
180
|
+
for (;;) {
|
|
181
|
+
if (this.isWord("isnull")) { this.pos++; left = { kind: "operator", op: "IS_NULL", children: [left] }; continue; }
|
|
182
|
+
if (this.isWord("notnull")) { this.pos++; left = { kind: "operator", op: "IS_NOT_NULL", children: [left] }; continue; }
|
|
183
|
+
if (this.isWord("is")) {
|
|
184
|
+
this.pos++;
|
|
185
|
+
const negated = this.isWord("not");
|
|
186
|
+
if (negated) this.pos++;
|
|
187
|
+
if (!this.isWord("null")) fail("only IS [NOT] NULL is supported");
|
|
188
|
+
this.pos++;
|
|
189
|
+
left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
return left;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private comparison(): ScalarNode {
|
|
197
|
+
const left = this.otherOp();
|
|
198
|
+
const t = this.peek();
|
|
199
|
+
if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
|
|
200
|
+
this.pos++;
|
|
201
|
+
const right = this.otherOp();
|
|
202
|
+
const next = this.peek();
|
|
203
|
+
if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v)) fail("chained comparisons are unsupported");
|
|
204
|
+
return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
|
|
205
|
+
}
|
|
206
|
+
for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
|
|
207
|
+
if (this.isWord(word)) fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
|
|
208
|
+
}
|
|
209
|
+
return left;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// DuckDB's generic operator precedence level (||, //, **).
|
|
213
|
+
private otherOp(): ScalarNode {
|
|
214
|
+
let left = this.additive();
|
|
215
|
+
for (;;) {
|
|
216
|
+
const t = this.peek();
|
|
217
|
+
if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
|
|
218
|
+
this.pos++;
|
|
219
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
return left;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private additive(): ScalarNode {
|
|
227
|
+
let left = this.multiplicative();
|
|
228
|
+
for (;;) {
|
|
229
|
+
const t = this.peek();
|
|
230
|
+
if (t.t === "op" && (t.v === "+" || t.v === "-")) {
|
|
231
|
+
this.pos++;
|
|
232
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
return left;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private multiplicative(): ScalarNode {
|
|
240
|
+
let left = this.power();
|
|
241
|
+
for (;;) {
|
|
242
|
+
const t = this.peek();
|
|
243
|
+
if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
|
|
244
|
+
this.pos++;
|
|
245
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
return left;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private power(): ScalarNode {
|
|
253
|
+
let left = this.unary();
|
|
254
|
+
while (this.isOp("^")) {
|
|
255
|
+
this.pos++;
|
|
256
|
+
left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
|
|
257
|
+
}
|
|
258
|
+
return left;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private unary(): ScalarNode {
|
|
262
|
+
if (this.isOp("-") || this.isOp("+")) {
|
|
263
|
+
const sign = (this.next() as { v: string }).v;
|
|
264
|
+
const operand = this.unary();
|
|
265
|
+
// The grammar folds a minus applied directly to a numeric literal.
|
|
266
|
+
if (sign === "-" && operand.kind === "constant" && (operand as any).fromNumber) {
|
|
267
|
+
const folded = literalNumber((operand as any).text, !(operand as any).negative);
|
|
268
|
+
return Object.assign(folded, { fromNumber: true, text: (operand as any).text, negative: !(operand as any).negative });
|
|
269
|
+
}
|
|
270
|
+
return { kind: "function", name: sign, qualified: false, children: [operand] };
|
|
271
|
+
}
|
|
272
|
+
return this.postfix();
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private postfix(): ScalarNode {
|
|
276
|
+
let node = this.primary();
|
|
277
|
+
for (;;) {
|
|
278
|
+
if (this.isOp("::")) {
|
|
279
|
+
this.pos++;
|
|
280
|
+
node = { kind: "cast", ...this.typeName(), child: node };
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (this.isOp("[")) fail("subscripts are unsupported");
|
|
284
|
+
return node;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private typeName(): { type: string | null; qualified: boolean } {
|
|
289
|
+
const t = this.next();
|
|
290
|
+
if (t.t !== "ident") fail("expected a type name");
|
|
291
|
+
const first = (t as { v: string }).v.toLowerCase();
|
|
292
|
+
let qualified = false;
|
|
293
|
+
while (this.isOp(".")) {
|
|
294
|
+
this.pos++;
|
|
295
|
+
if (this.next().t !== "ident") fail("expected a type name");
|
|
296
|
+
qualified = true;
|
|
297
|
+
}
|
|
298
|
+
let name = first;
|
|
299
|
+
if (first === "double" && this.isWord("precision")) { this.pos++; name = "double"; }
|
|
300
|
+
if (first === "character" && this.isWord("varying")) { this.pos++; name = "varchar"; }
|
|
301
|
+
let params: string[] = [];
|
|
302
|
+
if (this.isOp("(")) {
|
|
303
|
+
this.pos++;
|
|
304
|
+
for (;;) {
|
|
305
|
+
const p = this.next();
|
|
306
|
+
if (p.t !== "num") fail("unsupported type parameter");
|
|
307
|
+
params.push((p as { v: string }).v);
|
|
308
|
+
if (this.isOp(",")) { this.pos++; continue; }
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
this.expectOp(")");
|
|
312
|
+
}
|
|
313
|
+
if (this.isOp("[")) fail("array types are unsupported");
|
|
314
|
+
let type = CAST_TYPES[name] ?? null;
|
|
315
|
+
if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24) type = "DOUBLE";
|
|
316
|
+
return { type, qualified };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private primary(): ScalarNode {
|
|
320
|
+
const t = this.next();
|
|
321
|
+
if (t.t === "num") return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
|
|
322
|
+
if (t.t === "str") {
|
|
323
|
+
if (this.peek().t === "str") fail("adjacent string literals are unsupported");
|
|
324
|
+
return { kind: "constant", type: "VARCHAR" };
|
|
325
|
+
}
|
|
326
|
+
if (t.t === "op") {
|
|
327
|
+
if (t.v === "(") {
|
|
328
|
+
const inner = this.expr();
|
|
329
|
+
if (this.isOp(",")) fail("row constructors are unsupported");
|
|
330
|
+
this.expectOp(")");
|
|
331
|
+
return inner;
|
|
332
|
+
}
|
|
333
|
+
return fail(`unexpected '${t.v}'`);
|
|
334
|
+
}
|
|
335
|
+
if (t.t === "end") return fail("expected an expression");
|
|
336
|
+
const word = t.v.toLowerCase();
|
|
337
|
+
if (!t.quoted) {
|
|
338
|
+
if (word === "null") return { kind: "constant", type: "NULL" };
|
|
339
|
+
if (word === "true" || word === "false") return { kind: "constant", type: "BOOLEAN" };
|
|
340
|
+
if (word === "cast" && this.isOp("(")) {
|
|
341
|
+
this.pos++;
|
|
342
|
+
const child = this.expr();
|
|
343
|
+
if (!this.isWord("as")) fail("expected AS in CAST");
|
|
344
|
+
this.pos++;
|
|
345
|
+
const target = this.typeName();
|
|
346
|
+
this.expectOp(")");
|
|
347
|
+
return { kind: "cast", ...target, child };
|
|
348
|
+
}
|
|
349
|
+
if (word === "case") fail("CASE is outside the supported scalar grammar");
|
|
350
|
+
if (RESERVED.has(word)) fail(`unexpected keyword ${t.v.toUpperCase()}`);
|
|
351
|
+
}
|
|
352
|
+
// Qualified names: a column reference or function with more than one part.
|
|
353
|
+
const names = [t.v];
|
|
354
|
+
while (this.isOp(".")) {
|
|
355
|
+
this.pos++;
|
|
356
|
+
const part = this.next();
|
|
357
|
+
if (part.t !== "ident") fail("unsupported qualified name");
|
|
358
|
+
names.push((part as { v: string }).v);
|
|
359
|
+
}
|
|
360
|
+
if (this.isOp("(")) {
|
|
361
|
+
this.pos++;
|
|
362
|
+
const children: ScalarNode[] = [];
|
|
363
|
+
if (this.isWord("distinct")) fail("DISTINCT function arguments are unsupported");
|
|
364
|
+
if (!this.isOp(")")) {
|
|
365
|
+
for (;;) {
|
|
366
|
+
if (this.isOp("*")) fail("star arguments are unsupported");
|
|
367
|
+
if (this.peek(1).t === "op" && ((this.peek(1) as { v: string }).v === ":" || (this.peek(1) as { v: string }).v === "=")
|
|
368
|
+
&& this.peek().t === "ident") fail("named scalar arguments are unsupported");
|
|
369
|
+
children.push(this.expr());
|
|
370
|
+
if (this.isOp(",")) { this.pos++; continue; }
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (this.isWord("order")) fail("ordered function arguments are unsupported");
|
|
375
|
+
this.expectOp(")");
|
|
376
|
+
if (this.isWord("filter") || this.isWord("over")) fail("aggregate and window functions are unsupported");
|
|
377
|
+
if (names.length === 1 && !t.quoted && word === "coalesce") return { kind: "operator", op: "COALESCE", children };
|
|
378
|
+
return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
|
|
379
|
+
}
|
|
380
|
+
if (this.peek().t === "str") fail("typed literals are unsupported");
|
|
381
|
+
return { kind: "column", names };
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Parse one DuckDB scalar expression in the bounded grammar's syntax. */
|
|
386
|
+
export function parseScalarSql(sql: string): ScalarNode {
|
|
387
|
+
if (typeof sql !== "string" || !sql || sql.includes("\0") || new TextEncoder().encode(sql).length > 1024 * 1024)
|
|
388
|
+
fail("invalid SQL size or text");
|
|
389
|
+
return new Parser(tokenize(sql)).parseAll();
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
|
|
393
|
+
const GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
|
|
394
|
+
const ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Check `sql` against the extension's column-expression grammar
|
|
398
|
+
* (vgi_column_expression.cpp `Parse`): a DEFAULT (`usingColumns` false: no
|
|
399
|
+
* column references), a USING expression (`usingColumns` true: `/` allowed) or
|
|
400
|
+
* a VIRTUAL generated column (`generated`: column references, `||`, no
|
|
401
|
+
* DECIMAL/floating literals or casts). Returns the referenced column names.
|
|
402
|
+
* Throws an Error naming the rule broken.
|
|
403
|
+
*/
|
|
404
|
+
export function validateColumnExpressionSql(
|
|
405
|
+
sql: string,
|
|
406
|
+
options: { usingColumns: boolean; generated: boolean },
|
|
407
|
+
): string[] {
|
|
408
|
+
const { usingColumns, generated } = options;
|
|
409
|
+
const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
|
|
410
|
+
const columns: string[] = [];
|
|
411
|
+
let nodes = 0;
|
|
412
|
+
const visit = (node: ScalarNode, depth: number): void => {
|
|
413
|
+
if (depth > 64 || ++nodes > 4096) fail("scalar expression is too complex");
|
|
414
|
+
switch (node.kind) {
|
|
415
|
+
case "constant":
|
|
416
|
+
if (!primitive.has(node.type)) fail(`unsupported scalar literal type ${node.type}`);
|
|
417
|
+
return;
|
|
418
|
+
case "column":
|
|
419
|
+
if (!usingColumns || node.names.length !== 1) fail("column references are unsupported in this scope");
|
|
420
|
+
columns.push(node.names[0]);
|
|
421
|
+
return;
|
|
422
|
+
case "cast":
|
|
423
|
+
if (node.qualified) fail("qualified scalar cast types are unsupported");
|
|
424
|
+
if (node.type === null || !primitive.has(node.type)) fail("unsupported scalar cast");
|
|
425
|
+
visit(node.child, depth + 1);
|
|
426
|
+
return;
|
|
427
|
+
case "comparison":
|
|
428
|
+
visit(node.left, depth + 1);
|
|
429
|
+
visit(node.right, depth + 1);
|
|
430
|
+
return;
|
|
431
|
+
case "conjunction":
|
|
432
|
+
case "operator":
|
|
433
|
+
node.children.forEach((c) => visit(c, depth + 1));
|
|
434
|
+
return;
|
|
435
|
+
case "function": {
|
|
436
|
+
const lower = node.name.toLowerCase();
|
|
437
|
+
const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) ||
|
|
438
|
+
(usingColumns && !generated && node.name === "/") || (generated && node.name === "||"));
|
|
439
|
+
if (!ok) fail(`unsupported scalar function '${node.name}'`);
|
|
440
|
+
node.children.forEach((c) => visit(c, depth + 1));
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
try {
|
|
446
|
+
visit(parseScalarSql(sql), 0);
|
|
447
|
+
} catch (error) {
|
|
448
|
+
if (error instanceof GrammarError) throw error;
|
|
449
|
+
throw new GrammarError(String((error as Error)?.message ?? error));
|
|
450
|
+
}
|
|
451
|
+
return columns;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* The extension's native CHECK read grammar (`ParseNumericCheck`): exactly one
|
|
456
|
+
* comparison (=, <>, <, >, <=, >=) whose operands are each a non-NULL numeric
|
|
457
|
+
* literal or an unqualified column reference. `resolveColumn` checks a
|
|
458
|
+
* referenced column (by case-insensitive name) and throws when it is not an
|
|
459
|
+
* acceptable operand.
|
|
460
|
+
*/
|
|
461
|
+
export function validateNumericCheckSql(sql: string, resolveColumn: (name: string) => void): void {
|
|
462
|
+
const node = parseScalarSql(sql);
|
|
463
|
+
if (node.kind !== "comparison") fail("native CHECK read supports only Boolean numeric comparisons");
|
|
464
|
+
const comparison = node as Extract<ScalarNode, { kind: "comparison" }>;
|
|
465
|
+
for (const operand of [comparison.left, comparison.right]) {
|
|
466
|
+
if (operand.kind === "constant") {
|
|
467
|
+
if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
|
|
468
|
+
fail("CHECK requires numeric operands");
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (operand.kind !== "column") fail("native CHECK read supports only numeric column/constant comparisons");
|
|
472
|
+
const column = operand as Extract<ScalarNode, { kind: "column" }>;
|
|
473
|
+
if (column.names.length !== 1) fail("CHECK requires unqualified column references");
|
|
474
|
+
resolveColumn(column.names[0]);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
@@ -1,23 +1,49 @@
|
|
|
1
1
|
// Copyright 2026 Query Farm LLC - https://query.farm
|
|
2
2
|
import { MethodNotImplementedError } from "@query-farm/vgi-rpc";
|
|
3
3
|
import { deserializeSchema, isStruct, type VgiField } from "../arrow/index.js";
|
|
4
|
+
import { decodeConstraintDefinition } from "../generated/vgi-protocol-types.js";
|
|
4
5
|
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
/**
|
|
7
|
+
* Check CREATE TABLE columns against the canonical constraint definitions sent
|
|
8
|
+
* with them: a column may be non-nullable only when a NOT_NULL or PRIMARY_KEY
|
|
9
|
+
* definition names it (DuckDB marks exactly those), nested fields stay
|
|
10
|
+
* nullable, and logical column types are refused (they need negotiation).
|
|
11
|
+
* With no definitions every user column must be nullable.
|
|
12
|
+
*/
|
|
13
|
+
export function requireCreateColumns(columns: Uint8Array, constraintDefinitions: readonly Uint8Array[] = []): void {
|
|
14
|
+
const required = new Set<string>();
|
|
15
|
+
for (const bytes of constraintDefinitions) {
|
|
16
|
+
let def;
|
|
17
|
+
try {
|
|
18
|
+
def = decodeConstraintDefinition(bytes);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
throw new Error(`catalog_table_create: undecodable constraint definition: ${(error as Error).message}`);
|
|
21
|
+
}
|
|
22
|
+
if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
|
|
23
|
+
for (const path of def.column_paths) required.add(JSON.stringify([...path]));
|
|
24
|
+
}
|
|
25
|
+
const visit = (field: VgiField, path: string[], depth: number): void => {
|
|
8
26
|
if (depth > 64) throw new MethodNotImplementedError("catalog_table_create: column nesting exceeds supported depth");
|
|
9
|
-
if (
|
|
27
|
+
if (depth === 0 && field.metadata?.has("is_row_id")) return;
|
|
10
28
|
for (const key of field.metadata?.keys() ?? []) {
|
|
11
29
|
if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
|
|
12
30
|
throw new MethodNotImplementedError("catalog_table_create: logical column types require negotiation");
|
|
13
31
|
}
|
|
14
32
|
}
|
|
15
|
-
if (!field.nullable) {
|
|
16
|
-
throw new MethodNotImplementedError(
|
|
33
|
+
if (!field.nullable && !required.has(JSON.stringify(path))) {
|
|
34
|
+
throw new MethodNotImplementedError(
|
|
35
|
+
`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`,
|
|
36
|
+
);
|
|
17
37
|
}
|
|
18
38
|
if (isStruct(field.type)) {
|
|
19
|
-
for (const child of (field.type as VgiField["type"] & { children: readonly VgiField[] }).children)
|
|
39
|
+
for (const child of (field.type as VgiField["type"] & { children: readonly VgiField[] }).children)
|
|
40
|
+
visit(child, [...path, child.name], depth + 1);
|
|
20
41
|
}
|
|
21
42
|
};
|
|
22
|
-
for (const field of deserializeSchema(columns).fields) visit(field,
|
|
43
|
+
for (const field of deserializeSchema(columns).fields) visit(field, [field.name], 0);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** No constraint authority means every SQL user field must remain nullable. */
|
|
47
|
+
export function requireUnconstrainedColumns(columns: Uint8Array): void {
|
|
48
|
+
requireCreateColumns(columns, []);
|
|
23
49
|
}
|
package/src/client/client.ts
CHANGED
|
@@ -59,6 +59,7 @@ import { serializeAttachOptions } from "../catalog/attach-options.js";
|
|
|
59
59
|
import { VgiClientError, wrapRpcWithErrorEnrichment } from "./errors.js";
|
|
60
60
|
import { normalizeSchemaPath } from "../schema-path.js";
|
|
61
61
|
import { encodeASD } from "../codec/asd.js";
|
|
62
|
+
import { defaultClientCapabilities } from "../catalog/constraints.js";
|
|
62
63
|
import { ClientCapabilitiesSchema, MacroCreateRequestSchema, TableCreateRequestSchema } from "../generated/vgi-protocol-schemas.js";
|
|
63
64
|
import { decodeCatalogStreams } from "../catalog/contents-codec.js";
|
|
64
65
|
import { decodeCatalogContentsResponse } from "../generated/vgi-protocol-types.js";
|
|
@@ -727,9 +728,11 @@ export class VgiClient {
|
|
|
727
728
|
options: [wireOptions],
|
|
728
729
|
data_version_spec: [opts?.dataVersionSpec ?? null],
|
|
729
730
|
implementation_version: [opts?.implementationVersion ?? null],
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
731
|
+
// Absent → the default offer (constraint records + CHECK expressions,
|
|
732
|
+
// which readConstraintRecord decodes); explicit null → no offer.
|
|
733
|
+
client_capabilities: [opts?.clientCapabilities === null
|
|
734
|
+
? null
|
|
735
|
+
: encodeASD(ClientCapabilitiesSchema, opts?.clientCapabilities ?? defaultClientCapabilities("vgi-typescript-client"))],
|
|
733
736
|
},
|
|
734
737
|
schema,
|
|
735
738
|
);
|
package/src/client/types.ts
CHANGED
|
@@ -49,7 +49,11 @@ export interface CatalogAttachOptions {
|
|
|
49
49
|
optionsBytes?: Uint8Array;
|
|
50
50
|
dataVersionSpec?: string | null;
|
|
51
51
|
implementationVersion?: string | null;
|
|
52
|
-
/**
|
|
52
|
+
/**
|
|
53
|
+
* Engine capabilities serialized into the protocol's named inner record.
|
|
54
|
+
* Omitted: `defaultClientCapabilities()` (reads canonical constraint records
|
|
55
|
+
* and their CHECK expressions). `null`: send no offer.
|
|
56
|
+
*/
|
|
53
57
|
clientCapabilities?: import("../generated/vgi-client.js").ClientCapabilities | null;
|
|
54
58
|
}
|
|
55
59
|
|
package/src/client-entry.ts
CHANGED
|
@@ -75,6 +75,10 @@ export {
|
|
|
75
75
|
type TransactionOpaqueData,
|
|
76
76
|
} from "./catalog/interface.js";
|
|
77
77
|
|
|
78
|
+
// vgi.v3 records: decode constraint records (readConstraintRecord), negotiate
|
|
79
|
+
// catalog capabilities, and build/decode the other canonical records.
|
|
80
|
+
export * from "./catalog/public-codecs.js";
|
|
81
|
+
|
|
78
82
|
// Errors
|
|
79
83
|
export {
|
|
80
84
|
VgiError,
|
package/src/index.core.ts
CHANGED
|
@@ -86,7 +86,8 @@ export type { VgiFunction, FunctionMeta, StreamHandlers, FunctionExample, Handle
|
|
|
86
86
|
export { CatalogInterface, type CatalogAttachResult, type CatalogAttachResultInit, buildCatalogAttachResult, type SchemaContentsInfo, type CatalogContentsResult, type SchemaInfo, encodeSchemaInfo, decodeSchemaInfo, type TableInfo, encodeTableInfo, decodeTableInfo, type ViewInfo, encodeViewInfo, decodeViewInfo, type CatalogInfo, encodeCatalogInfo, decodeCatalogInfo, type FunctionInfo, encodeFunctionInfo, decodeFunctionInfo, type FunctionInfoOptions, type MacroInfo, encodeMacroInfo, decodeMacroInfo, type MacroType, type CopyFromFormatInfo, encodeCopyFromFormatInfo, type AttachOpaqueData, type TransactionOpaqueData, buildScanBranchesResult, encodeFormatOptions, type ScanBranchInput } from "./catalog/interface.js";
|
|
87
87
|
export type { CatalogDescriptor, SchemaDescriptor, TableDescriptor, ViewDescriptor, MacroDescriptor, SettingDescriptor, SecretTypeDescriptor, ForeignKeyDef, DefaultValue } from "./catalog/descriptors.js";
|
|
88
88
|
export { ReadOnlyCatalogInterface, READ_ONLY_ITEM_ATTACH_ID } from "./catalog/read-only.js";
|
|
89
|
-
|
|
89
|
+
// vgi.v3 records: constraints, capabilities, column expressions, indexes, macro overloads.
|
|
90
|
+
export * from "./catalog/public-codecs.js";
|
|
90
91
|
export { CompositeCatalogInterface } from "./catalog/composite.js";
|
|
91
92
|
export { FunctionRegistry } from "./functions/registry.js";
|
|
92
93
|
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
encodeCatalogInfo,
|
|
15
15
|
} from "../../../generated/vgi-client.js";
|
|
16
16
|
import { buildCatalogAttachResult, decodeCatalogCapabilities, encodeCatalogCapabilities } from "../../../generated/vgi-protocol-types.js";
|
|
17
|
-
import {
|
|
17
|
+
import { capabilitiesEmpty, catalogCapabilities, selectCatalogCapabilities } from "../../../catalog/constraints.js";
|
|
18
18
|
import { serveCatalogContents } from "./contents.js";
|
|
19
19
|
import { encodeFunctionInfoOnce } from "../../../catalog/item-encoding.js";
|
|
20
20
|
import { encodeCopyFromFormatInfo } from "../../../catalog/interface.js";
|
|
@@ -104,18 +104,19 @@ export function catalogAdminHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
|
|
|
104
104
|
innerParams.implementation_version ?? null,
|
|
105
105
|
clientCapabilities,
|
|
106
106
|
);
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
//
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
107
|
+
// Advertise and select catalog profiles here, from the request itself (as
|
|
108
|
+
// vgi-python's worker does), so a catalog whose attach() override drops
|
|
109
|
+
// the clientCapabilities argument still negotiates what it serves. A
|
|
110
|
+
// catalog that leaves catalog_capabilities unset advertises
|
|
111
|
+
// catalogCapabilities() (records, mutation, enforcement, ...).
|
|
112
|
+
const advertised = result.catalog_capabilities != null
|
|
113
|
+
? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities))
|
|
114
|
+
: await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
|
|
115
|
+
if (!capabilitiesEmpty(advertised)) {
|
|
116
|
+
result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised!));
|
|
117
|
+
result.selected_capabilities = encodeCatalogCapabilities(
|
|
118
|
+
selectCatalogCapabilities(advertised!, clientCapabilities, result.supports_transactions ?? false),
|
|
119
|
+
);
|
|
119
120
|
}
|
|
120
121
|
// Seal the attach value into an AEAD envelope bound to the caller's
|
|
121
122
|
// identity before it leaves the worker (HTTP transport; pass-through
|