1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Dialect {
9 Standard,
12 Sqlite,
13 Postgres,
14 MySql,
15 Mssql,
16}
17
18impl Dialect {
19 pub fn from_url(url: &str) -> Self {
26 let scheme = url
31 .trim_matches(|c: char| c <= ' ')
32 .split("://")
33 .next()
34 .unwrap_or("")
35 .split(':')
36 .next()
37 .unwrap_or("")
38 .to_ascii_lowercase();
39 match scheme.as_str() {
40 "postgres" | "postgresql" => Self::Postgres,
41 "mysql" | "mariadb" => Self::MySql,
42 "sqlite" => Self::Sqlite,
43 "mssql" | "sqlserver" => Self::Mssql,
44 _ => Self::Standard,
45 }
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn from_url_recognizes_each_scheme() {
55 assert_eq!(
56 Dialect::from_url("postgres://localhost/db"),
57 Dialect::Postgres
58 );
59 assert_eq!(
60 Dialect::from_url("postgresql://localhost/db"),
61 Dialect::Postgres
62 );
63 assert_eq!(Dialect::from_url("mysql://localhost/db"), Dialect::MySql);
64 assert_eq!(Dialect::from_url("mariadb://localhost/db"), Dialect::MySql);
65 assert_eq!(Dialect::from_url("sqlite::memory:"), Dialect::Sqlite);
66 assert_eq!(Dialect::from_url("sqlite:app.db"), Dialect::Sqlite);
67 assert_eq!(Dialect::from_url("mssql://host:1433/db"), Dialect::Mssql);
68 assert_eq!(
69 Dialect::from_url("sqlserver://host:1433/db"),
70 Dialect::Mssql
71 );
72 assert_eq!(Dialect::from_url("postgres"), Dialect::Postgres);
73 }
74
75 #[test]
76 fn from_url_unknown_scheme_is_standard() {
77 assert_eq!(Dialect::from_url("oracle://host/db"), Dialect::Standard);
78 assert_eq!(Dialect::from_url(""), Dialect::Standard);
79 assert_eq!(Dialect::from_url("nonsense"), Dialect::Standard);
80 }
81
82 #[test]
85 fn from_url_is_case_insensitive() {
86 assert_eq!(
87 Dialect::from_url("POSTGRES://localhost/db"),
88 Dialect::Postgres
89 );
90 assert_eq!(Dialect::from_url("MySQL://localhost/db"), Dialect::MySql);
91 assert_eq!(Dialect::from_url("SQLite:app.db"), Dialect::Sqlite);
92 }
93
94 #[test]
97 fn from_url_tolerates_surrounding_whitespace() {
98 assert_eq!(Dialect::from_url(" postgres://host/db"), Dialect::Postgres);
99 assert_eq!(Dialect::from_url("\tmysql://host/db"), Dialect::MySql);
100 assert_eq!(Dialect::from_url("sqlite:app.db\n"), Dialect::Sqlite);
101 assert_eq!(Dialect::from_url("\0postgres://host/db"), Dialect::Postgres);
103 assert_eq!(Dialect::from_url("\u{1}mysql://host/db"), Dialect::MySql);
104 }
105
106 #[test]
108 fn from_url_handles_sqlite_without_authority() {
109 assert_eq!(
110 Dialect::from_url("sqlite:ecat-test.db?mode=memory"),
111 Dialect::Sqlite
112 );
113 }
114}