mirror of
https://github.com/flibusta-apps/library_updater.git
synced 2025-12-06 07:45:35 +01:00
Use ON CONFLICT upsert for genres
Replace the previous IF EXISTS/UPDATE/INSERT logic in the update_genre PL/pgSQL function with a single INSERT ... ON CONFLICT DO UPDATE to perform an atomic upsert and avoid races. Reformat the client.execute call for readability.
This commit is contained in:
21
src/types.rs
21
src/types.rs
@@ -828,23 +828,26 @@ impl FromVecExpression<Genre> for Genre {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Update for Genre {
|
impl Update for Genre {
|
||||||
async fn before_update(client: &Client) -> Result<(), Box<tokio_postgres::Error>> {
|
async fn before_update(client: &Client) -> Result<(), Box<tokio_postgres::Error>> {
|
||||||
match client.execute(
|
match client
|
||||||
|
.execute(
|
||||||
"
|
"
|
||||||
CREATE OR REPLACE FUNCTION update_genre(
|
CREATE OR REPLACE FUNCTION update_genre(
|
||||||
source_ smallint, remote_id_ int, code_ varchar, description_ varchar, meta_ varchar
|
source_ smallint, remote_id_ int, code_ varchar, description_ varchar, meta_ varchar
|
||||||
) RETURNS void AS $$
|
) RETURNS void AS $$
|
||||||
BEGIN
|
BEGIN
|
||||||
IF EXISTS (SELECT * FROM genres WHERE source = source_ AND remote_id = remote_id_) THEN
|
|
||||||
UPDATE genres SET code = code_, description = description_, meta = meta_
|
|
||||||
WHERE source = source_ AND remote_id = remote_id_;
|
|
||||||
RETURN;
|
|
||||||
END IF;
|
|
||||||
INSERT INTO genres (source, remote_id, code, description, meta)
|
INSERT INTO genres (source, remote_id, code, description, meta)
|
||||||
VALUES (source_, remote_id_, code_, description_, meta_);
|
VALUES (source_, remote_id_, code_, description_, meta_)
|
||||||
|
ON CONFLICT (source, remote_id) DO UPDATE SET
|
||||||
|
code = EXCLUDED.code,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
meta = EXCLUDED.meta;
|
||||||
END;
|
END;
|
||||||
$$ LANGUAGE plpgsql;
|
$$ LANGUAGE plpgsql;
|
||||||
"
|
",
|
||||||
, &[]).await {
|
&[],
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
Err(err) => Err(Box::new(err)),
|
Err(err) => Err(Box::new(err)),
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user