Skip to main content

server/
user.rs

1use crate::db::DBError;
2use cfg_if::cfg_if;
3use 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.
9mod connection;
10mod userpool;
11
12pub use connection::TenantConnection;
13pub(crate) use userpool::tenant_usage;
14
15pub struct User {
16    pub id: Uuid,
17}
18
19impl User {
20    cfg_if! {
21        if #[cfg(test)] {
22        pub async fn get_connection(&self) -> Result<TenantConnection, DBError> {
23            crate::db::get_connection().await.map(TenantConnection::global)
24        }
25        } else if #[cfg(feature = "test-utils")] {
26        pub async fn get_connection(&self) -> Result<TenantConnection, DBError> {
27            if crate::db::test_pool_is_set() {
28                crate::db::get_connection().await.map(TenantConnection::global)
29            } else {
30                userpool::get_connection(self.id).await
31            }
32        }
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)]
42impl User {
43    /// `verified = TRUE`: the fixture is a usable account.
44    pub async fn commit(&self) -> Result<(), sqlx::Error> {
45        let mut conn = self.get_connection().await.unwrap();
46
47        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        .execute(&mut *conn)
57        .await?;
58
59        Ok(())
60    }
61}