@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,121 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Static secret requirements: what a function declares in `requiredSecrets`.
3
+ //
4
+ // Each requirement becomes one FunctionInfo `required_secrets` entry
5
+ // (`{secret_type, scope, secret_name}`). At bind the client resolves every entry
6
+ // with DuckDB's secret manager and sends the matches, one struct column per
7
+ // secret, keyed by the secret's unique NAME (see `docs/protocol/vgi-secrets.md`
8
+ // in vgi-python). A requirement the SDK does not understand must never be
9
+ // dropped: the client would not be asked for the secret and the function would
10
+ // run without credentials. Anything unrecognised is a definition-time error.
11
+
12
+ /**
13
+ * A secret requirement in object form. `scope` asks the client for the secret of
14
+ * `secretType` whose scope is the longest prefix of it; `secretName` asks for one
15
+ * secret by its DuckDB name (and takes precedence over `scope`, as it does on
16
+ * the client). Neither means "a secret of this type with an empty scope".
17
+ *
18
+ * The snake_case spelling of the wire entry (`secret_type` / `secret_name`) is
19
+ * accepted too.
20
+ */
21
+ export interface SecretRequirementSpec {
22
+ secretType?: string;
23
+ scope?: string | null;
24
+ secretName?: string | null;
25
+ secret_type?: string;
26
+ secret_name?: string | null;
27
+ }
28
+
29
+ /**
30
+ * One `requiredSecrets` entry: a bare secret type (the simplest form — "a secret
31
+ * of this type"), or a {@link SecretRequirementSpec} with a scope or a name.
32
+ */
33
+ export type RequiredSecret = string | SecretRequirementSpec;
34
+
35
+ /** A validated, normalized requirement — the shape sent on the wire. */
36
+ export interface SecretRequirement {
37
+ secretType: string;
38
+ scope: string | null;
39
+ secretName: string | null;
40
+ }
41
+
42
+ const KNOWN_KEYS = new Set(["secretType", "secret_type", "scope", "secretName", "secret_name"]);
43
+
44
+ function optionalString(
45
+ value: unknown,
46
+ what: string,
47
+ where: string,
48
+ ): string | null {
49
+ if (value === undefined || value === null) return null;
50
+ if (typeof value !== "string") {
51
+ throw new TypeError(`${where}: ${what} must be a string, got ${typeof value}`);
52
+ }
53
+ return value === "" ? null : value;
54
+ }
55
+
56
+ /**
57
+ * Validate and normalize a `requiredSecrets` declaration. Throws on anything
58
+ * that is not a list of bare type strings / requirement objects, on an empty
59
+ * type, on unknown object keys (a typo such as `{ type: "s3" }` would otherwise
60
+ * declare nothing), and on conflicting camelCase/snake_case spellings.
61
+ * Duplicate requirements (same type, scope and name) are collapsed.
62
+ *
63
+ * @param value The declared `requiredSecrets` (undefined → no requirements).
64
+ * @param functionName Used in error messages.
65
+ */
66
+ export function normalizeRequiredSecrets(
67
+ value: unknown,
68
+ functionName = "<function>",
69
+ ): SecretRequirement[] {
70
+ if (value === undefined || value === null) return [];
71
+ const where = `requiredSecrets of '${functionName}'`;
72
+ if (!Array.isArray(value)) {
73
+ throw new TypeError(
74
+ `${where} must be an array of secret types or { secretType, scope?, secretName? } objects, got ${typeof value}`,
75
+ );
76
+ }
77
+ const out: SecretRequirement[] = [];
78
+ const seen = new Set<string>();
79
+ value.forEach((entry: unknown, i: number) => {
80
+ const at = `${where}[${i}]`;
81
+ let req: SecretRequirement;
82
+ if (typeof entry === "string") {
83
+ if (entry === "") throw new TypeError(`${at}: secret type must not be empty`);
84
+ req = { secretType: entry, scope: null, secretName: null };
85
+ } else if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
86
+ const obj = entry as Record<string, unknown>;
87
+ const unknown = Object.keys(obj).filter((k) => !KNOWN_KEYS.has(k));
88
+ if (unknown.length > 0) {
89
+ throw new TypeError(
90
+ `${at}: unknown key(s) ${unknown.map((k) => `'${k}'`).join(", ")}; ` +
91
+ `expected secretType, scope, secretName`,
92
+ );
93
+ }
94
+ if (obj.secretType !== undefined && obj.secret_type !== undefined && obj.secretType !== obj.secret_type) {
95
+ throw new TypeError(`${at}: secretType and secret_type disagree`);
96
+ }
97
+ if (obj.secretName !== undefined && obj.secret_name !== undefined && obj.secretName !== obj.secret_name) {
98
+ throw new TypeError(`${at}: secretName and secret_name disagree`);
99
+ }
100
+ const secretType = obj.secretType ?? obj.secret_type;
101
+ if (typeof secretType !== "string" || secretType === "") {
102
+ throw new TypeError(`${at}: secretType must be a non-empty string`);
103
+ }
104
+ req = {
105
+ secretType,
106
+ scope: optionalString(obj.scope, "scope", at),
107
+ secretName: optionalString(obj.secretName ?? obj.secret_name, "secretName", at),
108
+ };
109
+ } else {
110
+ throw new TypeError(
111
+ `${at}: expected a secret type string or a { secretType, scope?, secretName? } object, got ` +
112
+ (entry === null ? "null" : Array.isArray(entry) ? "array" : typeof entry),
113
+ );
114
+ }
115
+ const key = JSON.stringify([req.secretType, req.scope, req.secretName]);
116
+ if (seen.has(key)) return;
117
+ seen.add(key);
118
+ out.push(req);
119
+ });
120
+ return out;
121
+ }
@@ -65,6 +65,15 @@ export {
65
65
  serializeColumnStatistics,
66
66
  BindResultSchema,
67
67
  ScanFunctionResultSchema,
68
+ // Resolved-secret selection (the batch is keyed by secret NAME, not type).
69
+ secretType,
70
+ secretsOfType,
71
+ secretOfType,
72
+ requireSecretOfType,
73
+ secretByName,
74
+ secretForScope,
75
+ secretForScopeOfType,
76
+ normalizeRequiredSecrets,
68
77
  } from "./index.core.js";
69
78
  // vgi.v3 records: constraints, capabilities, column expressions, indexes, macro overloads.
70
79
  export * from "./catalog/public-codecs.js";
@@ -90,6 +99,11 @@ export type {
90
99
  TableInOutBindParams,
91
100
  ConstraintRecordSpec,
92
101
  ConstraintRecordView,
102
+ SecretFields,
103
+ SecretsDict,
104
+ RequiredSecret,
105
+ SecretRequirement,
106
+ SecretRequirementSpec,
93
107
  } from "./index.core.js";
94
108
 
95
109
  export type { ProtocolConfig } from "./protocol/dispatch.js";
@@ -0,0 +1,174 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // SPDX-License-Identifier: LicenseRef-QueryFarm-Source-Available-1.0
3
+
4
+ // Writable-table result modes shared by catalogs and write functions.
5
+ // Port of vgi-python's `vgi/write_results.py`, plus the `write_options` decoder
6
+ // its write functions use.
7
+ //
8
+ // A writable table advertises, per operation (insert / update / delete), the
9
+ // richest result mode its write function can produce. Modes are ordered
10
+ // `count < rows < changes`, and a table that supports one mode supports every
11
+ // lower one. DuckDB asks for one mode per statement, in the `write_options`
12
+ // named argument of the write function's bind:
13
+ //
14
+ // count -- plain INSERT/UPDATE/DELETE: one row, `count BIGINT NOT NULL`
15
+ // rows -- `... RETURNING`: the written rows, in the table's schema
16
+ // changes -- old/new pairs: `old STRUCT(<table>)`, `new STRUCT(<table>)`
17
+ //
18
+ // UPDATE and DELETE identify rows by the table's row-id column (the one field
19
+ // carrying `is_row_id` metadata), which the scan function must emit.
20
+
21
+ import {
22
+ type VgiBatch,
23
+ type VgiField,
24
+ type VgiSchema,
25
+ batchFromColumns,
26
+ deserializeBatch,
27
+ field,
28
+ int64,
29
+ iterRows,
30
+ schema,
31
+ struct,
32
+ } from "./arrow/index.js";
33
+ import type { BindRequest } from "./protocol/types.js";
34
+ import { toUint8Array } from "./util/bytes.js";
35
+
36
+ export type WriteOperation = "insert" | "update" | "delete";
37
+ export type WriteResultMode = "count" | "rows" | "changes";
38
+
39
+ export const WRITE_OPERATIONS: readonly WriteOperation[] = ["insert", "update", "delete"];
40
+ export const WRITE_RESULT_MODES: readonly WriteResultMode[] = ["count", "rows", "changes"];
41
+ const MODE_RANK: Record<string, number> = { count: 0, rows: 1, changes: 2 };
42
+
43
+ /** Field metadata key that marks a table's row-id column. */
44
+ export const ROW_ID_METADATA_KEY = "is_row_id";
45
+
46
+ /**
47
+ * A row-id field for a writable table's columns and its scan's output:
48
+ * `rowIdField()` is DuckDB's conventional `rowid BIGINT`.
49
+ *
50
+ * DuckDB reads the row id as a *virtual* column, which it only requests from a
51
+ * scan that supports projection pushdown. So a table with UPDATE or DELETE
52
+ * needs a scan function that (1) emits this field, (2) is declared with
53
+ * `projectionPushdown: true` and honours `params.outputSchema`, and (3) is
54
+ * listed in its schema's `functions`, which is how DuckDB learns (2). Missing
55
+ * any of these, UPDATE/DELETE fail with "Virtual columns require projection
56
+ * pushdown". Row ids must be unique and stable for the life of a statement.
57
+ */
58
+ export function rowIdField(name = "rowid", type = int64()): VgiField {
59
+ return field(name, type, false, new Map([[ROW_ID_METADATA_KEY, ""]]));
60
+ }
61
+
62
+ /** Return a validated copy of an operation -> maximum-mode mapping. */
63
+ export function validateWriteResultModes(
64
+ modes: Partial<Record<string, string>>,
65
+ ): Partial<Record<WriteOperation, WriteResultMode>> {
66
+ const out: Partial<Record<WriteOperation, WriteResultMode>> = {};
67
+ const unknown = Object.keys(modes).filter((op) => !WRITE_OPERATIONS.includes(op as WriteOperation)).sort();
68
+ if (unknown.length) throw new Error(`Unknown write operation(s): ${unknown.join(", ")}`);
69
+ for (const [operation, mode] of Object.entries(modes)) {
70
+ if (mode === undefined) continue;
71
+ if (!(mode in MODE_RANK)) throw new Error(`Unknown write result mode '${mode}' for '${operation}'`);
72
+ out[operation as WriteOperation] = mode as WriteResultMode;
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /** Whether a table whose maximum is `maximum` supports `requested`. */
78
+ export function supportsWriteResultMode(maximum: string, requested: string): boolean {
79
+ return maximum in MODE_RANK && requested in MODE_RANK && MODE_RANK[maximum]! >= MODE_RANK[requested]!;
80
+ }
81
+
82
+ /** Validate a wire value and narrow it to a `WriteResultMode`. */
83
+ export function coerceWriteResultMode(value: unknown): WriteResultMode {
84
+ if (typeof value !== "string" || !(value in MODE_RANK)) {
85
+ throw new Error(`Unknown write result mode: ${JSON.stringify(value)}`);
86
+ }
87
+ return value as WriteResultMode;
88
+ }
89
+
90
+ /**
91
+ * The table's user columns: `columns` without the row-id field. Write results
92
+ * (`rows`, and both halves of `changes`) use this schema.
93
+ */
94
+ export function userColumns(columns: VgiSchema): VgiSchema {
95
+ return schema(columns.fields.filter((f) => !f.metadata?.has(ROW_ID_METADATA_KEY)));
96
+ }
97
+
98
+ /** The exact output schema a write function must bind for `mode`. */
99
+ export function writeResultSchema(mode: WriteResultMode, tableSchema: VgiSchema): VgiSchema {
100
+ if (mode === "count") return schema([field("count", int64(), false)]);
101
+ if (mode === "rows") return tableSchema;
102
+ const rowType = struct(tableSchema.fields as VgiField[]);
103
+ return schema([field("old", rowType, true), field("new", rowType, true)]);
104
+ }
105
+
106
+ /** A `count` result batch. */
107
+ export function writeCountBatch(count: number | bigint): VgiBatch {
108
+ return batchFromColumns({ count: [BigInt(count)] }, writeResultSchema("count", schema([])));
109
+ }
110
+
111
+ /** A `rows` result batch: the written rows as plain objects keyed by column. */
112
+ export function writeRowsBatch(tableSchema: VgiSchema, rows: readonly Record<string, unknown>[]): VgiBatch {
113
+ const columns: Record<string, unknown[]> = {};
114
+ for (const f of tableSchema.fields) columns[f.name] = rows.map((r) => r[f.name] ?? null);
115
+ return batchFromColumns(columns, tableSchema);
116
+ }
117
+
118
+ /**
119
+ * A `changes` result batch, one OLD/NEW pair per written row: `old` is null
120
+ * for an insert, `new` is null for a delete.
121
+ */
122
+ export function writeChangesBatch(
123
+ tableSchema: VgiSchema,
124
+ oldRows: readonly (Record<string, unknown> | null)[],
125
+ newRows: readonly (Record<string, unknown> | null)[],
126
+ ): VgiBatch {
127
+ if (oldRows.length !== newRows.length) throw new Error("oldRows and newRows must have equal length");
128
+ const pick = (row: Record<string, unknown> | null) =>
129
+ row == null ? null : Object.fromEntries(tableSchema.fields.map((f) => [f.name, row[f.name] ?? null]));
130
+ return batchFromColumns(
131
+ { old: oldRows.map(pick), new: newRows.map(pick) },
132
+ writeResultSchema("changes", tableSchema),
133
+ );
134
+ }
135
+
136
+ /** The result batch for `mode`, from the written rows' before/after images. */
137
+ export function writeResultBatch(
138
+ mode: WriteResultMode,
139
+ tableSchema: VgiSchema,
140
+ oldRows: readonly (Record<string, unknown> | null)[],
141
+ newRows: readonly (Record<string, unknown> | null)[],
142
+ ): VgiBatch {
143
+ if (mode === "count") return writeCountBatch(newRows.length);
144
+ if (mode === "changes") return writeChangesBatch(tableSchema, oldRows, newRows);
145
+ // RETURNING shows the row as written: the new image, or the old one for a delete.
146
+ return writeRowsBatch(
147
+ tableSchema,
148
+ newRows.map((row, i) => (row ?? oldRows[i]) as Record<string, unknown>),
149
+ );
150
+ }
151
+
152
+ /** What DuckDB asked a write function for, decoded from `write_options`. */
153
+ export interface WriteOptions {
154
+ resultMode: WriteResultMode;
155
+ /** `throw` (default), or the INSERT ... ON CONFLICT action DuckDB requested. */
156
+ onConflict: string;
157
+ onConflictColumns: string[];
158
+ }
159
+
160
+ /**
161
+ * Decode the `write_options` named argument of a write function's bind (a
162
+ * serialized one-row batch). Missing options mean a plain `count` write.
163
+ */
164
+ export function writeOptions(bindCall: Pick<BindRequest, "arguments">): WriteOptions {
165
+ const out: WriteOptions = { resultMode: "count", onConflict: "throw", onConflictColumns: [] };
166
+ const raw = bindCall.arguments?.get("write_options", null);
167
+ if (raw == null) return out;
168
+ const row = [...iterRows(deserializeBatch(toUint8Array(raw)))][0] as Record<string, unknown> | undefined;
169
+ if (!row) return out;
170
+ if (row.result_mode != null) out.resultMode = coerceWriteResultMode(row.result_mode);
171
+ if (row.on_conflict != null) out.onConflict = String(row.on_conflict);
172
+ if (row.on_conflict_columns != null) out.onConflictColumns = Array.from(row.on_conflict_columns as Iterable<string>);
173
+ return out;
174
+ }