use a transaction for committing invites to db

This commit is contained in:
Joe Ardent 2024-02-10 12:21:28 -08:00
parent 8ee362b991
commit 94e26f8080
2 changed files with 10 additions and 4 deletions

View file

@ -3,6 +3,7 @@ use std::time::Duration;
use clap::Parser;
use julid::Julid;
use parse_duration::parse;
use serde::Serialize;
use sqlx::SqlitePool;
use what2watch::{conf::Config, get_db_pool, Invitation, User};
@ -50,7 +51,9 @@ fn main() {
let invites = rt.block_on(async {
ensure_omega(&pool).await;
generate_invites(quest, num, &pool).await
let invites = generate_invites(quest, num, &pool).await;
pool.close().await;
invites
});
for invite in invites {
println!("{base_url}/signup/{invite}");

View file

@ -42,13 +42,14 @@ impl Default for Invitation {
impl Invitation {
pub async fn commit(&self, db: &SqlitePool) -> Result<Julid, CreateInviteError> {
sqlx::query_scalar(
let mut tx = db.begin().await.unwrap();
let id = sqlx::query_scalar(
"insert into invites (owner, expires_at, remaining) values (?, ?, ?) returning id",
)
.bind(self.owner)
.bind(self.expires_at)
.bind(self.remaining)
.fetch_optional(db)
.fetch_optional(&mut *tx)
.await
.map_err(|e| {
tracing::debug!("Got error creating invite: {e}");
@ -64,7 +65,9 @@ impl Invitation {
CreateInviteErrorKind::Unknown
}
})?
.ok_or(CreateInviteErrorKind::Unknown.into())
.ok_or(CreateInviteErrorKind::Unknown.into());
tx.commit().await.unwrap();
id
}
pub fn new(owner: Julid) -> Self {