|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from enum import StrEnum |
| 4 | +from typing import Any |
| 5 | +from zoneinfo import ZoneInfo |
| 6 | + |
| 7 | +import pyarrow as pa |
| 8 | +import pyarrow.compute as pc |
| 9 | + |
| 10 | + |
| 11 | +class TimePrecision(StrEnum): |
| 12 | + NANOSECOND = "ns" |
| 13 | + MICROSECOND = "us" |
| 14 | + MILLISECOND = "ms" |
| 15 | + SECOND = "s" |
| 16 | + |
| 17 | + |
| 18 | +class DataType: |
| 19 | + def __init__(self, dtype: pa.DataType): |
| 20 | + self._dtype = dtype |
| 21 | + |
| 22 | + @property |
| 23 | + def value(self) -> str: |
| 24 | + return str(self._dtype) |
| 25 | + |
| 26 | + def __eq__(self, other: Any) -> bool: |
| 27 | + if isinstance(other, DataType): |
| 28 | + return self.value == other.value |
| 29 | + return self.value == other |
| 30 | + |
| 31 | + def __str__(self) -> str: |
| 32 | + return self.value |
| 33 | + |
| 34 | + def to_arrow(self) -> pa.DataType: |
| 35 | + return self._dtype |
| 36 | + |
| 37 | + @classmethod |
| 38 | + def null(cls) -> DataType: |
| 39 | + return cls(pa.null()) |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def bool_(cls) -> DataType: |
| 43 | + return cls(pa.bool_()) |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def string(cls) -> DataType: |
| 47 | + return cls(pa.string()) |
| 48 | + |
| 49 | + @classmethod |
| 50 | + def int8(cls) -> DataType: |
| 51 | + return cls(pa.int8()) |
| 52 | + |
| 53 | + @classmethod |
| 54 | + def int16(cls) -> DataType: |
| 55 | + return cls(pa.int16()) |
| 56 | + |
| 57 | + @classmethod |
| 58 | + def int32(cls) -> DataType: |
| 59 | + return cls(pa.int32()) |
| 60 | + |
| 61 | + @classmethod |
| 62 | + def int64(cls) -> DataType: |
| 63 | + return cls(pa.int64()) |
| 64 | + |
| 65 | + @classmethod |
| 66 | + def uint8(cls) -> DataType: |
| 67 | + return cls(pa.uint8()) |
| 68 | + |
| 69 | + @classmethod |
| 70 | + def uint16(cls) -> DataType: |
| 71 | + return cls(pa.uint16()) |
| 72 | + |
| 73 | + @classmethod |
| 74 | + def uint32(cls) -> DataType: |
| 75 | + return cls(pa.uint32()) |
| 76 | + |
| 77 | + @classmethod |
| 78 | + def uint64(cls) -> DataType: |
| 79 | + return cls(pa.uint64()) |
| 80 | + |
| 81 | + @classmethod |
| 82 | + def float16(cls) -> DataType: |
| 83 | + return cls(pa.float16()) |
| 84 | + |
| 85 | + @classmethod |
| 86 | + def float32(cls) -> DataType: |
| 87 | + return cls(pa.float32()) |
| 88 | + |
| 89 | + @classmethod |
| 90 | + def float64(cls) -> DataType: |
| 91 | + return cls(pa.float64()) |
| 92 | + |
| 93 | + @classmethod |
| 94 | + def timestamp(cls, unit: TimePrecision, tz: str | None = None) -> DataType: |
| 95 | + if unit not in { |
| 96 | + TimePrecision.SECOND, |
| 97 | + TimePrecision.MILLISECOND, |
| 98 | + TimePrecision.MICROSECOND, |
| 99 | + TimePrecision.NANOSECOND, |
| 100 | + }: |
| 101 | + raise ValueError(f"timestamp does not support unit: '{unit}'") |
| 102 | + if tz: |
| 103 | + ZoneInfo(tz) # check if valid timezone |
| 104 | + return cls(pa.timestamp(unit.value, tz)) |
| 105 | + return cls(pa.timestamp(unit.value)) |
| 106 | + |
| 107 | + @classmethod |
| 108 | + def time32(cls, unit: TimePrecision) -> DataType: |
| 109 | + if unit.value == "s" or unit.value == "ms": |
| 110 | + return cls(pa.time32(unit.value)) |
| 111 | + raise ValueError(f"time32 does not support unit: '{unit}'") |
| 112 | + |
| 113 | + @classmethod |
| 114 | + def time64(cls, unit: TimePrecision) -> DataType: |
| 115 | + if unit.value == "us" or unit.value == "ns": |
| 116 | + return cls(pa.time64(unit.value)) |
| 117 | + raise ValueError(f"time64 does not support unit: '{unit}'") |
| 118 | + |
| 119 | + @classmethod |
| 120 | + def date32(cls) -> DataType: |
| 121 | + return cls(pa.date32()) |
| 122 | + |
| 123 | + @classmethod |
| 124 | + def date64(cls) -> DataType: |
| 125 | + return cls(pa.date64()) |
| 126 | + |
| 127 | + @classmethod |
| 128 | + def duration(cls, unit: TimePrecision) -> DataType: |
| 129 | + if unit not in { |
| 130 | + TimePrecision.SECOND, |
| 131 | + TimePrecision.MILLISECOND, |
| 132 | + TimePrecision.MICROSECOND, |
| 133 | + TimePrecision.NANOSECOND, |
| 134 | + }: |
| 135 | + raise ValueError(f"timestamp does not support unit: '{unit}'") |
| 136 | + return cls(pa.duration(unit.value)) |
| 137 | + |
| 138 | + |
| 139 | +class _Symbol: |
| 140 | + def __init__(self, field_or_scalar: pc.Expression): |
| 141 | + self._symbol = field_or_scalar |
| 142 | + |
| 143 | + def __str__(self) -> str: |
| 144 | + return str(self._symbol) |
| 145 | + |
| 146 | + def __eq__(self, other: Any) -> Expression: # type: ignore[reportIncompatibleMethodOverride] |
| 147 | + other = other._symbol if isinstance(other, _Symbol) else other |
| 148 | + return Expression(self._symbol == other) |
| 149 | + |
| 150 | + def __ne__(self, other: Any) -> Expression: # type: ignore[reportIncompatibleMethodOverride] |
| 151 | + other = other._symbol if isinstance(other, _Symbol) else other |
| 152 | + return Expression(self._symbol != other) |
| 153 | + |
| 154 | + def __gt__(self, other: Any) -> Expression: |
| 155 | + other = other._symbol if isinstance(other, _Symbol) else other |
| 156 | + return Expression(self._symbol > other) |
| 157 | + |
| 158 | + def __lt__(self, other: Any) -> Expression: |
| 159 | + other = other._symbol if isinstance(other, _Symbol) else other |
| 160 | + return Expression(self._symbol < other) |
| 161 | + |
| 162 | + def __ge__(self, other: Any) -> Expression: |
| 163 | + other = other._symbol if isinstance(other, _Symbol) else other |
| 164 | + return Expression(self._symbol >= other) |
| 165 | + |
| 166 | + def __le__(self, other: Any) -> Expression: |
| 167 | + other = other._symbol if isinstance(other, _Symbol) else other |
| 168 | + return Expression(self._symbol <= other) |
| 169 | + |
| 170 | + def isin(self, values: set[Any]) -> Expression: |
| 171 | + values = {v._symbol if isinstance(v, _Symbol) else v for v in values} |
| 172 | + return Expression(self._symbol.isin(values)) |
| 173 | + |
| 174 | + def is_null(self, nan_is_null: bool = False) -> Expression: |
| 175 | + return Expression(self._symbol.is_null(nan_is_null=nan_is_null)) |
| 176 | + |
| 177 | + def is_nan(self) -> Expression: |
| 178 | + return Expression(self._symbol.is_nan()) |
| 179 | + |
| 180 | + def is_valid(self) -> Expression: |
| 181 | + return Expression(self._symbol.is_valid()) # type: ignore[reportGeneralTypeIssue] - pyarrow typing confused |
| 182 | + |
| 183 | + |
| 184 | +class Field(_Symbol): |
| 185 | + def __init__(self, name: str): |
| 186 | + self._name = name |
| 187 | + super().__init__(pc.field(name)) |
| 188 | + |
| 189 | + @property |
| 190 | + def name(self) -> str: |
| 191 | + return self._name |
| 192 | + |
| 193 | + def cast( |
| 194 | + self, |
| 195 | + dtype: DataType, |
| 196 | + *, |
| 197 | + allow_int_overflow: bool | None = None, |
| 198 | + allow_time_truncate: bool | None = None, |
| 199 | + allow_time_overflow: bool | None = None, |
| 200 | + allow_decimal_truncate: bool | None = None, |
| 201 | + allow_float_truncate: bool | None = None, |
| 202 | + allow_invalid_utf8: bool | None = None, |
| 203 | + ) -> Expression: |
| 204 | + """ |
| 205 | + Apply a type cast onto the field. |
| 206 | +
|
| 207 | +
|
| 208 | + Parameters |
| 209 | + ---------- |
| 210 | + expression : pyarrow.compute.Expression |
| 211 | + The expression to type cast. |
| 212 | + dtype : str |
| 213 | + The data type to cast to. |
| 214 | + allow_int_overflow : bool, default False |
| 215 | + Whether integer overflow is allowed when casting. |
| 216 | + allow_time_truncate : bool, default False |
| 217 | + Whether time precision truncation is allowed when casting. |
| 218 | + allow_time_overflow : bool, default False |
| 219 | + Whether date/time range overflow is allowed when casting. |
| 220 | + allow_decimal_truncate : bool, default False |
| 221 | + Whether decimal precision truncation is allowed when casting. |
| 222 | + allow_float_truncate : bool, default False |
| 223 | + Whether floating-point precision truncation is allowed when casting. |
| 224 | + allow_invalid_utf8 : bool, default False |
| 225 | + Whether producing invalid utf8 data is allowed when casting. |
| 226 | +
|
| 227 | + Returns |
| 228 | + ------- |
| 229 | + Expression |
| 230 | + An expression to be evaluated at runtime. |
| 231 | + """ |
| 232 | + options = pc.CastOptions( |
| 233 | + target_type=dtype.to_arrow(), |
| 234 | + allow_int_overflow=allow_int_overflow, |
| 235 | + allow_time_truncate=allow_time_truncate, |
| 236 | + allow_time_overflow=allow_time_overflow, |
| 237 | + allow_decimal_truncate=allow_decimal_truncate, |
| 238 | + allow_float_truncate=allow_float_truncate, |
| 239 | + allow_invalid_utf8=allow_invalid_utf8, |
| 240 | + ) |
| 241 | + expr = self._symbol.cast(options=options) # type: ignore[reportGeneralTypeIssues] - pyarrow issue |
| 242 | + return Expression(expr) |
| 243 | + |
| 244 | + |
| 245 | +class Value(_Symbol): |
| 246 | + def __init__(self, value: Any): |
| 247 | + # pyarrow.scalar creates an arrow-compatible value |
| 248 | + self._value = pa.scalar(value) |
| 249 | + # pyarrow.compute.scalar creates a symbolic expression |
| 250 | + super().__init__(pc.scalar(value)) |
| 251 | + |
| 252 | + @property |
| 253 | + def value(self) -> Any: |
| 254 | + return self._value |
| 255 | + |
| 256 | + @property |
| 257 | + def dtype(self) -> DataType: |
| 258 | + return DataType(self._value.type) |
| 259 | + |
| 260 | + def cast( |
| 261 | + self, |
| 262 | + dtype: DataType, |
| 263 | + *, |
| 264 | + allow_int_overflow: bool | None = None, |
| 265 | + allow_time_truncate: bool | None = None, |
| 266 | + allow_time_overflow: bool | None = None, |
| 267 | + allow_decimal_truncate: bool | None = None, |
| 268 | + allow_float_truncate: bool | None = None, |
| 269 | + allow_invalid_utf8: bool | None = None, |
| 270 | + ) -> Value: |
| 271 | + """ |
| 272 | + Apply a type cast onto the value. |
| 273 | +
|
| 274 | + This creates a new value of the desired type. |
| 275 | +
|
| 276 | + Parameters |
| 277 | + ---------- |
| 278 | + expression : pyarrow.compute.Expression |
| 279 | + The expression to type cast. |
| 280 | + dtype : str |
| 281 | + The data type to cast to. |
| 282 | + allow_int_overflow : bool, default False |
| 283 | + Whether integer overflow is allowed when casting. |
| 284 | + allow_time_truncate : bool, default False |
| 285 | + Whether time precision truncation is allowed when casting. |
| 286 | + allow_time_overflow : bool, default False |
| 287 | + Whether date/time range overflow is allowed when casting. |
| 288 | + allow_decimal_truncate : bool, default False |
| 289 | + Whether decimal precision truncation is allowed when casting. |
| 290 | + allow_float_truncate : bool, default False |
| 291 | + Whether floating-point precision truncation is allowed when casting. |
| 292 | + allow_invalid_utf8 : bool, default False |
| 293 | + Whether producing invalid utf8 data is allowed when casting. |
| 294 | +
|
| 295 | + Returns |
| 296 | + ------- |
| 297 | + Value |
| 298 | + A copied value with the desired data type. |
| 299 | + """ |
| 300 | + options = pc.CastOptions( |
| 301 | + target_type=dtype.to_arrow(), |
| 302 | + allow_int_overflow=allow_int_overflow, |
| 303 | + allow_time_truncate=allow_time_truncate, |
| 304 | + allow_time_overflow=allow_time_overflow, |
| 305 | + allow_decimal_truncate=allow_decimal_truncate, |
| 306 | + allow_float_truncate=allow_float_truncate, |
| 307 | + allow_invalid_utf8=allow_invalid_utf8, |
| 308 | + ) |
| 309 | + return Value(self._value.cast(options=options)) |
| 310 | + |
| 311 | + |
| 312 | +class Expression: |
| 313 | + def __init__(self, expression: pc.Expression): |
| 314 | + self._expr = expression |
| 315 | + |
| 316 | + def __str__(self) -> str: |
| 317 | + return str(self._expr) |
| 318 | + |
| 319 | + def __and__(self, other: Expression) -> Expression: |
| 320 | + return Expression(self._expr & other._expr) |
| 321 | + |
| 322 | + def __or__(self, other: Expression) -> Expression: |
| 323 | + return Expression(self._expr | other._expr) |
| 324 | + |
| 325 | + def __xor__(self, other: Expression) -> Expression: |
| 326 | + return Expression(pc.xor(self._expr, other._expr)) # type: ignore[reportAttributeAccessIssue] |
| 327 | + |
| 328 | + def __iand__(self, other: Expression) -> Expression: |
| 329 | + self._expr &= other._expr |
| 330 | + return self |
| 331 | + |
| 332 | + def __ior__(self, other: Expression) -> Expression: |
| 333 | + self._expr |= other._expr |
| 334 | + return self |
| 335 | + |
| 336 | + def __ixor__(self, other: Expression) -> Expression: |
| 337 | + self._expr = pc.xor(self._expr, other._expr) # type: ignore[reportAttributeAccessIssue] |
| 338 | + return self |
| 339 | + |
| 340 | + def __inv__(self) -> Expression: |
| 341 | + return Expression(pc.invert(self._expr)) # type: ignore[reportAttributeAccessIssue] |
| 342 | + |
| 343 | + def is_null(self, nan_is_null: bool = False) -> Expression: |
| 344 | + return Expression(self._expr.is_null(nan_is_null=nan_is_null)) |
| 345 | + |
| 346 | + def is_nan(self, nan_is_null: bool = False) -> Expression: |
| 347 | + return Expression(self._expr.is_nan()) |
| 348 | + |
| 349 | + def is_valid(self) -> Expression: |
| 350 | + return Expression(self._expr.is_valid()) # type: ignore[reportGeneralTypeIssue] - pyarrow typing confused |
| 351 | + |
| 352 | + def to_arrow(self): |
| 353 | + return self._expr |
0 commit comments