|
| 1 | +# Copyright 2025, 2026 Query Farm LLC - https://query.farm |
| 2 | + |
| 3 | +"""Fixture ``COPY ... TO`` format writer for VGI integration tests. |
| 4 | +
|
| 5 | +``ExampleLinesCopyToFunction`` registers the SQL format ``example_lines_out`` — a |
| 6 | +toy delimited-text writer, the symmetric counterpart of the ``example_lines`` |
| 7 | +reader. It exercises the COPY-TO Sink+Combine path plus the option machinery: a |
| 8 | +required option (``null_string``), a defaulted option (``delimiter``), a BOOLEAN |
| 9 | +option (``header``), and an enum/``choices`` option (``on_exists``). |
| 10 | +
|
| 11 | +Shards are buffered in ``params.storage`` (``execution_id``-scoped) by ``write()`` |
| 12 | +and concatenated to the destination by ``close()`` — the cross-process-safe |
| 13 | +pattern, so it works under pool rotation / HTTP. |
| 14 | +
|
| 15 | +Usage:: |
| 16 | +
|
| 17 | + COPY (SELECT * FROM t) TO '/path/out.txt' (FORMAT 'acme.example_lines_out', null_string 'NA'); |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +from dataclasses import dataclass |
| 23 | +from typing import TYPE_CHECKING, Annotated, ClassVar |
| 24 | + |
| 25 | +import pyarrow as pa |
| 26 | + |
| 27 | +from vgi.arguments import Arg |
| 28 | +from vgi.copy_to_function import CopyToFunction |
| 29 | + |
| 30 | +if TYPE_CHECKING: |
| 31 | + from vgi.table_buffering_function import TableBufferingParams |
| 32 | + |
| 33 | +__all__ = ["ExampleLinesCopyToFunction", "ExampleLinesOrderedCopyToFunction"] |
| 34 | + |
| 35 | +_SHARD_NS = b"copy_to_shard" |
| 36 | + |
| 37 | + |
| 38 | +@dataclass(slots=True, frozen=True, kw_only=True) |
| 39 | +class ExampleLinesCopyToArgs: |
| 40 | + """Options for the ``example_lines_out`` COPY format.""" |
| 41 | + |
| 42 | + null_string: Annotated[str, Arg("null_string", doc="Token written for SQL NULL")] |
| 43 | + delimiter: Annotated[str, Arg("delimiter", default=",", doc="Field separator")] = "," |
| 44 | + header: Annotated[bool, Arg("header", default=False, doc="Write a header row of column names")] = False |
| 45 | + on_exists: Annotated[ |
| 46 | + str, |
| 47 | + Arg( |
| 48 | + "on_exists", |
| 49 | + default="overwrite", |
| 50 | + choices=["overwrite", "error"], |
| 51 | + doc="Behavior when the destination file already exists", |
| 52 | + ), |
| 53 | + ] = "overwrite" |
| 54 | + |
| 55 | + |
| 56 | +class ExampleLinesCopyToFunction(CopyToFunction[ExampleLinesCopyToArgs]): |
| 57 | + """Toy delimited-text ``COPY ... TO`` writer (test fixture).""" |
| 58 | + |
| 59 | + COPY_TO_FORMAT: ClassVar[str] = "example_lines_out" |
| 60 | + COPY_TO_COMMENT: ClassVar[str | None] = "Toy delimited-text writer for tests" |
| 61 | + |
| 62 | + class Meta: |
| 63 | + name = "example_lines_writer" |
| 64 | + description = "Write the COPY source to a delimited text file" |
| 65 | + categories = ["copy", "test"] |
| 66 | + tags = {"category": "copy_to", "stability": "test"} |
| 67 | + |
| 68 | + @classmethod |
| 69 | + def write( |
| 70 | + cls, |
| 71 | + *, |
| 72 | + batch: pa.RecordBatch, |
| 73 | + options: ExampleLinesCopyToArgs, |
| 74 | + file_path: str, |
| 75 | + params: TableBufferingParams[ExampleLinesCopyToArgs], |
| 76 | + ) -> None: |
| 77 | + """Buffer one input batch as an IPC blob in execution-scoped storage.""" |
| 78 | + sink = pa.BufferOutputStream() |
| 79 | + with pa.ipc.new_stream(sink, batch.schema) as writer: |
| 80 | + writer.write_batch(batch) |
| 81 | + # state_append is atomic + race-safe across parallel sink threads/workers. |
| 82 | + params.storage.state_append(_SHARD_NS, b"", sink.getvalue().to_pybytes()) |
| 83 | + |
| 84 | + @classmethod |
| 85 | + def close( |
| 86 | + cls, |
| 87 | + *, |
| 88 | + options: ExampleLinesCopyToArgs, |
| 89 | + file_path: str, |
| 90 | + params: TableBufferingParams[ExampleLinesCopyToArgs], |
| 91 | + ) -> int: |
| 92 | + """Concatenate every shard and write the delimited destination file (once).""" |
| 93 | + import os |
| 94 | + |
| 95 | + if options.on_exists == "error" and os.path.exists(file_path): |
| 96 | + raise FileExistsError(f"example_lines_out: destination already exists: {file_path}") |
| 97 | + |
| 98 | + shards = params.storage.state_log_scan(_SHARD_NS, b"", after_id=-1) |
| 99 | + |
| 100 | + def fmt(value: object) -> str: |
| 101 | + return options.null_string if value is None else str(value) |
| 102 | + |
| 103 | + rows_written = 0 |
| 104 | + with open(file_path, "w", encoding="utf-8") as fh: |
| 105 | + wrote_header = False |
| 106 | + for _log_id, blob in shards: |
| 107 | + table = pa.ipc.open_stream(blob).read_all() |
| 108 | + if options.header and not wrote_header: |
| 109 | + fh.write(options.delimiter.join(table.schema.names) + "\n") |
| 110 | + wrote_header = True |
| 111 | + for row in table.to_pylist(): |
| 112 | + fh.write(options.delimiter.join(fmt(row[name]) for name in table.schema.names) + "\n") |
| 113 | + rows_written += 1 |
| 114 | + # Empty COPY with header=true still emits the header row. We need the |
| 115 | + # source column names; they ride the bind's input_schema. |
| 116 | + if options.header and not wrote_header: |
| 117 | + assert params.init_call is not None |
| 118 | + in_schema = params.init_call.bind_call.input_schema |
| 119 | + if in_schema is not None: |
| 120 | + fh.write(options.delimiter.join(in_schema.names) + "\n") |
| 121 | + return rows_written |
| 122 | + |
| 123 | + |
| 124 | +class ExampleLinesOrderedCopyToFunction(ExampleLinesCopyToFunction): |
| 125 | + """Ordered variant of :class:`ExampleLinesCopyToFunction`. |
| 126 | +
|
| 127 | + ``Meta.ordered = True`` makes the extension use a single-threaded sink, so the |
| 128 | + worker receives every batch in source order and writes the file in order. |
| 129 | + """ |
| 130 | + |
| 131 | + COPY_TO_FORMAT: ClassVar[str] = "example_lines_ordered_out" |
| 132 | + COPY_TO_COMMENT: ClassVar[str | None] = "Toy delimited-text writer (ordered, single-thread sink)" |
| 133 | + |
| 134 | + class Meta: |
| 135 | + name = "example_lines_ordered_writer" |
| 136 | + description = "Write the COPY source to a delimited file, preserving source order" |
| 137 | + categories = ["copy", "test"] |
| 138 | + tags = {"category": "copy_to", "stability": "test"} |
| 139 | + sink_order_dependent = True # ordered COPY TO → single-thread sink |
0 commit comments