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
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Hash-based recursive bisection diffing algorithm for SQL database tables."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import math
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
8
|
+
from itertools import chain
|
|
9
|
+
from numbers import Number
|
|
10
|
+
from operator import attrgetter, methodcaller
|
|
11
|
+
|
|
12
|
+
from ..concurrency import ThreadedYielder
|
|
13
|
+
from ..geometry import Vector, create_mesh_from_points
|
|
14
|
+
from ..telemetry import InfoTree, QueryTracker, SegmentInfo
|
|
15
|
+
from ..types import Decimal, IKey
|
|
16
|
+
from ..utils import dataclass, field, strict_zip
|
|
17
|
+
from .differ import DiffResult, DiffResultWrapper
|
|
18
|
+
from .segment import EmptyTable, TableSegment
|
|
19
|
+
|
|
20
|
+
DEFAULT_BISECTION_THRESHOLD = 1024 * 16
|
|
21
|
+
DEFAULT_BISECTION_FACTOR = 32
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def compare_row_sets(rows_a: list, rows_b: list, skip_sort_results: bool, duplicate_rows_support: bool) -> Iterator:
|
|
27
|
+
"""Compare two row sets locally in Python memory.
|
|
28
|
+
|
|
29
|
+
Returns tuples of ('+' or '-', row_tuple).
|
|
30
|
+
"""
|
|
31
|
+
if duplicate_rows_support:
|
|
32
|
+
counter = Counter(rows_b)
|
|
33
|
+
counter.subtract(rows_a)
|
|
34
|
+
diff = (("+", row) if count > 0 else ("-", row) for row, count in counter.items() for _ in range(abs(count)))
|
|
35
|
+
else:
|
|
36
|
+
set_a = set(rows_a)
|
|
37
|
+
set_b = set(rows_b)
|
|
38
|
+
diff = chain((("-", row) for row in set_a - set_b), (("+", row) for row in set_b - set_a))
|
|
39
|
+
|
|
40
|
+
# Convert all elements in the row to str for stable, lexicographical sorting
|
|
41
|
+
return diff if skip_sort_results else sorted(diff, key=lambda item: tuple(map(str, item[1])))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class HashDiffer:
|
|
46
|
+
"""Finds the diff between two SQL tables.
|
|
47
|
+
|
|
48
|
+
The algorithm uses hashing to quickly check if the tables are different, and then applies a
|
|
49
|
+
bisection search recursively to find the differences efficiently.
|
|
50
|
+
|
|
51
|
+
Works best for comparing tables that are mostly the same, with minor discrepancies.
|
|
52
|
+
|
|
53
|
+
Parameters:
|
|
54
|
+
bisection_factor (int): Into how many segments to bisect per iteration.
|
|
55
|
+
bisection_threshold (Number): When should we stop bisecting and compare locally (in row count).
|
|
56
|
+
threaded (bool): Enable/disable threaded diffing. Needed to take advantage of database threads.
|
|
57
|
+
max_threadpool_size (int): Maximum size of each threadpool. ``None`` means auto.
|
|
58
|
+
Only relevant when `threaded` is ``True``.
|
|
59
|
+
There may be many pools, so number of actual threads can be a lot higher.
|
|
60
|
+
skip_sort_results (bool): Skip sorting the hashdiff output by key for better performance.
|
|
61
|
+
Entries with the same key but different column values may not appear adjacent in the output.
|
|
62
|
+
duplicate_rows_support (bool): If ``True``, the algorithm will support duplicate rows in the tables.
|
|
63
|
+
allow_empty_tables (bool): If ``False``, diffing an empty table raises :class:`EmptyTable`.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
bisection_factor: int = DEFAULT_BISECTION_FACTOR
|
|
67
|
+
bisection_threshold: Number = DEFAULT_BISECTION_THRESHOLD # Accepts inf for tests
|
|
68
|
+
threaded: bool = True
|
|
69
|
+
max_threadpool_size: int | None = 1
|
|
70
|
+
skip_sort_results: bool = False
|
|
71
|
+
duplicate_rows_support: bool = True
|
|
72
|
+
allow_empty_tables: bool = False
|
|
73
|
+
|
|
74
|
+
stats: dict = field(default_factory=dict)
|
|
75
|
+
|
|
76
|
+
def __post_init__(self):
|
|
77
|
+
# Validate options
|
|
78
|
+
if self.bisection_factor >= self.bisection_threshold:
|
|
79
|
+
raise ValueError("Incorrect param values (bisection factor must be lower than threshold)")
|
|
80
|
+
if self.bisection_factor < 2:
|
|
81
|
+
raise ValueError("Must have at least two segments per iteration (i.e. bisection_factor >= 2)")
|
|
82
|
+
|
|
83
|
+
def diff_tables(
|
|
84
|
+
self,
|
|
85
|
+
table1: TableSegment,
|
|
86
|
+
table2: TableSegment,
|
|
87
|
+
*,
|
|
88
|
+
info_tree: InfoTree = None,
|
|
89
|
+
track_queries: bool = True,
|
|
90
|
+
) -> DiffResultWrapper:
|
|
91
|
+
"""Diff the given tables.
|
|
92
|
+
|
|
93
|
+
Parameters:
|
|
94
|
+
table1 (TableSegment): The "before" table to compare. Or: source table
|
|
95
|
+
table2 (TableSegment): The "after" table to compare. Or: target table
|
|
96
|
+
track_queries (bool): Whether to record query executions and checksums for this run. Default True.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
An iterator that yields pair-tuples, representing the diff. Items can be either:
|
|
100
|
+
('-', row) for items in table1 but not in table2.
|
|
101
|
+
('+', row) for items in table2 but not in table1.
|
|
102
|
+
Where `row` is a tuple of values, corresponding to the diffed columns.
|
|
103
|
+
"""
|
|
104
|
+
if table1.key_positions != table2.key_positions:
|
|
105
|
+
raise ValueError(
|
|
106
|
+
"key_columns must sit at the same positions on both sides "
|
|
107
|
+
f"({table1.key_columns} at {table1.key_positions} vs {table2.key_columns} at {table2.key_positions})"
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
if info_tree is None:
|
|
111
|
+
info_tree = InfoTree(SegmentInfo([table1, table2]))
|
|
112
|
+
|
|
113
|
+
query_tracker = table1.query_tracker or table2.query_tracker
|
|
114
|
+
if query_tracker is None and track_queries:
|
|
115
|
+
query_tracker = QueryTracker()
|
|
116
|
+
table1 = table1.replace(query_tracker=query_tracker)
|
|
117
|
+
table2 = table2.replace(query_tracker=query_tracker)
|
|
118
|
+
|
|
119
|
+
# Unbounded result buffer for streaming diff segments
|
|
120
|
+
stream_yielder = ThreadedYielder(self.max_threadpool_size, yield_buffer_size=0)
|
|
121
|
+
return DiffResultWrapper(
|
|
122
|
+
self._diff_tables_wrapper(table1, table2, info_tree, stream_yielder),
|
|
123
|
+
info_tree,
|
|
124
|
+
self.stats,
|
|
125
|
+
stream_yielder=stream_yielder,
|
|
126
|
+
query_tracker=query_tracker,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def _diff_tables_wrapper(
|
|
130
|
+
self, table1: TableSegment, table2: TableSegment, info_tree: InfoTree, stream_yielder: ThreadedYielder
|
|
131
|
+
) -> DiffResult:
|
|
132
|
+
try:
|
|
133
|
+
# Column types come from each segment's `columns` (validated when the segment is created)
|
|
134
|
+
table1, table2 = self._validate_and_adjust_columns(table1, table2)
|
|
135
|
+
|
|
136
|
+
yield from self._bisect_and_diff_tables(table1, table2, info_tree, stream_yielder)
|
|
137
|
+
finally:
|
|
138
|
+
info_tree.aggregate_info()
|
|
139
|
+
|
|
140
|
+
def _bisect_and_diff_tables(
|
|
141
|
+
self, table1: TableSegment, table2: TableSegment, info_tree: InfoTree, stream_yielder: ThreadedYielder
|
|
142
|
+
):
|
|
143
|
+
if len(table1.bisection_columns) != len(table2.bisection_columns):
|
|
144
|
+
raise ValueError("Tables should have an equivalent number of key columns!")
|
|
145
|
+
|
|
146
|
+
key_types1 = table1.key_types
|
|
147
|
+
key_types2 = table2.key_types
|
|
148
|
+
|
|
149
|
+
for kt in key_types1 + key_types2:
|
|
150
|
+
if not isinstance(kt, IKey):
|
|
151
|
+
raise NotImplementedError(f"Cannot use a column of type {kt} as a key")
|
|
152
|
+
|
|
153
|
+
for kt1, kt2 in strict_zip(key_types1, key_types2):
|
|
154
|
+
if kt1.python_type is not kt2.python_type:
|
|
155
|
+
raise TypeError(f"Incompatible key types: {kt1} and {kt2}")
|
|
156
|
+
|
|
157
|
+
# Query min/max values
|
|
158
|
+
key_ranges = self._threaded_call_as_completed("query_key_range", [table1, table2])
|
|
159
|
+
|
|
160
|
+
# Start with the first completed value, so we don't waste time waiting
|
|
161
|
+
try:
|
|
162
|
+
min_key1, max_key1 = self._parse_key_range_result(key_types1, next(key_ranges))
|
|
163
|
+
except EmptyTable:
|
|
164
|
+
if not self.allow_empty_tables:
|
|
165
|
+
raise
|
|
166
|
+
try:
|
|
167
|
+
min_key1, max_key1 = self._parse_key_range_result(key_types2, next(key_ranges))
|
|
168
|
+
except EmptyTable:
|
|
169
|
+
# Both tables are empty
|
|
170
|
+
info_tree.info.set_diff([])
|
|
171
|
+
info_tree.info.max_rows = 0
|
|
172
|
+
info_tree.info.rowcounts = {1: 0, 2: 0}
|
|
173
|
+
return []
|
|
174
|
+
|
|
175
|
+
bounded_table1, bounded_table2 = [t.new_key_bounds(min_key=min_key1, max_key=max_key1) for t in (table1, table2)]
|
|
176
|
+
|
|
177
|
+
logger.info(
|
|
178
|
+
f"Diffing segments at key-range: {min_key1}..{max_key1}. "
|
|
179
|
+
f"size: table1 <= {bounded_table1.approximate_size()}, table2 <= {bounded_table2.approximate_size()}"
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
# Bisect (split) the table into segments, and diff them recursively.
|
|
183
|
+
stream_yielder.submit(self._bisect_and_diff_segments, stream_yielder, bounded_table1, bounded_table2, info_tree)
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
min_key2, max_key2 = self._parse_key_range_result(key_types1, next(key_ranges))
|
|
187
|
+
except StopIteration: # First table is empty
|
|
188
|
+
return stream_yielder
|
|
189
|
+
except EmptyTable: # Second table is empty
|
|
190
|
+
if not self.allow_empty_tables:
|
|
191
|
+
raise
|
|
192
|
+
return stream_yielder
|
|
193
|
+
|
|
194
|
+
points = [sorted(p) for p in strict_zip(min_key1, min_key2, max_key1, max_key2)]
|
|
195
|
+
box_mesh = create_mesh_from_points(*points)
|
|
196
|
+
|
|
197
|
+
new_regions = [(p1, p2) for p1, p2 in box_mesh if p1 < p2 and not (p1 >= min_key1 and p2 <= max_key1)]
|
|
198
|
+
|
|
199
|
+
for p1, p2 in new_regions:
|
|
200
|
+
extra_tables = [t.new_key_bounds(min_key=p1, max_key=p2) for t in (table1, table2)]
|
|
201
|
+
stream_yielder.submit(self._bisect_and_diff_segments, stream_yielder, *extra_tables, info_tree)
|
|
202
|
+
|
|
203
|
+
return stream_yielder
|
|
204
|
+
|
|
205
|
+
def _parse_key_range_result(self, key_types, key_range) -> tuple[Vector, Vector]:
|
|
206
|
+
if isinstance(key_range, Exception):
|
|
207
|
+
raise key_range
|
|
208
|
+
|
|
209
|
+
min_key_values, max_key_values = key_range
|
|
210
|
+
|
|
211
|
+
# We add 1 because our ranges are exclusive of the end (like in Python)
|
|
212
|
+
try:
|
|
213
|
+
min_key = Vector(key_type.make_value(lower_val) for key_type, lower_val in strict_zip(key_types, min_key_values))
|
|
214
|
+
max_key = Vector(key_type.next_value(key_type.make_value(upper_val)) for key_type, upper_val in strict_zip(key_types, max_key_values))
|
|
215
|
+
except (TypeError, ValueError) as e:
|
|
216
|
+
raise type(e)(f"Cannot apply {key_types} to '{min_key_values}', '{max_key_values}'.") from e
|
|
217
|
+
|
|
218
|
+
return min_key, max_key
|
|
219
|
+
|
|
220
|
+
def _validate_and_adjust_columns(self, table1: TableSegment, table2: TableSegment) -> tuple[TableSegment, TableSegment]:
|
|
221
|
+
"""Check that paired columns are comparable and bring both sides to the same precision.
|
|
222
|
+
|
|
223
|
+
Returns copies of the segments with adjusted column types; the caller's segments are left unchanged.
|
|
224
|
+
"""
|
|
225
|
+
table1 = table1.replace(_schema=dict(table1._schema))
|
|
226
|
+
table2 = table2.replace(_schema=dict(table2._schema))
|
|
227
|
+
for c1, c2 in strict_zip(table1.relevant_columns, table2.relevant_columns):
|
|
228
|
+
# Unscaled numbers (no declared scale, precision=None) are compared as whole numbers
|
|
229
|
+
for segment, col_name in ((table1, c1), (table2, c2)):
|
|
230
|
+
ctype = segment._schema[col_name]
|
|
231
|
+
if isinstance(ctype, Decimal) and ctype.precision is None:
|
|
232
|
+
logger.warning(
|
|
233
|
+
f"[{segment.database.name}] Column '{'.'.join(segment.table_path)}.{col_name}' has no declared "
|
|
234
|
+
"scale; comparing it as a whole number, so fractional differences won't be detected. "
|
|
235
|
+
"Declare a scale in its datatype on both sides (e.g. NUMBER(12,2) / numeric(12,2)) to compare decimals."
|
|
236
|
+
)
|
|
237
|
+
segment._schema[col_name] = ctype.replace(precision=0)
|
|
238
|
+
|
|
239
|
+
# Check compatibility and reconcile to a mutually comparable form (e.g. minimal precision).
|
|
240
|
+
# The rules live on the ColType classes (compat_accepts / reconcile in diffdb/types.py).
|
|
241
|
+
col1 = table1._schema[c1]
|
|
242
|
+
col2 = table2._schema[c2]
|
|
243
|
+
if col1.compat_accepts is not None and not isinstance(col2, col1.compat_accepts):
|
|
244
|
+
raise TypeError(f"Incompatible types for column '{c1}': {col1} <-> {col2}")
|
|
245
|
+
|
|
246
|
+
prec1, prec2 = getattr(col1, "precision", None), getattr(col2, "precision", None)
|
|
247
|
+
if prec1 is not None and prec2 is not None and prec1 != prec2:
|
|
248
|
+
lowest = min(col1, col2, key=attrgetter("precision"))
|
|
249
|
+
logger.warning(f"Using reduced precision {lowest} for column '{c1}'. Types={col1}, {col2}")
|
|
250
|
+
|
|
251
|
+
table1._schema[c1], table2._schema[c2] = col1.reconcile(col2)
|
|
252
|
+
|
|
253
|
+
return table1, table2
|
|
254
|
+
|
|
255
|
+
def _diff_segments(
|
|
256
|
+
self,
|
|
257
|
+
stream_yielder: ThreadedYielder,
|
|
258
|
+
table1: TableSegment,
|
|
259
|
+
table2: TableSegment,
|
|
260
|
+
info_tree: InfoTree,
|
|
261
|
+
max_rows: int,
|
|
262
|
+
level=0,
|
|
263
|
+
segment_index=None,
|
|
264
|
+
segment_count=None,
|
|
265
|
+
):
|
|
266
|
+
logger.info(
|
|
267
|
+
". " * level + f"Diffing segment {segment_index}/{segment_count}, "
|
|
268
|
+
f"key-range: {table1.min_key}..{table1.max_key}, "
|
|
269
|
+
f"size <= {max_rows}"
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
(count1, checksum1), (count2, checksum2) = self._threaded_call("count_and_checksum", [table1, table2])
|
|
273
|
+
|
|
274
|
+
assert not info_tree.info.rowcounts
|
|
275
|
+
info_tree.info.rowcounts = {1: count1, 2: count2}
|
|
276
|
+
|
|
277
|
+
if count1 == 0 and count2 == 0:
|
|
278
|
+
logger.debug(
|
|
279
|
+
"Uneven distribution of keys detected in segment %s..%s (big gaps in the key column). "
|
|
280
|
+
"For better performance, we recommend to increase the bisection-threshold.",
|
|
281
|
+
table1.min_key,
|
|
282
|
+
table1.max_key,
|
|
283
|
+
)
|
|
284
|
+
assert checksum1 is None and checksum2 is None
|
|
285
|
+
info_tree.info.is_diff = False
|
|
286
|
+
return
|
|
287
|
+
|
|
288
|
+
if checksum1 == checksum2 and count1 == count2:
|
|
289
|
+
info_tree.info.is_diff = False
|
|
290
|
+
return
|
|
291
|
+
|
|
292
|
+
info_tree.info.is_diff = True
|
|
293
|
+
return self._bisect_and_diff_segments(stream_yielder, table1, table2, info_tree, level=level, max_rows=max(count1, count2))
|
|
294
|
+
|
|
295
|
+
def _bisect_and_diff_segments(
|
|
296
|
+
self,
|
|
297
|
+
stream_yielder: ThreadedYielder,
|
|
298
|
+
table1: TableSegment,
|
|
299
|
+
table2: TableSegment,
|
|
300
|
+
info_tree: InfoTree,
|
|
301
|
+
level=0,
|
|
302
|
+
max_rows=None,
|
|
303
|
+
):
|
|
304
|
+
assert table1.is_bounded and table2.is_bounded
|
|
305
|
+
|
|
306
|
+
max_space_size = max(table1.approximate_size(), table2.approximate_size())
|
|
307
|
+
cant_split = max_space_size < self.bisection_factor * 2
|
|
308
|
+
if max_rows is None:
|
|
309
|
+
# Row count unknown: the root key range, or an extra range between the two tables' ranges.
|
|
310
|
+
# Bisection columns need not be unique, so the number of key values says nothing about the
|
|
311
|
+
# number of rows. A range that would be downloaded whole is checksummed and counted first:
|
|
312
|
+
# equal ranges are skipped, the others continue with their real row count.
|
|
313
|
+
if max_space_size < self.bisection_threshold or cant_split:
|
|
314
|
+
info_node = info_tree.add_node(table1, table2, max_rows=max_space_size)
|
|
315
|
+
return self._diff_segments(stream_yielder, table1, table2, info_node, max_rows=math.inf, level=level + 1)
|
|
316
|
+
max_rows = max_space_size
|
|
317
|
+
info_tree.info.max_rows = max_rows
|
|
318
|
+
|
|
319
|
+
# If count is below the threshold, just download and compare the columns locally
|
|
320
|
+
# This saves time, as bisection speed is limited by ping and query performance.
|
|
321
|
+
if max_rows < self.bisection_threshold or cant_split:
|
|
322
|
+
if cant_split and max_rows >= self.bisection_threshold:
|
|
323
|
+
logger.warning(
|
|
324
|
+
f"[{'.'.join(table1.table_path)}] Key range {table1.min_key}..{table1.max_key} holds up to "
|
|
325
|
+
f"{max_rows} rows but can't be split further; downloading them all. "
|
|
326
|
+
"Choose more selective bisection_columns to avoid this."
|
|
327
|
+
)
|
|
328
|
+
rows1, rows2 = self._threaded_call("get_values", [table1, table2])
|
|
329
|
+
diff = list(compare_row_sets(rows1, rows2, self.skip_sort_results, self.duplicate_rows_support))
|
|
330
|
+
|
|
331
|
+
info_tree.info.set_diff(diff)
|
|
332
|
+
info_tree.info.rowcounts = {1: len(rows1), 2: len(rows2)}
|
|
333
|
+
|
|
334
|
+
logger.info(". " * level + f"Diff found {len(diff)} different rows.")
|
|
335
|
+
self.stats["rows_downloaded"] = self.stats.get("rows_downloaded", 0) + max(len(rows1), len(rows2))
|
|
336
|
+
return diff
|
|
337
|
+
|
|
338
|
+
return self._split_and_submit(stream_yielder, table1, table2, info_tree, level, max_rows)
|
|
339
|
+
|
|
340
|
+
def _split_and_submit(
|
|
341
|
+
self,
|
|
342
|
+
stream_yielder: ThreadedYielder,
|
|
343
|
+
table1: TableSegment,
|
|
344
|
+
table2: TableSegment,
|
|
345
|
+
info_tree: InfoTree,
|
|
346
|
+
level: int,
|
|
347
|
+
max_rows: int,
|
|
348
|
+
):
|
|
349
|
+
"""Split both segments at the same checkpoints and submit each pair to _diff_segments."""
|
|
350
|
+
# Choose evenly spaced checkpoints (according to min_key and max_key)
|
|
351
|
+
biggest_table = max(table1, table2, key=methodcaller("approximate_size"))
|
|
352
|
+
checkpoints = biggest_table.choose_checkpoints(self.bisection_factor - 1)
|
|
353
|
+
|
|
354
|
+
# Create new instances of TableSegment between each checkpoint
|
|
355
|
+
segmented1 = table1.segment_by_checkpoints(checkpoints)
|
|
356
|
+
segmented2 = table2.segment_by_checkpoints(checkpoints)
|
|
357
|
+
|
|
358
|
+
# Recursively compare each pair of corresponding segments between table1 and table2
|
|
359
|
+
for i, (seg1, seg2) in enumerate(strict_zip(segmented1, segmented2)):
|
|
360
|
+
info_node = info_tree.add_node(seg1, seg2, max_rows=max_rows)
|
|
361
|
+
stream_yielder.submit(
|
|
362
|
+
self._diff_segments, stream_yielder, seg1, seg2, info_node, max_rows, level + 1, i + 1, len(segmented1), priority=level
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
# --- Threading helpers (threaded=False runs everything in the calling thread) ---
|
|
366
|
+
|
|
367
|
+
def _thread_map(self, func, iterable):
|
|
368
|
+
if not self.threaded:
|
|
369
|
+
return map(func, iterable)
|
|
370
|
+
|
|
371
|
+
with ThreadPoolExecutor(max_workers=self.max_threadpool_size) as task_pool:
|
|
372
|
+
return task_pool.map(func, iterable)
|
|
373
|
+
|
|
374
|
+
def _threaded_call(self, func, iterable, **kw):
|
|
375
|
+
"Calls a method for each object in iterable."
|
|
376
|
+
return list(self._thread_map(methodcaller(func, **kw), iterable))
|
|
377
|
+
|
|
378
|
+
def _thread_as_completed(self, func, iterable):
|
|
379
|
+
if not self.threaded:
|
|
380
|
+
yield from map(func, iterable)
|
|
381
|
+
return
|
|
382
|
+
|
|
383
|
+
with ThreadPoolExecutor(max_workers=self.max_threadpool_size) as task_pool:
|
|
384
|
+
futures = [task_pool.submit(func, item) for item in iterable]
|
|
385
|
+
for future in as_completed(futures):
|
|
386
|
+
yield future.result()
|
|
387
|
+
|
|
388
|
+
def _threaded_call_as_completed(self, func, iterable):
|
|
389
|
+
"Calls a method for each object in iterable. Returned in order of completion."
|
|
390
|
+
return self._thread_as_completed(methodcaller(func), iterable)
|