use proper sql functionality for upsert

This commit is contained in:
Felix Ableitner 2020-08-25 15:08:36 +02:00
parent fb88a5b3b4
commit 8ac0fa6d6c
3 changed files with 18 additions and 19 deletions

View file

@ -162,12 +162,13 @@ impl Community {
} }
pub fn upsert(conn: &PgConnection, community_form: &CommunityForm) -> Result<Community, Error> { pub fn upsert(conn: &PgConnection, community_form: &CommunityForm) -> Result<Community, Error> {
let existing = Self::read_from_actor_id(conn, &community_form.actor_id); use crate::schema::community::dsl::*;
match existing { insert_into(community)
Err(NotFound {}) => Ok(Self::create(conn, &community_form)?), .values(community_form)
Ok(c) => Ok(Self::update(conn, c.id, &community_form)?), .on_conflict(actor_id)
Err(e) => Err(e), .do_update()
} .set(community_form)
.get_result::<Self>(conn)
} }
} }

View file

@ -180,13 +180,11 @@ impl Post {
} }
pub fn upsert(conn: &PgConnection, post_form: &PostForm) -> Result<Post, Error> { pub fn upsert(conn: &PgConnection, post_form: &PostForm) -> Result<Post, Error> {
let existing = Self::read_from_apub_id(conn, &post_form.ap_id); use crate::schema::post::dsl::*;
match existing { insert_into(post)
Err(NotFound {}) => Ok(Self::create(conn, &post_form)?), .values(post_form)
// both the old and new comment should be identical so no need to do an update here .on_conflict_do_nothing()
Ok(p) => Ok(Self::read(conn, p.id)?), .get_result::<Self>(conn)
Err(e) => Err(e),
}
} }
} }

View file

@ -154,12 +154,12 @@ impl User_ {
} }
pub fn upsert(conn: &PgConnection, user_form: &UserForm) -> Result<User_, Error> { pub fn upsert(conn: &PgConnection, user_form: &UserForm) -> Result<User_, Error> {
let existing = Self::read_from_actor_id(conn, &user_form.actor_id); insert_into(user_)
match existing { .values(user_form)
Err(NotFound {}) => Ok(Self::create(conn, &user_form)?), .on_conflict(actor_id)
Ok(u) => Ok(Self::update(conn, u.id, &user_form)?), .do_update()
Err(e) => Err(e), .set(user_form)
} .get_result::<Self>(conn)
} }
} }