@query-farm/vgi 0.47.0 → 0.47.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/catalog/column-expressions.d.ts +22 -1
  2. package/dist/catalog/column-metadata.d.ts +7 -0
  3. package/dist/catalog/column-types.d.ts +15 -0
  4. package/dist/catalog/composite.d.ts +2 -0
  5. package/dist/catalog/constraints.d.ts +172 -0
  6. package/dist/catalog/descriptors.d.ts +19 -1
  7. package/dist/catalog/indexes.d.ts +29 -0
  8. package/dist/catalog/interface.d.ts +41 -0
  9. package/dist/catalog/public-codecs.d.ts +6 -0
  10. package/dist/catalog/read-only.d.ts +9 -0
  11. package/dist/catalog/sql-grammar.d.ts +53 -0
  12. package/dist/catalog/unconstrained-columns.d.ts +8 -0
  13. package/dist/client/types.d.ts +5 -1
  14. package/dist/client-entry.d.ts +1 -0
  15. package/dist/client-entry.js +1410 -152
  16. package/dist/client-entry.js.map +12 -8
  17. package/dist/index.core.d.ts +1 -0
  18. package/dist/index.js +1644 -226
  19. package/dist/index.js.map +19 -15
  20. package/dist/serve-entry.js +1100 -29
  21. package/dist/serve-entry.js.map +13 -10
  22. package/dist/worker-cf-entry.d.ts +2 -1
  23. package/dist/worker-cf-entry.js +1477 -54
  24. package/dist/worker-cf-entry.js.map +19 -15
  25. package/package.json +1 -1
  26. package/src/catalog/column-expressions.ts +85 -7
  27. package/src/catalog/column-metadata.ts +20 -2
  28. package/src/catalog/column-types.ts +50 -0
  29. package/src/catalog/composite.ts +10 -0
  30. package/src/catalog/constraints.ts +645 -0
  31. package/src/catalog/contents-codec.ts +3 -3
  32. package/src/catalog/descriptors.ts +19 -1
  33. package/src/catalog/indexes.ts +59 -0
  34. package/src/catalog/interface.ts +103 -1
  35. package/src/catalog/public-codecs.ts +36 -0
  36. package/src/catalog/read-only.ts +115 -30
  37. package/src/catalog/sql-grammar.ts +476 -0
  38. package/src/catalog/unconstrained-columns.ts +34 -8
  39. package/src/client/client.ts +6 -3
  40. package/src/client/types.ts +5 -1
  41. package/src/client-entry.ts +4 -0
  42. package/src/index.core.ts +2 -0
  43. package/src/protocol/handlers/catalog/admin.ts +19 -2
  44. package/src/protocol/handlers/catalog/table.ts +58 -11
  45. package/src/worker-cf-entry.ts +4 -0
package/dist/index.js CHANGED
@@ -8879,8 +8879,66 @@ var TableFunctionStatisticsParamsSchema = schema2([
8879
8879
  ]);
8880
8880
 
8881
8881
  // src/generated/vgi-protocol-types.ts
8882
+ function buildMacroOverload(init) {
8883
+ return {
8884
+ parameters: init.parameters,
8885
+ definition: init.definition,
8886
+ profile: init.profile,
8887
+ schema_path: init.schema_path,
8888
+ macro_type: init.macro_type,
8889
+ evaluation_context: init.evaluation_context
8890
+ };
8891
+ }
8892
+ var encodeMacroOverload = (v) => encodeASD(MacroOverloadSchema, v);
8893
+ var decodeMacroOverload = (b) => decodeASD(MacroOverloadSchema, b);
8894
+ function buildCatalogCapabilities(init) {
8895
+ return {
8896
+ read: init.read ?? [],
8897
+ ddl: init.ddl ?? [],
8898
+ write: init.write ?? [],
8899
+ transaction: init.transaction ?? []
8900
+ };
8901
+ }
8902
+ var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
8903
+ var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
8904
+ var encodeCatalogObjectRef = (v) => encodeASD(CatalogObjectRefSchema, v);
8905
+ var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
8882
8906
  var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
8883
8907
  var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
8908
+ var encodeForeignKeyDefinition = (v) => encodeASD(ForeignKeyDefinitionSchema, v);
8909
+ var decodeForeignKeyDefinition = (b) => decodeASD(ForeignKeyDefinitionSchema, b);
8910
+ function buildConstraintDefinition(init) {
8911
+ return {
8912
+ kind: init.kind,
8913
+ column_paths: init.column_paths ?? [],
8914
+ declared_name: init.declared_name ?? null,
8915
+ check_expression: init.check_expression ?? null,
8916
+ foreign_key: init.foreign_key ?? null
8917
+ };
8918
+ }
8919
+ var encodeConstraintDefinition = (v) => encodeASD(ConstraintDefinitionSchema, v);
8920
+ var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
8921
+ var encodeConstraintInfo = (v) => encodeASD(ConstraintInfoSchema, v);
8922
+ var decodeConstraintInfo = (b) => decodeASD(ConstraintInfoSchema, b);
8923
+ function buildConstraintChange(init) {
8924
+ return {
8925
+ operation: init.operation,
8926
+ ref: init.ref ?? null,
8927
+ definition: init.definition ?? null,
8928
+ enforcement: init.enforcement ?? null,
8929
+ validation: init.validation ?? null,
8930
+ cascade: init.cascade ?? null,
8931
+ declared_name: init.declared_name ?? null
8932
+ };
8933
+ }
8934
+ var encodeConstraintChange = (v) => encodeASD(ConstraintChangeSchema, v);
8935
+ var decodeConstraintChange = (b) => decodeASD(ConstraintChangeSchema, b);
8936
+ var encodeConstraintSnapshot = (v) => encodeASD(ConstraintSnapshotSchema, v);
8937
+ var decodeConstraintSnapshot = (b) => decodeASD(ConstraintSnapshotSchema, b);
8938
+ var encodeConstraintsApplyRequest = (v) => encodeASD(ConstraintsApplyRequestSchema, v);
8939
+ var decodeConstraintsApplyRequest = (b) => decodeASD(ConstraintsApplyRequestSchema, b);
8940
+ var encodeIndexDefinition = (v) => encodeASD(IndexDefinitionSchema, v);
8941
+ var decodeIndexDefinition = (b) => decodeASD(IndexDefinitionSchema, b);
8884
8942
  function buildCatalogAttachResult(init) {
8885
8943
  return {
8886
8944
  attach_opaque_data: init.attach_opaque_data,
@@ -8906,20 +8964,1298 @@ function buildCatalogAttachResult(init) {
8906
8964
  query_pushdown: init.query_pushdown ?? null
8907
8965
  };
8908
8966
  }
8909
- function buildCatalogContentsResponse(init) {
8910
- return {
8911
- catalog_version: init.catalog_version,
8912
- etag: init.etag ?? null,
8913
- not_modified: init.not_modified ?? false,
8914
- schemas: init.schemas ?? null,
8915
- tables: init.tables ?? null,
8916
- views: init.views ?? null,
8917
- functions: init.functions ?? null,
8918
- macros: init.macros ?? null,
8919
- indexes: init.indexes ?? null
8967
+ function buildCatalogContentsResponse(init) {
8968
+ return {
8969
+ catalog_version: init.catalog_version,
8970
+ etag: init.etag ?? null,
8971
+ not_modified: init.not_modified ?? false,
8972
+ schemas: init.schemas ?? null,
8973
+ tables: init.tables ?? null,
8974
+ views: init.views ?? null,
8975
+ functions: init.functions ?? null,
8976
+ macros: init.macros ?? null,
8977
+ indexes: init.indexes ?? null
8978
+ };
8979
+ }
8980
+ var decodeCatalogContentsResponse = (b) => decodeASD(CatalogContentsResultSchema, b);
8981
+
8982
+ // src/catalog/constraints.ts
8983
+ init_arrow();
8984
+
8985
+ // src/catalog/sql-grammar.ts
8986
+ class GrammarError extends Error {
8987
+ }
8988
+ var fail = (message) => {
8989
+ throw new GrammarError(message);
8990
+ };
8991
+ var RESERVED = new Set([
8992
+ "all",
8993
+ "and",
8994
+ "any",
8995
+ "array",
8996
+ "as",
8997
+ "asc",
8998
+ "between",
8999
+ "both",
9000
+ "case",
9001
+ "cast",
9002
+ "check",
9003
+ "collate",
9004
+ "column",
9005
+ "constraint",
9006
+ "create",
9007
+ "default",
9008
+ "desc",
9009
+ "distinct",
9010
+ "do",
9011
+ "else",
9012
+ "end",
9013
+ "except",
9014
+ "false",
9015
+ "fetch",
9016
+ "for",
9017
+ "foreign",
9018
+ "from",
9019
+ "glob",
9020
+ "grant",
9021
+ "group",
9022
+ "having",
9023
+ "ilike",
9024
+ "in",
9025
+ "intersect",
9026
+ "interval",
9027
+ "into",
9028
+ "is",
9029
+ "isnull",
9030
+ "like",
9031
+ "limit",
9032
+ "not",
9033
+ "notnull",
9034
+ "null",
9035
+ "offset",
9036
+ "on",
9037
+ "or",
9038
+ "order",
9039
+ "primary",
9040
+ "references",
9041
+ "returning",
9042
+ "select",
9043
+ "similar",
9044
+ "some",
9045
+ "table",
9046
+ "then",
9047
+ "to",
9048
+ "true",
9049
+ "try_cast",
9050
+ "union",
9051
+ "unique",
9052
+ "using",
9053
+ "when",
9054
+ "where",
9055
+ "window",
9056
+ "with"
9057
+ ]);
9058
+ var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
9059
+ function tokenize(sql) {
9060
+ const out = [];
9061
+ let i = 0;
9062
+ while (i < sql.length) {
9063
+ const c = sql[i];
9064
+ if (/\s/.test(c)) {
9065
+ i++;
9066
+ continue;
9067
+ }
9068
+ if (sql.startsWith("--", i)) {
9069
+ while (i < sql.length && sql[i] !== `
9070
+ `)
9071
+ i++;
9072
+ continue;
9073
+ }
9074
+ if (sql.startsWith("/*", i)) {
9075
+ const close = sql.indexOf("*/", i + 2);
9076
+ if (close < 0)
9077
+ fail("unterminated comment");
9078
+ i = close + 2;
9079
+ continue;
9080
+ }
9081
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
9082
+ const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
9083
+ if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
9084
+ fail("unsupported numeric literal");
9085
+ out.push({ t: "num", v: m[0] });
9086
+ i += m[0].length;
9087
+ continue;
9088
+ }
9089
+ if (c === "'" || c === '"') {
9090
+ let j = i + 1, text = "";
9091
+ for (;; ) {
9092
+ if (j >= sql.length)
9093
+ fail("unterminated quoted text");
9094
+ if (sql[j] === c) {
9095
+ if (sql[j + 1] === c) {
9096
+ text += c;
9097
+ j += 2;
9098
+ continue;
9099
+ }
9100
+ break;
9101
+ }
9102
+ text += sql[j++];
9103
+ }
9104
+ out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
9105
+ i = j + 1;
9106
+ continue;
9107
+ }
9108
+ if (/[A-Za-z_\u0080-￿]/.test(c)) {
9109
+ const m = /^[A-Za-z_\u0080-￿][A-Za-z0-9_$\u0080-￿]*/.exec(sql.slice(i));
9110
+ out.push({ t: "ident", v: m[0], quoted: false });
9111
+ i += m[0].length;
9112
+ continue;
9113
+ }
9114
+ const op = OPERATORS.find((o) => sql.startsWith(o, i));
9115
+ if (!op)
9116
+ fail(`unsupported character '${c}'`);
9117
+ out.push({ t: "op", v: op });
9118
+ i += op.length;
9119
+ }
9120
+ out.push({ t: "end" });
9121
+ return out;
9122
+ }
9123
+ var CAST_TYPES = {
9124
+ boolean: "BOOLEAN",
9125
+ bool: "BOOLEAN",
9126
+ logical: "BOOLEAN",
9127
+ tinyint: "TINYINT",
9128
+ int1: "TINYINT",
9129
+ smallint: "SMALLINT",
9130
+ int2: "SMALLINT",
9131
+ short: "SMALLINT",
9132
+ integer: "INTEGER",
9133
+ int: "INTEGER",
9134
+ int4: "INTEGER",
9135
+ signed: "INTEGER",
9136
+ bigint: "BIGINT",
9137
+ int8: "BIGINT",
9138
+ long: "BIGINT",
9139
+ float: "FLOAT",
9140
+ real: "FLOAT",
9141
+ float4: "FLOAT",
9142
+ double: "DOUBLE",
9143
+ float8: "DOUBLE",
9144
+ decimal: "DECIMAL",
9145
+ numeric: "DECIMAL",
9146
+ varchar: "VARCHAR",
9147
+ text: "VARCHAR",
9148
+ string: "VARCHAR",
9149
+ char: "VARCHAR",
9150
+ bpchar: "VARCHAR",
9151
+ nvarchar: "VARCHAR",
9152
+ character: "VARCHAR"
9153
+ };
9154
+ var INT64_MAX = (1n << 63n) - 1n;
9155
+ function literalNumber(text, negative) {
9156
+ if (/^[0-9]+$/.test(text)) {
9157
+ const value = BigInt(text) * (negative ? -1n : 1n);
9158
+ const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
9159
+ return { kind: "constant", type };
9160
+ }
9161
+ if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
9162
+ return { kind: "constant", type: "DECIMAL" };
9163
+ return { kind: "constant", type: "DOUBLE" };
9164
+ }
9165
+
9166
+ class Parser {
9167
+ tokens;
9168
+ pos = 0;
9169
+ constructor(tokens) {
9170
+ this.tokens = tokens;
9171
+ }
9172
+ peek(offset = 0) {
9173
+ return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
9174
+ }
9175
+ next() {
9176
+ return this.tokens[this.pos++];
9177
+ }
9178
+ isOp(v, offset = 0) {
9179
+ const t = this.peek(offset);
9180
+ return t.t === "op" && t.v === v;
9181
+ }
9182
+ isWord(word, offset = 0) {
9183
+ const t = this.peek(offset);
9184
+ return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
9185
+ }
9186
+ expectOp(v) {
9187
+ if (!this.isOp(v))
9188
+ fail(`expected '${v}'`);
9189
+ this.pos++;
9190
+ }
9191
+ parseAll() {
9192
+ const node = this.expr();
9193
+ if (this.peek().t !== "end")
9194
+ fail("unexpected text after the expression");
9195
+ return node;
9196
+ }
9197
+ expr() {
9198
+ return this.or();
9199
+ }
9200
+ or() {
9201
+ let left = this.and();
9202
+ while (this.isWord("or")) {
9203
+ this.pos++;
9204
+ left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
9205
+ }
9206
+ return left;
9207
+ }
9208
+ and() {
9209
+ let left = this.not();
9210
+ while (this.isWord("and")) {
9211
+ this.pos++;
9212
+ left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
9213
+ }
9214
+ return left;
9215
+ }
9216
+ not() {
9217
+ if (this.isWord("not")) {
9218
+ this.pos++;
9219
+ return { kind: "operator", op: "NOT", children: [this.not()] };
9220
+ }
9221
+ return this.is();
9222
+ }
9223
+ is() {
9224
+ let left = this.comparison();
9225
+ for (;; ) {
9226
+ if (this.isWord("isnull")) {
9227
+ this.pos++;
9228
+ left = { kind: "operator", op: "IS_NULL", children: [left] };
9229
+ continue;
9230
+ }
9231
+ if (this.isWord("notnull")) {
9232
+ this.pos++;
9233
+ left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
9234
+ continue;
9235
+ }
9236
+ if (this.isWord("is")) {
9237
+ this.pos++;
9238
+ const negated = this.isWord("not");
9239
+ if (negated)
9240
+ this.pos++;
9241
+ if (!this.isWord("null"))
9242
+ fail("only IS [NOT] NULL is supported");
9243
+ this.pos++;
9244
+ left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
9245
+ continue;
9246
+ }
9247
+ return left;
9248
+ }
9249
+ }
9250
+ comparison() {
9251
+ const left = this.otherOp();
9252
+ const t = this.peek();
9253
+ if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
9254
+ this.pos++;
9255
+ const right = this.otherOp();
9256
+ const next = this.peek();
9257
+ if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
9258
+ fail("chained comparisons are unsupported");
9259
+ return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
9260
+ }
9261
+ for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
9262
+ if (this.isWord(word))
9263
+ fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
9264
+ }
9265
+ return left;
9266
+ }
9267
+ otherOp() {
9268
+ let left = this.additive();
9269
+ for (;; ) {
9270
+ const t = this.peek();
9271
+ if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
9272
+ this.pos++;
9273
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
9274
+ continue;
9275
+ }
9276
+ return left;
9277
+ }
9278
+ }
9279
+ additive() {
9280
+ let left = this.multiplicative();
9281
+ for (;; ) {
9282
+ const t = this.peek();
9283
+ if (t.t === "op" && (t.v === "+" || t.v === "-")) {
9284
+ this.pos++;
9285
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
9286
+ continue;
9287
+ }
9288
+ return left;
9289
+ }
9290
+ }
9291
+ multiplicative() {
9292
+ let left = this.power();
9293
+ for (;; ) {
9294
+ const t = this.peek();
9295
+ if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
9296
+ this.pos++;
9297
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
9298
+ continue;
9299
+ }
9300
+ return left;
9301
+ }
9302
+ }
9303
+ power() {
9304
+ let left = this.unary();
9305
+ while (this.isOp("^")) {
9306
+ this.pos++;
9307
+ left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
9308
+ }
9309
+ return left;
9310
+ }
9311
+ unary() {
9312
+ if (this.isOp("-") || this.isOp("+")) {
9313
+ const sign = this.next().v;
9314
+ const operand = this.unary();
9315
+ if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
9316
+ const folded = literalNumber(operand.text, !operand.negative);
9317
+ return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
9318
+ }
9319
+ return { kind: "function", name: sign, qualified: false, children: [operand] };
9320
+ }
9321
+ return this.postfix();
9322
+ }
9323
+ postfix() {
9324
+ let node = this.primary();
9325
+ for (;; ) {
9326
+ if (this.isOp("::")) {
9327
+ this.pos++;
9328
+ node = { kind: "cast", ...this.typeName(), child: node };
9329
+ continue;
9330
+ }
9331
+ if (this.isOp("["))
9332
+ fail("subscripts are unsupported");
9333
+ return node;
9334
+ }
9335
+ }
9336
+ typeName() {
9337
+ const t = this.next();
9338
+ if (t.t !== "ident")
9339
+ fail("expected a type name");
9340
+ const first = t.v.toLowerCase();
9341
+ let qualified = false;
9342
+ while (this.isOp(".")) {
9343
+ this.pos++;
9344
+ if (this.next().t !== "ident")
9345
+ fail("expected a type name");
9346
+ qualified = true;
9347
+ }
9348
+ let name = first;
9349
+ if (first === "double" && this.isWord("precision")) {
9350
+ this.pos++;
9351
+ name = "double";
9352
+ }
9353
+ if (first === "character" && this.isWord("varying")) {
9354
+ this.pos++;
9355
+ name = "varchar";
9356
+ }
9357
+ let params = [];
9358
+ if (this.isOp("(")) {
9359
+ this.pos++;
9360
+ for (;; ) {
9361
+ const p = this.next();
9362
+ if (p.t !== "num")
9363
+ fail("unsupported type parameter");
9364
+ params.push(p.v);
9365
+ if (this.isOp(",")) {
9366
+ this.pos++;
9367
+ continue;
9368
+ }
9369
+ break;
9370
+ }
9371
+ this.expectOp(")");
9372
+ }
9373
+ if (this.isOp("["))
9374
+ fail("array types are unsupported");
9375
+ let type = CAST_TYPES[name] ?? null;
9376
+ if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
9377
+ type = "DOUBLE";
9378
+ return { type, qualified };
9379
+ }
9380
+ primary() {
9381
+ const t = this.next();
9382
+ if (t.t === "num")
9383
+ return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
9384
+ if (t.t === "str") {
9385
+ if (this.peek().t === "str")
9386
+ fail("adjacent string literals are unsupported");
9387
+ return { kind: "constant", type: "VARCHAR" };
9388
+ }
9389
+ if (t.t === "op") {
9390
+ if (t.v === "(") {
9391
+ const inner = this.expr();
9392
+ if (this.isOp(","))
9393
+ fail("row constructors are unsupported");
9394
+ this.expectOp(")");
9395
+ return inner;
9396
+ }
9397
+ return fail(`unexpected '${t.v}'`);
9398
+ }
9399
+ if (t.t === "end")
9400
+ return fail("expected an expression");
9401
+ const word = t.v.toLowerCase();
9402
+ if (!t.quoted) {
9403
+ if (word === "null")
9404
+ return { kind: "constant", type: "NULL" };
9405
+ if (word === "true" || word === "false")
9406
+ return { kind: "constant", type: "BOOLEAN" };
9407
+ if (word === "cast" && this.isOp("(")) {
9408
+ this.pos++;
9409
+ const child = this.expr();
9410
+ if (!this.isWord("as"))
9411
+ fail("expected AS in CAST");
9412
+ this.pos++;
9413
+ const target = this.typeName();
9414
+ this.expectOp(")");
9415
+ return { kind: "cast", ...target, child };
9416
+ }
9417
+ if (word === "case")
9418
+ fail("CASE is outside the supported scalar grammar");
9419
+ if (RESERVED.has(word))
9420
+ fail(`unexpected keyword ${t.v.toUpperCase()}`);
9421
+ }
9422
+ const names = [t.v];
9423
+ while (this.isOp(".")) {
9424
+ this.pos++;
9425
+ const part = this.next();
9426
+ if (part.t !== "ident")
9427
+ fail("unsupported qualified name");
9428
+ names.push(part.v);
9429
+ }
9430
+ if (this.isOp("(")) {
9431
+ this.pos++;
9432
+ const children = [];
9433
+ if (this.isWord("distinct"))
9434
+ fail("DISTINCT function arguments are unsupported");
9435
+ if (!this.isOp(")")) {
9436
+ for (;; ) {
9437
+ if (this.isOp("*"))
9438
+ fail("star arguments are unsupported");
9439
+ if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
9440
+ fail("named scalar arguments are unsupported");
9441
+ children.push(this.expr());
9442
+ if (this.isOp(",")) {
9443
+ this.pos++;
9444
+ continue;
9445
+ }
9446
+ break;
9447
+ }
9448
+ }
9449
+ if (this.isWord("order"))
9450
+ fail("ordered function arguments are unsupported");
9451
+ this.expectOp(")");
9452
+ if (this.isWord("filter") || this.isWord("over"))
9453
+ fail("aggregate and window functions are unsupported");
9454
+ if (names.length === 1 && !t.quoted && word === "coalesce")
9455
+ return { kind: "operator", op: "COALESCE", children };
9456
+ return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
9457
+ }
9458
+ if (this.peek().t === "str")
9459
+ fail("typed literals are unsupported");
9460
+ return { kind: "column", names };
9461
+ }
9462
+ }
9463
+ function parseScalarSql(sql) {
9464
+ if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
9465
+ fail("invalid SQL size or text");
9466
+ return new Parser(tokenize(sql)).parseAll();
9467
+ }
9468
+ var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
9469
+ var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
9470
+ var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
9471
+ function validateColumnExpressionSql(sql, options) {
9472
+ const { usingColumns, generated } = options;
9473
+ const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
9474
+ const columns = [];
9475
+ let nodes = 0;
9476
+ const visit = (node, depth) => {
9477
+ if (depth > 64 || ++nodes > 4096)
9478
+ fail("scalar expression is too complex");
9479
+ switch (node.kind) {
9480
+ case "constant":
9481
+ if (!primitive.has(node.type))
9482
+ fail(`unsupported scalar literal type ${node.type}`);
9483
+ return;
9484
+ case "column":
9485
+ if (!usingColumns || node.names.length !== 1)
9486
+ fail("column references are unsupported in this scope");
9487
+ columns.push(node.names[0]);
9488
+ return;
9489
+ case "cast":
9490
+ if (node.qualified)
9491
+ fail("qualified scalar cast types are unsupported");
9492
+ if (node.type === null || !primitive.has(node.type))
9493
+ fail("unsupported scalar cast");
9494
+ visit(node.child, depth + 1);
9495
+ return;
9496
+ case "comparison":
9497
+ visit(node.left, depth + 1);
9498
+ visit(node.right, depth + 1);
9499
+ return;
9500
+ case "conjunction":
9501
+ case "operator":
9502
+ node.children.forEach((c) => visit(c, depth + 1));
9503
+ return;
9504
+ case "function": {
9505
+ const lower = node.name.toLowerCase();
9506
+ const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
9507
+ if (!ok)
9508
+ fail(`unsupported scalar function '${node.name}'`);
9509
+ node.children.forEach((c) => visit(c, depth + 1));
9510
+ return;
9511
+ }
9512
+ }
9513
+ };
9514
+ try {
9515
+ visit(parseScalarSql(sql), 0);
9516
+ } catch (error) {
9517
+ if (error instanceof GrammarError)
9518
+ throw error;
9519
+ throw new GrammarError(String(error?.message ?? error));
9520
+ }
9521
+ return columns;
9522
+ }
9523
+ function validateNumericCheckSql(sql, resolveColumn) {
9524
+ const node = parseScalarSql(sql);
9525
+ if (node.kind !== "comparison")
9526
+ fail("native CHECK read supports only Boolean numeric comparisons");
9527
+ const comparison = node;
9528
+ for (const operand of [comparison.left, comparison.right]) {
9529
+ if (operand.kind === "constant") {
9530
+ if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
9531
+ fail("CHECK requires numeric operands");
9532
+ continue;
9533
+ }
9534
+ if (operand.kind !== "column")
9535
+ fail("native CHECK read supports only numeric column/constant comparisons");
9536
+ const column = operand;
9537
+ if (column.names.length !== 1)
9538
+ fail("CHECK requires unqualified column references");
9539
+ resolveColumn(column.names[0]);
9540
+ }
9541
+ }
9542
+
9543
+ // src/catalog/column-types.ts
9544
+ init_arrow();
9545
+ function isRowIdField(field) {
9546
+ return field.metadata?.has("is_row_id") ?? false;
9547
+ }
9548
+ function hasLogicalType(field) {
9549
+ for (const key of field.metadata?.keys() ?? [])
9550
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
9551
+ return true;
9552
+ return false;
9553
+ }
9554
+ function ordinaryStructChildren(field) {
9555
+ if (!isStruct(field.type) || hasLogicalType(field))
9556
+ return null;
9557
+ return field.type.children;
9558
+ }
9559
+ function isGeneratedField(field) {
9560
+ const m = field.metadata;
9561
+ return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
9562
+ }
9563
+ function duckdbPrimitive(field) {
9564
+ if (hasLogicalType(field))
9565
+ return null;
9566
+ const t = field.type;
9567
+ switch (t.typeId) {
9568
+ case TypeId.Bool:
9569
+ return "BOOLEAN";
9570
+ case TypeId.Utf8:
9571
+ return "VARCHAR";
9572
+ case TypeId.Int: {
9573
+ if (!(t.isSigned ?? t.signed ?? true))
9574
+ return null;
9575
+ return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
9576
+ }
9577
+ case TypeId.Float:
9578
+ return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
9579
+ case TypeId.Decimal:
9580
+ return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
9581
+ default:
9582
+ return null;
9583
+ }
9584
+ }
9585
+
9586
+ // src/catalog/column-expressions.ts
9587
+ init_arrow();
9588
+ var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
9589
+ var GENERATION_KEY = "vgi.column.generation.v1";
9590
+ var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
9591
+ var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
9592
+ var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
9593
+ var PROFILE = "vgi.expression.duckdb.scalar.v1";
9594
+ var MAX_BYTES = 8 * 1024 * 1024;
9595
+ var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
9596
+ function text(value, maximum) {
9597
+ if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > maximum)
9598
+ throw new Error("invalid generated expression text");
9599
+ for (let i = 0;i < value.length; i++) {
9600
+ const c = value.charCodeAt(i);
9601
+ if (c >= 55296 && c <= 56319) {
9602
+ const d = value.charCodeAt(++i);
9603
+ if (!(d >= 56320 && d <= 57343))
9604
+ throw new Error("invalid generated expression Unicode");
9605
+ } else if (c >= 56320 && c <= 57343)
9606
+ throw new Error("invalid generated expression Unicode");
9607
+ }
9608
+ }
9609
+ function expression(value, owner) {
9610
+ text(value.sql, 1024 * 1024);
9611
+ if (!value.sql.trim() || value.profile !== PROFILE)
9612
+ throw new Error("unsupported generated expression profile or empty SQL");
9613
+ if (!Array.isArray(value.schema_path) || value.schema_path.length > 32)
9614
+ throw new Error("invalid generated expression owner");
9615
+ value.schema_path.forEach((part) => text(part, 4096));
9616
+ if (JSON.stringify(value.schema_path) !== JSON.stringify(owner))
9617
+ throw new Error("generated expression owner differs from table schema");
9618
+ const context = value.evaluation_context;
9619
+ if (!context)
9620
+ throw new Error("generated expression requires explicit evaluation context");
9621
+ text(context.timezone, 256);
9622
+ text(context.collation, 256);
9623
+ if (!["asc", "desc"].includes(context.default_order) || ![
9624
+ "nulls_first",
9625
+ "nulls_last",
9626
+ "nulls_first_on_asc_last_on_desc",
9627
+ "nulls_last_on_asc_first_on_desc"
9628
+ ].includes(context.default_null_order) || typeof context.preserve_insertion_order !== "boolean")
9629
+ throw new Error("invalid generated expression evaluation context");
9630
+ }
9631
+ function envelope(bytes) {
9632
+ if (!bytes.length || bytes.length > MAX_BYTES)
9633
+ throw new Error("invalid generated expression size");
9634
+ const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9635
+ const kinds = [];
9636
+ const textBuffers = [];
9637
+ let offset = 0;
9638
+ while (offset < bytes.length) {
9639
+ const prefix = data.getInt32(offset, true) === -1 ? 8 : 4;
9640
+ const length = data.getInt32(offset + prefix - 4, true);
9641
+ offset += prefix;
9642
+ if (!length) {
9643
+ if (offset !== bytes.length || kinds.join(",") !== "1,3")
9644
+ throw new Error("SqlExpression requires exactly one complete IPC batch");
9645
+ return textBuffers;
9646
+ }
9647
+ if (length < 0 || offset + length > bytes.length)
9648
+ throw new Error("invalid expression IPC length");
9649
+ const p = offset + data.getUint32(offset, true), v = p - data.getInt32(p, true);
9650
+ const slot = (id) => 4 + id * 2 < data.getUint16(v, true) ? data.getUint16(v + 4 + id * 2, true) : 0;
9651
+ const kind = slot(1), body = slot(3);
9652
+ if (!kind)
9653
+ throw new Error("invalid expression IPC message");
9654
+ kinds.push(data.getUint8(p + kind));
9655
+ const bodyLength = body ? Number(data.getBigInt64(p + body, true)) : 0;
9656
+ if (bodyLength < 0 || bodyLength > bytes.length - offset - length)
9657
+ throw new Error("invalid expression IPC body");
9658
+ if (data.getUint8(p + kind) === 3) {
9659
+ const headerSlot = slot(2);
9660
+ const record = p + headerSlot + data.getUint32(p + headerSlot, true);
9661
+ const table = record - data.getInt32(record, true);
9662
+ const recordSlot = (id) => 4 + id * 2 < data.getUint16(table, true) ? data.getUint16(table + 4 + id * 2, true) : 0;
9663
+ if (recordSlot(3))
9664
+ throw new Error("compressed expression IPC is unsupported");
9665
+ const bufferSlot = recordSlot(2);
9666
+ const buffers = record + bufferSlot + data.getUint32(record + bufferSlot, true);
9667
+ if (data.getUint32(buffers, true) !== 26)
9668
+ throw new Error("invalid SqlExpression buffer layout");
9669
+ for (const index of [2, 5, 10, 14, 17, 20, 23]) {
9670
+ const buffer = buffers + 4 + index * 16;
9671
+ const start = Number(data.getBigInt64(buffer, true));
9672
+ const size = Number(data.getBigInt64(buffer + 8, true));
9673
+ if (start < 0 || size < 0 || start + size > bodyLength)
9674
+ throw new Error("invalid expression string buffer");
9675
+ textBuffers.push(bytes.subarray(offset + length + start, offset + length + start + size));
9676
+ }
9677
+ }
9678
+ offset += length + bodyLength;
9679
+ }
9680
+ throw new Error("expression IPC lacks end marker");
9681
+ }
9682
+ function shape(schema) {
9683
+ const field = (f) => [
9684
+ f.name,
9685
+ f.nullable,
9686
+ String(f.type),
9687
+ (f.type.children ?? []).map(field)
9688
+ ];
9689
+ return JSON.stringify(schema.fields.map(field));
9690
+ }
9691
+ function validateEncoded(encoded, owner) {
9692
+ if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
9693
+ throw new Error("invalid generated expression size");
9694
+ const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
9695
+ if (base64(bytes) !== encoded)
9696
+ throw new Error("generated expression requires canonical base64");
9697
+ const textBuffers = envelope(bytes);
9698
+ const batch = deserializeBatch(bytes);
9699
+ if (batch.numRows !== 1 || shape(batch.schema) !== shape(SqlExpressionSchema))
9700
+ throw new Error("invalid SqlExpression record schema");
9701
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
9702
+ textBuffers.forEach((buffer) => utf8.decode(buffer));
9703
+ const value = decodeSqlExpression(bytes);
9704
+ expression(value, owner);
9705
+ return value.sql;
9706
+ }
9707
+ function generatedExpressionMetadata(sql, owner) {
9708
+ try {
9709
+ validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
9710
+ } catch (error) {
9711
+ throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
9712
+ }
9713
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
9714
+ }
9715
+ function defaultExpressionMetadata(sql, owner) {
9716
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
9717
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
9718
+ }
9719
+ function sqlExpression(sql, schemaPath) {
9720
+ const owner = [...schemaPath];
9721
+ const value = {
9722
+ sql,
9723
+ profile: PROFILE,
9724
+ schema_path: [...owner],
9725
+ evaluation_context: {
9726
+ timezone: "UTC",
9727
+ collation: "binary",
9728
+ default_order: "asc",
9729
+ default_null_order: "nulls_last",
9730
+ preserve_insertion_order: true
9731
+ }
9732
+ };
9733
+ expression(value, owner);
9734
+ return value;
9735
+ }
9736
+ function validateColumnExpressions(schema, owner, allowGenerated = true) {
9737
+ const type = (t) => {
9738
+ for (const f of t?.children ?? t?.fields ?? [])
9739
+ field(f);
9740
+ if (t?.dictionary)
9741
+ type(t.dictionary);
9742
+ };
9743
+ const topLevel = new Map;
9744
+ for (const f of schema.fields) {
9745
+ const key = String(f.name).toLowerCase();
9746
+ topLevel.set(key, [...topLevel.get(key) ?? [], f]);
9747
+ }
9748
+ const field = (f, top = false) => {
9749
+ const metadata = f.metadata ?? new Map;
9750
+ for (const key of metadata.keys()) {
9751
+ if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
9752
+ throw new Error("unknown generated metadata version");
9753
+ }
9754
+ const where = `column ${f.name}`;
9755
+ if (metadata.has("generated_expression"))
9756
+ throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
9757
+ if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
9758
+ if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
9759
+ throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
9760
+ const type = duckdbPrimitive(f);
9761
+ if (!type || !DEFAULT_TYPES.has(type))
9762
+ throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
9763
+ const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
9764
+ try {
9765
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
9766
+ } catch (error) {
9767
+ throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
9768
+ }
9769
+ }
9770
+ if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
9771
+ throw new Error("generated expression and category must occur together");
9772
+ if (metadata.has(GENERATED_EXPRESSION_KEY)) {
9773
+ if (metadata.get(GENERATION_KEY) !== "virtual")
9774
+ throw new Error("only VIRTUAL generated columns are supported");
9775
+ if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
9776
+ throw new Error("generated column cannot have a default");
9777
+ const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
9778
+ if (!allowGenerated)
9779
+ throw new Error("generated columns unsupported by this catalog");
9780
+ if (!f.nullable)
9781
+ throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
9782
+ const type = duckdbPrimitive(f);
9783
+ if (!type || !GENERATED_TYPES.has(type))
9784
+ throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
9785
+ let references;
9786
+ try {
9787
+ references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
9788
+ } catch (error) {
9789
+ throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
9790
+ }
9791
+ if (top) {
9792
+ for (const name of references) {
9793
+ const matches = topLevel.get(name.toLowerCase()) ?? [];
9794
+ if (matches.length !== 1)
9795
+ throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
9796
+ const operand = duckdbPrimitive(matches[0]);
9797
+ if (!operand || !GENERATED_TYPES.has(operand))
9798
+ throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
9799
+ }
9800
+ }
9801
+ }
9802
+ type(f.type);
9803
+ };
9804
+ schema.fields.forEach((f) => field(f, true));
9805
+ }
9806
+ function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
9807
+ validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
9808
+ }
9809
+
9810
+ // src/catalog/constraints.ts
9811
+ var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
9812
+ var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
9813
+ var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
9814
+ var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
9815
+ var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
9816
+ var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
9817
+ var CHECK_CONTEXT = {
9818
+ timezone: "UTC",
9819
+ collation: "binary",
9820
+ default_order: "asc",
9821
+ default_null_order: "nulls_last",
9822
+ preserve_insertion_order: true
9823
+ };
9824
+ function identifier(value, what) {
9825
+ if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
9826
+ throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
9827
+ }
9828
+ function objectRef(kind, schemaPath, name, ownerTable) {
9829
+ return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
9830
+ }
9831
+ function checkPaths(paths, what, topLevelOnly) {
9832
+ if (paths.length > 1024)
9833
+ throw new Error(`${what}: too many column paths`);
9834
+ const seen = new Set;
9835
+ for (const path of paths) {
9836
+ if (path.length === 0 || path.length > 64)
9837
+ throw new Error(`${what}: column path must have 1..64 components`);
9838
+ if (topLevelOnly && path.length !== 1)
9839
+ throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
9840
+ path.forEach((part) => identifier(part, `${what}: column path component`));
9841
+ const key = JSON.stringify(path);
9842
+ if (seen.has(key))
9843
+ throw new Error(`${what}: duplicate column path ${path.join(".")}`);
9844
+ seen.add(key);
9845
+ }
9846
+ }
9847
+ function constraintRecord(spec) {
9848
+ const what = `constraint '${spec.id}' on '${spec.table}'`;
9849
+ if (!spec.id || spec.id.includes("\x00"))
9850
+ throw new Error("constraint id must be nonempty without NUL");
9851
+ identifier(spec.table, "table");
9852
+ if (spec.schemaPath.length !== 1)
9853
+ throw new Error(`${what}: DuckDB reads only one-component schema paths`);
9854
+ identifier(spec.schemaPath[0], "schema");
9855
+ if (spec.enforcement !== "ENFORCED" || spec.validation !== "ALL_ROWS")
9856
+ throw new Error(`${what} is ${spec.enforcement}/${spec.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
9857
+ if (spec.declaredName !== undefined)
9858
+ identifier(spec.declaredName, `${what}: declaredName`);
9859
+ if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
9860
+ throw new Error("checkSql is required for CHECK and only CHECK");
9861
+ if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
9862
+ throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
9863
+ if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
9864
+ throw new Error("NOT_NULL requires exactly one column path");
9865
+ if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
9866
+ throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
9867
+ checkPaths(spec.columns, what, spec.kind !== "NOT_NULL");
9868
+ if (spec.checkSql !== undefined) {
9869
+ try {
9870
+ validateNumericCheckSql(spec.checkSql, () => {});
9871
+ } catch (error) {
9872
+ throw new Error(`${what}: ${error.message} (CHECK SQL: ${spec.checkSql})`);
9873
+ }
9874
+ }
9875
+ const ref = spec.references;
9876
+ if (ref) {
9877
+ if (ref.columns.length !== spec.columns.length)
9878
+ throw new Error("foreign key local and referenced arity must match");
9879
+ if (JSON.stringify(ref.schemaPath) !== JSON.stringify(spec.schemaPath))
9880
+ throw new Error(`${what}: DuckDB reads only foreign keys to a table in the same schema`);
9881
+ identifier(ref.table, `${what}: referenced table`);
9882
+ identifier(ref.constraintId, `${what}: referenced constraintId`);
9883
+ checkPaths(ref.columns, `${what} (referenced)`, true);
9884
+ }
9885
+ const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
9886
+ sql: spec.checkSql,
9887
+ profile: ROW_SCALAR_EXPRESSION,
9888
+ schema_path: spec.schemaPath,
9889
+ evaluation_context: CHECK_CONTEXT
9890
+ });
9891
+ const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
9892
+ referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
9893
+ referenced_column_paths: ref.columns,
9894
+ match: "SIMPLE",
9895
+ on_update: "NO_ACTION",
9896
+ on_delete: "NO_ACTION"
9897
+ });
9898
+ return encodeASD(ConstraintInfoSchema, {
9899
+ ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
9900
+ definition: encodeASD(ConstraintDefinitionSchema, {
9901
+ kind: spec.kind,
9902
+ column_paths: spec.columns,
9903
+ declared_name: spec.declaredName ?? null,
9904
+ check_expression: check,
9905
+ foreign_key: foreign
9906
+ }),
9907
+ enforcement: spec.enforcement,
9908
+ validation: spec.validation,
9909
+ referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
9910
+ });
9911
+ }
9912
+ var KNOWN = {
9913
+ read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
9914
+ ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
9915
+ write: new Set([CONSTRAINT_ENFORCE]),
9916
+ transaction: new Set([TRANSACTION_DDL])
9917
+ };
9918
+ var REQUIRES = {
9919
+ [ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
9920
+ [CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
9921
+ [CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
9922
+ [CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
9923
+ "vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
9924
+ "vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
9925
+ };
9926
+ var CATEGORIES = ["read", "ddl", "write", "transaction"];
9927
+ function catalogCapabilities(init = {}) {
9928
+ return {
9929
+ read: [...new Set(init.read ?? [])].sort(),
9930
+ ddl: [...new Set(init.ddl ?? [])].sort(),
9931
+ write: [...new Set(init.write ?? [])].sort(),
9932
+ transaction: [...new Set(init.transaction ?? [])].sort()
9933
+ };
9934
+ }
9935
+ function constraintCapabilities(options = {}) {
9936
+ const enforce = options.enforce || options.create;
9937
+ return catalogCapabilities({
9938
+ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION],
9939
+ ddl: [...options.create ? [CONSTRAINT_CREATE] : [], ...options.mutate ? [CONSTRAINT_MUTATE] : []],
9940
+ write: enforce ? [CONSTRAINT_ENFORCE] : [],
9941
+ transaction: options.transactionDdl ? [TRANSACTION_DDL] : []
9942
+ });
9943
+ }
9944
+ function offeredCatalog(clientCapabilities) {
9945
+ if (clientCapabilities == null)
9946
+ return null;
9947
+ const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
9948
+ return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
9949
+ }
9950
+ function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
9951
+ const offered = offeredCatalog(clientCapabilities);
9952
+ if (offered == null)
9953
+ return catalogCapabilities();
9954
+ const chosen = new Set;
9955
+ for (const category of CATEGORIES)
9956
+ for (const p of available[category] ?? [])
9957
+ if (offered[category]?.includes(p))
9958
+ chosen.add(p);
9959
+ if (!supportsTransactions)
9960
+ chosen.delete(TRANSACTION_DDL);
9961
+ for (let changed = true;changed; ) {
9962
+ changed = false;
9963
+ for (const p of [...chosen])
9964
+ if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
9965
+ chosen.delete(p);
9966
+ changed = true;
9967
+ }
9968
+ }
9969
+ const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
9970
+ return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
9971
+ }
9972
+ function selectReadProfiles(available, clientCapabilities) {
9973
+ return selectCatalogCapabilities(catalogCapabilities({ read: [...available] }), clientCapabilities).read;
9974
+ }
9975
+ function defaultClientCapabilities(engine = "vgi-typescript") {
9976
+ return {
9977
+ engine,
9978
+ native_formats: [],
9979
+ catalogs: [],
9980
+ can_stream: true,
9981
+ filter_encodings: [],
9982
+ catalog: encodeCatalogCapabilities(catalogCapabilities({ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] })),
9983
+ query_pushdown: null
9984
+ };
9985
+ }
9986
+ function capabilitiesEmpty(caps) {
9987
+ return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
9988
+ }
9989
+ function readConstraintRecord(bytes) {
9990
+ const info = decodeASD(ConstraintInfoSchema, bytes);
9991
+ const ref = decodeASD(CatalogObjectRefSchema, info.ref);
9992
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
9993
+ const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
9994
+ const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
9995
+ const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
9996
+ return {
9997
+ schemaPath: [...ref.schema_path],
9998
+ table: ref.owner_table ?? "",
9999
+ id: ref.name,
10000
+ kind: def.kind,
10001
+ columns: [...def.column_paths].map((p) => [...p]),
10002
+ enforcement: info.enforcement,
10003
+ validation: info.validation,
10004
+ declaredName: def.declared_name ?? null,
10005
+ checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
10006
+ references: fk == null || target == null ? null : {
10007
+ schemaPath: [...target.schema_path],
10008
+ table: target.name,
10009
+ columns: [...fk.referenced_column_paths].map((p) => [...p]),
10010
+ constraintId: targetKey?.name ?? null,
10011
+ constraintTable: targetKey?.owner_table ?? null,
10012
+ constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
10013
+ match: fk.match,
10014
+ onUpdate: fk.on_update,
10015
+ onDelete: fk.on_delete
10016
+ }
10017
+ };
10018
+ }
10019
+ function fieldsByExactName(fields, name) {
10020
+ const out = [];
10021
+ fields.forEach((f, i) => {
10022
+ if (f.name === name)
10023
+ out.push(i);
10024
+ });
10025
+ return out;
10026
+ }
10027
+ function validateTableConstraints(table, schemaPath, fields, constraints) {
10028
+ if (constraints.length > 1024)
10029
+ throw new Error(`Table '${table}': too many constraints (at most 1024)`);
10030
+ const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
10031
+ if (rowIds.length > 1)
10032
+ throw new Error(`Table '${table}': at most one column may carry is_row_id`);
10033
+ const rowId = rowIds[0] ?? -1;
10034
+ const records = [];
10035
+ const required = new Set;
10036
+ const ids = new Set;
10037
+ const labels = new Set;
10038
+ let primaryKeys = 0;
10039
+ for (const bytes of constraints) {
10040
+ let record;
10041
+ try {
10042
+ record = readConstraintRecord(bytes);
10043
+ } catch (error) {
10044
+ throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
10045
+ }
10046
+ const where = `Table '${table}': constraint '${record.id}'`;
10047
+ const fail = (message) => {
10048
+ throw new Error(`${where}: ${message}`);
10049
+ };
10050
+ if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
10051
+ fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
10052
+ if (ids.has(record.id))
10053
+ fail("duplicate constraint id");
10054
+ ids.add(record.id);
10055
+ if (record.declaredName != null) {
10056
+ const label = record.declaredName.toLowerCase();
10057
+ if (labels.has(label))
10058
+ fail(`duplicate declared name '${record.declaredName}'`);
10059
+ labels.add(label);
10060
+ }
10061
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
10062
+ fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
10063
+ try {
10064
+ checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
10065
+ } catch (error) {
10066
+ fail(error.message);
10067
+ }
10068
+ const resolveTop = (path) => {
10069
+ const matches = fieldsByExactName(fields, path[0]);
10070
+ if (matches.length !== 1 || matches[0] === rowId)
10071
+ fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
10072
+ return matches[0];
10073
+ };
10074
+ switch (record.kind) {
10075
+ case "CHECK": {
10076
+ if (record.checkSql == null)
10077
+ fail("CHECK without an expression");
10078
+ validateCheckRecord(bytes, where, schemaPath, fields, rowId);
10079
+ break;
10080
+ }
10081
+ case "NOT_NULL": {
10082
+ if (record.columns.length !== 1)
10083
+ fail("NOT_NULL requires exactly one column path");
10084
+ const path = record.columns[0];
10085
+ let field = fields[resolveTop(path)];
10086
+ for (let depth = 1;depth < path.length; depth++) {
10087
+ const children = ordinaryStructChildren(field);
10088
+ if (!children)
10089
+ fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
10090
+ const matches = fieldsByExactName(children, path[depth]);
10091
+ if (matches.length !== 1)
10092
+ fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
10093
+ field = children[matches[0]];
10094
+ }
10095
+ if (path.length === 1 && isGeneratedField(field))
10096
+ fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
10097
+ required.add(JSON.stringify(path));
10098
+ break;
10099
+ }
10100
+ case "PRIMARY_KEY":
10101
+ case "UNIQUE": {
10102
+ for (const path of record.columns) {
10103
+ const index = resolveTop(path);
10104
+ if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
10105
+ fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
10106
+ }
10107
+ if (record.kind === "PRIMARY_KEY") {
10108
+ if (++primaryKeys > 1)
10109
+ fail("a table may have only one PRIMARY KEY");
10110
+ for (const path of record.columns)
10111
+ required.add(JSON.stringify(path));
10112
+ }
10113
+ break;
10114
+ }
10115
+ case "FOREIGN_KEY": {
10116
+ record.columns.forEach(resolveTop);
10117
+ const ref = record.references;
10118
+ if (ref == null || ref.constraintId == null)
10119
+ fail("FOREIGN_KEY requires a referenced table and referenced constraint");
10120
+ if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
10121
+ fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
10122
+ if (ref.columns.length !== record.columns.length)
10123
+ fail("foreign key arity mismatch");
10124
+ try {
10125
+ checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
10126
+ } catch (error) {
10127
+ fail(error.message);
10128
+ }
10129
+ if (ref.match !== undefined && ref.match !== "SIMPLE")
10130
+ fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
10131
+ for (const action of [ref.onUpdate, ref.onDelete])
10132
+ if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
10133
+ fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
10134
+ break;
10135
+ }
10136
+ default:
10137
+ fail(`unknown constraint kind ${String(record.kind)}`);
10138
+ }
10139
+ records.push(record);
10140
+ }
10141
+ return { records, required };
10142
+ }
10143
+ function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
10144
+ const info = decodeASD(ConstraintInfoSchema, bytes);
10145
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
10146
+ const expression = decodeASD(SqlExpressionSchema, def.check_expression);
10147
+ const fail = (message) => {
10148
+ throw new Error(`${where}: ${message}`);
10149
+ };
10150
+ if (expression.profile !== ROW_SCALAR_EXPRESSION)
10151
+ fail(`unsupported CHECK expression profile ${expression.profile}`);
10152
+ if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
10153
+ fail("CHECK expression belongs to another schema");
10154
+ const context = expression.evaluation_context ?? {};
10155
+ for (const [key, value] of Object.entries(CHECK_CONTEXT))
10156
+ if (context[key] !== value)
10157
+ fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
10158
+ try {
10159
+ validateNumericCheckSql(expression.sql, (name) => {
10160
+ const lower = name.toLowerCase();
10161
+ const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
10162
+ if (matches.length > 1)
10163
+ throw new Error(`ambiguous CHECK column reference ${name}`);
10164
+ if (matches.length === 0 || matches[0] === rowId)
10165
+ throw new Error(`CHECK references a missing or row-id column ${name}`);
10166
+ const column = fields[matches[0]];
10167
+ if (column.metadata.has("ARROW:extension:name"))
10168
+ throw new Error(`CHECK operand ${name} has an extension type`);
10169
+ if (isGeneratedField(column))
10170
+ throw new Error(`CHECK operand ${name} is a generated column`);
10171
+ const type = duckdbPrimitive(column);
10172
+ if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
10173
+ throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
10174
+ });
10175
+ } catch (error) {
10176
+ fail(`${error.message} (CHECK SQL: ${expression.sql})`);
10177
+ }
10178
+ }
10179
+ function validateForeignKeyTargets(tables) {
10180
+ const key = (schemaPath, name) => JSON.stringify([...schemaPath, name]);
10181
+ const byTable = new Map;
10182
+ for (const t of tables)
10183
+ byTable.set(key(t.schemaPath, t.name), t.constraints.map(readConstraintRecord));
10184
+ for (const t of tables) {
10185
+ for (const record of byTable.get(key(t.schemaPath, t.name)) ?? []) {
10186
+ if (record.kind !== "FOREIGN_KEY" || record.references == null)
10187
+ continue;
10188
+ const ref = record.references;
10189
+ const where = `Table '${t.name}': constraint '${record.id}'`;
10190
+ const target = byTable.get(key(ref.schemaPath, ref.table));
10191
+ if (!target)
10192
+ throw new Error(`${where}: references table ${[...ref.schemaPath, ref.table].join(".")}, which this catalog does not serve`);
10193
+ const key_ = target.find((r) => r.id === ref.constraintId);
10194
+ if (!key_ || key_.kind !== "PRIMARY_KEY" && key_.kind !== "UNIQUE")
10195
+ throw new Error(`${where}: referenced constraint '${ref.constraintId}' is not a PRIMARY_KEY or UNIQUE record of '${ref.table}'`);
10196
+ const want = new Set(ref.columns.map((p) => JSON.stringify(p)));
10197
+ if (key_.columns.length !== want.size || !key_.columns.every((p) => want.has(JSON.stringify(p))))
10198
+ throw new Error(`${where}: referenced columns do not match constraint '${ref.constraintId}' of '${ref.table}'`);
10199
+ }
10200
+ }
10201
+ }
10202
+ function servedConstraintFields(fields, required) {
10203
+ const rewrite = (list, prefix) => {
10204
+ let changed = false;
10205
+ const out = list.map((f) => {
10206
+ if (prefix.length === 0 && isRowIdField(f))
10207
+ return f;
10208
+ const path = [...prefix, f.name];
10209
+ const nullable = !required.has(JSON.stringify(path));
10210
+ const children = ordinaryStructChildren(f);
10211
+ const newChildren = children ? rewrite(children, path) : null;
10212
+ if (nullable === f.nullable && (newChildren == null || newChildren === children))
10213
+ return f;
10214
+ changed = true;
10215
+ const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
10216
+ return field2(f.name, type, nullable, new Map(f.metadata));
10217
+ });
10218
+ return changed ? out : list;
8920
10219
  };
10220
+ return rewrite(fields, []);
10221
+ }
10222
+ function validateConstraintNullability(table, fields, constraints) {
10223
+ const schemaPath = constraints.length ? readConstraintRecord(constraints[0]).schemaPath : ["main"];
10224
+ validateTableConstraints(table, schemaPath, fields, constraints);
10225
+ }
10226
+ function translateLegacyGenerated(fields, owner, table) {
10227
+ let changed = false;
10228
+ const out = fields.map((f) => {
10229
+ const sql = f.metadata.get("generated_expression");
10230
+ if (sql === undefined)
10231
+ return f;
10232
+ if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
10233
+ throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
10234
+ const metadata = new Map(f.metadata);
10235
+ metadata.delete("generated_expression");
10236
+ metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
10237
+ metadata.set(GENERATION_KEY, "virtual");
10238
+ changed = true;
10239
+ return field2(f.name, f.type, f.nullable, metadata);
10240
+ });
10241
+ return changed ? out : fields;
10242
+ }
10243
+ function servedTableSchema(table, schemaPath, schema, constraints) {
10244
+ let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
10245
+ const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
10246
+ fields = servedConstraintFields(fields, required);
10247
+ return fields === schema.fields ? schema : schema2(fields, schema.metadata);
10248
+ }
10249
+ function servedTableInfo(info) {
10250
+ if (!info.columns || info.columns.length === 0) {
10251
+ if ((info.constraints ?? []).length)
10252
+ throw new Error(`Table '${info.name}': constraints on a table without columns`);
10253
+ return info;
10254
+ }
10255
+ const schema = deserializeSchema(info.columns);
10256
+ const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
10257
+ return served === schema ? info : { ...info, columns: serializeSchema(served) };
8921
10258
  }
8922
- var decodeCatalogContentsResponse = (b) => decodeASD(CatalogContentsResultSchema, b);
8923
10259
  // src/generated/vgi-client.ts
8924
10260
  var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
8925
10261
  var decodeCatalogInfo = (b) => decodeASD(CatalogInfoSchema, b);
@@ -9111,6 +10447,56 @@ class CatalogInterface {
9111
10447
  tableCreate(attachOpaqueData, schemaPath, name, columns, onConflict, constraintDefinitions, transactionOpaqueData) {
9112
10448
  throw new CatalogReadOnlyError("table_create");
9113
10449
  }
10450
+ catalogCapabilities(_attachOpaqueData) {
10451
+ const proto = CatalogInterface.prototype;
10452
+ if (this.tableConstraintsApply !== proto.tableConstraintsApply || this._implementsLegacyNotNull())
10453
+ return constraintCapabilities({ mutate: true, enforce: true });
10454
+ return null;
10455
+ }
10456
+ _implementsLegacyNotNull() {
10457
+ const proto = CatalogInterface.prototype;
10458
+ return this.tableNotNullSet !== proto.tableNotNullSet || this.tableNotNullDrop !== proto.tableNotNullDrop;
10459
+ }
10460
+ async tableConstraintsApply(request) {
10461
+ if (!this._implementsLegacyNotNull())
10462
+ throw new VgiError("catalog_table_constraints_apply is not implemented by this catalog", "UNIMPLEMENTED");
10463
+ const target = decodeCatalogObjectRef(request.table);
10464
+ const attach = request.attach_opaque_data;
10465
+ const tx = request.transaction_opaque_data ?? undefined;
10466
+ const schemaPath = [...target.schema_path];
10467
+ const read = async () => {
10468
+ const info = await this.tableGet(attach, schemaPath, target.name, undefined, undefined, tx);
10469
+ if (!info)
10470
+ throw new CatalogNotFoundError("Table", target.name);
10471
+ return info;
10472
+ };
10473
+ const before = await read();
10474
+ if (!sameBytes2(before.definition_revision ?? null, request.expected_revision))
10475
+ throw new VgiError(`Table '${target.name}': definition_revision changed; retry the statement`, "FAILED_PRECONDITION");
10476
+ const records = (before.constraints ?? []).map(readConstraintRecord);
10477
+ for (const bytes of request.changes) {
10478
+ const change = decodeConstraintChange(bytes);
10479
+ if (change.operation === "ADD" && change.definition != null) {
10480
+ const def = decodeConstraintDefinition(change.definition);
10481
+ if (def.kind === "NOT_NULL" && def.column_paths.length === 1 && def.column_paths[0].length === 1) {
10482
+ await this.tableNotNullSet(attach, schemaPath, target.name, [...def.column_paths[0]], false, tx);
10483
+ continue;
10484
+ }
10485
+ } else if (change.operation === "DROP" && change.ref != null) {
10486
+ const id = decodeCatalogObjectRef(change.ref).name;
10487
+ const record = records.find((r) => r.id === id);
10488
+ if (record?.kind === "NOT_NULL" && record.columns[0]?.length === 1) {
10489
+ await this.tableNotNullDrop(attach, schemaPath, target.name, record.columns[0], false, tx);
10490
+ continue;
10491
+ }
10492
+ }
10493
+ throw new VgiError("catalog_table_constraints_apply: only ADD/DROP of a top-level NOT_NULL routes to tableNotNullSet/tableNotNullDrop; implement tableConstraintsApply", "UNIMPLEMENTED");
10494
+ }
10495
+ const after = await read();
10496
+ if (after.definition_revision == null || sameBytes2(after.definition_revision, before.definition_revision ?? null))
10497
+ 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");
10498
+ return { table: request.table, definition_revision: after.definition_revision, constraints: after.constraints ?? [] };
10499
+ }
9114
10500
  tableDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
9115
10501
  throw new CatalogReadOnlyError("table_drop");
9116
10502
  }
@@ -9238,172 +10624,16 @@ class CatalogInterface {
9238
10624
  transactionCommit(attachOpaqueData, transactionOpaqueData) {}
9239
10625
  transactionRollback(attachOpaqueData, transactionOpaqueData) {}
9240
10626
  }
9241
- // src/catalog/column-expressions.ts
9242
- init_arrow();
9243
- var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
9244
- var GENERATION_KEY = "vgi.column.generation.v1";
9245
- var PROFILE = "vgi.expression.duckdb.scalar.v1";
9246
- var MAX_BYTES = 8 * 1024 * 1024;
9247
- var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
9248
- function text(value, maximum) {
9249
- if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > maximum)
9250
- throw new Error("invalid generated expression text");
9251
- for (let i = 0;i < value.length; i++) {
9252
- const c = value.charCodeAt(i);
9253
- if (c >= 55296 && c <= 56319) {
9254
- const d = value.charCodeAt(++i);
9255
- if (!(d >= 56320 && d <= 57343))
9256
- throw new Error("invalid generated expression Unicode");
9257
- } else if (c >= 56320 && c <= 57343)
9258
- throw new Error("invalid generated expression Unicode");
9259
- }
9260
- }
9261
- function expression(value, owner) {
9262
- text(value.sql, 1024 * 1024);
9263
- if (!value.sql.trim() || value.profile !== PROFILE)
9264
- throw new Error("unsupported generated expression profile or empty SQL");
9265
- if (!Array.isArray(value.schema_path) || value.schema_path.length > 32)
9266
- throw new Error("invalid generated expression owner");
9267
- value.schema_path.forEach((part) => text(part, 4096));
9268
- if (JSON.stringify(value.schema_path) !== JSON.stringify(owner))
9269
- throw new Error("generated expression owner differs from table schema");
9270
- const context = value.evaluation_context;
9271
- if (!context)
9272
- throw new Error("generated expression requires explicit evaluation context");
9273
- text(context.timezone, 256);
9274
- text(context.collation, 256);
9275
- if (!["asc", "desc"].includes(context.default_order) || ![
9276
- "nulls_first",
9277
- "nulls_last",
9278
- "nulls_first_on_asc_last_on_desc",
9279
- "nulls_last_on_asc_first_on_desc"
9280
- ].includes(context.default_null_order) || typeof context.preserve_insertion_order !== "boolean")
9281
- throw new Error("invalid generated expression evaluation context");
9282
- }
9283
- function envelope(bytes) {
9284
- if (!bytes.length || bytes.length > MAX_BYTES)
9285
- throw new Error("invalid generated expression size");
9286
- const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9287
- const kinds = [];
9288
- const textBuffers = [];
9289
- let offset = 0;
9290
- while (offset < bytes.length) {
9291
- const prefix = data.getInt32(offset, true) === -1 ? 8 : 4;
9292
- const length = data.getInt32(offset + prefix - 4, true);
9293
- offset += prefix;
9294
- if (!length) {
9295
- if (offset !== bytes.length || kinds.join(",") !== "1,3")
9296
- throw new Error("SqlExpression requires exactly one complete IPC batch");
9297
- return textBuffers;
9298
- }
9299
- if (length < 0 || offset + length > bytes.length)
9300
- throw new Error("invalid expression IPC length");
9301
- const p = offset + data.getUint32(offset, true), v = p - data.getInt32(p, true);
9302
- const slot = (id) => 4 + id * 2 < data.getUint16(v, true) ? data.getUint16(v + 4 + id * 2, true) : 0;
9303
- const kind = slot(1), body = slot(3);
9304
- if (!kind)
9305
- throw new Error("invalid expression IPC message");
9306
- kinds.push(data.getUint8(p + kind));
9307
- const bodyLength = body ? Number(data.getBigInt64(p + body, true)) : 0;
9308
- if (bodyLength < 0 || bodyLength > bytes.length - offset - length)
9309
- throw new Error("invalid expression IPC body");
9310
- if (data.getUint8(p + kind) === 3) {
9311
- const headerSlot = slot(2);
9312
- const record = p + headerSlot + data.getUint32(p + headerSlot, true);
9313
- const table = record - data.getInt32(record, true);
9314
- const recordSlot = (id) => 4 + id * 2 < data.getUint16(table, true) ? data.getUint16(table + 4 + id * 2, true) : 0;
9315
- if (recordSlot(3))
9316
- throw new Error("compressed expression IPC is unsupported");
9317
- const bufferSlot = recordSlot(2);
9318
- const buffers = record + bufferSlot + data.getUint32(record + bufferSlot, true);
9319
- if (data.getUint32(buffers, true) !== 26)
9320
- throw new Error("invalid SqlExpression buffer layout");
9321
- for (const index of [2, 5, 10, 14, 17, 20, 23]) {
9322
- const buffer = buffers + 4 + index * 16;
9323
- const start = Number(data.getBigInt64(buffer, true));
9324
- const size = Number(data.getBigInt64(buffer + 8, true));
9325
- if (start < 0 || size < 0 || start + size > bodyLength)
9326
- throw new Error("invalid expression string buffer");
9327
- textBuffers.push(bytes.subarray(offset + length + start, offset + length + start + size));
9328
- }
9329
- }
9330
- offset += length + bodyLength;
9331
- }
9332
- throw new Error("expression IPC lacks end marker");
9333
- }
9334
- function shape(schema) {
9335
- const field = (f) => [
9336
- f.name,
9337
- f.nullable,
9338
- String(f.type),
9339
- (f.type.children ?? []).map(field)
9340
- ];
9341
- return JSON.stringify(schema.fields.map(field));
9342
- }
9343
- function validateEncoded(encoded, owner) {
9344
- if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
9345
- throw new Error("invalid generated expression size");
9346
- const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
9347
- if (base64(bytes) !== encoded)
9348
- throw new Error("generated expression requires canonical base64");
9349
- const textBuffers = envelope(bytes);
9350
- const batch = deserializeBatch(bytes);
9351
- if (batch.numRows !== 1 || shape(batch.schema) !== shape(SqlExpressionSchema))
9352
- throw new Error("invalid SqlExpression record schema");
9353
- const utf8 = new TextDecoder("utf-8", { fatal: true });
9354
- textBuffers.forEach((buffer) => utf8.decode(buffer));
9355
- expression(decodeSqlExpression(bytes), owner);
9356
- }
9357
- function generatedExpressionMetadata(sql, owner) {
9358
- const value = {
9359
- sql,
9360
- profile: PROFILE,
9361
- schema_path: [...owner],
9362
- evaluation_context: {
9363
- timezone: "UTC",
9364
- collation: "binary",
9365
- default_order: "asc",
9366
- default_null_order: "nulls_last",
9367
- preserve_insertion_order: true
9368
- }
9369
- };
9370
- expression(value, owner);
9371
- return base64(encodeSqlExpression(value));
9372
- }
9373
- function validateColumnExpressions(schema, owner, allowGenerated = true) {
9374
- const type = (t) => {
9375
- for (const f of t?.children ?? t?.fields ?? [])
9376
- field(f);
9377
- if (t?.dictionary)
9378
- type(t.dictionary);
9379
- };
9380
- const field = (f) => {
9381
- const metadata = f.metadata ?? new Map;
9382
- for (const key of metadata.keys()) {
9383
- if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
9384
- throw new Error("unknown generated metadata version");
9385
- }
9386
- if (metadata.has("generated_expression"))
9387
- throw new Error("legacy generated expression requires explicit canonical translation");
9388
- if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
9389
- throw new Error("generated expression and category must occur together");
9390
- if (metadata.has(GENERATED_EXPRESSION_KEY)) {
9391
- if (metadata.get(GENERATION_KEY) !== "virtual")
9392
- throw new Error("only VIRTUAL generated columns are supported");
9393
- if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
9394
- throw new Error("generated column cannot have a default");
9395
- validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
9396
- if (!allowGenerated)
9397
- throw new Error("generated columns unsupported by this catalog");
9398
- }
9399
- type(f.type);
9400
- };
9401
- schema.fields.forEach(field);
9402
- }
9403
- function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
9404
- validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
10627
+ function sameBytes2(a, b) {
10628
+ if (a == null || b == null)
10629
+ return a == b;
10630
+ if (a.length !== b.length)
10631
+ return false;
10632
+ for (let i = 0;i < a.length; i++)
10633
+ if (a[i] !== b[i])
10634
+ return false;
10635
+ return true;
9405
10636
  }
9406
-
9407
10637
  // src/catalog/column-metadata.ts
9408
10638
  function scalarText(value) {
9409
10639
  for (let i = 0;i < value.length; i++) {
@@ -9555,9 +10785,21 @@ function validateTableInfoColumns(info) {
9555
10785
  validateColumnExpressionsIpc(info.columns, info.schema_path);
9556
10786
  }
9557
10787
  }
10788
+ function servedValidatedTableInfo(info) {
10789
+ if (info.columns.length)
10790
+ validateColumnMetadataIpc(info.columns);
10791
+ const served = servedTableInfo(info);
10792
+ if (served.columns.length) {
10793
+ try {
10794
+ validateColumnExpressionsIpc(served.columns, served.schema_path);
10795
+ } catch (error) {
10796
+ throw new Error(`Table '${served.name}': ${error.message}`);
10797
+ }
10798
+ }
10799
+ return served;
10800
+ }
9558
10801
  function encodeValidatedTableInfo(info) {
9559
- validateTableInfoColumns(info);
9560
- return encodeTableInfo(info);
10802
+ return encodeTableInfo(servedValidatedTableInfo(info));
9561
10803
  }
9562
10804
 
9563
10805
  // src/catalog/read-only.ts
@@ -9993,6 +11235,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
9993
11235
  const settings = (this._descriptor.settings ?? []).map((s) => serializeSetting(s));
9994
11236
  const secretTypes = (this._descriptor.secretTypes ?? []).map((s) => serializeSecretType(s));
9995
11237
  const attachCatalogs = (this._descriptor.attachCatalogs ?? []).map((c) => encodeAttachCatalogInfo(c));
11238
+ const available = this.catalogReadProfiles();
11239
+ const read = selectReadProfiles(available, clientCapabilities);
9996
11240
  const hasTimeTravel = this._descriptor.schemas.some((s) => s.tables?.some((t) => t.supportsTimeTravel) ?? false);
9997
11241
  return buildCatalogAttachResult({
9998
11242
  attach_opaque_data: attachOpaqueData,
@@ -10012,9 +11256,19 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10012
11256
  global_function_prefix: this._descriptor.globalFunctionPrefix ?? "",
10013
11257
  resolved_data_version: null,
10014
11258
  resolved_implementation_version: null,
10015
- supports_catalog_contents: this.supportsCatalogContents
11259
+ supports_catalog_contents: this.supportsCatalogContents,
11260
+ catalog_capabilities: available.length ? encodeCatalogCapabilities({ read: [...available].sort(), ddl: [], write: [], transaction: [] }) : null,
11261
+ selected_capabilities: available.length ? encodeCatalogCapabilities({ read, ddl: [], write: [], transaction: [] }) : null
10016
11262
  });
10017
11263
  }
11264
+ catalogReadProfiles() {
11265
+ const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
11266
+ return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
11267
+ }
11268
+ catalogCapabilities(_attachOpaqueData) {
11269
+ const read = this.catalogReadProfiles();
11270
+ return read.length ? catalogCapabilities({ read }) : null;
11271
+ }
10018
11272
  detach(attachOpaqueData) {
10019
11273
  for (const [name, id] of this._attachments) {
10020
11274
  if (bufferEquals(id, attachOpaqueData)) {
@@ -10075,8 +11329,12 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10075
11329
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
10076
11330
  if (!schema || !schema.tables)
10077
11331
  return [];
10078
- return await Promise.all(schema.tables.map(async (t) => {
11332
+ const infos = await Promise.all(schema.tables.map(async (t) => {
11333
+ if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
11334
+ 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");
11335
+ }
10079
11336
  let colSchema;
11337
+ let bindFailed = false;
10080
11338
  if (t.columns) {
10081
11339
  colSchema = t.columns;
10082
11340
  } else if (t.function) {
@@ -10098,25 +11356,31 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10098
11356
  colSchema = response.output_schema;
10099
11357
  } catch {
10100
11358
  colSchema = schema2([]);
11359
+ bindFailed = true;
10101
11360
  }
10102
11361
  } else {
10103
11362
  colSchema = schema2([]);
10104
11363
  }
10105
- if (t.defaults) {
10106
- colSchema = applyDefaults(colSchema, t.defaults);
10107
- }
10108
- if (t.generatedColumns) {
10109
- colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path);
10110
- }
10111
- if (t.columnComments) {
10112
- colSchema = applyColumnComments(colSchema, t.columnComments);
11364
+ if (!bindFailed) {
11365
+ if (t.defaults) {
11366
+ colSchema = applyDefaults(colSchema, t.defaults, path);
11367
+ }
11368
+ if (t.generatedColumns) {
11369
+ colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path, t.name);
11370
+ }
11371
+ if (t.columnComments) {
11372
+ colSchema = applyColumnComments(colSchema, t.columnComments, t.name);
11373
+ }
10113
11374
  }
10114
11375
  validateColumnMetadata(colSchema);
10115
- validateColumnExpressions(colSchema, path);
10116
- const columns = serializeSchema(colSchema);
10117
- if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
10118
- throw new Error("legacy constraint metadata requires explicit canonical records");
11376
+ const constraints = bindFailed ? [] : t.constraints ?? [];
11377
+ colSchema = servedTableSchema(t.name, path, colSchema, constraints);
11378
+ try {
11379
+ validateColumnExpressions(colSchema, path);
11380
+ } catch (error) {
11381
+ throw new Error(`Table '${t.name}': ${error.message}`);
10119
11382
  }
11383
+ const columns = serializeSchema(colSchema);
10120
11384
  const requiredFilters = t.requiredFilters ?? [];
10121
11385
  for (const group of requiredFilters) {
10122
11386
  if (!Array.isArray(group) || group.length === 0)
@@ -10151,7 +11415,7 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10151
11415
  name: t.name,
10152
11416
  schema_path: normalizeSchemaPath(path),
10153
11417
  columns,
10154
- constraints: t.constraints ?? [],
11418
+ constraints: [...constraints],
10155
11419
  definition_revision: t.definitionRevision ?? null,
10156
11420
  write_result_modes: {},
10157
11421
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
@@ -10164,6 +11428,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10164
11428
  required_filters: requiredFilters
10165
11429
  };
10166
11430
  }));
11431
+ validateForeignKeyTargets(infos.map((info) => ({ schemaPath: info.schema_path, name: info.name, constraints: info.constraints })));
11432
+ return infos;
10167
11433
  }
10168
11434
  tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10169
11435
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
@@ -10473,7 +11739,14 @@ function defaultToSql(value) {
10473
11739
  const escaped = value.replace(/'/g, "''");
10474
11740
  return `'${escaped}'`;
10475
11741
  }
10476
- function applyDefaults(schema, defaults) {
11742
+ function canonicalDefault(type, value) {
11743
+ if (type === "BOOLEAN")
11744
+ return typeof value === "boolean";
11745
+ if (type === "VARCHAR")
11746
+ return typeof value === "string";
11747
+ return false;
11748
+ }
11749
+ function applyDefaults(schema, defaults, owner) {
10477
11750
  let result = schema;
10478
11751
  for (const [colName, value] of Object.entries(defaults)) {
10479
11752
  const idx = result.fields.findIndex((f) => f.name === colName);
@@ -10481,7 +11754,12 @@ function applyDefaults(schema, defaults) {
10481
11754
  continue;
10482
11755
  const f = result.fields[idx];
10483
11756
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
10484
- existingMeta.set("default", defaultToSql(value));
11757
+ const sql = defaultToSql(value);
11758
+ if (canonicalDefault(duckdbPrimitive(f), value)) {
11759
+ existingMeta.set("vgi.column.default.v1", defaultExpressionMetadata(sql, owner));
11760
+ } else {
11761
+ existingMeta.set("default", sql);
11762
+ }
10485
11763
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
10486
11764
  const fields = [...result.fields];
10487
11765
  fields[idx] = newField;
@@ -10489,17 +11767,21 @@ function applyDefaults(schema, defaults) {
10489
11767
  }
10490
11768
  return result;
10491
11769
  }
10492
- function applyGeneratedColumns(schema, generated, owner) {
11770
+ function applyGeneratedColumns(schema, generated, owner, table) {
10493
11771
  let result = schema;
10494
11772
  for (const [colName, expression] of Object.entries(generated)) {
10495
11773
  const idx = result.fields.findIndex((f) => f.name === colName);
10496
11774
  if (idx < 0)
10497
- throw new Error(`generated expression references unknown column ${colName}`);
11775
+ throw new Error(`Table '${table}': generatedColumns names unknown column ${colName}`);
10498
11776
  const f = result.fields[idx];
10499
11777
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
10500
11778
  if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression"))
10501
- throw new Error("generated convenience conflicts with existing expression metadata");
10502
- existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
11779
+ throw new Error(`Table '${table}': generatedColumns for ${colName} conflicts with existing expression metadata`);
11780
+ try {
11781
+ existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
11782
+ } catch (error) {
11783
+ throw new Error(`Table '${table}': column ${colName}: ${error.message}`);
11784
+ }
10503
11785
  existingMeta.set(GENERATION_KEY, "virtual");
10504
11786
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
10505
11787
  const fields = [...result.fields];
@@ -10508,12 +11790,12 @@ function applyGeneratedColumns(schema, generated, owner) {
10508
11790
  }
10509
11791
  return result;
10510
11792
  }
10511
- function applyColumnComments(schema, comments) {
11793
+ function applyColumnComments(schema, comments, table) {
10512
11794
  let result = schema;
10513
11795
  for (const [colName, comment] of Object.entries(comments)) {
10514
11796
  const idx = result.fields.findIndex((f) => f.name === colName);
10515
11797
  if (idx < 0)
10516
- throw new Error(`column comment references unknown field ${colName}`);
11798
+ throw new Error(`Table '${table}': columnComments names unknown column ${colName}`);
10517
11799
  const f = result.fields[idx];
10518
11800
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
10519
11801
  existingMeta.set("comment", comment);
@@ -10643,6 +11925,29 @@ function sameSpelling(left, right) {
10643
11925
  const b = normalizeSchemaPath(right);
10644
11926
  return a.length === b.length && a.every((part, i) => part === b[i]);
10645
11927
  }
11928
+ // src/catalog/indexes.ts
11929
+ var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
11930
+ function emptyIndexOptions() {
11931
+ return Uint8Array.from(atob(NO_OPTIONS_B64), (c) => c.charCodeAt(0));
11932
+ }
11933
+ function canonicalIndex(spec) {
11934
+ if (spec.columns.length === 0)
11935
+ throw new Error(`index on '${spec.table}' requires at least one key`);
11936
+ if (!spec.algorithm)
11937
+ throw new Error("index algorithm must be nonempty");
11938
+ const values = spec.options ?? emptyIndexOptions();
11939
+ return {
11940
+ definition: encodeASD(IndexDefinitionSchema, {
11941
+ table: encodeASD(CatalogObjectRefSchema, { kind: "table", schema_path: spec.schemaPath, name: spec.table, owner_table: null }),
11942
+ algorithm: spec.algorithm,
11943
+ keys: spec.columns.map((path) => encodeASD(IndexKeySchema, { column_path: path, expression: null })),
11944
+ options: values,
11945
+ constraint_type: spec.constraintType ?? "NONE",
11946
+ associated_constraint: spec.associatedConstraintId == null ? null : encodeASD(CatalogObjectRefSchema, { kind: "constraint", schema_path: spec.schemaPath, name: spec.associatedConstraintId, owner_table: spec.table })
11947
+ }),
11948
+ options: encodeASD(OptionStateSchema, { values, explicit_names: spec.explicitOptionNames ?? [] })
11949
+ };
11950
+ }
10646
11951
  // node_modules/@noble/ciphers/utils.js
10647
11952
  /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
10648
11953
  function isBytes(a) {
@@ -11579,6 +12884,12 @@ class CompositeCatalogInterface extends CatalogInterface {
11579
12884
  async tableNotNullDrop(...args) {
11580
12885
  await this._route(args[0]).tableNotNullDrop(...args);
11581
12886
  }
12887
+ async tableConstraintsApply(request) {
12888
+ return await this._route(request.attach_opaque_data).tableConstraintsApply(request);
12889
+ }
12890
+ async catalogCapabilities(attachOpaqueData) {
12891
+ return await this._route(attachOpaqueData).catalogCapabilities(attachOpaqueData);
12892
+ }
11582
12893
  async viewCreate(...args) {
11583
12894
  await this._route(args[0]).viewCreate(...args);
11584
12895
  }
@@ -14694,12 +16005,10 @@ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@qu
14694
16005
  var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
14695
16006
  var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
14696
16007
  function encodeCatalogStreams(inventory) {
14697
- for (const schema of inventory)
14698
- for (const table of schema.tables)
14699
- validateTableInfoColumns(table);
16008
+ const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
14700
16009
  const streams = {
14701
16010
  schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
14702
- tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
16011
+ tables: encodeASDCollection(TableInfoSchema, tables),
14703
16012
  views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
14704
16013
  functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
14705
16014
  macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
@@ -15753,7 +17062,13 @@ function catalogAdminHandlers(getCatalog, signingKey) {
15753
17062
  innerParams.implementation_version = restored.implementationVersion;
15754
17063
  optionsDict = restored.options;
15755
17064
  }
15756
- const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities));
17065
+ const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
17066
+ const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, clientCapabilities);
17067
+ const advertised = result.catalog_capabilities != null ? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities)) : await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
17068
+ if (!capabilitiesEmpty(advertised)) {
17069
+ result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
17070
+ result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
17071
+ }
15757
17072
  const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
15758
17073
  return wrapResult(buildCatalogAttachResult({
15759
17074
  ...result,
@@ -15889,27 +17204,39 @@ import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-
15889
17204
  // src/catalog/unconstrained-columns.ts
15890
17205
  init_arrow();
15891
17206
  import { MethodNotImplementedError as MethodNotImplementedError3 } from "@query-farm/vgi-rpc";
15892
- function requireUnconstrainedColumns(columns) {
15893
- const visit = (field, top, depth) => {
17207
+ function requireCreateColumns(columns, constraintDefinitions = []) {
17208
+ const required = new Set;
17209
+ for (const bytes of constraintDefinitions) {
17210
+ let def;
17211
+ try {
17212
+ def = decodeConstraintDefinition(bytes);
17213
+ } catch (error) {
17214
+ throw new Error(`catalog_table_create: undecodable constraint definition: ${error.message}`);
17215
+ }
17216
+ if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
17217
+ for (const path of def.column_paths)
17218
+ required.add(JSON.stringify([...path]));
17219
+ }
17220
+ const visit = (field, path, depth) => {
15894
17221
  if (depth > 64)
15895
17222
  throw new MethodNotImplementedError3("catalog_table_create: column nesting exceeds supported depth");
15896
- if (top && field.metadata?.has("is_row_id"))
17223
+ if (depth === 0 && field.metadata?.has("is_row_id"))
15897
17224
  return;
15898
17225
  for (const key of field.metadata?.keys() ?? []) {
15899
17226
  if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
15900
17227
  throw new MethodNotImplementedError3("catalog_table_create: logical column types require negotiation");
15901
17228
  }
15902
17229
  }
15903
- if (!field.nullable) {
15904
- throw new MethodNotImplementedError3("catalog_table_create: nonnullable user columns require canonical constraints");
17230
+ if (!field.nullable && !required.has(JSON.stringify(path))) {
17231
+ throw new MethodNotImplementedError3(`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`);
15905
17232
  }
15906
17233
  if (isStruct(field.type)) {
15907
17234
  for (const child of field.type.children)
15908
- visit(child, false, depth + 1);
17235
+ visit(child, [...path, child.name], depth + 1);
15909
17236
  }
15910
17237
  };
15911
17238
  for (const field of deserializeSchema(columns).fields)
15912
- visit(field, true, 0);
17239
+ visit(field, [field.name], 0);
15913
17240
  }
15914
17241
 
15915
17242
  // src/protocol/handlers/catalog/table.ts
@@ -15931,19 +17258,57 @@ function catalogTableHandlers(getCatalog, signingKey) {
15931
17258
  const catalogTableCreate = catalogHandler(signingKey, async (params) => {
15932
17259
  if (params.constraint_definitions == null)
15933
17260
  throw new Error("constraint_definitions is required");
15934
- if (Array.from(params.constraint_definitions).length > 0) {
15935
- throw new MethodNotImplementedError4("catalog_table_create: canonical constraint enforcement is not supported");
15936
- }
17261
+ const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
15937
17262
  if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
15938
17263
  throw new MethodNotImplementedError4("catalog_table_create: table metadata/options/layout profiles are not supported");
15939
17264
  }
17265
+ const attach = toUint8Array(params.attach_opaque_data);
17266
+ const cat = getCatalog();
17267
+ if (definitions.length > 0) {
17268
+ const caps = await cat.catalogCapabilities(attach);
17269
+ if (caps != null && !(caps.ddl.includes(CONSTRAINT_CREATE) && caps.write.includes(CONSTRAINT_ENFORCE))) {
17270
+ 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");
17271
+ }
17272
+ }
15940
17273
  validateColumnMetadataIpc(toUint8Array(params.columns));
15941
17274
  validateColumnExpressionsIpc(toUint8Array(params.columns), params.schema_path);
15942
- requireUnconstrainedColumns(toUint8Array(params.columns));
15943
- const cat = getCatalog();
15944
- 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);
17275
+ requireCreateColumns(toUint8Array(params.columns), definitions);
17276
+ 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);
15945
17277
  return {};
15946
17278
  });
17279
+ const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
17280
+ const attach = toUint8Array(params.attach_opaque_data);
17281
+ const cat = getCatalog();
17282
+ const caps = await cat.catalogCapabilities(attach);
17283
+ if (caps != null && !caps.ddl.includes(CONSTRAINT_MUTATE)) {
17284
+ throw new MethodNotImplementedError4("catalog_table_constraints_apply: this catalog does not advertise vgi.constraint.mutate.v1");
17285
+ }
17286
+ const table = toUint8Array(params.table);
17287
+ const expected = toUint8Array(params.expected_revision);
17288
+ const changes = Array.from(params.changes, (c) => toUint8Array(c));
17289
+ if (expected.length === 0 || changes.length === 0)
17290
+ throw new Error("catalog_table_constraints_apply: empty revision or change list");
17291
+ const snapshot = await cat.tableConstraintsApply({
17292
+ attach_opaque_data: attach,
17293
+ table,
17294
+ expected_revision: expected,
17295
+ changes,
17296
+ transaction_opaque_data: params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : null
17297
+ });
17298
+ const want = decodeCatalogObjectRef(table);
17299
+ const got = decodeCatalogObjectRef(toUint8Array(snapshot.table));
17300
+ if (got.name !== want.name || JSON.stringify([...got.schema_path]) !== JSON.stringify([...want.schema_path]))
17301
+ throw new Error("catalog_table_constraints_apply: the catalog returned a snapshot of a different table");
17302
+ const revision = toUint8Array(snapshot.definition_revision);
17303
+ if (revision.length === 0 || revision.length === expected.length && revision.every((b, i) => b === expected[i]))
17304
+ throw new Error(`catalog_table_constraints_apply: table '${want.name}' must return a new, nonempty definition_revision`);
17305
+ for (const record of snapshot.constraints) {
17306
+ const view = readConstraintRecord(toUint8Array(record));
17307
+ if (view.table !== want.name || JSON.stringify(view.schemaPath) !== JSON.stringify([...want.schema_path]))
17308
+ throw new Error(`catalog_table_constraints_apply: constraint '${view.id}' belongs to another table`);
17309
+ }
17310
+ return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
17311
+ });
15947
17312
  const catalogTableDrop = catalogHandler(signingKey, async (params) => {
15948
17313
  const cat = getCatalog();
15949
17314
  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);
@@ -16031,9 +17396,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
16031
17396
  return {};
16032
17397
  });
16033
17398
  return {
16034
- catalogTableConstraintsApply: async () => {
16035
- throw new MethodNotImplementedError4("catalog_table_constraints_apply");
16036
- },
17399
+ catalogTableConstraintsApply,
16037
17400
  catalogTableGet,
16038
17401
  catalogTableCreate,
16039
17402
  catalogTableDrop,
@@ -16821,7 +18184,7 @@ class VgiClient {
16821
18184
  options: [wireOptions],
16822
18185
  data_version_spec: [opts?.dataVersionSpec ?? null],
16823
18186
  implementation_version: [opts?.implementationVersion ?? null],
16824
- client_capabilities: [opts?.clientCapabilities ? encodeASD(ClientCapabilitiesSchema, opts.clientCapabilities) : null]
18187
+ client_capabilities: [opts?.clientCapabilities === null ? null : encodeASD(ClientCapabilitiesSchema, opts?.clientCapabilities ?? defaultClientCapabilities("vgi-typescript-client"))]
16825
18188
  }, schema);
16826
18189
  const result = await this.rpc.call("catalog_attach", wrapRequest(innerBatch));
16827
18190
  if (!result)
@@ -17849,6 +19212,10 @@ export {
17849
19212
  CACHE_STALE_IF_ERROR_KEY,
17850
19213
  CACHE_STALE_WHILE_REVALIDATE_KEY,
17851
19214
  CACHE_TTL_KEY,
19215
+ CONSTRAINT_CREATE,
19216
+ CONSTRAINT_ENFORCE,
19217
+ CONSTRAINT_MUTATE,
19218
+ CONSTRAINT_RECORDS_READ,
17852
19219
  CONTINUE,
17853
19220
  CatalogAlreadyExistsError,
17854
19221
  CatalogFunctionType,
@@ -17858,6 +19225,7 @@ export {
17858
19225
  CatalogSnapshotManager,
17859
19226
  ComparisonOp,
17860
19227
  CompositeCatalogInterface,
19228
+ DEFAULT_EXPRESSION_KEY,
17861
19229
  DEFAULT_MAX_WORKERS,
17862
19230
  DateUnit3 as DateUnit,
17863
19231
  DistinctDependence,
@@ -17869,6 +19237,8 @@ export {
17869
19237
  FunctionStorageCfDo,
17870
19238
  FunctionStorageSqlite,
17871
19239
  FunctionType,
19240
+ GENERATED_EXPRESSION_KEY,
19241
+ GENERATION_KEY,
17872
19242
  GROUP_COLUMN_NAME,
17873
19243
  GrantKeys2 as GrantKeys,
17874
19244
  GrantRefusedError,
@@ -17886,6 +19256,7 @@ export {
17886
19256
  PushdownFilters,
17887
19257
  READ_ONLY_ITEM_ATTACH_ID,
17888
19258
  RESERVED_ATTACH_OPTION,
19259
+ ROW_SCALAR_EXPRESSION,
17889
19260
  ReadOnlyCatalogInterface,
17890
19261
  ReservedAttachOptionError,
17891
19262
  RowCountMismatchError,
@@ -17897,6 +19268,7 @@ export {
17897
19268
  ScanFunctionResultSchema,
17898
19269
  SealAttachDeniedError,
17899
19270
  StatusError,
19271
+ TRANSACTION_DDL,
17900
19272
  TableInOutPhase,
17901
19273
  TimeUnit2 as TimeUnit,
17902
19274
  TypeId,
@@ -17936,14 +19308,22 @@ export {
17936
19308
  binary2 as binary,
17937
19309
  bool3 as bool,
17938
19310
  buildCatalogAttachResult,
19311
+ buildCatalogCapabilities,
19312
+ buildConstraintChange,
19313
+ buildConstraintDefinition,
17939
19314
  buildJoinKeysLookup,
19315
+ buildMacroOverload,
17940
19316
  buildRpcServer,
17941
19317
  buildScanBranchesResult,
17942
19318
  buildVgiProtocol,
17943
19319
  bytes,
17944
19320
  cacheControlMetadata,
19321
+ canonicalIndex,
19322
+ catalogCapabilities,
17945
19323
  codecFor,
17946
19324
  columnFromArray,
19325
+ constraintCapabilities,
19326
+ constraintRecord,
17947
19327
  constraintSpecFields,
17948
19328
  createLandingRoutes,
17949
19329
  date2 as date,
@@ -17952,13 +19332,26 @@ export {
17952
19332
  decimal2 as decimal,
17953
19333
  decimal1282 as decimal128,
17954
19334
  decimal2562 as decimal256,
19335
+ decodeCatalogCapabilities,
17955
19336
  decodeCatalogInfo,
19337
+ decodeCatalogObjectRef,
19338
+ decodeConstraintChange,
19339
+ decodeConstraintDefinition,
19340
+ decodeConstraintInfo,
19341
+ decodeConstraintSnapshot,
19342
+ decodeConstraintsApplyRequest,
17956
19343
  decodeDictValue,
19344
+ decodeForeignKeyDefinition,
17957
19345
  decodeFunctionInfo,
19346
+ decodeIndexDefinition,
17958
19347
  decodeMacroInfo,
19348
+ decodeMacroOverload,
17959
19349
  decodeSchemaInfo,
19350
+ decodeSqlExpression,
17960
19351
  decodeTableInfo,
17961
19352
  decodeViewInfo,
19353
+ defaultClientCapabilities,
19354
+ defaultExpressionMetadata,
17962
19355
  defineAggregate,
17963
19356
  defineCopyFromFunction,
17964
19357
  defineCopyToFunction,
@@ -17981,13 +19374,25 @@ export {
17981
19374
  durationNanos,
17982
19375
  durationSeconds,
17983
19376
  emptyBatch,
19377
+ emptyIndexOptions,
17984
19378
  encodeAttachTicket,
19379
+ encodeCatalogCapabilities,
17985
19380
  encodeCatalogInfo,
19381
+ encodeCatalogObjectRef,
19382
+ encodeConstraintChange,
19383
+ encodeConstraintDefinition,
19384
+ encodeConstraintInfo,
19385
+ encodeConstraintSnapshot,
19386
+ encodeConstraintsApplyRequest,
17986
19387
  encodeCopyFromFormatInfo,
19388
+ encodeForeignKeyDefinition,
17987
19389
  encodeFormatOptions,
17988
19390
  encodeFunctionInfo,
19391
+ encodeIndexDefinition,
17989
19392
  encodeMacroInfo,
19393
+ encodeMacroOverload,
17990
19394
  encodeSchemaInfo,
19395
+ encodeSqlExpression,
17991
19396
  encodeTableInfo,
17992
19397
  encodeViewInfo,
17993
19398
  field2 as field,
@@ -18004,6 +19409,7 @@ export {
18004
19409
  fromBrandedBigInt,
18005
19410
  fromBrandedNumber,
18006
19411
  storage as functionStorage,
19412
+ generatedExpressionMetadata,
18007
19413
  grantKeysFromArgv,
18008
19414
  httpConnect,
18009
19415
  int3 as int,
@@ -18049,6 +19455,7 @@ export {
18049
19455
  projectBatch,
18050
19456
  projectSchema,
18051
19457
  readCanonicalValue,
19458
+ readConstraintRecord,
18052
19459
  redeemAttachTicket,
18053
19460
  reprPushedFilters,
18054
19461
  resolveMetadata,
@@ -18063,14 +19470,20 @@ export {
18063
19470
  secretForScopeOfType,
18064
19471
  secretType,
18065
19472
  secretsOfType,
19473
+ selectCatalogCapabilities,
19474
+ selectReadProfiles,
18066
19475
  serializeAttachOptionSpec,
18067
19476
  serializeAttachOptionSpecs,
18068
19477
  serializeBatch,
18069
19478
  serializeColumnStatistics,
18070
19479
  serializeSchema,
18071
19480
  serializeUserState,
19481
+ servedConstraintFields,
19482
+ servedTableInfo,
19483
+ servedTableSchema,
18072
19484
  setStorage,
18073
19485
  sparseUnion2 as sparseUnion,
19486
+ sqlExpression,
18074
19487
  str,
18075
19488
  struct2 as struct,
18076
19489
  subprocessConnect,
@@ -18093,7 +19506,12 @@ export {
18093
19506
  uint642 as uint64,
18094
19507
  uint82 as uint8,
18095
19508
  union2 as union,
18096
- utf82 as utf8
19509
+ utf82 as utf8,
19510
+ validateColumnExpressionSql,
19511
+ validateConstraintNullability,
19512
+ validateForeignKeyTargets,
19513
+ validateNumericCheckSql,
19514
+ validateTableConstraints
18097
19515
  };
18098
19516
 
18099
- //# debugId=BD66CA0A252A167364756E2164756E21
19517
+ //# debugId=89F18E0425AB222A64756E2164756E21