Skip to content

Commit

Permalink
Split transaction into multiple commands (Postgres doesn't accept mul…
Browse files Browse the repository at this point in the history
…tiple commands in a single prepared statement)
  • Loading branch information
marcua committed Sep 12, 2023
1 parent f51c7e5 commit 8820c60
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions src/ayb_db/db_interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,30 +166,31 @@ WHERE slug = $1

async fn get_or_create_entity(&self, entity: &Entity) -> Result<InstantiatedEntity, AybError> {
// Get or create logic inspired by https://stackoverflow.com/a/66337293
let entity: InstantiatedEntity = sqlx::query_as(
let mut tx = self.pool.begin().await?;
sqlx::query(
r#"
BEGIN;
INSERT INTO entity ( slug, entity_type )
VALUES ( $1, $2 )
ON CONFLICT (slug) DO UPDATE
SET entity_type = $2
WHERE false
RETURNING id, slug, entity_type;
SET entity_type = $2
WHERE false;
"#,
)
.bind(&entity.slug)
.bind(entity.entity_type)
.execute(&mut tx)
.await?;
let entity: InstantiatedEntity = sqlx::query_as(
r#"
SELECT id, slug, entity_type
FROM entity
WHERE slug = $1;
COMMIT;
"#,
)
.bind(&entity.slug)
.bind(entity.entity_type)
.fetch_one(&self.pool)
.fetch_one(&mut tx)
.await?;

tx.commit().await?;
Ok(entity)
}

Expand Down

0 comments on commit 8820c60

Please sign in to comment.