Created
March 1, 2018 18:56
-
-
Save anonymous/6018b054bfc7fc63cde8c4dfabb8923f to your computer and use it in GitHub Desktop.
Rust code shared from the playground
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
// NOTE: THIS DOES NOT COMPILE | |
// | |
// Just a proof of concept of the code I have written and how I'd like to be | |
// able to use it. | |
pub trait AdapterInitalizer<T: ManageConnection + 'static> { | |
type Connection: Sized + Send + 'static; | |
type Error: Sized + Error + 'static; | |
fn init_pool<'a>(&self, creds: &'a str, pool_size: u32) -> Pool<T>; | |
} | |
#[cfg(feature = "diesel_sqlite")] | |
struct DieselSqliteAdapter; | |
#[cfg(feature = "diesel_sqlite")] | |
impl AdapterInitalizer<ConnectionManager<SqliteConnection>> for DieselSqliteAdapter { | |
type Connection = SqliteConnection; | |
type Error = diesel::r2d2::Error; | |
fn init_pool<'a>(&self, credentials: &'a str, pool_size: u32) -> Pool<ConnectionManager<SqliteConnection>> { | |
let manager = ConnectionManager::<SqliteConnection>::new(credentials); | |
Pool::builder().max_size(pool_size).build(manager).expect("Unable to create Sqlite pool") | |
} | |
} | |
#[cfg(feature = "pg_pool")] | |
struct PostgresAdapter; | |
#[cfg(feature = "pg_pool")] | |
impl AdapterInitalizer<PostgresConnectionManager> for PostgresAdapter { | |
type Connection = postgres::Connection; | |
type Error = postgres::Error; | |
fn init_pool<'a>(&self, credentials: &'a str, pool_size: u32) -> Pool<PostgresConnectionManager> { | |
let manager = PostgresConnectionManager::new(credentials, TlsMode::None).unwrap(); | |
Pool::builder().max_size(pool_size).build(manager).expect("Unable to build Postgres pool") | |
} | |
} | |
// I don't want this to be parameterized. I'd rather it is just the trait (or boxed trait) | |
pub struct Databases<T> { | |
initializers: HashMap<String, AdapterInitializer<T>> | |
}; | |
impl<T> Database<T> { | |
pub fn new() -> Self { | |
let initializers = HashMap::new(); | |
initializers.insert("diesel_sqlite", DieselSqliteAdapter); | |
initializers.insert("postgres", PostgresAdapter); | |
Databases { | |
initializers | |
} | |
} | |
} | |
fn main() { | |
let database_connections = ["diesel_sqlite", "postgres"]; | |
let credentials = ["./path/to/some/db.sqlite", "postgres://root:root@localhost/my_db"]; | |
let databases = Databases::new(); | |
for (adapter_type, credentials) in database_connections.iter().zip(credentials.iter()) { | |
// Do something with the returned pool, like store it in Rocket managed state | |
let pool = databases.initializers[adapter_type].init_pool(credentials, 10); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment