Skip to content

Commit 894fcc0

Browse files
rustyconoverclaude
andcommitted
Writable tables and transactions on a descriptor catalog, with public API
A worker ported from TypeScript (an UPDATE-able table whose changes are staged in DuckDB transactions) needed private fixture code and dataclasses.replace on the attach result. Each gap now has a public, documented API: - vgi.write_results: write_options() decodes the write_options argument (WriteOptions: result_mode, on_conflict, on_conflict_columns) from BindParams, ProcessParams or a BindRequest; row_id_field(), ROW_ID_METADATA_KEY, is_row_id_field(), row_id_column() and user_columns() for the row-id column; write_count_batch(), write_rows_batch() and write_result_batch() alongside write_changes_batch(). write_result_schema() and the batch helpers drop the row-id column, which never belongs in a write result (it used to leak into "rows" when given a table's columns). - Table rejects an update/delete function whose scan has no row-id column or lacks projection_pushdown, and Catalog rejects one whose scan is not listed in the table's schema functions, instead of DuckDB's opaque "Virtual columns require projection pushdown" at UPDATE time. Documented on Table. - ReadOnlyCatalogInterface: attach_opaque_data_for() and attach_supports_transactions() hooks decide the attach bytes and supports_transactions per ATTACH; overriding catalog_transaction_* is the documented way to add transactions (an attach that reports them without a begin hook is refused). attach_opaque_data_required now follows the bytes: False for the fixed default id (re-attaching is equivalent), True for custom bytes. - pack_attach_options()/unpack_attach_options() carry ATTACH options to every function and hook. Secret options never enter the bytes (sealing rule 5): they are kept in the shared function storage under a random handle. - Attach options may be typed `T | None` / Optional[T]; the AttachOption docstring no longer claims that omitting the default makes an option required (only required=True does). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f47160e commit 894fcc0

11 files changed

Lines changed: 1179 additions & 31 deletions

‎docs/catalog-interface.md‎

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ Returned by `catalog_attach()` with attachment metadata:
6565
| `supports_time_travel` | `bool` | Whether time travel queries work |
6666
| `catalog_version_frozen` | `bool` | Whether metadata will change |
6767
| `catalog_version` | `int` | Current version (increments on changes) |
68-
| `attach_opaque_data_required` | `bool` | Whether attach_opaque_data must be persisted |
68+
| `attach_opaque_data_required` | `bool` | `True`: the bytes name per-attach state, so the client must keep them. `False`: re-attaching yields an equivalent attach, so a client may attach per command |
6969
| `default_schema` | `str` | Name of the default schema (usually "main") |
7070

7171
> **`attach_opaque_data` / `transaction_opaque_data` are opaque, implementation-owned, and may carry secrets.**
@@ -367,6 +367,16 @@ class MyWorker(Worker):
367367
| `required=True` | The caller must supply the option. Declare it with no class-level default; `required` plus a default is rejected. |
368368
| `secret=True` | The option carries a credential. |
369369

370+
The class-level assignment is the option's default. Leaving it out makes the option optional with no
371+
default (it is simply absent from `options` when the caller omits it); only `required=True` makes it
372+
mandatory. The type may be written `T | None` (or `Optional[T]`) to say the value can be absent; it
373+
resolves to `T`'s Arrow type:
374+
375+
```python test="skip"
376+
class AttachOptions:
377+
endpoint: Annotated[str | None, AttachOption(desc="Override endpoint")] = None
378+
```
379+
370380
**Credential options (API keys, tokens, passwords) MUST be declared `secret=True`.** The caller passes them inline as attach options. Clients mask secret options, and the DuckDB extension redacts them from `duckdb_databases()`, keeps only a salted hash of them in its result-cache key, and never logs them. To keep a credential out of the SQL text (shell history, scripts, shared links), write the option as an expression:
371381

372382
```sql
@@ -423,6 +433,60 @@ class MyFunctionCatalog(ReadOnlyCatalogInterface):
423433
# SELECT * FROM my_funcs.main.my_scalar_function(args);
424434
```
425435

436+
### Per-attach options and transactions
437+
438+
"Read-only" means no DDL: a `ReadOnlyCatalogInterface` can still serve writable tables (see
439+
[Writable tables](#writable-tables)) and take part in DuckDB transactions. Override hooks rather than
440+
`catalog_attach`:
441+
442+
| Hook | Default | Purpose |
443+
|------|---------|---------|
444+
| `attach_opaque_data_for(name=, options=)` | a fixed id | The bytes every function and hook of this attach receives as `attach_opaque_data`. |
445+
| `attach_supports_transactions(name=, options=, attach_opaque_data=)` | the `supports_transactions` class attribute | `CatalogAttachResult.supports_transactions`, decided per attach. |
446+
| `catalog_transaction_begin` / `_commit` / `_rollback` | raise `CatalogReadOnlyError` | Mint the transaction id; apply or discard the transaction's work. |
447+
448+
`pack_attach_options(options, specs)` turns the ATTACH options into attach bytes and
449+
`unpack_attach_options(params.attach_opaque_data)` reads them back in any function or hook, in any
450+
worker process. Options declared `secret=True` never enter the bytes: they are kept in the shared
451+
function storage (`VGI_WORKER_SHARED_STORAGE`) under a random handle, so pass the specs.
452+
453+
```python test="skip"
454+
import os
455+
from vgi.catalog import (
456+
ReadOnlyCatalogInterface, TransactionOpaqueData, pack_attach_options, unpack_attach_options,
457+
)
458+
459+
class MyCatalog(ReadOnlyCatalogInterface):
460+
catalog = CATALOG
461+
462+
def attach_opaque_data_for(self, *, name, options):
463+
return pack_attach_options(options, self.attach_option_specs)
464+
465+
def attach_supports_transactions(self, *, name, options, attach_opaque_data):
466+
return unpack_attach_options(attach_opaque_data).get("transactional") is True
467+
468+
def catalog_transaction_begin(self, *, attach_opaque_data):
469+
return TransactionOpaqueData(os.urandom(16))
470+
471+
def catalog_transaction_commit(self, *, attach_opaque_data, transaction_opaque_data):
472+
... # apply the work staged under transaction_opaque_data
473+
474+
def catalog_transaction_rollback(self, *, attach_opaque_data, transaction_opaque_data):
475+
... # discard it
476+
```
477+
478+
DuckDB calls the transaction hooks, and passes `transaction_opaque_data` to functions, only on attaches
479+
that report `supports_transactions`. The hooks and the functions see the same plaintext id on every
480+
transport (over HTTP the worker seals it on the wire). Reporting transactions without overriding
481+
`catalog_transaction_begin` is refused at attach.
482+
483+
`attach_opaque_data_required` follows the bytes: `False` for the default fixed id (re-attaching is
484+
equivalent, so a client may attach per command), `True` for custom bytes. (The
485+
TypeScript SDK's `ReadOnlyCatalogInterface` mints a random id per attach and so always reports `True`.)
486+
487+
`vgi._test_fixtures.writable_tx` (`vgi-fixture-writable-tx-worker`) is a complete example: per-attach
488+
options including a secret, per-attach transactions, and an UPDATE that stages its changes in them.
489+
426490
### Usage Option 2: Custom Read-Only Catalog
427491

428492
Implement abstract methods for more control:
@@ -604,6 +668,42 @@ if __name__ == "__main__":
604668
| **Automatic scan handling** | Function-backed tables don't need `table_scan_function_get()` |
605669
| **Type safety** | Frozen dataclasses with runtime validation |
606670

671+
### Writable tables
672+
673+
A `Table` can declare `insert_function`, `update_function` and `delete_function` (table in-out
674+
functions) and, in `write_result_modes`, the richest result each produces: `count` (plain DML), `rows`
675+
(`RETURNING`) or `changes` (OLD/NEW pairs). DuckDB names the mode it wants in the `write_options`
676+
argument; the helpers in `vgi.write_results` decode it and build the result:
677+
678+
```python test="skip"
679+
from vgi.write_results import row_id_field, write_options, write_result_batch, write_result_schema
680+
681+
ITEMS = pa.schema([pa.field("id", pa.int32(), nullable=False), pa.field("qty", pa.int64())])
682+
683+
class ItemsUpdate(TableInOutGenerator[None, None]):
684+
@classmethod
685+
def on_bind(cls, params):
686+
return BindResponse(output_schema=write_result_schema(write_options(params).result_mode, ITEMS))
687+
688+
@classmethod
689+
def process(cls, params, state, batch, out):
690+
# batch: the SET columns plus "rowid" for each updated row
691+
old_rows, new_rows = apply(batch)
692+
out.emit(write_result_batch(write_options(params).result_mode, ITEMS, old_rows, new_rows))
693+
```
694+
695+
UPDATE and DELETE identify rows by the row-id column, which DuckDB reads as a *virtual* column. The
696+
table's scan `function` must therefore:
697+
698+
1. emit a row-id column, built with `row_id_field()` (`rowid BIGINT`, metadata key `is_row_id`);
699+
2. declare `projection_pushdown = True` in its `Meta` and honour `params.output_schema`;
700+
3. be listed in the `functions` of the table's `Schema`, which is how DuckDB learns (2).
701+
702+
`Table` checks (1) and (2), `Catalog` checks (3); otherwise UPDATE/DELETE would fail with DuckDB's
703+
"Virtual columns require projection pushdown". Write results never include the row id:
704+
`write_result_schema` and the batch helpers drop it (`user_columns()` does the same for a schema).
705+
`write_count_batch`, `write_rows_batch` and `write_changes_batch` build one mode each.
706+
607707
### Tables with Explicit Columns
608708

609709
For tables not backed by functions, provide the schema explicitly:

0 commit comments

Comments
 (0)