Upsert¶
rn_forge.sqlalchemy.upsert
¶
Bulk create-or-update by natural key, on PostgreSQL and SQLite.
UpsertCounts(created, updated, skipped)
dataclass
¶
How many input rows :func:upsert created, updated and left unchanged.
upsert(session, model, rows, *, key, fields, actor)
async
¶
Create the rows whose key is absent and update those whose fields differ.
The existing rows are read first, and the counts describe that snapshot. A
writer that commits between the read and the write can make them wrong, so
serialize writers when exact counts matter. Only new and changed rows are
written, with one INSERT … ON CONFLICT (key) DO UPDATE; create_time
and created_by are set on insert only, update_time and updated_by
on both. Never commits: the caller's transaction decides, and rolling back
after the call is a dry run. key must be backed by a unique constraint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
An |
required |
model
|
type[Base]
|
A model using :class: |
required |
rows
|
Sequence[Mapping[str, Any]]
|
One mapping per row, holding every column in key and fields. |
required |
key
|
Sequence[str]
|
The natural-key columns. |
required |
fields
|
Sequence[str]
|
The non-key columns to write. |
required |
actor
|
str
|
Stamped into |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
key is empty, a row lacks a column, or two rows share a key. |
TypeError
|
model does not use |
NotImplementedError
|
The session's dialect is not PostgreSQL or SQLite. |