1use crate::{error::ParseError, Database};
2use cfg_if::cfg_if;
3use std::{convert::TryFrom, ops::Deref};
4use url::Url;
5
6cfg_if! {if #[cfg(feature = "with-postgres")]{
7 use crate::pg::PostgresDB;
8}}
9
10cfg_if! {if #[cfg(feature = "with-sqlite")]{
11 use crate::sqlite::SqliteDB;
12}}
13
14cfg_if! {if #[cfg(feature = "with-mysql")]{
15 use crate::my::MysqlDB;
16}}
17
18pub enum DBPlatform {
19 #[cfg(feature = "with-postgres")]
20 Postgres(Box<PostgresDB>),
21 #[cfg(feature = "with-sqlite")]
22 Sqlite(Box<SqliteDB>),
23 #[cfg(feature = "with-mysql")]
24 Mysql(Box<MysqlDB>),
25}
26
27impl Deref for DBPlatform {
28 type Target = dyn Database;
29
30 fn deref(&self) -> &Self::Target {
31 match *self {
32 #[cfg(feature = "with-postgres")]
33 DBPlatform::Postgres(ref pg) => pg.deref(),
34 #[cfg(feature = "with-sqlite")]
35 DBPlatform::Sqlite(ref sq) => sq.deref(),
36 #[cfg(feature = "with-mysql")]
37 DBPlatform::Mysql(ref my) => my.deref(),
38 }
39 }
40}
41
42impl std::ops::DerefMut for DBPlatform {
43 fn deref_mut(&mut self) -> &mut Self::Target {
44 match *self {
45 #[cfg(feature = "with-postgres")]
46 DBPlatform::Postgres(ref mut pg) => pg.deref_mut(),
47 #[cfg(feature = "with-sqlite")]
48 DBPlatform::Sqlite(ref mut sq) => sq.deref_mut(),
49 #[cfg(feature = "with-mysql")]
50 DBPlatform::Mysql(ref mut my) => my.deref_mut(),
51 }
52 }
53}
54
55pub(crate) enum Platform {
56 #[cfg(feature = "with-postgres")]
57 Postgres,
58 #[cfg(feature = "with-sqlite")]
59 Sqlite(String),
60 #[cfg(feature = "with-mysql")]
61 Mysql,
62 Unsupported(String),
63}
64
65impl<'a> TryFrom<&'a str> for Platform {
66 type Error = ParseError;
67
68 fn try_from(s: &'a str) -> Result<Self, Self::Error> {
69 let url = Url::parse(s);
70 match url {
71 Ok(url) => {
72 let scheme = url.scheme();
73 match scheme {
74 #[cfg(feature = "with-postgres")]
75 "postgres" => Ok(Platform::Postgres),
76 #[cfg(feature = "with-sqlite")]
77 "sqlite" => {
78 let host = url.host_str().unwrap();
79 let path = url.path();
80 let path = if path == "/" { "" } else { path };
81 let db_file = format!("{}{}", host, path);
82 Ok(Platform::Sqlite(db_file))
83 }
84 #[cfg(feature = "with-mysql")]
85 "mysql" => Ok(Platform::Mysql),
86 _ => Ok(Platform::Unsupported(scheme.to_string())),
87 }
88 }
89 Err(e) => Err(ParseError::DbUrlParseError(e)),
90 }
91 }
92}