@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.
Files changed (45) hide show
  1. package/dist/catalog/column-expressions.d.ts +22 -1
  2. package/dist/catalog/column-metadata.d.ts +7 -0
  3. package/dist/catalog/column-types.d.ts +15 -0
  4. package/dist/catalog/composite.d.ts +2 -0
  5. package/dist/catalog/constraints.d.ts +110 -12
  6. package/dist/catalog/descriptors.d.ts +19 -1
  7. package/dist/catalog/indexes.d.ts +29 -0
  8. package/dist/catalog/interface.d.ts +41 -0
  9. package/dist/catalog/public-codecs.d.ts +6 -0
  10. package/dist/catalog/read-only.d.ts +3 -0
  11. package/dist/catalog/sql-grammar.d.ts +53 -0
  12. package/dist/catalog/unconstrained-columns.d.ts +8 -0
  13. package/dist/client/types.d.ts +5 -1
  14. package/dist/client-entry.d.ts +1 -0
  15. package/dist/client-entry.js +1410 -152
  16. package/dist/client-entry.js.map +12 -8
  17. package/dist/index.core.d.ts +1 -1
  18. package/dist/index.js +1681 -411
  19. package/dist/index.js.map +19 -16
  20. package/dist/serve-entry.js +1095 -49
  21. package/dist/serve-entry.js.map +13 -11
  22. package/dist/worker-cf-entry.d.ts +2 -1
  23. package/dist/worker-cf-entry.js +1459 -182
  24. package/dist/worker-cf-entry.js.map +19 -16
  25. package/package.json +1 -1
  26. package/src/catalog/column-expressions.ts +85 -7
  27. package/src/catalog/column-metadata.ts +20 -2
  28. package/src/catalog/column-types.ts +50 -0
  29. package/src/catalog/composite.ts +10 -0
  30. package/src/catalog/constraints.ts +496 -58
  31. package/src/catalog/contents-codec.ts +3 -3
  32. package/src/catalog/descriptors.ts +19 -1
  33. package/src/catalog/indexes.ts +59 -0
  34. package/src/catalog/interface.ts +103 -1
  35. package/src/catalog/public-codecs.ts +36 -0
  36. package/src/catalog/read-only.ts +92 -36
  37. package/src/catalog/sql-grammar.ts +476 -0
  38. package/src/catalog/unconstrained-columns.ts +34 -8
  39. package/src/client/client.ts +6 -3
  40. package/src/client/types.ts +5 -1
  41. package/src/client-entry.ts +4 -0
  42. package/src/index.core.ts +2 -1
  43. package/src/protocol/handlers/catalog/admin.ts +14 -13
  44. package/src/protocol/handlers/catalog/table.ts +58 -11
  45. package/src/worker-cf-entry.ts +2 -4
@@ -6364,7 +6364,10 @@ function decodeASDCollection(schema, bytes) {
6364
6364
  // src/generated/vgi-protocol-types.ts
6365
6365
  var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
6366
6366
  var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
6367
+ var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
6368
+ var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
6367
6369
  var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
6370
+ var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
6368
6371
  function buildCatalogAttachResult(init) {
6369
6372
  return {
6370
6373
  attach_opaque_data: init.attach_opaque_data,
@@ -6404,9 +6407,612 @@ function buildCatalogContentsResponse(init) {
6404
6407
  };
6405
6408
  }
6406
6409
 
6410
+ // src/catalog/sql-grammar.ts
6411
+ class GrammarError extends Error {
6412
+ }
6413
+ var fail = (message) => {
6414
+ throw new GrammarError(message);
6415
+ };
6416
+ var RESERVED = new Set([
6417
+ "all",
6418
+ "and",
6419
+ "any",
6420
+ "array",
6421
+ "as",
6422
+ "asc",
6423
+ "between",
6424
+ "both",
6425
+ "case",
6426
+ "cast",
6427
+ "check",
6428
+ "collate",
6429
+ "column",
6430
+ "constraint",
6431
+ "create",
6432
+ "default",
6433
+ "desc",
6434
+ "distinct",
6435
+ "do",
6436
+ "else",
6437
+ "end",
6438
+ "except",
6439
+ "false",
6440
+ "fetch",
6441
+ "for",
6442
+ "foreign",
6443
+ "from",
6444
+ "glob",
6445
+ "grant",
6446
+ "group",
6447
+ "having",
6448
+ "ilike",
6449
+ "in",
6450
+ "intersect",
6451
+ "interval",
6452
+ "into",
6453
+ "is",
6454
+ "isnull",
6455
+ "like",
6456
+ "limit",
6457
+ "not",
6458
+ "notnull",
6459
+ "null",
6460
+ "offset",
6461
+ "on",
6462
+ "or",
6463
+ "order",
6464
+ "primary",
6465
+ "references",
6466
+ "returning",
6467
+ "select",
6468
+ "similar",
6469
+ "some",
6470
+ "table",
6471
+ "then",
6472
+ "to",
6473
+ "true",
6474
+ "try_cast",
6475
+ "union",
6476
+ "unique",
6477
+ "using",
6478
+ "when",
6479
+ "where",
6480
+ "window",
6481
+ "with"
6482
+ ]);
6483
+ var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
6484
+ function tokenize(sql) {
6485
+ const out = [];
6486
+ let i = 0;
6487
+ while (i < sql.length) {
6488
+ const c = sql[i];
6489
+ if (/\s/.test(c)) {
6490
+ i++;
6491
+ continue;
6492
+ }
6493
+ if (sql.startsWith("--", i)) {
6494
+ while (i < sql.length && sql[i] !== `
6495
+ `)
6496
+ i++;
6497
+ continue;
6498
+ }
6499
+ if (sql.startsWith("/*", i)) {
6500
+ const close = sql.indexOf("*/", i + 2);
6501
+ if (close < 0)
6502
+ fail("unterminated comment");
6503
+ i = close + 2;
6504
+ continue;
6505
+ }
6506
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
6507
+ const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
6508
+ if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
6509
+ fail("unsupported numeric literal");
6510
+ out.push({ t: "num", v: m[0] });
6511
+ i += m[0].length;
6512
+ continue;
6513
+ }
6514
+ if (c === "'" || c === '"') {
6515
+ let j = i + 1, text = "";
6516
+ for (;; ) {
6517
+ if (j >= sql.length)
6518
+ fail("unterminated quoted text");
6519
+ if (sql[j] === c) {
6520
+ if (sql[j + 1] === c) {
6521
+ text += c;
6522
+ j += 2;
6523
+ continue;
6524
+ }
6525
+ break;
6526
+ }
6527
+ text += sql[j++];
6528
+ }
6529
+ out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
6530
+ i = j + 1;
6531
+ continue;
6532
+ }
6533
+ if (/[A-Za-z_\u0080-\uFFFF]/.test(c)) {
6534
+ const m = /^[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*/.exec(sql.slice(i));
6535
+ out.push({ t: "ident", v: m[0], quoted: false });
6536
+ i += m[0].length;
6537
+ continue;
6538
+ }
6539
+ const op = OPERATORS.find((o) => sql.startsWith(o, i));
6540
+ if (!op)
6541
+ fail(`unsupported character '${c}'`);
6542
+ out.push({ t: "op", v: op });
6543
+ i += op.length;
6544
+ }
6545
+ out.push({ t: "end" });
6546
+ return out;
6547
+ }
6548
+ var CAST_TYPES = {
6549
+ boolean: "BOOLEAN",
6550
+ bool: "BOOLEAN",
6551
+ logical: "BOOLEAN",
6552
+ tinyint: "TINYINT",
6553
+ int1: "TINYINT",
6554
+ smallint: "SMALLINT",
6555
+ int2: "SMALLINT",
6556
+ short: "SMALLINT",
6557
+ integer: "INTEGER",
6558
+ int: "INTEGER",
6559
+ int4: "INTEGER",
6560
+ signed: "INTEGER",
6561
+ bigint: "BIGINT",
6562
+ int8: "BIGINT",
6563
+ long: "BIGINT",
6564
+ float: "FLOAT",
6565
+ real: "FLOAT",
6566
+ float4: "FLOAT",
6567
+ double: "DOUBLE",
6568
+ float8: "DOUBLE",
6569
+ decimal: "DECIMAL",
6570
+ numeric: "DECIMAL",
6571
+ varchar: "VARCHAR",
6572
+ text: "VARCHAR",
6573
+ string: "VARCHAR",
6574
+ char: "VARCHAR",
6575
+ bpchar: "VARCHAR",
6576
+ nvarchar: "VARCHAR",
6577
+ character: "VARCHAR"
6578
+ };
6579
+ var INT64_MAX = (1n << 63n) - 1n;
6580
+ function literalNumber(text, negative) {
6581
+ if (/^[0-9]+$/.test(text)) {
6582
+ const value = BigInt(text) * (negative ? -1n : 1n);
6583
+ const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
6584
+ return { kind: "constant", type };
6585
+ }
6586
+ if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
6587
+ return { kind: "constant", type: "DECIMAL" };
6588
+ return { kind: "constant", type: "DOUBLE" };
6589
+ }
6590
+
6591
+ class Parser {
6592
+ tokens;
6593
+ pos = 0;
6594
+ constructor(tokens) {
6595
+ this.tokens = tokens;
6596
+ }
6597
+ peek(offset = 0) {
6598
+ return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
6599
+ }
6600
+ next() {
6601
+ return this.tokens[this.pos++];
6602
+ }
6603
+ isOp(v, offset = 0) {
6604
+ const t = this.peek(offset);
6605
+ return t.t === "op" && t.v === v;
6606
+ }
6607
+ isWord(word, offset = 0) {
6608
+ const t = this.peek(offset);
6609
+ return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
6610
+ }
6611
+ expectOp(v) {
6612
+ if (!this.isOp(v))
6613
+ fail(`expected '${v}'`);
6614
+ this.pos++;
6615
+ }
6616
+ parseAll() {
6617
+ const node = this.expr();
6618
+ if (this.peek().t !== "end")
6619
+ fail("unexpected text after the expression");
6620
+ return node;
6621
+ }
6622
+ expr() {
6623
+ return this.or();
6624
+ }
6625
+ or() {
6626
+ let left = this.and();
6627
+ while (this.isWord("or")) {
6628
+ this.pos++;
6629
+ left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
6630
+ }
6631
+ return left;
6632
+ }
6633
+ and() {
6634
+ let left = this.not();
6635
+ while (this.isWord("and")) {
6636
+ this.pos++;
6637
+ left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
6638
+ }
6639
+ return left;
6640
+ }
6641
+ not() {
6642
+ if (this.isWord("not")) {
6643
+ this.pos++;
6644
+ return { kind: "operator", op: "NOT", children: [this.not()] };
6645
+ }
6646
+ return this.is();
6647
+ }
6648
+ is() {
6649
+ let left = this.comparison();
6650
+ for (;; ) {
6651
+ if (this.isWord("isnull")) {
6652
+ this.pos++;
6653
+ left = { kind: "operator", op: "IS_NULL", children: [left] };
6654
+ continue;
6655
+ }
6656
+ if (this.isWord("notnull")) {
6657
+ this.pos++;
6658
+ left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
6659
+ continue;
6660
+ }
6661
+ if (this.isWord("is")) {
6662
+ this.pos++;
6663
+ const negated = this.isWord("not");
6664
+ if (negated)
6665
+ this.pos++;
6666
+ if (!this.isWord("null"))
6667
+ fail("only IS [NOT] NULL is supported");
6668
+ this.pos++;
6669
+ left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
6670
+ continue;
6671
+ }
6672
+ return left;
6673
+ }
6674
+ }
6675
+ comparison() {
6676
+ const left = this.otherOp();
6677
+ const t = this.peek();
6678
+ if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
6679
+ this.pos++;
6680
+ const right = this.otherOp();
6681
+ const next = this.peek();
6682
+ if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
6683
+ fail("chained comparisons are unsupported");
6684
+ return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
6685
+ }
6686
+ for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
6687
+ if (this.isWord(word))
6688
+ fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
6689
+ }
6690
+ return left;
6691
+ }
6692
+ otherOp() {
6693
+ let left = this.additive();
6694
+ for (;; ) {
6695
+ const t = this.peek();
6696
+ if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
6697
+ this.pos++;
6698
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
6699
+ continue;
6700
+ }
6701
+ return left;
6702
+ }
6703
+ }
6704
+ additive() {
6705
+ let left = this.multiplicative();
6706
+ for (;; ) {
6707
+ const t = this.peek();
6708
+ if (t.t === "op" && (t.v === "+" || t.v === "-")) {
6709
+ this.pos++;
6710
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
6711
+ continue;
6712
+ }
6713
+ return left;
6714
+ }
6715
+ }
6716
+ multiplicative() {
6717
+ let left = this.power();
6718
+ for (;; ) {
6719
+ const t = this.peek();
6720
+ if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
6721
+ this.pos++;
6722
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
6723
+ continue;
6724
+ }
6725
+ return left;
6726
+ }
6727
+ }
6728
+ power() {
6729
+ let left = this.unary();
6730
+ while (this.isOp("^")) {
6731
+ this.pos++;
6732
+ left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
6733
+ }
6734
+ return left;
6735
+ }
6736
+ unary() {
6737
+ if (this.isOp("-") || this.isOp("+")) {
6738
+ const sign = this.next().v;
6739
+ const operand = this.unary();
6740
+ if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
6741
+ const folded = literalNumber(operand.text, !operand.negative);
6742
+ return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
6743
+ }
6744
+ return { kind: "function", name: sign, qualified: false, children: [operand] };
6745
+ }
6746
+ return this.postfix();
6747
+ }
6748
+ postfix() {
6749
+ let node = this.primary();
6750
+ for (;; ) {
6751
+ if (this.isOp("::")) {
6752
+ this.pos++;
6753
+ node = { kind: "cast", ...this.typeName(), child: node };
6754
+ continue;
6755
+ }
6756
+ if (this.isOp("["))
6757
+ fail("subscripts are unsupported");
6758
+ return node;
6759
+ }
6760
+ }
6761
+ typeName() {
6762
+ const t = this.next();
6763
+ if (t.t !== "ident")
6764
+ fail("expected a type name");
6765
+ const first = t.v.toLowerCase();
6766
+ let qualified = false;
6767
+ while (this.isOp(".")) {
6768
+ this.pos++;
6769
+ if (this.next().t !== "ident")
6770
+ fail("expected a type name");
6771
+ qualified = true;
6772
+ }
6773
+ let name = first;
6774
+ if (first === "double" && this.isWord("precision")) {
6775
+ this.pos++;
6776
+ name = "double";
6777
+ }
6778
+ if (first === "character" && this.isWord("varying")) {
6779
+ this.pos++;
6780
+ name = "varchar";
6781
+ }
6782
+ let params = [];
6783
+ if (this.isOp("(")) {
6784
+ this.pos++;
6785
+ for (;; ) {
6786
+ const p = this.next();
6787
+ if (p.t !== "num")
6788
+ fail("unsupported type parameter");
6789
+ params.push(p.v);
6790
+ if (this.isOp(",")) {
6791
+ this.pos++;
6792
+ continue;
6793
+ }
6794
+ break;
6795
+ }
6796
+ this.expectOp(")");
6797
+ }
6798
+ if (this.isOp("["))
6799
+ fail("array types are unsupported");
6800
+ let type = CAST_TYPES[name] ?? null;
6801
+ if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
6802
+ type = "DOUBLE";
6803
+ return { type, qualified };
6804
+ }
6805
+ primary() {
6806
+ const t = this.next();
6807
+ if (t.t === "num")
6808
+ return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
6809
+ if (t.t === "str") {
6810
+ if (this.peek().t === "str")
6811
+ fail("adjacent string literals are unsupported");
6812
+ return { kind: "constant", type: "VARCHAR" };
6813
+ }
6814
+ if (t.t === "op") {
6815
+ if (t.v === "(") {
6816
+ const inner = this.expr();
6817
+ if (this.isOp(","))
6818
+ fail("row constructors are unsupported");
6819
+ this.expectOp(")");
6820
+ return inner;
6821
+ }
6822
+ return fail(`unexpected '${t.v}'`);
6823
+ }
6824
+ if (t.t === "end")
6825
+ return fail("expected an expression");
6826
+ const word = t.v.toLowerCase();
6827
+ if (!t.quoted) {
6828
+ if (word === "null")
6829
+ return { kind: "constant", type: "NULL" };
6830
+ if (word === "true" || word === "false")
6831
+ return { kind: "constant", type: "BOOLEAN" };
6832
+ if (word === "cast" && this.isOp("(")) {
6833
+ this.pos++;
6834
+ const child = this.expr();
6835
+ if (!this.isWord("as"))
6836
+ fail("expected AS in CAST");
6837
+ this.pos++;
6838
+ const target = this.typeName();
6839
+ this.expectOp(")");
6840
+ return { kind: "cast", ...target, child };
6841
+ }
6842
+ if (word === "case")
6843
+ fail("CASE is outside the supported scalar grammar");
6844
+ if (RESERVED.has(word))
6845
+ fail(`unexpected keyword ${t.v.toUpperCase()}`);
6846
+ }
6847
+ const names = [t.v];
6848
+ while (this.isOp(".")) {
6849
+ this.pos++;
6850
+ const part = this.next();
6851
+ if (part.t !== "ident")
6852
+ fail("unsupported qualified name");
6853
+ names.push(part.v);
6854
+ }
6855
+ if (this.isOp("(")) {
6856
+ this.pos++;
6857
+ const children = [];
6858
+ if (this.isWord("distinct"))
6859
+ fail("DISTINCT function arguments are unsupported");
6860
+ if (!this.isOp(")")) {
6861
+ for (;; ) {
6862
+ if (this.isOp("*"))
6863
+ fail("star arguments are unsupported");
6864
+ if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
6865
+ fail("named scalar arguments are unsupported");
6866
+ children.push(this.expr());
6867
+ if (this.isOp(",")) {
6868
+ this.pos++;
6869
+ continue;
6870
+ }
6871
+ break;
6872
+ }
6873
+ }
6874
+ if (this.isWord("order"))
6875
+ fail("ordered function arguments are unsupported");
6876
+ this.expectOp(")");
6877
+ if (this.isWord("filter") || this.isWord("over"))
6878
+ fail("aggregate and window functions are unsupported");
6879
+ if (names.length === 1 && !t.quoted && word === "coalesce")
6880
+ return { kind: "operator", op: "COALESCE", children };
6881
+ return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
6882
+ }
6883
+ if (this.peek().t === "str")
6884
+ fail("typed literals are unsupported");
6885
+ return { kind: "column", names };
6886
+ }
6887
+ }
6888
+ function parseScalarSql(sql) {
6889
+ if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
6890
+ fail("invalid SQL size or text");
6891
+ return new Parser(tokenize(sql)).parseAll();
6892
+ }
6893
+ var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
6894
+ var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
6895
+ var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
6896
+ function validateColumnExpressionSql(sql, options) {
6897
+ const { usingColumns, generated } = options;
6898
+ const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
6899
+ const columns = [];
6900
+ let nodes = 0;
6901
+ const visit = (node, depth) => {
6902
+ if (depth > 64 || ++nodes > 4096)
6903
+ fail("scalar expression is too complex");
6904
+ switch (node.kind) {
6905
+ case "constant":
6906
+ if (!primitive.has(node.type))
6907
+ fail(`unsupported scalar literal type ${node.type}`);
6908
+ return;
6909
+ case "column":
6910
+ if (!usingColumns || node.names.length !== 1)
6911
+ fail("column references are unsupported in this scope");
6912
+ columns.push(node.names[0]);
6913
+ return;
6914
+ case "cast":
6915
+ if (node.qualified)
6916
+ fail("qualified scalar cast types are unsupported");
6917
+ if (node.type === null || !primitive.has(node.type))
6918
+ fail("unsupported scalar cast");
6919
+ visit(node.child, depth + 1);
6920
+ return;
6921
+ case "comparison":
6922
+ visit(node.left, depth + 1);
6923
+ visit(node.right, depth + 1);
6924
+ return;
6925
+ case "conjunction":
6926
+ case "operator":
6927
+ node.children.forEach((c) => visit(c, depth + 1));
6928
+ return;
6929
+ case "function": {
6930
+ const lower = node.name.toLowerCase();
6931
+ const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
6932
+ if (!ok)
6933
+ fail(`unsupported scalar function '${node.name}'`);
6934
+ node.children.forEach((c) => visit(c, depth + 1));
6935
+ return;
6936
+ }
6937
+ }
6938
+ };
6939
+ try {
6940
+ visit(parseScalarSql(sql), 0);
6941
+ } catch (error) {
6942
+ if (error instanceof GrammarError)
6943
+ throw error;
6944
+ throw new GrammarError(String(error?.message ?? error));
6945
+ }
6946
+ return columns;
6947
+ }
6948
+ function validateNumericCheckSql(sql, resolveColumn) {
6949
+ const node = parseScalarSql(sql);
6950
+ if (node.kind !== "comparison")
6951
+ fail("native CHECK read supports only Boolean numeric comparisons");
6952
+ const comparison = node;
6953
+ for (const operand of [comparison.left, comparison.right]) {
6954
+ if (operand.kind === "constant") {
6955
+ if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
6956
+ fail("CHECK requires numeric operands");
6957
+ continue;
6958
+ }
6959
+ if (operand.kind !== "column")
6960
+ fail("native CHECK read supports only numeric column/constant comparisons");
6961
+ const column = operand;
6962
+ if (column.names.length !== 1)
6963
+ fail("CHECK requires unqualified column references");
6964
+ resolveColumn(column.names[0]);
6965
+ }
6966
+ }
6967
+
6968
+ // src/catalog/column-types.ts
6969
+ function isRowIdField(field) {
6970
+ return field.metadata?.has("is_row_id") ?? false;
6971
+ }
6972
+ function hasLogicalType(field) {
6973
+ for (const key of field.metadata?.keys() ?? [])
6974
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
6975
+ return true;
6976
+ return false;
6977
+ }
6978
+ function ordinaryStructChildren(field) {
6979
+ if (!isStruct(field.type) || hasLogicalType(field))
6980
+ return null;
6981
+ return field.type.children;
6982
+ }
6983
+ function isGeneratedField(field) {
6984
+ const m = field.metadata;
6985
+ return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
6986
+ }
6987
+ function duckdbPrimitive(field) {
6988
+ if (hasLogicalType(field))
6989
+ return null;
6990
+ const t = field.type;
6991
+ switch (t.typeId) {
6992
+ case TypeId.Bool:
6993
+ return "BOOLEAN";
6994
+ case TypeId.Utf8:
6995
+ return "VARCHAR";
6996
+ case TypeId.Int: {
6997
+ if (!(t.isSigned ?? t.signed ?? true))
6998
+ return null;
6999
+ return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
7000
+ }
7001
+ case TypeId.Float:
7002
+ return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
7003
+ case TypeId.Decimal:
7004
+ return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
7005
+ default:
7006
+ return null;
7007
+ }
7008
+ }
7009
+
6407
7010
  // src/catalog/column-expressions.ts
6408
7011
  var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
6409
7012
  var GENERATION_KEY = "vgi.column.generation.v1";
7013
+ var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
7014
+ var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
7015
+ var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
6410
7016
  var PROFILE = "vgi.expression.duckdb.scalar.v1";
6411
7017
  var MAX_BYTES = 8 * 1024 * 1024;
6412
7018
  var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
@@ -6517,7 +7123,34 @@ function validateEncoded(encoded, owner) {
6517
7123
  throw new Error("invalid SqlExpression record schema");
6518
7124
  const utf8 = new TextDecoder("utf-8", { fatal: true });
6519
7125
  textBuffers.forEach((buffer) => utf8.decode(buffer));
6520
- expression(decodeSqlExpression(bytes), owner);
7126
+ const value = decodeSqlExpression(bytes);
7127
+ expression(value, owner);
7128
+ return value.sql;
7129
+ }
7130
+ function generatedExpressionMetadata(sql, owner) {
7131
+ try {
7132
+ validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
7133
+ } catch (error) {
7134
+ throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
7135
+ }
7136
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
7137
+ }
7138
+ function sqlExpression(sql, schemaPath) {
7139
+ const owner = [...schemaPath];
7140
+ const value = {
7141
+ sql,
7142
+ profile: PROFILE,
7143
+ schema_path: [...owner],
7144
+ evaluation_context: {
7145
+ timezone: "UTC",
7146
+ collation: "binary",
7147
+ default_order: "asc",
7148
+ default_null_order: "nulls_last",
7149
+ preserve_insertion_order: true
7150
+ }
7151
+ };
7152
+ expression(value, owner);
7153
+ return value;
6521
7154
  }
6522
7155
  function validateColumnExpressions(schema, owner, allowGenerated = true) {
6523
7156
  const type = (t) => {
@@ -6526,14 +7159,33 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
6526
7159
  if (t?.dictionary)
6527
7160
  type(t.dictionary);
6528
7161
  };
6529
- const field = (f) => {
7162
+ const topLevel = new Map;
7163
+ for (const f of schema.fields) {
7164
+ const key = String(f.name).toLowerCase();
7165
+ topLevel.set(key, [...topLevel.get(key) ?? [], f]);
7166
+ }
7167
+ const field = (f, top = false) => {
6530
7168
  const metadata = f.metadata ?? new Map;
6531
7169
  for (const key of metadata.keys()) {
6532
7170
  if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
6533
7171
  throw new Error("unknown generated metadata version");
6534
7172
  }
7173
+ const where = `column ${f.name}`;
6535
7174
  if (metadata.has("generated_expression"))
6536
- throw new Error("legacy generated expression requires explicit canonical translation");
7175
+ throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
7176
+ if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
7177
+ if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
7178
+ throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
7179
+ const type = duckdbPrimitive(f);
7180
+ if (!type || !DEFAULT_TYPES.has(type))
7181
+ throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
7182
+ const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
7183
+ try {
7184
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
7185
+ } catch (error) {
7186
+ throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
7187
+ }
7188
+ }
6537
7189
  if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
6538
7190
  throw new Error("generated expression and category must occur together");
6539
7191
  if (metadata.has(GENERATED_EXPRESSION_KEY)) {
@@ -6541,13 +7193,34 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
6541
7193
  throw new Error("only VIRTUAL generated columns are supported");
6542
7194
  if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
6543
7195
  throw new Error("generated column cannot have a default");
6544
- validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
7196
+ const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
6545
7197
  if (!allowGenerated)
6546
7198
  throw new Error("generated columns unsupported by this catalog");
7199
+ if (!f.nullable)
7200
+ throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
7201
+ const type = duckdbPrimitive(f);
7202
+ if (!type || !GENERATED_TYPES.has(type))
7203
+ throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
7204
+ let references;
7205
+ try {
7206
+ references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
7207
+ } catch (error) {
7208
+ throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
7209
+ }
7210
+ if (top) {
7211
+ for (const name of references) {
7212
+ const matches = topLevel.get(name.toLowerCase()) ?? [];
7213
+ if (matches.length !== 1)
7214
+ throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
7215
+ const operand = duckdbPrimitive(matches[0]);
7216
+ if (!operand || !GENERATED_TYPES.has(operand))
7217
+ throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
7218
+ }
7219
+ }
6547
7220
  }
6548
7221
  type(f.type);
6549
7222
  };
6550
- schema.fields.forEach(field);
7223
+ schema.fields.forEach((f) => field(f, true));
6551
7224
  }
6552
7225
  function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
6553
7226
  validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
@@ -8658,6 +9331,338 @@ var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
8658
9331
  var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
8659
9332
  var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
8660
9333
 
9334
+ // src/catalog/constraints.ts
9335
+ var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
9336
+ var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
9337
+ var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
9338
+ var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
9339
+ var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
9340
+ var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
9341
+ var CHECK_CONTEXT = {
9342
+ timezone: "UTC",
9343
+ collation: "binary",
9344
+ default_order: "asc",
9345
+ default_null_order: "nulls_last",
9346
+ preserve_insertion_order: true
9347
+ };
9348
+ function identifier(value, what) {
9349
+ if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
9350
+ throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
9351
+ }
9352
+ function checkPaths(paths, what, topLevelOnly) {
9353
+ if (paths.length > 1024)
9354
+ throw new Error(`${what}: too many column paths`);
9355
+ const seen = new Set;
9356
+ for (const path of paths) {
9357
+ if (path.length === 0 || path.length > 64)
9358
+ throw new Error(`${what}: column path must have 1..64 components`);
9359
+ if (topLevelOnly && path.length !== 1)
9360
+ throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
9361
+ path.forEach((part) => identifier(part, `${what}: column path component`));
9362
+ const key = JSON.stringify(path);
9363
+ if (seen.has(key))
9364
+ throw new Error(`${what}: duplicate column path ${path.join(".")}`);
9365
+ seen.add(key);
9366
+ }
9367
+ }
9368
+ var KNOWN = {
9369
+ read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
9370
+ ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
9371
+ write: new Set([CONSTRAINT_ENFORCE]),
9372
+ transaction: new Set([TRANSACTION_DDL])
9373
+ };
9374
+ var REQUIRES = {
9375
+ [ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
9376
+ [CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
9377
+ [CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
9378
+ [CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
9379
+ "vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
9380
+ "vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
9381
+ };
9382
+ var CATEGORIES = ["read", "ddl", "write", "transaction"];
9383
+ function catalogCapabilities(init = {}) {
9384
+ return {
9385
+ read: [...new Set(init.read ?? [])].sort(),
9386
+ ddl: [...new Set(init.ddl ?? [])].sort(),
9387
+ write: [...new Set(init.write ?? [])].sort(),
9388
+ transaction: [...new Set(init.transaction ?? [])].sort()
9389
+ };
9390
+ }
9391
+ function offeredCatalog(clientCapabilities) {
9392
+ if (clientCapabilities == null)
9393
+ return null;
9394
+ const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
9395
+ return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
9396
+ }
9397
+ function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
9398
+ const offered = offeredCatalog(clientCapabilities);
9399
+ if (offered == null)
9400
+ return catalogCapabilities();
9401
+ const chosen = new Set;
9402
+ for (const category of CATEGORIES)
9403
+ for (const p of available[category] ?? [])
9404
+ if (offered[category]?.includes(p))
9405
+ chosen.add(p);
9406
+ if (!supportsTransactions)
9407
+ chosen.delete(TRANSACTION_DDL);
9408
+ for (let changed = true;changed; ) {
9409
+ changed = false;
9410
+ for (const p of [...chosen])
9411
+ if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
9412
+ chosen.delete(p);
9413
+ changed = true;
9414
+ }
9415
+ }
9416
+ const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
9417
+ return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
9418
+ }
9419
+ function capabilitiesEmpty(caps) {
9420
+ return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
9421
+ }
9422
+ function readConstraintRecord(bytes) {
9423
+ const info = decodeASD(ConstraintInfoSchema, bytes);
9424
+ const ref = decodeASD(CatalogObjectRefSchema, info.ref);
9425
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
9426
+ const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
9427
+ const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
9428
+ const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
9429
+ return {
9430
+ schemaPath: [...ref.schema_path],
9431
+ table: ref.owner_table ?? "",
9432
+ id: ref.name,
9433
+ kind: def.kind,
9434
+ columns: [...def.column_paths].map((p) => [...p]),
9435
+ enforcement: info.enforcement,
9436
+ validation: info.validation,
9437
+ declaredName: def.declared_name ?? null,
9438
+ checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
9439
+ references: fk == null || target == null ? null : {
9440
+ schemaPath: [...target.schema_path],
9441
+ table: target.name,
9442
+ columns: [...fk.referenced_column_paths].map((p) => [...p]),
9443
+ constraintId: targetKey?.name ?? null,
9444
+ constraintTable: targetKey?.owner_table ?? null,
9445
+ constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
9446
+ match: fk.match,
9447
+ onUpdate: fk.on_update,
9448
+ onDelete: fk.on_delete
9449
+ }
9450
+ };
9451
+ }
9452
+ function fieldsByExactName(fields, name) {
9453
+ const out = [];
9454
+ fields.forEach((f, i) => {
9455
+ if (f.name === name)
9456
+ out.push(i);
9457
+ });
9458
+ return out;
9459
+ }
9460
+ function validateTableConstraints(table, schemaPath, fields, constraints) {
9461
+ if (constraints.length > 1024)
9462
+ throw new Error(`Table '${table}': too many constraints (at most 1024)`);
9463
+ const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
9464
+ if (rowIds.length > 1)
9465
+ throw new Error(`Table '${table}': at most one column may carry is_row_id`);
9466
+ const rowId = rowIds[0] ?? -1;
9467
+ const records = [];
9468
+ const required = new Set;
9469
+ const ids = new Set;
9470
+ const labels = new Set;
9471
+ let primaryKeys = 0;
9472
+ for (const bytes of constraints) {
9473
+ let record;
9474
+ try {
9475
+ record = readConstraintRecord(bytes);
9476
+ } catch (error) {
9477
+ throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
9478
+ }
9479
+ const where = `Table '${table}': constraint '${record.id}'`;
9480
+ const fail = (message) => {
9481
+ throw new Error(`${where}: ${message}`);
9482
+ };
9483
+ if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
9484
+ fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
9485
+ if (ids.has(record.id))
9486
+ fail("duplicate constraint id");
9487
+ ids.add(record.id);
9488
+ if (record.declaredName != null) {
9489
+ const label = record.declaredName.toLowerCase();
9490
+ if (labels.has(label))
9491
+ fail(`duplicate declared name '${record.declaredName}'`);
9492
+ labels.add(label);
9493
+ }
9494
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
9495
+ fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
9496
+ try {
9497
+ checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
9498
+ } catch (error) {
9499
+ fail(error.message);
9500
+ }
9501
+ const resolveTop = (path) => {
9502
+ const matches = fieldsByExactName(fields, path[0]);
9503
+ if (matches.length !== 1 || matches[0] === rowId)
9504
+ fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
9505
+ return matches[0];
9506
+ };
9507
+ switch (record.kind) {
9508
+ case "CHECK": {
9509
+ if (record.checkSql == null)
9510
+ fail("CHECK without an expression");
9511
+ validateCheckRecord(bytes, where, schemaPath, fields, rowId);
9512
+ break;
9513
+ }
9514
+ case "NOT_NULL": {
9515
+ if (record.columns.length !== 1)
9516
+ fail("NOT_NULL requires exactly one column path");
9517
+ const path = record.columns[0];
9518
+ let field = fields[resolveTop(path)];
9519
+ for (let depth = 1;depth < path.length; depth++) {
9520
+ const children = ordinaryStructChildren(field);
9521
+ if (!children)
9522
+ fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
9523
+ const matches = fieldsByExactName(children, path[depth]);
9524
+ if (matches.length !== 1)
9525
+ fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
9526
+ field = children[matches[0]];
9527
+ }
9528
+ if (path.length === 1 && isGeneratedField(field))
9529
+ fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
9530
+ required.add(JSON.stringify(path));
9531
+ break;
9532
+ }
9533
+ case "PRIMARY_KEY":
9534
+ case "UNIQUE": {
9535
+ for (const path of record.columns) {
9536
+ const index = resolveTop(path);
9537
+ if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
9538
+ fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
9539
+ }
9540
+ if (record.kind === "PRIMARY_KEY") {
9541
+ if (++primaryKeys > 1)
9542
+ fail("a table may have only one PRIMARY KEY");
9543
+ for (const path of record.columns)
9544
+ required.add(JSON.stringify(path));
9545
+ }
9546
+ break;
9547
+ }
9548
+ case "FOREIGN_KEY": {
9549
+ record.columns.forEach(resolveTop);
9550
+ const ref = record.references;
9551
+ if (ref == null || ref.constraintId == null)
9552
+ fail("FOREIGN_KEY requires a referenced table and referenced constraint");
9553
+ if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
9554
+ fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
9555
+ if (ref.columns.length !== record.columns.length)
9556
+ fail("foreign key arity mismatch");
9557
+ try {
9558
+ checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
9559
+ } catch (error) {
9560
+ fail(error.message);
9561
+ }
9562
+ if (ref.match !== undefined && ref.match !== "SIMPLE")
9563
+ fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
9564
+ for (const action of [ref.onUpdate, ref.onDelete])
9565
+ if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
9566
+ fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
9567
+ break;
9568
+ }
9569
+ default:
9570
+ fail(`unknown constraint kind ${String(record.kind)}`);
9571
+ }
9572
+ records.push(record);
9573
+ }
9574
+ return { records, required };
9575
+ }
9576
+ function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
9577
+ const info = decodeASD(ConstraintInfoSchema, bytes);
9578
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
9579
+ const expression = decodeASD(SqlExpressionSchema, def.check_expression);
9580
+ const fail = (message) => {
9581
+ throw new Error(`${where}: ${message}`);
9582
+ };
9583
+ if (expression.profile !== ROW_SCALAR_EXPRESSION)
9584
+ fail(`unsupported CHECK expression profile ${expression.profile}`);
9585
+ if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
9586
+ fail("CHECK expression belongs to another schema");
9587
+ const context = expression.evaluation_context ?? {};
9588
+ for (const [key, value] of Object.entries(CHECK_CONTEXT))
9589
+ if (context[key] !== value)
9590
+ fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
9591
+ try {
9592
+ validateNumericCheckSql(expression.sql, (name) => {
9593
+ const lower = name.toLowerCase();
9594
+ const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
9595
+ if (matches.length > 1)
9596
+ throw new Error(`ambiguous CHECK column reference ${name}`);
9597
+ if (matches.length === 0 || matches[0] === rowId)
9598
+ throw new Error(`CHECK references a missing or row-id column ${name}`);
9599
+ const column = fields[matches[0]];
9600
+ if (column.metadata.has("ARROW:extension:name"))
9601
+ throw new Error(`CHECK operand ${name} has an extension type`);
9602
+ if (isGeneratedField(column))
9603
+ throw new Error(`CHECK operand ${name} is a generated column`);
9604
+ const type = duckdbPrimitive(column);
9605
+ if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
9606
+ throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
9607
+ });
9608
+ } catch (error) {
9609
+ fail(`${error.message} (CHECK SQL: ${expression.sql})`);
9610
+ }
9611
+ }
9612
+ function servedConstraintFields(fields, required) {
9613
+ const rewrite = (list, prefix) => {
9614
+ let changed = false;
9615
+ const out = list.map((f) => {
9616
+ if (prefix.length === 0 && isRowIdField(f))
9617
+ return f;
9618
+ const path = [...prefix, f.name];
9619
+ const nullable = !required.has(JSON.stringify(path));
9620
+ const children = ordinaryStructChildren(f);
9621
+ const newChildren = children ? rewrite(children, path) : null;
9622
+ if (nullable === f.nullable && (newChildren == null || newChildren === children))
9623
+ return f;
9624
+ changed = true;
9625
+ const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
9626
+ return field2(f.name, type, nullable, new Map(f.metadata));
9627
+ });
9628
+ return changed ? out : list;
9629
+ };
9630
+ return rewrite(fields, []);
9631
+ }
9632
+ function translateLegacyGenerated(fields, owner, table) {
9633
+ let changed = false;
9634
+ const out = fields.map((f) => {
9635
+ const sql = f.metadata.get("generated_expression");
9636
+ if (sql === undefined)
9637
+ return f;
9638
+ if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
9639
+ throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
9640
+ const metadata = new Map(f.metadata);
9641
+ metadata.delete("generated_expression");
9642
+ metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
9643
+ metadata.set(GENERATION_KEY, "virtual");
9644
+ changed = true;
9645
+ return field2(f.name, f.type, f.nullable, metadata);
9646
+ });
9647
+ return changed ? out : fields;
9648
+ }
9649
+ function servedTableSchema(table, schemaPath, schema, constraints) {
9650
+ let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
9651
+ const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
9652
+ fields = servedConstraintFields(fields, required);
9653
+ return fields === schema.fields ? schema : schema2(fields, schema.metadata);
9654
+ }
9655
+ function servedTableInfo(info) {
9656
+ if (!info.columns || info.columns.length === 0) {
9657
+ if ((info.constraints ?? []).length)
9658
+ throw new Error(`Table '${info.name}': constraints on a table without columns`);
9659
+ return info;
9660
+ }
9661
+ const schema = deserializeSchema(info.columns);
9662
+ const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
9663
+ return served === schema ? info : { ...info, columns: serializeSchema(served) };
9664
+ }
9665
+
8661
9666
  // src/catalog/column-metadata.ts
8662
9667
  function scalarText(value) {
8663
9668
  for (let i = 0;i < value.length; i++) {
@@ -8794,9 +9799,21 @@ function validateTableInfoColumns(info) {
8794
9799
  validateColumnExpressionsIpc(info.columns, info.schema_path);
8795
9800
  }
8796
9801
  }
9802
+ function servedValidatedTableInfo(info) {
9803
+ if (info.columns.length)
9804
+ validateColumnMetadataIpc(info.columns);
9805
+ const served = servedTableInfo(info);
9806
+ if (served.columns.length) {
9807
+ try {
9808
+ validateColumnExpressionsIpc(served.columns, served.schema_path);
9809
+ } catch (error) {
9810
+ throw new Error(`Table '${served.name}': ${error.message}`);
9811
+ }
9812
+ }
9813
+ return served;
9814
+ }
8797
9815
  function encodeValidatedTableInfo(info) {
8798
- validateTableInfoColumns(info);
8799
- return encodeTableInfo(info);
9816
+ return encodeTableInfo(servedValidatedTableInfo(info));
8800
9817
  }
8801
9818
 
8802
9819
  // src/protocol/handlers/catalog/admin.ts
@@ -8818,20 +9835,6 @@ function catalogStringMap(raw) {
8818
9835
  return result;
8819
9836
  }
8820
9837
 
8821
- // src/catalog/constraints.ts
8822
- var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
8823
- var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
8824
- function selectReadProfiles(available, clientCapabilities) {
8825
- if (clientCapabilities == null || available.length === 0)
8826
- return [];
8827
- const client = decodeASD(ClientCapabilitiesSchema, clientCapabilities);
8828
- const offered = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
8829
- const selected = available.filter((p) => offered.includes(p));
8830
- if (!selected.includes(CONSTRAINT_RECORDS_READ))
8831
- return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
8832
- return selected.sort();
8833
- }
8834
-
8835
9838
  // src/protocol/handlers/catalog/contents.ts
8836
9839
  import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
8837
9840
 
@@ -8842,12 +9845,10 @@ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@qu
8842
9845
  var schemaPathKey = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
8843
9846
  var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
8844
9847
  function encodeCatalogStreams(inventory) {
8845
- for (const schema of inventory)
8846
- for (const table of schema.tables)
8847
- validateTableInfoColumns(table);
9848
+ const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
8848
9849
  const streams = {
8849
9850
  schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
8850
- tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
9851
+ tables: encodeASDCollection(TableInfoSchema, tables),
8851
9852
  views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
8852
9853
  functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
8853
9854
  macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
@@ -9915,13 +10916,10 @@ function catalogAdminHandlers(getCatalog, signingKey) {
9915
10916
  }
9916
10917
  const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
9917
10918
  const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, clientCapabilities);
9918
- if (result.catalog_capabilities != null) {
9919
- const available = decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities));
9920
- const chosen = result.selected_capabilities == null ? { read: [], ddl: [], write: [], transaction: [] } : decodeCatalogCapabilities(toUint8Array(result.selected_capabilities));
9921
- result.selected_capabilities = encodeCatalogCapabilities({
9922
- ...chosen,
9923
- read: selectReadProfiles(available.read, clientCapabilities)
9924
- });
10919
+ const advertised = result.catalog_capabilities != null ? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities)) : await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
10920
+ if (!capabilitiesEmpty(advertised)) {
10921
+ result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
10922
+ result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
9925
10923
  }
9926
10924
  const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
9927
10925
  return wrapResult(buildCatalogAttachResult({
@@ -10057,27 +11055,39 @@ import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-
10057
11055
 
10058
11056
  // src/catalog/unconstrained-columns.ts
10059
11057
  import { MethodNotImplementedError as MethodNotImplementedError3 } from "@query-farm/vgi-rpc";
10060
- function requireUnconstrainedColumns(columns) {
10061
- const visit = (field, top, depth) => {
11058
+ function requireCreateColumns(columns, constraintDefinitions = []) {
11059
+ const required = new Set;
11060
+ for (const bytes of constraintDefinitions) {
11061
+ let def;
11062
+ try {
11063
+ def = decodeConstraintDefinition(bytes);
11064
+ } catch (error) {
11065
+ throw new Error(`catalog_table_create: undecodable constraint definition: ${error.message}`);
11066
+ }
11067
+ if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
11068
+ for (const path of def.column_paths)
11069
+ required.add(JSON.stringify([...path]));
11070
+ }
11071
+ const visit = (field, path, depth) => {
10062
11072
  if (depth > 64)
10063
11073
  throw new MethodNotImplementedError3("catalog_table_create: column nesting exceeds supported depth");
10064
- if (top && field.metadata?.has("is_row_id"))
11074
+ if (depth === 0 && field.metadata?.has("is_row_id"))
10065
11075
  return;
10066
11076
  for (const key of field.metadata?.keys() ?? []) {
10067
11077
  if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
10068
11078
  throw new MethodNotImplementedError3("catalog_table_create: logical column types require negotiation");
10069
11079
  }
10070
11080
  }
10071
- if (!field.nullable) {
10072
- throw new MethodNotImplementedError3("catalog_table_create: nonnullable user columns require canonical constraints");
11081
+ if (!field.nullable && !required.has(JSON.stringify(path))) {
11082
+ throw new MethodNotImplementedError3(`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`);
10073
11083
  }
10074
11084
  if (isStruct(field.type)) {
10075
11085
  for (const child of field.type.children)
10076
- visit(child, false, depth + 1);
11086
+ visit(child, [...path, child.name], depth + 1);
10077
11087
  }
10078
11088
  };
10079
11089
  for (const field of deserializeSchema(columns).fields)
10080
- visit(field, true, 0);
11090
+ visit(field, [field.name], 0);
10081
11091
  }
10082
11092
 
10083
11093
  // src/protocol/handlers/catalog/table.ts
@@ -10099,19 +11109,57 @@ function catalogTableHandlers(getCatalog, signingKey) {
10099
11109
  const catalogTableCreate = catalogHandler(signingKey, async (params) => {
10100
11110
  if (params.constraint_definitions == null)
10101
11111
  throw new Error("constraint_definitions is required");
10102
- if (Array.from(params.constraint_definitions).length > 0) {
10103
- throw new MethodNotImplementedError4("catalog_table_create: canonical constraint enforcement is not supported");
10104
- }
11112
+ const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
10105
11113
  if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
10106
11114
  throw new MethodNotImplementedError4("catalog_table_create: table metadata/options/layout profiles are not supported");
10107
11115
  }
11116
+ const attach = toUint8Array(params.attach_opaque_data);
11117
+ const cat = getCatalog();
11118
+ if (definitions.length > 0) {
11119
+ const caps = await cat.catalogCapabilities(attach);
11120
+ if (caps != null && !(caps.ddl.includes(CONSTRAINT_CREATE) && caps.write.includes(CONSTRAINT_ENFORCE))) {
11121
+ throw new MethodNotImplementedError4("catalog_table_create: this catalog does not enforce constraints (NOT NULL, PRIMARY KEY, UNIQUE, CHECK, " + "FOREIGN KEY); it advertises neither vgi.constraint.create.v1 nor vgi.constraint.enforce.v1");
11122
+ }
11123
+ }
10108
11124
  validateColumnMetadataIpc(toUint8Array(params.columns));
10109
11125
  validateColumnExpressionsIpc(toUint8Array(params.columns), params.schema_path);
10110
- requireUnconstrainedColumns(toUint8Array(params.columns));
10111
- const cat = getCatalog();
10112
- await cat.tableCreate(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, [], params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11126
+ requireCreateColumns(toUint8Array(params.columns), definitions);
11127
+ await cat.tableCreate(attach, params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, definitions, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
10113
11128
  return {};
10114
11129
  });
11130
+ const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
11131
+ const attach = toUint8Array(params.attach_opaque_data);
11132
+ const cat = getCatalog();
11133
+ const caps = await cat.catalogCapabilities(attach);
11134
+ if (caps != null && !caps.ddl.includes(CONSTRAINT_MUTATE)) {
11135
+ throw new MethodNotImplementedError4("catalog_table_constraints_apply: this catalog does not advertise vgi.constraint.mutate.v1");
11136
+ }
11137
+ const table = toUint8Array(params.table);
11138
+ const expected = toUint8Array(params.expected_revision);
11139
+ const changes = Array.from(params.changes, (c) => toUint8Array(c));
11140
+ if (expected.length === 0 || changes.length === 0)
11141
+ throw new Error("catalog_table_constraints_apply: empty revision or change list");
11142
+ const snapshot = await cat.tableConstraintsApply({
11143
+ attach_opaque_data: attach,
11144
+ table,
11145
+ expected_revision: expected,
11146
+ changes,
11147
+ transaction_opaque_data: params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : null
11148
+ });
11149
+ const want = decodeCatalogObjectRef(table);
11150
+ const got = decodeCatalogObjectRef(toUint8Array(snapshot.table));
11151
+ if (got.name !== want.name || JSON.stringify([...got.schema_path]) !== JSON.stringify([...want.schema_path]))
11152
+ throw new Error("catalog_table_constraints_apply: the catalog returned a snapshot of a different table");
11153
+ const revision = toUint8Array(snapshot.definition_revision);
11154
+ if (revision.length === 0 || revision.length === expected.length && revision.every((b, i) => b === expected[i]))
11155
+ throw new Error(`catalog_table_constraints_apply: table '${want.name}' must return a new, nonempty definition_revision`);
11156
+ for (const record of snapshot.constraints) {
11157
+ const view = readConstraintRecord(toUint8Array(record));
11158
+ if (view.table !== want.name || JSON.stringify(view.schemaPath) !== JSON.stringify([...want.schema_path]))
11159
+ throw new Error(`catalog_table_constraints_apply: constraint '${view.id}' belongs to another table`);
11160
+ }
11161
+ return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
11162
+ });
10115
11163
  const catalogTableDrop = catalogHandler(signingKey, async (params) => {
10116
11164
  const cat = getCatalog();
10117
11165
  await cat.tableDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -10199,9 +11247,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
10199
11247
  return {};
10200
11248
  });
10201
11249
  return {
10202
- catalogTableConstraintsApply: async () => {
10203
- throw new MethodNotImplementedError4("catalog_table_constraints_apply");
10204
- },
11250
+ catalogTableConstraintsApply,
10205
11251
  catalogTableGet,
10206
11252
  catalogTableCreate,
10207
11253
  catalogTableDrop,
@@ -10788,4 +11834,4 @@ export {
10788
11834
  serveVgiWorker
10789
11835
  };
10790
11836
 
10791
- //# debugId=9488384AF40D279864756E2164756E21
11837
+ //# debugId=CFEC3B6AACFA587664756E2164756E21