From a4acd3a8172a6a3179724956b55368aca18b7755 Mon Sep 17 00:00:00 2001 From: nickyoung-github Date: Sun, 29 Nov 2026 22:07:26 +0000 Subject: [PATCH] Hold the Rust structs in Arrow tables, by arrow-rs: as ARROW_FORMAT.md has it --- ARROW_FORMAT.md | 16 +- DESIGN.md | 20 +- README.md | 31 +- src/dataclass_native/backends/pyo3.py | 42 +- src/dataclass_native/backends/rust.py | 50 +- src/dataclass_native/rust/Cargo.toml | 12 +- src/dataclass_native/rust/src/arrow.rs | 1510 +++++++++++++++++++++++ src/dataclass_native/rust/src/lib.rs | 22 + src/dataclass_native/rust/src/python.rs | 117 ++ tests/performance.py | 2 +- tests/test_pyo3.py | 10 +- tests/test_rust.py | 55 +- 12 files changed, 1854 insertions(+), 33 deletions(-) create mode 100644 src/dataclass_native/rust/src/arrow.rs diff --git a/ARROW_FORMAT.md b/ARROW_FORMAT.md index 2b28436..1486ca9 100644 --- a/ARROW_FORMAT.md +++ b/ARROW_FORMAT.md @@ -1,8 +1,9 @@ # dataclass-native: Arrow and Parquet layout How objects of a `@native` class are held in [Arrow](https://arrow.apache.org/docs/format/Columnar.html) tables, -and in the Parquet files of those tables. There are two implementations, in Python and in C++. The Python one -is the reference: where this document and it disagree, one of them has a bug. +and in the Parquet files of those tables. There are three implementations, in Python, in C++ and in Rust. The +Python one is the reference: where this document and it disagree, one of them has a bug. What is asked of them is +that each reads the tables which any of them makes. The objects of a class are a table: a row for each object, and a column for each field. A reader is given the class it is to read. @@ -122,6 +123,17 @@ library imports and exports without copying. It needs no Arrow library itself. list: from Python, such tables are read by the Python implementation instead. - It does not check that the tables it is given are valid Arrow. +## In Rust + +The crate's `arrow`, with its feature of that name, builds and reads the tables as the arrays of +[arrow-rs](https://github.com/apache/arrow-rs): so they are what the rest of Rust's Arrow takes, as its Parquet. + +- What it builds is as above, with every member's name in an enum's dictionary, in the order of the members, as + C++ builds. +- It reads what C++ reads, and not the variations which the Python implementation allows: from Python, such + tables are read by the Python implementation instead. +- With Python it exchanges them as the Arrow PyCapsule interface has them, without copying. + ## Not decided - Holding a class which holds itself, as rows which refer to rows of its own table. diff --git a/DESIGN.md b/DESIGN.md index 2856154..5edff53 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -277,7 +277,21 @@ the structs, by [pyo3](https://pyo3.rs), as nanobind does in those of C++. its members reads it. serde_json is given a formatter which writes a float as Python does, so the text is that of Python and C++, though it need not be. What is rejected is said as serde says it. -Not yet in Rust, so done by Python for what is held in it: Arrow. +- Arrow is by [arrow-rs](https://github.com/apache/arrow-rs), with the crate's feature `arrow`: of its crates + for arrays alone, not of all of it, and of one major version, 59, as the arrays of two do not mix in a + program. So what is made is a `RecordBatch`, which the rest of Rust's Arrow takes. The generated code says + what each struct, enum and union is by the crate's macros `arrow_struct!`, `arrow_enum!` and `arrow_union!`, + which are of nothing without the feature. Each type has a builder of its column, and a reader of one, of its + own type: so nothing is found by name or cast as each row is held, or read. +- What an object shares is given its row before it is held, by first going through what it shares: so that the + rows of each table are in the order in which Python has them, though the table of each class is built whole. +- An extension holds its classes in Arrow only if its crate has a feature `arrow`, and is built with it: as + arrow-rs is much to build, and Python holds them otherwise. Tables go to and from Python as the capsules of + the Arrow PyCapsule interface, which the extension makes itself, as that of C++ does: not by a crate which + is tied to a version of pyo3. +- Two faults of arrow-rs are worked around, where tables go to and from Python: it does not say that the keys of + a map which is a field are in order, and it takes the rows of a struct within a struct twice, where the outer + is some of the rows of another, as when a table has been sliced. ## Python runtime @@ -439,8 +453,8 @@ what an object is made from, before the native class checks it. depends on nothing; and Python's objects stored in the structs, as they are in those of C++, by an extension generated for pyo3, with arrays which share their numbers with numpy; and functions written in Rust, called as those of C++ are, and fields read and set by descriptors of the extension's own, as those of - C++ are; and msgpack, and JSON by serde. To come: Arrow in Rust, which Python does until then; and an - example built with maturin. + C++ are; and msgpack, JSON by serde, and Arrow by arrow-rs. To come: Parquet from Rust alone, which + arrow-rs has; and an example built with maturin. 6. **Done:** classes which are not frozen, whose fields may be set, held by reference, and whose arrays may be written to. To come: lists. 7. JSON. The aim is that pydantic's `TypeAdapter` reads what this writes, and this reads what it writes: not that diff --git a/README.md b/README.md index a5c33c3..cd4772a 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,16 @@ let trade: Trade = from_json(&data)?; `serde_json::to_string(&trade)` writes the same, but for the exponent of a float, which it has as `1e-5` where Python has `1e-05`: either is read. The crate depends on nothing without the feature. +With its feature `arrow` they are held in Arrow tables, as [ARROW_FORMAT.md](ARROW_FORMAT.md) has it, by +[arrow-rs](https://github.com/apache/arrow-rs): of version 59, as the arrays of two versions do not mix. + +```rust +use dataclass_native::arrow::{from_arrow, to_arrow}; + +let tables = to_arrow(&trades)?; // tables.root is a RecordBatch, and tables.shared one for each class shared +let trades: Vec = from_arrow(&tables)?; +``` + To store Python's objects in them, as in the structs of C++ below, generate for [pyo3](https://pyo3.rs) instead, which also writes `src/my_schemas_native.rs`: @@ -186,8 +196,9 @@ fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> { Built as an extension module (`crate-type = ["cdylib"]`) and placed in the package as `_native`, the classes of `my_schemas` are then bound to the Rust structs as they would be to those of C++. Rust writes and reads them -as msgpack and as JSON: Arrow Python does for it, until Rust has its own. An example built with maturin is to -come. +as msgpack and as JSON. It holds them in Arrow tables too if the extension's crate has a feature `arrow`, which is +`["dataclass_native/arrow"]`, and is built with it: else Python does, as arrow-rs is much to build. An example +built with maturin is to come. ## Storing Python objects in the structs @@ -405,14 +416,14 @@ here is of two customers, each with two addresses: 15 values, in 7 objects. Arro | Microseconds, for each `Order`, to | `pure` | C++ | Rust | |---|---:|---:|---:| | Write msgpack | 8.9 | 1.9 | 1.8 | -| Read msgpack | 24.4 | 2.6 | 2.8 | -| Write JSON | 10.7 | 2.3 | 2.1 | -| Read JSON | 13.6 | 3.1 | 2.8 | -| Write Arrow | 11.2 | 0.4 | 16.2 | -| Read Arrow | 9.3 | 0.7 | 14.3 | - -C++ writes and reads the structs itself, as Rust does msgpack and JSON. Arrow Rust does not yet, so Python -does, reading each field from the struct: which is slower than `pure`, until Rust has its own. +| Read msgpack | 24.5 | 2.6 | 2.8 | +| Write JSON | 10.7 | 2.3 | 2.0 | +| Read JSON | 13.8 | 3.2 | 2.7 | +| Write Arrow | 11.5 | 0.4 | 0.3 | +| Read Arrow | 9.4 | 0.8 | 0.7 | + +C++ and Rust write and read the structs themselves: Rust's Arrow with the feature `arrow` of its crate, without +which Python does it, reading each field from the struct, which is slower than `pure`. ## Examples diff --git a/src/dataclass_native/backends/pyo3.py b/src/dataclass_native/backends/pyo3.py index 0b7be07..e932491 100644 --- a/src/dataclass_native/backends/pyo3.py +++ b/src/dataclass_native/backends/pyo3.py @@ -13,7 +13,7 @@ from collections import defaultdict from .. import schema as s -from .cpp import in_json +from .cpp import in_arrow, in_json from .rust import KEYWORDS, RUNTIME, _ModuleGenerator, identifier from .rust import generate as generate_structs @@ -64,12 +64,14 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: f"// Generated by dataclass-native from {package}: do not edit\n" f"//! The classes which hold Python's objects of {package} in the structs generated for it. `register` adds\n" f"//! them to an extension module, which is to be {package}._native\n" - "#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, clippy::all)]\n\n" + "#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unexpected_cfgs, clippy::all)]\n\n" f"use {RUNTIME}::python::{{\n" " from_json, from_msgpack, maker, member, to_json, to_msgpack, Changing, Fields, Frozen, Held, Native,\n" " Told,\n" "};\n" f"use {RUNTIME}::Mutable;\n" + '#[cfg(feature = "arrow")]\n' + f"use {RUNTIME}::python::{{from_arrow, to_arrow}};\n" "use pyo3::exceptions::PyTypeError;\n" "use pyo3::prelude::*;\n" "use pyo3::types::{PyBytes, PyDict, PyModule};\n" @@ -87,7 +89,9 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: for name, (variants, members) in generator.unions.items(): parts.append(_union(_plain(module.name, name), variants, members)) for struct in module.structs: - parts.append(_struct(struct, in_json(schema, struct.ref))) + parts.append( + _struct(struct, in_json(schema, struct.ref), in_arrow(schema, struct)) + ) added.append(_class(struct.module, struct.name)) hashes.append((struct.name, s.schema_hash(struct))) structs.append((struct.name, added[-1])) @@ -206,7 +210,7 @@ def _union(plain: str, variants: list[str], members: tuple[s.Type, ...]) -> str: ) -def _struct(struct: s.Struct, in_json: bool) -> str: +def _struct(struct: s.Struct, in_json: bool, in_arrow: bool) -> str: plain, name = _plain(struct.module, struct.name), _class(struct.module, struct.name) if struct.mutable: held, trait, read, written = ( @@ -273,6 +277,35 @@ def _struct(struct: s.Struct, in_json: bool) -> str: if in_json else "" ) + # Not if it, or a struct it may share, holds itself: and only with the feature arrow, of the crate it is in + rows = ( + " let held: Vec<_> = objects.iter().map(|object| object.0.read()).collect();\n" + " to_arrow(py, held.iter().map(|held| &**held))\n" + if struct.mutable + else " to_arrow(py, objects.iter().map(|object| &*object.0))\n" + ) + arrow = ( + ( + " /// As Arrow tables, and those which tables hold: by arrow-rs, as the crate's arrow has it\n" + ' #[cfg(feature = "arrow")]\n' + " #[staticmethod]\n" + " fn __arrow__<'py>(py: Python<'py>, objects: Vec>) -> PyResult> {\n" + f"{rows}" + " }\n\n" + ' #[cfg(feature = "arrow")]\n' + " #[staticmethod]\n" + " fn __from_arrow__(\n" + " schema: &Bound<'_, PyAny>,\n" + " array: &Bound<'_, PyAny>,\n" + " shared: &Bound<'_, PyDict>,\n" + " ) -> PyResult>> {\n" + f" let read: Option> = from_arrow(schema, array, shared)?;\n" + f" Ok(read.map(|read| read.into_iter().map(|held| Self({held.partition('<')[0]}::new(held))).collect()))\n" + " }\n\n" + ) + if in_arrow + else "" + ) write = ( "" if struct.mutable @@ -322,6 +355,7 @@ def _struct(struct: s.Struct, in_json: bool) -> str: f" Ok(Self({held.partition('<')[0]}::new(from_msgpack(data)?)))\n" " }\n\n" f"{json}" + f"{arrow}" " /// As what it holds is: so that one made anew for the same struct is found to be of it\n" " fn __hash__(&self) -> usize {\n" " self.0.address()\n" diff --git a/src/dataclass_native/backends/rust.py b/src/dataclass_native/backends/rust.py index 5ebcb21..22f1adc 100644 --- a/src/dataclass_native/backends/rust.py +++ b/src/dataclass_native/backends/rust.py @@ -14,10 +14,11 @@ from typing import Any from .. import schema as s +from .._arrow import _member_names from .._wire import _reaches from ..introspect import _tag from ..schema import SchemaError -from .cpp import in_json +from .cpp import in_arrow, in_json, shared_structs RUNTIME = "dataclass_native" @@ -499,6 +500,8 @@ def __init__(self, schema: s.Schema, module: s.Module): # The enums which unions are, in the order met: by name, their source self.__unions: dict[str, str] = {} self.unions: dict[str, tuple[list[str], tuple[s.Type, ...]]] = {} + # Whether the struct whose fields are being typed may be held in Arrow + self.__arrow = False """Of each, what its members are named and what they are: once generate() has been called""" def generate(self) -> str: @@ -546,16 +549,26 @@ def __enum(self, enum: s.Enum) -> str: f" _ => Err({WIRE}::Fault::Mismatch),\n" " }\n" " }\n" - "}\n\n" + _json_enum(enum, name) + "}\n\n" + + _json_enum(enum, name) + + "\n" + + f"{RUNTIME}::arrow_enum!({name} {{ " + + ", ".join(f"{member} = {text}" for member, text in names) + + " });\n" ) def __struct(self, struct: s.Struct) -> str: name = identifier(struct.name) - fields, defaults = [], [] - for f in struct.fields: + # Not if it, or a struct it may share, holds itself: nor then are the unions of its fields + self.__arrow = in_arrow(self.__schema, struct) + fields, defaults, columns = [], [], [] + for index, f in enumerate(struct.fields): where = f"{struct.name}.{f.name}" typ = self.type(f.type, _pascal(struct.name) + _pascal(f.name)) fields.append(f" pub {identifier(f.name)}: {typ},\n") + columns.append( + f" {index}: {identifier(f.name)}: {typ} = {_string(f.name)}, {_bool(f.has_default)};\n" + ) value = ( self.value( f.type, f.default, where, _pascal(struct.name) + _pascal(f.name) @@ -631,6 +644,18 @@ def __struct(self, struct: s.Struct) -> str: if in_json(self.__schema, struct.ref) else "" ) + + (self.__arrow_struct(struct, name, columns) if self.__arrow else "") + ) + + def __arrow_struct(self, struct: s.Struct, name: str, columns: list[str]) -> str: + """How a struct is held in Arrow: as the crate's macro makes of its fields, and of the classes it may share""" + shared = shared_structs(self.__schema, struct.ref, [], set()) + return ( + f"\n{RUNTIME}::arrow_struct!(\n" + f" {name}, {_string(struct.tag)}, {_bool(_reaches(struct.ref, set()))}, " + f"[{', '.join(self.__path(ref.module, ref.name) for ref in shared)}], {{\n" + f"{''.join(columns)}" + "}\n);\n" ) def __path(self, module: str, name: str) -> str: @@ -722,9 +747,26 @@ def __union(self, t: s.Union, members: tuple[s.Type, ...], name: str) -> str: if in_json(self.__schema, t) else "" ) + + ( + self.__arrow_union(t, members, name, variants) + if self.__arrow + else "" + ) ) return name + def __arrow_union( + self, t: s.Union, members: tuple[s.Type, ...], name: str, variants: list[str] + ) -> str: + """How a union is held in Arrow: a field for each member, by the name which Arrow has for it""" + columns = "".join( + f" {index}: {variant}({self.type(member, name + variant)}) = {_string(field)};\n" + for index, (variant, member, field) in enumerate( + zip(variants, members, _member_names(members), strict=True) + ) + ) + return f"\n{RUNTIME}::arrow_union!({name}, {_bool(_reaches(t, set()))}, {{\n{columns}}});\n" + def value(self, t: s.Type, v: Any, where: str, union: str) -> str: """A Rust expression of type t, for the Python value v""" match t: diff --git a/src/dataclass_native/rust/Cargo.toml b/src/dataclass_native/rust/Cargo.toml index c3cd80f..ccc7555 100644 --- a/src/dataclass_native/rust/Cargo.toml +++ b/src/dataclass_native/rust/Cargo.toml @@ -1,5 +1,5 @@ # The types used by the Rust which dataclass-native generates. A crate to depend on by path, which -# `dataclass-native rust-dir` prints: it depends on nothing itself, but for its features json and python. +# `dataclass-native rust-dir` prints: it depends on nothing itself, but for its features arrow, json and python. [package] name = "dataclass_native" version = "0.0.0" @@ -11,13 +11,19 @@ publish = false [lib] path = "src/lib.rs" -# With json, the generated structs are serde's, by which they are written as JSON and read from it. With python, -# also what a Python extension needs to hold Python's objects in them: by pyo3 +# With json, the generated structs are serde's, by which they are written as JSON and read from it. With arrow, +# they are held in Arrow tables, by arrow-rs: of one major version, as those of two do not mix. With python, also +# what a Python extension needs to hold Python's objects in them: by pyo3 [features] +arrow = ["dep:arrow-array", "dep:arrow-buffer", "dep:arrow-data", "dep:arrow-schema"] json = ["dep:serde", "dep:serde_json"] python = ["dep:pyo3", "json"] [dependencies] +arrow-array = { version = "59", optional = true, features = ["ffi"] } +arrow-buffer = { version = "59", optional = true } +arrow-data = { version = "59", optional = true } +arrow-schema = { version = "59", optional = true, features = ["ffi"] } pyo3 = { version = "0.30", optional = true } serde = { version = "1", optional = true } # Which reads a float as exactly what was written diff --git a/src/dataclass_native/rust/src/arrow.rs b/src/dataclass_native/rust/src/arrow.rs new file mode 100644 index 0000000..55b0268 --- /dev/null +++ b/src/dataclass_native/rust/src/arrow.rs @@ -0,0 +1,1510 @@ +//! The generated structs as Arrow tables, as ARROW_FORMAT.md has it: which Python and C++ hold, and read. By the +//! arrays of arrow-rs, so what is made is what the rest of Rust's Arrow takes: as its Parquet. The generated code +//! says of each struct, enum and union what it is, by the macros of this crate: `arrow_struct!`, `arrow_enum!` and +//! `arrow_union!`. + +use crate::msgpack::Record; +use crate::{ + Array, Bytes, Date, DateTime, Decimal, Mutable, MutableArray, NaiveDateTime, Ordered, TimeDelta, TimeOfDay, Uuid, +}; +pub use arrow_array; +use arrow_array::builder::{BinaryBuilder, BooleanBuilder, FixedSizeBinaryBuilder, PrimitiveBuilder, StringBuilder}; +use arrow_array::types::{ + Date32Type, Decimal128Type, DurationMicrosecondType, Float32Type, Float64Type, Int16Type, + Int32Type, Int64Type, Int8Type, Time64MicrosecondType, TimestampMicrosecondType, UInt16Type, UInt32Type, + UInt64Type, UInt8Type, +}; +use arrow_array::{ + Array as _, ArrayRef, BinaryArray, BooleanArray, DictionaryArray, FixedSizeBinaryArray, FixedSizeListArray, + ListArray, MapArray, PrimitiveArray, RecordBatch, RecordBatchOptions, StringArray, StructArray, +}; +pub use arrow_buffer; +use arrow_buffer::{NullBuffer, NullBufferBuilder, OffsetBuffer, ScalarBuffer}; +pub use arrow_schema; +use arrow_schema::{DataType, Field, Fields, Schema, TimeUnit}; +use std::any::Any; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt; +use std::rc::Rc; +use std::sync::Arc; + +/// Of a table's schema: the tag of the class its rows are of +pub const TAG: &str = "dataclass_native:tag"; +/// Of a field which shares an object: the tag of the class of it +pub const SHARED: &str = "dataclass_native:shared"; + +/// A value cannot be held, or tables are not of the type being read +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Error {} + +/// What is read is not of its type, as held +#[derive(Debug)] +pub struct Fault; + +pub type Read = Result; + +/// A type which a column may be of +pub trait Column: Sized { + /// Whether a Shared may be reached from it, however deeply + const SHARES: bool = false; + + /// What gathers the values of a column + type Builder: Default; + + /// The column of an array, as what its values are read from + type Reader: 'static; + + fn data_type() -> DataType; + + /// A field of it: none is declared as not null + fn field(name: &str) -> Field { + Field::new(name, Self::data_type(), true) + } + + /// Gives a row to each object it shares which has none, in the order met + fn walk(&self, _writer: &mut Writer) {} + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error>; + + fn append_null(builder: &mut Self::Builder); + + fn finish(builder: Self::Builder) -> ArrayRef; + + fn reader(array: &ArrayRef) -> Read; + + fn is_null(reader: &Self::Reader, row: usize) -> bool; + + /// The value of a row: which is not null, as only what may be None is + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read; +} + +/// A struct, whose objects are a table: by the tag of its class, and with the classes which it may share +pub trait Table: Column + 'static { + const TAG: &'static str; + + /// Says each class which it may share, however deeply: in the order which the schema has them + fn shared(sharing: &mut S) -> Read<()>; +} + +/// What is told the classes which a table's objects may share +pub trait Sharing { + fn class(&mut self) -> Read<()>; +} + +/// The table of some objects, and that of each class which they may share: by its tag +pub struct Tables { + pub root: RecordBatch, + pub shared: Vec<(String, RecordBatch)>, +} + +/// Objects as Arrow tables: a row each, and a column for each field +pub fn to_arrow<'a, T: Table>(values: impl IntoIterator) -> Result { + let mut writer = Writer::default(); + T::shared(&mut writer).map_err(|_| Error("A class is shared which has no table".to_string()))?; + let mut builder = T::Builder::default(); + for value in values { + if T::SHARES { + value.walk(&mut writer); + } + T::append(&mut builder, value, &writer)?; + } + let root = table::(builder)?; + // Each after the root, as it is then known what is shared: and nothing more is met in holding them + let mut shared = Vec::new(); + for index in 0..writer.tables.len() { + let objects = std::mem::take(&mut writer.tables[index].objects); + let held = (writer.tables[index].build)(&objects, &writer)?; + shared.push((writer.tables[index].tag.to_string(), held)); + } + Ok(Tables { root, shared }) +} + +/// The objects which Arrow tables hold +pub fn from_arrow(tables: &Tables) -> Result, Error> { + let read = || -> Read> { + let mut reading = Reading { given: &tables.shared, tables: Vec::new() }; + T::shared(&mut reading)?; + let rows: ArrayRef = Arc::new(StructArray::from(tables.root.clone())); + let reader = T::reader(&rows)?; + (0..tables.root.num_rows()).map(|row| T::get(&reader, row, &mut reading)).collect() + }; + read().map_err(|Fault| Error(format!("The tables do not hold {}, as it is held", std::any::type_name::()))) +} + +/// The table which the rows of a struct are: of its fields, with its tag +fn table(builder: T::Builder) -> Result { + let rows = T::finish(builder); + let rows = rows.as_any().downcast_ref::().expect("a Table is a struct"); + let metadata = HashMap::from([(TAG.to_string(), T::TAG.to_string())]); + let schema = Arc::new(Schema::new_with_metadata(rows.fields().clone(), metadata)); + let options = RecordBatchOptions::new().with_row_count(Some(rows.len())); + RecordBatch::try_new_with_options(schema, rows.columns().to_vec(), &options).map_err(|e| Error(e.to_string())) +} + +type Object = Arc; + +struct Written { + tag: &'static str, + objects: Vec, + build: fn(&[Object], &Writer) -> Result, +} + +/// The objects which are shared by what is being written: each of which has a row of the table of its class +#[derive(Default)] +pub struct Writer { + /// By where a shared object is, its row + rows: HashMap, + tables: Vec, +} + +impl Sharing for Writer { + fn class(&mut self) -> Read<()> { + fn build(objects: &[Object], writer: &Writer) -> Result { + let mut builder = T::Builder::default(); + for object in objects { + let object = object.downcast_ref::().expect("a table is of the objects of its class"); + T::append(&mut builder, object, writer)?; + } + table::(builder) + } + self.tables.push(Written { tag: ::TAG, objects: Vec::new(), build: build:: }); + Ok(()) + } +} + +impl Writer { + /// Gives a shared object a row, if it has none: and then those it shares, as they are first met in it + pub fn share(&mut self, shared: &Arc) { + let address = Arc::as_ptr(shared) as usize; + if self.rows.contains_key(&address) { + return; + } + let Some(table) = self.tables.iter_mut().find(|table| table.tag == ::TAG) else { return }; + self.rows.insert(address, table.objects.len() as u32); + table.objects.push(shared.clone()); + // What it shares itself, not it again + T::walk(shared, self); + } + + /// The row of a shared object + pub fn row(&self, shared: &Arc) -> Result { + let row = self.rows.get(&(Arc::as_ptr(shared) as usize)); + row.copied().ok_or_else(|| Error("An object is shared whose class the schema does not say is".to_string())) + } +} + +enum Slot { + Unread, + Reading, + Read(Object), +} + +struct Held { + tag: &'static str, + /// The reader of its rows, as a struct: of the class it is of + reader: Rc, + rows: Vec, +} + +/// The tables of the objects which are shared by what is being read, and those which have been read +pub struct Reading<'a> { + given: &'a [(String, RecordBatch)], + tables: Vec, +} + +impl Sharing for Reading<'_> { + fn class(&mut self) -> Read<()> { + // One which is not given is not referred to, or what refers to it is not read + let Some((_, rows)) = self.given.iter().find(|(tag, _)| tag == ::TAG) else { return Ok(()) }; + let array: ArrayRef = Arc::new(StructArray::from(rows.clone())); + let reader: Rc = Rc::new(T::reader(&array)?); + let slots = (0..rows.num_rows()).map(|_| Slot::Unread).collect(); + self.tables.push(Held { tag: ::TAG, reader, rows: slots }); + Ok(()) + } +} + +impl Reading<'_> { + /// The shared object which is a row of the table of its class, which is read if it has not been + pub fn shared(&mut self, row: u32) -> Read> { + let row = row as usize; + let index = self.tables.iter().position(|table| table.tag == ::TAG).ok_or(Fault)?; + match self.tables[index].rows.get(row).ok_or(Fault)? { + Slot::Read(object) => return Arc::clone(object).downcast().map_err(|_| Fault), + // It shares itself, which no object held could + Slot::Reading => return Err(Fault), + Slot::Unread => {} + } + self.tables[index].rows[row] = Slot::Reading; + let reader = Rc::clone(&self.tables[index].reader); + let reader = reader.downcast_ref::().ok_or(Fault)?; + let object = Arc::new(T::get(reader, row, self)?); + self.tables[index].rows[row] = Slot::Read(object.clone()); + Ok(object) + } +} + +/// The array which an array of some type is, if it is one +pub fn cast(array: &ArrayRef) -> Read { + array.as_any().downcast_ref::().cloned().ok_or(Fault) +} + +impl Column for bool { + type Builder = BooleanBuilder; + type Reader = BooleanArray; + + fn data_type() -> DataType { + DataType::Boolean + } + + fn append(builder: &mut Self::Builder, value: &Self, _: &Writer) -> Result<(), Error> { + builder.append_value(*value); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + builder.append_null(); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + Arc::new(builder.finish()) + } + + fn reader(array: &ArrayRef) -> Read { + cast(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, _: &mut Reading) -> Read { + (!reader.is_null(row)).then(|| reader.value(row)).ok_or(Fault) + } +} + +/// A type which is held as a number of Arrow's: by how it is one, and how it is made of one +macro_rules! primitive { + ($([$($generics:tt)*] $of:ty: $arrow:ty, $data:expr, |$value:ident| $native:expr, |$read:ident| $made:expr;)*) => {$( + impl<$($generics)*> Column for $of { + type Builder = PrimitiveBuilder<$arrow>; + type Reader = PrimitiveArray<$arrow>; + + fn data_type() -> DataType { + $data + } + + fn append(builder: &mut Self::Builder, $value: &Self, _: &Writer) -> Result<(), Error> { + builder.append_value($native); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + builder.append_null(); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + Arc::new(builder.finish().with_data_type(::data_type())) + } + + fn reader(array: &ArrayRef) -> Read { + let reader: Self::Reader = cast(array)?; + // Of its unit, and its places: and of a timezone, whatever that is, if it is to have one + let same = match (reader.data_type(), &::data_type()) { + (DataType::Timestamp(unit, zone), DataType::Timestamp(of, zoned)) => { + unit == of && zone.is_some() == zoned.is_some() + } + (DataType::Decimal128(_, scale), DataType::Decimal128(_, of)) => scale == of, + (held, of) => held == of, + }; + same.then_some(reader).ok_or(Fault) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, _: &mut Reading) -> Read { + if reader.is_null(row) { + return Err(Fault); + } + let $read = reader.value(row); + $made + } + } + )*}; +} + +fn microseconds(zone: Option<&str>) -> DataType { + DataType::Timestamp(TimeUnit::Microsecond, zone.map(Arc::from)) +} + +primitive! { + [] i8: Int8Type, DataType::Int8, |value| *value, |read| Ok(read); + [] i16: Int16Type, DataType::Int16, |value| *value, |read| Ok(read); + [] i32: Int32Type, DataType::Int32, |value| *value, |read| Ok(read); + [] i64: Int64Type, DataType::Int64, |value| *value, |read| Ok(read); + [] u8: UInt8Type, DataType::UInt8, |value| *value, |read| Ok(read); + [] u16: UInt16Type, DataType::UInt16, |value| *value, |read| Ok(read); + [] u32: UInt32Type, DataType::UInt32, |value| *value, |read| Ok(read); + [] u64: UInt64Type, DataType::UInt64, |value| *value, |read| Ok(read); + [] f32: Float32Type, DataType::Float32, |value| *value, |read| Ok(read); + [] f64: Float64Type, DataType::Float64, |value| *value, |read| Ok(read); + [] Date: Date32Type, DataType::Date32, |value| value.0, |read| Ok(Date(read)); + [] TimeOfDay: Time64MicrosecondType, DataType::Time64(TimeUnit::Microsecond), |value| value.0, + |read| Ok(TimeOfDay(read)); + [] DateTime: TimestampMicrosecondType, microseconds(Some("UTC")), |value| value.0, |read| Ok(DateTime(read)); + [] NaiveDateTime: TimestampMicrosecondType, microseconds(None), |value| value.0, |read| Ok(NaiveDateTime(read)); + [] TimeDelta: DurationMicrosecondType, DataType::Duration(TimeUnit::Microsecond), |value| value.0, + |read| Ok(TimeDelta(read)); + [const PLACES: u32] Decimal: Decimal128Type, DataType::Decimal128(18, PLACES as i8), + |value| i128::from(value.0), + |read| i64::try_from(read).ok().map(Decimal).filter(Decimal::fits).ok_or(Fault); +} + +impl Column for String { + type Builder = StringBuilder; + type Reader = StringArray; + + fn data_type() -> DataType { + DataType::Utf8 + } + + fn append(builder: &mut Self::Builder, value: &Self, _: &Writer) -> Result<(), Error> { + builder.append_value(value); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + builder.append_null(); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + Arc::new(builder.finish()) + } + + fn reader(array: &ArrayRef) -> Read { + cast(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, _: &mut Reading) -> Read { + (!reader.is_null(row)).then(|| reader.value(row).to_string()).ok_or(Fault) + } +} + +impl Column for Bytes { + type Builder = BinaryBuilder; + type Reader = BinaryArray; + + fn data_type() -> DataType { + DataType::Binary + } + + fn append(builder: &mut Self::Builder, value: &Self, _: &Writer) -> Result<(), Error> { + builder.append_value(&value.0); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + builder.append_null(); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + Arc::new(builder.finish()) + } + + fn reader(array: &ArrayRef) -> Read { + cast(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, _: &mut Reading) -> Read { + (!reader.is_null(row)).then(|| Bytes(reader.value(row).to_vec())).ok_or(Fault) + } +} + +/// Of the 16 bytes of each UUID +pub struct Uuids(FixedSizeBinaryBuilder); + +impl Default for Uuids { + fn default() -> Self { + Self(FixedSizeBinaryBuilder::new(16)) + } +} + +/// As Arrow's own UUID, `arrow.uuid`: which is held as its 16 bytes +impl Column for Uuid { + type Builder = Uuids; + type Reader = FixedSizeBinaryArray; + + fn data_type() -> DataType { + DataType::FixedSizeBinary(16) + } + + fn field(name: &str) -> Field { + let extension = [("ARROW:extension:name", "arrow.uuid"), ("ARROW:extension:metadata", "")]; + let metadata = extension.into_iter().map(|(key, value)| (key.to_string(), value.to_string())); + Field::new(name, Self::data_type(), true).with_metadata(metadata.collect()) + } + + fn append(builder: &mut Self::Builder, value: &Self, _: &Writer) -> Result<(), Error> { + builder.0.append_value(value.0).map_err(|error| Error(error.to_string())) + } + + fn append_null(builder: &mut Self::Builder) { + builder.0.append_null(); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + Arc::new(builder.0.finish()) + } + + fn reader(array: &ArrayRef) -> Read { + cast::(array).ok().filter(|reader| reader.value_length() == 16).ok_or(Fault) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, _: &mut Reading) -> Read { + if reader.is_null(row) { + return Err(Fault); + } + <[u8; 16]>::try_from(reader.value(row)).map(Uuid).map_err(|_| Fault) + } +} + +/// An enum: by the names of its members, in their order, which its dictionary is of +pub trait Member: Copy + PartialEq + 'static { + const MEMBERS: &'static [(Self, &'static str)]; +} + +/// The dictionary of an enum which was read, as the member each of its names is of: and the place in it of each row +pub struct Members { + of: Vec>, + keys: PrimitiveArray, +} + +/// What an enum is held as: used by `arrow_enum!` +pub mod members { + use super::*; + + pub fn data_type() -> DataType { + DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)) + } + + pub fn append(builder: &mut PrimitiveBuilder, value: &E) -> Result<(), Error> { + let place = E::MEMBERS.iter().position(|(member, _)| member == value); + builder.append_value(place.ok_or_else(|| Error("A value which is not a member".to_string()))? as i32); + Ok(()) + } + + pub fn finish(mut builder: PrimitiveBuilder) -> ArrayRef { + let names: StringArray = E::MEMBERS.iter().map(|(_, name)| Some(*name)).collect(); + Arc::new(DictionaryArray::new(builder.finish(), Arc::new(names))) + } + + pub fn reader(array: &ArrayRef) -> Read> { + let held: DictionaryArray = cast(array)?; + let names: StringArray = cast(held.values())?; + let member = |name: Option<&str>| E::MEMBERS.iter().find(|(_, of)| Some(*of) == name).map(|(member, _)| *member); + Ok(Members { of: names.iter().map(member).collect(), keys: held.keys().clone() }) + } + + pub fn is_null(reader: &Members, row: usize) -> bool { + reader.keys.is_null(row) + } + + pub fn get(reader: &Members, row: usize) -> Read { + if reader.keys.is_null(row) { + return Err(Fault); + } + reader.of.get(reader.keys.value(row) as usize).copied().flatten().ok_or(Fault) + } +} + +/// null for None, else as its T +impl Column for Option { + const SHARES: bool = T::SHARES; + type Builder = T::Builder; + type Reader = T::Reader; + + fn data_type() -> DataType { + T::data_type() + } + + fn field(name: &str) -> Field { + T::field(name) + } + + fn walk(&self, writer: &mut Writer) { + if let Some(value) = self { + value.walk(writer); + } + } + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error> { + match value { + Some(value) => T::append(builder, value, writer), + None => { + T::append_null(builder); + Ok(()) + } + } + } + + fn append_null(builder: &mut Self::Builder) { + T::append_null(builder); + } + + fn finish(builder: Self::Builder) -> ArrayRef { + T::finish(builder) + } + + fn reader(array: &ArrayRef) -> Read { + T::reader(array) + } + + fn is_null(_: &Self::Reader, _: usize) -> bool { + false + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read { + if T::is_null(reader, row) { + Ok(None) + } else { + T::get(reader, row, tables).map(Some) + } + } +} + +/// As its float +impl Column for Ordered { + type Builder = F::Builder; + type Reader = F::Reader; + + fn data_type() -> DataType { + F::data_type() + } + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error> { + F::append(builder, &value.0, writer) + } + + fn append_null(builder: &mut Self::Builder) { + F::append_null(builder); + } + + fn finish(builder: Self::Builder) -> ArrayRef { + F::finish(builder) + } + + fn reader(array: &ArrayRef) -> Read { + F::reader(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + F::is_null(reader, row) + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read { + F::get(reader, row, tables).map(Ordered) + } +} + +/// The rows of a list, or of a map: where the values of each end, among those of them all +pub struct Lists { + ends: Vec, + count: i32, + values: B, + nulls: NullBufferBuilder, +} + +impl Default for Lists { + fn default() -> Self { + Self { ends: vec![0], count: 0, values: B::default(), nulls: NullBufferBuilder::new(0) } + } +} + +impl Lists { + fn end(&mut self, added: usize, valid: bool) { + self.count += added as i32; + self.ends.push(self.count); + self.nulls.append(valid); + } + + fn offsets(&mut self) -> (OffsetBuffer, Option) { + (OffsetBuffer::new(ScalarBuffer::from(std::mem::take(&mut self.ends))), self.nulls.finish()) + } +} + +/// A list which was read: the values of them all, and where those of each row are among them +pub struct Listed { + offsets: OffsetBuffer, + nulls: Option, + values: R, +} + +impl Listed { + fn is_null(&self, row: usize) -> bool { + self.nulls.as_ref().is_some_and(|nulls| nulls.is_null(row)) + } + + /// Which of the values are of a row: which is not null + fn of(&self, row: usize) -> Read> { + if self.is_null(row) { + return Err(Fault); + } + Ok(self.offsets[row] as usize..self.offsets[row + 1] as usize) + } +} + +fn list_type() -> DataType { + DataType::List(Arc::new(T::field("item"))) +} + +fn list_append<'a, T: Column + 'a>( + builder: &mut Lists, + items: impl ExactSizeIterator, + writer: &Writer, +) -> Result<(), Error> { + let count = items.len(); + for item in items { + T::append(&mut builder.values, item, writer)?; + } + builder.end(count, true); + Ok(()) +} + +fn list_finish(mut builder: Lists) -> ArrayRef { + let (offsets, nulls) = builder.offsets(); + Arc::new(ListArray::new(Arc::new(T::field("item")), offsets, T::finish(builder.values), nulls)) +} + +fn list_reader(array: &ArrayRef) -> Read> { + let list: ListArray = cast(array)?; + Ok(Listed { offsets: list.offsets().clone(), nulls: list.nulls().cloned(), values: T::reader(list.values())? }) +} + +macro_rules! list { + ($($of:ident $(: $bound:ident)?),*) => {$( + impl Column for $of { + const SHARES: bool = T::SHARES; + type Builder = Lists; + type Reader = Listed; + + fn data_type() -> DataType { + list_type::() + } + + fn walk(&self, writer: &mut Writer) { + if T::SHARES { + self.iter().for_each(|item| item.walk(writer)); + } + } + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error> { + list_append(builder, value.iter(), writer) + } + + fn append_null(builder: &mut Self::Builder) { + builder.end(0, false); + } + + fn finish(builder: Self::Builder) -> ArrayRef { + list_finish::(builder) + } + + fn reader(array: &ArrayRef) -> Read { + list_reader::(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read { + reader.of(row)?.map(|at| T::get(&reader.values, at, tables)).collect() + } + } + )*}; +} + +// A frozenset is a list in ascending order: read whatever its order +list!(Vec, BTreeSet: Ord); + +/// The keys and the values of the rows of a map +#[derive(Default)] +pub struct Entries { + keys: K, + values: V, +} + +fn entries() -> Fields { + Fields::from(vec![K::field("key").with_nullable(false), V::field("value")]) +} + +/// A map, in ascending order of key: read whatever its order +impl Column for BTreeMap { + const SHARES: bool = V::SHARES; + type Builder = Lists>; + type Reader = Listed>; + + fn data_type() -> DataType { + DataType::Map(Arc::new(Field::new("entries", DataType::Struct(entries::()), false)), true) + } + + fn walk(&self, writer: &mut Writer) { + if V::SHARES { + self.values().for_each(|value| value.walk(writer)); + } + } + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error> { + for (key, held) in value { + K::append(&mut builder.values.keys, key, writer)?; + V::append(&mut builder.values.values, held, writer)?; + } + builder.end(value.len(), true); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + builder.end(0, false); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + let (offsets, nulls) = builder.offsets(); + let held = vec![K::finish(builder.values.keys), V::finish(builder.values.values)]; + let held = StructArray::new(entries::(), held, None); + let DataType::Map(field, sorted) = Self::data_type() else { unreachable!() }; + Arc::new(MapArray::new(field, offsets, held, nulls, sorted)) + } + + fn reader(array: &ArrayRef) -> Read { + let map: MapArray = cast(array)?; + let values = Entries { keys: K::reader(map.keys())?, values: V::reader(map.values())? }; + Ok(Listed { offsets: map.offsets().clone(), nulls: map.nulls().cloned(), values }) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read { + let Entries { keys, values } = &reader.values; + reader.of(row)?.map(|at| Ok((K::get(keys, at, tables)?, V::get(values, at, tables)?))).collect() + } +} + +/// The rows of a struct: the builder of each of its fields, and which rows are null +pub struct Rows { + pub fields: B, + pub nulls: NullBufferBuilder, + pub len: usize, +} + +/// The builders of a struct's fields, new: which a tuple of so many as a struct may have is not, by Default +pub trait Fresh { + fn fresh() -> Self; +} + +macro_rules! fresh { + () => { + impl Fresh for () { + fn fresh() -> Self {} + } + }; + ($first:ident $($rest:ident)*) => { + impl<$first: Default, $($rest: Default),*> Fresh for ($first, $($rest,)*) { + fn fresh() -> Self { + ($first::default(), $($rest::default(),)*) + } + } + + fresh!($($rest)*); + }; +} + +// Of as many fields as a struct may have: 120 +#[rustfmt::skip] +fresh!( + A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 + A20 A21 A22 A23 A24 A25 A26 A27 A28 A29 A30 A31 A32 A33 A34 A35 A36 A37 A38 A39 + A40 A41 A42 A43 A44 A45 A46 A47 A48 A49 A50 A51 A52 A53 A54 A55 A56 A57 A58 A59 + A60 A61 A62 A63 A64 A65 A66 A67 A68 A69 A70 A71 A72 A73 A74 A75 A76 A77 A78 A79 + A80 A81 A82 A83 A84 A85 A86 A87 A88 A89 A90 A91 A92 A93 A94 A95 A96 A97 A98 A99 + A100 A101 A102 A103 A104 A105 A106 A107 A108 A109 A110 A111 A112 A113 A114 A115 A116 A117 A118 A119 +); + +impl Default for Rows { + fn default() -> Self { + Self { fields: B::fresh(), nulls: NullBufferBuilder::new(0), len: 0 } + } +} + +impl Rows { + pub fn end(&mut self, valid: bool) { + self.nulls.append(valid); + self.len += 1; + } +} + +/// The struct of the arrays of its fields: of so many rows, some of which may be null +pub fn rows(fields: Vec, arrays: Vec, mut nulls: NullBufferBuilder, len: usize) -> ArrayRef { + let nulls = nulls.finish(); + Arc::new(if fields.is_empty() { + StructArray::new_empty_fields(len, nulls) + } else { + StructArray::new(Fields::from(fields), arrays, nulls) + }) +} + +/// A struct which was read: the reader of each of its fields which has a column, and which rows are null +pub struct Struct { + pub fields: R, + pub nulls: Option, + pub held: StructArray, +} + +impl Struct { + pub fn is_null(&self, row: usize) -> bool { + self.nulls.as_ref().is_some_and(|nulls| nulls.is_null(row)) + } +} + +/// The struct which an array is, and its column of a name: if it has one +pub fn column(held: &StructArray, name: &str) -> Read> { + held.column_by_name(name).map(T::reader).transpose() +} + +macro_rules! tuple { + ($($name:ident $index:tt),+) => { + /// A struct, of a field for each: named for its place + impl<$($name: Column),+> Column for ($($name,)+) { + const SHARES: bool = $($name::SHARES)||+; + type Builder = Rows<($($name::Builder,)+)>; + type Reader = Struct<($($name::Reader,)+)>; + + fn data_type() -> DataType { + DataType::Struct(Fields::from(vec![$($name::field(stringify!($index))),+])) + } + + fn walk(&self, writer: &mut Writer) { + $(if $name::SHARES { + self.$index.walk(writer); + })+ + } + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error> { + $($name::append(&mut builder.fields.$index, &value.$index, writer)?;)+ + builder.end(true); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + $($name::append_null(&mut builder.fields.$index);)+ + builder.end(false); + } + + fn finish(builder: Self::Builder) -> ArrayRef { + let Rows { fields, nulls, len } = builder; + let arrays = vec![$($name::finish(fields.$index)),+]; + rows(vec![$($name::field(stringify!($index))),+], arrays, nulls, len) + } + + fn reader(array: &ArrayRef) -> Read { + let held: StructArray = cast(array)?; + let fields = ($(column::<$name>(&held, stringify!($index))?.ok_or(Fault)?,)+); + Ok(Struct { fields, nulls: held.nulls().cloned(), held }) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read { + if reader.is_null(row) { + return Err(Fault); + } + Ok(($($name::get(&reader.fields.$index, row, tables)?,)+)) + } + } + }; +} + +tuple!(A 0); +tuple!(A 0, B 1); +tuple!(A 0, B 1, C 2); +tuple!(A 0, B 1, C 2, D 3); +tuple!(A 0, B 1, C 2, D 3, E 4); +tuple!(A 0, B 1, C 2, D 3, E 4, F 5); +tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6); +tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7); + +/// The row, in the table of its class, of the object it shares +impl Column for Arc { + const SHARES: bool = true; + type Builder = PrimitiveBuilder; + type Reader = PrimitiveArray; + + fn data_type() -> DataType { + DataType::UInt32 + } + + fn field(name: &str) -> Field { + let metadata = HashMap::from([(SHARED.to_string(), ::TAG.to_string())]); + Field::new(name, DataType::UInt32, true).with_metadata(metadata) + } + + fn walk(&self, writer: &mut Writer) { + writer.share(self); + } + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error> { + builder.append_value(writer.row(value)?); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + builder.append_null(); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + Arc::new(builder.finish()) + } + + fn reader(array: &ArrayRef) -> Read { + cast(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read { + if reader.is_null(row) { + return Err(Fault); + } + tables.shared(reader.value(row)) + } +} + +/// As its T +impl Column for Mutable { + const SHARES: bool = T::SHARES; + type Builder = T::Builder; + type Reader = T::Reader; + + fn data_type() -> DataType { + T::data_type() + } + + fn field(name: &str) -> Field { + T::field(name) + } + + fn walk(&self, writer: &mut Writer) { + self.read().walk(writer); + } + + fn append(builder: &mut Self::Builder, value: &Self, writer: &Writer) -> Result<(), Error> { + T::append(builder, &value.read(), writer) + } + + fn append_null(builder: &mut Self::Builder) { + T::append_null(builder); + } + + fn finish(builder: Self::Builder) -> ArrayRef { + T::finish(builder) + } + + fn reader(array: &ArrayRef) -> Read { + T::reader(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + T::is_null(reader, row) + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut Reading) -> Read { + T::get(reader, row, tables).map(Mutable::new) + } +} + +/// What an array may be of: its numbers are held as a tuple of them is, which is binary if they are bytes +pub trait Numbers: Copy + 'static { + type Builder: Default; + type Reader: 'static; + + fn data_type() -> DataType; + + fn append(builder: &mut Self::Builder, numbers: &[Self]); + + fn append_null(builder: &mut Self::Builder); + + fn finish(builder: Self::Builder) -> ArrayRef; + + fn reader(array: &ArrayRef) -> Read; + + fn is_null(reader: &Self::Reader, row: usize) -> bool; + + fn get(reader: &Self::Reader, row: usize) -> Read>; +} + +impl Numbers for u8 { + type Builder = BinaryBuilder; + type Reader = BinaryArray; + + fn data_type() -> DataType { + DataType::Binary + } + + fn append(builder: &mut Self::Builder, numbers: &[Self]) { + builder.append_value(numbers); + } + + fn append_null(builder: &mut Self::Builder) { + builder.append_null(); + } + + fn finish(mut builder: Self::Builder) -> ArrayRef { + Arc::new(builder.finish()) + } + + fn reader(array: &ArrayRef) -> Read { + cast(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize) -> Read> { + (!reader.is_null(row)).then(|| reader.value(row).to_vec()).ok_or(Fault) + } +} + +macro_rules! numbers { + ($($number:ty: $arrow:ty),*) => {$( + impl Numbers for $number { + type Builder = Lists>; + type Reader = Listed>; + + fn data_type() -> DataType { + list_type::<$number>() + } + + fn append(builder: &mut Self::Builder, numbers: &[Self]) { + builder.values.append_slice(numbers); + builder.end(numbers.len(), true); + } + + fn append_null(builder: &mut Self::Builder) { + builder.end(0, false); + } + + fn finish(builder: Self::Builder) -> ArrayRef { + list_finish::<$number>(builder) + } + + fn reader(array: &ArrayRef) -> Read { + list_reader::<$number>(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize) -> Read> { + let of = reader.of(row)?; + // Of numbers alone, none of which is null + if reader.values.null_count() != 0 { + return Err(Fault); + } + Ok(reader.values.values()[of].to_vec()) + } + } + )*}; +} + +numbers!(i8: Int8Type, i16: Int16Type, i32: Int32Type, i64: Int64Type, u16: UInt16Type, u32: UInt32Type, + u64: UInt64Type, f32: Float32Type, f64: Float64Type); + +/// The rows of an array of numbers: its numbers, and its shape if it is of more than one dimension +pub struct Shaped { + data: T::Builder, + shape: PrimitiveBuilder, + shapes: NullBufferBuilder, + nulls: NullBufferBuilder, + len: usize, +} + +impl Default for Shaped { + fn default() -> Self { + let nulls = || NullBufferBuilder::new(0); + Self { data: T::Builder::default(), shape: PrimitiveBuilder::new(), shapes: nulls(), nulls: nulls(), len: 0 } + } +} + +/// An array of numbers which was read +pub struct ShapedReader { + data: T::Reader, + /// Of one of more than one dimension: its shapes, and which rows are null + shape: Option<(PrimitiveArray, Option)>, + /// Where the shape of its first row is, among them + at: usize, +} + +fn shape_field() -> Field { + let sizes = DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), N as i32); + Field::new("shape", sizes, true) +} + +fn array_type() -> DataType { + if N == 1 { + return T::data_type(); + } + // As Arrow's arrow.variable_shape_tensor is stored + DataType::Struct(Fields::from(vec![Field::new("data", T::data_type(), true), shape_field::()])) +} + +fn array_append(builder: &mut Shaped, shape: &[usize; N], numbers: &[T]) { + T::append(&mut builder.data, numbers); + if N > 1 { + shape.iter().for_each(|size| builder.shape.append_value(*size as i32)); + builder.shapes.append_non_null(); + builder.nulls.append_non_null(); + builder.len += 1; + } +} + +fn array_append_null(builder: &mut Shaped) { + T::append_null(&mut builder.data); + if N > 1 { + (0..N).for_each(|_| builder.shape.append_null()); + builder.shapes.append_null(); + builder.nulls.append_null(); + builder.len += 1; + } +} + +fn array_finish(mut builder: Shaped) -> ArrayRef { + let data = T::finish(builder.data); + if N == 1 { + return data; + } + let DataType::FixedSizeList(item, size) = shape_field::().data_type().clone() else { unreachable!() }; + let shape = FixedSizeListArray::new(item, size, Arc::new(builder.shape.finish()), builder.shapes.finish()); + let fields = vec![Field::new("data", T::data_type(), true), shape_field::()]; + rows(fields, vec![data, Arc::new(shape)], builder.nulls, builder.len) +} + +fn array_reader(array: &ArrayRef) -> Read> { + if N == 1 { + return Ok(ShapedReader { data: T::reader(array)?, shape: None, at: 0 }); + } + let held: StructArray = cast(array)?; + let shape: FixedSizeListArray = cast(held.column_by_name("shape").ok_or(Fault)?)?; + if shape.value_length() != N as i32 { + return Err(Fault); + } + let sizes: PrimitiveArray = cast(shape.values())?; + let data = T::reader(held.column_by_name("data").ok_or(Fault)?)?; + let at = shape.value_offset(0) as usize; + Ok(ShapedReader { data, shape: Some((sizes, held.nulls().cloned())), at }) +} + +fn array_is_null(reader: &ShapedReader, row: usize) -> bool { + match &reader.shape { + Some((_, nulls)) => nulls.as_ref().is_some_and(|nulls| nulls.is_null(row)), + None => T::is_null(&reader.data, row), + } +} + +fn array_get(reader: &ShapedReader, row: usize) -> Read<([usize; N], Vec)> { + if array_is_null(reader, row) { + return Err(Fault); + } + let numbers = T::get(&reader.data, row)?; + let mut shape = [numbers.len(); N]; + if let Some((sizes, _)) = &reader.shape { + for (place, size) in shape.iter_mut().enumerate() { + let at = reader.at + row * N + place; + *size = usize::try_from(sizes.value(at)).ok().filter(|_| !sizes.is_null(at)).ok_or(Fault)?; + } + } + Ok((shape, numbers)) +} + +macro_rules! array { + ($($of:ident, |$value:ident| $numbers:expr;)*) => {$( + impl Column for $of { + type Builder = Shaped; + type Reader = ShapedReader; + + fn data_type() -> DataType { + array_type::() + } + + fn append(builder: &mut Self::Builder, $value: &Self, _: &Writer) -> Result<(), Error> { + array_append(builder, $value.shape(), $numbers); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + array_append_null::(builder); + } + + fn finish(builder: Self::Builder) -> ArrayRef { + array_finish::(builder) + } + + fn reader(array: &ArrayRef) -> Read { + array_reader::(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + array_is_null(reader, row) + } + + fn get(reader: &Self::Reader, row: usize, _: &mut Reading) -> Read { + let (shape, numbers) = array_get::(reader, row)?; + $of::new(numbers, shape).ok_or(Fault) + } + } + )*}; +} + +array! { + Array, |value| value.as_slice(); + MutableArray, |value| &value.read(); +} + +/// An enum, as the names of its members: `arrow_enum!(Currency { USD = "USD", EUR = "EUR" })` +#[macro_export] +macro_rules! arrow_enum { + ($of:ident { $($member:ident = $name:literal),* $(,)? }) => { + impl $crate::arrow::Member for $of { + const MEMBERS: &'static [(Self, &'static str)] = &[$(($of::$member, $name)),*]; + } + + impl $crate::arrow::Column for $of { + type Builder = $crate::arrow::arrow_array::builder::Int32Builder; + type Reader = $crate::arrow::Members<$of>; + + fn data_type() -> $crate::arrow::arrow_schema::DataType { + $crate::arrow::members::data_type() + } + + fn append( + builder: &mut Self::Builder, + value: &Self, + _: &$crate::arrow::Writer, + ) -> Result<(), $crate::arrow::Error> { + $crate::arrow::members::append(builder, value) + } + + fn append_null(builder: &mut Self::Builder) { + builder.append_null(); + } + + fn finish(builder: Self::Builder) -> $crate::arrow::arrow_array::ArrayRef { + $crate::arrow::members::finish::<$of>(builder) + } + + fn reader(array: &$crate::arrow::arrow_array::ArrayRef) -> $crate::arrow::Read { + $crate::arrow::members::reader(array) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + $crate::arrow::members::is_null(reader, row) + } + + fn get(reader: &Self::Reader, row: usize, _: &mut $crate::arrow::Reading) -> $crate::arrow::Read { + $crate::arrow::members::get(reader, row) + } + } + }; +} + +/// A struct, as a struct of a field for each of its own: and as the table which its objects are. Each field is given +/// as its place, its name in Rust, its type, its name in Python and whether it has a default: +/// `arrow_struct!(Money, "schemas.common.Money", false, [], { 0: amount: f64 = "amount", false; })` +#[macro_export] +macro_rules! arrow_struct { + ($of:ident, $tag:literal, $shares:literal, [$($shared:ty),*], + { $($index:tt: $field:ident: $type:ty = $name:literal, $default:literal;)* }) => { + impl $crate::arrow::Column for $of { + const SHARES: bool = $shares; + type Builder = $crate::arrow::Rows<($(<$type as $crate::arrow::Column>::Builder,)*)>; + type Reader = $crate::arrow::Struct<($(Option<<$type as $crate::arrow::Column>::Reader>,)*)>; + + fn data_type() -> $crate::arrow::arrow_schema::DataType { + $crate::arrow::arrow_schema::DataType::Struct($crate::arrow::arrow_schema::Fields::from(vec![ + $(<$type as $crate::arrow::Column>::field($name)),* + ])) + } + + #[allow(unused_variables)] + fn walk(&self, writer: &mut $crate::arrow::Writer) { + $(if <$type as $crate::arrow::Column>::SHARES { + $crate::arrow::Column::walk(&self.$field, writer); + })* + } + + #[allow(unused_variables)] + fn append( + builder: &mut Self::Builder, + value: &Self, + writer: &$crate::arrow::Writer, + ) -> Result<(), $crate::arrow::Error> { + $(<$type as $crate::arrow::Column>::append(&mut builder.fields.$index, &value.$field, writer)?;)* + builder.end(true); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + $(<$type as $crate::arrow::Column>::append_null(&mut builder.fields.$index);)* + builder.end(false); + } + + #[allow(unused_variables)] + fn finish(builder: Self::Builder) -> $crate::arrow::arrow_array::ArrayRef { + let $crate::arrow::Rows { fields, nulls, len } = builder; + let arrays = vec![$(<$type as $crate::arrow::Column>::finish(fields.$index)),*]; + $crate::arrow::rows(vec![$(<$type as $crate::arrow::Column>::field($name)),*], arrays, nulls, len) + } + + fn reader(array: &$crate::arrow::arrow_array::ArrayRef) -> $crate::arrow::Read { + let held: $crate::arrow::arrow_array::StructArray = $crate::arrow::cast(array)?; + // Of each which is a column: one which is not takes its default + let fields = ($($crate::arrow::column::<$type>(&held, $name)?,)*); + Ok($crate::arrow::Struct { fields, nulls: $crate::arrow::arrow_array::Array::nulls(&held).cloned(), held }) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + #[allow(unused_variables)] + fn get(reader: &Self::Reader, row: usize, tables: &mut $crate::arrow::Reading) -> $crate::arrow::Read { + if reader.is_null(row) { + return Err($crate::arrow::Fault); + } + Ok($of { + $($field: match &reader.fields.$index { + Some(column) => <$type as $crate::arrow::Column>::get(column, row, tables)?, + None if $default => <$of>::default().$field, + None => return Err($crate::arrow::Fault), + },)* + }) + } + } + + impl $crate::arrow::Table for $of { + const TAG: &'static str = $tag; + + #[allow(unused_variables)] + fn shared(sharing: &mut S) -> $crate::arrow::Read<()> { + $(sharing.class::<$shared>()?;)* + Ok(()) + } + } + }; +} + +/// A union, as a struct of a field for each of its members, one of which is not null. Each member is given as its +/// place, its name in Rust, its type and the name of its field: +/// `arrow_union!(KindsNumber, false, { 0: Int(i64) = "int"; 1: Str(String) = "str"; })` +#[macro_export] +macro_rules! arrow_union { + ($of:ident, $shares:literal, { $($index:tt: $member:ident($type:ty) = $name:literal;)* }) => { + impl $crate::arrow::Column for $of { + const SHARES: bool = $shares; + type Builder = $crate::arrow::Rows<($(<$type as $crate::arrow::Column>::Builder,)*)>; + type Reader = $crate::arrow::Struct<($(Option<<$type as $crate::arrow::Column>::Reader>,)*)>; + + fn data_type() -> $crate::arrow::arrow_schema::DataType { + $crate::arrow::arrow_schema::DataType::Struct($crate::arrow::arrow_schema::Fields::from(vec![ + $(<$type as $crate::arrow::Column>::field($name)),* + ])) + } + + fn walk(&self, writer: &mut $crate::arrow::Writer) { + match self { + $($of::$member(held) => $crate::arrow::Column::walk(held, writer),)* + } + } + + fn append( + builder: &mut Self::Builder, + value: &Self, + writer: &$crate::arrow::Writer, + ) -> Result<(), $crate::arrow::Error> { + $(match value { + $of::$member(held) => <$type as $crate::arrow::Column>::append(&mut builder.fields.$index, held, writer)?, + #[allow(unreachable_patterns)] + _ => <$type as $crate::arrow::Column>::append_null(&mut builder.fields.$index), + })* + builder.end(true); + Ok(()) + } + + fn append_null(builder: &mut Self::Builder) { + $(<$type as $crate::arrow::Column>::append_null(&mut builder.fields.$index);)* + builder.end(false); + } + + fn finish(builder: Self::Builder) -> $crate::arrow::arrow_array::ArrayRef { + let $crate::arrow::Rows { fields, nulls, len } = builder; + let arrays = vec![$(<$type as $crate::arrow::Column>::finish(fields.$index)),*]; + $crate::arrow::rows(vec![$(<$type as $crate::arrow::Column>::field($name)),*], arrays, nulls, len) + } + + fn reader(array: &$crate::arrow::arrow_array::ArrayRef) -> $crate::arrow::Read { + let held: $crate::arrow::arrow_array::StructArray = $crate::arrow::cast(array)?; + let fields = ($($crate::arrow::column::<$type>(&held, $name)?,)*); + Ok($crate::arrow::Struct { fields, nulls: $crate::arrow::arrow_array::Array::nulls(&held).cloned(), held }) + } + + fn is_null(reader: &Self::Reader, row: usize) -> bool { + reader.is_null(row) + } + + fn get(reader: &Self::Reader, row: usize, tables: &mut $crate::arrow::Reading) -> $crate::arrow::Read { + if reader.is_null(row) { + return Err($crate::arrow::Fault); + } + // The one which is not null: and no other is + let mut read = None; + $(if let Some(column) = &reader.fields.$index { + if !<$type as $crate::arrow::Column>::is_null(column, row) { + if read.is_some() { + return Err($crate::arrow::Fault); + } + read = Some($of::$member(<$type as $crate::arrow::Column>::get(column, row, tables)?)); + } + })* + read.ok_or($crate::arrow::Fault) + } + } + }; +} diff --git a/src/dataclass_native/rust/src/lib.rs b/src/dataclass_native/rust/src/lib.rs index f0b28d7..b0da26b 100644 --- a/src/dataclass_native/rust/src/lib.rs +++ b/src/dataclass_native/rust/src/lib.rs @@ -5,6 +5,8 @@ use std::cmp::Ordering; use std::fmt; use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; +#[cfg(feature = "arrow")] +pub mod arrow; #[cfg(feature = "python")] mod fields; #[cfg(feature = "json")] @@ -25,6 +27,26 @@ macro_rules! json { ($($items:tt)*) => {}; } +/// What the generated code says of Arrow, of each struct, enum and union: which is nothing without the feature +/// arrow, as it is the feature which has Arrow +#[cfg(not(feature = "arrow"))] +#[macro_export] +macro_rules! arrow_struct { + ($($said:tt)*) => {}; +} + +#[cfg(not(feature = "arrow"))] +#[macro_export] +macro_rules! arrow_enum { + ($($said:tt)*) => {}; +} + +#[cfg(not(feature = "arrow"))] +#[macro_export] +macro_rules! arrow_union { + ($($said:tt)*) => {}; +} + /// The days since 1970-01-01 of a date, and the year, month and day of that many #[cfg(feature = "json")] pub(crate) fn days_of(year: i64, month: i64, day: i64) -> i64 { diff --git a/src/dataclass_native/rust/src/python.rs b/src/dataclass_native/rust/src/python.rs index fb9e079..38853db 100644 --- a/src/dataclass_native/rust/src/python.rs +++ b/src/dataclass_native/rust/src/python.rs @@ -942,3 +942,120 @@ pub fn from_json(of: &str, data: &[u8]) -> PyResult { }) }) } + +/// Structs as Arrow tables, and those which tables hold: what the class of each has as `__arrow__` and +/// `__from_arrow__`, which dataclass_native's to_arrow and from_arrow call. A table is given as the capsules of the +/// Arrow PyCapsule interface, of its schema and of its array, which pyarrow imports and exports without copying +#[cfg(feature = "arrow")] +pub use held_in_arrow::{from_arrow, to_arrow}; + +#[cfg(feature = "arrow")] +mod held_in_arrow { + use crate::arrow::arrow_array::ffi::{from_ffi, FFI_ArrowArray, FFI_ArrowSchema}; + use crate::arrow::arrow_array::{make_array, Array, ArrayRef, RecordBatch, StructArray}; + use crate::arrow::arrow_schema::DataType; + use crate::arrow::{self, Table, Tables}; + use arrow_data::ArrayData; + use pyo3::exceptions::PyValueError; + use pyo3::prelude::*; + use pyo3::types::{PyCapsule, PyDict}; + use std::ffi::{c_char, c_void, CStr}; + use std::sync::Arc; + + type Capsules<'py> = (Bound<'py, PyCapsule>, Bound<'py, PyCapsule>); + + /// A schema as the Arrow C data interface has it, which is how arrow-rs holds one + #[repr(C)] + struct Schema { + format: *const c_char, + name: *const c_char, + metadata: *const c_char, + flags: i64, + n_children: i64, + children: *mut *mut Schema, + dictionary: *mut Schema, + release: Option, + private_data: *mut c_void, + } + + /// Says of each map that its keys are in order: which arrow-rs does not, of one which is a field + unsafe fn sorted(schema: *mut Schema) { + const MAP_KEYS_SORTED: i64 = 4; + if CStr::from_ptr((*schema).format) == c"+m" { + (*schema).flags |= MAP_KEYS_SORTED; + } + for child in 0..(*schema).n_children as usize { + sorted(*(*schema).children.add(child)); + } + if !(*schema).dictionary.is_null() { + sorted((*schema).dictionary); + } + } + + fn capsules<'py>(py: Python<'py>, table: &RecordBatch) -> PyResult> { + let schema = FFI_ArrowSchema::try_from(table.schema().as_ref()); + let mut schema = schema.map_err(|error| PyValueError::new_err(error.to_string()))?; + unsafe { sorted(std::ptr::from_mut(&mut schema).cast()) }; + let array = FFI_ArrowArray::new(&StructArray::from(table.clone()).to_data()); + Ok(( + PyCapsule::new_with_value(py, schema, c"arrow_schema")?, + PyCapsule::new_with_value(py, array, c"arrow_array")?, + )) + } + + /// The capsules of the table of some structs, and those of each class they may share, with its tag + pub fn to_arrow<'a, 'py, T: Table>( + py: Python<'py>, + values: impl IntoIterator, + ) -> PyResult> { + let tables = arrow::to_arrow(values).map_err(|error| PyValueError::new_err(error.0))?; + let shared = tables.shared.iter().map(|(tag, table)| Ok((tag.as_str(), capsules(py, table)?))); + Ok((capsules(py, &tables.root)?, shared.collect::>>()?).into_pyobject(py)?.into_any()) + } + + /// The table which capsules are of, which it takes: or None, if it is not one of rows + fn imported(schema: &Bound<'_, PyAny>, array: &Bound<'_, PyAny>) -> PyResult> { + let schema = schema.cast::()?.pointer_checked(Some(c"arrow_schema"))?; + let array = array.cast::()?.pointer_checked(Some(c"arrow_array"))?; + // What the capsules hold is as their names say, by the interface + let data = unsafe { + let array = FFI_ArrowArray::from_raw(array.as_ptr().cast()); + from_ffi(array, schema.cast::().as_ref()) + }; + let Some(rows) = data.ok().and_then(|data| rows(&data)) else { return Ok(None) }; + Ok(rows.as_any().downcast_ref::().filter(|rows| rows.null_count() == 0).map(RecordBatch::from)) + } + + /// The array which what was imported is of. A struct which is some of the rows of another, as a table which + /// is some of the rows of another has, is made here: arrow-rs takes the rows of what is within it twice + fn rows(data: &ArrayData) -> Option { + let DataType::Struct(fields) = data.data_type() else { return Some(make_array(data.clone())) }; + let (offset, len) = (data.offset(), data.len()); + let within = |child: &ArrayData| rows(child).filter(|held| offset + len <= held.len()); + let children: Option> = data.child_data().iter().map(within).collect(); + let children = children?.iter().map(|held| held.slice(offset, len)).collect::>(); + let nulls = data.nulls().cloned(); + Some(Arc::new(if fields.is_empty() { + StructArray::new_empty_fields(len, nulls) + } else { + StructArray::try_new(fields.clone(), children, nulls).ok()? + })) + } + + /// The structs which tables hold, given as their capsules: shared is of those of the objects they share, by + /// tag. None if the tables are not read, for whatever reason: Python then reads them, or says why not + pub fn from_arrow( + schema: &Bound<'_, PyAny>, + array: &Bound<'_, PyAny>, + shared: &Bound<'_, PyDict>, + ) -> PyResult>> { + let Some(root) = imported(schema, array)? else { return Ok(None) }; + let mut tables = Tables { root, shared: Vec::new() }; + for (tag, held) in shared.iter() { + let (schema, array): (Bound<'_, PyAny>, Bound<'_, PyAny>) = held.extract()?; + let Some(table) = imported(&schema, &array)? else { return Ok(None) }; + tables.shared.push((tag.extract()?, table)); + } + Ok(arrow::from_arrow(&tables).ok()) + } +} diff --git a/tests/performance.py b/tests/performance.py index 1f07908..5f0b073 100644 --- a/tests/performance.py +++ b/tests/performance.py @@ -99,7 +99,7 @@ def _rust() -> Path: crate = BUILD / "rust" / "extension" subprocess.run( # Not stripped, as the loader of macOS has refused one which cargo had - ["cargo", "build", "--release", "--quiet"] + ["cargo", "build", "--release", "--quiet", "--features", "arrow"] + ["--config", "profile.release.strip=false"], cwd=crate, env=os.environ diff --git a/tests/test_pyo3.py b/tests/test_pyo3.py index e141cfa..6bc6f1b 100644 --- a/tests/test_pyo3.py +++ b/tests/test_pyo3.py @@ -28,8 +28,6 @@ "schemas.scalars", "schemas.mutable", ] -# What an extension in Rust is yet to do, so the test of it is not run: Arrow -TO_COME = ["test_arrow.py::test_bound_objects_are_held_natively"] # What serde reads otherwise than Python and C++ do, of JSON which none of them writes: -0, which is not an int # to it, and is the float -0.0, and a key which is a number with spaces about it OTHERWISE = [ @@ -50,6 +48,10 @@ name = "_native" crate-type = ["cdylib"] +# Which the classes of the extension are held in Arrow with: else Python holds them +[features] +arrow = ["dataclass_native/arrow"] + [dependencies] pyo3 = "0.30" dataclass_native = {{ path = "{runtime}", features = ["python"] }} @@ -193,7 +195,7 @@ def built(sources) -> Path: _MANIFEST.format(runtime=rust_dir().as_posix()), encoding="utf-8" ) result = subprocess.run( - ["cargo", "build", "--quiet"], + ["cargo", "build", "--quiet", "--features", "arrow"], cwd=crate, # An extension is not linked with Python, which the interpreter loading it is env=os.environ @@ -235,7 +237,7 @@ def test_runtime_with_the_extension(built, mode): result = subprocess.run( [sys.executable, "-m", "pytest", "-q", "--no-cov", "-p", "no:cacheprovider"] + [f"tests/{file}" for file in files] - + [f"--deselect=tests/{test}" for test in TO_COME + OTHERWISE] + + [f"--deselect=tests/{test}" for test in OTHERWISE] # Not prepending tests to the path, where the schemas have no extension + ["--import-mode=importlib", "-o", f"pythonpath={built.as_posix()}"], cwd=TESTS.parent, diff --git a/tests/test_rust.py b/tests/test_rust.py index c9666c2..95880c5 100644 --- a/tests/test_rust.py +++ b/tests/test_rust.py @@ -163,6 +163,8 @@ def test_common(sources): dataclass_native::serde_by_form!([] Currency); } + dataclass_native::arrow_enum!(Currency { USD = "USD", EUR = "EUR", GBP = "GBP" }); + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(i8)] @@ -235,6 +237,8 @@ def test_common(sources): dataclass_native::serde_by_form!([] Side); } + dataclass_native::arrow_enum!(Side { BUY = "BUY", SELL = "SELL" }); + #[derive(Debug, Clone, PartialEq)] pub struct Money { pub amount: f64, @@ -340,6 +344,13 @@ def test_common(sources): dataclass_native::serde_by_form!([] Money); } + + dataclass_native::arrow_struct!( + Money, "schemas.common.Money", false, [], { + 0: amount: f64 = "amount", false; + 1: currency: Currency = "currency", true; + } + ); """ ) ) @@ -552,9 +563,46 @@ def test_cli(tmp_path, capsys): #[cfg(feature = "json")] json(&keyed, &curve, &surface, &path, &first); + #[cfg(feature = "arrow")] + arrow(&keyed, &curve, &surface, &path, &both); println!("ok"); } +/// As Arrow tables, by arrow-rs: as ARROW_FORMAT.md has it, and read back as what was held +#[cfg(feature = "arrow")] +fn arrow(keyed: &Everything, curve: &Curve, surface: &Surface, path: &Path, links: &(Shared, Shared)) { + use dataclass_native::arrow::arrow_array::Array; + use dataclass_native::arrow::{from_arrow, to_arrow, Tables}; + + let moneys = [Money { amount: 1.5, currency: Currency::EUR }, Money::default()]; + let tables = to_arrow(&moneys).unwrap(); + assert_eq!((tables.root.num_rows(), tables.root.num_columns(), tables.shared.len()), (2, 2, 0)); + assert_eq!(tables.root.schema().metadata()["dataclass_native:tag"], "schemas.common.Money"); + assert_eq!(tables.root.schema().field(1).data_type().to_string(), "Dictionary(Int32, Utf8)"); + assert_eq!(from_arrow::(&tables).unwrap(), moneys); + // A column which is not there is of its default, if it has one + let amounts = tables.root.project(&[0]).unwrap(); + assert_eq!(from_arrow::(&Tables { root: amounts, shared: Vec::new() }).unwrap()[0].amount, 1.5); + let currencies = Tables { root: tables.root.project(&[1]).unwrap(), shared: Vec::new() }; + assert!(from_arrow::(¤cies).is_err()); + + let kinds = [Kinds::default(), Kinds { number: KindsNumber::Str("x".to_string()), ..Kinds::default() }]; + assert_eq!(from_arrow::(&to_arrow(&kinds).unwrap()).unwrap(), kinds); + assert_eq!(from_arrow::(&to_arrow([keyed]).unwrap()).unwrap(), [keyed.clone()]); + assert_eq!(from_arrow::(&to_arrow([curve]).unwrap()).unwrap(), [curve.clone()]); + assert_eq!(from_arrow::(&to_arrow([surface]).unwrap()).unwrap(), [surface.clone()]); + assert_eq!(from_arrow::(&to_arrow([path]).unwrap()).unwrap(), [path.clone()]); + + // What is shared is a row of the table of its class, once: and is still shared when it is read + let (first, last) = links; + let held = [(**first).clone(), Link { name: "c".to_string(), next: Some(last.clone()) }]; + let tables = to_arrow(&held).unwrap(); + let (tag, shared) = &tables.shared[0]; + assert_eq!((tag.as_str(), shared.num_rows(), tables.root.column(1).null_count()), ("schemas.kinds.Link", 1, 0)); + let read = from_arrow::(&tables).unwrap(); + assert!(read == held && Shared::ptr_eq(read[0].next.as_ref().unwrap(), read[1].next.as_ref().unwrap())); +} + /// As JSON, by serde: as JSON_FORMAT.md has it, and read back as what was written #[cfg(feature = "json")] fn json(keyed: &Everything, curve: &Curve, surface: &Surface, path: &Path, link: &Link) { @@ -582,10 +630,12 @@ def test_cli(tmp_path, capsys): @needs_cargo -@pytest.mark.parametrize("features", [(), ("--features", "json")]) +@pytest.mark.parametrize( + "features", [(), ("--features", "json"), ("--features", "arrow")] +) def test_cargo_compiles_it(sources, features): """With warnings as errors, and it holds what it is to: with no crate but dataclass-native's own, which has - serde only with its feature json""" + serde only with its feature json, and arrow-rs only with its feature arrow""" # Kept between runs, so that only what has changed is built crate = BUILD / "crate" shutil.rmtree(crate / "src", ignore_errors=True) @@ -603,6 +653,7 @@ def test_cargo_compiles_it(sources, features): edition = "2021" [features] + arrow = ["dataclass_native/arrow"] json = ["dataclass_native/json"] [dependencies]