dataclass-native 1.0.0__py3-none-any.whl
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.
- dataclass_native/__init__.py +60 -0
- dataclass_native/__main__.py +5 -0
- dataclass_native/_arrow.py +822 -0
- dataclass_native/_json.py +783 -0
- dataclass_native/_mode.py +57 -0
- dataclass_native/_msgpack.py +207 -0
- dataclass_native/_native.py +234 -0
- dataclass_native/_runtime.py +607 -0
- dataclass_native/_version.py +24 -0
- dataclass_native/_wire.py +901 -0
- dataclass_native/arrays.py +13 -0
- dataclass_native/backends/__init__.py +0 -0
- dataclass_native/backends/bindings.py +74 -0
- dataclass_native/backends/cpp.py +574 -0
- dataclass_native/backends/templates/bindings.cpp.j2 +58 -0
- dataclass_native/backends/templates/extensions.cmake.j2 +12 -0
- dataclass_native/backends/templates/header.hpp.j2 +75 -0
- dataclass_native/cli.py +125 -0
- dataclass_native/cmake/dataclass_native-config.cmake +67 -0
- dataclass_native/include/dataclass_native/arrow.hpp +2022 -0
- dataclass_native/include/dataclass_native/json.hpp +1903 -0
- dataclass_native/include/dataclass_native/msgpack.hpp +1513 -0
- dataclass_native/include/dataclass_native/python.hpp +594 -0
- dataclass_native/include/dataclass_native/reflect.hpp +63 -0
- dataclass_native/include/dataclass_native/types.hpp +417 -0
- dataclass_native/introspect.py +811 -0
- dataclass_native/py.typed +0 -0
- dataclass_native/schema.py +553 -0
- dataclass_native/types.py +103 -0
- dataclass_native-1.0.0.dist-info/METADATA +339 -0
- dataclass_native-1.0.0.dist-info/RECORD +35 -0
- dataclass_native-1.0.0.dist-info/WHEEL +5 -0
- dataclass_native-1.0.0.dist-info/entry_points.txt +2 -0
- dataclass_native-1.0.0.dist-info/licenses/LICENSE +21 -0
- dataclass_native-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,822 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Arrow tables of @native objects, and Parquet files of those tables, in the layout of ARROW_FORMAT.md.
|
|
3
|
+
|
|
4
|
+
write() and read() are the reference implementation of that layout, in Python: they get and set the fields of @native
|
|
5
|
+
objects as any Python code does, so work in every mode. to_arrow() and from_arrow() use them, unless the objects are
|
|
6
|
+
stored natively: then the C++ of dataclass_native/arrow.hpp builds and reads the tables from the native objects
|
|
7
|
+
themselves. pyarrow is needed only to call any of these.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import decimal
|
|
12
|
+
import struct
|
|
13
|
+
import uuid
|
|
14
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, NamedTuple
|
|
17
|
+
from urllib.parse import quote, unquote
|
|
18
|
+
from weakref import WeakKeyDictionary
|
|
19
|
+
|
|
20
|
+
from . import schema as s
|
|
21
|
+
from ._native import is_native, native_info
|
|
22
|
+
from ._wire import (
|
|
23
|
+
_array,
|
|
24
|
+
_brief,
|
|
25
|
+
_Invalid,
|
|
26
|
+
_member,
|
|
27
|
+
_native_class,
|
|
28
|
+
_numbers,
|
|
29
|
+
_order,
|
|
30
|
+
_ordered,
|
|
31
|
+
_struct_class,
|
|
32
|
+
)
|
|
33
|
+
from ._wire import _codec as _wire_codec
|
|
34
|
+
from .introspect import _tag, describe, walk
|
|
35
|
+
from .schema import SchemaError
|
|
36
|
+
|
|
37
|
+
TAG = b"dataclass_native:tag"
|
|
38
|
+
"""In a table's metadata: the tag of the class its rows are of"""
|
|
39
|
+
SHARED = b"dataclass_native:shared"
|
|
40
|
+
"""In the metadata of a field which refers to a shared object: the tag of that object's class, and so its table"""
|
|
41
|
+
|
|
42
|
+
_BYTE = s.Int(8, signed=False)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ArrowTables(NamedTuple):
|
|
46
|
+
"""Objects as Arrow tables, a pyarrow.Table each"""
|
|
47
|
+
|
|
48
|
+
root: Any
|
|
49
|
+
"""A row for each object"""
|
|
50
|
+
shared: dict[str, Any]
|
|
51
|
+
"""By its tag, the table of each class the objects may share: a row for each object shared"""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def to_arrow(values: Iterable[Any], cls: type | None = None) -> ArrowTables:
|
|
55
|
+
"""
|
|
56
|
+
Objects of a @native class as Arrow tables: a row each, and a column for each field. Objects stored natively are
|
|
57
|
+
held natively.
|
|
58
|
+
|
|
59
|
+
:param cls: Their class, which need be given only if there may be none
|
|
60
|
+
"""
|
|
61
|
+
values = list(values)
|
|
62
|
+
cls = _class(values, cls)
|
|
63
|
+
native = _native(cls)
|
|
64
|
+
if native is None:
|
|
65
|
+
return write(values, cls)
|
|
66
|
+
|
|
67
|
+
from ._runtime import native_object
|
|
68
|
+
|
|
69
|
+
pa = _pyarrow()
|
|
70
|
+
objects = []
|
|
71
|
+
for value in values:
|
|
72
|
+
if type(value) is not cls:
|
|
73
|
+
raise TypeError(f"{value!r} is not a {cls.__qualname__}")
|
|
74
|
+
objects.append(native_object(value))
|
|
75
|
+
root, shared = native.__arrow__(objects)
|
|
76
|
+
return ArrowTables(
|
|
77
|
+
_imported(pa, root),
|
|
78
|
+
{tag: _imported(pa, capsules) for tag, capsules in shared},
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def from_arrow(cls: type, tables: Any) -> tuple[Any, ...]:
|
|
83
|
+
"""
|
|
84
|
+
The objects of a @native class which Arrow tables hold. Raises ValueError if they are not tables of that class.
|
|
85
|
+
|
|
86
|
+
:param tables: As to_arrow gives. Or the pyarrow.Table of the objects alone, if their class shares none
|
|
87
|
+
"""
|
|
88
|
+
native = _native(cls)
|
|
89
|
+
# A pydantic dataclass is made in Python, so that pydantic validates it
|
|
90
|
+
if native is not None and not _wire_codec(cls).validated:
|
|
91
|
+
from ._runtime import wrap
|
|
92
|
+
|
|
93
|
+
pa = _pyarrow()
|
|
94
|
+
root, shared = tables if isinstance(tables, tuple) else (tables, {})
|
|
95
|
+
objects = native.__from_arrow__(
|
|
96
|
+
*_exported(pa, root),
|
|
97
|
+
{tag: _exported(pa, table) for tag, table in shared.items()},
|
|
98
|
+
)
|
|
99
|
+
# None if it does not read them: then what follows does, or says why not
|
|
100
|
+
if objects is not None:
|
|
101
|
+
return tuple(wrap(cls, obj) for obj in objects)
|
|
102
|
+
return read(cls, tables)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _native(cls: Any) -> Any:
|
|
106
|
+
"""The native class of a bound class, if that holds its objects in Arrow tables itself"""
|
|
107
|
+
native = _native_class(cls)
|
|
108
|
+
return native if hasattr(native, "__arrow__") else None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class _Capsules:
|
|
112
|
+
"""A table as the Arrow PyCapsule interface exports it, which pyarrow imports"""
|
|
113
|
+
|
|
114
|
+
def __init__(self, capsules: tuple[Any, Any]):
|
|
115
|
+
self.capsules = capsules
|
|
116
|
+
|
|
117
|
+
def __arrow_c_array__(self, requested_schema: Any = None) -> tuple[Any, Any]:
|
|
118
|
+
return self.capsules
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _imported(pa: Any, capsules: tuple[Any, Any]) -> Any:
|
|
122
|
+
return pa.Table.from_batches([pa.record_batch(_Capsules(capsules))])
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _exported(pa: Any, table: Any) -> tuple[Any, Any]:
|
|
126
|
+
"""The capsules of a table, as one array"""
|
|
127
|
+
if isinstance(table, pa.Table):
|
|
128
|
+
batches = table.combine_chunks().to_batches()
|
|
129
|
+
table = (
|
|
130
|
+
batches[0]
|
|
131
|
+
if len(batches) == 1
|
|
132
|
+
else pa.RecordBatch.from_pylist([], schema=table.schema)
|
|
133
|
+
)
|
|
134
|
+
return table.__arrow_c_array__()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _class(values: list[Any], cls: type | None) -> type:
|
|
138
|
+
if cls is not None:
|
|
139
|
+
return cls
|
|
140
|
+
if not values:
|
|
141
|
+
raise TypeError("The class of no objects must be given")
|
|
142
|
+
return type(values[0])
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def write(values: Iterable[Any], cls: type | None = None) -> ArrowTables:
|
|
146
|
+
"""As to_arrow, in Python alone"""
|
|
147
|
+
pa = _pyarrow()
|
|
148
|
+
values = list(values)
|
|
149
|
+
cls = _class(values, cls)
|
|
150
|
+
codec = _codec(cls)
|
|
151
|
+
codecs = {c.tag: c for c in (codec, *map(_codec, codec.shared))}
|
|
152
|
+
# Before any is written, as a class may not have one
|
|
153
|
+
schemas = {tag: c.schema(pa) for tag, c in codecs.items()}
|
|
154
|
+
|
|
155
|
+
writer = _Writer({_codec(c).tag: [] for c in codec.shared})
|
|
156
|
+
rows = []
|
|
157
|
+
for value in values:
|
|
158
|
+
try:
|
|
159
|
+
rows.append(codec.plain(value, writer))
|
|
160
|
+
except _Invalid:
|
|
161
|
+
raise TypeError(f"{value!r} is not a {cls.__qualname__}") from None
|
|
162
|
+
|
|
163
|
+
def table(tag: str, rows: list[Any]) -> Any:
|
|
164
|
+
# Made as its extension types are stored: pyarrow makes no others from Python's values, within a container
|
|
165
|
+
stored = codecs[tag].schema(_Stored(pa))
|
|
166
|
+
made = pa.Table.from_pylist(rows, schema=stored)
|
|
167
|
+
return made if stored.equals(schemas[tag]) else made.cast(schemas[tag])
|
|
168
|
+
|
|
169
|
+
return ArrowTables(
|
|
170
|
+
table(codec.tag, rows),
|
|
171
|
+
{tag: table(tag, shared) for tag, shared in writer.tables.items()},
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def read(cls: type, tables: Any) -> tuple[Any, ...]:
|
|
176
|
+
"""As from_arrow, in Python alone"""
|
|
177
|
+
codec = _codec(cls)
|
|
178
|
+
root, shared = tables if isinstance(tables, tuple) else (tables, {})
|
|
179
|
+
reader = _Reader({tag: table.to_pylist() for tag, table in shared.items()})
|
|
180
|
+
objects = []
|
|
181
|
+
for row in root.to_pylist():
|
|
182
|
+
try:
|
|
183
|
+
objects.append(codec.object(row, reader))
|
|
184
|
+
except _Invalid:
|
|
185
|
+
raise ValueError(
|
|
186
|
+
f"The table does not hold {cls.__qualname__}: {_brief(row)}"
|
|
187
|
+
) from None
|
|
188
|
+
return tuple(objects)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def to_parquet(values: Iterable[Any], directory: str | Path, cls: type | None = None):
|
|
192
|
+
"""
|
|
193
|
+
Writes objects of a @native class as Parquet: root.parquet, and a file in shared/ for each class they may share.
|
|
194
|
+
|
|
195
|
+
:param cls: Their class, which need be given only if there may be none
|
|
196
|
+
"""
|
|
197
|
+
pq = _parquet()
|
|
198
|
+
tables = to_arrow(values, cls)
|
|
199
|
+
directory = Path(directory)
|
|
200
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
201
|
+
pq.write_table(tables.root, directory / "root.parquet")
|
|
202
|
+
for tag, table in tables.shared.items():
|
|
203
|
+
(directory / "shared").mkdir(exist_ok=True)
|
|
204
|
+
pq.write_table(table, directory / "shared" / f"{quote(tag, safe='')}.parquet")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def from_parquet(cls: type, directory: str | Path) -> tuple[Any, ...]:
|
|
208
|
+
"""The objects of a @native class which to_parquet wrote"""
|
|
209
|
+
pq = _parquet()
|
|
210
|
+
directory = Path(directory)
|
|
211
|
+
shared = {
|
|
212
|
+
unquote(path.stem): pq.read_table(path)
|
|
213
|
+
for path in sorted((directory / "shared").glob("*.parquet"))
|
|
214
|
+
}
|
|
215
|
+
return from_arrow(
|
|
216
|
+
cls, ArrowTables(pq.read_table(directory / "root.parquet"), shared)
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _pyarrow() -> Any:
|
|
221
|
+
try:
|
|
222
|
+
import pyarrow
|
|
223
|
+
except ImportError:
|
|
224
|
+
raise ImportError(
|
|
225
|
+
"pyarrow is needed for Arrow and Parquet: install dataclass-native[arrow]"
|
|
226
|
+
) from None
|
|
227
|
+
return pyarrow
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class _Stored:
|
|
231
|
+
"""pyarrow, but for its extension types being those they are stored as"""
|
|
232
|
+
|
|
233
|
+
def __init__(self, pa: Any):
|
|
234
|
+
self.__pa = pa
|
|
235
|
+
|
|
236
|
+
def __getattr__(self, name: str) -> Any:
|
|
237
|
+
return getattr(self.__pa, name)
|
|
238
|
+
|
|
239
|
+
def uuid(self) -> Any:
|
|
240
|
+
return self.__pa.binary(16)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _parquet() -> Any:
|
|
244
|
+
_pyarrow()
|
|
245
|
+
import pyarrow.parquet
|
|
246
|
+
|
|
247
|
+
return pyarrow.parquet
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
class _Writer:
|
|
251
|
+
"""The shared objects of what is being written"""
|
|
252
|
+
|
|
253
|
+
def __init__(self, tables: dict[str, list[Any]]):
|
|
254
|
+
self.tables = tables
|
|
255
|
+
"""By tag: the objects, as plain rows"""
|
|
256
|
+
self.rows: dict[int, int] = {}
|
|
257
|
+
"""By id of a shared object, its row in its class's table"""
|
|
258
|
+
self.shared: list[Any] = []
|
|
259
|
+
"""The shared objects, kept so that no other object comes to have an id of theirs"""
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class _Reader:
|
|
263
|
+
"""The shared objects of what is being read"""
|
|
264
|
+
|
|
265
|
+
def __init__(self, tables: dict[str, list[Any]]):
|
|
266
|
+
self.tables = tables
|
|
267
|
+
self.objects: dict[tuple[str, int], Any] = {}
|
|
268
|
+
"""By tag and row, the objects read so far: _READING while one is being read"""
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
_READING = object()
|
|
272
|
+
|
|
273
|
+
# Makes a value plain: of what pyarrow makes an array of. And an object of what pyarrow gives for a value of one
|
|
274
|
+
type _Plain = Callable[[Any, _Writer], Any]
|
|
275
|
+
type _Object = Callable[[Any, _Reader], Any]
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class _Codec:
|
|
279
|
+
"""Writes and reads the objects of a class as the rows of a table"""
|
|
280
|
+
|
|
281
|
+
def __init__(self, cls: type):
|
|
282
|
+
if not (isinstance(cls, type) and is_native(cls)):
|
|
283
|
+
raise TypeError(f"{cls!r} is not a @native class")
|
|
284
|
+
struct_ = describe(cls)
|
|
285
|
+
assert isinstance(struct_, s.Struct)
|
|
286
|
+
self.cls = cls
|
|
287
|
+
self.tag = struct_.tag
|
|
288
|
+
self.struct = struct_
|
|
289
|
+
self.shared = _shared_classes(struct_.ref, [], set())
|
|
290
|
+
"""The classes its objects may share, however deeply"""
|
|
291
|
+
self.fields = [
|
|
292
|
+
(f.name, _plain(f.type), _object(f.type)) for f in struct_.fields
|
|
293
|
+
]
|
|
294
|
+
|
|
295
|
+
def schema(self, pa: Any) -> Any:
|
|
296
|
+
fields = [_field(f.name, f.type, pa, (self.cls,)) for f in self.struct.fields]
|
|
297
|
+
return pa.schema(fields, metadata={TAG: self.tag})
|
|
298
|
+
|
|
299
|
+
def plain(self, value: Any, writer: _Writer) -> dict[str, Any]:
|
|
300
|
+
# Exactly, as a subclass is another struct
|
|
301
|
+
if type(value) is not self.cls:
|
|
302
|
+
raise _Invalid
|
|
303
|
+
row = {}
|
|
304
|
+
for name, plain, _ in self.fields:
|
|
305
|
+
item = getattr(value, name)
|
|
306
|
+
try:
|
|
307
|
+
row[name] = plain(item, writer)
|
|
308
|
+
except _Invalid:
|
|
309
|
+
raise TypeError(
|
|
310
|
+
f"{self.cls.__qualname__}.{name} cannot be {item!r}"
|
|
311
|
+
) from None
|
|
312
|
+
return row
|
|
313
|
+
|
|
314
|
+
def object(self, row: Any, reader: _Reader) -> Any:
|
|
315
|
+
if type(row) is not dict:
|
|
316
|
+
raise _Invalid
|
|
317
|
+
# Those which are columns: one which is not takes its default, and a column which is not a field is ignored
|
|
318
|
+
fields = {}
|
|
319
|
+
for name, _, make in self.fields:
|
|
320
|
+
if name in row:
|
|
321
|
+
try:
|
|
322
|
+
fields[name] = make(row[name], reader)
|
|
323
|
+
except _Invalid:
|
|
324
|
+
raise ValueError(
|
|
325
|
+
f"{self.cls.__qualname__}.{name} cannot be read from {_brief(row[name])}"
|
|
326
|
+
) from None
|
|
327
|
+
try:
|
|
328
|
+
return self.cls(**fields)
|
|
329
|
+
except TypeError as e:
|
|
330
|
+
# A field with no default has no column, or a native field rejects what its column holds
|
|
331
|
+
raise ValueError(f"{self.cls.__qualname__} cannot be read: {e}") from None
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
_codecs: WeakKeyDictionary[type, _Codec] = WeakKeyDictionary()
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _codec(cls: type) -> _Codec:
|
|
338
|
+
try:
|
|
339
|
+
return _codecs[cls]
|
|
340
|
+
except (KeyError, TypeError):
|
|
341
|
+
codec = _Codec(cls)
|
|
342
|
+
_codecs[cls] = codec
|
|
343
|
+
return codec
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _shared_classes(t: s.Type, shared: list[type], seen: set[type]) -> list[type]:
|
|
347
|
+
"""The classes which a value of the type may share, however deeply, in the order met"""
|
|
348
|
+
for inner in walk(t):
|
|
349
|
+
if isinstance(inner, s.Shared) and inner.target.cls not in shared:
|
|
350
|
+
shared.append(inner.target.cls)
|
|
351
|
+
if isinstance(inner, s.StructRef) and inner.cls not in seen:
|
|
352
|
+
seen.add(inner.cls)
|
|
353
|
+
struct_ = describe(inner.cls)
|
|
354
|
+
assert isinstance(struct_, s.Struct)
|
|
355
|
+
for f in struct_.fields:
|
|
356
|
+
_shared_classes(f.type, shared, seen)
|
|
357
|
+
return shared
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _member_name(member: s.Type) -> str:
|
|
361
|
+
"""What names a union's member, as a field of the struct the union is: its tag, else what msgpack writes it as"""
|
|
362
|
+
if isinstance(member, s.Sequence) and member.element == _BYTE:
|
|
363
|
+
# As bytes, which it is natively
|
|
364
|
+
return "bytes"
|
|
365
|
+
return _tag(member) or s.wire_kind(member)[0]
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _member_names(members: tuple[s.Type, ...]) -> list[str]:
|
|
369
|
+
names = [_member_name(member) for member in members]
|
|
370
|
+
if len(set(names)) != len(names):
|
|
371
|
+
raise SchemaError(
|
|
372
|
+
f"The members of a union have the same name in Arrow: {names}"
|
|
373
|
+
)
|
|
374
|
+
return names
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _field(name: str, t: s.Type, pa: Any, within: tuple[type, ...]) -> Any:
|
|
378
|
+
"""The Arrow field of a type: one of a class in within is of a class which holds itself"""
|
|
379
|
+
inner = t.inner if isinstance(t, s.Optional) else t
|
|
380
|
+
metadata = (
|
|
381
|
+
{SHARED: native_info(inner.target.cls).tag}
|
|
382
|
+
if isinstance(inner, s.Shared)
|
|
383
|
+
else None
|
|
384
|
+
)
|
|
385
|
+
return pa.field(name, _type(inner, pa, within), metadata=metadata)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _type(t: s.Type, pa: Any, within: tuple[type, ...]) -> Any:
|
|
389
|
+
match t:
|
|
390
|
+
case s.Bool():
|
|
391
|
+
return pa.bool_()
|
|
392
|
+
case s.Int(bits, signed):
|
|
393
|
+
return getattr(pa, f"{'' if signed else 'u'}int{bits}")()
|
|
394
|
+
case s.Float(bits):
|
|
395
|
+
return pa.float32() if bits == 32 else pa.float64()
|
|
396
|
+
case s.Str():
|
|
397
|
+
return pa.string()
|
|
398
|
+
case s.Bytes():
|
|
399
|
+
return pa.binary()
|
|
400
|
+
case s.Date():
|
|
401
|
+
return pa.date32()
|
|
402
|
+
case s.Time():
|
|
403
|
+
return pa.time64("us")
|
|
404
|
+
case s.DateTime():
|
|
405
|
+
return pa.timestamp("us", tz="UTC")
|
|
406
|
+
case s.NaiveDateTime():
|
|
407
|
+
return pa.timestamp("us")
|
|
408
|
+
case s.TimeDelta():
|
|
409
|
+
return pa.duration("us")
|
|
410
|
+
case s.Uuid():
|
|
411
|
+
return pa.uuid()
|
|
412
|
+
case s.Decimal(places):
|
|
413
|
+
return pa.decimal128(s.DECIMAL_DIGITS, places)
|
|
414
|
+
case s.EnumRef():
|
|
415
|
+
return pa.dictionary(pa.int32(), pa.string())
|
|
416
|
+
case s.Optional(inner):
|
|
417
|
+
return _type(inner, pa, within)
|
|
418
|
+
case s.Sequence(element) if element == _BYTE:
|
|
419
|
+
return pa.binary()
|
|
420
|
+
case s.Sequence(element) | s.Set(element):
|
|
421
|
+
return pa.list_(_field("item", element, pa, within))
|
|
422
|
+
case s.Array(element, dimensions):
|
|
423
|
+
numbers = _type(s.Sequence(element), pa, within)
|
|
424
|
+
if dimensions == 1:
|
|
425
|
+
return numbers
|
|
426
|
+
# As Arrow's arrow.variable_shape_tensor is stored
|
|
427
|
+
shape = pa.list_(pa.field("item", pa.int32()), dimensions)
|
|
428
|
+
return pa.struct([pa.field("data", numbers), pa.field("shape", shape)])
|
|
429
|
+
case s.Tuple(elements):
|
|
430
|
+
return pa.struct(
|
|
431
|
+
[_field(str(i), e, pa, within) for i, e in enumerate(elements)]
|
|
432
|
+
)
|
|
433
|
+
case s.Map(key, value):
|
|
434
|
+
return pa.map_(
|
|
435
|
+
_type(key, pa, within),
|
|
436
|
+
_field("value", value, pa, within),
|
|
437
|
+
keys_sorted=True,
|
|
438
|
+
)
|
|
439
|
+
case s.Union(members):
|
|
440
|
+
names = _member_names(members)
|
|
441
|
+
return pa.struct(
|
|
442
|
+
[_field(n, m, pa, within) for n, m in zip(names, members, strict=True)]
|
|
443
|
+
)
|
|
444
|
+
case s.Shared():
|
|
445
|
+
return pa.uint32()
|
|
446
|
+
case s.StructRef(cls=cls) | s.Indirect(s.StructRef(cls=cls)):
|
|
447
|
+
if cls in within:
|
|
448
|
+
raise SchemaError(
|
|
449
|
+
f"{within[0].__qualname__} cannot be written as Arrow, as {cls.__qualname__} holds itself: "
|
|
450
|
+
"a table's columns cannot. A Shared field may hold its own class"
|
|
451
|
+
)
|
|
452
|
+
struct_ = describe(cls)
|
|
453
|
+
assert isinstance(struct_, s.Struct)
|
|
454
|
+
return pa.struct(
|
|
455
|
+
[_field(f.name, f.type, pa, (*within, cls)) for f in struct_.fields]
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _exactly(typ: type) -> _Plain:
|
|
460
|
+
def plain(value: Any, writer: _Writer) -> Any:
|
|
461
|
+
if type(value) is not typ:
|
|
462
|
+
raise _Invalid
|
|
463
|
+
return value
|
|
464
|
+
|
|
465
|
+
return plain
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _number(t: s.Decimal) -> Callable[[Any, Any], decimal.Decimal]:
|
|
469
|
+
"""Gives a Decimal as one of exactly the type's decimal places, raising _Invalid if it is not one"""
|
|
470
|
+
|
|
471
|
+
def number(value: Any, _: Any) -> decimal.Decimal:
|
|
472
|
+
if type(value) is not decimal.Decimal:
|
|
473
|
+
raise _Invalid
|
|
474
|
+
try:
|
|
475
|
+
return t.value(t.unscaled(value))
|
|
476
|
+
except ValueError:
|
|
477
|
+
raise _Invalid from None
|
|
478
|
+
|
|
479
|
+
return number
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _plain(t: s.Type) -> _Plain:
|
|
483
|
+
"""Makes a value of the type plain, raising _Invalid if it is not one"""
|
|
484
|
+
if cls := _struct_class(t):
|
|
485
|
+
if not isinstance(t, s.Shared):
|
|
486
|
+
# Its codec is found when used, not now, as the class may share itself
|
|
487
|
+
return lambda value, writer: _codec(cls).plain(value, writer)
|
|
488
|
+
|
|
489
|
+
def share(value: Any, writer: _Writer) -> int:
|
|
490
|
+
codec = _codec(cls)
|
|
491
|
+
if type(value) is not cls:
|
|
492
|
+
raise _Invalid
|
|
493
|
+
row = writer.rows.get(id(value))
|
|
494
|
+
if row is None:
|
|
495
|
+
rows = writer.tables[codec.tag]
|
|
496
|
+
row = writer.rows[id(value)] = len(rows)
|
|
497
|
+
writer.shared.append(value)
|
|
498
|
+
# Its row is taken before it is written, as it may share objects of its own class
|
|
499
|
+
rows.append(None)
|
|
500
|
+
rows[row] = codec.plain(value, writer)
|
|
501
|
+
return row
|
|
502
|
+
|
|
503
|
+
return share
|
|
504
|
+
|
|
505
|
+
match t:
|
|
506
|
+
case s.Uuid():
|
|
507
|
+
return lambda value, writer: _exactly(uuid.UUID)(value, writer).bytes
|
|
508
|
+
|
|
509
|
+
case s.Decimal():
|
|
510
|
+
return _number(t)
|
|
511
|
+
|
|
512
|
+
case (
|
|
513
|
+
s.Bool()
|
|
514
|
+
| s.Int()
|
|
515
|
+
| s.Str()
|
|
516
|
+
| s.Bytes()
|
|
517
|
+
| s.Date()
|
|
518
|
+
| s.Time()
|
|
519
|
+
| s.DateTime()
|
|
520
|
+
| s.NaiveDateTime()
|
|
521
|
+
| s.TimeDelta()
|
|
522
|
+
):
|
|
523
|
+
|
|
524
|
+
def scalar(value: Any, writer: _Writer) -> Any:
|
|
525
|
+
if not s.conforms(t, value):
|
|
526
|
+
raise _Invalid
|
|
527
|
+
return value
|
|
528
|
+
|
|
529
|
+
return scalar
|
|
530
|
+
|
|
531
|
+
case s.Float(bits=bits):
|
|
532
|
+
|
|
533
|
+
def number(value: Any, writer: _Writer) -> float:
|
|
534
|
+
if type(value) not in (float, int):
|
|
535
|
+
raise _Invalid
|
|
536
|
+
try:
|
|
537
|
+
if bits == 32:
|
|
538
|
+
struct.pack(">f", value)
|
|
539
|
+
return float(value)
|
|
540
|
+
except (OverflowError, struct.error):
|
|
541
|
+
raise _Invalid from None
|
|
542
|
+
|
|
543
|
+
return number
|
|
544
|
+
|
|
545
|
+
case s.EnumRef(cls=enum):
|
|
546
|
+
names = {
|
|
547
|
+
value: member.name for value, member in s.enum_members(enum).items()
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
def member(value: Any, writer: _Writer) -> str:
|
|
551
|
+
try:
|
|
552
|
+
return names[value]
|
|
553
|
+
except (KeyError, TypeError):
|
|
554
|
+
raise _Invalid from None
|
|
555
|
+
|
|
556
|
+
return member
|
|
557
|
+
|
|
558
|
+
case s.Optional(inner):
|
|
559
|
+
plain = _plain(inner)
|
|
560
|
+
return lambda value, writer: None if value is None else plain(value, writer)
|
|
561
|
+
|
|
562
|
+
case s.Sequence(element) if element == _BYTE:
|
|
563
|
+
|
|
564
|
+
def octets(value: Any, writer: _Writer) -> bytes:
|
|
565
|
+
if type(value) is not tuple:
|
|
566
|
+
raise _Invalid
|
|
567
|
+
try:
|
|
568
|
+
return bytes(value)
|
|
569
|
+
except (TypeError, ValueError):
|
|
570
|
+
raise _Invalid from None
|
|
571
|
+
|
|
572
|
+
return octets
|
|
573
|
+
|
|
574
|
+
case s.Sequence(element) | s.Set(element):
|
|
575
|
+
plain = _plain(element)
|
|
576
|
+
typ, key = (
|
|
577
|
+
(frozenset, _order(element)) if isinstance(t, s.Set) else (tuple, None)
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
def array(value: Any, writer: _Writer) -> list[Any]:
|
|
581
|
+
if type(value) is not typ:
|
|
582
|
+
raise _Invalid
|
|
583
|
+
items = _ordered(value, key) if typ is frozenset else value
|
|
584
|
+
return [plain(item, writer) for item in items]
|
|
585
|
+
|
|
586
|
+
return array
|
|
587
|
+
|
|
588
|
+
case s.Array(element, dimensions):
|
|
589
|
+
numbers, plain = _numbers(t), _plain(s.Sequence(element))
|
|
590
|
+
if dimensions == 1:
|
|
591
|
+
return lambda value, writer: plain(numbers(value), writer)
|
|
592
|
+
return lambda value, writer: {
|
|
593
|
+
"data": plain(numbers(value), writer),
|
|
594
|
+
"shape": list(value.shape),
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
case s.Tuple(elements):
|
|
598
|
+
plains = [_plain(e) for e in elements]
|
|
599
|
+
|
|
600
|
+
def fixed(value: Any, writer: _Writer) -> dict[str, Any]:
|
|
601
|
+
if type(value) is not tuple or len(value) != len(plains):
|
|
602
|
+
raise _Invalid
|
|
603
|
+
return {
|
|
604
|
+
str(i): plain(item, writer)
|
|
605
|
+
for i, (plain, item) in enumerate(zip(plains, value, strict=True))
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
return fixed
|
|
609
|
+
|
|
610
|
+
case s.Map(key_type, value_type):
|
|
611
|
+
plain_key, plain_value = _plain(key_type), _plain(value_type)
|
|
612
|
+
key = _order(key_type)
|
|
613
|
+
|
|
614
|
+
def mapping(value: Any, writer: _Writer) -> list[tuple[Any, Any]]:
|
|
615
|
+
if not isinstance(value, Mapping):
|
|
616
|
+
raise _Invalid
|
|
617
|
+
return [
|
|
618
|
+
(plain_key(k, writer), plain_value(value[k], writer))
|
|
619
|
+
for k in _ordered(value, key)
|
|
620
|
+
]
|
|
621
|
+
|
|
622
|
+
return mapping
|
|
623
|
+
|
|
624
|
+
case s.Union(members):
|
|
625
|
+
plains = [_plain(member) for member in members]
|
|
626
|
+
names = _member_names(members)
|
|
627
|
+
|
|
628
|
+
def union(value: Any, writer: _Writer) -> dict[str, Any]:
|
|
629
|
+
index = _member(members, value)
|
|
630
|
+
return {names[index]: plains[index](value, writer)}
|
|
631
|
+
|
|
632
|
+
return union
|
|
633
|
+
|
|
634
|
+
case _:
|
|
635
|
+
raise AssertionError(t)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _of(typ: type, convert: Callable[[Any], Any] | None = None) -> _Object:
|
|
639
|
+
def make(plain: Any, reader: _Reader) -> Any:
|
|
640
|
+
if type(plain) is not typ:
|
|
641
|
+
raise _Invalid
|
|
642
|
+
return convert(plain) if convert else plain
|
|
643
|
+
|
|
644
|
+
return make
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _object(t: s.Type) -> _Object:
|
|
648
|
+
"""Makes a value of the type from what pyarrow gives for one, raising _Invalid if that is not one"""
|
|
649
|
+
if cls := _struct_class(t):
|
|
650
|
+
if not isinstance(t, s.Shared):
|
|
651
|
+
return lambda plain, reader: _codec(cls).object(plain, reader)
|
|
652
|
+
|
|
653
|
+
def shared(plain: Any, reader: _Reader) -> Any:
|
|
654
|
+
codec = _codec(cls)
|
|
655
|
+
rows = reader.tables.get(codec.tag)
|
|
656
|
+
if type(plain) is not int or rows is None or not 0 <= plain < len(rows):
|
|
657
|
+
raise _Invalid
|
|
658
|
+
key = (codec.tag, plain)
|
|
659
|
+
obj = reader.objects.get(key)
|
|
660
|
+
if obj is None:
|
|
661
|
+
reader.objects[key] = _READING
|
|
662
|
+
obj = reader.objects[key] = codec.object(rows[plain], reader)
|
|
663
|
+
elif obj is _READING:
|
|
664
|
+
# It shares itself, which no object written could
|
|
665
|
+
raise _Invalid
|
|
666
|
+
return obj
|
|
667
|
+
|
|
668
|
+
return shared
|
|
669
|
+
|
|
670
|
+
match t:
|
|
671
|
+
case s.Bool():
|
|
672
|
+
return _of(bool)
|
|
673
|
+
|
|
674
|
+
case s.Int(min=low, max=high):
|
|
675
|
+
|
|
676
|
+
def integer(plain: Any, reader: _Reader) -> int:
|
|
677
|
+
if type(plain) is not int or not low <= plain <= high:
|
|
678
|
+
raise _Invalid
|
|
679
|
+
return plain
|
|
680
|
+
|
|
681
|
+
return integer
|
|
682
|
+
|
|
683
|
+
case s.Float():
|
|
684
|
+
return _of(float)
|
|
685
|
+
case s.Str():
|
|
686
|
+
return _of(str)
|
|
687
|
+
case s.Bytes():
|
|
688
|
+
return _of(bytes)
|
|
689
|
+
case s.Date():
|
|
690
|
+
return _of(dt.date)
|
|
691
|
+
case s.Time():
|
|
692
|
+
return _of(dt.time)
|
|
693
|
+
case s.TimeDelta():
|
|
694
|
+
return _of(dt.timedelta)
|
|
695
|
+
|
|
696
|
+
case s.Decimal():
|
|
697
|
+
# Of whatever places the column holds
|
|
698
|
+
return _number(t)
|
|
699
|
+
|
|
700
|
+
case s.Uuid():
|
|
701
|
+
|
|
702
|
+
def identifier(plain: Any, reader: _Reader) -> uuid.UUID:
|
|
703
|
+
# Its bytes, if the column is not named as Arrow's arrow.uuid
|
|
704
|
+
if type(plain) is bytes and len(plain) == 16:
|
|
705
|
+
return uuid.UUID(bytes=plain)
|
|
706
|
+
if type(plain) is not uuid.UUID:
|
|
707
|
+
raise _Invalid
|
|
708
|
+
return plain
|
|
709
|
+
|
|
710
|
+
return identifier
|
|
711
|
+
|
|
712
|
+
case s.NaiveDateTime():
|
|
713
|
+
|
|
714
|
+
def local(plain: Any, reader: _Reader) -> dt.datetime:
|
|
715
|
+
if type(plain) is not dt.datetime or plain.tzinfo is not None:
|
|
716
|
+
raise _Invalid
|
|
717
|
+
return plain
|
|
718
|
+
|
|
719
|
+
return local
|
|
720
|
+
|
|
721
|
+
case s.DateTime():
|
|
722
|
+
|
|
723
|
+
def instant(plain: Any, reader: _Reader) -> dt.datetime:
|
|
724
|
+
if type(plain) is not dt.datetime or plain.utcoffset() is None:
|
|
725
|
+
raise _Invalid
|
|
726
|
+
return plain.astimezone(dt.UTC)
|
|
727
|
+
|
|
728
|
+
return instant
|
|
729
|
+
|
|
730
|
+
case s.EnumRef(cls=enum):
|
|
731
|
+
members = {member.name: member for member in enum}
|
|
732
|
+
|
|
733
|
+
def member(plain: Any, reader: _Reader) -> Any:
|
|
734
|
+
try:
|
|
735
|
+
return members[plain]
|
|
736
|
+
except (KeyError, TypeError):
|
|
737
|
+
raise _Invalid from None
|
|
738
|
+
|
|
739
|
+
return member
|
|
740
|
+
|
|
741
|
+
case s.Optional(inner):
|
|
742
|
+
make = _object(inner)
|
|
743
|
+
return lambda plain, reader: None if plain is None else make(plain, reader)
|
|
744
|
+
|
|
745
|
+
case s.Sequence(element) if element == _BYTE:
|
|
746
|
+
return _of(bytes, tuple)
|
|
747
|
+
|
|
748
|
+
case s.Sequence(element) | s.Set(element):
|
|
749
|
+
make = _object(element)
|
|
750
|
+
container = frozenset if isinstance(t, s.Set) else tuple
|
|
751
|
+
|
|
752
|
+
def array(plain: Any, reader: _Reader) -> Any:
|
|
753
|
+
if type(plain) is not list:
|
|
754
|
+
raise _Invalid
|
|
755
|
+
return container(make(item, reader) for item in plain)
|
|
756
|
+
|
|
757
|
+
return array
|
|
758
|
+
|
|
759
|
+
case s.Array(element, dimensions):
|
|
760
|
+
held, make = _array(t), _object(s.Sequence(element))
|
|
761
|
+
if dimensions == 1:
|
|
762
|
+
return lambda plain, reader: held(make(plain, reader))
|
|
763
|
+
make_shape = _object(s.Sequence(s.Int(32)))
|
|
764
|
+
|
|
765
|
+
def shaped(plain: Any, reader: _Reader) -> Any:
|
|
766
|
+
if type(plain) is not dict or plain.keys() != {"data", "shape"}:
|
|
767
|
+
raise _Invalid
|
|
768
|
+
return held(
|
|
769
|
+
make(plain["data"], reader), make_shape(plain["shape"], reader)
|
|
770
|
+
)
|
|
771
|
+
|
|
772
|
+
return shaped
|
|
773
|
+
|
|
774
|
+
case s.Tuple(elements):
|
|
775
|
+
makes = [_object(e) for e in elements]
|
|
776
|
+
|
|
777
|
+
def fixed(plain: Any, reader: _Reader) -> tuple[Any, ...]:
|
|
778
|
+
if type(plain) is not dict:
|
|
779
|
+
raise _Invalid
|
|
780
|
+
try:
|
|
781
|
+
return tuple(
|
|
782
|
+
make(plain[str(i)], reader) for i, make in enumerate(makes)
|
|
783
|
+
)
|
|
784
|
+
except KeyError:
|
|
785
|
+
raise _Invalid from None
|
|
786
|
+
|
|
787
|
+
return fixed
|
|
788
|
+
|
|
789
|
+
case s.Map(key_type, value_type):
|
|
790
|
+
make_key, make_value = _object(key_type), _object(value_type)
|
|
791
|
+
|
|
792
|
+
def mapping(plain: Any, reader: _Reader) -> dict[Any, Any]:
|
|
793
|
+
if type(plain) is not list:
|
|
794
|
+
raise _Invalid
|
|
795
|
+
items = {make_key(k, reader): make_value(v, reader) for k, v in plain}
|
|
796
|
+
if len(items) != len(plain):
|
|
797
|
+
# A key twice
|
|
798
|
+
raise _Invalid
|
|
799
|
+
return items
|
|
800
|
+
|
|
801
|
+
return mapping
|
|
802
|
+
|
|
803
|
+
case s.Union(members):
|
|
804
|
+
makes = dict(
|
|
805
|
+
zip(_member_names(members), map(_object, members), strict=True)
|
|
806
|
+
)
|
|
807
|
+
|
|
808
|
+
def union(plain: Any, reader: _Reader) -> Any:
|
|
809
|
+
if type(plain) is not dict:
|
|
810
|
+
raise _Invalid
|
|
811
|
+
# The one member which is not null
|
|
812
|
+
held = [
|
|
813
|
+
(n, v) for n, v in plain.items() if v is not None and n in makes
|
|
814
|
+
]
|
|
815
|
+
if len(held) != 1:
|
|
816
|
+
raise _Invalid
|
|
817
|
+
return makes[held[0][0]](held[0][1], reader)
|
|
818
|
+
|
|
819
|
+
return union
|
|
820
|
+
|
|
821
|
+
case _:
|
|
822
|
+
raise AssertionError(t)
|