@query-farm/vgi 0.47.1 → 0.48.0

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