Metadata-Version: 2.4
Name: diffdb-core
Version: 0.1.0
Summary: Cross-database table diffing by recursive checksum bisection, with declarative YAML SQL dialects
Author: Sarath Mohan
License: MIT
Project-URL: Homepage, https://github.com/sarath-mec/diffdb-core
Project-URL: Documentation, https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md
Project-URL: Issues, https://github.com/sarath-mec/diffdb-core/issues
Keywords: database,diff,data-validation,migration,checksum,oracle,postgresql
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: dsnparse>=0.2.0
Requires-Dist: pyyaml>=6.0
Provides-Extra: oracle
Requires-Dist: oracledb>=2.0.0; extra == "oracle"
Provides-Extra: postgresql
Requires-Dist: psycopg2-binary>=2.9.0; extra == "postgresql"
Provides-Extra: redshift
Requires-Dist: psycopg2-binary>=2.9.0; extra == "redshift"
Provides-Extra: mysql
Requires-Dist: pymysql>=1.0.0; extra == "mysql"
Provides-Extra: snowflake
Requires-Dist: snowflake-connector-python>=3.0.0; extra == "snowflake"
Requires-Dist: cryptography>=41.0.0; extra == "snowflake"
Provides-Extra: bigquery
Requires-Dist: google-cloud-bigquery>=3.0.0; extra == "bigquery"
Provides-Extra: databricks
Requires-Dist: databricks-sql-connector>=2.0.0; extra == "databricks"
Provides-Extra: duckdb
Requires-Dist: duckdb>=0.9.0; extra == "duckdb"
Provides-Extra: trino
Requires-Dist: trino>=0.320.0; extra == "trino"
Provides-Extra: presto
Requires-Dist: presto-python-client>=0.8.0; extra == "presto"
Provides-Extra: clickhouse
Requires-Dist: clickhouse-driver>=0.2.0; extra == "clickhouse"
Provides-Extra: vertica
Requires-Dist: vertica-python>=1.0.0; extra == "vertica"
Dynamic: license-file

# diffdb-core

Compare tables across different databases without moving the data. `diffdb` pushes a
`count(*)` + checksum query for each key range down to both databases, and recursively splits only the ranges
whose checksums differ. Rows are downloaded only for the small segments that actually contain differences,
then paired by key into a per-row, per-column summary.

Built for validating database migrations (e.g. Oracle → PostgreSQL), where the two sides run on different
engines and a `FULL OUTER JOIN` isn't possible.

- **12 databases** through declarative YAML dialects: PostgreSQL, Oracle, MySQL, Snowflake, BigQuery, Redshift,
  Databricks, DuckDB, Trino, Presto, ClickHouse, Vertica.
- **Any pair**: the source and target can be different engines; each side renders values to the same text before hashing.
- **No metadata reads**: you pass the columns, their native types and optional SQL transform rules, so the
  engine sends only four read-only query shapes and never touches the catalog.
- **Non-unique keys** work: bisection columns need only be selective, and duplicate rows are counted.
- **Per-key summary**: changed rows with their differing columns, source-only and target-only rows, duplicate keys.
- **Telemetry**: every query, row count, checksum and duration can be captured for auditing.

## Install

```bash
pip install "diffdb-core[postgresql,oracle]"   # pick the extras for your databases
```

Extras: `oracle`, `postgresql`, `redshift`, `mysql`, `snowflake`, `bigquery`, `databricks`, `duckdb`, `trino`,
`presto`, `clickhouse`, `vertica`. The package is imported as `diffdb`. Python ≥ 3.12.

## Quick start

```python
from diffdb import connect_to_table, diff_tables

# Every compared column with its native datatype. Source and target are paired by position,
# so both dicts list the columns in the same order (bisection columns first).
src = connect_to_table(
    "oracle://app_user:pwd@oracle-host:1521/ORCL",
    "SALES.CUSTOMER",
    bisection_columns=("CUSTOMER_ID",),
    columns={
        "CUSTOMER_ID": {"datatype": "NUMBER(10,0)"},
        "EMAIL": {"datatype": "VARCHAR2(200)"},
        "BALANCE": {"datatype": "NUMBER(12,2)"},
        "NOTES": {"datatype": "NUMBER(10,0)", "transform_rule": 'DBMS_LOB.GETLENGTH("NOTES")'},  # CLOB -> length
    },
)
tgt = connect_to_table(
    "postgresql://app_user:pwd@pg-host:5432/sales",
    "sales.customer",
    bisection_columns=("customer_id",),
    columns={
        "customer_id": {"datatype": "bigint"},
        "email": {"datatype": "varchar(200)"},
        "balance": {"datatype": "numeric(12,2)"},
        "notes": {"datatype": "integer", "transform_rule": 'LENGTH("notes")'},
    },
)

diff = diff_tables(src, tgt)
try:
    summary = diff.summarize(limit=1000)  # stop after 1000 differing keys
finally:
    diff.close()

print(summary.changed, summary.source_only, summary.target_only, summary.limit_reached)
for kd in summary.key_diffs:  # kind: changed | source_only | target_only | duplicate_key
    if kd.kind == "changed":
        for cd in kd.column_diffs:
            print(kd.key, cd.target_column, cd.source_value, "->", cd.target_value)
    else:  # source_only | target_only | duplicate_key: the unpaired rows
        print(kd.key, kd.kind, kd.source_rows, kd.target_rows)
```

Rows are paired into `changed` results by `key_columns`, which default to the bisection columns; see
[Keys and the per-key summary](#keys-and-the-per-key-summary).

You can also iterate the raw stream (`for sign, row in diff_tables(...)`, with `-` = source only and `+` = target
only), get counts with `get_stats_dict()`, and capture every query with `track_queries=True, return_queries=True`.
See [ARCHITECTURE.md](https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md#6-python-api-reference--practical-recipes) for these recipes.

### Connections

`connect()` / `connect_to_table()` take a URI (`postgresql://user:pwd@host:5432/db`) or a dict whose `driver` is
one of the schemes above and whose other keys go to that database's Python driver:

```python
import diffdb

pg = diffdb.connect({"driver": "postgresql", "host": "pg-host", "port": 5432, "database": "sales",
                     "user": "app_user", "password": "..."})
ora = diffdb.connect({"driver": "oracle", "user": "app_user", "password": "...",
                      "dsn": "oracle-host:1521/ORCLPDB1"}, thread_count=4)
```

An existing `Database` can be passed to `connect_to_table()` instead of a URI, so one connection pool serves many tables.

## How it works

1. **Divide**: the key space of `bisection_columns` (from `min`/`max`) is split into `bisection_factor` ranges (default 32).
2. **Checksum**: for each range, both databases compute `count(*)` and the sum of a 60-bit integer taken from the MD5
   of each row, where the row is its normalized columns joined with `'|'`.
3. **Recurse**: ranges with equal counts and checksums are done. The others are split again until they hold fewer
   rows than `bisection_threshold` (default 16,384).
4. **Download & compare**: only those small ranges are downloaded and compared in memory.
5. **Summarize**: `summarize()` pairs the differing rows by `key_columns` (default: the bisection columns).

For a table bisected on `(ADDRESS_SK, ORACLE_COLUMN_NAME)` the checksum queries look like this. Oracle (database
character set isn't AL32UTF8, so the row is converted first, to hash the same bytes as PostgreSQL; detected from
`NLS_CHARACTERSET` or forced with a `hash_charset` connection setting):

```sql
SELECT
  count(*),
  sum(to_number(substr(standard_hash(CONVERT((
        NVL(to_char("ADDRESS_SK", 'FM99999999999999999999999999999999999999'), '<null>')
    ||  '|'  ||  NVL("ORACLE_COLUMN_NAME", '<null>')
    ||  '|'  ||  NVL(to_char(cast(("UPDATE_TMSTMP" + INTERVAL '+5' HOUR) as timestamp(6)), 'YYYY-MM-DD HH24:MI:SS.FF6'), '<null>')
    ||  '|'  ||  NVL("UPDATE_USER_ID", '<null>')
  ), 'AL32UTF8'), 'MD5'), 18), 'xxxxxxxxxxxxxxx'))
FROM "SALES"."ADDRESS_AUDIT"
WHERE ("ADDRESS_SK" >= 1405) AND ("ORACLE_COLUMN_NAME" >= 'active_ind')
  AND ("ADDRESS_SK" < 2662) AND ("ORACLE_COLUMN_NAME" < 'dffkhzQ2yoa4QcQl')
```

PostgreSQL (with a `COLLATE "C"` transform rule on the string bisection column, see Limitations):

```sql
SELECT
  count(*),
  sum(('x' || substring(md5((
        coalesce("address_sk"::varchar, '<null>')
    ||  '|'  ||  coalesce(("oracle_column_name" COLLATE "C"), '<null>')
    ||  '|'  ||  coalesce(to_char("update_tmstmp"::timestamp(6), 'YYYY-mm-dd HH24:MI:SS.US'), '<null>')
    ||  '|'  ||  coalesce("update_user_id", '<null>')
  )), 18))::bit(60)::bigint)
FROM "sales"."address_audit"
WHERE ("address_sk" >= 1405) AND (("oracle_column_name" COLLATE "C") >= 'active_ind')
  AND ("address_sk" < 2662) AND (("oracle_column_name" COLLATE "C") < 'dffkhzQ2yoa4QcQl')
```

## Defining columns

`TableSegment` (or `connect_to_table`) takes:

| Argument | Meaning |
| :--- | :--- |
| `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. |
| `columns` | `{name: {"datatype": "<native type>", "transform_rule": "<sql>"}}` for every compared column, bisection columns included. `transform_rule` replaces the column (wrapped in parentheses); `datatype` is then the type of the expression's result. |
| `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). |
| `where` | Optional SQL filter added to every query, e.g. a time window. |

All problems with `columns` (missing datatype, unknown or unsupported type, bisection column not listed) are
reported together in one `ValueError`.

**Types.** The engine compares numbers, strings, timestamps/dates and booleans (hashed as `1`/`0`); `NULL` is
`'<null>'` on every side. LOB and binary types (`CLOB`, `BLOB`, `RAW`, `bytea`, …) are rejected on purpose: reduce
them with a `transform_rule` (e.g. a length). When the two sides declare different precisions, both are compared
at the lower one. An unscaled decimal (Oracle `NUMBER`, PostgreSQL `numeric`) is compared as a whole number, with a
warning; declare a scale on both sides (`NUMBER(12,2)` / `numeric(12,2)`) to compare decimals.

## Keys and the per-key summary

The diff itself works on whole rows: a range whose checksums differ is downloaded, and every row that isn't
present on the other side, value for value, comes out as `('-', row)` (source only) or `('+', row)` (target only).
`key_columns` decide how `summarize()` and `get_stats_dict()` turn those rows into results. They are never sent to
the database and don't change which rows are compared.

- **Bisection columns vs key columns**: `bisection_columns` split the table into ranges (they should be indexed);
  `key_columns` say which rows are "the same row" (usually the primary key). The default is the bisection columns.
- **Positions, not names**: the two sides are paired by column position, so the key columns must sit at the same
  positions in both `columns` dicts; `diff_tables` checks this before running any query.
- **Not unique**: keys may repeat. Nothing in the database is checked.
- **Include every bisection column** in the key when you can. Both versions of a key then land in the same range, so
  pairing stays exact even when `summarize(limit=N)` stops the run early.

### How rows become `key_diffs`

All differing rows are grouped by key. Rows that appear identically on both sides cancel out first, so only the
leftover rows of a key decide its `kind`:

| Leftover rows for a key | `kind` | What the `KeyDiff` holds | Counted in |
| :--- | :--- | :--- | :--- |
| 1 source, 1 target | `changed` | `column_diffs`: the differing columns, with both sides' names and values | `changed` (1) |
| source only (1 or more) | `source_only` | `source_rows` | `source_only` (one per row) |
| target only (1 or more) | `target_only` | `target_rows` | `target_only` (one per row) |
| 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) |

`summary.duplicate_keys` is `True` when any key had more than one leftover row on a side. Rows hold the values as
downloaded (normalized strings), in `columns` order with the bisection columns first.

For example, with `key_columns=("ORDER_ID", "LINE_NO")` these differing rows:

```text
-  (1, 1, QTY 5)    +  (1, 1, QTY 6)                       one row each side
-  (2, 1, QTY 3)                                           source only
                    +  (3, 1, QTY 9)                       target only
-  (4, 1, QTY 2)    +  (4, 1, QTY 8)                       key 4 is duplicated in the source:
-  (4, 1, QTY 7)                                           2 source rows, 1 target row
```

summarize to (`summary.as_dict()["key_diffs"]`, abridged):

```text
key ["1","1"]  changed        column_diffs [QTY/qty: "5" -> "6"]
key ["2","1"]  source_only    source_rows [["2","1","3"]]
key ["3","1"]  target_only    target_rows [["3","1","9"]]
key ["4","1"]  duplicate_key  source_rows [["4","1","2"], ["4","1","7"]]   target_rows [["4","1","8"]]

counts: changed 1, source_only 3, target_only 2; duplicate_keys: true
```

Duplicates often look like ordinary differences, because matching copies cancel:

| Source rows for a key | Target rows | Reported as |
| :--- | :--- | :--- |
| `A`, `A` | `A`, `A` | nothing (identical) |
| `A`, `A` | `A` | `source_only` with one row `A` (the extra copy); `duplicate_keys` stays `False` |
| `A`, `B` | `A`, `C` | `changed`, `B` → `C` (the `A` copies cancel) |
| `B`, `C` | `D` | `duplicate_key`: no way to tell which source row became `D` |

Use a key that is unique in your data when you need every difference to be a `changed` row. Use `duplicate_key`
entries and `duplicate_keys` as the signal to look at the rows yourself.

## Known limitations

- **String collation**: Oracle sorts strings by bytes, PostgreSQL by its collation by default, so the same key
  range selects different rows. Add `COLLATE "C"` as the PostgreSQL `transform_rule` of string bisection columns.
  That bypasses the default index (create one with `COLLATE "C"`), so prefer numeric bisection columns.
- **Alphanumeric keys**: string bisection keys may only contain `space - . 0-9 A-Z _ a-z`
  (`diffdb/geometry/arithmetic.py`). Bisect on another column when keys contain other characters.
- **Oracle 4000-byte limit**: the row string must fit in a `VARCHAR2` (`ORA-01489` otherwise). Compare very wide
  text columns through a transform rule such as `LENGTH(col)`.
- **Live data**: rows changing during a run show up as differences. Restrict `where` to a stable window.
- **Character sets**: values both drivers decode to the same Unicode text compare equal at row level, but a
  checksum mismatch still costs a download of that segment.

## Adding a database

1. A YAML dialect in `src/diffdb/databases/dialects/<db>.yaml` that `extends: _base.yaml` and declares its SQL
   fragments, type mapping and normalization templates. `_base.yaml` documents every key; unknown keys, type
   classes and template placeholders are rejected when the dialect loads.
2. A small driver class in `src/diffdb/databases/<db>.py` (driver import and connection creation), registered in
   `DATABASE_BY_SCHEME` (`src/diffdb/databases/_connect.py`).

The new dialect must render every value byte-identically to its counterpart. See
[ARCHITECTURE.md](https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md#4-declarative-yaml-dialect-framework).

## Development

```bash
uv sync                      # installs the package with pytest, ruff and duckdb
uv run pytest                # no external database needed
uv run ruff check .
```

The tests include unit tests, a DuckDB end-to-end diff with planted differences, and golden snapshots of the SQL
every dialect generates (`tests/golden/`). After an intended dialect or SQL change, regenerate and review them:

```bash
DIFFDB_UPDATE_GOLDEN=1 uv run python -m unittest tests.test_dialects tests.test_query_snapshot
```

## License

MIT. `diffdb` adapts code from [reladiff](https://github.com/erezsh/reladiff) and
[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).
