Skip to content

Commit

Permalink
add on_conflict to Builder
Browse files Browse the repository at this point in the history
To allow for upsert resolution on an explicitly identified unique index.
  • Loading branch information
jgraettinger authored and soedirgo committed May 4, 2022
1 parent 84ffd68 commit 37ee410
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,38 @@ impl<'a> Builder<'a> {
self
}

/// Resolve upsert conflicts on unique columns other than the primary key.
///
/// # Note
///
/// This informs PostgREST to resolve upsert conflicts through an
/// alternative, unique index other than the primary key of the table.
/// See the related
/// [PostgREST documentation](https://postgrest.org/en/stable/api.html?highlight=upsert#on-conflict).
///
/// # Example
///
/// ```
/// use postgrest::Postgrest;
///
/// let client = Postgrest::new("https://your.postgrest.endpoint");
/// // Suppose `users` are keyed an SERIAL primary key,
/// // but have a unique index on `username`.
/// client
/// .from("users")
/// .upsert(r#"[{ "username": "soedirgo", "status": "online" },
/// { "username": "jose", "status": "offline" }]"#)
/// .on_conflict("username");
/// ```
pub fn on_conflict<T>(mut self, columns: T) -> Self
where
T: Into<String>,
{
self.queries
.push(("on_conflict".to_string(), columns.into()));
self
}

/// Performs an UPDATE using the `body` (in JSON) on the table.
///
/// # Example
Expand Down
1 change: 1 addition & 0 deletions tests/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ async fn upsert_existing() -> Result<(), Box<dyn Error>> {
let resp = client
.from("users")
.upsert(r#"{"username": "dragarcia", "status": "ONLINE"}"#)
.on_conflict("username")
.execute()
.await?;
let body = resp.text().await?;
Expand Down

0 comments on commit 37ee410

Please sign in to comment.