@query-farm/vgi 0.46.0 → 0.47.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 (89) hide show
  1. package/README.md +11 -5
  2. package/dist/arrow/impl-arrowjs/index.d.ts +1 -1
  3. package/dist/arrow/impl-arrowjs/iterate.d.ts +2 -0
  4. package/dist/arrow/impl-flechette/index.d.ts +1 -1
  5. package/dist/arrow/impl-flechette/iterate.d.ts +2 -0
  6. package/dist/arrow/index.d.ts +1 -1
  7. package/dist/catalog/column-expressions.d.ts +8 -0
  8. package/dist/catalog/column-metadata.d.ts +11 -0
  9. package/dist/catalog/composite.d.ts +2 -1
  10. package/dist/catalog/descriptors.d.ts +21 -29
  11. package/dist/catalog/interface.d.ts +15 -20
  12. package/dist/catalog/macro-overloads.d.ts +4 -0
  13. package/dist/catalog/read-only.d.ts +1 -1
  14. package/dist/catalog/unconstrained-columns.d.ts +2 -0
  15. package/dist/client/client.d.ts +18 -13
  16. package/dist/client-entry.js +753 -103
  17. package/dist/client-entry.js.map +16 -14
  18. package/dist/functions/projection.d.ts +18 -0
  19. package/dist/functions/table.d.ts +6 -1
  20. package/dist/functions/types.d.ts +1 -0
  21. package/dist/generated/vgi-client.d.ts +177 -36
  22. package/dist/generated/vgi-protocol-schemas.d.ts +51 -1
  23. package/dist/generated/vgi-protocol-types.d.ts +317 -3
  24. package/dist/generated/vgi-service.d.ts +266 -29
  25. package/dist/index.core.d.ts +2 -1
  26. package/dist/index.js +1480 -238
  27. package/dist/index.js.map +40 -34
  28. package/dist/protocol/dispatch.d.ts +9 -9
  29. package/dist/protocol/handlers/aggregate.d.ts +1 -1
  30. package/dist/protocol/handlers/catalog/index.d.ts +1 -1
  31. package/dist/protocol/handlers/catalog/metadata.d.ts +1 -0
  32. package/dist/protocol/handlers/function.d.ts +1 -1
  33. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  34. package/dist/protocol/handlers/unimplemented.d.ts +1 -1
  35. package/dist/protocol/serializers/bind.d.ts +5 -1
  36. package/dist/protocol/types.d.ts +5 -0
  37. package/dist/rpc-server.d.ts +6 -6
  38. package/dist/serve-entry.js +1593 -452
  39. package/dist/serve-entry.js.map +31 -26
  40. package/dist/util/arrow/index.d.ts +1 -1
  41. package/dist/worker-cf-entry.js +1814 -589
  42. package/dist/worker-cf-entry.js.map +39 -33
  43. package/dist/worker.d.ts +1 -1
  44. package/package.json +5 -4
  45. package/src/arrow/impl-arrowjs/index.ts +1 -1
  46. package/src/arrow/impl-arrowjs/iterate.ts +9 -1
  47. package/src/arrow/impl-arrowjs/project.ts +1 -1
  48. package/src/arrow/impl-flechette/index.ts +1 -1
  49. package/src/arrow/impl-flechette/ipc.ts +12 -0
  50. package/src/arrow/impl-flechette/iterate.ts +5 -0
  51. package/src/arrow/impl-flechette/project.ts +6 -8
  52. package/src/arrow/index.ts +1 -1
  53. package/src/catalog/column-expressions.ts +224 -0
  54. package/src/catalog/column-metadata.ts +151 -0
  55. package/src/catalog/composite.ts +5 -1
  56. package/src/catalog/contents-codec.ts +6 -1
  57. package/src/catalog/descriptors.ts +21 -29
  58. package/src/catalog/interface.ts +70 -55
  59. package/src/catalog/macro-overloads.ts +44 -0
  60. package/src/catalog/read-only.ts +63 -71
  61. package/src/catalog/unconstrained-columns.ts +23 -0
  62. package/src/client/client.ts +100 -58
  63. package/src/codec/asd.ts +3 -1
  64. package/src/functions/projection.ts +207 -0
  65. package/src/functions/table.ts +10 -0
  66. package/src/functions/types.ts +1 -0
  67. package/src/generated/vgi-client.ts +199 -37
  68. package/src/generated/vgi-protocol-schemas.ts +455 -41
  69. package/src/generated/vgi-protocol-types.ts +879 -5
  70. package/src/generated/vgi-service.ts +514 -42
  71. package/src/http/client-bundle.ts +1 -1
  72. package/src/http/fetch.ts +1 -1
  73. package/src/index.core.ts +4 -0
  74. package/src/protocol/dispatch.ts +9 -9
  75. package/src/protocol/handlers/aggregate.ts +1 -1
  76. package/src/protocol/handlers/catalog/admin.ts +10 -5
  77. package/src/protocol/handlers/catalog/index.ts +2 -2
  78. package/src/protocol/handlers/catalog/macro.ts +6 -5
  79. package/src/protocol/handlers/catalog/metadata.ts +16 -0
  80. package/src/protocol/handlers/catalog/table.ts +72 -26
  81. package/src/protocol/handlers/catalog/view.ts +24 -3
  82. package/src/protocol/handlers/function.ts +67 -1
  83. package/src/protocol/handlers/table-buffering.ts +1 -1
  84. package/src/protocol/handlers/unimplemented.ts +6 -6
  85. package/src/protocol/serializers/bind.ts +17 -1
  86. package/src/protocol/types.ts +6 -0
  87. package/src/rpc-server.ts +9 -9
  88. package/src/util/arrow/index.ts +1 -1
  89. package/src/worker.ts +1 -1
@@ -25,6 +25,9 @@ export interface ForeignKeyDef {
25
25
  export type DefaultValue = string | number | boolean | null;
26
26
 
27
27
  export interface TableDescriptor {
28
+ /** Canonical ConstraintInfo IPC records with provider-owned stable identities. */
29
+ constraints?: Uint8Array[];
30
+ definitionRevision?: Uint8Array | null;
28
31
  name: string;
29
32
  columns?: VgiSchema;
30
33
  function?: VgiFunction;
@@ -40,7 +43,7 @@ export interface TableDescriptor {
40
43
  /**
41
44
  * Generated (virtual) columns: map of column name → SQL expression computed
42
45
  * from other physical columns. Applied as Arrow field metadata
43
- * `generated_expression`, which the DuckDB VGI extension reads at table
46
+ * canonical SqlExpression IPC with explicit owner/context, which DuckDB reads at table
44
47
  * registration. The backing scan function should not return these columns —
45
48
  * DuckDB evaluates the expressions client-side.
46
49
  */
@@ -59,25 +62,10 @@ export interface TableDescriptor {
59
62
  * (always re-fetch).
60
63
  */
61
64
  statisticsCacheMaxAgeSeconds?: number | null;
62
- /**
63
- * Required WHERE-filter groups in conjunctive normal form — an AND (outer
64
- * list) of OR-groups (inner lists) of dotted-path column references that MUST
65
- * appear in a WHERE expression for any scan of this table. A group is
66
- * satisfied when any one of its paths has a filter; every group must be
67
- * satisfied. So `[["accession_number"], ["ticker", "cik"]]` means
68
- * "accession_number AND one of (ticker, cik)"; a single-path group
69
- * `[["country"]]` is a plain mandatory filter. Paths are top-level names
70
- * (`"country"`) or struct subfields (`"bbox.xmin"`, `"nested.outer.inner"`).
71
- * Empty/undefined (default) means no enforcement — the zero-cost fast path
72
- * for every existing table.
73
- *
74
- * Satisfaction is prefix-based: a present filter on a shorter path satisfies
75
- * any required path it is a prefix of. So a whole-struct filter on `bbox`
76
- * satisfies all of `bbox.xmin` / `.xmax` / `.ymin` / `.ymax`. The VGI DuckDB
77
- * extension's optimizer pass consults this at bind time and throws a
78
- * `BinderException` listing any unsatisfied groups.
79
- */
80
- requiredFilters?: string[][];
65
+ /** AND-of-OR groups of raw component paths, e.g. `[[["bbox", "xmin"]], [["ticker"], ["cik"]]]`.
66
+ * Dots and quotes are literal. A present component prefix satisfies a path;
67
+ * a child does not satisfy its parent. Empty/undefined means no requirements. */
68
+ requiredFilters?: string[][][];
81
69
  supportsTimeTravel?: boolean;
82
70
  /**
83
71
  * Inline cardinality estimate/max surfaced through TableInfo. When set,
@@ -92,6 +80,10 @@ export interface TableDescriptor {
92
80
 
93
81
  export interface ViewDescriptor {
94
82
  name: string;
83
+ /** Ordered raw output identifiers; empty uses query names. */
84
+ aliases?: string[];
85
+ /** Optimization barrier mode; readers must enforce or reject it. */
86
+ security?: "regular" | "barrier";
95
87
  definition: string;
96
88
  comment?: string;
97
89
  /**
@@ -111,11 +103,12 @@ export interface MacroDescriptor {
111
103
  macroType: "scalar" | "table";
112
104
  parameters: string[];
113
105
  parameterDefaultValues?: Uint8Array | null;
106
+ /** Complete canonical family; simple-definition fields must be empty when supplied. */
107
+ overloads?: import("../generated/vgi-client.js").MacroOverload[];
114
108
  /**
115
109
  * Optional mapping of parameter name to a human/agent-facing description.
116
110
  * Keys must appear in `parameters`. Descriptions flow over the wire via the
117
- * macro `arguments_schema`'s `vgi_doc` field metadata (the same channel
118
- * functions use for per-argument docs), so the DuckDB extension's
111
+ * canonical parameter's `documentation` field, so the DuckDB extension's
119
112
  * `vgi_function_arguments()` can surface them. Empty/omitted = no docs.
120
113
  */
121
114
  parameterDocs?: Record<string, string>;
@@ -126,12 +119,10 @@ export interface MacroDescriptor {
126
119
 
127
120
  export interface IndexDescriptor {
128
121
  name: string;
129
- tableName: string;
130
- expressions: string[];
131
- /** UNIQUE / PRIMARY / NONE; defaults to NONE. */
132
- constraintType?: "NONE" | "UNIQUE" | "PRIMARY";
133
- indexType?: string;
134
- options?: Record<string, string>;
122
+ /** Complete provider-authored definition; no expression strings or options are inferred. */
123
+ definition: Uint8Array;
124
+ /** Effective values and persisted override names, including explicit NULL. */
125
+ options: Uint8Array;
135
126
  comment?: string;
136
127
  tags?: Record<string, string>;
137
128
  }
@@ -164,7 +155,8 @@ export interface SecretTypeDescriptor {
164
155
 
165
156
  export interface CatalogDescriptor {
166
157
  name: string;
167
- defaultSchema?: string;
158
+ /** One raw root identifier; null means no implicit default, omitted means main. */
159
+ defaultSchema?: string | null;
168
160
  schemas: SchemaDescriptor[];
169
161
  settings?: SettingDescriptor[];
170
162
  secretTypes?: SecretTypeDescriptor[];
@@ -68,8 +68,8 @@ export type { MacroInfo };
68
68
  export { encodeMacroInfo, decodeMacroInfo } from "../generated/vgi-client.js";
69
69
 
70
70
  // IndexInfo wire shape — declarative indexes a worker advertises and DuckDB
71
- // surfaces under duckdb_indexes(). Constraint type maps to is_unique /
72
- // is_primary on the DuckDB side.
71
+ // surfaces under duckdb_indexes(). Definitions preserve raw paths, contextual
72
+ // expressions, typed options and explicit logical-constraint associations.
73
73
  import type { IndexInfo, IndexConstraintType } from "../generated/vgi-client.js";
74
74
  export type { IndexInfo, IndexConstraintType };
75
75
  export { encodeIndexInfo, decodeIndexInfo } from "../generated/vgi-client.js";
@@ -627,6 +627,7 @@ export abstract class CatalogInterface {
627
627
  options?: Record<string, unknown>,
628
628
  dataVersionSpec?: string | null,
629
629
  implementationVersion?: string | null,
630
+ clientCapabilities?: Uint8Array | null,
630
631
  ): Awaitable<CatalogAttachResult>;
631
632
  /**
632
633
  * List the catalogs this worker exposes with their version metadata. The
@@ -668,8 +669,9 @@ export abstract class CatalogInterface {
668
669
  attachOpaqueData: AttachOpaqueData,
669
670
  path: string[],
670
671
  comment?: string | null,
671
- tags?: any,
672
- transactionOpaqueData?: TransactionOpaqueData
672
+ tags?: Record<string, string> | null,
673
+ transactionOpaqueData?: TransactionOpaqueData,
674
+ onConflict?: string
673
675
  ): Awaitable<void> {
674
676
  throw new CatalogReadOnlyError("schema_create");
675
677
  }
@@ -720,9 +722,7 @@ export abstract class CatalogInterface {
720
722
  name: string,
721
723
  columns: Uint8Array,
722
724
  onConflict: string,
723
- notNullConstraints?: number[],
724
- uniqueConstraints?: number[][],
725
- checkConstraints?: string[],
725
+ constraintDefinitions?: Uint8Array[],
726
726
  transactionOpaqueData?: TransactionOpaqueData
727
727
  ): Awaitable<void> {
728
728
  throw new CatalogReadOnlyError("table_create");
@@ -807,86 +807,100 @@ export abstract class CatalogInterface {
807
807
  attachOpaqueData: AttachOpaqueData,
808
808
  schemaPath: string[],
809
809
  name: string,
810
- columnName: string,
811
- columnType: string,
812
- defaultValue?: string,
813
- ignoreNotFound?: boolean,
814
- transactionOpaqueData?: TransactionOpaqueData
810
+ columnPath: string[],
811
+ columnDefinition: Uint8Array,
812
+ ignoreNotFound: boolean = false,
813
+ ifColumnNotExists: boolean = false,
814
+ transactionOpaqueData?: TransactionOpaqueData,
815
815
  ): Awaitable<void> {
816
- throw new CatalogReadOnlyError("table_column_add");
816
+ throw new CatalogReadOnlyError("catalog_table_column_add");
817
817
  }
818
818
  tableColumnDrop(
819
819
  attachOpaqueData: AttachOpaqueData,
820
820
  schemaPath: string[],
821
821
  name: string,
822
- columnName: string,
823
- ignoreNotFound?: boolean,
824
- transactionOpaqueData?: TransactionOpaqueData
822
+ columnPath: string[],
823
+ ignoreNotFound: boolean = false,
824
+ ifColumnExists: boolean = false,
825
+ cascade: boolean = false,
826
+ transactionOpaqueData?: TransactionOpaqueData,
825
827
  ): Awaitable<void> {
826
- throw new CatalogReadOnlyError("table_column_drop");
828
+ throw new CatalogReadOnlyError("catalog_table_column_drop");
827
829
  }
828
830
  tableColumnRename(
829
831
  attachOpaqueData: AttachOpaqueData,
830
832
  schemaPath: string[],
831
833
  name: string,
832
- columnName: string,
833
- newName: string,
834
- ignoreNotFound?: boolean,
835
- transactionOpaqueData?: TransactionOpaqueData
834
+ columnPath: string[],
835
+ newColumnName: string,
836
+ ignoreNotFound: boolean = false,
837
+ transactionOpaqueData?: TransactionOpaqueData,
838
+ ): Awaitable<void> {
839
+ throw new CatalogReadOnlyError("catalog_table_column_rename");
840
+ }
841
+ tableColumnCommentSet(
842
+ attachOpaqueData: AttachOpaqueData,
843
+ schemaPath: string[],
844
+ name: string,
845
+ columnPath: string[],
846
+ comment: string | null,
847
+ ignoreNotFound: boolean = false,
848
+ transactionOpaqueData?: TransactionOpaqueData,
836
849
  ): Awaitable<void> {
837
- throw new CatalogReadOnlyError("table_column_rename");
850
+ throw new CatalogReadOnlyError("catalog_table_column_comment_set");
838
851
  }
839
852
  tableColumnDefaultSet(
840
853
  attachOpaqueData: AttachOpaqueData,
841
854
  schemaPath: string[],
842
855
  name: string,
843
- columnName: string,
844
- defaultValue: string,
845
- ignoreNotFound?: boolean,
846
- transactionOpaqueData?: TransactionOpaqueData
856
+ columnPath: string[],
857
+ expression: Uint8Array,
858
+ ignoreNotFound: boolean = false,
859
+ transactionOpaqueData?: TransactionOpaqueData,
847
860
  ): Awaitable<void> {
848
- throw new CatalogReadOnlyError("table_column_default_set");
861
+ throw new CatalogReadOnlyError("catalog_table_column_default_set");
849
862
  }
850
863
  tableColumnDefaultDrop(
851
864
  attachOpaqueData: AttachOpaqueData,
852
865
  schemaPath: string[],
853
866
  name: string,
854
- columnName: string,
855
- ignoreNotFound?: boolean,
856
- transactionOpaqueData?: TransactionOpaqueData
867
+ columnPath: string[],
868
+ ignoreNotFound: boolean = false,
869
+ transactionOpaqueData?: TransactionOpaqueData,
857
870
  ): Awaitable<void> {
858
- throw new CatalogReadOnlyError("table_column_default_drop");
871
+ throw new CatalogReadOnlyError("catalog_table_column_default_drop");
859
872
  }
860
873
  tableColumnTypeChange(
861
874
  attachOpaqueData: AttachOpaqueData,
862
875
  schemaPath: string[],
863
876
  name: string,
864
- columnName: string,
865
- newType: string,
866
- ignoreNotFound?: boolean,
867
- transactionOpaqueData?: TransactionOpaqueData
877
+ columnPath: string[],
878
+ columnDefinition: Uint8Array,
879
+ expression: Uint8Array | null = null,
880
+ ignoreNotFound: boolean = false,
881
+ transactionOpaqueData?: TransactionOpaqueData,
868
882
  ): Awaitable<void> {
869
- throw new CatalogReadOnlyError("table_column_type_change");
883
+ throw new CatalogReadOnlyError("catalog_table_column_type_change");
870
884
  }
871
885
  tableNotNullSet(
872
886
  attachOpaqueData: AttachOpaqueData,
873
887
  schemaPath: string[],
874
888
  name: string,
875
- columnName: string,
876
- ignoreNotFound?: boolean,
877
- transactionOpaqueData?: TransactionOpaqueData
889
+ columnPath: string[],
890
+ ignoreNotFound: boolean = false,
891
+ transactionOpaqueData?: TransactionOpaqueData,
878
892
  ): Awaitable<void> {
879
- throw new CatalogReadOnlyError("table_not_null_set");
893
+ throw new CatalogReadOnlyError("catalog_table_not_null_set");
880
894
  }
881
895
  tableNotNullDrop(
882
896
  attachOpaqueData: AttachOpaqueData,
883
897
  schemaPath: string[],
884
898
  name: string,
885
- columnName: string,
886
- ignoreNotFound?: boolean,
887
- transactionOpaqueData?: TransactionOpaqueData
899
+ columnPath: string[],
900
+ ignoreNotFound: boolean = false,
901
+ transactionOpaqueData?: TransactionOpaqueData,
888
902
  ): Awaitable<void> {
889
- throw new CatalogReadOnlyError("table_not_null_drop");
903
+ throw new CatalogReadOnlyError("catalog_table_not_null_drop");
890
904
  }
891
905
  viewGet(
892
906
  attachOpaqueData: AttachOpaqueData,
@@ -902,7 +916,11 @@ export abstract class CatalogInterface {
902
916
  name: string,
903
917
  definition: string,
904
918
  onConflict: string,
905
- transactionOpaqueData?: TransactionOpaqueData
919
+ transactionOpaqueData?: TransactionOpaqueData,
920
+ aliases?: string[],
921
+ comment?: string | null,
922
+ tags?: Record<string, string> | null,
923
+ columnComments?: Record<string, string> | null
906
924
  ): Awaitable<void> {
907
925
  throw new CatalogReadOnlyError("view_create");
908
926
  }
@@ -935,6 +953,12 @@ export abstract class CatalogInterface {
935
953
  ): Awaitable<void> {
936
954
  throw new CatalogReadOnlyError("view_comment_set");
937
955
  }
956
+ viewColumnCommentSet(
957
+ attachOpaqueData: AttachOpaqueData, schemaPath: string[], name: string, columnPath: string[],
958
+ comment?: string | null, ignoreNotFound?: boolean, transactionOpaqueData?: TransactionOpaqueData
959
+ ): Awaitable<void> {
960
+ throw new CatalogReadOnlyError("view_column_comment_set");
961
+ }
938
962
  macroGet(
939
963
  attachOpaqueData: AttachOpaqueData,
940
964
  schemaPath: string[],
@@ -948,17 +972,8 @@ export abstract class CatalogInterface {
948
972
  schemaPath: string[],
949
973
  name: string,
950
974
  macroType: MacroType,
951
- parameters: string[],
952
- definition: string,
975
+ overloads: import("../generated/vgi-client.js").MacroOverload[],
953
976
  onConflict: string,
954
- parameterDefaultValues?: Uint8Array | null,
955
- /**
956
- * Optional Arrow schema (one nullable field per parameter, in `parameters`
957
- * order) serialized as IPC bytes, carrying per-parameter descriptions via the
958
- * `vgi_doc` field metadata key. `null`/omitted when no per-parameter docs are
959
- * supplied. Build with `macroArgumentsSchema` + `serializeSchema`.
960
- */
961
- argumentsSchema?: Uint8Array | null,
962
977
  transactionOpaqueData?: TransactionOpaqueData
963
978
  ): Awaitable<void> {
964
979
  throw new CatalogReadOnlyError("macro_create");
@@ -0,0 +1,44 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ import type { MacroDescriptor } from "./descriptors.js";
3
+ import type { MacroOverload } from "../generated/vgi-client.js";
4
+ import { deserializeBatch, projectBatch, serializeBatch } from "../arrow/index.js";
5
+
6
+ /** Convert a simple descriptor without treating default-value types as declarations. */
7
+ export function macroOverloads(macro: MacroDescriptor, owner: string[]): MacroOverload[] {
8
+ if (macro.overloads != null) {
9
+ if (macro.parameters.length || macro.definition || macro.parameterDefaultValues ||
10
+ Object.keys(macro.parameterDocs ?? {}).length) throw new Error("macro family conflicts with single-definition descriptor");
11
+ if (!macro.overloads.length) throw new Error("macro overload family must be nonempty");
12
+ for (const overload of macro.overloads) {
13
+ if (overload.parameters.some(p => p.default_expression != null)) throw new Error("discovery macro defaults must be resolved values");
14
+ if (overload.macro_type !== macro.macroType || JSON.stringify(overload.schema_path) !== JSON.stringify(owner)) {
15
+ throw new Error("macro overload owner and kind must equal the parent macro");
16
+ }
17
+ }
18
+ return macro.overloads;
19
+ }
20
+ if (!macro.definition.trim() || macro.definition.includes("\0")) throw new Error("macro definition must be nonempty SQL without NUL");
21
+ const defaults = macro.parameterDefaultValues?.length ? deserializeBatch(macro.parameterDefaultValues) : null;
22
+ if (defaults && defaults.numRows !== 1) throw new Error("macro defaults require exactly one row");
23
+ for (const name of [...(defaults?.schema.fields.map(f => f.name) ?? []), ...Object.keys(macro.parameterDocs ?? {})]) {
24
+ if (!macro.parameters.includes(name)) throw new Error(`unknown macro parameter '${name}'`);
25
+ }
26
+ const defaultNames = defaults?.schema.fields.map(f => f.name) ?? [];
27
+ if (new Set(defaultNames).size !== defaultNames.length) throw new Error("duplicate macro default");
28
+ const seen = new Set<string>();
29
+ let hasDefault = false;
30
+ const parameters = macro.parameters.map(name => {
31
+ if (!name || name.includes("\0") || seen.has(name.toLowerCase())) throw new Error("invalid or duplicate macro parameter");
32
+ seen.add(name.toLowerCase());
33
+ const index = defaults?.schema.fields.findIndex(f => f.name === name) ?? -1;
34
+ if (index < 0 && hasDefault) throw new Error("required macro parameter cannot follow a default");
35
+ hasDefault ||= index >= 0;
36
+ return { name, declared_type: null, default_expression: null,
37
+ default_value: index < 0 ? null : serializeBatch(projectBatch([index], defaults!)),
38
+ documentation: macro.parameterDocs?.[name] ?? null };
39
+ });
40
+ return [{ parameters, definition: macro.definition, profile: "duckdb.macro.v1",
41
+ schema_path: [...owner], macro_type: macro.macroType,
42
+ evaluation_context: { timezone: "UTC", collation: "binary", default_order: "asc",
43
+ default_null_order: "nulls_last", preserve_insertion_order: true } }];
44
+ }
@@ -1,7 +1,9 @@
1
+ import { generatedExpressionMetadata, GENERATED_EXPRESSION_KEY, GENERATION_KEY, validateColumnExpressions } from "./column-expressions.js";
2
+ import { validateColumnMetadata } from "./column-metadata.js";
1
3
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
4
  // ReadOnlyCatalogInterface: derives catalog from registered functions + descriptors.
3
5
 
4
- import { type VgiSchema, schema as schema_, type VgiField, field, type VgiDataType, int64, utf8, binary, bool, nullType, list, isInt, typeSignature } from "../arrow/index.js";
6
+ import { type VgiSchema, schema as schema_, type VgiField, field, type VgiDataType, int64, utf8, binary, bool, nullType, list, isInt, isStruct, typeSignature } from "../arrow/index.js";
5
7
  import {
6
8
  CatalogInterface,
7
9
  type AttachOpaqueData,
@@ -14,7 +16,6 @@ import {
14
16
  type FunctionInfo,
15
17
  type MacroInfo,
16
18
  type IndexInfo,
17
- type IndexConstraintType,
18
19
  type CopyFromFormatInfo,
19
20
  encodeAttachCatalogInfo,
20
21
  encodeScanFunctionResult,
@@ -24,7 +25,7 @@ import { schemaDescriptorPath, type CatalogDescriptor, type SchemaDescriptor, ty
24
25
  import { serializeColumnStatistics } from "../util/statistics.js";
25
26
  import type { VgiFunction } from "../functions/types.js";
26
27
  import type { FunctionRegistry } from "../functions/registry.js";
27
- import { argumentSpecsToSchema, macroArgumentsSchema } from "../arguments/argument-spec.js";
28
+ import { argumentSpecsToSchema } from "../arguments/argument-spec.js";
28
29
  import { serializeSchema, serializeBatch, emptyBatch, batchFromColumns } from "../util/arrow/index.js";
29
30
  import { resolveMetadata } from "../metadata/resolve.js";
30
31
  import { type AttachOptionSpec, validateRequiredAttachOptions } from "./attach-option.js";
@@ -35,6 +36,7 @@ import { ForeignKeyInfoSchema } from "../generated/vgi-protocol-schemas.js";
35
36
  import { conformColumns } from "../codec/conform.js";
36
37
  import { VgiError } from "../errors.js";
37
38
  import { encodeFunctionInfoOnce, freezeCatalogItem } from "./item-encoding.js";
39
+ import { macroOverloads } from "./macro-overloads.js";
38
40
 
39
41
  /**
40
42
  * The fixed attach id ReadOnlyCatalogInterface writes into its items (same
@@ -100,6 +102,10 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
100
102
  options: { perAttachItemIds?: boolean } = {},
101
103
  ) {
102
104
  super();
105
+ if (descriptor.defaultSchema != null &&
106
+ (descriptor.defaultSchema.length === 0 || descriptor.defaultSchema.includes("\0"))) {
107
+ throw new Error("defaultSchema must be a non-empty raw root identifier without NUL, or null");
108
+ }
103
109
  this._descriptor = descriptor;
104
110
  this._registry = registry;
105
111
  if (options.perAttachItemIds) this.perAttachItemIds = true;
@@ -178,6 +184,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
178
184
  options?: Record<string, unknown>,
179
185
  dataVersionSpec?: string | null,
180
186
  implementationVersion?: string | null,
187
+ clientCapabilities?: Uint8Array | null,
181
188
  ): CatalogAttachResult | Promise<CatalogAttachResult> {
182
189
  if (!this.catalogs().includes(name)) {
183
190
  throw new VgiError(`No worker handles catalog '${name}'`, "NOT_FOUND");
@@ -217,7 +224,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
217
224
  catalog_version_frozen: true,
218
225
  catalog_version: this._version,
219
226
  attach_opaque_data_required: true,
220
- default_schema: this._descriptor.defaultSchema ?? "main",
227
+ default_schema: this._descriptor.defaultSchema === undefined ? "main" : this._descriptor.defaultSchema,
221
228
  settings,
222
229
  secret_types: secretTypes,
223
230
  attach_catalogs: attachCatalogs,
@@ -353,11 +360,11 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
353
360
  colSchema = applyDefaults(colSchema, t.defaults);
354
361
  }
355
362
  // Apply generated-column expressions as Arrow field metadata
356
- // (`generated_expression`). DuckDB registers these columns as GENERATED
363
+ // (canonical SqlExpression IPC). DuckDB registers these columns as GENERATED
357
364
  // and evaluates the SQL expression client-side — the scan function
358
365
  // should not return values for them.
359
366
  if (t.generatedColumns) {
360
- colSchema = applyGeneratedColumns(colSchema, t.generatedColumns);
367
+ colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path);
361
368
  }
362
369
  // Apply per-column comments as Arrow field metadata (matches Python's
363
370
  // `comment` metadata key on columns).
@@ -365,41 +372,33 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
365
372
  colSchema = applyColumnComments(colSchema, t.columnComments);
366
373
  }
367
374
 
375
+ validateColumnMetadata(colSchema);
376
+ validateColumnExpressions(colSchema, path);
368
377
  const columns = serializeSchema(colSchema);
369
378
 
370
- // Resolve constraint column names → indices
371
- const notNullIndices = resolveIndices(colSchema, t.notNull);
372
- const uniqueIndices = resolveIndexGroups(colSchema, t.unique);
373
- const pkIndices = resolveIndexGroups(colSchema, t.primaryKey);
374
- const fkBytes = serializeForeignKeys(t.foreignKey, path);
375
-
376
- // Validate required_filters: an AND (outer list) of OR-groups (inner
377
- // lists). Each OR-group must be non-empty, and the leading dotted segment
378
- // of each path must be a real column on this table. Struct subfield
379
- // validity is not checked here — DuckDB's binder catches typos at scan
380
- // time, and the descriptor doesn't unpack STRUCT subfields. (Mirrors
381
- // vgi-python's Table descriptor validation.)
379
+ if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
380
+ throw new Error("legacy constraint metadata requires explicit canonical records");
381
+ }
382
+
383
+ // Validate exact raw paths against the full table schema.
382
384
  const requiredFilters = t.requiredFilters ?? [];
383
- if (requiredFilters.length > 0) {
384
- const columnNames = new Set(colSchema.fields.map((f) => f.name));
385
- for (const group of requiredFilters) {
386
- if (!group || group.length === 0) {
387
- throw new Error(
388
- `Table '${t.name}': requiredFilters must not contain empty groups`
389
- );
390
- }
391
- for (const path of group) {
392
- if (!path) {
393
- throw new Error(
394
- `Table '${t.name}': requiredFilters must not contain empty strings`
395
- );
396
- }
397
- const head = path.split(".", 1)[0];
398
- if (!columnNames.has(head)) {
399
- throw new Error(
400
- `Table '${t.name}': requiredFilters path '${path}' references ` +
401
- `unknown column '${head}'. Available columns: ${[...columnNames].sort().join(", ")}`
402
- );
385
+ for (const group of requiredFilters) {
386
+ if (!Array.isArray(group) || group.length === 0) throw new Error("requiredFilters contains an empty group");
387
+ const seen = new Set<string>();
388
+ for (const path of group) {
389
+ if (!Array.isArray(path) || path.length === 0) throw new Error("requiredFilters requires raw nonempty paths");
390
+ const key = JSON.stringify(path);
391
+ if (seen.has(key)) throw new Error("requiredFilters contains a duplicate path");
392
+ seen.add(key);
393
+ let fields = colSchema.fields;
394
+ for (let i = 0; i < path.length; ++i) {
395
+ const part = path[i];
396
+ if (typeof part !== "string" || !part || part.includes("\0")) throw new Error("invalid requiredFilters component");
397
+ const matches = fields.filter((f) => f.name === part);
398
+ if (matches.length !== 1) throw new Error(`unknown or ambiguous requiredFilters component: ${part}`);
399
+ if (i + 1 < path.length) {
400
+ if (!isStruct(matches[0].type)) throw new Error(`non-struct requiredFilters parent: ${part}`);
401
+ fields = (matches[0].type as VgiDataType & { children: readonly VgiField[] }).children;
403
402
  }
404
403
  }
405
404
  }
@@ -411,11 +410,8 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
411
410
  name: t.name,
412
411
  schema_path: normalizeSchemaPath(path),
413
412
  columns,
414
- not_null_constraints: notNullIndices,
415
- unique_constraints: uniqueIndices,
416
- check_constraints: t.check ?? [],
417
- primary_key_constraints: pkIndices,
418
- foreign_key_constraints: fkBytes,
413
+ constraints: t.constraints ?? [],
414
+ definition_revision: t.definitionRevision ?? null,
419
415
  write_result_modes: {},
420
416
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
421
417
  // Inline scan_function only for purely function-backed tables.
@@ -473,6 +469,8 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
473
469
  schema_path: normalizeSchemaPath(path),
474
470
  definition: v.definition,
475
471
  column_comments: v.columnComments ?? {},
472
+ aliases: [...(v.aliases ?? [])],
473
+ security: v.security ?? "regular",
476
474
  }));
477
475
  }
478
476
 
@@ -758,16 +756,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
758
756
  name: m.name,
759
757
  schema_path: normalizeSchemaPath(path),
760
758
  macro_type: (m.macroType === "scalar" ? "SCALAR" : "TABLE") as "SCALAR" | "TABLE",
761
- parameters: m.parameters,
762
- parameter_default_values: m.parameterDefaultValues ?? new Uint8Array(0),
763
- definition: m.definition,
764
- // One nullable Arrow field per parameter (in order), carrying each
765
- // documented parameter's description via the vgi_doc field-metadata key
766
- // (the same channel functions use). Type = default-value type when known
767
- // else null. Serialized as IPC bytes into the generated schema slot.
768
- arguments_schema: serializeSchema(
769
- macroArgumentsSchema(m.parameters, m.parameterDefaultValues, m.parameterDocs),
770
- ),
759
+ overloads: macroOverloads(m, normalizeSchemaPath(path)),
771
760
  }));
772
761
  }
773
762
 
@@ -778,17 +767,19 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
778
767
  ): IndexInfo[] {
779
768
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
780
769
  if (!schema || !schema.indexes) return [];
781
- return schema.indexes.map((idx) => ({
782
- comment: idx.comment ?? null,
783
- tags: idx.tags ?? {},
784
- name: idx.name,
785
- schema_path: normalizeSchemaPath(path),
786
- table_name: idx.tableName,
787
- index_type: idx.indexType ?? "ART",
788
- constraint_type: (idx.constraintType ?? "NONE") as IndexConstraintType,
789
- expressions: idx.expressions,
790
- options: idx.options ?? {},
791
- }));
770
+ return schema.indexes.map((idx) => {
771
+ if (!idx.definition || !idx.options) {
772
+ throw new Error("index discovery requires a canonical definition and typed option state");
773
+ }
774
+ return {
775
+ comment: idx.comment ?? null,
776
+ tags: idx.tags ?? {},
777
+ name: idx.name,
778
+ schema_path: normalizeSchemaPath(path),
779
+ definition: idx.definition,
780
+ options: idx.options,
781
+ };
782
+ });
792
783
  }
793
784
 
794
785
  override indexGet(
@@ -1001,18 +992,20 @@ function applyDefaults(schema: VgiSchema, defaults: Record<string, DefaultValue>
1001
992
  return result;
1002
993
  }
1003
994
 
1004
- function applyGeneratedColumns(schema: VgiSchema, generated: Record<string, string>): VgiSchema {
995
+ function applyGeneratedColumns(schema: VgiSchema, generated: Record<string, string>, owner: string[]): VgiSchema {
1005
996
  let result = schema;
1006
997
  for (const [colName, expression] of Object.entries(generated)) {
1007
998
  const idx = result.fields.findIndex((f) => f.name === colName);
1008
- if (idx < 0) continue;
999
+ if (idx < 0) throw new Error(`generated expression references unknown column ${colName}`);
1009
1000
  const f = result.fields[idx];
1010
1001
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
1011
- existingMeta.set("generated_expression", expression);
1002
+ if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression")) throw new Error("generated convenience conflicts with existing expression metadata");
1003
+ existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
1004
+ existingMeta.set(GENERATION_KEY, "virtual");
1012
1005
  const newField = field(f.name, f.type, f.nullable, existingMeta);
1013
1006
  const fields = [...result.fields];
1014
1007
  fields[idx] = newField;
1015
- result = schema_(fields);
1008
+ result = schema_(fields, result.metadata);
1016
1009
  }
1017
1010
  return result;
1018
1011
  }
@@ -1020,16 +1013,15 @@ function applyGeneratedColumns(schema: VgiSchema, generated: Record<string, stri
1020
1013
  function applyColumnComments(schema: VgiSchema, comments: Record<string, string>): VgiSchema {
1021
1014
  let result = schema;
1022
1015
  for (const [colName, comment] of Object.entries(comments)) {
1023
- if (!comment) continue;
1024
1016
  const idx = result.fields.findIndex((f) => f.name === colName);
1025
- if (idx < 0) continue;
1017
+ if (idx < 0) throw new Error(`column comment references unknown field ${colName}`);
1026
1018
  const f = result.fields[idx];
1027
1019
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
1028
1020
  existingMeta.set("comment", comment);
1029
1021
  const newField = field(f.name, f.type, f.nullable, existingMeta);
1030
1022
  const fields = [...result.fields];
1031
1023
  fields[idx] = newField;
1032
- result = schema_(fields);
1024
+ result = schema_(fields, result.metadata);
1033
1025
  }
1034
1026
  return result;
1035
1027
  }
@@ -0,0 +1,23 @@
1
+ // Copyright 2026 Query Farm LLC - https://query.farm
2
+ import { MethodNotImplementedError } from "@query-farm/vgi-rpc";
3
+ import { deserializeSchema, isStruct, type VgiField } from "../arrow/index.js";
4
+
5
+ /** No constraint authority means every SQL user field must remain nullable. */
6
+ export function requireUnconstrainedColumns(columns: Uint8Array): void {
7
+ const visit = (field: VgiField, top: boolean, depth: number): void => {
8
+ if (depth > 64) throw new MethodNotImplementedError("catalog_table_create: column nesting exceeds supported depth");
9
+ if (top && field.metadata?.has("is_row_id")) return;
10
+ for (const key of field.metadata?.keys() ?? []) {
11
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
12
+ throw new MethodNotImplementedError("catalog_table_create: logical column types require negotiation");
13
+ }
14
+ }
15
+ if (!field.nullable) {
16
+ throw new MethodNotImplementedError("catalog_table_create: nonnullable user columns require canonical constraints");
17
+ }
18
+ if (isStruct(field.type)) {
19
+ for (const child of (field.type as VgiField["type"] & { children: readonly VgiField[] }).children) visit(child, false, depth + 1);
20
+ }
21
+ };
22
+ for (const field of deserializeSchema(columns).fields) visit(field, true, 0);
23
+ }