diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ebcedc5..c93af1c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,7 +5,15 @@ on: tags: ["v*"] jobs: + version: + # The crate is of the version of the tag, which the package is of: else neither is released + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: grep -qx "version = \"${GITHUB_REF_NAME#v}\"" src/dataclass_native/rust/Cargo.toml + publish: + needs: version runs-on: ubuntu-latest environment: pypi permissions: @@ -18,3 +26,13 @@ jobs: - uses: astral-sh/setup-uv@v6 - run: uv build - uses: pypa/gh-action-pypi-publish@release/v1 + + crate: + # dataclass_native, on crates.io: which the Rust that is generated uses + needs: version + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: cargo publish --manifest-path src/dataclass_native/rust/Cargo.toml + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/DESIGN.md b/DESIGN.md index 5edff53..567a44b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -213,9 +213,11 @@ which has a `mod.rs` naming what is in it: so `mod pkg;` in a crate whose `src` package. A type of another module is named by way of what both are within, as `super::common::Money`, so the modules may be anywhere in a crate. -- The generated code uses the crate `dataclass_native`, which is in the Python package and depends on nothing, - but on pyo3 for its feature `python`: - `dataclass-native rust-dir` prints its directory, to depend on by path. +- The generated code uses the crate `dataclass_native`, which depends on nothing but for its features: pyo3 + for `python`, serde for `json` and arrow-rs for `arrow`. It is released to crates.io with the Python package, + at its version, as what is generated and the crate are of each other: the release is refused if the crate's + version is not the tag's. It is also in the Python package, where `dataclass-native rust-dir` prints, to + depend on by path. - Names are Python's: a struct's, its fields', an enum's and its members', so `Currency::USD`. One which is a keyword of Rust has `_` after it. - A struct has the defaults of its class, as its `Default`: a field which has none has that of its type, as in C++. @@ -453,8 +455,9 @@ 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, JSON by serde, and Arrow by arrow-rs. To come: Parquet from Rust alone, which - arrow-rs has; and an example built with maturin. + C++ are; and msgpack, JSON by serde, and Arrow by arrow-rs. Parquet from Rust alone needs arrow-rs's + `parquet`, which is not a dependency: the parquet-rust example uses it. The functions-rust example is an + extension built with maturin, whose `build.rs` generates the Rust when it is built. 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 cd4772a..1963ec2 100644 --- a/README.md +++ b/README.md @@ -5,18 +5,25 @@ Use Python dataclasses as a data description language. Why do this? I'm glad you asked! This approach solves several problems I've wrestled with when creating object models in Python which need to interact with native code implementations for performance reasons. The classic example is quant finance code. My main requirements are: 1. Pythonic data classes, which interact nicely with pyright and other static checkers -2. Ability to run the python code without code generation steps -3. No-copy semantics when interacting with native code +2. Idiomatic generated classes/structs in C++ and Rust, which integrate well with native code +3. Ability to run the python code without code generation steps +4. No-copy semantics when interacting with native code Protobufs fail on points 1. and 2., produce hideous python and require you to distribute the protobuf definitions. AVRO is a bit more friendly but generates its classes dynamically which fails point 1. -The approach of dataclass-native is to generate native classes - currently C++, with Rust to follow, -whose storage the Python classes use directly. Native serialisation (msgpack, Arrow/Parquet) is planned. +dataclass-native provides ways to generate native C++ and Rust structs, whose storage the Python classes use directly. +Descriptors replace the dataclass attributes which marshal the values into the native classes. The initial implementation of these was in +python but they have been superseded by native implementations for performance reasons. -**Status:** early. Schema introspection, C++ header generation and the native Python binding work. Serialisation -works to msgpack and to Arrow, in Python and C++, and to Parquet through pyarrow. Rust is to come: see +Serialisation to JSON, msgpack and arrow is supported in python, Rust and C++. Going from arrow to parquet is a simple step, illustrated +in the examples. + +Write your object model using standard python dataclasses. Annotate with `@native`. Let dataclass-native generate you the +C++ and Rust structs to use in your native code. Invoke native code taking your dataclasses using `@native_function`. + +**Status:** early. Caveat Emptor. Tests cover foreseeable edge cases but there are naturally some compromises: see [DESIGN.md](DESIGN.md). ## Defining a schema @@ -76,7 +83,7 @@ class Trade: Classes are best frozen. One which is not may have its fields set, and what holds it holds that object, not a copy of it, as in Python: `order.customer.name = "Ann"` changes the customer. Its containers are still immutable, so are -set whole. +set whole. See [Frozen or not](#frozen-or-not). Containers are `tuple[T, ...]`, `tuple[A, B]`, `frozenset[T]` and `Mapping[K, V]`. @@ -92,6 +99,35 @@ needs numpy: install `dataclass-native[numpy]`. A class may also be a pydantic dataclass (`pydantic.dataclasses.dataclass(frozen=True)`), to validate and convert what its objects are made from. pydantic's `BaseModel` is not supported, it does unfortunate things like setting `__dict__` directly on objects and has complicated (and rather ugly) code in `__setattr__` etc, which interferes with the descriptors. `BaseModel` and descriptors are generally unhappy bedfellows. +### Frozen or not + +A class may be frozen (`@dataclass(frozen=True)`) or not. Frozen is the better default: the differences are +mostly of what the objects mean, not of speed. + +| | Frozen | Not frozen | +|---|---|---| +| Its fields | Set once, when it is made | May be set at any time | +| Held by another object | By value: natively, within the struct which holds it | By reference: what holds it holds that object, and sees what is set on it | +| Read from a field | A view of it within a frozen object, without copying. A copy, if what holds it is not frozen | The object which was given, itself | +| `Shared[...]` | May be, so that it is written once, and is still shared when read | May not be. It is written wherever it is held, so what was one object is read back as several | +| Hash | As a dataclass has | None | +| Numpy arrays | Read-only | May be written to | +| An object which holds itself | Cannot be | Can be, but is then not written as msgpack or JSON | +| Natively | A plain struct | A struct behind a reference-counted pointer: in Rust also behind a lock | + +Either kind may hold the other, and both are compared by value. The containers of both are immutable: a tuple of +a class which is not frozen is set whole, though its objects may themselves be set. + +In speed there is little between them. Setting a field costs about what reading one does, and making an object +about the same of either kind: see [Performance](#performance). Reading an object from a field, in nanoseconds, +measured as there: + +| Read | C++ | Rust | +|---|---:|---:| +| A frozen object from a frozen one | 148 | 166 | +| A frozen object from one which is not, which is a copy | 179 | 216 | +| An object which is not frozen, which is the object given | 97 | 157 | + ## Generating C++ ```shell @@ -122,9 +158,18 @@ Unchanged files are untouched, so builds don't rerun needlessly. ```shell dataclass-native generate rust --package my_schemas --out src -dataclass-native rust-dir # dataclass_native's own crate, which the generated modules use: depend on it by path ``` +The generated modules use the crate [`dataclass_native`](https://crates.io/crates/dataclass_native), which is +released with the Python package, at its version: so depend on the version of what generated them. + +```toml +[dependencies] +dataclass_native = "=1.2.0" +``` + +It is also in the Python package, where `dataclass-native rust-dir` prints, to depend on by path. + This writes a file per module (`src/my_schemas/trades.rs`, the module `my_schemas::trades` once a crate has `mod my_schemas;`) of plain structs and enums. A union is an enum of its own, named for its class and field: @@ -172,6 +217,9 @@ let tables = to_arrow(&trades)?; // tables.root is a RecordBatch, and tables.s let trades: Vec = from_arrow(&tables)?; ``` +Which arrow-rs's `parquet` writes as files: the [parquet-rust example](examples/parquet-rust) writes and reads +those which `to_parquet` and `from_parquet` do, in Rust alone. + 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`: @@ -197,8 +245,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. 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. +`["dataclass_native/arrow"]`, and is built with it: else Python does, as arrow-rs is much to build. +[examples/functions-rust](examples/functions-rust) is such a project, built with +[maturin](https://www.maturin.rs). ## Storing Python objects in the structs @@ -290,7 +339,7 @@ fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> { ``` What it takes and gives are what fields may be of. If it gives a `Result`, Python raises its error: as a -`ValueError`, if it is not an exception of pyo3's. +`ValueError`, if it is not an exception of pyo3's. See [examples/functions-rust](examples/functions-rust). ## Serialising @@ -363,7 +412,8 @@ auto tables = dataclass_native::arrow::to_arrow(std::span(tr Parquet files are written from them, in C++, by an Arrow library which you link: the [parquet example](examples/parquet) does so with Arrow C++, writing and reading the files which `to_parquet` and -`from_parquet` do. +`from_parquet` do. In Rust they are by arrow-rs's `parquet`, as the +[parquet-rust example](examples/parquet-rust) does. ## Modes @@ -428,7 +478,8 @@ which Python does it, reading each field from the struct, which is slower than ` ## Examples [examples](examples) has projects to copy from: a schema stored natively and one with C++ functions, each built by -scikit-build-core, and a C++ program which writes Parquet files with Arrow C++. +scikit-build-core; the same functions in Rust, built by maturin; and programs which write Parquet files, one of +C++, with Arrow C++, and one of Rust, with arrow-rs. ## Development diff --git a/examples/functions-rust/.gitignore b/examples/functions-rust/.gitignore new file mode 100644 index 0000000..a8f8446 --- /dev/null +++ b/examples/functions-rust/.gitignore @@ -0,0 +1,8 @@ +# Generated from python/shop, by build.rs +/src/shop/ +/src/shop_native.rs +/target/ +Cargo.lock +# The extension, where maturin develop puts it +/python/shop/*.so +/python/shop/*.pyd diff --git a/examples/functions-rust/Cargo.toml b/examples/functions-rust/Cargo.toml new file mode 100644 index 0000000..2489167 --- /dev/null +++ b/examples/functions-rust/Cargo.toml @@ -0,0 +1,25 @@ +# The extension shop._native: which holds the objects of the package's classes in Rust, and has its functions +[package] +name = "shop" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +name = "_native" +crate-type = ["cdylib"] + +# With arrow, the classes are held in Arrow tables by the extension: else by Python, as arrow-rs is much to build. +# maturin builds with it if pyproject.toml's [tool.maturin] has features = ["arrow"] +[features] +arrow = ["dataclass_native/arrow"] + +[dependencies] +# dataclass-native's own crate. In a project of your own it is that of crates.io, of the version of the Python +# package which generates the Rust: dataclass_native = { version = "=1.2.0", features = ["python"] }. Here it is +# that of this repository +dataclass_native = { path = "../../src/dataclass_native/rust", features = ["python"] } +pyo3 = "0.30" + +[build-dependencies] +pyo3-build-config = "0.30" diff --git a/examples/functions-rust/build.rs b/examples/functions-rust/build.rs new file mode 100644 index 0000000..23fac57 --- /dev/null +++ b/examples/functions-rust/build.rs @@ -0,0 +1,23 @@ +//! Generates the Rust of the package, src/shop and src/shop_native.rs, from python/shop: as +//! `dataclass-native generate pyo3` does. By the Python which the extension is built for, which is to have +//! dataclass-native installed: as that which builds it has, by pyproject.toml's build-system. + +use std::process::Command; + +fn main() { + println!("cargo:rerun-if-changed=python/shop"); + println!("cargo:rerun-if-env-changed=PYO3_PYTHON"); + // Which maturin says: or python3, of cargo alone + let python = std::env::var("PYO3_PYTHON").unwrap_or_else(|_| "python3".to_string()); + let generated = Command::new(&python) + .args(["-m", "dataclass_native", "generate", "pyo3", "--package", "shop", "--out", "src"]) + .env("PYTHONPATH", "python") + // Which would else be in the wheel, with the package + .env("PYTHONDONTWRITEBYTECODE", "1") + .status() + .unwrap_or_else(|error| panic!("{python} could not be run, to generate the Rust of the package: {error}")); + assert!(generated.success(), "dataclass-native did not generate the Rust of the package"); + + // What links an extension, where cargo alone builds it: maturin does so itself + pyo3_build_config::add_extension_module_link_args(); +} diff --git a/examples/functions-rust/demo.py b/examples/functions-rust/demo.py new file mode 100644 index 0000000..fe8b8ea --- /dev/null +++ b/examples/functions-rust/demo.py @@ -0,0 +1,22 @@ +import datetime as dt + +from dataclass_native import mode +from shop.model import Address, Customer, Line, Order +from shop.pricing import ship, total + +alice = Customer(1, "Alice", Address("1 High St", "Leeds", "LS1 1AA")) +order = Order( + id=100, + customer=alice, + lines=(Line("widget", 2, 9.99), Line("gadget", 1, 24.50)), + placed=dt.date(2026, 11, 27), +) + +print(f"Mode: {mode()}") +print(f"Total: {total(order):.2f}") + +shipped = ship(order) +print(f"Shipped to: {shipped.ship_to}") +print(f"Still sharing the customer: {shipped.customer is alice}") +print(f"Or to: {ship(order, Address('2 Low Rd', 'York', 'YO1 2BB')).ship_to}") +print(f"The order itself is unchanged: {order.status}") diff --git a/examples/functions-rust/pyproject.toml b/examples/functions-rust/pyproject.toml new file mode 100644 index 0000000..9920351 --- /dev/null +++ b/examples/functions-rust/pyproject.toml @@ -0,0 +1,18 @@ +[project] +name = "shop" +version = "0.1.0" +requires-python = ">=3.13" +dependencies = ["dataclass-native"] + +# maturin builds Cargo.toml's crate, and puts it into the wheel as shop._native, with the package of python/ +[build-system] +requires = ["maturin>=1.9.4,<2", "dataclass-native"] +build-backend = "maturin" + +[tool.maturin] +python-source = "python" +module-name = "shop._native" + +# This repository's dataclass-native, to run and to build with: not needed in a project of your own +[tool.uv.sources] +dataclass-native = { path = "../..", editable = true } diff --git a/examples/functions-rust/python/shop/__init__.py b/examples/functions-rust/python/shop/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/functions-rust/python/shop/model.py b/examples/functions-rust/python/shop/model.py new file mode 100644 index 0000000..93fabf0 --- /dev/null +++ b/examples/functions-rust/python/shop/model.py @@ -0,0 +1,48 @@ +import datetime as dt +from dataclasses import dataclass +from enum import Enum, auto + +from dataclass_native import Int32, Shared, native + + +class Status(Enum): + PENDING = auto() + SHIPPED = auto() + DELIVERED = auto() + + +@native +@dataclass(frozen=True) +class Address: + street: str + city: str + postcode: str + country: str = "GB" + + +@native +@dataclass(frozen=True) +class Customer: + id: int + name: str + address: Address + email: str | None = None + + +@native +@dataclass(frozen=True) +class Line: + sku: str + quantity: Int32 + unit_price: float + + +@native +@dataclass(frozen=True) +class Order: + id: int + customer: Shared[Customer] # Shared by a customer's orders, not copied into each + lines: tuple[Line, ...] + placed: dt.date + status: Status = Status.PENDING + ship_to: Address | None = None # The customer's address, if None diff --git a/examples/functions-rust/python/shop/pricing.py b/examples/functions-rust/python/shop/pricing.py new file mode 100644 index 0000000..c1e1669 --- /dev/null +++ b/examples/functions-rust/python/shop/pricing.py @@ -0,0 +1,18 @@ +"""Functions of orders, implemented in Rust by src/pricing.rs: their bodies are what runs in pure mode""" + +from dataclasses import replace + +from dataclass_native import native_function + +from .model import Address, Order, Status + + +@native_function("._native") +def total(order: Order) -> float: + return sum(line.quantity * line.unit_price for line in order.lines) + + +@native_function("._native") +def ship(order: Order, to: Address | None = None) -> Order: + """The order, shipped to the address given, or else to its customer's""" + return replace(order, status=Status.SHIPPED, ship_to=to or order.customer.address) diff --git a/examples/functions-rust/src/lib.rs b/examples/functions-rust/src/lib.rs new file mode 100644 index 0000000..84cfc16 --- /dev/null +++ b/examples/functions-rust/src/lib.rs @@ -0,0 +1,20 @@ +//! The extension shop._native: the classes which hold Python's objects in the generated structs, and the functions +//! of pricing.rs, for those of python/shop/pricing.py + +mod pricing; +// Generated from python/shop, by build.rs +#[allow(dead_code)] +mod shop; +mod shop_native; + +use dataclass_native::python::{function, Held}; +use pyo3::prelude::*; +use shop::model::{Address, Order}; + +#[pymodule(name = "_native")] +fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> { + shop_native::register(extension)?; + // A Held is the struct in which Python's order is stored, not a copy of it + function(extension, "total", |order: Held| pricing::total(&order))?; + function(extension, "ship", |order: Held, to: Option
| pricing::ship(&order, to)) +} diff --git a/examples/functions-rust/src/pricing.rs b/examples/functions-rust/src/pricing.rs new file mode 100644 index 0000000..3cef2ad --- /dev/null +++ b/examples/functions-rust/src/pricing.rs @@ -0,0 +1,13 @@ +//! Plain Rust, of the generated structs: nothing here knows about Python + +use crate::shop::model::{Address, Order, Status}; + +pub fn total(order: &Order) -> f64 { + order.lines.iter().map(|line| f64::from(line.quantity) * line.unit_price).sum() +} + +/// The order, shipped to the address given, or else to its customer's +pub fn ship(order: &Order, to: Option
) -> Order { + let ship_to = to.unwrap_or_else(|| order.customer.address.clone()); + Order { status: Status::SHIPPED, ship_to: Some(ship_to), ..order.clone() } +} diff --git a/examples/parquet-rust/.gitignore b/examples/parquet-rust/.gitignore new file mode 100644 index 0000000..2a041df --- /dev/null +++ b/examples/parquet-rust/.gitignore @@ -0,0 +1,4 @@ +# Generated from python/shop, by build.rs +/src/shop/ +/target/ +Cargo.lock diff --git a/examples/parquet-rust/Cargo.toml b/examples/parquet-rust/Cargo.toml new file mode 100644 index 0000000..e4f738b --- /dev/null +++ b/examples/parquet-rust/Cargo.toml @@ -0,0 +1,16 @@ +# A program which writes the objects of a schema as Parquet files, and reads them back, in Rust alone +[package] +name = "orders" +version = "0.0.0" +edition = "2021" +publish = false + +[dependencies] +# dataclass-native's own crate. In a project of your own it is that of crates.io, of the version of the Python +# package which generates the Rust: dataclass_native = { version = "=1.2.0", features = ["arrow"] }. Here it is +# that of this repository +dataclass_native = { path = "../../src/dataclass_native/rust", features = ["arrow"] } +# arrow-rs's Parquet, which dataclass-native does not depend on: of the version of arrow-rs which dataclass_native +# is of, as it is its arrays which this writes +parquet = { version = "59", default-features = false, features = ["arrow", "snap"] } +arrow-select = "59" diff --git a/examples/parquet-rust/build.rs b/examples/parquet-rust/build.rs new file mode 100644 index 0000000..cb49759 --- /dev/null +++ b/examples/parquet-rust/build.rs @@ -0,0 +1,16 @@ +//! Generates the Rust of the schema, src/shop, from python/shop: as `dataclass-native generate rust` does. By the +//! Python which PYTHON names, or python3, which is to have dataclass-native installed. + +use std::process::Command; + +fn main() { + println!("cargo:rerun-if-changed=python/shop"); + println!("cargo:rerun-if-env-changed=PYTHON"); + let python = std::env::var("PYTHON").unwrap_or_else(|_| "python3".to_string()); + let generated = Command::new(&python) + .args(["-m", "dataclass_native", "generate", "rust", "--package", "shop", "--out", "src"]) + .env("PYTHONPATH", "python") + .status() + .unwrap_or_else(|error| panic!("{python} could not be run, to generate the Rust of the schema: {error}")); + assert!(generated.success(), "dataclass-native did not generate the Rust of the schema"); +} diff --git a/examples/parquet-rust/python/shop/__init__.py b/examples/parquet-rust/python/shop/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/parquet-rust/python/shop/model.py b/examples/parquet-rust/python/shop/model.py new file mode 100644 index 0000000..93fabf0 --- /dev/null +++ b/examples/parquet-rust/python/shop/model.py @@ -0,0 +1,48 @@ +import datetime as dt +from dataclasses import dataclass +from enum import Enum, auto + +from dataclass_native import Int32, Shared, native + + +class Status(Enum): + PENDING = auto() + SHIPPED = auto() + DELIVERED = auto() + + +@native +@dataclass(frozen=True) +class Address: + street: str + city: str + postcode: str + country: str = "GB" + + +@native +@dataclass(frozen=True) +class Customer: + id: int + name: str + address: Address + email: str | None = None + + +@native +@dataclass(frozen=True) +class Line: + sku: str + quantity: Int32 + unit_price: float + + +@native +@dataclass(frozen=True) +class Order: + id: int + customer: Shared[Customer] # Shared by a customer's orders, not copied into each + lines: tuple[Line, ...] + placed: dt.date + status: Status = Status.PENDING + ship_to: Address | None = None # The customer's address, if None diff --git a/examples/parquet-rust/read.py b/examples/parquet-rust/read.py new file mode 100644 index 0000000..5165385 --- /dev/null +++ b/examples/parquet-rust/read.py @@ -0,0 +1,11 @@ +"""Reads, in Python, the orders which the Rust program wrote""" + +import sys + +from dataclass_native import from_parquet +from shop.model import Order + +orders = from_parquet(Order, sys.argv[1] if len(sys.argv) > 1 else "orders") +for order in orders: + print(order) +print(f"The customer is still shared: {orders[0].customer is orders[1].customer}") diff --git a/examples/parquet-rust/src/main.rs b/examples/parquet-rust/src/main.rs new file mode 100644 index 0000000..69e6fdf --- /dev/null +++ b/examples/parquet-rust/src/main.rs @@ -0,0 +1,61 @@ +//! Writes orders as Parquet files, and reads them back, in Rust alone. Given `read` after the directory, it only +//! reads them: as Python or C++ may have written them. + +mod parquet_files; +// Generated from python/shop/model.py, by build.rs +#[allow(dead_code)] +mod shop; + +use dataclass_native::{Date, Shared}; +use parquet_files::{from_parquet, to_parquet}; +use shop::model::{Address, Customer, Line, Order, Status}; +use std::path::PathBuf; + +fn main() -> Result<(), Box> { + let mut arguments = std::env::args().skip(1); + let directory = PathBuf::from(arguments.next().unwrap_or("orders".to_string())); + let only_read = arguments.next().as_deref() == Some("read"); + + // Shared by her orders, so written once: as a row of the customers' own file + let address = + Address { street: "1 High St".into(), city: "Leeds".into(), postcode: "LS1 1AA".into(), ..Address::default() }; + let alice = Shared::new(Customer { id: 1, name: "Alice".into(), address, ..Customer::default() }); + // 2026-11-27, as the days since 1970-01-01 which a Date is + let placed = Date(20_784); + let line = |sku: &str, quantity, unit_price| Line { sku: sku.into(), quantity, unit_price }; + let orders = vec![ + Order { + id: 100, + customer: alice.clone(), + lines: vec![line("widget", 2, 9.99), line("gadget", 1, 24.5)], + placed, + ..Order::default() + }, + Order { + id: 101, + customer: alice.clone(), + lines: vec![line("widget", 5, 9.99)], + placed: Date(placed.0 + 1), + status: Status::SHIPPED, + ship_to: Some(Address { + street: "2 Low Rd".into(), + city: "York".into(), + postcode: "YO1 7HH".into(), + ..Address::default() + }), + }, + ]; + + if !only_read { + to_parquet(&orders, &directory)?; + println!("Wrote {} orders to {}", orders.len(), directory.display()); + } + + let read: Vec = from_parquet(&directory)?; + println!("Read them back the same: {}", read == orders); + println!("The customer is still shared: {}", Shared::ptr_eq(&read[0].customer, &read[1].customer)); + if read != orders { + return Err("What was read is not what was written".into()); + } + Ok(()) +} diff --git a/examples/parquet-rust/src/parquet_files.rs b/examples/parquet-rust/src/parquet_files.rs new file mode 100644 index 0000000..c5cb640 --- /dev/null +++ b/examples/parquet-rust/src/parquet_files.rs @@ -0,0 +1,66 @@ +//! Parquet files of the structs which dataclass-native generates, written and read with arrow-rs's parquet: as +//! Python's to_parquet and from_parquet write and read them. To copy from: dataclass-native has no need of +//! Parquet, so has none of this. + +use arrow_select::concat::concat_batches; +use dataclass_native::arrow::arrow_array::RecordBatch; +use dataclass_native::arrow::{from_arrow, to_arrow, Table, Tables, TAG}; +use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; +use parquet::arrow::ArrowWriter; +use std::error::Error; +use std::fs::{self, File}; +use std::path::Path; + +type Result = std::result::Result>; + +/// A table as a file: with its Arrow schema, so that it is read back as the table it was +fn write(table: &RecordBatch, path: &Path) -> Result<()> { + let mut writer = ArrowWriter::try_new(File::create(path)?, table.schema(), None)?; + writer.write(table)?; + writer.close()?; + Ok(()) +} + +fn read(path: &Path) -> Result { + let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(path)?)?; + let schema = reader.schema().clone(); + let batches = reader.build()?.collect::, _>>()?; + Ok(concat_batches(&schema, &batches)?) +} + +/// The file of the table of a shared class: named by its tag, percent-encoded but for letters, digits and `-._~` +fn file_name(tag: &str) -> String { + let encoded = |byte: u8| match byte { + b'-' | b'.' | b'_' | b'~' => char::from(byte).to_string(), + byte if byte.is_ascii_alphanumeric() => char::from(byte).to_string(), + byte => format!("%{byte:02X}"), + }; + tag.bytes().map(encoded).collect::() + ".parquet" +} + +/// Writes objects as Parquet: root.parquet, and a file in shared/ for each class they may share +pub fn to_parquet<'a, T: Table>(values: impl IntoIterator, directory: &Path) -> Result<()> { + let tables = to_arrow(values)?; + fs::create_dir_all(directory)?; + write(&tables.root, &directory.join("root.parquet"))?; + for (tag, table) in &tables.shared { + fs::create_dir_all(directory.join("shared"))?; + write(table, &directory.join("shared").join(file_name(tag)))?; + } + Ok(()) +} + +/// The objects which to_parquet wrote: here, or in Python or C++ +pub fn from_parquet(directory: &Path) -> Result> { + let root = read(&directory.join("root.parquet"))?; + let mut shared = Vec::new(); + if let Ok(files) = fs::read_dir(directory.join("shared")) { + for file in files { + let table = read(&file?.path())?; + // Each says which class it is of, as well as its name does + let tag = table.schema().metadata().get(TAG).ok_or("A shared table does not say which class it is of")?.clone(); + shared.push((tag, table)); + } + } + Ok(from_arrow(&Tables { root, shared })?) +} diff --git a/src/dataclass_native/backends/pyo3.py b/src/dataclass_native/backends/pyo3.py index e932491..84455cc 100644 --- a/src/dataclass_native/backends/pyo3.py +++ b/src/dataclass_native/backends/pyo3.py @@ -64,7 +64,7 @@ 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, unexpected_cfgs, clippy::all)]\n\n" + "#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unexpected_cfgs, unused_imports, 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" diff --git a/src/dataclass_native/rust/Cargo.toml b/src/dataclass_native/rust/Cargo.toml index ccc7555..3fda3e3 100644 --- a/src/dataclass_native/rust/Cargo.toml +++ b/src/dataclass_native/rust/Cargo.toml @@ -1,12 +1,13 @@ -# The types used by the Rust which dataclass-native generates. A crate to depend on by path, which +# The types used by the Rust which dataclass-native generates. It is on crates.io, and in the Python package, where # `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" +# That of the Python package it is released with, which is the tag's: the release is refused if they differ +version = "1.2.0" edition = "2021" description = "Types used by the Rust generated by dataclass-native" license = "MIT" -publish = false +repository = "https://github.com/nickyoung-github/dataclass-native" [lib] path = "src/lib.rs" diff --git a/tests/test_examples.py b/tests/test_examples.py index f79e490..827ab4b 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -1,10 +1,12 @@ -"""The projects of examples: built with CMake, as scikit-build-core builds them, and their demos run in each mode""" +"""The projects of examples: built with CMake, as scikit-build-core builds them, and their demos run in each mode. And +that of Rust, built with cargo""" import os import re import shutil import subprocess import sys +from importlib.machinery import EXTENSION_SUFFIXES from pathlib import Path import pytest @@ -28,7 +30,11 @@ def _demo(example: str, installed: Path) -> dict[Mode, list[str]]: # The example's package, with its extensions: as its wheel has them shutil.copytree(source / "src", installed, dirs_exist_ok=True) _cmake("--install", str(build), "--prefix", str(installed), *RELEASE) + return _modes(source, installed) + +def _modes(source: Path, installed: Path) -> dict[Mode, list[str]]: + """The lines which an example's demo prints in each mode, with its package where it is installed""" lines = {} for mode in Mode: result = subprocess.run( @@ -65,6 +71,45 @@ def test_functions(tmp_path): assert lines[Mode.STRICT][2] == "Still sharing the customer: True" +def test_functions_rust(tmp_path): + """The extension in Rust which maturin builds: built here by cargo, as maturin builds it""" + if shutil.which("cargo") is None: + pytest.skip("No cargo") + source = EXAMPLES / "functions-rust" + target = BUILD / "examples" / "functions-rust" + result = subprocess.run( + ["cargo", "build", "--quiet"], + cwd=source, + # As maturin says: which Python it is for, whose its build.rs generates the Rust with, and that it is an + # extension, so is not linked with Python + env=os.environ + | { + "PYO3_PYTHON": sys.executable, + "PYO3_BUILD_EXTENSION_MODULE": "1", + "CARGO_TARGET_DIR": str(target), + }, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + # The example's package, with its extension: as its wheel has them + shutil.copytree(source / "python", tmp_path, dirs_exist_ok=True) + (library,) = ( + path + for name in ("lib_native.so", "lib_native.dylib", "_native.dll") + if (path := target / "debug" / name).is_file() + ) + shutil.copyfile(library, tmp_path / "shop" / f"_native{EXTENSION_SUFFIXES[0]}") + + lines = _modes(source, tmp_path) + # The Rust and the Python implementations agree: and with those of C++, of the example which that is of + assert lines[Mode.STRICT] == lines[Mode.MIXED] == lines[Mode.PURE] + assert lines[Mode.STRICT][0] == "Total: 44.48" + assert lines[Mode.STRICT][2] == "Still sharing the customer: True" + + def test_parquet(tmp_path): """The C++ program which writes Parquet: built by its own CMakeLists.txt, with the Arrow C++ which pyarrow has""" pa = pytest.importorskip("pyarrow") @@ -136,3 +181,65 @@ def test_parquet(tmp_path): lines = read.stdout.splitlines() assert len(lines) == 3 and lines[0].startswith("Order(id=100, customer=Customer(") assert lines[2] == "The customer is still shared: True" + + +def test_parquet_rust(tmp_path): + """The Rust program which writes Parquet: built by cargo, with the Parquet of arrow-rs""" + pytest.importorskip("pyarrow") + if shutil.which("cargo") is None: + pytest.skip("No cargo") + source = EXAMPLES / "parquet-rust" + python = {ENV_VAR: Mode.PURE, "PYTHONPATH": str(source / "python")} + + def run(*arguments: str) -> list[str]: + result = subprocess.run( + ["cargo", "run", "--quiet", "--", *arguments], + cwd=source, + # Its build.rs generates the Rust of the schema with this Python: built where the tests build + env=os.environ + | { + "PYTHON": sys.executable, + "CARGO_TARGET_DIR": str(BUILD / "examples" / "parquet-rust"), + }, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + return result.stdout.splitlines() + + same = ["Read them back the same: true", "The customer is still shared: true"] + orders = tmp_path / "orders" + assert run(str(orders))[1:] == same + assert sorted( + p.relative_to(orders).as_posix() for p in orders.rglob("*.parquet") + ) == [ + "root.parquet", + "shared/shop.model.Customer.parquet", + ] + + # And Python reads what Rust wrote + read = subprocess.run( + [sys.executable, str(source / "read.py"), str(orders)], + env=os.environ | python, + capture_output=True, + text=True, + check=False, + ) + assert read.returncode == 0, read.stderr + lines = read.stdout.splitlines() + assert len(lines) == 3 and lines[0].startswith("Order(id=100, customer=Customer(") + assert lines[2] == "The customer is still shared: True" + + # And Rust what Python writes: here, of what it read + written = tmp_path / "written" + script = ( + "import sys; from dataclass_native import from_parquet, to_parquet; from shop.model import Order; " + "to_parquet(from_parquet(Order, sys.argv[1]), sys.argv[2])" + ) + subprocess.run( + [sys.executable, "-c", script, str(orders), str(written)], + env=os.environ | python, + check=True, + ) + assert run(str(written), "read") == same