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/core/segment.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""Table segment definitions and boundary management for database tables."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import time
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
|
|
7
|
+
from ..databases import Database, DbKey, DbPath
|
|
8
|
+
from ..geometry import (
|
|
9
|
+
Vector,
|
|
10
|
+
create_mesh_from_points,
|
|
11
|
+
int_product,
|
|
12
|
+
split_compound_key_space,
|
|
13
|
+
)
|
|
14
|
+
from ..telemetry import QueryTracker
|
|
15
|
+
from ..types import (
|
|
16
|
+
ColType,
|
|
17
|
+
String_UUID,
|
|
18
|
+
String_VaryingAlphanum,
|
|
19
|
+
Text,
|
|
20
|
+
UnknownColType,
|
|
21
|
+
)
|
|
22
|
+
from ..utils import dataclass, field, strict_zip
|
|
23
|
+
from . import sql
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
RECOMMENDED_CHECKSUM_DURATION = 20
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class EmptyTable(ValueError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Keys allowed in each `columns` entry
|
|
35
|
+
_COLUMN_KEYS = frozenset({"datatype", "transform_rule"})
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class TableSegment:
|
|
40
|
+
"""Signifies a segment of rows (and selected columns) within a table.
|
|
41
|
+
|
|
42
|
+
The caller decides everything about the table: which columns to compare, how to read each one
|
|
43
|
+
and its type. The core never reads the database catalog.
|
|
44
|
+
|
|
45
|
+
Parameters:
|
|
46
|
+
database (Database): Database instance. See :meth:`connect`
|
|
47
|
+
table_path (:data:`DbPath`): Path to table in form of a tuple. e.g. `('my_dataset', 'table_name')`
|
|
48
|
+
bisection_columns (Tuple[str]): Columns used to split the table into key ranges. They need not
|
|
49
|
+
be unique, but should be selective: a single key value holding more rows than the bisection
|
|
50
|
+
threshold can't be split further and is downloaded as a whole. Each must be a key of `columns`.
|
|
51
|
+
columns (dict): Every column to compare, in order, including the bisection columns:
|
|
52
|
+
``{name: {"datatype": "NUMBER(12,2)", "transform_rule": "<sql>"}}``
|
|
53
|
+
|
|
54
|
+
* ``datatype`` (required): native type of the value that is hashed, e.g. ``NUMBER(10,0)``,
|
|
55
|
+
``VARCHAR2(100)``, ``TIMESTAMP(3)``, ``numeric(12,2)``. When a transform_rule changes the
|
|
56
|
+
type, give the result's type (``LENGTH("NOTE")`` -> ``NUMBER(10,0)``). Must be a basic type
|
|
57
|
+
mapped in the dialect's ``type_classes``; LOB/binary types are rejected.
|
|
58
|
+
* ``transform_rule`` (optional): SQL expression used instead of the column, e.g.
|
|
59
|
+
``TRUNC("HIRE_DT")``. It is wrapped in parentheses.
|
|
60
|
+
|
|
61
|
+
Source and target are paired by position: build both dicts in the same order.
|
|
62
|
+
key_columns (Tuple[str], optional): Columns that identify a logical row when summarizing results:
|
|
63
|
+
a '-' and a '+' row with the same key values are reported as one changed row with column-level
|
|
64
|
+
differences (see :meth:`DiffResultWrapper.summarize`). Defaults to `bisection_columns`. Need not
|
|
65
|
+
be unique (repeated keys are reported as a duplicate-key group). Each must be a key of `columns`.
|
|
66
|
+
Including every bisection column keeps the pairing exact when the summary stops at a limit.
|
|
67
|
+
min_key (:data:`Vector`, optional): Lowest key value, used to restrict the segment
|
|
68
|
+
max_key (:data:`Vector`, optional): Highest key value, used to restrict the segment
|
|
69
|
+
where (str, optional): An additional 'where' expression to restrict the search space,
|
|
70
|
+
e.g. a CDC time window on an update column.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
# Location of table
|
|
74
|
+
database: Database
|
|
75
|
+
table_path: DbPath
|
|
76
|
+
|
|
77
|
+
# Columns
|
|
78
|
+
bisection_columns: tuple[str, ...]
|
|
79
|
+
columns: dict[str, dict[str, str]] = field(default_factory=dict)
|
|
80
|
+
key_columns: tuple[str, ...] = ()
|
|
81
|
+
|
|
82
|
+
# Restrict the segment
|
|
83
|
+
min_key: Vector = None
|
|
84
|
+
max_key: Vector = None
|
|
85
|
+
where: str = None
|
|
86
|
+
|
|
87
|
+
query_tracker: QueryTracker | None = None
|
|
88
|
+
# Internal: column name -> ColType, built from `columns` by __post_init__. Not for callers.
|
|
89
|
+
_schema: dict[str, ColType] | None = None
|
|
90
|
+
|
|
91
|
+
def __post_init__(self):
|
|
92
|
+
if self.min_key is not None and self.max_key is not None and self.min_key >= self.max_key:
|
|
93
|
+
raise ValueError(f"Error: min_key expected to be smaller than max_key! ({self.min_key} >= {self.max_key})")
|
|
94
|
+
|
|
95
|
+
self.bisection_columns = tuple(self.bisection_columns)
|
|
96
|
+
self.key_columns = tuple(self.key_columns) or self.bisection_columns
|
|
97
|
+
if self._schema is None:
|
|
98
|
+
self._schema = self._build_schema()
|
|
99
|
+
|
|
100
|
+
def _build_schema(self) -> dict[str, ColType]:
|
|
101
|
+
"""Validate `columns` / `bisection_columns` and turn each datatype into a ColType."""
|
|
102
|
+
table_name = ".".join(self.table_path)
|
|
103
|
+
if not isinstance(self.columns, dict) or not self.columns:
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"Invalid TableSegment for {table_name}: `columns` must be a non-empty dict like "
|
|
106
|
+
"{'ID': {'datatype': 'NUMBER(10,0)'}}"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
errors = []
|
|
110
|
+
if not self.bisection_columns:
|
|
111
|
+
errors.append("`bisection_columns` is empty")
|
|
112
|
+
missing = [c for c in self.bisection_columns if c not in self.columns]
|
|
113
|
+
if missing:
|
|
114
|
+
errors.append(f"bisection column(s) {missing} are not in `columns`")
|
|
115
|
+
missing_keys = [c for c in self.key_columns if c not in self.columns]
|
|
116
|
+
if missing_keys:
|
|
117
|
+
errors.append(f"key column(s) {missing_keys} are not in `columns`")
|
|
118
|
+
|
|
119
|
+
dialect = self.database.dialect
|
|
120
|
+
schema = {}
|
|
121
|
+
for name, spec in self.columns.items():
|
|
122
|
+
datatype = spec.get("datatype") if isinstance(spec, dict) else None
|
|
123
|
+
if not isinstance(datatype, str) or not datatype.strip():
|
|
124
|
+
errors.append(f"{name}: needs a 'datatype' string, e.g. {{'datatype': 'NUMBER(10,0)'}}")
|
|
125
|
+
continue
|
|
126
|
+
unknown = set(spec) - _COLUMN_KEYS
|
|
127
|
+
if unknown:
|
|
128
|
+
errors.append(f"{name}: unknown key(s) {sorted(unknown)}; allowed: {sorted(_COLUMN_KEYS)}")
|
|
129
|
+
rule = spec.get("transform_rule")
|
|
130
|
+
if rule is not None and not (isinstance(rule, str) and rule.strip()):
|
|
131
|
+
errors.append(f"{name}: 'transform_rule' must be a non-empty SQL string")
|
|
132
|
+
coltype = dialect.parse_type(datatype)
|
|
133
|
+
if isinstance(coltype, Text):
|
|
134
|
+
# Strings are a basic type: hashed as-is (same normalization) and usable as bisection keys
|
|
135
|
+
coltype = String_VaryingAlphanum()
|
|
136
|
+
if isinstance(coltype, UnknownColType):
|
|
137
|
+
errors.append(
|
|
138
|
+
f"{name}: unsupported datatype {datatype!r} for {dialect.name}; reduce it to a basic type with "
|
|
139
|
+
"a 'transform_rule' and declare the result's datatype (e.g. LENGTH(...) as NUMBER(10,0))"
|
|
140
|
+
)
|
|
141
|
+
schema[name] = coltype
|
|
142
|
+
|
|
143
|
+
if errors:
|
|
144
|
+
raise ValueError(f"Invalid TableSegment for {table_name}:\n - " + "\n - ".join(errors))
|
|
145
|
+
return schema
|
|
146
|
+
|
|
147
|
+
def _cast_col_value(self, col, value):
|
|
148
|
+
"""Cast the value to the right type, based on the type of the column.
|
|
149
|
+
|
|
150
|
+
Currently only used to support native vs string UUID values.
|
|
151
|
+
"""
|
|
152
|
+
assert self._schema
|
|
153
|
+
t = self._schema[col]
|
|
154
|
+
if isinstance(t, String_UUID):
|
|
155
|
+
return str(value)
|
|
156
|
+
return value
|
|
157
|
+
|
|
158
|
+
def _column_sql(self, col_name: str) -> str:
|
|
159
|
+
"""SQL for a column: its transform_rule (parenthesized) if it has one, else the quoted column."""
|
|
160
|
+
rule = self.columns[col_name].get("transform_rule")
|
|
161
|
+
return f"({rule})" if rule else self.database.dialect.quote(col_name)
|
|
162
|
+
|
|
163
|
+
def _filters(self) -> list[str]:
|
|
164
|
+
"""WHERE conditions: the key range (lower bounds, then upper bounds), then the caller's `where`."""
|
|
165
|
+
dialect = self.database.dialect
|
|
166
|
+
filters = []
|
|
167
|
+
if self.min_key is not None:
|
|
168
|
+
for mn, k in strict_zip(self.min_key, self.bisection_columns):
|
|
169
|
+
filters.append(f"({self._column_sql(k)} >= {sql.literal(dialect, self._cast_col_value(k, mn))})")
|
|
170
|
+
if self.max_key is not None:
|
|
171
|
+
for k, mx in strict_zip(self.bisection_columns, self.max_key):
|
|
172
|
+
filters.append(f"({self._column_sql(k)} < {sql.literal(dialect, self._cast_col_value(k, mx))})")
|
|
173
|
+
if self.where:
|
|
174
|
+
filters.append(f"({self.where})")
|
|
175
|
+
return filters
|
|
176
|
+
|
|
177
|
+
def _select(self, columns: list[str]) -> str:
|
|
178
|
+
return sql.select(self.database.dialect, self.table_path, columns, self._filters())
|
|
179
|
+
|
|
180
|
+
def _record_query(self, method: str, query: str, row_count, checksum, duration: float, unbounded=None):
|
|
181
|
+
"""Record an executed query in the segment's QueryTracker (if any). `unbounded`: key value logged when
|
|
182
|
+
the segment has no key bound."""
|
|
183
|
+
if self.query_tracker is None:
|
|
184
|
+
return
|
|
185
|
+
self.query_tracker.record(
|
|
186
|
+
{
|
|
187
|
+
"method": method,
|
|
188
|
+
"database": self.database.name.upper(),
|
|
189
|
+
"table_name": ".".join(self.table_path),
|
|
190
|
+
"min_key": list(self.min_key) if self.min_key is not None else unbounded,
|
|
191
|
+
"max_key": list(self.max_key) if self.max_key is not None else unbounded,
|
|
192
|
+
"query": query,
|
|
193
|
+
"row_count": int(row_count) if row_count else 0,
|
|
194
|
+
"checksum": str(checksum) if checksum else None,
|
|
195
|
+
"duration": duration,
|
|
196
|
+
}
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def get_values(self) -> list:
|
|
200
|
+
"Download all the relevant values of the segment from the database"
|
|
201
|
+
q = self._select(self.build_column_expressions)
|
|
202
|
+
start = time.monotonic()
|
|
203
|
+
rows = self.database.query(q, list[tuple])
|
|
204
|
+
self._record_query("get_values", q, len(rows), None, time.monotonic() - start, unbounded=["<below-threshold>"])
|
|
205
|
+
return rows
|
|
206
|
+
|
|
207
|
+
def count(self) -> int:
|
|
208
|
+
"""Count how many rows are in the segment, in one pass."""
|
|
209
|
+
q = self._select(["count(*)"])
|
|
210
|
+
start = time.monotonic()
|
|
211
|
+
res = self.database.query(q, int)
|
|
212
|
+
self._record_query("count", q, res, None, time.monotonic() - start)
|
|
213
|
+
return res
|
|
214
|
+
|
|
215
|
+
def count_and_checksum(self) -> tuple[int, int]:
|
|
216
|
+
"""Count and checksum the rows in the segment, in one pass."""
|
|
217
|
+
q = self._select(["count(*)", sql.checksum(self.database.dialect, self.build_column_expressions)])
|
|
218
|
+
start = time.monotonic()
|
|
219
|
+
count, checksum = self.database.query(q, tuple)
|
|
220
|
+
duration = time.monotonic() - start
|
|
221
|
+
self._record_query("count_and_checksum", q, count, checksum, duration)
|
|
222
|
+
|
|
223
|
+
if duration > RECOMMENDED_CHECKSUM_DURATION:
|
|
224
|
+
logger.warning(
|
|
225
|
+
"Checksum is taking longer than expected (%.2f). "
|
|
226
|
+
"We recommend increasing bisection_factor or reducing the number of threads.",
|
|
227
|
+
duration,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
if count:
|
|
231
|
+
assert checksum, (count, checksum)
|
|
232
|
+
return count or 0, int(checksum) if count else None
|
|
233
|
+
|
|
234
|
+
def query_key_range(self) -> tuple[tuple, tuple]:
|
|
235
|
+
"""Query database for minimum and maximum key. This is used for setting the initial bounds."""
|
|
236
|
+
# Normalizes the result (needed for UUIDs) after the min/max computation
|
|
237
|
+
dialect = self.database.dialect
|
|
238
|
+
q = self._select([
|
|
239
|
+
sql.key_bound(dialect, func, self._column_sql(k), self._schema[k])
|
|
240
|
+
for k in self.bisection_columns
|
|
241
|
+
for func in ("min", "max")
|
|
242
|
+
])
|
|
243
|
+
result = tuple(self.database.query(q, tuple))
|
|
244
|
+
|
|
245
|
+
if any(i is None for i in result):
|
|
246
|
+
# We return EmptyTable instead of raising it, so that we can consume
|
|
247
|
+
# the key_ranges as an iterator.
|
|
248
|
+
# _parse_key_range_result() will raise the error we return.
|
|
249
|
+
return EmptyTable(f"Table {self.table_path} appears to be empty.", self)
|
|
250
|
+
|
|
251
|
+
# Min/max keys are interleaved
|
|
252
|
+
min_key, max_key = result[::2], result[1::2]
|
|
253
|
+
assert len(min_key) == len(max_key)
|
|
254
|
+
|
|
255
|
+
return min_key, max_key
|
|
256
|
+
|
|
257
|
+
@property
|
|
258
|
+
def relevant_columns(self) -> list[str]:
|
|
259
|
+
"""Bisection columns first, then the other `columns` in dict order."""
|
|
260
|
+
return list(self.bisection_columns) + [c for c in self.columns if c not in self.bisection_columns]
|
|
261
|
+
|
|
262
|
+
@property
|
|
263
|
+
def build_column_expressions(self) -> list[str]:
|
|
264
|
+
"""Normalized SQL expressions for all relevant columns (what is compared and hashed)."""
|
|
265
|
+
dialect = self.database.dialect
|
|
266
|
+
return [sql.normalized(dialect, self._column_sql(c), self._schema[c]) for c in self.relevant_columns]
|
|
267
|
+
|
|
268
|
+
def choose_checkpoints(self, count: int) -> list[list[DbKey]]:
|
|
269
|
+
"Suggests a bunch of evenly-spaced checkpoints to split by, including start, end."
|
|
270
|
+
|
|
271
|
+
assert self.is_bounded
|
|
272
|
+
|
|
273
|
+
# Take Nth root of count, to approximate the appropriate box size
|
|
274
|
+
count = int(count ** (1 / len(self.bisection_columns))) or 1
|
|
275
|
+
|
|
276
|
+
return split_compound_key_space(self.min_key, self.max_key, count)
|
|
277
|
+
|
|
278
|
+
def segment_by_checkpoints(self, checkpoints: list[list[DbKey]]) -> list["TableSegment"]:
|
|
279
|
+
"Split the current TableSegment to a bunch of smaller ones, separated by the given checkpoints"
|
|
280
|
+
|
|
281
|
+
return [self.new_key_bounds(min_key=s, max_key=e) for s, e in create_mesh_from_points(*checkpoints)]
|
|
282
|
+
|
|
283
|
+
def new(self, **kwargs) -> "TableSegment":
|
|
284
|
+
"""Creates a copy of the instance using 'replace()'"""
|
|
285
|
+
if "bisection_columns" in kwargs and "key_columns" not in kwargs and self.key_columns == self.bisection_columns:
|
|
286
|
+
kwargs["key_columns"] = () # the key defaulted to the bisection columns: follow the new ones
|
|
287
|
+
if {"columns", "bisection_columns", "key_columns", "database"} & kwargs.keys() and "_schema" not in kwargs:
|
|
288
|
+
kwargs["_schema"] = None # rebuild (and re-validate) the schema from the new definitions
|
|
289
|
+
return self.replace(**kwargs)
|
|
290
|
+
|
|
291
|
+
def new_key_bounds(self, min_key: Vector, max_key: Vector) -> "TableSegment":
|
|
292
|
+
if self.min_key is not None:
|
|
293
|
+
assert self.min_key <= min_key, (self.min_key, min_key)
|
|
294
|
+
assert self.min_key < max_key
|
|
295
|
+
|
|
296
|
+
if self.max_key is not None:
|
|
297
|
+
assert min_key < self.max_key
|
|
298
|
+
assert max_key <= self.max_key
|
|
299
|
+
|
|
300
|
+
return self.replace(min_key=min_key, max_key=max_key)
|
|
301
|
+
|
|
302
|
+
@property
|
|
303
|
+
def is_bounded(self):
|
|
304
|
+
return self.min_key is not None and self.max_key is not None
|
|
305
|
+
|
|
306
|
+
def approximate_size(self):
|
|
307
|
+
if not self.is_bounded:
|
|
308
|
+
raise RuntimeError("Cannot approximate the size of an unbounded segment. Must have min_key and max_key.")
|
|
309
|
+
diff = self.max_key - self.min_key
|
|
310
|
+
|
|
311
|
+
numeric_diff = [d.total_seconds() if isinstance(d, timedelta) else d for d in diff]
|
|
312
|
+
assert all(d > 0 for d in numeric_diff)
|
|
313
|
+
return int(int_product(numeric_diff))
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def key_positions(self) -> list[int]:
|
|
317
|
+
"""Indexes of the key columns within a row returned by get_values() (i.e. `relevant_columns`)."""
|
|
318
|
+
relevant = self.relevant_columns
|
|
319
|
+
return [relevant.index(c) for c in self.key_columns]
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def key_types(self):
|
|
323
|
+
return [self._schema[i] for i in self.bisection_columns]
|
diffdb/core/sql.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""All SQL the diff sends, built as plain strings from the dialect.
|
|
2
|
+
|
|
3
|
+
There are only four queries per segment (see TableSegment):
|
|
4
|
+
|
|
5
|
+
count SELECT count(*) FROM t WHERE <filters>
|
|
6
|
+
count_and_checksum SELECT count(*), sum(<hash of the row string>) FROM t WHERE <filters>
|
|
7
|
+
query_key_range SELECT min(k1), max(k1), ... FROM t WHERE <filters>
|
|
8
|
+
get_values SELECT <normalized columns> FROM t WHERE <filters>
|
|
9
|
+
|
|
10
|
+
Everything database-specific (quoting, NULL handling, concatenation, hashing, value formatting) comes from the
|
|
11
|
+
YAML dialect. The output is pinned byte-for-byte for every dialect by tests/golden/query_sql.json.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from datetime import date, datetime
|
|
15
|
+
from decimal import Decimal
|
|
16
|
+
from uuid import UUID
|
|
17
|
+
|
|
18
|
+
from ..databases.yaml_dialect import YamlDialect
|
|
19
|
+
from ..types import ColType, Native_UUID
|
|
20
|
+
from ..utils import ArithString
|
|
21
|
+
|
|
22
|
+
NULL_MARKER = "'<null>'"
|
|
23
|
+
ROW_SEPARATOR = "'|'"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def table_sql(dialect: YamlDialect, path: tuple[str, ...]) -> str:
|
|
27
|
+
return ".".join(map(dialect.quote, path))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def literal(dialect: YamlDialect, value) -> str:
|
|
31
|
+
"""A key-bound value as a SQL literal."""
|
|
32
|
+
if value is None:
|
|
33
|
+
return "NULL"
|
|
34
|
+
if isinstance(value, UUID): # incl. ArithUUID
|
|
35
|
+
return dialect.uuid_value(value)
|
|
36
|
+
if isinstance(value, ArithString):
|
|
37
|
+
return f"'{value}'"
|
|
38
|
+
if isinstance(value, str):
|
|
39
|
+
escaped = value.replace("'", "''")
|
|
40
|
+
return f"'{escaped}'"
|
|
41
|
+
if isinstance(value, (int, float, Decimal)):
|
|
42
|
+
return str(value)
|
|
43
|
+
if isinstance(value, datetime):
|
|
44
|
+
return dialect.timestamp_value(value)
|
|
45
|
+
if isinstance(value, date):
|
|
46
|
+
return literal(dialect, str(value))
|
|
47
|
+
raise TypeError(f"Cannot render a SQL literal for {type(value).__name__}: {value!r}")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def normalized(dialect: YamlDialect, column_sql: str, coltype: ColType) -> str:
|
|
51
|
+
"""The column rendered as its canonical string (what gets compared and hashed)."""
|
|
52
|
+
return dialect.normalize_value_by_type(column_sql, coltype)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def key_bound(dialect: YamlDialect, func: str, column_sql: str, coltype: ColType) -> str:
|
|
56
|
+
"""min()/max() of a key column, normalized. UUIDs are normalized first (min/max on native UUIDs fails in PostgreSQL)."""
|
|
57
|
+
if isinstance(coltype, Native_UUID):
|
|
58
|
+
return f"{func}({normalized(dialect, column_sql, coltype)})"
|
|
59
|
+
return normalized(dialect, f"{func}({column_sql})", coltype)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def checksum(dialect: YamlDialect, normalized_columns: list[str]) -> str:
|
|
63
|
+
"""sum() of the hash of each row: the normalized columns, NULLs as '<null>', joined with '|'."""
|
|
64
|
+
if len(normalized_columns) > 1:
|
|
65
|
+
items = []
|
|
66
|
+
for i, expr in enumerate(normalized_columns):
|
|
67
|
+
if i:
|
|
68
|
+
items.append(ROW_SEPARATOR)
|
|
69
|
+
# On some databases (e.g. MySQL) concat('a', NULL) is NULL
|
|
70
|
+
items.append(expr if expr.lower().startswith(("coalesce(", "nvl(")) else dialect.coalesce(expr, NULL_MARKER))
|
|
71
|
+
row = dialect.concat(items)
|
|
72
|
+
else:
|
|
73
|
+
(row,) = normalized_columns # a single (key) column: never NULL
|
|
74
|
+
return f"sum({dialect.md5_as_int(row)})"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def select(dialect: YamlDialect, path: tuple[str, ...], columns: list[str], filters: list[str]) -> str:
|
|
78
|
+
sql = f"SELECT {', '.join(columns)} FROM {table_sql(dialect, path)}"
|
|
79
|
+
if filters:
|
|
80
|
+
sql += " WHERE " + " AND ".join(filters)
|
|
81
|
+
return sql
|
diffdb/core/summary.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Summarize a diff stream per key.
|
|
2
|
+
|
|
3
|
+
The differ yields ('-', row) for rows only in table 1 (source) and ('+', row) for rows only in table 2
|
|
4
|
+
(target). This module pairs them by the key columns: a key with one '-' and one '+' row is one changed
|
|
5
|
+
row with column-level differences; keys seen on one side only are source/target-only rows; keys with
|
|
6
|
+
several rows on a side form a duplicate-key group.
|
|
7
|
+
|
|
8
|
+
Pairing is done over the whole stream (a key's two versions can come from different segments when the
|
|
9
|
+
key doesn't include every bisection column), in one pass, keeping only differing rows in memory.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from collections import Counter
|
|
13
|
+
from collections.abc import Iterable, Sequence
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from ..utils import dataclass, field
|
|
17
|
+
|
|
18
|
+
CHANGED = "changed"
|
|
19
|
+
SOURCE_ONLY = "source_only"
|
|
20
|
+
TARGET_ONLY = "target_only"
|
|
21
|
+
DUPLICATE_KEY = "duplicate_key"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class ColumnDiff:
|
|
26
|
+
"""One differing column of a changed row."""
|
|
27
|
+
|
|
28
|
+
source_column: str
|
|
29
|
+
target_column: str
|
|
30
|
+
source_value: Any
|
|
31
|
+
target_value: Any
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class KeyDiff:
|
|
36
|
+
"""All differences found for one key value."""
|
|
37
|
+
|
|
38
|
+
key: tuple # key values, in key_columns order
|
|
39
|
+
kind: str # CHANGED | SOURCE_ONLY | TARGET_ONLY | DUPLICATE_KEY
|
|
40
|
+
column_diffs: list[ColumnDiff] = field(default_factory=list) # CHANGED only
|
|
41
|
+
source_rows: list[tuple] = field(default_factory=list) # unmatched source rows (not for CHANGED)
|
|
42
|
+
target_rows: list[tuple] = field(default_factory=list) # unmatched target rows (not for CHANGED)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class DiffSummary:
|
|
47
|
+
"""Per-key result of a diff, with row counts.
|
|
48
|
+
|
|
49
|
+
`changed` counts changed rows; `source_only` / `target_only` count unmatched rows (one-sided keys and
|
|
50
|
+
the leftovers of duplicate-key groups). `source_scanned` / `target_scanned` are the rows the diff
|
|
51
|
+
covered on each side. When `limit_reached` is true the diff was stopped early, so every count is
|
|
52
|
+
partial, and a key whose other version hadn't arrived yet may be reported as one-sided (this can't
|
|
53
|
+
happen when the key columns include every bisection column).
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
source_key_columns: tuple[str, ...]
|
|
57
|
+
target_key_columns: tuple[str, ...]
|
|
58
|
+
key_diffs: list[KeyDiff] = field(default_factory=list)
|
|
59
|
+
changed: int = 0
|
|
60
|
+
source_only: int = 0
|
|
61
|
+
target_only: int = 0
|
|
62
|
+
raw_rows: int = 0 # '-'/'+' rows read from the diff stream
|
|
63
|
+
duplicate_keys: bool = False # some key had several unmatched rows on one side
|
|
64
|
+
limit_reached: bool = False
|
|
65
|
+
source_scanned: int | None = None
|
|
66
|
+
target_scanned: int | None = None
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def total_diff(self) -> int:
|
|
70
|
+
return self.changed + self.source_only + self.target_only
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def unchanged(self) -> int | None:
|
|
74
|
+
if self.source_scanned is None:
|
|
75
|
+
return None
|
|
76
|
+
return self.source_scanned - self.source_only - self.changed
|
|
77
|
+
|
|
78
|
+
def as_dict(self) -> dict:
|
|
79
|
+
"""JSON-ready dict (values are as downloaded, i.e. the normalized strings)."""
|
|
80
|
+
return {
|
|
81
|
+
"source_key_columns": list(self.source_key_columns),
|
|
82
|
+
"target_key_columns": list(self.target_key_columns),
|
|
83
|
+
"counts": {
|
|
84
|
+
"changed": self.changed,
|
|
85
|
+
"source_only": self.source_only,
|
|
86
|
+
"target_only": self.target_only,
|
|
87
|
+
"total_diff": self.total_diff,
|
|
88
|
+
"unchanged": self.unchanged,
|
|
89
|
+
"source_scanned": self.source_scanned,
|
|
90
|
+
"target_scanned": self.target_scanned,
|
|
91
|
+
"raw_rows": self.raw_rows,
|
|
92
|
+
},
|
|
93
|
+
"duplicate_keys": self.duplicate_keys,
|
|
94
|
+
"limit_reached": self.limit_reached,
|
|
95
|
+
"key_diffs": [
|
|
96
|
+
{
|
|
97
|
+
"key": list(kd.key),
|
|
98
|
+
"kind": kd.kind,
|
|
99
|
+
"column_diffs": [cd.asdict() for cd in kd.column_diffs],
|
|
100
|
+
"source_rows": [list(r) for r in kd.source_rows],
|
|
101
|
+
"target_rows": [list(r) for r in kd.target_rows],
|
|
102
|
+
}
|
|
103
|
+
for kd in self.key_diffs
|
|
104
|
+
],
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _sort_key(values: Sequence) -> tuple:
|
|
109
|
+
return tuple(map(str, values))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def summarize_diff(
|
|
113
|
+
diff: Iterable[tuple[str, tuple]],
|
|
114
|
+
key_positions: Sequence[int],
|
|
115
|
+
source_columns: Sequence[str],
|
|
116
|
+
target_columns: Sequence[str],
|
|
117
|
+
limit: int | None = None,
|
|
118
|
+
) -> DiffSummary:
|
|
119
|
+
"""Pair '-'/'+' rows by key and summarize them.
|
|
120
|
+
|
|
121
|
+
Parameters:
|
|
122
|
+
diff: ('-' | '+', row) tuples, rows laid out as `source_columns` / `target_columns` (paired by position).
|
|
123
|
+
key_positions: indexes of the key columns within a row (same on both sides).
|
|
124
|
+
limit: stop reading once this many distinct keys differ (None or negative = no limit). Rows for
|
|
125
|
+
keys already collected are still accepted; the first row of a new key beyond the limit stops
|
|
126
|
+
the read and sets `limit_reached`.
|
|
127
|
+
"""
|
|
128
|
+
summary = DiffSummary(
|
|
129
|
+
source_key_columns=tuple(source_columns[i] for i in key_positions),
|
|
130
|
+
target_key_columns=tuple(target_columns[i] for i in key_positions),
|
|
131
|
+
)
|
|
132
|
+
use_limit = limit is not None and limit >= 0
|
|
133
|
+
pending: dict[tuple, tuple[Counter, Counter]] = {}
|
|
134
|
+
|
|
135
|
+
for sign, row in diff:
|
|
136
|
+
key = tuple(row[i] for i in key_positions)
|
|
137
|
+
sides = pending.get(key)
|
|
138
|
+
if sides is None:
|
|
139
|
+
if use_limit and len(pending) >= limit:
|
|
140
|
+
summary.limit_reached = True
|
|
141
|
+
break
|
|
142
|
+
sides = pending[key] = (Counter(), Counter())
|
|
143
|
+
sides[0 if sign == "-" else 1][row] += 1
|
|
144
|
+
summary.raw_rows += 1
|
|
145
|
+
|
|
146
|
+
for key, (src, tgt) in pending.items():
|
|
147
|
+
# Rows present on both sides (e.g. duplicates that were split across segments) cancel out
|
|
148
|
+
common = src & tgt
|
|
149
|
+
if common:
|
|
150
|
+
src -= common
|
|
151
|
+
tgt -= common
|
|
152
|
+
src_rows = sorted(src.elements(), key=_sort_key)
|
|
153
|
+
tgt_rows = sorted(tgt.elements(), key=_sort_key)
|
|
154
|
+
if not src_rows and not tgt_rows:
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
if len(src_rows) == 1 and len(tgt_rows) == 1:
|
|
158
|
+
s, t = src_rows[0], tgt_rows[0]
|
|
159
|
+
column_diffs = [
|
|
160
|
+
ColumnDiff(source_columns[i], target_columns[i], sv, tv)
|
|
161
|
+
for i, (sv, tv) in enumerate(zip(s, t))
|
|
162
|
+
if sv != tv
|
|
163
|
+
]
|
|
164
|
+
summary.key_diffs.append(KeyDiff(key, CHANGED, column_diffs=column_diffs))
|
|
165
|
+
summary.changed += 1
|
|
166
|
+
continue
|
|
167
|
+
|
|
168
|
+
if src_rows and tgt_rows:
|
|
169
|
+
kind = DUPLICATE_KEY
|
|
170
|
+
else:
|
|
171
|
+
kind = SOURCE_ONLY if src_rows else TARGET_ONLY
|
|
172
|
+
if len(src_rows) > 1 or len(tgt_rows) > 1:
|
|
173
|
+
summary.duplicate_keys = True
|
|
174
|
+
summary.key_diffs.append(KeyDiff(key, kind, source_rows=src_rows, target_rows=tgt_rows))
|
|
175
|
+
summary.source_only += len(src_rows)
|
|
176
|
+
summary.target_only += len(tgt_rows)
|
|
177
|
+
|
|
178
|
+
summary.key_diffs.sort(key=lambda kd: _sort_key(kd.key))
|
|
179
|
+
return summary
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# diffdb/databases/__init__.py
|
|
2
|
+
"""diffdb.databases package.
|
|
3
|
+
|
|
4
|
+
Declarative, YAML-configured database engine and dialect implementations.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._connect import DATABASE_BY_SCHEME, Connect, connect
|
|
8
|
+
from .base import (
|
|
9
|
+
ConnectError,
|
|
10
|
+
Database,
|
|
11
|
+
DbKey,
|
|
12
|
+
DbPath,
|
|
13
|
+
DbTime,
|
|
14
|
+
QueryError,
|
|
15
|
+
QueryResult,
|
|
16
|
+
ThreadedDatabase,
|
|
17
|
+
parse_table_name,
|
|
18
|
+
)
|
|
19
|
+
from .bigquery import BigQuery
|
|
20
|
+
from .clickhouse import Clickhouse
|
|
21
|
+
from .databricks import Databricks
|
|
22
|
+
from .duckdb import DuckDB
|
|
23
|
+
from .mysql import MySQL
|
|
24
|
+
from .oracle import Oracle
|
|
25
|
+
from .postgresql import PostgreSQL
|
|
26
|
+
from .presto import Presto
|
|
27
|
+
from .redshift import Redshift
|
|
28
|
+
from .snowflake import Snowflake
|
|
29
|
+
from .trino import Trino
|
|
30
|
+
from .vertica import Vertica
|
|
31
|
+
from .yaml_dialect import YamlDialect
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"DATABASE_BY_SCHEME",
|
|
35
|
+
"BigQuery",
|
|
36
|
+
"Clickhouse",
|
|
37
|
+
"Connect",
|
|
38
|
+
"ConnectError",
|
|
39
|
+
"Database",
|
|
40
|
+
"Databricks",
|
|
41
|
+
"DbKey",
|
|
42
|
+
"DbPath",
|
|
43
|
+
"DbTime",
|
|
44
|
+
"DuckDB",
|
|
45
|
+
"MySQL",
|
|
46
|
+
"Oracle",
|
|
47
|
+
"PostgreSQL",
|
|
48
|
+
"Presto",
|
|
49
|
+
"QueryError",
|
|
50
|
+
"QueryResult",
|
|
51
|
+
"Redshift",
|
|
52
|
+
"Snowflake",
|
|
53
|
+
"ThreadedDatabase",
|
|
54
|
+
"Trino",
|
|
55
|
+
"Vertica",
|
|
56
|
+
"YamlDialect",
|
|
57
|
+
"connect",
|
|
58
|
+
"parse_table_name",
|
|
59
|
+
]
|