@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.47.1",
3
+ "version": "0.48.0",
4
4
  "description": "TypeScript framework for extending DuckDB with user-defined functions via the Vector Gateway Interface (VGI) over Arrow IPC.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Query Farm LLC (https://query.farm)",
@@ -10,9 +10,15 @@ import {
10
10
  encodeSqlExpression,
11
11
  } from "../generated/vgi-protocol-types.js";
12
12
  import type { SqlExpression } from "../generated/vgi-client.js";
13
+ import { validateColumnExpressionSql } from "./sql-grammar.js";
14
+ import { duckdbPrimitive } from "./column-types.js";
13
15
 
14
16
  export const GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
15
17
  export const GENERATION_KEY = "vgi.column.generation.v1";
18
+ /** Canonical DEFAULT: base64 of one `SqlExpression` IPC record. */
19
+ export const DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
20
+ const GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
21
+ const DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
16
22
  const PROFILE = "vgi.expression.duckdb.scalar.v1";
17
23
  const MAX_BYTES = 8 * 1024 * 1024;
18
24
  const base64 = (bytes: Uint8Array): string =>
@@ -143,7 +149,8 @@ function shape(schema: VgiSchema): string {
143
149
  ];
144
150
  return JSON.stringify(schema.fields.map(field));
145
151
  }
146
- export function validateEncoded(encoded: string, owner: string[]): void {
152
+ /** Validate one canonical base64 `SqlExpression` and return its SQL. */
153
+ export function validateEncoded(encoded: string, owner: string[]): string {
147
154
  if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
148
155
  throw new Error("invalid generated expression size");
149
156
  const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
@@ -155,12 +162,42 @@ export function validateEncoded(encoded: string, owner: string[]): void {
155
162
  throw new Error("invalid SqlExpression record schema");
156
163
  const utf8 = new TextDecoder("utf-8", { fatal: true });
157
164
  textBuffers.forEach((buffer) => utf8.decode(buffer));
158
- expression(decodeSqlExpression(bytes), owner);
165
+ const value = decodeSqlExpression(bytes);
166
+ expression(value, owner);
167
+ return value.sql;
159
168
  }
169
+ /**
170
+ * Encode `sql` as canonical `vgi.column.generated.v1` metadata (base64 of a
171
+ * `SqlExpression` owned by schema `owner`). Pair it with
172
+ * `vgi.column.generation.v1 = "virtual"` on a nullable field.
173
+ */
160
174
  export function generatedExpressionMetadata(
161
175
  sql: string,
162
176
  owner: string[],
163
177
  ): string {
178
+ try {
179
+ validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
180
+ } catch (error) {
181
+ throw new Error(`generated expression ${JSON.stringify(sql)}: ${(error as Error).message}`);
182
+ }
183
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
184
+ }
185
+ /**
186
+ * Encode `sql` as canonical `vgi.column.default.v1` metadata. DuckDB reads it
187
+ * for boolean, signed-integer, float, decimal128 and utf8 columns; the SQL is a
188
+ * constant expression (no column references).
189
+ */
190
+ export function defaultExpressionMetadata(sql: string, owner: string[]): string {
191
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
192
+ return base64(encodeSqlExpression(sqlExpression(sql, owner)));
193
+ }
194
+ /**
195
+ * A DuckDB scalar `SqlExpression` owned by `schemaPath`, in the default
196
+ * evaluation context (UTC, binary collation, ASC NULLS LAST) — the only one the
197
+ * extension's native adapter accepts. Encode with `encodeSqlExpression`.
198
+ */
199
+ export function sqlExpression(sql: string, schemaPath: readonly string[]): SqlExpression {
200
+ const owner = [...schemaPath];
164
201
  const value: SqlExpression = {
165
202
  sql,
166
203
  profile: PROFILE,
@@ -174,7 +211,7 @@ export function generatedExpressionMetadata(
174
211
  },
175
212
  };
176
213
  expression(value, owner);
177
- return base64(encodeSqlExpression(value));
214
+ return value;
178
215
  }
179
216
  /** Validate canonical VIRTUAL metadata without evaluating or rewriting SQL. */
180
217
  export function validateColumnExpressions(
@@ -186,7 +223,12 @@ export function validateColumnExpressions(
186
223
  for (const f of t?.children ?? t?.fields ?? []) field(f);
187
224
  if (t?.dictionary) type(t.dictionary);
188
225
  };
189
- const field = (f: any): void => {
226
+ const topLevel = new Map<string, any[]>();
227
+ for (const f of schema.fields) {
228
+ const key = String(f.name).toLowerCase();
229
+ topLevel.set(key, [...(topLevel.get(key) ?? []), f]);
230
+ }
231
+ const field = (f: any, top = false): void => {
190
232
  const metadata: Map<string, string> = f.metadata ?? new Map();
191
233
  for (const key of metadata.keys()) {
192
234
  if (
@@ -196,10 +238,25 @@ export function validateColumnExpressions(
196
238
  )
197
239
  throw new Error("unknown generated metadata version");
198
240
  }
241
+ const where = `column ${f.name}`;
199
242
  if (metadata.has("generated_expression"))
200
243
  throw new Error(
201
- "legacy generated expression requires explicit canonical translation",
244
+ `${where}: legacy generated_expression metadata is not read under vgi.v3; ` +
245
+ "use generatedExpressionMetadata() (served tables are translated automatically)",
202
246
  );
247
+ if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
248
+ if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
249
+ throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
250
+ const type = duckdbPrimitive(f);
251
+ if (!type || !DEFAULT_TYPES.has(type))
252
+ throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
253
+ const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY)!, owner);
254
+ try {
255
+ validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
256
+ } catch (error) {
257
+ throw new Error(`${where}: default ${JSON.stringify(sql)}: ${(error as Error).message}`);
258
+ }
259
+ }
203
260
  if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
204
261
  throw new Error("generated expression and category must occur together");
205
262
  if (metadata.has(GENERATED_EXPRESSION_KEY)) {
@@ -207,13 +264,34 @@ export function validateColumnExpressions(
207
264
  throw new Error("only VIRTUAL generated columns are supported");
208
265
  if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
209
266
  throw new Error("generated column cannot have a default");
210
- validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY)!, owner);
267
+ const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY)!, owner);
211
268
  if (!allowGenerated)
212
269
  throw new Error("generated columns unsupported by this catalog");
270
+ if (!f.nullable)
271
+ throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
272
+ const type = duckdbPrimitive(f);
273
+ if (!type || !GENERATED_TYPES.has(type))
274
+ throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
275
+ let references: string[];
276
+ try {
277
+ references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
278
+ } catch (error) {
279
+ throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${(error as Error).message}`);
280
+ }
281
+ if (top) {
282
+ for (const name of references) {
283
+ const matches = topLevel.get(name.toLowerCase()) ?? [];
284
+ if (matches.length !== 1)
285
+ throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
286
+ const operand = duckdbPrimitive(matches[0]);
287
+ if (!operand || !GENERATED_TYPES.has(operand))
288
+ throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
289
+ }
290
+ }
213
291
  }
214
292
  type(f.type);
215
293
  };
216
- schema.fields.forEach(field);
294
+ schema.fields.forEach((f) => field(f, true));
217
295
  }
218
296
  export function validateColumnExpressionsIpc(
219
297
  bytes: Uint8Array,
@@ -2,6 +2,7 @@
2
2
  import { validateColumnExpressionsIpc } from "./column-expressions.js";
3
3
  import type { VgiSchema } from "../arrow/index.js";
4
4
  import { encodeTableInfo, type TableInfo } from "../generated/vgi-client.js";
5
+ import { servedTableInfo } from "./constraints.js";
5
6
 
6
7
  function scalarText(value: string): void {
7
8
  for (let i = 0; i < value.length; i++) {
@@ -145,7 +146,24 @@ export function validateColumnMetadataIpc(bytes: Uint8Array): void {
145
146
  export function validateTableInfoColumns(info: TableInfo): void {
146
147
  if (info.columns.length) { validateColumnMetadataIpc(info.columns); validateColumnExpressionsIpc(info.columns, info.schema_path); }
147
148
  }
149
+ /**
150
+ * The TableInfo a worker sends: raw column metadata checked on the original
151
+ * bytes, then the served schema (see `servedTableInfo`: constraint records
152
+ * checked as DuckDB checks them, nullability derived from them, legacy
153
+ * generated metadata translated), whose column expressions are checked last.
154
+ */
155
+ export function servedValidatedTableInfo(info: TableInfo): TableInfo {
156
+ if (info.columns.length) validateColumnMetadataIpc(info.columns);
157
+ const served = servedTableInfo(info);
158
+ if (served.columns.length) {
159
+ try {
160
+ validateColumnExpressionsIpc(served.columns, served.schema_path);
161
+ } catch (error) {
162
+ throw new Error(`Table '${served.name}': ${(error as Error).message}`);
163
+ }
164
+ }
165
+ return served;
166
+ }
148
167
  export function encodeValidatedTableInfo(info: TableInfo): Uint8Array {
149
- validateTableInfoColumns(info);
150
- return encodeTableInfo(info);
168
+ return encodeTableInfo(servedValidatedTableInfo(info));
151
169
  }
@@ -0,0 +1,50 @@
1
+ // Copyright 2026 Query Farm LLC - https://query.farm
2
+ // How the DuckDB vgi extension classifies an Arrow field, for the checks the
3
+ // SDK mirrors (constraint paths, CHECK operands, column-expression types).
4
+
5
+ import { isStruct, TypeId, type VgiDataType, type VgiField } from "../arrow/index.js";
6
+
7
+ /** The top-level column carrying `is_row_id` metadata (DuckDB's rowid, never a user column). */
8
+ export function isRowIdField(field: VgiField): boolean {
9
+ return field.metadata?.has("is_row_id") ?? false;
10
+ }
11
+
12
+ /** Whether the field carries an Arrow extension type or a VGI logical type. */
13
+ export function hasLogicalType(field: VgiField): boolean {
14
+ for (const key of field.metadata?.keys() ?? [])
15
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) return true;
16
+ return false;
17
+ }
18
+
19
+ /** A field's children when it is an ordinary STRUCT (not an extension or logical type), else null. */
20
+ export function ordinaryStructChildren(field: VgiField): readonly VgiField[] | null {
21
+ if (!isStruct(field.type) || hasLogicalType(field)) return null;
22
+ return (field.type as VgiDataType & { children: readonly VgiField[] }).children;
23
+ }
24
+
25
+ /** Whether the field is a generated column (canonical or legacy metadata). */
26
+ export function isGeneratedField(field: VgiField): boolean {
27
+ const m = field.metadata;
28
+ return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
29
+ }
30
+
31
+ /**
32
+ * The DuckDB primitive a field maps to for the bounded expression and CHECK
33
+ * profiles, or null for every other type (unsigned, large/dictionary strings,
34
+ * temporal, nested, extension and logical types).
35
+ */
36
+ export function duckdbPrimitive(field: VgiField): string | null {
37
+ if (hasLogicalType(field)) return null;
38
+ const t = field.type as any;
39
+ switch (t.typeId) {
40
+ case TypeId.Bool: return "BOOLEAN";
41
+ case TypeId.Utf8: return "VARCHAR";
42
+ case TypeId.Int: {
43
+ if (!(t.isSigned ?? t.signed ?? true)) return null;
44
+ return ({ 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" } as Record<number, string>)[t.bitWidth] ?? null;
45
+ }
46
+ case TypeId.Float: return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
47
+ case TypeId.Decimal: return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
48
+ default: return null;
49
+ }
50
+ }
@@ -224,6 +224,16 @@ export class CompositeCatalogInterface extends CatalogInterface {
224
224
  override async tableNotNullDrop(...args: Parameters<CatalogInterface["tableNotNullDrop"]>): Promise<void> {
225
225
  await (this._route(args[0]).tableNotNullDrop as (...a: typeof args) => unknown)(...args);
226
226
  }
227
+ override async tableConstraintsApply(
228
+ request: Parameters<CatalogInterface["tableConstraintsApply"]>[0],
229
+ ): ReturnType<CatalogInterface["tableConstraintsApply"]> {
230
+ return await this._route(request.attach_opaque_data).tableConstraintsApply(request);
231
+ }
232
+ override async catalogCapabilities(
233
+ attachOpaqueData: AttachOpaqueData,
234
+ ): Promise<Awaited<ReturnType<CatalogInterface["catalogCapabilities"]>>> {
235
+ return await this._route(attachOpaqueData).catalogCapabilities(attachOpaqueData);
236
+ }
227
237
  override async viewCreate(...args: Parameters<CatalogInterface["viewCreate"]>): Promise<void> {
228
238
  await (this._route(args[0]).viewCreate as (...a: typeof args) => unknown)(...args);
229
239
  }