@query-farm/vgi 0.47.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +1 -1
  2. package/dist/catalog/column-expressions.d.ts +22 -1
  3. package/dist/catalog/column-metadata.d.ts +7 -0
  4. package/dist/catalog/column-types.d.ts +15 -0
  5. package/dist/catalog/composite.d.ts +2 -0
  6. package/dist/catalog/constraints.d.ts +110 -12
  7. package/dist/catalog/descriptors.d.ts +19 -1
  8. package/dist/catalog/indexes.d.ts +29 -0
  9. package/dist/catalog/interface.d.ts +41 -0
  10. package/dist/catalog/public-codecs.d.ts +6 -0
  11. package/dist/catalog/read-only.d.ts +3 -0
  12. package/dist/catalog/sql-grammar.d.ts +53 -0
  13. package/dist/catalog/unconstrained-columns.d.ts +8 -0
  14. package/dist/client/types.d.ts +5 -1
  15. package/dist/client-entry.d.ts +1 -0
  16. package/dist/client-entry.js +1435 -152
  17. package/dist/client-entry.js.map +15 -11
  18. package/dist/generated/vgi-client.d.ts +5 -0
  19. package/dist/generated/vgi-protocol-schemas.d.ts +5 -0
  20. package/dist/generated/vgi-protocol-types.d.ts +57 -0
  21. package/dist/generated/vgi-service.d.ts +1 -1
  22. package/dist/index.core.d.ts +3 -1
  23. package/dist/index.js +1940 -545
  24. package/dist/index.js.map +26 -22
  25. package/dist/protocol/dispatch.d.ts +1 -1
  26. package/dist/protocol/serializers/splits.d.ts +41 -1
  27. package/dist/serve-entry.js +1172 -58
  28. package/dist/serve-entry.js.map +20 -17
  29. package/dist/worker-cf-entry.d.ts +2 -1
  30. package/dist/worker-cf-entry.js +1538 -191
  31. package/dist/worker-cf-entry.js.map +26 -22
  32. package/package.json +1 -1
  33. package/src/catalog/column-expressions.ts +85 -7
  34. package/src/catalog/column-metadata.ts +20 -2
  35. package/src/catalog/column-types.ts +50 -0
  36. package/src/catalog/composite.ts +10 -0
  37. package/src/catalog/constraints.ts +496 -58
  38. package/src/catalog/contents-codec.ts +3 -3
  39. package/src/catalog/descriptors.ts +19 -1
  40. package/src/catalog/indexes.ts +59 -0
  41. package/src/catalog/interface.ts +103 -1
  42. package/src/catalog/public-codecs.ts +36 -0
  43. package/src/catalog/read-only.ts +92 -36
  44. package/src/catalog/sql-grammar.ts +476 -0
  45. package/src/catalog/unconstrained-columns.ts +34 -8
  46. package/src/client/client.ts +6 -3
  47. package/src/client/types.ts +5 -1
  48. package/src/client-entry.ts +4 -0
  49. package/src/generated/vgi-client.ts +6 -1
  50. package/src/generated/vgi-protocol-schemas.ts +36 -1
  51. package/src/generated/vgi-protocol-types.ts +130 -1
  52. package/src/generated/vgi-service.ts +2 -2
  53. package/src/index.core.ts +34 -1
  54. package/src/protocol/dispatch.ts +1 -1
  55. package/src/protocol/handlers/catalog/admin.ts +14 -13
  56. package/src/protocol/handlers/catalog/table.ts +58 -11
  57. package/src/protocol/serializers/splits.ts +82 -9
  58. package/src/worker-cf-entry.ts +2 -4
@@ -4459,6 +4459,20 @@ function deserializeBindResponse(params) {
4459
4459
  }
4460
4460
  // src/protocol/serializers/init.ts
4461
4461
  init_arrow();
4462
+
4463
+ // src/protocol/types.ts
4464
+ var OrderByDirection;
4465
+ ((OrderByDirection) => {
4466
+ OrderByDirection["ASC"] = "ASC";
4467
+ OrderByDirection["DESC"] = "DESC";
4468
+ })(OrderByDirection ||= {});
4469
+ var OrderByNullOrder;
4470
+ ((OrderByNullOrder) => {
4471
+ OrderByNullOrder["NULLS_FIRST"] = "NULLS_FIRST";
4472
+ OrderByNullOrder["NULLS_LAST"] = "NULLS_LAST";
4473
+ })(OrderByNullOrder ||= {});
4474
+
4475
+ // src/protocol/serializers/init.ts
4462
4476
  var INIT_REQUEST_SCHEMA = schema2([
4463
4477
  field2("bind_call", binary2(), false),
4464
4478
  field2("output_schema", binary2(), false),
@@ -4901,7 +4915,7 @@ import {
4901
4915
  Protocol
4902
4916
  } from "@query-farm/vgi-rpc";
4903
4917
  var VGI_PROTOCOL_NAME = "vgi.v3";
4904
- var VGI_PROTOCOL_VERSION = "3.0.0";
4918
+ var VGI_PROTOCOL_VERSION = "3.1.0";
4905
4919
  function exchangeStream(callbacks) {
4906
4920
  return { kind: "exchange", ...callbacks };
4907
4921
  }
@@ -6501,6 +6515,26 @@ var CopyFromFormatInfoSchema = schema2([
6501
6515
  field2("description", utf82(), false),
6502
6516
  field2("ordered", bool2(), false)
6503
6517
  ]);
6518
+ var FieldPathSchema = schema2([
6519
+ field2("components", list2(field2("item", utf82(), true)), false)
6520
+ ]);
6521
+ var TransformSpecSchema = schema2([
6522
+ field2("id", utf82(), false),
6523
+ field2("inputs", list2(field2("item", binary2(), true)), false),
6524
+ field2("parameters", binary2(), true)
6525
+ ]);
6526
+ var KeyGroupingSchema = schema2([
6527
+ field2("keys", list2(field2("item", binary2(), true)), false)
6528
+ ]);
6529
+ var RangeKeySchema = schema2([
6530
+ field2("transform", binary2(), false),
6531
+ field2("direction", dictionary2(utf82(), int162()), false),
6532
+ field2("null_order", dictionary2(utf82(), int162()), false)
6533
+ ]);
6534
+ var RangePartitioningSchema = schema2([
6535
+ field2("keys", list2(field2("item", binary2(), true)), false),
6536
+ field2("split_points", binary2(), false)
6537
+ ]);
6504
6538
  var MacroParameterSchema = schema2([
6505
6539
  field2("name", utf82(), false),
6506
6540
  field2("declared_type", binary2(), true),
@@ -6731,6 +6765,9 @@ var ScanSplitSchema = schema2([
6731
6765
  field2("estimated_rows", int642(), true),
6732
6766
  field2("rows_exact", bool2(), false),
6733
6767
  field2("estimated_bytes", int642(), true),
6768
+ field2("key_value", binary2(), true),
6769
+ field2("range_index", int642(), true),
6770
+ field2("column_bounds", binary2(), true),
6734
6771
  field2("partition_bounds", binary2(), true),
6735
6772
  field2("column_statistics", binary2(), true),
6736
6773
  field2("location_ids", list2(field2("item", int642(), true)), true),
@@ -7206,6 +7243,8 @@ var TableFunctionPlanResultSchema = schema2([
7206
7243
  field2("catalog_version", int642(), true),
7207
7244
  field2("scope", utf82(), false),
7208
7245
  field2("locations", list2(field2("item", utf82(), true)), true),
7246
+ field2("key_grouping", binary2(), true),
7247
+ field2("range_partitioning", binary2(), true),
7209
7248
  field2("partitioning", list2(field2("item", binary2(), true)), true),
7210
7249
  field2("sort_order", list2(field2("item", binary2(), true)), true),
7211
7250
  field2("cache_max_age_seconds", int642(), true),
@@ -7878,10 +7917,66 @@ function decodeASDCollection(schema, bytes) {
7878
7917
  }
7879
7918
 
7880
7919
  // src/generated/vgi-protocol-types.ts
7920
+ function buildMacroOverload(init) {
7921
+ return {
7922
+ parameters: init.parameters,
7923
+ definition: init.definition,
7924
+ profile: init.profile,
7925
+ schema_path: init.schema_path,
7926
+ macro_type: init.macro_type,
7927
+ evaluation_context: init.evaluation_context
7928
+ };
7929
+ }
7930
+ var encodeMacroOverload = (v) => encodeASD(MacroOverloadSchema, v);
7931
+ var decodeMacroOverload = (b) => decodeASD(MacroOverloadSchema, b);
7932
+ function buildCatalogCapabilities(init) {
7933
+ return {
7934
+ read: init.read ?? [],
7935
+ ddl: init.ddl ?? [],
7936
+ write: init.write ?? [],
7937
+ transaction: init.transaction ?? []
7938
+ };
7939
+ }
7881
7940
  var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
7882
7941
  var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
7942
+ var encodeCatalogObjectRef = (v) => encodeASD(CatalogObjectRefSchema, v);
7943
+ var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
7883
7944
  var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
7884
7945
  var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
7946
+ var encodeForeignKeyDefinition = (v) => encodeASD(ForeignKeyDefinitionSchema, v);
7947
+ var decodeForeignKeyDefinition = (b) => decodeASD(ForeignKeyDefinitionSchema, b);
7948
+ function buildConstraintDefinition(init) {
7949
+ return {
7950
+ kind: init.kind,
7951
+ column_paths: init.column_paths ?? [],
7952
+ declared_name: init.declared_name ?? null,
7953
+ check_expression: init.check_expression ?? null,
7954
+ foreign_key: init.foreign_key ?? null
7955
+ };
7956
+ }
7957
+ var encodeConstraintDefinition = (v) => encodeASD(ConstraintDefinitionSchema, v);
7958
+ var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
7959
+ var encodeConstraintInfo = (v) => encodeASD(ConstraintInfoSchema, v);
7960
+ var decodeConstraintInfo = (b) => decodeASD(ConstraintInfoSchema, b);
7961
+ function buildConstraintChange(init) {
7962
+ return {
7963
+ operation: init.operation,
7964
+ ref: init.ref ?? null,
7965
+ definition: init.definition ?? null,
7966
+ enforcement: init.enforcement ?? null,
7967
+ validation: init.validation ?? null,
7968
+ cascade: init.cascade ?? null,
7969
+ declared_name: init.declared_name ?? null
7970
+ };
7971
+ }
7972
+ var encodeConstraintChange = (v) => encodeASD(ConstraintChangeSchema, v);
7973
+ var decodeConstraintChange = (b) => decodeASD(ConstraintChangeSchema, b);
7974
+ var encodeConstraintSnapshot = (v) => encodeASD(ConstraintSnapshotSchema, v);
7975
+ var decodeConstraintSnapshot = (b) => decodeASD(ConstraintSnapshotSchema, b);
7976
+ var encodeConstraintsApplyRequest = (v) => encodeASD(ConstraintsApplyRequestSchema, v);
7977
+ var decodeConstraintsApplyRequest = (b) => decodeASD(ConstraintsApplyRequestSchema, b);
7978
+ var encodeIndexDefinition = (v) => encodeASD(IndexDefinitionSchema, v);
7979
+ var decodeIndexDefinition = (b) => decodeASD(IndexDefinitionSchema, b);
7885
7980
  function buildCatalogAttachResult(init) {
7886
7981
  return {
7887
7982
  attach_opaque_data: init.attach_opaque_data,
@@ -7921,9 +8016,613 @@ function buildCatalogContentsResponse(init) {
7921
8016
  };
7922
8017
  }
7923
8018
 
8019
+ // src/catalog/sql-grammar.ts
8020
+ class GrammarError extends Error {
8021
+ }
8022
+ var fail = (message) => {
8023
+ throw new GrammarError(message);
8024
+ };
8025
+ var RESERVED = new Set([
8026
+ "all",
8027
+ "and",
8028
+ "any",
8029
+ "array",
8030
+ "as",
8031
+ "asc",
8032
+ "between",
8033
+ "both",
8034
+ "case",
8035
+ "cast",
8036
+ "check",
8037
+ "collate",
8038
+ "column",
8039
+ "constraint",
8040
+ "create",
8041
+ "default",
8042
+ "desc",
8043
+ "distinct",
8044
+ "do",
8045
+ "else",
8046
+ "end",
8047
+ "except",
8048
+ "false",
8049
+ "fetch",
8050
+ "for",
8051
+ "foreign",
8052
+ "from",
8053
+ "glob",
8054
+ "grant",
8055
+ "group",
8056
+ "having",
8057
+ "ilike",
8058
+ "in",
8059
+ "intersect",
8060
+ "interval",
8061
+ "into",
8062
+ "is",
8063
+ "isnull",
8064
+ "like",
8065
+ "limit",
8066
+ "not",
8067
+ "notnull",
8068
+ "null",
8069
+ "offset",
8070
+ "on",
8071
+ "or",
8072
+ "order",
8073
+ "primary",
8074
+ "references",
8075
+ "returning",
8076
+ "select",
8077
+ "similar",
8078
+ "some",
8079
+ "table",
8080
+ "then",
8081
+ "to",
8082
+ "true",
8083
+ "try_cast",
8084
+ "union",
8085
+ "unique",
8086
+ "using",
8087
+ "when",
8088
+ "where",
8089
+ "window",
8090
+ "with"
8091
+ ]);
8092
+ var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
8093
+ function tokenize(sql) {
8094
+ const out = [];
8095
+ let i = 0;
8096
+ while (i < sql.length) {
8097
+ const c = sql[i];
8098
+ if (/\s/.test(c)) {
8099
+ i++;
8100
+ continue;
8101
+ }
8102
+ if (sql.startsWith("--", i)) {
8103
+ while (i < sql.length && sql[i] !== `
8104
+ `)
8105
+ i++;
8106
+ continue;
8107
+ }
8108
+ if (sql.startsWith("/*", i)) {
8109
+ const close = sql.indexOf("*/", i + 2);
8110
+ if (close < 0)
8111
+ fail("unterminated comment");
8112
+ i = close + 2;
8113
+ continue;
8114
+ }
8115
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
8116
+ const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
8117
+ if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
8118
+ fail("unsupported numeric literal");
8119
+ out.push({ t: "num", v: m[0] });
8120
+ i += m[0].length;
8121
+ continue;
8122
+ }
8123
+ if (c === "'" || c === '"') {
8124
+ let j = i + 1, text = "";
8125
+ for (;; ) {
8126
+ if (j >= sql.length)
8127
+ fail("unterminated quoted text");
8128
+ if (sql[j] === c) {
8129
+ if (sql[j + 1] === c) {
8130
+ text += c;
8131
+ j += 2;
8132
+ continue;
8133
+ }
8134
+ break;
8135
+ }
8136
+ text += sql[j++];
8137
+ }
8138
+ out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
8139
+ i = j + 1;
8140
+ continue;
8141
+ }
8142
+ if (/[A-Za-z_\u0080-￿]/.test(c)) {
8143
+ const m = /^[A-Za-z_\u0080-￿][A-Za-z0-9_$\u0080-￿]*/.exec(sql.slice(i));
8144
+ out.push({ t: "ident", v: m[0], quoted: false });
8145
+ i += m[0].length;
8146
+ continue;
8147
+ }
8148
+ const op = OPERATORS.find((o) => sql.startsWith(o, i));
8149
+ if (!op)
8150
+ fail(`unsupported character '${c}'`);
8151
+ out.push({ t: "op", v: op });
8152
+ i += op.length;
8153
+ }
8154
+ out.push({ t: "end" });
8155
+ return out;
8156
+ }
8157
+ var CAST_TYPES = {
8158
+ boolean: "BOOLEAN",
8159
+ bool: "BOOLEAN",
8160
+ logical: "BOOLEAN",
8161
+ tinyint: "TINYINT",
8162
+ int1: "TINYINT",
8163
+ smallint: "SMALLINT",
8164
+ int2: "SMALLINT",
8165
+ short: "SMALLINT",
8166
+ integer: "INTEGER",
8167
+ int: "INTEGER",
8168
+ int4: "INTEGER",
8169
+ signed: "INTEGER",
8170
+ bigint: "BIGINT",
8171
+ int8: "BIGINT",
8172
+ long: "BIGINT",
8173
+ float: "FLOAT",
8174
+ real: "FLOAT",
8175
+ float4: "FLOAT",
8176
+ double: "DOUBLE",
8177
+ float8: "DOUBLE",
8178
+ decimal: "DECIMAL",
8179
+ numeric: "DECIMAL",
8180
+ varchar: "VARCHAR",
8181
+ text: "VARCHAR",
8182
+ string: "VARCHAR",
8183
+ char: "VARCHAR",
8184
+ bpchar: "VARCHAR",
8185
+ nvarchar: "VARCHAR",
8186
+ character: "VARCHAR"
8187
+ };
8188
+ var INT64_MAX = (1n << 63n) - 1n;
8189
+ function literalNumber(text, negative) {
8190
+ if (/^[0-9]+$/.test(text)) {
8191
+ const value = BigInt(text) * (negative ? -1n : 1n);
8192
+ const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
8193
+ return { kind: "constant", type };
8194
+ }
8195
+ if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
8196
+ return { kind: "constant", type: "DECIMAL" };
8197
+ return { kind: "constant", type: "DOUBLE" };
8198
+ }
8199
+
8200
+ class Parser {
8201
+ tokens;
8202
+ pos = 0;
8203
+ constructor(tokens) {
8204
+ this.tokens = tokens;
8205
+ }
8206
+ peek(offset = 0) {
8207
+ return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
8208
+ }
8209
+ next() {
8210
+ return this.tokens[this.pos++];
8211
+ }
8212
+ isOp(v, offset = 0) {
8213
+ const t = this.peek(offset);
8214
+ return t.t === "op" && t.v === v;
8215
+ }
8216
+ isWord(word, offset = 0) {
8217
+ const t = this.peek(offset);
8218
+ return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
8219
+ }
8220
+ expectOp(v) {
8221
+ if (!this.isOp(v))
8222
+ fail(`expected '${v}'`);
8223
+ this.pos++;
8224
+ }
8225
+ parseAll() {
8226
+ const node = this.expr();
8227
+ if (this.peek().t !== "end")
8228
+ fail("unexpected text after the expression");
8229
+ return node;
8230
+ }
8231
+ expr() {
8232
+ return this.or();
8233
+ }
8234
+ or() {
8235
+ let left = this.and();
8236
+ while (this.isWord("or")) {
8237
+ this.pos++;
8238
+ left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
8239
+ }
8240
+ return left;
8241
+ }
8242
+ and() {
8243
+ let left = this.not();
8244
+ while (this.isWord("and")) {
8245
+ this.pos++;
8246
+ left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
8247
+ }
8248
+ return left;
8249
+ }
8250
+ not() {
8251
+ if (this.isWord("not")) {
8252
+ this.pos++;
8253
+ return { kind: "operator", op: "NOT", children: [this.not()] };
8254
+ }
8255
+ return this.is();
8256
+ }
8257
+ is() {
8258
+ let left = this.comparison();
8259
+ for (;; ) {
8260
+ if (this.isWord("isnull")) {
8261
+ this.pos++;
8262
+ left = { kind: "operator", op: "IS_NULL", children: [left] };
8263
+ continue;
8264
+ }
8265
+ if (this.isWord("notnull")) {
8266
+ this.pos++;
8267
+ left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
8268
+ continue;
8269
+ }
8270
+ if (this.isWord("is")) {
8271
+ this.pos++;
8272
+ const negated = this.isWord("not");
8273
+ if (negated)
8274
+ this.pos++;
8275
+ if (!this.isWord("null"))
8276
+ fail("only IS [NOT] NULL is supported");
8277
+ this.pos++;
8278
+ left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
8279
+ continue;
8280
+ }
8281
+ return left;
8282
+ }
8283
+ }
8284
+ comparison() {
8285
+ const left = this.otherOp();
8286
+ const t = this.peek();
8287
+ if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
8288
+ this.pos++;
8289
+ const right = this.otherOp();
8290
+ const next = this.peek();
8291
+ if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
8292
+ fail("chained comparisons are unsupported");
8293
+ return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
8294
+ }
8295
+ for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
8296
+ if (this.isWord(word))
8297
+ fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
8298
+ }
8299
+ return left;
8300
+ }
8301
+ otherOp() {
8302
+ let left = this.additive();
8303
+ for (;; ) {
8304
+ const t = this.peek();
8305
+ if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
8306
+ this.pos++;
8307
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
8308
+ continue;
8309
+ }
8310
+ return left;
8311
+ }
8312
+ }
8313
+ additive() {
8314
+ let left = this.multiplicative();
8315
+ for (;; ) {
8316
+ const t = this.peek();
8317
+ if (t.t === "op" && (t.v === "+" || t.v === "-")) {
8318
+ this.pos++;
8319
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
8320
+ continue;
8321
+ }
8322
+ return left;
8323
+ }
8324
+ }
8325
+ multiplicative() {
8326
+ let left = this.power();
8327
+ for (;; ) {
8328
+ const t = this.peek();
8329
+ if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
8330
+ this.pos++;
8331
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
8332
+ continue;
8333
+ }
8334
+ return left;
8335
+ }
8336
+ }
8337
+ power() {
8338
+ let left = this.unary();
8339
+ while (this.isOp("^")) {
8340
+ this.pos++;
8341
+ left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
8342
+ }
8343
+ return left;
8344
+ }
8345
+ unary() {
8346
+ if (this.isOp("-") || this.isOp("+")) {
8347
+ const sign = this.next().v;
8348
+ const operand = this.unary();
8349
+ if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
8350
+ const folded = literalNumber(operand.text, !operand.negative);
8351
+ return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
8352
+ }
8353
+ return { kind: "function", name: sign, qualified: false, children: [operand] };
8354
+ }
8355
+ return this.postfix();
8356
+ }
8357
+ postfix() {
8358
+ let node = this.primary();
8359
+ for (;; ) {
8360
+ if (this.isOp("::")) {
8361
+ this.pos++;
8362
+ node = { kind: "cast", ...this.typeName(), child: node };
8363
+ continue;
8364
+ }
8365
+ if (this.isOp("["))
8366
+ fail("subscripts are unsupported");
8367
+ return node;
8368
+ }
8369
+ }
8370
+ typeName() {
8371
+ const t = this.next();
8372
+ if (t.t !== "ident")
8373
+ fail("expected a type name");
8374
+ const first = t.v.toLowerCase();
8375
+ let qualified = false;
8376
+ while (this.isOp(".")) {
8377
+ this.pos++;
8378
+ if (this.next().t !== "ident")
8379
+ fail("expected a type name");
8380
+ qualified = true;
8381
+ }
8382
+ let name = first;
8383
+ if (first === "double" && this.isWord("precision")) {
8384
+ this.pos++;
8385
+ name = "double";
8386
+ }
8387
+ if (first === "character" && this.isWord("varying")) {
8388
+ this.pos++;
8389
+ name = "varchar";
8390
+ }
8391
+ let params = [];
8392
+ if (this.isOp("(")) {
8393
+ this.pos++;
8394
+ for (;; ) {
8395
+ const p = this.next();
8396
+ if (p.t !== "num")
8397
+ fail("unsupported type parameter");
8398
+ params.push(p.v);
8399
+ if (this.isOp(",")) {
8400
+ this.pos++;
8401
+ continue;
8402
+ }
8403
+ break;
8404
+ }
8405
+ this.expectOp(")");
8406
+ }
8407
+ if (this.isOp("["))
8408
+ fail("array types are unsupported");
8409
+ let type = CAST_TYPES[name] ?? null;
8410
+ if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
8411
+ type = "DOUBLE";
8412
+ return { type, qualified };
8413
+ }
8414
+ primary() {
8415
+ const t = this.next();
8416
+ if (t.t === "num")
8417
+ return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
8418
+ if (t.t === "str") {
8419
+ if (this.peek().t === "str")
8420
+ fail("adjacent string literals are unsupported");
8421
+ return { kind: "constant", type: "VARCHAR" };
8422
+ }
8423
+ if (t.t === "op") {
8424
+ if (t.v === "(") {
8425
+ const inner = this.expr();
8426
+ if (this.isOp(","))
8427
+ fail("row constructors are unsupported");
8428
+ this.expectOp(")");
8429
+ return inner;
8430
+ }
8431
+ return fail(`unexpected '${t.v}'`);
8432
+ }
8433
+ if (t.t === "end")
8434
+ return fail("expected an expression");
8435
+ const word = t.v.toLowerCase();
8436
+ if (!t.quoted) {
8437
+ if (word === "null")
8438
+ return { kind: "constant", type: "NULL" };
8439
+ if (word === "true" || word === "false")
8440
+ return { kind: "constant", type: "BOOLEAN" };
8441
+ if (word === "cast" && this.isOp("(")) {
8442
+ this.pos++;
8443
+ const child = this.expr();
8444
+ if (!this.isWord("as"))
8445
+ fail("expected AS in CAST");
8446
+ this.pos++;
8447
+ const target = this.typeName();
8448
+ this.expectOp(")");
8449
+ return { kind: "cast", ...target, child };
8450
+ }
8451
+ if (word === "case")
8452
+ fail("CASE is outside the supported scalar grammar");
8453
+ if (RESERVED.has(word))
8454
+ fail(`unexpected keyword ${t.v.toUpperCase()}`);
8455
+ }
8456
+ const names = [t.v];
8457
+ while (this.isOp(".")) {
8458
+ this.pos++;
8459
+ const part = this.next();
8460
+ if (part.t !== "ident")
8461
+ fail("unsupported qualified name");
8462
+ names.push(part.v);
8463
+ }
8464
+ if (this.isOp("(")) {
8465
+ this.pos++;
8466
+ const children = [];
8467
+ if (this.isWord("distinct"))
8468
+ fail("DISTINCT function arguments are unsupported");
8469
+ if (!this.isOp(")")) {
8470
+ for (;; ) {
8471
+ if (this.isOp("*"))
8472
+ fail("star arguments are unsupported");
8473
+ if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
8474
+ fail("named scalar arguments are unsupported");
8475
+ children.push(this.expr());
8476
+ if (this.isOp(",")) {
8477
+ this.pos++;
8478
+ continue;
8479
+ }
8480
+ break;
8481
+ }
8482
+ }
8483
+ if (this.isWord("order"))
8484
+ fail("ordered function arguments are unsupported");
8485
+ this.expectOp(")");
8486
+ if (this.isWord("filter") || this.isWord("over"))
8487
+ fail("aggregate and window functions are unsupported");
8488
+ if (names.length === 1 && !t.quoted && word === "coalesce")
8489
+ return { kind: "operator", op: "COALESCE", children };
8490
+ return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
8491
+ }
8492
+ if (this.peek().t === "str")
8493
+ fail("typed literals are unsupported");
8494
+ return { kind: "column", names };
8495
+ }
8496
+ }
8497
+ function parseScalarSql(sql) {
8498
+ if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
8499
+ fail("invalid SQL size or text");
8500
+ return new Parser(tokenize(sql)).parseAll();
8501
+ }
8502
+ var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
8503
+ var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
8504
+ var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
8505
+ function validateColumnExpressionSql(sql, options) {
8506
+ const { usingColumns, generated } = options;
8507
+ const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
8508
+ const columns = [];
8509
+ let nodes = 0;
8510
+ const visit = (node, depth) => {
8511
+ if (depth > 64 || ++nodes > 4096)
8512
+ fail("scalar expression is too complex");
8513
+ switch (node.kind) {
8514
+ case "constant":
8515
+ if (!primitive.has(node.type))
8516
+ fail(`unsupported scalar literal type ${node.type}`);
8517
+ return;
8518
+ case "column":
8519
+ if (!usingColumns || node.names.length !== 1)
8520
+ fail("column references are unsupported in this scope");
8521
+ columns.push(node.names[0]);
8522
+ return;
8523
+ case "cast":
8524
+ if (node.qualified)
8525
+ fail("qualified scalar cast types are unsupported");
8526
+ if (node.type === null || !primitive.has(node.type))
8527
+ fail("unsupported scalar cast");
8528
+ visit(node.child, depth + 1);
8529
+ return;
8530
+ case "comparison":
8531
+ visit(node.left, depth + 1);
8532
+ visit(node.right, depth + 1);
8533
+ return;
8534
+ case "conjunction":
8535
+ case "operator":
8536
+ node.children.forEach((c) => visit(c, depth + 1));
8537
+ return;
8538
+ case "function": {
8539
+ const lower = node.name.toLowerCase();
8540
+ const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
8541
+ if (!ok)
8542
+ fail(`unsupported scalar function '${node.name}'`);
8543
+ node.children.forEach((c) => visit(c, depth + 1));
8544
+ return;
8545
+ }
8546
+ }
8547
+ };
8548
+ try {
8549
+ visit(parseScalarSql(sql), 0);
8550
+ } catch (error) {
8551
+ if (error instanceof GrammarError)
8552
+ throw error;
8553
+ throw new GrammarError(String(error?.message ?? error));
8554
+ }
8555
+ return columns;
8556
+ }
8557
+ function validateNumericCheckSql(sql, resolveColumn) {
8558
+ const node = parseScalarSql(sql);
8559
+ if (node.kind !== "comparison")
8560
+ fail("native CHECK read supports only Boolean numeric comparisons");
8561
+ const comparison = node;
8562
+ for (const operand of [comparison.left, comparison.right]) {
8563
+ if (operand.kind === "constant") {
8564
+ if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
8565
+ fail("CHECK requires numeric operands");
8566
+ continue;
8567
+ }
8568
+ if (operand.kind !== "column")
8569
+ fail("native CHECK read supports only numeric column/constant comparisons");
8570
+ const column = operand;
8571
+ if (column.names.length !== 1)
8572
+ fail("CHECK requires unqualified column references");
8573
+ resolveColumn(column.names[0]);
8574
+ }
8575
+ }
8576
+
8577
+ // src/catalog/column-types.ts
8578
+ init_arrow();
8579
+ function isRowIdField(field) {
8580
+ return field.metadata?.has("is_row_id") ?? false;
8581
+ }
8582
+ function hasLogicalType(field) {
8583
+ for (const key of field.metadata?.keys() ?? [])
8584
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
8585
+ return true;
8586
+ return false;
8587
+ }
8588
+ function ordinaryStructChildren(field) {
8589
+ if (!isStruct(field.type) || hasLogicalType(field))
8590
+ return null;
8591
+ return field.type.children;
8592
+ }
8593
+ function isGeneratedField(field) {
8594
+ const m = field.metadata;
8595
+ return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
8596
+ }
8597
+ function duckdbPrimitive(field) {
8598
+ if (hasLogicalType(field))
8599
+ return null;
8600
+ const t = field.type;
8601
+ switch (t.typeId) {
8602
+ case TypeId.Bool:
8603
+ return "BOOLEAN";
8604
+ case TypeId.Utf8:
8605
+ return "VARCHAR";
8606
+ case TypeId.Int: {
8607
+ if (!(t.isSigned ?? t.signed ?? true))
8608
+ return null;
8609
+ return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
8610
+ }
8611
+ case TypeId.Float:
8612
+ return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
8613
+ case TypeId.Decimal:
8614
+ return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
8615
+ default:
8616
+ return null;
8617
+ }
8618
+ }
8619
+
7924
8620
  // src/catalog/column-expressions.ts
7925
8621
  var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
7926
8622
  var GENERATION_KEY = "vgi.column.generation.v1";
8623
+ var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
8624
+ var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
8625
+ var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
7927
8626
  var PROFILE = "vgi.expression.duckdb.scalar.v1";
7928
8627
  var MAX_BYTES = 8 * 1024 * 1024;
7929
8628
  var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
@@ -8034,9 +8733,24 @@ function validateEncoded(encoded, owner) {
8034
8733
  throw new Error("invalid SqlExpression record schema");
8035
8734
  const utf8 = new TextDecoder("utf-8", { fatal: true });
8036
8735
  textBuffers.forEach((buffer) => utf8.decode(buffer));
8037
- expression(decodeSqlExpression(bytes), owner);
8736
+ const value = decodeSqlExpression(bytes);
8737
+ expression(value, owner);
8738
+ return value.sql;
8038
8739
  }
8039
8740
  function generatedExpressionMetadata(sql, owner) {
8741
+ try {
8742
+ validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
8743
+ } catch (error) {
8744
+ throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
8745
+ }
8746
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
8747
+ }
8748
+ function defaultExpressionMetadata(sql, owner) {
8749
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
8750
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
8751
+ }
8752
+ function sqlExpression(sql, schemaPath) {
8753
+ const owner = [...schemaPath];
8040
8754
  const value = {
8041
8755
  sql,
8042
8756
  profile: PROFILE,
@@ -8050,7 +8764,7 @@ function generatedExpressionMetadata(sql, owner) {
8050
8764
  }
8051
8765
  };
8052
8766
  expression(value, owner);
8053
- return base64(encodeSqlExpression(value));
8767
+ return value;
8054
8768
  }
8055
8769
  function validateColumnExpressions(schema, owner, allowGenerated = true) {
8056
8770
  const type = (t) => {
@@ -8059,14 +8773,33 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
8059
8773
  if (t?.dictionary)
8060
8774
  type(t.dictionary);
8061
8775
  };
8062
- const field = (f) => {
8776
+ const topLevel = new Map;
8777
+ for (const f of schema.fields) {
8778
+ const key = String(f.name).toLowerCase();
8779
+ topLevel.set(key, [...topLevel.get(key) ?? [], f]);
8780
+ }
8781
+ const field = (f, top = false) => {
8063
8782
  const metadata = f.metadata ?? new Map;
8064
8783
  for (const key of metadata.keys()) {
8065
8784
  if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
8066
8785
  throw new Error("unknown generated metadata version");
8067
8786
  }
8787
+ const where = `column ${f.name}`;
8068
8788
  if (metadata.has("generated_expression"))
8069
- throw new Error("legacy generated expression requires explicit canonical translation");
8789
+ throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
8790
+ if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
8791
+ if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
8792
+ throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
8793
+ const type = duckdbPrimitive(f);
8794
+ if (!type || !DEFAULT_TYPES.has(type))
8795
+ throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
8796
+ const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
8797
+ try {
8798
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
8799
+ } catch (error) {
8800
+ throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
8801
+ }
8802
+ }
8070
8803
  if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
8071
8804
  throw new Error("generated expression and category must occur together");
8072
8805
  if (metadata.has(GENERATED_EXPRESSION_KEY)) {
@@ -8074,13 +8807,34 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
8074
8807
  throw new Error("only VIRTUAL generated columns are supported");
8075
8808
  if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
8076
8809
  throw new Error("generated column cannot have a default");
8077
- validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
8810
+ const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
8078
8811
  if (!allowGenerated)
8079
8812
  throw new Error("generated columns unsupported by this catalog");
8813
+ if (!f.nullable)
8814
+ throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
8815
+ const type = duckdbPrimitive(f);
8816
+ if (!type || !GENERATED_TYPES.has(type))
8817
+ throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
8818
+ let references;
8819
+ try {
8820
+ references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
8821
+ } catch (error) {
8822
+ throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
8823
+ }
8824
+ if (top) {
8825
+ for (const name of references) {
8826
+ const matches = topLevel.get(name.toLowerCase()) ?? [];
8827
+ if (matches.length !== 1)
8828
+ throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
8829
+ const operand = duckdbPrimitive(matches[0]);
8830
+ if (!operand || !GENERATED_TYPES.has(operand))
8831
+ throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
8832
+ }
8833
+ }
8080
8834
  }
8081
8835
  type(f.type);
8082
8836
  };
8083
- schema.fields.forEach(field);
8837
+ schema.fields.forEach((f) => field(f, true));
8084
8838
  }
8085
8839
  function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
8086
8840
  validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
@@ -8395,6 +9149,13 @@ class CatalogReadOnlyError extends VgiError {
8395
9149
  this.name = "CatalogReadOnlyError";
8396
9150
  }
8397
9151
  }
9152
+
9153
+ class CatalogNotFoundError extends VgiError {
9154
+ constructor(entity, name) {
9155
+ super(`${entity} '${name}' not found`, "NOT_FOUND");
9156
+ this.name = "CatalogNotFoundError";
9157
+ }
9158
+ }
8398
9159
  class ArgumentValidationError extends VgiError {
8399
9160
  constructor(message) {
8400
9161
  super(message, "INVALID_ARGUMENT");
@@ -9294,14 +10055,40 @@ function deserializePlanRequest(params) {
9294
10055
  projectionIds = [...raw].map(Number);
9295
10056
  }
9296
10057
  const asBigInt = (v) => v == null ? null : typeof v === "bigint" ? v : BigInt(Number(v));
10058
+ const asBytes = (v) => v == null ? null : toUint8Array2(v);
10059
+ const asBytesList = (v) => {
10060
+ if (v == null)
10061
+ return null;
10062
+ const values = Array.isArray(v) ? v : v && typeof v[Symbol.iterator] === "function" ? [...v] : [];
10063
+ return values.filter((entry) => entry != null).map(toUint8Array2);
10064
+ };
10065
+ const enumValue = (v, values) => {
10066
+ if (v == null)
10067
+ return null;
10068
+ const text = String(v);
10069
+ return values.includes(text) ? text : null;
10070
+ };
9297
10071
  return {
9298
10072
  bind_call: bindCall,
9299
- bind_opaque_data: params.bind_opaque_data ? toUint8Array2(params.bind_opaque_data) : null,
10073
+ bind_opaque_data: asBytes(params.bind_opaque_data),
9300
10074
  projection_ids: projectionIds,
9301
- pushdown_filters: params.pushdown_filters ? toUint8Array2(params.pushdown_filters) : null,
10075
+ pushdown_filters: asBytes(params.pushdown_filters),
10076
+ join_keys: asBytesList(params.join_keys),
10077
+ row_limit: asBigInt(params.row_limit),
9302
10078
  target_split_bytes: asBigInt(params.target_split_bytes),
9303
10079
  min_splits: asBigInt(params.min_splits),
9304
- cursor: params.cursor ? toUint8Array2(params.cursor) : null
10080
+ max_splits_per_response: asBigInt(params.max_splits_per_response),
10081
+ cursor: asBytes(params.cursor),
10082
+ refined_filters: asBytes(params.refined_filters),
10083
+ filters_complete: params.filters_complete == null ? true : Boolean(params.filters_complete),
10084
+ start_position: asBytes(params.start_position),
10085
+ end_position: asBytes(params.end_position),
10086
+ order_by_column_name: params.order_by_column_name == null ? null : String(params.order_by_column_name),
10087
+ order_by_direction: enumValue(params.order_by_direction, Object.values(OrderByDirection)),
10088
+ order_by_null_order: enumValue(params.order_by_null_order, Object.values(OrderByNullOrder)),
10089
+ order_by_limit: asBigInt(params.order_by_limit),
10090
+ tablesample_percentage: params.tablesample_percentage == null ? null : Number(params.tablesample_percentage),
10091
+ tablesample_seed: asBigInt(params.tablesample_seed)
9305
10092
  };
9306
10093
  }
9307
10094
  function fingerprintInputs(bindCallBytes) {
@@ -9321,6 +10108,9 @@ function scanSplitRow(split, token) {
9321
10108
  estimated_rows: asBigInt(split.estimatedRows),
9322
10109
  rows_exact: split.rowsExact === true,
9323
10110
  estimated_bytes: asBigInt(split.estimatedBytes),
10111
+ key_value: split.keyValue ?? null,
10112
+ range_index: asBigInt(split.rangeIndex),
10113
+ column_bounds: split.columnBounds ?? null,
9324
10114
  partition_bounds: split.partitionBounds ?? null,
9325
10115
  column_statistics: split.columnStatistics ?? null,
9326
10116
  location_ids: split.locationIds ?? null,
@@ -9341,12 +10131,14 @@ function planResponseRow(result, splitBlobs) {
9341
10131
  estimated_total_bytes: asBigInt(result.estimatedTotalBytes),
9342
10132
  catalog_version: asBigInt(result.catalogVersion),
9343
10133
  scope: result.scope ?? "catalog",
9344
- locations: null,
9345
- partitioning: [],
9346
- sort_order: [],
10134
+ locations: result.locations ?? null,
10135
+ key_grouping: result.keyGrouping ?? null,
10136
+ range_partitioning: result.rangePartitioning ?? null,
10137
+ partitioning: result.partitioning ?? null,
10138
+ sort_order: result.sortOrder ?? null,
9347
10139
  cache_max_age_seconds: asBigInt(result.cacheMaxAgeSeconds),
9348
- start_position: new Uint8Array(0),
9349
- end_position: new Uint8Array(0)
10140
+ start_position: result.startPosition ?? null,
10141
+ end_position: result.endPosition ?? null
9350
10142
  };
9351
10143
  }
9352
10144
 
@@ -10573,6 +11365,457 @@ var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
10573
11365
  var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
10574
11366
  var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
10575
11367
 
11368
+ // src/catalog/constraints.ts
11369
+ init_arrow();
11370
+ var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
11371
+ var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
11372
+ var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
11373
+ var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
11374
+ var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
11375
+ var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
11376
+ var CHECK_CONTEXT = {
11377
+ timezone: "UTC",
11378
+ collation: "binary",
11379
+ default_order: "asc",
11380
+ default_null_order: "nulls_last",
11381
+ preserve_insertion_order: true
11382
+ };
11383
+ function identifier(value, what) {
11384
+ if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
11385
+ throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
11386
+ }
11387
+ function objectRef(kind, schemaPath, name, ownerTable) {
11388
+ return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
11389
+ }
11390
+ function checkPaths(paths, what, topLevelOnly) {
11391
+ if (paths.length > 1024)
11392
+ throw new Error(`${what}: too many column paths`);
11393
+ const seen = new Set;
11394
+ for (const path of paths) {
11395
+ if (path.length === 0 || path.length > 64)
11396
+ throw new Error(`${what}: column path must have 1..64 components`);
11397
+ if (topLevelOnly && path.length !== 1)
11398
+ throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
11399
+ path.forEach((part) => identifier(part, `${what}: column path component`));
11400
+ const key = JSON.stringify(path);
11401
+ if (seen.has(key))
11402
+ throw new Error(`${what}: duplicate column path ${path.join(".")}`);
11403
+ seen.add(key);
11404
+ }
11405
+ }
11406
+ function constraintRecord(spec) {
11407
+ const what = `constraint '${spec.id}' on '${spec.table}'`;
11408
+ if (!spec.id || spec.id.includes("\x00"))
11409
+ throw new Error("constraint id must be nonempty without NUL");
11410
+ identifier(spec.table, "table");
11411
+ if (spec.schemaPath.length !== 1)
11412
+ throw new Error(`${what}: DuckDB reads only one-component schema paths`);
11413
+ identifier(spec.schemaPath[0], "schema");
11414
+ if (spec.enforcement !== "ENFORCED" || spec.validation !== "ALL_ROWS")
11415
+ throw new Error(`${what} is ${spec.enforcement}/${spec.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
11416
+ if (spec.declaredName !== undefined)
11417
+ identifier(spec.declaredName, `${what}: declaredName`);
11418
+ if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
11419
+ throw new Error("checkSql is required for CHECK and only CHECK");
11420
+ if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
11421
+ throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
11422
+ if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
11423
+ throw new Error("NOT_NULL requires exactly one column path");
11424
+ if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
11425
+ throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
11426
+ checkPaths(spec.columns, what, spec.kind !== "NOT_NULL");
11427
+ if (spec.checkSql !== undefined) {
11428
+ try {
11429
+ validateNumericCheckSql(spec.checkSql, () => {});
11430
+ } catch (error) {
11431
+ throw new Error(`${what}: ${error.message} (CHECK SQL: ${spec.checkSql})`);
11432
+ }
11433
+ }
11434
+ const ref = spec.references;
11435
+ if (ref) {
11436
+ if (ref.columns.length !== spec.columns.length)
11437
+ throw new Error("foreign key local and referenced arity must match");
11438
+ if (JSON.stringify(ref.schemaPath) !== JSON.stringify(spec.schemaPath))
11439
+ throw new Error(`${what}: DuckDB reads only foreign keys to a table in the same schema`);
11440
+ identifier(ref.table, `${what}: referenced table`);
11441
+ identifier(ref.constraintId, `${what}: referenced constraintId`);
11442
+ checkPaths(ref.columns, `${what} (referenced)`, true);
11443
+ }
11444
+ const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
11445
+ sql: spec.checkSql,
11446
+ profile: ROW_SCALAR_EXPRESSION,
11447
+ schema_path: spec.schemaPath,
11448
+ evaluation_context: CHECK_CONTEXT
11449
+ });
11450
+ const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
11451
+ referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
11452
+ referenced_column_paths: ref.columns,
11453
+ match: "SIMPLE",
11454
+ on_update: "NO_ACTION",
11455
+ on_delete: "NO_ACTION"
11456
+ });
11457
+ return encodeASD(ConstraintInfoSchema, {
11458
+ ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
11459
+ definition: encodeASD(ConstraintDefinitionSchema, {
11460
+ kind: spec.kind,
11461
+ column_paths: spec.columns,
11462
+ declared_name: spec.declaredName ?? null,
11463
+ check_expression: check,
11464
+ foreign_key: foreign
11465
+ }),
11466
+ enforcement: spec.enforcement,
11467
+ validation: spec.validation,
11468
+ referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
11469
+ });
11470
+ }
11471
+ var KNOWN = {
11472
+ read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
11473
+ ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
11474
+ write: new Set([CONSTRAINT_ENFORCE]),
11475
+ transaction: new Set([TRANSACTION_DDL])
11476
+ };
11477
+ var REQUIRES = {
11478
+ [ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
11479
+ [CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
11480
+ [CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
11481
+ [CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
11482
+ "vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
11483
+ "vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
11484
+ };
11485
+ var CATEGORIES = ["read", "ddl", "write", "transaction"];
11486
+ function catalogCapabilities(init = {}) {
11487
+ return {
11488
+ read: [...new Set(init.read ?? [])].sort(),
11489
+ ddl: [...new Set(init.ddl ?? [])].sort(),
11490
+ write: [...new Set(init.write ?? [])].sort(),
11491
+ transaction: [...new Set(init.transaction ?? [])].sort()
11492
+ };
11493
+ }
11494
+ function constraintCapabilities(options = {}) {
11495
+ const enforce = options.enforce || options.create;
11496
+ return catalogCapabilities({
11497
+ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION],
11498
+ ddl: [...options.create ? [CONSTRAINT_CREATE] : [], ...options.mutate ? [CONSTRAINT_MUTATE] : []],
11499
+ write: enforce ? [CONSTRAINT_ENFORCE] : [],
11500
+ transaction: options.transactionDdl ? [TRANSACTION_DDL] : []
11501
+ });
11502
+ }
11503
+ function offeredCatalog(clientCapabilities) {
11504
+ if (clientCapabilities == null)
11505
+ return null;
11506
+ const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
11507
+ return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
11508
+ }
11509
+ function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
11510
+ const offered = offeredCatalog(clientCapabilities);
11511
+ if (offered == null)
11512
+ return catalogCapabilities();
11513
+ const chosen = new Set;
11514
+ for (const category of CATEGORIES)
11515
+ for (const p of available[category] ?? [])
11516
+ if (offered[category]?.includes(p))
11517
+ chosen.add(p);
11518
+ if (!supportsTransactions)
11519
+ chosen.delete(TRANSACTION_DDL);
11520
+ for (let changed = true;changed; ) {
11521
+ changed = false;
11522
+ for (const p of [...chosen])
11523
+ if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
11524
+ chosen.delete(p);
11525
+ changed = true;
11526
+ }
11527
+ }
11528
+ const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
11529
+ return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
11530
+ }
11531
+ function selectReadProfiles(available, clientCapabilities) {
11532
+ return selectCatalogCapabilities(catalogCapabilities({ read: [...available] }), clientCapabilities).read;
11533
+ }
11534
+ function defaultClientCapabilities(engine = "vgi-typescript") {
11535
+ return {
11536
+ engine,
11537
+ native_formats: [],
11538
+ catalogs: [],
11539
+ can_stream: true,
11540
+ filter_encodings: [],
11541
+ catalog: encodeCatalogCapabilities(catalogCapabilities({ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] })),
11542
+ query_pushdown: null
11543
+ };
11544
+ }
11545
+ function capabilitiesEmpty(caps) {
11546
+ return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
11547
+ }
11548
+ function readConstraintRecord(bytes) {
11549
+ const info = decodeASD(ConstraintInfoSchema, bytes);
11550
+ const ref = decodeASD(CatalogObjectRefSchema, info.ref);
11551
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
11552
+ const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
11553
+ const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
11554
+ const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
11555
+ return {
11556
+ schemaPath: [...ref.schema_path],
11557
+ table: ref.owner_table ?? "",
11558
+ id: ref.name,
11559
+ kind: def.kind,
11560
+ columns: [...def.column_paths].map((p) => [...p]),
11561
+ enforcement: info.enforcement,
11562
+ validation: info.validation,
11563
+ declaredName: def.declared_name ?? null,
11564
+ checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
11565
+ references: fk == null || target == null ? null : {
11566
+ schemaPath: [...target.schema_path],
11567
+ table: target.name,
11568
+ columns: [...fk.referenced_column_paths].map((p) => [...p]),
11569
+ constraintId: targetKey?.name ?? null,
11570
+ constraintTable: targetKey?.owner_table ?? null,
11571
+ constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
11572
+ match: fk.match,
11573
+ onUpdate: fk.on_update,
11574
+ onDelete: fk.on_delete
11575
+ }
11576
+ };
11577
+ }
11578
+ function fieldsByExactName(fields, name) {
11579
+ const out = [];
11580
+ fields.forEach((f, i) => {
11581
+ if (f.name === name)
11582
+ out.push(i);
11583
+ });
11584
+ return out;
11585
+ }
11586
+ function validateTableConstraints(table, schemaPath, fields, constraints) {
11587
+ if (constraints.length > 1024)
11588
+ throw new Error(`Table '${table}': too many constraints (at most 1024)`);
11589
+ const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
11590
+ if (rowIds.length > 1)
11591
+ throw new Error(`Table '${table}': at most one column may carry is_row_id`);
11592
+ const rowId = rowIds[0] ?? -1;
11593
+ const records = [];
11594
+ const required = new Set;
11595
+ const ids = new Set;
11596
+ const labels = new Set;
11597
+ let primaryKeys = 0;
11598
+ for (const bytes of constraints) {
11599
+ let record;
11600
+ try {
11601
+ record = readConstraintRecord(bytes);
11602
+ } catch (error) {
11603
+ throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
11604
+ }
11605
+ const where = `Table '${table}': constraint '${record.id}'`;
11606
+ const fail = (message) => {
11607
+ throw new Error(`${where}: ${message}`);
11608
+ };
11609
+ if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
11610
+ fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
11611
+ if (ids.has(record.id))
11612
+ fail("duplicate constraint id");
11613
+ ids.add(record.id);
11614
+ if (record.declaredName != null) {
11615
+ const label = record.declaredName.toLowerCase();
11616
+ if (labels.has(label))
11617
+ fail(`duplicate declared name '${record.declaredName}'`);
11618
+ labels.add(label);
11619
+ }
11620
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
11621
+ fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
11622
+ try {
11623
+ checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
11624
+ } catch (error) {
11625
+ fail(error.message);
11626
+ }
11627
+ const resolveTop = (path) => {
11628
+ const matches = fieldsByExactName(fields, path[0]);
11629
+ if (matches.length !== 1 || matches[0] === rowId)
11630
+ fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
11631
+ return matches[0];
11632
+ };
11633
+ switch (record.kind) {
11634
+ case "CHECK": {
11635
+ if (record.checkSql == null)
11636
+ fail("CHECK without an expression");
11637
+ validateCheckRecord(bytes, where, schemaPath, fields, rowId);
11638
+ break;
11639
+ }
11640
+ case "NOT_NULL": {
11641
+ if (record.columns.length !== 1)
11642
+ fail("NOT_NULL requires exactly one column path");
11643
+ const path = record.columns[0];
11644
+ let field = fields[resolveTop(path)];
11645
+ for (let depth = 1;depth < path.length; depth++) {
11646
+ const children = ordinaryStructChildren(field);
11647
+ if (!children)
11648
+ fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
11649
+ const matches = fieldsByExactName(children, path[depth]);
11650
+ if (matches.length !== 1)
11651
+ fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
11652
+ field = children[matches[0]];
11653
+ }
11654
+ if (path.length === 1 && isGeneratedField(field))
11655
+ fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
11656
+ required.add(JSON.stringify(path));
11657
+ break;
11658
+ }
11659
+ case "PRIMARY_KEY":
11660
+ case "UNIQUE": {
11661
+ for (const path of record.columns) {
11662
+ const index = resolveTop(path);
11663
+ if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
11664
+ fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
11665
+ }
11666
+ if (record.kind === "PRIMARY_KEY") {
11667
+ if (++primaryKeys > 1)
11668
+ fail("a table may have only one PRIMARY KEY");
11669
+ for (const path of record.columns)
11670
+ required.add(JSON.stringify(path));
11671
+ }
11672
+ break;
11673
+ }
11674
+ case "FOREIGN_KEY": {
11675
+ record.columns.forEach(resolveTop);
11676
+ const ref = record.references;
11677
+ if (ref == null || ref.constraintId == null)
11678
+ fail("FOREIGN_KEY requires a referenced table and referenced constraint");
11679
+ if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
11680
+ fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
11681
+ if (ref.columns.length !== record.columns.length)
11682
+ fail("foreign key arity mismatch");
11683
+ try {
11684
+ checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
11685
+ } catch (error) {
11686
+ fail(error.message);
11687
+ }
11688
+ if (ref.match !== undefined && ref.match !== "SIMPLE")
11689
+ fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
11690
+ for (const action of [ref.onUpdate, ref.onDelete])
11691
+ if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
11692
+ fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
11693
+ break;
11694
+ }
11695
+ default:
11696
+ fail(`unknown constraint kind ${String(record.kind)}`);
11697
+ }
11698
+ records.push(record);
11699
+ }
11700
+ return { records, required };
11701
+ }
11702
+ function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
11703
+ const info = decodeASD(ConstraintInfoSchema, bytes);
11704
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
11705
+ const expression = decodeASD(SqlExpressionSchema, def.check_expression);
11706
+ const fail = (message) => {
11707
+ throw new Error(`${where}: ${message}`);
11708
+ };
11709
+ if (expression.profile !== ROW_SCALAR_EXPRESSION)
11710
+ fail(`unsupported CHECK expression profile ${expression.profile}`);
11711
+ if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
11712
+ fail("CHECK expression belongs to another schema");
11713
+ const context = expression.evaluation_context ?? {};
11714
+ for (const [key, value] of Object.entries(CHECK_CONTEXT))
11715
+ if (context[key] !== value)
11716
+ fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
11717
+ try {
11718
+ validateNumericCheckSql(expression.sql, (name) => {
11719
+ const lower = name.toLowerCase();
11720
+ const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
11721
+ if (matches.length > 1)
11722
+ throw new Error(`ambiguous CHECK column reference ${name}`);
11723
+ if (matches.length === 0 || matches[0] === rowId)
11724
+ throw new Error(`CHECK references a missing or row-id column ${name}`);
11725
+ const column = fields[matches[0]];
11726
+ if (column.metadata.has("ARROW:extension:name"))
11727
+ throw new Error(`CHECK operand ${name} has an extension type`);
11728
+ if (isGeneratedField(column))
11729
+ throw new Error(`CHECK operand ${name} is a generated column`);
11730
+ const type = duckdbPrimitive(column);
11731
+ if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
11732
+ throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
11733
+ });
11734
+ } catch (error) {
11735
+ fail(`${error.message} (CHECK SQL: ${expression.sql})`);
11736
+ }
11737
+ }
11738
+ function validateForeignKeyTargets(tables) {
11739
+ const key = (schemaPath, name) => JSON.stringify([...schemaPath, name]);
11740
+ const byTable = new Map;
11741
+ for (const t of tables)
11742
+ byTable.set(key(t.schemaPath, t.name), t.constraints.map(readConstraintRecord));
11743
+ for (const t of tables) {
11744
+ for (const record of byTable.get(key(t.schemaPath, t.name)) ?? []) {
11745
+ if (record.kind !== "FOREIGN_KEY" || record.references == null)
11746
+ continue;
11747
+ const ref = record.references;
11748
+ const where = `Table '${t.name}': constraint '${record.id}'`;
11749
+ const target = byTable.get(key(ref.schemaPath, ref.table));
11750
+ if (!target)
11751
+ throw new Error(`${where}: references table ${[...ref.schemaPath, ref.table].join(".")}, which this catalog does not serve`);
11752
+ const key_ = target.find((r) => r.id === ref.constraintId);
11753
+ if (!key_ || key_.kind !== "PRIMARY_KEY" && key_.kind !== "UNIQUE")
11754
+ throw new Error(`${where}: referenced constraint '${ref.constraintId}' is not a PRIMARY_KEY or UNIQUE record of '${ref.table}'`);
11755
+ const want = new Set(ref.columns.map((p) => JSON.stringify(p)));
11756
+ if (key_.columns.length !== want.size || !key_.columns.every((p) => want.has(JSON.stringify(p))))
11757
+ throw new Error(`${where}: referenced columns do not match constraint '${ref.constraintId}' of '${ref.table}'`);
11758
+ }
11759
+ }
11760
+ }
11761
+ function servedConstraintFields(fields, required) {
11762
+ const rewrite = (list, prefix) => {
11763
+ let changed = false;
11764
+ const out = list.map((f) => {
11765
+ if (prefix.length === 0 && isRowIdField(f))
11766
+ return f;
11767
+ const path = [...prefix, f.name];
11768
+ const nullable = !required.has(JSON.stringify(path));
11769
+ const children = ordinaryStructChildren(f);
11770
+ const newChildren = children ? rewrite(children, path) : null;
11771
+ if (nullable === f.nullable && (newChildren == null || newChildren === children))
11772
+ return f;
11773
+ changed = true;
11774
+ const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
11775
+ return field2(f.name, type, nullable, new Map(f.metadata));
11776
+ });
11777
+ return changed ? out : list;
11778
+ };
11779
+ return rewrite(fields, []);
11780
+ }
11781
+ function validateConstraintNullability(table, fields, constraints) {
11782
+ const schemaPath = constraints.length ? readConstraintRecord(constraints[0]).schemaPath : ["main"];
11783
+ validateTableConstraints(table, schemaPath, fields, constraints);
11784
+ }
11785
+ function translateLegacyGenerated(fields, owner, table) {
11786
+ let changed = false;
11787
+ const out = fields.map((f) => {
11788
+ const sql = f.metadata.get("generated_expression");
11789
+ if (sql === undefined)
11790
+ return f;
11791
+ if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
11792
+ throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
11793
+ const metadata = new Map(f.metadata);
11794
+ metadata.delete("generated_expression");
11795
+ metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
11796
+ metadata.set(GENERATION_KEY, "virtual");
11797
+ changed = true;
11798
+ return field2(f.name, f.type, f.nullable, metadata);
11799
+ });
11800
+ return changed ? out : fields;
11801
+ }
11802
+ function servedTableSchema(table, schemaPath, schema, constraints) {
11803
+ let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
11804
+ const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
11805
+ fields = servedConstraintFields(fields, required);
11806
+ return fields === schema.fields ? schema : schema2(fields, schema.metadata);
11807
+ }
11808
+ function servedTableInfo(info) {
11809
+ if (!info.columns || info.columns.length === 0) {
11810
+ if ((info.constraints ?? []).length)
11811
+ throw new Error(`Table '${info.name}': constraints on a table without columns`);
11812
+ return info;
11813
+ }
11814
+ const schema = deserializeSchema(info.columns);
11815
+ const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
11816
+ return served === schema ? info : { ...info, columns: serializeSchema(served) };
11817
+ }
11818
+
10576
11819
  // src/catalog/column-metadata.ts
10577
11820
  function scalarText(value) {
10578
11821
  for (let i = 0;i < value.length; i++) {
@@ -10724,9 +11967,21 @@ function validateTableInfoColumns(info) {
10724
11967
  validateColumnExpressionsIpc(info.columns, info.schema_path);
10725
11968
  }
10726
11969
  }
11970
+ function servedValidatedTableInfo(info) {
11971
+ if (info.columns.length)
11972
+ validateColumnMetadataIpc(info.columns);
11973
+ const served = servedTableInfo(info);
11974
+ if (served.columns.length) {
11975
+ try {
11976
+ validateColumnExpressionsIpc(served.columns, served.schema_path);
11977
+ } catch (error) {
11978
+ throw new Error(`Table '${served.name}': ${error.message}`);
11979
+ }
11980
+ }
11981
+ return served;
11982
+ }
10727
11983
  function encodeValidatedTableInfo(info) {
10728
- validateTableInfoColumns(info);
10729
- return encodeTableInfo(info);
11984
+ return encodeTableInfo(servedValidatedTableInfo(info));
10730
11985
  }
10731
11986
 
10732
11987
  // src/protocol/handlers/catalog/admin.ts
@@ -10748,128 +12003,6 @@ function catalogStringMap(raw) {
10748
12003
  return result;
10749
12004
  }
10750
12005
 
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
12006
  // src/protocol/handlers/catalog/contents.ts
10874
12007
  import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
10875
12008
 
@@ -10881,12 +12014,10 @@ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@qu
10881
12014
  var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
10882
12015
  var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
10883
12016
  function encodeCatalogStreams(inventory) {
10884
- for (const schema of inventory)
10885
- for (const table of schema.tables)
10886
- validateTableInfoColumns(table);
12017
+ const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
10887
12018
  const streams = {
10888
12019
  schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
10889
- tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
12020
+ tables: encodeASDCollection(TableInfoSchema, tables),
10890
12021
  views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
10891
12022
  functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
10892
12023
  macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
@@ -11546,6 +12677,56 @@ class CatalogInterface {
11546
12677
  tableCreate(attachOpaqueData, schemaPath, name, columns, onConflict, constraintDefinitions, transactionOpaqueData) {
11547
12678
  throw new CatalogReadOnlyError("table_create");
11548
12679
  }
12680
+ catalogCapabilities(_attachOpaqueData) {
12681
+ const proto = CatalogInterface.prototype;
12682
+ if (this.tableConstraintsApply !== proto.tableConstraintsApply || this._implementsLegacyNotNull())
12683
+ return constraintCapabilities({ mutate: true, enforce: true });
12684
+ return null;
12685
+ }
12686
+ _implementsLegacyNotNull() {
12687
+ const proto = CatalogInterface.prototype;
12688
+ return this.tableNotNullSet !== proto.tableNotNullSet || this.tableNotNullDrop !== proto.tableNotNullDrop;
12689
+ }
12690
+ async tableConstraintsApply(request) {
12691
+ if (!this._implementsLegacyNotNull())
12692
+ throw new VgiError("catalog_table_constraints_apply is not implemented by this catalog", "UNIMPLEMENTED");
12693
+ const target = decodeCatalogObjectRef(request.table);
12694
+ const attach = request.attach_opaque_data;
12695
+ const tx = request.transaction_opaque_data ?? undefined;
12696
+ const schemaPath = [...target.schema_path];
12697
+ const read = async () => {
12698
+ const info = await this.tableGet(attach, schemaPath, target.name, undefined, undefined, tx);
12699
+ if (!info)
12700
+ throw new CatalogNotFoundError("Table", target.name);
12701
+ return info;
12702
+ };
12703
+ const before = await read();
12704
+ if (!sameBytes2(before.definition_revision ?? null, request.expected_revision))
12705
+ throw new VgiError(`Table '${target.name}': definition_revision changed; retry the statement`, "FAILED_PRECONDITION");
12706
+ const records = (before.constraints ?? []).map(readConstraintRecord);
12707
+ for (const bytes of request.changes) {
12708
+ const change = decodeConstraintChange(bytes);
12709
+ if (change.operation === "ADD" && change.definition != null) {
12710
+ const def = decodeConstraintDefinition(change.definition);
12711
+ if (def.kind === "NOT_NULL" && def.column_paths.length === 1 && def.column_paths[0].length === 1) {
12712
+ await this.tableNotNullSet(attach, schemaPath, target.name, [...def.column_paths[0]], false, tx);
12713
+ continue;
12714
+ }
12715
+ } else if (change.operation === "DROP" && change.ref != null) {
12716
+ const id = decodeCatalogObjectRef(change.ref).name;
12717
+ const record = records.find((r) => r.id === id);
12718
+ if (record?.kind === "NOT_NULL" && record.columns[0]?.length === 1) {
12719
+ await this.tableNotNullDrop(attach, schemaPath, target.name, record.columns[0], false, tx);
12720
+ continue;
12721
+ }
12722
+ }
12723
+ throw new VgiError("catalog_table_constraints_apply: only ADD/DROP of a top-level NOT_NULL routes to tableNotNullSet/tableNotNullDrop; implement tableConstraintsApply", "UNIMPLEMENTED");
12724
+ }
12725
+ const after = await read();
12726
+ if (after.definition_revision == null || sameBytes2(after.definition_revision, before.definition_revision ?? null))
12727
+ 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");
12728
+ return { table: request.table, definition_revision: after.definition_revision, constraints: after.constraints ?? [] };
12729
+ }
11549
12730
  tableDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
11550
12731
  throw new CatalogReadOnlyError("table_drop");
11551
12732
  }
@@ -11673,6 +12854,16 @@ class CatalogInterface {
11673
12854
  transactionCommit(attachOpaqueData, transactionOpaqueData) {}
11674
12855
  transactionRollback(attachOpaqueData, transactionOpaqueData) {}
11675
12856
  }
12857
+ function sameBytes2(a, b) {
12858
+ if (a == null || b == null)
12859
+ return a == b;
12860
+ if (a.length !== b.length)
12861
+ return false;
12862
+ for (let i = 0;i < a.length; i++)
12863
+ if (a[i] !== b[i])
12864
+ return false;
12865
+ return true;
12866
+ }
11676
12867
 
11677
12868
  // src/attach-ticket.ts
11678
12869
  init_arrow();
@@ -12232,13 +13423,10 @@ function catalogAdminHandlers(getCatalog, signingKey) {
12232
13423
  }
12233
13424
  const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
12234
13425
  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
- });
13426
+ const advertised = result.catalog_capabilities != null ? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities)) : await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
13427
+ if (!capabilitiesEmpty(advertised)) {
13428
+ result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
13429
+ result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
12242
13430
  }
12243
13431
  const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
12244
13432
  return wrapResult(buildCatalogAttachResult({
@@ -12375,27 +13563,39 @@ import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-
12375
13563
  // src/catalog/unconstrained-columns.ts
12376
13564
  init_arrow();
12377
13565
  import { MethodNotImplementedError as MethodNotImplementedError3 } from "@query-farm/vgi-rpc";
12378
- function requireUnconstrainedColumns(columns) {
12379
- const visit = (field, top, depth) => {
13566
+ function requireCreateColumns(columns, constraintDefinitions = []) {
13567
+ const required = new Set;
13568
+ for (const bytes of constraintDefinitions) {
13569
+ let def;
13570
+ try {
13571
+ def = decodeConstraintDefinition(bytes);
13572
+ } catch (error) {
13573
+ throw new Error(`catalog_table_create: undecodable constraint definition: ${error.message}`);
13574
+ }
13575
+ if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
13576
+ for (const path of def.column_paths)
13577
+ required.add(JSON.stringify([...path]));
13578
+ }
13579
+ const visit = (field, path, depth) => {
12380
13580
  if (depth > 64)
12381
13581
  throw new MethodNotImplementedError3("catalog_table_create: column nesting exceeds supported depth");
12382
- if (top && field.metadata?.has("is_row_id"))
13582
+ if (depth === 0 && field.metadata?.has("is_row_id"))
12383
13583
  return;
12384
13584
  for (const key of field.metadata?.keys() ?? []) {
12385
13585
  if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
12386
13586
  throw new MethodNotImplementedError3("catalog_table_create: logical column types require negotiation");
12387
13587
  }
12388
13588
  }
12389
- if (!field.nullable) {
12390
- throw new MethodNotImplementedError3("catalog_table_create: nonnullable user columns require canonical constraints");
13589
+ if (!field.nullable && !required.has(JSON.stringify(path))) {
13590
+ throw new MethodNotImplementedError3(`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`);
12391
13591
  }
12392
13592
  if (isStruct(field.type)) {
12393
13593
  for (const child of field.type.children)
12394
- visit(child, false, depth + 1);
13594
+ visit(child, [...path, child.name], depth + 1);
12395
13595
  }
12396
13596
  };
12397
13597
  for (const field of deserializeSchema(columns).fields)
12398
- visit(field, true, 0);
13598
+ visit(field, [field.name], 0);
12399
13599
  }
12400
13600
 
12401
13601
  // src/protocol/handlers/catalog/table.ts
@@ -12417,19 +13617,57 @@ function catalogTableHandlers(getCatalog, signingKey) {
12417
13617
  const catalogTableCreate = catalogHandler(signingKey, async (params) => {
12418
13618
  if (params.constraint_definitions == null)
12419
13619
  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
- }
13620
+ const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
12423
13621
  if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
12424
13622
  throw new MethodNotImplementedError4("catalog_table_create: table metadata/options/layout profiles are not supported");
12425
13623
  }
13624
+ const attach = toUint8Array(params.attach_opaque_data);
13625
+ const cat = getCatalog();
13626
+ if (definitions.length > 0) {
13627
+ const caps = await cat.catalogCapabilities(attach);
13628
+ if (caps != null && !(caps.ddl.includes(CONSTRAINT_CREATE) && caps.write.includes(CONSTRAINT_ENFORCE))) {
13629
+ 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");
13630
+ }
13631
+ }
12426
13632
  validateColumnMetadataIpc(toUint8Array(params.columns));
12427
13633
  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);
13634
+ requireCreateColumns(toUint8Array(params.columns), definitions);
13635
+ 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
13636
  return {};
12432
13637
  });
13638
+ const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
13639
+ const attach = toUint8Array(params.attach_opaque_data);
13640
+ const cat = getCatalog();
13641
+ const caps = await cat.catalogCapabilities(attach);
13642
+ if (caps != null && !caps.ddl.includes(CONSTRAINT_MUTATE)) {
13643
+ throw new MethodNotImplementedError4("catalog_table_constraints_apply: this catalog does not advertise vgi.constraint.mutate.v1");
13644
+ }
13645
+ const table = toUint8Array(params.table);
13646
+ const expected = toUint8Array(params.expected_revision);
13647
+ const changes = Array.from(params.changes, (c) => toUint8Array(c));
13648
+ if (expected.length === 0 || changes.length === 0)
13649
+ throw new Error("catalog_table_constraints_apply: empty revision or change list");
13650
+ const snapshot = await cat.tableConstraintsApply({
13651
+ attach_opaque_data: attach,
13652
+ table,
13653
+ expected_revision: expected,
13654
+ changes,
13655
+ transaction_opaque_data: params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : null
13656
+ });
13657
+ const want = decodeCatalogObjectRef(table);
13658
+ const got = decodeCatalogObjectRef(toUint8Array(snapshot.table));
13659
+ if (got.name !== want.name || JSON.stringify([...got.schema_path]) !== JSON.stringify([...want.schema_path]))
13660
+ throw new Error("catalog_table_constraints_apply: the catalog returned a snapshot of a different table");
13661
+ const revision = toUint8Array(snapshot.definition_revision);
13662
+ if (revision.length === 0 || revision.length === expected.length && revision.every((b, i) => b === expected[i]))
13663
+ throw new Error(`catalog_table_constraints_apply: table '${want.name}' must return a new, nonempty definition_revision`);
13664
+ for (const record of snapshot.constraints) {
13665
+ const view = readConstraintRecord(toUint8Array(record));
13666
+ if (view.table !== want.name || JSON.stringify(view.schemaPath) !== JSON.stringify([...want.schema_path]))
13667
+ throw new Error(`catalog_table_constraints_apply: constraint '${view.id}' belongs to another table`);
13668
+ }
13669
+ return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
13670
+ });
12433
13671
  const catalogTableDrop = catalogHandler(signingKey, async (params) => {
12434
13672
  const cat = getCatalog();
12435
13673
  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 +13755,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
12517
13755
  return {};
12518
13756
  });
12519
13757
  return {
12520
- catalogTableConstraintsApply: async () => {
12521
- throw new MethodNotImplementedError4("catalog_table_constraints_apply");
12522
- },
13758
+ catalogTableConstraintsApply,
12523
13759
  catalogTableGet,
12524
13760
  catalogTableCreate,
12525
13761
  catalogTableDrop,
@@ -14270,6 +15506,10 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14270
15506
  const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
14271
15507
  return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
14272
15508
  }
15509
+ catalogCapabilities(_attachOpaqueData) {
15510
+ const read = this.catalogReadProfiles();
15511
+ return read.length ? catalogCapabilities({ read }) : null;
15512
+ }
14273
15513
  detach(attachOpaqueData) {
14274
15514
  for (const [name, id] of this._attachments) {
14275
15515
  if (bufferEquals(id, attachOpaqueData)) {
@@ -14330,8 +15570,12 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14330
15570
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
14331
15571
  if (!schema || !schema.tables)
14332
15572
  return [];
14333
- return await Promise.all(schema.tables.map(async (t) => {
15573
+ const infos = await Promise.all(schema.tables.map(async (t) => {
15574
+ if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
15575
+ 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");
15576
+ }
14334
15577
  let colSchema;
15578
+ let bindFailed = false;
14335
15579
  if (t.columns) {
14336
15580
  colSchema = t.columns;
14337
15581
  } else if (t.function) {
@@ -14353,26 +15597,31 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14353
15597
  colSchema = response.output_schema;
14354
15598
  } catch {
14355
15599
  colSchema = schema2([]);
15600
+ bindFailed = true;
14356
15601
  }
14357
15602
  } else {
14358
15603
  colSchema = schema2([]);
14359
15604
  }
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);
15605
+ if (!bindFailed) {
15606
+ if (t.defaults) {
15607
+ colSchema = applyDefaults(colSchema, t.defaults, path);
15608
+ }
15609
+ if (t.generatedColumns) {
15610
+ colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path, t.name);
15611
+ }
15612
+ if (t.columnComments) {
15613
+ colSchema = applyColumnComments(colSchema, t.columnComments, t.name);
15614
+ }
14368
15615
  }
14369
15616
  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");
15617
+ const constraints = bindFailed ? [] : t.constraints ?? [];
15618
+ colSchema = servedTableSchema(t.name, path, colSchema, constraints);
15619
+ try {
15620
+ validateColumnExpressions(colSchema, path);
15621
+ } catch (error) {
15622
+ throw new Error(`Table '${t.name}': ${error.message}`);
14375
15623
  }
15624
+ const columns = serializeSchema(colSchema);
14376
15625
  const requiredFilters = t.requiredFilters ?? [];
14377
15626
  for (const group of requiredFilters) {
14378
15627
  if (!Array.isArray(group) || group.length === 0)
@@ -14407,7 +15656,7 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14407
15656
  name: t.name,
14408
15657
  schema_path: normalizeSchemaPath(path),
14409
15658
  columns,
14410
- constraints: t.constraints ?? [],
15659
+ constraints: [...constraints],
14411
15660
  definition_revision: t.definitionRevision ?? null,
14412
15661
  write_result_modes: {},
14413
15662
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
@@ -14420,6 +15669,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
14420
15669
  required_filters: requiredFilters
14421
15670
  };
14422
15671
  }));
15672
+ validateForeignKeyTargets(infos.map((info) => ({ schemaPath: info.schema_path, name: info.name, constraints: info.constraints })));
15673
+ return infos;
14423
15674
  }
14424
15675
  tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
14425
15676
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
@@ -14729,7 +15980,14 @@ function defaultToSql(value) {
14729
15980
  const escaped = value.replace(/'/g, "''");
14730
15981
  return `'${escaped}'`;
14731
15982
  }
14732
- function applyDefaults(schema, defaults) {
15983
+ function canonicalDefault(type, value) {
15984
+ if (type === "BOOLEAN")
15985
+ return typeof value === "boolean";
15986
+ if (type === "VARCHAR")
15987
+ return typeof value === "string";
15988
+ return false;
15989
+ }
15990
+ function applyDefaults(schema, defaults, owner) {
14733
15991
  let result = schema;
14734
15992
  for (const [colName, value] of Object.entries(defaults)) {
14735
15993
  const idx = result.fields.findIndex((f) => f.name === colName);
@@ -14737,7 +15995,12 @@ function applyDefaults(schema, defaults) {
14737
15995
  continue;
14738
15996
  const f = result.fields[idx];
14739
15997
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
14740
- existingMeta.set("default", defaultToSql(value));
15998
+ const sql = defaultToSql(value);
15999
+ if (canonicalDefault(duckdbPrimitive(f), value)) {
16000
+ existingMeta.set("vgi.column.default.v1", defaultExpressionMetadata(sql, owner));
16001
+ } else {
16002
+ existingMeta.set("default", sql);
16003
+ }
14741
16004
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
14742
16005
  const fields = [...result.fields];
14743
16006
  fields[idx] = newField;
@@ -14745,17 +16008,21 @@ function applyDefaults(schema, defaults) {
14745
16008
  }
14746
16009
  return result;
14747
16010
  }
14748
- function applyGeneratedColumns(schema, generated, owner) {
16011
+ function applyGeneratedColumns(schema, generated, owner, table) {
14749
16012
  let result = schema;
14750
16013
  for (const [colName, expression] of Object.entries(generated)) {
14751
16014
  const idx = result.fields.findIndex((f) => f.name === colName);
14752
16015
  if (idx < 0)
14753
- throw new Error(`generated expression references unknown column ${colName}`);
16016
+ throw new Error(`Table '${table}': generatedColumns names unknown column ${colName}`);
14754
16017
  const f = result.fields[idx];
14755
16018
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
14756
16019
  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));
16020
+ throw new Error(`Table '${table}': generatedColumns for ${colName} conflicts with existing expression metadata`);
16021
+ try {
16022
+ existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
16023
+ } catch (error) {
16024
+ throw new Error(`Table '${table}': column ${colName}: ${error.message}`);
16025
+ }
14759
16026
  existingMeta.set(GENERATION_KEY, "virtual");
14760
16027
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
14761
16028
  const fields = [...result.fields];
@@ -14764,12 +16031,12 @@ function applyGeneratedColumns(schema, generated, owner) {
14764
16031
  }
14765
16032
  return result;
14766
16033
  }
14767
- function applyColumnComments(schema, comments) {
16034
+ function applyColumnComments(schema, comments, table) {
14768
16035
  let result = schema;
14769
16036
  for (const [colName, comment] of Object.entries(comments)) {
14770
16037
  const idx = result.fields.findIndex((f) => f.name === colName);
14771
16038
  if (idx < 0)
14772
- throw new Error(`column comment references unknown field ${colName}`);
16039
+ throw new Error(`Table '${table}': columnComments names unknown column ${colName}`);
14773
16040
  const f = result.fields[idx];
14774
16041
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
14775
16042
  existingMeta.set("comment", comment);
@@ -14899,6 +16166,29 @@ function sameSpelling(left, right) {
14899
16166
  const b = normalizeSchemaPath(right);
14900
16167
  return a.length === b.length && a.every((part, i) => part === b[i]);
14901
16168
  }
16169
+ // src/catalog/indexes.ts
16170
+ var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
16171
+ function emptyIndexOptions() {
16172
+ return Uint8Array.from(atob(NO_OPTIONS_B64), (c) => c.charCodeAt(0));
16173
+ }
16174
+ function canonicalIndex(spec) {
16175
+ if (spec.columns.length === 0)
16176
+ throw new Error(`index on '${spec.table}' requires at least one key`);
16177
+ if (!spec.algorithm)
16178
+ throw new Error("index algorithm must be nonempty");
16179
+ const values = spec.options ?? emptyIndexOptions();
16180
+ return {
16181
+ definition: encodeASD(IndexDefinitionSchema, {
16182
+ table: encodeASD(CatalogObjectRefSchema, { kind: "table", schema_path: spec.schemaPath, name: spec.table, owner_table: null }),
16183
+ algorithm: spec.algorithm,
16184
+ keys: spec.columns.map((path) => encodeASD(IndexKeySchema, { column_path: path, expression: null })),
16185
+ options: values,
16186
+ constraint_type: spec.constraintType ?? "NONE",
16187
+ associated_constraint: spec.associatedConstraintId == null ? null : encodeASD(CatalogObjectRefSchema, { kind: "constraint", schema_path: spec.schemaPath, name: spec.associatedConstraintId, owner_table: spec.table })
16188
+ }),
16189
+ options: encodeASD(OptionStateSchema, { values, explicit_names: spec.explicitOptionNames ?? [] })
16190
+ };
16191
+ }
14902
16192
  // src/catalog/composite.ts
14903
16193
  var ROUTE_BYTE = 0;
14904
16194
 
@@ -15048,6 +16338,12 @@ class CompositeCatalogInterface extends CatalogInterface {
15048
16338
  async tableNotNullDrop(...args) {
15049
16339
  await this._route(args[0]).tableNotNullDrop(...args);
15050
16340
  }
16341
+ async tableConstraintsApply(request) {
16342
+ return await this._route(request.attach_opaque_data).tableConstraintsApply(request);
16343
+ }
16344
+ async catalogCapabilities(attachOpaqueData) {
16345
+ return await this._route(attachOpaqueData).catalogCapabilities(attachOpaqueData);
16346
+ }
15051
16347
  async viewCreate(...args) {
15052
16348
  await this._route(args[0]).viewCreate(...args);
15053
16349
  }
@@ -15391,13 +16687,19 @@ export {
15391
16687
  AuthContext3 as AuthContext,
15392
16688
  AuthUnavailableError2 as AuthUnavailableError,
15393
16689
  BindResultSchema,
16690
+ CONSTRAINT_CREATE,
16691
+ CONSTRAINT_ENFORCE,
16692
+ CONSTRAINT_MUTATE,
15394
16693
  CONSTRAINT_RECORDS_READ,
15395
16694
  CatalogInterface,
15396
16695
  CompositeCatalogInterface,
16696
+ DEFAULT_EXPRESSION_KEY,
15397
16697
  DateUnit3 as DateUnit,
15398
16698
  EXCHANGE_STATE_SCHEMA,
15399
16699
  FunctionRegistry,
15400
16700
  FunctionType,
16701
+ GENERATED_EXPRESSION_KEY,
16702
+ GENERATION_KEY,
15401
16703
  GrantKeys3 as GrantKeys,
15402
16704
  GrantRefusedError2 as GrantRefusedError,
15403
16705
  IdentityUnavailableError2 as IdentityUnavailableError,
@@ -15408,6 +16710,7 @@ export {
15408
16710
  ReadOnlyCatalogInterface,
15409
16711
  ScanFunctionResultSchema,
15410
16712
  StatusError2 as StatusError,
16713
+ TRANSACTION_DDL,
15411
16714
  TimeUnit2 as TimeUnit,
15412
16715
  TypeId,
15413
16716
  UnionMode2 as UnionMode,
@@ -15419,9 +16722,16 @@ export {
15419
16722
  batchToSecretDict,
15420
16723
  binary2 as binary,
15421
16724
  bool2 as bool,
16725
+ buildCatalogCapabilities,
16726
+ buildConstraintChange,
16727
+ buildConstraintDefinition,
16728
+ buildMacroOverload,
15422
16729
  buildStatisticsBatch,
15423
16730
  cacheControlMetadata,
16731
+ canonicalIndex,
16732
+ catalogCapabilities,
15424
16733
  columnFromArray,
16734
+ constraintCapabilities,
15425
16735
  constraintRecord,
15426
16736
  constraintSpecFields,
15427
16737
  createLandingRoutes,
@@ -15432,7 +16742,20 @@ export {
15432
16742
  decimal2 as decimal,
15433
16743
  decimal1282 as decimal128,
15434
16744
  decimal2562 as decimal256,
16745
+ decodeCatalogCapabilities,
16746
+ decodeCatalogObjectRef,
16747
+ decodeConstraintChange,
16748
+ decodeConstraintDefinition,
16749
+ decodeConstraintInfo,
16750
+ decodeConstraintSnapshot,
16751
+ decodeConstraintsApplyRequest,
15435
16752
  decodeDictValue,
16753
+ decodeForeignKeyDefinition,
16754
+ decodeIndexDefinition,
16755
+ decodeMacroOverload,
16756
+ decodeSqlExpression,
16757
+ defaultClientCapabilities,
16758
+ defaultExpressionMetadata,
15436
16759
  defineAggregate,
15437
16760
  defineRowTransformFunction,
15438
16761
  defineScalarFunction,
@@ -15444,6 +16767,18 @@ export {
15444
16767
  dictionary2 as dictionary,
15445
16768
  duration2 as duration,
15446
16769
  emptyBatch,
16770
+ emptyIndexOptions,
16771
+ encodeCatalogCapabilities,
16772
+ encodeCatalogObjectRef,
16773
+ encodeConstraintChange,
16774
+ encodeConstraintDefinition,
16775
+ encodeConstraintInfo,
16776
+ encodeConstraintSnapshot,
16777
+ encodeConstraintsApplyRequest,
16778
+ encodeForeignKeyDefinition,
16779
+ encodeIndexDefinition,
16780
+ encodeMacroOverload,
16781
+ encodeSqlExpression,
15447
16782
  field2 as field,
15448
16783
  filterBatch,
15449
16784
  fixedSizeBinary2 as fixedSizeBinary,
@@ -15451,6 +16786,7 @@ export {
15451
16786
  float162 as float16,
15452
16787
  float322 as float32,
15453
16788
  float642 as float64,
16789
+ generatedExpressionMetadata,
15454
16790
  int2 as int,
15455
16791
  int162 as int16,
15456
16792
  int322 as int32,
@@ -15488,12 +16824,18 @@ export {
15488
16824
  readConstraintRecord,
15489
16825
  safeNumber,
15490
16826
  schema2 as schema,
16827
+ selectCatalogCapabilities,
16828
+ selectReadProfiles,
15491
16829
  serializeAttachOptionSpec,
15492
16830
  serializeAttachOptionSpecs,
15493
16831
  serializeBatch,
15494
16832
  serializeColumnStatistics,
15495
16833
  serializeSchema,
16834
+ servedConstraintFields,
16835
+ servedTableInfo,
16836
+ servedTableSchema,
15496
16837
  sparseUnion2 as sparseUnion,
16838
+ sqlExpression,
15497
16839
  struct2 as struct,
15498
16840
  time2 as time,
15499
16841
  timeMicrosecond2 as timeMicrosecond,
@@ -15506,7 +16848,12 @@ export {
15506
16848
  uint642 as uint64,
15507
16849
  uint82 as uint8,
15508
16850
  union2 as union,
15509
- utf82 as utf8
16851
+ utf82 as utf8,
16852
+ validateColumnExpressionSql,
16853
+ validateConstraintNullability,
16854
+ validateForeignKeyTargets,
16855
+ validateNumericCheckSql,
16856
+ validateTableConstraints
15510
16857
  };
15511
16858
 
15512
- //# debugId=FE84125A7F5CDDE564756E2164756E21
16859
+ //# debugId=BAA5461FE644FC2564756E2164756E21