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.
- diffdb/__init__.py +179 -0
- diffdb/concurrency/__init__.py +10 -0
- diffdb/concurrency/pool.py +88 -0
- diffdb/concurrency/stream.py +111 -0
- diffdb/core/__init__.py +38 -0
- diffdb/core/differ.py +136 -0
- diffdb/core/hash_differ.py +390 -0
- diffdb/core/segment.py +323 -0
- diffdb/core/sql.py +81 -0
- diffdb/core/summary.py +179 -0
- diffdb/databases/__init__.py +59 -0
- diffdb/databases/_connect.py +210 -0
- diffdb/databases/base.py +266 -0
- diffdb/databases/bigquery.py +54 -0
- diffdb/databases/clickhouse.py +35 -0
- diffdb/databases/databricks.py +40 -0
- diffdb/databases/dialects/_base.yaml +182 -0
- diffdb/databases/dialects/bigquery.yaml +39 -0
- diffdb/databases/dialects/clickhouse.yaml +42 -0
- diffdb/databases/dialects/databricks.yaml +36 -0
- diffdb/databases/dialects/duckdb.yaml +48 -0
- diffdb/databases/dialects/mysql.yaml +45 -0
- diffdb/databases/dialects/oracle.yaml +44 -0
- diffdb/databases/dialects/postgresql.yaml +44 -0
- diffdb/databases/dialects/presto.yaml +37 -0
- diffdb/databases/dialects/redshift.yaml +11 -0
- diffdb/databases/dialects/snowflake.yaml +55 -0
- diffdb/databases/dialects/trino.yaml +5 -0
- diffdb/databases/dialects/vertica.yaml +39 -0
- diffdb/databases/duckdb.py +40 -0
- diffdb/databases/mysql.py +38 -0
- diffdb/databases/oracle.py +99 -0
- diffdb/databases/postgresql.py +34 -0
- diffdb/databases/presto.py +41 -0
- diffdb/databases/redshift.py +12 -0
- diffdb/databases/snowflake.py +55 -0
- diffdb/databases/trino.py +41 -0
- diffdb/databases/vertica.py +43 -0
- diffdb/databases/yaml_dialect.py +428 -0
- diffdb/geometry/__init__.py +42 -0
- diffdb/geometry/arithmetic.py +141 -0
- diffdb/geometry/bisection.py +100 -0
- diffdb/geometry/vector.py +42 -0
- diffdb/telemetry/__init__.py +11 -0
- diffdb/telemetry/info_tree.py +52 -0
- diffdb/telemetry/query_tracker.py +53 -0
- diffdb/types.py +302 -0
- diffdb/utils.py +121 -0
- diffdb_core-0.1.0.dist-info/METADATA +315 -0
- diffdb_core-0.1.0.dist-info/RECORD +53 -0
- diffdb_core-0.1.0.dist-info/WHEEL +5 -0
- diffdb_core-0.1.0.dist-info/licenses/LICENSE.md +87 -0
- diffdb_core-0.1.0.dist-info/top_level.txt +1 -0
diffdb/__init__.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
|
|
3
|
+
from .core import (
|
|
4
|
+
DEFAULT_BISECTION_FACTOR,
|
|
5
|
+
DEFAULT_BISECTION_THRESHOLD,
|
|
6
|
+
ColumnDiff,
|
|
7
|
+
DiffResultWrapper,
|
|
8
|
+
DiffSummary,
|
|
9
|
+
EmptyTable,
|
|
10
|
+
HashDiffer,
|
|
11
|
+
KeyDiff,
|
|
12
|
+
TableSegment,
|
|
13
|
+
compare_row_sets,
|
|
14
|
+
)
|
|
15
|
+
from .databases import Database, connect
|
|
16
|
+
from .geometry import Vector
|
|
17
|
+
from .telemetry import QueryTracker
|
|
18
|
+
from .types import DbPath
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def connect_to_table(
|
|
24
|
+
db_info: str | dict | Database,
|
|
25
|
+
table_name: DbPath | str,
|
|
26
|
+
bisection_columns: str | Sequence[str],
|
|
27
|
+
columns: dict[str, dict[str, str]],
|
|
28
|
+
thread_count: int | None = 1,
|
|
29
|
+
**kwargs,
|
|
30
|
+
) -> TableSegment:
|
|
31
|
+
"""Connects to the given database, and creates a TableSegment instance
|
|
32
|
+
|
|
33
|
+
Parameters:
|
|
34
|
+
db_info: Either a URI string, dict of connection options or a connected diffdb Database.
|
|
35
|
+
table_name: Name of the table as a string, or a tuple that signifies the path.
|
|
36
|
+
bisection_columns: Names of the columns used to split the table into key ranges (need not be unique)
|
|
37
|
+
columns: Every column to compare, ``{name: {"datatype": ..., "transform_rule": ...}}``.
|
|
38
|
+
See :class:`TableSegment`. Pass ``key_columns=...`` in kwargs to pair rows by other columns.
|
|
39
|
+
thread_count: Number of threads for this connection (only if using a threadpooled db implementation)
|
|
40
|
+
|
|
41
|
+
See Also:
|
|
42
|
+
:meth:`connect`
|
|
43
|
+
"""
|
|
44
|
+
if isinstance(bisection_columns, str):
|
|
45
|
+
bisection_columns = (bisection_columns,)
|
|
46
|
+
if isinstance(db_info, Database):
|
|
47
|
+
db = db_info
|
|
48
|
+
else:
|
|
49
|
+
db = connect(db_info, thread_count=thread_count)
|
|
50
|
+
|
|
51
|
+
if isinstance(table_name, str):
|
|
52
|
+
table_name = db.parse_table_name(table_name)
|
|
53
|
+
|
|
54
|
+
return TableSegment(db, tuple(table_name), tuple(bisection_columns), columns, **kwargs)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def diff_tables(
|
|
58
|
+
table1: TableSegment,
|
|
59
|
+
table2: TableSegment,
|
|
60
|
+
*,
|
|
61
|
+
# Columns used to split the tables into key ranges (need not be unique)
|
|
62
|
+
bisection_columns: Sequence[str] | None = None,
|
|
63
|
+
# Columns identifying a logical row when summarizing (default: bisection_columns)
|
|
64
|
+
key_columns: Sequence[str] | None = None,
|
|
65
|
+
# Start/end bisection key values, used to restrict the segment
|
|
66
|
+
min_key: Vector | None = None,
|
|
67
|
+
max_key: Vector | None = None,
|
|
68
|
+
# Enable/disable threaded diffing. Needed to take advantage of database threads.
|
|
69
|
+
threaded: bool = True,
|
|
70
|
+
# Maximum size of each threadpool. None = auto. Only relevant when threaded is True.
|
|
71
|
+
# There may be many pools, so number of actual threads can be a lot higher.
|
|
72
|
+
max_threadpool_size: int | None = 1,
|
|
73
|
+
# An additional 'where' expression to restrict the search space.
|
|
74
|
+
where: str | None = None,
|
|
75
|
+
# Into how many segments to bisect per iteration
|
|
76
|
+
bisection_factor: int = DEFAULT_BISECTION_FACTOR,
|
|
77
|
+
# When should we stop bisecting and compare locally (in row count)
|
|
78
|
+
bisection_threshold: int = DEFAULT_BISECTION_THRESHOLD,
|
|
79
|
+
# Count identical duplicate rows when comparing downloaded rows (needed when keys aren't unique)
|
|
80
|
+
duplicate_rows_support: bool = True,
|
|
81
|
+
# If false, diffing on empty tables raises an EmptyTable(ValueError) exception.
|
|
82
|
+
allow_empty_tables: bool = False,
|
|
83
|
+
# Skip sorting the output for better performance.
|
|
84
|
+
skip_sort_results: bool = False,
|
|
85
|
+
# Enable/disable tracking queries and checksums for this run
|
|
86
|
+
track_queries: bool = True,
|
|
87
|
+
# If true, return (DiffResultWrapper, QueryTracker)
|
|
88
|
+
return_queries: bool = False,
|
|
89
|
+
) -> DiffResultWrapper | tuple[DiffResultWrapper, QueryTracker]:
|
|
90
|
+
"""Finds the diff between table1 and table2.
|
|
91
|
+
|
|
92
|
+
Parameters:
|
|
93
|
+
bisection_columns (Tuple[str, ...]): Columns used to split the tables into key ranges. Need not be unique.
|
|
94
|
+
key_columns (Tuple[str, ...]): Columns identifying a logical row in :meth:`DiffResultWrapper.summarize`.
|
|
95
|
+
min_key (:data:`Vector`, optional): Lowest key value, used to restrict the segment
|
|
96
|
+
max_key (:data:`Vector`, optional): Highest key value, used to restrict the segment
|
|
97
|
+
threaded (bool): Enable/disable threaded diffing. Needed to take advantage of database threads.
|
|
98
|
+
max_threadpool_size (int): Maximum size of each threadpool. ``None`` means auto.
|
|
99
|
+
Only relevant when `threaded` is ``True``.
|
|
100
|
+
There may be many pools, so number of actual threads can be a lot higher.
|
|
101
|
+
(Note: For best performance, we recommend setting this to at least twice the
|
|
102
|
+
`thread_count` argument provided to the driver through `connect()`/`connect_to_table()`.
|
|
103
|
+
where (str, optional): An additional 'where' expression to restrict the search space.
|
|
104
|
+
bisection_factor (int): Into how many segments to bisect per iteration.
|
|
105
|
+
bisection_threshold (Number): Minimal row count of segment to bisect, otherwise download
|
|
106
|
+
and compare locally.
|
|
107
|
+
duplicate_rows_support (bool): Count identical duplicate rows when comparing downloaded rows, so a
|
|
108
|
+
row present twice on one side and once on the other is reported.
|
|
109
|
+
Needed when the bisection columns aren't unique. (default: True)
|
|
110
|
+
allow_empty_tables (bool): If false, diffing on empty tables raises an EmptyTable(ValueError) exception.
|
|
111
|
+
skip_sort_results (bool): Skip sorting the output for better performance. (default: False)
|
|
112
|
+
track_queries (bool): Enable/disable tracking queries and checksums for this run. (default: True)
|
|
113
|
+
return_queries (bool): If true, return (DiffResultWrapper, QueryTracker). (default: False)
|
|
114
|
+
|
|
115
|
+
Note:
|
|
116
|
+
`bisection_columns`, `key_columns`, `min_key`, `max_key` and `where` override the corresponding attributes of both
|
|
117
|
+
:class:`TableSegment` instances. Column definitions (`columns`) differ per side, so they are set
|
|
118
|
+
only when creating each :class:`TableSegment`.
|
|
119
|
+
|
|
120
|
+
Note:
|
|
121
|
+
It is recommended to call .close() on the returned object when done, to release thread-pool. Alternatively, you may use it as a context manager.
|
|
122
|
+
|
|
123
|
+
See Also:
|
|
124
|
+
:class:`TableSegment`
|
|
125
|
+
:class:`HashDiffer`
|
|
126
|
+
|
|
127
|
+
"""
|
|
128
|
+
if isinstance(bisection_columns, str):
|
|
129
|
+
bisection_columns = (bisection_columns,)
|
|
130
|
+
if isinstance(key_columns, str):
|
|
131
|
+
key_columns = (key_columns,)
|
|
132
|
+
|
|
133
|
+
tables = [table1, table2]
|
|
134
|
+
override_attrs = {
|
|
135
|
+
k: v
|
|
136
|
+
for k, v in {
|
|
137
|
+
"bisection_columns": bisection_columns,
|
|
138
|
+
"key_columns": key_columns,
|
|
139
|
+
"min_key": min_key,
|
|
140
|
+
"max_key": max_key,
|
|
141
|
+
"where": where,
|
|
142
|
+
}.items()
|
|
143
|
+
if v is not None
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
segments = [t.new(**override_attrs) for t in tables] if override_attrs else tables
|
|
147
|
+
|
|
148
|
+
differ = HashDiffer(
|
|
149
|
+
bisection_factor=bisection_factor,
|
|
150
|
+
bisection_threshold=bisection_threshold,
|
|
151
|
+
threaded=threaded,
|
|
152
|
+
max_threadpool_size=max_threadpool_size,
|
|
153
|
+
allow_empty_tables=allow_empty_tables,
|
|
154
|
+
skip_sort_results=skip_sort_results,
|
|
155
|
+
duplicate_rows_support=duplicate_rows_support,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
diff_res = differ.diff_tables(*segments, track_queries=track_queries)
|
|
159
|
+
if return_queries:
|
|
160
|
+
return diff_res, diff_res.query_tracker
|
|
161
|
+
return diff_res
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
__all__ = [
|
|
165
|
+
"ColumnDiff",
|
|
166
|
+
"DiffResultWrapper",
|
|
167
|
+
"DiffSummary",
|
|
168
|
+
"EmptyTable",
|
|
169
|
+
"HashDiffer",
|
|
170
|
+
"KeyDiff",
|
|
171
|
+
"QueryTracker",
|
|
172
|
+
"TableSegment",
|
|
173
|
+
"Vector",
|
|
174
|
+
"compare_row_sets",
|
|
175
|
+
"connect",
|
|
176
|
+
"connect_to_table",
|
|
177
|
+
"diff_tables",
|
|
178
|
+
]
|
|
179
|
+
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Priority-based thread worker pool.
|
|
2
|
+
|
|
3
|
+
Executes submitted tasks in priority order (higher priority first) with FIFO tie-breaking.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import contextlib
|
|
7
|
+
import itertools
|
|
8
|
+
import os
|
|
9
|
+
import threading
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from queue import PriorityQueue
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PriorityWorkerPool:
|
|
15
|
+
"""Thread pool where tasks are executed in priority order (higher priority first).
|
|
16
|
+
|
|
17
|
+
Safe across all Python versions without monkey-patching ThreadPoolExecutor or private _WorkItem.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, max_workers: int | None = 1):
|
|
21
|
+
if max_workers is None or max_workers <= 0:
|
|
22
|
+
max_workers = min(32, (os.cpu_count() or 1) + 4)
|
|
23
|
+
self.max_workers = max_workers
|
|
24
|
+
self._work_queue: PriorityQueue = PriorityQueue()
|
|
25
|
+
self._counter = itertools.count()
|
|
26
|
+
self._threads: list = []
|
|
27
|
+
self._shutdown = False
|
|
28
|
+
self._lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
for i in range(self.max_workers):
|
|
31
|
+
t = threading.Thread(
|
|
32
|
+
target=self._worker_loop,
|
|
33
|
+
daemon=True,
|
|
34
|
+
name=f"diffdb-worker-{i}",
|
|
35
|
+
)
|
|
36
|
+
t.start()
|
|
37
|
+
self._threads.append(t)
|
|
38
|
+
|
|
39
|
+
def submit(self, fn: Callable, *args, priority: int = 0, **kwargs):
|
|
40
|
+
with self._lock:
|
|
41
|
+
if self._shutdown:
|
|
42
|
+
return
|
|
43
|
+
count = next(self._counter)
|
|
44
|
+
# Store (-priority, count, fn, args, kwargs)
|
|
45
|
+
# Negative priority ensures higher numerical priority is dequeued first.
|
|
46
|
+
# Count ensures FIFO order for tasks with identical priority.
|
|
47
|
+
self._work_queue.put((-priority, count, fn, args, kwargs))
|
|
48
|
+
|
|
49
|
+
def _worker_loop(self):
|
|
50
|
+
while True:
|
|
51
|
+
try:
|
|
52
|
+
item = self._work_queue.get()
|
|
53
|
+
except Exception:
|
|
54
|
+
break
|
|
55
|
+
|
|
56
|
+
if item is None or self._shutdown:
|
|
57
|
+
self._work_queue.task_done()
|
|
58
|
+
break
|
|
59
|
+
|
|
60
|
+
_p, _c, fn, args, kwargs = item
|
|
61
|
+
if fn is None or self._shutdown:
|
|
62
|
+
self._work_queue.task_done()
|
|
63
|
+
break
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
with contextlib.suppress(Exception):
|
|
67
|
+
fn(*args, **kwargs)
|
|
68
|
+
finally:
|
|
69
|
+
self._work_queue.task_done()
|
|
70
|
+
|
|
71
|
+
def shutdown(self, wait: bool = True):
|
|
72
|
+
with self._lock:
|
|
73
|
+
if self._shutdown:
|
|
74
|
+
return
|
|
75
|
+
if not wait:
|
|
76
|
+
self._shutdown = True
|
|
77
|
+
|
|
78
|
+
# If wait=True, poison pill is lowest priority (runs after pending items).
|
|
79
|
+
# If wait=False, poison pill is highest priority (unblocks workers immediately).
|
|
80
|
+
priority = -float("inf") if not wait else float("inf")
|
|
81
|
+
for _ in self._threads:
|
|
82
|
+
count = next(self._counter)
|
|
83
|
+
self._work_queue.put((priority, count, None, None, None))
|
|
84
|
+
|
|
85
|
+
if wait:
|
|
86
|
+
for t in self._threads:
|
|
87
|
+
t.join(timeout=5.0)
|
|
88
|
+
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Stream yielder for gathering background task results into an iterable stream.
|
|
2
|
+
"""
|
|
3
|
+
|
|
4
|
+
import threading
|
|
5
|
+
from collections import deque
|
|
6
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
7
|
+
from queue import Empty, Full, Queue
|
|
8
|
+
|
|
9
|
+
from .pool import PriorityWorkerPool
|
|
10
|
+
|
|
11
|
+
_SENTINEL = object()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ThreadedYielder(Iterable):
|
|
15
|
+
"""Yields results from multiple threads into a single iterator, ordered by priority.
|
|
16
|
+
|
|
17
|
+
To add a source iterator or task, call ``submit()`` with a function that returns an iterator or list.
|
|
18
|
+
Priority for the iterator can be provided via the keyword argument 'priority' (higher runs first).
|
|
19
|
+
|
|
20
|
+
Parameters:
|
|
21
|
+
max_workers: Maximum number of worker threads.
|
|
22
|
+
yield_buffer_size: Maximum items buffered before applying backpressure.
|
|
23
|
+
0 or negative means unbounded. Default is 1.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, max_workers: int | None = None, yield_buffer_size: int = 1):
|
|
27
|
+
self._pool = PriorityWorkerPool(max_workers=max_workers)
|
|
28
|
+
maxsize = yield_buffer_size if yield_buffer_size and yield_buffer_size > 0 else 0
|
|
29
|
+
self._result_queue: Queue = Queue(maxsize=maxsize)
|
|
30
|
+
self._tasks_remaining = 0
|
|
31
|
+
self._exception: Exception | None = None
|
|
32
|
+
self._lock = threading.Lock()
|
|
33
|
+
self._closed = False
|
|
34
|
+
|
|
35
|
+
def submit(self, fn: Callable, *args, priority: int = 0, **kwargs):
|
|
36
|
+
with self._lock:
|
|
37
|
+
if self._closed or self._exception is not None:
|
|
38
|
+
return
|
|
39
|
+
self._tasks_remaining += 1
|
|
40
|
+
self._pool.submit(self._task_wrapper, fn, args, kwargs, priority=priority)
|
|
41
|
+
|
|
42
|
+
def _task_wrapper(self, fn, args, kwargs):
|
|
43
|
+
if self._closed or self._exception is not None:
|
|
44
|
+
self._on_task_finished()
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
res = fn(*args, **kwargs)
|
|
49
|
+
if res is not None and not self._closed:
|
|
50
|
+
# Put result into queue with timeout to allow clean shutdown
|
|
51
|
+
while not self._closed and self._exception is None:
|
|
52
|
+
try:
|
|
53
|
+
self._result_queue.put(res, timeout=0.2)
|
|
54
|
+
break
|
|
55
|
+
except Full:
|
|
56
|
+
continue
|
|
57
|
+
except Exception as e:
|
|
58
|
+
with self._lock:
|
|
59
|
+
if self._exception is None:
|
|
60
|
+
self._exception = e
|
|
61
|
+
self._result_queue.put(_SENTINEL)
|
|
62
|
+
finally:
|
|
63
|
+
self._on_task_finished()
|
|
64
|
+
|
|
65
|
+
def _on_task_finished(self):
|
|
66
|
+
with self._lock:
|
|
67
|
+
self._tasks_remaining -= 1
|
|
68
|
+
if self._tasks_remaining == 0 and not self._closed:
|
|
69
|
+
self._result_queue.put(_SENTINEL)
|
|
70
|
+
|
|
71
|
+
def shutdown(self, wait: bool = True):
|
|
72
|
+
with self._lock:
|
|
73
|
+
if self._closed:
|
|
74
|
+
return
|
|
75
|
+
self._closed = True
|
|
76
|
+
self._result_queue.put(_SENTINEL)
|
|
77
|
+
self._pool.shutdown(wait=wait)
|
|
78
|
+
|
|
79
|
+
def close(self):
|
|
80
|
+
self.shutdown(wait=False)
|
|
81
|
+
|
|
82
|
+
def __enter__(self):
|
|
83
|
+
return self
|
|
84
|
+
|
|
85
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
86
|
+
self.close()
|
|
87
|
+
|
|
88
|
+
def __iter__(self) -> Iterator:
|
|
89
|
+
while True:
|
|
90
|
+
if self._exception is not None:
|
|
91
|
+
raise self._exception
|
|
92
|
+
|
|
93
|
+
if self._closed:
|
|
94
|
+
break
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
item = self._result_queue.get(timeout=0.2)
|
|
98
|
+
except Empty:
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
if item is _SENTINEL:
|
|
102
|
+
if self._exception is not None:
|
|
103
|
+
raise self._exception
|
|
104
|
+
break
|
|
105
|
+
|
|
106
|
+
if isinstance(item, (list, tuple, deque)) or (
|
|
107
|
+
hasattr(item, "__iter__") and not isinstance(item, (str, bytes, dict))
|
|
108
|
+
):
|
|
109
|
+
yield from item
|
|
110
|
+
else:
|
|
111
|
+
yield item
|
diffdb/core/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Core diffing algorithms, table segments, and result structures for diffdb.
|
|
2
|
+
"""
|
|
3
|
+
|
|
4
|
+
from .differ import (
|
|
5
|
+
DiffResult,
|
|
6
|
+
DiffResultWrapper,
|
|
7
|
+
DiffStats,
|
|
8
|
+
)
|
|
9
|
+
from .hash_differ import (
|
|
10
|
+
DEFAULT_BISECTION_FACTOR,
|
|
11
|
+
DEFAULT_BISECTION_THRESHOLD,
|
|
12
|
+
HashDiffer,
|
|
13
|
+
compare_row_sets,
|
|
14
|
+
)
|
|
15
|
+
from .segment import (
|
|
16
|
+
RECOMMENDED_CHECKSUM_DURATION,
|
|
17
|
+
EmptyTable,
|
|
18
|
+
TableSegment,
|
|
19
|
+
)
|
|
20
|
+
from .summary import ColumnDiff, DiffSummary, KeyDiff, summarize_diff
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"DEFAULT_BISECTION_FACTOR",
|
|
24
|
+
"DEFAULT_BISECTION_THRESHOLD",
|
|
25
|
+
"RECOMMENDED_CHECKSUM_DURATION",
|
|
26
|
+
"ColumnDiff",
|
|
27
|
+
"DiffResult",
|
|
28
|
+
"DiffResultWrapper",
|
|
29
|
+
"DiffStats",
|
|
30
|
+
"DiffSummary",
|
|
31
|
+
"EmptyTable",
|
|
32
|
+
"HashDiffer",
|
|
33
|
+
"KeyDiff",
|
|
34
|
+
"TableSegment",
|
|
35
|
+
"compare_row_sets",
|
|
36
|
+
"summarize_diff",
|
|
37
|
+
]
|
|
38
|
+
|
diffdb/core/differ.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Diff results: the lazy result stream (DiffResultWrapper) and its statistics."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
from itertools import chain
|
|
6
|
+
|
|
7
|
+
from ..concurrency import ThreadedYielder
|
|
8
|
+
from ..telemetry import InfoTree, QueryTracker
|
|
9
|
+
from ..utils import dataclass, field
|
|
10
|
+
from .summary import DiffSummary, summarize_diff
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
DiffResult = Iterator[tuple[str, tuple]]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class DiffStats:
|
|
20
|
+
diff_by_sign: dict[str, int]
|
|
21
|
+
table1_count: int
|
|
22
|
+
table2_count: int
|
|
23
|
+
unchanged: int
|
|
24
|
+
diff_percent: float
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class DiffResultWrapper:
|
|
29
|
+
"""Wrapper for the diff result, with additional stats and info.
|
|
30
|
+
|
|
31
|
+
Supports reenterant iteration, context management, and immediate closing of the thread pool.
|
|
32
|
+
Note: Once the threadpool is closed, the iterator will not be able to continue.
|
|
33
|
+
"""
|
|
34
|
+
diff: iter # DiffResult
|
|
35
|
+
info_tree: InfoTree
|
|
36
|
+
stats: dict
|
|
37
|
+
stream_yielder: ThreadedYielder = None
|
|
38
|
+
result_list: list = field(default_factory=list)
|
|
39
|
+
query_tracker: QueryTracker | None = None
|
|
40
|
+
_summarized: bool = False # set by summarize(), which consumes the stream without storing raw rows
|
|
41
|
+
|
|
42
|
+
def __iter__(self):
|
|
43
|
+
"""Iterate over the results of the diff.
|
|
44
|
+
|
|
45
|
+
It's a "lazy-list": Repeated calls will return the same results, but will not re-run the diff.
|
|
46
|
+
"""
|
|
47
|
+
if self._summarized:
|
|
48
|
+
raise RuntimeError("This diff was consumed by summarize(); use the DiffSummary it returned")
|
|
49
|
+
yield from self.result_list
|
|
50
|
+
for i in self.diff:
|
|
51
|
+
self.result_list.append(i)
|
|
52
|
+
yield i
|
|
53
|
+
|
|
54
|
+
def close(self):
|
|
55
|
+
"Immediately stop diffing and close the thread pool"
|
|
56
|
+
if self.stream_yielder is not None:
|
|
57
|
+
self.stream_yielder.shutdown(wait=False)
|
|
58
|
+
|
|
59
|
+
def __enter__(self):
|
|
60
|
+
return self
|
|
61
|
+
|
|
62
|
+
def __exit__(self, *args):
|
|
63
|
+
self.close()
|
|
64
|
+
|
|
65
|
+
def _get_stats(self) -> DiffStats:
|
|
66
|
+
list(self) # Consume the iterator into result_list, if we haven't already
|
|
67
|
+
|
|
68
|
+
summary = self._summarize(self.result_list, limit=None)
|
|
69
|
+
diff_by_sign = {"-": summary.source_only, "+": summary.target_only, "!": summary.changed}
|
|
70
|
+
table1_count = self.info_tree.info.rowcounts[1]
|
|
71
|
+
table2_count = self.info_tree.info.rowcounts[2]
|
|
72
|
+
unchanged = table1_count - diff_by_sign["-"] - diff_by_sign["!"]
|
|
73
|
+
diff_percent = 1 - unchanged / max(table1_count, table2_count, 1)
|
|
74
|
+
|
|
75
|
+
return DiffStats(diff_by_sign, table1_count, table2_count, unchanged, diff_percent)
|
|
76
|
+
|
|
77
|
+
def _summarize(self, rows, limit: int | None) -> DiffSummary:
|
|
78
|
+
table1, table2 = self.info_tree.info.tables
|
|
79
|
+
return summarize_diff(rows, table1.key_positions, table1.relevant_columns, table2.relevant_columns, limit)
|
|
80
|
+
|
|
81
|
+
def summarize(self, limit: int | None = 1000) -> DiffSummary:
|
|
82
|
+
"""Run the diff (if not already run) and summarize it per key. See :class:`DiffSummary`.
|
|
83
|
+
|
|
84
|
+
Rows are paired by the segments' `key_columns`: one '-' and one '+' row with the same key become a
|
|
85
|
+
changed row with column-level differences. Only differing rows are kept in memory.
|
|
86
|
+
|
|
87
|
+
Parameters:
|
|
88
|
+
limit: stop the diff once this many distinct keys differ (``None`` or negative = no limit).
|
|
89
|
+
The remaining queries are cancelled and `limit_reached` is set; counts are then partial.
|
|
90
|
+
|
|
91
|
+
Note:
|
|
92
|
+
Consumes the diff stream without storing every raw row, so the wrapper can't be iterated
|
|
93
|
+
afterwards.
|
|
94
|
+
"""
|
|
95
|
+
if self._summarized:
|
|
96
|
+
raise RuntimeError("summarize() was already called on this diff")
|
|
97
|
+
object.__setattr__(self, "_summarized", True)
|
|
98
|
+
|
|
99
|
+
summary = self._summarize(chain(self.result_list, self.diff), limit)
|
|
100
|
+
if summary.limit_reached:
|
|
101
|
+
self.close() # stop scheduling queries
|
|
102
|
+
self.diff.close() # runs the differ's cleanup, which aggregates the (partial) row counts
|
|
103
|
+
self.result_list.clear()
|
|
104
|
+
|
|
105
|
+
rowcounts = self.info_tree.info.rowcounts
|
|
106
|
+
summary.source_scanned = rowcounts.get(1)
|
|
107
|
+
summary.target_scanned = rowcounts.get(2)
|
|
108
|
+
return summary
|
|
109
|
+
|
|
110
|
+
def get_stats_dict(self):
|
|
111
|
+
"""Return a dictionary of the diff stats"""
|
|
112
|
+
diff_stats = self._get_stats()
|
|
113
|
+
json_output = {
|
|
114
|
+
"rows_A": diff_stats.table1_count,
|
|
115
|
+
"rows_B": diff_stats.table2_count,
|
|
116
|
+
"exclusive_A": diff_stats.diff_by_sign["-"],
|
|
117
|
+
"exclusive_B": diff_stats.diff_by_sign["+"],
|
|
118
|
+
"updated": diff_stats.diff_by_sign["!"],
|
|
119
|
+
"unchanged": diff_stats.unchanged,
|
|
120
|
+
"total": sum(diff_stats.diff_by_sign.values()),
|
|
121
|
+
"stats": self.stats,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return json_output
|
|
125
|
+
|
|
126
|
+
def get_queries(self) -> list[dict]:
|
|
127
|
+
"""Return list of query dictionaries executed during this diff run."""
|
|
128
|
+
return self.query_tracker.get_queries() if self.query_tracker is not None else []
|
|
129
|
+
|
|
130
|
+
def get_queries_and_checksums(self) -> list[dict]:
|
|
131
|
+
"""Return list of queries, checksums, key bounds, and row counts executed during this diff run."""
|
|
132
|
+
return self.query_tracker.get_queries_and_checksums() if self.query_tracker is not None else []
|
|
133
|
+
|
|
134
|
+
def get_query_logs(self) -> list[dict]:
|
|
135
|
+
"""Alias for get_queries_and_checksums(), compatible with thread log database formats."""
|
|
136
|
+
return self.get_queries_and_checksums()
|