arrow2xmla 0.2.0__cp310-abi3-win_amd64.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.
arrow2xmla/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """Arrow in, XMLA out. The Python face of the `arrow2xmla` Rust crate: no engine, no product names, no dependencies.
2
+
3
+ from arrow2xmla import Cellset, CellValues, LevelAxis, Member, TupleAxis, MemberType
4
+
5
+ cs = Cellset(
6
+ cube="Sales",
7
+ columns_axis=TupleAxis.from_tuples([[Member("[Measures]", "[Measures].[MeasuresLevel]", 0, "[Measures].[Revenue]", "Revenue", member_type=MemberType.MEASURE)]]),
8
+ rows_axis=LevelAxis(Member("[Customer].[Name]", "[Customer].[Name].[Name]", 1, parent_unique_name="[Customer].[Name].[All]"), customer_names),
9
+ values=[CellValues(revenue, "#,##0.00")],
10
+ )
11
+ xml = cs.to_xml()
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.
18
+
19
+ Everything this package refuses raises a subclass of `XmlaError` (itself a `ValueError`).
20
+ """
21
+
22
+ from arrow2xmla import _native
23
+ from arrow2xmla._model import CellProperty, ChunkIterator, Cellset, CellValues, LevelAxis, Member, MemberProperty, MemberType, Rowset, RowsetColumn, TupleAxis
24
+ from arrow2xmla._soap import Envelope, Method, fault
25
+ from arrow2xmla._native import CellsetError, DoctypeError, RequestError, RequestTooLarge, UnsupportedTypeError, XmlaError
26
+
27
+ try:
28
+ from importlib.metadata import version as _version
29
+
30
+ __version__ = _version("arrow2xmla")
31
+ except Exception: # not installed as a distribution (a source checkout)
32
+ __version__ = "0+unknown"
33
+
34
+
35
+ __all__ = [
36
+ "__version__", "Cellset", "CellValues", "LevelAxis", "TupleAxis", "Member",
37
+ "MemberType", "MemberProperty", "CellProperty", "ChunkIterator", "Rowset", "RowsetColumn", "Envelope", "Method", "fault",
38
+ "XmlaError", "CellsetError", "UnsupportedTypeError", "RequestError", "DoctypeError", "RequestTooLarge",
39
+ ] # fmt: skip
40
+
41
+ # the request parser is a build feature (`request`, on by default)
42
+ if hasattr(_native, "parse_request"):
43
+ from arrow2xmla._request import Discover, Execute, Other, Request, Session, SessionKind, parse_request
44
+
45
+ __all__ += ["parse_request", "Request", "Session", "SessionKind", "Discover", "Execute", "Other"]
arrow2xmla/_model.py ADDED
@@ -0,0 +1,466 @@
1
+ """The cellset model: frozen dataclasses and enums, checked when they are made."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import queue
7
+ import threading
8
+ import weakref
9
+ from collections.abc import Mapping, Sequence
10
+ from dataclasses import dataclass, field
11
+ from enum import Enum, IntEnum
12
+ from typing import Any
13
+
14
+ from arrow2xmla._native import CellsetError
15
+
16
+
17
+ class MemberType(IntEnum):
18
+ """MDSCHEMA `MEMBER_TYPE`."""
19
+
20
+ REGULAR = 1 # a value of a field
21
+ ALL = 2 # the All member
22
+ MEASURE = 3
23
+ FORMULA = 4 # a calculated member
24
+
25
+
26
+ class MemberProperty(str, Enum):
27
+ """A member property a client may ask for (`DIMENSION PROPERTIES`), written after each member of its axis."""
28
+
29
+ PARENT_UNIQUE_NAME = "PARENT_UNIQUE_NAME"
30
+ HIERARCHY_UNIQUE_NAME = "HIERARCHY_UNIQUE_NAME"
31
+ MEMBER_UNIQUE_NAME = "MEMBER_UNIQUE_NAME"
32
+ MEMBER_CAPTION = "MEMBER_CAPTION"
33
+ LEVEL_UNIQUE_NAME = "LEVEL_UNIQUE_NAME"
34
+ LEVEL_NUMBER = "LEVEL_NUMBER"
35
+ CHILDREN_CARDINALITY = "CHILDREN_CARDINALITY"
36
+ PARENT_LEVEL = "PARENT_LEVEL"
37
+ PARENT_COUNT = "PARENT_COUNT"
38
+ MEMBER_TYPE = "MEMBER_TYPE"
39
+
40
+
41
+ class CellProperty(str, Enum):
42
+ """What is written in each cell: only the properties this package produces."""
43
+
44
+ VALUE = "VALUE"
45
+ FORMAT_STRING = "FORMAT_STRING"
46
+ LANGUAGE = "LANGUAGE"
47
+
48
+
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
58
+
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__}")
63
+
64
+
65
+ def _enums(kind: type[Enum], items: Any, what: str, one: str) -> tuple[Any, ...]:
66
+ if isinstance(items, (str, bytes)) or not isinstance(items, Sequence):
67
+ raise TypeError(f"{what} is a sequence of {kind.__name__}, not {type(items).__name__}")
68
+ out = []
69
+ for i in items:
70
+ try:
71
+ out.append(kind(i))
72
+ except ValueError:
73
+ raise CellsetError(f"unknown {one} {i!r} (one of {', '.join(m.value for m in kind)})") from None
74
+ return tuple(out)
75
+
76
+
77
+ def _threads(threads: object) -> int:
78
+ if isinstance(threads, bool) or not isinstance(threads, int) or threads < 0:
79
+ raise ValueError(f"threads is a number of threads, 0 or more (0: the machine's cores), not {threads!r}")
80
+ return min(threads, 1 << 16)
81
+
82
+
83
+ class _Stopped(Exception):
84
+ """The consumer of `iter_xml` stopped before the end."""
85
+
86
+
87
+ class _Sink:
88
+ def __init__(self, write: Any) -> None:
89
+ self.write = write
90
+
91
+
92
+ _live: weakref.WeakSet[ChunkIterator] = weakref.WeakSet()
93
+
94
+
95
+ def _stop_all() -> None:
96
+ for it in list(_live):
97
+ it.close()
98
+
99
+
100
+ atexit.register(_stop_all)
101
+
102
+
103
+ class ChunkIterator:
104
+ """The chunks of an answer, written ahead on a worker thread (`Cellset.iter_xml`). Closing it, using it up or dropping
105
+ it stops the worker; it is also a context manager."""
106
+
107
+ def __init__(self, cellset: Cellset, threads: int, buffer: int) -> None:
108
+ self._chunks: queue.Queue[Any] = queue.Queue(maxsize=buffer)
109
+ self._stop = threading.Event()
110
+ self._done = False
111
+ chunks, stop = self._chunks, self._stop # the worker holds these, not the iterator: dropping it is noticed
112
+ finished = object()
113
+ self._finished = finished
114
+
115
+ def put(chunk: Any) -> None:
116
+ while not stop.is_set():
117
+ try:
118
+ chunks.put(chunk, timeout=0.1)
119
+ return
120
+ except queue.Full:
121
+ continue
122
+ raise _Stopped
123
+
124
+ def run() -> None:
125
+ try:
126
+ cellset.write_to(_Sink(put), threads)
127
+ put(finished)
128
+ except _Stopped:
129
+ pass
130
+ except BaseException as e: # noqa: BLE001: handed to the consumer
131
+ try:
132
+ put(e)
133
+ except _Stopped:
134
+ pass
135
+
136
+ self._worker = threading.Thread(target=run, daemon=True, name="arrow2xmla-writer")
137
+ _live.add(self)
138
+ self._worker.start()
139
+
140
+ def __iter__(self) -> ChunkIterator:
141
+ return self
142
+
143
+ def __next__(self) -> bytes:
144
+ if self._done:
145
+ raise StopIteration
146
+ item = self._chunks.get()
147
+ if item is self._finished:
148
+ self.close()
149
+ raise StopIteration
150
+ if isinstance(item, BaseException):
151
+ self.close()
152
+ raise item
153
+ return item
154
+
155
+ def close(self) -> None:
156
+ """Stops the writer (the chunks not yet read are dropped)."""
157
+ self._done = True
158
+ self._stop.set()
159
+ if self._worker is not threading.current_thread():
160
+ self._worker.join()
161
+ _live.discard(self)
162
+
163
+ def __enter__(self) -> ChunkIterator:
164
+ return self
165
+
166
+ def __exit__(self, *_: object) -> None:
167
+ self.close()
168
+
169
+ def __del__(self) -> None:
170
+ stop = getattr(self, "_stop", None)
171
+ if stop is not None:
172
+ stop.set()
173
+
174
+
175
+ def _set(obj: Any, name: str, value: Any) -> None:
176
+ object.__setattr__(obj, name, value)
177
+
178
+
179
+ @dataclass(frozen=True, slots=True)
180
+ class Member:
181
+ """One member of a hierarchy: a value of a field, its All member, a measure."""
182
+
183
+ hierarchy: str
184
+ level_name: str
185
+ level_number: int
186
+ unique_name: str = "" # a level axis makes each value's own
187
+ caption: str = "" # likewise
188
+ parent_unique_name: str = "" # "" for All and for a measure
189
+ children_cardinality: int = 0
190
+ member_type: MemberType = MemberType.REGULAR
191
+
192
+ def __post_init__(self) -> None:
193
+ for name in ("hierarchy", "level_name", "unique_name", "caption", "parent_unique_name"):
194
+ if not isinstance(getattr(self, name), str):
195
+ raise TypeError(f"Member.{name} is a str, not {type(getattr(self, name)).__name__}")
196
+ for name in ("level_number", "children_cardinality"):
197
+ v = getattr(self, name)
198
+ if isinstance(v, bool) or not isinstance(v, int):
199
+ raise TypeError(f"Member.{name} is an int, not {type(v).__name__}")
200
+ if not -(2**31) <= self.level_number < 2**31:
201
+ raise CellsetError("level_number is a signed 32-bit number")
202
+ if not 0 <= self.children_cardinality <= 0xFFFFFFFF:
203
+ raise CellsetError("children_cardinality is an unsigned 32-bit number")
204
+ try:
205
+ _set(self, "member_type", MemberType(self.member_type))
206
+ except ValueError:
207
+ raise CellsetError(f"member_type {self.member_type!r} is not a MemberType (1 value, 2 All, 3 measure, 4 calculated)") from None
208
+
209
+
210
+
211
+ @dataclass(frozen=True, slots=True, eq=False)
212
+ class LevelAxis:
213
+ """The values of one hierarchy's level, read from a text array: nothing is built per value (the fast form for
214
+ big axes). A value's unique name is `<hierarchy>.&[<key>]` (`]` doubled), its caption the key; a null key is the
215
+ blank member."""
216
+
217
+ template: Member # hierarchy, level_name, level_number, parent_unique_name, children_cardinality, member_type
218
+ keys: Any # an Arrow text array (string, large_string or string_view)
219
+ all: Member | None = None # the All member, shown first
220
+ blank_caption: str = "(blank)"
221
+ properties: tuple[MemberProperty, ...] = ()
222
+
223
+ def __post_init__(self) -> None:
224
+ if not isinstance(self.template, Member):
225
+ raise TypeError("LevelAxis.template is a Member")
226
+ if self.all is not None and not isinstance(self.all, Member):
227
+ raise TypeError("LevelAxis.all is a Member or None")
228
+ if not isinstance(self.blank_caption, str):
229
+ raise TypeError("LevelAxis.blank_caption is a str")
230
+ _set(self, "keys", _plain(self.keys))
231
+ _set(self, "properties", _enums(MemberProperty, self.properties, "member properties", "member property"))
232
+
233
+
234
+
235
+ @dataclass(frozen=True, slots=True, eq=False)
236
+ class TupleAxis:
237
+ """Explicit tuples: the distinct `members` once, each tuple as indices into them (all tuples of one width).
238
+ `DISPLAY_INFO` (children, drilled down, same parent) is worked out from them. Build one from tuples of members
239
+ with `TupleAxis.from_tuples`."""
240
+
241
+ members: Sequence[Member]
242
+ tuples: Sequence[Sequence[int]]
243
+ properties: tuple[MemberProperty, ...] = ()
244
+
245
+ def __post_init__(self) -> None:
246
+ _set(self, "members", tuple(self.members))
247
+ if not all(isinstance(m, Member) for m in self.members):
248
+ raise TypeError("TupleAxis.members are Members")
249
+ tuples = tuple(tuple(t) for t in self.tuples)
250
+ if not all(isinstance(k, int) and not isinstance(k, bool) for t in tuples for k in t):
251
+ raise TypeError("TupleAxis.tuples are sequences of member indices (ints)")
252
+ if not all(0 <= k < len(self.members) for t in tuples for k in t):
253
+ raise CellsetError("a tuple names a member that is not in members")
254
+ _set(self, "tuples", tuples)
255
+ _set(self, "properties", _enums(MemberProperty, self.properties, "member properties", "member property"))
256
+
257
+ @classmethod
258
+ def from_tuples(cls, tuples: Sequence[Sequence[Member]], properties: Sequence[MemberProperty | str] = ()) -> TupleAxis:
259
+ """From tuples of members: equal members are stored once."""
260
+ index: dict[Member, int] = {}
261
+ out = [[index.setdefault(m, len(index)) for m in t] for t in tuples]
262
+ return cls(tuple(index), out, tuple(properties))
263
+
264
+
265
+
266
+ @dataclass(frozen=True, slots=True, eq=False)
267
+ class CellValues:
268
+ """One column of cells: an Arrow array of numbers or text, one per row, and its number format. A null is a cell
269
+ with no value."""
270
+
271
+ values: Any
272
+ format: str = ""
273
+
274
+ def __post_init__(self) -> None:
275
+ if not isinstance(self.format, str):
276
+ raise TypeError("CellValues.format is a str")
277
+ _set(self, "values", _plain(self.values))
278
+
279
+
280
+ @dataclass(frozen=True, slots=True, eq=False)
281
+ class Cellset:
282
+ """A whole cellset, the answer to an MDX `Execute`. A cell's ordinal is `row * len(values) + column`.
283
+
284
+ `columns_axis` lists the columns, `rows_axis` the rows. With neither the answer has at most one cell; with only
285
+ `columns_axis` it lists `rows * len(values)` tuples, the cells in order; `rows_axis` alone is not valid. With no
286
+ `values` at all there are no cells, so the axes are written as they are (a header-only answer)."""
287
+
288
+ cube: str
289
+ values: Sequence[CellValues]
290
+ columns_axis: LevelAxis | TupleAxis | None = None
291
+ rows_axis: LevelAxis | TupleAxis | None = None
292
+ slicer: Sequence[Member] = ()
293
+ cell_properties: Sequence[CellProperty | str] = (CellProperty.VALUE, CellProperty.FORMAT_STRING)
294
+ language: int = 1033 # the LCID written in each cell's Language
295
+
296
+ def __post_init__(self) -> None:
297
+ if not isinstance(self.cube, str):
298
+ raise TypeError("Cellset.cube is a str")
299
+ values = tuple(self.values) if isinstance(self.values, Sequence) and not isinstance(self.values, (str, bytes)) else None
300
+ if values is None or not all(isinstance(v, CellValues) for v in values):
301
+ raise TypeError("Cellset.values is a sequence of CellValues")
302
+ _set(self, "values", values)
303
+ for name in ("columns_axis", "rows_axis"):
304
+ a = getattr(self, name)
305
+ if a is not None and not isinstance(a, (LevelAxis, TupleAxis)):
306
+ raise TypeError(f"Cellset.{name} is a LevelAxis, a TupleAxis or None")
307
+ if self.rows_axis is not None and self.columns_axis is None:
308
+ raise CellsetError("rows_axis needs a columns_axis (the first axis is the columns)")
309
+ slicer = tuple(self.slicer)
310
+ if not all(isinstance(m, Member) for m in slicer):
311
+ raise TypeError("Cellset.slicer is a sequence of Members")
312
+ _set(self, "slicer", slicer)
313
+ _set(self, "cell_properties", _enums(CellProperty, self.cell_properties, "cell properties", "cell property"))
314
+ if isinstance(self.language, bool) or not isinstance(self.language, int):
315
+ raise TypeError("Cellset.language is an LCID (an int)")
316
+ if not 0 <= self.language <= 0xFFFFFFFF:
317
+ raise CellsetError("language is an unsigned 32-bit LCID")
318
+
319
+ def to_xml(self, threads: int = 0) -> bytes:
320
+ """The answer as bytes. `threads`: 0 uses the machine's cores (at most 8, and never more than are free: many
321
+ answers written at once share them), 1 stays on the calling thread. The whole answer is in memory (about
322
+ twice its size at the peak): for a big one, `write_to` or `iter_xml` hold about a megabyte."""
323
+ from arrow2xmla import _native
324
+
325
+ return _native.cellset_xml(self, _threads(threads))
326
+
327
+ def write_to(self, fp: Any, threads: int = 0) -> None:
328
+ """Writes the answer to `fp.write(bytes)` in chunks of about 1 MB as they are made, so it never exists whole in
329
+ memory. Whatever is wrong with the cellset is raised before the first chunk; an error of `fp.write` is raised
330
+ as it is."""
331
+ from arrow2xmla import _native
332
+
333
+ _native.cellset_write(self, fp.write, _threads(threads))
334
+
335
+ def iter_xml(self, threads: int = 0, buffer: int = 4) -> ChunkIterator:
336
+ """The answer as an iterator of chunks of about 1 MB, written ahead on another thread (at most `buffer` chunks
337
+ ahead). For a streaming response: it is lazy, so pass it on without `list()` or `*`. Whatever is wrong with the
338
+ cellset is raised by the first `next()`. The writer stops when the iterator is closed, used up or dropped."""
339
+ _threads(threads)
340
+ if isinstance(buffer, bool) or not isinstance(buffer, int) or buffer < 1:
341
+ raise ValueError(f"buffer is a number of chunks, 1 or more, not {buffer!r}")
342
+ return ChunkIterator(self, threads, buffer)
343
+
344
+ @classmethod
345
+ def from_dict(cls, d: Mapping[str, Any]) -> Cellset:
346
+ """From plain data (for a spec that comes from JSON or a config): the keys are the field names, `values` a list
347
+ of `(array, format)`, members and axes dicts of their fields (`{"level": {...}}` or `{"tuples": [...]}`).
348
+ An unknown key is an error."""
349
+ return _cellset_from(d)
350
+
351
+
352
+ @dataclass(frozen=True, slots=True, eq=False)
353
+ class RowsetColumn:
354
+ """One column of a rowset: its name (an XML name, e.g. `CUBE_NAME`) and an Arrow array, one value per row; a null is
355
+ left out of its row. The type declared to the client follows the array (text `xsd:string`, integers `xsd:int` /
356
+ `xsd:long`, floats `xsd:double`); `xsd_type` overrides it (`"xsd:boolean"` for text holding `true` / `false`). A
357
+ boolean array (pyarrow) is written as `true` / `false` and declared `xsd:boolean`."""
358
+
359
+ name: str
360
+ values: Any
361
+ xsd_type: str | None = None
362
+
363
+ def __post_init__(self) -> None:
364
+ if not isinstance(self.name, str):
365
+ raise TypeError("RowsetColumn.name is a str")
366
+ if self.xsd_type is not None and not isinstance(self.xsd_type, str):
367
+ raise TypeError("RowsetColumn.xsd_type is a str or None")
368
+ values = _plain(self.values)
369
+ if str(getattr(values, "type", None)) == "bool": # the XMLA way: text `true` / `false`, declared `xsd:boolean`
370
+ import pyarrow as pa
371
+ import pyarrow.compute as pc
372
+
373
+ values = pc.if_else(values, pa.scalar("true"), pa.scalar("false"))
374
+ if self.xsd_type is None:
375
+ _set(self, "xsd_type", "xsd:boolean")
376
+ _set(self, "values", values)
377
+
378
+
379
+ @dataclass(frozen=True, slots=True, eq=False)
380
+ class Rowset:
381
+ """The answer to a `Discover` (cubes, dimensions, properties, ...): columns of Arrow arrays of one length."""
382
+
383
+ columns: Sequence[RowsetColumn]
384
+
385
+ def __post_init__(self) -> None:
386
+ columns = tuple(self.columns) if isinstance(self.columns, Sequence) and not isinstance(self.columns, (str, bytes)) else None
387
+ if columns is None or not all(isinstance(c, RowsetColumn) for c in columns):
388
+ raise TypeError("Rowset.columns is a sequence of RowsetColumn")
389
+ _set(self, "columns", columns)
390
+
391
+ @classmethod
392
+ def from_columns(cls, columns: Mapping[str, Any]) -> Rowset:
393
+ """From `{name: array}`, typed after the arrays."""
394
+ return cls([RowsetColumn(name, values) for name, values in columns.items()])
395
+
396
+ def to_xml(self) -> bytes:
397
+ """The rowset (`<root>` with its schema block and rows) as bytes; for `Envelope(Method.DISCOVER).wrap(...)`."""
398
+ from arrow2xmla import _native
399
+
400
+ return _native.rowset_xml(self)
401
+
402
+
403
+ def _only(d: Mapping[str, Any], keys: tuple[str, ...], what: str) -> None:
404
+ if not isinstance(d, Mapping):
405
+ raise TypeError(f"{what} is a dict, not {type(d).__name__}")
406
+ for k in d:
407
+ if k not in keys:
408
+ raise CellsetError(f"{what} has no key {k!r} (keys: {', '.join(keys)})")
409
+
410
+
411
+ def _member_from(d: Any) -> Member:
412
+ if isinstance(d, Member):
413
+ return d
414
+ _only(d, ("hierarchy", "unique_name", "caption", "level_name", "level_number", "parent_unique_name", "children_cardinality", "member_type"), "a member")
415
+ for k in ("hierarchy", "level_name", "level_number"):
416
+ if k not in d:
417
+ raise CellsetError(f"a member needs {k!r}")
418
+ return Member(**d)
419
+
420
+
421
+ def _axis_from(d: Any) -> LevelAxis | TupleAxis:
422
+ if isinstance(d, (LevelAxis, TupleAxis)):
423
+ return d
424
+ _only(d, ("level", "tuples", "members", "properties"), "an axis")
425
+ props = tuple(d.get("properties", ()))
426
+ if "level" in d:
427
+ if "tuples" in d or "members" in d:
428
+ raise CellsetError("an axis is a level or tuples, not both")
429
+ lv = d["level"]
430
+ _only(lv, ("template", "keys", "all", "blank_caption"), "a level")
431
+ if "template" not in lv or "keys" not in lv:
432
+ raise CellsetError("a level needs 'template' and 'keys'")
433
+ a = lv.get("all")
434
+ return LevelAxis(_member_from(lv["template"]), lv["keys"], None if a is None else _member_from(a), lv.get("blank_caption", "(blank)"), props)
435
+ if "tuples" not in d:
436
+ raise CellsetError("an axis needs 'level' or 'tuples'")
437
+ if "members" in d:
438
+ return TupleAxis([_member_from(m) for m in d["members"]], d["tuples"], props)
439
+ return TupleAxis.from_tuples([[_member_from(m) for m in t] for t in d["tuples"]], props)
440
+
441
+
442
+ def _cellset_from(d: Mapping[str, Any]) -> Cellset:
443
+ _only(d, ("cube", "values", "columns_axis", "rows_axis", "slicer", "cell_properties", "language"), "a cellset")
444
+ if "cube" not in d:
445
+ raise CellsetError("a cellset needs 'cube'")
446
+ vals = d.get("values", ())
447
+ if not isinstance(vals, Sequence) or isinstance(vals, (str, bytes)):
448
+ raise TypeError("values is a list of (array, number format) pairs")
449
+ cells = []
450
+ for v in vals:
451
+ if isinstance(v, CellValues):
452
+ cells.append(v)
453
+ elif isinstance(v, (list, tuple)) and len(v) == 2:
454
+ cells.append(CellValues(*v))
455
+ else:
456
+ raise TypeError("each of values is an (array, number format) pair")
457
+ kw: dict[str, Any] = {}
458
+ for k in ("columns_axis", "rows_axis"):
459
+ if d.get(k) is not None:
460
+ kw[k] = _axis_from(d[k])
461
+ if "slicer" in d:
462
+ kw["slicer"] = [_member_from(m) for m in d["slicer"]]
463
+ for k in ("cell_properties", "language"):
464
+ if k in d:
465
+ kw[k] = d[k]
466
+ return Cellset(d["cube"], cells, **kw)
arrow2xmla/_native.pyd ADDED
Binary file
arrow2xmla/_request.py ADDED
@@ -0,0 +1,94 @@
1
+ """XMLA requests: what a client sent, as frozen dataclasses (match on them)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+
8
+ from arrow2xmla import _native
9
+
10
+
11
+ class SessionKind(str, Enum):
12
+ """What the SOAP header says about the session."""
13
+
14
+ NONE = "none" # no session header
15
+ BEGIN = "begin" # the server makes an id
16
+ USE = "use" # the client's own id, to echo
17
+ END = "end" # the client ends the session
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class Session:
22
+ """The session header: `id` is set for USE, and for END when the client names one."""
23
+
24
+ kind: SessionKind
25
+ id: str | None = None
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class Discover:
30
+ """A request for a rowset of metadata."""
31
+
32
+ request_type: str
33
+ restrictions: tuple[tuple[str, tuple[str, ...]], ...] # name -> values, in order
34
+ properties: tuple[tuple[str, str], ...] # the PropertyList, in order
35
+
36
+ def restriction(self, name: str) -> tuple[str, ...]:
37
+ """The values of a restriction (the last one when it is repeated); empty when absent."""
38
+ return next((v for k, v in reversed(self.restrictions) if k == name), ())
39
+
40
+ def property(self, name: str) -> str | None:
41
+ """A property's value (the last one when it is repeated)."""
42
+ return next((v for k, v in reversed(self.properties) if k == name), None)
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class Execute:
47
+ """An MDX statement."""
48
+
49
+ statement: str
50
+ properties: tuple[tuple[str, str], ...]
51
+
52
+ def property(self, name: str) -> str | None:
53
+ """A property's value (the last one when it is repeated)."""
54
+ return next((v for k, v in reversed(self.properties) if k == name), None)
55
+
56
+
57
+ @dataclass(frozen=True, slots=True)
58
+ class Other:
59
+ """A body with neither a Discover nor an Execute."""
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class Request:
64
+ """A parsed request: the session header and the first Discover or Execute."""
65
+
66
+ session: Session
67
+ call: Discover | Execute | Other
68
+
69
+
70
+ # the longest request read: a real one is a few KB
71
+ DEFAULT_MAX_SIZE: int = _native.DEFAULT_MAX_REQUEST
72
+
73
+
74
+ def parse_request(body: bytes, max_size: int = DEFAULT_MAX_SIZE) -> Request:
75
+ """Read an XMLA request (a SOAP envelope holding a Discover or an Execute), UTF-8 or UTF-16 with a BOM.
76
+
77
+ Raises `DoctypeError` for a DOCTYPE (never accepted: no entity expansion), `RequestTooLarge` for a body longer
78
+ than `max_size` bytes (refused before it is read) and `RequestError` for anything else that is not accepted.
79
+ """
80
+ if isinstance(max_size, bool) or not isinstance(max_size, int) or max_size < 0:
81
+ raise ValueError(f"max_size is a number of bytes, 0 or more, not {max_size!r}")
82
+ r = _native.parse_request(body, min(max_size, 1 << 62))
83
+ kind, sid = r["session"]
84
+ c = r["call"]
85
+ match c["kind"]:
86
+ case "discover":
87
+ call: Discover | Execute | Other = Discover(
88
+ c["request_type"], tuple((k, tuple(v)) for k, v in c["restrictions"]), tuple(map(tuple, c["properties"]))
89
+ )
90
+ case "execute":
91
+ call = Execute(c["statement"], tuple(map(tuple, c["properties"])))
92
+ case _:
93
+ call = Other()
94
+ return Request(Session(SessionKind(kind), sid), call)
arrow2xmla/_soap.py ADDED
@@ -0,0 +1,55 @@
1
+ """The SOAP envelope around an answer, and the fault that answers a request that failed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+
8
+ from arrow2xmla import _native
9
+
10
+
11
+ class Method(str, Enum):
12
+ """What an answer is to: the response element is `DiscoverResponse` or `ExecuteResponse`."""
13
+
14
+ DISCOVER = "Discover"
15
+ EXECUTE = "Execute"
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class Envelope:
20
+ """The envelope of an answer. A small answer is `wrap`ped; a big one is sent between `head()` and `tail()` while it
21
+ is written (`Cellset.iter_xml()` in between). `session`: the id to answer with (the client's own, or a new one for
22
+ `BeginSession`); none writes no session header."""
23
+
24
+ method: Method
25
+ session: str | None = None
26
+
27
+ def __post_init__(self) -> None:
28
+ object.__setattr__(self, "method", Method(self.method))
29
+ if self.session is not None and not isinstance(self.session, str):
30
+ raise TypeError("Envelope.session is a str or None")
31
+
32
+ def head(self) -> bytes:
33
+ """Everything before the answer."""
34
+ return _native.envelope(self.method.value, self.session, "head")
35
+
36
+ def tail(self) -> bytes:
37
+ """Everything after the answer."""
38
+ return _native.envelope(self.method.value, self.session, "tail")
39
+
40
+ def wrap(self, body: bytes) -> bytes:
41
+ """`head()`, `body` and `tail()` as one."""
42
+ return _native.envelope(self.method.value, self.session, "wrap", memoryview(body).tobytes())
43
+
44
+
45
+ DEFAULT_FAULT_CODE = 0xC1100000
46
+
47
+
48
+ def fault(message: str, *, code: int = DEFAULT_FAULT_CODE, source: str = "arrow2xmla", session: str | None = None) -> bytes:
49
+ """A SOAP fault (send it with HTTP status 500), in the form Analysis Services gives: `faultcode`
50
+ `XMLAnalysisError.0x<code>`, the message, and the error in `detail`."""
51
+ if not isinstance(message, str):
52
+ raise TypeError("the message of a fault is a str")
53
+ if isinstance(code, bool) or not isinstance(code, int) or not 0 <= code <= 0xFFFFFFFF:
54
+ raise ValueError("the code of a fault is an unsigned 32-bit number")
55
+ return _native.fault(message, code, source, session)
arrow2xmla/py.typed ADDED
File without changes