@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
package/dist/index.js CHANGED
@@ -5795,6 +5795,20 @@ function deserializeBindResponse(params) {
5795
5795
  }
5796
5796
  // src/protocol/serializers/init.ts
5797
5797
  init_arrow();
5798
+
5799
+ // src/protocol/types.ts
5800
+ var OrderByDirection;
5801
+ ((OrderByDirection) => {
5802
+ OrderByDirection["ASC"] = "ASC";
5803
+ OrderByDirection["DESC"] = "DESC";
5804
+ })(OrderByDirection ||= {});
5805
+ var OrderByNullOrder;
5806
+ ((OrderByNullOrder) => {
5807
+ OrderByNullOrder["NULLS_FIRST"] = "NULLS_FIRST";
5808
+ OrderByNullOrder["NULLS_LAST"] = "NULLS_LAST";
5809
+ })(OrderByNullOrder ||= {});
5810
+
5811
+ // src/protocol/serializers/init.ts
5798
5812
  var INIT_REQUEST_SCHEMA = schema2([
5799
5813
  field2("bind_call", binary2(), false),
5800
5814
  field2("output_schema", binary2(), false),
@@ -7707,6 +7721,26 @@ var CopyFromFormatInfoSchema = schema2([
7707
7721
  field2("description", utf82(), false),
7708
7722
  field2("ordered", bool2(), false)
7709
7723
  ]);
7724
+ var FieldPathSchema = schema2([
7725
+ field2("components", list2(field2("item", utf82(), true)), false)
7726
+ ]);
7727
+ var TransformSpecSchema = schema2([
7728
+ field2("id", utf82(), false),
7729
+ field2("inputs", list2(field2("item", binary2(), true)), false),
7730
+ field2("parameters", binary2(), true)
7731
+ ]);
7732
+ var KeyGroupingSchema = schema2([
7733
+ field2("keys", list2(field2("item", binary2(), true)), false)
7734
+ ]);
7735
+ var RangeKeySchema = schema2([
7736
+ field2("transform", binary2(), false),
7737
+ field2("direction", dictionary2(utf82(), int162()), false),
7738
+ field2("null_order", dictionary2(utf82(), int162()), false)
7739
+ ]);
7740
+ var RangePartitioningSchema = schema2([
7741
+ field2("keys", list2(field2("item", binary2(), true)), false),
7742
+ field2("split_points", binary2(), false)
7743
+ ]);
7710
7744
  var MacroParameterSchema = schema2([
7711
7745
  field2("name", utf82(), false),
7712
7746
  field2("declared_type", binary2(), true),
@@ -7937,6 +7971,9 @@ var ScanSplitSchema = schema2([
7937
7971
  field2("estimated_rows", int642(), true),
7938
7972
  field2("rows_exact", bool2(), false),
7939
7973
  field2("estimated_bytes", int642(), true),
7974
+ field2("key_value", binary2(), true),
7975
+ field2("range_index", int642(), true),
7976
+ field2("column_bounds", binary2(), true),
7940
7977
  field2("partition_bounds", binary2(), true),
7941
7978
  field2("column_statistics", binary2(), true),
7942
7979
  field2("location_ids", list2(field2("item", int642(), true)), true),
@@ -8412,6 +8449,8 @@ var TableFunctionPlanResultSchema = schema2([
8412
8449
  field2("catalog_version", int642(), true),
8413
8450
  field2("scope", utf82(), false),
8414
8451
  field2("locations", list2(field2("item", utf82(), true)), true),
8452
+ field2("key_grouping", binary2(), true),
8453
+ field2("range_partitioning", binary2(), true),
8415
8454
  field2("partitioning", list2(field2("item", binary2(), true)), true),
8416
8455
  field2("sort_order", list2(field2("item", binary2(), true)), true),
8417
8456
  field2("cache_max_age_seconds", int642(), true),
@@ -8879,10 +8918,106 @@ var TableFunctionStatisticsParamsSchema = schema2([
8879
8918
  ]);
8880
8919
 
8881
8920
  // src/generated/vgi-protocol-types.ts
8921
+ function buildFieldPath(init) {
8922
+ return {
8923
+ components: init.components
8924
+ };
8925
+ }
8926
+ var encodeFieldPath = (v) => encodeASD(FieldPathSchema, v);
8927
+ var decodeFieldPath = (b) => decodeASD(FieldPathSchema, b);
8928
+ function buildTransformSpec(init) {
8929
+ return {
8930
+ id: init.id,
8931
+ inputs: init.inputs ?? [],
8932
+ parameters: init.parameters ?? null
8933
+ };
8934
+ }
8935
+ var encodeTransformSpec = (v) => encodeASD(TransformSpecSchema, v);
8936
+ var decodeTransformSpec = (b) => decodeASD(TransformSpecSchema, b);
8937
+ function buildKeyGrouping(init) {
8938
+ return {
8939
+ keys: init.keys
8940
+ };
8941
+ }
8942
+ var encodeKeyGrouping = (v) => encodeASD(KeyGroupingSchema, v);
8943
+ var decodeKeyGrouping = (b) => decodeASD(KeyGroupingSchema, b);
8944
+ function buildRangeKey(init) {
8945
+ return {
8946
+ transform: init.transform,
8947
+ direction: init.direction,
8948
+ null_order: init.null_order
8949
+ };
8950
+ }
8951
+ var encodeRangeKey = (v) => encodeASD(RangeKeySchema, v);
8952
+ var decodeRangeKey = (b) => decodeASD(RangeKeySchema, b);
8953
+ function buildRangePartitioning(init) {
8954
+ return {
8955
+ keys: init.keys,
8956
+ split_points: init.split_points
8957
+ };
8958
+ }
8959
+ var encodeRangePartitioning = (v) => encodeASD(RangePartitioningSchema, v);
8960
+ var decodeRangePartitioning = (b) => decodeASD(RangePartitioningSchema, b);
8961
+ function buildMacroOverload(init) {
8962
+ return {
8963
+ parameters: init.parameters,
8964
+ definition: init.definition,
8965
+ profile: init.profile,
8966
+ schema_path: init.schema_path,
8967
+ macro_type: init.macro_type,
8968
+ evaluation_context: init.evaluation_context
8969
+ };
8970
+ }
8971
+ var encodeMacroOverload = (v) => encodeASD(MacroOverloadSchema, v);
8972
+ var decodeMacroOverload = (b) => decodeASD(MacroOverloadSchema, b);
8973
+ function buildCatalogCapabilities(init) {
8974
+ return {
8975
+ read: init.read ?? [],
8976
+ ddl: init.ddl ?? [],
8977
+ write: init.write ?? [],
8978
+ transaction: init.transaction ?? []
8979
+ };
8980
+ }
8882
8981
  var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
8883
8982
  var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
8983
+ var encodeCatalogObjectRef = (v) => encodeASD(CatalogObjectRefSchema, v);
8984
+ var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
8884
8985
  var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
8885
8986
  var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
8987
+ var encodeForeignKeyDefinition = (v) => encodeASD(ForeignKeyDefinitionSchema, v);
8988
+ var decodeForeignKeyDefinition = (b) => decodeASD(ForeignKeyDefinitionSchema, b);
8989
+ function buildConstraintDefinition(init) {
8990
+ return {
8991
+ kind: init.kind,
8992
+ column_paths: init.column_paths ?? [],
8993
+ declared_name: init.declared_name ?? null,
8994
+ check_expression: init.check_expression ?? null,
8995
+ foreign_key: init.foreign_key ?? null
8996
+ };
8997
+ }
8998
+ var encodeConstraintDefinition = (v) => encodeASD(ConstraintDefinitionSchema, v);
8999
+ var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
9000
+ var encodeConstraintInfo = (v) => encodeASD(ConstraintInfoSchema, v);
9001
+ var decodeConstraintInfo = (b) => decodeASD(ConstraintInfoSchema, b);
9002
+ function buildConstraintChange(init) {
9003
+ return {
9004
+ operation: init.operation,
9005
+ ref: init.ref ?? null,
9006
+ definition: init.definition ?? null,
9007
+ enforcement: init.enforcement ?? null,
9008
+ validation: init.validation ?? null,
9009
+ cascade: init.cascade ?? null,
9010
+ declared_name: init.declared_name ?? null
9011
+ };
9012
+ }
9013
+ var encodeConstraintChange = (v) => encodeASD(ConstraintChangeSchema, v);
9014
+ var decodeConstraintChange = (b) => decodeASD(ConstraintChangeSchema, b);
9015
+ var encodeConstraintSnapshot = (v) => encodeASD(ConstraintSnapshotSchema, v);
9016
+ var decodeConstraintSnapshot = (b) => decodeASD(ConstraintSnapshotSchema, b);
9017
+ var encodeConstraintsApplyRequest = (v) => encodeASD(ConstraintsApplyRequestSchema, v);
9018
+ var decodeConstraintsApplyRequest = (b) => decodeASD(ConstraintsApplyRequestSchema, b);
9019
+ var encodeIndexDefinition = (v) => encodeASD(IndexDefinitionSchema, v);
9020
+ var decodeIndexDefinition = (b) => decodeASD(IndexDefinitionSchema, b);
8886
9021
  function buildCatalogAttachResult(init) {
8887
9022
  return {
8888
9023
  attach_opaque_data: init.attach_opaque_data,
@@ -8922,328 +9057,618 @@ function buildCatalogContentsResponse(init) {
8922
9057
  };
8923
9058
  }
8924
9059
  var decodeCatalogContentsResponse = (b) => decodeASD(CatalogContentsResultSchema, b);
8925
- // src/generated/vgi-client.ts
8926
- var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
8927
- var decodeCatalogInfo = (b) => decodeASD(CatalogInfoSchema, b);
8928
- var encodeFunctionInfo = (v) => encodeASD(FunctionInfoSchema, v);
8929
- var decodeFunctionInfo = (b) => decodeASD(FunctionInfoSchema, b);
8930
- var encodeIndexInfo = (v) => encodeASD(IndexInfoSchema, v);
8931
- var decodeIndexInfo = (b) => decodeASD(IndexInfoSchema, b);
8932
- var encodeMacroInfo = (v) => encodeASD(MacroInfoSchema, v);
8933
- var decodeMacroInfo = (b) => decodeASD(MacroInfoSchema, b);
8934
- var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
8935
- var decodeSchemaInfo = (b) => decodeASD(SchemaInfoSchema, b);
8936
- var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
8937
- var decodeTableInfo = (b) => decodeASD(TableInfoSchema, b);
8938
- var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
8939
- var decodeViewInfo = (b) => decodeASD(ViewInfoSchema, b);
8940
- // src/catalog/interface.ts
9060
+
9061
+ // src/catalog/constraints.ts
8941
9062
  init_arrow();
8942
- var encodeCopyFromFormatInfo = (v) => encodeASD(CopyFromFormatInfoSchema, {
8943
- comment: v.comment ?? null,
8944
- tags: v.tags ?? {},
8945
- format_name: v.format_name,
8946
- handler: v.handler,
8947
- options: v.options,
8948
- direction: v.direction ?? "from",
8949
- description: v.description ?? "",
8950
- ordered: v.ordered ?? false
8951
- });
8952
- var encodeAttachCatalogInfo = (v) => encodeASD(AttachCatalogInfoSchema, {
8953
- alias: v.alias,
8954
- target: v.target,
8955
- db_type: v.db_type ?? "",
8956
- options: v.options ?? {},
8957
- hidden: v.hidden ?? false,
8958
- required: v.required ?? false,
8959
- secret_ref: v.secret_ref ?? ""
8960
- });
8961
- function encodeScanFunctionResult(functionName, argumentsBytes, requiredExtensions = [], schemaPath = null) {
8962
- return serializeBatch(batchFromColumns(conformColumns(ScanFunctionResultSchema, {
8963
- function_name: [functionName],
8964
- arguments: [argumentsBytes],
8965
- required_extensions: [requiredExtensions],
8966
- schema_path: [schemaPath]
8967
- }), ScanFunctionResultSchema));
9063
+
9064
+ // src/catalog/sql-grammar.ts
9065
+ class GrammarError extends Error {
8968
9066
  }
8969
- function decodeScanFunctionResult(inner) {
8970
- const argsBytes = inner.arguments;
8971
- const positionalArguments = [];
8972
- const namedArguments = {};
8973
- if (argsBytes != null) {
8974
- const batch = deserializeBatch(toUint8Array(argsBytes));
8975
- for (const field of batch.schema.fields) {
8976
- const col = batch.getChild(field.name);
8977
- const value = col ? col.get(0) : null;
8978
- if (field.name.startsWith("arg_")) {
8979
- const idx = parseInt(field.name.slice(4), 10);
8980
- while (positionalArguments.length <= idx)
8981
- positionalArguments.push(null);
8982
- positionalArguments[idx] = value;
8983
- } else {
8984
- namedArguments[field.name] = value;
9067
+ var fail = (message) => {
9068
+ throw new GrammarError(message);
9069
+ };
9070
+ var RESERVED = new Set([
9071
+ "all",
9072
+ "and",
9073
+ "any",
9074
+ "array",
9075
+ "as",
9076
+ "asc",
9077
+ "between",
9078
+ "both",
9079
+ "case",
9080
+ "cast",
9081
+ "check",
9082
+ "collate",
9083
+ "column",
9084
+ "constraint",
9085
+ "create",
9086
+ "default",
9087
+ "desc",
9088
+ "distinct",
9089
+ "do",
9090
+ "else",
9091
+ "end",
9092
+ "except",
9093
+ "false",
9094
+ "fetch",
9095
+ "for",
9096
+ "foreign",
9097
+ "from",
9098
+ "glob",
9099
+ "grant",
9100
+ "group",
9101
+ "having",
9102
+ "ilike",
9103
+ "in",
9104
+ "intersect",
9105
+ "interval",
9106
+ "into",
9107
+ "is",
9108
+ "isnull",
9109
+ "like",
9110
+ "limit",
9111
+ "not",
9112
+ "notnull",
9113
+ "null",
9114
+ "offset",
9115
+ "on",
9116
+ "or",
9117
+ "order",
9118
+ "primary",
9119
+ "references",
9120
+ "returning",
9121
+ "select",
9122
+ "similar",
9123
+ "some",
9124
+ "table",
9125
+ "then",
9126
+ "to",
9127
+ "true",
9128
+ "try_cast",
9129
+ "union",
9130
+ "unique",
9131
+ "using",
9132
+ "when",
9133
+ "where",
9134
+ "window",
9135
+ "with"
9136
+ ]);
9137
+ var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
9138
+ function tokenize(sql) {
9139
+ const out = [];
9140
+ let i = 0;
9141
+ while (i < sql.length) {
9142
+ const c = sql[i];
9143
+ if (/\s/.test(c)) {
9144
+ i++;
9145
+ continue;
9146
+ }
9147
+ if (sql.startsWith("--", i)) {
9148
+ while (i < sql.length && sql[i] !== `
9149
+ `)
9150
+ i++;
9151
+ continue;
9152
+ }
9153
+ if (sql.startsWith("/*", i)) {
9154
+ const close = sql.indexOf("*/", i + 2);
9155
+ if (close < 0)
9156
+ fail("unterminated comment");
9157
+ i = close + 2;
9158
+ continue;
9159
+ }
9160
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
9161
+ const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
9162
+ if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
9163
+ fail("unsupported numeric literal");
9164
+ out.push({ t: "num", v: m[0] });
9165
+ i += m[0].length;
9166
+ continue;
9167
+ }
9168
+ if (c === "'" || c === '"') {
9169
+ let j = i + 1, text = "";
9170
+ for (;; ) {
9171
+ if (j >= sql.length)
9172
+ fail("unterminated quoted text");
9173
+ if (sql[j] === c) {
9174
+ if (sql[j + 1] === c) {
9175
+ text += c;
9176
+ j += 2;
9177
+ continue;
9178
+ }
9179
+ break;
9180
+ }
9181
+ text += sql[j++];
8985
9182
  }
9183
+ out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
9184
+ i = j + 1;
9185
+ continue;
8986
9186
  }
9187
+ if (/[A-Za-z_\u0080-￿]/.test(c)) {
9188
+ const m = /^[A-Za-z_\u0080-￿][A-Za-z0-9_$\u0080-￿]*/.exec(sql.slice(i));
9189
+ out.push({ t: "ident", v: m[0], quoted: false });
9190
+ i += m[0].length;
9191
+ continue;
9192
+ }
9193
+ const op = OPERATORS.find((o) => sql.startsWith(o, i));
9194
+ if (!op)
9195
+ fail(`unsupported character '${c}'`);
9196
+ out.push({ t: "op", v: op });
9197
+ i += op.length;
8987
9198
  }
8988
- const exts = inner.required_extensions;
8989
- const requiredExtensions = exts == null ? [] : (Array.isArray(exts) ? exts : [...exts]).filter((v) => v != null).map(String);
8990
- return {
8991
- functionName: String(inner.function_name ?? ""),
8992
- positionalArguments,
8993
- namedArguments,
8994
- requiredExtensions,
8995
- schemaPath: inner.schema_path == null ? null : (Array.isArray(inner.schema_path) ? inner.schema_path : [...inner.schema_path]).filter((value) => value != null).map(String)
8996
- };
8997
- }
8998
- function singleBranchResult(legacy) {
8999
- return {
9000
- branches: [
9001
- encodeScanBranch({
9002
- function_name: legacy.function_name,
9003
- arguments: toUint8Array(legacy.arguments),
9004
- schema_path: legacy.schema_path ?? null
9005
- })
9006
- ],
9007
- required_extensions: legacy.required_extensions ?? []
9008
- };
9009
- }
9010
- function encodeScanBranch(cols) {
9011
- return serializeBatch(batchFromColumns(conformColumns(ScanBranchSchema, {
9012
- function_name: [cols.function_name],
9013
- arguments: [cols.arguments],
9014
- branch_filter: [cols.branch_filter ?? null],
9015
- writable: [cols.writable ?? false],
9016
- source_catalog: [cols.source_catalog ?? null],
9017
- source_schema_path: [cols.source_schema_path ?? null],
9018
- source_table: [cols.source_table ?? null],
9019
- format_name: [cols.format_name ?? null],
9020
- format_locations: [cols.format_locations ?? null],
9021
- format_options: [cols.format_options ?? null],
9022
- schema_path: [cols.schema_path ?? null]
9023
- }), ScanBranchSchema));
9024
- }
9025
- function encodeFormatOptions(options) {
9026
- const fields = [];
9027
- const values = {};
9028
- for (const [name, arg] of Object.entries(options)) {
9029
- fields.push(field2(name, arg.type, true));
9030
- values[name] = [arg.value];
9031
- }
9032
- return serializeBatch(batchFromColumns(values, schema2(fields)));
9199
+ out.push({ t: "end" });
9200
+ return out;
9033
9201
  }
9034
- function serializeBranchArguments(branch) {
9035
- const fields = [];
9036
- const values = {};
9037
- const positional = branch.positionalArguments ?? [];
9038
- positional.forEach((arg, index) => {
9039
- const name = `arg_${index}`;
9040
- fields.push(field2(name, arg.type, true));
9041
- values[name] = [arg.value];
9042
- });
9043
- for (const [name, arg] of Object.entries(branch.namedArguments ?? {})) {
9044
- fields.push(field2(name, arg.type, true));
9045
- values[name] = [arg.value];
9202
+ var CAST_TYPES = {
9203
+ boolean: "BOOLEAN",
9204
+ bool: "BOOLEAN",
9205
+ logical: "BOOLEAN",
9206
+ tinyint: "TINYINT",
9207
+ int1: "TINYINT",
9208
+ smallint: "SMALLINT",
9209
+ int2: "SMALLINT",
9210
+ short: "SMALLINT",
9211
+ integer: "INTEGER",
9212
+ int: "INTEGER",
9213
+ int4: "INTEGER",
9214
+ signed: "INTEGER",
9215
+ bigint: "BIGINT",
9216
+ int8: "BIGINT",
9217
+ long: "BIGINT",
9218
+ float: "FLOAT",
9219
+ real: "FLOAT",
9220
+ float4: "FLOAT",
9221
+ double: "DOUBLE",
9222
+ float8: "DOUBLE",
9223
+ decimal: "DECIMAL",
9224
+ numeric: "DECIMAL",
9225
+ varchar: "VARCHAR",
9226
+ text: "VARCHAR",
9227
+ string: "VARCHAR",
9228
+ char: "VARCHAR",
9229
+ bpchar: "VARCHAR",
9230
+ nvarchar: "VARCHAR",
9231
+ character: "VARCHAR"
9232
+ };
9233
+ var INT64_MAX = (1n << 63n) - 1n;
9234
+ function literalNumber(text, negative) {
9235
+ if (/^[0-9]+$/.test(text)) {
9236
+ const value = BigInt(text) * (negative ? -1n : 1n);
9237
+ const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
9238
+ return { kind: "constant", type };
9046
9239
  }
9047
- const batchSchema = schema2(fields);
9048
- return serializeBatch(batchFromColumns(values, batchSchema));
9049
- }
9050
- function buildScanBranchesResult(branches, requiredExtensions = []) {
9051
- const serializedBranches = branches.map((branch) => encodeScanBranch({
9052
- function_name: branch.functionName,
9053
- arguments: serializeBranchArguments(branch),
9054
- branch_filter: branch.branchFilter,
9055
- writable: branch.writable,
9056
- source_catalog: branch.sourceCatalog,
9057
- source_schema_path: branch.sourceSchemaPath,
9058
- source_table: branch.sourceTable,
9059
- format_name: branch.formatName,
9060
- format_locations: branch.formatLocations,
9061
- format_options: branch.formatOptions,
9062
- schema_path: branch.schemaPath
9063
- }));
9064
- return {
9065
- branches: serializedBranches,
9066
- required_extensions: requiredExtensions
9067
- };
9068
- }
9069
- function isPromise(v) {
9070
- return v != null && typeof v.then === "function";
9240
+ if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
9241
+ return { kind: "constant", type: "DECIMAL" };
9242
+ return { kind: "constant", type: "DOUBLE" };
9071
9243
  }
9072
9244
 
9073
- class CatalogInterface {
9074
- catalogSnapshotPolicy = null;
9075
- catalogContentsEtag = null;
9076
- catalogContentsAttachIndependent = false;
9077
- catalogVersionFrozen = false;
9078
- catalogNameForAttach(_attachOpaqueData) {
9079
- const names = this.catalogs();
9080
- return names.length === 1 ? names[0] : null;
9245
+ class Parser {
9246
+ tokens;
9247
+ pos = 0;
9248
+ constructor(tokens) {
9249
+ this.tokens = tokens;
9081
9250
  }
9082
- create(name, onConflict, options) {
9083
- throw new CatalogReadOnlyError("create");
9251
+ peek(offset = 0) {
9252
+ return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
9084
9253
  }
9085
- drop(name) {
9086
- throw new CatalogReadOnlyError("drop");
9254
+ next() {
9255
+ return this.tokens[this.pos++];
9087
9256
  }
9088
- schemaGet(attachOpaqueData, path, transactionOpaqueData) {
9089
- const all = this.schemas(attachOpaqueData, transactionOpaqueData);
9090
- if (isPromise(all)) {
9091
- return all.then((arr) => arr.find((s) => schemaPathsEqual(s.path, path)) ?? null);
9092
- }
9093
- return all.find((s) => schemaPathsEqual(s.path, path)) ?? null;
9257
+ isOp(v, offset = 0) {
9258
+ const t = this.peek(offset);
9259
+ return t.t === "op" && t.v === v;
9094
9260
  }
9095
- schemaCreate(attachOpaqueData, path, comment, tags, transactionOpaqueData, onConflict) {
9096
- throw new CatalogReadOnlyError("schema_create");
9261
+ isWord(word, offset = 0) {
9262
+ const t = this.peek(offset);
9263
+ return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
9097
9264
  }
9098
- schemaDrop(attachOpaqueData, path, ignoreNotFound, cascade, transactionOpaqueData) {
9099
- throw new CatalogReadOnlyError("schema_drop");
9265
+ expectOp(v) {
9266
+ if (!this.isOp(v))
9267
+ fail(`expected '${v}'`);
9268
+ this.pos++;
9100
9269
  }
9101
- schemaContentsTables(attachOpaqueData, path, transactionOpaqueData) {
9102
- return [];
9270
+ parseAll() {
9271
+ const node = this.expr();
9272
+ if (this.peek().t !== "end")
9273
+ fail("unexpected text after the expression");
9274
+ return node;
9103
9275
  }
9104
- schemaContentsViews(attachOpaqueData, path, transactionOpaqueData) {
9105
- return [];
9276
+ expr() {
9277
+ return this.or();
9106
9278
  }
9107
- schemaContentsFunctions(attachOpaqueData, path, type, transactionOpaqueData) {
9108
- return [];
9279
+ or() {
9280
+ let left = this.and();
9281
+ while (this.isWord("or")) {
9282
+ this.pos++;
9283
+ left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
9284
+ }
9285
+ return left;
9109
9286
  }
9110
- tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
9111
- return null;
9287
+ and() {
9288
+ let left = this.not();
9289
+ while (this.isWord("and")) {
9290
+ this.pos++;
9291
+ left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
9292
+ }
9293
+ return left;
9112
9294
  }
9113
- tableCreate(attachOpaqueData, schemaPath, name, columns, onConflict, constraintDefinitions, transactionOpaqueData) {
9114
- throw new CatalogReadOnlyError("table_create");
9295
+ not() {
9296
+ if (this.isWord("not")) {
9297
+ this.pos++;
9298
+ return { kind: "operator", op: "NOT", children: [this.not()] };
9299
+ }
9300
+ return this.is();
9115
9301
  }
9116
- tableDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
9117
- throw new CatalogReadOnlyError("table_drop");
9302
+ is() {
9303
+ let left = this.comparison();
9304
+ for (;; ) {
9305
+ if (this.isWord("isnull")) {
9306
+ this.pos++;
9307
+ left = { kind: "operator", op: "IS_NULL", children: [left] };
9308
+ continue;
9309
+ }
9310
+ if (this.isWord("notnull")) {
9311
+ this.pos++;
9312
+ left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
9313
+ continue;
9314
+ }
9315
+ if (this.isWord("is")) {
9316
+ this.pos++;
9317
+ const negated = this.isWord("not");
9318
+ if (negated)
9319
+ this.pos++;
9320
+ if (!this.isWord("null"))
9321
+ fail("only IS [NOT] NULL is supported");
9322
+ this.pos++;
9323
+ left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
9324
+ continue;
9325
+ }
9326
+ return left;
9327
+ }
9118
9328
  }
9119
- tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
9120
- throw new CatalogReadOnlyError("table_scan_function_get");
9329
+ comparison() {
9330
+ const left = this.otherOp();
9331
+ const t = this.peek();
9332
+ if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
9333
+ this.pos++;
9334
+ const right = this.otherOp();
9335
+ const next = this.peek();
9336
+ if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
9337
+ fail("chained comparisons are unsupported");
9338
+ return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
9339
+ }
9340
+ for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
9341
+ if (this.isWord(word))
9342
+ fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
9343
+ }
9344
+ return left;
9121
9345
  }
9122
- tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
9123
- const legacy = this.tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
9124
- return isPromise(legacy) ? legacy.then((r) => singleBranchResult(r)) : singleBranchResult(legacy);
9125
- }
9126
- tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9127
- return null;
9128
- }
9129
- tableCommentSet(attachOpaqueData, schemaPath, name, comment, ignoreNotFound, transactionOpaqueData) {
9130
- throw new CatalogReadOnlyError("table_comment_set");
9131
- }
9132
- tableRename(attachOpaqueData, schemaPath, name, newName, ignoreNotFound, transactionOpaqueData) {
9133
- throw new CatalogReadOnlyError("table_rename");
9134
- }
9135
- tableColumnAdd(attachOpaqueData, schemaPath, name, columnPath, columnDefinition, ignoreNotFound = false, ifColumnNotExists = false, transactionOpaqueData) {
9136
- throw new CatalogReadOnlyError("catalog_table_column_add");
9137
- }
9138
- tableColumnDrop(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, ifColumnExists = false, cascade = false, transactionOpaqueData) {
9139
- throw new CatalogReadOnlyError("catalog_table_column_drop");
9140
- }
9141
- tableColumnRename(attachOpaqueData, schemaPath, name, columnPath, newColumnName, ignoreNotFound = false, transactionOpaqueData) {
9142
- throw new CatalogReadOnlyError("catalog_table_column_rename");
9143
- }
9144
- tableColumnCommentSet(attachOpaqueData, schemaPath, name, columnPath, comment, ignoreNotFound = false, transactionOpaqueData) {
9145
- throw new CatalogReadOnlyError("catalog_table_column_comment_set");
9146
- }
9147
- tableColumnDefaultSet(attachOpaqueData, schemaPath, name, columnPath, expression, ignoreNotFound = false, transactionOpaqueData) {
9148
- throw new CatalogReadOnlyError("catalog_table_column_default_set");
9149
- }
9150
- tableColumnDefaultDrop(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, transactionOpaqueData) {
9151
- throw new CatalogReadOnlyError("catalog_table_column_default_drop");
9152
- }
9153
- tableColumnTypeChange(attachOpaqueData, schemaPath, name, columnPath, columnDefinition, expression = null, ignoreNotFound = false, transactionOpaqueData) {
9154
- throw new CatalogReadOnlyError("catalog_table_column_type_change");
9155
- }
9156
- tableNotNullSet(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, transactionOpaqueData) {
9157
- throw new CatalogReadOnlyError("catalog_table_not_null_set");
9158
- }
9159
- tableNotNullDrop(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, transactionOpaqueData) {
9160
- throw new CatalogReadOnlyError("catalog_table_not_null_drop");
9161
- }
9162
- viewGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9163
- return null;
9164
- }
9165
- viewCreate(attachOpaqueData, schemaPath, name, definition, onConflict, transactionOpaqueData, aliases, comment, tags, columnComments) {
9166
- throw new CatalogReadOnlyError("view_create");
9167
- }
9168
- viewDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
9169
- throw new CatalogReadOnlyError("view_drop");
9170
- }
9171
- viewRename(attachOpaqueData, schemaPath, name, newName, ignoreNotFound, transactionOpaqueData) {
9172
- throw new CatalogReadOnlyError("view_rename");
9173
- }
9174
- viewCommentSet(attachOpaqueData, schemaPath, name, comment, ignoreNotFound, transactionOpaqueData) {
9175
- throw new CatalogReadOnlyError("view_comment_set");
9176
- }
9177
- viewColumnCommentSet(attachOpaqueData, schemaPath, name, columnPath, comment, ignoreNotFound, transactionOpaqueData) {
9178
- throw new CatalogReadOnlyError("view_column_comment_set");
9346
+ otherOp() {
9347
+ let left = this.additive();
9348
+ for (;; ) {
9349
+ const t = this.peek();
9350
+ if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
9351
+ this.pos++;
9352
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
9353
+ continue;
9354
+ }
9355
+ return left;
9356
+ }
9179
9357
  }
9180
- macroGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9181
- return null;
9358
+ additive() {
9359
+ let left = this.multiplicative();
9360
+ for (;; ) {
9361
+ const t = this.peek();
9362
+ if (t.t === "op" && (t.v === "+" || t.v === "-")) {
9363
+ this.pos++;
9364
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
9365
+ continue;
9366
+ }
9367
+ return left;
9368
+ }
9182
9369
  }
9183
- macroCreate(attachOpaqueData, schemaPath, name, macroType, overloads, onConflict, transactionOpaqueData) {
9184
- throw new CatalogReadOnlyError("macro_create");
9370
+ multiplicative() {
9371
+ let left = this.power();
9372
+ for (;; ) {
9373
+ const t = this.peek();
9374
+ if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
9375
+ this.pos++;
9376
+ left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
9377
+ continue;
9378
+ }
9379
+ return left;
9380
+ }
9185
9381
  }
9186
- macroDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
9187
- throw new CatalogReadOnlyError("macro_drop");
9382
+ power() {
9383
+ let left = this.unary();
9384
+ while (this.isOp("^")) {
9385
+ this.pos++;
9386
+ left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
9387
+ }
9388
+ return left;
9188
9389
  }
9189
- schemaContentsMacros(attachOpaqueData, path, type, transactionOpaqueData) {
9190
- return [];
9390
+ unary() {
9391
+ if (this.isOp("-") || this.isOp("+")) {
9392
+ const sign = this.next().v;
9393
+ const operand = this.unary();
9394
+ if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
9395
+ const folded = literalNumber(operand.text, !operand.negative);
9396
+ return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
9397
+ }
9398
+ return { kind: "function", name: sign, qualified: false, children: [operand] };
9399
+ }
9400
+ return this.postfix();
9191
9401
  }
9192
- schemaContentsIndexes(attachOpaqueData, path, transactionOpaqueData) {
9193
- return [];
9402
+ postfix() {
9403
+ let node = this.primary();
9404
+ for (;; ) {
9405
+ if (this.isOp("::")) {
9406
+ this.pos++;
9407
+ node = { kind: "cast", ...this.typeName(), child: node };
9408
+ continue;
9409
+ }
9410
+ if (this.isOp("["))
9411
+ fail("subscripts are unsupported");
9412
+ return node;
9413
+ }
9414
+ }
9415
+ typeName() {
9416
+ const t = this.next();
9417
+ if (t.t !== "ident")
9418
+ fail("expected a type name");
9419
+ const first = t.v.toLowerCase();
9420
+ let qualified = false;
9421
+ while (this.isOp(".")) {
9422
+ this.pos++;
9423
+ if (this.next().t !== "ident")
9424
+ fail("expected a type name");
9425
+ qualified = true;
9426
+ }
9427
+ let name = first;
9428
+ if (first === "double" && this.isWord("precision")) {
9429
+ this.pos++;
9430
+ name = "double";
9431
+ }
9432
+ if (first === "character" && this.isWord("varying")) {
9433
+ this.pos++;
9434
+ name = "varchar";
9435
+ }
9436
+ let params = [];
9437
+ if (this.isOp("(")) {
9438
+ this.pos++;
9439
+ for (;; ) {
9440
+ const p = this.next();
9441
+ if (p.t !== "num")
9442
+ fail("unsupported type parameter");
9443
+ params.push(p.v);
9444
+ if (this.isOp(",")) {
9445
+ this.pos++;
9446
+ continue;
9447
+ }
9448
+ break;
9449
+ }
9450
+ this.expectOp(")");
9451
+ }
9452
+ if (this.isOp("["))
9453
+ fail("array types are unsupported");
9454
+ let type = CAST_TYPES[name] ?? null;
9455
+ if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
9456
+ type = "DOUBLE";
9457
+ return { type, qualified };
9458
+ }
9459
+ primary() {
9460
+ const t = this.next();
9461
+ if (t.t === "num")
9462
+ return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
9463
+ if (t.t === "str") {
9464
+ if (this.peek().t === "str")
9465
+ fail("adjacent string literals are unsupported");
9466
+ return { kind: "constant", type: "VARCHAR" };
9467
+ }
9468
+ if (t.t === "op") {
9469
+ if (t.v === "(") {
9470
+ const inner = this.expr();
9471
+ if (this.isOp(","))
9472
+ fail("row constructors are unsupported");
9473
+ this.expectOp(")");
9474
+ return inner;
9475
+ }
9476
+ return fail(`unexpected '${t.v}'`);
9477
+ }
9478
+ if (t.t === "end")
9479
+ return fail("expected an expression");
9480
+ const word = t.v.toLowerCase();
9481
+ if (!t.quoted) {
9482
+ if (word === "null")
9483
+ return { kind: "constant", type: "NULL" };
9484
+ if (word === "true" || word === "false")
9485
+ return { kind: "constant", type: "BOOLEAN" };
9486
+ if (word === "cast" && this.isOp("(")) {
9487
+ this.pos++;
9488
+ const child = this.expr();
9489
+ if (!this.isWord("as"))
9490
+ fail("expected AS in CAST");
9491
+ this.pos++;
9492
+ const target = this.typeName();
9493
+ this.expectOp(")");
9494
+ return { kind: "cast", ...target, child };
9495
+ }
9496
+ if (word === "case")
9497
+ fail("CASE is outside the supported scalar grammar");
9498
+ if (RESERVED.has(word))
9499
+ fail(`unexpected keyword ${t.v.toUpperCase()}`);
9500
+ }
9501
+ const names = [t.v];
9502
+ while (this.isOp(".")) {
9503
+ this.pos++;
9504
+ const part = this.next();
9505
+ if (part.t !== "ident")
9506
+ fail("unsupported qualified name");
9507
+ names.push(part.v);
9508
+ }
9509
+ if (this.isOp("(")) {
9510
+ this.pos++;
9511
+ const children = [];
9512
+ if (this.isWord("distinct"))
9513
+ fail("DISTINCT function arguments are unsupported");
9514
+ if (!this.isOp(")")) {
9515
+ for (;; ) {
9516
+ if (this.isOp("*"))
9517
+ fail("star arguments are unsupported");
9518
+ if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
9519
+ fail("named scalar arguments are unsupported");
9520
+ children.push(this.expr());
9521
+ if (this.isOp(",")) {
9522
+ this.pos++;
9523
+ continue;
9524
+ }
9525
+ break;
9526
+ }
9527
+ }
9528
+ if (this.isWord("order"))
9529
+ fail("ordered function arguments are unsupported");
9530
+ this.expectOp(")");
9531
+ if (this.isWord("filter") || this.isWord("over"))
9532
+ fail("aggregate and window functions are unsupported");
9533
+ if (names.length === 1 && !t.quoted && word === "coalesce")
9534
+ return { kind: "operator", op: "COALESCE", children };
9535
+ return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
9536
+ }
9537
+ if (this.peek().t === "str")
9538
+ fail("typed literals are unsupported");
9539
+ return { kind: "column", names };
9540
+ }
9541
+ }
9542
+ function parseScalarSql(sql) {
9543
+ if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
9544
+ fail("invalid SQL size or text");
9545
+ return new Parser(tokenize(sql)).parseAll();
9546
+ }
9547
+ var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
9548
+ var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
9549
+ var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
9550
+ function validateColumnExpressionSql(sql, options) {
9551
+ const { usingColumns, generated } = options;
9552
+ const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
9553
+ const columns = [];
9554
+ let nodes = 0;
9555
+ const visit = (node, depth) => {
9556
+ if (depth > 64 || ++nodes > 4096)
9557
+ fail("scalar expression is too complex");
9558
+ switch (node.kind) {
9559
+ case "constant":
9560
+ if (!primitive.has(node.type))
9561
+ fail(`unsupported scalar literal type ${node.type}`);
9562
+ return;
9563
+ case "column":
9564
+ if (!usingColumns || node.names.length !== 1)
9565
+ fail("column references are unsupported in this scope");
9566
+ columns.push(node.names[0]);
9567
+ return;
9568
+ case "cast":
9569
+ if (node.qualified)
9570
+ fail("qualified scalar cast types are unsupported");
9571
+ if (node.type === null || !primitive.has(node.type))
9572
+ fail("unsupported scalar cast");
9573
+ visit(node.child, depth + 1);
9574
+ return;
9575
+ case "comparison":
9576
+ visit(node.left, depth + 1);
9577
+ visit(node.right, depth + 1);
9578
+ return;
9579
+ case "conjunction":
9580
+ case "operator":
9581
+ node.children.forEach((c) => visit(c, depth + 1));
9582
+ return;
9583
+ case "function": {
9584
+ const lower = node.name.toLowerCase();
9585
+ const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
9586
+ if (!ok)
9587
+ fail(`unsupported scalar function '${node.name}'`);
9588
+ node.children.forEach((c) => visit(c, depth + 1));
9589
+ return;
9590
+ }
9591
+ }
9592
+ };
9593
+ try {
9594
+ visit(parseScalarSql(sql), 0);
9595
+ } catch (error) {
9596
+ if (error instanceof GrammarError)
9597
+ throw error;
9598
+ throw new GrammarError(String(error?.message ?? error));
9599
+ }
9600
+ return columns;
9601
+ }
9602
+ function validateNumericCheckSql(sql, resolveColumn) {
9603
+ const node = parseScalarSql(sql);
9604
+ if (node.kind !== "comparison")
9605
+ fail("native CHECK read supports only Boolean numeric comparisons");
9606
+ const comparison = node;
9607
+ for (const operand of [comparison.left, comparison.right]) {
9608
+ if (operand.kind === "constant") {
9609
+ if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
9610
+ fail("CHECK requires numeric operands");
9611
+ continue;
9612
+ }
9613
+ if (operand.kind !== "column")
9614
+ fail("native CHECK read supports only numeric column/constant comparisons");
9615
+ const column = operand;
9616
+ if (column.names.length !== 1)
9617
+ fail("CHECK requires unqualified column references");
9618
+ resolveColumn(column.names[0]);
9194
9619
  }
9195
- indexGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9620
+ }
9621
+
9622
+ // src/catalog/column-types.ts
9623
+ init_arrow();
9624
+ function isRowIdField(field) {
9625
+ return field.metadata?.has("is_row_id") ?? false;
9626
+ }
9627
+ function hasLogicalType(field) {
9628
+ for (const key of field.metadata?.keys() ?? [])
9629
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
9630
+ return true;
9631
+ return false;
9632
+ }
9633
+ function ordinaryStructChildren(field) {
9634
+ if (!isStruct(field.type) || hasLogicalType(field))
9196
9635
  return null;
9197
- }
9198
- copyFromFormats(attachOpaqueData, transactionOpaqueData) {
9199
- return [];
9200
- }
9201
- async catalogContents(attachOpaqueData, _ifNoneMatch) {
9202
- const schemas = await this.schemas(attachOpaqueData, undefined);
9203
- const contents = await Promise.all(schemas.map(async (schema) => {
9204
- const counts = schema.estimated_object_count ?? {};
9205
- const path = schema.path;
9206
- const kind = async (countKey, list) => (counts[countKey] ?? 1) === 0 ? [] : [...await list()];
9207
- const [tables, views, scalarFunctions, aggregateFunctions, tableFunctions, scalarMacros, tableMacros, indexes] = await Promise.all([
9208
- kind("table", () => this.schemaContentsTables(attachOpaqueData, path)),
9209
- kind("view", () => this.schemaContentsViews(attachOpaqueData, path)),
9210
- kind("scalar_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "scalar_function")),
9211
- kind("aggregate_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "aggregate_function")),
9212
- kind("table_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "table_function")),
9213
- kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "scalar_macro")),
9214
- kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "table_macro")),
9215
- kind("index", () => this.schemaContentsIndexes(attachOpaqueData, path))
9216
- ]);
9217
- return {
9218
- schema,
9219
- tables,
9220
- views,
9221
- scalar_functions: scalarFunctions,
9222
- aggregate_functions: aggregateFunctions,
9223
- table_functions: tableFunctions,
9224
- scalar_macros: scalarMacros,
9225
- table_macros: tableMacros,
9226
- indexes
9227
- };
9228
- }));
9229
- return { schemas: contents };
9230
- }
9231
- catalogContentsCacheable() {
9232
- return this.catalogContentsAttachIndependent && this.catalogVersionFrozen;
9233
- }
9234
- catalogContentsOwner(_attachOpaqueData) {
9235
- return this;
9236
- }
9237
- transactionBegin(attachOpaqueData) {
9636
+ return field.type.children;
9637
+ }
9638
+ function isGeneratedField(field) {
9639
+ const m = field.metadata;
9640
+ return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
9641
+ }
9642
+ function duckdbPrimitive(field) {
9643
+ if (hasLogicalType(field))
9238
9644
  return null;
9645
+ const t = field.type;
9646
+ switch (t.typeId) {
9647
+ case TypeId.Bool:
9648
+ return "BOOLEAN";
9649
+ case TypeId.Utf8:
9650
+ return "VARCHAR";
9651
+ case TypeId.Int: {
9652
+ if (!(t.isSigned ?? t.signed ?? true))
9653
+ return null;
9654
+ return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
9655
+ }
9656
+ case TypeId.Float:
9657
+ return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
9658
+ case TypeId.Decimal:
9659
+ return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
9660
+ default:
9661
+ return null;
9239
9662
  }
9240
- transactionCommit(attachOpaqueData, transactionOpaqueData) {}
9241
- transactionRollback(attachOpaqueData, transactionOpaqueData) {}
9242
9663
  }
9664
+
9243
9665
  // src/catalog/column-expressions.ts
9244
9666
  init_arrow();
9245
9667
  var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
9246
9668
  var GENERATION_KEY = "vgi.column.generation.v1";
9669
+ var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
9670
+ var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
9671
+ var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
9247
9672
  var PROFILE = "vgi.expression.duckdb.scalar.v1";
9248
9673
  var MAX_BYTES = 8 * 1024 * 1024;
9249
9674
  var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
@@ -9331,81 +9756,963 @@ function envelope(bytes) {
9331
9756
  }
9332
9757
  offset += length + bodyLength;
9333
9758
  }
9334
- throw new Error("expression IPC lacks end marker");
9335
- }
9336
- function shape(schema) {
9337
- const field = (f) => [
9338
- f.name,
9339
- f.nullable,
9340
- String(f.type),
9341
- (f.type.children ?? []).map(field)
9342
- ];
9343
- return JSON.stringify(schema.fields.map(field));
9344
- }
9345
- function validateEncoded(encoded, owner) {
9346
- if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
9347
- throw new Error("invalid generated expression size");
9348
- const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
9349
- if (base64(bytes) !== encoded)
9350
- throw new Error("generated expression requires canonical base64");
9351
- const textBuffers = envelope(bytes);
9352
- const batch = deserializeBatch(bytes);
9353
- if (batch.numRows !== 1 || shape(batch.schema) !== shape(SqlExpressionSchema))
9354
- throw new Error("invalid SqlExpression record schema");
9355
- const utf8 = new TextDecoder("utf-8", { fatal: true });
9356
- textBuffers.forEach((buffer) => utf8.decode(buffer));
9357
- expression(decodeSqlExpression(bytes), owner);
9358
- }
9359
- function generatedExpressionMetadata(sql, owner) {
9360
- const value = {
9361
- sql,
9362
- profile: PROFILE,
9363
- schema_path: [...owner],
9364
- evaluation_context: {
9365
- timezone: "UTC",
9366
- collation: "binary",
9367
- default_order: "asc",
9368
- default_null_order: "nulls_last",
9369
- preserve_insertion_order: true
9370
- }
9371
- };
9372
- expression(value, owner);
9373
- return base64(encodeSqlExpression(value));
9374
- }
9375
- function validateColumnExpressions(schema, owner, allowGenerated = true) {
9376
- const type = (t) => {
9377
- for (const f of t?.children ?? t?.fields ?? [])
9378
- field(f);
9379
- if (t?.dictionary)
9380
- type(t.dictionary);
9381
- };
9382
- const field = (f) => {
9383
- const metadata = f.metadata ?? new Map;
9384
- for (const key of metadata.keys()) {
9385
- if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
9386
- throw new Error("unknown generated metadata version");
9387
- }
9388
- if (metadata.has("generated_expression"))
9389
- throw new Error("legacy generated expression requires explicit canonical translation");
9390
- if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
9391
- throw new Error("generated expression and category must occur together");
9392
- if (metadata.has(GENERATED_EXPRESSION_KEY)) {
9393
- if (metadata.get(GENERATION_KEY) !== "virtual")
9394
- throw new Error("only VIRTUAL generated columns are supported");
9395
- if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
9396
- throw new Error("generated column cannot have a default");
9397
- validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
9398
- if (!allowGenerated)
9399
- throw new Error("generated columns unsupported by this catalog");
9400
- }
9401
- type(f.type);
9402
- };
9403
- schema.fields.forEach(field);
9759
+ throw new Error("expression IPC lacks end marker");
9760
+ }
9761
+ function shape(schema) {
9762
+ const field = (f) => [
9763
+ f.name,
9764
+ f.nullable,
9765
+ String(f.type),
9766
+ (f.type.children ?? []).map(field)
9767
+ ];
9768
+ return JSON.stringify(schema.fields.map(field));
9769
+ }
9770
+ function validateEncoded(encoded, owner) {
9771
+ if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
9772
+ throw new Error("invalid generated expression size");
9773
+ const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
9774
+ if (base64(bytes) !== encoded)
9775
+ throw new Error("generated expression requires canonical base64");
9776
+ const textBuffers = envelope(bytes);
9777
+ const batch = deserializeBatch(bytes);
9778
+ if (batch.numRows !== 1 || shape(batch.schema) !== shape(SqlExpressionSchema))
9779
+ throw new Error("invalid SqlExpression record schema");
9780
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
9781
+ textBuffers.forEach((buffer) => utf8.decode(buffer));
9782
+ const value = decodeSqlExpression(bytes);
9783
+ expression(value, owner);
9784
+ return value.sql;
9785
+ }
9786
+ function generatedExpressionMetadata(sql, owner) {
9787
+ try {
9788
+ validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
9789
+ } catch (error) {
9790
+ throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
9791
+ }
9792
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
9793
+ }
9794
+ function defaultExpressionMetadata(sql, owner) {
9795
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
9796
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
9797
+ }
9798
+ function sqlExpression(sql, schemaPath) {
9799
+ const owner = [...schemaPath];
9800
+ const value = {
9801
+ sql,
9802
+ profile: PROFILE,
9803
+ schema_path: [...owner],
9804
+ evaluation_context: {
9805
+ timezone: "UTC",
9806
+ collation: "binary",
9807
+ default_order: "asc",
9808
+ default_null_order: "nulls_last",
9809
+ preserve_insertion_order: true
9810
+ }
9811
+ };
9812
+ expression(value, owner);
9813
+ return value;
9814
+ }
9815
+ function validateColumnExpressions(schema, owner, allowGenerated = true) {
9816
+ const type = (t) => {
9817
+ for (const f of t?.children ?? t?.fields ?? [])
9818
+ field(f);
9819
+ if (t?.dictionary)
9820
+ type(t.dictionary);
9821
+ };
9822
+ const topLevel = new Map;
9823
+ for (const f of schema.fields) {
9824
+ const key = String(f.name).toLowerCase();
9825
+ topLevel.set(key, [...topLevel.get(key) ?? [], f]);
9826
+ }
9827
+ const field = (f, top = false) => {
9828
+ const metadata = f.metadata ?? new Map;
9829
+ for (const key of metadata.keys()) {
9830
+ if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
9831
+ throw new Error("unknown generated metadata version");
9832
+ }
9833
+ const where = `column ${f.name}`;
9834
+ if (metadata.has("generated_expression"))
9835
+ throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
9836
+ if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
9837
+ if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
9838
+ throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
9839
+ const type = duckdbPrimitive(f);
9840
+ if (!type || !DEFAULT_TYPES.has(type))
9841
+ throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
9842
+ const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
9843
+ try {
9844
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
9845
+ } catch (error) {
9846
+ throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
9847
+ }
9848
+ }
9849
+ if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
9850
+ throw new Error("generated expression and category must occur together");
9851
+ if (metadata.has(GENERATED_EXPRESSION_KEY)) {
9852
+ if (metadata.get(GENERATION_KEY) !== "virtual")
9853
+ throw new Error("only VIRTUAL generated columns are supported");
9854
+ if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
9855
+ throw new Error("generated column cannot have a default");
9856
+ const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
9857
+ if (!allowGenerated)
9858
+ throw new Error("generated columns unsupported by this catalog");
9859
+ if (!f.nullable)
9860
+ throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
9861
+ const type = duckdbPrimitive(f);
9862
+ if (!type || !GENERATED_TYPES.has(type))
9863
+ throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
9864
+ let references;
9865
+ try {
9866
+ references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
9867
+ } catch (error) {
9868
+ throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
9869
+ }
9870
+ if (top) {
9871
+ for (const name of references) {
9872
+ const matches = topLevel.get(name.toLowerCase()) ?? [];
9873
+ if (matches.length !== 1)
9874
+ throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
9875
+ const operand = duckdbPrimitive(matches[0]);
9876
+ if (!operand || !GENERATED_TYPES.has(operand))
9877
+ throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
9878
+ }
9879
+ }
9880
+ }
9881
+ type(f.type);
9882
+ };
9883
+ schema.fields.forEach((f) => field(f, true));
9884
+ }
9885
+ function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
9886
+ validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
9887
+ }
9888
+
9889
+ // src/catalog/constraints.ts
9890
+ var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
9891
+ var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
9892
+ var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
9893
+ var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
9894
+ var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
9895
+ var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
9896
+ var CHECK_CONTEXT = {
9897
+ timezone: "UTC",
9898
+ collation: "binary",
9899
+ default_order: "asc",
9900
+ default_null_order: "nulls_last",
9901
+ preserve_insertion_order: true
9902
+ };
9903
+ function identifier(value, what) {
9904
+ if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
9905
+ throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
9906
+ }
9907
+ function objectRef(kind, schemaPath, name, ownerTable) {
9908
+ return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
9909
+ }
9910
+ function checkPaths(paths, what, topLevelOnly) {
9911
+ if (paths.length > 1024)
9912
+ throw new Error(`${what}: too many column paths`);
9913
+ const seen = new Set;
9914
+ for (const path of paths) {
9915
+ if (path.length === 0 || path.length > 64)
9916
+ throw new Error(`${what}: column path must have 1..64 components`);
9917
+ if (topLevelOnly && path.length !== 1)
9918
+ throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
9919
+ path.forEach((part) => identifier(part, `${what}: column path component`));
9920
+ const key = JSON.stringify(path);
9921
+ if (seen.has(key))
9922
+ throw new Error(`${what}: duplicate column path ${path.join(".")}`);
9923
+ seen.add(key);
9924
+ }
9925
+ }
9926
+ function constraintRecord(spec) {
9927
+ const what = `constraint '${spec.id}' on '${spec.table}'`;
9928
+ if (!spec.id || spec.id.includes("\x00"))
9929
+ throw new Error("constraint id must be nonempty without NUL");
9930
+ identifier(spec.table, "table");
9931
+ if (spec.schemaPath.length !== 1)
9932
+ throw new Error(`${what}: DuckDB reads only one-component schema paths`);
9933
+ identifier(spec.schemaPath[0], "schema");
9934
+ if (spec.enforcement !== "ENFORCED" || spec.validation !== "ALL_ROWS")
9935
+ throw new Error(`${what} is ${spec.enforcement}/${spec.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
9936
+ if (spec.declaredName !== undefined)
9937
+ identifier(spec.declaredName, `${what}: declaredName`);
9938
+ if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
9939
+ throw new Error("checkSql is required for CHECK and only CHECK");
9940
+ if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
9941
+ throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
9942
+ if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
9943
+ throw new Error("NOT_NULL requires exactly one column path");
9944
+ if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
9945
+ throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
9946
+ checkPaths(spec.columns, what, spec.kind !== "NOT_NULL");
9947
+ if (spec.checkSql !== undefined) {
9948
+ try {
9949
+ validateNumericCheckSql(spec.checkSql, () => {});
9950
+ } catch (error) {
9951
+ throw new Error(`${what}: ${error.message} (CHECK SQL: ${spec.checkSql})`);
9952
+ }
9953
+ }
9954
+ const ref = spec.references;
9955
+ if (ref) {
9956
+ if (ref.columns.length !== spec.columns.length)
9957
+ throw new Error("foreign key local and referenced arity must match");
9958
+ if (JSON.stringify(ref.schemaPath) !== JSON.stringify(spec.schemaPath))
9959
+ throw new Error(`${what}: DuckDB reads only foreign keys to a table in the same schema`);
9960
+ identifier(ref.table, `${what}: referenced table`);
9961
+ identifier(ref.constraintId, `${what}: referenced constraintId`);
9962
+ checkPaths(ref.columns, `${what} (referenced)`, true);
9963
+ }
9964
+ const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
9965
+ sql: spec.checkSql,
9966
+ profile: ROW_SCALAR_EXPRESSION,
9967
+ schema_path: spec.schemaPath,
9968
+ evaluation_context: CHECK_CONTEXT
9969
+ });
9970
+ const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
9971
+ referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
9972
+ referenced_column_paths: ref.columns,
9973
+ match: "SIMPLE",
9974
+ on_update: "NO_ACTION",
9975
+ on_delete: "NO_ACTION"
9976
+ });
9977
+ return encodeASD(ConstraintInfoSchema, {
9978
+ ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
9979
+ definition: encodeASD(ConstraintDefinitionSchema, {
9980
+ kind: spec.kind,
9981
+ column_paths: spec.columns,
9982
+ declared_name: spec.declaredName ?? null,
9983
+ check_expression: check,
9984
+ foreign_key: foreign
9985
+ }),
9986
+ enforcement: spec.enforcement,
9987
+ validation: spec.validation,
9988
+ referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
9989
+ });
9990
+ }
9991
+ var KNOWN = {
9992
+ read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
9993
+ ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
9994
+ write: new Set([CONSTRAINT_ENFORCE]),
9995
+ transaction: new Set([TRANSACTION_DDL])
9996
+ };
9997
+ var REQUIRES = {
9998
+ [ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
9999
+ [CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
10000
+ [CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
10001
+ [CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
10002
+ "vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
10003
+ "vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
10004
+ };
10005
+ var CATEGORIES = ["read", "ddl", "write", "transaction"];
10006
+ function catalogCapabilities(init = {}) {
10007
+ return {
10008
+ read: [...new Set(init.read ?? [])].sort(),
10009
+ ddl: [...new Set(init.ddl ?? [])].sort(),
10010
+ write: [...new Set(init.write ?? [])].sort(),
10011
+ transaction: [...new Set(init.transaction ?? [])].sort()
10012
+ };
10013
+ }
10014
+ function constraintCapabilities(options = {}) {
10015
+ const enforce = options.enforce || options.create;
10016
+ return catalogCapabilities({
10017
+ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION],
10018
+ ddl: [...options.create ? [CONSTRAINT_CREATE] : [], ...options.mutate ? [CONSTRAINT_MUTATE] : []],
10019
+ write: enforce ? [CONSTRAINT_ENFORCE] : [],
10020
+ transaction: options.transactionDdl ? [TRANSACTION_DDL] : []
10021
+ });
10022
+ }
10023
+ function offeredCatalog(clientCapabilities) {
10024
+ if (clientCapabilities == null)
10025
+ return null;
10026
+ const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
10027
+ return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
10028
+ }
10029
+ function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
10030
+ const offered = offeredCatalog(clientCapabilities);
10031
+ if (offered == null)
10032
+ return catalogCapabilities();
10033
+ const chosen = new Set;
10034
+ for (const category of CATEGORIES)
10035
+ for (const p of available[category] ?? [])
10036
+ if (offered[category]?.includes(p))
10037
+ chosen.add(p);
10038
+ if (!supportsTransactions)
10039
+ chosen.delete(TRANSACTION_DDL);
10040
+ for (let changed = true;changed; ) {
10041
+ changed = false;
10042
+ for (const p of [...chosen])
10043
+ if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
10044
+ chosen.delete(p);
10045
+ changed = true;
10046
+ }
10047
+ }
10048
+ const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
10049
+ return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
10050
+ }
10051
+ function selectReadProfiles(available, clientCapabilities) {
10052
+ return selectCatalogCapabilities(catalogCapabilities({ read: [...available] }), clientCapabilities).read;
10053
+ }
10054
+ function defaultClientCapabilities(engine = "vgi-typescript") {
10055
+ return {
10056
+ engine,
10057
+ native_formats: [],
10058
+ catalogs: [],
10059
+ can_stream: true,
10060
+ filter_encodings: [],
10061
+ catalog: encodeCatalogCapabilities(catalogCapabilities({ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] })),
10062
+ query_pushdown: null
10063
+ };
10064
+ }
10065
+ function capabilitiesEmpty(caps) {
10066
+ return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
10067
+ }
10068
+ function readConstraintRecord(bytes) {
10069
+ const info = decodeASD(ConstraintInfoSchema, bytes);
10070
+ const ref = decodeASD(CatalogObjectRefSchema, info.ref);
10071
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
10072
+ const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
10073
+ const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
10074
+ const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
10075
+ return {
10076
+ schemaPath: [...ref.schema_path],
10077
+ table: ref.owner_table ?? "",
10078
+ id: ref.name,
10079
+ kind: def.kind,
10080
+ columns: [...def.column_paths].map((p) => [...p]),
10081
+ enforcement: info.enforcement,
10082
+ validation: info.validation,
10083
+ declaredName: def.declared_name ?? null,
10084
+ checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
10085
+ references: fk == null || target == null ? null : {
10086
+ schemaPath: [...target.schema_path],
10087
+ table: target.name,
10088
+ columns: [...fk.referenced_column_paths].map((p) => [...p]),
10089
+ constraintId: targetKey?.name ?? null,
10090
+ constraintTable: targetKey?.owner_table ?? null,
10091
+ constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
10092
+ match: fk.match,
10093
+ onUpdate: fk.on_update,
10094
+ onDelete: fk.on_delete
10095
+ }
10096
+ };
10097
+ }
10098
+ function fieldsByExactName(fields, name) {
10099
+ const out = [];
10100
+ fields.forEach((f, i) => {
10101
+ if (f.name === name)
10102
+ out.push(i);
10103
+ });
10104
+ return out;
10105
+ }
10106
+ function validateTableConstraints(table, schemaPath, fields, constraints) {
10107
+ if (constraints.length > 1024)
10108
+ throw new Error(`Table '${table}': too many constraints (at most 1024)`);
10109
+ const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
10110
+ if (rowIds.length > 1)
10111
+ throw new Error(`Table '${table}': at most one column may carry is_row_id`);
10112
+ const rowId = rowIds[0] ?? -1;
10113
+ const records = [];
10114
+ const required = new Set;
10115
+ const ids = new Set;
10116
+ const labels = new Set;
10117
+ let primaryKeys = 0;
10118
+ for (const bytes of constraints) {
10119
+ let record;
10120
+ try {
10121
+ record = readConstraintRecord(bytes);
10122
+ } catch (error) {
10123
+ throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
10124
+ }
10125
+ const where = `Table '${table}': constraint '${record.id}'`;
10126
+ const fail = (message) => {
10127
+ throw new Error(`${where}: ${message}`);
10128
+ };
10129
+ if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
10130
+ fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
10131
+ if (ids.has(record.id))
10132
+ fail("duplicate constraint id");
10133
+ ids.add(record.id);
10134
+ if (record.declaredName != null) {
10135
+ const label = record.declaredName.toLowerCase();
10136
+ if (labels.has(label))
10137
+ fail(`duplicate declared name '${record.declaredName}'`);
10138
+ labels.add(label);
10139
+ }
10140
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
10141
+ fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
10142
+ try {
10143
+ checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
10144
+ } catch (error) {
10145
+ fail(error.message);
10146
+ }
10147
+ const resolveTop = (path) => {
10148
+ const matches = fieldsByExactName(fields, path[0]);
10149
+ if (matches.length !== 1 || matches[0] === rowId)
10150
+ fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
10151
+ return matches[0];
10152
+ };
10153
+ switch (record.kind) {
10154
+ case "CHECK": {
10155
+ if (record.checkSql == null)
10156
+ fail("CHECK without an expression");
10157
+ validateCheckRecord(bytes, where, schemaPath, fields, rowId);
10158
+ break;
10159
+ }
10160
+ case "NOT_NULL": {
10161
+ if (record.columns.length !== 1)
10162
+ fail("NOT_NULL requires exactly one column path");
10163
+ const path = record.columns[0];
10164
+ let field = fields[resolveTop(path)];
10165
+ for (let depth = 1;depth < path.length; depth++) {
10166
+ const children = ordinaryStructChildren(field);
10167
+ if (!children)
10168
+ fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
10169
+ const matches = fieldsByExactName(children, path[depth]);
10170
+ if (matches.length !== 1)
10171
+ fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
10172
+ field = children[matches[0]];
10173
+ }
10174
+ if (path.length === 1 && isGeneratedField(field))
10175
+ fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
10176
+ required.add(JSON.stringify(path));
10177
+ break;
10178
+ }
10179
+ case "PRIMARY_KEY":
10180
+ case "UNIQUE": {
10181
+ for (const path of record.columns) {
10182
+ const index = resolveTop(path);
10183
+ if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
10184
+ fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
10185
+ }
10186
+ if (record.kind === "PRIMARY_KEY") {
10187
+ if (++primaryKeys > 1)
10188
+ fail("a table may have only one PRIMARY KEY");
10189
+ for (const path of record.columns)
10190
+ required.add(JSON.stringify(path));
10191
+ }
10192
+ break;
10193
+ }
10194
+ case "FOREIGN_KEY": {
10195
+ record.columns.forEach(resolveTop);
10196
+ const ref = record.references;
10197
+ if (ref == null || ref.constraintId == null)
10198
+ fail("FOREIGN_KEY requires a referenced table and referenced constraint");
10199
+ if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
10200
+ fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
10201
+ if (ref.columns.length !== record.columns.length)
10202
+ fail("foreign key arity mismatch");
10203
+ try {
10204
+ checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
10205
+ } catch (error) {
10206
+ fail(error.message);
10207
+ }
10208
+ if (ref.match !== undefined && ref.match !== "SIMPLE")
10209
+ fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
10210
+ for (const action of [ref.onUpdate, ref.onDelete])
10211
+ if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
10212
+ fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
10213
+ break;
10214
+ }
10215
+ default:
10216
+ fail(`unknown constraint kind ${String(record.kind)}`);
10217
+ }
10218
+ records.push(record);
10219
+ }
10220
+ return { records, required };
10221
+ }
10222
+ function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
10223
+ const info = decodeASD(ConstraintInfoSchema, bytes);
10224
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
10225
+ const expression = decodeASD(SqlExpressionSchema, def.check_expression);
10226
+ const fail = (message) => {
10227
+ throw new Error(`${where}: ${message}`);
10228
+ };
10229
+ if (expression.profile !== ROW_SCALAR_EXPRESSION)
10230
+ fail(`unsupported CHECK expression profile ${expression.profile}`);
10231
+ if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
10232
+ fail("CHECK expression belongs to another schema");
10233
+ const context = expression.evaluation_context ?? {};
10234
+ for (const [key, value] of Object.entries(CHECK_CONTEXT))
10235
+ if (context[key] !== value)
10236
+ fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
10237
+ try {
10238
+ validateNumericCheckSql(expression.sql, (name) => {
10239
+ const lower = name.toLowerCase();
10240
+ const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
10241
+ if (matches.length > 1)
10242
+ throw new Error(`ambiguous CHECK column reference ${name}`);
10243
+ if (matches.length === 0 || matches[0] === rowId)
10244
+ throw new Error(`CHECK references a missing or row-id column ${name}`);
10245
+ const column = fields[matches[0]];
10246
+ if (column.metadata.has("ARROW:extension:name"))
10247
+ throw new Error(`CHECK operand ${name} has an extension type`);
10248
+ if (isGeneratedField(column))
10249
+ throw new Error(`CHECK operand ${name} is a generated column`);
10250
+ const type = duckdbPrimitive(column);
10251
+ if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
10252
+ throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
10253
+ });
10254
+ } catch (error) {
10255
+ fail(`${error.message} (CHECK SQL: ${expression.sql})`);
10256
+ }
10257
+ }
10258
+ function validateForeignKeyTargets(tables) {
10259
+ const key = (schemaPath, name) => JSON.stringify([...schemaPath, name]);
10260
+ const byTable = new Map;
10261
+ for (const t of tables)
10262
+ byTable.set(key(t.schemaPath, t.name), t.constraints.map(readConstraintRecord));
10263
+ for (const t of tables) {
10264
+ for (const record of byTable.get(key(t.schemaPath, t.name)) ?? []) {
10265
+ if (record.kind !== "FOREIGN_KEY" || record.references == null)
10266
+ continue;
10267
+ const ref = record.references;
10268
+ const where = `Table '${t.name}': constraint '${record.id}'`;
10269
+ const target = byTable.get(key(ref.schemaPath, ref.table));
10270
+ if (!target)
10271
+ throw new Error(`${where}: references table ${[...ref.schemaPath, ref.table].join(".")}, which this catalog does not serve`);
10272
+ const key_ = target.find((r) => r.id === ref.constraintId);
10273
+ if (!key_ || key_.kind !== "PRIMARY_KEY" && key_.kind !== "UNIQUE")
10274
+ throw new Error(`${where}: referenced constraint '${ref.constraintId}' is not a PRIMARY_KEY or UNIQUE record of '${ref.table}'`);
10275
+ const want = new Set(ref.columns.map((p) => JSON.stringify(p)));
10276
+ if (key_.columns.length !== want.size || !key_.columns.every((p) => want.has(JSON.stringify(p))))
10277
+ throw new Error(`${where}: referenced columns do not match constraint '${ref.constraintId}' of '${ref.table}'`);
10278
+ }
10279
+ }
10280
+ }
10281
+ function servedConstraintFields(fields, required) {
10282
+ const rewrite = (list, prefix) => {
10283
+ let changed = false;
10284
+ const out = list.map((f) => {
10285
+ if (prefix.length === 0 && isRowIdField(f))
10286
+ return f;
10287
+ const path = [...prefix, f.name];
10288
+ const nullable = !required.has(JSON.stringify(path));
10289
+ const children = ordinaryStructChildren(f);
10290
+ const newChildren = children ? rewrite(children, path) : null;
10291
+ if (nullable === f.nullable && (newChildren == null || newChildren === children))
10292
+ return f;
10293
+ changed = true;
10294
+ const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
10295
+ return field2(f.name, type, nullable, new Map(f.metadata));
10296
+ });
10297
+ return changed ? out : list;
10298
+ };
10299
+ return rewrite(fields, []);
10300
+ }
10301
+ function validateConstraintNullability(table, fields, constraints) {
10302
+ const schemaPath = constraints.length ? readConstraintRecord(constraints[0]).schemaPath : ["main"];
10303
+ validateTableConstraints(table, schemaPath, fields, constraints);
10304
+ }
10305
+ function translateLegacyGenerated(fields, owner, table) {
10306
+ let changed = false;
10307
+ const out = fields.map((f) => {
10308
+ const sql = f.metadata.get("generated_expression");
10309
+ if (sql === undefined)
10310
+ return f;
10311
+ if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
10312
+ throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
10313
+ const metadata = new Map(f.metadata);
10314
+ metadata.delete("generated_expression");
10315
+ metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
10316
+ metadata.set(GENERATION_KEY, "virtual");
10317
+ changed = true;
10318
+ return field2(f.name, f.type, f.nullable, metadata);
10319
+ });
10320
+ return changed ? out : fields;
10321
+ }
10322
+ function servedTableSchema(table, schemaPath, schema, constraints) {
10323
+ let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
10324
+ const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
10325
+ fields = servedConstraintFields(fields, required);
10326
+ return fields === schema.fields ? schema : schema2(fields, schema.metadata);
10327
+ }
10328
+ function servedTableInfo(info) {
10329
+ if (!info.columns || info.columns.length === 0) {
10330
+ if ((info.constraints ?? []).length)
10331
+ throw new Error(`Table '${info.name}': constraints on a table without columns`);
10332
+ return info;
10333
+ }
10334
+ const schema = deserializeSchema(info.columns);
10335
+ const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
10336
+ return served === schema ? info : { ...info, columns: serializeSchema(served) };
10337
+ }
10338
+ // src/generated/vgi-client.ts
10339
+ var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
10340
+ var decodeCatalogInfo = (b) => decodeASD(CatalogInfoSchema, b);
10341
+ var encodeFunctionInfo = (v) => encodeASD(FunctionInfoSchema, v);
10342
+ var decodeFunctionInfo = (b) => decodeASD(FunctionInfoSchema, b);
10343
+ var encodeIndexInfo = (v) => encodeASD(IndexInfoSchema, v);
10344
+ var decodeIndexInfo = (b) => decodeASD(IndexInfoSchema, b);
10345
+ var encodeMacroInfo = (v) => encodeASD(MacroInfoSchema, v);
10346
+ var decodeMacroInfo = (b) => decodeASD(MacroInfoSchema, b);
10347
+ var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
10348
+ var decodeSchemaInfo = (b) => decodeASD(SchemaInfoSchema, b);
10349
+ var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
10350
+ var decodeTableInfo = (b) => decodeASD(TableInfoSchema, b);
10351
+ var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
10352
+ var decodeViewInfo = (b) => decodeASD(ViewInfoSchema, b);
10353
+ // src/catalog/interface.ts
10354
+ init_arrow();
10355
+ var encodeCopyFromFormatInfo = (v) => encodeASD(CopyFromFormatInfoSchema, {
10356
+ comment: v.comment ?? null,
10357
+ tags: v.tags ?? {},
10358
+ format_name: v.format_name,
10359
+ handler: v.handler,
10360
+ options: v.options,
10361
+ direction: v.direction ?? "from",
10362
+ description: v.description ?? "",
10363
+ ordered: v.ordered ?? false
10364
+ });
10365
+ var encodeAttachCatalogInfo = (v) => encodeASD(AttachCatalogInfoSchema, {
10366
+ alias: v.alias,
10367
+ target: v.target,
10368
+ db_type: v.db_type ?? "",
10369
+ options: v.options ?? {},
10370
+ hidden: v.hidden ?? false,
10371
+ required: v.required ?? false,
10372
+ secret_ref: v.secret_ref ?? ""
10373
+ });
10374
+ function encodeScanFunctionResult(functionName, argumentsBytes, requiredExtensions = [], schemaPath = null) {
10375
+ return serializeBatch(batchFromColumns(conformColumns(ScanFunctionResultSchema, {
10376
+ function_name: [functionName],
10377
+ arguments: [argumentsBytes],
10378
+ required_extensions: [requiredExtensions],
10379
+ schema_path: [schemaPath]
10380
+ }), ScanFunctionResultSchema));
10381
+ }
10382
+ function decodeScanFunctionResult(inner) {
10383
+ const argsBytes = inner.arguments;
10384
+ const positionalArguments = [];
10385
+ const namedArguments = {};
10386
+ if (argsBytes != null) {
10387
+ const batch = deserializeBatch(toUint8Array(argsBytes));
10388
+ for (const field of batch.schema.fields) {
10389
+ const col = batch.getChild(field.name);
10390
+ const value = col ? col.get(0) : null;
10391
+ if (field.name.startsWith("arg_")) {
10392
+ const idx = parseInt(field.name.slice(4), 10);
10393
+ while (positionalArguments.length <= idx)
10394
+ positionalArguments.push(null);
10395
+ positionalArguments[idx] = value;
10396
+ } else {
10397
+ namedArguments[field.name] = value;
10398
+ }
10399
+ }
10400
+ }
10401
+ const exts = inner.required_extensions;
10402
+ const requiredExtensions = exts == null ? [] : (Array.isArray(exts) ? exts : [...exts]).filter((v) => v != null).map(String);
10403
+ return {
10404
+ functionName: String(inner.function_name ?? ""),
10405
+ positionalArguments,
10406
+ namedArguments,
10407
+ requiredExtensions,
10408
+ schemaPath: inner.schema_path == null ? null : (Array.isArray(inner.schema_path) ? inner.schema_path : [...inner.schema_path]).filter((value) => value != null).map(String)
10409
+ };
10410
+ }
10411
+ function singleBranchResult(legacy) {
10412
+ return {
10413
+ branches: [
10414
+ encodeScanBranch({
10415
+ function_name: legacy.function_name,
10416
+ arguments: toUint8Array(legacy.arguments),
10417
+ schema_path: legacy.schema_path ?? null
10418
+ })
10419
+ ],
10420
+ required_extensions: legacy.required_extensions ?? []
10421
+ };
10422
+ }
10423
+ function encodeScanBranch(cols) {
10424
+ return serializeBatch(batchFromColumns(conformColumns(ScanBranchSchema, {
10425
+ function_name: [cols.function_name],
10426
+ arguments: [cols.arguments],
10427
+ branch_filter: [cols.branch_filter ?? null],
10428
+ writable: [cols.writable ?? false],
10429
+ source_catalog: [cols.source_catalog ?? null],
10430
+ source_schema_path: [cols.source_schema_path ?? null],
10431
+ source_table: [cols.source_table ?? null],
10432
+ format_name: [cols.format_name ?? null],
10433
+ format_locations: [cols.format_locations ?? null],
10434
+ format_options: [cols.format_options ?? null],
10435
+ schema_path: [cols.schema_path ?? null]
10436
+ }), ScanBranchSchema));
10437
+ }
10438
+ function encodeFormatOptions(options) {
10439
+ const fields = [];
10440
+ const values = {};
10441
+ for (const [name, arg] of Object.entries(options)) {
10442
+ fields.push(field2(name, arg.type, true));
10443
+ values[name] = [arg.value];
10444
+ }
10445
+ return serializeBatch(batchFromColumns(values, schema2(fields)));
10446
+ }
10447
+ function serializeBranchArguments(branch) {
10448
+ const fields = [];
10449
+ const values = {};
10450
+ const positional = branch.positionalArguments ?? [];
10451
+ positional.forEach((arg, index) => {
10452
+ const name = `arg_${index}`;
10453
+ fields.push(field2(name, arg.type, true));
10454
+ values[name] = [arg.value];
10455
+ });
10456
+ for (const [name, arg] of Object.entries(branch.namedArguments ?? {})) {
10457
+ fields.push(field2(name, arg.type, true));
10458
+ values[name] = [arg.value];
10459
+ }
10460
+ const batchSchema = schema2(fields);
10461
+ return serializeBatch(batchFromColumns(values, batchSchema));
10462
+ }
10463
+ function buildScanBranchesResult(branches, requiredExtensions = []) {
10464
+ const serializedBranches = branches.map((branch) => encodeScanBranch({
10465
+ function_name: branch.functionName,
10466
+ arguments: serializeBranchArguments(branch),
10467
+ branch_filter: branch.branchFilter,
10468
+ writable: branch.writable,
10469
+ source_catalog: branch.sourceCatalog,
10470
+ source_schema_path: branch.sourceSchemaPath,
10471
+ source_table: branch.sourceTable,
10472
+ format_name: branch.formatName,
10473
+ format_locations: branch.formatLocations,
10474
+ format_options: branch.formatOptions,
10475
+ schema_path: branch.schemaPath
10476
+ }));
10477
+ return {
10478
+ branches: serializedBranches,
10479
+ required_extensions: requiredExtensions
10480
+ };
10481
+ }
10482
+ function isPromise(v) {
10483
+ return v != null && typeof v.then === "function";
10484
+ }
10485
+
10486
+ class CatalogInterface {
10487
+ catalogSnapshotPolicy = null;
10488
+ catalogContentsEtag = null;
10489
+ catalogContentsAttachIndependent = false;
10490
+ catalogVersionFrozen = false;
10491
+ catalogNameForAttach(_attachOpaqueData) {
10492
+ const names = this.catalogs();
10493
+ return names.length === 1 ? names[0] : null;
10494
+ }
10495
+ create(name, onConflict, options) {
10496
+ throw new CatalogReadOnlyError("create");
10497
+ }
10498
+ drop(name) {
10499
+ throw new CatalogReadOnlyError("drop");
10500
+ }
10501
+ schemaGet(attachOpaqueData, path, transactionOpaqueData) {
10502
+ const all = this.schemas(attachOpaqueData, transactionOpaqueData);
10503
+ if (isPromise(all)) {
10504
+ return all.then((arr) => arr.find((s) => schemaPathsEqual(s.path, path)) ?? null);
10505
+ }
10506
+ return all.find((s) => schemaPathsEqual(s.path, path)) ?? null;
10507
+ }
10508
+ schemaCreate(attachOpaqueData, path, comment, tags, transactionOpaqueData, onConflict) {
10509
+ throw new CatalogReadOnlyError("schema_create");
10510
+ }
10511
+ schemaDrop(attachOpaqueData, path, ignoreNotFound, cascade, transactionOpaqueData) {
10512
+ throw new CatalogReadOnlyError("schema_drop");
10513
+ }
10514
+ schemaContentsTables(attachOpaqueData, path, transactionOpaqueData) {
10515
+ return [];
10516
+ }
10517
+ schemaContentsViews(attachOpaqueData, path, transactionOpaqueData) {
10518
+ return [];
10519
+ }
10520
+ schemaContentsFunctions(attachOpaqueData, path, type, transactionOpaqueData) {
10521
+ return [];
10522
+ }
10523
+ tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10524
+ return null;
10525
+ }
10526
+ tableCreate(attachOpaqueData, schemaPath, name, columns, onConflict, constraintDefinitions, transactionOpaqueData) {
10527
+ throw new CatalogReadOnlyError("table_create");
10528
+ }
10529
+ catalogCapabilities(_attachOpaqueData) {
10530
+ const proto = CatalogInterface.prototype;
10531
+ if (this.tableConstraintsApply !== proto.tableConstraintsApply || this._implementsLegacyNotNull())
10532
+ return constraintCapabilities({ mutate: true, enforce: true });
10533
+ return null;
10534
+ }
10535
+ _implementsLegacyNotNull() {
10536
+ const proto = CatalogInterface.prototype;
10537
+ return this.tableNotNullSet !== proto.tableNotNullSet || this.tableNotNullDrop !== proto.tableNotNullDrop;
10538
+ }
10539
+ async tableConstraintsApply(request) {
10540
+ if (!this._implementsLegacyNotNull())
10541
+ throw new VgiError("catalog_table_constraints_apply is not implemented by this catalog", "UNIMPLEMENTED");
10542
+ const target = decodeCatalogObjectRef(request.table);
10543
+ const attach = request.attach_opaque_data;
10544
+ const tx = request.transaction_opaque_data ?? undefined;
10545
+ const schemaPath = [...target.schema_path];
10546
+ const read = async () => {
10547
+ const info = await this.tableGet(attach, schemaPath, target.name, undefined, undefined, tx);
10548
+ if (!info)
10549
+ throw new CatalogNotFoundError("Table", target.name);
10550
+ return info;
10551
+ };
10552
+ const before = await read();
10553
+ if (!sameBytes2(before.definition_revision ?? null, request.expected_revision))
10554
+ throw new VgiError(`Table '${target.name}': definition_revision changed; retry the statement`, "FAILED_PRECONDITION");
10555
+ const records = (before.constraints ?? []).map(readConstraintRecord);
10556
+ for (const bytes of request.changes) {
10557
+ const change = decodeConstraintChange(bytes);
10558
+ if (change.operation === "ADD" && change.definition != null) {
10559
+ const def = decodeConstraintDefinition(change.definition);
10560
+ if (def.kind === "NOT_NULL" && def.column_paths.length === 1 && def.column_paths[0].length === 1) {
10561
+ await this.tableNotNullSet(attach, schemaPath, target.name, [...def.column_paths[0]], false, tx);
10562
+ continue;
10563
+ }
10564
+ } else if (change.operation === "DROP" && change.ref != null) {
10565
+ const id = decodeCatalogObjectRef(change.ref).name;
10566
+ const record = records.find((r) => r.id === id);
10567
+ if (record?.kind === "NOT_NULL" && record.columns[0]?.length === 1) {
10568
+ await this.tableNotNullDrop(attach, schemaPath, target.name, record.columns[0], false, tx);
10569
+ continue;
10570
+ }
10571
+ }
10572
+ throw new VgiError("catalog_table_constraints_apply: only ADD/DROP of a top-level NOT_NULL routes to tableNotNullSet/tableNotNullDrop; implement tableConstraintsApply", "UNIMPLEMENTED");
10573
+ }
10574
+ const after = await read();
10575
+ if (after.definition_revision == null || sameBytes2(after.definition_revision, before.definition_revision ?? null))
10576
+ throw new VgiError(`Table '${target.name}': the NOT NULL change was applied but tableGet still serves the old definition_revision; ` + "a catalog using tableNotNullSet/tableNotNullDrop must rotate it (or implement tableConstraintsApply)", "INTERNAL");
10577
+ return { table: request.table, definition_revision: after.definition_revision, constraints: after.constraints ?? [] };
10578
+ }
10579
+ tableDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
10580
+ throw new CatalogReadOnlyError("table_drop");
10581
+ }
10582
+ tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10583
+ throw new CatalogReadOnlyError("table_scan_function_get");
10584
+ }
10585
+ tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10586
+ const legacy = this.tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
10587
+ return isPromise(legacy) ? legacy.then((r) => singleBranchResult(r)) : singleBranchResult(legacy);
10588
+ }
10589
+ tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10590
+ return null;
10591
+ }
10592
+ tableCommentSet(attachOpaqueData, schemaPath, name, comment, ignoreNotFound, transactionOpaqueData) {
10593
+ throw new CatalogReadOnlyError("table_comment_set");
10594
+ }
10595
+ tableRename(attachOpaqueData, schemaPath, name, newName, ignoreNotFound, transactionOpaqueData) {
10596
+ throw new CatalogReadOnlyError("table_rename");
10597
+ }
10598
+ tableColumnAdd(attachOpaqueData, schemaPath, name, columnPath, columnDefinition, ignoreNotFound = false, ifColumnNotExists = false, transactionOpaqueData) {
10599
+ throw new CatalogReadOnlyError("catalog_table_column_add");
10600
+ }
10601
+ tableColumnDrop(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, ifColumnExists = false, cascade = false, transactionOpaqueData) {
10602
+ throw new CatalogReadOnlyError("catalog_table_column_drop");
10603
+ }
10604
+ tableColumnRename(attachOpaqueData, schemaPath, name, columnPath, newColumnName, ignoreNotFound = false, transactionOpaqueData) {
10605
+ throw new CatalogReadOnlyError("catalog_table_column_rename");
10606
+ }
10607
+ tableColumnCommentSet(attachOpaqueData, schemaPath, name, columnPath, comment, ignoreNotFound = false, transactionOpaqueData) {
10608
+ throw new CatalogReadOnlyError("catalog_table_column_comment_set");
10609
+ }
10610
+ tableColumnDefaultSet(attachOpaqueData, schemaPath, name, columnPath, expression, ignoreNotFound = false, transactionOpaqueData) {
10611
+ throw new CatalogReadOnlyError("catalog_table_column_default_set");
10612
+ }
10613
+ tableColumnDefaultDrop(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, transactionOpaqueData) {
10614
+ throw new CatalogReadOnlyError("catalog_table_column_default_drop");
10615
+ }
10616
+ tableColumnTypeChange(attachOpaqueData, schemaPath, name, columnPath, columnDefinition, expression = null, ignoreNotFound = false, transactionOpaqueData) {
10617
+ throw new CatalogReadOnlyError("catalog_table_column_type_change");
10618
+ }
10619
+ tableNotNullSet(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, transactionOpaqueData) {
10620
+ throw new CatalogReadOnlyError("catalog_table_not_null_set");
10621
+ }
10622
+ tableNotNullDrop(attachOpaqueData, schemaPath, name, columnPath, ignoreNotFound = false, transactionOpaqueData) {
10623
+ throw new CatalogReadOnlyError("catalog_table_not_null_drop");
10624
+ }
10625
+ viewGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10626
+ return null;
10627
+ }
10628
+ viewCreate(attachOpaqueData, schemaPath, name, definition, onConflict, transactionOpaqueData, aliases, comment, tags, columnComments) {
10629
+ throw new CatalogReadOnlyError("view_create");
10630
+ }
10631
+ viewDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
10632
+ throw new CatalogReadOnlyError("view_drop");
10633
+ }
10634
+ viewRename(attachOpaqueData, schemaPath, name, newName, ignoreNotFound, transactionOpaqueData) {
10635
+ throw new CatalogReadOnlyError("view_rename");
10636
+ }
10637
+ viewCommentSet(attachOpaqueData, schemaPath, name, comment, ignoreNotFound, transactionOpaqueData) {
10638
+ throw new CatalogReadOnlyError("view_comment_set");
10639
+ }
10640
+ viewColumnCommentSet(attachOpaqueData, schemaPath, name, columnPath, comment, ignoreNotFound, transactionOpaqueData) {
10641
+ throw new CatalogReadOnlyError("view_column_comment_set");
10642
+ }
10643
+ macroGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10644
+ return null;
10645
+ }
10646
+ macroCreate(attachOpaqueData, schemaPath, name, macroType, overloads, onConflict, transactionOpaqueData) {
10647
+ throw new CatalogReadOnlyError("macro_create");
10648
+ }
10649
+ macroDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
10650
+ throw new CatalogReadOnlyError("macro_drop");
10651
+ }
10652
+ schemaContentsMacros(attachOpaqueData, path, type, transactionOpaqueData) {
10653
+ return [];
10654
+ }
10655
+ schemaContentsIndexes(attachOpaqueData, path, transactionOpaqueData) {
10656
+ return [];
10657
+ }
10658
+ indexGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10659
+ return null;
10660
+ }
10661
+ copyFromFormats(attachOpaqueData, transactionOpaqueData) {
10662
+ return [];
10663
+ }
10664
+ async catalogContents(attachOpaqueData, _ifNoneMatch) {
10665
+ const schemas = await this.schemas(attachOpaqueData, undefined);
10666
+ const contents = await Promise.all(schemas.map(async (schema) => {
10667
+ const counts = schema.estimated_object_count ?? {};
10668
+ const path = schema.path;
10669
+ const kind = async (countKey, list) => (counts[countKey] ?? 1) === 0 ? [] : [...await list()];
10670
+ const [tables, views, scalarFunctions, aggregateFunctions, tableFunctions, scalarMacros, tableMacros, indexes] = await Promise.all([
10671
+ kind("table", () => this.schemaContentsTables(attachOpaqueData, path)),
10672
+ kind("view", () => this.schemaContentsViews(attachOpaqueData, path)),
10673
+ kind("scalar_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "scalar_function")),
10674
+ kind("aggregate_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "aggregate_function")),
10675
+ kind("table_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "table_function")),
10676
+ kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "scalar_macro")),
10677
+ kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "table_macro")),
10678
+ kind("index", () => this.schemaContentsIndexes(attachOpaqueData, path))
10679
+ ]);
10680
+ return {
10681
+ schema,
10682
+ tables,
10683
+ views,
10684
+ scalar_functions: scalarFunctions,
10685
+ aggregate_functions: aggregateFunctions,
10686
+ table_functions: tableFunctions,
10687
+ scalar_macros: scalarMacros,
10688
+ table_macros: tableMacros,
10689
+ indexes
10690
+ };
10691
+ }));
10692
+ return { schemas: contents };
10693
+ }
10694
+ catalogContentsCacheable() {
10695
+ return this.catalogContentsAttachIndependent && this.catalogVersionFrozen;
10696
+ }
10697
+ catalogContentsOwner(_attachOpaqueData) {
10698
+ return this;
10699
+ }
10700
+ transactionBegin(attachOpaqueData) {
10701
+ return null;
10702
+ }
10703
+ transactionCommit(attachOpaqueData, transactionOpaqueData) {}
10704
+ transactionRollback(attachOpaqueData, transactionOpaqueData) {}
9404
10705
  }
9405
- function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
9406
- validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
10706
+ function sameBytes2(a, b) {
10707
+ if (a == null || b == null)
10708
+ return a == b;
10709
+ if (a.length !== b.length)
10710
+ return false;
10711
+ for (let i = 0;i < a.length; i++)
10712
+ if (a[i] !== b[i])
10713
+ return false;
10714
+ return true;
9407
10715
  }
9408
-
9409
10716
  // src/catalog/column-metadata.ts
9410
10717
  function scalarText(value) {
9411
10718
  for (let i = 0;i < value.length; i++) {
@@ -9557,9 +10864,21 @@ function validateTableInfoColumns(info) {
9557
10864
  validateColumnExpressionsIpc(info.columns, info.schema_path);
9558
10865
  }
9559
10866
  }
10867
+ function servedValidatedTableInfo(info) {
10868
+ if (info.columns.length)
10869
+ validateColumnMetadataIpc(info.columns);
10870
+ const served = servedTableInfo(info);
10871
+ if (served.columns.length) {
10872
+ try {
10873
+ validateColumnExpressionsIpc(served.columns, served.schema_path);
10874
+ } catch (error) {
10875
+ throw new Error(`Table '${served.name}': ${error.message}`);
10876
+ }
10877
+ }
10878
+ return served;
10879
+ }
9560
10880
  function encodeValidatedTableInfo(info) {
9561
- validateTableInfoColumns(info);
9562
- return encodeTableInfo(info);
10881
+ return encodeTableInfo(servedValidatedTableInfo(info));
9563
10882
  }
9564
10883
 
9565
10884
  // src/catalog/read-only.ts
@@ -9926,128 +11245,6 @@ function macroOverloads(macro, owner) {
9926
11245
  }];
9927
11246
  }
9928
11247
 
9929
- // src/catalog/constraints.ts
9930
- init_arrow();
9931
- var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
9932
- var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
9933
- function objectRef(kind, schemaPath, name, ownerTable) {
9934
- return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
9935
- }
9936
- function constraintRecord(spec) {
9937
- if (!spec.id || spec.id.includes("\x00"))
9938
- throw new Error("constraint id must be nonempty without NUL");
9939
- if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
9940
- throw new Error("checkSql is required for CHECK and only CHECK");
9941
- if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
9942
- throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
9943
- if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
9944
- throw new Error("NOT_NULL requires exactly one column path");
9945
- if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
9946
- throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
9947
- if (spec.references && spec.references.columns.length !== spec.columns.length)
9948
- throw new Error("foreign key local and referenced arity must match");
9949
- const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
9950
- sql: spec.checkSql,
9951
- profile: ROW_SCALAR_EXPRESSION,
9952
- schema_path: spec.schemaPath,
9953
- evaluation_context: {
9954
- timezone: "UTC",
9955
- collation: "binary",
9956
- default_order: "asc",
9957
- default_null_order: "nulls_last",
9958
- preserve_insertion_order: true
9959
- }
9960
- });
9961
- const ref = spec.references;
9962
- const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
9963
- referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
9964
- referenced_column_paths: ref.columns,
9965
- match: "SIMPLE",
9966
- on_update: "NO_ACTION",
9967
- on_delete: "NO_ACTION"
9968
- });
9969
- return encodeASD(ConstraintInfoSchema, {
9970
- ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
9971
- definition: encodeASD(ConstraintDefinitionSchema, {
9972
- kind: spec.kind,
9973
- column_paths: spec.columns,
9974
- declared_name: spec.declaredName ?? null,
9975
- check_expression: check,
9976
- foreign_key: foreign
9977
- }),
9978
- enforcement: spec.enforcement,
9979
- validation: spec.validation,
9980
- referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
9981
- });
9982
- }
9983
- function selectReadProfiles(available, clientCapabilities) {
9984
- if (clientCapabilities == null || available.length === 0)
9985
- return [];
9986
- const client = decodeASD(ClientCapabilitiesSchema, clientCapabilities);
9987
- const offered = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
9988
- const selected = available.filter((p) => offered.includes(p));
9989
- if (!selected.includes(CONSTRAINT_RECORDS_READ))
9990
- return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
9991
- return selected.sort();
9992
- }
9993
- function readConstraintRecord(bytes) {
9994
- const info = decodeASD(ConstraintInfoSchema, bytes);
9995
- const ref = decodeASD(CatalogObjectRefSchema, info.ref);
9996
- const def = decodeASD(ConstraintDefinitionSchema, info.definition);
9997
- const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
9998
- const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
9999
- const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
10000
- return {
10001
- schemaPath: [...ref.schema_path],
10002
- table: ref.owner_table ?? "",
10003
- id: ref.name,
10004
- kind: def.kind,
10005
- columns: [...def.column_paths].map((p) => [...p]),
10006
- enforcement: info.enforcement,
10007
- validation: info.validation,
10008
- declaredName: def.declared_name ?? null,
10009
- checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
10010
- references: fk == null || target == null ? null : {
10011
- schemaPath: [...target.schema_path],
10012
- table: target.name,
10013
- columns: [...fk.referenced_column_paths].map((p) => [...p]),
10014
- constraintId: targetKey?.name ?? null
10015
- }
10016
- };
10017
- }
10018
- function ordinaryStructChildren(field) {
10019
- if (!isStruct(field.type))
10020
- return null;
10021
- for (const key of field.metadata.keys())
10022
- if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
10023
- return null;
10024
- return field.type.children;
10025
- }
10026
- function validateConstraintNullability(table, fields, constraints) {
10027
- const required = new Set;
10028
- for (const bytes of constraints) {
10029
- const record = readConstraintRecord(bytes);
10030
- if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
10031
- throw new Error(`Table '${table}': constraint '${record.id}' is ${record.enforcement}/${record.validation}; ` + "DuckDB accepts only ENFORCED + ALL_ROWS records");
10032
- if (record.kind === "NOT_NULL" || record.kind === "PRIMARY_KEY")
10033
- for (const path of record.columns)
10034
- required.add(JSON.stringify(path));
10035
- }
10036
- const walk = (children, prefix) => {
10037
- for (const field of children) {
10038
- const path = [...prefix, field.name];
10039
- const key = JSON.stringify(path);
10040
- if (field.nullable === required.has(key)) {
10041
- throw new Error(field.nullable ? `Table '${table}': column ${path.join(".")} is in a NOT_NULL/PRIMARY_KEY record but its Arrow field is nullable` : `Table '${table}': column ${path.join(".")} is non-nullable in Arrow but no NOT_NULL/PRIMARY_KEY record names it; ` + "declare one with constraintRecord() or make the field nullable");
10042
- }
10043
- const nested = ordinaryStructChildren(field);
10044
- if (nested)
10045
- walk(nested, path);
10046
- }
10047
- };
10048
- walk(fields, []);
10049
- }
10050
-
10051
11248
  // src/catalog/read-only.ts
10052
11249
  var READ_ONLY_ITEM_ATTACH_ID = new TextEncoder().encode("readonly-catalog-");
10053
11250
 
@@ -10147,6 +11344,10 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10147
11344
  const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
10148
11345
  return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
10149
11346
  }
11347
+ catalogCapabilities(_attachOpaqueData) {
11348
+ const read = this.catalogReadProfiles();
11349
+ return read.length ? catalogCapabilities({ read }) : null;
11350
+ }
10150
11351
  detach(attachOpaqueData) {
10151
11352
  for (const [name, id] of this._attachments) {
10152
11353
  if (bufferEquals(id, attachOpaqueData)) {
@@ -10207,8 +11408,12 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10207
11408
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
10208
11409
  if (!schema || !schema.tables)
10209
11410
  return [];
10210
- return await Promise.all(schema.tables.map(async (t) => {
11411
+ const infos = await Promise.all(schema.tables.map(async (t) => {
11412
+ if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
11413
+ throw new Error(`Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` + "declare canonical records with constraintRecord() in `constraints` instead");
11414
+ }
10211
11415
  let colSchema;
11416
+ let bindFailed = false;
10212
11417
  if (t.columns) {
10213
11418
  colSchema = t.columns;
10214
11419
  } else if (t.function) {
@@ -10230,26 +11435,31 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10230
11435
  colSchema = response.output_schema;
10231
11436
  } catch {
10232
11437
  colSchema = schema2([]);
11438
+ bindFailed = true;
10233
11439
  }
10234
11440
  } else {
10235
11441
  colSchema = schema2([]);
10236
11442
  }
10237
- if (t.defaults) {
10238
- colSchema = applyDefaults(colSchema, t.defaults);
10239
- }
10240
- if (t.generatedColumns) {
10241
- colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path);
10242
- }
10243
- if (t.columnComments) {
10244
- colSchema = applyColumnComments(colSchema, t.columnComments);
11443
+ if (!bindFailed) {
11444
+ if (t.defaults) {
11445
+ colSchema = applyDefaults(colSchema, t.defaults, path);
11446
+ }
11447
+ if (t.generatedColumns) {
11448
+ colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path, t.name);
11449
+ }
11450
+ if (t.columnComments) {
11451
+ colSchema = applyColumnComments(colSchema, t.columnComments, t.name);
11452
+ }
10245
11453
  }
10246
11454
  validateColumnMetadata(colSchema);
10247
- validateConstraintNullability(t.name, colSchema.fields, t.constraints ?? []);
10248
- validateColumnExpressions(colSchema, path);
10249
- const columns = serializeSchema(colSchema);
10250
- if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
10251
- throw new Error(`Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` + "declare canonical records with constraintRecord() in `constraints` instead");
11455
+ const constraints = bindFailed ? [] : t.constraints ?? [];
11456
+ colSchema = servedTableSchema(t.name, path, colSchema, constraints);
11457
+ try {
11458
+ validateColumnExpressions(colSchema, path);
11459
+ } catch (error) {
11460
+ throw new Error(`Table '${t.name}': ${error.message}`);
10252
11461
  }
11462
+ const columns = serializeSchema(colSchema);
10253
11463
  const requiredFilters = t.requiredFilters ?? [];
10254
11464
  for (const group of requiredFilters) {
10255
11465
  if (!Array.isArray(group) || group.length === 0)
@@ -10284,7 +11494,7 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10284
11494
  name: t.name,
10285
11495
  schema_path: normalizeSchemaPath(path),
10286
11496
  columns,
10287
- constraints: t.constraints ?? [],
11497
+ constraints: [...constraints],
10288
11498
  definition_revision: t.definitionRevision ?? null,
10289
11499
  write_result_modes: {},
10290
11500
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
@@ -10297,6 +11507,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10297
11507
  required_filters: requiredFilters
10298
11508
  };
10299
11509
  }));
11510
+ validateForeignKeyTargets(infos.map((info) => ({ schemaPath: info.schema_path, name: info.name, constraints: info.constraints })));
11511
+ return infos;
10300
11512
  }
10301
11513
  tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10302
11514
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
@@ -10606,7 +11818,14 @@ function defaultToSql(value) {
10606
11818
  const escaped = value.replace(/'/g, "''");
10607
11819
  return `'${escaped}'`;
10608
11820
  }
10609
- function applyDefaults(schema, defaults) {
11821
+ function canonicalDefault(type, value) {
11822
+ if (type === "BOOLEAN")
11823
+ return typeof value === "boolean";
11824
+ if (type === "VARCHAR")
11825
+ return typeof value === "string";
11826
+ return false;
11827
+ }
11828
+ function applyDefaults(schema, defaults, owner) {
10610
11829
  let result = schema;
10611
11830
  for (const [colName, value] of Object.entries(defaults)) {
10612
11831
  const idx = result.fields.findIndex((f) => f.name === colName);
@@ -10614,7 +11833,12 @@ function applyDefaults(schema, defaults) {
10614
11833
  continue;
10615
11834
  const f = result.fields[idx];
10616
11835
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
10617
- existingMeta.set("default", defaultToSql(value));
11836
+ const sql = defaultToSql(value);
11837
+ if (canonicalDefault(duckdbPrimitive(f), value)) {
11838
+ existingMeta.set("vgi.column.default.v1", defaultExpressionMetadata(sql, owner));
11839
+ } else {
11840
+ existingMeta.set("default", sql);
11841
+ }
10618
11842
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
10619
11843
  const fields = [...result.fields];
10620
11844
  fields[idx] = newField;
@@ -10622,17 +11846,21 @@ function applyDefaults(schema, defaults) {
10622
11846
  }
10623
11847
  return result;
10624
11848
  }
10625
- function applyGeneratedColumns(schema, generated, owner) {
11849
+ function applyGeneratedColumns(schema, generated, owner, table) {
10626
11850
  let result = schema;
10627
11851
  for (const [colName, expression] of Object.entries(generated)) {
10628
11852
  const idx = result.fields.findIndex((f) => f.name === colName);
10629
11853
  if (idx < 0)
10630
- throw new Error(`generated expression references unknown column ${colName}`);
11854
+ throw new Error(`Table '${table}': generatedColumns names unknown column ${colName}`);
10631
11855
  const f = result.fields[idx];
10632
11856
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
10633
11857
  if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression"))
10634
- throw new Error("generated convenience conflicts with existing expression metadata");
10635
- existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
11858
+ throw new Error(`Table '${table}': generatedColumns for ${colName} conflicts with existing expression metadata`);
11859
+ try {
11860
+ existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
11861
+ } catch (error) {
11862
+ throw new Error(`Table '${table}': column ${colName}: ${error.message}`);
11863
+ }
10636
11864
  existingMeta.set(GENERATION_KEY, "virtual");
10637
11865
  const newField = field2(f.name, f.type, f.nullable, existingMeta);
10638
11866
  const fields = [...result.fields];
@@ -10641,12 +11869,12 @@ function applyGeneratedColumns(schema, generated, owner) {
10641
11869
  }
10642
11870
  return result;
10643
11871
  }
10644
- function applyColumnComments(schema, comments) {
11872
+ function applyColumnComments(schema, comments, table) {
10645
11873
  let result = schema;
10646
11874
  for (const [colName, comment] of Object.entries(comments)) {
10647
11875
  const idx = result.fields.findIndex((f) => f.name === colName);
10648
11876
  if (idx < 0)
10649
- throw new Error(`column comment references unknown field ${colName}`);
11877
+ throw new Error(`Table '${table}': columnComments names unknown column ${colName}`);
10650
11878
  const f = result.fields[idx];
10651
11879
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
10652
11880
  existingMeta.set("comment", comment);
@@ -10776,6 +12004,29 @@ function sameSpelling(left, right) {
10776
12004
  const b = normalizeSchemaPath(right);
10777
12005
  return a.length === b.length && a.every((part, i) => part === b[i]);
10778
12006
  }
12007
+ // src/catalog/indexes.ts
12008
+ var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
12009
+ function emptyIndexOptions() {
12010
+ return Uint8Array.from(atob(NO_OPTIONS_B64), (c) => c.charCodeAt(0));
12011
+ }
12012
+ function canonicalIndex(spec) {
12013
+ if (spec.columns.length === 0)
12014
+ throw new Error(`index on '${spec.table}' requires at least one key`);
12015
+ if (!spec.algorithm)
12016
+ throw new Error("index algorithm must be nonempty");
12017
+ const values = spec.options ?? emptyIndexOptions();
12018
+ return {
12019
+ definition: encodeASD(IndexDefinitionSchema, {
12020
+ table: encodeASD(CatalogObjectRefSchema, { kind: "table", schema_path: spec.schemaPath, name: spec.table, owner_table: null }),
12021
+ algorithm: spec.algorithm,
12022
+ keys: spec.columns.map((path) => encodeASD(IndexKeySchema, { column_path: path, expression: null })),
12023
+ options: values,
12024
+ constraint_type: spec.constraintType ?? "NONE",
12025
+ associated_constraint: spec.associatedConstraintId == null ? null : encodeASD(CatalogObjectRefSchema, { kind: "constraint", schema_path: spec.schemaPath, name: spec.associatedConstraintId, owner_table: spec.table })
12026
+ }),
12027
+ options: encodeASD(OptionStateSchema, { values, explicit_names: spec.explicitOptionNames ?? [] })
12028
+ };
12029
+ }
10779
12030
  // node_modules/@noble/ciphers/utils.js
10780
12031
  /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
10781
12032
  function isBytes(a) {
@@ -11712,6 +12963,12 @@ class CompositeCatalogInterface extends CatalogInterface {
11712
12963
  async tableNotNullDrop(...args) {
11713
12964
  await this._route(args[0]).tableNotNullDrop(...args);
11714
12965
  }
12966
+ async tableConstraintsApply(request) {
12967
+ return await this._route(request.attach_opaque_data).tableConstraintsApply(request);
12968
+ }
12969
+ async catalogCapabilities(attachOpaqueData) {
12970
+ return await this._route(attachOpaqueData).catalogCapabilities(attachOpaqueData);
12971
+ }
11715
12972
  async viewCreate(...args) {
11716
12973
  await this._route(args[0]).viewCreate(...args);
11717
12974
  }
@@ -12261,7 +13518,7 @@ import {
12261
13518
  Protocol
12262
13519
  } from "@query-farm/vgi-rpc";
12263
13520
  var VGI_PROTOCOL_NAME = "vgi.v3";
12264
- var VGI_PROTOCOL_VERSION = "3.0.0";
13521
+ var VGI_PROTOCOL_VERSION = "3.1.0";
12265
13522
  function exchangeStream(callbacks) {
12266
13523
  return { kind: "exchange", ...callbacks };
12267
13524
  }
@@ -14001,14 +15258,40 @@ function deserializePlanRequest(params) {
14001
15258
  projectionIds = [...raw].map(Number);
14002
15259
  }
14003
15260
  const asBigInt = (v) => v == null ? null : typeof v === "bigint" ? v : BigInt(Number(v));
15261
+ const asBytes = (v) => v == null ? null : toUint8Array2(v);
15262
+ const asBytesList = (v) => {
15263
+ if (v == null)
15264
+ return null;
15265
+ const values = Array.isArray(v) ? v : v && typeof v[Symbol.iterator] === "function" ? [...v] : [];
15266
+ return values.filter((entry) => entry != null).map(toUint8Array2);
15267
+ };
15268
+ const enumValue = (v, values) => {
15269
+ if (v == null)
15270
+ return null;
15271
+ const text = String(v);
15272
+ return values.includes(text) ? text : null;
15273
+ };
14004
15274
  return {
14005
15275
  bind_call: bindCall,
14006
- bind_opaque_data: params.bind_opaque_data ? toUint8Array2(params.bind_opaque_data) : null,
15276
+ bind_opaque_data: asBytes(params.bind_opaque_data),
14007
15277
  projection_ids: projectionIds,
14008
- pushdown_filters: params.pushdown_filters ? toUint8Array2(params.pushdown_filters) : null,
15278
+ pushdown_filters: asBytes(params.pushdown_filters),
15279
+ join_keys: asBytesList(params.join_keys),
15280
+ row_limit: asBigInt(params.row_limit),
14009
15281
  target_split_bytes: asBigInt(params.target_split_bytes),
14010
15282
  min_splits: asBigInt(params.min_splits),
14011
- cursor: params.cursor ? toUint8Array2(params.cursor) : null
15283
+ max_splits_per_response: asBigInt(params.max_splits_per_response),
15284
+ cursor: asBytes(params.cursor),
15285
+ refined_filters: asBytes(params.refined_filters),
15286
+ filters_complete: params.filters_complete == null ? true : Boolean(params.filters_complete),
15287
+ start_position: asBytes(params.start_position),
15288
+ end_position: asBytes(params.end_position),
15289
+ order_by_column_name: params.order_by_column_name == null ? null : String(params.order_by_column_name),
15290
+ order_by_direction: enumValue(params.order_by_direction, Object.values(OrderByDirection)),
15291
+ order_by_null_order: enumValue(params.order_by_null_order, Object.values(OrderByNullOrder)),
15292
+ order_by_limit: asBigInt(params.order_by_limit),
15293
+ tablesample_percentage: params.tablesample_percentage == null ? null : Number(params.tablesample_percentage),
15294
+ tablesample_seed: asBigInt(params.tablesample_seed)
14012
15295
  };
14013
15296
  }
14014
15297
  function fingerprintInputs(bindCallBytes) {
@@ -14028,6 +15311,9 @@ function scanSplitRow(split, token) {
14028
15311
  estimated_rows: asBigInt(split.estimatedRows),
14029
15312
  rows_exact: split.rowsExact === true,
14030
15313
  estimated_bytes: asBigInt(split.estimatedBytes),
15314
+ key_value: split.keyValue ?? null,
15315
+ range_index: asBigInt(split.rangeIndex),
15316
+ column_bounds: split.columnBounds ?? null,
14031
15317
  partition_bounds: split.partitionBounds ?? null,
14032
15318
  column_statistics: split.columnStatistics ?? null,
14033
15319
  location_ids: split.locationIds ?? null,
@@ -14048,12 +15334,14 @@ function planResponseRow(result, splitBlobs) {
14048
15334
  estimated_total_bytes: asBigInt(result.estimatedTotalBytes),
14049
15335
  catalog_version: asBigInt(result.catalogVersion),
14050
15336
  scope: result.scope ?? "catalog",
14051
- locations: null,
14052
- partitioning: [],
14053
- sort_order: [],
15337
+ locations: result.locations ?? null,
15338
+ key_grouping: result.keyGrouping ?? null,
15339
+ range_partitioning: result.rangePartitioning ?? null,
15340
+ partitioning: result.partitioning ?? null,
15341
+ sort_order: result.sortOrder ?? null,
14054
15342
  cache_max_age_seconds: asBigInt(result.cacheMaxAgeSeconds),
14055
- start_position: new Uint8Array(0),
14056
- end_position: new Uint8Array(0)
15343
+ start_position: result.startPosition ?? null,
15344
+ end_position: result.endPosition ?? null
14057
15345
  };
14058
15346
  }
14059
15347
 
@@ -14827,12 +16115,10 @@ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@qu
14827
16115
  var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
14828
16116
  var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
14829
16117
  function encodeCatalogStreams(inventory) {
14830
- for (const schema of inventory)
14831
- for (const table of schema.tables)
14832
- validateTableInfoColumns(table);
16118
+ const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
14833
16119
  const streams = {
14834
16120
  schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
14835
- tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
16121
+ tables: encodeASDCollection(TableInfoSchema, tables),
14836
16122
  views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
14837
16123
  functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
14838
16124
  macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
@@ -15888,13 +17174,10 @@ function catalogAdminHandlers(getCatalog, signingKey) {
15888
17174
  }
15889
17175
  const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
15890
17176
  const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, clientCapabilities);
15891
- if (result.catalog_capabilities != null) {
15892
- const available = decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities));
15893
- const chosen = result.selected_capabilities == null ? { read: [], ddl: [], write: [], transaction: [] } : decodeCatalogCapabilities(toUint8Array(result.selected_capabilities));
15894
- result.selected_capabilities = encodeCatalogCapabilities({
15895
- ...chosen,
15896
- read: selectReadProfiles(available.read, clientCapabilities)
15897
- });
17177
+ const advertised = result.catalog_capabilities != null ? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities)) : await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
17178
+ if (!capabilitiesEmpty(advertised)) {
17179
+ result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
17180
+ result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
15898
17181
  }
15899
17182
  const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
15900
17183
  return wrapResult(buildCatalogAttachResult({
@@ -16031,27 +17314,39 @@ import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-
16031
17314
  // src/catalog/unconstrained-columns.ts
16032
17315
  init_arrow();
16033
17316
  import { MethodNotImplementedError as MethodNotImplementedError3 } from "@query-farm/vgi-rpc";
16034
- function requireUnconstrainedColumns(columns) {
16035
- const visit = (field, top, depth) => {
17317
+ function requireCreateColumns(columns, constraintDefinitions = []) {
17318
+ const required = new Set;
17319
+ for (const bytes of constraintDefinitions) {
17320
+ let def;
17321
+ try {
17322
+ def = decodeConstraintDefinition(bytes);
17323
+ } catch (error) {
17324
+ throw new Error(`catalog_table_create: undecodable constraint definition: ${error.message}`);
17325
+ }
17326
+ if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
17327
+ for (const path of def.column_paths)
17328
+ required.add(JSON.stringify([...path]));
17329
+ }
17330
+ const visit = (field, path, depth) => {
16036
17331
  if (depth > 64)
16037
17332
  throw new MethodNotImplementedError3("catalog_table_create: column nesting exceeds supported depth");
16038
- if (top && field.metadata?.has("is_row_id"))
17333
+ if (depth === 0 && field.metadata?.has("is_row_id"))
16039
17334
  return;
16040
17335
  for (const key of field.metadata?.keys() ?? []) {
16041
17336
  if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
16042
17337
  throw new MethodNotImplementedError3("catalog_table_create: logical column types require negotiation");
16043
17338
  }
16044
17339
  }
16045
- if (!field.nullable) {
16046
- throw new MethodNotImplementedError3("catalog_table_create: nonnullable user columns require canonical constraints");
17340
+ if (!field.nullable && !required.has(JSON.stringify(path))) {
17341
+ throw new MethodNotImplementedError3(`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`);
16047
17342
  }
16048
17343
  if (isStruct(field.type)) {
16049
17344
  for (const child of field.type.children)
16050
- visit(child, false, depth + 1);
17345
+ visit(child, [...path, child.name], depth + 1);
16051
17346
  }
16052
17347
  };
16053
17348
  for (const field of deserializeSchema(columns).fields)
16054
- visit(field, true, 0);
17349
+ visit(field, [field.name], 0);
16055
17350
  }
16056
17351
 
16057
17352
  // src/protocol/handlers/catalog/table.ts
@@ -16073,19 +17368,57 @@ function catalogTableHandlers(getCatalog, signingKey) {
16073
17368
  const catalogTableCreate = catalogHandler(signingKey, async (params) => {
16074
17369
  if (params.constraint_definitions == null)
16075
17370
  throw new Error("constraint_definitions is required");
16076
- if (Array.from(params.constraint_definitions).length > 0) {
16077
- throw new MethodNotImplementedError4("catalog_table_create: canonical constraint enforcement is not supported");
16078
- }
17371
+ const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
16079
17372
  if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
16080
17373
  throw new MethodNotImplementedError4("catalog_table_create: table metadata/options/layout profiles are not supported");
16081
17374
  }
17375
+ const attach = toUint8Array(params.attach_opaque_data);
17376
+ const cat = getCatalog();
17377
+ if (definitions.length > 0) {
17378
+ const caps = await cat.catalogCapabilities(attach);
17379
+ if (caps != null && !(caps.ddl.includes(CONSTRAINT_CREATE) && caps.write.includes(CONSTRAINT_ENFORCE))) {
17380
+ throw new MethodNotImplementedError4("catalog_table_create: this catalog does not enforce constraints (NOT NULL, PRIMARY KEY, UNIQUE, CHECK, " + "FOREIGN KEY); it advertises neither vgi.constraint.create.v1 nor vgi.constraint.enforce.v1");
17381
+ }
17382
+ }
16082
17383
  validateColumnMetadataIpc(toUint8Array(params.columns));
16083
17384
  validateColumnExpressionsIpc(toUint8Array(params.columns), params.schema_path);
16084
- requireUnconstrainedColumns(toUint8Array(params.columns));
16085
- const cat = getCatalog();
16086
- await cat.tableCreate(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, [], params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
17385
+ requireCreateColumns(toUint8Array(params.columns), definitions);
17386
+ await cat.tableCreate(attach, params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, definitions, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
16087
17387
  return {};
16088
17388
  });
17389
+ const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
17390
+ const attach = toUint8Array(params.attach_opaque_data);
17391
+ const cat = getCatalog();
17392
+ const caps = await cat.catalogCapabilities(attach);
17393
+ if (caps != null && !caps.ddl.includes(CONSTRAINT_MUTATE)) {
17394
+ throw new MethodNotImplementedError4("catalog_table_constraints_apply: this catalog does not advertise vgi.constraint.mutate.v1");
17395
+ }
17396
+ const table = toUint8Array(params.table);
17397
+ const expected = toUint8Array(params.expected_revision);
17398
+ const changes = Array.from(params.changes, (c) => toUint8Array(c));
17399
+ if (expected.length === 0 || changes.length === 0)
17400
+ throw new Error("catalog_table_constraints_apply: empty revision or change list");
17401
+ const snapshot = await cat.tableConstraintsApply({
17402
+ attach_opaque_data: attach,
17403
+ table,
17404
+ expected_revision: expected,
17405
+ changes,
17406
+ transaction_opaque_data: params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : null
17407
+ });
17408
+ const want = decodeCatalogObjectRef(table);
17409
+ const got = decodeCatalogObjectRef(toUint8Array(snapshot.table));
17410
+ if (got.name !== want.name || JSON.stringify([...got.schema_path]) !== JSON.stringify([...want.schema_path]))
17411
+ throw new Error("catalog_table_constraints_apply: the catalog returned a snapshot of a different table");
17412
+ const revision = toUint8Array(snapshot.definition_revision);
17413
+ if (revision.length === 0 || revision.length === expected.length && revision.every((b, i) => b === expected[i]))
17414
+ throw new Error(`catalog_table_constraints_apply: table '${want.name}' must return a new, nonempty definition_revision`);
17415
+ for (const record of snapshot.constraints) {
17416
+ const view = readConstraintRecord(toUint8Array(record));
17417
+ if (view.table !== want.name || JSON.stringify(view.schemaPath) !== JSON.stringify([...want.schema_path]))
17418
+ throw new Error(`catalog_table_constraints_apply: constraint '${view.id}' belongs to another table`);
17419
+ }
17420
+ return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
17421
+ });
16089
17422
  const catalogTableDrop = catalogHandler(signingKey, async (params) => {
16090
17423
  const cat = getCatalog();
16091
17424
  await cat.tableDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -16173,9 +17506,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
16173
17506
  return {};
16174
17507
  });
16175
17508
  return {
16176
- catalogTableConstraintsApply: async () => {
16177
- throw new MethodNotImplementedError4("catalog_table_constraints_apply");
16178
- },
17509
+ catalogTableConstraintsApply,
16179
17510
  catalogTableGet,
16180
17511
  catalogTableCreate,
16181
17512
  catalogTableDrop,
@@ -16963,7 +18294,7 @@ class VgiClient {
16963
18294
  options: [wireOptions],
16964
18295
  data_version_spec: [opts?.dataVersionSpec ?? null],
16965
18296
  implementation_version: [opts?.implementationVersion ?? null],
16966
- client_capabilities: [opts?.clientCapabilities ? encodeASD(ClientCapabilitiesSchema, opts.clientCapabilities) : null]
18297
+ client_capabilities: [opts?.clientCapabilities === null ? null : encodeASD(ClientCapabilitiesSchema, opts?.clientCapabilities ?? defaultClientCapabilities("vgi-typescript-client"))]
16967
18298
  }, schema);
16968
18299
  const result = await this.rpc.call("catalog_attach", wrapRequest(innerBatch));
16969
18300
  if (!result)
@@ -17991,6 +19322,9 @@ export {
17991
19322
  CACHE_STALE_IF_ERROR_KEY,
17992
19323
  CACHE_STALE_WHILE_REVALIDATE_KEY,
17993
19324
  CACHE_TTL_KEY,
19325
+ CONSTRAINT_CREATE,
19326
+ CONSTRAINT_ENFORCE,
19327
+ CONSTRAINT_MUTATE,
17994
19328
  CONSTRAINT_RECORDS_READ,
17995
19329
  CONTINUE,
17996
19330
  CatalogAlreadyExistsError,
@@ -18001,6 +19335,7 @@ export {
18001
19335
  CatalogSnapshotManager,
18002
19336
  ComparisonOp,
18003
19337
  CompositeCatalogInterface,
19338
+ DEFAULT_EXPRESSION_KEY,
18004
19339
  DEFAULT_MAX_WORKERS,
18005
19340
  DateUnit3 as DateUnit,
18006
19341
  DistinctDependence,
@@ -18012,6 +19347,8 @@ export {
18012
19347
  FunctionStorageCfDo,
18013
19348
  FunctionStorageSqlite,
18014
19349
  FunctionType,
19350
+ GENERATED_EXPRESSION_KEY,
19351
+ GENERATION_KEY,
18015
19352
  GROUP_COLUMN_NAME,
18016
19353
  GrantKeys2 as GrantKeys,
18017
19354
  GrantRefusedError,
@@ -18041,6 +19378,7 @@ export {
18041
19378
  ScanFunctionResultSchema,
18042
19379
  SealAttachDeniedError,
18043
19380
  StatusError,
19381
+ TRANSACTION_DDL,
18044
19382
  TableInOutPhase,
18045
19383
  TimeUnit2 as TimeUnit,
18046
19384
  TypeId,
@@ -18080,14 +19418,26 @@ export {
18080
19418
  binary2 as binary,
18081
19419
  bool3 as bool,
18082
19420
  buildCatalogAttachResult,
19421
+ buildCatalogCapabilities,
19422
+ buildConstraintChange,
19423
+ buildConstraintDefinition,
19424
+ buildFieldPath,
18083
19425
  buildJoinKeysLookup,
19426
+ buildKeyGrouping,
19427
+ buildMacroOverload,
19428
+ buildRangeKey,
19429
+ buildRangePartitioning,
18084
19430
  buildRpcServer,
18085
19431
  buildScanBranchesResult,
19432
+ buildTransformSpec,
18086
19433
  buildVgiProtocol,
18087
19434
  bytes,
18088
19435
  cacheControlMetadata,
19436
+ canonicalIndex,
19437
+ catalogCapabilities,
18089
19438
  codecFor,
18090
19439
  columnFromArray,
19440
+ constraintCapabilities,
18091
19441
  constraintRecord,
18092
19442
  constraintSpecFields,
18093
19443
  createLandingRoutes,
@@ -18097,13 +19447,31 @@ export {
18097
19447
  decimal2 as decimal,
18098
19448
  decimal1282 as decimal128,
18099
19449
  decimal2562 as decimal256,
19450
+ decodeCatalogCapabilities,
18100
19451
  decodeCatalogInfo,
19452
+ decodeCatalogObjectRef,
19453
+ decodeConstraintChange,
19454
+ decodeConstraintDefinition,
19455
+ decodeConstraintInfo,
19456
+ decodeConstraintSnapshot,
19457
+ decodeConstraintsApplyRequest,
18101
19458
  decodeDictValue,
19459
+ decodeFieldPath,
19460
+ decodeForeignKeyDefinition,
18102
19461
  decodeFunctionInfo,
19462
+ decodeIndexDefinition,
19463
+ decodeKeyGrouping,
18103
19464
  decodeMacroInfo,
19465
+ decodeMacroOverload,
19466
+ decodeRangeKey,
19467
+ decodeRangePartitioning,
18104
19468
  decodeSchemaInfo,
19469
+ decodeSqlExpression,
18105
19470
  decodeTableInfo,
19471
+ decodeTransformSpec,
18106
19472
  decodeViewInfo,
19473
+ defaultClientCapabilities,
19474
+ defaultExpressionMetadata,
18107
19475
  defineAggregate,
18108
19476
  defineCopyFromFunction,
18109
19477
  defineCopyToFunction,
@@ -18126,14 +19494,31 @@ export {
18126
19494
  durationNanos,
18127
19495
  durationSeconds,
18128
19496
  emptyBatch,
19497
+ emptyIndexOptions,
18129
19498
  encodeAttachTicket,
19499
+ encodeCatalogCapabilities,
18130
19500
  encodeCatalogInfo,
19501
+ encodeCatalogObjectRef,
19502
+ encodeConstraintChange,
19503
+ encodeConstraintDefinition,
19504
+ encodeConstraintInfo,
19505
+ encodeConstraintSnapshot,
19506
+ encodeConstraintsApplyRequest,
18131
19507
  encodeCopyFromFormatInfo,
19508
+ encodeFieldPath,
19509
+ encodeForeignKeyDefinition,
18132
19510
  encodeFormatOptions,
18133
19511
  encodeFunctionInfo,
19512
+ encodeIndexDefinition,
19513
+ encodeKeyGrouping,
18134
19514
  encodeMacroInfo,
19515
+ encodeMacroOverload,
19516
+ encodeRangeKey,
19517
+ encodeRangePartitioning,
18135
19518
  encodeSchemaInfo,
19519
+ encodeSqlExpression,
18136
19520
  encodeTableInfo,
19521
+ encodeTransformSpec,
18137
19522
  encodeViewInfo,
18138
19523
  field2 as field,
18139
19524
  filterBatch,
@@ -18149,6 +19534,7 @@ export {
18149
19534
  fromBrandedBigInt,
18150
19535
  fromBrandedNumber,
18151
19536
  storage as functionStorage,
19537
+ generatedExpressionMetadata,
18152
19538
  grantKeysFromArgv,
18153
19539
  httpConnect,
18154
19540
  int3 as int,
@@ -18209,6 +19595,7 @@ export {
18209
19595
  secretForScopeOfType,
18210
19596
  secretType,
18211
19597
  secretsOfType,
19598
+ selectCatalogCapabilities,
18212
19599
  selectReadProfiles,
18213
19600
  serializeAttachOptionSpec,
18214
19601
  serializeAttachOptionSpecs,
@@ -18216,8 +19603,12 @@ export {
18216
19603
  serializeColumnStatistics,
18217
19604
  serializeSchema,
18218
19605
  serializeUserState,
19606
+ servedConstraintFields,
19607
+ servedTableInfo,
19608
+ servedTableSchema,
18219
19609
  setStorage,
18220
19610
  sparseUnion2 as sparseUnion,
19611
+ sqlExpression,
18221
19612
  str,
18222
19613
  struct2 as struct,
18223
19614
  subprocessConnect,
@@ -18241,7 +19632,11 @@ export {
18241
19632
  uint82 as uint8,
18242
19633
  union2 as union,
18243
19634
  utf82 as utf8,
18244
- validateConstraintNullability
19635
+ validateColumnExpressionSql,
19636
+ validateConstraintNullability,
19637
+ validateForeignKeyTargets,
19638
+ validateNumericCheckSql,
19639
+ validateTableConstraints
18245
19640
  };
18246
19641
 
18247
- //# debugId=0952F70BC6F2E0DE64756E2164756E21
19642
+ //# debugId=67FF9BC53B3C318564756E2164756E21