Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions ARROW_FORMAT.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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.
Expand Down
20 changes: 17 additions & 3 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
31 changes: 21 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Trade> = 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`:

Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down
42 changes: 38 additions & 4 deletions src/dataclass_native/backends/pyo3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"
Expand All @@ -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]))
Expand Down Expand Up @@ -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 = (
Expand Down Expand Up @@ -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<PyRef<'py, Self>>) -> PyResult<Bound<'py, PyAny>> {\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<Option<Vec<Self>>> {\n"
f" let read: Option<Vec<{plain}>> = 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
Expand Down Expand Up @@ -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"
Expand Down
50 changes: 46 additions & 4 deletions src/dataclass_native/backends/rust.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
12 changes: 9 additions & 3 deletions src/dataclass_native/rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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
Expand Down
Loading
Loading