Coverage for src/signalk_cli/_arrow.py: 92%
76 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-22 09:25 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-22 09:25 +0000
1"""A small Arrow table built with nanoarrow, handed to dataframe libraries via the PyCapsule interface."""
3from __future__ import annotations
5import json
6from collections.abc import Mapping, Sequence
7from datetime import datetime
8from types import CapsuleType
9from typing import Any
11import nanoarrow as na
13_TIMESTAMP = na.timestamp("us", timezone="UTC")
15FEATHER_EXTENSIONS = {".feather", ".arrow", ".fea"}
18def _is_number(v: object) -> bool:
19 return isinstance(v, (int, float)) and not isinstance(v, bool)
22def as_text(v: object) -> str | None:
23 if v is None or isinstance(v, str):
24 return v
25 if isinstance(v, (dict, list)):
26 return json.dumps(v)
27 return str(v)
30def _epoch_us(ts: str | datetime | None) -> int | None:
31 if ts is None:
32 return None
33 dt = datetime.fromisoformat(ts) if isinstance(ts, str) else ts
34 return round(dt.timestamp() * 1_000_000)
37def infer_column(values: Sequence[Any]) -> tuple[list[str | float | bool | None], Any]:
38 """Pick one Arrow type for a column of JSON values: float64, bool, or string.
40 Numbers (and nulls) become float64, booleans stay bool, and anything else
41 — strings, objects, arrays, or a mix — becomes a string column, with
42 objects and arrays JSON-encoded.
43 """
44 present = [v for v in values if v is not None]
45 if all(_is_number(v) for v in present):
46 return [None if v is None else float(v) for v in values], na.float64()
47 if all(isinstance(v, bool) for v in present): 47 ↛ 48line 47 didn't jump to line 48 because the condition on line 47 was never true
48 return list(values), na.bool_()
49 return [as_text(v) for v in values], na.string()
52class ArrowTable:
53 """A table of query results, ready to load into any Arrow-aware dataframe library.
55 It implements the [Arrow PyCapsule interface](https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html),
56 so it can be passed straight to polars, pandas, pyarrow, DuckDB and others
57 without signalk-cli depending on any of them:
59 Examples:
60 ```python
61 import polars as pl
62 df = pl.DataFrame(table)
63 import pandas as pd
64 df = pd.DataFrame.from_arrow(table) # pandas >= 3.0
65 import pyarrow as pa
66 t = pa.table(table)
67 ```
68 """
70 def __init__(self, columns: dict[str, tuple[list[Any], Any]]) -> None:
71 self._columns = {name: values for name, (values, _) in columns.items()}
72 self._types = {name: t for name, (_, t) in columns.items()}
73 lengths = {len(v) for v in self._columns.values()}
74 if len(lengths) > 1: 74 ↛ 75line 74 didn't jump to line 75 because the condition on line 74 was never true
75 raise ValueError(f"Columns have different lengths: {sorted(lengths)}")
76 self._num_rows = lengths.pop() if lengths else 0
78 @classmethod
79 def from_rows(
80 cls,
81 timestamps: Sequence[str | datetime | None],
82 columns: Mapping[str, Sequence[Any]],
83 *,
84 text_columns: Sequence[str] = (),
85 timestamp_name: str = "timestamp",
86 ) -> ArrowTable:
87 """Build a table with a UTC timestamp column followed by the given columns.
89 Column types are inferred from the values (see `infer_column`),
90 except `text_columns`, which are always strings so an empty result
91 keeps the same schema.
92 """
93 built: dict[str, tuple[list[Any], Any]] = {
94 timestamp_name: ([_epoch_us(t) for t in timestamps], _TIMESTAMP)
95 }
96 for name, values in columns.items():
97 if name in text_columns:
98 built[name] = ([as_text(v) for v in values], na.string())
99 else:
100 built[name] = infer_column(values)
101 return cls(built)
103 @property
104 def num_rows(self) -> int:
105 return self._num_rows
107 @property
108 def column_names(self) -> list[str]:
109 return list(self._columns)
111 def __len__(self) -> int:
112 return self._num_rows
114 def __repr__(self) -> str:
115 cols = ", ".join(f"{n}: {self._types[n].type.name}" for n in self._columns)
116 return f"ArrowTable({self._num_rows} rows; {cols})"
118 def to_pydict(self) -> dict[str, list[Any]]:
119 """Return the columns as plain Python lists (timestamps as epoch microseconds)."""
120 return {name: list(values) for name, values in self._columns.items()}
122 def _batch(self) -> Any:
123 children = [
124 na.c_array(values, self._types[name])
125 for name, values in self._columns.items()
126 ]
127 schema = na.struct({name: self._types[name] for name in self._columns})
128 return na.c_array_from_buffers(
129 schema, self._num_rows, [None], children=children
130 )
132 def __arrow_c_schema__(self) -> CapsuleType:
133 capsule: CapsuleType = na.c_schema(
134 na.struct({name: self._types[name] for name in self._columns})
135 ).__arrow_c_schema__()
136 return capsule
138 def __arrow_c_stream__(
139 self, requested_schema: CapsuleType | None = None
140 ) -> CapsuleType:
141 stream = na.ArrayStream(self._batch())
142 capsule: CapsuleType = stream.__arrow_c_stream__(requested_schema)
143 return capsule
146def write_feather(table: ArrowTable, output: str) -> None:
147 """Write a table to a Feather (Arrow IPC file) — needs pyarrow."""
148 try:
149 import pyarrow as pa
150 from pyarrow import feather
151 except ImportError:
152 raise ImportError(
153 "pyarrow is required for Feather output: pip install 'signalk-cli[feather]'"
154 ) from None
155 feather.write_feather(pa.table(table), output)