@query-farm/vgi 0.47.1 → 0.47.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/catalog/column-expressions.d.ts +22 -1
  2. package/dist/catalog/column-metadata.d.ts +7 -0
  3. package/dist/catalog/column-types.d.ts +15 -0
  4. package/dist/catalog/composite.d.ts +2 -0
  5. package/dist/catalog/constraints.d.ts +110 -12
  6. package/dist/catalog/descriptors.d.ts +19 -1
  7. package/dist/catalog/indexes.d.ts +29 -0
  8. package/dist/catalog/interface.d.ts +41 -0
  9. package/dist/catalog/public-codecs.d.ts +6 -0
  10. package/dist/catalog/read-only.d.ts +3 -0
  11. package/dist/catalog/sql-grammar.d.ts +53 -0
  12. package/dist/catalog/unconstrained-columns.d.ts +8 -0
  13. package/dist/client/types.d.ts +5 -1
  14. package/dist/client-entry.d.ts +1 -0
  15. package/dist/client-entry.js +1410 -152
  16. package/dist/client-entry.js.map +12 -8
  17. package/dist/index.core.d.ts +1 -1
  18. package/dist/index.js +1681 -411
  19. package/dist/index.js.map +19 -16
  20. package/dist/serve-entry.js +1095 -49
  21. package/dist/serve-entry.js.map +13 -11
  22. package/dist/worker-cf-entry.d.ts +2 -1
  23. package/dist/worker-cf-entry.js +1459 -182
  24. package/dist/worker-cf-entry.js.map +19 -16
  25. package/package.json +1 -1
  26. package/src/catalog/column-expressions.ts +85 -7
  27. package/src/catalog/column-metadata.ts +20 -2
  28. package/src/catalog/column-types.ts +50 -0
  29. package/src/catalog/composite.ts +10 -0
  30. package/src/catalog/constraints.ts +496 -58
  31. package/src/catalog/contents-codec.ts +3 -3
  32. package/src/catalog/descriptors.ts +19 -1
  33. package/src/catalog/indexes.ts +59 -0
  34. package/src/catalog/interface.ts +103 -1
  35. package/src/catalog/public-codecs.ts +36 -0
  36. package/src/catalog/read-only.ts +92 -36
  37. package/src/catalog/sql-grammar.ts +476 -0
  38. package/src/catalog/unconstrained-columns.ts +34 -8
  39. package/src/client/client.ts +6 -3
  40. package/src/client/types.ts +5 -1
  41. package/src/client-entry.ts +4 -0
  42. package/src/index.core.ts +2 -1
  43. package/src/protocol/handlers/catalog/admin.ts +14 -13
  44. package/src/protocol/handlers/catalog/table.ts +58 -11
  45. package/src/worker-cf-entry.ts +2 -4
@@ -1,6 +1,6 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Catalog-wide collection streams, independent of delivery and attachment state.
3
- import { validateTableInfoColumns } from "./column-metadata.js";
3
+ import { servedValidatedTableInfo, validateTableInfoColumns } from "./column-metadata.js";
4
4
  import { encodeASDCollection, decodeASDCollection } from "../codec/asd.js";
5
5
  import {
6
6
  SchemaInfoSchema, TableInfoSchema, ViewInfoSchema, FunctionInfoSchema, MacroInfoSchema, IndexInfoSchema,
@@ -15,10 +15,10 @@ export const CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions",
15
15
  export type CatalogStreams = Pick<CatalogContentsResponse, typeof CATALOG_STREAM_KINDS[number]>;
16
16
 
17
17
  export function encodeCatalogStreams(inventory: readonly SchemaContentsInfo[]): CatalogStreams {
18
- for (const schema of inventory) for (const table of schema.tables) validateTableInfoColumns(table);
18
+ const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
19
19
  const streams = {
20
20
  schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
21
- tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
21
+ tables: encodeASDCollection(TableInfoSchema, tables),
22
22
  views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
23
23
  functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
24
24
  macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
@@ -25,18 +25,36 @@ 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. */
28
+ /**
29
+ * Canonical ConstraintInfo IPC records with provider-owned stable identities
30
+ * (build them with `constraintRecord`). They also set the served Arrow
31
+ * nullability: a column is served non-nullable exactly when a NOT_NULL or
32
+ * PRIMARY_KEY record names it, so a non-nullable field nobody names is
33
+ * served nullable.
34
+ */
29
35
  constraints?: Uint8Array[];
36
+ /** Opaque token that changes whenever `constraints` change. */
30
37
  definitionRevision?: Uint8Array | null;
31
38
  name: string;
32
39
  columns?: VgiSchema;
33
40
  function?: VgiFunction;
34
41
  arguments?: Arguments;
42
+ /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "NOT_NULL", ... })]`. */
35
43
  notNull?: string[];
44
+ /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "UNIQUE", ... })]`. */
36
45
  unique?: string[][];
46
+ /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "CHECK", ... })]`. */
37
47
  check?: string[];
48
+ /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "PRIMARY_KEY", ... })]`. */
38
49
  primaryKey?: string[][];
50
+ /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "FOREIGN_KEY", ... })]`. */
39
51
  foreignKey?: ForeignKeyDef[];
52
+ /**
53
+ * Column defaults as literals. Served as canonical `vgi.column.default.v1`
54
+ * when a string literal meets a utf8 column or a boolean a boolean column,
55
+ * and as the legacy `default` SQL key otherwise (numeric defaults included:
56
+ * their canonical form would show in duckdb_columns() as a folded cast).
57
+ */
40
58
  defaults?: Record<string, DefaultValue>;
41
59
  /** Per-column comment strings, applied as field metadata `comment`. */
42
60
  columnComments?: Record<string, string>;
@@ -0,0 +1,59 @@
1
+ // Copyright 2026 Query Farm LLC - https://query.farm
2
+ // Canonical index definitions (`IndexInfo.definition` / `IndexInfo.options`).
3
+
4
+ import { encodeASD } from "../codec/asd.js";
5
+ import {
6
+ CatalogObjectRefSchema, IndexDefinitionSchema, IndexKeySchema, OptionStateSchema,
7
+ } from "../generated/vgi-protocol-schemas.js";
8
+ import type { IndexConstraintType } from "../generated/vgi-client.js";
9
+
10
+ // A one-row, zero-column Arrow IPC stream: "no options". Fixed bytes so both
11
+ // Arrow backends produce the identical value.
12
+ const NO_OPTIONS_B64 =
13
+ "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
14
+
15
+ /** The typed-value batch for an index with no options. */
16
+ export function emptyIndexOptions(): Uint8Array {
17
+ return Uint8Array.from(atob(NO_OPTIONS_B64), (c) => c.charCodeAt(0));
18
+ }
19
+
20
+ export interface CanonicalIndexSpec {
21
+ /** Schema path of the indexed table. */
22
+ schemaPath: readonly string[];
23
+ /** Indexed table. */
24
+ table: string;
25
+ /** Raw column paths, one per key, in key order. */
26
+ columns: readonly (readonly string[])[];
27
+ /** Provider algorithm name, e.g. "art" or "btree". */
28
+ algorithm: string;
29
+ /** What the index claims; DuckDB reads NONE without a constraint. Default NONE. */
30
+ constraintType?: IndexConstraintType;
31
+ /** The id of the PRIMARY_KEY/UNIQUE constraint record the index implements, if any. */
32
+ associatedConstraintId?: string;
33
+ /** Typed option values (a one-row IPC batch); default: no options. */
34
+ options?: Uint8Array;
35
+ /** Options the user set explicitly (names in `options`). */
36
+ explicitOptionNames?: readonly string[];
37
+ }
38
+
39
+ /**
40
+ * Encode an index's `IndexInfo.definition` (`IndexDefinition`) and
41
+ * `IndexInfo.options` (`OptionState`) records.
42
+ */
43
+ export function canonicalIndex(spec: CanonicalIndexSpec): { definition: Uint8Array; options: Uint8Array } {
44
+ if (spec.columns.length === 0) throw new Error(`index on '${spec.table}' requires at least one key`);
45
+ if (!spec.algorithm) throw new Error("index algorithm must be nonempty");
46
+ const values = spec.options ?? emptyIndexOptions();
47
+ return {
48
+ definition: encodeASD(IndexDefinitionSchema, {
49
+ table: encodeASD(CatalogObjectRefSchema, { kind: "table", schema_path: spec.schemaPath, name: spec.table, owner_table: null }),
50
+ algorithm: spec.algorithm,
51
+ keys: spec.columns.map((path) => encodeASD(IndexKeySchema, { column_path: path, expression: null })),
52
+ options: values,
53
+ constraint_type: spec.constraintType ?? "NONE",
54
+ associated_constraint: spec.associatedConstraintId == null ? null
55
+ : encodeASD(CatalogObjectRefSchema, { kind: "constraint", schema_path: spec.schemaPath, name: spec.associatedConstraintId, owner_table: spec.table }),
56
+ }),
57
+ options: encodeASD(OptionStateSchema, { values, explicit_names: spec.explicitOptionNames ?? [] }),
58
+ };
59
+ }
@@ -3,8 +3,11 @@ import type { CatalogSnapshotPolicy } from "./publication.js";
3
3
  // CatalogInterface abstract class with ~35 methods.
4
4
  // Matching Python's vgi/catalog/catalog_interface.py
5
5
 
6
- import { CatalogReadOnlyError } from "../errors.js";
6
+ import { CatalogNotFoundError, CatalogReadOnlyError, VgiError } from "../errors.js";
7
7
  import { schemaPathsEqual } from "../schema-path.js";
8
+ import type { CatalogCapabilities, ConstraintSnapshot, ConstraintsApplyRequest } from "../generated/vgi-protocol-types.js";
9
+ import { decodeCatalogObjectRef, decodeConstraintChange, decodeConstraintDefinition } from "../generated/vgi-protocol-types.js";
10
+ import { constraintCapabilities, readConstraintRecord } from "./constraints.js";
8
11
 
9
12
  export type AttachOpaqueData = Uint8Array;
10
13
  export type TransactionOpaqueData = Uint8Array;
@@ -716,6 +719,16 @@ export abstract class CatalogInterface {
716
719
  ): Awaitable<TableInfo | null> {
717
720
  return null;
718
721
  }
722
+ /**
723
+ * CREATE TABLE. `constraintDefinitions` carries one canonical
724
+ * `ConstraintDefinition` record per declared constraint (decode with
725
+ * `decodeConstraintDefinition`); `columns` marks exactly the NOT NULL and
726
+ * PRIMARY KEY columns non-nullable. DuckDB sends definitions only when the
727
+ * attach negotiated `vgi.constraint.create.v1` (advertise it from
728
+ * `catalogCapabilities()`), and the catalog must then enforce every one on
729
+ * every write and serve each back as an ENFORCED + ALL_ROWS `ConstraintInfo`
730
+ * record (see `constraintRecord`). Refuse any it cannot enforce.
731
+ */
719
732
  tableCreate(
720
733
  attachOpaqueData: AttachOpaqueData,
721
734
  schemaPath: string[],
@@ -727,6 +740,86 @@ export abstract class CatalogInterface {
727
740
  ): Awaitable<void> {
728
741
  throw new CatalogReadOnlyError("table_create");
729
742
  }
743
+ /**
744
+ * The profiles this catalog implements for an attachment (advertised as
745
+ * `CatalogAttachResult.catalog_capabilities` when `attach()` leaves it
746
+ * unset; the worker selects against the client's offer). Override to serve
747
+ * canonical constraint records from a custom catalog, e.g.
748
+ * `return constraintCapabilities({ enforce: true })`. The default advertises
749
+ * nothing, unless the catalog implements `tableConstraintsApply` or the
750
+ * deprecated not-null hooks, in which case it advertises records read,
751
+ * mutation and enforcement. Return null for "unknown" (no SDK-side gating).
752
+ */
753
+ catalogCapabilities(_attachOpaqueData: AttachOpaqueData): Awaitable<CatalogCapabilities | null> {
754
+ const proto = CatalogInterface.prototype;
755
+ if (this.tableConstraintsApply !== proto.tableConstraintsApply || this._implementsLegacyNotNull())
756
+ return constraintCapabilities({ mutate: true, enforce: true });
757
+ return null;
758
+ }
759
+ /** Whether a subclass overrides either deprecated not-null hook. */
760
+ private _implementsLegacyNotNull(): boolean {
761
+ const proto = CatalogInterface.prototype;
762
+ return this.tableNotNullSet !== proto.tableNotNullSet || this.tableNotNullDrop !== proto.tableNotNullDrop;
763
+ }
764
+ /**
765
+ * Apply canonical constraint changes atomically (`catalog_table_constraints_apply`;
766
+ * DuckDB sends ALTER TABLE ... SET/DROP NOT NULL this way). Attach and
767
+ * transaction values arrive unwrapped. Reject the request when the table's
768
+ * current `definition_revision` differs from `request.expected_revision`;
769
+ * on success return the table's new records under a NEW definition revision.
770
+ * Requires `vgi.constraint.mutate.v1` (see `catalogCapabilities`).
771
+ *
772
+ * The default routes NOT NULL changes to the deprecated `tableNotNullSet` /
773
+ * `tableNotNullDrop` hooks when a catalog implements them (re-reading the
774
+ * table with `tableGet` for the snapshot, so that catalog must serve the
775
+ * NOT_NULL records and rotate `definition_revision` itself); otherwise it is
776
+ * unimplemented.
777
+ */
778
+ async tableConstraintsApply(request: ConstraintsApplyRequest): Promise<ConstraintSnapshot> {
779
+ if (!this._implementsLegacyNotNull()) throw new VgiError("catalog_table_constraints_apply is not implemented by this catalog", "UNIMPLEMENTED");
780
+ const target = decodeCatalogObjectRef(request.table);
781
+ const attach = request.attach_opaque_data;
782
+ const tx = request.transaction_opaque_data ?? undefined;
783
+ const schemaPath = [...target.schema_path];
784
+ const read = async () => {
785
+ const info = await this.tableGet(attach, schemaPath, target.name, undefined, undefined, tx);
786
+ if (!info) throw new CatalogNotFoundError("Table", target.name);
787
+ return info;
788
+ };
789
+ const before = await read();
790
+ if (!sameBytes(before.definition_revision ?? null, request.expected_revision))
791
+ throw new VgiError(`Table '${target.name}': definition_revision changed; retry the statement`, "FAILED_PRECONDITION");
792
+ const records = (before.constraints ?? []).map(readConstraintRecord);
793
+ for (const bytes of request.changes) {
794
+ const change = decodeConstraintChange(bytes);
795
+ if (change.operation === "ADD" && change.definition != null) {
796
+ const def = decodeConstraintDefinition(change.definition);
797
+ if (def.kind === "NOT_NULL" && def.column_paths.length === 1 && def.column_paths[0].length === 1) {
798
+ await this.tableNotNullSet(attach, schemaPath, target.name, [...def.column_paths[0]], false, tx);
799
+ continue;
800
+ }
801
+ } else if (change.operation === "DROP" && change.ref != null) {
802
+ const id = decodeCatalogObjectRef(change.ref).name;
803
+ const record = records.find((r) => r.id === id);
804
+ if (record?.kind === "NOT_NULL" && record.columns[0]?.length === 1) {
805
+ await this.tableNotNullDrop(attach, schemaPath, target.name, record.columns[0], false, tx);
806
+ continue;
807
+ }
808
+ }
809
+ throw new VgiError(
810
+ "catalog_table_constraints_apply: only ADD/DROP of a top-level NOT_NULL routes to tableNotNullSet/tableNotNullDrop; implement tableConstraintsApply",
811
+ "UNIMPLEMENTED",
812
+ );
813
+ }
814
+ const after = await read();
815
+ if (after.definition_revision == null || sameBytes(after.definition_revision, before.definition_revision ?? null))
816
+ throw new VgiError(
817
+ `Table '${target.name}': the NOT NULL change was applied but tableGet still serves the old definition_revision; ` +
818
+ "a catalog using tableNotNullSet/tableNotNullDrop must rotate it (or implement tableConstraintsApply)",
819
+ "INTERNAL",
820
+ );
821
+ return { table: request.table, definition_revision: after.definition_revision, constraints: after.constraints ?? [] };
822
+ }
730
823
  tableDrop(
731
824
  attachOpaqueData: AttachOpaqueData,
732
825
  schemaPath: string[],
@@ -882,6 +975,7 @@ export abstract class CatalogInterface {
882
975
  ): Awaitable<void> {
883
976
  throw new CatalogReadOnlyError("catalog_table_column_type_change");
884
977
  }
978
+ /** @deprecated DuckDB sends SET NOT NULL through `tableConstraintsApply`; the default routes it here. */
885
979
  tableNotNullSet(
886
980
  attachOpaqueData: AttachOpaqueData,
887
981
  schemaPath: string[],
@@ -892,6 +986,7 @@ export abstract class CatalogInterface {
892
986
  ): Awaitable<void> {
893
987
  throw new CatalogReadOnlyError("catalog_table_not_null_set");
894
988
  }
989
+ /** @deprecated DuckDB sends DROP NOT NULL through `tableConstraintsApply`; the default routes it here. */
895
990
  tableNotNullDrop(
896
991
  attachOpaqueData: AttachOpaqueData,
897
992
  schemaPath: string[],
@@ -1114,3 +1209,10 @@ export abstract class CatalogInterface {
1114
1209
  transactionOpaqueData: TransactionOpaqueData
1115
1210
  ): Awaitable<void> {}
1116
1211
  }
1212
+
1213
+ function sameBytes(a: Uint8Array | null, b: Uint8Array | null): boolean {
1214
+ if (a == null || b == null) return a == b;
1215
+ if (a.length !== b.length) return false;
1216
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1217
+ return true;
1218
+ }
@@ -0,0 +1,36 @@
1
+ // Copyright 2026 Query Farm LLC - https://query.farm
2
+ // The vgi.v3 record codecs and builders a custom catalog (worker side) or a
3
+ // client needs, re-exported from one place for every package entry point.
4
+
5
+ export {
6
+ constraintRecord, readConstraintRecord, validateTableConstraints, validateForeignKeyTargets,
7
+ servedTableSchema, servedTableInfo, servedConstraintFields, validateConstraintNullability,
8
+ selectReadProfiles, selectCatalogCapabilities, catalogCapabilities, constraintCapabilities,
9
+ defaultClientCapabilities,
10
+ CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, CONSTRAINT_CREATE, CONSTRAINT_MUTATE, CONSTRAINT_ENFORCE, TRANSACTION_DDL,
11
+ type ConstraintRecordSpec, type ConstraintRecordView, type ConstraintKind, type ConstraintEnforcement,
12
+ type ConstraintValidation, type ConstraintTableRef, type ValidatedConstraints,
13
+ } from "./constraints.js";
14
+ export {
15
+ sqlExpression, generatedExpressionMetadata, defaultExpressionMetadata,
16
+ GENERATED_EXPRESSION_KEY, GENERATION_KEY, DEFAULT_EXPRESSION_KEY,
17
+ } from "./column-expressions.js";
18
+ export { validateColumnExpressionSql, validateNumericCheckSql } from "./sql-grammar.js";
19
+ export { canonicalIndex, emptyIndexOptions, type CanonicalIndexSpec } from "./indexes.js";
20
+ export {
21
+ encodeCatalogCapabilities, decodeCatalogCapabilities, buildCatalogCapabilities,
22
+ encodeSqlExpression, decodeSqlExpression,
23
+ encodeCatalogObjectRef, decodeCatalogObjectRef,
24
+ encodeConstraintInfo, decodeConstraintInfo,
25
+ encodeConstraintDefinition, decodeConstraintDefinition, buildConstraintDefinition,
26
+ encodeForeignKeyDefinition, decodeForeignKeyDefinition,
27
+ encodeConstraintChange, decodeConstraintChange, buildConstraintChange,
28
+ encodeConstraintSnapshot, decodeConstraintSnapshot,
29
+ encodeConstraintsApplyRequest, decodeConstraintsApplyRequest,
30
+ encodeIndexDefinition, decodeIndexDefinition,
31
+ encodeMacroOverload, decodeMacroOverload, buildMacroOverload,
32
+ type CatalogCapabilities, type SqlExpression, type CatalogObjectRef, type ConstraintInfo, type ConstraintDefinition,
33
+ type ForeignKeyDefinition, type ConstraintChange, type ConstraintSnapshot, type ConstraintsApplyRequest,
34
+ type IndexDefinition, type MacroOverload, type MacroParameter,
35
+ } from "../generated/vgi-protocol-types.js";
36
+ export type { ClientCapabilities } from "../generated/vgi-client.js";
@@ -37,7 +37,10 @@ import { conformColumns } from "../codec/conform.js";
37
37
  import { VgiError } from "../errors.js";
38
38
  import { encodeFunctionInfoOnce, freezeCatalogItem } from "./item-encoding.js";
39
39
  import { macroOverloads } from "./macro-overloads.js";
40
- import { CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, selectReadProfiles, validateConstraintNullability } from "./constraints.js";
40
+ import { CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, catalogCapabilities, selectReadProfiles, servedTableSchema, validateForeignKeyTargets } from "./constraints.js";
41
+ import { duckdbPrimitive } from "./column-types.js";
42
+ import { defaultExpressionMetadata } from "./column-expressions.js";
43
+ import type { CatalogCapabilities } from "../generated/vgi-protocol-types.js";
41
44
  import { encodeCatalogCapabilities } from "../generated/vgi-protocol-types.js";
42
45
 
43
46
  /**
@@ -270,6 +273,12 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
270
273
  return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
271
274
  }
272
275
 
276
+ /** The descriptor's read profiles (records are served, never mutated here). */
277
+ override catalogCapabilities(_attachOpaqueData: AttachOpaqueData): CatalogCapabilities | null {
278
+ const read = this.catalogReadProfiles();
279
+ return read.length ? catalogCapabilities({ read }) : null;
280
+ }
281
+
273
282
  detach(attachOpaqueData: AttachOpaqueData): void {
274
283
  // Remove attachment
275
284
  for (const [name, id] of this._attachments) {
@@ -350,9 +359,20 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
350
359
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
351
360
  if (!schema || !schema.tables) return [];
352
361
 
353
- return await Promise.all(schema.tables.map(async (t) => {
362
+ const infos = await Promise.all(schema.tables.map(async (t) => {
363
+ // Refuse the pre-v3 constraint fields before anything else, so the author
364
+ // sees the replacement rather than an error about a derived schema.
365
+ if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
366
+ throw new Error(
367
+ `Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` +
368
+ "declare canonical records with constraintRecord() in `constraints` instead"
369
+ );
370
+ }
354
371
  // Resolve the column schema
355
372
  let colSchema: VgiSchema;
373
+ // True when a function-backed table's dummy bind failed: the table is
374
+ // listed with no columns, and per-column decorations cannot apply.
375
+ let bindFailed = false;
356
376
  if (t.columns) {
357
377
  colSchema = t.columns;
358
378
  } else if (t.function) {
@@ -374,40 +394,46 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
374
394
  colSchema = response.output_schema;
375
395
  } catch {
376
396
  colSchema = schema_([]);
397
+ bindFailed = true;
377
398
  }
378
399
  } else {
379
400
  colSchema = schema_([]);
380
401
  }
381
402
 
382
- // Apply defaults as Arrow field metadata
383
- if (t.defaults) {
384
- colSchema = applyDefaults(colSchema, t.defaults);
385
- }
386
- // Apply generated-column expressions as Arrow field metadata
387
- // (canonical SqlExpression IPC). DuckDB registers these columns as GENERATED
388
- // and evaluates the SQL expression client-side — the scan function
389
- // should not return values for them.
390
- if (t.generatedColumns) {
391
- colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path);
392
- }
393
- // Apply per-column comments as Arrow field metadata (matches Python's
394
- // `comment` metadata key on columns).
395
- if (t.columnComments) {
396
- colSchema = applyColumnComments(colSchema, t.columnComments);
403
+ if (!bindFailed) {
404
+ // Apply defaults as Arrow field metadata
405
+ if (t.defaults) {
406
+ colSchema = applyDefaults(colSchema, t.defaults, path);
407
+ }
408
+ // Apply generated-column expressions as Arrow field metadata
409
+ // (canonical SqlExpression IPC). DuckDB registers these columns as GENERATED
410
+ // and evaluates the SQL expression client-side — the scan function
411
+ // should not return values for them.
412
+ if (t.generatedColumns) {
413
+ colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path, t.name);
414
+ }
415
+ // Apply per-column comments as Arrow field metadata (matches Python's
416
+ // `comment` metadata key on columns).
417
+ if (t.columnComments) {
418
+ colSchema = applyColumnComments(colSchema, t.columnComments, t.name);
419
+ }
397
420
  }
398
421
 
399
422
  validateColumnMetadata(colSchema);
400
- // The extension rejects the table at ATTACH when these disagree.
401
- validateConstraintNullability(t.name, colSchema.fields, t.constraints ?? []);
402
- validateColumnExpressions(colSchema, path);
403
- const columns = serializeSchema(colSchema);
404
-
405
- if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
406
- throw new Error(
407
- `Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` +
408
- "declare canonical records with constraintRecord() in `constraints` instead"
409
- );
423
+ // Constraint records about columns a failed bind could not produce are
424
+ // unservable (DuckDB would reject the table); list the table bare.
425
+ const constraints = bindFailed ? [] : (t.constraints ?? []);
426
+ // The served schema: legacy generated metadata translated, records
427
+ // checked as DuckDB checks them at ATTACH, nullability exactly the
428
+ // records' (a non-nullable field no NOT_NULL/PRIMARY_KEY names is served
429
+ // nullable; a named one non-nullable).
430
+ colSchema = servedTableSchema(t.name, path, colSchema, constraints);
431
+ try {
432
+ validateColumnExpressions(colSchema, path);
433
+ } catch (error) {
434
+ throw new Error(`Table '${t.name}': ${(error as Error).message}`);
410
435
  }
436
+ const columns = serializeSchema(colSchema);
411
437
 
412
438
  // Validate exact raw paths against the full table schema.
413
439
  const requiredFilters = t.requiredFilters ?? [];
@@ -439,7 +465,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
439
465
  name: t.name,
440
466
  schema_path: normalizeSchemaPath(path),
441
467
  columns,
442
- constraints: t.constraints ?? [],
468
+ constraints: [...constraints],
443
469
  definition_revision: t.definitionRevision ?? null,
444
470
  write_result_modes: {},
445
471
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
@@ -463,6 +489,10 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
463
489
  required_filters: requiredFilters,
464
490
  };
465
491
  }));
492
+ // DuckDB resolves a foreign key against its target when the referencing
493
+ // table loads; every target is in this schema, so check them all here.
494
+ validateForeignKeyTargets(infos.map((info) => ({ schemaPath: info.schema_path, name: info.name, constraints: info.constraints })));
495
+ return infos;
466
496
  }
467
497
 
468
498
  override tableColumnStatisticsGet(
@@ -1005,14 +1035,35 @@ function defaultToSql(value: DefaultValue): string {
1005
1035
  return `'${escaped}'`;
1006
1036
  }
1007
1037
 
1008
- function applyDefaults(schema: VgiSchema, defaults: Record<string, DefaultValue>): VgiSchema {
1038
+ /**
1039
+ * Whether a literal default is served as canonical `vgi.column.default.v1`.
1040
+ * DuckDB folds a canonical default to a typed constant, so it is used only
1041
+ * where that constant renders exactly as the literal: a string for a utf8
1042
+ * column, a boolean for a boolean column. Numeric defaults fold to a cast
1043
+ * (`CAST(0 AS BIGINT)`, `CAST(9.99 AS DOUBLE)`) in duckdb_columns(), so they
1044
+ * keep the legacy `default` key, which DuckDB shows verbatim.
1045
+ */
1046
+ function canonicalDefault(type: string | null, value: DefaultValue): boolean {
1047
+ if (type === "BOOLEAN") return typeof value === "boolean";
1048
+ if (type === "VARCHAR") return typeof value === "string";
1049
+ return false;
1050
+ }
1051
+
1052
+ function applyDefaults(schema: VgiSchema, defaults: Record<string, DefaultValue>, owner: string[]): VgiSchema {
1009
1053
  let result = schema;
1010
1054
  for (const [colName, value] of Object.entries(defaults)) {
1011
1055
  const idx = result.fields.findIndex((f) => f.name === colName);
1012
1056
  if (idx < 0) continue;
1013
1057
  const f = result.fields[idx];
1014
1058
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
1015
- existingMeta.set("default", defaultToSql(value));
1059
+ const sql = defaultToSql(value);
1060
+ // Canonical where it is exact (see canonicalDefault); the legacy "default"
1061
+ // key otherwise, which DuckDB still parses as raw SQL.
1062
+ if (canonicalDefault(duckdbPrimitive(f), value)) {
1063
+ existingMeta.set("vgi.column.default.v1", defaultExpressionMetadata(sql, owner));
1064
+ } else {
1065
+ existingMeta.set("default", sql);
1066
+ }
1016
1067
  const newField = field(f.name, f.type, f.nullable, existingMeta);
1017
1068
  const fields = [...result.fields];
1018
1069
  fields[idx] = newField;
@@ -1021,15 +1072,20 @@ function applyDefaults(schema: VgiSchema, defaults: Record<string, DefaultValue>
1021
1072
  return result;
1022
1073
  }
1023
1074
 
1024
- function applyGeneratedColumns(schema: VgiSchema, generated: Record<string, string>, owner: string[]): VgiSchema {
1075
+ function applyGeneratedColumns(schema: VgiSchema, generated: Record<string, string>, owner: string[], table: string): VgiSchema {
1025
1076
  let result = schema;
1026
1077
  for (const [colName, expression] of Object.entries(generated)) {
1027
1078
  const idx = result.fields.findIndex((f) => f.name === colName);
1028
- if (idx < 0) throw new Error(`generated expression references unknown column ${colName}`);
1079
+ if (idx < 0) throw new Error(`Table '${table}': generatedColumns names unknown column ${colName}`);
1029
1080
  const f = result.fields[idx];
1030
1081
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
1031
- if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression")) throw new Error("generated convenience conflicts with existing expression metadata");
1032
- existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
1082
+ if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression"))
1083
+ throw new Error(`Table '${table}': generatedColumns for ${colName} conflicts with existing expression metadata`);
1084
+ try {
1085
+ existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
1086
+ } catch (error) {
1087
+ throw new Error(`Table '${table}': column ${colName}: ${(error as Error).message}`);
1088
+ }
1033
1089
  existingMeta.set(GENERATION_KEY, "virtual");
1034
1090
  const newField = field(f.name, f.type, f.nullable, existingMeta);
1035
1091
  const fields = [...result.fields];
@@ -1039,11 +1095,11 @@ function applyGeneratedColumns(schema: VgiSchema, generated: Record<string, stri
1039
1095
  return result;
1040
1096
  }
1041
1097
 
1042
- function applyColumnComments(schema: VgiSchema, comments: Record<string, string>): VgiSchema {
1098
+ function applyColumnComments(schema: VgiSchema, comments: Record<string, string>, table: string): VgiSchema {
1043
1099
  let result = schema;
1044
1100
  for (const [colName, comment] of Object.entries(comments)) {
1045
1101
  const idx = result.fields.findIndex((f) => f.name === colName);
1046
- if (idx < 0) throw new Error(`column comment references unknown field ${colName}`);
1102
+ if (idx < 0) throw new Error(`Table '${table}': columnComments names unknown column ${colName}`);
1047
1103
  const f = result.fields[idx];
1048
1104
  const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
1049
1105
  existingMeta.set("comment", comment);