|
1 | 1 | use sqlx::query;
|
| 2 | +use sqlx::Acquire; |
| 3 | +use sqlx::Connection; |
2 | 4 |
|
3 | 5 | async fn insert_and_verify(
|
4 | 6 | transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
5 | 7 | test_id: i64,
|
6 | 8 | ) -> Result<(), Box<dyn std::error::Error>> {
|
| 9 | + let connection = transaction.acquire().await?; |
7 | 10 | query!(
|
8 | 11 | r#"INSERT INTO todos (id, description)
|
9 | 12 | VALUES ( $1, $2 )
|
10 | 13 | "#,
|
11 | 14 | test_id,
|
12 | 15 | "test todo"
|
13 | 16 | )
|
14 |
| - .execute(&mut *transaction) |
| 17 | + .execute(&mut *connection) |
15 | 18 | .await?;
|
16 | 19 |
|
17 | 20 | // check that inserted todo can be fetched inside the uncommitted transaction
|
18 | 21 | let _ = query!(r#"SELECT FROM todos WHERE id = $1"#, test_id)
|
19 |
| - .fetch_one(transaction) |
| 22 | + .fetch_one(&mut *connection) |
20 | 23 | .await?;
|
21 | 24 |
|
22 | 25 | Ok(())
|
@@ -60,6 +63,33 @@ async fn commit_example(
|
60 | 63 | Ok(())
|
61 | 64 | }
|
62 | 65 |
|
| 66 | +async fn insert_and_update_description( |
| 67 | + pool: &sqlx::PgPool, |
| 68 | + test_id: i64, |
| 69 | + new_description: &str, |
| 70 | +) -> Result<(), Box<dyn std::error::Error>> { |
| 71 | + let mut connection = pool.acquire().await?; |
| 72 | + |
| 73 | + connection |
| 74 | + .transaction(|tx| { |
| 75 | + Box::pin(async { |
| 76 | + insert_and_verify(tx, test_id).await.unwrap(); |
| 77 | + let conn = tx.acquire().await?; |
| 78 | + query!( |
| 79 | + r#"UPDATE todos set description = $1 where id = $2"#, |
| 80 | + new_description, |
| 81 | + test_id, |
| 82 | + ) |
| 83 | + .execute(conn) |
| 84 | + .await?; |
| 85 | + Ok::<_, sqlx::Error>(()) |
| 86 | + }) |
| 87 | + }) |
| 88 | + .await?; |
| 89 | + |
| 90 | + Ok(()) |
| 91 | +} |
| 92 | + |
63 | 93 | #[tokio::main]
|
64 | 94 | async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
65 | 95 | let conn_str =
|
@@ -100,5 +130,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
100 | 130 |
|
101 | 131 | assert!(inserted_todo.is_ok());
|
102 | 132 |
|
| 133 | + let test_id = 2; |
| 134 | + |
| 135 | + let description = String::from("hello world"); |
| 136 | + insert_and_update_description(&pool, test_id, &description).await?; |
| 137 | + |
| 138 | + // check that inserted todo is visible outside the transaction after commit |
| 139 | + let inserted_todo: Result<_, _> = query!(r#"SELECT * FROM todos WHERE id = $1"#, test_id) |
| 140 | + .fetch_one(&pool) |
| 141 | + .await; |
| 142 | + |
| 143 | + assert!(inserted_todo.is_ok()); |
| 144 | + assert_eq!(inserted_todo.unwrap().description, description); |
| 145 | + |
103 | 146 | Ok(())
|
104 | 147 | }
|
0 commit comments