Skip to main content

schedr_db/
backend.rs

1//! The two database backends and their migrations.
2//!
3//! Production uses Postgres, local development SQLite (see archive/PROJECT.md, State storage). Each
4//! backend has its own migration files because column types differ (`TIMESTAMPTZ` / `UUID` /
5//! `JSONB` in Postgres, text in SQLite); both sets always have the same versions.
6
7use sqlx::migrate::Migrator;
8
9#[cfg(test)]
10mod tests;
11
12/// The migrations for SQLite, built into the binary.
13static SQLITE_MIGRATIONS: Migrator = sqlx::migrate!("migrations/sqlite");
14
15/// The migrations for Postgres, built into the binary.
16static POSTGRES_MIGRATIONS: Migrator = sqlx::migrate!("migrations/postgres");
17
18/// A database backend.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum Backend {
21    /// SQLite: local development and standalone mode.
22    Sqlite,
23    /// Postgres: production.
24    Postgres,
25}
26
27/// The URL doesn't name a supported database.
28#[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    /// The backend a connection URL names: `sqlite:` or `postgres://` / `postgresql://`.
34    ///
35    /// # Errors
36    ///
37    /// Returns [`UnsupportedUrl`] for any other scheme. The URL in the error has any password
38    /// removed.
39    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    /// The migrations for this backend.
50    #[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    /// The versions of this backend's migrations, in order.
59    #[must_use]
60    pub fn migration_versions(self) -> Vec<i64> {
61        self.migrator().iter().map(|m| m.version).collect()
62    }
63}
64
65/// `url` with its passwords replaced by `***`, for messages and logs: the user-info part's
66/// (`user:***@host`) and a query parameter's naming one (`?password=***`, `sslpassword`;
67/// B203: sqlx takes both).
68#[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
97/// The query parameters sqlx 0.9 reads from a Postgres URL (`sqlx-postgres`'s
98/// `options/parse.rs`); it ignores any other, warning with its value.
99const 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/// The names of a Postgres URL's query parameters sqlx would ignore (`sslmod=require`, a
121/// typo), percent-decoded: for schedr to warn of them by name, since sqlx's own warning,
122/// kept out of the log, shows their values (B203's review).
123#[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/// Whether a query parameter's name, percent-decoded and in any case, names a password.
141#[must_use]
142pub fn names_a_password(name: &str) -> bool {
143    percent_decoded(name)
144        .to_ascii_lowercase()
145        .ends_with("password")
146}
147
148/// `%70assword` → `password`; tabs and line breaks dropped, a malformed
149/// escape kept as it is.
150fn percent_decoded(text: &str) -> String {
151    // Tabs and line breaks dropped first, as a URL parser drops them (sqlx's does: B203's
152    // review, `pass<TAB>word=` is its `password`).
153    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/// Where `url`'s database is, for a person to check: a Postgres server's `host:port` (or its
179/// socket's folder) as sqlx reads the URL (its `host=` and `port=` parameters, the `PG*`
180/// variables, the defaults), a SQLite file's path; never its user or password (the user,
181/// 2026-11-15: a role waiting for its database names where, so a typo shows).
182#[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}