1
//! The one place a command turns a failed connection into its error.
2

            
3
use rust_i18n::t;
4
use sqlx::{Postgres, pool::PoolConnection};
5

            
6
use crate::command::CmdError;
7
use crate::db::{DBError, get_connection};
8
use crate::user::{TenantConnection, User};
9

            
10
/// Logs an unreachable database here, since callers answer it without a log of their own.
11
/// Any other fault is left to the caller that handles it, so each error logs once.
12
6307
fn refused(err: DBError) -> CmdError {
13
6307
    if err.is_unavailable() {
14
6126
        tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
15
181
    }
16
6307
    err.into()
17
6307
}
18

            
19
/// The user's tenant connection.
20
///
21
/// # Errors
22
/// [`CmdError::Server`] carrying the [`DBError`] that refused the connection.
23
1512585
pub(crate) async fn connection(user: &User) -> Result<TenantConnection, CmdError> {
24
1512585
    user.get_connection().await.map_err(refused)
25
1512405
}
26

            
27
/// A connection to the global directory.
28
///
29
/// # Errors
30
/// [`CmdError::Server`] carrying the [`DBError`] that refused the connection.
31
71699
pub(crate) async fn admin_connection() -> Result<PoolConnection<Postgres>, CmdError> {
32
71699
    get_connection().await.map_err(refused)
33
71699
}
34

            
35
#[cfg(test)]
36
#[path = "connect_tests.rs"]
37
mod tests;