@query-farm/vgi 0.48.2 → 0.48.4

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 (54) hide show
  1. package/README.md +27 -0
  2. package/dist/arrow/impl-arrowjs/iterate.d.ts +7 -3
  3. package/dist/arrow/impl-flechette/iterate.d.ts +2 -1
  4. package/dist/catalog/descriptors.d.ts +30 -0
  5. package/dist/catalog/interface.d.ts +28 -0
  6. package/dist/catalog/read-only.d.ts +16 -2
  7. package/dist/client-entry.js +9 -25
  8. package/dist/client-entry.js.map +4 -4
  9. package/dist/functions/aggregate.d.ts +2 -1
  10. package/dist/functions/copy-from.d.ts +2 -1
  11. package/dist/functions/copy-to.d.ts +2 -1
  12. package/dist/functions/scalar.d.ts +2 -1
  13. package/dist/functions/table-buffering.d.ts +2 -1
  14. package/dist/functions/table-in-out.d.ts +3 -2
  15. package/dist/functions/table.d.ts +2 -1
  16. package/dist/functions/types.d.ts +2 -1
  17. package/dist/index.core.d.ts +4 -1
  18. package/dist/index.js +360 -72
  19. package/dist/index.js.map +25 -23
  20. package/dist/metadata/types.d.ts +3 -1
  21. package/dist/protocol/handlers/catalog/shared.d.ts +8 -0
  22. package/dist/secrets/helpers.d.ts +31 -3
  23. package/dist/secrets/requirements.d.ts +38 -0
  24. package/dist/serve-entry.js +51 -33
  25. package/dist/serve-entry.js.map +9 -9
  26. package/dist/worker-cf-entry.d.ts +2 -2
  27. package/dist/worker-cf-entry.js +296 -50
  28. package/dist/worker-cf-entry.js.map +21 -18
  29. package/dist/write-results.d.ts +57 -0
  30. package/package.json +1 -1
  31. package/src/arrow/impl-arrowjs/iterate.ts +17 -40
  32. package/src/arrow/impl-flechette/iterate.ts +5 -24
  33. package/src/catalog/descriptors.ts +30 -0
  34. package/src/catalog/interface.ts +51 -0
  35. package/src/catalog/read-only.ts +129 -21
  36. package/src/functions/aggregate.ts +3 -2
  37. package/src/functions/copy-from.ts +3 -2
  38. package/src/functions/copy-to.ts +2 -1
  39. package/src/functions/scalar.ts +3 -2
  40. package/src/functions/table-buffering.ts +3 -2
  41. package/src/functions/table-in-out.ts +5 -4
  42. package/src/functions/table.ts +3 -2
  43. package/src/functions/types.ts +2 -1
  44. package/src/index.core.ts +33 -0
  45. package/src/metadata/resolve.ts +2 -1
  46. package/src/metadata/serialize.ts +25 -5
  47. package/src/metadata/types.ts +3 -1
  48. package/src/protocol/handlers/catalog/shared.ts +17 -0
  49. package/src/protocol/handlers/catalog/table.ts +37 -0
  50. package/src/protocol/handlers/function.ts +42 -14
  51. package/src/secrets/helpers.ts +96 -9
  52. package/src/secrets/requirements.ts +121 -0
  53. package/src/worker-cf-entry.ts +14 -0
  54. package/src/write-results.ts +174 -0
@@ -0,0 +1,57 @@
1
+ import { type VgiBatch, type VgiField, type VgiSchema } from "./arrow/index.js";
2
+ import type { BindRequest } from "./protocol/types.js";
3
+ export type WriteOperation = "insert" | "update" | "delete";
4
+ export type WriteResultMode = "count" | "rows" | "changes";
5
+ export declare const WRITE_OPERATIONS: readonly WriteOperation[];
6
+ export declare const WRITE_RESULT_MODES: readonly WriteResultMode[];
7
+ /** Field metadata key that marks a table's row-id column. */
8
+ export declare const ROW_ID_METADATA_KEY = "is_row_id";
9
+ /**
10
+ * A row-id field for a writable table's columns and its scan's output:
11
+ * `rowIdField()` is DuckDB's conventional `rowid BIGINT`.
12
+ *
13
+ * DuckDB reads the row id as a *virtual* column, which it only requests from a
14
+ * scan that supports projection pushdown. So a table with UPDATE or DELETE
15
+ * needs a scan function that (1) emits this field, (2) is declared with
16
+ * `projectionPushdown: true` and honours `params.outputSchema`, and (3) is
17
+ * listed in its schema's `functions`, which is how DuckDB learns (2). Missing
18
+ * any of these, UPDATE/DELETE fail with "Virtual columns require projection
19
+ * pushdown". Row ids must be unique and stable for the life of a statement.
20
+ */
21
+ export declare function rowIdField(name?: string, type?: import("./index.core.js").Int64Type): VgiField;
22
+ /** Return a validated copy of an operation -> maximum-mode mapping. */
23
+ export declare function validateWriteResultModes(modes: Partial<Record<string, string>>): Partial<Record<WriteOperation, WriteResultMode>>;
24
+ /** Whether a table whose maximum is `maximum` supports `requested`. */
25
+ export declare function supportsWriteResultMode(maximum: string, requested: string): boolean;
26
+ /** Validate a wire value and narrow it to a `WriteResultMode`. */
27
+ export declare function coerceWriteResultMode(value: unknown): WriteResultMode;
28
+ /**
29
+ * The table's user columns: `columns` without the row-id field. Write results
30
+ * (`rows`, and both halves of `changes`) use this schema.
31
+ */
32
+ export declare function userColumns(columns: VgiSchema): VgiSchema;
33
+ /** The exact output schema a write function must bind for `mode`. */
34
+ export declare function writeResultSchema(mode: WriteResultMode, tableSchema: VgiSchema): VgiSchema;
35
+ /** A `count` result batch. */
36
+ export declare function writeCountBatch(count: number | bigint): VgiBatch;
37
+ /** A `rows` result batch: the written rows as plain objects keyed by column. */
38
+ export declare function writeRowsBatch(tableSchema: VgiSchema, rows: readonly Record<string, unknown>[]): VgiBatch;
39
+ /**
40
+ * A `changes` result batch, one OLD/NEW pair per written row: `old` is null
41
+ * for an insert, `new` is null for a delete.
42
+ */
43
+ export declare function writeChangesBatch(tableSchema: VgiSchema, oldRows: readonly (Record<string, unknown> | null)[], newRows: readonly (Record<string, unknown> | null)[]): VgiBatch;
44
+ /** The result batch for `mode`, from the written rows' before/after images. */
45
+ export declare function writeResultBatch(mode: WriteResultMode, tableSchema: VgiSchema, oldRows: readonly (Record<string, unknown> | null)[], newRows: readonly (Record<string, unknown> | null)[]): VgiBatch;
46
+ /** What DuckDB asked a write function for, decoded from `write_options`. */
47
+ export interface WriteOptions {
48
+ resultMode: WriteResultMode;
49
+ /** `throw` (default), or the INSERT ... ON CONFLICT action DuckDB requested. */
50
+ onConflict: string;
51
+ onConflictColumns: string[];
52
+ }
53
+ /**
54
+ * Decode the `write_options` named argument of a write function's bind (a
55
+ * serialized one-row batch). Missing options mean a plain `count` write.
56
+ */
57
+ export declare function writeOptions(bindCall: Pick<BindRequest, "arguments">): WriteOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.48.2",
3
+ "version": "0.48.4",
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)",
@@ -93,9 +93,13 @@ export function decodeDictValue(value: any, index = 0): any {
93
93
  }
94
94
 
95
95
  /**
96
- * Extract single-row batch to a secret dict (column per secret, each value is a struct).
97
- * Handles both named secrets (column name = secret type) and scoped secrets
98
- * (column name = "secret_N" with secret_type in field metadata).
96
+ * Extract a single-row resolved-secrets batch to a dict: one entry per column,
97
+ * keyed by the column name — the secret's unique DuckDB NAME, not its type (an
98
+ * unnamed secret arrives as `__default_<type>`). Each value is the secret's
99
+ * struct as a plain object, including its serialized `type`, `name` and `scope`
100
+ * fields. Select from it with the helpers in `secrets/helpers.ts`
101
+ * (`secretOfType`, `secretByName`, `secretForScopeOfType`, ...), never by
102
+ * indexing it with a type. A null struct (secret not found) is skipped.
99
103
  */
100
104
  export function batchToSecretDict(
101
105
  batch: RecordBatch | VgiBatch | null
@@ -106,43 +110,16 @@ export function batchToSecretDict(
106
110
  const result: Record<string, Record<string, any>> = {};
107
111
  for (const field of a.schema.fields) {
108
112
  const col = a.getChild(field.name);
109
- if (col) {
110
- // Read in RICH form via the canonical reader + codec — a secret column is
111
- // a struct scalar, which surfaces as a plain { field: value } object
112
- // (same path as iterRows), so no Arrow-scalar toJSON() shimming is needed.
113
- const type = field.type as unknown as VgiDataType;
114
- const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
115
-
116
- // Determine the key: for scoped secrets (secret_N), use secret_type from metadata
117
- let key = field.name;
118
- let scope: string | undefined;
119
- if (field.name.startsWith("secret_")) {
120
- const secretType = field.metadata?.get?.("secret_type");
121
- if (secretType) {
122
- key = secretType;
123
- scope = field.metadata?.get?.("scope") ?? undefined;
124
- }
125
- }
126
-
127
- if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
128
- // Struct scalar -> already a plain object from the canonical reader.
129
- const dict: Record<string, any> = { ...(val as Record<string, any>) };
130
- if (key in result) {
131
- throw new Error(
132
- `batchToSecretDict: duplicate secret_type '${key}' (scope=${scope ?? "none"}). ` +
133
- `Use scoped secrets with distinct scopes to avoid collisions.`
134
- );
135
- }
136
- result[key] = dict;
137
- // Store scope-qualified key for disambiguation
138
- if (scope) {
139
- result[`${key}:${scope}`] = dict;
140
- }
141
- } else if (val === null || val === undefined) {
142
- // Skip null struct values (secret not found)
143
- } else {
144
- result[key] = {};
145
- }
113
+ if (!col) continue;
114
+ // Read in RICH form via the canonical reader + codec — a secret column is
115
+ // a struct scalar, which surfaces as a plain { field: value } object
116
+ // (same path as iterRows), so no Arrow-scalar toJSON() shimming is needed.
117
+ const type = field.type as unknown as VgiDataType;
118
+ const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
119
+ if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
120
+ result[field.name] = { ...(val as Record<string, any>) };
121
+ } else if (val !== null && val !== undefined) {
122
+ result[field.name] = {};
146
123
  }
147
124
  }
148
125
  return result;
@@ -66,7 +66,8 @@ export function decodeDictValue(value: any, _index = 0): any {
66
66
  }
67
67
 
68
68
  /**
69
- * Single-row batch → secret dict. Mirrors impl-arrowjs's same-named function.
69
+ * Single-row resolved-secrets batch → dict keyed by column name (the secret's
70
+ * unique DuckDB NAME, not its type). Mirrors impl-arrowjs's same-named function.
70
71
  */
71
72
  export function batchToSecretDict(
72
73
  batch: VgiBatch | null,
@@ -83,30 +84,10 @@ export function batchToSecretDict(
83
84
  // iterRows), identical to the arrow-js backend.
84
85
  const type = f.type as VgiDataType;
85
86
  const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
86
-
87
- let key = f.name;
88
- let scope: string | undefined;
89
- if (f.name.startsWith("secret_")) {
90
- const secretType = f.metadata?.get?.("secret_type");
91
- if (secretType) {
92
- key = secretType;
93
- scope = f.metadata?.get?.("scope") ?? undefined;
94
- }
95
- }
96
-
97
87
  if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
98
- const dict: Record<string, any> = { ...(val as Record<string, any>) };
99
- if (key in result) {
100
- throw new Error(
101
- `batchToSecretDict: duplicate secret_type '${key}' (scope=${scope ?? "none"}).`,
102
- );
103
- }
104
- result[key] = dict;
105
- if (scope) result[`${key}:${scope}`] = dict;
106
- } else if (val === null || val === undefined) {
107
- // skip
108
- } else {
109
- result[key] = {};
88
+ result[f.name] = { ...(val as Record<string, any>) };
89
+ } else if (val !== null && val !== undefined) {
90
+ result[f.name] = {};
110
91
  }
111
92
  }
112
93
  return result;
@@ -4,6 +4,7 @@
4
4
  import type { VgiSchema, VgiDataType } from "../arrow/index.js";
5
5
  import type { AttachCatalogInfo } from "./interface.js";
6
6
  import type { AttachOptionSpec } from "./attach-option.js";
7
+ import type { WriteOperation, WriteResultMode } from "../write-results.js";
7
8
  import type { VgiFunction } from "../functions/types.js";
8
9
  import type { Arguments } from "../arguments/arguments.js";
9
10
  import type { ColumnStatistics } from "../util/statistics.js";
@@ -40,6 +41,35 @@ export interface TableDescriptor {
40
41
  columns?: VgiSchema;
41
42
  function?: VgiFunction;
42
43
  arguments?: Arguments;
44
+ /**
45
+ * Table in-out function backing `INSERT INTO <table>`. It receives the new
46
+ * rows (the table's user columns) and returns a `writeResultSchema` batch
47
+ * for the mode in its `write_options` (see `write-results.ts`). Omitted
48
+ * means the table does not accept INSERT.
49
+ */
50
+ insertFunction?: VgiFunction;
51
+ /**
52
+ * Table in-out function backing `UPDATE <table>`. It receives the changed
53
+ * columns plus the row-id column (`rowIdField()`, which the scan
54
+ * `function` must emit) for each updated row. Requires `function`, which
55
+ * must also support projection pushdown and be listed in the schema's
56
+ * `functions` (see `rowIdField`).
57
+ */
58
+ updateFunction?: VgiFunction;
59
+ /**
60
+ * Table in-out function backing `DELETE FROM <table>`. It receives the
61
+ * row-id column of each deleted row. Requires `function`, with the same
62
+ * projection-pushdown conditions as `updateFunction`.
63
+ */
64
+ deleteFunction?: VgiFunction;
65
+ /**
66
+ * The richest result mode each write function produces: `count` (plain
67
+ * DML), `rows` (`RETURNING`) or `changes` (old/new pairs). Ordered
68
+ * `count < rows < changes`; supporting one mode promises every lower one.
69
+ * An operation with a write function but no entry defaults to `count`.
70
+ * Mirrors vgi-python's `Table.write_result_modes`.
71
+ */
72
+ writeResultModes?: Partial<Record<WriteOperation, WriteResultMode>>;
43
73
  /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "NOT_NULL", ... })]`. */
44
74
  notNull?: string[];
45
75
  /** @deprecated Not sent under vgi.v3 (serving throws). Use `constraints: [constraintRecord({ kind: "UNIQUE", ... })]`. */
@@ -201,6 +201,19 @@ export interface ScanFunctionResult {
201
201
  schemaPath: string[] | null;
202
202
  }
203
203
 
204
+ /**
205
+ * The `ScanFunctionResult` wire record as a catalog method returns it:
206
+ * `tableScanFunctionGet` (untyped, for history) and the write-function lookups
207
+ * `tableInsertFunctionGet` / `tableUpdateFunctionGet` / `tableDeleteFunctionGet`.
208
+ * `arguments` is the serialized inner arguments batch.
209
+ */
210
+ export interface ScanFunctionResultRecord {
211
+ function_name: string;
212
+ arguments: Uint8Array;
213
+ required_extensions: string[];
214
+ schema_path: string[] | null;
215
+ }
216
+
204
217
  /**
205
218
  * Encode a ScanFunctionResult wire record — the single-row batch shape
206
219
  * `{ function_name, arguments, required_extensions, schema_path }` that
@@ -839,6 +852,44 @@ export abstract class CatalogInterface {
839
852
  ): Awaitable<any> {
840
853
  throw new CatalogReadOnlyError("table_scan_function_get");
841
854
  }
855
+ /**
856
+ * The table in-out function backing `INSERT INTO` this table. Default:
857
+ * the table is read-only. `writableBranchFunctionName` names the writable
858
+ * arm of a multi-branch table (null for a single-branch one).
859
+ */
860
+ tableInsertFunctionGet(
861
+ attachOpaqueData: AttachOpaqueData,
862
+ schemaPath: string[],
863
+ name: string,
864
+ transactionOpaqueData?: TransactionOpaqueData,
865
+ writableBranchFunctionName?: string | null,
866
+ ): Awaitable<ScanFunctionResultRecord> {
867
+ throw new CatalogReadOnlyError("table_insert_function_get");
868
+ }
869
+ /**
870
+ * The table in-out function backing `UPDATE` of this table. Its input is the
871
+ * changed columns plus the row-id column. Default: the table is read-only.
872
+ */
873
+ tableUpdateFunctionGet(
874
+ attachOpaqueData: AttachOpaqueData,
875
+ schemaPath: string[],
876
+ name: string,
877
+ transactionOpaqueData?: TransactionOpaqueData,
878
+ ): Awaitable<ScanFunctionResultRecord> {
879
+ throw new CatalogReadOnlyError("table_update_function_get");
880
+ }
881
+ /**
882
+ * The table in-out function backing `DELETE FROM` this table. Its input is
883
+ * the row-id column. Default: the table is read-only.
884
+ */
885
+ tableDeleteFunctionGet(
886
+ attachOpaqueData: AttachOpaqueData,
887
+ schemaPath: string[],
888
+ name: string,
889
+ transactionOpaqueData?: TransactionOpaqueData,
890
+ ): Awaitable<ScanFunctionResultRecord> {
891
+ throw new CatalogReadOnlyError("table_delete_function_get");
892
+ }
842
893
  /**
843
894
  * Return the scan branches for a (possibly multi-source) table. Default
844
895
  * delegates to `tableScanFunctionGet` and wraps the single result as a
@@ -17,6 +17,7 @@ import {
17
17
  type MacroInfo,
18
18
  type IndexInfo,
19
19
  type CopyFromFormatInfo,
20
+ type ScanFunctionResultRecord,
20
21
  encodeAttachCatalogInfo,
21
22
  encodeScanFunctionResult,
22
23
  buildCatalogAttachResult,
@@ -34,11 +35,12 @@ import { Arguments } from "../arguments/arguments.js";
34
35
  import { normalizeSchemaPath, schemaPathDisplay, schemaPathsEqual } from "../schema-path.js";
35
36
  import { ForeignKeyInfoSchema } from "../generated/vgi-protocol-schemas.js";
36
37
  import { conformColumns } from "../codec/conform.js";
37
- import { VgiError } from "../errors.js";
38
+ import { CatalogReadOnlyError, VgiError } from "../errors.js";
38
39
  import { encodeFunctionInfoOnce, freezeCatalogItem } from "./item-encoding.js";
39
40
  import { macroOverloads } from "./macro-overloads.js";
40
- import { CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, catalogCapabilities, selectReadProfiles, servedTableSchema, validateForeignKeyTargets } from "./constraints.js";
41
+ import { CONSTRAINT_ENFORCE, CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, catalogCapabilities, selectCatalogCapabilities, servedTableSchema, validateForeignKeyTargets } from "./constraints.js";
41
42
  import { duckdbPrimitive } from "./column-types.js";
43
+ import { WRITE_OPERATIONS, type WriteOperation, validateWriteResultModes } from "../write-results.js";
42
44
  import { defaultExpressionMetadata } from "./column-expressions.js";
43
45
  import type { CatalogCapabilities } from "../generated/vgi-protocol-types.js";
44
46
  import { encodeCatalogCapabilities } from "../generated/vgi-protocol-types.js";
@@ -114,6 +116,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
114
116
  this._descriptor = descriptor;
115
117
  this._registry = registry;
116
118
  if (options.perAttachItemIds) this.perAttachItemIds = true;
119
+ for (const sch of descriptor.schemas ?? []) for (const tbl of sch.tables ?? []) validateWritableTable(tbl);
117
120
  // Index every function this catalog declares by its owning schema, so a
118
121
  // schema-qualified bind resolves to the right implementation when one name
119
122
  // is declared in more than one schema. Table-backing functions are indexed
@@ -222,9 +225,11 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
222
225
  encodeAttachCatalogInfo(c)
223
226
  );
224
227
 
225
- // Constraint records are readable only under a negotiated profile.
226
- const available = this.catalogReadProfiles();
227
- const read = selectReadProfiles(available, clientCapabilities);
228
+ // Constraint records are readable, and writes to constrained tables
229
+ // accepted, only under negotiated profiles.
230
+ const available = catalogCapabilities({ read: this.catalogReadProfiles(), write: this.catalogWriteProfiles() });
231
+ const advertised = available.read.length + available.write.length > 0;
232
+ const selected = selectCatalogCapabilities(available, clientCapabilities);
228
233
 
229
234
  // Auto-derive supportsTimeTravel from table descriptors
230
235
  const hasTimeTravel = this._descriptor.schemas.some(
@@ -257,12 +262,8 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
257
262
  // Static, version-frozen catalog: the whole thing can be served in one
258
263
  // catalog_contents call (as vgi-python's ReadOnlyCatalogInterface does).
259
264
  supports_catalog_contents: this.supportsCatalogContents,
260
- catalog_capabilities: available.length
261
- ? encodeCatalogCapabilities({ read: [...available].sort(), ddl: [], write: [], transaction: [] })
262
- : null,
263
- selected_capabilities: available.length
264
- ? encodeCatalogCapabilities({ read, ddl: [], write: [], transaction: [] })
265
- : null,
265
+ catalog_capabilities: advertised ? encodeCatalogCapabilities(available) : null,
266
+ selected_capabilities: advertised ? encodeCatalogCapabilities(selected) : null,
266
267
  });
267
268
  }
268
269
 
@@ -278,10 +279,28 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
278
279
  return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
279
280
  }
280
281
 
281
- /** The descriptor's read profiles (records are served, never mutated here). */
282
+ /**
283
+ * Write profiles this catalog implements. A table that carries constraint
284
+ * records AND has a write function makes the catalog advertise
285
+ * `vgi.constraint.enforce.v1`: DuckDB only writes to a constrained table
286
+ * when the provider promises to keep its ENFORCED constraints, so such a
287
+ * table's write functions must reject rows that would violate them (for
288
+ * instance by refusing to change key columns).
289
+ */
290
+ catalogWriteProfiles(): string[] {
291
+ const writableConstrained = this._descriptor.schemas.some(
292
+ (s) =>
293
+ s.tables?.some(
294
+ (t) => (t.constraints?.length ?? 0) > 0 && (t.insertFunction || t.updateFunction || t.deleteFunction),
295
+ ) ?? false,
296
+ );
297
+ return writableConstrained ? [CONSTRAINT_ENFORCE] : [];
298
+ }
299
+
300
+ /** The descriptor's profiles: records are served, never mutated here; writable constrained tables enforce. */
282
301
  override catalogCapabilities(_attachOpaqueData: AttachOpaqueData): CatalogCapabilities | null {
283
- const read = this.catalogReadProfiles();
284
- return read.length ? catalogCapabilities({ read }) : null;
302
+ const caps = catalogCapabilities({ read: this.catalogReadProfiles(), write: this.catalogWriteProfiles() });
303
+ return caps.read.length + caps.write.length ? caps : null;
285
304
  }
286
305
 
287
306
  detach(attachOpaqueData: AttachOpaqueData): void {
@@ -473,7 +492,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
473
492
  columns,
474
493
  constraints: [...constraints],
475
494
  definition_revision: t.definitionRevision ?? null,
476
- write_result_modes: {},
495
+ write_result_modes: writeResultModesFor(t),
477
496
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
478
497
  // Inline scan_function only for purely function-backed tables.
479
498
  // When explicit `columns` are also declared, the table is on the
@@ -483,9 +502,13 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
483
502
  scan_function: t.function && !t.columns
484
503
  ? inlineScanFunction(t.function, t.arguments, this._schemaForFunction(t.function))
485
504
  : null,
486
- insert_function: null,
487
- update_function: null,
488
- delete_function: null,
505
+ // Write functions are inlined like a purely function-backed scan:
506
+ // they take no catalog-supplied arguments (DuckDB passes the rows and
507
+ // `write_options`), so the extension can skip the per-statement
508
+ // catalog_table_{insert,update,delete}_function_get round trip.
509
+ insert_function: t.insertFunction ? inlineScanFunction(t.insertFunction, undefined, this._schemaForFunction(t.insertFunction)) : null,
510
+ update_function: t.updateFunction ? inlineScanFunction(t.updateFunction, undefined, this._schemaForFunction(t.updateFunction)) : null,
511
+ delete_function: t.deleteFunction ? inlineScanFunction(t.deleteFunction, undefined, this._schemaForFunction(t.deleteFunction)) : null,
489
512
  cardinality_estimate: t.inlinedCardinality
490
513
  ? Number(t.inlinedCardinality.estimate)
491
514
  : null,
@@ -639,9 +662,12 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
639
662
  f.defaultOutputSchema ?? schema_([])
640
663
  );
641
664
 
642
- const requiredSecrets = (meta.requiredSecrets ?? []).map(
643
- (secretType: string) => ({ secret_type: secretType, scope: null, secret_name: null })
644
- );
665
+ // Every validated requirement reaches the wire: type, scope and name.
666
+ const requiredSecrets = meta.requiredSecrets.map((s) => ({
667
+ secret_type: s.secretType,
668
+ scope: s.scope,
669
+ secret_name: s.secretName,
670
+ }));
645
671
 
646
672
  // Function-level tags surfaced into duckdb_functions().tags. The wire
647
673
  // map is string→string, so the metadata linter (vgi-lint-check) and any
@@ -910,6 +936,56 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
910
936
  throw new Error(`Table '${name}' is not function-backed`);
911
937
  }
912
938
 
939
+ /** The write function for `operation`, or a read-only / not-found error. */
940
+ private _writeFunctionGet(schemaPath: string[], name: string, operation: WriteOperation): ScanFunctionResultRecord {
941
+ const schema = this._descriptor.schemas.find((sch) => schemaPathsEqual(schemaDescriptorPath(sch), schemaPath));
942
+ const table = schema?.tables?.find((t) => t.name.toLowerCase() === name.toLowerCase());
943
+ if (!table) {
944
+ throw new VgiError(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`, "NOT_FOUND");
945
+ }
946
+ const fn = writeFunctionOf(table, operation);
947
+ if (!fn) {
948
+ throw new CatalogReadOnlyError(
949
+ `Table ${schemaPathDisplay(schemaPath)}.${table.name} does not support ${operation.toUpperCase()}`,
950
+ );
951
+ }
952
+ return {
953
+ function_name: fn.meta.name,
954
+ arguments: serializeArgsBatch(new Arguments(), argumentSpecsToSchema(fn.argumentSpecs)),
955
+ required_extensions: [],
956
+ schema_path: this._schemaForFunction(fn),
957
+ };
958
+ }
959
+
960
+ override tableInsertFunctionGet(
961
+ _attachOpaqueData: AttachOpaqueData,
962
+ schemaPath: string[],
963
+ name: string,
964
+ _transactionOpaqueData?: TransactionOpaqueData,
965
+ // Descriptor tables are single-branch: the writable-arm hint does not apply.
966
+ _writableBranchFunctionName?: string | null,
967
+ ): ScanFunctionResultRecord {
968
+ return this._writeFunctionGet(schemaPath, name, "insert");
969
+ }
970
+
971
+ override tableUpdateFunctionGet(
972
+ _attachOpaqueData: AttachOpaqueData,
973
+ schemaPath: string[],
974
+ name: string,
975
+ _transactionOpaqueData?: TransactionOpaqueData,
976
+ ): ScanFunctionResultRecord {
977
+ return this._writeFunctionGet(schemaPath, name, "update");
978
+ }
979
+
980
+ override tableDeleteFunctionGet(
981
+ _attachOpaqueData: AttachOpaqueData,
982
+ schemaPath: string[],
983
+ name: string,
984
+ _transactionOpaqueData?: TransactionOpaqueData,
985
+ ): ScanFunctionResultRecord {
986
+ return this._writeFunctionGet(schemaPath, name, "delete");
987
+ }
988
+
913
989
  override async tableGet(
914
990
  attachOpaqueData: AttachOpaqueData,
915
991
  schemaPath: string[],
@@ -1285,3 +1361,35 @@ function sameSpelling(left: Iterable<unknown> | string, right: Iterable<unknown>
1285
1361
  const b = normalizeSchemaPath(right);
1286
1362
  return a.length === b.length && a.every((part, i) => part === b[i]);
1287
1363
  }
1364
+
1365
+ // ---------------------------------------------------------------- writable tables
1366
+
1367
+ function writeFunctionOf(table: TableDescriptor, operation: WriteOperation): VgiFunction | undefined {
1368
+ return operation === "insert" ? table.insertFunction : operation === "update" ? table.updateFunction : table.deleteFunction;
1369
+ }
1370
+
1371
+ /**
1372
+ * Reject a writable-table declaration vgi-python's `Table.__post_init__` would:
1373
+ * an unknown operation or mode, a mode for an operation with no function, or
1374
+ * UPDATE/DELETE without a scan function to supply row ids.
1375
+ */
1376
+ function validateWritableTable(table: TableDescriptor): void {
1377
+ const modes = validateWriteResultModes((table.writeResultModes ?? {}) as Record<string, string>);
1378
+ for (const operation of Object.keys(modes) as WriteOperation[]) {
1379
+ if (!writeFunctionOf(table, operation)) {
1380
+ throw new Error(`Table '${table.name}': writeResultModes declares '${operation}' without a corresponding ${operation}Function`);
1381
+ }
1382
+ }
1383
+ if ((table.updateFunction || table.deleteFunction) && !table.function) {
1384
+ throw new Error(`Table '${table.name}': updateFunction and deleteFunction require a scan function (set 'function') to provide row ids`);
1385
+ }
1386
+ }
1387
+
1388
+ /** TableInfo.write_result_modes: each configured operation's maximum mode (default `count`). */
1389
+ function writeResultModesFor(table: TableDescriptor): Record<string, string> {
1390
+ const out: Record<string, string> = {};
1391
+ for (const operation of WRITE_OPERATIONS) {
1392
+ if (writeFunctionOf(table, operation)) out[operation] = table.writeResultModes?.[operation] ?? "count";
1393
+ }
1394
+ return out;
1395
+ }
@@ -13,6 +13,7 @@
13
13
  // aggregate_finalize → emit one result row per group_id
14
14
  // aggregate_destructor → free states (best-effort; see Python worker.py)
15
15
 
16
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
16
17
  import { type VgiSchema, schema, type VgiField, field, type VgiBatch, type VgiDataType, nullType, isNull } from "../arrow/index.js";
17
18
  import type { Arguments } from "../arguments/arguments.js";
18
19
  import {
@@ -165,7 +166,7 @@ export interface AggregateFunctionConfig<TArgs = Record<string, any>, TState = a
165
166
  * empty ResolvedSecrets. Mirrors vgi-python's `Secret()` annotation on an
166
167
  * aggregate `on_bind`.
167
168
  */
168
- requiredSecrets?: string[];
169
+ requiredSecrets?: RequiredSecret[];
169
170
  }
170
171
 
171
172
  // Per-execution state registry. Value = (gid → state) + bind context.
@@ -376,7 +377,7 @@ export function defineAggregate<TArgs = Record<string, any>, TState = any>(
376
377
  tags: config.tags,
377
378
  parameterDefaultValues: config.parameterDefaultValues,
378
379
  nullHandling: config.nullHandling as any,
379
- requiredSecrets: config.requiredSecrets,
380
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
380
381
  };
381
382
 
382
383
  // The normal VgiFunction methods (bind/globalInit/createStreamHandlers) are
@@ -19,6 +19,7 @@
19
19
  // arrive as the function's normal named arguments. Mirrors vgi-python's
20
20
  // `vgi.copy_from_function.CopyFromFunction`.
21
21
 
22
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
22
23
  import { type VgiSchema, type VgiDataType } from "../arrow/index.js";
23
24
  import type { OutputCollector } from "@query-farm/vgi-rpc";
24
25
  import { DEFAULT_MAX_WORKERS } from "../types.js";
@@ -88,7 +89,7 @@ export interface CopyFromFunctionConfig<TArgs = Record<string, unknown>> {
88
89
  tags?: Record<string, string>;
89
90
  examples?: FunctionExample[];
90
91
  requiredSettings?: string[];
91
- requiredSecrets?: string[];
92
+ requiredSecrets?: RequiredSecret[];
92
93
  /**
93
94
  * Optional secret-bind hook: forward CREATE SECRET credentials for
94
95
  * secret-backed cloud sources (S3/GCS/HTTP/…). Called during bind (only on the
@@ -140,7 +141,7 @@ export function defineCopyFromFunction<TArgs = Record<string, unknown>>(
140
141
  tags: config.tags,
141
142
  examples: config.examples,
142
143
  requiredSettings: config.requiredSettings,
143
- requiredSecrets: config.requiredSecrets,
144
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
144
145
  copyFromFormat: config.format,
145
146
  copyFromDirection: config.direction ?? "from",
146
147
  copyFromComment: config.comment ?? null,
@@ -35,6 +35,7 @@
35
35
  // arguments. The source schema rides `BindRequest.input_schema`. Mirrors
36
36
  // vgi-python's `vgi.copy_to_function.CopyToFunction`.
37
37
 
38
+ import type { RequiredSecret } from "../secrets/requirements.js";
38
39
  import { type VgiSchema, schema, type VgiBatch, type VgiDataType } from "../arrow/index.js";
39
40
  import type { BindRequest } from "../protocol/types.js";
40
41
  import type { FunctionMeta, FunctionExample } from "./types.js";
@@ -134,7 +135,7 @@ export interface CopyToFunctionConfig<TArgs = Record<string, unknown>> {
134
135
  tags?: Record<string, string>;
135
136
  examples?: FunctionExample[];
136
137
  requiredSettings?: string[];
137
- requiredSecrets?: string[];
138
+ requiredSecrets?: RequiredSecret[];
138
139
  /**
139
140
  * Optional secret-bind hook: forward CREATE SECRET credentials for
140
141
  * secret-backed cloud writes (S3/GCS/HTTP/…). Called during bind (only on the
@@ -3,6 +3,7 @@
3
3
  // Scalar functions receive columnar input and produce a single output column
4
4
  // with 1:1 row mapping.
5
5
 
6
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
6
7
  import {
7
8
  type VgiSchema,
8
9
  type VgiField,
@@ -203,7 +204,7 @@ export interface ScalarFunctionConfig<
203
204
  parameterDefaultValues?: VgiBatch | null;
204
205
  maxWorkers?: number;
205
206
  requiredSettings?: string[];
206
- requiredSecrets?: string[];
207
+ requiredSecrets?: RequiredSecret[];
207
208
  /**
208
209
  * Result-cache opt-in: when set, this CacheControl's `vgi.cache.*` metadata
209
210
  * rides every output batch's custom metadata (per-batch — NOT the schema,
@@ -331,7 +332,7 @@ export function defineScalarFunction<
331
332
  parameterDefaultValues: config.parameterDefaultValues,
332
333
  maxWorkers: config.maxWorkers,
333
334
  requiredSettings: config.requiredSettings,
334
- requiredSecrets: config.requiredSecrets,
335
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
335
336
  };
336
337
 
337
338
  // Default output schema for catalog registration.
@@ -16,6 +16,7 @@
16
16
  // The Source phase may route a finalize_state_id to a worker process that
17
17
  // did NOT run the corresponding process() calls.
18
18
 
19
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
19
20
  import {
20
21
  type VgiSchema,
21
22
  schema,
@@ -179,7 +180,7 @@ export interface TableBufferingConfig<
179
180
  tags?: Record<string, string> | undefined;
180
181
  maxWorkers?: number | undefined;
181
182
  requiredSettings?: string[] | undefined;
182
- requiredSecrets?: string[] | undefined;
183
+ requiredSecrets?: RequiredSecret[] | undefined;
183
184
  }
184
185
 
185
186
  /**
@@ -257,7 +258,7 @@ export function defineTableBufferingFunction<
257
258
  parameterDefaultValues: config.parameterDefaultValues,
258
259
  maxWorkers: config.maxWorkers,
259
260
  requiredSettings: config.requiredSettings,
260
- requiredSecrets: config.requiredSecrets,
261
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
261
262
  // The Source phase always runs (it's how output is produced), so a
262
263
  // table_buffering function always advertises has_finalize.
263
264
  hasFinalize: true,