Created
March 9, 2021 18:16
-
-
Save hediet/37d86ee2cfa18a590be4937ec7e243dc to your computer and use it in GitHub Desktop.
Rust Sqlx Crazyness
This file contains hidden or 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 std::{marker::PhantomData, path::PathBuf}; | |
use sqlx::{sqlite::SqliteConnectOptions, Error}; | |
use sqlx::{Connection, Sqlite, Transaction}; | |
use sqlx::{Executor, SqliteConnection}; | |
pub struct DbFactory { | |
conn: SqliteConnection, | |
} | |
impl DbFactory { | |
pub async fn connect() -> Result<DbFactory, Error> { | |
let mut conn = SqliteConnection::connect_with( | |
&SqliteConnectOptions::new() | |
.filename(&"test.db") | |
.create_if_missing(true), | |
) | |
.await?; | |
sqlx::migrate!("./migrations").run(&mut conn).await?; | |
Ok(DbFactory { conn }) | |
} | |
pub fn db<'c>(self: &'c mut Self) -> Db<'c, &'c mut SqliteConnection> { | |
Db { | |
executor: &mut self.conn, | |
_marker: PhantomData::default(), | |
} | |
} | |
pub async fn begin_transaction<'c>(self: &'c mut Self) -> Result<DbTransaction<'c>, Error> { | |
Ok(DbTransaction { | |
tx: self.conn.begin().await?, | |
}) | |
} | |
} | |
struct DbTransaction<'c> { | |
tx: Transaction<'c, Sqlite>, | |
} | |
impl<'c> DbTransaction<'c> { | |
pub fn db(&'c mut self) -> Db<'c, &'c mut Transaction<'c, Sqlite>> { | |
let tx: &'c mut Transaction<'c, Sqlite> = &mut self.tx; | |
Db { | |
executor: tx, | |
_marker: PhantomData::default(), | |
} | |
} | |
} | |
pub struct Db<'c, E> | |
where | |
E: Executor<'c>, | |
{ | |
executor: E, | |
_marker: PhantomData<&'c ()>, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment