From c2268c285648ef02ece04de0d9df0813c6d70ff8 Mon Sep 17 00:00:00 2001 From: benj Date: Sat, 24 Dec 2022 00:43:38 -0800 Subject: refactor everything with more abstraction and a nicer interface --- crates/secd/src/util/from.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 crates/secd/src/util/from.rs (limited to 'crates/secd/src/util/from.rs') diff --git a/crates/secd/src/util/from.rs b/crates/secd/src/util/from.rs new file mode 100644 index 0000000..bab8a25 --- /dev/null +++ b/crates/secd/src/util/from.rs @@ -0,0 +1,66 @@ +use std::str::FromStr; + +use crate::AuthStore; + +impl From> for AuthStore { + fn from(s: Option) -> Self { + let conn = s.clone().unwrap_or("sqlite::memory:".into()); + match conn.split(":").next() { + Some("postgresql") | Some("postgres") => AuthStore::Postgres { conn }, + Some("sqlite") => AuthStore::Sqlite { conn }, + _ => panic!( + "AuthStore: Invalid database connection string provided. Found: {:?}", + s + ), + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn auth_store_from_string() { + let in_conn = None; + let a = AuthStore::from(in_conn.clone()); + match AuthStore::from(in_conn.clone()) { + AuthStore::Sqlite { conn } => assert_eq!(conn, "sqlite::memory:"), + r @ _ => assert!( + false, + "should have parsed None as in-memory sqlite. Found: {:?}", + r + ), + } + + let postgresql_conn = Some("postgresql://testuser:p4ssw0rd@1.2.3.4:5432/test-db".into()); + match AuthStore::from(postgresql_conn.clone()) { + AuthStore::Postgres { conn } => assert_eq!(conn, postgresql_conn.unwrap()), + r @ _ => assert!(false, "should have parsed as postgres. Found: {:?}", r), + } + + let postgres_conn = Some("postgres://testuser:p4ssw0rd@1.2.3.4:5432/test-db".into()); + match AuthStore::from(postgres_conn.clone()) { + AuthStore::Postgres { conn } => assert_eq!(conn, postgres_conn.unwrap()), + r @ _ => assert!(false, "should have parsed as postgres. Found: {:?}", r), + } + + let sqlite_conn = Some("sqlite:///path/to/db.sql".into()); + let a = AuthStore::from(sqlite_conn.clone()); + match AuthStore::from(sqlite_conn.clone()) { + AuthStore::Sqlite { conn } => assert_eq!(conn, sqlite_conn.unwrap()), + r @ _ => assert!(false, "should have parsed as sqlite. Found: {:?}", r), + } + + let sqlite_mem_conn = Some("sqlite:memory:".into()); + let a = AuthStore::from(sqlite_mem_conn.clone()); + match AuthStore::from(sqlite_mem_conn.clone()) { + AuthStore::Sqlite { conn } => assert_eq!(conn, sqlite_mem_conn.unwrap()), + r @ _ => assert!( + false, + "should have parsed as in-memoy sqlite. Found: {:?}", + r + ), + } + } +} -- cgit v1.2.3