Skip to content

Commit 37ee410

Browse files
jgraettingersoedirgo
authored andcommitted
add on_conflict to Builder
To allow for upsert resolution on an explicitly identified unique index.
1 parent 84ffd68 commit 37ee410

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/builder.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,38 @@ impl<'a> Builder<'a> {
368368
self
369369
}
370370

371+
/// Resolve upsert conflicts on unique columns other than the primary key.
372+
///
373+
/// # Note
374+
///
375+
/// This informs PostgREST to resolve upsert conflicts through an
376+
/// alternative, unique index other than the primary key of the table.
377+
/// See the related
378+
/// [PostgREST documentation](https://postgrest.org/en/stable/api.html?highlight=upsert#on-conflict).
379+
///
380+
/// # Example
381+
///
382+
/// ```
383+
/// use postgrest::Postgrest;
384+
///
385+
/// let client = Postgrest::new("https://your.postgrest.endpoint");
386+
/// // Suppose `users` are keyed an SERIAL primary key,
387+
/// // but have a unique index on `username`.
388+
/// client
389+
/// .from("users")
390+
/// .upsert(r#"[{ "username": "soedirgo", "status": "online" },
391+
/// { "username": "jose", "status": "offline" }]"#)
392+
/// .on_conflict("username");
393+
/// ```
394+
pub fn on_conflict<T>(mut self, columns: T) -> Self
395+
where
396+
T: Into<String>,
397+
{
398+
self.queries
399+
.push(("on_conflict".to_string(), columns.into()));
400+
self
401+
}
402+
371403
/// Performs an UPDATE using the `body` (in JSON) on the table.
372404
///
373405
/// # Example

tests/client.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ async fn upsert_existing() -> Result<(), Box<dyn Error>> {
8080
let resp = client
8181
.from("users")
8282
.upsert(r#"{"username": "dragarcia", "status": "ONLINE"}"#)
83+
.on_conflict("username")
8384
.execute()
8485
.await?;
8586
let body = resp.text().await?;

0 commit comments

Comments
 (0)