@query-farm/vgi 0.47.0 → 0.47.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/catalog/column-expressions.d.ts +22 -1
- package/dist/catalog/column-metadata.d.ts +7 -0
- package/dist/catalog/column-types.d.ts +15 -0
- package/dist/catalog/composite.d.ts +2 -0
- package/dist/catalog/constraints.d.ts +172 -0
- package/dist/catalog/descriptors.d.ts +19 -1
- package/dist/catalog/indexes.d.ts +29 -0
- package/dist/catalog/interface.d.ts +41 -0
- package/dist/catalog/public-codecs.d.ts +6 -0
- package/dist/catalog/read-only.d.ts +9 -0
- package/dist/catalog/sql-grammar.d.ts +53 -0
- package/dist/catalog/unconstrained-columns.d.ts +8 -0
- package/dist/client/types.d.ts +5 -1
- package/dist/client-entry.d.ts +1 -0
- package/dist/client-entry.js +1410 -152
- package/dist/client-entry.js.map +12 -8
- package/dist/index.core.d.ts +1 -0
- package/dist/index.js +1644 -226
- package/dist/index.js.map +19 -15
- package/dist/serve-entry.js +1100 -29
- package/dist/serve-entry.js.map +13 -10
- package/dist/worker-cf-entry.d.ts +2 -1
- package/dist/worker-cf-entry.js +1477 -54
- package/dist/worker-cf-entry.js.map +19 -15
- package/package.json +1 -1
- package/src/catalog/column-expressions.ts +85 -7
- package/src/catalog/column-metadata.ts +20 -2
- package/src/catalog/column-types.ts +50 -0
- package/src/catalog/composite.ts +10 -0
- package/src/catalog/constraints.ts +645 -0
- package/src/catalog/contents-codec.ts +3 -3
- package/src/catalog/descriptors.ts +19 -1
- package/src/catalog/indexes.ts +59 -0
- package/src/catalog/interface.ts +103 -1
- package/src/catalog/public-codecs.ts +36 -0
- package/src/catalog/read-only.ts +115 -30
- package/src/catalog/sql-grammar.ts +476 -0
- package/src/catalog/unconstrained-columns.ts +34 -8
- package/src/client/client.ts +6 -3
- package/src/client/types.ts +5 -1
- package/src/client-entry.ts +4 -0
- package/src/index.core.ts +2 -0
- package/src/protocol/handlers/catalog/admin.ts +19 -2
- package/src/protocol/handlers/catalog/table.ts +58 -11
- package/src/worker-cf-entry.ts +4 -0
|
@@ -25,18 +25,36 @@ export interface ForeignKeyDef {
|
|
|
25
25
|
export type DefaultValue = string | number | boolean | null;
|
|
26
26
|
|
|
27
27
|
export interface TableDescriptor {
|
|
28
|
-
/**
|
|
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
|
+
}
|
package/src/catalog/interface.ts
CHANGED
|
@@ -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";
|
package/src/catalog/read-only.ts
CHANGED
|
@@ -37,6 +37,11 @@ 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, 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";
|
|
44
|
+
import { encodeCatalogCapabilities } from "../generated/vgi-protocol-types.js";
|
|
40
45
|
|
|
41
46
|
/**
|
|
42
47
|
* The fixed attach id ReadOnlyCatalogInterface writes into its items (same
|
|
@@ -212,6 +217,10 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
212
217
|
encodeAttachCatalogInfo(c)
|
|
213
218
|
);
|
|
214
219
|
|
|
220
|
+
// Constraint records are readable only under a negotiated profile.
|
|
221
|
+
const available = this.catalogReadProfiles();
|
|
222
|
+
const read = selectReadProfiles(available, clientCapabilities);
|
|
223
|
+
|
|
215
224
|
// Auto-derive supportsTimeTravel from table descriptors
|
|
216
225
|
const hasTimeTravel = this._descriptor.schemas.some(
|
|
217
226
|
(s) => s.tables?.some((t) => t.supportsTimeTravel) ?? false
|
|
@@ -243,9 +252,33 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
243
252
|
// Static, version-frozen catalog: the whole thing can be served in one
|
|
244
253
|
// catalog_contents call (as vgi-python's ReadOnlyCatalogInterface does).
|
|
245
254
|
supports_catalog_contents: this.supportsCatalogContents,
|
|
255
|
+
catalog_capabilities: available.length
|
|
256
|
+
? encodeCatalogCapabilities({ read: [...available].sort(), ddl: [], write: [], transaction: [] })
|
|
257
|
+
: null,
|
|
258
|
+
selected_capabilities: available.length
|
|
259
|
+
? encodeCatalogCapabilities({ read, ddl: [], write: [], transaction: [] })
|
|
260
|
+
: null,
|
|
246
261
|
});
|
|
247
262
|
}
|
|
248
263
|
|
|
264
|
+
/**
|
|
265
|
+
* Read profiles this catalog implements. Defaults to constraint records
|
|
266
|
+
* (with scalar CHECK expressions) when any descriptor table carries
|
|
267
|
+
* `constraints`; override when tables are served outside the descriptor.
|
|
268
|
+
*/
|
|
269
|
+
catalogReadProfiles(): string[] {
|
|
270
|
+
const hasConstraints = this._descriptor.schemas.some(
|
|
271
|
+
(s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false
|
|
272
|
+
);
|
|
273
|
+
return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
|
|
274
|
+
}
|
|
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
|
+
|
|
249
282
|
detach(attachOpaqueData: AttachOpaqueData): void {
|
|
250
283
|
// Remove attachment
|
|
251
284
|
for (const [name, id] of this._attachments) {
|
|
@@ -326,9 +359,20 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
326
359
|
const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
|
|
327
360
|
if (!schema || !schema.tables) return [];
|
|
328
361
|
|
|
329
|
-
|
|
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
|
+
}
|
|
330
371
|
// Resolve the column schema
|
|
331
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;
|
|
332
376
|
if (t.columns) {
|
|
333
377
|
colSchema = t.columns;
|
|
334
378
|
} else if (t.function) {
|
|
@@ -350,35 +394,46 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
350
394
|
colSchema = response.output_schema;
|
|
351
395
|
} catch {
|
|
352
396
|
colSchema = schema_([]);
|
|
397
|
+
bindFailed = true;
|
|
353
398
|
}
|
|
354
399
|
} else {
|
|
355
400
|
colSchema = schema_([]);
|
|
356
401
|
}
|
|
357
402
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
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
|
+
}
|
|
373
420
|
}
|
|
374
421
|
|
|
375
422
|
validateColumnMetadata(colSchema);
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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}`);
|
|
381
435
|
}
|
|
436
|
+
const columns = serializeSchema(colSchema);
|
|
382
437
|
|
|
383
438
|
// Validate exact raw paths against the full table schema.
|
|
384
439
|
const requiredFilters = t.requiredFilters ?? [];
|
|
@@ -410,7 +465,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
410
465
|
name: t.name,
|
|
411
466
|
schema_path: normalizeSchemaPath(path),
|
|
412
467
|
columns,
|
|
413
|
-
constraints:
|
|
468
|
+
constraints: [...constraints],
|
|
414
469
|
definition_revision: t.definitionRevision ?? null,
|
|
415
470
|
write_result_modes: {},
|
|
416
471
|
supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
|
|
@@ -434,6 +489,10 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
434
489
|
required_filters: requiredFilters,
|
|
435
490
|
};
|
|
436
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;
|
|
437
496
|
}
|
|
438
497
|
|
|
439
498
|
override tableColumnStatisticsGet(
|
|
@@ -976,14 +1035,35 @@ function defaultToSql(value: DefaultValue): string {
|
|
|
976
1035
|
return `'${escaped}'`;
|
|
977
1036
|
}
|
|
978
1037
|
|
|
979
|
-
|
|
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 {
|
|
980
1053
|
let result = schema;
|
|
981
1054
|
for (const [colName, value] of Object.entries(defaults)) {
|
|
982
1055
|
const idx = result.fields.findIndex((f) => f.name === colName);
|
|
983
1056
|
if (idx < 0) continue;
|
|
984
1057
|
const f = result.fields[idx];
|
|
985
1058
|
const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
|
|
986
|
-
|
|
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
|
+
}
|
|
987
1067
|
const newField = field(f.name, f.type, f.nullable, existingMeta);
|
|
988
1068
|
const fields = [...result.fields];
|
|
989
1069
|
fields[idx] = newField;
|
|
@@ -992,15 +1072,20 @@ function applyDefaults(schema: VgiSchema, defaults: Record<string, DefaultValue>
|
|
|
992
1072
|
return result;
|
|
993
1073
|
}
|
|
994
1074
|
|
|
995
|
-
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 {
|
|
996
1076
|
let result = schema;
|
|
997
1077
|
for (const [colName, expression] of Object.entries(generated)) {
|
|
998
1078
|
const idx = result.fields.findIndex((f) => f.name === colName);
|
|
999
|
-
if (idx < 0) throw new Error(`
|
|
1079
|
+
if (idx < 0) throw new Error(`Table '${table}': generatedColumns names unknown column ${colName}`);
|
|
1000
1080
|
const f = result.fields[idx];
|
|
1001
1081
|
const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
|
|
1002
|
-
if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression"))
|
|
1003
|
-
|
|
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
|
+
}
|
|
1004
1089
|
existingMeta.set(GENERATION_KEY, "virtual");
|
|
1005
1090
|
const newField = field(f.name, f.type, f.nullable, existingMeta);
|
|
1006
1091
|
const fields = [...result.fields];
|
|
@@ -1010,11 +1095,11 @@ function applyGeneratedColumns(schema: VgiSchema, generated: Record<string, stri
|
|
|
1010
1095
|
return result;
|
|
1011
1096
|
}
|
|
1012
1097
|
|
|
1013
|
-
function applyColumnComments(schema: VgiSchema, comments: Record<string, string
|
|
1098
|
+
function applyColumnComments(schema: VgiSchema, comments: Record<string, string>, table: string): VgiSchema {
|
|
1014
1099
|
let result = schema;
|
|
1015
1100
|
for (const [colName, comment] of Object.entries(comments)) {
|
|
1016
1101
|
const idx = result.fields.findIndex((f) => f.name === colName);
|
|
1017
|
-
if (idx < 0) throw new Error(`
|
|
1102
|
+
if (idx < 0) throw new Error(`Table '${table}': columnComments names unknown column ${colName}`);
|
|
1018
1103
|
const f = result.fields[idx];
|
|
1019
1104
|
const existingMeta = f.metadata ? new Map(f.metadata) : new Map<string, string>();
|
|
1020
1105
|
existingMeta.set("comment", comment);
|