Skip to main content

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. (The one exception: an Oracle connection reads NLS_CHARACTERSET once when it opens, unless hash_charset is given.)
  • 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

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

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.

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 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:

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 (ORDER_ID, LINE_CODE), with columns ORDER_ID NUMBER(12,0) / bigint, LINE_CODE VARCHAR2(20) / varchar(20), UPDATED_AT TIMESTAMP(6) / timestamp(6) and UPDATED_BY VARCHAR2(30) / varchar(30), 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):

SELECT
  count(*),
  sum(to_number(substr(standard_hash(CONVERT((
        NVL(to_char("ORDER_ID", 'FM99999999999999999999999999999999999999'), '<null>')
    ||  '|'  ||  NVL("LINE_CODE", '<null>')
    ||  '|'  ||  NVL(to_char(cast("UPDATED_AT" as timestamp(6)), 'YYYY-MM-DD HH24:MI:SS.FF6'), '<null>')
    ||  '|'  ||  NVL("UPDATED_BY", '<null>')
  ), 'AL32UTF8'), 'MD5'), 18), 'xxxxxxxxxxxxxxx'))
FROM "SALES"."ORDER_LINE"
WHERE ("ORDER_ID" >= 1405) AND ("LINE_CODE" >= 'A-001')
  AND ("ORDER_ID" < 2662) AND ("LINE_CODE" < 'K-250')

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

SELECT
  count(*),
  sum(('x' || substring(md5((
        coalesce("order_id"::varchar, '<null>')
    ||  '|'  ||  coalesce(("line_code" COLLATE "C"), '<null>')
    ||  '|'  ||  coalesce(to_char("updated_at"::timestamp(6), 'YYYY-mm-dd HH24:MI:SS.US'), '<null>')
    ||  '|'  ||  coalesce("updated_by", '<null>')
  )), 18))::bit(60)::bigint)
FROM "sales"."order_line"
WHERE ("order_id" >= 1405) AND (("line_code" COLLATE "C") >= 'A-001')
  AND ("order_id" < 2662) AND (("line_code" COLLATE "C") < 'K-250')

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.
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:

-  (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):

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.

Development

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:

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

License

MIT. diffdb adapts code from reladiff and sqeleton (both MIT, by Erez Shinan); see LICENSE.md.

Metadata

Release files for diffdb-core 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for diffdb-core 0.1.1
File Size Uploaded Provenance Actions
diffdb_core-0.1.1.tar.gz 84.1 kB Without provenance Details for diffdb_core-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for diffdb-core 0.1.1
File Interpreter ABI Platform Actions
diffdb_core-0.1.1-py3-none-any.whl Python 3 none any Details for diffdb_core-0.1.1-py3-none-any.whl

Total release size: 158.6 kB

Release files / diffdb_core-0.1.1.tar.gz

Download URL diffdb_core-0.1.1.tar.gz
Size 84.1 kB
Tags Source
SHA-256 checksum
How to use checksums
4380da4e5855151da62e70fdbe302b2dd05b600ffb60ee9c13ce4dd8da93cfa6
BLAKE2b-256 checksum
How to use checksums
c4b6e41dbecb58d940635b95a4bf40ce3c0fef3d51b82eb3516979eafb793b70
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.24 {"installer":{"name":"uv","version":"0.9.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / diffdb_core-0.1.1-py3-none-any.whl

Download URL diffdb_core-0.1.1-py3-none-any.whl
Size 74.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d8fb128a7a44d619f8f8ddc37068c6d9b5c88fe6d44cb510fdd5e401e9d43fb9
BLAKE2b-256 checksum
How to use checksums
c855b66d56b68743d0361aea9334a47ab680e0584a4e49921e92b79b86613ad9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.24 {"installer":{"name":"uv","version":"0.9.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for diffdb-core 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page