Experiments related to ababo's StackOverflow question. This compiles, but I am not sure if its functionality is correct. Error handling is all removed since it's not the main focus.
Last active
May 30, 2022 13:10
-
-
Save kotatsuyaki/81d7d6758797af71b3abbc636f3309bb to your computer and use it in GitHub Desktop.
Experiments for "How to wrap Sqlx data access types retaining transaction support?"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "sqlx-wrapper-question" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
sqlx = { version = "0.5", features = [ "runtime-tokio-rustls", "sqlite" ] } | |
async-trait = "0.1" | |
tokio = { version = "1", features = [ "rt", "macros" ] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use async_trait::async_trait; | |
#[tokio::main] | |
async fn main() { | |
use sqlx::Connection; | |
let conn = SqliteConnection { | |
inner: sqlx::SqliteConnection::connect("sqlite::memory:") | |
.await | |
.unwrap(), | |
}; | |
test_transaction(conn).await; | |
println!("Success"); | |
} | |
async fn test_transaction(mut conn: impl Connection) { | |
let mut tx = conn.begin().await; | |
let _tx2 = tx.begin().await; | |
} | |
#[async_trait] | |
trait Connection { | |
async fn begin(&mut self) -> SqliteTransaction; | |
} | |
#[async_trait] | |
trait Transaction { | |
async fn begin(&mut self) -> SqliteTransaction; | |
} | |
struct SqliteConnection { | |
inner: sqlx::SqliteConnection, | |
} | |
struct SqliteTransaction<'c> { | |
inner: sqlx::Transaction<'c, sqlx::Sqlite>, | |
} | |
#[async_trait] | |
impl Connection for SqliteConnection { | |
async fn begin(&mut self) -> SqliteTransaction { | |
use sqlx::Connection; | |
SqliteTransaction { | |
inner: self.inner.begin().await.unwrap(), | |
} | |
} | |
} | |
#[async_trait] | |
impl<'c> Transaction for SqliteTransaction<'c> { | |
async fn begin(&mut self) -> SqliteTransaction { | |
use sqlx::Connection; | |
SqliteTransaction { | |
inner: self.inner.begin().await.unwrap(), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment