arrow2xmla 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/Cargo.lock +2 -2
  2. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/Cargo.toml +1 -1
  3. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/PKG-INFO +88 -40
  4. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/README.md +87 -37
  5. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/README.md +87 -37
  6. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla-py/src/lib.rs +405 -0
  7. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/pyproject.toml +0 -3
  8. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/python/arrow2xmla/__init__.py +7 -8
  9. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/python/arrow2xmla/_model.py +36 -12
  10. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/LICENSE +0 -0
  11. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/Cargo.toml +0 -0
  12. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/examples/basic.rs +0 -0
  13. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/array.rs +0 -0
  14. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/cellset.rs +0 -0
  15. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/display.rs +0 -0
  16. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/esc.rs +0 -0
  17. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/float.rs +0 -0
  18. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/lib.rs +0 -0
  19. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/model.rs +0 -0
  20. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/request.rs +0 -0
  21. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/rowset.rs +0 -0
  22. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla/src/soap.rs +0 -0
  23. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/crates/arrow2xmla-py/Cargo.toml +0 -0
  24. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/python/arrow2xmla/_request.py +0 -0
  25. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/python/arrow2xmla/_soap.py +0 -0
  26. {arrow2xmla-0.2.0 → arrow2xmla-0.3.0}/python/arrow2xmla/py.typed +0 -0
@@ -76,7 +76,7 @@ checksum = "3e7574c4175cc731e0d26a8384bc25d455c5e220250988a772c1af843592444b"
76
76
 
77
77
  [[package]]
78
78
  name = "arrow2xmla"
79
- version = "0.2.0"
79
+ version = "0.3.0"
80
80
  dependencies = [
81
81
  "arrow-array",
82
82
  "arrow-schema",
@@ -87,7 +87,7 @@ dependencies = [
87
87
 
88
88
  [[package]]
89
89
  name = "arrow2xmla-py"
90
- version = "0.2.0"
90
+ version = "0.3.0"
91
91
  dependencies = [
92
92
  "arrow2xmla",
93
93
  "pyo3",
@@ -3,7 +3,7 @@ resolver = "2"
3
3
  members = ["crates/arrow2xmla", "crates/arrow2xmla-py"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.2.0"
6
+ version = "0.3.0"
7
7
  edition = "2021"
8
8
  rust-version = "1.88"
9
9
  license = "MIT"
@@ -1,11 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: arrow2xmla
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: 3
6
6
  Classifier: Topic :: Database
7
- Requires-Dist: pyarrow>=15 ; extra == 'pyarrow'
8
- Provides-Extra: pyarrow
9
7
  License-File: LICENSE
10
8
  Summary: Arrow in, XMLA out: a generic, engine-free XMLA cellset writer and request parser (Rust core).
11
9
  Keywords: xmla,arrow,excel,olap,mdx
@@ -44,6 +42,26 @@ A pivot of 490 000 rows × 3 measures is **296 MB of XML**. arrow2xmla writes it
44
42
  | **arrow2xmla, 1 thread** | **81 ms** | **3.6 GB/s** | **16×** |
45
43
  | **arrow2xmla, all cores** (`threads=0`) | **23 ms** | **12.8 GB/s** | **57×** |
46
44
 
45
+ ### From DuckDB
46
+
47
+ The same pivot straight from a DuckDB query (500 000 customers × 3 measures, the All row first and the customers sorted: a
48
+ **330 MB** answer), measured from the query to the finished XML:
49
+
50
+ | Route | Time | Throughput |
51
+ |---|---:|---:|
52
+ | `ax.columns(rel)` → `cellset.write_to(sink)`, streamed | **32 ms** | **10.4 GB/s** |
53
+ | `ax.columns(rel)` → `cellset.iter_xml()`, streamed | 34 ms | 9.8 GB/s |
54
+ | `rel.to_arrow_table()` → `cellset.to_xml()` | 33 ms | 9.9 GB/s |
55
+ | `ax.columns(rel)` → `cellset.to_xml()`, whole bytes | 38 ms | 8.7 GB/s |
56
+ | `rel.fetchall()` → plain-Python writer | 1 538 ms | 0.2 GB/s |
57
+
58
+ Of those 32 ms, DuckDB running the queries and `columns()` copying the result into arrays take about 13 ms (the sort and the
59
+ second query for the All row are most of it; one unsorted query is 4.7 ms), and writing the XML takes about 20 ms. Streaming
60
+ with `write_to` beats `to_xml()` by about 20% and holds about 1 MB instead of the whole answer. At 3 000 000 customers (a 2 GB
61
+ answer) the routes take 190 to 240 ms. DuckDB's own threads matter: 1 thread 54 ms, 4 or more 37 ms.
62
+ Reproduce with `uv run --with duckdb python benchmarks/duckdb_bench.py --rows 500000`; it checks that every route writes the
63
+ same bytes (except the All row, whose parallel `sum` can differ in its last digits from run to run).
64
+
47
65
  More cases (`uv run pytest benchmarks --benchmark-only`, mean time per call):
48
66
 
49
67
  | Case | Answer | Time |
@@ -77,39 +95,49 @@ Arrow crates in it: arrays are read through the Arrow C interface.
77
95
  pip install arrow2xmla
78
96
  ```
79
97
 
80
- Python 3.10+, one `abi3` wheel per platform (Linux, macOS, Windows). `pyarrow` is optional: any library that exports the
81
- Arrow PyCapsule interface works (`pyarrow`, `nanoarrow`, ...; a `polars` Series goes through `pyarrow`, or `.to_arrow()` it first).
98
+ Python 3.10+, one `abi3` wheel per platform (Linux, macOS, Windows). Data comes in through the
99
+ Arrow PyCapsule interface: `columns(table)` reads the columns of anything that exports `__arrow_c_stream__` (a DuckDB relation, a
100
+ polars DataFrame, a pyarrow Table), and an array that exports `__arrow_c_array__` (pyarrow, nanoarrow, ...) is read in place.
101
+
102
+ The Rust crate is not published on crates.io; the package is PyPI only. To use the crate from Rust, depend on it from git
103
+ (Rust 1.88+):
82
104
 
83
105
  ```toml
84
- # Cargo.toml (Rust 1.88+)
85
- arrow2xmla = "0.2"
106
+ arrow2xmla = { git = "https://github.com/bmsuisse/arrow2xmla", tag = "v0.3.0" }
86
107
  ```
87
108
 
88
109
  ## Quick start
89
110
 
90
- Abridged from [`examples/quickstart.py`](examples/quickstart.py), which runs as it is (the snippet leaves out the request body).
111
+ With DuckDB. This is [`examples/quickstart.py`](examples/quickstart.py), which runs as it is
112
+ (`uv run --with duckdb python examples/quickstart.py`); the snippet shortens its data and leaves out the request body.
91
113
 
92
114
  ```python
93
- import pyarrow as pa
115
+ import duckdb
116
+ import arrow2xmla as ax
94
117
  from arrow2xmla import CellValues, Cellset, Discover, Execute, LevelAxis, Member, MemberProperty, MemberType, TupleAxis, parse_request
95
118
 
96
- # the rows: one member per customer, read straight from an Arrow text column (nothing is built per value)
97
- customers = pa.array(["Acme", "Globex", None, "Initech & Co"])
119
+ con = duckdb.connect()
120
+ con.sql("create table orders as select * from (values ('Acme', 1000.5), ('Acme', 500.0), ('Globex', 920.0), (NULL, 77.25)) t(customer, amount)")
121
+ by_customer = "select customer, sum(amount) as revenue, count(*) as orders from orders group by customer"
122
+
123
+ # the rows of the pivot: one member per customer, read from the result of a query (NULL is the blank member)
124
+ customers = ax.columns(con.sql(f"select customer from ({by_customer}) order by customer nulls last"))["customer"]
125
+ # the cells: the All row first, then the customers in the same order
126
+ cells = ax.columns(con.sql(f"""
127
+ select revenue, orders from (
128
+ select 0 as k, null as customer, sum(revenue) as revenue, sum(orders) as orders from ({by_customer})
129
+ union all select 1, customer, revenue, orders from ({by_customer})
130
+ ) order by k, customer nulls last"""))
131
+
98
132
  customer = Member("[Customer].[Name]", "[Customer].[Name].[Name]", 1, parent_unique_name="[Customer].[Name].[All]")
99
133
  all_customers = Member("[Customer].[Name]", "[Customer].[Name].[(All)]", 0, "[Customer].[Name].[All]", "All", member_type=MemberType.ALL)
100
-
101
- # the columns: two measures, listed once
102
134
  measure = lambda name: Member("[Measures]", "[Measures].[MeasuresLevel]", 0, f"[Measures].[{name}]", name, member_type=MemberType.MEASURE)
103
135
 
104
136
  cellset = Cellset(
105
137
  cube="Sales",
106
138
  columns_axis=TupleAxis.from_tuples([[measure("Revenue")], [measure("Orders")]]),
107
139
  rows_axis=LevelAxis(customer, customers, all=all_customers, properties=[MemberProperty.MEMBER_CAPTION]),
108
- # one array per column of cells, in the order of the columns axis; a null is an empty cell
109
- values=[
110
- CellValues(pa.array([1500.5, 920.0, None, 77.25, 12.0]), "#,##0.00"), # the All row, then the customers
111
- CellValues(pa.array([30, 12, 1, 4, 2]), "0"),
112
- ],
140
+ values=[CellValues(cells["revenue"], "#,##0.00"), CellValues(cells["orders"], "0")], # one per column of the pivot
113
141
  )
114
142
  xml = cellset.to_xml() # bytes: an XMLA MDDataset, for the body of an Execute response
115
143
 
@@ -119,6 +147,23 @@ match request.call:
119
147
  case Discover(request_type=kind): ...
120
148
  ```
121
149
 
150
+ `ax.columns(...)` takes the result of any query, with no casts: DuckDB's `DECIMAL` (what `sum(amount)` and decimal literals are)
151
+ is read as a double, and a whole-number decimal or `HUGEINT` (a sum of integers) as an int64 when it fits. The same works with
152
+ polars (`ax.columns(df)`) and pyarrow (`ax.columns(table)`), and arrays you already hold (`pa.array([...])`) go straight into
153
+ `CellValues`.
154
+
155
+ Tested with DuckDB 1.1.3, 1.2.2, 1.3.2, 1.4.4, 1.5.2 and 2.0.1 (CI runs the examples against several of them). Older DuckDB does not export Arrow streams.
156
+
157
+ ### Examples
158
+
159
+ Each runs as it is with `uv run --with duckdb python examples/<name>.py`:
160
+
161
+ - [`examples/quickstart.py`](examples/quickstart.py): a pivot answer from a DuckDB query, and a parsed request.
162
+ - [`examples/streaming.py`](examples/streaming.py): a million customers written with `write_to` and `iter_xml`, with the time
163
+ and the memory it takes (`EXAMPLE_ROWS=20000` for a quick run).
164
+ - [`examples/server.py`](examples/server.py): a complete XMLA endpoint over the standard library's `http.server`
165
+ (`python examples/server.py --port 8000`): sessions, the Discover rowsets, a streamed pivot, faults.
166
+
122
167
  ### In Rust
123
168
 
124
169
  [`crates/arrow2xmla/examples/basic.rs`](crates/arrow2xmla/examples/basic.rs): the same model over zero-copy `Array`s.
@@ -137,35 +182,37 @@ let xml = cellset.to_vec()?; // or cellset.write_to(&mut writer), or write_chu
137
182
  ## A server
138
183
 
139
184
  The three writers (cellset, rowset, fault) and the envelope are all a server needs next to `parse_request`; what it
140
- answers with is up to it. This is the shape of one (the mock endpoint in
141
- [`tests/e2e/xmla_mock.py`](tests/e2e/xmla_mock.py) is a complete one, read by olap4j in the tests):
185
+ answers with is up to it. [`examples/server.py`](examples/server.py) is a complete one in the standard library's
186
+ `http.server` over an in-memory DuckDB table (`python examples/server.py --port 8000`): it answers the Discover requests
187
+ Excel opens with, honours their restrictions, echoes sessions, streams the pivot of an Execute and answers a request it
188
+ refuses with a fault. It does not parse MDX, which is the engine's job. Its core, abridged:
142
189
 
143
190
  ```python
144
- import itertools
145
- import pyarrow as pa
146
- import arrow2xmla as ax
147
-
148
- def answer(body: bytes):
149
- """-> (HTTP status, an iterable of bytes)"""
191
+ def answer(con, body: bytes):
192
+ """-> (HTTP status, a list of bytes, or an iterator of bytes to stream)"""
150
193
  try:
151
- request = ax.parse_request(body, max_size=1 << 20)
194
+ request = ax.parse_request(body, max_size=MAX_REQUEST)
195
+ session = {ax.SessionKind.BEGIN: str(uuid.uuid4()), ax.SessionKind.USE: request.session.id}.get(request.session.kind)
196
+ match request.call:
197
+ case ax.Discover() as call: # a rowset from a DuckDB query: Rowset.from_columns(ax.columns(con.sql(...)))
198
+ return 200, [ax.Envelope(ax.Method.DISCOVER, session).wrap(discover(con, call))]
199
+ case ax.Execute(statement=mdx):
200
+ envelope = ax.Envelope(ax.Method.EXECUTE, session)
201
+ chunks = pivot(con).iter_xml() # your engine: the Cellset for the statement
202
+ first = next(chunks) # whatever is wrong with the cellset is raised here, before anything is sent
203
+ return 200, itertools.chain([envelope.head(), first], chunks, [envelope.tail()]) # lazy: ~1 MB in memory
204
+ return 500, [ax.fault("only Discover and Execute are supported", session=session)]
152
205
  except ax.XmlaError as e:
153
- return 500, [ax.fault(str(e))]
154
- session = "new-id" if request.session.kind is ax.SessionKind.BEGIN else request.session.id
155
- match request.call:
156
- case ax.Discover(request_type="MDSCHEMA_CUBES"):
157
- rows = ax.Rowset.from_columns({"CUBE_NAME": pa.array(["Sales"]), "CUBE_TYPE": pa.array(["CUBE"])})
158
- return 200, [ax.Envelope(ax.Method.DISCOVER, session).wrap(rows.to_xml())]
159
- case ax.Execute(statement=mdx):
160
- envelope = ax.Envelope(ax.Method.EXECUTE, session)
161
- cellset = run(mdx) # your engine: an ax.Cellset over its Arrow results
162
- return 200, itertools.chain([envelope.head()], cellset.iter_xml(), [envelope.tail()]) # lazy: ~1 MB in memory
163
- return 500, [ax.fault("not supported", session=session)]
206
+ return 500, [ax.fault(str(e), session=session)]
164
207
  ```
165
208
 
209
+ The handler sends a list with a `Content-Length`, and an iterator as HTTP/1.1 chunked transfer, so a 300 MB answer is never
210
+ whole in memory.
211
+
166
212
  ### Streaming
167
213
 
168
- `to_xml()` builds the whole answer (about twice its size in memory at the peak). For a big one:
214
+ `to_xml()` builds the whole answer (about twice its size in memory at the peak). For a big one,
215
+ [`examples/streaming.py`](examples/streaming.py) writes a million customers (505 MB) both ways and checks they are the same:
169
216
 
170
217
  ```python
171
218
  with open("answer.xml", "wb") as fp:
@@ -210,9 +257,10 @@ byte is written:
210
257
  |---|---|
211
258
  | `int8` … `int64`, `uint8` … `uint64` | `xsd:int`; `xsd:long` / `xsd:unsignedLong` when 32 bits do not hold the value |
212
259
  | `float16`, `float32`, `float64` | `xsd:double`, Python's shortest `repr` digits; `NaN`, `INF`, `-INF` |
260
+ | `decimal32`/`64`/`128` (DuckDB's `DECIMAL` and `HUGEINT`; as an array or through `columns()`) | `xsd:int` / `xsd:long` when the scale is 0 and every value fits 64 bits, else `xsd:double` (the unscaled value divided by 10^scale) |
213
261
  | `string`, `large_string`, `string_view` | `xsd:string`, escaped |
214
262
  | null | no value: the cell is left out |
215
- | anything else (bool, dates, decimals, dictionaries, ...) | refused with `UnsupportedTypeError`: cast it first |
263
+ | anything else (bool, dates, 256-bit decimals, dictionaries, ...) | refused with `UnsupportedTypeError`, naming the column: cast it first |
216
264
 
217
265
  Characters XML 1.0 forbids are replaced with U+FFFD, so Excel's parser accepts the answer. Chunked arrays are combined
218
266
  first. Only `VALUE`, `FORMAT_STRING` and `LANGUAGE` are written in a cell (`CellProperty`); a property that is not
@@ -26,6 +26,26 @@ A pivot of 490 000 rows × 3 measures is **296 MB of XML**. arrow2xmla writes it
26
26
  | **arrow2xmla, 1 thread** | **81 ms** | **3.6 GB/s** | **16×** |
27
27
  | **arrow2xmla, all cores** (`threads=0`) | **23 ms** | **12.8 GB/s** | **57×** |
28
28
 
29
+ ### From DuckDB
30
+
31
+ The same pivot straight from a DuckDB query (500 000 customers × 3 measures, the All row first and the customers sorted: a
32
+ **330 MB** answer), measured from the query to the finished XML:
33
+
34
+ | Route | Time | Throughput |
35
+ |---|---:|---:|
36
+ | `ax.columns(rel)` → `cellset.write_to(sink)`, streamed | **32 ms** | **10.4 GB/s** |
37
+ | `ax.columns(rel)` → `cellset.iter_xml()`, streamed | 34 ms | 9.8 GB/s |
38
+ | `rel.to_arrow_table()` → `cellset.to_xml()` | 33 ms | 9.9 GB/s |
39
+ | `ax.columns(rel)` → `cellset.to_xml()`, whole bytes | 38 ms | 8.7 GB/s |
40
+ | `rel.fetchall()` → plain-Python writer | 1 538 ms | 0.2 GB/s |
41
+
42
+ Of those 32 ms, DuckDB running the queries and `columns()` copying the result into arrays take about 13 ms (the sort and the
43
+ second query for the All row are most of it; one unsorted query is 4.7 ms), and writing the XML takes about 20 ms. Streaming
44
+ with `write_to` beats `to_xml()` by about 20% and holds about 1 MB instead of the whole answer. At 3 000 000 customers (a 2 GB
45
+ answer) the routes take 190 to 240 ms. DuckDB's own threads matter: 1 thread 54 ms, 4 or more 37 ms.
46
+ Reproduce with `uv run --with duckdb python benchmarks/duckdb_bench.py --rows 500000`; it checks that every route writes the
47
+ same bytes (except the All row, whose parallel `sum` can differ in its last digits from run to run).
48
+
29
49
  More cases (`uv run pytest benchmarks --benchmark-only`, mean time per call):
30
50
 
31
51
  | Case | Answer | Time |
@@ -59,39 +79,49 @@ Arrow crates in it: arrays are read through the Arrow C interface.
59
79
  pip install arrow2xmla
60
80
  ```
61
81
 
62
- Python 3.10+, one `abi3` wheel per platform (Linux, macOS, Windows). `pyarrow` is optional: any library that exports the
63
- Arrow PyCapsule interface works (`pyarrow`, `nanoarrow`, ...; a `polars` Series goes through `pyarrow`, or `.to_arrow()` it first).
82
+ Python 3.10+, one `abi3` wheel per platform (Linux, macOS, Windows). Data comes in through the
83
+ Arrow PyCapsule interface: `columns(table)` reads the columns of anything that exports `__arrow_c_stream__` (a DuckDB relation, a
84
+ polars DataFrame, a pyarrow Table), and an array that exports `__arrow_c_array__` (pyarrow, nanoarrow, ...) is read in place.
85
+
86
+ The Rust crate is not published on crates.io; the package is PyPI only. To use the crate from Rust, depend on it from git
87
+ (Rust 1.88+):
64
88
 
65
89
  ```toml
66
- # Cargo.toml (Rust 1.88+)
67
- arrow2xmla = "0.2"
90
+ arrow2xmla = { git = "https://github.com/bmsuisse/arrow2xmla", tag = "v0.3.0" }
68
91
  ```
69
92
 
70
93
  ## Quick start
71
94
 
72
- Abridged from [`examples/quickstart.py`](examples/quickstart.py), which runs as it is (the snippet leaves out the request body).
95
+ With DuckDB. This is [`examples/quickstart.py`](examples/quickstart.py), which runs as it is
96
+ (`uv run --with duckdb python examples/quickstart.py`); the snippet shortens its data and leaves out the request body.
73
97
 
74
98
  ```python
75
- import pyarrow as pa
99
+ import duckdb
100
+ import arrow2xmla as ax
76
101
  from arrow2xmla import CellValues, Cellset, Discover, Execute, LevelAxis, Member, MemberProperty, MemberType, TupleAxis, parse_request
77
102
 
78
- # the rows: one member per customer, read straight from an Arrow text column (nothing is built per value)
79
- customers = pa.array(["Acme", "Globex", None, "Initech & Co"])
103
+ con = duckdb.connect()
104
+ con.sql("create table orders as select * from (values ('Acme', 1000.5), ('Acme', 500.0), ('Globex', 920.0), (NULL, 77.25)) t(customer, amount)")
105
+ by_customer = "select customer, sum(amount) as revenue, count(*) as orders from orders group by customer"
106
+
107
+ # the rows of the pivot: one member per customer, read from the result of a query (NULL is the blank member)
108
+ customers = ax.columns(con.sql(f"select customer from ({by_customer}) order by customer nulls last"))["customer"]
109
+ # the cells: the All row first, then the customers in the same order
110
+ cells = ax.columns(con.sql(f"""
111
+ select revenue, orders from (
112
+ select 0 as k, null as customer, sum(revenue) as revenue, sum(orders) as orders from ({by_customer})
113
+ union all select 1, customer, revenue, orders from ({by_customer})
114
+ ) order by k, customer nulls last"""))
115
+
80
116
  customer = Member("[Customer].[Name]", "[Customer].[Name].[Name]", 1, parent_unique_name="[Customer].[Name].[All]")
81
117
  all_customers = Member("[Customer].[Name]", "[Customer].[Name].[(All)]", 0, "[Customer].[Name].[All]", "All", member_type=MemberType.ALL)
82
-
83
- # the columns: two measures, listed once
84
118
  measure = lambda name: Member("[Measures]", "[Measures].[MeasuresLevel]", 0, f"[Measures].[{name}]", name, member_type=MemberType.MEASURE)
85
119
 
86
120
  cellset = Cellset(
87
121
  cube="Sales",
88
122
  columns_axis=TupleAxis.from_tuples([[measure("Revenue")], [measure("Orders")]]),
89
123
  rows_axis=LevelAxis(customer, customers, all=all_customers, properties=[MemberProperty.MEMBER_CAPTION]),
90
- # one array per column of cells, in the order of the columns axis; a null is an empty cell
91
- values=[
92
- CellValues(pa.array([1500.5, 920.0, None, 77.25, 12.0]), "#,##0.00"), # the All row, then the customers
93
- CellValues(pa.array([30, 12, 1, 4, 2]), "0"),
94
- ],
124
+ values=[CellValues(cells["revenue"], "#,##0.00"), CellValues(cells["orders"], "0")], # one per column of the pivot
95
125
  )
96
126
  xml = cellset.to_xml() # bytes: an XMLA MDDataset, for the body of an Execute response
97
127
 
@@ -101,6 +131,23 @@ match request.call:
101
131
  case Discover(request_type=kind): ...
102
132
  ```
103
133
 
134
+ `ax.columns(...)` takes the result of any query, with no casts: DuckDB's `DECIMAL` (what `sum(amount)` and decimal literals are)
135
+ is read as a double, and a whole-number decimal or `HUGEINT` (a sum of integers) as an int64 when it fits. The same works with
136
+ polars (`ax.columns(df)`) and pyarrow (`ax.columns(table)`), and arrays you already hold (`pa.array([...])`) go straight into
137
+ `CellValues`.
138
+
139
+ Tested with DuckDB 1.1.3, 1.2.2, 1.3.2, 1.4.4, 1.5.2 and 2.0.1 (CI runs the examples against several of them). Older DuckDB does not export Arrow streams.
140
+
141
+ ### Examples
142
+
143
+ Each runs as it is with `uv run --with duckdb python examples/<name>.py`:
144
+
145
+ - [`examples/quickstart.py`](examples/quickstart.py): a pivot answer from a DuckDB query, and a parsed request.
146
+ - [`examples/streaming.py`](examples/streaming.py): a million customers written with `write_to` and `iter_xml`, with the time
147
+ and the memory it takes (`EXAMPLE_ROWS=20000` for a quick run).
148
+ - [`examples/server.py`](examples/server.py): a complete XMLA endpoint over the standard library's `http.server`
149
+ (`python examples/server.py --port 8000`): sessions, the Discover rowsets, a streamed pivot, faults.
150
+
104
151
  ### In Rust
105
152
 
106
153
  [`crates/arrow2xmla/examples/basic.rs`](crates/arrow2xmla/examples/basic.rs): the same model over zero-copy `Array`s.
@@ -119,35 +166,37 @@ let xml = cellset.to_vec()?; // or cellset.write_to(&mut writer), or write_chu
119
166
  ## A server
120
167
 
121
168
  The three writers (cellset, rowset, fault) and the envelope are all a server needs next to `parse_request`; what it
122
- answers with is up to it. This is the shape of one (the mock endpoint in
123
- [`tests/e2e/xmla_mock.py`](tests/e2e/xmla_mock.py) is a complete one, read by olap4j in the tests):
169
+ answers with is up to it. [`examples/server.py`](examples/server.py) is a complete one in the standard library's
170
+ `http.server` over an in-memory DuckDB table (`python examples/server.py --port 8000`): it answers the Discover requests
171
+ Excel opens with, honours their restrictions, echoes sessions, streams the pivot of an Execute and answers a request it
172
+ refuses with a fault. It does not parse MDX, which is the engine's job. Its core, abridged:
124
173
 
125
174
  ```python
126
- import itertools
127
- import pyarrow as pa
128
- import arrow2xmla as ax
129
-
130
- def answer(body: bytes):
131
- """-> (HTTP status, an iterable of bytes)"""
175
+ def answer(con, body: bytes):
176
+ """-> (HTTP status, a list of bytes, or an iterator of bytes to stream)"""
132
177
  try:
133
- request = ax.parse_request(body, max_size=1 << 20)
178
+ request = ax.parse_request(body, max_size=MAX_REQUEST)
179
+ session = {ax.SessionKind.BEGIN: str(uuid.uuid4()), ax.SessionKind.USE: request.session.id}.get(request.session.kind)
180
+ match request.call:
181
+ case ax.Discover() as call: # a rowset from a DuckDB query: Rowset.from_columns(ax.columns(con.sql(...)))
182
+ return 200, [ax.Envelope(ax.Method.DISCOVER, session).wrap(discover(con, call))]
183
+ case ax.Execute(statement=mdx):
184
+ envelope = ax.Envelope(ax.Method.EXECUTE, session)
185
+ chunks = pivot(con).iter_xml() # your engine: the Cellset for the statement
186
+ first = next(chunks) # whatever is wrong with the cellset is raised here, before anything is sent
187
+ return 200, itertools.chain([envelope.head(), first], chunks, [envelope.tail()]) # lazy: ~1 MB in memory
188
+ return 500, [ax.fault("only Discover and Execute are supported", session=session)]
134
189
  except ax.XmlaError as e:
135
- return 500, [ax.fault(str(e))]
136
- session = "new-id" if request.session.kind is ax.SessionKind.BEGIN else request.session.id
137
- match request.call:
138
- case ax.Discover(request_type="MDSCHEMA_CUBES"):
139
- rows = ax.Rowset.from_columns({"CUBE_NAME": pa.array(["Sales"]), "CUBE_TYPE": pa.array(["CUBE"])})
140
- return 200, [ax.Envelope(ax.Method.DISCOVER, session).wrap(rows.to_xml())]
141
- case ax.Execute(statement=mdx):
142
- envelope = ax.Envelope(ax.Method.EXECUTE, session)
143
- cellset = run(mdx) # your engine: an ax.Cellset over its Arrow results
144
- return 200, itertools.chain([envelope.head()], cellset.iter_xml(), [envelope.tail()]) # lazy: ~1 MB in memory
145
- return 500, [ax.fault("not supported", session=session)]
190
+ return 500, [ax.fault(str(e), session=session)]
146
191
  ```
147
192
 
193
+ The handler sends a list with a `Content-Length`, and an iterator as HTTP/1.1 chunked transfer, so a 300 MB answer is never
194
+ whole in memory.
195
+
148
196
  ### Streaming
149
197
 
150
- `to_xml()` builds the whole answer (about twice its size in memory at the peak). For a big one:
198
+ `to_xml()` builds the whole answer (about twice its size in memory at the peak). For a big one,
199
+ [`examples/streaming.py`](examples/streaming.py) writes a million customers (505 MB) both ways and checks they are the same:
151
200
 
152
201
  ```python
153
202
  with open("answer.xml", "wb") as fp:
@@ -192,9 +241,10 @@ byte is written:
192
241
  |---|---|
193
242
  | `int8` … `int64`, `uint8` … `uint64` | `xsd:int`; `xsd:long` / `xsd:unsignedLong` when 32 bits do not hold the value |
194
243
  | `float16`, `float32`, `float64` | `xsd:double`, Python's shortest `repr` digits; `NaN`, `INF`, `-INF` |
244
+ | `decimal32`/`64`/`128` (DuckDB's `DECIMAL` and `HUGEINT`; as an array or through `columns()`) | `xsd:int` / `xsd:long` when the scale is 0 and every value fits 64 bits, else `xsd:double` (the unscaled value divided by 10^scale) |
195
245
  | `string`, `large_string`, `string_view` | `xsd:string`, escaped |
196
246
  | null | no value: the cell is left out |
197
- | anything else (bool, dates, decimals, dictionaries, ...) | refused with `UnsupportedTypeError`: cast it first |
247
+ | anything else (bool, dates, 256-bit decimals, dictionaries, ...) | refused with `UnsupportedTypeError`, naming the column: cast it first |
198
248
 
199
249
  Characters XML 1.0 forbids are replaced with U+FFFD, so Excel's parser accepts the answer. Chunked arrays are combined
200
250
  first. Only `VALUE`, `FORMAT_STRING` and `LANGUAGE` are written in a cell (`CellProperty`); a property that is not
@@ -26,6 +26,26 @@ A pivot of 490 000 rows × 3 measures is **296 MB of XML**. arrow2xmla writes it
26
26
  | **arrow2xmla, 1 thread** | **81 ms** | **3.6 GB/s** | **16×** |
27
27
  | **arrow2xmla, all cores** (`threads=0`) | **23 ms** | **12.8 GB/s** | **57×** |
28
28
 
29
+ ### From DuckDB
30
+
31
+ The same pivot straight from a DuckDB query (500 000 customers × 3 measures, the All row first and the customers sorted: a
32
+ **330 MB** answer), measured from the query to the finished XML:
33
+
34
+ | Route | Time | Throughput |
35
+ |---|---:|---:|
36
+ | `ax.columns(rel)` → `cellset.write_to(sink)`, streamed | **32 ms** | **10.4 GB/s** |
37
+ | `ax.columns(rel)` → `cellset.iter_xml()`, streamed | 34 ms | 9.8 GB/s |
38
+ | `rel.to_arrow_table()` → `cellset.to_xml()` | 33 ms | 9.9 GB/s |
39
+ | `ax.columns(rel)` → `cellset.to_xml()`, whole bytes | 38 ms | 8.7 GB/s |
40
+ | `rel.fetchall()` → plain-Python writer | 1 538 ms | 0.2 GB/s |
41
+
42
+ Of those 32 ms, DuckDB running the queries and `columns()` copying the result into arrays take about 13 ms (the sort and the
43
+ second query for the All row are most of it; one unsorted query is 4.7 ms), and writing the XML takes about 20 ms. Streaming
44
+ with `write_to` beats `to_xml()` by about 20% and holds about 1 MB instead of the whole answer. At 3 000 000 customers (a 2 GB
45
+ answer) the routes take 190 to 240 ms. DuckDB's own threads matter: 1 thread 54 ms, 4 or more 37 ms.
46
+ Reproduce with `uv run --with duckdb python benchmarks/duckdb_bench.py --rows 500000`; it checks that every route writes the
47
+ same bytes (except the All row, whose parallel `sum` can differ in its last digits from run to run).
48
+
29
49
  More cases (`uv run pytest benchmarks --benchmark-only`, mean time per call):
30
50
 
31
51
  | Case | Answer | Time |
@@ -59,39 +79,49 @@ Arrow crates in it: arrays are read through the Arrow C interface.
59
79
  pip install arrow2xmla
60
80
  ```
61
81
 
62
- Python 3.10+, one `abi3` wheel per platform (Linux, macOS, Windows). `pyarrow` is optional: any library that exports the
63
- Arrow PyCapsule interface works (`pyarrow`, `nanoarrow`, ...; a `polars` Series goes through `pyarrow`, or `.to_arrow()` it first).
82
+ Python 3.10+, one `abi3` wheel per platform (Linux, macOS, Windows). Data comes in through the
83
+ Arrow PyCapsule interface: `columns(table)` reads the columns of anything that exports `__arrow_c_stream__` (a DuckDB relation, a
84
+ polars DataFrame, a pyarrow Table), and an array that exports `__arrow_c_array__` (pyarrow, nanoarrow, ...) is read in place.
85
+
86
+ The Rust crate is not published on crates.io; the package is PyPI only. To use the crate from Rust, depend on it from git
87
+ (Rust 1.88+):
64
88
 
65
89
  ```toml
66
- # Cargo.toml (Rust 1.88+)
67
- arrow2xmla = "0.2"
90
+ arrow2xmla = { git = "https://github.com/bmsuisse/arrow2xmla", tag = "v0.3.0" }
68
91
  ```
69
92
 
70
93
  ## Quick start
71
94
 
72
- Abridged from [`examples/quickstart.py`](examples/quickstart.py), which runs as it is (the snippet leaves out the request body).
95
+ With DuckDB. This is [`examples/quickstart.py`](examples/quickstart.py), which runs as it is
96
+ (`uv run --with duckdb python examples/quickstart.py`); the snippet shortens its data and leaves out the request body.
73
97
 
74
98
  ```python
75
- import pyarrow as pa
99
+ import duckdb
100
+ import arrow2xmla as ax
76
101
  from arrow2xmla import CellValues, Cellset, Discover, Execute, LevelAxis, Member, MemberProperty, MemberType, TupleAxis, parse_request
77
102
 
78
- # the rows: one member per customer, read straight from an Arrow text column (nothing is built per value)
79
- customers = pa.array(["Acme", "Globex", None, "Initech & Co"])
103
+ con = duckdb.connect()
104
+ con.sql("create table orders as select * from (values ('Acme', 1000.5), ('Acme', 500.0), ('Globex', 920.0), (NULL, 77.25)) t(customer, amount)")
105
+ by_customer = "select customer, sum(amount) as revenue, count(*) as orders from orders group by customer"
106
+
107
+ # the rows of the pivot: one member per customer, read from the result of a query (NULL is the blank member)
108
+ customers = ax.columns(con.sql(f"select customer from ({by_customer}) order by customer nulls last"))["customer"]
109
+ # the cells: the All row first, then the customers in the same order
110
+ cells = ax.columns(con.sql(f"""
111
+ select revenue, orders from (
112
+ select 0 as k, null as customer, sum(revenue) as revenue, sum(orders) as orders from ({by_customer})
113
+ union all select 1, customer, revenue, orders from ({by_customer})
114
+ ) order by k, customer nulls last"""))
115
+
80
116
  customer = Member("[Customer].[Name]", "[Customer].[Name].[Name]", 1, parent_unique_name="[Customer].[Name].[All]")
81
117
  all_customers = Member("[Customer].[Name]", "[Customer].[Name].[(All)]", 0, "[Customer].[Name].[All]", "All", member_type=MemberType.ALL)
82
-
83
- # the columns: two measures, listed once
84
118
  measure = lambda name: Member("[Measures]", "[Measures].[MeasuresLevel]", 0, f"[Measures].[{name}]", name, member_type=MemberType.MEASURE)
85
119
 
86
120
  cellset = Cellset(
87
121
  cube="Sales",
88
122
  columns_axis=TupleAxis.from_tuples([[measure("Revenue")], [measure("Orders")]]),
89
123
  rows_axis=LevelAxis(customer, customers, all=all_customers, properties=[MemberProperty.MEMBER_CAPTION]),
90
- # one array per column of cells, in the order of the columns axis; a null is an empty cell
91
- values=[
92
- CellValues(pa.array([1500.5, 920.0, None, 77.25, 12.0]), "#,##0.00"), # the All row, then the customers
93
- CellValues(pa.array([30, 12, 1, 4, 2]), "0"),
94
- ],
124
+ values=[CellValues(cells["revenue"], "#,##0.00"), CellValues(cells["orders"], "0")], # one per column of the pivot
95
125
  )
96
126
  xml = cellset.to_xml() # bytes: an XMLA MDDataset, for the body of an Execute response
97
127
 
@@ -101,6 +131,23 @@ match request.call:
101
131
  case Discover(request_type=kind): ...
102
132
  ```
103
133
 
134
+ `ax.columns(...)` takes the result of any query, with no casts: DuckDB's `DECIMAL` (what `sum(amount)` and decimal literals are)
135
+ is read as a double, and a whole-number decimal or `HUGEINT` (a sum of integers) as an int64 when it fits. The same works with
136
+ polars (`ax.columns(df)`) and pyarrow (`ax.columns(table)`), and arrays you already hold (`pa.array([...])`) go straight into
137
+ `CellValues`.
138
+
139
+ Tested with DuckDB 1.1.3, 1.2.2, 1.3.2, 1.4.4, 1.5.2 and 2.0.1 (CI runs the examples against several of them). Older DuckDB does not export Arrow streams.
140
+
141
+ ### Examples
142
+
143
+ Each runs as it is with `uv run --with duckdb python examples/<name>.py`:
144
+
145
+ - [`examples/quickstart.py`](examples/quickstart.py): a pivot answer from a DuckDB query, and a parsed request.
146
+ - [`examples/streaming.py`](examples/streaming.py): a million customers written with `write_to` and `iter_xml`, with the time
147
+ and the memory it takes (`EXAMPLE_ROWS=20000` for a quick run).
148
+ - [`examples/server.py`](examples/server.py): a complete XMLA endpoint over the standard library's `http.server`
149
+ (`python examples/server.py --port 8000`): sessions, the Discover rowsets, a streamed pivot, faults.
150
+
104
151
  ### In Rust
105
152
 
106
153
  [`crates/arrow2xmla/examples/basic.rs`](crates/arrow2xmla/examples/basic.rs): the same model over zero-copy `Array`s.
@@ -119,35 +166,37 @@ let xml = cellset.to_vec()?; // or cellset.write_to(&mut writer), or write_chu
119
166
  ## A server
120
167
 
121
168
  The three writers (cellset, rowset, fault) and the envelope are all a server needs next to `parse_request`; what it
122
- answers with is up to it. This is the shape of one (the mock endpoint in
123
- [`tests/e2e/xmla_mock.py`](tests/e2e/xmla_mock.py) is a complete one, read by olap4j in the tests):
169
+ answers with is up to it. [`examples/server.py`](examples/server.py) is a complete one in the standard library's
170
+ `http.server` over an in-memory DuckDB table (`python examples/server.py --port 8000`): it answers the Discover requests
171
+ Excel opens with, honours their restrictions, echoes sessions, streams the pivot of an Execute and answers a request it
172
+ refuses with a fault. It does not parse MDX, which is the engine's job. Its core, abridged:
124
173
 
125
174
  ```python
126
- import itertools
127
- import pyarrow as pa
128
- import arrow2xmla as ax
129
-
130
- def answer(body: bytes):
131
- """-> (HTTP status, an iterable of bytes)"""
175
+ def answer(con, body: bytes):
176
+ """-> (HTTP status, a list of bytes, or an iterator of bytes to stream)"""
132
177
  try:
133
- request = ax.parse_request(body, max_size=1 << 20)
178
+ request = ax.parse_request(body, max_size=MAX_REQUEST)
179
+ session = {ax.SessionKind.BEGIN: str(uuid.uuid4()), ax.SessionKind.USE: request.session.id}.get(request.session.kind)
180
+ match request.call:
181
+ case ax.Discover() as call: # a rowset from a DuckDB query: Rowset.from_columns(ax.columns(con.sql(...)))
182
+ return 200, [ax.Envelope(ax.Method.DISCOVER, session).wrap(discover(con, call))]
183
+ case ax.Execute(statement=mdx):
184
+ envelope = ax.Envelope(ax.Method.EXECUTE, session)
185
+ chunks = pivot(con).iter_xml() # your engine: the Cellset for the statement
186
+ first = next(chunks) # whatever is wrong with the cellset is raised here, before anything is sent
187
+ return 200, itertools.chain([envelope.head(), first], chunks, [envelope.tail()]) # lazy: ~1 MB in memory
188
+ return 500, [ax.fault("only Discover and Execute are supported", session=session)]
134
189
  except ax.XmlaError as e:
135
- return 500, [ax.fault(str(e))]
136
- session = "new-id" if request.session.kind is ax.SessionKind.BEGIN else request.session.id
137
- match request.call:
138
- case ax.Discover(request_type="MDSCHEMA_CUBES"):
139
- rows = ax.Rowset.from_columns({"CUBE_NAME": pa.array(["Sales"]), "CUBE_TYPE": pa.array(["CUBE"])})
140
- return 200, [ax.Envelope(ax.Method.DISCOVER, session).wrap(rows.to_xml())]
141
- case ax.Execute(statement=mdx):
142
- envelope = ax.Envelope(ax.Method.EXECUTE, session)
143
- cellset = run(mdx) # your engine: an ax.Cellset over its Arrow results
144
- return 200, itertools.chain([envelope.head()], cellset.iter_xml(), [envelope.tail()]) # lazy: ~1 MB in memory
145
- return 500, [ax.fault("not supported", session=session)]
190
+ return 500, [ax.fault(str(e), session=session)]
146
191
  ```
147
192
 
193
+ The handler sends a list with a `Content-Length`, and an iterator as HTTP/1.1 chunked transfer, so a 300 MB answer is never
194
+ whole in memory.
195
+
148
196
  ### Streaming
149
197
 
150
- `to_xml()` builds the whole answer (about twice its size in memory at the peak). For a big one:
198
+ `to_xml()` builds the whole answer (about twice its size in memory at the peak). For a big one,
199
+ [`examples/streaming.py`](examples/streaming.py) writes a million customers (505 MB) both ways and checks they are the same:
151
200
 
152
201
  ```python
153
202
  with open("answer.xml", "wb") as fp:
@@ -192,9 +241,10 @@ byte is written:
192
241
  |---|---|
193
242
  | `int8` … `int64`, `uint8` … `uint64` | `xsd:int`; `xsd:long` / `xsd:unsignedLong` when 32 bits do not hold the value |
194
243
  | `float16`, `float32`, `float64` | `xsd:double`, Python's shortest `repr` digits; `NaN`, `INF`, `-INF` |
244
+ | `decimal32`/`64`/`128` (DuckDB's `DECIMAL` and `HUGEINT`; as an array or through `columns()`) | `xsd:int` / `xsd:long` when the scale is 0 and every value fits 64 bits, else `xsd:double` (the unscaled value divided by 10^scale) |
195
245
  | `string`, `large_string`, `string_view` | `xsd:string`, escaped |
196
246
  | null | no value: the cell is left out |
197
- | anything else (bool, dates, decimals, dictionaries, ...) | refused with `UnsupportedTypeError`: cast it first |
247
+ | anything else (bool, dates, 256-bit decimals, dictionaries, ...) | refused with `UnsupportedTypeError`, naming the column: cast it first |
198
248
 
199
249
  Characters XML 1.0 forbids are replaced with U+FFFD, so Excel's parser accepts the answer. Chunked arrays are combined
200
250
  first. Only `VALUE`, `FORMAT_STRING` and `LANGUAGE` are written in a cell (`CellProperty`); a property that is not
@@ -82,6 +82,14 @@ fn count(v: i64, what: &str) -> PyResult<usize> {
82
82
  }
83
83
 
84
84
  fn import<'a>(obj: &Bound<'_, PyAny>, keep: &mut Keep) -> PyResult<Array<'a>> {
85
+ // a column this module read from a stream (`read_stream`) owns its buffers
86
+ if let Ok(col) = obj.extract::<Py<ArrowColumn>>() {
87
+ let r: &ArrowColumn = col.get();
88
+ // SAFETY: the column is frozen and lives as long as `keep` holds it, which outlives every view
89
+ let r: &'a ArrowColumn = unsafe { &*(r as *const ArrowColumn) };
90
+ keep.capsules.push(col.into_any());
91
+ return Ok(r.array());
92
+ }
85
93
  let method = obj.getattr("__arrow_c_array__").map_err(|_| {
86
94
  bad(format!(
87
95
  "expected an Arrow array (an object with __arrow_c_array__, such as a pyarrow Array), not {}",
@@ -100,6 +108,28 @@ fn import<'a>(obj: &Bound<'_, PyAny>, keep: &mut Keep) -> PyResult<Array<'a>> {
100
108
  if schema.release.is_none() || array.release.is_none() {
101
109
  return Err(bad("an Arrow array that was already released"));
102
110
  }
111
+ if !schema.format.is_null() {
112
+ // SAFETY: a format string of a schema that has not been released
113
+ if let Ok(format) = unsafe { CStr::from_ptr(schema.format) }.to_str() {
114
+ if parse_decimal(format).is_some() {
115
+ // a decimal array is read as `columns()` reads one: an int64 when whole and it fits, else a double
116
+ let mut acc = Acc::new(format, "")?;
117
+ acc.push_decimal(array)?;
118
+ let col = Py::new(obj.py(), acc.finish())?;
119
+ let r: &ArrowColumn = col.get();
120
+ // SAFETY: as above: the column is frozen and `keep` holds it
121
+ let r: &'a ArrowColumn = unsafe { &*(r as *const ArrowColumn) };
122
+ keep.capsules.push(col.into_any());
123
+ return Ok(r.array());
124
+ }
125
+ }
126
+ }
127
+ import_raw(schema, array, keep)
128
+ }
129
+
130
+ /// A view of an array given as C data interface structs (checked as far as the structs show). The buffers are trusted
131
+ /// to be as long as the array says; they must outlive the view.
132
+ fn import_raw<'a>(schema: &ArrowSchema, array: &ArrowArray, keep: &mut Keep) -> PyResult<Array<'a>> {
103
133
  if schema.format.is_null() {
104
134
  return Err(bad("an Arrow schema without a format"));
105
135
  }
@@ -184,6 +214,379 @@ fn import<'a>(obj: &Bound<'_, PyAny>, keep: &mut Keep) -> PyResult<Array<'a>> {
184
214
  }
185
215
  }
186
216
 
217
+ // A stream of arrays (`__arrow_c_stream__`: a DuckDB relation, a polars Series, a pyarrow Table, ...) read into columns
218
+ // this module owns: the batches are copied into one array per column, which is how a column is cut out of a table and
219
+ // chunks are combined.
220
+ #[repr(C)]
221
+ struct ArrowArrayStream {
222
+ get_schema: Option<unsafe extern "C" fn(*mut ArrowArrayStream, *mut ArrowSchema) -> i32>,
223
+ get_next: Option<unsafe extern "C" fn(*mut ArrowArrayStream, *mut ArrowArray) -> i32>,
224
+ get_last_error: Option<unsafe extern "C" fn(*mut ArrowArrayStream) -> *const c_char>,
225
+ release: Option<unsafe extern "C" fn(*mut ArrowArrayStream)>,
226
+ private_data: *mut c_void,
227
+ }
228
+
229
+ struct SchemaGuard(ArrowSchema);
230
+ impl Drop for SchemaGuard {
231
+ fn drop(&mut self) {
232
+ if let Some(release) = self.0.release {
233
+ // SAFETY: a schema the producer filled in and has not released
234
+ unsafe { release(&mut self.0) };
235
+ }
236
+ }
237
+ }
238
+
239
+ struct ArrayGuard(ArrowArray);
240
+ impl Drop for ArrayGuard {
241
+ fn drop(&mut self) {
242
+ if let Some(release) = self.0.release {
243
+ // SAFETY: an array the producer filled in and has not released
244
+ unsafe { release(&mut self.0) };
245
+ }
246
+ }
247
+ }
248
+
249
+ enum Owned {
250
+ F64(Vec<f64>),
251
+ F32(Vec<f32>),
252
+ F16(Vec<u16>),
253
+ I64(Vec<i64>),
254
+ I32(Vec<i32>),
255
+ I16(Vec<i16>),
256
+ I8(Vec<i8>),
257
+ U64(Vec<u64>),
258
+ U32(Vec<u32>),
259
+ U16(Vec<u16>),
260
+ U8(Vec<u8>),
261
+ Text { offsets: Vec<i64>, data: Vec<u8> },
262
+ }
263
+
264
+ /// One column read from a stream: Arrow values this module owns (text as `large_string`), usable wherever an Arrow
265
+ /// array is.
266
+ #[pyclass(frozen, module = "arrow2xmla._native")]
267
+ struct ArrowColumn {
268
+ owned: Owned,
269
+ validity: Option<Vec<u8>>,
270
+ len: usize,
271
+ }
272
+
273
+ impl ArrowColumn {
274
+ fn array(&self) -> Array<'_> {
275
+ let values = match &self.owned {
276
+ Owned::F64(v) => Values::F64(v),
277
+ Owned::F32(v) => Values::F32(v),
278
+ Owned::F16(v) => Values::F16(v),
279
+ Owned::I64(v) => Values::I64(v),
280
+ Owned::I32(v) => Values::I32(v),
281
+ Owned::I16(v) => Values::I16(v),
282
+ Owned::I8(v) => Values::I8(v),
283
+ Owned::U64(v) => Values::U64(v),
284
+ Owned::U32(v) => Values::U32(v),
285
+ Owned::U16(v) => Values::U16(v),
286
+ Owned::U8(v) => Values::U8(v),
287
+ Owned::Text { offsets, data } => Values::LargeUtf8 { offsets, data },
288
+ };
289
+ let array = Array::new(values);
290
+ match &self.validity {
291
+ Some(bits) => array.with_validity(bits, 0),
292
+ None => array,
293
+ }
294
+ }
295
+
296
+ fn type_name(&self) -> &'static str {
297
+ match self.owned {
298
+ Owned::F64(_) => "double",
299
+ Owned::F32(_) => "float",
300
+ Owned::F16(_) => "halffloat",
301
+ Owned::I64(_) => "int64",
302
+ Owned::I32(_) => "int32",
303
+ Owned::I16(_) => "int16",
304
+ Owned::I8(_) => "int8",
305
+ Owned::U64(_) => "uint64",
306
+ Owned::U32(_) => "uint32",
307
+ Owned::U16(_) => "uint16",
308
+ Owned::U8(_) => "uint8",
309
+ Owned::Text { .. } => "large_string",
310
+ }
311
+ }
312
+ }
313
+
314
+ #[pymethods]
315
+ impl ArrowColumn {
316
+ fn __len__(&self) -> usize {
317
+ self.len
318
+ }
319
+
320
+ /// The Arrow type, e.g. `double`, `int64`, `large_string`.
321
+ #[getter]
322
+ fn r#type(&self) -> &'static str {
323
+ self.type_name()
324
+ }
325
+
326
+ fn __repr__(&self) -> String {
327
+ let nulls = self.validity.as_ref().map_or(0, |_| (0..self.len).filter(|&i| !self.array().is_valid(i)).count());
328
+ format!("<ArrowColumn {} x {}, {} null>", self.type_name(), self.len, nulls)
329
+ }
330
+ }
331
+
332
+ /// A decimal column (`d:precision,scale[,bits]`): its unscaled integers, converted when the column is finished.
333
+ struct Dec {
334
+ scale: i32,
335
+ width: usize,
336
+ vals: Vec<i128>,
337
+ }
338
+
339
+ /// `(scale, bytes per value)` of a decimal format: `d:precision,scale` (128 bits) or `d:precision,scale,32|64|128`.
340
+ fn parse_decimal(format: &str) -> Option<(i32, usize)> {
341
+ let mut parts = format.strip_prefix("d:")?.split(',');
342
+ let _precision: u32 = parts.next()?.parse().ok()?;
343
+ let scale: i32 = parts.next()?.parse().ok()?;
344
+ let bits: usize = match parts.next() {
345
+ None => 128,
346
+ Some(b) => b.parse().ok()?,
347
+ };
348
+ if parts.next().is_some() {
349
+ return None;
350
+ }
351
+ matches!(bits, 32 | 64 | 128).then_some((scale, bits / 8))
352
+ }
353
+
354
+ /// Copies of one column's batches, appended.
355
+ struct Acc {
356
+ owned: Owned,
357
+ dec: Option<Dec>,
358
+ valid: Vec<bool>,
359
+ nulls: bool,
360
+ }
361
+
362
+ impl Acc {
363
+ fn new(format: &str, name: &str) -> PyResult<Acc> {
364
+ if let Some((scale, width)) = parse_decimal(format) {
365
+ return Ok(Acc { owned: Owned::F64(vec![]), dec: Some(Dec { scale, width, vals: vec![] }), valid: vec![], nulls: false });
366
+ }
367
+ let owned = match format {
368
+ "g" => Owned::F64(vec![]),
369
+ "f" => Owned::F32(vec![]),
370
+ "e" => Owned::F16(vec![]),
371
+ "l" => Owned::I64(vec![]),
372
+ "i" => Owned::I32(vec![]),
373
+ "s" => Owned::I16(vec![]),
374
+ "c" => Owned::I8(vec![]),
375
+ "L" => Owned::U64(vec![]),
376
+ "I" => Owned::U32(vec![]),
377
+ "S" => Owned::U16(vec![]),
378
+ "C" => Owned::U8(vec![]),
379
+ "u" | "U" | "vu" => Owned::Text { offsets: vec![0], data: vec![] },
380
+ other => {
381
+ let what = if name.is_empty() { "an Arrow array".to_string() } else { format!("column {name:?}") };
382
+ return Err(UnsupportedTypeError::new_err(format!("{what} has Arrow format {other:?}, which is not supported (floats, integers, decimals, text): cast it first (in a query: `x::DOUBLE`, `x::BIGINT`, `x::VARCHAR`)")));
383
+ }
384
+ };
385
+ Ok(Acc { owned, dec: None, valid: vec![], nulls: false })
386
+ }
387
+
388
+ /// Appends the values of a decimal array (read as the little-endian integers the Arrow layout says they are).
389
+ fn push_decimal(&mut self, array: &ArrowArray) -> PyResult<()> {
390
+ let dec = self.dec.as_mut().expect("a decimal column");
391
+ if !array.dictionary.is_null() || array.n_children != 0 {
392
+ return Err(bad("a dictionary or nested array: cast it to its plain type first"));
393
+ }
394
+ if array.null_count < -1 {
395
+ return Err(bad("an Arrow array with an invalid null count"));
396
+ }
397
+ let len = count(array.length, "length")?;
398
+ let off = count(array.offset, "offset")?;
399
+ let end = off.checked_add(len).ok_or_else(|| bad("an Arrow array too long"))?;
400
+ if count(array.n_buffers, "buffer count")? < 2 || array.buffers.is_null() {
401
+ return Err(bad("an Arrow array with too few buffers"));
402
+ }
403
+ // SAFETY: the buffers are those the array declares, as long as it says (the interface has no way to say more)
404
+ let (data, bits) = unsafe {
405
+ let buffers = std::slice::from_raw_parts(array.buffers, 2);
406
+ let data = slice::<u8>(buffers[1], end.checked_mul(dec.width).ok_or_else(|| bad("an Arrow array too long"))?, "data")?;
407
+ let bits = if array.null_count != 0 && !buffers[0].is_null() { Some(slice::<u8>(buffers[0], end.div_ceil(8), "validity")?) } else { None };
408
+ (data, bits)
409
+ };
410
+ for i in off..end {
411
+ let ok = bits.is_none_or(|b| b[i >> 3] >> (i & 7) & 1 == 1);
412
+ let raw = &data[i * dec.width..(i + 1) * dec.width];
413
+ let v = match dec.width {
414
+ 4 => i128::from(i32::from_le_bytes(raw.try_into().expect("4 bytes"))),
415
+ 8 => i128::from(i64::from_le_bytes(raw.try_into().expect("8 bytes"))),
416
+ _ => i128::from_le_bytes(raw.try_into().expect("16 bytes")),
417
+ };
418
+ dec.vals.push(if ok { v } else { 0 }); // what a null row holds is not to be read
419
+ self.nulls |= !ok;
420
+ self.valid.push(ok);
421
+ }
422
+ Ok(())
423
+ }
424
+
425
+ fn push(&mut self, a: &Array<'_>) {
426
+ let n = a.len();
427
+ match (&mut self.owned, a.values) {
428
+ (Owned::F64(v), Values::F64(s)) => v.extend_from_slice(s),
429
+ (Owned::F32(v), Values::F32(s)) => v.extend_from_slice(s),
430
+ (Owned::F16(v), Values::F16(s)) => v.extend_from_slice(s),
431
+ (Owned::I64(v), Values::I64(s)) => v.extend_from_slice(s),
432
+ (Owned::I32(v), Values::I32(s)) => v.extend_from_slice(s),
433
+ (Owned::I16(v), Values::I16(s)) => v.extend_from_slice(s),
434
+ (Owned::I8(v), Values::I8(s)) => v.extend_from_slice(s),
435
+ (Owned::U64(v), Values::U64(s)) => v.extend_from_slice(s),
436
+ (Owned::U32(v), Values::U32(s)) => v.extend_from_slice(s),
437
+ (Owned::U16(v), Values::U16(s)) => v.extend_from_slice(s),
438
+ (Owned::U8(v), Values::U8(s)) => v.extend_from_slice(s),
439
+ (Owned::Text { offsets, data }, _) => {
440
+ for i in 0..n {
441
+ if let Some(t) = a.text(i) {
442
+ data.extend_from_slice(t);
443
+ }
444
+ offsets.push(data.len() as i64);
445
+ }
446
+ }
447
+ _ => unreachable!("the batches of a stream have one type"),
448
+ }
449
+ for i in 0..n {
450
+ let ok = a.is_valid(i);
451
+ self.nulls |= !ok;
452
+ self.valid.push(ok);
453
+ }
454
+ }
455
+
456
+ fn finish(mut self) -> ArrowColumn {
457
+ let len = self.valid.len();
458
+ if let Some(d) = self.dec.take() {
459
+ // a decimal is read as the number Excel holds it as: a whole number as int64 when they all fit, else a double
460
+ // (the unscaled value divided by 10^scale: exact for what a double holds, correctly rounded beyond)
461
+ self.owned = if d.scale == 0 && d.vals.iter().all(|v| i64::try_from(*v).is_ok()) {
462
+ Owned::I64(d.vals.iter().map(|v| *v as i64).collect())
463
+ } else if d.scale < 0 {
464
+ Owned::F64(d.vals.iter().map(|v| *v as f64 * 10f64.powi(-d.scale)).collect())
465
+ } else {
466
+ Owned::F64(d.vals.iter().map(|v| *v as f64 / 10f64.powi(d.scale)).collect())
467
+ };
468
+ }
469
+ let validity = self.nulls.then(|| {
470
+ let mut bits = vec![0u8; len.div_ceil(8)];
471
+ for (i, ok) in self.valid.iter().enumerate() {
472
+ if *ok {
473
+ bits[i >> 3] |= 1 << (i & 7);
474
+ }
475
+ }
476
+ bits
477
+ });
478
+ ArrowColumn { owned: self.owned, validity, len }
479
+ }
480
+ }
481
+
482
+ /// `read_stream(obj) -> [(name | None, ArrowColumn)]`: the columns of an Arrow stream. A table (a stream of structs) gives
483
+ /// one entry per column, named; a stream of plain arrays gives one unnamed column.
484
+ #[pyfunction]
485
+ fn read_stream(obj: &Bound<'_, PyAny>) -> PyResult<Vec<(Option<String>, ArrowColumn)>> {
486
+ let method = obj.getattr("__arrow_c_stream__").map_err(|_| {
487
+ bad(format!(
488
+ "expected an Arrow table or stream (an object with __arrow_c_stream__, such as a DuckDB relation or a pyarrow Table), not {}",
489
+ obj.get_type().name().map_or_else(|_| "this".to_string(), |n| format!("a {n}"))
490
+ ))
491
+ })?;
492
+ let capsule = method.call0()?.cast_into::<PyCapsule>().map_err(|_| bad("__arrow_c_stream__ did not return a capsule"))?;
493
+ let stream = capsule.pointer_checked(Some(c"arrow_array_stream"))?.as_ptr().cast::<ArrowArrayStream>();
494
+ // SAFETY: the capsule holds a C stream interface struct (the protocol's contract) and stays alive until the end of
495
+ // this function; its destructor releases the stream. What the structs show to be wrong is refused.
496
+ unsafe {
497
+ let s = &*stream;
498
+ let (Some(get_schema), Some(get_next)) = (s.get_schema, s.get_next) else {
499
+ return Err(bad("an Arrow stream without its functions, or one that was already released"));
500
+ };
501
+ if s.release.is_none() {
502
+ return Err(bad("an Arrow stream that was already released"));
503
+ }
504
+ let last_error = |stream: *mut ArrowArrayStream| -> String {
505
+ match (*stream).get_last_error {
506
+ Some(f) => {
507
+ let p = f(stream);
508
+ if p.is_null() { "unknown error".into() } else { CStr::from_ptr(p).to_string_lossy().into_owned() }
509
+ }
510
+ None => "unknown error".into(),
511
+ }
512
+ };
513
+ let mut schema = SchemaGuard(std::mem::zeroed());
514
+ if get_schema(stream, &mut schema.0) != 0 {
515
+ return Err(bad(format!("the Arrow stream failed: {}", last_error(stream))));
516
+ }
517
+ if schema.0.format.is_null() {
518
+ return Err(bad("an Arrow stream schema without a format"));
519
+ }
520
+ let format = CStr::from_ptr(schema.0.format).to_str().map_err(|_| bad("an Arrow format that is not text"))?;
521
+ let is_table = format == "+s";
522
+ let columns = if is_table { count(schema.0.n_children, "child count")? } else { 1 };
523
+ if is_table && columns > 0 && schema.0.children.is_null() {
524
+ return Err(bad("an Arrow table schema without its children"));
525
+ }
526
+ let child_schema = |j: usize| -> &ArrowSchema { if is_table { &**schema.0.children.add(j) } else { &schema.0 } };
527
+ let mut names: Vec<Option<String>> = vec![];
528
+ let mut accs: Vec<Acc> = vec![];
529
+ for j in 0..columns {
530
+ let cs = child_schema(j);
531
+ if cs.format.is_null() {
532
+ return Err(bad("an Arrow column without a format"));
533
+ }
534
+ let name = if is_table && !cs.name.is_null() { CStr::from_ptr(cs.name).to_string_lossy().into_owned() } else { String::new() };
535
+ let f = CStr::from_ptr(cs.format).to_str().map_err(|_| bad("an Arrow format that is not text"))?;
536
+ if !cs.dictionary.is_null() {
537
+ let what = if name.is_empty() { "an Arrow array".to_string() } else { format!("column {name:?}") };
538
+ return Err(UnsupportedTypeError::new_err(format!("{what} is dictionary-encoded, which is not supported: cast it to its plain type first (in a query: `x::VARCHAR`)")));
539
+ }
540
+ accs.push(Acc::new(f, &name)?);
541
+ names.push(is_table.then_some(name));
542
+ }
543
+ let mut keep = Keep::default();
544
+ loop {
545
+ let mut batch = ArrayGuard(std::mem::zeroed());
546
+ if get_next(stream, &mut batch.0) != 0 {
547
+ return Err(bad(format!("the Arrow stream failed: {}", last_error(stream))));
548
+ }
549
+ if batch.0.release.is_none() {
550
+ break; // the end of the stream
551
+ }
552
+ if is_table {
553
+ if count(batch.0.n_children, "child count")? != columns || (columns > 0 && batch.0.children.is_null()) {
554
+ return Err(bad("an Arrow table batch that does not match its schema"));
555
+ }
556
+ if batch.0.null_count != 0 {
557
+ return Err(bad("an Arrow table with null rows is not supported"));
558
+ }
559
+ }
560
+ for (j, acc) in accs.iter_mut().enumerate() {
561
+ let view;
562
+ let array: &ArrowArray = if is_table {
563
+ let child = *batch.0.children.add(j);
564
+ if child.is_null() {
565
+ return Err(bad("an Arrow table batch without one of its columns"));
566
+ }
567
+ // the offset of a struct applies to its children
568
+ let mut copy = std::ptr::read(child);
569
+ copy.offset = copy.offset.checked_add(batch.0.offset).ok_or_else(|| bad("an Arrow array too long"))?;
570
+ copy.length = batch.0.length;
571
+ view = copy;
572
+ &view
573
+ } else {
574
+ &batch.0
575
+ };
576
+ if acc.dec.is_some() {
577
+ acc.push_decimal(array)?;
578
+ } else {
579
+ let a = import_raw(child_schema(j), array, &mut keep)?;
580
+ a.check().map_err(|e| bad(e.to_string()))?;
581
+ acc.push(&a);
582
+ }
583
+ }
584
+ }
585
+ drop(keep);
586
+ Ok(names.into_iter().zip(accs.into_iter().map(Acc::finish)).collect())
587
+ }
588
+ }
589
+
187
590
  // The model is read from the Python dataclasses (`arrow2xmla._model`) by attribute: they are the one description of
188
591
  // its shape, and they have checked the types. What the core's `validate()` knows, the core says.
189
592
 
@@ -436,6 +839,8 @@ fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> {
436
839
  m.add_function(wrap_pyfunction!(cellset_xml, m)?)?;
437
840
  #[cfg(feature = "request")]
438
841
  m.add("DEFAULT_MAX_REQUEST", arrow2xmla::DEFAULT_MAX_REQUEST)?;
842
+ m.add_class::<ArrowColumn>()?;
843
+ m.add_function(wrap_pyfunction!(read_stream, m)?)?;
439
844
  m.add_function(wrap_pyfunction!(cellset_write, m)?)?;
440
845
  m.add_function(wrap_pyfunction!(rowset_xml, m)?)?;
441
846
  m.add_function(wrap_pyfunction!(envelope, m)?)?;
@@ -18,9 +18,6 @@ classifiers = [
18
18
  ]
19
19
  dependencies = [] # none: Arrow arrays are read through the PyCapsule interface
20
20
 
21
- [project.optional-dependencies]
22
- pyarrow = ["pyarrow>=15"] # for chunked arrays and Arrow streams; any other Arrow library works as well
23
-
24
21
  [project.urls]
25
22
  Homepage = "https://github.com/bmsuisse/arrow2xmla"
26
23
  Repository = "https://github.com/bmsuisse/arrow2xmla"
@@ -10,19 +10,18 @@
10
10
  )
11
11
  xml = cs.to_xml()
12
12
 
13
- Arrays are read through the Arrow PyCapsule interface (`__arrow_c_array__`): pyarrow, nanoarrow and every other
14
- library that exports it work, and none is imported here. A chunked array is combined into one first (an object that
15
- only exports `__arrow_c_stream__`, such as a polars Series, goes through pyarrow if it is installed, else convert it
16
- with `.to_arrow()`). The producer of an array is trusted to give buffers as long as it says: this is not a validator
17
- of untrusted Arrow memory.
13
+ Data comes in through the Arrow PyCapsule interface. An array (`__arrow_c_array__`: pyarrow, nanoarrow, ...) is read in
14
+ place; a table or stream (`__arrow_c_stream__`: a DuckDB relation, a polars DataFrame or Series, a pyarrow Table) is read
15
+ with `columns(table)`, which gives its columns by name. The producer of an array is trusted to give buffers as long as it
16
+ says: this is not a validator of untrusted Arrow memory.
18
17
 
19
18
  Everything this package refuses raises a subclass of `XmlaError` (itself a `ValueError`).
20
19
  """
21
20
 
22
21
  from arrow2xmla import _native
23
- from arrow2xmla._model import CellProperty, ChunkIterator, Cellset, CellValues, LevelAxis, Member, MemberProperty, MemberType, Rowset, RowsetColumn, TupleAxis
22
+ from arrow2xmla._model import CellProperty, ChunkIterator, Cellset, CellValues, LevelAxis, Member, MemberProperty, MemberType, Rowset, RowsetColumn, TupleAxis, columns
24
23
  from arrow2xmla._soap import Envelope, Method, fault
25
- from arrow2xmla._native import CellsetError, DoctypeError, RequestError, RequestTooLarge, UnsupportedTypeError, XmlaError
24
+ from arrow2xmla._native import ArrowColumn, CellsetError, DoctypeError, RequestError, RequestTooLarge, UnsupportedTypeError, XmlaError
26
25
 
27
26
  try:
28
27
  from importlib.metadata import version as _version
@@ -34,7 +33,7 @@ except Exception: # not installed as a distribution (a source checkout)
34
33
 
35
34
  __all__ = [
36
35
  "__version__", "Cellset", "CellValues", "LevelAxis", "TupleAxis", "Member",
37
- "MemberType", "MemberProperty", "CellProperty", "ChunkIterator", "Rowset", "RowsetColumn", "Envelope", "Method", "fault",
36
+ "MemberType", "MemberProperty", "CellProperty", "ChunkIterator", "Rowset", "RowsetColumn", "columns", "ArrowColumn", "Envelope", "Method", "fault",
38
37
  "XmlaError", "CellsetError", "UnsupportedTypeError", "RequestError", "DoctypeError", "RequestTooLarge",
39
38
  ] # fmt: skip
40
39
 
@@ -47,19 +47,43 @@ class CellProperty(str, Enum):
47
47
 
48
48
 
49
49
  def _plain(x: Any) -> Any:
50
- """One Arrow array: as it is, or a chunked array combined."""
51
- if hasattr(x, "__arrow_c_array__"):
52
- return x
53
- if hasattr(x, "combine_chunks"):
54
- return x.combine_chunks()
55
- if hasattr(x, "__arrow_c_stream__"):
56
- try:
57
- import pyarrow as pa
50
+ """One Arrow array: as it is, a column read from a stream, or a chunked array combined."""
51
+ from arrow2xmla import _native
58
52
 
59
- return pa.chunked_array(x).combine_chunks()
60
- except ImportError:
61
- raise CellsetError("an Arrow stream needs pyarrow to be combined into an array: pass an array (.to_arrow())") from None
62
- raise TypeError(f"expected an Arrow array (something with __arrow_c_array__), not {type(x).__name__}")
53
+ if isinstance(x, _native.ArrowColumn) or hasattr(x, "__arrow_c_array__"):
54
+ return x
55
+ if hasattr(x, "combine_chunks"): # a pyarrow ChunkedArray (a Table has the method too, and combines to a Table)
56
+ combined = x.combine_chunks()
57
+ if hasattr(combined, "__arrow_c_array__"):
58
+ return combined
59
+ if hasattr(x, "__arrow_c_stream__"): # a polars Series, a one-column stream: read here
60
+ columns = _native.read_stream(x)
61
+ if len(columns) != 1 or columns[0][0] is not None:
62
+ raise CellsetError("this is a table, not one column: take a column of it with `columns(table)[name]`")
63
+ return columns[0][1]
64
+ raise TypeError(f"expected an Arrow array (something with __arrow_c_array__ or __arrow_c_stream__), not {type(x).__name__}")
65
+
66
+
67
+ def columns(table: Any) -> dict[str, Any]:
68
+ """The columns of an Arrow table or stream by name, ready for `CellValues`, `LevelAxis` and `Rowset`.
69
+ Anything that exports `__arrow_c_stream__` works (a DuckDB relation, a polars DataFrame, a pyarrow Table).
70
+
71
+ columns(duckdb.sql("select name, sum(x) as total from t group by name"))["total"]
72
+
73
+ The batches are copied once into one array per column. Types: floats, integers, text, and decimals (DuckDB's `DECIMAL` and
74
+ `HUGEINT`): a decimal is read as an int64 when its scale is 0 and every value fits, else as a double. Anything else (dates,
75
+ booleans, 256-bit decimals, ...) raises `UnsupportedTypeError` naming the column: cast it in the query."""
76
+ from arrow2xmla import _native
77
+
78
+ if not hasattr(table, "__arrow_c_stream__"):
79
+ raise TypeError(f"expected an Arrow table or stream (something with __arrow_c_stream__), not {type(table).__name__}")
80
+ read = _native.read_stream(table)
81
+ if any(name is None for name, _ in read):
82
+ raise CellsetError("this is one column, not a table: use it as it is")
83
+ names = [name for name, _ in read]
84
+ if len(set(names)) != len(names):
85
+ raise CellsetError("the table has two columns of one name: name them apart")
86
+ return {name: column for name, column in read}
63
87
 
64
88
 
65
89
  def _enums(kind: type[Enum], items: Any, what: str, one: str) -> tuple[Any, ...]:
File without changes