diffdb-core 0.1.1__tar.gz → 0.2.0__tar.gz
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_core-0.2.0/PKG-INFO +663 -0
- diffdb_core-0.2.0/README.md +614 -0
- diffdb_core-0.2.0/diffdb_core.egg-info/PKG-INFO +663 -0
- diffdb_core-0.2.0/diffdb_core.egg-info/SOURCES.txt +64 -0
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/pyproject.toml +11 -2
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/__init__.py +1 -1
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/core/hash_differ.py +1 -12
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/core/segment.py +105 -17
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/core/sql.py +13 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/base.py +45 -1
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/duckdb.py +7 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/oracle.py +43 -3
- diffdb_core-0.2.0/src/databases/postgresql.py +70 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/redshift.py +3 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/yaml_dialect.py +1 -1
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/types.py +4 -4
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/tests/golden/query_sql.json +208 -0
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/tests/test_dialects.py +15 -17
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/tests/test_diffdb_core.py +207 -3
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/tests/test_e2e_duckdb.py +18 -0
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/tests/test_query_snapshot.py +6 -2
- diffdb_core-0.1.1/PKG-INFO +0 -318
- diffdb_core-0.1.1/README.md +0 -269
- diffdb_core-0.1.1/src/diffdb/databases/postgresql.py +0 -34
- diffdb_core-0.1.1/src/diffdb_core.egg-info/PKG-INFO +0 -318
- diffdb_core-0.1.1/src/diffdb_core.egg-info/SOURCES.txt +0 -64
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/LICENSE.md +0 -0
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/MANIFEST.in +0 -0
- {diffdb_core-0.1.1/src → diffdb_core-0.2.0}/diffdb_core.egg-info/dependency_links.txt +0 -0
- {diffdb_core-0.1.1/src → diffdb_core-0.2.0}/diffdb_core.egg-info/requires.txt +0 -0
- {diffdb_core-0.1.1/src → diffdb_core-0.2.0}/diffdb_core.egg-info/top_level.txt +0 -0
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/setup.cfg +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/concurrency/__init__.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/concurrency/pool.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/concurrency/stream.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/core/__init__.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/core/differ.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/core/summary.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/__init__.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/_connect.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/bigquery.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/clickhouse.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/databricks.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/_base.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/bigquery.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/clickhouse.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/databricks.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/duckdb.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/mysql.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/oracle.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/postgresql.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/presto.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/redshift.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/snowflake.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/trino.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/dialects/vertica.yaml +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/mysql.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/presto.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/snowflake.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/trino.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/databases/vertica.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/geometry/__init__.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/geometry/arithmetic.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/geometry/bisection.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/geometry/vector.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/telemetry/__init__.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/telemetry/info_tree.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/telemetry/query_tracker.py +0 -0
- {diffdb_core-0.1.1/src/diffdb → diffdb_core-0.2.0/src}/utils.py +0 -0
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/tests/golden/dialect_sql.json +0 -0
- {diffdb_core-0.1.1 → diffdb_core-0.2.0}/tests/test_connect.py +0 -0
|
@@ -0,0 +1,663 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: diffdb-core
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Cross-database table diffing by recursive checksum bisection, with declarative YAML SQL dialects
|
|
5
|
+
Author: Sarath Mohan
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/sarath-mec/diffdb-core
|
|
8
|
+
Project-URL: Documentation, https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md
|
|
9
|
+
Project-URL: Issues, https://github.com/sarath-mec/diffdb-core/issues
|
|
10
|
+
Keywords: database,diff,data-validation,migration,checksum,oracle,postgresql
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Database
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE.md
|
|
21
|
+
Requires-Dist: dsnparse>=0.2.0
|
|
22
|
+
Requires-Dist: pyyaml>=6.0
|
|
23
|
+
Provides-Extra: oracle
|
|
24
|
+
Requires-Dist: oracledb>=2.0.0; extra == "oracle"
|
|
25
|
+
Provides-Extra: postgresql
|
|
26
|
+
Requires-Dist: psycopg2-binary>=2.9.0; extra == "postgresql"
|
|
27
|
+
Provides-Extra: redshift
|
|
28
|
+
Requires-Dist: psycopg2-binary>=2.9.0; extra == "redshift"
|
|
29
|
+
Provides-Extra: mysql
|
|
30
|
+
Requires-Dist: pymysql>=1.0.0; extra == "mysql"
|
|
31
|
+
Provides-Extra: snowflake
|
|
32
|
+
Requires-Dist: snowflake-connector-python>=3.0.0; extra == "snowflake"
|
|
33
|
+
Requires-Dist: cryptography>=41.0.0; extra == "snowflake"
|
|
34
|
+
Provides-Extra: bigquery
|
|
35
|
+
Requires-Dist: google-cloud-bigquery>=3.0.0; extra == "bigquery"
|
|
36
|
+
Provides-Extra: databricks
|
|
37
|
+
Requires-Dist: databricks-sql-connector>=2.0.0; extra == "databricks"
|
|
38
|
+
Provides-Extra: duckdb
|
|
39
|
+
Requires-Dist: duckdb>=0.9.0; extra == "duckdb"
|
|
40
|
+
Provides-Extra: trino
|
|
41
|
+
Requires-Dist: trino>=0.320.0; extra == "trino"
|
|
42
|
+
Provides-Extra: presto
|
|
43
|
+
Requires-Dist: presto-python-client>=0.8.0; extra == "presto"
|
|
44
|
+
Provides-Extra: clickhouse
|
|
45
|
+
Requires-Dist: clickhouse-driver>=0.2.0; extra == "clickhouse"
|
|
46
|
+
Provides-Extra: vertica
|
|
47
|
+
Requires-Dist: vertica-python>=1.0.0; extra == "vertica"
|
|
48
|
+
Dynamic: license-file
|
|
49
|
+
|
|
50
|
+
# diffdb-core
|
|
51
|
+
|
|
52
|
+
Compare tables across different databases without moving the data. `diffdb` pushes a
|
|
53
|
+
`count(*)` + checksum query for each key range down to both databases, and recursively splits only the ranges
|
|
54
|
+
whose checksums differ. Rows are downloaded only for the small segments that actually contain differences,
|
|
55
|
+
then paired by key into a per-row, per-column summary.
|
|
56
|
+
|
|
57
|
+
Built for validating database migrations (e.g. Oracle → PostgreSQL), where the two sides run on different
|
|
58
|
+
engines and a `FULL OUTER JOIN` isn't possible.
|
|
59
|
+
|
|
60
|
+
- **12 databases** through declarative YAML dialects: PostgreSQL, Oracle, MySQL, Snowflake, BigQuery, Redshift,
|
|
61
|
+
Databricks, DuckDB, Trino, Presto, ClickHouse, Vertica.
|
|
62
|
+
- **Any pair**: the source and target can be different engines; each side renders values to the same text before hashing.
|
|
63
|
+
- **Just name the columns**: on PostgreSQL, Oracle and DuckDB the column types come from the database. Declare a
|
|
64
|
+
type or compare an SQL expression only when you need to.
|
|
65
|
+
- **No catalog reads**: no `information_schema`, primary-key or table-list queries. The engine sends a handful of
|
|
66
|
+
read-only query shapes (see [How it works](#how-it-works)).
|
|
67
|
+
- **Non-unique keys** work: bisection columns need only be selective, and duplicate rows are counted.
|
|
68
|
+
- **Per-key summary**: changed rows with their differing columns, source-only and target-only rows, duplicate keys.
|
|
69
|
+
- **Telemetry**: every query, row count, checksum and duration can be captured for auditing.
|
|
70
|
+
|
|
71
|
+
**Contents**
|
|
72
|
+
|
|
73
|
+
- Getting started: [Install](#install) · [Quick start](#quick-start-no-database-server-needed) ·
|
|
74
|
+
[Compare two real databases](#compare-two-real-databases) · [Reading the results](#reading-the-results)
|
|
75
|
+
- Going further: [When to declare a datatype](#when-to-declare-a-datatype) ·
|
|
76
|
+
[Comparing expressions](#comparing-expressions-transform_rule) · [Filtering](#filtering-and-incremental-runs) ·
|
|
77
|
+
[Performance](#performance) · [Auditing](#auditing-queries-raw-rows-and-stats) · [Common errors](#common-errors)
|
|
78
|
+
- Reference: [Arguments](#reference) · [How it works](#how-it-works) ·
|
|
79
|
+
[Keys and the per-key summary](#keys-and-the-per-key-summary) · [Known limitations](#known-limitations)
|
|
80
|
+
- Background: [From fingerprints to bisection](#background-from-aggregate-fingerprints-to-checksum-bisection) ·
|
|
81
|
+
[How diffdb-core differs from reladiff](#how-diffdb-core-differs-from-reladiff) ·
|
|
82
|
+
[Adding a database](#adding-a-database) · [Development](#development)
|
|
83
|
+
|
|
84
|
+
## Install
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
pip install "diffdb-core[postgresql,oracle]" # pick the extras for your databases
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Extras: `oracle`, `postgresql`, `redshift`, `mysql`, `snowflake`, `bigquery`, `databricks`, `duckdb`, `trino`,
|
|
91
|
+
`presto`, `clickhouse`, `vertica`. The package is imported as `diffdb`. Python ≥ 3.12.
|
|
92
|
+
|
|
93
|
+
## Quick start (no database server needed)
|
|
94
|
+
|
|
95
|
+
This runs as is after `pip install "diffdb-core[duckdb]"`. It builds two small tables in a local DuckDB file, with
|
|
96
|
+
three differences between them, and finds them:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import diffdb
|
|
100
|
+
|
|
101
|
+
db = diffdb.connect("duckdb://demo@demo.duckdb") # a local file; created if missing
|
|
102
|
+
|
|
103
|
+
# Two copies of a table, with a few differences in the new one
|
|
104
|
+
db.query("""CREATE OR REPLACE TABLE customers_old AS
|
|
105
|
+
SELECT i AS id, 'user' || i || '@example.com' AS email, CAST(i * 1.5 AS DECIMAL(10,2)) AS balance
|
|
106
|
+
FROM range(1, 10001) t(i)""")
|
|
107
|
+
db.query("CREATE OR REPLACE TABLE customers_new AS SELECT * FROM customers_old")
|
|
108
|
+
db.query("UPDATE customers_new SET balance = balance + 1 WHERE id = 42")
|
|
109
|
+
db.query("DELETE FROM customers_new WHERE id = 7")
|
|
110
|
+
db.query("INSERT INTO customers_new VALUES (10001, 'new@example.com', 0)")
|
|
111
|
+
|
|
112
|
+
columns = {"id": {}, "email": {}, "balance": {}} # just the names; types come from the database
|
|
113
|
+
|
|
114
|
+
src = diffdb.connect_to_table(db, "customers_old", "id", columns) # "id" splits the table into key ranges
|
|
115
|
+
tgt = diffdb.connect_to_table(db, "customers_new", "id", columns)
|
|
116
|
+
|
|
117
|
+
with diffdb.diff_tables(src, tgt) as diff:
|
|
118
|
+
summary = diff.summarize()
|
|
119
|
+
|
|
120
|
+
print(f"changed rows: {summary.changed}")
|
|
121
|
+
print(f"only in source: {summary.source_only}")
|
|
122
|
+
print(f"only in target: {summary.target_only}")
|
|
123
|
+
|
|
124
|
+
for kd in summary.key_diffs:
|
|
125
|
+
if kd.kind == "changed":
|
|
126
|
+
for cd in kd.column_diffs:
|
|
127
|
+
print(f"id {kd.key[0]}: {cd.source_column} changed from {cd.source_value} to {cd.target_value}")
|
|
128
|
+
else:
|
|
129
|
+
print(f"id {kd.key[0]}: {kd.kind}")
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
```text
|
|
133
|
+
changed rows: 1
|
|
134
|
+
only in source: 1
|
|
135
|
+
only in target: 1
|
|
136
|
+
id 10001: target_only
|
|
137
|
+
id 42: balance changed from 63.00 to 64.00
|
|
138
|
+
id 7: source_only
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The three things you always give are the table, the **bisection column** (`"id"`: the column used to split the
|
|
142
|
+
table into ranges, ideally the indexed primary key) and the **columns to compare**.
|
|
143
|
+
|
|
144
|
+
## Compare two real databases
|
|
145
|
+
|
|
146
|
+
The same call, one connection per side. Here an Oracle table is checked against its PostgreSQL copy:
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
from diffdb import connect_to_table, diff_tables
|
|
150
|
+
|
|
151
|
+
src = connect_to_table(
|
|
152
|
+
"oracle://app_user:pwd@oracle-host:1521/ORCLPDB1",
|
|
153
|
+
"SALES.CUSTOMER",
|
|
154
|
+
bisection_columns="CUSTOMER_ID",
|
|
155
|
+
columns={"CUSTOMER_ID": {}, "EMAIL": {}, "BALANCE": {}, "CREATED_AT": {}},
|
|
156
|
+
)
|
|
157
|
+
tgt = connect_to_table(
|
|
158
|
+
"postgresql://app_user:pwd@pg-host:5432/sales",
|
|
159
|
+
"sales.customer",
|
|
160
|
+
bisection_columns="customer_id",
|
|
161
|
+
columns={"customer_id": {}, "email": {}, "balance": {}, "created_at": {}},
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
with diff_tables(src, tgt) as diff:
|
|
165
|
+
summary = diff.summarize(limit=1000) # stop after 1000 differing keys
|
|
166
|
+
|
|
167
|
+
print(f"changed rows: {summary.changed}")
|
|
168
|
+
print(f"only in Oracle: {summary.source_only}")
|
|
169
|
+
print(f"only in PG: {summary.target_only}")
|
|
170
|
+
if summary.limit_reached:
|
|
171
|
+
print("stopped at 1000 differing keys: the counts above are partial")
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Two rules to know from the start:
|
|
175
|
+
|
|
176
|
+
- **Columns are paired by position, not by name.** The first source column is compared with the first target
|
|
177
|
+
column, and so on, so list both sides in the same order. Names may differ (`CUSTOMER_ID` ↔ `customer_id`).
|
|
178
|
+
- **The bisection column is always compared first**, whatever its place in the dict.
|
|
179
|
+
|
|
180
|
+
That's all a typical migration check needs. If a column can't be compared as is (a plain Oracle `NUMBER`, a
|
|
181
|
+
`CLOB`, a database without type reporting), `connect_to_table` raises one `ValueError` that lists every such
|
|
182
|
+
column and how to fix it; the next sections explain the fixes.
|
|
183
|
+
|
|
184
|
+
Connections take a URI or a dict whose other keys go to that database's Python driver:
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
import diffdb
|
|
188
|
+
|
|
189
|
+
pg = diffdb.connect({"driver": "postgresql", "host": "pg-host", "port": 5432, "database": "sales",
|
|
190
|
+
"user": "app_user", "password": "..."})
|
|
191
|
+
ora = diffdb.connect({"driver": "oracle", "user": "app_user", "password": "...",
|
|
192
|
+
"dsn": "oracle-host:1521/ORCLPDB1"}, thread_count=4)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Pass a connected `Database` to `connect_to_table()` instead of a URI so one connection pool serves many tables.
|
|
196
|
+
|
|
197
|
+
## Reading the results
|
|
198
|
+
|
|
199
|
+
`summarize()` returns a `DiffSummary`:
|
|
200
|
+
|
|
201
|
+
| Field | Meaning |
|
|
202
|
+
| :--- | :--- |
|
|
203
|
+
| `changed` | keys present on both sides with different values |
|
|
204
|
+
| `source_only` / `target_only` | rows found on one side only |
|
|
205
|
+
| `source_scanned` / `target_scanned` | rows covered on each side |
|
|
206
|
+
| `limit_reached` | `True` if `limit` stopped the run early (the counts are then partial) |
|
|
207
|
+
| `duplicate_keys` | `True` if some key had several differing rows on one side |
|
|
208
|
+
| `key_diffs` | one `KeyDiff` per differing key: `key`, `kind` (`changed`, `source_only`, `target_only`, `duplicate_key`), `column_diffs` for changed rows, `source_rows` / `target_rows` otherwise |
|
|
209
|
+
|
|
210
|
+
Each `ColumnDiff` holds `source_column`, `target_column`, `source_value` and `target_value`. Values are the
|
|
211
|
+
normalized text that was compared (`'63.00'`, `'2024-01-01 12:57:00.777000'`, `'<null>'` for NULL).
|
|
212
|
+
`summary.as_dict()` gives the whole result as JSON-ready data.
|
|
213
|
+
|
|
214
|
+
```python
|
|
215
|
+
for kd in summary.key_diffs:
|
|
216
|
+
if kd.kind == "changed":
|
|
217
|
+
for cd in kd.column_diffs:
|
|
218
|
+
print(kd.key, cd.target_column, cd.source_value, "->", cd.target_value)
|
|
219
|
+
else: # source_only | target_only | duplicate_key: the unpaired rows
|
|
220
|
+
print(kd.key, kd.kind, kd.source_rows, kd.target_rows)
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
## Going further
|
|
224
|
+
|
|
225
|
+
### When to declare a datatype
|
|
226
|
+
|
|
227
|
+
Each entry in `columns` takes two optional keys: `{"datatype": "<native type>", "transform_rule": "<sql>"}`. With
|
|
228
|
+
neither, diffdb asks the database for the type: when the table is opened it sends one query that returns no
|
|
229
|
+
rows (`SELECT "CUSTOMER_ID", "EMAIL", … FROM "SALES"."CUSTOMER" WHERE 1=0`) and reads each column's type from the
|
|
230
|
+
driver's result metadata. `src.datatypes` shows the type used for every column.
|
|
231
|
+
|
|
232
|
+
Declare `datatype` yourself when:
|
|
233
|
+
|
|
234
|
+
| Situation | Example | Why |
|
|
235
|
+
| :--- | :--- | :--- |
|
|
236
|
+
| A plain decimal with no scale | Oracle `NUMBER`, PostgreSQL `numeric` | The number of decimals to compare is unknown, so it's rejected. Declare it: `{"datatype": "NUMBER(12,2)"}` / `{"datatype": "numeric(12,2)"}`, or `NUMBER(*,0)` / `numeric(38,0)` for whole numbers. |
|
|
237
|
+
| The database can't report types | MySQL, Snowflake, BigQuery, Redshift, Databricks, Trino, Presto, ClickHouse, Vertica | Type reporting is available on PostgreSQL, Oracle and DuckDB only. |
|
|
238
|
+
| An Oracle `TIMESTAMP(0)` | | Oracle reports no precision for it. |
|
|
239
|
+
| The bisection column is a plain `NUMBER` | `"ID": {"datatype": "NUMBER(12,0)"}` | Better than a `CAST` in a `transform_rule`, which would stop the database from using the column's index. |
|
|
240
|
+
|
|
241
|
+
A declared `datatype` always wins and isn't probed, so you can mix both styles in one dict:
|
|
242
|
+
|
|
243
|
+
```python
|
|
244
|
+
columns={
|
|
245
|
+
"ID": {"datatype": "NUMBER(12,0)"}, # plain NUMBER key: declared
|
|
246
|
+
"EMAIL": {}, # VARCHAR2, reported
|
|
247
|
+
"AMOUNT": {}, # NUMBER(12,2), reported
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
`datatype` is the native type name as the database spells it (`VARCHAR2(100)`, `TIMESTAMP(3)`, `numeric(12,2)`,
|
|
252
|
+
`bigint`). Only basic types compare: numbers, strings, timestamps/dates and booleans; see [Types](#types).
|
|
253
|
+
|
|
254
|
+
### Comparing expressions: `transform_rule`
|
|
255
|
+
|
|
256
|
+
A `transform_rule` is an SQL expression used instead of the column, on that side only. Use it to reduce a type
|
|
257
|
+
that can't be compared (LOBs, binary), to clean values, or to make both engines agree:
|
|
258
|
+
|
|
259
|
+
```python
|
|
260
|
+
oracle_columns = {
|
|
261
|
+
"ID": {},
|
|
262
|
+
"NOTES": {"transform_rule": 'CAST(DBMS_LOB.GETLENGTH("NOTES") AS NUMBER(10,0))'}, # CLOB -> its length
|
|
263
|
+
"NAME": {"transform_rule": 'TRIM("NAME")'},
|
|
264
|
+
"CREATED": {"transform_rule": 'TRUNC("CREATED")'}, # drop the time of day
|
|
265
|
+
}
|
|
266
|
+
postgres_columns = {
|
|
267
|
+
"id": {},
|
|
268
|
+
"notes": {"transform_rule": 'length("notes")'},
|
|
269
|
+
"name": {"transform_rule": 'trim("name")'},
|
|
270
|
+
"created": {"transform_rule": "date_trunc('day', \"created\")"},
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
- The rule is wrapped in parentheses and used **everywhere** the column appears: the checksum, the key-range
|
|
275
|
+
`MIN`/`MAX`, the downloaded rows and, for a bisection column, the key-range `WHERE` clauses.
|
|
276
|
+
- The type of the rule's result is reported like a column's, but engines often can't name it exactly. Oracle
|
|
277
|
+
reports `LENGTH`, `ROUND` and arithmetic as a plain `NUMBER`, and PostgreSQL reports `round()` and arithmetic as a
|
|
278
|
+
plain `numeric`. Both are rejected, so `CAST` the result (as above) or declare `datatype` for the result:
|
|
279
|
+
`{"datatype": "NUMBER(10,0)", "transform_rule": 'DBMS_LOB.GETLENGTH("NOTES")'}`.
|
|
280
|
+
- PostgreSQL's `length()` returns `integer`, so it needs no cast.
|
|
281
|
+
|
|
282
|
+
### Filtering and incremental runs
|
|
283
|
+
|
|
284
|
+
`where` adds an SQL filter to every query on that side, e.g. to check only recent changes (CDC windows):
|
|
285
|
+
|
|
286
|
+
```python
|
|
287
|
+
src = connect_to_table(ora, "SALES.ORDERS", "ORDER_ID", cols,
|
|
288
|
+
where="\"UPDATED_AT\" >= TIMESTAMP '2026-10-01 00:00:00'")
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
`diff_tables(..., where=...)` sets the same filter on both sides, and `min_key` / `max_key` restrict the
|
|
292
|
+
bisection key range.
|
|
293
|
+
|
|
294
|
+
### Performance
|
|
295
|
+
|
|
296
|
+
- **Bisect on an indexed, selective column**, usually the primary key. Every checksum query filters on it.
|
|
297
|
+
- **Threads**: `connect(..., thread_count=N)` opens N connections per database, and
|
|
298
|
+
`diff_tables(..., max_threadpool_size=M)` sets how many queries run at once; make M at least 2 × N.
|
|
299
|
+
- **`bisection_factor`** (default 32): how many ranges each mismatching range is split into.
|
|
300
|
+
**`bisection_threshold`** (default 16,384): ranges with fewer rows are downloaded and compared in memory.
|
|
301
|
+
- **Mostly identical tables are fast**: matching ranges cost one checksum query each and nothing is downloaded.
|
|
302
|
+
- `summarize(limit=N)` stops after N differing keys and cancels the remaining queries.
|
|
303
|
+
|
|
304
|
+
### Auditing: queries, raw rows and stats
|
|
305
|
+
|
|
306
|
+
- `diff.get_queries_and_checksums()` lists every query sent, with row counts, checksums and durations
|
|
307
|
+
(`diff_tables(..., return_queries=True)` also returns the `QueryTracker`).
|
|
308
|
+
- `for sign, row in diff_tables(src, tgt)` streams the raw differences: `'-'` = source only, `'+'` = target only.
|
|
309
|
+
- `diff.get_stats_dict()` returns counts only.
|
|
310
|
+
- Logging goes through the `diffdb` logger (`logging.getLogger("diffdb").setLevel(logging.INFO)` shows each
|
|
311
|
+
reported column type).
|
|
312
|
+
|
|
313
|
+
See [ARCHITECTURE.md](https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md#6-python-api-reference--practical-recipes)
|
|
314
|
+
for more recipes.
|
|
315
|
+
|
|
316
|
+
### Common errors
|
|
317
|
+
|
|
318
|
+
All problems with `columns` are reported together in one `ValueError` when the table is opened.
|
|
319
|
+
|
|
320
|
+
| Error says | Fix |
|
|
321
|
+
| :--- | :--- |
|
|
322
|
+
| `datatype 'NUMBER' has no scale` / `reports 'NUMBER' (no scale)` | Declare the scale (`NUMBER(12,2)`, `NUMBER(*,0)`) or `CAST` the rule. |
|
|
323
|
+
| `unsupported type 'CLOB'` (or `BLOB`, `bytea`, …) | Reduce it with a `transform_rule`, e.g. its length. |
|
|
324
|
+
| `can't report column types yet` | That database has no type reporting: declare `datatype` for each column. |
|
|
325
|
+
| `doesn't report enough to name the exact type` | Declare `datatype` (e.g. an Oracle `TIMESTAMP(0)`). |
|
|
326
|
+
| `bisection column(s) [...] are not in columns` | Add the bisection column to `columns`. |
|
|
327
|
+
| `Incompatible types for column` | The paired columns have different kinds (e.g. a string and a number). Check the column order, or cast one side. |
|
|
328
|
+
| `key_columns must sit at the same positions on both sides` | List the columns in the same order on both sides. |
|
|
329
|
+
| `EmptyTable` | A side has no rows in range: pass `allow_empty_tables=True` if that's expected. |
|
|
330
|
+
| `ORA-01489` | The Oracle row string is longer than 4000 bytes: compare wide text columns through `LENGTH(...)`. |
|
|
331
|
+
|
|
332
|
+
## Reference
|
|
333
|
+
|
|
334
|
+
`TableSegment` (or `connect_to_table`) takes:
|
|
335
|
+
|
|
336
|
+
| Argument | Meaning |
|
|
337
|
+
| :--- | :--- |
|
|
338
|
+
| `bisection_columns` | Columns that split the table into key ranges. Need not be unique, but should be selective and indexed: one value holding more rows than `bisection_threshold` can't be split and is downloaded whole (with a warning). Integers, decimals, timestamps, UUIDs and alphanumeric strings are supported. |
|
|
339
|
+
| `columns` | `{name: {"datatype": "<native type>", "transform_rule": "<sql>"}}` for every compared column, bisection columns included. Both keys are optional (see [When to declare a datatype](#when-to-declare-a-datatype) and [Comparing expressions](#comparing-expressions-transform_rule)). Paired with the other side by position. |
|
|
340
|
+
| `key_columns` | Columns identifying a logical row in the summary (default: `bisection_columns`). Used only to report differences; see [Keys and the per-key summary](#keys-and-the-per-key-summary). |
|
|
341
|
+
| `where` | Optional SQL filter added to every query, e.g. a time window. |
|
|
342
|
+
|
|
343
|
+
`diff_tables(src, tgt, ...)` options:
|
|
344
|
+
|
|
345
|
+
| Option | Default | Meaning |
|
|
346
|
+
| :--- | :--- | :--- |
|
|
347
|
+
| `bisection_columns`, `key_columns`, `where`, `min_key`, `max_key` | from the tables | override these on both sides |
|
|
348
|
+
| `bisection_factor` | 32 | ranges per split |
|
|
349
|
+
| `bisection_threshold` | 16384 | rows below which a range is downloaded |
|
|
350
|
+
| `threaded` / `max_threadpool_size` | `True` / 1 | run queries concurrently |
|
|
351
|
+
| `duplicate_rows_support` | `True` | count identical duplicate rows (needed when keys repeat) |
|
|
352
|
+
| `allow_empty_tables` | `False` | don't raise `EmptyTable` for empty sides |
|
|
353
|
+
| `skip_sort_results` | `False` | skip sorting the raw stream |
|
|
354
|
+
| `track_queries` / `return_queries` | `True` / `False` | record queries; also return the `QueryTracker` |
|
|
355
|
+
|
|
356
|
+
### Types
|
|
357
|
+
|
|
358
|
+
The engine compares numbers, strings, timestamps/dates and booleans (hashed as `1`/`0`); `NULL` is `'<null>'` on
|
|
359
|
+
every side. LOB and binary types (`CLOB`, `BLOB`, `RAW`, `bytea`, …) are rejected on purpose: reduce them with a
|
|
360
|
+
`transform_rule`. When the two sides have different precisions (`TIMESTAMP(3)` vs `timestamp(6)`, `NUMBER(12,4)`
|
|
361
|
+
vs `numeric(12,2)`), both are compared at the lower one.
|
|
362
|
+
|
|
363
|
+
A decimal must have a scale, declared or reported: a plain Oracle `NUMBER` / `NUMBER(*)` or PostgreSQL `numeric`
|
|
364
|
+
(or any dialect's decimal type without arguments) is rejected, because the number of fractional digits to compare
|
|
365
|
+
is unknown. An engine that can't name the exact type of a column or expression makes it fail the same way,
|
|
366
|
+
instead of comparing it at a guessed precision. One exception is safe: psycopg2 doesn't report a PostgreSQL
|
|
367
|
+
timestamp's precision, so it takes 6, PostgreSQL's maximum. That never understates it, and the other side's lower
|
|
368
|
+
precision still wins.
|
|
369
|
+
|
|
370
|
+
## How it works
|
|
371
|
+
|
|
372
|
+
1. **Divide**: the key space of `bisection_columns` (from `min`/`max`) is split into `bisection_factor` ranges (default 32).
|
|
373
|
+
2. **Checksum**: for each range, both databases compute `count(*)` and the sum of a 60-bit integer taken from the MD5
|
|
374
|
+
of each row, where the row is its normalized columns joined with `'|'`.
|
|
375
|
+
3. **Recurse**: ranges with equal counts and checksums are done. The others are split again until they hold fewer
|
|
376
|
+
rows than `bisection_threshold` (default 16,384).
|
|
377
|
+
4. **Download & compare**: only those small ranges are downloaded and compared in memory.
|
|
378
|
+
5. **Summarize**: `summarize()` pairs the differing rows by `key_columns` (default: the bisection columns).
|
|
379
|
+
|
|
380
|
+
Before that, once per table and only for columns without a declared `datatype`, one query that returns no rows
|
|
381
|
+
(`SELECT <columns> FROM t WHERE 1=0`) reads their types from the driver's result metadata.
|
|
382
|
+
|
|
383
|
+
For a table bisected on `(ORDER_ID, LINE_CODE)`, with columns `ORDER_ID NUMBER(12,0)` / `bigint`,
|
|
384
|
+
`LINE_CODE VARCHAR2(20)` / `varchar(20)`, `UPDATED_AT TIMESTAMP(6)` / `timestamp(6)` and
|
|
385
|
+
`UPDATED_BY VARCHAR2(30)` / `varchar(30)`, the checksum queries look like this. Oracle (database character set
|
|
386
|
+
isn't AL32UTF8, so the row is converted first, to hash the same bytes as PostgreSQL; detected from
|
|
387
|
+
`NLS_CHARACTERSET` or forced with a `hash_charset` connection setting):
|
|
388
|
+
|
|
389
|
+
```sql
|
|
390
|
+
SELECT
|
|
391
|
+
count(*),
|
|
392
|
+
sum(to_number(substr(standard_hash(CONVERT((
|
|
393
|
+
NVL(to_char("ORDER_ID", 'FM99999999999999999999999999999999999999'), '<null>')
|
|
394
|
+
|| '|' || NVL("LINE_CODE", '<null>')
|
|
395
|
+
|| '|' || NVL(to_char(cast("UPDATED_AT" as timestamp(6)), 'YYYY-MM-DD HH24:MI:SS.FF6'), '<null>')
|
|
396
|
+
|| '|' || NVL("UPDATED_BY", '<null>')
|
|
397
|
+
), 'AL32UTF8'), 'MD5'), 18), 'xxxxxxxxxxxxxxx'))
|
|
398
|
+
FROM "SALES"."ORDER_LINE"
|
|
399
|
+
WHERE ("ORDER_ID" >= 1405) AND ("LINE_CODE" >= 'A-001')
|
|
400
|
+
AND ("ORDER_ID" < 2662) AND ("LINE_CODE" < 'K-250')
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
PostgreSQL (with a `COLLATE "C"` transform rule on the string bisection column, see Limitations):
|
|
404
|
+
|
|
405
|
+
```sql
|
|
406
|
+
SELECT
|
|
407
|
+
count(*),
|
|
408
|
+
sum(('x' || substring(md5((
|
|
409
|
+
coalesce("order_id"::varchar, '<null>')
|
|
410
|
+
|| '|' || coalesce(("line_code" COLLATE "C"), '<null>')
|
|
411
|
+
|| '|' || coalesce(to_char("updated_at"::timestamp(6), 'YYYY-mm-dd HH24:MI:SS.US'), '<null>')
|
|
412
|
+
|| '|' || coalesce("updated_by", '<null>')
|
|
413
|
+
)), 18))::bit(60)::bigint)
|
|
414
|
+
FROM "sales"."order_line"
|
|
415
|
+
WHERE ("order_id" >= 1405) AND (("line_code" COLLATE "C") >= 'A-001')
|
|
416
|
+
AND ("order_id" < 2662) AND (("line_code" COLLATE "C") < 'K-250')
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
The only other query is Oracle's `NLS_CHARACTERSET` lookup, once per connection, unless `hash_charset` is given.
|
|
420
|
+
|
|
421
|
+
## Keys and the per-key summary
|
|
422
|
+
|
|
423
|
+
The diff itself works on whole rows: a range whose checksums differ is downloaded, and every row that isn't
|
|
424
|
+
present on the other side, value for value, comes out as `('-', row)` (source only) or `('+', row)` (target only).
|
|
425
|
+
`key_columns` decide how `summarize()` and `get_stats_dict()` turn those rows into results. They are never sent to
|
|
426
|
+
the database and don't change which rows are compared.
|
|
427
|
+
|
|
428
|
+
- **Bisection columns vs key columns**: `bisection_columns` split the table into ranges (they should be indexed);
|
|
429
|
+
`key_columns` say which rows are "the same row" (usually the primary key). The default is the bisection columns.
|
|
430
|
+
- **Positions, not names**: the two sides are paired by column position, so the key columns must sit at the same
|
|
431
|
+
positions in both `columns` dicts; `diff_tables` checks this before running any query.
|
|
432
|
+
- **Not unique**: keys may repeat. Nothing in the database is checked.
|
|
433
|
+
- **Include every bisection column** in the key when you can. Both versions of a key then land in the same range, so
|
|
434
|
+
pairing stays exact even when `summarize(limit=N)` stops the run early.
|
|
435
|
+
|
|
436
|
+
### How rows become `key_diffs`
|
|
437
|
+
|
|
438
|
+
All differing rows are grouped by key. Rows that appear identically on both sides cancel out first, so only the
|
|
439
|
+
leftover rows of a key decide its `kind`:
|
|
440
|
+
|
|
441
|
+
| Leftover rows for a key | `kind` | What the `KeyDiff` holds | Counted in |
|
|
442
|
+
| :--- | :--- | :--- | :--- |
|
|
443
|
+
| 1 source, 1 target | `changed` | `column_diffs`: the differing columns, with both sides' names and values | `changed` (1) |
|
|
444
|
+
| source only (1 or more) | `source_only` | `source_rows` | `source_only` (one per row) |
|
|
445
|
+
| target only (1 or more) | `target_only` | `target_rows` | `target_only` (one per row) |
|
|
446
|
+
| both sides, not exactly 1 and 1 (e.g. 2 source, 1 target) | `duplicate_key` | `source_rows` and `target_rows`, unpaired, no `column_diffs` | `source_only` and `target_only` (one per row) |
|
|
447
|
+
|
|
448
|
+
`summary.duplicate_keys` is `True` when any key had more than one leftover row on a side. Rows hold the values as
|
|
449
|
+
downloaded (normalized strings), in `columns` order with the bisection columns first.
|
|
450
|
+
|
|
451
|
+
For example, with `key_columns=("ORDER_ID", "LINE_NO")` these differing rows:
|
|
452
|
+
|
|
453
|
+
```text
|
|
454
|
+
- (1, 1, QTY 5) + (1, 1, QTY 6) one row each side
|
|
455
|
+
- (2, 1, QTY 3) source only
|
|
456
|
+
+ (3, 1, QTY 9) target only
|
|
457
|
+
- (4, 1, QTY 2) + (4, 1, QTY 8) key 4 is duplicated in the source:
|
|
458
|
+
- (4, 1, QTY 7) 2 source rows, 1 target row
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
summarize to (`summary.as_dict()["key_diffs"]`, abridged):
|
|
462
|
+
|
|
463
|
+
```text
|
|
464
|
+
key ["1","1"] changed column_diffs [QTY/qty: "5" -> "6"]
|
|
465
|
+
key ["2","1"] source_only source_rows [["2","1","3"]]
|
|
466
|
+
key ["3","1"] target_only target_rows [["3","1","9"]]
|
|
467
|
+
key ["4","1"] duplicate_key source_rows [["4","1","2"], ["4","1","7"]] target_rows [["4","1","8"]]
|
|
468
|
+
|
|
469
|
+
counts: changed 1, source_only 3, target_only 2; duplicate_keys: true
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
Duplicates often look like ordinary differences, because matching copies cancel:
|
|
473
|
+
|
|
474
|
+
| Source rows for a key | Target rows | Reported as |
|
|
475
|
+
| :--- | :--- | :--- |
|
|
476
|
+
| `A`, `A` | `A`, `A` | nothing (identical) |
|
|
477
|
+
| `A`, `A` | `A` | `source_only` with one row `A` (the extra copy); `duplicate_keys` stays `False` |
|
|
478
|
+
| `A`, `B` | `A`, `C` | `changed`, `B` → `C` (the `A` copies cancel) |
|
|
479
|
+
| `B`, `C` | `D` | `duplicate_key`: no way to tell which source row became `D` |
|
|
480
|
+
|
|
481
|
+
Use a key that is unique in your data when you need every difference to be a `changed` row. Use `duplicate_key`
|
|
482
|
+
entries and `duplicate_keys` as the signal to look at the rows yourself.
|
|
483
|
+
|
|
484
|
+
## Known limitations
|
|
485
|
+
|
|
486
|
+
- **String collation**: Oracle sorts strings by bytes, PostgreSQL by its collation by default, so the same key
|
|
487
|
+
range selects different rows. Add `COLLATE "C"` as the PostgreSQL `transform_rule` of string bisection columns.
|
|
488
|
+
That bypasses the default index (create one with `COLLATE "C"`), so prefer numeric bisection columns.
|
|
489
|
+
- **Alphanumeric keys**: string bisection keys may only contain `space - . 0-9 A-Z _ a-z`
|
|
490
|
+
(`diffdb/geometry/arithmetic.py`). Bisect on another column when keys contain other characters.
|
|
491
|
+
- **Oracle 4000-byte limit**: the row string must fit in a `VARCHAR2` (`ORA-01489` otherwise). Compare very wide
|
|
492
|
+
text columns through a transform rule such as `LENGTH(col)`.
|
|
493
|
+
- **Live data**: rows changing during a run show up as differences. Restrict `where` to a stable window.
|
|
494
|
+
- **Character sets**: values both drivers decode to the same Unicode text compare equal at row level, but a
|
|
495
|
+
checksum mismatch still costs a download of that segment.
|
|
496
|
+
|
|
497
|
+
## Background: from aggregate fingerprints to checksum bisection
|
|
498
|
+
|
|
499
|
+
diffdb-core is the third iteration of my migration data-validation tooling, after `simple-dv-tool` and
|
|
500
|
+
`ibis-dv-tool`, and is built on reladiff's algorithm. The first two are archived and kept for reference.
|
|
501
|
+
|
|
502
|
+
### 1. simple-dv-tool: hand-written aggregate SQL
|
|
503
|
+
|
|
504
|
+
[simple-dv-tool](https://github.com/sarath-mec/simple-dv-tool) validated Hive / MySQL → BigQuery migrations from a
|
|
505
|
+
notebook. It split the source into N batches by ranking on a split key, sent each batch's source key range to
|
|
506
|
+
BigQuery as a temp table, and compared **aggregate fingerprints** per batch: `COUNT(1)`, and per column
|
|
507
|
+
`COUNT(DISTINCT c)`, null count, `MIN(c)` and `MAX(c)`. The results were compared in DuckDB, and a BigQuery UDF
|
|
508
|
+
decided what counted as a match (rounding, timezone shifts, NULL-like strings).
|
|
509
|
+
|
|
510
|
+
- Every query was an f-string, with engine-specific code (Hive `DESCRIBE` parsing, MySQL collation, BigQuery scripting).
|
|
511
|
+
- The target could only be BigQuery, and each table was configured by hand.
|
|
512
|
+
|
|
513
|
+
### 2. ibis-dv-tool: the same idea on Ibis, database-wide
|
|
514
|
+
|
|
515
|
+
[ibis-dv-tool](https://github.com/sarath-mec/ibis-dv-tool) kept the fingerprint idea but wrote every query as an
|
|
516
|
+
[Ibis](https://ibis-project.org/) expression, compiled to each backend's SQL, so any Ibis-supported pair worked. It
|
|
517
|
+
added a database-wide mapping phase (a metadata view in each database, fuzzy table/column matching, a reviewable
|
|
518
|
+
YAML config per table) and a **detailed** mode that pulled small tables into pandas and diffed them cell by cell on
|
|
519
|
+
the primary key.
|
|
520
|
+
|
|
521
|
+
Both tools hit the same limits:
|
|
522
|
+
|
|
523
|
+
- **Fingerprints miss changes.** `COUNT(DISTINCT)`, `MIN` and `MAX` stay the same when a value changes in the
|
|
524
|
+
middle of a range, or when two rows swap values. They show *which batch and column* look wrong, never *which rows*.
|
|
525
|
+
- **Row-level comparison doesn't scale.** Detailed mode had to pull the whole table (or batch) into pandas.
|
|
526
|
+
- **Batches are fixed up front.** Narrowing a mismatch inside a large batch was manual drill-down SQL.
|
|
527
|
+
- **Matching rules ran after the fact.** Values were compared in whatever text each engine returned, then a UDF or
|
|
528
|
+
pandas dtype alignment tried to make them agree.
|
|
529
|
+
|
|
530
|
+
### 3. reladiff: what checksum bisection fixed
|
|
531
|
+
|
|
532
|
+
[reladiff](https://github.com/erezsh/reladiff) (a maintained fork of data-diff) solves those problems with
|
|
533
|
+
**recursive checksum bisection**, which is the algorithm diffdb-core uses:
|
|
534
|
+
|
|
535
|
+
| | simple-dv-tool / ibis-dv-tool | reladiff (and diffdb-core) |
|
|
536
|
+
| :--- | :--- | :--- |
|
|
537
|
+
| What is compared | `COUNT`, `COUNT(DISTINCT)`, `MIN`, `MAX` per column | `count(*)` + sum of an MD5 of **every value of every row** |
|
|
538
|
+
| Detects | changes that move a count, min or max | any changed, missing or extra row |
|
|
539
|
+
| Result | batch + column that differ, plus drill-down SQL | the exact differing rows |
|
|
540
|
+
| Narrowing down | fixed batches; manual drill-down | ranges that differ are split again, automatically, until small |
|
|
541
|
+
| Rows moved | none (summary) or the whole table (detailed) | only the rows of small, mismatching ranges |
|
|
542
|
+
| Cross-engine values | compared as returned, then matched by tolerance rules | normalized to the same text **in SQL** before hashing, with precision lowered to the common minimum |
|
|
543
|
+
|
|
544
|
+
What reladiff doesn't do, and the earlier tools did: database-wide table and column mapping, fuzzy name matching
|
|
545
|
+
and tolerance rules. diffdb-core doesn't do those either; it expects the caller to supply the pairing (see below).
|
|
546
|
+
|
|
547
|
+
## How diffdb-core differs from reladiff
|
|
548
|
+
|
|
549
|
+
diffdb-core adapts reladiff's bisection engine (`HashDiffer`, segments, key-space geometry, threaded yielder; see
|
|
550
|
+
[License](#license)) and changes how tables are described, how dialects are defined and how results are reported.
|
|
551
|
+
|
|
552
|
+
| | reladiff | diffdb-core |
|
|
553
|
+
| :--- | :--- | :--- |
|
|
554
|
+
| Column definitions | column **names** (`key_columns`, `extra_columns`); types read from the database | column names per side, paired by position; types from the result metadata of a zero-row query, or declared; optional `transform_rule` per column |
|
|
555
|
+
| Metadata queries | reads `information_schema` and samples rows to refine types | no catalog reads: one `WHERE 1=0` probe per table for columns without a declared type, plus Oracle `NLS_CHARACTERSET` once per connection |
|
|
556
|
+
| Compare an SQL expression | not supported (create a view) | `transform_rule` on any column, bisection columns included |
|
|
557
|
+
| LOB / binary / unknown types | compared anyway, with a "may result in false positives" warning | rejected up front; reduce them with a `transform_rule` |
|
|
558
|
+
| Types an engine can't name exactly | sampled / guessed | rejected with the fix (declare the type, or `CAST`), never compared at a guessed precision |
|
|
559
|
+
| Dialects | Python classes and mixins from [sqeleton](https://github.com/erezsh/sqeleton), SQL built by its query builder | one validated YAML file per database; SQL built as plain strings in `core/sql.py` |
|
|
560
|
+
| Result | `+`/`-` row stream; `get_stats_dict()` counts | the same stream, plus `summarize()`: per-key, per-column results |
|
|
561
|
+
| Duplicate keys in stats | a key with two differing rows on the same side fails an `assert` | reported as `duplicate_key`, with `duplicate_keys=True` |
|
|
562
|
+
| Limit | `--limit` on rows (CLI; can't be combined with `--stats`) | `summarize(limit=N)` on distinct differing keys, cancels outstanding queries |
|
|
563
|
+
| Algorithms | `hashdiff` (cross-database) and `joindiff` (same database) | `hashdiff` only |
|
|
564
|
+
| Interface | CLI, TOML run config, Python API | Python API only |
|
|
565
|
+
| Incremental runs | `update_column` with `min_update` / `max_update` | a `where` filter |
|
|
566
|
+
|
|
567
|
+
### `transform_rule`: comparing expressions, not just columns
|
|
568
|
+
|
|
569
|
+
In reladiff a compared column is a name that must exist in the table's schema. To compare `TRIM(name)`, a CLOB's
|
|
570
|
+
length, or a string key under binary collation, you have to create a view on each side first. In diffdb-core each
|
|
571
|
+
column entry can carry a `transform_rule` (see [Comparing expressions](#comparing-expressions-transform_rule)):
|
|
572
|
+
|
|
573
|
+
- The rule is used **everywhere** the column appears, including the key-range `WHERE` clauses when it's a
|
|
574
|
+
bisection column (see the PostgreSQL query in [How it works](#how-it-works)).
|
|
575
|
+
- Each side has its own rule, so the two sides can use different SQL to reach the same value.
|
|
576
|
+
- The result's type (declared, or reported by the database for the rule) drives normalization and precision
|
|
577
|
+
reconciliation, so the result is hashed as the expression's type, not the column's original type.
|
|
578
|
+
- This is how unsupported types are handled: LOB and binary columns are rejected unless a rule reduces them to a
|
|
579
|
+
number, string or timestamp. reladiff instead hashes them with a warning, which can report false differences.
|
|
580
|
+
|
|
581
|
+
This is the same idea as ibis-dv-tool's editable `src_matched_cols` (where a source "column" could be a cast), now
|
|
582
|
+
applied inside the hash, on both sides, with a known type.
|
|
583
|
+
|
|
584
|
+
### YAML dialect declarations
|
|
585
|
+
|
|
586
|
+
reladiff gets its dialects from sqeleton: each database is a Python class composed from mixins
|
|
587
|
+
(`oracle.Dialect, oracle.Mixin_MD5, oracle.Mixin_NormalizeValue, …`), with type parsing and value normalization
|
|
588
|
+
spread across Python methods. Checking that two engines render a timestamp identically means reading code in
|
|
589
|
+
several classes.
|
|
590
|
+
|
|
591
|
+
diffdb-core declares each dialect in one YAML file (`src/databases/dialects/<db>.yaml`):
|
|
592
|
+
|
|
593
|
+
- `extends:` another dialect (usually `_base.yaml`, which holds portable ANSI defaults and documents every key).
|
|
594
|
+
- `syntax:` fragments (quoting, concatenation, `md5_as_int`, …), `type_classes` / `type_regexps` (native type name
|
|
595
|
+
→ diffdb type, e.g. `NUMBER` → `Decimal`), and `normalization:` templates (how each type becomes text before
|
|
596
|
+
hashing).
|
|
597
|
+
- **Validated when it loads**: unknown keys, unknown type classes and unknown template placeholders raise
|
|
598
|
+
`DialectConfigError`, rather than producing wrong SQL at run time.
|
|
599
|
+
- Engine-specific behaviour lives in YAML, not in `if name == ...` branches. The only Python per database is a small
|
|
600
|
+
driver class (import, connection and, optionally, naming the types in the driver's result metadata).
|
|
601
|
+
- Every dialect's generated SQL is pinned by golden snapshots (`tests/golden/`), so a YAML change that alters a
|
|
602
|
+
query shows up as a test diff.
|
|
603
|
+
|
|
604
|
+
A column's native type (reported by the database, or declared) is turned into a diffdb type by the dialect's
|
|
605
|
+
`type_classes`. That replaces reladiff's `information_schema` query and row sampling.
|
|
606
|
+
|
|
607
|
+
(This YAML is a dialect definition. It is different from reladiff's TOML file, which describes runs, and from
|
|
608
|
+
ibis-dv-tool's YAML, which described the table mapping. diffdb-core has no run-config file.)
|
|
609
|
+
|
|
610
|
+
### Summarization
|
|
611
|
+
|
|
612
|
+
reladiff's result is a stream of `('-', row)` and `('+', row)`. `get_stats_dict()` groups that stream by key and
|
|
613
|
+
returns counts: `rows_A`, `rows_B`, `exclusive_A`, `exclusive_B`, `updated`, `unchanged`, `total`. It doesn't say
|
|
614
|
+
*which* columns of an updated row changed, and it assumes each key has at most one differing row per side.
|
|
615
|
+
|
|
616
|
+
diffdb-core keeps that stream and `get_stats_dict()`, and adds `summarize(limit=N)`, which returns a `DiffSummary`:
|
|
617
|
+
|
|
618
|
+
| | reladiff `get_stats_dict()` | diffdb-core `summarize()` |
|
|
619
|
+
| :--- | :--- | :--- |
|
|
620
|
+
| Granularity | counts only | one `KeyDiff` per differing key |
|
|
621
|
+
| Changed rows | counted as `updated` | `changed`, with a `ColumnDiff` per differing column: source and target column names and values |
|
|
622
|
+
| Missing / extra rows | `exclusive_A` / `exclusive_B` counts | `source_only` / `target_only`, with the rows |
|
|
623
|
+
| Pairing key | the table's key columns | `key_columns`, separate from the bisection columns, need not be unique |
|
|
624
|
+
| Duplicate keys | `AssertionError` when one side has two differing rows for a key | `duplicate_key` entries with all unpaired rows, and `duplicate_keys=True` |
|
|
625
|
+
| Early stop | none for stats | `limit` = number of distinct differing keys; queries are cancelled and `limit_reached=True` |
|
|
626
|
+
| Rows covered | `rows_A` / `rows_B` | `source_scanned` / `target_scanned`, plus `raw_rows` read from the stream |
|
|
627
|
+
| Export | dict | `as_dict()`, JSON-ready |
|
|
628
|
+
|
|
629
|
+
See [Keys and the per-key summary](#keys-and-the-per-key-summary) for how rows are paired. This brings back the
|
|
630
|
+
cell-level report of ibis-dv-tool's detailed mode (key, column, source value, target value) without pulling whole
|
|
631
|
+
tables into memory: only the rows of mismatching segments are ever downloaded.
|
|
632
|
+
|
|
633
|
+
## Adding a database
|
|
634
|
+
|
|
635
|
+
1. A YAML dialect in `src/databases/dialects/<db>.yaml` that `extends: _base.yaml` and declares its SQL
|
|
636
|
+
fragments, type mapping and normalization templates. `_base.yaml` documents every key; unknown keys, type
|
|
637
|
+
classes and template placeholders are rejected when the dialect loads.
|
|
638
|
+
2. A small driver class in `src/databases/<db>.py` (driver import and connection creation), registered in
|
|
639
|
+
`DATABASE_BY_SCHEME` (`src/databases/_connect.py`). Optionally a `_native_type()` hook that names the type of
|
|
640
|
+
a `cursor.description` entry, so `datatype` can be left out on that database.
|
|
641
|
+
|
|
642
|
+
The new dialect must render every value byte-identically to its counterpart. See
|
|
643
|
+
[ARCHITECTURE.md](https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md#4-declarative-yaml-dialect-framework).
|
|
644
|
+
|
|
645
|
+
## Development
|
|
646
|
+
|
|
647
|
+
```bash
|
|
648
|
+
uv sync # installs the package with pytest, ruff and duckdb
|
|
649
|
+
uv run pytest # no external database needed
|
|
650
|
+
uv run ruff check .
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
The tests include unit tests, a DuckDB end-to-end diff with planted differences, and golden snapshots of the SQL
|
|
654
|
+
every dialect generates (`tests/golden/`). After an intended dialect or SQL change, regenerate and review them:
|
|
655
|
+
|
|
656
|
+
```bash
|
|
657
|
+
DIFFDB_UPDATE_GOLDEN=1 uv run python -m unittest tests.test_dialects tests.test_query_snapshot
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
## License
|
|
661
|
+
|
|
662
|
+
MIT. `diffdb` adapts code from [reladiff](https://github.com/erezsh/reladiff) and
|
|
663
|
+
[sqeleton](https://github.com/erezsh/sqeleton) (both MIT, by Erez Shinan); see [LICENSE.md](https://github.com/sarath-mec/diffdb-core/blob/main/LICENSE.md).
|