diffdb-core 0.1.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.
Files changed (53) hide show
  1. diffdb/__init__.py +179 -0
  2. diffdb/concurrency/__init__.py +10 -0
  3. diffdb/concurrency/pool.py +88 -0
  4. diffdb/concurrency/stream.py +111 -0
  5. diffdb/core/__init__.py +38 -0
  6. diffdb/core/differ.py +136 -0
  7. diffdb/core/hash_differ.py +390 -0
  8. diffdb/core/segment.py +323 -0
  9. diffdb/core/sql.py +81 -0
  10. diffdb/core/summary.py +179 -0
  11. diffdb/databases/__init__.py +59 -0
  12. diffdb/databases/_connect.py +210 -0
  13. diffdb/databases/base.py +266 -0
  14. diffdb/databases/bigquery.py +54 -0
  15. diffdb/databases/clickhouse.py +35 -0
  16. diffdb/databases/databricks.py +40 -0
  17. diffdb/databases/dialects/_base.yaml +182 -0
  18. diffdb/databases/dialects/bigquery.yaml +39 -0
  19. diffdb/databases/dialects/clickhouse.yaml +42 -0
  20. diffdb/databases/dialects/databricks.yaml +36 -0
  21. diffdb/databases/dialects/duckdb.yaml +48 -0
  22. diffdb/databases/dialects/mysql.yaml +45 -0
  23. diffdb/databases/dialects/oracle.yaml +44 -0
  24. diffdb/databases/dialects/postgresql.yaml +44 -0
  25. diffdb/databases/dialects/presto.yaml +37 -0
  26. diffdb/databases/dialects/redshift.yaml +11 -0
  27. diffdb/databases/dialects/snowflake.yaml +55 -0
  28. diffdb/databases/dialects/trino.yaml +5 -0
  29. diffdb/databases/dialects/vertica.yaml +39 -0
  30. diffdb/databases/duckdb.py +40 -0
  31. diffdb/databases/mysql.py +38 -0
  32. diffdb/databases/oracle.py +99 -0
  33. diffdb/databases/postgresql.py +34 -0
  34. diffdb/databases/presto.py +41 -0
  35. diffdb/databases/redshift.py +12 -0
  36. diffdb/databases/snowflake.py +55 -0
  37. diffdb/databases/trino.py +41 -0
  38. diffdb/databases/vertica.py +43 -0
  39. diffdb/databases/yaml_dialect.py +428 -0
  40. diffdb/geometry/__init__.py +42 -0
  41. diffdb/geometry/arithmetic.py +141 -0
  42. diffdb/geometry/bisection.py +100 -0
  43. diffdb/geometry/vector.py +42 -0
  44. diffdb/telemetry/__init__.py +11 -0
  45. diffdb/telemetry/info_tree.py +52 -0
  46. diffdb/telemetry/query_tracker.py +53 -0
  47. diffdb/types.py +302 -0
  48. diffdb/utils.py +121 -0
  49. diffdb_core-0.1.0.dist-info/METADATA +315 -0
  50. diffdb_core-0.1.0.dist-info/RECORD +53 -0
  51. diffdb_core-0.1.0.dist-info/WHEEL +5 -0
  52. diffdb_core-0.1.0.dist-info/licenses/LICENSE.md +87 -0
  53. diffdb_core-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,100 @@
1
+ """Algorithms for splitting 1D and multi-dimensional key-spaces for bisection-based diffing.
2
+
3
+ Supports integers, alphanumeric strings, UUIDs, datetimes, and decimals.
4
+ """
5
+
6
+ from datetime import datetime, timedelta
7
+ from decimal import Decimal
8
+ from itertools import pairwise, product
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from .arithmetic import ArithString, split_space
12
+ from .vector import Vector
13
+
14
+ if TYPE_CHECKING:
15
+ from ..types import DbKey
16
+ else:
17
+ DbKey = Any
18
+
19
+
20
+ def int_product(nums) -> int:
21
+ p = 1
22
+ for n in nums:
23
+ p *= n
24
+ return p
25
+
26
+
27
+ def split_datetime_range(min_key: datetime, max_key: datetime, count: int) -> list[datetime]:
28
+ """Split a datetime range into `count` evenly-spaced checkpoints."""
29
+ duration = max_key - min_key
30
+ total_seconds = duration.total_seconds()
31
+ step_seconds = total_seconds / (count + 1)
32
+
33
+ is_multi_day = step_seconds >= 86400
34
+ checkpoints = []
35
+ for i in range(1, count + 1):
36
+ ckpt = min_key + timedelta(seconds=step_seconds * i)
37
+ if is_multi_day:
38
+ ckpt = ckpt.replace(hour=0, minute=0, second=0, microsecond=0)
39
+ if min_key < ckpt < max_key and (not checkpoints or ckpt > checkpoints[-1]):
40
+ checkpoints.append(ckpt)
41
+
42
+ return [min_key] + checkpoints + [max_key]
43
+
44
+
45
+ def split_decimal_range(min_key: Decimal, max_key: Decimal, count: int) -> list[Decimal]:
46
+ """Split a Decimal range into `count` evenly-spaced checkpoints."""
47
+ step = (max_key - min_key) / (count + 1)
48
+ checkpoints = []
49
+ for i in range(1, count + 1):
50
+ ckpt = min_key + (step * i)
51
+ if min_key < ckpt < max_key:
52
+ checkpoints.append(ckpt)
53
+
54
+ return [min_key] + checkpoints + [max_key]
55
+
56
+
57
+ def split_key_space(min_key: DbKey, max_key: DbKey, count: int) -> list[DbKey]:
58
+ """Split a 1-dimensional key space between min_key and max_key into `count` slices."""
59
+ assert min_key < max_key
60
+
61
+ if isinstance(min_key, datetime):
62
+ return split_datetime_range(min_key, max_key, count)
63
+
64
+ if isinstance(min_key, Decimal):
65
+ return split_decimal_range(min_key, max_key, count)
66
+
67
+ if max_key - min_key <= count:
68
+ count = 1
69
+
70
+ if isinstance(min_key, ArithString):
71
+ assert type(min_key) is type(max_key)
72
+ checkpoints = list(min_key.range(max_key, count))
73
+ else:
74
+ checkpoints = split_space(min_key, max_key, count)
75
+
76
+ assert all(min_key < x < max_key for x in checkpoints)
77
+ return [min_key] + checkpoints + [max_key]
78
+
79
+
80
+ def split_compound_key_space(lower_bound: Vector, upper_bound: Vector, count: int) -> list[list[DbKey]]:
81
+ """Returns a list of split-points for each key dimension."""
82
+ return [
83
+ split_key_space(lower_key, upper_key, count)
84
+ for lower_key, upper_key in zip(lower_bound, upper_bound, strict=True)
85
+ ]
86
+
87
+
88
+ def create_mesh_from_points(*values_per_dim: list):
89
+ """Given a list of values along each axis of N dimensional space,
90
+ return an array of boxes whose start-points & end-points align with the given values.
91
+ """
92
+ assert all(len(v) >= 2 for v in values_per_dim), values_per_dim
93
+
94
+ ranges = [list(pairwise(values)) for values in values_per_dim]
95
+ assert all(a <= b for r in ranges for a, b in r)
96
+
97
+ res = [tuple(Vector(a) for a in zip(*r, strict=True)) for r in product(*ranges)]
98
+ expected_len = int_product(len(v) - 1 for v in values_per_dim)
99
+ assert len(res) == expected_len, (len(res), expected_len)
100
+ return res
@@ -0,0 +1,42 @@
1
+ """Immutable multidimensional Vector over arithmetic types with product-order comparison.
2
+ """
3
+
4
+
5
+ class Vector(tuple):
6
+ """Immutable implementation of a regular vector over any arithmetic value.
7
+
8
+ Implements a product order: https://en.wikipedia.org/wiki/Product_order
9
+ """
10
+
11
+ def __lt__(self, other: "Vector") -> bool:
12
+ if isinstance(other, Vector):
13
+ return all(a < b for a, b in zip(self, other, strict=True))
14
+ return NotImplemented
15
+
16
+ def __le__(self, other: "Vector") -> bool:
17
+ if isinstance(other, Vector):
18
+ return all(a <= b for a, b in zip(self, other, strict=True))
19
+ return NotImplemented
20
+
21
+ def __gt__(self, other: "Vector") -> bool:
22
+ if isinstance(other, Vector):
23
+ return all(a > b for a, b in zip(self, other, strict=True))
24
+ return NotImplemented
25
+
26
+ def __ge__(self, other: "Vector") -> bool:
27
+ if isinstance(other, Vector):
28
+ return all(a >= b for a, b in zip(self, other, strict=True))
29
+ return NotImplemented
30
+
31
+ def __eq__(self, other: object) -> bool:
32
+ if isinstance(other, Vector):
33
+ return all(a == b for a, b in zip(self, other, strict=True))
34
+ return NotImplemented
35
+
36
+ def __sub__(self, other: "Vector") -> "Vector":
37
+ if isinstance(other, Vector):
38
+ return Vector((a - b) for a, b in zip(self, other, strict=True))
39
+ raise NotImplementedError()
40
+
41
+ def __repr__(self) -> str:
42
+ return f"({', '.join(str(k) for k in self)})"
@@ -0,0 +1,11 @@
1
+ """Telemetry, query tracking, and hierarchical diff progress trees for diffdb.
2
+ """
3
+
4
+ from .info_tree import InfoTree, SegmentInfo
5
+ from .query_tracker import QueryTracker
6
+
7
+ __all__ = [
8
+ "InfoTree",
9
+ "QueryTracker",
10
+ "SegmentInfo",
11
+ ]
@@ -0,0 +1,52 @@
1
+ """Hierarchical tree data structure tracking segment diff results and row counts.
2
+ """
3
+
4
+ from typing import Any
5
+
6
+ from ..utils import dataclass, field
7
+
8
+
9
+ @dataclass(frozen=False)
10
+ class SegmentInfo:
11
+ tables: list[Any]
12
+
13
+ diff: list | None = None
14
+ is_diff: bool | None = None
15
+ diff_count: int | None = None
16
+
17
+ rowcounts: dict[int, int] = field(default_factory=dict)
18
+ max_rows: int | None = None
19
+
20
+ def set_diff(self, diff: list):
21
+ self.diff = diff
22
+ self.diff_count = len(diff)
23
+ self.is_diff = self.diff_count > 0
24
+
25
+ def update_from_children(self, child_infos):
26
+ child_infos = list(child_infos)
27
+ assert child_infos
28
+
29
+ self.diff_count = sum(c.diff_count for c in child_infos if c.diff_count is not None)
30
+ self.is_diff = any(c.is_diff for c in child_infos)
31
+
32
+ self.rowcounts = {
33
+ 1: sum(c.rowcounts[1] for c in child_infos if c.rowcounts),
34
+ 2: sum(c.rowcounts[2] for c in child_infos if c.rowcounts),
35
+ }
36
+
37
+
38
+ @dataclass
39
+ class InfoTree:
40
+ info: SegmentInfo
41
+ children: list["InfoTree"] = field(default_factory=list)
42
+
43
+ def add_node(self, table1: Any, table2: Any, max_rows: int | None = None):
44
+ node = InfoTree(SegmentInfo([table1, table2], max_rows=max_rows))
45
+ self.children.append(node)
46
+ return node
47
+
48
+ def aggregate_info(self):
49
+ if self.children:
50
+ for c in self.children:
51
+ c.aggregate_info()
52
+ self.info.update_from_children(c.info for c in self.children)
@@ -0,0 +1,53 @@
1
+ """Thread-safe collector for capturing SQL queries, checksums, row counts, and durations.
2
+ """
3
+
4
+ import threading
5
+ from collections.abc import Iterator
6
+ from typing import Any
7
+
8
+
9
+ class QueryTracker:
10
+ """Thread-safe collector for capturing SQL queries, checksums, row counts, and durations.
11
+
12
+ Used during diffing without relying on global state.
13
+ """
14
+
15
+ def __init__(self):
16
+ self._entries: list[dict[str, Any]] = []
17
+ self._lock = threading.Lock()
18
+
19
+ def record(self, entry: dict[str, Any]) -> None:
20
+ """Record a query execution entry."""
21
+ with self._lock:
22
+ self._entries.append(entry)
23
+
24
+ def get_queries(self) -> list[dict[str, Any]]:
25
+ """Return a copy of all recorded query logs."""
26
+ with self._lock:
27
+ return list(self._entries)
28
+
29
+ def get_queries_and_checksums(self) -> list[dict[str, Any]]:
30
+ """Return all executed queries along with their checksums, key bounds, and row counts."""
31
+ with self._lock:
32
+ return list(self._entries)
33
+
34
+ def get_query_logs(self) -> list[dict[str, Any]]:
35
+ """Alias for get_queries_and_checksums() compatible with thread logger formats."""
36
+ return self.get_queries_and_checksums()
37
+
38
+ def clear(self) -> None:
39
+ """Clear recorded entries."""
40
+ with self._lock:
41
+ self._entries.clear()
42
+
43
+ def __len__(self) -> int:
44
+ with self._lock:
45
+ return len(self._entries)
46
+
47
+ def __iter__(self) -> Iterator[dict[str, Any]]:
48
+ with self._lock:
49
+ return iter(list(self._entries))
50
+
51
+ def __repr__(self) -> str:
52
+ with self._lock:
53
+ return f"<QueryTracker entries={len(self._entries)}>"
diffdb/types.py ADDED
@@ -0,0 +1,302 @@
1
+ import decimal
2
+ from abc import ABC, abstractmethod
3
+ from datetime import datetime, timedelta
4
+ from operator import attrgetter
5
+
6
+ from .utils import ArithAlphanumeric, ArithUUID, Unknown, dataclass
7
+
8
+ DbPath = tuple[str, ...]
9
+ DbKey = int | str | bytes | ArithUUID | ArithAlphanumeric
10
+ DbTime = datetime
11
+
12
+
13
+ # Defaults used when a type name carries no precision, e.g. TIMESTAMP or FLOAT
14
+ DEFAULT_DATETIME_PRECISION = 6
15
+ DEFAULT_NUMERIC_PRECISION = 24
16
+
17
+
18
+ # ---------------------------------------------------------------------------------------------
19
+ # Type registry
20
+ #
21
+ # Every ColType declares, as class attributes / classmethods, everything the engine needs:
22
+ # norm_key How values are normalized to a string before hashing. The dialect dispatches
23
+ # to `normalize_<norm_key>()` when it has one (timestamp/number/uuid/boolean/
24
+ # string), otherwise to the YAML template `normalization.<norm_key>`.
25
+ # None = plain `to_string()`.
26
+ # compat_accepts Classes the *other* side's column must be an instance of when this type is
27
+ # on side 1 (checked in HashDiffer). None = no check.
28
+ # reconcile() Adjusts both sides to a mutually comparable form (e.g. lowest precision).
29
+ # from_type_args() Builds an instance from the arguments of a native type name, e.g.
30
+ # NUMBER(12,2) -> (12, 2) (None = not constructible -> unsupported type).
31
+ #
32
+ # Types registered with @register_type can be referenced by name in dialect YAML
33
+ # (`type_classes` / `type_regexps`). Adding a datatype = one subclass here + YAML entries.
34
+ # ---------------------------------------------------------------------------------------------
35
+ TYPE_REGISTRY: dict[str, type["ColType"]] = {}
36
+ # The dialect dispatches to normalize_<norm_key>(), so these would hit the dispatcher itself
37
+ _RESERVED_NORM_KEYS = frozenset({"value_by_type", "by_template"})
38
+
39
+
40
+ def register_type(cls_or_name=None):
41
+ """Register a ColType so dialect YAML can reference it by name (defaults to the class name)."""
42
+
43
+ def deco(cls):
44
+ name = cls_or_name if isinstance(cls_or_name, str) else cls.__name__
45
+ if cls.norm_key in _RESERVED_NORM_KEYS:
46
+ raise ValueError(f"{cls.__name__}.norm_key `{cls.norm_key}` is reserved")
47
+ if name in TYPE_REGISTRY and TYPE_REGISTRY[name] is not cls:
48
+ raise ValueError(f"ColType name `{name}` is already registered to {TYPE_REGISTRY[name]}")
49
+ TYPE_REGISTRY[name] = cls
50
+ return cls
51
+
52
+ if isinstance(cls_or_name, type):
53
+ return deco(cls_or_name)
54
+ return deco
55
+
56
+
57
+ class ColType:
58
+ norm_key: str | None = None
59
+ compat_accepts: tuple[type, ...] | None = None
60
+
61
+ @classmethod
62
+ def from_type_args(cls, dialect, args=()):
63
+ """Build an instance from the integer arguments of a native type name.
64
+
65
+ `args` holds the parenthesised arguments in order, e.g. NUMBER(12,2) -> (12, 2); a non-integer
66
+ argument (Oracle NUMBER(*,0), VARCHAR2(100 BYTE)) is None or its leading integer.
67
+ Return None if this type can't be built from a type name.
68
+ """
69
+ return
70
+
71
+ def reconcile(self, other: "ColType") -> tuple["ColType", "ColType"]:
72
+ "Return (self, other) adjusted to a mutually comparable form. Default: unchanged."
73
+ return self, other
74
+
75
+
76
+ class IKey(ABC):
77
+ "Interface for ColType, for using a column as a key in table."
78
+
79
+ @property
80
+ @abstractmethod
81
+ def python_type(self) -> type:
82
+ "Return the equivalent Python type of the key"
83
+
84
+ def make_value(self, value):
85
+ return self.python_type(value)
86
+
87
+ def next_value(self, value):
88
+ """Return the next value to serve as an exclusive upper bound.
89
+ Default implementation adds 1 (works for int, decimal, uuid, alphanum).
90
+ """
91
+ return value + 1
92
+
93
+
94
+ @dataclass
95
+ class PrecisionType(ColType):
96
+ precision: int
97
+ rounds: bool | Unknown = Unknown
98
+
99
+ def reconcile(self, other):
100
+ # Both sides take the lowest precision (and its rounding mode)
101
+ lowest = min(self, other, key=attrgetter("precision"))
102
+ return (
103
+ self.replace(precision=lowest.precision, rounds=lowest.rounds),
104
+ other.replace(precision=lowest.precision, rounds=lowest.rounds),
105
+ )
106
+
107
+
108
+ @register_type
109
+ class Boolean(ColType):
110
+ precision = 0
111
+ norm_key = "boolean"
112
+
113
+ @classmethod
114
+ def from_type_args(cls, dialect, args=()):
115
+ return cls()
116
+
117
+ def reconcile(self, other):
118
+ return _reconcile_numeric(self, other)
119
+
120
+
121
+ class TemporalType(PrecisionType, IKey):
122
+ norm_key = "timestamp"
123
+ default_precision = DEFAULT_DATETIME_PRECISION
124
+
125
+ @property
126
+ def python_type(self) -> type:
127
+ return datetime
128
+
129
+ @classmethod
130
+ def from_type_args(cls, dialect, args=()):
131
+ # TIMESTAMP(3) -> 3 fractional digits; no argument -> DEFAULT_DATETIME_PRECISION
132
+ precision = args[0] if args and args[0] is not None else cls.default_precision
133
+ return cls(precision=precision, rounds=dialect.ROUNDS_ON_PREC_LOSS)
134
+
135
+ def make_value(self, value):
136
+ if isinstance(value, str):
137
+ value = datetime.fromisoformat(value)
138
+ if isinstance(value, datetime):
139
+ return value.replace(hour=0, minute=0, second=0, microsecond=0)
140
+ raise TypeError(f"Cannot convert value of type {type(value)} to datetime")
141
+
142
+ def next_value(self, value):
143
+ return value + timedelta(days=1)
144
+
145
+
146
+ @register_type
147
+ class Timestamp(TemporalType):
148
+ pass
149
+
150
+
151
+ @register_type
152
+ class TimestampTZ(TemporalType):
153
+ pass
154
+
155
+
156
+ @register_type
157
+ class Datetime(TemporalType):
158
+ pass
159
+
160
+
161
+ @register_type
162
+ class Date(TemporalType):
163
+ default_precision = 0 # a plain DATE has no fractional seconds
164
+
165
+
166
+ @dataclass
167
+ class NumericType(ColType):
168
+ # 'precision' signifies how many fractional digits (after the dot) we want to compare
169
+ precision: int
170
+
171
+ def reconcile(self, other):
172
+ return _reconcile_numeric(self, other)
173
+
174
+
175
+ def _reconcile_numeric(col1, col2):
176
+ # Only the side(s) with higher precision are lowered; rounding mode is untouched
177
+ lowest = min(col1, col2, key=attrgetter("precision"))
178
+ if lowest.precision != col1.precision:
179
+ col1 = col1.replace(precision=lowest.precision)
180
+ if lowest.precision != col2.precision:
181
+ col2 = col2.replace(precision=lowest.precision)
182
+ return col1, col2
183
+
184
+
185
+ class FractionalType(NumericType):
186
+ norm_key = "number"
187
+
188
+
189
+ @register_type
190
+ class Float(FractionalType):
191
+ python_type = float
192
+
193
+ @classmethod
194
+ def from_type_args(cls, dialect, args=()):
195
+ # FLOAT(p): p is the binary precision; no argument -> DEFAULT_NUMERIC_PRECISION
196
+ binary_precision = args[0] if args and args[0] is not None else DEFAULT_NUMERIC_PRECISION
197
+ return cls(precision=dialect._convert_db_precision_to_digits(binary_precision))
198
+
199
+
200
+ @register_type
201
+ class Decimal(FractionalType, IKey): # Snowflake may use Decimal as a key
202
+ """Fixed-point number. `precision` is the number of fractional digits compared.
203
+
204
+ precision=None marks an unscaled column (datatype Oracle NUMBER / PostgreSQL numeric without a
205
+ declared scale). It is a marker only: HashDiffer warns and compares it with 0 fractional digits. To
206
+ compare decimals, declare a scale in the datatype on both sides (NUMBER(12,2) / numeric(12,2)).
207
+ """
208
+
209
+ precision: int | None
210
+
211
+ @property
212
+ def python_type(self) -> type:
213
+ if self.precision == 0 or self.precision is None:
214
+ return int
215
+ return decimal.Decimal
216
+
217
+ @classmethod
218
+ def from_type_args(cls, dialect, args=()):
219
+ # NUMBER(12,2) -> scale 2; NUMBER(10) / NUMBER(*,0) -> 0; plain NUMBER / numeric -> None (unscaled)
220
+ if not args:
221
+ return cls(precision=None)
222
+ if len(args) == 1:
223
+ return cls(precision=0)
224
+ return cls(precision=args[1] if args[1] is not None else 0)
225
+
226
+
227
+ @dataclass
228
+ class StringType(ColType):
229
+ python_type = str
230
+ norm_key = "string"
231
+
232
+
233
+ @register_type
234
+ class ColType_UUID(ColType, IKey):
235
+ python_type = ArithUUID
236
+ norm_key = "uuid"
237
+
238
+
239
+ class ColType_Alphanum(ColType, IKey):
240
+ python_type = ArithAlphanumeric
241
+
242
+
243
+ @register_type
244
+ class Native_UUID(ColType_UUID):
245
+ @classmethod
246
+ def from_type_args(cls, dialect, args=()):
247
+ return cls()
248
+
249
+
250
+ @register_type
251
+ class String_UUID(ColType_UUID, StringType):
252
+ pass
253
+
254
+
255
+ class String_Alphanum(ColType_Alphanum, StringType):
256
+ def make_value(self, value):
257
+ return self.python_type(value)
258
+
259
+
260
+ class String_VaryingAlphanum(String_Alphanum):
261
+ pass
262
+
263
+
264
+ @register_type
265
+ @dataclass
266
+ class Text(StringType):
267
+ """A string column as mapped in dialect YAML. TableSegment turns it into String_VaryingAlphanum, which
268
+ hashes the same way and can also serve as a bisection key."""
269
+
270
+ @classmethod
271
+ def from_type_args(cls, dialect, args=()):
272
+ return cls()
273
+
274
+
275
+ @register_type
276
+ @dataclass
277
+ class Integer(NumericType, IKey):
278
+ precision: int = 0
279
+ python_type: type = int
280
+
281
+ def __post_init__(self):
282
+ assert self.precision == 0
283
+
284
+ @classmethod
285
+ def from_type_args(cls, dialect, args=()):
286
+ return cls()
287
+
288
+
289
+ @dataclass
290
+ class UnknownColType(ColType):
291
+ """A datatype the dialect doesn't map. TableSegment rejects it."""
292
+
293
+ text: str
294
+
295
+
296
+ # Compatibility groups: when a column of this type is on side 1, side 2 must be one of these.
297
+ # Assigned after all classes exist; subclasses inherit through the MRO (e.g. String_UUID -> UUID rule).
298
+ PrecisionType.compat_accepts = (PrecisionType,)
299
+ NumericType.compat_accepts = (NumericType, Boolean)
300
+ Boolean.compat_accepts = (NumericType, Boolean)
301
+ ColType_UUID.compat_accepts = (ColType_UUID,)
302
+ StringType.compat_accepts = (StringType,)
diffdb/utils.py ADDED
@@ -0,0 +1,121 @@
1
+ import threading
2
+ from collections.abc import (
3
+ Hashable,
4
+ )
5
+ from dataclasses import dataclass as _std_dataclass
6
+ from dataclasses import field
7
+ from dataclasses import replace as _std_replace
8
+ from typing import (
9
+ Any,
10
+ )
11
+ from weakref import ref
12
+
13
+
14
+ def dataclass(*args, **kwargs):
15
+ def decorator(cls):
16
+ c = _std_dataclass(cls, **kwargs)
17
+ if not hasattr(c, "replace"):
18
+ c.replace = lambda self, **kw: _std_replace(self, **kw)
19
+ if not hasattr(c, "new"):
20
+ c.new = lambda self, **kw: _std_replace(self, **kw)
21
+ if not hasattr(c, "asdict"):
22
+ c.asdict = lambda self: {f: getattr(self, f) for f in self.__dataclass_fields__} if hasattr(self, "__dataclass_fields__") else dict(self.__dict__)
23
+ return c
24
+ if args:
25
+ return decorator(args[0])
26
+ return decorator
27
+
28
+
29
+ # -- Typing & Common --
30
+
31
+ try:
32
+ from typing import Self
33
+ except ImportError:
34
+ Self = Any
35
+
36
+
37
+ class WeakCache:
38
+ def __init__(self):
39
+ self._cache = {}
40
+ self._lock = threading.Lock()
41
+
42
+ def _hashable_key(self, k: dict | Hashable) -> Hashable:
43
+ if isinstance(k, dict):
44
+ return tuple(sorted(k.items(), key=lambda x: x[0]))
45
+ return k
46
+
47
+ def add(self, key: dict | Hashable, value: Any):
48
+ key = self._hashable_key(key)
49
+ with self._lock:
50
+ self._cache[key] = ref(value)
51
+
52
+ def get(self, key: dict | Hashable) -> Any:
53
+ key = self._hashable_key(key)
54
+ with self._lock:
55
+ value = self._cache[key]()
56
+ if value is None:
57
+ del self._cache[key]
58
+ raise KeyError(f"Key {key} not found, or no longer a valid reference")
59
+ return value
60
+
61
+
62
+ def strict_zip(*args):
63
+ """Zip sequences together, raising ValueError if lengths do not match."""
64
+ lens = list(map(len, args))
65
+ if len(set(lens)) != 1:
66
+ raise ValueError(f"Mismatching lengths in arguments to strict_zip: {lens}")
67
+ return zip(*args)
68
+
69
+
70
+ # -- Alphanumerics, Numbers, and Geometry --
71
+
72
+ from .geometry import (
73
+ ArithAlphanumeric,
74
+ ArithString,
75
+ ArithUUID,
76
+ Vector,
77
+ alphanums,
78
+ alphanums_to_numbers,
79
+ alphanumToNumber,
80
+ justify_alphanums,
81
+ numberToAlphanum,
82
+ split_space,
83
+ )
84
+
85
+
86
+ class UnknownMeta(type):
87
+ def __instancecheck__(self, instance):
88
+ return instance is Unknown
89
+
90
+ def __repr__(self):
91
+ return "Unknown"
92
+
93
+
94
+ class Unknown(metaclass=UnknownMeta):
95
+ def __nonzero__(self):
96
+ raise TypeError()
97
+
98
+ def __new__(cls, *args, **kwargs):
99
+ raise RuntimeError("Unknown is a singleton")
100
+
101
+
102
+ __all__ = [
103
+ "ArithAlphanumeric",
104
+ "ArithString",
105
+ "ArithUUID",
106
+ "Self",
107
+ "Unknown",
108
+ "UnknownMeta",
109
+ "Vector",
110
+ "WeakCache",
111
+ "alphanumToNumber",
112
+ "alphanums",
113
+ "alphanums_to_numbers",
114
+ "dataclass",
115
+ "field",
116
+ "justify_alphanums",
117
+ "numberToAlphanum",
118
+ "split_space",
119
+ "strict_zip",
120
+ ]
121
+