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> {
let existing = Self::read_from_actor_id(conn, &community_form.actor_id);
match existing {
Err(NotFound {}) => Ok(Self::create(conn, &community_form)?),
Ok(c) => Ok(Self::update(conn, c.id, &community_form)?),
Err(e) => Err(e),
}
use crate::schema::community::dsl::*;
insert_into(community)
.values(community_form)
.on_conflict(actor_id)
.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> {
let existing = Self::read_from_apub_id(conn, &post_form.ap_id);
match existing {
Err(NotFound {}) => Ok(Self::create(conn, &post_form)?),
// both the old and new comment should be identical so no need to do an update here
Ok(p) => Ok(Self::read(conn, p.id)?),
Err(e) => Err(e),
}
use crate::schema::post::dsl::*;
insert_into(post)
.values(post_form)
.on_conflict_do_nothing()
.get_result::<Self>(conn)
}
}

View file

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