1
use crate::db::DBError;
2
use cfg_if::cfg_if;
3
use sqlx::types::Uuid;
4

            
5
// `userpool` is the production per-user routing path. Its DB-facing half is
6
// excluded from server's own `cfg(test)` runs (see the module docs), where
7
// `get_connection` below short-circuits to the injected test pool; the
8
// bookkeeping half compiles always so it can be tested.
9
mod connection;
10
mod userpool;
11

            
12
pub use connection::TenantConnection;
13
pub(crate) use userpool::tenant_usage;
14

            
15
pub struct User {
16
    pub id: Uuid,
17
}
18

            
19
impl User {
20
    cfg_if! {
21
        if #[cfg(test)] {
22
6098
        pub async fn get_connection(&self) -> Result<TenantConnection, DBError> {
23
6098
            crate::db::get_connection().await.map(TenantConnection::global)
24
6098
        }
25
        } else if #[cfg(feature = "test-utils")] {
26
2507040
        pub async fn get_connection(&self) -> Result<TenantConnection, DBError> {
27
2507040
            if crate::db::test_pool_is_set() {
28
1614420
                crate::db::get_connection().await.map(TenantConnection::global)
29
            } else {
30
892620
                userpool::get_connection(self.id).await
31
            }
32
2506860
        }
33
        } else {
34
        pub async fn get_connection(&self) -> Result<TenantConnection, DBError> {
35
            userpool::get_connection(self.id).await
36
        }
37
        }
38
    }
39
}
40

            
41
#[cfg(test)]
42
impl User {
43
    /// `verified = TRUE`: the fixture is a usable account.
44
361
    pub async fn commit(&self) -> Result<(), sqlx::Error> {
45
361
        let mut conn = self.get_connection().await.unwrap();
46

            
47
361
        sqlx::query!(
48
            "INSERT INTO users (
49
                id, user_name, email, photo, verified, user_password, user_role, database_name, created_at
50
            ) VALUES (
51
                $1, 'Test User', 'test@example.com', 'default.png',
52
                TRUE, 'password123', 'user', 'database', NOW()
53
            )",
54
            self.id,
55
        )
56
361
        .execute(&mut *conn)
57
361
        .await?;
58

            
59
361
        Ok(())
60
361
    }
61
}