@query-farm/vgi 0.48.3 → 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.
- package/dist/catalog/descriptors.d.ts +30 -0
- package/dist/catalog/interface.d.ts +28 -0
- package/dist/catalog/read-only.d.ts +16 -2
- package/dist/client-entry.js.map +2 -2
- package/dist/index.core.d.ts +2 -0
- package/dist/index.js +230 -34
- package/dist/index.js.map +12 -11
- package/dist/protocol/handlers/catalog/shared.d.ts +8 -0
- package/dist/serve-entry.js +43 -9
- package/dist/serve-entry.js.map +6 -6
- package/dist/worker-cf-entry.js +136 -19
- package/dist/worker-cf-entry.js.map +11 -10
- package/dist/write-results.d.ts +57 -0
- package/package.json +1 -1
- package/src/catalog/descriptors.ts +30 -0
- package/src/catalog/interface.ts +51 -0
- package/src/catalog/read-only.ts +123 -18
- package/src/index.core.ts +23 -0
- package/src/protocol/handlers/catalog/shared.ts +17 -0
- package/src/protocol/handlers/catalog/table.ts +37 -0
- package/src/protocol/handlers/function.ts +42 -14
- 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.
|
|
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)",
|
|
@@ -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", ... })]`. */
|
package/src/catalog/interface.ts
CHANGED
|
@@ -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
|
package/src/catalog/read-only.ts
CHANGED
|
@@ -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,
|
|
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
|
|
226
|
-
|
|
227
|
-
const
|
|
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
|
|
261
|
-
|
|
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
|
-
/**
|
|
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
|
|
284
|
-
return read.length
|
|
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
|
-
|
|
487
|
-
|
|
488
|
-
|
|
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,
|
|
@@ -913,6 +936,56 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
913
936
|
throw new Error(`Table '${name}' is not function-backed`);
|
|
914
937
|
}
|
|
915
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
|
+
|
|
916
989
|
override async tableGet(
|
|
917
990
|
attachOpaqueData: AttachOpaqueData,
|
|
918
991
|
schemaPath: string[],
|
|
@@ -1288,3 +1361,35 @@ function sameSpelling(left: Iterable<unknown> | string, right: Iterable<unknown>
|
|
|
1288
1361
|
const b = normalizeSchemaPath(right);
|
|
1289
1362
|
return a.length === b.length && a.every((part, i) => part === b[i]);
|
|
1290
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
|
+
}
|
package/src/index.core.ts
CHANGED
|
@@ -30,6 +30,29 @@ export {
|
|
|
30
30
|
type CacheScope,
|
|
31
31
|
} from "./cache-control.js";
|
|
32
32
|
|
|
33
|
+
// Writable tables: result modes, row ids and the write_options decoder for
|
|
34
|
+
// INSERT / UPDATE / DELETE functions (TableDescriptor.insertFunction etc.).
|
|
35
|
+
export {
|
|
36
|
+
type WriteOperation,
|
|
37
|
+
type WriteResultMode,
|
|
38
|
+
type WriteOptions,
|
|
39
|
+
WRITE_OPERATIONS,
|
|
40
|
+
WRITE_RESULT_MODES,
|
|
41
|
+
ROW_ID_METADATA_KEY,
|
|
42
|
+
rowIdField,
|
|
43
|
+
userColumns,
|
|
44
|
+
validateWriteResultModes,
|
|
45
|
+
supportsWriteResultMode,
|
|
46
|
+
coerceWriteResultMode,
|
|
47
|
+
writeResultSchema,
|
|
48
|
+
writeCountBatch,
|
|
49
|
+
writeRowsBatch,
|
|
50
|
+
writeChangesBatch,
|
|
51
|
+
writeResultBatch,
|
|
52
|
+
writeOptions,
|
|
53
|
+
} from "./write-results.js";
|
|
54
|
+
export type { ScanFunctionResultRecord } from "./catalog/interface.js";
|
|
55
|
+
|
|
33
56
|
// Function factories (primary API)
|
|
34
57
|
export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarComputeInfo, type ScalarParameterDef } from "./functions/scalar.js";
|
|
35
58
|
export { defineTableFunction, type TableFunctionConfig, type TableBindParams, type TableProcessParams } from "./functions/table.js";
|
|
@@ -128,6 +128,23 @@ export async function sealTransaction(
|
|
|
128
128
|
return sealBytes(plaintext, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION);
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
/**
|
|
132
|
+
* Open a transaction_opaque_data envelope (sealed on HTTP only, no UUID prefix).
|
|
133
|
+
* `attachEnvelope` is the request's *sealed* attach, which the transaction
|
|
134
|
+
* envelope's AAD binds. A pass-through without a signing key or for an empty
|
|
135
|
+
* value. Catalog hooks and function bodies must see the same plaintext, or a
|
|
136
|
+
* worker cannot tie a function call to its transaction's commit/rollback.
|
|
137
|
+
*/
|
|
138
|
+
export async function openTransaction(
|
|
139
|
+
envelope: Uint8Array,
|
|
140
|
+
attachEnvelope: Uint8Array,
|
|
141
|
+
auth: AuthContext | undefined,
|
|
142
|
+
signingKey: Uint8Array | undefined,
|
|
143
|
+
): Promise<Uint8Array> {
|
|
144
|
+
if (!signingKey || envelope.length === 0) return envelope;
|
|
145
|
+
return openBytes(envelope, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION, "transaction_opaque_data");
|
|
146
|
+
}
|
|
147
|
+
|
|
131
148
|
/**
|
|
132
149
|
* Unwrap the attach_opaque_data / transaction_opaque_data fields of a catalog
|
|
133
150
|
* request in place, so handler bodies always see plaintext. The transaction
|
|
@@ -162,6 +162,40 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
|
|
|
162
162
|
return wrapResult(scanResult, ScanFunctionResultSchema);
|
|
163
163
|
});
|
|
164
164
|
|
|
165
|
+
// catalog_table_{insert,update,delete}_function_get — the table in-out
|
|
166
|
+
// function backing each DML statement. A catalog whose tables inline these
|
|
167
|
+
// into TableInfo is only asked when the client skipped the inline value.
|
|
168
|
+
const optionalTx = (params: Record<string, any>): Uint8Array | undefined =>
|
|
169
|
+
params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
|
|
170
|
+
const catalogTableInsertFunctionGet = catalogHandler(signingKey, async (params) => {
|
|
171
|
+
const result = await getCatalog().tableInsertFunctionGet(
|
|
172
|
+
toUint8Array(params.attach_opaque_data),
|
|
173
|
+
params.schema_path,
|
|
174
|
+
params.name,
|
|
175
|
+
optionalTx(params),
|
|
176
|
+
params.writable_branch_function_name ?? null,
|
|
177
|
+
);
|
|
178
|
+
return wrapResult(result, ScanFunctionResultSchema);
|
|
179
|
+
});
|
|
180
|
+
const catalogTableUpdateFunctionGet = catalogHandler(signingKey, async (params) => {
|
|
181
|
+
const result = await getCatalog().tableUpdateFunctionGet(
|
|
182
|
+
toUint8Array(params.attach_opaque_data),
|
|
183
|
+
params.schema_path,
|
|
184
|
+
params.name,
|
|
185
|
+
optionalTx(params),
|
|
186
|
+
);
|
|
187
|
+
return wrapResult(result, ScanFunctionResultSchema);
|
|
188
|
+
});
|
|
189
|
+
const catalogTableDeleteFunctionGet = catalogHandler(signingKey, async (params) => {
|
|
190
|
+
const result = await getCatalog().tableDeleteFunctionGet(
|
|
191
|
+
toUint8Array(params.attach_opaque_data),
|
|
192
|
+
params.schema_path,
|
|
193
|
+
params.name,
|
|
194
|
+
optionalTx(params),
|
|
195
|
+
);
|
|
196
|
+
return wrapResult(result, ScanFunctionResultSchema);
|
|
197
|
+
});
|
|
198
|
+
|
|
165
199
|
// catalog_table_scan_branches_get — branches-aware variant of
|
|
166
200
|
// scan_function_get. The branches-aware C++ extension calls this for every
|
|
167
201
|
// table scan; single-source catalogs synthesise a one-branch result.
|
|
@@ -350,6 +384,9 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
|
|
|
350
384
|
catalogTableDrop,
|
|
351
385
|
catalogTableColumnStatisticsGet,
|
|
352
386
|
catalogTableScanFunctionGet,
|
|
387
|
+
catalogTableInsertFunctionGet,
|
|
388
|
+
catalogTableUpdateFunctionGet,
|
|
389
|
+
catalogTableDeleteFunctionGet,
|
|
353
390
|
catalogTableScanBranchesGet,
|
|
354
391
|
catalogTableCommentSet,
|
|
355
392
|
catalogTableRename,
|
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
} from "../../generated/vgi-protocol-schemas.js";
|
|
35
35
|
import { unwrapRequest, wrapResult, overloadContext } from "./shared.js";
|
|
36
36
|
import { parseCarriedInitRequest } from "../carried-init-request.js";
|
|
37
|
-
import { openAttach } from "./catalog/shared.js";
|
|
37
|
+
import { openAttach, openTransaction } from "./catalog/shared.js";
|
|
38
38
|
import { currentRequestAuth } from "../../request-auth.js";
|
|
39
39
|
import { batchFromColumns, serializeBatch } from "../../util/arrow/index.js";
|
|
40
40
|
import {
|
|
@@ -93,9 +93,18 @@ async function liveSplitAnchor(
|
|
|
93
93
|
): Promise<Uint8Array | undefined> {
|
|
94
94
|
if (!catalogInterface?.version || bindCall.attach_opaque_data == null) return undefined;
|
|
95
95
|
const raw = toUint8Array(bindCall.attach_opaque_data);
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
96
|
+
// The transaction id is likewise sealed at `plan` (HTTP) and already open at
|
|
97
|
+
// `init`; the catalog's version() takes plaintext, as its own RPC does, so
|
|
98
|
+
// open it when it opens under this attach and use it as-is otherwise. Both
|
|
99
|
+
// stages must ask the same question or mint and redemption disagree.
|
|
100
|
+
let txn = bindCall.transaction_opaque_data ? toUint8Array(bindCall.transaction_opaque_data) : undefined;
|
|
101
|
+
if (txn && txn.length > 0 && signingKey) {
|
|
102
|
+
try {
|
|
103
|
+
txn = await openTransaction(txn, raw, auth, signingKey);
|
|
104
|
+
} catch {
|
|
105
|
+
// already plaintext (init), keep it
|
|
106
|
+
}
|
|
107
|
+
}
|
|
99
108
|
|
|
100
109
|
// The two call sites see the attach envelope at DIFFERENT processing stages —
|
|
101
110
|
// `plan` receives it with the framework's 16-byte UUID prefix still attached,
|
|
@@ -212,19 +221,41 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
|
|
|
212
221
|
return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey);
|
|
213
222
|
}
|
|
214
223
|
|
|
224
|
+
// Unseal a bind call's opaque values in place, as the catalog handlers do:
|
|
225
|
+
// the transaction first (its envelope binds the *sealed* attach), then the
|
|
226
|
+
// attach. Every function-side request goes through this, so function bodies
|
|
227
|
+
// see the same transaction plaintext that transactionCommit/Rollback get.
|
|
228
|
+
async function openOpaque(
|
|
229
|
+
bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null },
|
|
230
|
+
ctx: any,
|
|
231
|
+
): Promise<void> {
|
|
232
|
+
const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
|
|
233
|
+
if (bindCall.transaction_opaque_data != null) {
|
|
234
|
+
bindCall.transaction_opaque_data = await openTransaction(
|
|
235
|
+
toUint8Array(bindCall.transaction_opaque_data),
|
|
236
|
+
sealedAttach,
|
|
237
|
+
ctx?.auth ?? currentRequestAuth(),
|
|
238
|
+
signingKey,
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
bindCall.attach_opaque_data = await stripAttach(bindCall.attach_opaque_data, ctx);
|
|
242
|
+
}
|
|
243
|
+
|
|
215
244
|
// Build an overload context whose attach has been unsealed, so catalog
|
|
216
245
|
// resolution sees the real route byte. The bind/init handlers strip their
|
|
217
246
|
// request in place and can call overloadContext directly; every other site
|
|
218
247
|
// still holds the sealed envelope (73 bytes on HTTP vs 16 plaintext), whose
|
|
219
248
|
// leading byte would otherwise route to an arbitrary catalog.
|
|
220
249
|
async function strippedContext(bindCall: any, ctx?: any) {
|
|
221
|
-
|
|
250
|
+
const copy = { ...bindCall };
|
|
222
251
|
try {
|
|
223
|
-
|
|
252
|
+
await openOpaque(copy, ctx);
|
|
224
253
|
} catch {
|
|
225
|
-
|
|
254
|
+
// Unopenable (wrong key / not sealed) — resolve unscoped.
|
|
255
|
+
copy.attach_opaque_data = null;
|
|
256
|
+
copy.transaction_opaque_data = null;
|
|
226
257
|
}
|
|
227
|
-
return overloadContext(
|
|
258
|
+
return overloadContext(copy, catalogInterface);
|
|
228
259
|
}
|
|
229
260
|
|
|
230
261
|
const emptySchema = schema([]);
|
|
@@ -243,7 +274,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
|
|
|
243
274
|
const bind: VgiService["bind"] = async (params, ctx) => {
|
|
244
275
|
const innerParams = unwrapRequest(params.request);
|
|
245
276
|
const request = deserializeBindRequest(innerParams);
|
|
246
|
-
|
|
277
|
+
await openOpaque(request, ctx);
|
|
247
278
|
const func = registry.get(request.function_name, overloadContext(request, catalogInterface));
|
|
248
279
|
const response = await func.bind(request);
|
|
249
280
|
validateProjectionOffer(response);
|
|
@@ -280,10 +311,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
|
|
|
280
311
|
// attach_opaque_data not recognized` on its first scan, i.e. this worker
|
|
281
312
|
// could not serve authenticated traffic at all.
|
|
282
313
|
const auth = ctx?.auth ?? currentRequestAuth();
|
|
283
|
-
request.bind_call
|
|
284
|
-
request.bind_call.attach_opaque_data,
|
|
285
|
-
ctx,
|
|
286
|
-
);
|
|
314
|
+
await openOpaque(request.bind_call, ctx);
|
|
287
315
|
|
|
288
316
|
// Verify and strip the split envelopes BEFORE any user code runs, so an
|
|
289
317
|
// unverified token can never be acted on.
|
|
@@ -381,7 +409,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
|
|
|
381
409
|
// a hard error here, as on the init turn: the cursor is caller-bound.)
|
|
382
410
|
// `carried.request.bind_call` is a per-call copy, so this does not
|
|
383
411
|
// disturb the memoised parse other turns share.
|
|
384
|
-
|
|
412
|
+
await openOpaque(request.bind_call, undefined);
|
|
385
413
|
// Re-derive the split payloads. The cursor carries the wire request,
|
|
386
414
|
// which has `split_tokens` but not the opened `split_payloads` — that
|
|
387
415
|
// field only ever existed in memory on the init turn. Without this a
|