@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
@@ -7878,10 +7878,66 @@ function decodeASDCollection(schema, bytes) {
7878
7878
  }
7879
7879
 
7880
7880
  // src/generated/vgi-protocol-types.ts
7881
+ function buildMacroOverload(init) {
7882
+ return {
7883
+ parameters: init.parameters,
7884
+ definition: init.definition,
7885
+ profile: init.profile,
7886
+ schema_path: init.schema_path,
7887
+ macro_type: init.macro_type,
7888
+ evaluation_context: init.evaluation_context
7889
+ };
7890
+ }
7891
+ var encodeMacroOverload = (v) => encodeASD(MacroOverloadSchema, v);
7892
+ var decodeMacroOverload = (b) => decodeASD(MacroOverloadSchema, b);
7893
+ function buildCatalogCapabilities(init) {
7894
+ return {
7895
+ read: init.read ?? [],
7896
+ ddl: init.ddl ?? [],
7897
+ write: init.write ?? [],
7898
+ transaction: init.transaction ?? []
7899
+ };
7900
+ }
7881
7901
  var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
7882
7902
  var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
7903
+ var encodeCatalogObjectRef = (v) => encodeASD(CatalogObjectRefSchema, v);
7904
+ var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
7883
7905
  var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
7884
7906
  var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
7907
+ var encodeForeignKeyDefinition = (v) => encodeASD(ForeignKeyDefinitionSchema, v);
7908
+ var decodeForeignKeyDefinition = (b) => decodeASD(ForeignKeyDefinitionSchema, b);
7909
+ function buildConstraintDefinition(init) {
7910
+ return {
7911
+ kind: init.kind,
7912
+ column_paths: init.column_paths ?? [],
7913
+ declared_name: init.declared_name ?? null,
7914
+ check_expression: init.check_expression ?? null,
7915
+ foreign_key: init.foreign_key ?? null
7916
+ };
7917
+ }
7918
+ var encodeConstraintDefinition = (v) => encodeASD(ConstraintDefinitionSchema, v);
7919
+ var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
7920
+ var encodeConstraintInfo = (v) => encodeASD(ConstraintInfoSchema, v);
7921
+ var decodeConstraintInfo = (b) => decodeASD(ConstraintInfoSchema, b);
7922
+ function buildConstraintChange(init) {
7923
+ return {
7924
+ operation: init.operation,
7925
+ ref: init.ref ?? null,
7926
+ definition: init.definition ?? null,
7927
+ enforcement: init.enforcement ?? null,
7928
+ validation: init.validation ?? null,
7929
+ cascade: init.cascade ?? null,
7930
+ declared_name: init.declared_name ?? null
7931
+ };
7932
+ }
7933
+ var encodeConstraintChange = (v) => encodeASD(ConstraintChangeSchema, v);
7934
+ var decodeConstraintChange = (b) => decodeASD(ConstraintChangeSchema, b);
7935
+ var encodeConstraintSnapshot = (v) => encodeASD(ConstraintSnapshotSchema, v);
7936
+ var decodeConstraintSnapshot = (b) => decodeASD(ConstraintSnapshotSchema, b);
7937
+ var encodeConstraintsApplyRequest = (v) => encodeASD(ConstraintsApplyRequestSchema, v);
7938
+ var decodeConstraintsApplyRequest = (b) => decodeASD(ConstraintsApplyRequestSchema, b);
7939
+ var encodeIndexDefinition = (v) => encodeASD(IndexDefinitionSchema, v);
7940
+ var decodeIndexDefinition = (b) => decodeASD(IndexDefinitionSchema, b);
7885
7941
  function buildCatalogAttachResult(init) {
7886
7942
  return {
7887
7943
  attach_opaque_data: init.attach_opaque_data,
@@ -7921,9 +7977,613 @@ function buildCatalogContentsResponse(init) {
7921
7977
  };
7922
7978
  }
7923
7979
 
7980
+ // src/catalog/sql-grammar.ts
7981
+ class GrammarError extends Error {
7982
+ }
7983
+ var fail = (message) => {
7984
+ throw new GrammarError(message);
7985
+ };
7986
+ var RESERVED = new Set([
7987
+ "all",
7988
+ "and",
7989
+ "any",
7990
+ "array",
7991
+ "as",
7992
+ "asc",
7993
+ "between",
7994
+ "both",
7995
+ "case",
7996
+ "cast",
7997
+ "check",
7998
+ "collate",
7999
+ "column",
8000
+ "constraint",
8001
+ "create",
8002
+ "default",
8003
+ "desc",
8004
+ "distinct",
8005
+ "do",
8006
+ "else",
8007
+ "end",
8008
+ "except",
8009
+ "false",
8010
+ "fetch",
8011
+ "for",
8012
+ "foreign",
8013
+ "from",
8014
+ "glob",
8015
+ "grant",
8016
+ "group",
8017
+ "having",
8018
+ "ilike",
8019
+ "in",
8020
+ "intersect",
8021
+ "interval",
8022
+ "into",
8023
+ "is",
8024
+ "isnull",
8025
+ "like",
8026
+ "limit",
8027
+ "not",
8028
+ "notnull",
8029
+ "null",
8030
+ "offset",
8031
+ "on",
8032
+ "or",
8033
+ "order",
8034
+ "primary",
8035
+ "references",
8036
+ "returning",
8037
+ "select",
8038
+ "similar",
8039
+ "some",
8040
+ "table",
8041
+ "then",
8042
+ "to",
8043
+ "true",
8044
+ "try_cast",
8045
+ "union",
8046
+ "unique",
8047
+ "using",
8048
+ "when",
8049
+ "where",
8050
+ "window",
8051
+ "with"
8052
+ ]);
8053
+ var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
8054
+ function tokenize(sql) {
8055
+ const out = [];
8056
+ let i = 0;
8057
+ while (i < sql.length) {
8058
+ const c = sql[i];
8059
+ if (/\s/.test(c)) {
8060
+ i++;
8061
+ continue;
8062
+ }
8063
+ if (sql.startsWith("--", i)) {
8064
+ while (i < sql.length && sql[i] !== `
8065
+ `)
8066
+ i++;
8067
+ continue;
8068
+ }
8069
+ if (sql.startsWith("/*", i)) {
8070
+ const close = sql.indexOf("*/", i + 2);
8071
+ if (close < 0)
8072
+ fail("unterminated comment");
8073
+ i = close + 2;
8074
+ continue;
8075
+ }
8076
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
8077
+ const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
8078
+ if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
8079
+ fail("unsupported numeric literal");
8080
+ out.push({ t: "num", v: m[0] });
8081
+ i += m[0].length;
8082
+ continue;
8083
+ }
8084
+ if (c === "'" || c === '"') {
8085
+ let j = i + 1, text = "";
8086
+ for (;; ) {
8087
+ if (j >= sql.length)
8088
+ fail("unterminated quoted text");
8089
+ if (sql[j] === c) {
8090
+ if (sql[j + 1] === c) {
8091
+ text += c;
8092
+ j += 2;
8093
+ continue;
8094
+ }
8095
+ break;
8096
+ }
8097
+ text += sql[j++];
8098
+ }
8099
+ out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
8100
+ i = j + 1;
8101
+ continue;
8102
+ }
8103
+ if (/[A-Za-z_\u0080-￿]/.test(c)) {
8104
+ const m = /^[A-Za-z_\u0080-￿][A-Za-z0-9_$\u0080-￿]*/.exec(sql.slice(i));
8105
+ out.push({ t: "ident", v: m[0], quoted: false });
8106
+ i += m[0].length;
8107
+ continue;
8108
+ }
8109
+ const op = OPERATORS.find((o) => sql.startsWith(o, i));
8110
+ if (!op)
8111
+ fail(`unsupported character '${c}'`);
8112
+ out.push({ t: "op", v: op });
8113
+ i += op.length;
8114
+ }
8115
+ out.push({ t: "end" });
8116
+ return out;
8117
+ }
8118
+ var CAST_TYPES = {
8119
+ boolean: "BOOLEAN",
8120
+ bool: "BOOLEAN",
8121
+ logical: "BOOLEAN",
8122
+ tinyint: "TINYINT",
8123
+ int1: "TINYINT",
8124
+ smallint: "SMALLINT",
8125
+ int2: "SMALLINT",
8126
+ short: "SMALLINT",
8127
+ integer: "INTEGER",
8128
+ int: "INTEGER",
8129
+ int4: "INTEGER",
8130
+ signed: "INTEGER",
8131
+ bigint: "BIGINT",
8132
+ int8: "BIGINT",
8133
+ long: "BIGINT",
8134
+ float: "FLOAT",
8135
+ real: "FLOAT",
8136
+ float4: "FLOAT",
8137
+ double: "DOUBLE",
8138
+ float8: "DOUBLE",
8139
+ decimal: "DECIMAL",
8140
+ numeric: "DECIMAL",
8141
+ varchar: "VARCHAR",
8142
+ text: "VARCHAR",
8143
+ string: "VARCHAR",
8144
+ char: "VARCHAR",
8145
+ bpchar: "VARCHAR",
8146
+ nvarchar: "VARCHAR",
8147
+ character: "VARCHAR"
8148
+ };
8149
+ var INT64_MAX = (1n << 63n) - 1n;
8150
+ function literalNumber(text, negative) {
8151
+ if (/^[0-9]+$/.test(text)) {
8152
+ const value = BigInt(text) * (negative ? -1n : 1n);
8153
+ const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
8154
+ return { kind: "constant", type };
8155
+ }
8156
+ if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
8157
+ return { kind: "constant", type: "DECIMAL" };
8158
+ return { kind: "constant", type: "DOUBLE" };
8159
+ }
8160
+
8161
+ class Parser {
8162
+ tokens;
8163
+ pos = 0;
8164
+ constructor(tokens) {
8165
+ this.tokens = tokens;
8166
+ }
8167
+ peek(offset = 0) {
8168
+ return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
8169
+ }
8170
+ next() {
8171
+ return this.tokens[this.pos++];
8172
+ }
8173
+ isOp(v, offset = 0) {
8174
+ const t = this.peek(offset);
8175
+ return t.t === "op" && t.v === v;
8176
+ }
8177
+ isWord(word, offset = 0) {
8178
+ const t = this.peek(offset);
8179
+ return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
8180
+ }
8181
+ expectOp(v) {
8182
+ if (!this.isOp(v))
8183
+ fail(`expected '${v}'`);
8184
+ this.pos++;
8185
+ }
8186
+ parseAll() {
8187
+ const node = this.expr();
8188
+ if (this.peek().t !== "end")
8189
+ fail("unexpected text after the expression");
8190
+ return node;
8191
+ }
8192
+ expr() {
8193
+ return this.or();
8194
+ }
8195
+ or() {
8196
+ let left = this.and();
8197
+ while (this.isWord("or")) {
8198
+ this.pos++;
8199
+ left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
8200
+ }
8201
+ return left;
8202
+ }
8203
+ and() {
8204
+ let left = this.not();
8205
+ while (this.isWord("and")) {
8206
+ this.pos++;
8207
+ left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
8208
+ }
8209
+ return left;
8210
+ }
8211
+ not() {
8212
+ if (this.isWord("not")) {
8213
+ this.pos++;
8214
+ return { kind: "operator", op: "NOT", children: [this.not()] };
8215
+ }
8216
+ return this.is();
8217
+ }
8218
+ is() {
8219
+ let left = this.comparison();
8220
+ for (;; ) {
8221
+ if (this.isWord("isnull")) {
8222
+ this.pos++;
8223
+ left = { kind: "operator", op: "IS_NULL", children: [left] };
8224
+ continue;
8225
+ }
8226
+ if (this.isWord("notnull")) {
8227
+ this.pos++;
8228
+ left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
8229
+ continue;
8230
+ }
8231
+ if (this.isWord("is")) {
8232
+ this.pos++;
8233
+ const negated = this.isWord("not");
8234
+ if (negated)
8235
+ this.pos++;
8236
+ if (!this.isWord("null"))
8237
+ fail("only IS [NOT] NULL is supported");
8238
+ this.pos++;
8239
+ left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
8240
+ continue;
8241
+ }
8242
+ return left;
8243
+ }
8244
+ }
8245
+ comparison() {
8246
+ const left = this.otherOp();
8247
+ const t = this.peek();
8248
+ if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
8249
+ this.pos++;
8250
+ const right = this.otherOp();
8251
+ const next = this.peek();
8252
+ if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
8253
+ fail("chained comparisons are unsupported");
8254
+ return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
8255
+ }
8256
+ for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
8257
+ if (this.isWord(word))
8258
+ fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
8259
+ }
8260
+ return left;
8261
+ }
8262
+ otherOp() {
8263
+ let left = this.additive();
8264
+ for (;; ) {
8265
+ const t = this.peek();
8266
+ if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
8267
+ this.pos++;
8268
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
8269
+ continue;
8270
+ }
8271
+ return left;
8272
+ }
8273
+ }
8274
+ additive() {
8275
+ let left = this.multiplicative();
8276
+ for (;; ) {
8277
+ const t = this.peek();
8278
+ if (t.t === "op" && (t.v === "+" || t.v === "-")) {
8279
+ this.pos++;
8280
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
8281
+ continue;
8282
+ }
8283
+ return left;
8284
+ }
8285
+ }
8286
+ multiplicative() {
8287
+ let left = this.power();
8288
+ for (;; ) {
8289
+ const t = this.peek();
8290
+ if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
8291
+ this.pos++;
8292
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
8293
+ continue;
8294
+ }
8295
+ return left;
8296
+ }
8297
+ }
8298
+ power() {
8299
+ let left = this.unary();
8300
+ while (this.isOp("^")) {
8301
+ this.pos++;
8302
+ left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
8303
+ }
8304
+ return left;
8305
+ }
8306
+ unary() {
8307
+ if (this.isOp("-") || this.isOp("+")) {
8308
+ const sign = this.next().v;
8309
+ const operand = this.unary();
8310
+ if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
8311
+ const folded = literalNumber(operand.text, !operand.negative);
8312
+ return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
8313
+ }
8314
+ return { kind: "function", name: sign, qualified: false, children: [operand] };
8315
+ }
8316
+ return this.postfix();
8317
+ }
8318
+ postfix() {
8319
+ let node = this.primary();
8320
+ for (;; ) {
8321
+ if (this.isOp("::")) {
8322
+ this.pos++;
8323
+ node = { kind: "cast", ...this.typeName(), child: node };
8324
+ continue;
8325
+ }
8326
+ if (this.isOp("["))
8327
+ fail("subscripts are unsupported");
8328
+ return node;
8329
+ }
8330
+ }
8331
+ typeName() {
8332
+ const t = this.next();
8333
+ if (t.t !== "ident")
8334
+ fail("expected a type name");
8335
+ const first = t.v.toLowerCase();
8336
+ let qualified = false;
8337
+ while (this.isOp(".")) {
8338
+ this.pos++;
8339
+ if (this.next().t !== "ident")
8340
+ fail("expected a type name");
8341
+ qualified = true;
8342
+ }
8343
+ let name = first;
8344
+ if (first === "double" && this.isWord("precision")) {
8345
+ this.pos++;
8346
+ name = "double";
8347
+ }
8348
+ if (first === "character" && this.isWord("varying")) {
8349
+ this.pos++;
8350
+ name = "varchar";
8351
+ }
8352
+ let params = [];
8353
+ if (this.isOp("(")) {
8354
+ this.pos++;
8355
+ for (;; ) {
8356
+ const p = this.next();
8357
+ if (p.t !== "num")
8358
+ fail("unsupported type parameter");
8359
+ params.push(p.v);
8360
+ if (this.isOp(",")) {
8361
+ this.pos++;
8362
+ continue;
8363
+ }
8364
+ break;
8365
+ }
8366
+ this.expectOp(")");
8367
+ }
8368
+ if (this.isOp("["))
8369
+ fail("array types are unsupported");
8370
+ let type = CAST_TYPES[name] ?? null;
8371
+ if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
8372
+ type = "DOUBLE";
8373
+ return { type, qualified };
8374
+ }
8375
+ primary() {
8376
+ const t = this.next();
8377
+ if (t.t === "num")
8378
+ return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
8379
+ if (t.t === "str") {
8380
+ if (this.peek().t === "str")
8381
+ fail("adjacent string literals are unsupported");
8382
+ return { kind: "constant", type: "VARCHAR" };
8383
+ }
8384
+ if (t.t === "op") {
8385
+ if (t.v === "(") {
8386
+ const inner = this.expr();
8387
+ if (this.isOp(","))
8388
+ fail("row constructors are unsupported");
8389
+ this.expectOp(")");
8390
+ return inner;
8391
+ }
8392
+ return fail(`unexpected '${t.v}'`);
8393
+ }
8394
+ if (t.t === "end")
8395
+ return fail("expected an expression");
8396
+ const word = t.v.toLowerCase();
8397
+ if (!t.quoted) {
8398
+ if (word === "null")
8399
+ return { kind: "constant", type: "NULL" };
8400
+ if (word === "true" || word === "false")
8401
+ return { kind: "constant", type: "BOOLEAN" };
8402
+ if (word === "cast" && this.isOp("(")) {
8403
+ this.pos++;
8404
+ const child = this.expr();
8405
+ if (!this.isWord("as"))
8406
+ fail("expected AS in CAST");
8407
+ this.pos++;
8408
+ const target = this.typeName();
8409
+ this.expectOp(")");
8410
+ return { kind: "cast", ...target, child };
8411
+ }
8412
+ if (word === "case")
8413
+ fail("CASE is outside the supported scalar grammar");
8414
+ if (RESERVED.has(word))
8415
+ fail(`unexpected keyword ${t.v.toUpperCase()}`);
8416
+ }
8417
+ const names = [t.v];
8418
+ while (this.isOp(".")) {
8419
+ this.pos++;
8420
+ const part = this.next();
8421
+ if (part.t !== "ident")
8422
+ fail("unsupported qualified name");
8423
+ names.push(part.v);
8424
+ }
8425
+ if (this.isOp("(")) {
8426
+ this.pos++;
8427
+ const children = [];
8428
+ if (this.isWord("distinct"))
8429
+ fail("DISTINCT function arguments are unsupported");
8430
+ if (!this.isOp(")")) {
8431
+ for (;; ) {
8432
+ if (this.isOp("*"))
8433
+ fail("star arguments are unsupported");
8434
+ if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
8435
+ fail("named scalar arguments are unsupported");
8436
+ children.push(this.expr());
8437
+ if (this.isOp(",")) {
8438
+ this.pos++;
8439
+ continue;
8440
+ }
8441
+ break;
8442
+ }
8443
+ }
8444
+ if (this.isWord("order"))
8445
+ fail("ordered function arguments are unsupported");
8446
+ this.expectOp(")");
8447
+ if (this.isWord("filter") || this.isWord("over"))
8448
+ fail("aggregate and window functions are unsupported");
8449
+ if (names.length === 1 && !t.quoted && word === "coalesce")
8450
+ return { kind: "operator", op: "COALESCE", children };
8451
+ return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
8452
+ }
8453
+ if (this.peek().t === "str")
8454
+ fail("typed literals are unsupported");
8455
+ return { kind: "column", names };
8456
+ }
8457
+ }
8458
+ function parseScalarSql(sql) {
8459
+ if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
8460
+ fail("invalid SQL size or text");
8461
+ return new Parser(tokenize(sql)).parseAll();
8462
+ }
8463
+ var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
8464
+ var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
8465
+ var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
8466
+ function validateColumnExpressionSql(sql, options) {
8467
+ const { usingColumns, generated } = options;
8468
+ const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
8469
+ const columns = [];
8470
+ let nodes = 0;
8471
+ const visit = (node, depth) => {
8472
+ if (depth > 64 || ++nodes > 4096)
8473
+ fail("scalar expression is too complex");
8474
+ switch (node.kind) {
8475
+ case "constant":
8476
+ if (!primitive.has(node.type))
8477
+ fail(`unsupported scalar literal type ${node.type}`);
8478
+ return;
8479
+ case "column":
8480
+ if (!usingColumns || node.names.length !== 1)
8481
+ fail("column references are unsupported in this scope");
8482
+ columns.push(node.names[0]);
8483
+ return;
8484
+ case "cast":
8485
+ if (node.qualified)
8486
+ fail("qualified scalar cast types are unsupported");
8487
+ if (node.type === null || !primitive.has(node.type))
8488
+ fail("unsupported scalar cast");
8489
+ visit(node.child, depth + 1);
8490
+ return;
8491
+ case "comparison":
8492
+ visit(node.left, depth + 1);
8493
+ visit(node.right, depth + 1);
8494
+ return;
8495
+ case "conjunction":
8496
+ case "operator":
8497
+ node.children.forEach((c) => visit(c, depth + 1));
8498
+ return;
8499
+ case "function": {
8500
+ const lower = node.name.toLowerCase();
8501
+ const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
8502
+ if (!ok)
8503
+ fail(`unsupported scalar function '${node.name}'`);
8504
+ node.children.forEach((c) => visit(c, depth + 1));
8505
+ return;
8506
+ }
8507
+ }
8508
+ };
8509
+ try {
8510
+ visit(parseScalarSql(sql), 0);
8511
+ } catch (error) {
8512
+ if (error instanceof GrammarError)
8513
+ throw error;
8514
+ throw new GrammarError(String(error?.message ?? error));
8515
+ }
8516
+ return columns;
8517
+ }
8518
+ function validateNumericCheckSql(sql, resolveColumn) {
8519
+ const node = parseScalarSql(sql);
8520
+ if (node.kind !== "comparison")
8521
+ fail("native CHECK read supports only Boolean numeric comparisons");
8522
+ const comparison = node;
8523
+ for (const operand of [comparison.left, comparison.right]) {
8524
+ if (operand.kind === "constant") {
8525
+ if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
8526
+ fail("CHECK requires numeric operands");
8527
+ continue;
8528
+ }
8529
+ if (operand.kind !== "column")
8530
+ fail("native CHECK read supports only numeric column/constant comparisons");
8531
+ const column = operand;
8532
+ if (column.names.length !== 1)
8533
+ fail("CHECK requires unqualified column references");
8534
+ resolveColumn(column.names[0]);
8535
+ }
8536
+ }
8537
+
8538
+ // src/catalog/column-types.ts
8539
+ init_arrow();
8540
+ function isRowIdField(field) {
8541
+ return field.metadata?.has("is_row_id") ?? false;
8542
+ }
8543
+ function hasLogicalType(field) {
8544
+ for (const key of field.metadata?.keys() ?? [])
8545
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
8546
+ return true;
8547
+ return false;
8548
+ }
8549
+ function ordinaryStructChildren(field) {
8550
+ if (!isStruct(field.type) || hasLogicalType(field))
8551
+ return null;
8552
+ return field.type.children;
8553
+ }
8554
+ function isGeneratedField(field) {
8555
+ const m = field.metadata;
8556
+ return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
8557
+ }
8558
+ function duckdbPrimitive(field) {
8559
+ if (hasLogicalType(field))
8560
+ return null;
8561
+ const t = field.type;
8562
+ switch (t.typeId) {
8563
+ case TypeId.Bool:
8564
+ return "BOOLEAN";
8565
+ case TypeId.Utf8:
8566
+ return "VARCHAR";
8567
+ case TypeId.Int: {
8568
+ if (!(t.isSigned ?? t.signed ?? true))
8569
+ return null;
8570
+ return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
8571
+ }
8572
+ case TypeId.Float:
8573
+ return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
8574
+ case TypeId.Decimal:
8575
+ return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
8576
+ default:
8577
+ return null;
8578
+ }
8579
+ }
8580
+
7924
8581
  // src/catalog/column-expressions.ts
7925
8582
  var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
7926
8583
  var GENERATION_KEY = "vgi.column.generation.v1";
8584
+ var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
8585
+ var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
8586
+ var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
7927
8587
  var PROFILE = "vgi.expression.duckdb.scalar.v1";
7928
8588
  var MAX_BYTES = 8 * 1024 * 1024;
7929
8589
  var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
@@ -8034,9 +8694,24 @@ function validateEncoded(encoded, owner) {
8034
8694
  throw new Error("invalid SqlExpression record schema");
8035
8695
  const utf8 = new TextDecoder("utf-8", { fatal: true });
8036
8696
  textBuffers.forEach((buffer) => utf8.decode(buffer));
8037
- expression(decodeSqlExpression(bytes), owner);
8697
+ const value = decodeSqlExpression(bytes);
8698
+ expression(value, owner);
8699
+ return value.sql;
8038
8700
  }
8039
8701
  function generatedExpressionMetadata(sql, owner) {
8702
+ try {
8703
+ validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
8704
+ } catch (error) {
8705
+ throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
8706
+ }
8707
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
8708
+ }
8709
+ function defaultExpressionMetadata(sql, owner) {
8710
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
8711
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
8712
+ }
8713
+ function sqlExpression(sql, schemaPath) {
8714
+ const owner = [...schemaPath];
8040
8715
  const value = {
8041
8716
  sql,
8042
8717
  profile: PROFILE,
@@ -8050,7 +8725,7 @@ function generatedExpressionMetadata(sql, owner) {
8050
8725
  }
8051
8726
  };
8052
8727
  expression(value, owner);
8053
- return base64(encodeSqlExpression(value));
8728
+ return value;
8054
8729
  }
8055
8730
  function validateColumnExpressions(schema, owner, allowGenerated = true) {
8056
8731
  const type = (t) => {
@@ -8059,14 +8734,33 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
8059
8734
  if (t?.dictionary)
8060
8735
  type(t.dictionary);
8061
8736
  };
8062
- const field = (f) => {
8737
+ const topLevel = new Map;
8738
+ for (const f of schema.fields) {
8739
+ const key = String(f.name).toLowerCase();
8740
+ topLevel.set(key, [...topLevel.get(key) ?? [], f]);
8741
+ }
8742
+ const field = (f, top = false) => {
8063
8743
  const metadata = f.metadata ?? new Map;
8064
8744
  for (const key of metadata.keys()) {
8065
8745
  if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
8066
8746
  throw new Error("unknown generated metadata version");
8067
8747
  }
8748
+ const where = `column ${f.name}`;
8068
8749
  if (metadata.has("generated_expression"))
8069
- throw new Error("legacy generated expression requires explicit canonical translation");
8750
+ throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
8751
+ if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
8752
+ if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
8753
+ throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
8754
+ const type = duckdbPrimitive(f);
8755
+ if (!type || !DEFAULT_TYPES.has(type))
8756
+ throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
8757
+ const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
8758
+ try {
8759
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
8760
+ } catch (error) {
8761
+ throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
8762
+ }
8763
+ }
8070
8764
  if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
8071
8765
  throw new Error("generated expression and category must occur together");
8072
8766
  if (metadata.has(GENERATED_EXPRESSION_KEY)) {
@@ -8074,13 +8768,34 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
8074
8768
  throw new Error("only VIRTUAL generated columns are supported");
8075
8769
  if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
8076
8770
  throw new Error("generated column cannot have a default");
8077
- validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
8771
+ const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
8078
8772
  if (!allowGenerated)
8079
8773
  throw new Error("generated columns unsupported by this catalog");
8774
+ if (!f.nullable)
8775
+ throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
8776
+ const type = duckdbPrimitive(f);
8777
+ if (!type || !GENERATED_TYPES.has(type))
8778
+ throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
8779
+ let references;
8780
+ try {
8781
+ references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
8782
+ } catch (error) {
8783
+ throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
8784
+ }
8785
+ if (top) {
8786
+ for (const name of references) {
8787
+ const matches = topLevel.get(name.toLowerCase()) ?? [];
8788
+ if (matches.length !== 1)
8789
+ throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
8790
+ const operand = duckdbPrimitive(matches[0]);
8791
+ if (!operand || !GENERATED_TYPES.has(operand))
8792
+ throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
8793
+ }
8794
+ }
8080
8795
  }
8081
8796
  type(f.type);
8082
8797
  };
8083
- schema.fields.forEach(field);
8798
+ schema.fields.forEach((f) => field(f, true));
8084
8799
  }
8085
8800
  function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
8086
8801
  validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
@@ -8395,6 +9110,13 @@ class CatalogReadOnlyError extends VgiError {
8395
9110
  this.name = "CatalogReadOnlyError";
8396
9111
  }
8397
9112
  }
9113
+
9114
+ class CatalogNotFoundError extends VgiError {
9115
+ constructor(entity, name) {
9116
+ super(`${entity} '${name}' not found`, "NOT_FOUND");
9117
+ this.name = "CatalogNotFoundError";
9118
+ }
9119
+ }
8398
9120
  class ArgumentValidationError extends VgiError {
8399
9121
  constructor(message) {
8400
9122
  super(message, "INVALID_ARGUMENT");
@@ -10573,6 +11295,457 @@ var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
10573
11295
  var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
10574
11296
  var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
10575
11297
 
11298
+ // src/catalog/constraints.ts
11299
+ init_arrow();
11300
+ var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
11301
+ var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
11302
+ var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
11303
+ var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
11304
+ var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
11305
+ var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
11306
+ var CHECK_CONTEXT = {
11307
+ timezone: "UTC",
11308
+ collation: "binary",
11309
+ default_order: "asc",
11310
+ default_null_order: "nulls_last",
11311
+ preserve_insertion_order: true
11312
+ };
11313
+ function identifier(value, what) {
11314
+ if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
11315
+ throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
11316
+ }
11317
+ function objectRef(kind, schemaPath, name, ownerTable) {
11318
+ return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
11319
+ }
11320
+ function checkPaths(paths, what, topLevelOnly) {
11321
+ if (paths.length > 1024)
11322
+ throw new Error(`${what}: too many column paths`);
11323
+ const seen = new Set;
11324
+ for (const path of paths) {
11325
+ if (path.length === 0 || path.length > 64)
11326
+ throw new Error(`${what}: column path must have 1..64 components`);
11327
+ if (topLevelOnly && path.length !== 1)
11328
+ throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
11329
+ path.forEach((part) => identifier(part, `${what}: column path component`));
11330
+ const key = JSON.stringify(path);
11331
+ if (seen.has(key))
11332
+ throw new Error(`${what}: duplicate column path ${path.join(".")}`);
11333
+ seen.add(key);
11334
+ }
11335
+ }
11336
+ function constraintRecord(spec) {
11337
+ const what = `constraint '${spec.id}' on '${spec.table}'`;
11338
+ if (!spec.id || spec.id.includes("\x00"))
11339
+ throw new Error("constraint id must be nonempty without NUL");
11340
+ identifier(spec.table, "table");
11341
+ if (spec.schemaPath.length !== 1)
11342
+ throw new Error(`${what}: DuckDB reads only one-component schema paths`);
11343
+ identifier(spec.schemaPath[0], "schema");
11344
+ if (spec.enforcement !== "ENFORCED" || spec.validation !== "ALL_ROWS")
11345
+ throw new Error(`${what} is ${spec.enforcement}/${spec.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
11346
+ if (spec.declaredName !== undefined)
11347
+ identifier(spec.declaredName, `${what}: declaredName`);
11348
+ if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
11349
+ throw new Error("checkSql is required for CHECK and only CHECK");
11350
+ if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
11351
+ throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
11352
+ if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
11353
+ throw new Error("NOT_NULL requires exactly one column path");
11354
+ if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
11355
+ throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
11356
+ checkPaths(spec.columns, what, spec.kind !== "NOT_NULL");
11357
+ if (spec.checkSql !== undefined) {
11358
+ try {
11359
+ validateNumericCheckSql(spec.checkSql, () => {});
11360
+ } catch (error) {
11361
+ throw new Error(`${what}: ${error.message} (CHECK SQL: ${spec.checkSql})`);
11362
+ }
11363
+ }
11364
+ const ref = spec.references;
11365
+ if (ref) {
11366
+ if (ref.columns.length !== spec.columns.length)
11367
+ throw new Error("foreign key local and referenced arity must match");
11368
+ if (JSON.stringify(ref.schemaPath) !== JSON.stringify(spec.schemaPath))
11369
+ throw new Error(`${what}: DuckDB reads only foreign keys to a table in the same schema`);
11370
+ identifier(ref.table, `${what}: referenced table`);
11371
+ identifier(ref.constraintId, `${what}: referenced constraintId`);
11372
+ checkPaths(ref.columns, `${what} (referenced)`, true);
11373
+ }
11374
+ const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
11375
+ sql: spec.checkSql,
11376
+ profile: ROW_SCALAR_EXPRESSION,
11377
+ schema_path: spec.schemaPath,
11378
+ evaluation_context: CHECK_CONTEXT
11379
+ });
11380
+ const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
11381
+ referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
11382
+ referenced_column_paths: ref.columns,
11383
+ match: "SIMPLE",
11384
+ on_update: "NO_ACTION",
11385
+ on_delete: "NO_ACTION"
11386
+ });
11387
+ return encodeASD(ConstraintInfoSchema, {
11388
+ ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
11389
+ definition: encodeASD(ConstraintDefinitionSchema, {
11390
+ kind: spec.kind,
11391
+ column_paths: spec.columns,
11392
+ declared_name: spec.declaredName ?? null,
11393
+ check_expression: check,
11394
+ foreign_key: foreign
11395
+ }),
11396
+ enforcement: spec.enforcement,
11397
+ validation: spec.validation,
11398
+ referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
11399
+ });
11400
+ }
11401
+ var KNOWN = {
11402
+ read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
11403
+ ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
11404
+ write: new Set([CONSTRAINT_ENFORCE]),
11405
+ transaction: new Set([TRANSACTION_DDL])
11406
+ };
11407
+ var REQUIRES = {
11408
+ [ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
11409
+ [CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
11410
+ [CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
11411
+ [CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
11412
+ "vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
11413
+ "vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
11414
+ };
11415
+ var CATEGORIES = ["read", "ddl", "write", "transaction"];
11416
+ function catalogCapabilities(init = {}) {
11417
+ return {
11418
+ read: [...new Set(init.read ?? [])].sort(),
11419
+ ddl: [...new Set(init.ddl ?? [])].sort(),
11420
+ write: [...new Set(init.write ?? [])].sort(),
11421
+ transaction: [...new Set(init.transaction ?? [])].sort()
11422
+ };
11423
+ }
11424
+ function constraintCapabilities(options = {}) {
11425
+ const enforce = options.enforce || options.create;
11426
+ return catalogCapabilities({
11427
+ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION],
11428
+ ddl: [...options.create ? [CONSTRAINT_CREATE] : [], ...options.mutate ? [CONSTRAINT_MUTATE] : []],
11429
+ write: enforce ? [CONSTRAINT_ENFORCE] : [],
11430
+ transaction: options.transactionDdl ? [TRANSACTION_DDL] : []
11431
+ });
11432
+ }
11433
+ function offeredCatalog(clientCapabilities) {
11434
+ if (clientCapabilities == null)
11435
+ return null;
11436
+ const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
11437
+ return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
11438
+ }
11439
+ function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
11440
+ const offered = offeredCatalog(clientCapabilities);
11441
+ if (offered == null)
11442
+ return catalogCapabilities();
11443
+ const chosen = new Set;
11444
+ for (const category of CATEGORIES)
11445
+ for (const p of available[category] ?? [])
11446
+ if (offered[category]?.includes(p))
11447
+ chosen.add(p);
11448
+ if (!supportsTransactions)
11449
+ chosen.delete(TRANSACTION_DDL);
11450
+ for (let changed = true;changed; ) {
11451
+ changed = false;
11452
+ for (const p of [...chosen])
11453
+ if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
11454
+ chosen.delete(p);
11455
+ changed = true;
11456
+ }
11457
+ }
11458
+ const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
11459
+ return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
11460
+ }
11461
+ function selectReadProfiles(available, clientCapabilities) {
11462
+ return selectCatalogCapabilities(catalogCapabilities({ read: [...available] }), clientCapabilities).read;
11463
+ }
11464
+ function defaultClientCapabilities(engine = "vgi-typescript") {
11465
+ return {
11466
+ engine,
11467
+ native_formats: [],
11468
+ catalogs: [],
11469
+ can_stream: true,
11470
+ filter_encodings: [],
11471
+ catalog: encodeCatalogCapabilities(catalogCapabilities({ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] })),
11472
+ query_pushdown: null
11473
+ };
11474
+ }
11475
+ function capabilitiesEmpty(caps) {
11476
+ return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
11477
+ }
11478
+ function readConstraintRecord(bytes) {
11479
+ const info = decodeASD(ConstraintInfoSchema, bytes);
11480
+ const ref = decodeASD(CatalogObjectRefSchema, info.ref);
11481
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
11482
+ const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
11483
+ const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
11484
+ const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
11485
+ return {
11486
+ schemaPath: [...ref.schema_path],
11487
+ table: ref.owner_table ?? "",
11488
+ id: ref.name,
11489
+ kind: def.kind,
11490
+ columns: [...def.column_paths].map((p) => [...p]),
11491
+ enforcement: info.enforcement,
11492
+ validation: info.validation,
11493
+ declaredName: def.declared_name ?? null,
11494
+ checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
11495
+ references: fk == null || target == null ? null : {
11496
+ schemaPath: [...target.schema_path],
11497
+ table: target.name,
11498
+ columns: [...fk.referenced_column_paths].map((p) => [...p]),
11499
+ constraintId: targetKey?.name ?? null,
11500
+ constraintTable: targetKey?.owner_table ?? null,
11501
+ constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
11502
+ match: fk.match,
11503
+ onUpdate: fk.on_update,
11504
+ onDelete: fk.on_delete
11505
+ }
11506
+ };
11507
+ }
11508
+ function fieldsByExactName(fields, name) {
11509
+ const out = [];
11510
+ fields.forEach((f, i) => {
11511
+ if (f.name === name)
11512
+ out.push(i);
11513
+ });
11514
+ return out;
11515
+ }
11516
+ function validateTableConstraints(table, schemaPath, fields, constraints) {
11517
+ if (constraints.length > 1024)
11518
+ throw new Error(`Table '${table}': too many constraints (at most 1024)`);
11519
+ const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
11520
+ if (rowIds.length > 1)
11521
+ throw new Error(`Table '${table}': at most one column may carry is_row_id`);
11522
+ const rowId = rowIds[0] ?? -1;
11523
+ const records = [];
11524
+ const required = new Set;
11525
+ const ids = new Set;
11526
+ const labels = new Set;
11527
+ let primaryKeys = 0;
11528
+ for (const bytes of constraints) {
11529
+ let record;
11530
+ try {
11531
+ record = readConstraintRecord(bytes);
11532
+ } catch (error) {
11533
+ throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
11534
+ }
11535
+ const where = `Table '${table}': constraint '${record.id}'`;
11536
+ const fail = (message) => {
11537
+ throw new Error(`${where}: ${message}`);
11538
+ };
11539
+ if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
11540
+ fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
11541
+ if (ids.has(record.id))
11542
+ fail("duplicate constraint id");
11543
+ ids.add(record.id);
11544
+ if (record.declaredName != null) {
11545
+ const label = record.declaredName.toLowerCase();
11546
+ if (labels.has(label))
11547
+ fail(`duplicate declared name '${record.declaredName}'`);
11548
+ labels.add(label);
11549
+ }
11550
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
11551
+ fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
11552
+ try {
11553
+ checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
11554
+ } catch (error) {
11555
+ fail(error.message);
11556
+ }
11557
+ const resolveTop = (path) => {
11558
+ const matches = fieldsByExactName(fields, path[0]);
11559
+ if (matches.length !== 1 || matches[0] === rowId)
11560
+ fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
11561
+ return matches[0];
11562
+ };
11563
+ switch (record.kind) {
11564
+ case "CHECK": {
11565
+ if (record.checkSql == null)
11566
+ fail("CHECK without an expression");
11567
+ validateCheckRecord(bytes, where, schemaPath, fields, rowId);
11568
+ break;
11569
+ }
11570
+ case "NOT_NULL": {
11571
+ if (record.columns.length !== 1)
11572
+ fail("NOT_NULL requires exactly one column path");
11573
+ const path = record.columns[0];
11574
+ let field = fields[resolveTop(path)];
11575
+ for (let depth = 1;depth < path.length; depth++) {
11576
+ const children = ordinaryStructChildren(field);
11577
+ if (!children)
11578
+ fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
11579
+ const matches = fieldsByExactName(children, path[depth]);
11580
+ if (matches.length !== 1)
11581
+ fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
11582
+ field = children[matches[0]];
11583
+ }
11584
+ if (path.length === 1 && isGeneratedField(field))
11585
+ fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
11586
+ required.add(JSON.stringify(path));
11587
+ break;
11588
+ }
11589
+ case "PRIMARY_KEY":
11590
+ case "UNIQUE": {
11591
+ for (const path of record.columns) {
11592
+ const index = resolveTop(path);
11593
+ if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
11594
+ fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
11595
+ }
11596
+ if (record.kind === "PRIMARY_KEY") {
11597
+ if (++primaryKeys > 1)
11598
+ fail("a table may have only one PRIMARY KEY");
11599
+ for (const path of record.columns)
11600
+ required.add(JSON.stringify(path));
11601
+ }
11602
+ break;
11603
+ }
11604
+ case "FOREIGN_KEY": {
11605
+ record.columns.forEach(resolveTop);
11606
+ const ref = record.references;
11607
+ if (ref == null || ref.constraintId == null)
11608
+ fail("FOREIGN_KEY requires a referenced table and referenced constraint");
11609
+ if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
11610
+ fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
11611
+ if (ref.columns.length !== record.columns.length)
11612
+ fail("foreign key arity mismatch");
11613
+ try {
11614
+ checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
11615
+ } catch (error) {
11616
+ fail(error.message);
11617
+ }
11618
+ if (ref.match !== undefined && ref.match !== "SIMPLE")
11619
+ fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
11620
+ for (const action of [ref.onUpdate, ref.onDelete])
11621
+ if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
11622
+ fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
11623
+ break;
11624
+ }
11625
+ default:
11626
+ fail(`unknown constraint kind ${String(record.kind)}`);
11627
+ }
11628
+ records.push(record);
11629
+ }
11630
+ return { records, required };
11631
+ }
11632
+ function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
11633
+ const info = decodeASD(ConstraintInfoSchema, bytes);
11634
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
11635
+ const expression = decodeASD(SqlExpressionSchema, def.check_expression);
11636
+ const fail = (message) => {
11637
+ throw new Error(`${where}: ${message}`);
11638
+ };
11639
+ if (expression.profile !== ROW_SCALAR_EXPRESSION)
11640
+ fail(`unsupported CHECK expression profile ${expression.profile}`);
11641
+ if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
11642
+ fail("CHECK expression belongs to another schema");
11643
+ const context = expression.evaluation_context ?? {};
11644
+ for (const [key, value] of Object.entries(CHECK_CONTEXT))
11645
+ if (context[key] !== value)
11646
+ fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
11647
+ try {
11648
+ validateNumericCheckSql(expression.sql, (name) => {
11649
+ const lower = name.toLowerCase();
11650
+ const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
11651
+ if (matches.length > 1)
11652
+ throw new Error(`ambiguous CHECK column reference ${name}`);
11653
+ if (matches.length === 0 || matches[0] === rowId)
11654
+ throw new Error(`CHECK references a missing or row-id column ${name}`);
11655
+ const column = fields[matches[0]];
11656
+ if (column.metadata.has("ARROW:extension:name"))
11657
+ throw new Error(`CHECK operand ${name} has an extension type`);
11658
+ if (isGeneratedField(column))
11659
+ throw new Error(`CHECK operand ${name} is a generated column`);
11660
+ const type = duckdbPrimitive(column);
11661
+ if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
11662
+ throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
11663
+ });
11664
+ } catch (error) {
11665
+ fail(`${error.message} (CHECK SQL: ${expression.sql})`);
11666
+ }
11667
+ }
11668
+ function validateForeignKeyTargets(tables) {
11669
+ const key = (schemaPath, name) => JSON.stringify([...schemaPath, name]);
11670
+ const byTable = new Map;
11671
+ for (const t of tables)
11672
+ byTable.set(key(t.schemaPath, t.name), t.constraints.map(readConstraintRecord));
11673
+ for (const t of tables) {
11674
+ for (const record of byTable.get(key(t.schemaPath, t.name)) ?? []) {
11675
+ if (record.kind !== "FOREIGN_KEY" || record.references == null)
11676
+ continue;
11677
+ const ref = record.references;
11678
+ const where = `Table '${t.name}': constraint '${record.id}'`;
11679
+ const target = byTable.get(key(ref.schemaPath, ref.table));
11680
+ if (!target)
11681
+ throw new Error(`${where}: references table ${[...ref.schemaPath, ref.table].join(".")}, which this catalog does not serve`);
11682
+ const key_ = target.find((r) => r.id === ref.constraintId);
11683
+ if (!key_ || key_.kind !== "PRIMARY_KEY" && key_.kind !== "UNIQUE")
11684
+ throw new Error(`${where}: referenced constraint '${ref.constraintId}' is not a PRIMARY_KEY or UNIQUE record of '${ref.table}'`);
11685
+ const want = new Set(ref.columns.map((p) => JSON.stringify(p)));
11686
+ if (key_.columns.length !== want.size || !key_.columns.every((p) => want.has(JSON.stringify(p))))
11687
+ throw new Error(`${where}: referenced columns do not match constraint '${ref.constraintId}' of '${ref.table}'`);
11688
+ }
11689
+ }
11690
+ }
11691
+ function servedConstraintFields(fields, required) {
11692
+ const rewrite = (list, prefix) => {
11693
+ let changed = false;
11694
+ const out = list.map((f) => {
11695
+ if (prefix.length === 0 && isRowIdField(f))
11696
+ return f;
11697
+ const path = [...prefix, f.name];
11698
+ const nullable = !required.has(JSON.stringify(path));
11699
+ const children = ordinaryStructChildren(f);
11700
+ const newChildren = children ? rewrite(children, path) : null;
11701
+ if (nullable === f.nullable && (newChildren == null || newChildren === children))
11702
+ return f;
11703
+ changed = true;
11704
+ const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
11705
+ return field2(f.name, type, nullable, new Map(f.metadata));
11706
+ });
11707
+ return changed ? out : list;
11708
+ };
11709
+ return rewrite(fields, []);
11710
+ }
11711
+ function validateConstraintNullability(table, fields, constraints) {
11712
+ const schemaPath = constraints.length ? readConstraintRecord(constraints[0]).schemaPath : ["main"];
11713
+ validateTableConstraints(table, schemaPath, fields, constraints);
11714
+ }
11715
+ function translateLegacyGenerated(fields, owner, table) {
11716
+ let changed = false;
11717
+ const out = fields.map((f) => {
11718
+ const sql = f.metadata.get("generated_expression");
11719
+ if (sql === undefined)
11720
+ return f;
11721
+ if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
11722
+ throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
11723
+ const metadata = new Map(f.metadata);
11724
+ metadata.delete("generated_expression");
11725
+ metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
11726
+ metadata.set(GENERATION_KEY, "virtual");
11727
+ changed = true;
11728
+ return field2(f.name, f.type, f.nullable, metadata);
11729
+ });
11730
+ return changed ? out : fields;
11731
+ }
11732
+ function servedTableSchema(table, schemaPath, schema, constraints) {
11733
+ let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
11734
+ const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
11735
+ fields = servedConstraintFields(fields, required);
11736
+ return fields === schema.fields ? schema : schema2(fields, schema.metadata);
11737
+ }
11738
+ function servedTableInfo(info) {
11739
+ if (!info.columns || info.columns.length === 0) {
11740
+ if ((info.constraints ?? []).length)
11741
+ throw new Error(`Table '${info.name}': constraints on a table without columns`);
11742
+ return info;
11743
+ }
11744
+ const schema = deserializeSchema(info.columns);
11745
+ const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
11746
+ return served === schema ? info : { ...info, columns: serializeSchema(served) };
11747
+ }
11748
+
10576
11749
  // src/catalog/column-metadata.ts
10577
11750
  function scalarText(value) {
10578
11751
  for (let i = 0;i < value.length; i++) {
@@ -10724,9 +11897,21 @@ function validateTableInfoColumns(info) {
10724
11897
  validateColumnExpressionsIpc(info.columns, info.schema_path);
10725
11898
  }
10726
11899
  }
11900
+ function servedValidatedTableInfo(info) {
11901
+ if (info.columns.length)
11902
+ validateColumnMetadataIpc(info.columns);
11903
+ const served = servedTableInfo(info);
11904
+ if (served.columns.length) {
11905
+ try {
11906
+ validateColumnExpressionsIpc(served.columns, served.schema_path);
11907
+ } catch (error) {
11908
+ throw new Error(`Table '${served.name}': ${error.message}`);
11909
+ }
11910
+ }
11911
+ return served;
11912
+ }
10727
11913
  function encodeValidatedTableInfo(info) {
10728
- validateTableInfoColumns(info);
10729
- return encodeTableInfo(info);
11914
+ return encodeTableInfo(servedValidatedTableInfo(info));
10730
11915
  }
10731
11916
 
10732
11917
  // src/protocol/handlers/catalog/admin.ts
@@ -10748,128 +11933,6 @@ function catalogStringMap(raw) {
10748
11933
  return result;
10749
11934
  }
10750
11935
 
10751
- // src/catalog/constraints.ts
10752
- init_arrow();
10753
- var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
10754
- var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
10755
- function objectRef(kind, schemaPath, name, ownerTable) {
10756
- return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
10757
- }
10758
- function constraintRecord(spec) {
10759
- if (!spec.id || spec.id.includes("\x00"))
10760
- throw new Error("constraint id must be nonempty without NUL");
10761
- if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
10762
- throw new Error("checkSql is required for CHECK and only CHECK");
10763
- if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
10764
- throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
10765
- if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
10766
- throw new Error("NOT_NULL requires exactly one column path");
10767
- if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
10768
- throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
10769
- if (spec.references && spec.references.columns.length !== spec.columns.length)
10770
- throw new Error("foreign key local and referenced arity must match");
10771
- const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
10772
- sql: spec.checkSql,
10773
- profile: ROW_SCALAR_EXPRESSION,
10774
- schema_path: spec.schemaPath,
10775
- evaluation_context: {
10776
- timezone: "UTC",
10777
- collation: "binary",
10778
- default_order: "asc",
10779
- default_null_order: "nulls_last",
10780
- preserve_insertion_order: true
10781
- }
10782
- });
10783
- const ref = spec.references;
10784
- const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
10785
- referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
10786
- referenced_column_paths: ref.columns,
10787
- match: "SIMPLE",
10788
- on_update: "NO_ACTION",
10789
- on_delete: "NO_ACTION"
10790
- });
10791
- return encodeASD(ConstraintInfoSchema, {
10792
- ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
10793
- definition: encodeASD(ConstraintDefinitionSchema, {
10794
- kind: spec.kind,
10795
- column_paths: spec.columns,
10796
- declared_name: spec.declaredName ?? null,
10797
- check_expression: check,
10798
- foreign_key: foreign
10799
- }),
10800
- enforcement: spec.enforcement,
10801
- validation: spec.validation,
10802
- referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
10803
- });
10804
- }
10805
- function selectReadProfiles(available, clientCapabilities) {
10806
- if (clientCapabilities == null || available.length === 0)
10807
- return [];
10808
- const client = decodeASD(ClientCapabilitiesSchema, clientCapabilities);
10809
- const offered = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
10810
- const selected = available.filter((p) => offered.includes(p));
10811
- if (!selected.includes(CONSTRAINT_RECORDS_READ))
10812
- return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
10813
- return selected.sort();
10814
- }
10815
- function readConstraintRecord(bytes) {
10816
- const info = decodeASD(ConstraintInfoSchema, bytes);
10817
- const ref = decodeASD(CatalogObjectRefSchema, info.ref);
10818
- const def = decodeASD(ConstraintDefinitionSchema, info.definition);
10819
- const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
10820
- const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
10821
- const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
10822
- return {
10823
- schemaPath: [...ref.schema_path],
10824
- table: ref.owner_table ?? "",
10825
- id: ref.name,
10826
- kind: def.kind,
10827
- columns: [...def.column_paths].map((p) => [...p]),
10828
- enforcement: info.enforcement,
10829
- validation: info.validation,
10830
- declaredName: def.declared_name ?? null,
10831
- checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
10832
- references: fk == null || target == null ? null : {
10833
- schemaPath: [...target.schema_path],
10834
- table: target.name,
10835
- columns: [...fk.referenced_column_paths].map((p) => [...p]),
10836
- constraintId: targetKey?.name ?? null
10837
- }
10838
- };
10839
- }
10840
- function ordinaryStructChildren(field) {
10841
- if (!isStruct(field.type))
10842
- return null;
10843
- for (const key of field.metadata.keys())
10844
- if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
10845
- return null;
10846
- return field.type.children;
10847
- }
10848
- function validateConstraintNullability(table, fields, constraints) {
10849
- const required = new Set;
10850
- for (const bytes of constraints) {
10851
- const record = readConstraintRecord(bytes);
10852
- if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
10853
- throw new Error(`Table '${table}': constraint '${record.id}' is ${record.enforcement}/${record.validation}; ` + "DuckDB accepts only ENFORCED + ALL_ROWS records");
10854
- if (record.kind === "NOT_NULL" || record.kind === "PRIMARY_KEY")
10855
- for (const path of record.columns)
10856
- required.add(JSON.stringify(path));
10857
- }
10858
- const walk = (children, prefix) => {
10859
- for (const field of children) {
10860
- const path = [...prefix, field.name];
10861
- const key = JSON.stringify(path);
10862
- if (field.nullable === required.has(key)) {
10863
- throw new Error(field.nullable ? `Table '${table}': column ${path.join(".")} is in a NOT_NULL/PRIMARY_KEY record but its Arrow field is nullable` : `Table '${table}': column ${path.join(".")} is non-nullable in Arrow but no NOT_NULL/PRIMARY_KEY record names it; ` + "declare one with constraintRecord() or make the field nullable");
10864
- }
10865
- const nested = ordinaryStructChildren(field);
10866
- if (nested)
10867
- walk(nested, path);
10868
- }
10869
- };
10870
- walk(fields, []);
10871
- }
10872
-
10873
11936
  // src/protocol/handlers/catalog/contents.ts
10874
11937
  import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
10875
11938
 
@@ -10881,12 +11944,10 @@ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@qu
10881
11944
  var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
10882
11945
  var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
10883
11946
  function encodeCatalogStreams(inventory) {
10884
- for (const schema of inventory)
10885
- for (const table of schema.tables)
10886
- validateTableInfoColumns(table);
11947
+ const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
10887
11948
  const streams = {
10888
11949
  schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
10889
- tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
11950
+ tables: encodeASDCollection(TableInfoSchema, tables),
10890
11951
  views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
10891
11952
  functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
10892
11953
  macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
@@ -11546,6 +12607,56 @@ class CatalogInterface {
11546
12607
  tableCreate(attachOpaqueData, schemaPath, name, columns, onConflict, constraintDefinitions, transactionOpaqueData) {
11547
12608
  throw new CatalogReadOnlyError("table_create");
11548
12609
  }
12610
+ catalogCapabilities(_attachOpaqueData) {
12611
+ const proto = CatalogInterface.prototype;
12612
+ if (this.tableConstraintsApply !== proto.tableConstraintsApply || this._implementsLegacyNotNull())
12613
+ return constraintCapabilities({ mutate: true, enforce: true });
12614
+ return null;
12615
+ }
12616
+ _implementsLegacyNotNull() {
12617
+ const proto = CatalogInterface.prototype;
12618
+ return this.tableNotNullSet !== proto.tableNotNullSet || this.tableNotNullDrop !== proto.tableNotNullDrop;
12619
+ }
12620
+ async tableConstraintsApply(request) {
12621
+ if (!this._implementsLegacyNotNull())
12622
+ throw new VgiError("catalog_table_constraints_apply is not implemented by this catalog", "UNIMPLEMENTED");
12623
+ const target = decodeCatalogObjectRef(request.table);
12624
+ const attach = request.attach_opaque_data;
12625
+ const tx = request.transaction_opaque_data ?? undefined;
12626
+ const schemaPath = [...target.schema_path];
12627
+ const read = async () => {
12628
+ const info = await this.tableGet(attach, schemaPath, target.name, undefined, undefined, tx);
12629
+ if (!info)
12630
+ throw new CatalogNotFoundError("Table", target.name);
12631
+ return info;
12632
+ };
12633
+ const before = await read();
12634
+ if (!sameBytes2(before.definition_revision ?? null, request.expected_revision))
12635
+ throw new VgiError(`Table '${target.name}': definition_revision changed; retry the statement`, "FAILED_PRECONDITION");
12636
+ const records = (before.constraints ?? []).map(readConstraintRecord);
12637
+ for (const bytes of request.changes) {
12638
+ const change = decodeConstraintChange(bytes);
12639
+ if (change.operation === "ADD" && change.definition != null) {
12640
+ const def = decodeConstraintDefinition(change.definition);
12641
+ if (def.kind === "NOT_NULL" && def.column_paths.length === 1 && def.column_paths[0].length === 1) {
12642
+ await this.tableNotNullSet(attach, schemaPath, target.name, [...def.column_paths[0]], false, tx);
12643
+ continue;
12644
+ }
12645
+ } else if (change.operation === "DROP" && change.ref != null) {
12646
+ const id = decodeCatalogObjectRef(change.ref).name;
12647
+ const record = records.find((r) => r.id === id);
12648
+ if (record?.kind === "NOT_NULL" && record.columns[0]?.length === 1) {
12649
+ await this.tableNotNullDrop(attach, schemaPath, target.name, record.columns[0], false, tx);
12650
+ continue;
12651
+ }
12652
+ }
12653
+ throw new VgiError("catalog_table_constraints_apply: only ADD/DROP of a top-level NOT_NULL routes to tableNotNullSet/tableNotNullDrop; implement tableConstraintsApply", "UNIMPLEMENTED");
12654
+ }
12655
+ const after = await read();
12656
+ if (after.definition_revision == null || sameBytes2(after.definition_revision, before.definition_revision ?? null))
12657
+ throw new VgiError(`Table '${target.name}': the NOT NULL change was applied but tableGet still serves the old definition_revision; ` + "a catalog using tableNotNullSet/tableNotNullDrop must rotate it (or implement tableConstraintsApply)", "INTERNAL");
12658
+ return { table: request.table, definition_revision: after.definition_revision, constraints: after.constraints ?? [] };
12659
+ }
11549
12660
  tableDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
11550
12661
  throw new CatalogReadOnlyError("table_drop");
11551
12662
  }
@@ -11673,6 +12784,16 @@ class CatalogInterface {
11673
12784
  transactionCommit(attachOpaqueData, transactionOpaqueData) {}
11674
12785
  transactionRollback(attachOpaqueData, transactionOpaqueData) {}
11675
12786
  }
12787
+ function sameBytes2(a, b) {
12788
+ if (a == null || b == null)
12789
+ return a == b;
12790
+ if (a.length !== b.length)
12791
+ return false;
12792
+ for (let i = 0;i < a.length; i++)
12793
+ if (a[i] !== b[i])
12794
+ return false;
12795
+ return true;
12796
+ }
11676
12797
 
11677
12798
  // src/attach-ticket.ts
11678
12799
  init_arrow();
@@ -12232,13 +13353,10 @@ function catalogAdminHandlers(getCatalog, signingKey) {
12232
13353
  }
12233
13354
  const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
12234
13355
  const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, clientCapabilities);
12235
- if (result.catalog_capabilities != null) {
12236
- const available = decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities));
12237
- const chosen = result.selected_capabilities == null ? { read: [], ddl: [], write: [], transaction: [] } : decodeCatalogCapabilities(toUint8Array(result.selected_capabilities));
12238
- result.selected_capabilities = encodeCatalogCapabilities({
12239
- ...chosen,
12240
- read: selectReadProfiles(available.read, clientCapabilities)
12241
- });
13356
+ const advertised = result.catalog_capabilities != null ? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities)) : await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
13357
+ if (!capabilitiesEmpty(advertised)) {
13358
+ result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
13359
+ result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
12242
13360
  }
12243
13361
  const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
12244
13362
  return wrapResult(buildCatalogAttachResult({
@@ -12375,27 +13493,39 @@ import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-
12375
13493
  // src/catalog/unconstrained-columns.ts
12376
13494
  init_arrow();
12377
13495
  import { MethodNotImplementedError as MethodNotImplementedError3 } from "@query-farm/vgi-rpc";
12378
- function requireUnconstrainedColumns(columns) {
12379
- const visit = (field, top, depth) => {
13496
+ function requireCreateColumns(columns, constraintDefinitions = []) {
13497
+ const required = new Set;
13498
+ for (const bytes of constraintDefinitions) {
13499
+ let def;
13500
+ try {
13501
+ def = decodeConstraintDefinition(bytes);
13502
+ } catch (error) {
13503
+ throw new Error(`catalog_table_create: undecodable constraint definition: ${error.message}`);
13504
+ }
13505
+ if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
13506
+ for (const path of def.column_paths)
13507
+ required.add(JSON.stringify([...path]));
13508
+ }
13509
+ const visit = (field, path, depth) => {
12380
13510
  if (depth > 64)
12381
13511
  throw new MethodNotImplementedError3("catalog_table_create: column nesting exceeds supported depth");
12382
- if (top && field.metadata?.has("is_row_id"))
13512
+ if (depth === 0 && field.metadata?.has("is_row_id"))
12383
13513
  return;
12384
13514
  for (const key of field.metadata?.keys() ?? []) {
12385
13515
  if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
12386
13516
  throw new MethodNotImplementedError3("catalog_table_create: logical column types require negotiation");
12387
13517
  }
12388
13518
  }
12389
- if (!field.nullable) {
12390
- throw new MethodNotImplementedError3("catalog_table_create: nonnullable user columns require canonical constraints");
13519
+ if (!field.nullable && !required.has(JSON.stringify(path))) {
13520
+ throw new MethodNotImplementedError3(`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`);
12391
13521
  }
12392
13522
  if (isStruct(field.type)) {
12393
13523
  for (const child of field.type.children)
12394
- visit(child, false, depth + 1);
13524
+ visit(child, [...path, child.name], depth + 1);
12395
13525
  }
12396
13526
  };
12397
13527
  for (const field of deserializeSchema(columns).fields)
12398
- visit(field, true, 0);
13528
+ visit(field, [field.name], 0);
12399
13529
  }
12400
13530
 
12401
13531
  // src/protocol/handlers/catalog/table.ts
@@ -12417,19 +13547,57 @@ function catalogTableHandlers(getCatalog, signingKey) {
12417
13547
  const catalogTableCreate = catalogHandler(signingKey, async (params) => {
12418
13548
  if (params.constraint_definitions == null)
12419
13549
  throw new Error("constraint_definitions is required");
12420
- if (Array.from(params.constraint_definitions).length > 0) {
12421
- throw new MethodNotImplementedError4("catalog_table_create: canonical constraint enforcement is not supported");
12422
- }
13550
+ const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
12423
13551
  if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
12424
13552
  throw new MethodNotImplementedError4("catalog_table_create: table metadata/options/layout profiles are not supported");
12425
13553
  }
13554
+ const attach = toUint8Array(params.attach_opaque_data);
13555
+ const cat = getCatalog();
13556
+ if (definitions.length > 0) {
13557
+ const caps = await cat.catalogCapabilities(attach);
13558
+ if (caps != null && !(caps.ddl.includes(CONSTRAINT_CREATE) && caps.write.includes(CONSTRAINT_ENFORCE))) {
13559
+ 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");
13560
+ }
13561
+ }
12426
13562
  validateColumnMetadataIpc(toUint8Array(params.columns));
12427
13563
  validateColumnExpressionsIpc(toUint8Array(params.columns), params.schema_path);
12428
- requireUnconstrainedColumns(toUint8Array(params.columns));
12429
- const cat = getCatalog();
12430
- 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);
13564
+ requireCreateColumns(toUint8Array(params.columns), definitions);
13565
+ 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);
12431
13566
  return {};
12432
13567
  });
13568
+ const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
13569
+ const attach = toUint8Array(params.attach_opaque_data);
13570
+ const cat = getCatalog();
13571
+ const caps = await cat.catalogCapabilities(attach);
13572
+ if (caps != null && !caps.ddl.includes(CONSTRAINT_MUTATE)) {
13573
+ throw new MethodNotImplementedError4("catalog_table_constraints_apply: this catalog does not advertise vgi.constraint.mutate.v1");
13574
+ }
13575
+ const table = toUint8Array(params.table);
13576
+ const expected = toUint8Array(params.expected_revision);
13577
+ const changes = Array.from(params.changes, (c) => toUint8Array(c));
13578
+ if (expected.length === 0 || changes.length === 0)
13579
+ throw new Error("catalog_table_constraints_apply: empty revision or change list");
13580
+ const snapshot = await cat.tableConstraintsApply({
13581
+ attach_opaque_data: attach,
13582
+ table,
13583
+ expected_revision: expected,
13584
+ changes,
13585
+ transaction_opaque_data: params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : null
13586
+ });
13587
+ const want = decodeCatalogObjectRef(table);
13588
+ const got = decodeCatalogObjectRef(toUint8Array(snapshot.table));
13589
+ if (got.name !== want.name || JSON.stringify([...got.schema_path]) !== JSON.stringify([...want.schema_path]))
13590
+ throw new Error("catalog_table_constraints_apply: the catalog returned a snapshot of a different table");
13591
+ const revision = toUint8Array(snapshot.definition_revision);
13592
+ if (revision.length === 0 || revision.length === expected.length && revision.every((b, i) => b === expected[i]))
13593
+ throw new Error(`catalog_table_constraints_apply: table '${want.name}' must return a new, nonempty definition_revision`);
13594
+ for (const record of snapshot.constraints) {
13595
+ const view = readConstraintRecord(toUint8Array(record));
13596
+ if (view.table !== want.name || JSON.stringify(view.schemaPath) !== JSON.stringify([...want.schema_path]))
13597
+ throw new Error(`catalog_table_constraints_apply: constraint '${view.id}' belongs to another table`);
13598
+ }
13599
+ return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
13600
+ });
12433
13601
  const catalogTableDrop = catalogHandler(signingKey, async (params) => {
12434
13602
  const cat = getCatalog();
12435
13603
  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);
@@ -12517,9 +13685,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
12517
13685
  return {};
12518
13686
  });
12519
13687
  return {
12520
- catalogTableConstraintsApply: async () => {
12521
- throw new MethodNotImplementedError4("catalog_table_constraints_apply");
12522
- },
13688
+ catalogTableConstraintsApply,
12523
13689
  catalogTableGet,
12524
13690
  catalogTableCreate,
12525
13691
  catalogTableDrop,
@@ -14270,6 +15436,10 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14270
15436
  const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
14271
15437
  return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
14272
15438
  }
15439
+ catalogCapabilities(_attachOpaqueData) {
15440
+ const read = this.catalogReadProfiles();
15441
+ return read.length ? catalogCapabilities({ read }) : null;
15442
+ }
14273
15443
  detach(attachOpaqueData) {
14274
15444
  for (const [name, id] of this._attachments) {
14275
15445
  if (bufferEquals(id, attachOpaqueData)) {
@@ -14330,8 +15500,12 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14330
15500
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
14331
15501
  if (!schema || !schema.tables)
14332
15502
  return [];
14333
- return await Promise.all(schema.tables.map(async (t) => {
15503
+ const infos = await Promise.all(schema.tables.map(async (t) => {
15504
+ if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
15505
+ throw new Error(`Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` + "declare canonical records with constraintRecord() in `constraints` instead");
15506
+ }
14334
15507
  let colSchema;
15508
+ let bindFailed = false;
14335
15509
  if (t.columns) {
14336
15510
  colSchema = t.columns;
14337
15511
  } else if (t.function) {
@@ -14353,26 +15527,31 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14353
15527
  colSchema = response.output_schema;
14354
15528
  } catch {
14355
15529
  colSchema = schema2([]);
15530
+ bindFailed = true;
14356
15531
  }
14357
15532
  } else {
14358
15533
  colSchema = schema2([]);
14359
15534
  }
14360
- if (t.defaults) {
14361
- colSchema = applyDefaults(colSchema, t.defaults);
14362
- }
14363
- if (t.generatedColumns) {
14364
- colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path);
14365
- }
14366
- if (t.columnComments) {
14367
- colSchema = applyColumnComments(colSchema, t.columnComments);
15535
+ if (!bindFailed) {
15536
+ if (t.defaults) {
15537
+ colSchema = applyDefaults(colSchema, t.defaults, path);
15538
+ }
15539
+ if (t.generatedColumns) {
15540
+ colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path, t.name);
15541
+ }
15542
+ if (t.columnComments) {
15543
+ colSchema = applyColumnComments(colSchema, t.columnComments, t.name);
15544
+ }
14368
15545
  }
14369
15546
  validateColumnMetadata(colSchema);
14370
- validateConstraintNullability(t.name, colSchema.fields, t.constraints ?? []);
14371
- validateColumnExpressions(colSchema, path);
14372
- const columns = serializeSchema(colSchema);
14373
- if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
14374
- throw new Error(`Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` + "declare canonical records with constraintRecord() in `constraints` instead");
15547
+ const constraints = bindFailed ? [] : t.constraints ?? [];
15548
+ colSchema = servedTableSchema(t.name, path, colSchema, constraints);
15549
+ try {
15550
+ validateColumnExpressions(colSchema, path);
15551
+ } catch (error) {
15552
+ throw new Error(`Table '${t.name}': ${error.message}`);
14375
15553
  }
15554
+ const columns = serializeSchema(colSchema);
14376
15555
  const requiredFilters = t.requiredFilters ?? [];
14377
15556
  for (const group of requiredFilters) {
14378
15557
  if (!Array.isArray(group) || group.length === 0)
@@ -14407,7 +15586,7 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14407
15586
  name: t.name,
14408
15587
  schema_path: normalizeSchemaPath(path),
14409
15588
  columns,
14410
- constraints: t.constraints ?? [],
15589
+ constraints: [...constraints],
14411
15590
  definition_revision: t.definitionRevision ?? null,
14412
15591
  write_result_modes: {},
14413
15592
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
@@ -14420,6 +15599,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14420
15599
  required_filters: requiredFilters
14421
15600
  };
14422
15601
  }));
15602
+ validateForeignKeyTargets(infos.map((info) => ({ schemaPath: info.schema_path, name: info.name, constraints: info.constraints })));
15603
+ return infos;
14423
15604
  }
14424
15605
  tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
14425
15606
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
@@ -14729,7 +15910,14 @@ function defaultToSql(value) {
14729
15910
  const escaped = value.replace(/'/g, "''");
14730
15911
  return `'${escaped}'`;
14731
15912
  }
14732
- function applyDefaults(schema, defaults) {
15913
+ function canonicalDefault(type, value) {
15914
+ if (type === "BOOLEAN")
15915
+ return typeof value === "boolean";
15916
+ if (type === "VARCHAR")
15917
+ return typeof value === "string";
15918
+ return false;
15919
+ }
15920
+ function applyDefaults(schema, defaults, owner) {
14733
15921
  let result = schema;
14734
15922
  for (const [colName, value] of Object.entries(defaults)) {
14735
15923
  const idx = result.fields.findIndex((f) => f.name === colName);
@@ -14737,7 +15925,12 @@ function applyDefaults(schema, defaults) {
14737
15925
  continue;
14738
15926
  const f = result.fields[idx];
14739
15927
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
14740
- existingMeta.set("default", defaultToSql(value));
15928
+ const sql = defaultToSql(value);
15929
+ if (canonicalDefault(duckdbPrimitive(f), value)) {
15930
+ existingMeta.set("vgi.column.default.v1", defaultExpressionMetadata(sql, owner));
15931
+ } else {
15932
+ existingMeta.set("default", sql);
15933
+ }
14741
15934
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
14742
15935
  const fields = [...result.fields];
14743
15936
  fields[idx] = newField;
@@ -14745,17 +15938,21 @@ function applyDefaults(schema, defaults) {
14745
15938
  }
14746
15939
  return result;
14747
15940
  }
14748
- function applyGeneratedColumns(schema, generated, owner) {
15941
+ function applyGeneratedColumns(schema, generated, owner, table) {
14749
15942
  let result = schema;
14750
15943
  for (const [colName, expression] of Object.entries(generated)) {
14751
15944
  const idx = result.fields.findIndex((f) => f.name === colName);
14752
15945
  if (idx < 0)
14753
- throw new Error(`generated expression references unknown column ${colName}`);
15946
+ throw new Error(`Table '${table}': generatedColumns names unknown column ${colName}`);
14754
15947
  const f = result.fields[idx];
14755
15948
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
14756
15949
  if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression"))
14757
- throw new Error("generated convenience conflicts with existing expression metadata");
14758
- existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
15950
+ throw new Error(`Table '${table}': generatedColumns for ${colName} conflicts with existing expression metadata`);
15951
+ try {
15952
+ existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
15953
+ } catch (error) {
15954
+ throw new Error(`Table '${table}': column ${colName}: ${error.message}`);
15955
+ }
14759
15956
  existingMeta.set(GENERATION_KEY, "virtual");
14760
15957
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
14761
15958
  const fields = [...result.fields];
@@ -14764,12 +15961,12 @@ function applyGeneratedColumns(schema, generated, owner) {
14764
15961
  }
14765
15962
  return result;
14766
15963
  }
14767
- function applyColumnComments(schema, comments) {
15964
+ function applyColumnComments(schema, comments, table) {
14768
15965
  let result = schema;
14769
15966
  for (const [colName, comment] of Object.entries(comments)) {
14770
15967
  const idx = result.fields.findIndex((f) => f.name === colName);
14771
15968
  if (idx < 0)
14772
- throw new Error(`column comment references unknown field ${colName}`);
15969
+ throw new Error(`Table '${table}': columnComments names unknown column ${colName}`);
14773
15970
  const f = result.fields[idx];
14774
15971
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
14775
15972
  existingMeta.set("comment", comment);
@@ -14899,6 +16096,29 @@ function sameSpelling(left, right) {
14899
16096
  const b = normalizeSchemaPath(right);
14900
16097
  return a.length === b.length && a.every((part, i) => part === b[i]);
14901
16098
  }
16099
+ // src/catalog/indexes.ts
16100
+ var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
16101
+ function emptyIndexOptions() {
16102
+ return Uint8Array.from(atob(NO_OPTIONS_B64), (c) => c.charCodeAt(0));
16103
+ }
16104
+ function canonicalIndex(spec) {
16105
+ if (spec.columns.length === 0)
16106
+ throw new Error(`index on '${spec.table}' requires at least one key`);
16107
+ if (!spec.algorithm)
16108
+ throw new Error("index algorithm must be nonempty");
16109
+ const values = spec.options ?? emptyIndexOptions();
16110
+ return {
16111
+ definition: encodeASD(IndexDefinitionSchema, {
16112
+ table: encodeASD(CatalogObjectRefSchema, { kind: "table", schema_path: spec.schemaPath, name: spec.table, owner_table: null }),
16113
+ algorithm: spec.algorithm,
16114
+ keys: spec.columns.map((path) => encodeASD(IndexKeySchema, { column_path: path, expression: null })),
16115
+ options: values,
16116
+ constraint_type: spec.constraintType ?? "NONE",
16117
+ associated_constraint: spec.associatedConstraintId == null ? null : encodeASD(CatalogObjectRefSchema, { kind: "constraint", schema_path: spec.schemaPath, name: spec.associatedConstraintId, owner_table: spec.table })
16118
+ }),
16119
+ options: encodeASD(OptionStateSchema, { values, explicit_names: spec.explicitOptionNames ?? [] })
16120
+ };
16121
+ }
14902
16122
  // src/catalog/composite.ts
14903
16123
  var ROUTE_BYTE = 0;
14904
16124
 
@@ -15048,6 +16268,12 @@ class CompositeCatalogInterface extends CatalogInterface {
15048
16268
  async tableNotNullDrop(...args) {
15049
16269
  await this._route(args[0]).tableNotNullDrop(...args);
15050
16270
  }
16271
+ async tableConstraintsApply(request) {
16272
+ return await this._route(request.attach_opaque_data).tableConstraintsApply(request);
16273
+ }
16274
+ async catalogCapabilities(attachOpaqueData) {
16275
+ return await this._route(attachOpaqueData).catalogCapabilities(attachOpaqueData);
16276
+ }
15051
16277
  async viewCreate(...args) {
15052
16278
  await this._route(args[0]).viewCreate(...args);
15053
16279
  }
@@ -15391,13 +16617,19 @@ export {
15391
16617
  AuthContext3 as AuthContext,
15392
16618
  AuthUnavailableError2 as AuthUnavailableError,
15393
16619
  BindResultSchema,
16620
+ CONSTRAINT_CREATE,
16621
+ CONSTRAINT_ENFORCE,
16622
+ CONSTRAINT_MUTATE,
15394
16623
  CONSTRAINT_RECORDS_READ,
15395
16624
  CatalogInterface,
15396
16625
  CompositeCatalogInterface,
16626
+ DEFAULT_EXPRESSION_KEY,
15397
16627
  DateUnit3 as DateUnit,
15398
16628
  EXCHANGE_STATE_SCHEMA,
15399
16629
  FunctionRegistry,
15400
16630
  FunctionType,
16631
+ GENERATED_EXPRESSION_KEY,
16632
+ GENERATION_KEY,
15401
16633
  GrantKeys3 as GrantKeys,
15402
16634
  GrantRefusedError2 as GrantRefusedError,
15403
16635
  IdentityUnavailableError2 as IdentityUnavailableError,
@@ -15408,6 +16640,7 @@ export {
15408
16640
  ReadOnlyCatalogInterface,
15409
16641
  ScanFunctionResultSchema,
15410
16642
  StatusError2 as StatusError,
16643
+ TRANSACTION_DDL,
15411
16644
  TimeUnit2 as TimeUnit,
15412
16645
  TypeId,
15413
16646
  UnionMode2 as UnionMode,
@@ -15419,9 +16652,16 @@ export {
15419
16652
  batchToSecretDict,
15420
16653
  binary2 as binary,
15421
16654
  bool2 as bool,
16655
+ buildCatalogCapabilities,
16656
+ buildConstraintChange,
16657
+ buildConstraintDefinition,
16658
+ buildMacroOverload,
15422
16659
  buildStatisticsBatch,
15423
16660
  cacheControlMetadata,
16661
+ canonicalIndex,
16662
+ catalogCapabilities,
15424
16663
  columnFromArray,
16664
+ constraintCapabilities,
15425
16665
  constraintRecord,
15426
16666
  constraintSpecFields,
15427
16667
  createLandingRoutes,
@@ -15432,7 +16672,20 @@ export {
15432
16672
  decimal2 as decimal,
15433
16673
  decimal1282 as decimal128,
15434
16674
  decimal2562 as decimal256,
16675
+ decodeCatalogCapabilities,
16676
+ decodeCatalogObjectRef,
16677
+ decodeConstraintChange,
16678
+ decodeConstraintDefinition,
16679
+ decodeConstraintInfo,
16680
+ decodeConstraintSnapshot,
16681
+ decodeConstraintsApplyRequest,
15435
16682
  decodeDictValue,
16683
+ decodeForeignKeyDefinition,
16684
+ decodeIndexDefinition,
16685
+ decodeMacroOverload,
16686
+ decodeSqlExpression,
16687
+ defaultClientCapabilities,
16688
+ defaultExpressionMetadata,
15436
16689
  defineAggregate,
15437
16690
  defineRowTransformFunction,
15438
16691
  defineScalarFunction,
@@ -15444,6 +16697,18 @@ export {
15444
16697
  dictionary2 as dictionary,
15445
16698
  duration2 as duration,
15446
16699
  emptyBatch,
16700
+ emptyIndexOptions,
16701
+ encodeCatalogCapabilities,
16702
+ encodeCatalogObjectRef,
16703
+ encodeConstraintChange,
16704
+ encodeConstraintDefinition,
16705
+ encodeConstraintInfo,
16706
+ encodeConstraintSnapshot,
16707
+ encodeConstraintsApplyRequest,
16708
+ encodeForeignKeyDefinition,
16709
+ encodeIndexDefinition,
16710
+ encodeMacroOverload,
16711
+ encodeSqlExpression,
15447
16712
  field2 as field,
15448
16713
  filterBatch,
15449
16714
  fixedSizeBinary2 as fixedSizeBinary,
@@ -15451,6 +16716,7 @@ export {
15451
16716
  float162 as float16,
15452
16717
  float322 as float32,
15453
16718
  float642 as float64,
16719
+ generatedExpressionMetadata,
15454
16720
  int2 as int,
15455
16721
  int162 as int16,
15456
16722
  int322 as int32,
@@ -15488,12 +16754,18 @@ export {
15488
16754
  readConstraintRecord,
15489
16755
  safeNumber,
15490
16756
  schema2 as schema,
16757
+ selectCatalogCapabilities,
16758
+ selectReadProfiles,
15491
16759
  serializeAttachOptionSpec,
15492
16760
  serializeAttachOptionSpecs,
15493
16761
  serializeBatch,
15494
16762
  serializeColumnStatistics,
15495
16763
  serializeSchema,
16764
+ servedConstraintFields,
16765
+ servedTableInfo,
16766
+ servedTableSchema,
15496
16767
  sparseUnion2 as sparseUnion,
16768
+ sqlExpression,
15497
16769
  struct2 as struct,
15498
16770
  time2 as time,
15499
16771
  timeMicrosecond2 as timeMicrosecond,
@@ -15506,7 +16778,12 @@ export {
15506
16778
  uint642 as uint64,
15507
16779
  uint82 as uint8,
15508
16780
  union2 as union,
15509
- utf82 as utf8
16781
+ utf82 as utf8,
16782
+ validateColumnExpressionSql,
16783
+ validateConstraintNullability,
16784
+ validateForeignKeyTargets,
16785
+ validateNumericCheckSql,
16786
+ validateTableConstraints
15510
16787
  };
15511
16788
 
15512
- //# debugId=FE84125A7F5CDDE564756E2164756E21
16789
+ //# debugId=F6DD0A9F209BC28864756E2164756E21