@query-farm/vgi 0.47.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +1 -1
  2. package/dist/catalog/column-expressions.d.ts +22 -1
  3. package/dist/catalog/column-metadata.d.ts +7 -0
  4. package/dist/catalog/column-types.d.ts +15 -0
  5. package/dist/catalog/composite.d.ts +2 -0
  6. package/dist/catalog/constraints.d.ts +110 -12
  7. package/dist/catalog/descriptors.d.ts +19 -1
  8. package/dist/catalog/indexes.d.ts +29 -0
  9. package/dist/catalog/interface.d.ts +41 -0
  10. package/dist/catalog/public-codecs.d.ts +6 -0
  11. package/dist/catalog/read-only.d.ts +3 -0
  12. package/dist/catalog/sql-grammar.d.ts +53 -0
  13. package/dist/catalog/unconstrained-columns.d.ts +8 -0
  14. package/dist/client/types.d.ts +5 -1
  15. package/dist/client-entry.d.ts +1 -0
  16. package/dist/client-entry.js +1435 -152
  17. package/dist/client-entry.js.map +15 -11
  18. package/dist/generated/vgi-client.d.ts +5 -0
  19. package/dist/generated/vgi-protocol-schemas.d.ts +5 -0
  20. package/dist/generated/vgi-protocol-types.d.ts +57 -0
  21. package/dist/generated/vgi-service.d.ts +1 -1
  22. package/dist/index.core.d.ts +3 -1
  23. package/dist/index.js +1940 -545
  24. package/dist/index.js.map +26 -22
  25. package/dist/protocol/dispatch.d.ts +1 -1
  26. package/dist/protocol/serializers/splits.d.ts +41 -1
  27. package/dist/serve-entry.js +1172 -58
  28. package/dist/serve-entry.js.map +20 -17
  29. package/dist/worker-cf-entry.d.ts +2 -1
  30. package/dist/worker-cf-entry.js +1538 -191
  31. package/dist/worker-cf-entry.js.map +26 -22
  32. package/package.json +1 -1
  33. package/src/catalog/column-expressions.ts +85 -7
  34. package/src/catalog/column-metadata.ts +20 -2
  35. package/src/catalog/column-types.ts +50 -0
  36. package/src/catalog/composite.ts +10 -0
  37. package/src/catalog/constraints.ts +496 -58
  38. package/src/catalog/contents-codec.ts +3 -3
  39. package/src/catalog/descriptors.ts +19 -1
  40. package/src/catalog/indexes.ts +59 -0
  41. package/src/catalog/interface.ts +103 -1
  42. package/src/catalog/public-codecs.ts +36 -0
  43. package/src/catalog/read-only.ts +92 -36
  44. package/src/catalog/sql-grammar.ts +476 -0
  45. package/src/catalog/unconstrained-columns.ts +34 -8
  46. package/src/client/client.ts +6 -3
  47. package/src/client/types.ts +5 -1
  48. package/src/client-entry.ts +4 -0
  49. package/src/generated/vgi-client.ts +6 -1
  50. package/src/generated/vgi-protocol-schemas.ts +36 -1
  51. package/src/generated/vgi-protocol-types.ts +130 -1
  52. package/src/generated/vgi-service.ts +2 -2
  53. package/src/index.core.ts +34 -1
  54. package/src/protocol/dispatch.ts +1 -1
  55. package/src/protocol/handlers/catalog/admin.ts +14 -13
  56. package/src/protocol/handlers/catalog/table.ts +58 -11
  57. package/src/protocol/serializers/splits.ts +82 -9
  58. package/src/worker-cf-entry.ts +2 -4
@@ -1,8 +1,13 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
- // Canonical constraint records for catalogs that state their own facts.
2
+ // Canonical constraint records for catalogs that state their own facts, the
3
+ // checks the DuckDB extension applies to them at ATTACH, and the catalog
4
+ // capability negotiation that makes them readable.
3
5
 
4
6
  import { encodeASD, decodeASD } from "../codec/asd.js";
5
- import { isStruct, type VgiDataType, type VgiField } from "../arrow/index.js";
7
+ import {
8
+ deserializeSchema, field as field_, schema as schema_, serializeSchema, struct as struct_,
9
+ type VgiDataType, type VgiField, type VgiSchema,
10
+ } from "../arrow/index.js";
6
11
  import {
7
12
  CatalogObjectRefSchema,
8
13
  ClientCapabilitiesSchema,
@@ -11,12 +16,26 @@ import {
11
16
  ForeignKeyDefinitionSchema,
12
17
  SqlExpressionSchema,
13
18
  } from "../generated/vgi-protocol-schemas.js";
14
- import { decodeCatalogCapabilities, type CatalogCapabilities } from "../generated/vgi-protocol-types.js";
19
+ import {
20
+ decodeCatalogCapabilities, encodeCatalogCapabilities, type CatalogCapabilities,
21
+ } from "../generated/vgi-protocol-types.js";
22
+ import type { ClientCapabilities, TableInfo } from "../generated/vgi-client.js";
23
+ import { validateNumericCheckSql } from "./sql-grammar.js";
24
+ import { duckdbPrimitive, isGeneratedField, isRowIdField, ordinaryStructChildren } from "./column-types.js";
25
+ import { GENERATED_EXPRESSION_KEY, GENERATION_KEY, generatedExpressionMetadata } from "./column-expressions.js";
15
26
 
16
27
  /** Read profile: the catalog serves canonical ConstraintInfo records. */
17
28
  export const CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
18
29
  /** Read profile: CHECK constraints carry DuckDB scalar SQL expressions. */
19
30
  export const ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
31
+ /** DDL profile: CREATE TABLE may carry canonical constraint definitions. */
32
+ export const CONSTRAINT_CREATE = "vgi.constraint.create.v1";
33
+ /** DDL profile: `catalog_table_constraints_apply` (e.g. ALTER ... SET/DROP NOT NULL). */
34
+ export const CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
35
+ /** Write profile: the provider enforces its ENFORCED records on every write. */
36
+ export const CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
37
+ /** Transaction profile: constraint DDL may run inside a catalog transaction. */
38
+ export const TRANSACTION_DDL = "vgi.transaction.ddl.v1";
20
39
 
21
40
  export type ConstraintKind = "NOT_NULL" | "PRIMARY_KEY" | "UNIQUE" | "CHECK" | "FOREIGN_KEY";
22
41
  /** Whether the authority enforces the constraint on every write path. */
@@ -25,27 +44,34 @@ export type ConstraintEnforcement = "ENFORCED" | "METADATA_ONLY";
25
44
  export type ConstraintValidation = "ALL_ROWS" | "FUTURE_WRITES" | "UNVALIDATED";
26
45
 
27
46
  export interface ConstraintRecordSpec {
28
- /** Schema path of the owning table. */
47
+ /** Schema path of the owning table (one component: DuckDB reads no other). */
29
48
  schemaPath: readonly string[];
30
49
  /** Owning table name. */
31
50
  table: string;
32
51
  /** Stable provider-owned identity, unique within the table. Never derived by the SDK. */
33
52
  id: string;
34
53
  kind: ConstraintKind;
35
- /** Raw component paths, e.g. `[["id"]]` or `[["bbox", "xmin"]]`; empty for CHECK. */
54
+ /**
55
+ * Raw component paths, e.g. `[["id"]]`; empty for CHECK. Only NOT_NULL may
56
+ * name a nested STRUCT field (`[["bbox", "xmin"]]`).
57
+ */
36
58
  columns: readonly (readonly string[])[];
37
59
  /**
38
60
  * The provider's attestation. The DuckDB extension reads only
39
61
  * ENFORCED + ALL_ROWS records, so state that only when every row the table
40
- * can ever return satisfies the constraint.
62
+ * can ever return satisfies the constraint; the builder refuses anything else.
41
63
  */
42
64
  enforcement: ConstraintEnforcement;
43
65
  validation: ConstraintValidation;
44
- /** Optional SQL label (CONSTRAINT <name>). */
66
+ /** Optional SQL label (CONSTRAINT <name>); unique per table, case-insensitively. */
45
67
  declaredName?: string;
46
- /** CHECK only: a DuckDB scalar expression over the table's columns. */
68
+ /**
69
+ * CHECK only: one numeric comparison, e.g. `price >= 0` or `lo < hi`. Each
70
+ * operand is a numeric literal or a signed-integer/float column; DuckDB reads
71
+ * nothing else.
72
+ */
47
73
  checkSql?: string;
48
- /** FOREIGN_KEY only: the referenced key and its constraint identity. */
74
+ /** FOREIGN_KEY only: the referenced key (same schema) and its constraint identity. */
49
75
  references?: {
50
76
  schemaPath: readonly string[];
51
77
  table: string;
@@ -55,13 +81,45 @@ export interface ConstraintRecordSpec {
55
81
  };
56
82
  }
57
83
 
84
+ /** The evaluation context DuckDB accepts for a CHECK expression. */
85
+ const CHECK_CONTEXT = {
86
+ timezone: "UTC", collation: "binary", default_order: "asc",
87
+ default_null_order: "nulls_last", preserve_insertion_order: true,
88
+ } as const;
89
+
90
+ function identifier(value: unknown, what: string): asserts value is string {
91
+ if (typeof value !== "string" || !value || value.includes("\0") || new TextEncoder().encode(value).length > 4096)
92
+ throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
93
+ }
94
+
58
95
  function objectRef(kind: "table" | "constraint", schemaPath: readonly string[], name: string, ownerTable: string | null): Uint8Array {
59
96
  return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
60
97
  }
61
98
 
99
+ function checkPaths(paths: readonly (readonly string[])[], what: string, topLevelOnly: boolean): void {
100
+ if (paths.length > 1024) throw new Error(`${what}: too many column paths`);
101
+ const seen = new Set<string>();
102
+ for (const path of paths) {
103
+ if (path.length === 0 || path.length > 64) throw new Error(`${what}: column path must have 1..64 components`);
104
+ if (topLevelOnly && path.length !== 1)
105
+ throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
106
+ path.forEach((part) => identifier(part, `${what}: column path component`));
107
+ const key = JSON.stringify(path);
108
+ if (seen.has(key)) throw new Error(`${what}: duplicate column path ${path.join(".")}`);
109
+ seen.add(key);
110
+ }
111
+ }
112
+
62
113
  /** Encode one canonical `ConstraintInfo` record for `TableDescriptor.constraints`. */
63
114
  export function constraintRecord(spec: ConstraintRecordSpec): Uint8Array {
115
+ const what = `constraint '${spec.id}' on '${spec.table}'`;
64
116
  if (!spec.id || spec.id.includes("\0")) throw new Error("constraint id must be nonempty without NUL");
117
+ identifier(spec.table, "table");
118
+ if (spec.schemaPath.length !== 1) throw new Error(`${what}: DuckDB reads only one-component schema paths`);
119
+ identifier(spec.schemaPath[0], "schema");
120
+ if (spec.enforcement !== "ENFORCED" || spec.validation !== "ALL_ROWS")
121
+ throw new Error(`${what} is ${spec.enforcement}/${spec.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
122
+ if (spec.declaredName !== undefined) identifier(spec.declaredName, `${what}: declaredName`);
65
123
  if ((spec.kind === "CHECK") !== (spec.checkSql !== undefined))
66
124
  throw new Error("checkSql is required for CHECK and only CHECK");
67
125
  if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
@@ -69,18 +127,30 @@ export function constraintRecord(spec: ConstraintRecordSpec): Uint8Array {
69
127
  if (spec.kind === "NOT_NULL" && spec.columns.length !== 1) throw new Error("NOT_NULL requires exactly one column path");
70
128
  if ((spec.kind === "FOREIGN_KEY") !== (spec.references !== undefined))
71
129
  throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
72
- if (spec.references && spec.references.columns.length !== spec.columns.length)
73
- throw new Error("foreign key local and referenced arity must match");
130
+ checkPaths(spec.columns, what, spec.kind !== "NOT_NULL");
131
+ if (spec.checkSql !== undefined) {
132
+ // Column types are checked when the table is served; the shape is checkable now.
133
+ try {
134
+ validateNumericCheckSql(spec.checkSql, () => {});
135
+ } catch (error) {
136
+ throw new Error(`${what}: ${(error as Error).message} (CHECK SQL: ${spec.checkSql})`);
137
+ }
138
+ }
139
+ const ref = spec.references;
140
+ if (ref) {
141
+ if (ref.columns.length !== spec.columns.length) throw new Error("foreign key local and referenced arity must match");
142
+ if (JSON.stringify(ref.schemaPath) !== JSON.stringify(spec.schemaPath))
143
+ throw new Error(`${what}: DuckDB reads only foreign keys to a table in the same schema`);
144
+ identifier(ref.table, `${what}: referenced table`);
145
+ identifier(ref.constraintId, `${what}: referenced constraintId`);
146
+ checkPaths(ref.columns, `${what} (referenced)`, true);
147
+ }
74
148
  const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
75
149
  sql: spec.checkSql,
76
150
  profile: ROW_SCALAR_EXPRESSION,
77
151
  schema_path: spec.schemaPath,
78
- evaluation_context: {
79
- timezone: "UTC", collation: "binary", default_order: "asc",
80
- default_null_order: "nulls_last", preserve_insertion_order: true,
81
- },
152
+ evaluation_context: CHECK_CONTEXT,
82
153
  });
83
- const ref = spec.references;
84
154
  const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
85
155
  referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
86
156
  referenced_column_paths: ref.columns,
@@ -101,19 +171,124 @@ export function constraintRecord(spec: ConstraintRecordSpec): Uint8Array {
101
171
  });
102
172
  }
103
173
 
174
+ // ---------------------------------------------------------------------------
175
+ // Capability negotiation
176
+ // ---------------------------------------------------------------------------
177
+
178
+ /** Profiles DuckDB's vgi extension offers, by category (BuildNativeConstraintCapabilities). */
179
+ const KNOWN: Record<keyof CatalogCapabilities, ReadonlySet<string>> = {
180
+ read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
181
+ ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
182
+ write: new Set([CONSTRAINT_ENFORCE]),
183
+ transaction: new Set([TRANSACTION_DDL]),
184
+ };
185
+ /** A profile is selected only together with its prerequisites. */
186
+ const REQUIRES: Record<string, readonly string[]> = {
187
+ [ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
188
+ [CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
189
+ [CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
190
+ [CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
191
+ "vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
192
+ "vgi.index.drop.v1": ["vgi.index.definition.read.v1"],
193
+ };
194
+
195
+ const CATEGORIES = ["read", "ddl", "write", "transaction"] as const;
196
+
104
197
  /**
105
- * The client-offered profiles from `available`, in canonical (sorted) order.
198
+ * Build a catalog's profile advertisement (`CatalogAttachResult.catalog_capabilities`).
199
+ * Returned by `CatalogInterface.catalogCapabilities()`; the attach handler
200
+ * selects from it against the client's offer.
201
+ */
202
+ export function catalogCapabilities(init: Partial<CatalogCapabilities> = {}): CatalogCapabilities {
203
+ return {
204
+ read: [...new Set(init.read ?? [])].sort(),
205
+ ddl: [...new Set(init.ddl ?? [])].sort(),
206
+ write: [...new Set(init.write ?? [])].sort(),
207
+ transaction: [...new Set(init.transaction ?? [])].sort(),
208
+ };
209
+ }
210
+
211
+ /** What a catalog that serves (and enforces/mutates) canonical constraint records advertises. */
212
+ export function constraintCapabilities(options: { create?: boolean; mutate?: boolean; enforce?: boolean; transactionDdl?: boolean } = {}): CatalogCapabilities {
213
+ const enforce = options.enforce || options.create;
214
+ return catalogCapabilities({
215
+ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION],
216
+ ddl: [...(options.create ? [CONSTRAINT_CREATE] : []), ...(options.mutate ? [CONSTRAINT_MUTATE] : [])],
217
+ write: enforce ? [CONSTRAINT_ENFORCE] : [],
218
+ transaction: options.transactionDdl ? [TRANSACTION_DDL] : [],
219
+ });
220
+ }
221
+
222
+ function offeredCatalog(clientCapabilities: Uint8Array | ClientCapabilities | null | undefined): CatalogCapabilities | null {
223
+ if (clientCapabilities == null) return null;
224
+ const client = clientCapabilities instanceof Uint8Array
225
+ ? decodeASD<{ catalog?: Uint8Array | null }>(ClientCapabilitiesSchema, clientCapabilities)
226
+ : clientCapabilities;
227
+ return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
228
+ }
229
+
230
+ /**
231
+ * Select the client-offered subset of `available`, canonically sorted, keeping
232
+ * a profile only when its prerequisites were selected too (CONSTRAINT_CREATE
233
+ * needs records read + enforcement; the scalar expression read needs records
234
+ * read). The DDL transaction profile requires `supportsTransactions`.
235
+ */
236
+ export function selectCatalogCapabilities(
237
+ available: CatalogCapabilities,
238
+ clientCapabilities: Uint8Array | ClientCapabilities | null | undefined,
239
+ supportsTransactions = false,
240
+ ): CatalogCapabilities {
241
+ const offered = offeredCatalog(clientCapabilities);
242
+ if (offered == null) return catalogCapabilities();
243
+ const chosen = new Set<string>();
244
+ for (const category of CATEGORIES)
245
+ for (const p of available[category] ?? []) if (offered[category]?.includes(p)) chosen.add(p);
246
+ if (!supportsTransactions) chosen.delete(TRANSACTION_DDL);
247
+ // Drop profiles whose prerequisites are missing until nothing changes.
248
+ for (let changed = true; changed;) {
249
+ changed = false;
250
+ for (const p of [...chosen])
251
+ if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) { chosen.delete(p); changed = true; }
252
+ }
253
+ const pick = (category: keyof CatalogCapabilities) => (available[category] ?? []).filter((p) => chosen.has(p));
254
+ return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
255
+ }
256
+
257
+ /**
258
+ * The client-offered read profiles from `available`, in canonical (sorted) order.
106
259
  * A scalar-expression read is selected only alongside constraint records.
107
260
  */
108
261
  export function selectReadProfiles(available: readonly string[], clientCapabilities: Uint8Array | null | undefined): string[] {
109
- if (clientCapabilities == null || available.length === 0) return [];
110
- const client = decodeASD<{ catalog?: Uint8Array | null }>(ClientCapabilitiesSchema, clientCapabilities);
111
- const offered: CatalogCapabilities["read"] = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
112
- const selected = available.filter((p) => offered.includes(p));
113
- if (!selected.includes(CONSTRAINT_RECORDS_READ)) return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
114
- return selected.sort();
262
+ return selectCatalogCapabilities(catalogCapabilities({ read: [...available] }), clientCapabilities).read;
263
+ }
264
+
265
+ /**
266
+ * The ClientCapabilities a client sends when the caller supplies none: it can
267
+ * read canonical constraint records (decode them with `readConstraintRecord`)
268
+ * and their CHECK expressions. It offers no DDL or enforcement; pass an
269
+ * explicit offer to negotiate those.
270
+ */
271
+ export function defaultClientCapabilities(engine = "vgi-typescript"): ClientCapabilities {
272
+ return {
273
+ engine,
274
+ native_formats: [],
275
+ catalogs: [],
276
+ can_stream: true,
277
+ filter_encodings: [],
278
+ catalog: encodeCatalogCapabilities(catalogCapabilities({ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] })),
279
+ query_pushdown: null,
280
+ };
115
281
  }
116
282
 
283
+ /** True when every category of `caps` is empty. */
284
+ export function capabilitiesEmpty(caps: CatalogCapabilities | null | undefined): boolean {
285
+ return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
286
+ }
287
+
288
+ // ---------------------------------------------------------------------------
289
+ // Decoding
290
+ // ---------------------------------------------------------------------------
291
+
117
292
  /** A decoded `ConstraintInfo` record, in `constraintRecord()`'s vocabulary. */
118
293
  export interface ConstraintRecordView {
119
294
  schemaPath: string[];
@@ -125,7 +300,18 @@ export interface ConstraintRecordView {
125
300
  validation: ConstraintValidation;
126
301
  declaredName: string | null;
127
302
  checkSql: string | null;
128
- references: { schemaPath: string[]; table: string; columns: string[][]; constraintId: string | null } | null;
303
+ references: {
304
+ schemaPath: string[];
305
+ table: string;
306
+ columns: string[][];
307
+ constraintId: string | null;
308
+ /** The referenced constraint's owner table (should equal `table`). */
309
+ constraintTable?: string | null;
310
+ constraintSchemaPath?: string[] | null;
311
+ match?: string;
312
+ onUpdate?: string;
313
+ onDelete?: string;
314
+ } | null;
129
315
  }
130
316
 
131
317
  type RefRow = { kind: string; schema_path: string[]; name: string; owner_table: string | null };
@@ -153,55 +339,307 @@ export function readConstraintRecord(bytes: Uint8Array): ConstraintRecordView {
153
339
  table: target.name,
154
340
  columns: [...fk.referenced_column_paths].map((p: Iterable<string>) => [...p]),
155
341
  constraintId: targetKey?.name ?? null,
342
+ constraintTable: targetKey?.owner_table ?? null,
343
+ constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
344
+ match: fk.match,
345
+ onUpdate: fk.on_update,
346
+ onDelete: fk.on_delete,
156
347
  },
157
348
  };
158
349
  }
159
350
 
160
- function ordinaryStructChildren(field: VgiField): readonly VgiField[] | null {
161
- if (!isStruct(field.type)) return null;
162
- for (const key of field.metadata.keys())
163
- if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) return null;
164
- return (field.type as VgiDataType & { children: readonly VgiField[] }).children;
351
+ // ---------------------------------------------------------------------------
352
+ // Serving: the checks DuckDB applies at ATTACH (DecodeNativeConstraints)
353
+ // ---------------------------------------------------------------------------
354
+
355
+ export interface ValidatedConstraints {
356
+ records: ConstraintRecordView[];
357
+ /** JSON-encoded column paths a NOT_NULL or PRIMARY_KEY record makes non-nullable. */
358
+ required: Set<string>;
359
+ }
360
+
361
+ function fieldsByExactName(fields: readonly VgiField[], name: string): number[] {
362
+ const out: number[] = [];
363
+ fields.forEach((f, i) => { if (f.name === name) out.push(i); });
364
+ return out;
165
365
  }
166
366
 
167
367
  /**
168
- * Check a table's records the way the DuckDB extension does at ATTACH: every
169
- * record is ENFORCED + ALL_ROWS, and Arrow nullability agrees with the
170
- * NOT_NULL/PRIMARY_KEY records (a field, descending through ordinary STRUCTs,
171
- * is non-nullable exactly when a record names its path).
368
+ * Check a table's canonical records exactly as the DuckDB extension does at
369
+ * ATTACH, so a worker's own tests fail with the table, constraint id and path
370
+ * instead of an opaque ATTACH error: identity (owner table and one-component
371
+ * schema), unique ids and declared names, ENFORCED + ALL_ROWS only, at most one
372
+ * PRIMARY KEY, resolvable column paths (nested only for NOT_NULL, never the
373
+ * row-id column), the native CHECK grammar and its operand types, and foreign
374
+ * keys DuckDB can represent (same schema, MATCH SIMPLE, NO ACTION/RESTRICT).
375
+ * Foreign-key targets are checked across tables by `validateForeignKeyTargets`.
172
376
  */
173
- export function validateConstraintNullability(
377
+ export function validateTableConstraints(
174
378
  table: string,
379
+ schemaPath: readonly string[],
175
380
  fields: readonly VgiField[],
176
381
  constraints: readonly Uint8Array[],
177
- ): void {
382
+ ): ValidatedConstraints {
383
+ if (constraints.length > 1024) throw new Error(`Table '${table}': too many constraints (at most 1024)`);
384
+ const rowIds = fields.map((f, i) => (isRowIdField(f) ? i : -1)).filter((i) => i >= 0);
385
+ if (rowIds.length > 1) throw new Error(`Table '${table}': at most one column may carry is_row_id`);
386
+ const rowId = rowIds[0] ?? -1;
387
+ const records: ConstraintRecordView[] = [];
178
388
  const required = new Set<string>();
389
+ const ids = new Set<string>();
390
+ const labels = new Set<string>();
391
+ let primaryKeys = 0;
179
392
  for (const bytes of constraints) {
180
- const record = readConstraintRecord(bytes);
181
- // DuckDB reads only facts that hold for every row; anything else fails ATTACH.
393
+ let record: ConstraintRecordView;
394
+ try {
395
+ record = readConstraintRecord(bytes);
396
+ } catch (error) {
397
+ throw new Error(`Table '${table}': undecodable constraint record: ${(error as Error).message}`);
398
+ }
399
+ const where = `Table '${table}': constraint '${record.id}'`;
400
+ const fail = (message: string): never => { throw new Error(`${where}: ${message}`); };
401
+ if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
402
+ fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` +
403
+ `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
404
+ if (ids.has(record.id)) fail("duplicate constraint id");
405
+ ids.add(record.id);
406
+ if (record.declaredName != null) {
407
+ const label = record.declaredName.toLowerCase();
408
+ if (labels.has(label)) fail(`duplicate declared name '${record.declaredName}'`);
409
+ labels.add(label);
410
+ }
182
411
  if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
183
- throw new Error(
184
- `Table '${table}': constraint '${record.id}' is ${record.enforcement}/${record.validation}; ` +
185
- "DuckDB accepts only ENFORCED + ALL_ROWS records"
186
- );
187
- if (record.kind === "NOT_NULL" || record.kind === "PRIMARY_KEY")
188
- for (const path of record.columns) required.add(JSON.stringify(path));
189
- }
190
- const walk = (children: readonly VgiField[], prefix: string[]) => {
191
- for (const field of children) {
192
- const path = [...prefix, field.name];
193
- const key = JSON.stringify(path);
194
- if (field.nullable === required.has(key)) {
195
- throw new Error(
196
- field.nullable
197
- ? `Table '${table}': column ${path.join(".")} is in a NOT_NULL/PRIMARY_KEY record but its Arrow field is nullable`
198
- : `Table '${table}': column ${path.join(".")} is non-nullable in Arrow but no NOT_NULL/PRIMARY_KEY record names it; ` +
199
- "declare one with constraintRecord() or make the field nullable"
200
- );
412
+ fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
413
+ try {
414
+ checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
415
+ } catch (error) {
416
+ fail((error as Error).message);
417
+ }
418
+ const resolveTop = (path: string[]): number => {
419
+ const matches = fieldsByExactName(fields, path[0]);
420
+ if (matches.length !== 1 || matches[0] === rowId)
421
+ fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
422
+ return matches[0];
423
+ };
424
+ switch (record.kind) {
425
+ case "CHECK": {
426
+ if (record.checkSql == null) fail("CHECK without an expression");
427
+ validateCheckRecord(bytes, where, schemaPath, fields, rowId);
428
+ break;
429
+ }
430
+ case "NOT_NULL": {
431
+ if (record.columns.length !== 1) fail("NOT_NULL requires exactly one column path");
432
+ const path = record.columns[0];
433
+ let field = fields[resolveTop(path)];
434
+ for (let depth = 1; depth < path.length; depth++) {
435
+ const children = ordinaryStructChildren(field);
436
+ if (!children) fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
437
+ const matches = fieldsByExactName(children!, path[depth]);
438
+ if (matches.length !== 1) fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
439
+ field = children![matches[0]];
440
+ }
441
+ if (path.length === 1 && isGeneratedField(field))
442
+ fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
443
+ required.add(JSON.stringify(path));
444
+ break;
201
445
  }
202
- const nested = ordinaryStructChildren(field);
203
- if (nested) walk(nested, path);
446
+ case "PRIMARY_KEY":
447
+ case "UNIQUE": {
448
+ for (const path of record.columns) {
449
+ const index = resolveTop(path);
450
+ if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
451
+ fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
452
+ }
453
+ if (record.kind === "PRIMARY_KEY") {
454
+ if (++primaryKeys > 1) fail("a table may have only one PRIMARY KEY");
455
+ for (const path of record.columns) required.add(JSON.stringify(path));
456
+ }
457
+ break;
458
+ }
459
+ case "FOREIGN_KEY": {
460
+ record.columns.forEach(resolveTop);
461
+ const ref = record.references;
462
+ if (ref == null || ref.constraintId == null) fail("FOREIGN_KEY requires a referenced table and referenced constraint");
463
+ if (ref!.schemaPath.length !== 1 || ref!.schemaPath[0] !== schemaPath[0] ||
464
+ JSON.stringify(ref!.constraintSchemaPath) !== JSON.stringify(ref!.schemaPath) || ref!.constraintTable !== ref!.table)
465
+ fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
466
+ if (ref!.columns.length !== record.columns.length) fail("foreign key arity mismatch");
467
+ try {
468
+ checkPaths(ref!.columns, "FOREIGN_KEY referenced", true);
469
+ } catch (error) {
470
+ fail((error as Error).message);
471
+ }
472
+ if (ref!.match !== undefined && ref!.match !== "SIMPLE") fail(`MATCH ${ref!.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
473
+ for (const action of [ref!.onUpdate, ref!.onDelete])
474
+ if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
475
+ fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
476
+ break;
477
+ }
478
+ default:
479
+ fail(`unknown constraint kind ${String(record.kind)}`);
204
480
  }
481
+ records.push(record);
482
+ }
483
+ return { records, required };
484
+ }
485
+
486
+ function validateCheckRecord(
487
+ bytes: Uint8Array,
488
+ where: string,
489
+ schemaPath: readonly string[],
490
+ fields: readonly VgiField[],
491
+ rowId: number,
492
+ ): void {
493
+ const info = decodeASD<any>(ConstraintInfoSchema, bytes);
494
+ const def = decodeASD<any>(ConstraintDefinitionSchema, info.definition);
495
+ const expression = decodeASD<any>(SqlExpressionSchema, def.check_expression);
496
+ const fail = (message: string): never => { throw new Error(`${where}: ${message}`); };
497
+ if (expression.profile !== ROW_SCALAR_EXPRESSION) fail(`unsupported CHECK expression profile ${expression.profile}`);
498
+ if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath])) fail("CHECK expression belongs to another schema");
499
+ const context = expression.evaluation_context ?? {};
500
+ for (const [key, value] of Object.entries(CHECK_CONTEXT))
501
+ if (context[key] !== value) fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
502
+ try {
503
+ validateNumericCheckSql(expression.sql, (name) => {
504
+ const lower = name.toLowerCase();
505
+ const matches = fields.map((f, i) => (f.name.toLowerCase() === lower ? i : -1)).filter((i) => i >= 0);
506
+ if (matches.length > 1) throw new Error(`ambiguous CHECK column reference ${name}`);
507
+ if (matches.length === 0 || matches[0] === rowId) throw new Error(`CHECK references a missing or row-id column ${name}`);
508
+ const column = fields[matches[0]];
509
+ if (column.metadata.has("ARROW:extension:name")) throw new Error(`CHECK operand ${name} has an extension type`);
510
+ if (isGeneratedField(column)) throw new Error(`CHECK operand ${name} is a generated column`);
511
+ const type = duckdbPrimitive(column);
512
+ if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
513
+ throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
514
+ });
515
+ } catch (error) {
516
+ fail(`${(error as Error).message} (CHECK SQL: ${expression.sql})`);
517
+ }
518
+ }
519
+
520
+ /** A table's identity and records, for `validateForeignKeyTargets`. */
521
+ export interface ConstraintTableRef {
522
+ schemaPath: readonly string[];
523
+ name: string;
524
+ constraints: readonly Uint8Array[];
525
+ }
526
+
527
+ /**
528
+ * Check every FOREIGN_KEY among `tables` against its target: the referenced
529
+ * table is among `tables`, and the referenced constraint id is that table's
530
+ * PRIMARY_KEY or UNIQUE record over the referenced columns.
531
+ */
532
+ export function validateForeignKeyTargets(tables: readonly ConstraintTableRef[]): void {
533
+ const key = (schemaPath: readonly string[], name: string) => JSON.stringify([...schemaPath, name]);
534
+ const byTable = new Map<string, ConstraintRecordView[]>();
535
+ for (const t of tables) byTable.set(key(t.schemaPath, t.name), t.constraints.map(readConstraintRecord));
536
+ for (const t of tables) {
537
+ for (const record of byTable.get(key(t.schemaPath, t.name)) ?? []) {
538
+ if (record.kind !== "FOREIGN_KEY" || record.references == null) continue;
539
+ const ref = record.references;
540
+ const where = `Table '${t.name}': constraint '${record.id}'`;
541
+ const target = byTable.get(key(ref.schemaPath, ref.table));
542
+ if (!target) throw new Error(`${where}: references table ${[...ref.schemaPath, ref.table].join(".")}, which this catalog does not serve`);
543
+ const key_ = target.find((r) => r.id === ref.constraintId);
544
+ if (!key_ || (key_.kind !== "PRIMARY_KEY" && key_.kind !== "UNIQUE"))
545
+ throw new Error(`${where}: referenced constraint '${ref.constraintId}' is not a PRIMARY_KEY or UNIQUE record of '${ref.table}'`);
546
+ const want = new Set(ref.columns.map((p) => JSON.stringify(p)));
547
+ if (key_.columns.length !== want.size || !key_.columns.every((p) => want.has(JSON.stringify(p))))
548
+ throw new Error(`${where}: referenced columns do not match constraint '${ref.constraintId}' of '${ref.table}'`);
549
+ }
550
+ }
551
+ }
552
+
553
+ /**
554
+ * The served Arrow fields for a table's records: nullability is exactly the
555
+ * records' (a field, descending through ordinary STRUCTs, is non-nullable iff
556
+ * a NOT_NULL or PRIMARY_KEY record names its path; the top-level row-id column
557
+ * is untouched). Returns `fields` itself when nothing changes.
558
+ */
559
+ export function servedConstraintFields(fields: readonly VgiField[], required: ReadonlySet<string>): readonly VgiField[] {
560
+ const rewrite = (list: readonly VgiField[], prefix: string[]): readonly VgiField[] => {
561
+ let changed = false;
562
+ const out = list.map((f) => {
563
+ if (prefix.length === 0 && isRowIdField(f)) return f;
564
+ const path = [...prefix, f.name];
565
+ const nullable = !required.has(JSON.stringify(path));
566
+ const children = ordinaryStructChildren(f);
567
+ const newChildren = children ? rewrite(children, path) : null;
568
+ if (nullable === f.nullable && (newChildren == null || newChildren === children)) return f;
569
+ changed = true;
570
+ const type: VgiDataType = newChildren && newChildren !== children ? struct_(newChildren) : f.type;
571
+ return field_(f.name, type, nullable, new Map(f.metadata));
572
+ });
573
+ return changed ? out : list;
205
574
  };
206
- walk(fields, []);
575
+ return rewrite(fields, []);
207
576
  }
577
+
578
+ /**
579
+ * @deprecated Since 0.48: tables are served with nullability derived from their
580
+ * records automatically, so a non-nullable field no record names is no longer
581
+ * an error. Use `validateTableConstraints` for the remaining ATTACH checks.
582
+ */
583
+ export function validateConstraintNullability(
584
+ table: string,
585
+ fields: readonly VgiField[],
586
+ constraints: readonly Uint8Array[],
587
+ ): void {
588
+ const schemaPath = constraints.length ? readConstraintRecord(constraints[0]).schemaPath : ["main"];
589
+ validateTableConstraints(table, schemaPath, fields, constraints);
590
+ }
591
+
592
+ /**
593
+ * Translate the pre-v3 `generated_expression` field metadata (raw SQL) to the
594
+ * canonical `vgi.column.generated.v1` + `vgi.column.generation.v1 = virtual`
595
+ * pair, when that is unambiguous: the field carries no canonical key.
596
+ */
597
+ function translateLegacyGenerated(fields: readonly VgiField[], owner: readonly string[], table: string): readonly VgiField[] {
598
+ let changed = false;
599
+ const out = fields.map((f) => {
600
+ const sql = f.metadata.get("generated_expression");
601
+ if (sql === undefined) return f;
602
+ if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
603
+ throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
604
+ const metadata = new Map(f.metadata);
605
+ metadata.delete("generated_expression");
606
+ metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
607
+ metadata.set(GENERATION_KEY, "virtual");
608
+ changed = true;
609
+ return field_(f.name, f.type, f.nullable, metadata);
610
+ });
611
+ return changed ? out : fields;
612
+ }
613
+
614
+ /**
615
+ * The served form of a table's Arrow schema: legacy generated metadata
616
+ * translated, records validated as DuckDB validates them at ATTACH, and
617
+ * nullability made exactly the records' (see `servedConstraintFields`).
618
+ * Returns the input schema itself when nothing changes.
619
+ */
620
+ export function servedTableSchema(
621
+ table: string,
622
+ schemaPath: readonly string[],
623
+ schema: VgiSchema,
624
+ constraints: readonly Uint8Array[],
625
+ ): VgiSchema {
626
+ let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
627
+ const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
628
+ fields = servedConstraintFields(fields, required);
629
+ return fields === schema.fields ? schema : schema_(fields, schema.metadata);
630
+ }
631
+
632
+ /**
633
+ * Apply `servedTableSchema` to a TableInfo about to be sent. The original
634
+ * column bytes are kept when nothing changes.
635
+ */
636
+ export function servedTableInfo(info: TableInfo): TableInfo {
637
+ if (!info.columns || info.columns.length === 0) {
638
+ if ((info.constraints ?? []).length) throw new Error(`Table '${info.name}': constraints on a table without columns`);
639
+ return info;
640
+ }
641
+ const schema = deserializeSchema(info.columns);
642
+ const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
643
+ return served === schema ? info : { ...info, columns: serializeSchema(served) };
644
+ }
645
+