@query-farm/vgi 0.47.0 → 0.47.1

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.
@@ -0,0 +1,74 @@
1
+ import { type VgiField } from "../arrow/index.js";
2
+ /** Read profile: the catalog serves canonical ConstraintInfo records. */
3
+ export declare const CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
4
+ /** Read profile: CHECK constraints carry DuckDB scalar SQL expressions. */
5
+ export declare const ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
6
+ export type ConstraintKind = "NOT_NULL" | "PRIMARY_KEY" | "UNIQUE" | "CHECK" | "FOREIGN_KEY";
7
+ /** Whether the authority enforces the constraint on every write path. */
8
+ export type ConstraintEnforcement = "ENFORCED" | "METADATA_ONLY";
9
+ /** Coverage of existing rows; only ALL_ROWS justifies engine facts. */
10
+ export type ConstraintValidation = "ALL_ROWS" | "FUTURE_WRITES" | "UNVALIDATED";
11
+ export interface ConstraintRecordSpec {
12
+ /** Schema path of the owning table. */
13
+ schemaPath: readonly string[];
14
+ /** Owning table name. */
15
+ table: string;
16
+ /** Stable provider-owned identity, unique within the table. Never derived by the SDK. */
17
+ id: string;
18
+ kind: ConstraintKind;
19
+ /** Raw component paths, e.g. `[["id"]]` or `[["bbox", "xmin"]]`; empty for CHECK. */
20
+ columns: readonly (readonly string[])[];
21
+ /**
22
+ * The provider's attestation. The DuckDB extension reads only
23
+ * ENFORCED + ALL_ROWS records, so state that only when every row the table
24
+ * can ever return satisfies the constraint.
25
+ */
26
+ enforcement: ConstraintEnforcement;
27
+ validation: ConstraintValidation;
28
+ /** Optional SQL label (CONSTRAINT <name>). */
29
+ declaredName?: string;
30
+ /** CHECK only: a DuckDB scalar expression over the table's columns. */
31
+ checkSql?: string;
32
+ /** FOREIGN_KEY only: the referenced key and its constraint identity. */
33
+ references?: {
34
+ schemaPath: readonly string[];
35
+ table: string;
36
+ columns: readonly (readonly string[])[];
37
+ /** `id` of the referenced table's PRIMARY_KEY or UNIQUE record. */
38
+ constraintId: string;
39
+ };
40
+ }
41
+ /** Encode one canonical `ConstraintInfo` record for `TableDescriptor.constraints`. */
42
+ export declare function constraintRecord(spec: ConstraintRecordSpec): Uint8Array;
43
+ /**
44
+ * The client-offered profiles from `available`, in canonical (sorted) order.
45
+ * A scalar-expression read is selected only alongside constraint records.
46
+ */
47
+ export declare function selectReadProfiles(available: readonly string[], clientCapabilities: Uint8Array | null | undefined): string[];
48
+ /** A decoded `ConstraintInfo` record, in `constraintRecord()`'s vocabulary. */
49
+ export interface ConstraintRecordView {
50
+ schemaPath: string[];
51
+ table: string;
52
+ id: string;
53
+ kind: ConstraintKind;
54
+ columns: string[][];
55
+ enforcement: ConstraintEnforcement;
56
+ validation: ConstraintValidation;
57
+ declaredName: string | null;
58
+ checkSql: string | null;
59
+ references: {
60
+ schemaPath: string[];
61
+ table: string;
62
+ columns: string[][];
63
+ constraintId: string | null;
64
+ } | null;
65
+ }
66
+ /** Decode a `TableInfo.constraints` entry (the inverse of `constraintRecord`). */
67
+ export declare function readConstraintRecord(bytes: Uint8Array): ConstraintRecordView;
68
+ /**
69
+ * Check a table's records the way the DuckDB extension does at ATTACH: every
70
+ * record is ENFORCED + ALL_ROWS, and Arrow nullability agrees with the
71
+ * NOT_NULL/PRIMARY_KEY records (a field, descending through ordinary STRUCTs,
72
+ * is non-nullable exactly when a record names its path).
73
+ */
74
+ export declare function validateConstraintNullability(table: string, fields: readonly VgiField[], constraints: readonly Uint8Array[]): void;
@@ -87,6 +87,12 @@ export declare class ReadOnlyCatalogInterface extends CatalogInterface {
87
87
  attachOptionSpecs(_name: string): AttachOptionSpec[];
88
88
  catalogsInfo(): CatalogInfo[];
89
89
  attach(name: string, options?: Record<string, unknown>, dataVersionSpec?: string | null, implementationVersion?: string | null, clientCapabilities?: Uint8Array | null): CatalogAttachResult | Promise<CatalogAttachResult>;
90
+ /**
91
+ * Read profiles this catalog implements. Defaults to constraint records
92
+ * (with scalar CHECK expressions) when any descriptor table carries
93
+ * `constraints`; override when tables are served outside the descriptor.
94
+ */
95
+ catalogReadProfiles(): string[];
90
96
  detach(attachOpaqueData: AttachOpaqueData): void;
91
97
  version(attachOpaqueData: AttachOpaqueData, transactionOpaqueData?: TransactionOpaqueData): number | Promise<number>;
92
98
  /**
@@ -11,6 +11,7 @@ export type { VgiFunction, FunctionMeta, StreamHandlers, FunctionExample, Handle
11
11
  export { CatalogInterface, type CatalogAttachResult, type CatalogAttachResultInit, buildCatalogAttachResult, type SchemaContentsInfo, type CatalogContentsResult, type SchemaInfo, encodeSchemaInfo, decodeSchemaInfo, type TableInfo, encodeTableInfo, decodeTableInfo, type ViewInfo, encodeViewInfo, decodeViewInfo, type CatalogInfo, encodeCatalogInfo, decodeCatalogInfo, type FunctionInfo, encodeFunctionInfo, decodeFunctionInfo, type FunctionInfoOptions, type MacroInfo, encodeMacroInfo, decodeMacroInfo, type MacroType, type CopyFromFormatInfo, encodeCopyFromFormatInfo, type AttachOpaqueData, type TransactionOpaqueData, buildScanBranchesResult, encodeFormatOptions, type ScanBranchInput } from "./catalog/interface.js";
12
12
  export type { CatalogDescriptor, SchemaDescriptor, TableDescriptor, ViewDescriptor, MacroDescriptor, SettingDescriptor, SecretTypeDescriptor, ForeignKeyDef, DefaultValue } from "./catalog/descriptors.js";
13
13
  export { ReadOnlyCatalogInterface, READ_ONLY_ITEM_ATTACH_ID } from "./catalog/read-only.js";
14
+ export { constraintRecord, readConstraintRecord, validateConstraintNullability, selectReadProfiles, CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, type ConstraintRecordSpec, type ConstraintRecordView, type ConstraintKind, type ConstraintEnforcement, type ConstraintValidation } from "./catalog/constraints.js";
14
15
  export { CompositeCatalogInterface } from "./catalog/composite.js";
15
16
  export { FunctionRegistry } from "./functions/registry.js";
16
17
  export { FunctionType, FunctionStability, NullHandling, ArgumentMonotonicity, OrderPreservation, OrderDependence, DistinctDependence, TableInOutPhase, DEFAULT_MAX_WORKERS, } from "./types.js";
package/dist/index.js CHANGED
@@ -8879,6 +8879,8 @@ var TableFunctionStatisticsParamsSchema = schema2([
8879
8879
  ]);
8880
8880
 
8881
8881
  // src/generated/vgi-protocol-types.ts
8882
+ var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
8883
+ var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
8882
8884
  var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
8883
8885
  var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
8884
8886
  function buildCatalogAttachResult(init) {
@@ -9924,6 +9926,128 @@ function macroOverloads(macro, owner) {
9924
9926
  }];
9925
9927
  }
9926
9928
 
9929
+ // src/catalog/constraints.ts
9930
+ init_arrow();
9931
+ var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
9932
+ var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
9933
+ function objectRef(kind, schemaPath, name, ownerTable) {
9934
+ return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
9935
+ }
9936
+ function constraintRecord(spec) {
9937
+ if (!spec.id || spec.id.includes("\x00"))
9938
+ throw new Error("constraint id must be nonempty without NUL");
9939
+ if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
9940
+ throw new Error("checkSql is required for CHECK and only CHECK");
9941
+ if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
9942
+ throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
9943
+ if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
9944
+ throw new Error("NOT_NULL requires exactly one column path");
9945
+ if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
9946
+ throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
9947
+ if (spec.references && spec.references.columns.length !== spec.columns.length)
9948
+ throw new Error("foreign key local and referenced arity must match");
9949
+ const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
9950
+ sql: spec.checkSql,
9951
+ profile: ROW_SCALAR_EXPRESSION,
9952
+ schema_path: spec.schemaPath,
9953
+ evaluation_context: {
9954
+ timezone: "UTC",
9955
+ collation: "binary",
9956
+ default_order: "asc",
9957
+ default_null_order: "nulls_last",
9958
+ preserve_insertion_order: true
9959
+ }
9960
+ });
9961
+ const ref = spec.references;
9962
+ const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
9963
+ referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
9964
+ referenced_column_paths: ref.columns,
9965
+ match: "SIMPLE",
9966
+ on_update: "NO_ACTION",
9967
+ on_delete: "NO_ACTION"
9968
+ });
9969
+ return encodeASD(ConstraintInfoSchema, {
9970
+ ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
9971
+ definition: encodeASD(ConstraintDefinitionSchema, {
9972
+ kind: spec.kind,
9973
+ column_paths: spec.columns,
9974
+ declared_name: spec.declaredName ?? null,
9975
+ check_expression: check,
9976
+ foreign_key: foreign
9977
+ }),
9978
+ enforcement: spec.enforcement,
9979
+ validation: spec.validation,
9980
+ referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
9981
+ });
9982
+ }
9983
+ function selectReadProfiles(available, clientCapabilities) {
9984
+ if (clientCapabilities == null || available.length === 0)
9985
+ return [];
9986
+ const client = decodeASD(ClientCapabilitiesSchema, clientCapabilities);
9987
+ const offered = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
9988
+ const selected = available.filter((p) => offered.includes(p));
9989
+ if (!selected.includes(CONSTRAINT_RECORDS_READ))
9990
+ return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
9991
+ return selected.sort();
9992
+ }
9993
+ function readConstraintRecord(bytes) {
9994
+ const info = decodeASD(ConstraintInfoSchema, bytes);
9995
+ const ref = decodeASD(CatalogObjectRefSchema, info.ref);
9996
+ const def = decodeASD(ConstraintDefinitionSchema, info.definition);
9997
+ const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
9998
+ const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
9999
+ const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
10000
+ return {
10001
+ schemaPath: [...ref.schema_path],
10002
+ table: ref.owner_table ?? "",
10003
+ id: ref.name,
10004
+ kind: def.kind,
10005
+ columns: [...def.column_paths].map((p) => [...p]),
10006
+ enforcement: info.enforcement,
10007
+ validation: info.validation,
10008
+ declaredName: def.declared_name ?? null,
10009
+ checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
10010
+ references: fk == null || target == null ? null : {
10011
+ schemaPath: [...target.schema_path],
10012
+ table: target.name,
10013
+ columns: [...fk.referenced_column_paths].map((p) => [...p]),
10014
+ constraintId: targetKey?.name ?? null
10015
+ }
10016
+ };
10017
+ }
10018
+ function ordinaryStructChildren(field) {
10019
+ if (!isStruct(field.type))
10020
+ return null;
10021
+ for (const key of field.metadata.keys())
10022
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
10023
+ return null;
10024
+ return field.type.children;
10025
+ }
10026
+ function validateConstraintNullability(table, fields, constraints) {
10027
+ const required = new Set;
10028
+ for (const bytes of constraints) {
10029
+ const record = readConstraintRecord(bytes);
10030
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
10031
+ throw new Error(`Table '${table}': constraint '${record.id}' is ${record.enforcement}/${record.validation}; ` + "DuckDB accepts only ENFORCED + ALL_ROWS records");
10032
+ if (record.kind === "NOT_NULL" || record.kind === "PRIMARY_KEY")
10033
+ for (const path of record.columns)
10034
+ required.add(JSON.stringify(path));
10035
+ }
10036
+ const walk = (children, prefix) => {
10037
+ for (const field of children) {
10038
+ const path = [...prefix, field.name];
10039
+ const key = JSON.stringify(path);
10040
+ if (field.nullable === required.has(key)) {
10041
+ throw new Error(field.nullable ? `Table '${table}': column ${path.join(".")} is in a NOT_NULL/PRIMARY_KEY record but its Arrow field is nullable` : `Table '${table}': column ${path.join(".")} is non-nullable in Arrow but no NOT_NULL/PRIMARY_KEY record names it; ` + "declare one with constraintRecord() or make the field nullable");
10042
+ }
10043
+ const nested = ordinaryStructChildren(field);
10044
+ if (nested)
10045
+ walk(nested, path);
10046
+ }
10047
+ };
10048
+ walk(fields, []);
10049
+ }
10050
+
9927
10051
  // src/catalog/read-only.ts
9928
10052
  var READ_ONLY_ITEM_ATTACH_ID = new TextEncoder().encode("readonly-catalog-");
9929
10053
 
@@ -9993,6 +10117,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
9993
10117
  const settings = (this._descriptor.settings ?? []).map((s) => serializeSetting(s));
9994
10118
  const secretTypes = (this._descriptor.secretTypes ?? []).map((s) => serializeSecretType(s));
9995
10119
  const attachCatalogs = (this._descriptor.attachCatalogs ?? []).map((c) => encodeAttachCatalogInfo(c));
10120
+ const available = this.catalogReadProfiles();
10121
+ const read = selectReadProfiles(available, clientCapabilities);
9996
10122
  const hasTimeTravel = this._descriptor.schemas.some((s) => s.tables?.some((t) => t.supportsTimeTravel) ?? false);
9997
10123
  return buildCatalogAttachResult({
9998
10124
  attach_opaque_data: attachOpaqueData,
@@ -10012,9 +10138,15 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10012
10138
  global_function_prefix: this._descriptor.globalFunctionPrefix ?? "",
10013
10139
  resolved_data_version: null,
10014
10140
  resolved_implementation_version: null,
10015
- supports_catalog_contents: this.supportsCatalogContents
10141
+ supports_catalog_contents: this.supportsCatalogContents,
10142
+ catalog_capabilities: available.length ? encodeCatalogCapabilities({ read: [...available].sort(), ddl: [], write: [], transaction: [] }) : null,
10143
+ selected_capabilities: available.length ? encodeCatalogCapabilities({ read, ddl: [], write: [], transaction: [] }) : null
10016
10144
  });
10017
10145
  }
10146
+ catalogReadProfiles() {
10147
+ const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
10148
+ return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
10149
+ }
10018
10150
  detach(attachOpaqueData) {
10019
10151
  for (const [name, id] of this._attachments) {
10020
10152
  if (bufferEquals(id, attachOpaqueData)) {
@@ -10112,10 +10244,11 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
10112
10244
  colSchema = applyColumnComments(colSchema, t.columnComments);
10113
10245
  }
10114
10246
  validateColumnMetadata(colSchema);
10247
+ validateConstraintNullability(t.name, colSchema.fields, t.constraints ?? []);
10115
10248
  validateColumnExpressions(colSchema, path);
10116
10249
  const columns = serializeSchema(colSchema);
10117
10250
  if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
10118
- throw new Error("legacy constraint metadata requires explicit canonical records");
10251
+ throw new Error(`Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` + "declare canonical records with constraintRecord() in `constraints` instead");
10119
10252
  }
10120
10253
  const requiredFilters = t.requiredFilters ?? [];
10121
10254
  for (const group of requiredFilters) {
@@ -15753,7 +15886,16 @@ function catalogAdminHandlers(getCatalog, signingKey) {
15753
15886
  innerParams.implementation_version = restored.implementationVersion;
15754
15887
  optionsDict = restored.options;
15755
15888
  }
15756
- const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities));
15889
+ const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
15890
+ const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, clientCapabilities);
15891
+ if (result.catalog_capabilities != null) {
15892
+ const available = decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities));
15893
+ const chosen = result.selected_capabilities == null ? { read: [], ddl: [], write: [], transaction: [] } : decodeCatalogCapabilities(toUint8Array(result.selected_capabilities));
15894
+ result.selected_capabilities = encodeCatalogCapabilities({
15895
+ ...chosen,
15896
+ read: selectReadProfiles(available.read, clientCapabilities)
15897
+ });
15898
+ }
15757
15899
  const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
15758
15900
  return wrapResult(buildCatalogAttachResult({
15759
15901
  ...result,
@@ -17849,6 +17991,7 @@ export {
17849
17991
  CACHE_STALE_IF_ERROR_KEY,
17850
17992
  CACHE_STALE_WHILE_REVALIDATE_KEY,
17851
17993
  CACHE_TTL_KEY,
17994
+ CONSTRAINT_RECORDS_READ,
17852
17995
  CONTINUE,
17853
17996
  CatalogAlreadyExistsError,
17854
17997
  CatalogFunctionType,
@@ -17886,6 +18029,7 @@ export {
17886
18029
  PushdownFilters,
17887
18030
  READ_ONLY_ITEM_ATTACH_ID,
17888
18031
  RESERVED_ATTACH_OPTION,
18032
+ ROW_SCALAR_EXPRESSION,
17889
18033
  ReadOnlyCatalogInterface,
17890
18034
  ReservedAttachOptionError,
17891
18035
  RowCountMismatchError,
@@ -17944,6 +18088,7 @@ export {
17944
18088
  cacheControlMetadata,
17945
18089
  codecFor,
17946
18090
  columnFromArray,
18091
+ constraintRecord,
17947
18092
  constraintSpecFields,
17948
18093
  createLandingRoutes,
17949
18094
  date2 as date,
@@ -18049,6 +18194,7 @@ export {
18049
18194
  projectBatch,
18050
18195
  projectSchema,
18051
18196
  readCanonicalValue,
18197
+ readConstraintRecord,
18052
18198
  redeemAttachTicket,
18053
18199
  reprPushedFilters,
18054
18200
  resolveMetadata,
@@ -18063,6 +18209,7 @@ export {
18063
18209
  secretForScopeOfType,
18064
18210
  secretType,
18065
18211
  secretsOfType,
18212
+ selectReadProfiles,
18066
18213
  serializeAttachOptionSpec,
18067
18214
  serializeAttachOptionSpecs,
18068
18215
  serializeBatch,
@@ -18093,7 +18240,8 @@ export {
18093
18240
  uint642 as uint64,
18094
18241
  uint82 as uint8,
18095
18242
  union2 as union,
18096
- utf82 as utf8
18243
+ utf82 as utf8,
18244
+ validateConstraintNullability
18097
18245
  };
18098
18246
 
18099
- //# debugId=BD66CA0A252A167364756E2164756E21
18247
+ //# debugId=0952F70BC6F2E0DE64756E2164756E21