@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
@@ -3937,174 +3937,674 @@ var TableFunctionStatisticsParamsSchema = schema2([
3937
3937
  ]);
3938
3938
 
3939
3939
  // src/generated/vgi-protocol-types.ts
3940
- var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
3941
- var decodeCatalogContentsResponse = (b) => decodeASD(CatalogContentsResultSchema, b);
3942
-
3943
- // src/generated/vgi-client.ts
3944
- var decodeCatalogInfo = (b) => decodeASD(CatalogInfoSchema, b);
3945
- var encodeFunctionInfo = (v) => encodeASD(FunctionInfoSchema, v);
3946
- var decodeFunctionInfo = (b) => decodeASD(FunctionInfoSchema, b);
3947
- var decodeIndexInfo = (b) => decodeASD(IndexInfoSchema, b);
3948
- var encodeMacroInfo = (v) => encodeASD(MacroInfoSchema, v);
3949
- var decodeMacroInfo = (b) => decodeASD(MacroInfoSchema, b);
3950
- var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
3951
- var decodeSchemaInfo = (b) => decodeASD(SchemaInfoSchema, b);
3952
- var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
3953
- var decodeTableInfo = (b) => decodeASD(TableInfoSchema, b);
3954
- var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
3955
- var decodeViewInfo = (b) => decodeASD(ViewInfoSchema, b);
3956
- // src/catalog/interface.ts
3957
- function decodeScanFunctionResult(inner) {
3958
- const argsBytes = inner.arguments;
3959
- const positionalArguments = [];
3960
- const namedArguments = {};
3961
- if (argsBytes != null) {
3962
- const batch = deserializeBatch(toUint8Array(argsBytes));
3963
- for (const field of batch.schema.fields) {
3964
- const col = batch.getChild(field.name);
3965
- const value = col ? col.get(0) : null;
3966
- if (field.name.startsWith("arg_")) {
3967
- const idx = parseInt(field.name.slice(4), 10);
3968
- while (positionalArguments.length <= idx)
3969
- positionalArguments.push(null);
3970
- positionalArguments[idx] = value;
3971
- } else {
3972
- namedArguments[field.name] = value;
3973
- }
3974
- }
3975
- }
3976
- const exts = inner.required_extensions;
3977
- const requiredExtensions = exts == null ? [] : (Array.isArray(exts) ? exts : [...exts]).filter((v) => v != null).map(String);
3940
+ function buildMacroOverload(init) {
3978
3941
  return {
3979
- functionName: String(inner.function_name ?? ""),
3980
- positionalArguments,
3981
- namedArguments,
3982
- requiredExtensions,
3983
- schemaPath: inner.schema_path == null ? null : (Array.isArray(inner.schema_path) ? inner.schema_path : [...inner.schema_path]).filter((value) => value != null).map(String)
3942
+ parameters: init.parameters,
3943
+ definition: init.definition,
3944
+ profile: init.profile,
3945
+ schema_path: init.schema_path,
3946
+ macro_type: init.macro_type,
3947
+ evaluation_context: init.evaluation_context
3984
3948
  };
3985
3949
  }
3986
-
3987
- // src/client/protocol.ts
3988
- function wrapRequest(batch) {
3989
- return { request: serializeBatch(batch) };
3950
+ var encodeMacroOverload = (v) => encodeASD(MacroOverloadSchema, v);
3951
+ var decodeMacroOverload = (b) => decodeASD(MacroOverloadSchema, b);
3952
+ function buildCatalogCapabilities(init) {
3953
+ return {
3954
+ read: init.read ?? [],
3955
+ ddl: init.ddl ?? [],
3956
+ write: init.write ?? [],
3957
+ transaction: init.transaction ?? []
3958
+ };
3990
3959
  }
3991
- function unwrapResult(result) {
3992
- const resultBytes = toUint8Array(result.result);
3993
- const innerBatch = deserializeBatch(resultBytes);
3994
- return batchToScalarDict(innerBatch);
3960
+ var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
3961
+ var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
3962
+ var encodeCatalogObjectRef = (v) => encodeASD(CatalogObjectRefSchema, v);
3963
+ var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
3964
+ var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
3965
+ var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
3966
+ var encodeForeignKeyDefinition = (v) => encodeASD(ForeignKeyDefinitionSchema, v);
3967
+ var decodeForeignKeyDefinition = (b) => decodeASD(ForeignKeyDefinitionSchema, b);
3968
+ function buildConstraintDefinition(init) {
3969
+ return {
3970
+ kind: init.kind,
3971
+ column_paths: init.column_paths ?? [],
3972
+ declared_name: init.declared_name ?? null,
3973
+ check_expression: init.check_expression ?? null,
3974
+ foreign_key: init.foreign_key ?? null
3975
+ };
3995
3976
  }
3977
+ var encodeConstraintDefinition = (v) => encodeASD(ConstraintDefinitionSchema, v);
3978
+ var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
3979
+ var encodeConstraintInfo = (v) => encodeASD(ConstraintInfoSchema, v);
3980
+ var decodeConstraintInfo = (b) => decodeASD(ConstraintInfoSchema, b);
3981
+ function buildConstraintChange(init) {
3982
+ return {
3983
+ operation: init.operation,
3984
+ ref: init.ref ?? null,
3985
+ definition: init.definition ?? null,
3986
+ enforcement: init.enforcement ?? null,
3987
+ validation: init.validation ?? null,
3988
+ cascade: init.cascade ?? null,
3989
+ declared_name: init.declared_name ?? null
3990
+ };
3991
+ }
3992
+ var encodeConstraintChange = (v) => encodeASD(ConstraintChangeSchema, v);
3993
+ var decodeConstraintChange = (b) => decodeASD(ConstraintChangeSchema, b);
3994
+ var encodeConstraintSnapshot = (v) => encodeASD(ConstraintSnapshotSchema, v);
3995
+ var decodeConstraintSnapshot = (b) => decodeASD(ConstraintSnapshotSchema, b);
3996
+ var encodeConstraintsApplyRequest = (v) => encodeASD(ConstraintsApplyRequestSchema, v);
3997
+ var decodeConstraintsApplyRequest = (b) => decodeASD(ConstraintsApplyRequestSchema, b);
3998
+ var encodeIndexDefinition = (v) => encodeASD(IndexDefinitionSchema, v);
3999
+ var decodeIndexDefinition = (b) => decodeASD(IndexDefinitionSchema, b);
4000
+ var decodeCatalogContentsResponse = (b) => decodeASD(CatalogContentsResultSchema, b);
3996
4001
 
3997
- // src/catalog/attach-options.ts
3998
- function inferAttachOptionArrowType(value) {
3999
- if (value === null)
4000
- return nullType2();
4001
- if (typeof value === "string")
4002
- return utf82();
4003
- if (typeof value === "bigint")
4004
- return int642();
4005
- if (typeof value === "number") {
4006
- if (!Number.isFinite(value)) {
4007
- throw new TypeError(`Attach option number values must be finite (got ${value}). ` + `Use a bigint for integers or a finite number for floats.`);
4002
+ // src/catalog/sql-grammar.ts
4003
+ class GrammarError extends Error {
4004
+ }
4005
+ var fail = (message) => {
4006
+ throw new GrammarError(message);
4007
+ };
4008
+ var RESERVED = new Set([
4009
+ "all",
4010
+ "and",
4011
+ "any",
4012
+ "array",
4013
+ "as",
4014
+ "asc",
4015
+ "between",
4016
+ "both",
4017
+ "case",
4018
+ "cast",
4019
+ "check",
4020
+ "collate",
4021
+ "column",
4022
+ "constraint",
4023
+ "create",
4024
+ "default",
4025
+ "desc",
4026
+ "distinct",
4027
+ "do",
4028
+ "else",
4029
+ "end",
4030
+ "except",
4031
+ "false",
4032
+ "fetch",
4033
+ "for",
4034
+ "foreign",
4035
+ "from",
4036
+ "glob",
4037
+ "grant",
4038
+ "group",
4039
+ "having",
4040
+ "ilike",
4041
+ "in",
4042
+ "intersect",
4043
+ "interval",
4044
+ "into",
4045
+ "is",
4046
+ "isnull",
4047
+ "like",
4048
+ "limit",
4049
+ "not",
4050
+ "notnull",
4051
+ "null",
4052
+ "offset",
4053
+ "on",
4054
+ "or",
4055
+ "order",
4056
+ "primary",
4057
+ "references",
4058
+ "returning",
4059
+ "select",
4060
+ "similar",
4061
+ "some",
4062
+ "table",
4063
+ "then",
4064
+ "to",
4065
+ "true",
4066
+ "try_cast",
4067
+ "union",
4068
+ "unique",
4069
+ "using",
4070
+ "when",
4071
+ "where",
4072
+ "window",
4073
+ "with"
4074
+ ]);
4075
+ var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
4076
+ function tokenize(sql) {
4077
+ const out = [];
4078
+ let i = 0;
4079
+ while (i < sql.length) {
4080
+ const c = sql[i];
4081
+ if (/\s/.test(c)) {
4082
+ i++;
4083
+ continue;
4008
4084
  }
4009
- return float642();
4085
+ if (sql.startsWith("--", i)) {
4086
+ while (i < sql.length && sql[i] !== `
4087
+ `)
4088
+ i++;
4089
+ continue;
4090
+ }
4091
+ if (sql.startsWith("/*", i)) {
4092
+ const close = sql.indexOf("*/", i + 2);
4093
+ if (close < 0)
4094
+ fail("unterminated comment");
4095
+ i = close + 2;
4096
+ continue;
4097
+ }
4098
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
4099
+ const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
4100
+ if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
4101
+ fail("unsupported numeric literal");
4102
+ out.push({ t: "num", v: m[0] });
4103
+ i += m[0].length;
4104
+ continue;
4105
+ }
4106
+ if (c === "'" || c === '"') {
4107
+ let j = i + 1, text = "";
4108
+ for (;; ) {
4109
+ if (j >= sql.length)
4110
+ fail("unterminated quoted text");
4111
+ if (sql[j] === c) {
4112
+ if (sql[j + 1] === c) {
4113
+ text += c;
4114
+ j += 2;
4115
+ continue;
4116
+ }
4117
+ break;
4118
+ }
4119
+ text += sql[j++];
4120
+ }
4121
+ out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
4122
+ i = j + 1;
4123
+ continue;
4124
+ }
4125
+ if (/[A-Za-z_\u0080-￿]/.test(c)) {
4126
+ const m = /^[A-Za-z_\u0080-￿][A-Za-z0-9_$\u0080-￿]*/.exec(sql.slice(i));
4127
+ out.push({ t: "ident", v: m[0], quoted: false });
4128
+ i += m[0].length;
4129
+ continue;
4130
+ }
4131
+ const op = OPERATORS.find((o) => sql.startsWith(o, i));
4132
+ if (!op)
4133
+ fail(`unsupported character '${c}'`);
4134
+ out.push({ t: "op", v: op });
4135
+ i += op.length;
4010
4136
  }
4011
- if (typeof value === "boolean")
4012
- return bool2();
4013
- if (value instanceof Uint8Array)
4014
- return binary2();
4015
- throw new TypeError(`Unsupported attach option value type: ${typeof value}. ` + `Supported: string, number, bigint, boolean, null, Uint8Array.`);
4137
+ out.push({ t: "end" });
4138
+ return out;
4016
4139
  }
4017
- function serializeAttachOptions(options) {
4018
- if (!options)
4019
- return null;
4020
- const entries = Object.entries(options);
4021
- if (entries.length === 0)
4022
- return null;
4023
- const fields = [];
4024
- const columns = {};
4025
- for (const [key, value] of entries) {
4026
- const type = inferAttachOptionArrowType(value);
4027
- fields.push(field2(key, type, true));
4028
- columns[key] = [value];
4140
+ var CAST_TYPES = {
4141
+ boolean: "BOOLEAN",
4142
+ bool: "BOOLEAN",
4143
+ logical: "BOOLEAN",
4144
+ tinyint: "TINYINT",
4145
+ int1: "TINYINT",
4146
+ smallint: "SMALLINT",
4147
+ int2: "SMALLINT",
4148
+ short: "SMALLINT",
4149
+ integer: "INTEGER",
4150
+ int: "INTEGER",
4151
+ int4: "INTEGER",
4152
+ signed: "INTEGER",
4153
+ bigint: "BIGINT",
4154
+ int8: "BIGINT",
4155
+ long: "BIGINT",
4156
+ float: "FLOAT",
4157
+ real: "FLOAT",
4158
+ float4: "FLOAT",
4159
+ double: "DOUBLE",
4160
+ float8: "DOUBLE",
4161
+ decimal: "DECIMAL",
4162
+ numeric: "DECIMAL",
4163
+ varchar: "VARCHAR",
4164
+ text: "VARCHAR",
4165
+ string: "VARCHAR",
4166
+ char: "VARCHAR",
4167
+ bpchar: "VARCHAR",
4168
+ nvarchar: "VARCHAR",
4169
+ character: "VARCHAR"
4170
+ };
4171
+ var INT64_MAX = (1n << 63n) - 1n;
4172
+ function literalNumber(text, negative) {
4173
+ if (/^[0-9]+$/.test(text)) {
4174
+ const value = BigInt(text) * (negative ? -1n : 1n);
4175
+ const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
4176
+ return { kind: "constant", type };
4029
4177
  }
4030
- const schema = schema2(fields);
4031
- const batch = batchFromColumns(columns, schema);
4032
- return serializeBatch(batch);
4178
+ if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
4179
+ return { kind: "constant", type: "DECIMAL" };
4180
+ return { kind: "constant", type: "DOUBLE" };
4033
4181
  }
4034
4182
 
4035
- // src/client/errors.ts
4036
- import { RpcError } from "@query-farm/vgi-rpc/connect";
4037
-
4038
- class VgiClientError extends Error {
4039
- remoteTraceback;
4040
- errorType;
4041
- constructor(message, options) {
4042
- super(message, options?.cause != null ? { cause: options.cause } : undefined);
4043
- this.name = "VgiClientError";
4044
- if (options?.remoteTraceback)
4045
- this.remoteTraceback = options.remoteTraceback;
4046
- if (options?.errorType)
4047
- this.errorType = options.errorType;
4183
+ class Parser {
4184
+ tokens;
4185
+ pos = 0;
4186
+ constructor(tokens) {
4187
+ this.tokens = tokens;
4188
+ }
4189
+ peek(offset = 0) {
4190
+ return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
4191
+ }
4192
+ next() {
4193
+ return this.tokens[this.pos++];
4194
+ }
4195
+ isOp(v, offset = 0) {
4196
+ const t = this.peek(offset);
4197
+ return t.t === "op" && t.v === v;
4198
+ }
4199
+ isWord(word, offset = 0) {
4200
+ const t = this.peek(offset);
4201
+ return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
4202
+ }
4203
+ expectOp(v) {
4204
+ if (!this.isOp(v))
4205
+ fail(`expected '${v}'`);
4206
+ this.pos++;
4207
+ }
4208
+ parseAll() {
4209
+ const node = this.expr();
4210
+ if (this.peek().t !== "end")
4211
+ fail("unexpected text after the expression");
4212
+ return node;
4213
+ }
4214
+ expr() {
4215
+ return this.or();
4216
+ }
4217
+ or() {
4218
+ let left = this.and();
4219
+ while (this.isWord("or")) {
4220
+ this.pos++;
4221
+ left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
4222
+ }
4223
+ return left;
4048
4224
  }
4049
- static fromRpcError(e) {
4050
- const head = `${e.errorType}: ${e.errorMessage}`;
4051
- const message = e.remoteTraceback ? `${head}
4052
-
4053
- Remote traceback:
4054
- ${e.remoteTraceback}` : head;
4055
- return new VgiClientError(message, {
4056
- remoteTraceback: e.remoteTraceback || undefined,
4057
- errorType: e.errorType,
4058
- cause: e
4059
- });
4225
+ and() {
4226
+ let left = this.not();
4227
+ while (this.isWord("and")) {
4228
+ this.pos++;
4229
+ left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
4230
+ }
4231
+ return left;
4060
4232
  }
4061
- }
4062
- function wrapRpcWithErrorEnrichment(rpc) {
4063
- return {
4064
- async call(method, params) {
4065
- try {
4066
- return await rpc.call(method, params);
4067
- } catch (e) {
4068
- if (e instanceof RpcError)
4069
- throw VgiClientError.fromRpcError(e);
4070
- throw e;
4233
+ not() {
4234
+ if (this.isWord("not")) {
4235
+ this.pos++;
4236
+ return { kind: "operator", op: "NOT", children: [this.not()] };
4237
+ }
4238
+ return this.is();
4239
+ }
4240
+ is() {
4241
+ let left = this.comparison();
4242
+ for (;; ) {
4243
+ if (this.isWord("isnull")) {
4244
+ this.pos++;
4245
+ left = { kind: "operator", op: "IS_NULL", children: [left] };
4246
+ continue;
4071
4247
  }
4072
- },
4073
- async stream(method, params) {
4074
- try {
4075
- return await rpc.stream(method, params);
4076
- } catch (e) {
4077
- if (e instanceof RpcError)
4078
- throw VgiClientError.fromRpcError(e);
4079
- throw e;
4248
+ if (this.isWord("notnull")) {
4249
+ this.pos++;
4250
+ left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
4251
+ continue;
4080
4252
  }
4081
- },
4082
- async callRaw(method, input) {
4083
- try {
4084
- return await rpc.callRaw(method, input);
4085
- } catch (e) {
4086
- if (e instanceof RpcError)
4087
- throw VgiClientError.fromRpcError(e);
4088
- throw e;
4253
+ if (this.isWord("is")) {
4254
+ this.pos++;
4255
+ const negated = this.isWord("not");
4256
+ if (negated)
4257
+ this.pos++;
4258
+ if (!this.isWord("null"))
4259
+ fail("only IS [NOT] NULL is supported");
4260
+ this.pos++;
4261
+ left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
4262
+ continue;
4089
4263
  }
4090
- },
4091
- async streamRaw(method, input, options) {
4092
- try {
4093
- return await rpc.streamRaw(method, input, options);
4094
- } catch (e) {
4095
- if (e instanceof RpcError)
4096
- throw VgiClientError.fromRpcError(e);
4097
- throw e;
4264
+ return left;
4265
+ }
4266
+ }
4267
+ comparison() {
4268
+ const left = this.otherOp();
4269
+ const t = this.peek();
4270
+ if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
4271
+ this.pos++;
4272
+ const right = this.otherOp();
4273
+ const next = this.peek();
4274
+ if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
4275
+ fail("chained comparisons are unsupported");
4276
+ return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
4277
+ }
4278
+ for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
4279
+ if (this.isWord(word))
4280
+ fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
4281
+ }
4282
+ return left;
4283
+ }
4284
+ otherOp() {
4285
+ let left = this.additive();
4286
+ for (;; ) {
4287
+ const t = this.peek();
4288
+ if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
4289
+ this.pos++;
4290
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
4291
+ continue;
4098
4292
  }
4099
- },
4100
- describe: () => rpc.describe(),
4101
- close: () => rpc.close()
4293
+ return left;
4294
+ }
4295
+ }
4296
+ additive() {
4297
+ let left = this.multiplicative();
4298
+ for (;; ) {
4299
+ const t = this.peek();
4300
+ if (t.t === "op" && (t.v === "+" || t.v === "-")) {
4301
+ this.pos++;
4302
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
4303
+ continue;
4304
+ }
4305
+ return left;
4306
+ }
4307
+ }
4308
+ multiplicative() {
4309
+ let left = this.power();
4310
+ for (;; ) {
4311
+ const t = this.peek();
4312
+ if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
4313
+ this.pos++;
4314
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
4315
+ continue;
4316
+ }
4317
+ return left;
4318
+ }
4319
+ }
4320
+ power() {
4321
+ let left = this.unary();
4322
+ while (this.isOp("^")) {
4323
+ this.pos++;
4324
+ left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
4325
+ }
4326
+ return left;
4327
+ }
4328
+ unary() {
4329
+ if (this.isOp("-") || this.isOp("+")) {
4330
+ const sign = this.next().v;
4331
+ const operand = this.unary();
4332
+ if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
4333
+ const folded = literalNumber(operand.text, !operand.negative);
4334
+ return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
4335
+ }
4336
+ return { kind: "function", name: sign, qualified: false, children: [operand] };
4337
+ }
4338
+ return this.postfix();
4339
+ }
4340
+ postfix() {
4341
+ let node = this.primary();
4342
+ for (;; ) {
4343
+ if (this.isOp("::")) {
4344
+ this.pos++;
4345
+ node = { kind: "cast", ...this.typeName(), child: node };
4346
+ continue;
4347
+ }
4348
+ if (this.isOp("["))
4349
+ fail("subscripts are unsupported");
4350
+ return node;
4351
+ }
4352
+ }
4353
+ typeName() {
4354
+ const t = this.next();
4355
+ if (t.t !== "ident")
4356
+ fail("expected a type name");
4357
+ const first = t.v.toLowerCase();
4358
+ let qualified = false;
4359
+ while (this.isOp(".")) {
4360
+ this.pos++;
4361
+ if (this.next().t !== "ident")
4362
+ fail("expected a type name");
4363
+ qualified = true;
4364
+ }
4365
+ let name = first;
4366
+ if (first === "double" && this.isWord("precision")) {
4367
+ this.pos++;
4368
+ name = "double";
4369
+ }
4370
+ if (first === "character" && this.isWord("varying")) {
4371
+ this.pos++;
4372
+ name = "varchar";
4373
+ }
4374
+ let params = [];
4375
+ if (this.isOp("(")) {
4376
+ this.pos++;
4377
+ for (;; ) {
4378
+ const p = this.next();
4379
+ if (p.t !== "num")
4380
+ fail("unsupported type parameter");
4381
+ params.push(p.v);
4382
+ if (this.isOp(",")) {
4383
+ this.pos++;
4384
+ continue;
4385
+ }
4386
+ break;
4387
+ }
4388
+ this.expectOp(")");
4389
+ }
4390
+ if (this.isOp("["))
4391
+ fail("array types are unsupported");
4392
+ let type = CAST_TYPES[name] ?? null;
4393
+ if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
4394
+ type = "DOUBLE";
4395
+ return { type, qualified };
4396
+ }
4397
+ primary() {
4398
+ const t = this.next();
4399
+ if (t.t === "num")
4400
+ return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
4401
+ if (t.t === "str") {
4402
+ if (this.peek().t === "str")
4403
+ fail("adjacent string literals are unsupported");
4404
+ return { kind: "constant", type: "VARCHAR" };
4405
+ }
4406
+ if (t.t === "op") {
4407
+ if (t.v === "(") {
4408
+ const inner = this.expr();
4409
+ if (this.isOp(","))
4410
+ fail("row constructors are unsupported");
4411
+ this.expectOp(")");
4412
+ return inner;
4413
+ }
4414
+ return fail(`unexpected '${t.v}'`);
4415
+ }
4416
+ if (t.t === "end")
4417
+ return fail("expected an expression");
4418
+ const word = t.v.toLowerCase();
4419
+ if (!t.quoted) {
4420
+ if (word === "null")
4421
+ return { kind: "constant", type: "NULL" };
4422
+ if (word === "true" || word === "false")
4423
+ return { kind: "constant", type: "BOOLEAN" };
4424
+ if (word === "cast" && this.isOp("(")) {
4425
+ this.pos++;
4426
+ const child = this.expr();
4427
+ if (!this.isWord("as"))
4428
+ fail("expected AS in CAST");
4429
+ this.pos++;
4430
+ const target = this.typeName();
4431
+ this.expectOp(")");
4432
+ return { kind: "cast", ...target, child };
4433
+ }
4434
+ if (word === "case")
4435
+ fail("CASE is outside the supported scalar grammar");
4436
+ if (RESERVED.has(word))
4437
+ fail(`unexpected keyword ${t.v.toUpperCase()}`);
4438
+ }
4439
+ const names = [t.v];
4440
+ while (this.isOp(".")) {
4441
+ this.pos++;
4442
+ const part = this.next();
4443
+ if (part.t !== "ident")
4444
+ fail("unsupported qualified name");
4445
+ names.push(part.v);
4446
+ }
4447
+ if (this.isOp("(")) {
4448
+ this.pos++;
4449
+ const children = [];
4450
+ if (this.isWord("distinct"))
4451
+ fail("DISTINCT function arguments are unsupported");
4452
+ if (!this.isOp(")")) {
4453
+ for (;; ) {
4454
+ if (this.isOp("*"))
4455
+ fail("star arguments are unsupported");
4456
+ if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
4457
+ fail("named scalar arguments are unsupported");
4458
+ children.push(this.expr());
4459
+ if (this.isOp(",")) {
4460
+ this.pos++;
4461
+ continue;
4462
+ }
4463
+ break;
4464
+ }
4465
+ }
4466
+ if (this.isWord("order"))
4467
+ fail("ordered function arguments are unsupported");
4468
+ this.expectOp(")");
4469
+ if (this.isWord("filter") || this.isWord("over"))
4470
+ fail("aggregate and window functions are unsupported");
4471
+ if (names.length === 1 && !t.quoted && word === "coalesce")
4472
+ return { kind: "operator", op: "COALESCE", children };
4473
+ return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
4474
+ }
4475
+ if (this.peek().t === "str")
4476
+ fail("typed literals are unsupported");
4477
+ return { kind: "column", names };
4478
+ }
4479
+ }
4480
+ function parseScalarSql(sql) {
4481
+ if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
4482
+ fail("invalid SQL size or text");
4483
+ return new Parser(tokenize(sql)).parseAll();
4484
+ }
4485
+ var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
4486
+ var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
4487
+ var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
4488
+ function validateColumnExpressionSql(sql, options) {
4489
+ const { usingColumns, generated } = options;
4490
+ const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
4491
+ const columns = [];
4492
+ let nodes = 0;
4493
+ const visit = (node, depth) => {
4494
+ if (depth > 64 || ++nodes > 4096)
4495
+ fail("scalar expression is too complex");
4496
+ switch (node.kind) {
4497
+ case "constant":
4498
+ if (!primitive.has(node.type))
4499
+ fail(`unsupported scalar literal type ${node.type}`);
4500
+ return;
4501
+ case "column":
4502
+ if (!usingColumns || node.names.length !== 1)
4503
+ fail("column references are unsupported in this scope");
4504
+ columns.push(node.names[0]);
4505
+ return;
4506
+ case "cast":
4507
+ if (node.qualified)
4508
+ fail("qualified scalar cast types are unsupported");
4509
+ if (node.type === null || !primitive.has(node.type))
4510
+ fail("unsupported scalar cast");
4511
+ visit(node.child, depth + 1);
4512
+ return;
4513
+ case "comparison":
4514
+ visit(node.left, depth + 1);
4515
+ visit(node.right, depth + 1);
4516
+ return;
4517
+ case "conjunction":
4518
+ case "operator":
4519
+ node.children.forEach((c) => visit(c, depth + 1));
4520
+ return;
4521
+ case "function": {
4522
+ const lower = node.name.toLowerCase();
4523
+ const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
4524
+ if (!ok)
4525
+ fail(`unsupported scalar function '${node.name}'`);
4526
+ node.children.forEach((c) => visit(c, depth + 1));
4527
+ return;
4528
+ }
4529
+ }
4102
4530
  };
4531
+ try {
4532
+ visit(parseScalarSql(sql), 0);
4533
+ } catch (error) {
4534
+ if (error instanceof GrammarError)
4535
+ throw error;
4536
+ throw new GrammarError(String(error?.message ?? error));
4537
+ }
4538
+ return columns;
4539
+ }
4540
+ function validateNumericCheckSql(sql, resolveColumn) {
4541
+ const node = parseScalarSql(sql);
4542
+ if (node.kind !== "comparison")
4543
+ fail("native CHECK read supports only Boolean numeric comparisons");
4544
+ const comparison = node;
4545
+ for (const operand of [comparison.left, comparison.right]) {
4546
+ if (operand.kind === "constant") {
4547
+ if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
4548
+ fail("CHECK requires numeric operands");
4549
+ continue;
4550
+ }
4551
+ if (operand.kind !== "column")
4552
+ fail("native CHECK read supports only numeric column/constant comparisons");
4553
+ const column = operand;
4554
+ if (column.names.length !== 1)
4555
+ fail("CHECK requires unqualified column references");
4556
+ resolveColumn(column.names[0]);
4557
+ }
4558
+ }
4559
+
4560
+ // src/catalog/column-types.ts
4561
+ function isRowIdField(field) {
4562
+ return field.metadata?.has("is_row_id") ?? false;
4563
+ }
4564
+ function hasLogicalType(field) {
4565
+ for (const key of field.metadata?.keys() ?? [])
4566
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
4567
+ return true;
4568
+ return false;
4569
+ }
4570
+ function ordinaryStructChildren(field) {
4571
+ if (!isStruct(field.type) || hasLogicalType(field))
4572
+ return null;
4573
+ return field.type.children;
4574
+ }
4575
+ function isGeneratedField(field) {
4576
+ const m = field.metadata;
4577
+ return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
4578
+ }
4579
+ function duckdbPrimitive(field) {
4580
+ if (hasLogicalType(field))
4581
+ return null;
4582
+ const t = field.type;
4583
+ switch (t.typeId) {
4584
+ case TypeId.Bool:
4585
+ return "BOOLEAN";
4586
+ case TypeId.Utf8:
4587
+ return "VARCHAR";
4588
+ case TypeId.Int: {
4589
+ if (!(t.isSigned ?? t.signed ?? true))
4590
+ return null;
4591
+ return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
4592
+ }
4593
+ case TypeId.Float:
4594
+ return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
4595
+ case TypeId.Decimal:
4596
+ return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
4597
+ default:
4598
+ return null;
4599
+ }
4103
4600
  }
4104
4601
 
4105
4602
  // src/catalog/column-expressions.ts
4106
4603
  var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
4107
4604
  var GENERATION_KEY = "vgi.column.generation.v1";
4605
+ var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
4606
+ var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
4607
+ var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
4108
4608
  var PROFILE = "vgi.expression.duckdb.scalar.v1";
4109
4609
  var MAX_BYTES = 8 * 1024 * 1024;
4110
4610
  var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
@@ -4215,7 +4715,38 @@ function validateEncoded(encoded, owner) {
4215
4715
  throw new Error("invalid SqlExpression record schema");
4216
4716
  const utf8 = new TextDecoder("utf-8", { fatal: true });
4217
4717
  textBuffers.forEach((buffer) => utf8.decode(buffer));
4218
- expression(decodeSqlExpression(bytes), owner);
4718
+ const value = decodeSqlExpression(bytes);
4719
+ expression(value, owner);
4720
+ return value.sql;
4721
+ }
4722
+ function generatedExpressionMetadata(sql, owner) {
4723
+ try {
4724
+ validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
4725
+ } catch (error) {
4726
+ throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
4727
+ }
4728
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
4729
+ }
4730
+ function defaultExpressionMetadata(sql, owner) {
4731
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
4732
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
4733
+ }
4734
+ function sqlExpression(sql, schemaPath) {
4735
+ const owner = [...schemaPath];
4736
+ const value = {
4737
+ sql,
4738
+ profile: PROFILE,
4739
+ schema_path: [...owner],
4740
+ evaluation_context: {
4741
+ timezone: "UTC",
4742
+ collation: "binary",
4743
+ default_order: "asc",
4744
+ default_null_order: "nulls_last",
4745
+ preserve_insertion_order: true
4746
+ }
4747
+ };
4748
+ expression(value, owner);
4749
+ return value;
4219
4750
  }
4220
4751
  function validateColumnExpressions(schema, owner, allowGenerated = true) {
4221
4752
  const type = (t) => {
@@ -4224,14 +4755,33 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
4224
4755
  if (t?.dictionary)
4225
4756
  type(t.dictionary);
4226
4757
  };
4227
- const field = (f) => {
4758
+ const topLevel = new Map;
4759
+ for (const f of schema.fields) {
4760
+ const key = String(f.name).toLowerCase();
4761
+ topLevel.set(key, [...topLevel.get(key) ?? [], f]);
4762
+ }
4763
+ const field = (f, top = false) => {
4228
4764
  const metadata = f.metadata ?? new Map;
4229
4765
  for (const key of metadata.keys()) {
4230
4766
  if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
4231
4767
  throw new Error("unknown generated metadata version");
4232
4768
  }
4769
+ const where = `column ${f.name}`;
4233
4770
  if (metadata.has("generated_expression"))
4234
- throw new Error("legacy generated expression requires explicit canonical translation");
4771
+ throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
4772
+ if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
4773
+ if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
4774
+ throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
4775
+ const type = duckdbPrimitive(f);
4776
+ if (!type || !DEFAULT_TYPES.has(type))
4777
+ throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
4778
+ const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
4779
+ try {
4780
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
4781
+ } catch (error) {
4782
+ throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
4783
+ }
4784
+ }
4235
4785
  if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
4236
4786
  throw new Error("generated expression and category must occur together");
4237
4787
  if (metadata.has(GENERATED_EXPRESSION_KEY)) {
@@ -4239,18 +4789,648 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
4239
4789
  throw new Error("only VIRTUAL generated columns are supported");
4240
4790
  if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
4241
4791
  throw new Error("generated column cannot have a default");
4242
- validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
4792
+ const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
4243
4793
  if (!allowGenerated)
4244
4794
  throw new Error("generated columns unsupported by this catalog");
4795
+ if (!f.nullable)
4796
+ throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
4797
+ const type = duckdbPrimitive(f);
4798
+ if (!type || !GENERATED_TYPES.has(type))
4799
+ throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
4800
+ let references;
4801
+ try {
4802
+ references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
4803
+ } catch (error) {
4804
+ throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
4805
+ }
4806
+ if (top) {
4807
+ for (const name of references) {
4808
+ const matches = topLevel.get(name.toLowerCase()) ?? [];
4809
+ if (matches.length !== 1)
4810
+ throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
4811
+ const operand = duckdbPrimitive(matches[0]);
4812
+ if (!operand || !GENERATED_TYPES.has(operand))
4813
+ throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
4814
+ }
4815
+ }
4245
4816
  }
4246
4817
  type(f.type);
4247
4818
  };
4248
- schema.fields.forEach(field);
4819
+ schema.fields.forEach((f) => field(f, true));
4249
4820
  }
4250
4821
  function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
4251
4822
  validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
4252
4823
  }
4253
4824
 
4825
+ // src/catalog/constraints.ts
4826
+ var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
4827
+ var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
4828
+ var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
4829
+ var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
4830
+ var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
4831
+ var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
4832
+ var CHECK_CONTEXT = {
4833
+ timezone: "UTC",
4834
+ collation: "binary",
4835
+ default_order: "asc",
4836
+ default_null_order: "nulls_last",
4837
+ preserve_insertion_order: true
4838
+ };
4839
+ function identifier(value, what) {
4840
+ if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
4841
+ throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
4842
+ }
4843
+ function objectRef(kind, schemaPath, name, ownerTable) {
4844
+ return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
4845
+ }
4846
+ function checkPaths(paths, what, topLevelOnly) {
4847
+ if (paths.length > 1024)
4848
+ throw new Error(`${what}: too many column paths`);
4849
+ const seen = new Set;
4850
+ for (const path of paths) {
4851
+ if (path.length === 0 || path.length > 64)
4852
+ throw new Error(`${what}: column path must have 1..64 components`);
4853
+ if (topLevelOnly && path.length !== 1)
4854
+ throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
4855
+ path.forEach((part) => identifier(part, `${what}: column path component`));
4856
+ const key = JSON.stringify(path);
4857
+ if (seen.has(key))
4858
+ throw new Error(`${what}: duplicate column path ${path.join(".")}`);
4859
+ seen.add(key);
4860
+ }
4861
+ }
4862
+ function constraintRecord(spec) {
4863
+ const what = `constraint '${spec.id}' on '${spec.table}'`;
4864
+ if (!spec.id || spec.id.includes("\x00"))
4865
+ throw new Error("constraint id must be nonempty without NUL");
4866
+ identifier(spec.table, "table");
4867
+ if (spec.schemaPath.length !== 1)
4868
+ throw new Error(`${what}: DuckDB reads only one-component schema paths`);
4869
+ identifier(spec.schemaPath[0], "schema");
4870
+ if (spec.enforcement !== "ENFORCED" || spec.validation !== "ALL_ROWS")
4871
+ throw new Error(`${what} is ${spec.enforcement}/${spec.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
4872
+ if (spec.declaredName !== undefined)
4873
+ identifier(spec.declaredName, `${what}: declaredName`);
4874
+ if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
4875
+ throw new Error("checkSql is required for CHECK and only CHECK");
4876
+ if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
4877
+ throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
4878
+ if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
4879
+ throw new Error("NOT_NULL requires exactly one column path");
4880
+ if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
4881
+ throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
4882
+ checkPaths(spec.columns, what, spec.kind !== "NOT_NULL");
4883
+ if (spec.checkSql !== undefined) {
4884
+ try {
4885
+ validateNumericCheckSql(spec.checkSql, () => {});
4886
+ } catch (error) {
4887
+ throw new Error(`${what}: ${error.message} (CHECK SQL: ${spec.checkSql})`);
4888
+ }
4889
+ }
4890
+ const ref = spec.references;
4891
+ if (ref) {
4892
+ if (ref.columns.length !== spec.columns.length)
4893
+ throw new Error("foreign key local and referenced arity must match");
4894
+ if (JSON.stringify(ref.schemaPath) !== JSON.stringify(spec.schemaPath))
4895
+ throw new Error(`${what}: DuckDB reads only foreign keys to a table in the same schema`);
4896
+ identifier(ref.table, `${what}: referenced table`);
4897
+ identifier(ref.constraintId, `${what}: referenced constraintId`);
4898
+ checkPaths(ref.columns, `${what} (referenced)`, true);
4899
+ }
4900
+ const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
4901
+ sql: spec.checkSql,
4902
+ profile: ROW_SCALAR_EXPRESSION,
4903
+ schema_path: spec.schemaPath,
4904
+ evaluation_context: CHECK_CONTEXT
4905
+ });
4906
+ const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
4907
+ referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
4908
+ referenced_column_paths: ref.columns,
4909
+ match: "SIMPLE",
4910
+ on_update: "NO_ACTION",
4911
+ on_delete: "NO_ACTION"
4912
+ });
4913
+ return encodeASD(ConstraintInfoSchema, {
4914
+ ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
4915
+ definition: encodeASD(ConstraintDefinitionSchema, {
4916
+ kind: spec.kind,
4917
+ column_paths: spec.columns,
4918
+ declared_name: spec.declaredName ?? null,
4919
+ check_expression: check,
4920
+ foreign_key: foreign
4921
+ }),
4922
+ enforcement: spec.enforcement,
4923
+ validation: spec.validation,
4924
+ referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
4925
+ });
4926
+ }
4927
+ var KNOWN = {
4928
+ read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
4929
+ ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
4930
+ write: new Set([CONSTRAINT_ENFORCE]),
4931
+ transaction: new Set([TRANSACTION_DDL])
4932
+ };
4933
+ var REQUIRES = {
4934
+ [ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
4935
+ [CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
4936
+ [CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
4937
+ [CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
4938
+ "vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
4939
+ "vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
4940
+ };
4941
+ var CATEGORIES = ["read", "ddl", "write", "transaction"];
4942
+ function catalogCapabilities(init = {}) {
4943
+ return {
4944
+ read: [...new Set(init.read ?? [])].sort(),
4945
+ ddl: [...new Set(init.ddl ?? [])].sort(),
4946
+ write: [...new Set(init.write ?? [])].sort(),
4947
+ transaction: [...new Set(init.transaction ?? [])].sort()
4948
+ };
4949
+ }
4950
+ function constraintCapabilities(options = {}) {
4951
+ const enforce = options.enforce || options.create;
4952
+ return catalogCapabilities({
4953
+ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION],
4954
+ ddl: [...options.create ? [CONSTRAINT_CREATE] : [], ...options.mutate ? [CONSTRAINT_MUTATE] : []],
4955
+ write: enforce ? [CONSTRAINT_ENFORCE] : [],
4956
+ transaction: options.transactionDdl ? [TRANSACTION_DDL] : []
4957
+ });
4958
+ }
4959
+ function offeredCatalog(clientCapabilities) {
4960
+ if (clientCapabilities == null)
4961
+ return null;
4962
+ const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
4963
+ return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
4964
+ }
4965
+ function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
4966
+ const offered = offeredCatalog(clientCapabilities);
4967
+ if (offered == null)
4968
+ return catalogCapabilities();
4969
+ const chosen = new Set;
4970
+ for (const category of CATEGORIES)
4971
+ for (const p of available[category] ?? [])
4972
+ if (offered[category]?.includes(p))
4973
+ chosen.add(p);
4974
+ if (!supportsTransactions)
4975
+ chosen.delete(TRANSACTION_DDL);
4976
+ for (let changed = true;changed; ) {
4977
+ changed = false;
4978
+ for (const p of [...chosen])
4979
+ if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
4980
+ chosen.delete(p);
4981
+ changed = true;
4982
+ }
4983
+ }
4984
+ const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
4985
+ return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
4986
+ }
4987
+ function selectReadProfiles(available, clientCapabilities) {
4988
+ return selectCatalogCapabilities(catalogCapabilities({ read: [...available] }), clientCapabilities).read;
4989
+ }
4990
+ function defaultClientCapabilities(engine = "vgi-typescript") {
4991
+ return {
4992
+ engine,
4993
+ native_formats: [],
4994
+ catalogs: [],
4995
+ can_stream: true,
4996
+ filter_encodings: [],
4997
+ catalog: encodeCatalogCapabilities(catalogCapabilities({ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] })),
4998
+ query_pushdown: null
4999
+ };
5000
+ }
5001
+ function readConstraintRecord(bytes) {
5002
+ const info = decodeASD(ConstraintInfoSchema, bytes);
5003
+ const ref = decodeASD(CatalogObjectRefSchema, info.ref);
5004
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
5005
+ const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
5006
+ const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
5007
+ const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
5008
+ return {
5009
+ schemaPath: [...ref.schema_path],
5010
+ table: ref.owner_table ?? "",
5011
+ id: ref.name,
5012
+ kind: def.kind,
5013
+ columns: [...def.column_paths].map((p) => [...p]),
5014
+ enforcement: info.enforcement,
5015
+ validation: info.validation,
5016
+ declaredName: def.declared_name ?? null,
5017
+ checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
5018
+ references: fk == null || target == null ? null : {
5019
+ schemaPath: [...target.schema_path],
5020
+ table: target.name,
5021
+ columns: [...fk.referenced_column_paths].map((p) => [...p]),
5022
+ constraintId: targetKey?.name ?? null,
5023
+ constraintTable: targetKey?.owner_table ?? null,
5024
+ constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
5025
+ match: fk.match,
5026
+ onUpdate: fk.on_update,
5027
+ onDelete: fk.on_delete
5028
+ }
5029
+ };
5030
+ }
5031
+ function fieldsByExactName(fields, name) {
5032
+ const out = [];
5033
+ fields.forEach((f, i) => {
5034
+ if (f.name === name)
5035
+ out.push(i);
5036
+ });
5037
+ return out;
5038
+ }
5039
+ function validateTableConstraints(table, schemaPath, fields, constraints) {
5040
+ if (constraints.length > 1024)
5041
+ throw new Error(`Table '${table}': too many constraints (at most 1024)`);
5042
+ const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
5043
+ if (rowIds.length > 1)
5044
+ throw new Error(`Table '${table}': at most one column may carry is_row_id`);
5045
+ const rowId = rowIds[0] ?? -1;
5046
+ const records = [];
5047
+ const required = new Set;
5048
+ const ids = new Set;
5049
+ const labels = new Set;
5050
+ let primaryKeys = 0;
5051
+ for (const bytes of constraints) {
5052
+ let record;
5053
+ try {
5054
+ record = readConstraintRecord(bytes);
5055
+ } catch (error) {
5056
+ throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
5057
+ }
5058
+ const where = `Table '${table}': constraint '${record.id}'`;
5059
+ const fail = (message) => {
5060
+ throw new Error(`${where}: ${message}`);
5061
+ };
5062
+ if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
5063
+ fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
5064
+ if (ids.has(record.id))
5065
+ fail("duplicate constraint id");
5066
+ ids.add(record.id);
5067
+ if (record.declaredName != null) {
5068
+ const label = record.declaredName.toLowerCase();
5069
+ if (labels.has(label))
5070
+ fail(`duplicate declared name '${record.declaredName}'`);
5071
+ labels.add(label);
5072
+ }
5073
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
5074
+ fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
5075
+ try {
5076
+ checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
5077
+ } catch (error) {
5078
+ fail(error.message);
5079
+ }
5080
+ const resolveTop = (path) => {
5081
+ const matches = fieldsByExactName(fields, path[0]);
5082
+ if (matches.length !== 1 || matches[0] === rowId)
5083
+ fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
5084
+ return matches[0];
5085
+ };
5086
+ switch (record.kind) {
5087
+ case "CHECK": {
5088
+ if (record.checkSql == null)
5089
+ fail("CHECK without an expression");
5090
+ validateCheckRecord(bytes, where, schemaPath, fields, rowId);
5091
+ break;
5092
+ }
5093
+ case "NOT_NULL": {
5094
+ if (record.columns.length !== 1)
5095
+ fail("NOT_NULL requires exactly one column path");
5096
+ const path = record.columns[0];
5097
+ let field = fields[resolveTop(path)];
5098
+ for (let depth = 1;depth < path.length; depth++) {
5099
+ const children = ordinaryStructChildren(field);
5100
+ if (!children)
5101
+ fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
5102
+ const matches = fieldsByExactName(children, path[depth]);
5103
+ if (matches.length !== 1)
5104
+ fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
5105
+ field = children[matches[0]];
5106
+ }
5107
+ if (path.length === 1 && isGeneratedField(field))
5108
+ fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
5109
+ required.add(JSON.stringify(path));
5110
+ break;
5111
+ }
5112
+ case "PRIMARY_KEY":
5113
+ case "UNIQUE": {
5114
+ for (const path of record.columns) {
5115
+ const index = resolveTop(path);
5116
+ if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
5117
+ fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
5118
+ }
5119
+ if (record.kind === "PRIMARY_KEY") {
5120
+ if (++primaryKeys > 1)
5121
+ fail("a table may have only one PRIMARY KEY");
5122
+ for (const path of record.columns)
5123
+ required.add(JSON.stringify(path));
5124
+ }
5125
+ break;
5126
+ }
5127
+ case "FOREIGN_KEY": {
5128
+ record.columns.forEach(resolveTop);
5129
+ const ref = record.references;
5130
+ if (ref == null || ref.constraintId == null)
5131
+ fail("FOREIGN_KEY requires a referenced table and referenced constraint");
5132
+ if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
5133
+ fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
5134
+ if (ref.columns.length !== record.columns.length)
5135
+ fail("foreign key arity mismatch");
5136
+ try {
5137
+ checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
5138
+ } catch (error) {
5139
+ fail(error.message);
5140
+ }
5141
+ if (ref.match !== undefined && ref.match !== "SIMPLE")
5142
+ fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
5143
+ for (const action of [ref.onUpdate, ref.onDelete])
5144
+ if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
5145
+ fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
5146
+ break;
5147
+ }
5148
+ default:
5149
+ fail(`unknown constraint kind ${String(record.kind)}`);
5150
+ }
5151
+ records.push(record);
5152
+ }
5153
+ return { records, required };
5154
+ }
5155
+ function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
5156
+ const info = decodeASD(ConstraintInfoSchema, bytes);
5157
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
5158
+ const expression = decodeASD(SqlExpressionSchema, def.check_expression);
5159
+ const fail = (message) => {
5160
+ throw new Error(`${where}: ${message}`);
5161
+ };
5162
+ if (expression.profile !== ROW_SCALAR_EXPRESSION)
5163
+ fail(`unsupported CHECK expression profile ${expression.profile}`);
5164
+ if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
5165
+ fail("CHECK expression belongs to another schema");
5166
+ const context = expression.evaluation_context ?? {};
5167
+ for (const [key, value] of Object.entries(CHECK_CONTEXT))
5168
+ if (context[key] !== value)
5169
+ fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
5170
+ try {
5171
+ validateNumericCheckSql(expression.sql, (name) => {
5172
+ const lower = name.toLowerCase();
5173
+ const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
5174
+ if (matches.length > 1)
5175
+ throw new Error(`ambiguous CHECK column reference ${name}`);
5176
+ if (matches.length === 0 || matches[0] === rowId)
5177
+ throw new Error(`CHECK references a missing or row-id column ${name}`);
5178
+ const column = fields[matches[0]];
5179
+ if (column.metadata.has("ARROW:extension:name"))
5180
+ throw new Error(`CHECK operand ${name} has an extension type`);
5181
+ if (isGeneratedField(column))
5182
+ throw new Error(`CHECK operand ${name} is a generated column`);
5183
+ const type = duckdbPrimitive(column);
5184
+ if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
5185
+ throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
5186
+ });
5187
+ } catch (error) {
5188
+ fail(`${error.message} (CHECK SQL: ${expression.sql})`);
5189
+ }
5190
+ }
5191
+ function validateForeignKeyTargets(tables) {
5192
+ const key = (schemaPath, name) => JSON.stringify([...schemaPath, name]);
5193
+ const byTable = new Map;
5194
+ for (const t of tables)
5195
+ byTable.set(key(t.schemaPath, t.name), t.constraints.map(readConstraintRecord));
5196
+ for (const t of tables) {
5197
+ for (const record of byTable.get(key(t.schemaPath, t.name)) ?? []) {
5198
+ if (record.kind !== "FOREIGN_KEY" || record.references == null)
5199
+ continue;
5200
+ const ref = record.references;
5201
+ const where = `Table '${t.name}': constraint '${record.id}'`;
5202
+ const target = byTable.get(key(ref.schemaPath, ref.table));
5203
+ if (!target)
5204
+ throw new Error(`${where}: references table ${[...ref.schemaPath, ref.table].join(".")}, which this catalog does not serve`);
5205
+ const key_ = target.find((r) => r.id === ref.constraintId);
5206
+ if (!key_ || key_.kind !== "PRIMARY_KEY" && key_.kind !== "UNIQUE")
5207
+ throw new Error(`${where}: referenced constraint '${ref.constraintId}' is not a PRIMARY_KEY or UNIQUE record of '${ref.table}'`);
5208
+ const want = new Set(ref.columns.map((p) => JSON.stringify(p)));
5209
+ if (key_.columns.length !== want.size || !key_.columns.every((p) => want.has(JSON.stringify(p))))
5210
+ throw new Error(`${where}: referenced columns do not match constraint '${ref.constraintId}' of '${ref.table}'`);
5211
+ }
5212
+ }
5213
+ }
5214
+ function servedConstraintFields(fields, required) {
5215
+ const rewrite = (list, prefix) => {
5216
+ let changed = false;
5217
+ const out = list.map((f) => {
5218
+ if (prefix.length === 0 && isRowIdField(f))
5219
+ return f;
5220
+ const path = [...prefix, f.name];
5221
+ const nullable = !required.has(JSON.stringify(path));
5222
+ const children = ordinaryStructChildren(f);
5223
+ const newChildren = children ? rewrite(children, path) : null;
5224
+ if (nullable === f.nullable && (newChildren == null || newChildren === children))
5225
+ return f;
5226
+ changed = true;
5227
+ const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
5228
+ return field2(f.name, type, nullable, new Map(f.metadata));
5229
+ });
5230
+ return changed ? out : list;
5231
+ };
5232
+ return rewrite(fields, []);
5233
+ }
5234
+ function validateConstraintNullability(table, fields, constraints) {
5235
+ const schemaPath = constraints.length ? readConstraintRecord(constraints[0]).schemaPath : ["main"];
5236
+ validateTableConstraints(table, schemaPath, fields, constraints);
5237
+ }
5238
+ function translateLegacyGenerated(fields, owner, table) {
5239
+ let changed = false;
5240
+ const out = fields.map((f) => {
5241
+ const sql = f.metadata.get("generated_expression");
5242
+ if (sql === undefined)
5243
+ return f;
5244
+ if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
5245
+ throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
5246
+ const metadata = new Map(f.metadata);
5247
+ metadata.delete("generated_expression");
5248
+ metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
5249
+ metadata.set(GENERATION_KEY, "virtual");
5250
+ changed = true;
5251
+ return field2(f.name, f.type, f.nullable, metadata);
5252
+ });
5253
+ return changed ? out : fields;
5254
+ }
5255
+ function servedTableSchema(table, schemaPath, schema, constraints) {
5256
+ let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
5257
+ const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
5258
+ fields = servedConstraintFields(fields, required);
5259
+ return fields === schema.fields ? schema : schema2(fields, schema.metadata);
5260
+ }
5261
+ function servedTableInfo(info) {
5262
+ if (!info.columns || info.columns.length === 0) {
5263
+ if ((info.constraints ?? []).length)
5264
+ throw new Error(`Table '${info.name}': constraints on a table without columns`);
5265
+ return info;
5266
+ }
5267
+ const schema = deserializeSchema(info.columns);
5268
+ const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
5269
+ return served === schema ? info : { ...info, columns: serializeSchema(served) };
5270
+ }
5271
+
5272
+ // src/generated/vgi-client.ts
5273
+ var decodeCatalogInfo = (b) => decodeASD(CatalogInfoSchema, b);
5274
+ var encodeFunctionInfo = (v) => encodeASD(FunctionInfoSchema, v);
5275
+ var decodeFunctionInfo = (b) => decodeASD(FunctionInfoSchema, b);
5276
+ var decodeIndexInfo = (b) => decodeASD(IndexInfoSchema, b);
5277
+ var encodeMacroInfo = (v) => encodeASD(MacroInfoSchema, v);
5278
+ var decodeMacroInfo = (b) => decodeASD(MacroInfoSchema, b);
5279
+ var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
5280
+ var decodeSchemaInfo = (b) => decodeASD(SchemaInfoSchema, b);
5281
+ var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
5282
+ var decodeTableInfo = (b) => decodeASD(TableInfoSchema, b);
5283
+ var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
5284
+ var decodeViewInfo = (b) => decodeASD(ViewInfoSchema, b);
5285
+ // src/catalog/interface.ts
5286
+ function decodeScanFunctionResult(inner) {
5287
+ const argsBytes = inner.arguments;
5288
+ const positionalArguments = [];
5289
+ const namedArguments = {};
5290
+ if (argsBytes != null) {
5291
+ const batch = deserializeBatch(toUint8Array(argsBytes));
5292
+ for (const field of batch.schema.fields) {
5293
+ const col = batch.getChild(field.name);
5294
+ const value = col ? col.get(0) : null;
5295
+ if (field.name.startsWith("arg_")) {
5296
+ const idx = parseInt(field.name.slice(4), 10);
5297
+ while (positionalArguments.length <= idx)
5298
+ positionalArguments.push(null);
5299
+ positionalArguments[idx] = value;
5300
+ } else {
5301
+ namedArguments[field.name] = value;
5302
+ }
5303
+ }
5304
+ }
5305
+ const exts = inner.required_extensions;
5306
+ const requiredExtensions = exts == null ? [] : (Array.isArray(exts) ? exts : [...exts]).filter((v) => v != null).map(String);
5307
+ return {
5308
+ functionName: String(inner.function_name ?? ""),
5309
+ positionalArguments,
5310
+ namedArguments,
5311
+ requiredExtensions,
5312
+ schemaPath: inner.schema_path == null ? null : (Array.isArray(inner.schema_path) ? inner.schema_path : [...inner.schema_path]).filter((value) => value != null).map(String)
5313
+ };
5314
+ }
5315
+
5316
+ // src/client/protocol.ts
5317
+ function wrapRequest(batch) {
5318
+ return { request: serializeBatch(batch) };
5319
+ }
5320
+ function unwrapResult(result) {
5321
+ const resultBytes = toUint8Array(result.result);
5322
+ const innerBatch = deserializeBatch(resultBytes);
5323
+ return batchToScalarDict(innerBatch);
5324
+ }
5325
+
5326
+ // src/catalog/attach-options.ts
5327
+ function inferAttachOptionArrowType(value) {
5328
+ if (value === null)
5329
+ return nullType2();
5330
+ if (typeof value === "string")
5331
+ return utf82();
5332
+ if (typeof value === "bigint")
5333
+ return int642();
5334
+ if (typeof value === "number") {
5335
+ if (!Number.isFinite(value)) {
5336
+ throw new TypeError(`Attach option number values must be finite (got ${value}). ` + `Use a bigint for integers or a finite number for floats.`);
5337
+ }
5338
+ return float642();
5339
+ }
5340
+ if (typeof value === "boolean")
5341
+ return bool2();
5342
+ if (value instanceof Uint8Array)
5343
+ return binary2();
5344
+ throw new TypeError(`Unsupported attach option value type: ${typeof value}. ` + `Supported: string, number, bigint, boolean, null, Uint8Array.`);
5345
+ }
5346
+ function serializeAttachOptions(options) {
5347
+ if (!options)
5348
+ return null;
5349
+ const entries = Object.entries(options);
5350
+ if (entries.length === 0)
5351
+ return null;
5352
+ const fields = [];
5353
+ const columns = {};
5354
+ for (const [key, value] of entries) {
5355
+ const type = inferAttachOptionArrowType(value);
5356
+ fields.push(field2(key, type, true));
5357
+ columns[key] = [value];
5358
+ }
5359
+ const schema = schema2(fields);
5360
+ const batch = batchFromColumns(columns, schema);
5361
+ return serializeBatch(batch);
5362
+ }
5363
+
5364
+ // src/client/errors.ts
5365
+ import { RpcError } from "@query-farm/vgi-rpc/connect";
5366
+
5367
+ class VgiClientError extends Error {
5368
+ remoteTraceback;
5369
+ errorType;
5370
+ constructor(message, options) {
5371
+ super(message, options?.cause != null ? { cause: options.cause } : undefined);
5372
+ this.name = "VgiClientError";
5373
+ if (options?.remoteTraceback)
5374
+ this.remoteTraceback = options.remoteTraceback;
5375
+ if (options?.errorType)
5376
+ this.errorType = options.errorType;
5377
+ }
5378
+ static fromRpcError(e) {
5379
+ const head = `${e.errorType}: ${e.errorMessage}`;
5380
+ const message = e.remoteTraceback ? `${head}
5381
+
5382
+ Remote traceback:
5383
+ ${e.remoteTraceback}` : head;
5384
+ return new VgiClientError(message, {
5385
+ remoteTraceback: e.remoteTraceback || undefined,
5386
+ errorType: e.errorType,
5387
+ cause: e
5388
+ });
5389
+ }
5390
+ }
5391
+ function wrapRpcWithErrorEnrichment(rpc) {
5392
+ return {
5393
+ async call(method, params) {
5394
+ try {
5395
+ return await rpc.call(method, params);
5396
+ } catch (e) {
5397
+ if (e instanceof RpcError)
5398
+ throw VgiClientError.fromRpcError(e);
5399
+ throw e;
5400
+ }
5401
+ },
5402
+ async stream(method, params) {
5403
+ try {
5404
+ return await rpc.stream(method, params);
5405
+ } catch (e) {
5406
+ if (e instanceof RpcError)
5407
+ throw VgiClientError.fromRpcError(e);
5408
+ throw e;
5409
+ }
5410
+ },
5411
+ async callRaw(method, input) {
5412
+ try {
5413
+ return await rpc.callRaw(method, input);
5414
+ } catch (e) {
5415
+ if (e instanceof RpcError)
5416
+ throw VgiClientError.fromRpcError(e);
5417
+ throw e;
5418
+ }
5419
+ },
5420
+ async streamRaw(method, input, options) {
5421
+ try {
5422
+ return await rpc.streamRaw(method, input, options);
5423
+ } catch (e) {
5424
+ if (e instanceof RpcError)
5425
+ throw VgiClientError.fromRpcError(e);
5426
+ throw e;
5427
+ }
5428
+ },
5429
+ describe: () => rpc.describe(),
5430
+ close: () => rpc.close()
5431
+ };
5432
+ }
5433
+
4254
5434
  // src/catalog/column-metadata.ts
4255
5435
  function scalarText(value) {
4256
5436
  for (let i = 0;i < value.length; i++) {
@@ -4831,7 +6011,7 @@ class VgiClient {
4831
6011
  options: [wireOptions],
4832
6012
  data_version_spec: [opts?.dataVersionSpec ?? null],
4833
6013
  implementation_version: [opts?.implementationVersion ?? null],
4834
- client_capabilities: [opts?.clientCapabilities ? encodeASD(ClientCapabilitiesSchema, opts.clientCapabilities) : null]
6014
+ client_capabilities: [opts?.clientCapabilities === null ? null : encodeASD(ClientCapabilitiesSchema, opts?.clientCapabilities ?? defaultClientCapabilities("vgi-typescript-client"))]
4835
6015
  }, schema);
4836
6016
  const result = await this.rpc.call("catalog_attach", wrapRequest(innerBatch));
4837
6017
  if (!result)
@@ -5477,6 +6657,29 @@ function schemaToArgumentSpecs(schema) {
5477
6657
  }
5478
6658
  return specs;
5479
6659
  }
6660
+ // src/catalog/indexes.ts
6661
+ var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
6662
+ function emptyIndexOptions() {
6663
+ return Uint8Array.from(atob(NO_OPTIONS_B64), (c) => c.charCodeAt(0));
6664
+ }
6665
+ function canonicalIndex(spec) {
6666
+ if (spec.columns.length === 0)
6667
+ throw new Error(`index on '${spec.table}' requires at least one key`);
6668
+ if (!spec.algorithm)
6669
+ throw new Error("index algorithm must be nonempty");
6670
+ const values = spec.options ?? emptyIndexOptions();
6671
+ return {
6672
+ definition: encodeASD(IndexDefinitionSchema, {
6673
+ table: encodeASD(CatalogObjectRefSchema, { kind: "table", schema_path: spec.schemaPath, name: spec.table, owner_table: null }),
6674
+ algorithm: spec.algorithm,
6675
+ keys: spec.columns.map((path) => encodeASD(IndexKeySchema, { column_path: path, expression: null })),
6676
+ options: values,
6677
+ constraint_type: spec.constraintType ?? "NONE",
6678
+ associated_constraint: spec.associatedConstraintId == null ? null : encodeASD(CatalogObjectRefSchema, { kind: "constraint", schema_path: spec.schemaPath, name: spec.associatedConstraintId, owner_table: spec.table })
6679
+ }),
6680
+ options: encodeASD(OptionStateSchema, { values, explicit_names: spec.explicitOptionNames ?? [] })
6681
+ };
6682
+ }
5480
6683
  // src/catalog/attach-option.ts
5481
6684
  var SPEC_SCHEMA = schema2([
5482
6685
  field2("name", utf82(), false),
@@ -5518,18 +6721,27 @@ export {
5518
6721
  ArgumentMonotonicity,
5519
6722
  ArgumentValidationError,
5520
6723
  Arguments,
6724
+ CONSTRAINT_CREATE,
6725
+ CONSTRAINT_ENFORCE,
6726
+ CONSTRAINT_MUTATE,
6727
+ CONSTRAINT_RECORDS_READ,
5521
6728
  CatalogAlreadyExistsError,
5522
6729
  CatalogNotFoundError,
5523
6730
  CatalogReadOnlyError,
6731
+ DEFAULT_EXPRESSION_KEY,
5524
6732
  DistinctDependence,
5525
6733
  FunctionNotFoundError,
5526
6734
  FunctionStability,
5527
6735
  FunctionType,
6736
+ GENERATED_EXPRESSION_KEY,
6737
+ GENERATION_KEY,
5528
6738
  NoCatalogError,
5529
6739
  NullHandling,
5530
6740
  OrderDependence,
5531
6741
  OrderPreservation,
6742
+ ROW_SCALAR_EXPRESSION,
5532
6743
  RowCountMismatchError,
6744
+ TRANSACTION_DDL,
5533
6745
  TableInOutPhase,
5534
6746
  TypeId,
5535
6747
  VgiClient,
@@ -5539,31 +6751,77 @@ export {
5539
6751
  batchFromColumns,
5540
6752
  batchFromRows,
5541
6753
  batchToScalarDict,
6754
+ buildCatalogCapabilities,
6755
+ buildConstraintChange,
6756
+ buildConstraintDefinition,
6757
+ buildMacroOverload,
6758
+ canonicalIndex,
6759
+ catalogCapabilities,
6760
+ constraintCapabilities,
6761
+ constraintRecord,
6762
+ decodeCatalogCapabilities,
6763
+ decodeCatalogObjectRef,
6764
+ decodeConstraintChange,
6765
+ decodeConstraintDefinition,
6766
+ decodeConstraintInfo,
6767
+ decodeConstraintSnapshot,
6768
+ decodeConstraintsApplyRequest,
6769
+ decodeForeignKeyDefinition,
5542
6770
  decodeFunctionInfo,
6771
+ decodeIndexDefinition,
5543
6772
  decodeMacroInfo,
6773
+ decodeMacroOverload,
5544
6774
  decodeSchemaInfo,
6775
+ decodeSqlExpression,
5545
6776
  decodeTableInfo,
5546
6777
  decodeViewInfo,
6778
+ defaultClientCapabilities,
6779
+ defaultExpressionMetadata,
5547
6780
  deserializeAttachOptionSpec,
5548
6781
  deserializeAttachOptionSpecs,
5549
6782
  deserializeBatch,
5550
6783
  deserializeSchema,
5551
6784
  emptyBatch,
6785
+ emptyIndexOptions,
6786
+ encodeCatalogCapabilities,
6787
+ encodeCatalogObjectRef,
6788
+ encodeConstraintChange,
6789
+ encodeConstraintDefinition,
6790
+ encodeConstraintInfo,
6791
+ encodeConstraintSnapshot,
6792
+ encodeConstraintsApplyRequest,
6793
+ encodeForeignKeyDefinition,
5552
6794
  encodeFunctionInfo,
6795
+ encodeIndexDefinition,
5553
6796
  encodeMacroInfo,
6797
+ encodeMacroOverload,
5554
6798
  encodeSchemaInfo,
6799
+ encodeSqlExpression,
5555
6800
  encodeTableInfo,
5556
6801
  encodeViewInfo,
5557
6802
  filterBatch,
6803
+ generatedExpressionMetadata,
5558
6804
  iterRows,
5559
6805
  projectBatch,
5560
6806
  projectSchema,
6807
+ readConstraintRecord,
5561
6808
  safeNumber,
5562
6809
  schemaToArgumentSpecs,
6810
+ selectCatalogCapabilities,
6811
+ selectReadProfiles,
5563
6812
  serializeBatch,
5564
6813
  serializeSchema,
6814
+ servedConstraintFields,
6815
+ servedTableInfo,
6816
+ servedTableSchema,
6817
+ sqlExpression,
5565
6818
  toUint8Array,
5566
- typeSignature
6819
+ typeSignature,
6820
+ validateColumnExpressionSql,
6821
+ validateConstraintNullability,
6822
+ validateForeignKeyTargets,
6823
+ validateNumericCheckSql,
6824
+ validateTableConstraints
5567
6825
  };
5568
6826
 
5569
- //# debugId=4510F06EECD1F22E64756E2164756E21
6827
+ //# debugId=E76CFFFCFD3AD3B764756E2164756E21