1use sqlx::migrate::Migrator;
8
9#[cfg(test)]
10mod tests;
11
12static SQLITE_MIGRATIONS: Migrator = sqlx::migrate!("migrations/sqlite");
14
15static POSTGRES_MIGRATIONS: Migrator = sqlx::migrate!("migrations/postgres");
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum Backend {
21 Sqlite,
23 Postgres,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29#[error("unsupported database URL `{0}` (use `sqlite:...` or `postgres://...`)")]
30pub struct UnsupportedUrl(pub String);
31
32impl Backend {
33 pub fn from_url(url: &str) -> Result<Self, UnsupportedUrl> {
40 if url.starts_with("sqlite:") {
41 Ok(Self::Sqlite)
42 } else if url.starts_with("postgres://") || url.starts_with("postgresql://") {
43 Ok(Self::Postgres)
44 } else {
45 Err(UnsupportedUrl(redact_password(url)))
46 }
47 }
48
49 #[must_use]
51 pub fn migrator(self) -> &'static Migrator {
52 match self {
53 Self::Sqlite => &SQLITE_MIGRATIONS,
54 Self::Postgres => &POSTGRES_MIGRATIONS,
55 }
56 }
57
58 #[must_use]
60 pub fn migration_versions(self) -> Vec<i64> {
61 self.migrator().iter().map(|m| m.version).collect()
62 }
63}
64
65#[must_use]
69pub fn redact_password(url: &str) -> String {
70 let (base, query) = match url.split_once('?') {
71 Some((base, query)) => (base, Some(query)),
72 None => (url, None),
73 };
74 let mut out = redact_user_info(base);
75 if let Some(query) = query {
76 let (query, fragment) = match query.split_once('#') {
77 Some((query, fragment)) => (query, Some(fragment)),
78 None => (query, None),
79 };
80 out.push('?');
81 let pairs: Vec<String> = query
82 .split('&')
83 .map(|pair| match pair.split_once('=') {
84 Some((name, _)) if names_a_password(name) => format!("{name}=***"),
85 _ => pair.to_owned(),
86 })
87 .collect();
88 out.push_str(&pairs.join("&"));
89 if let Some(fragment) = fragment {
90 out.push('#');
91 out.push_str(fragment);
92 }
93 }
94 out
95}
96
97const POSTGRES_PARAMETERS: [&str; 18] = [
100 "sslmode",
101 "ssl-mode",
102 "sslrootcert",
103 "ssl-root-cert",
104 "ssl-ca",
105 "sslcert",
106 "ssl-cert",
107 "sslkey",
108 "ssl-key",
109 "statement-cache-capacity",
110 "host",
111 "hostaddr",
112 "port",
113 "dbname",
114 "user",
115 "password",
116 "application_name",
117 "options",
118];
119
120#[must_use]
124pub fn unknown_postgres_parameters(url: &str) -> Vec<String> {
125 let Some((_, query)) = url.split_once('?') else {
126 return Vec::new();
127 };
128 let query = query.split('#').next().unwrap_or_default();
129 query
130 .split('&')
131 .filter(|pair| !pair.is_empty())
132 .map(|pair| percent_decoded(pair.split_once('=').map_or(pair, |(name, _)| name)))
133 .filter(|name| {
134 let indexed = name.starts_with("options[") && name.ends_with(']');
135 !(indexed || POSTGRES_PARAMETERS.contains(&name.as_str()))
136 })
137 .collect()
138}
139
140#[must_use]
142pub fn names_a_password(name: &str) -> bool {
143 percent_decoded(name)
144 .to_ascii_lowercase()
145 .ends_with("password")
146}
147
148fn percent_decoded(text: &str) -> String {
151 let text: String = text
154 .chars()
155 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
156 .collect();
157 let bytes = text.as_bytes();
158 let mut out = Vec::with_capacity(bytes.len());
159 let mut i = 0;
160 while i < bytes.len() {
161 let hex = bytes
162 .get(i + 1..i + 3)
163 .and_then(|h| std::str::from_utf8(h).ok());
164 match (bytes[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
165 (b'%', Some(byte)) => {
166 out.push(byte);
167 i += 3;
168 }
169 (byte, _) => {
170 out.push(byte);
171 i += 1;
172 }
173 }
174 }
175 String::from_utf8_lossy(&out).into_owned()
176}
177
178#[must_use]
183pub fn database_place(url: &str) -> String {
184 if let Some(path) = url
185 .strip_prefix("sqlite://")
186 .or_else(|| url.strip_prefix("sqlite:"))
187 {
188 let path = path.split('?').next().unwrap_or_default();
189 return if path.is_empty() || path == ":memory:" {
190 "memory".to_owned()
191 } else {
192 path.to_owned()
193 };
194 }
195 if !(url.starts_with("postgres://") || url.starts_with("postgresql://")) {
196 return "an unreadable URL".to_owned();
197 }
198 let Ok(options) = url.parse::<sqlx::postgres::PgConnectOptions>() else {
199 return "an unreadable URL".to_owned();
200 };
201 let (host, port) = (options.get_host(), options.get_port());
202 if let Some(socket) = options.get_socket() {
203 format!("{} (port {port})", socket.display())
204 } else if host.starts_with('/') {
205 format!("{host} (port {port})")
206 } else if host.contains(':') && !host.starts_with('[') {
207 format!("[{host}]:{port}")
208 } else {
209 format!("{host}:{port}")
210 }
211}
212
213fn redact_user_info(url: &str) -> String {
214 let Some((scheme, rest)) = url.split_once("://") else {
215 return url.to_owned();
216 };
217 let authority_end = rest.find('/').unwrap_or(rest.len());
218 let (authority, path) = rest.split_at(authority_end);
219 match authority.rsplit_once('@') {
220 Some((user_info, host)) => match user_info.split_once(':') {
221 Some((user, _password)) => format!("{scheme}://{user}:***@{host}{path}"),
222 None => url.to_owned(),
223 },
224 None => url.to_owned(),
225 }
226}