# dbmerge

> Python library for bulk UPSERT across SQL databases. DBMerge loads a staging table, then inserts new rows and updates changed rows by key. It can optionally delete or mark missing rows for snapshot synchronization. Loaders and write semantics vary by backend.

Install: `pip install dbmerge`. Requires SQLAlchemy 2.x. Accepts `list[dict]`, `dict[str, list]`, `pandas.DataFrame`, `polars.DataFrame`, a database table/view, or a SELECT query (`source_query`, since 2.7.0).

Version note: `DBMerge` is introduced in 2.6.0. With
released versions through 2.5.0, use `from dbmerge import dbmerge as DBMerge`.
Version 2.6.0 retains `dbmerge` as an alias; the logger remains `dbmerge`.

Supported: PostgreSQL, MySQL/MariaDB, SQLite, MS SQL Server, CockroachDB, DuckDB, ClickHouse, Oracle ([COMPATIBILITY.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/COMPATIBILITY.md) lists the drivers and versions). Oracle support has limitations — see [ORACLE.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/ORACLE.md).

## Rules for AI coding assistants

1. **Check the installed DBMerge version** before using new options. Use the compatibility matrix for driver and backend limitations.
2. **Always use a context manager:** `with DBMerge(...) as merge:` and call `merge.exec()` inside it. `exec()` may be called only once per instance.
3. **Never enable deletion implicitly.** `delete_mode` defaults to `'no'`. Only pass `'delete'`/`'mark'` when the user explicitly wants missing rows removed — and then see rule 4.
4. **Delete only from a complete snapshot.** A complete slice needs a matching target `delete_condition`; a batch of changes should keep `delete_mode='no'`. An accepted empty snapshot affects every target row in scope.
5. **Pass `data_types` when the exact column type matters** and `dbmerge` may create the table or column. Auto-detection infers a type from a sample value, so it cannot know the precision and scale of a decimal, the length of a string, or your timezone policy. A type given in `data_types` is never second-guessed, even if the engine then refuses to create the column from it.
6. **`key` must be non-null and unique**, and should be backed by a primary key or unique index in the target table.
7. Conditions (`delete_condition`, `update_condition`, `insert_condition`, `source_condition`) must be SQLAlchemy expressions built on `merge.table.c`, `merge.temp_table.c` or `merge.source_table.c` — never strings.

## Constructor parameters

`DBMerge(engine, table_name, data=None, ...)`

| Parameter | Meaning |
|---|---|
| `engine` | SQLAlchemy `Engine` from `create_engine()`. For ClickHouse also a clickhouse-connect client. |
| `table_name` | Target table. |
| `data` | Python source rows. Supply exactly one of `data`, `source_table_name`, or `source_query`. All dict rows must have the same keys; DataFrame column names must be unique. |
| `source_table_name` / `source_schema` | Read the source straight from a table or view instead of Python memory. |
| `source_query` | SQL string or SQLAlchemy SELECT/text on the merge connection. Use uniquely named output columns, bind runtime values, and qualify schemas in the query (not via `source_schema`). |
| `key` | List of column names forming the unique key. Defaults to the target's primary key; **required** when the table does not exist yet. Key values always come from your data, so a key column DBMerge creates is never `AUTO_INCREMENT`/`SERIAL`/`IDENTITY`. |
| `delete_mode` | `'no'` (default), `'delete'`, `'mark'`. |
| `delete_mark_field` | Column flagged when a row is missing from the source. Must be a **dedicated** Boolean or Integer column. On MySQL/MariaDB a `BOOLEAN` is really `TINYINT(1)`, so the flag reads back as `0`/`1`. |
| `merged_on_field` / `inserted_on_field` | Managed timestamps; values supplied in the source are ignored. Untracked merges use the destination clock; tracked merges sample the journal clock per write phase. |
| `delete_mark_values` | `{'col': value}` written on a row when it is marked deleted, in addition to the flag (e.g. a load id). Requires `delete_mode='mark'`. |
| `skip_update_fields` | Columns written on insert only, never on update — and therefore never compared either. |
| `skip_compare_fields` | Columns written but never compared: they do not cause an update on their own, but are written when the row is updated for another reason. For a column that changes on every load (a load id) and would otherwise make every row look modified. |
| `data_types` | `{'col': SQLAlchemyType()}` used when creating tables/columns. |
| `schema` / `temp_schema` | Target and staging schema. `schema` is **required** for MySQL/MariaDB (set it to the database name). |
| `can_create_table` / `can_create_columns` / `can_create_schemas` | All default to `True`. Set to `False` in production against a migration-managed schema. |
| `tracker` / `lease_options` / `lease_handle` / `use_safe_border` | Optional tracking and coordination. A lease needs a tracker; choose lease options or a borrowed handle, not both. Safe-border protection requires tracking, a timestamp `merged_on_field`, and `delete_mode='no'` or `'mark'`. |

`exec(delete_condition=None, source_condition=None, update_condition=None, insert_condition=None, commit_all_steps=None, chunk_size=None, bulk_load=None)` inherits execution defaults from the constructor (normally `commit_all_steps=True`, `bulk_load=True`). It returns a `mergeResult` with `total_row_count`, `inserted_row_count`, `updated_row_count`, `deleted_row_count`, `total_time`, `temp_insert_time`, `insert_time`, `update_time`, `delete_time`, `table_created`, `added_fields`. A busy configured lease or acquisition timeout raises `LeaseBusy`; lost ownership raises `LeaseLost`. A successful no-op still returns a result.

`table_created` / `added_fields` report the schema changes the merge made to the target table. `added_fields` is a `{column name: SQLAlchemy type}` mapping — the type each column was really created with, after any adjustment for the target engine. It covers only columns added to an already existing table, never the auto-managed timestamp/delete-flag columns, and stays empty with `can_create_columns=False`. Use them downstream: a dataset built incrementally from a `merged_on_field` watermark can not detect a new column by itself — adding a column moves no watermark — so `added_fields` is the signal to rebuild it in full.

`chunk_size` defaults to 10,000 rows (100,000 for mssql-python bulk copy; 1,000,000 on ClickHouse). `bulk_load=False` selects the generic Python loader where available; it has no effect on ClickHouse or SQL sources. CockroachDB COPY can store out-of-range values differently from the generic loader. ClickHouse uses native loading for `Point` even with Arrow installed.

Phases run in this order: staging load → `UPDATE` → `INSERT` → `DELETE`/mark.

## 1. Basic upsert

```python
from sqlalchemy import create_engine
from dbmerge import DBMerge

engine = create_engine("sqlite://")
data = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]

with DBMerge(engine=engine, data=data, table_name="users", key=['id']) as merge:
    result = merge.exec()
    print(result.inserted_row_count, result.updated_row_count)
```

## 2. Partial sync with scoped deletion

```python
from datetime import date

# data holds only January 2025 rows, so deletion must be restricted to January.
with DBMerge(engine=engine, data=data, table_name="Sales", key=['id'],
             delete_mode='delete') as merge:
    merge.exec(delete_condition=merge.table.c['Date'].between(date(2025, 1, 1), date(2025, 1, 31)))
```

## 3. Soft delete

```python
# 'is_deleted' must exist for no other purpose: missing rows get 1/True,
# rows present in the source get reset to 0/False.
with DBMerge(engine=engine, data=data, table_name="Sales", key=['id'],
             delete_mode='mark', delete_mark_field='is_deleted') as merge:
    merge.exec()
```

## 4. Conditional update and insert

`update_condition` restricts which existing rows may be overwritten. Rows failing it are left untouched (never deleted); the insert phase is unaffected.

```python
with DBMerge(engine=engine, data=data, table_name="Sales", key=['id']) as merge:
    merge.exec(update_condition=merge.table.c['is_protected'] == False)

# Keep the freshest write when several sources update the same rows:
with DBMerge(engine=engine, data=data, table_name="Sales", key=['id']) as merge:
    merge.exec(update_condition=merge.temp_table.c['updated_at'] >= merge.table.c['updated_at'])
```

`insert_condition` restricts which missing source rows are inserted. Build it on `merge.temp_table.c` — do **not** reference `merge.table.c` directly, because during insert the target row is `NULL` by definition. To inspect other target rows, use a correlated `EXISTS` over `merge.table.alias()`.

```python
from sqlalchemy import exists

with DBMerge(engine=engine, data=data, table_name="Sales", key=['id']) as merge:
    merge.exec(insert_condition=merge.temp_table.c['amount'] > 0)

with DBMerge(engine=engine, data=data, table_name="Sales", key=['id']) as merge:
    g = merge.table.alias()
    guard = ~exists().where((g.c['category'] == merge.temp_table.c['category']) & (g.c['locked'] == True))
    merge.exec(insert_condition=guard)
```

## 5. Materializing a view

```python
with DBMerge(engine=engine, source_table_name="slow_complex_view",
             table_name="fast_materialized_table", key=['id']) as merge:
    merge.exec()
```

## 6. Explicit types and a production-safe configuration

```python
from sqlalchemy import String, Numeric, Double, DateTime

with DBMerge(engine=engine, data=data, table_name="Facts", key=['id'],
             can_create_table=False, can_create_columns=False,
             data_types={'Name': String(100), 'Price': Numeric(12, 2),
                         'Ratio': Double(), 'Ts': DateTime(timezone=True)}) as merge:
    result = merge.exec(commit_all_steps=False)  # one data transaction on transactional backends
```

## Design trade-offs to account for

- **With `delete_mode='delete'` or `'mark'`, absence means deletion or marking within the selected scope.** Use `delete_condition` for a complete slice and leave deletion off for an incremental batch. An accepted empty snapshot affects every target row in scope.
- **`commit_all_steps=True` (the default) is not atomic.** Earlier committed phases survive a failure. On transactional backends, `commit_all_steps=False` groups data writes in one transaction; this does not include DDL or the tracking journal and has no effect on ClickHouse.
- **`commit_all_steps` covers the data, never the schema.** Creating the target table, adding a column and creating or dropping the staging table are always committed on their own, whichever value you pass.
- **The merge key must be unique in the target table.** Duplicates in the *source* are caught automatically by the staging table's primary key (not on ClickHouse), but if the target has no primary key or unique index on the key columns, duplicate rows there are all overwritten with the same source row, silently. That is the database schema's responsibility.
- **Automatic schema creation is a convenience, not a schema tool.** It infers types from sample values and cannot recover precision, scale, length or timezone policy, and each backend resolves the resulting generic type differently. In production, manage the schema with migrations and pass `can_create_table=False, can_create_columns=False`.
- **`delete_mark_field` must be a dedicated flag column.** The mark phase writes `1`/`True` into it and the update phase writes `0`/`False` back, so any other meaning the column carries is destroyed. It cannot be part of `key`, nor the same column as `merged_on_field`/`inserted_on_field` — those combinations are rejected.
- **PostgreSQL/CockroachDB need `JSONB`, not `JSON`** (`from sqlalchemy.dialects.postgresql import JSONB`) — plain `JSON` cannot be compared to detect changes and is rejected.
- **Exceptions** are exported from the package root: `from dbmerge import IncorrectParameter, IncorrectDataError, NoKeyError, TableNotFoundError, TempTableAlreadyExists` (the old `from dbmerge.dbmerge import …` works too), or simply catch `RuntimeError` — all of them subclass it. The package root exports `DBMerge`, `mergeResult`, `drop_table_if_exists`, `format_ms`, `__version__` and these exceptions.

## Audit timestamps

Without tracking, the destination database supplies audit time. With tracking, the journal database supplies time per write phase and the destination type determines how it is stored. These are not commit timestamps. The table below describes untracked merges:

An auto-created audit column is a **naive** timestamp, so the offset is dropped. Give it a timezone-aware type instead — pre-create it, or `data_types={'Merged On': DateTime(timezone=True)}` — and on PostgreSQL/CockroachDB it becomes `timestamptz` and keeps the instant. MySQL/MariaDB have no type that stores an offset; on MS SQL `CURRENT_TIMESTAMP` returns no offset either, so a `datetimeoffset` column would only mislabel server-local time as UTC. The table describes the naive default:

| Engine | Emitted SQL | Timezone of the stored value | Resolution |
|---|---|---|---|
| PostgreSQL / CockroachDB | `now()` | session `TimeZone` (the naive column strips the `timestamptz` offset); CockroachDB defaults to UTC | microseconds |
| MySQL / MariaDB | `NOW(6)` | server `time_zone` | microseconds |
| SQLite | `CURRENT_TIMESTAMP` | always UTC | whole seconds |
| MS SQL Server | `CURRENT_TIMESTAMP` | server timezone | ~3.3 ms |

Do not assume a naive timestamp means UTC. On PostgreSQL/CockroachDB `now()` is the transaction start time. Timestamp-only incremental reads can miss rows at the cutoff; replay an overlapping window or use a commit-ordered change cursor. See [audit timestamps](https://github.com/pavel-v-sobolev/dbmerge/blob/main/DOCUMENTATION.md#audit-timestamps) for other backends and clock details.

## Staging table

Build `source_condition` on `merge.source_table`, not the destination `merge.table`.
Disconnected outer FROM elements raise `IncorrectParameter` before staging INSERT;
linked joins and nested IN/EXISTS queries are supported. Destination deletion scope
uses `delete_condition`. ClickHouse `total_row_count` uses server `written_rows`,
which can include materialized-view side effects rather than only physical staging rows.

Each merge stages its data in a table named `tmp_<yymmddHHMMSS>_<table>_<hex8>`. The timestamp normally comes from the destination clock; the random suffix reduces collisions. Do not drop staging based on age alone: an active merge may still use it.

Since 2.7.2, PostgreSQL and CockroachDB `COPY` preserves literal `%` in identifiers, and both ClickHouse bulk loaders preserve literal dots in staging table names. Pass raw names and supply schemas separately.

Since 2.8.0, mart lease rows store `schema`, `table_name` and phase `scope` separately and use a fresh `id` per acquisition. Stop old mart workers and let their passes finish before starting new workers on the same journal. Watermarks and rebuild state are preserved.

DBMerge attempts cleanup after execution or on context exit. PostgreSQL, SQLite, MariaDB and DuckDB use session-scoped temporary tables. MS SQL Server, CockroachDB and MySQL use regular staging. ClickHouse uses regular staging for hard deletion or a sessionless client; Oracle uses a global temporary table whose definition can survive a crash. See [staging lifetime](https://github.com/pavel-v-sobolev/dbmerge/blob/main/DOCUMENTATION.md#the-staging-table).

## Database-specific notes

- **PostgreSQL:** staging tables are `TEMPORARY`, so they stay out of `shared_buffers` and vanish with the session; `temp_schema` does not apply and is quietly ignored.
- **MySQL/MariaDB:** `schema` is required. A **string column of the merge key** needs an explicit length (`data_types={'col': String(100)}`) because InnoDB shares one 3072-byte index budget between all key columns; other string columns become `LONGTEXT` automatically. Timezone-aware datetimes lose their UTC offset — no MySQL type stores one. Default collation ignores case and trailing spaces, so `'test'` and `' Test'` may not register as a change.
- **SQLite:** no schema support; `schema`/`temp_schema` are reset to `None` with a warning.
- **MS SQL Server:** use pyodbc or mssql-python (SQLAlchemy 2.1+) for a fast staging load; pymssql loads row by row and truncates microseconds to milliseconds.
- **DuckDB:** use a database file: with `:memory:` every connection sees its own database.
- **ClickHouse:** through clickhouse-connect (`clickhousedb://` or its client), server 23.8+. The target must be a `ReplacingMergeTree` whose `ORDER BY` is exactly the merge key; a changed row is written as a new version, so read the table with `FINAL`. No transactions, duplicate source keys are not refused. `source_table_name` can be any table or view ClickHouse reads, a PostgreSQL database attached with its database engine included; an `IN` of one column over a subquery in `source_condition` is run first, so that only the rows it picks are read from PostgreSQL. A `datetime` in a condition is compared as its moment, microseconds included. See the ClickHouse section of DOCUMENTATION.md.
- **CockroachDB:** uses the `sqlalchemy-cockroachdb` dialect over the PostgreSQL wire protocol. `exec(commit_all_steps=False)` is markedly faster: one commit costs a consensus round whatever it carries (200 000 rows inserted in ~6s against ~16s on a single node; no difference on the update phase).

## Docs

- [DOCUMENTATION.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/DOCUMENTATION.md): full API reference, plus a **Data Loss Risks** section covering deletion semantics, type conversion and non-atomic commits.
- [GUIDES.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/GUIDES.md): full and scoped snapshots, plus SQL inputs.
- [TRACKING_AND_MARTS.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/TRACKING_AND_MARTS.md): optional journal, leases and mart lifecycle.
- [README.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/README.md): overview, benchmarks, database-specific limitations.
- [COMPATIBILITY.md](https://github.com/pavel-v-sobolev/dbmerge/blob/main/COMPATIBILITY.md): tested databases, drivers and versions, the bulk staging load of each driver, and where drivers store data differently.
- [user_guide.py](https://github.com/pavel-v-sobolev/dbmerge/blob/main/user_guide.py): runnable advanced examples.
