The Catalog Interface enables VGI workers to expose database-like structures to clients, supporting DuckDB's ATTACH command for external catalogs.
While VGI functions provide computational capabilities (scalar transforms, table generation), the Catalog Interface provides metadata management - exposing catalogs, schemas, tables, views, and functions as first-class database objects.
-- Attach a VGI-backed catalog in DuckDB
ATTACH 'mydb' (TYPE 'vgi', LOCATION './my-worker');
-- Query tables from the attached catalog
SELECT * FROM mydb.main.users;
-- List available schemas
SELECT * FROM information_schema.schemata WHERE catalog_name = 'mydb';Key Characteristics:
| Aspect | Functions | Catalog Interface |
|---|---|---|
| Purpose | Compute data | Manage metadata |
| Protocol | Bind → Init → Stream | vgi_rpc typed dispatch |
| Stateful | Per-invocation | Per-attachment |
| Discovery | Worker.functions list |
CatalogInterface.catalogs() |
Catalog methods are dispatched via vgi_rpc typed protocol methods. Each method has its own typed request/response defined in vgi.protocol, with automatic Arrow serialization handled by the RPC layer. This is simpler than the function protocol — no bind/init phases.
VGI protocol 2.0 represents every schema location as a SchemaPath = list[str], ordered from the outermost schema to the innermost schema. The components are raw identifiers: ["a.b"] is one schema whose name contains a dot, while ["a", "b"] is a nested schema. Implementations must preserve those boundaries and must not flatten a path to a dotted string. On the Arrow wire these values are list<utf8>.
Schema paths are non-empty and contain only non-empty strings. Every nested path must have its parent path in the catalog. Schema enumeration preserves a worker's order among peers while ensuring that parents precede children.
CatalogAttachResult.default_schema remains a single string because it selects a root-level default/search-path schema. DuckDB 1.5 adapters—including the bundled Python transactor—consume protocol 2.0 by accepting only paths of length one and rejecting deeper paths explicitly.
from vgi.catalog import AttachOpaqueData, TransactionOpaqueData, SerializedSchema, SqlExpression
from vgi import SchemaPath
AttachOpaqueData = NewType("AttachOpaqueData", bytes) # Unique attachment identifier
TransactionOpaqueData = NewType("TransactionOpaqueData", bytes) # Transaction identifier
SerializedSchema = NewType("SerializedSchema", bytes) # Arrow schema bytes
SqlExpression = NewType("SqlExpression", str) # SQL expression string
# SchemaPath is list[str]: outermost-to-innermost raw schema identifiersReturned by catalog_attach() with attachment metadata:
| Field | Type | Description |
|---|---|---|
attach_opaque_data |
AttachOpaqueData |
Opaque per-attachment state the implementation owns (see note below) |
supports_transactions |
bool |
Whether transactions are supported |
supports_time_travel |
bool |
Whether time travel queries work |
catalog_version_frozen |
bool |
Whether metadata will change |
catalog_version |
int |
Current version (increments on changes) |
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 |
default_schema |
str |
Name of the default schema (usually "main") |
attach_opaque_data/transaction_opaque_dataare opaque, implementation-owned, and may carry secrets. They are not framework identifiers — they are arbitrarybytesyour implementation returns fromcatalog_attach()/catalog_transaction_begin(), and the client round-trips them back verbatim on every subsequent call. An implementation may pack connection handles, credentials, or any state into them. Never log either value raw — treat them like theoptionsdict. The worker already enforces this for its own catalog-lifecycle logs (it short-hashes both fields at a single chokepoint), and on HTTP transport it additionally seals each value in an AEAD envelope bound to the caller's identity, so a value minted for one principal cannot be replayed by another. Your implementation only ever sees the plaintext; the sealing and unsealing happen transparently in the worker.
Client.catalog_attach(..., client_capabilities=offer) accepts the existing
vgi.protocol.ClientCapabilities record. The worker passes it to
CatalogInterface.catalog_attach as the keyword argument client_capabilities.
Custom overrides must accept this argument (usually
client_capabilities: ClientCapabilities | None = None) and forward it when
delegating to another catalog implementation. This is an SDK hook change; the
wire record and protocol version are unchanged.
The offer describes the consuming engine's native formats, companion catalogs,
streaming support, and filter encodings. None means support is unspecified.
It does not imply support for optional behavior, and the offer is not an
authorization grant. Attach-ticket redemption keeps the redeeming client's
offer rather than recording the ticket creator's capabilities.
If catalog behavior depends on the offer, retain the selected behavior in
attachment-scoped shared storage or in attach_opaque_data. Later requests may
reach another worker process. Do not put one client's agreement on the shared
catalog instance. Override catalog_contents_attach_independent = False when
metadata differs between attachments; the read-only base class otherwise
permits reuse across clients. New DuckDB 2.0 capability fields and mandatory
execution checks remain part of the combined protocol design.
Information about a schema in a catalog:
| Field | Type | Description |
|---|---|---|
attach_opaque_data |
AttachOpaqueData |
Parent attachment |
path |
SchemaPath |
Qualified schema path |
comment |
str | None |
Optional description |
tags |
dict[str, str] |
Key-value metadata |
Information about a table:
| Field | Type | Description |
|---|---|---|
name |
str |
Table name |
schema_path |
SchemaPath |
Parent schema path |
columns |
SerializedSchema |
Column definitions as Arrow schema bytes |
constraints |
list[bytes] |
Canonical ConstraintInfo records (see Constraints) |
definition_revision |
bytes | None |
Opaque table-definition revision |
comment |
str | None |
Optional description |
tags |
dict[str, str] |
Key-value metadata |
Information about a view:
| Field | Type | Description |
|---|---|---|
name |
str |
View name |
schema_path |
SchemaPath |
Parent schema path |
definition |
str |
SQL SELECT statement |
comment |
str | None |
Optional description |
tags |
dict[str, str] |
Key-value metadata |
Information about a function in a schema:
| Field | Type | Description |
|---|---|---|
name |
str |
Function name |
schema_path |
SchemaPath |
Parent schema path |
function_type |
FunctionType |
SCALAR or TABLE |
arguments |
SerializedSchema |
Argument schema as Arrow bytes |
output_schema |
SerializedSchema |
Output schema as Arrow bytes |
parameter_default_values |
pa.RecordBatch | None |
One-row typed defaults batch containing only defaulted parameters in signature order; a present null is an explicit NULL default |
argument_monotonicity |
list[ArgumentMonotonicity] | None |
Scalar-only claims aligned exactly with arguments; a vararg declaration occupies one slot |
comment |
str | None |
Optional description |
tags |
dict[str, str] |
Key-value metadata |
visibility |
str | None |
Protocol 3.3: "public" (or None) for an ordinary function, "table_only" for one listed only so a table can resolve it (see Table functions and visibility) |
Enum for filtering objects in schema_contents():
| Value | Description |
|---|---|
TABLE |
Filter to return only tables |
VIEW |
Filter to return only views |
SCALAR_FUNCTION |
Filter to return only scalar functions |
TABLE_FUNCTION |
Filter to return only table functions |
Result from table_scan_function_get() that tells the VGI DuckDB extension which DuckDB function to call to obtain table data. (On the wire it travels as the one branch of catalog_table_scan_branches_get, which the default table_scan_branches_get builds from it; protocol 3.3 removed the single-function RPC.) This enables catalogs to delegate scanning to any DuckDB function (e.g., read_parquet, iceberg_scan, or a custom VGI table function) with appropriate arguments.
| Field | Type | Description |
|---|---|---|
function_name |
str |
The DuckDB function to call (e.g., "read_parquet", "iceberg_scan") |
positional_arguments |
list[pa.Scalar] |
Positional arguments to pass to the function |
named_arguments |
dict[str, pa.Scalar] |
Named arguments to pass to the function |
required_extensions |
list[str] |
DuckDB extensions that must be loaded before calling the function |
Example usage:
def table_scan_function_get(
self,
*,
attach_opaque_data: AttachOpaqueData,
transaction_opaque_data: TransactionOpaqueData | None,
schema_path: SchemaPath,
name: str,
at_unit: str | None,
at_value: str | None,
) -> ScanFunctionResult:
# Return a parquet scan for this table
return ScanFunctionResult(
function_name="read_parquet",
positional_arguments=[pa.scalar(f"s3://bucket/{'/'.join(schema_path)}/{name}/*.parquet")],
named_arguments={"hive_partitioning": pa.scalar(True)},
required_extensions=["parquet", "httpfs"],
)The CatalogInterface abstract base class defines all catalog operations. Subclass it and implement the abstract methods.
from abc import ABC, abstractmethod
from vgi.catalog import CatalogInterface, CatalogAttachResult, SchemaInfo, TableInfo, ViewInfo
class MyCatalog(CatalogInterface):
@abstractmethod
def catalogs(self) -> Iterable[str]:
"""List available catalog names."""
@abstractmethod
def catalog_attach(self, *, name: str, options: dict[str, Any]) -> CatalogAttachResult:
"""Attach to a catalog, returning attachment metadata."""
@abstractmethod
def schema_get(self, *, attach_opaque_data: AttachOpaqueData, transaction_opaque_data: TransactionOpaqueData | None, path: SchemaPath) -> SchemaInfo | None:
"""Get schema info, or None if not found."""
@abstractmethod
def table_get(self, *, attach_opaque_data: AttachOpaqueData, transaction_opaque_data: TransactionOpaqueData | None, schema_path: SchemaPath, name: str) -> TableInfo | None:
"""Get table info, or None if not found."""
@abstractmethod
def view_get(self, *, attach_opaque_data: AttachOpaqueData, transaction_opaque_data: TransactionOpaqueData | None, schema_path: SchemaPath, name: str) -> ViewInfo | None:
"""Get view info, or None if not found."""| Category | Method | Default Behavior |
|---|---|---|
| Catalog | catalog_create() |
UnsupportedOperationError |
catalog_drop() |
UnsupportedOperationError |
|
catalog_detach() |
No-op | |
catalog_version() |
Returns 0 |
|
| Transaction | catalog_transaction_begin() |
UnsupportedOperationError |
catalog_transaction_commit() |
UnsupportedOperationError |
|
catalog_transaction_rollback() |
UnsupportedOperationError |
|
| Schema | schemas() |
Returns ["main"] |
schema_create() |
UnsupportedOperationError |
|
schema_drop() |
UnsupportedOperationError |
|
schema_contents() |
UnsupportedOperationError |
|
| Table | table_create() |
UnsupportedOperationError |
table_drop() |
UnsupportedOperationError |
|
table_rename() |
UnsupportedOperationError |
|
table_comment_set() |
UnsupportedOperationError |
|
table_column_add() |
UnsupportedOperationError |
|
table_column_drop() |
UnsupportedOperationError |
|
table_column_rename() |
UnsupportedOperationError |
|
table_column_type_change() |
UnsupportedOperationError |
|
table_column_default_set() |
UnsupportedOperationError |
|
table_column_default_drop() |
UnsupportedOperationError |
|
table_not_null_set() |
UnsupportedOperationError |
|
table_not_null_drop() |
UnsupportedOperationError |
|
table_scan_function_get() |
UnsupportedOperationError |
|
| View | view_create() |
UnsupportedOperationError |
view_drop() |
UnsupportedOperationError |
|
view_rename() |
UnsupportedOperationError |
|
view_comment_set() |
UnsupportedOperationError |
|
| Observability | loggable_attach_options() |
Returns {} (no options logged — see below) |
| Bulk load | catalog_contents() |
Composes schemas() + schema_contents() per kind; no etag (see below) |
UnsupportedOperationError (from vgi.exceptions) subclasses NotImplementedError and is
sent to the client with error code UNIMPLEMENTED.
A client normally learns a catalog lazily: catalog_schemas, then one
catalog_schema_contents_* call per schema and object kind. When the attach
result sets supports_catalog_contents (ReadOnlyCatalogInterface does), the
client may instead load everything with one catalog_contents RPC (protocol
2.1.0):
catalog_contents(attach_opaque_data: binary, if_none_match: utf8 nullable)
-> CatalogContentsResponse {
catalog_version: int64
etag: utf8 nullable -- null: the worker does not revalidate
not_modified: bool -- true: schemas is empty, keep what you have
schemas: list<struct<path: list<utf8>, schema: binary,
tables, views, scalar_functions, aggregate_functions,
table_functions, scalar_macros, table_macros,
indexes: list<binary>>> -- parents before children
}
Each struct row is one schema: path equals the SchemaInfo.path encoded in
schema, and every item is byte-identical to what the matching per-schema RPC
returns. There is no transaction parameter: it is the committed catalog at
catalog_version.
CatalogInterface.catalog_contents(*, attach_opaque_data, if_none_match=None)
returns a CatalogContentsResult(schemas, etag=None, not_modified=False). The
default composes schemas() and schema_contents() for every kind (skipping
kinds whose estimated_object_count is exactly 0) and returns no etag.
Revalidation. Return an etag to let a client revalidate a non-frozen
catalog with if_none_match instead of re-downloading it. Check it before
building, so an unchanged catalog costs almost nothing:
from vgi.catalog import CatalogContentsResult, CatalogInterface
class GenerationCatalog(CatalogInterface): # other methods omitted
generation = 1 # bumped by every DDL
def catalog_contents(self, *, attach_opaque_data, if_none_match=None):
etag = f"gen-{self.generation}"
if if_none_match == etag:
return CatalogContentsResult(etag=etag, not_modified=True) # nothing built
full = super().catalog_contents(attach_opaque_data=attach_opaque_data)
return CatalogContentsResult(schemas=full.schemas, etag=etag)The worker enforces the rules: not_modified requires an etag equal to
if_none_match and no schemas; a full answer whose etag equals
if_none_match is turned into not_modified; a catalog with no etag always
answers in full (it ignores if_none_match).
Content-hash etag. A catalog without a cheap validator can set
catalog_contents_etag = "content-hash": when it returns no etag, the worker
uses the hex SHA-256 of the serialized snapshot. The worker still builds the
snapshot on every call, but an unchanged catalog skips the transfer and the
client's decode. It is off by default, because for a non-frozen catalog the
client would revalidate with a full build on every transaction instead of a
cheap catalog_version poll.
Worker cache. When the catalog's version is frozen
(catalog_version_frozen) and its contents do not depend on the attach or the
caller (catalog_contents_attach_independent = True, the
ReadOnlyCatalogInterface default), the worker builds the response once per
catalog version and serves the same pre-serialized bytes to every call. A
ReadOnlyCatalogInterface subclass whose contents vary per caller must set
catalog_contents_attach_independent = False.
A worker declares the options its catalogs accept at ATTACH time in an AttachOptions inner class. Each option is advertised to clients at discovery (CatalogInfo.attach_option_specs), so DuckDB can cast and validate it, and frontends can render an options form.
from typing import Annotated
from vgi import Worker
from vgi.catalog.attach_option import AttachOption
class MyWorker(Worker):
class AttachOptions:
region: Annotated[str, AttachOption(desc="AWS region")] = "us-east-1"
# A credential: required, secret, and with no default.
api_key: Annotated[str, AttachOption(desc="API key", required=True, secret=True)]| Flag | Meaning |
|---|---|
required=True |
The caller must supply the option. Declare it with no class-level default; required plus a default is rejected. |
secret=True |
The option carries a credential. |
The class-level assignment is the option's default. Leaving it out makes the option optional with no
default (it is simply absent from options when the caller omits it); only required=True makes it
mandatory. The type may be written T | None (or Optional[T]) to say the value can be absent; it
resolves to T's Arrow type:
class AttachOptions:
endpoint: Annotated[str | None, AttachOption(desc="Override endpoint")] = NoneCredential 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:
ATTACH 'mydb' (TYPE vgi, LOCATION 'https://worker.example.com', api_key getenv('MYDB_API_KEY'));secret combines with required. It is allowed together with a default, but a secret option should normally have none: the default is advertised in plain text to every client at discovery.
On the wire, required and secret are nullable boolean columns appended after the four shared spec columns (name, description, type, default_value), in that order. Readers look columns up by name, so a spec from a peer that predates either column reads it as false, and older peers ignore columns they don't know.
Read options, secret ones included, with the framework accessor: params.attach_options in any
function (bind, init and process, every function kind) or vgi.catalog.attach_options(attach_opaque_data)
in a catalog hook such as catalog_transaction_commit. The worker carries the ATTACH options inside
attach_opaque_data itself, so they reach every worker process on every transport, and encrypts the
secret=True ones with a key the client never has (an HKDF subkey of the signing key on HTTP, or of a
per-user host-local key file on stdio, unix sockets and launcher pools). Never put a secret option's
value in your catalog's own attach bytes: over stdio and unix sockets those reach the client, and the
DuckDB extension, unsealed. Catalogs that need only a fingerprint can still store a digest instead, as
the ticket_probe fixture does (see Opaque values: sealing,
rule 5).
class Lookup(TableFunctionGenerator[None, None]):
@classmethod
def process(cls, params, state, out):
api_key = params.attach_options.get("api_key") # decrypted by the framework
...A ScalarFunction's compute() has no params; declare a parameter annotated with Attach()
instead. It receives the same dict ({} when the call is not through an attached catalog):
from vgi import Attach, Param, Returns, ScalarFunction
class Lookup(ScalarFunction):
@classmethod
def compute(
cls,
key: Annotated[pa.StringArray, Param(doc="Key")],
options: Annotated[dict[str, Any], Attach()],
) -> Annotated[pa.StringArray, Returns()]:
base_url = options.get("base_url", "https://api.example.com")
...On a host whose temp directory is shared or unsuitable, point VGI_ATTACH_SECRET_KEY_FILE at a
private file (all worker processes of the deployment must use the same one), or call
vgi.attach_secret_options.set_attach_secret_options_key(key) at startup.
secret does not change what the worker itself logs: attach options are never logged unless the catalog opts in through loggable_attach_options() (below), which must never return a secret option.
The worker emits structured _logger.info records and Sentry breadcrumbs for catalog lifecycle events (catalog.attach, catalog.detach, catalog.create, catalog.transaction.begin, catalog.transaction.commit, catalog.transaction.rollback). attach_opaque_data and transaction_opaque_data are short-hashed (12-char SHA-256 prefixes) before they reach the log record, the breadcrumb data, or the Sentry scope tags — the raw values never appear in observability output, since they may carry secrets. An operator correlates the short hash back to the catalog via these breadcrumbs.
The options dict passed to catalog_attach() and catalog_create() routinely carries credentials — passwords, tokens, OAuth secrets, connection strings. To avoid leaking these to logs and Sentry, the worker does not log option fields by default. Implementers opt in by overriding loggable_attach_options():
class MyCatalog(CatalogInterface):
def loggable_attach_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
# Allowlist the keys you know are safe. Never include password / token / secret.
safe_keys = {"host", "region", "bucket", "database"}
return {k: v for k, v in options.items() if k in safe_keys}When the override returns an empty mapping (the default behaviour for catalogs that haven't opted in), the options field is omitted from the lifecycle event entirely — fail-closed: nothing is preferred over partial-leak.
The catalog name, attach id, transaction id, and version specs are always logged regardless.
A convenience base class for read-only catalogs that don't support DDL operations. All modification methods raise CatalogReadOnlyError.
The simplest way to expose VGI functions as a catalog:
from vgi.catalog import ReadOnlyCatalogInterface
from vgi import ScalarFunction, TableFunctionGenerator
class MyFunctionCatalog(ReadOnlyCatalogInterface):
catalog_name = "my_funcs" # Name for ATTACH
functions = [MyScalarFunction, MyTableFunction]
# Functions appear in the "main" schema:
# SELECT * FROM my_funcs.main.my_scalar_function(args);"Read-only" means no DDL: a ReadOnlyCatalogInterface can still serve writable tables (see
Writable tables) and take part in DuckDB transactions. Override hooks rather than
catalog_attach:
| Hook | Default | Purpose |
|---|---|---|
attach_opaque_data_for(name=, options=) |
a fixed id | The bytes every function and hook of this attach receives as attach_opaque_data. |
attach_supports_transactions(name=, options=, attach_opaque_data=) |
the supports_transactions class attribute |
CatalogAttachResult.supports_transactions, decided per attach. |
catalog_transaction_begin / _commit / _rollback |
raise CatalogReadOnlyError |
Mint the transaction id; apply or discard the transaction's work. |
Functions and hooks read the ATTACH options with params.attach_options /
attach_options(attach_opaque_data) (secret options included, see
Declaring Attach Options), so most catalogs need not override
attach_opaque_data_for at all. (pack_attach_options(options, specs) remains for a catalog whose
own bytes should depend on the non-secret options; it drops secret ones.)
import os
from vgi.catalog import ReadOnlyCatalogInterface, TransactionOpaqueData, attach_options
class MyCatalog(ReadOnlyCatalogInterface):
catalog = CATALOG
def attach_supports_transactions(self, *, name, options, attach_opaque_data):
return options.get("transactional") is True
def catalog_transaction_begin(self, *, attach_opaque_data):
return TransactionOpaqueData(os.urandom(16))
def catalog_transaction_commit(self, *, attach_opaque_data, transaction_opaque_data):
token = attach_options(attach_opaque_data).get("token") # a secret option, decrypted
... # apply the work staged under transaction_opaque_data
def catalog_transaction_rollback(self, *, attach_opaque_data, transaction_opaque_data):
... # discard itDuckDB calls the transaction hooks, and passes transaction_opaque_data to functions, only on attaches
that report supports_transactions. The hooks and the functions see the same plaintext id on every
transport (over HTTP the worker seals it on the wire). Reporting transactions without overriding
catalog_transaction_begin is refused at attach.
attach_opaque_data_required follows the bytes: False for the default fixed id (re-attaching is
equivalent, so a client may attach per command), True for custom bytes. (The
TypeScript SDK's ReadOnlyCatalogInterface mints a random id per attach and so always reports True.)
vgi._test_fixtures.writable_tx (vgi-fixture-writable-tx-worker) is a complete example: per-attach
options including a secret, per-attach transactions, and an UPDATE that stages its changes in them.
Implement abstract methods for more control:
from vgi.catalog import ReadOnlyCatalogInterface, CatalogAttachResult, SchemaInfo
class MyReadOnlyCatalog(ReadOnlyCatalogInterface):
def catalogs(self) -> Iterable[str]:
return ["readonly_db"]
def catalog_attach(self, *, name: str, options: dict[str, Any]) -> CatalogAttachResult:
return CatalogAttachResult(
attach_opaque_data=AttachOpaqueData(b"fixed-id"),
supports_transactions=False,
supports_time_travel=False,
catalog_version_frozen=True,
catalog_version=1,
attach_opaque_data_required=False,
)
def schema_get(self, *, attach_opaque_data, transaction_opaque_data, path) -> SchemaInfo | None:
if path == ["main"]:
return SchemaInfo(attach_opaque_data=attach_opaque_data, path=["main"], comment=None, tags={})
return None
# table_get, view_get return None by defaultA function name is not a global key. The worker resolves a call by the pair
(schema, function name), so the same name may be declared in more than one
schema of a catalog, and a schema-qualified call reaches the implementation in
that schema:
Catalog(
name="example",
default_schema="main",
schemas=[
Schema(path=["main"], functions=[ProdLookup]), # Meta.name = "lookup"
Schema(path=["staging"], functions=[StagingLookup]), # Meta.name = "lookup"
],
)SELECT example.main.lookup(1); -- ProdLookup
SELECT example.staging.lookup(1); -- StagingLookupThe DuckDB extension carries the owning schema on every bind request
(BindRequest.schema_path), taken from the schema entry the function was
registered into. Two consequences worth knowing:
- Overloads still work. Several classes sharing a name within one schema are overloads, disambiguated by argument signature as before. Only the cross-schema case is resolved by schema.
- Callers without a schema must be unambiguous. The pure-Python
Clientand the CLI send no schema. If the name is unique across the worker they resolve normally; if two schemas declare it, the worker raises an ambiguity error naming the schemas involved.
Functions declared via the legacy Worker.functions list have no schema of
their own, so they are registered into the catalog's default_schema — the
same schema DuckDB registers them into.
Across catalogs, the key is the attachment rather than the name: two
catalogs served by one worker process (see vgi.meta_worker.MetaWorker) may
each declare main.lookup, and each attachment's attach_opaque_data routes
its calls to the right catalog.
For most use cases, the declarative catalog API provides a simpler way to define catalogs using Python dataclasses instead of implementing CatalogInterface directly.
from vgi import Worker, TableFunctionGenerator
from vgi.catalog import Catalog, Schema, Table, View, constraint_recordThe recommended pattern is to back tables with TableFunctionGenerator functions. The table schema is automatically derived from the function's output_schema, eliminating duplication:
import pyarrow as pa
from dataclasses import dataclass
from typing import ClassVar
from vgi import TableFunctionGenerator
from vgi.table_function import ProcessParams, OutputCollector
class UsersFunction(TableFunctionGenerator):
"""Generate user data."""
FIXED_SCHEMA: ClassVar[pa.Schema] = pa.schema([
pa.field("id", pa.int64()), # served NOT NULL: the PRIMARY_KEY record below names it
("name", pa.string()),
("active", pa.bool_()),
])
@classmethod
def process(cls, params, state, out: OutputCollector) -> None:
out.emit(pa.RecordBatch.from_pydict({
"id": [1, 2, 3],
"name": ["Alice", "Bob", "Carol"],
"active": [True, True, False],
}, schema=params.output_schema))
out.finish()
# Table with auto-derived schema
users_table = Table(
name="users",
function=UsersFunction, # Schema derived from FIXED_SCHEMA
constraints=( # Paths and nullability validated at definition time
constraint_record(
["main"], "users", "users.id.not_null", "NOT_NULL", [["id"]],
enforcement="ENFORCED", validation="ALL_ROWS",
),
constraint_record(
["main"], "users", "users.id.unique", "UNIQUE", [["id"]],
enforcement="ENFORCED", validation="ALL_ROWS",
),
),
comment="User accounts",
)from vgi import Worker
from vgi.catalog import Catalog, Schema, Table, View
class MyWorker(Worker):
catalog = Catalog(
name="myapp",
default_schema="main",
schemas=[
Schema(
path=["main"],
comment="Main application data",
tables=[users_table],
views=[
View(
name="active_users",
definition="SELECT * FROM users WHERE active = true",
comment="Active user accounts only",
),
],
functions=[UsersFunction],
),
Schema(
path=["analytics"],
comment="Analytics data",
tables=[events_table],
functions=[AggregateFunction],
),
],
)
if __name__ == "__main__":
MyWorker().run()| Feature | Description |
|---|---|
| No schema duplication | Function-backed tables derive schema automatically |
| Constraint validation | DuckDB's ATTACH rules for records and generated columns checked at definition time |
| Automatic scan handling | Function-backed tables don't need table_scan_function_get() |
| Type safety | Frozen dataclasses with runtime validation |
DuckDB takes a table's scan and write capabilities (projection, filter and sampling pushdown, row
ids, has_finalize, required secrets, partitioning, ordering) only from the named function's entry
in the schema's function listing. ReadOnlyCatalogInterface therefore lists every function a
Table names (function, insert_function, update_function, delete_function) whether or not
you repeat it in the schema's functions, and marks each with the protocol 3.3
FunctionInfo.visibility:
| Function | Visibility |
|---|---|
| insert, update, delete function | always "table_only" |
scan function |
"table_only", unless Table(expose_scan=True) or the class is also in a schema's functions |
anything else in a schema's functions |
public |
A "table_only" function backs its tables but is not a SQL function: it is absent from
duckdb_functions() and SELECT * FROM cat.main.items_scan() fails. To let users call a scan
directly as well, set expose_scan:
Schema(
path=["main"],
tables=[
Table(name="items", function=ItemsScan, update_function=ItemsUpdate), # items_scan hidden
Table(name="labels", function=LabelsScan, expose_scan=True), # labels_scan() callable
],
)The Python Client can still call any function by name (Client.table_function), table-only or not.
A hand-written CatalogInterface that builds its own FunctionInfo listing sets visibility
itself (FUNCTION_VISIBILITY_TABLE_ONLY from vgi.catalog) and must list every function its tables
return from table_scan_function_get / table_*_function_get.
A Table can declare insert_function, update_function and delete_function (table in-out
functions) and, in write_result_modes, the richest result each produces: count (plain DML), rows
(RETURNING) or changes (OLD/NEW pairs). DuckDB names the mode it wants in the write_options
argument; the helpers in vgi.write_results decode it and build the result:
from vgi.write_results import row_id_field, write_options, write_result_batch, write_result_schema
ITEMS = pa.schema([pa.field("id", pa.int32(), nullable=False), pa.field("qty", pa.int64())])
class ItemsUpdate(TableInOutGenerator[None, None]):
@classmethod
def on_bind(cls, params):
return BindResponse(output_schema=write_result_schema(write_options(params).result_mode, ITEMS))
@classmethod
def process(cls, params, state, batch, out):
# batch: the SET columns plus "rowid" for each updated row
old_rows, new_rows = apply(batch)
out.emit(write_result_batch(write_options(params).result_mode, ITEMS, old_rows, new_rows))UPDATE and DELETE identify rows by the row-id column, which DuckDB reads as a virtual column. The
table's scan function must therefore:
- emit a row-id column, built with
row_id_field()(rowid BIGINT, metadata keyis_row_id); - declare
projection_pushdown = Truein itsMetaand honourparams.output_schema.
Table checks both; otherwise UPDATE/DELETE would fail with DuckDB's "Virtual columns require
projection pushdown". DuckDB learns (2) from the scan's function listing, which the catalog sends for
you (see Table functions and visibility). Write results never
include the row id: write_result_schema and the batch helpers drop it (user_columns() does the same for a schema).
write_count_batch, write_rows_batch and write_changes_batch build one mode each.
For tables not backed by functions, provide the schema explicitly:
# Explicit columns - requires table_scan_function_get() implementation
config_table = Table(
name="config",
columns=pa.schema([
pa.field("key", pa.string(), nullable=False),
("value", pa.string()),
]),
constraints=(
constraint_record(
["main"], "config", "config.key.pk", "PRIMARY_KEY", [["key"]],
enforcement="ENFORCED", validation="ALL_ROWS",
),
),
)Note: Tables with explicit columns require the worker to implement table_scan_function_get() to tell DuckDB how to scan the data.
A table states its constraints as canonical records built with
constraint_record(). Each record is the worker's own attestation — the SDK
never derives one — so enforcement and validation are always explicit:
from vgi.catalog import ReferencedKey, constraint_record
constraint_record(
["main"], "orders", "orders.customer.fk", "FOREIGN_KEY", [["customer_id"]],
enforcement="ENFORCED", validation="ALL_ROWS",
references=ReferencedKey(
schema_path=["main"], table="customers", columns=[["id"]], constraint_id="customers.pk",
),
)
constraint_record(
["main"], "orders", "orders.amount.check", "CHECK", [],
enforcement="ENFORCED", validation="ALL_ROWS", check_sql="amount >= 0",
)DuckDB rejects a table at ATTACH unless its records follow the extension's
rules. Table checks them at definition time, ReadOnlyCatalogInterface checks
ownership and foreign-key targets across the catalog when it builds its
registries, and the worker checks every table again when serving it (so a
custom catalog's own unit tests and RPC calls see the same errors):
- Only
ENFORCED+ALL_ROWSrecords; state one only when every row the table can ever return satisfies it. - Each record is owned by its table and schema; ids are unique, declared names
are unique case-insensitively, and there is at most one
PRIMARY_KEY. - Column paths resolve. Only
NOT_NULLmay name a nested struct child;PRIMARY_KEY,UNIQUEandFOREIGN_KEYname top-level columns, never theis_row_idcolumn. - A
FOREIGN_KEYreferences a served table in the same schema, whosePRIMARY_KEYorUNIQUErecord has the referenced id and columns, withMATCH SIMPLEandNO_ACTION/RESTRICTactions. - A
CHECKis a single comparison between signed integer or floating-point columns and numeric constants, such asamount >= 0. The grammar is checked with DuckDB's own parser whenhaybarnorduckdbis installed.
Nullability is derived, not declared. DuckDB requires every Arrow field
(descending through ordinary structs, but not into extension or logical-type
storage) to be non-nullable exactly when a NOT_NULL or PRIMARY_KEY record
names it. The worker serves the schema that way: a non-nullable field no record
names is served nullable, and a field a record names is served non-nullable.
Arrow nullability in columns or a function's output schema is therefore never
a constraint claim, and there is nothing to keep in sync by hand.
served_table_schema() shows the schema a table is served with.
Negotiation. Records are readable only under
vgi.constraint.records.read.v1 (plus vgi.expression.duckdb.scalar.v1 for
CHECK), and DuckDB writes a constrained table only under
vgi.constraint.enforce.v1. ReadOnlyCatalogInterface advertises the read
profiles when any declared table carries records, and the enforcement profile
when such a table also has write functions: records on a writable table attest
that the write functions enforce them. A catalog that serves tables some other
way returns catalog_capabilities_for(tables, indexes) from its
catalog_capabilities() override (union it with anything else it
implements). If enforcement is not negotiated, the worker serves a constrained
table read-only and logs a warning saying why.
The legacy not_null, unique, check, primary_key and foreign_key
fields type-check only as () and raise when set; ForeignKeyDef and
ForeignKeyInfo are deprecated. Replace them with records.
DuckDB reads only VIRTUAL generated columns of type Boolean, int8–int64 or
string, with no default and no extension type, whose expression uses columns,
Boolean/integer/string literals, CAST to those types, comparisons,
AND/OR/NOT, IS [NOT] NULL, COALESCE, + - * %, ||, abs, lower
and upper. A generated column must be nullable; one no record names is
served nullable automatically, and naming it in a NOT_NULL or PRIMARY_KEY
record is an error. Legacy generated_expression field metadata is translated
to the canonical record when it is the field's only expression metadata.
Declarative catalogs include comprehensive validation:
# Error: missing columns or function
Table(name="bad") # ValueError: must specify either 'columns' or 'function'
# Error: invalid constraint column
Table(
name="users",
columns=pa.schema([pa.field("id", pa.int64(), nullable=False)]),
constraints=(
constraint_record(
["main"], "users", "nn", "NOT_NULL", [["nonexistent"]],
enforcement="ENFORCED", validation="ALL_ROWS",
), # ValueError: column path ['nonexistent'] is missing
),
)
# Error: more than one PRIMARY_KEY record
Table(
name="users",
columns=pa.schema([("id", pa.int64()), ("email", pa.string())]),
constraints=(
constraint_record(["main"], "users", "pk1", "PRIMARY_KEY", [["id"]],
enforcement="ENFORCED", validation="ALL_ROWS"),
constraint_record(["main"], "users", "pk2", "PRIMARY_KEY", [["email"]],
enforcement="ENFORCED", validation="ALL_ROWS"),
),
) # ValueError: Table 'users': more than one PRIMARY_KEY
# Error: default_schema not in schemas
Catalog(
name="myapp",
default_schema="missing",
schemas=[Schema(path=["main"])], # ValueError: default_schema 'missing' not found
)Workers with functions automatically get a ReadOnlyCatalogInterface:
from vgi import Worker, ScalarFunction
class MyWorker(Worker):
functions = [MyFunction, OtherFunction]
catalog_name = "my_catalog" # Default: "functions"
# Automatically creates ReadOnlyCatalogInterface exposing functionsSet catalog_interface for full control:
from vgi import Worker
from vgi.catalog import CatalogInterface
class MyFullCatalog(CatalogInterface):
# ... implement abstract methods
class MyWorker(Worker):
catalog_interface = MyFullCatalog
functions = [] # Optional: functions can still be registeredTo disable the catalog interface entirely:
class MyWorker(Worker):
catalog_interface = None
catalog_name = None # Required to fully disable
functions = [...]A catalog-less worker is reachable only from the pure-Python [Client][], which
binds by (schema, function name) and needs no attachment — its functions
register into the default main schema. It is not reachable from DuckDB:
ATTACH ... (TYPE vgi) requires a catalog, and there is no standalone
call form. If the worker should be usable from SQL, give it a catalog.
The CatalogClientMixin adds catalog methods to the VGI Client:
from vgi.client import Client
from vgi.client.catalog_mixin import CatalogClientMixin
class CatalogClient(CatalogClientMixin, Client):
pass
# Connect and interact with catalog
client = CatalogClient("./my-worker")
# List catalogs
catalogs = client.catalogs() # ["my_catalog"]
# Attach to a catalog
result = client.catalog_attach(name="my_catalog", options={})
attach_opaque_data = result.attach_opaque_data
# List schemas
for schema in client.schemas(attach_opaque_data=attach_opaque_data):
print(f"Schema: {schema.path}")
# Get schema contents (tables, views, functions)
for obj in client.schema_contents(attach_opaque_data=attach_opaque_data, path=["main"]):
if isinstance(obj, TableInfo):
print(f"Table: {obj.name}")
elif isinstance(obj, ViewInfo):
print(f"View: {obj.name}")
elif isinstance(obj, FunctionInfo):
print(f"Function: {obj.name}")
# Or load the whole catalog at once. Uses one catalog_contents RPC when the
# attach result advertises supports_catalog_contents, else the per-schema RPCs.
snapshot = client.load_catalog(attach=result)
for entry in snapshot.schemas:
print(entry.schema.path, [t.name for t in entry.tables])
# Later: revalidate. A not_modified answer returns the same content cheaply.
snapshot = client.load_catalog(attach=result, previous=snapshot)
# Get only scalar functions using type filter
from vgi.catalog import SchemaObjectType
for obj in client.schema_contents(
attach_opaque_data=attach_opaque_data, path=["main"], type=SchemaObjectType.SCALAR_FUNCTION
):
print(f"Scalar Function: {obj.name}")
# Detach when done
client.catalog_detach(attach_opaque_data=attach_opaque_data)| Method | Description |
|---|---|
catalogs() |
List catalog names |
catalog_attach() |
Attach to a catalog |
catalog_detach() |
Detach from a catalog |
catalog_create() |
Create a new catalog |
catalog_drop() |
Drop a catalog |
catalog_version() |
Get catalog version |
schemas() |
List schemas |
schema_get() |
Get schema info |
schema_create() |
Create a schema |
schema_drop() |
Drop a schema |
schema_contents() |
List schema contents (optional type filter) |
load_catalog() |
Load the whole catalog: one catalog_contents call when the attach advertises it, else (or on failure, or inside a transaction) catalog_schemas + the per-schema RPCs; pass previous= to revalidate with if_none_match |
contents() |
The raw catalog_contents RPC (only valid when advertised; if_none_match revalidates) |
table_get() |
Get table info |
table_create() |
Create a table |
table_drop() |
Drop a table |
table_rename() |
Rename a table |
table_comment_set() |
Set table comment |
table_column_add() |
Add a column |
table_column_drop() |
Drop a column |
table_column_rename() |
Rename a column |
table_scan_function_get() |
Get scan function |
view_get() |
Get view info |
view_create() |
Create a view |
view_drop() |
Drop a view |
view_rename() |
Rename a view |
view_comment_set() |
Set view comment |
catalog_transaction_begin() |
Begin transaction |
catalog_transaction_commit() |
Commit transaction |
catalog_transaction_rollback() |
Rollback transaction |
For stateful catalogs, VGI provides CatalogStorage for persisting attachment and transaction state across worker processes.
SQLite-backed storage with WAL mode for concurrent access:
from vgi.catalog import CatalogStorageSqlite, AttachOpaqueData
# Use default location (~/.local/state/vgi/vgi_catalog.db)
storage = CatalogStorageSqlite()
# Or specify a custom path
storage = CatalogStorageSqlite("/path/to/catalog.db")
# Store attachment
attach_opaque_data = storage.generate_attach_opaque_data()
storage.attach_put(attach_opaque_data, catalog_name="mydb", options={"key": "value"})
# Retrieve attachment
result = storage.attach_get(attach_opaque_data) # ("mydb", {"key": "value"})
# List all attachments
all_ids = storage.attach_list()
# Delete attachment
storage.attach_delete(attach_opaque_data)from typing import Protocol
from vgi.catalog import AttachOpaqueData, TransactionOpaqueData
class CatalogStorage(Protocol):
# Attachment state
def attach_put(self, attach_opaque_data: AttachOpaqueData, catalog_name: str, options: dict) -> None: ...
def attach_get(self, attach_opaque_data: AttachOpaqueData) -> tuple[str, dict] | None: ...
def attach_delete(self, attach_opaque_data: AttachOpaqueData) -> None: ...
def attach_list(self) -> list[AttachOpaqueData]: ...
# Transaction state
def transaction_put(self, transaction_opaque_data: TransactionOpaqueData, attach_opaque_data: AttachOpaqueData, state: bytes) -> None: ...
def transaction_get(self, transaction_opaque_data: TransactionOpaqueData) -> tuple[AttachOpaqueData, bytes] | None: ...
def transaction_delete(self, transaction_opaque_data: TransactionOpaqueData) -> None: ...Catalogs can optionally support transactions:
class TransactionalCatalog(CatalogInterface):
def catalog_attach(self, *, name, options) -> CatalogAttachResult:
return CatalogAttachResult(
attach_opaque_data=...,
supports_transactions=True, # Enable transactions
...
)
def catalog_transaction_begin(self, *, attach_opaque_data) -> TransactionOpaqueData:
txn_id = self._create_transaction(attach_opaque_data)
return txn_id
def catalog_transaction_commit(self, *, attach_opaque_data, transaction_opaque_data) -> None:
self._commit_transaction(transaction_opaque_data)
def catalog_transaction_rollback(self, *, attach_opaque_data, transaction_opaque_data) -> None:
self._rollback_transaction(transaction_opaque_data)Transaction Guarantees:
- Transactions MAY span multiple worker processes
- Workers MUST treat
transaction_opaque_dataas opaque bytes - Workers MUST ensure idempotency of commit/rollback
- If
supports_transactions=False, transaction methods won't be called
Errors are returned as exceptions that propagate through the VGI protocol:
| Error | When Raised |
|---|---|
ValueError |
Invalid arguments, object not found |
UnsupportedOperationError |
Method not supported |
CatalogReadOnlyError |
DDL on read-only catalog |
Example error handling:
from vgi.exceptions import CatalogReadOnlyError
class MyReadOnlyCatalog(ReadOnlyCatalogInterface):
def table_create(self, **kwargs) -> None:
# Automatically raises CatalogReadOnlyError
raise CatalogReadOnlyError("Cannot create table: catalog is read-only")from collections.abc import Iterable
from typing import Any
import uuid
from vgi import Worker
from vgi.catalog import (
AttachOpaqueData,
CatalogAttachResult,
CatalogInterface,
SchemaInfo,
TableInfo,
TransactionOpaqueData,
ViewInfo,
)
class SimpleCatalog(CatalogInterface):
"""A minimal catalog with a single schema."""
def __init__(self):
self._attachments: dict[AttachOpaqueData, str] = {}
def catalogs(self) -> Iterable[str]:
return ["simple_db"]
def catalog_attach(self, *, name: str, options: dict[str, Any]) -> CatalogAttachResult:
if name != "simple_db":
raise ValueError(f"Unknown catalog: {name}")
attach_opaque_data = AttachOpaqueData(uuid.uuid4().bytes)
self._attachments[attach_opaque_data] = name
return CatalogAttachResult(
attach_opaque_data=attach_opaque_data,
supports_transactions=False,
supports_time_travel=False,
catalog_version_frozen=True,
catalog_version=1,
attach_opaque_data_required=False,
)
def catalog_detach(self, *, attach_opaque_data: AttachOpaqueData) -> None:
self._attachments.pop(attach_opaque_data, None)
def schema_get(
self, *, attach_opaque_data: AttachOpaqueData, transaction_opaque_data: TransactionOpaqueData | None, path: SchemaPath
) -> SchemaInfo | None:
if path == ["main"]:
return SchemaInfo(
attach_opaque_data=attach_opaque_data,
path=["main"],
comment="Default schema",
tags={},
)
return None
def table_get(
self, *, attach_opaque_data: AttachOpaqueData, transaction_opaque_data: TransactionOpaqueData | None,
schema_path: SchemaPath, name: str
) -> TableInfo | None:
return None # No tables
def view_get(
self, *, attach_opaque_data: AttachOpaqueData, transaction_opaque_data: TransactionOpaqueData | None,
schema_path: SchemaPath, name: str
) -> ViewInfo | None:
return None # No views
class SimpleCatalogWorker(Worker):
catalog_interface = SimpleCatalog
functions = []
if __name__ == "__main__":
SimpleCatalogWorker().run()The current CatalogInterface has the following limitations:
- Functions: Cannot be created or dropped via catalog methods (use
Worker.functions) - Tags: Cannot be updated after object creation
- Schema metadata: Comments and tags cannot be updated on schemas
- Constraints: Only NOT NULL can be added/dropped (no ALTER for UNIQUE/CHECK)
- Constrained CREATE TABLE:
CREATE TABLEwithNOT NULL,PRIMARY KEY,UNIQUE,CHECKorFOREIGN KEYreaches a catalog only when it advertisesvgi.constraint.create.v1andvgi.constraint.enforce.v1, i.e. when itstable_create()stores the records and its write paths enforce them. The SDK ships no catalog that does (the in-memory test catalog stores no rows), so such statements are refused with an error naming the missing profile.
INSERT, UPDATE, and DELETE are supported when the catalog supplies a write
function for the operation. For declarative catalogs, configure the
[Table][vgi.catalog.descriptors.Table] descriptor:
| Operation | Descriptor field | Requirement |
|---|---|---|
INSERT |
insert_function |
A TableInOutGenerator that accepts rows to insert |
UPDATE |
update_function |
A write function and a scan function that provides row IDs |
DELETE |
delete_function |
A write function and a scan function that provides row IDs |
Each field defaults to None, which leaves that operation unsupported. Custom
catalogs implement table_insert_function_get(), table_update_function_get(),
or table_delete_function_get() to return the corresponding ScanFunctionResult.
The worker's write functions implement the changes to the backing data source;
declaring a table alone does not make it writable.
ReadOnlyCatalogInterface rejects catalog DDL, but can expose these write functions
on declarative tables. Table writes do not require the bundled
transactor; that is an optional database-access service with
additional engine requirements.
Index metadata can be declared with [Index][vgi.catalog.descriptors.Index],
building its definition with index_definition():
from vgi.catalog import Index, index_definition
Index(name="orders_customer", definition=index_definition(["main"], "orders", [["customer_id"]], algorithm="art"))ReadOnlyCatalogInterface advertises vgi.index.definition.read.v1 when any
schema declares an index. Custom catalogs can implement index_get(),
index_create(), and index_drop(); support depends on the catalog
implementation and backing data source.
vgi.v3 added keyword arguments to several CatalogInterface methods
(catalog_attach(client_capabilities=), schema_create(options=),
view_create(aliases=, security=, comment=, tags=, column_comments=),
table_create(constraint_definitions=, ...)) and renamed column_name to
column_path. The worker inspects an override's signature and passes only
what it accepts, emitting a DeprecationWarning (and one log line) when it
drops an argument. It drops one only when the value carries nothing the old
override could have honoured (None, empty, a top-level column path); a
barrier view, schema options or a nested column path fail with an error naming
the parameter instead of being silently ignored. Update overrides to the
current signatures, or accept **kwargs.
- Function Lifecycle - Function execution phases
- Function Metadata - Function introspection