|
| 1 | +# Copyright 2025, 2026 Query Farm LLC - https://query.farm |
| 2 | + |
| 3 | +"""The ``example.contract`` schema: the cross-SDK table-only / write-contract fixtures. |
| 4 | +
|
| 5 | +Every SDK's standard example worker serves the same schema, so the C++ |
| 6 | +extension's ``visibility/example_table_only.test``, |
| 7 | +``write_contract/example_insert_finalize.test`` and |
| 8 | +``write_contract/example_decimal_width.test`` run unchanged against each of them:: |
| 9 | +
|
| 10 | + good id BIGINT, label VARCHAR, row id ``rowid`` (= id); scan |
| 11 | + ``contract_good_scan`` with projection pushdown. Rows (1,a) (2,b) (3,c). |
| 12 | + ranged who VARCHAR; scan named exactly ``range`` (table_only, so the |
| 13 | + extension binds the worker's function, not DuckDB's range()). |
| 14 | + notes id BIGINT (NOT_NULL record ``notes_id_not_null``), note VARCHAR; |
| 15 | + scan ``contract_notes_scan`` (always empty) and INSERT function |
| 16 | + ``contract_notes_insert`` (count only) whose count comes from |
| 17 | + finalize only. It refuses a non-nullable input field and a NULL id. |
| 18 | + amounts id BIGINT, d32 DECIMAL(7,2) as decimal32, d64 DECIMAL(15,3) as |
| 19 | + decimal64, d128 DECIMAL(9,2) as decimal128; INSERT function |
| 20 | + ``contract_amounts_insert`` (count or rows) refuses any column not |
| 21 | + at exactly its declared Arrow type. |
| 22 | +
|
| 23 | +Nothing is stored: the insert functions validate, count and discard. Every |
| 24 | +function is table_only (no ``expose_scan``), so none is listed in |
| 25 | +``duckdb_functions()``. |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +from dataclasses import dataclass |
| 31 | +from decimal import Decimal |
| 32 | +from typing import Any, ClassVar |
| 33 | + |
| 34 | +import pyarrow as pa |
| 35 | +from vgi_rpc import ArrowSerializableDataclass |
| 36 | +from vgi_rpc.rpc import OutputCollector |
| 37 | + |
| 38 | +from vgi.catalog import Schema, Table, constraint_record |
| 39 | +from vgi.invocation import BindResponse |
| 40 | +from vgi.metadata import FunctionStability |
| 41 | +from vgi.table_function import BindParams, ProcessParams, TableFunctionGenerator, init_single_worker |
| 42 | +from vgi.table_in_out_function import TableInOutGenerator |
| 43 | +from vgi.write_results import row_id_field, write_count_batch, write_options, write_result_batch, write_result_schema |
| 44 | + |
| 45 | + |
| 46 | +def _schema(*fields: pa.Field[Any]) -> pa.Schema: |
| 47 | + return pa.schema(list(fields)) |
| 48 | + |
| 49 | + |
| 50 | +GOOD = _schema(pa.field("id", pa.int64()), pa.field("label", pa.string())) |
| 51 | +RANGED = _schema(pa.field("who", pa.string())) |
| 52 | +NOTES = _schema(pa.field("id", pa.int64(), nullable=False), pa.field("note", pa.string())) |
| 53 | +AMOUNTS = _schema( |
| 54 | + pa.field("id", pa.int64()), |
| 55 | + pa.field("d32", pa.decimal32(7, 2)), |
| 56 | + pa.field("d64", pa.decimal64(15, 3)), |
| 57 | + pa.field("d128", pa.decimal128(9, 2)), |
| 58 | +) |
| 59 | + |
| 60 | +# Counter namespace for contract_notes_insert in the execution-scoped storage. |
| 61 | +_NOTES_COUNT_NS = b"contract_notes_count" |
| 62 | + |
| 63 | + |
| 64 | +@dataclass(kw_only=True) |
| 65 | +class _Once(ArrowSerializableDataclass): |
| 66 | + done: bool = False |
| 67 | + |
| 68 | + |
| 69 | +@init_single_worker |
| 70 | +class _ContractScan(TableFunctionGenerator[None, _Once]): |
| 71 | + """A no-argument scan emitting its rows once, only the columns DuckDB asked for.""" |
| 72 | + |
| 73 | + OUTPUT: ClassVar[pa.Schema] |
| 74 | + |
| 75 | + @classmethod |
| 76 | + def rows(cls) -> list[dict[str, Any]]: |
| 77 | + """The rows to emit, keyed by column name.""" |
| 78 | + raise NotImplementedError |
| 79 | + |
| 80 | + @classmethod |
| 81 | + def on_bind(cls, params: BindParams[None]) -> BindResponse: |
| 82 | + """The table's columns.""" |
| 83 | + del params |
| 84 | + return BindResponse(output_schema=cls.OUTPUT) |
| 85 | + |
| 86 | + @classmethod |
| 87 | + def initial_state(cls, params: ProcessParams[None]) -> _Once: |
| 88 | + """Nothing emitted yet.""" |
| 89 | + del params |
| 90 | + return _Once() |
| 91 | + |
| 92 | + @classmethod |
| 93 | + def process(cls, params: ProcessParams[None], state: _Once, out: OutputCollector) -> None: |
| 94 | + """Emit the rows once (none for an empty table).""" |
| 95 | + if not state.done: |
| 96 | + state.done = True |
| 97 | + rows = cls.rows() |
| 98 | + if rows: |
| 99 | + arrays = [pa.array([row[f.name] for row in rows], type=f.type) for f in params.output_schema] |
| 100 | + out.emit(pa.RecordBatch.from_arrays(arrays, schema=params.output_schema)) |
| 101 | + out.finish() |
| 102 | + |
| 103 | + |
| 104 | +class ContractGoodScan(_ContractScan): |
| 105 | + """contract.good, with a row id equal to id.""" |
| 106 | + |
| 107 | + OUTPUT = pa.schema([*GOOD, row_id_field()]) |
| 108 | + |
| 109 | + class Meta: |
| 110 | + """Function metadata.""" |
| 111 | + |
| 112 | + name = "contract_good_scan" |
| 113 | + description = "The rows of contract.good, with rowid" |
| 114 | + stability = FunctionStability.VOLATILE |
| 115 | + # DuckDB reads `rowid` as a virtual column, which needs projection pushdown. |
| 116 | + projection_pushdown = True |
| 117 | + |
| 118 | + @classmethod |
| 119 | + def rows(cls) -> list[dict[str, Any]]: |
| 120 | + """Three fixed rows.""" |
| 121 | + return [{"id": i, "label": label, "rowid": i} for i, label in ((1, "a"), (2, "b"), (3, "c"))] |
| 122 | + |
| 123 | + |
| 124 | +class ContractRangeScan(_ContractScan): |
| 125 | + """contract.ranged: a table_only scan named like DuckDB's range().""" |
| 126 | + |
| 127 | + OUTPUT = RANGED |
| 128 | + |
| 129 | + class Meta: |
| 130 | + """Function metadata.""" |
| 131 | + |
| 132 | + name = "range" |
| 133 | + description = "The rows of contract.ranged (table_only, so it shadows nothing)" |
| 134 | + stability = FunctionStability.VOLATILE |
| 135 | + |
| 136 | + @classmethod |
| 137 | + def rows(cls) -> list[dict[str, Any]]: |
| 138 | + """One row only this worker produces.""" |
| 139 | + return [{"who": "vgi example worker"}] |
| 140 | + |
| 141 | + |
| 142 | +class ContractNotesScan(_ContractScan): |
| 143 | + """contract.notes: nothing is stored, so always empty.""" |
| 144 | + |
| 145 | + OUTPUT = NOTES |
| 146 | + |
| 147 | + class Meta: |
| 148 | + """Function metadata.""" |
| 149 | + |
| 150 | + name = "contract_notes_scan" |
| 151 | + description = "The rows of contract.notes (always empty)" |
| 152 | + stability = FunctionStability.VOLATILE |
| 153 | + |
| 154 | + @classmethod |
| 155 | + def rows(cls) -> list[dict[str, Any]]: |
| 156 | + """No rows.""" |
| 157 | + return [] |
| 158 | + |
| 159 | + |
| 160 | +class ContractNotesInsert(TableInOutGenerator[None, None]): |
| 161 | + """Backs INSERT INTO contract.notes; the row count comes from finalize only.""" |
| 162 | + |
| 163 | + class Meta: |
| 164 | + """Function metadata.""" |
| 165 | + |
| 166 | + name = "contract_notes_insert" |
| 167 | + description = "Backs INSERT INTO contract.notes, counting in finalize" |
| 168 | + stability = FunctionStability.VOLATILE |
| 169 | + has_finalize = True |
| 170 | + |
| 171 | + @classmethod |
| 172 | + def on_bind(cls, params: BindParams[None]) -> BindResponse: |
| 173 | + """Count mode only.""" |
| 174 | + return BindResponse(output_schema=write_result_schema(write_options(params).result_mode, NOTES)) |
| 175 | + |
| 176 | + @classmethod |
| 177 | + def process(cls, params: ProcessParams[None], state: None, batch: pa.RecordBatch, out: OutputCollector) -> None: |
| 178 | + """Validate the batch and count it; report nothing yet (finalize reports the count).""" |
| 179 | + del state |
| 180 | + for field in batch.schema: |
| 181 | + if not field.nullable: |
| 182 | + raise ValueError(f"contract: notes_insert input field {field.name} is non-nullable") |
| 183 | + if batch.column("id").null_count: |
| 184 | + raise ValueError("contract: notes.id required") |
| 185 | + # Execution-scoped shared storage: pooled worker processes may serve one statement. |
| 186 | + params.storage.counter_add(_NOTES_COUNT_NS, b"", batch.num_rows) |
| 187 | + out.emit(write_count_batch(0).slice(0, 0)) |
| 188 | + |
| 189 | + @classmethod |
| 190 | + def finalize(cls, params: ProcessParams[None]) -> list[pa.RecordBatch]: |
| 191 | + """The call's row count, once.""" |
| 192 | + total = params.storage.counter_get(_NOTES_COUNT_NS, b"") |
| 193 | + params.storage.counter_delete(_NOTES_COUNT_NS, b"") |
| 194 | + return [write_count_batch(total)] |
| 195 | + |
| 196 | + |
| 197 | +class ContractAmountsScan(_ContractScan): |
| 198 | + """contract.amounts: fixed rows at the declared decimal widths.""" |
| 199 | + |
| 200 | + OUTPUT = AMOUNTS |
| 201 | + |
| 202 | + class Meta: |
| 203 | + """Function metadata.""" |
| 204 | + |
| 205 | + name = "contract_amounts_scan" |
| 206 | + description = "The fixed rows of contract.amounts" |
| 207 | + stability = FunctionStability.VOLATILE |
| 208 | + |
| 209 | + @classmethod |
| 210 | + def rows(cls) -> list[dict[str, Any]]: |
| 211 | + """Three rows exercising each width's range.""" |
| 212 | + return [ |
| 213 | + {"id": 1, "d32": Decimal("12345.67"), "d64": Decimal("-123456789012.345"), "d128": Decimal("1234567.89")}, |
| 214 | + {"id": 2, "d32": Decimal("-99999.99"), "d64": Decimal("999999999999.999"), "d128": Decimal("-9999999.99")}, |
| 215 | + {"id": 3, "d32": None, "d64": Decimal("0.001"), "d128": None}, |
| 216 | + ] |
| 217 | + |
| 218 | + |
| 219 | +class ContractAmountsInsert(TableInOutGenerator[None, None]): |
| 220 | + """Backs INSERT INTO contract.amounts; refuses a column not at its declared type.""" |
| 221 | + |
| 222 | + class Meta: |
| 223 | + """Function metadata.""" |
| 224 | + |
| 225 | + name = "contract_amounts_insert" |
| 226 | + description = "Backs INSERT INTO contract.amounts, checking decimal widths" |
| 227 | + stability = FunctionStability.VOLATILE |
| 228 | + |
| 229 | + @classmethod |
| 230 | + def on_bind(cls, params: BindParams[None]) -> BindResponse: |
| 231 | + """Count or rows.""" |
| 232 | + return BindResponse(output_schema=write_result_schema(write_options(params).result_mode, AMOUNTS)) |
| 233 | + |
| 234 | + @classmethod |
| 235 | + def process(cls, params: ProcessParams[None], state: None, batch: pa.RecordBatch, out: OutputCollector) -> None: |
| 236 | + """Check every declared type arrived bit-for-bit, then report the rows.""" |
| 237 | + del state |
| 238 | + for field in AMOUNTS: |
| 239 | + got = batch.schema.field(field.name).type |
| 240 | + if got != field.type: |
| 241 | + raise ValueError(f"contract: amounts.{field.name} arrived as {got}, declared {field.type}") |
| 242 | + rows = batch.to_pylist() |
| 243 | + out.emit(write_result_batch(write_options(params).result_mode, AMOUNTS, [None] * len(rows), rows)) |
| 244 | + |
| 245 | + |
| 246 | +CONTRACT_SCHEMA = Schema( |
| 247 | + path=["contract"], |
| 248 | + functions=[], |
| 249 | + tables=[ |
| 250 | + Table(name="good", function=ContractGoodScan), |
| 251 | + Table(name="ranged", function=ContractRangeScan), |
| 252 | + Table( |
| 253 | + name="notes", |
| 254 | + function=ContractNotesScan, |
| 255 | + insert_function=ContractNotesInsert, |
| 256 | + constraints=( |
| 257 | + constraint_record( |
| 258 | + ["contract"], |
| 259 | + "notes", |
| 260 | + "notes_id_not_null", |
| 261 | + "NOT_NULL", |
| 262 | + [["id"]], |
| 263 | + enforcement="ENFORCED", |
| 264 | + validation="ALL_ROWS", |
| 265 | + ), |
| 266 | + ), |
| 267 | + ), |
| 268 | + Table( |
| 269 | + name="amounts", |
| 270 | + function=ContractAmountsScan, |
| 271 | + insert_function=ContractAmountsInsert, |
| 272 | + write_result_modes={"insert": "rows"}, |
| 273 | + ), |
| 274 | + ], |
| 275 | +) |
0 commit comments