Metadata-Version: 2.5
Name: dbmerge
Version: 2.7.2
Summary: Bulk UPSERT and snapshot synchronization for Python and SQL sources across PostgreSQL, MySQL/MariaDB, SQLite, MS SQL Server, CockroachDB, DuckDB, ClickHouse and Oracle.
Project-URL: Homepage, https://github.com/pavel-v-sobolev/dbmerge
Project-URL: Issues, https://github.com/pavel-v-sobolev/dbmerge/issues
Project-URL: Documentation, https://github.com/pavel-v-sobolev/dbmerge/blob/main/DOCUMENTATION.md
Project-URL: Examples, https://github.com/pavel-v-sobolev/dbmerge/blob/main/user_guide.py
Project-URL: Repository, https://github.com/pavel-v-sobolev/dbmerge
Project-URL: Changelog, https://github.com/pavel-v-sobolev/dbmerge/blob/main/CHANGELOG.md
Author-email: Pavel Sobolev <pavel-v-sobolev@yandex.ru>
License-Expression: MIT
License-File: LICENSE
Keywords: bulk-insert,clickhouse,cockroachdb,data-engineering,database,database-sync,duckdb,dwh,etl,mariadb,merge,mssql,mysql,oracle,pandas,polars,postgres,python,sql,sql-server,sqlalchemy,sqlite,synchronization,upsert
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Database
Classifier: Topic :: Database :: Front-Ends
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: alembic>=1.13.0
Requires-Dist: sqlalchemy>=2.0.23
Provides-Extra: clickhouse
Requires-Dist: clickhouse-connect>=1.9; extra == 'clickhouse'
Requires-Dist: pyarrow; extra == 'clickhouse'
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: clickhouse-connect>=1.9; extra == 'dev'
Requires-Dist: duckdb-engine; extra == 'dev'
Requires-Dist: mariadb>=1.1.5; extra == 'dev'
Requires-Dist: mysql-connector-python; extra == 'dev'
Requires-Dist: pandas>=2.0.1; extra == 'dev'
Requires-Dist: pg8000; extra == 'dev'
Requires-Dist: polars; extra == 'dev'
Requires-Dist: psycopg2>=2.9; extra == 'dev'
Requires-Dist: psycopg[binary]; extra == 'dev'
Requires-Dist: pyarrow; extra == 'dev'
Requires-Dist: pymysql; extra == 'dev'
Requires-Dist: pyodbc; extra == 'dev'
Requires-Dist: pytest>=7.1.1; extra == 'dev'
Requires-Dist: sqlalchemy-cockroachdb; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Requires-Dist: ydb-sqlalchemy; extra == 'dev'
Provides-Extra: oracle
Requires-Dist: oracledb>=2; extra == 'oracle'
Provides-Extra: pandas
Requires-Dist: pandas>=2.0.1; extra == 'pandas'
Provides-Extra: polars
Requires-Dist: polars; extra == 'polars'
Description-Content-Type: text/markdown

<p align="left">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/pavel-v-sobolev/dbmerge/main/assets/logo_dark.png">
    <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/pavel-v-sobolev/dbmerge/main/assets/logo_light.png">
    <img alt="dbmerge logo" src="https://raw.githubusercontent.com/pavel-v-sobolev/dbmerge/main/assets/logo_light.png" width="500">
  </picture>
</p>

**DBMerge** is a Python library for bulk **UPSERT** across SQL databases: it inserts new rows and updates existing rows only when their values change. For snapshot synchronization, it can also delete or mark target rows missing from the source. The same Python API works across supported databases without dialect-specific merge statements in your code.

[![PyPI version](https://img.shields.io/pypi/v/dbmerge.svg)](https://pypi.org/project/dbmerge/)
[![Python versions](https://img.shields.io/pypi/pyversions/dbmerge.svg)](https://pypi.org/project/dbmerge/)

[![PostgreSQL](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_postgresql.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_postgresql.yml) [![MariaDB](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_mariadb.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_mariadb.yml) [![SQLite](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_sqlite.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_sqlite.yml) [![MS SQL](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_mssql.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_mssql.yml) [![CockroachDB](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_cockroach.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_cockroach.yml) [![MySQL](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_mysql.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_mysql.yml) [![DuckDB](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_duckdb.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_duckdb.yml) [![ClickHouse](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_clickhouse.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_clickhouse.yml) [![Oracle](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_oracle.yml/badge.svg)](https://github.com/pavel-v-sobolev/dbmerge/actions/workflows/test_oracle.yml)


## Overview
**Common problems solved**

- **Efficient bulk upsert with conflict resolution** - Insert or update records in bulk without writing complex SQL. DBMerge automatically handles primary key conflicts: existing rows are updated, new rows are inserted.
- **Update rows only when values change** - Automatically compares source data against the target table and skips writes for unchanged rows, reducing database load and I/O.
- **Materialize complex views** - Persist results of heavy computations to a physical table for fast querying, supporting also partial data updates.

**DBMerge accepts multiple data sources as input:**
- Pandas/Polars DataFrame
- Lists of dictionaries / Dictionary of Lists
- Database table, view, or SQL query

DBMerge automates data update process by comparing your source data against the target table and automatically performing the required operations.

- **Insert** new records that do not exist in the target table.
- **Update** existing records only if their values have changed.
- **Delete (or mark)** existing records in the target table that are no longer present in the source data.

To ensure optimal performance, the library loads your data into a temporary table first, and then executes bulk synchronization queries.


## Supported Databases
Tested and verified with:
- PostgreSQL
- MariaDB / MySQL
- SQLite
- MS SQL Server
- CockroachDB
- DuckDB
- ClickHouse
- Oracle

[COMPATIBILITY.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/COMPATIBILITY.md) lists the tested drivers and versions.

## Installation

```bash
pip install dbmerge
```

Optional extras for specific databases:

```bash
pip install 'dbmerge[oracle]'      # python-oracledb
pip install 'dbmerge[clickhouse]'  # clickhouse-connect + pyarrow
```

## Quick Start Example

The library uses a context manager to handle database connections and ensure resources are safely released.


```python
from sqlalchemy import create_engine, text
from datetime import date
from dbmerge import DBMerge

# 1. Initialize DB engine
engine = create_engine("sqlite://")

# 2. Prepare your source data
data = [
    {'Shop': '123', 'Product': 'A1', 'Date': date(2025, 1, 1), 'Qty': 2, 'Price': 50.10},
    {'Shop': '124', 'Product': 'A1', 'Date': date(2025, 1, 1), 'Qty': 1, 'Price': 100.50}
]

# 3. Execute the merge operation
# The table will be created automatically if it doesn't exist.
with DBMerge(engine=engine, data=data, table_name="Facts",
             key=['Shop', 'Product', 'Date']) as merge:
    result = merge.exec()

```

This example uses only SQLite and SQLAlchemy: no database server, pandas or
polars is required. Run `python quick_start.py` from a source checkout after
installing the project with `pip install -e .`. The first merge creates `Facts`;
repeating the same data against a persistent database makes no row changes.
The default `delete_mode='no'` keeps target rows absent from the input. Do not
enable deletion for a partial snapshot without a `delete_condition`.

### Choose the guide for your task

| Task | Start here |
|---|---|
| Load new and changed rows without deleting anything | Quick start above |
| Make a target table match a full snapshot | [Full snapshot](https://github.com/pavel-v-sobolev/dbmerge/blob/main/GUIDES.md#full-snapshot) |
| Reconcile one month, shop, or tenant from a complete snapshot | [Scoped snapshot](https://github.com/pavel-v-sobolev/dbmerge/blob/main/GUIDES.md#scoped-snapshot) |
| Refresh a table from a SQL table, view, or query | [SQL sources](https://github.com/pavel-v-sobolev/dbmerge/blob/main/GUIDES.md#sql-sources) |
| Load PostgreSQL data directly into ClickHouse | [PostgreSQL to ClickHouse](https://github.com/pavel-v-sobolev/dbmerge/blob/main/POSTGRESQL_TO_CLICKHOUSE.md) |
| Refresh a derived table when its sources change (**beta**) | [Marts](https://github.com/pavel-v-sobolev/dbmerge/blob/main/TRACKING_AND_MARTS.md#marts) |
| Track merges and coordinate concurrent writers (**beta**) | [Tracking and leases](https://github.com/pavel-v-sobolev/dbmerge/blob/main/TRACKING_AND_MARTS.md#tracking) |

## Key Features

- **Portable API:** The same merge workflow runs across supported backends. Column types, transaction guarantees and native loaders vary by database.
- **Set-based writes:** Loads a staging table and reconciles rows in bulk; the loader and staging lifetime depend on the backend.
- **Smart Deletion:** Supports scoped deletion. You can pass a SQLAlchemy logical expression to delete missing data only within a specific timeframe or subset (e.g., updating only a single month).
- **Auto-Schema Management:** Automatically creates missing tables or columns in the database.
- **Audit:** Optional parameters to automatically add `merged_on` and `inserted_on` timestamps to track when rows were created or modified.
- **Statistics:** Measures number of updated/inserted/deleted rows, total time and time for each operation step.


## Benchmark

DBMerge handles the entire reconciliation process (staging, comparing, updating, inserting) with solid performance, scaling well even for larger datasets.

Here is a rough performance comparison for synchronizing data of different sizes using DBMerge (measured on a developer laptop with an Intel Core i5-1235U, the driver in parentheses):

| Database | DBMerge (100k rows) | DBMerge (1mil rows) |
|----------|---------------------|---------------------|
| **DuckDB** (duckdb_engine) | ~0.3s | ~1.7s |
| **ClickHouse** (clickhouse-connect) | ~0.4s | ~4.1s |
| **SQLite** (sqlite3) | ~0.7s | ~7.7s |
| **Oracle** (python-oracledb) | ~0.8s | ~9.5s |
| **PostgreSQL** (psycopg2) | ~1.2s | ~7.5s |
| **MS SQL Server** (mssql-python) | ~1.1s | ~6.2s |
| **MariaDB** (mariadb) | ~1.0s | ~12.1s |
| **MySQL** (PyMySQL) | ~2.2s | ~25.4s |
| **CockroachDB** (psycopg2) | ~2.7s | ~47s |

The staging table is loaded in bulk where the driver allows it: `COPY FROM STDIN` on PostgreSQL and CockroachDB, bulk copy on MS SQL Server, Arrow on DuckDB and ClickHouse, array DML (`executemany`) on Oracle. The other drivers of PostgreSQL (`psycopg`, `pg8000`) and CockroachDB (`psycopg`) are within a few percent of `psycopg2`; on MS SQL Server `pyodbc` takes ~1.7s / ~14.6s and `pymssql`, which loads row by row, ~11s for 100k rows. See [COMPATIBILITY.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/COMPATIBILITY.md#bulk-staging-load) for every driver.


## Database-Specific Notes & Limitations

- **PostgreSQL:** 
  - Staging tables are real `TEMPORARY` tables, they are invisible to other connections and vanish with the session. `temp_schema` does not apply here and is quietly ignored — PostgreSQL keeps temporary tables in its own session schema.
  - `JSONB` type is supported, but not `JSON` (as it cannot be compared to detect changes).
- **MariaDB / MySQL:** 
  - Does not detect changes in uppercase vs. lowercase or space padding by default (e.g., `'test' == ' Test'`). If this is important, you need to change the collation settings in your database.
  - The schema is treated the same as the database, but schema settings are still supported by this library.
  - A **string column of the merge key** needs an explicit length, because InnoDB shares one 3072-byte index budget between all columns of the key (e.g., `data_types={'Your Key Field': String(100)}`). Other string columns are created as `LONGTEXT` automatically.
  - Timezone-aware datetimes lose their UTC offset: no MySQL/MariaDB type stores one. Normalize to UTC before merging if the offset matters.
  - A `BOOLEAN` column is stored as `TINYINT(1)`, so a `delete_mark_field` there holds `0`/`1` rather than `False`/`True`.
  - The staging table is `TEMPORARY` on MariaDB and a regular table on MySQL, which can not refer to one temporary table twice in a statement.
- **SQLite:** Does not support schemas. If a schema setting is provided, it is automatically reset to `None` with a warning.
- **MS SQL Server:** Use `pyodbc` or `mssql-python` for a fast staging load. `pymssql` loads row by row and keeps milliseconds only.
- **CockroachDB:** Uses the official `sqlalchemy-cockroachdb` dialect (over `psycopg2` or `psycopg`); speaks the PostgreSQL wire protocol.
  - `exec(commit_all_steps=False)` groups data writes in one transaction, not DDL. On a single-node benchmark, merging 200,000 rows took ~6s versus ~16s with step commits; the update phase showed no difference. A larger transaction can require a serialization retry.
- **Oracle:** Through `python-oracledb` (`pip install dbmerge[oracle]`), tested on XE 21c in Thin mode. Staging uses a `GLOBAL TEMPORARY` table and array DML. Inferred strings become `CLOB` (a string key needs an explicit `String(length)`), datetimes become `TIMESTAMP`, and floats become `BINARY_DOUBLE`. DBMerge does not create Oracle users. See [Oracle support](https://github.com/pavel-v-sobolev/dbmerge/blob/main/ORACLE.md) for JSON, LOB and other type limitations.
- **DuckDB:** Use a database file: with `duckdb:///:memory:` every connection gets a database of its own.
- **ClickHouse:** Through `clickhouse-connect` (`pip install dbmerge[clickhouse]`). The target must be a `ReplacingMergeTree` ordered by the merge key; a changed row is written as a new version, so read the table with `FINAL`. See [ClickHouse](https://github.com/pavel-v-sobolev/dbmerge/blob/main/DOCUMENTATION.md#clickhouse).

## Data Loss Risks

DBMerge modifies your target table in bulk, and three deliberate design trade-offs that may have negative effects on your data:
- `delete_mode='delete'` or `'mark'` without `delete_condition` treats the source as a **complete** snapshot. An accepted empty source affects every target row.
- automatic schema creation with default `can_create_table=True` and `can_create_columns=True` infers column types from a sample of your data.
- default `commit_all_steps=True` commits each phase separately, so a failure leaves a partial result.

Read [Data Loss Risks](https://github.com/pavel-v-sobolev/dbmerge/blob/main/DOCUMENTATION.md#data-loss-risks) for the full list and the pre-merge checklist.

## Change Tracking & Marts (beta)

Beyond a single merge, DBMerge ships two optional layers that turn merges into a coordinated pipeline:

- **`MergeTracker`** (`dbmerge.tracking`) journals opted-in writes. Consumers can ask whether a table changed since a timestamp (`is_changed_since`), inspect its last finished operation (`last_merge`), or bound their progress while a tracked writer is active (`safe_boundary`).
- **`MartLoop`** (`dbmerge.mart`) registers a derived table (a *mart*), performs an initial rebuild without requiring a journal change, then refreshes it when its declared sources change. Sources must be ready before enabling the loop.

See [Tracking and Marts](https://github.com/pavel-v-sobolev/dbmerge/blob/main/TRACKING_AND_MARTS.md) for the full reference and [examples/product_daily_sales.py](https://github.com/pavel-v-sobolev/dbmerge/blob/main/examples/product_daily_sales.py) for a ready-to-run template.

## Documentation

- [Full Module Documentation](https://github.com/pavel-v-sobolev/dbmerge/blob/main/DOCUMENTATION.md)
- [Merge recipes](https://github.com/pavel-v-sobolev/dbmerge/blob/main/GUIDES.md)
- [Advanced Examples (Python)](https://github.com/pavel-v-sobolev/dbmerge/blob/main/user_guide.py)
- [Compatibility matrix](https://github.com/pavel-v-sobolev/dbmerge/blob/main/COMPATIBILITY.md)
- [Oracle support](https://github.com/pavel-v-sobolev/dbmerge/blob/main/ORACLE.md)
- [ClickHouse guide](https://github.com/pavel-v-sobolev/dbmerge/blob/main/CLICKHOUSE.md) ([RU](https://github.com/pavel-v-sobolev/dbmerge/blob/main/CLICKHOUSE_RU.md))
- [Tracking and Marts](https://github.com/pavel-v-sobolev/dbmerge/blob/main/TRACKING_AND_MARTS.md)
- [Development, tests and release checks](https://github.com/pavel-v-sobolev/dbmerge/blob/main/CONTRIBUTING.md)
