Handle a function that can be called within a transaction or not #3406
Unanswered
frederikhors
asked this question in
Q&A
Replies: 1 comment
-
(you forgot to ask a concrete question. assuming you want feedback on the code provided) Why do you have two sources for your pgconnection? (pool vs db) Also lets drop the async fn find_player_id_and_assign_goal(id: &str) -> anyhowResult<String> {
let mut tx = self.pool.begin().await?;
let player_id = self.repo.find_player_id(tx, id).await?;
self.goal_service.assign_to_player(tx, id).await?;
tx.commit().await?;
Ok(player_id)
} Then, consider if you can do this in one sql query (for this one, you don't need a transaction, repository or service.. the code provied sounds like OOP-overengineering) async fn assign_goal_to_player(&self, different_id: &str) -> anyhow::Result<String> {
Ok(sqlx::query_scalar!(
r#"INSERT INTO goals(player_id)
SELECT id FROM players
WHERE different_id=$1
RETURNING player_id"#,
different_id
)
.fetch_one(&self.pool)
.await?)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
If a function can be called with a transaction or a direct connection (and so it should start a new transaction from there because it needs one) what do you suggest to use?
Example code:
This can work, but I only have one issue:
If
Some(db) => db
I need to detect there if we're already in a transaction (ifdb
is one). If not I should start a new one.Do you think is there a better way to accomplish this?
Beta Was this translation helpful? Give feedback.
All reactions