pg-upsert
A Rust library for PostgreSQL UPSERT operations using sqlx.
Features
- Simple macro-based API for defining fields
- Support for
ON CONFLICT DO UPDATEandON CONFLICT DO NOTHING - Optimistic locking with version field support
- Batch upsert for multiple rows
- Runtime-agnostic (you choose: tokio, async-std, etc.)
Installation
Add to your Cargo.toml:
[]
= "0.1"
= { = "0.8", = ["runtime-tokio", "postgres"] }
= "0.4" # Required for date/time field types
Usage
Basic Upsert
use ;
use PgPool;
async
With Version Field (Optimistic Locking)
Only updates if incoming version > existing version:
let rows_affected = upsert.await?;
Do Nothing on Conflict
Insert only, skip if row exists:
let rows_affected = upsert.await?;
Multiple Conflict Fields
let rows_affected = upsert.await?;
Supported Field Types
The fields! macro supports:
- Integers:
i32,i64 - Floats:
f32,f64 - Strings:
String,&str - Booleans:
bool - Bytes:
Vec<u8> - Date/Time:
chrono::NaiveDate,chrono::NaiveTime,chrono::NaiveDateTime,chrono::DateTime<Utc> - Optional:
Option<T>(becomes NULL when None)
use ;
fields!
Builder Pattern for Options
let options = new
.with_version_field
.with_do_nothing_on_conflict;
License
MIT