sylvia_iot_auth/models/
model_sqlite.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! Pure SQLite model.

use std::{error::Error as StdError, sync::Arc};

use async_trait::async_trait;
use sqlx::SqlitePool;

use super::{
    access_token, authorization_code, client, login_session, refresh_token,
    sqlite::{
        access_token::Model as AccessTokenModel,
        authorization_code::Model as AuthorizationCodeModel,
        client::Model as ClientModel,
        conn::{self, Options},
        login_session::Model as LoginSessionModel,
        refresh_token::Model as RefreshTokenModel,
        user::Model as UserModel,
    },
    user,
};

/// Pure SQLite model.
#[derive(Clone)]
pub struct Model {
    conn: Arc<SqlitePool>,
    user: Arc<UserModel>,
    client: Arc<ClientModel>,
    login_session: Arc<LoginSessionModel>,
    authorization_code: Arc<AuthorizationCodeModel>,
    access_token: Arc<AccessTokenModel>,
    refresh_token: Arc<RefreshTokenModel>,
}

impl Model {
    /// Create an instance.
    pub async fn new(opts: &Options) -> Result<Self, Box<dyn StdError>> {
        let conn = Arc::new(conn::connect(opts).await?);
        Ok(Model {
            conn: conn.clone(),
            user: Arc::new(UserModel::new(conn.clone()).await?),
            client: Arc::new(ClientModel::new(conn.clone()).await?),
            login_session: Arc::new(LoginSessionModel::new(conn.clone()).await?),
            authorization_code: Arc::new(AuthorizationCodeModel::new(conn.clone()).await?),
            access_token: Arc::new(AccessTokenModel::new(conn.clone()).await?),
            refresh_token: Arc::new(RefreshTokenModel::new(conn.clone()).await?),
        })
    }

    /// Get the raw database connection ([`SqlitePool`]).
    pub fn get_connection(&self) -> &SqlitePool {
        &self.conn
    }
}

#[async_trait]
impl super::Model for Model {
    async fn close(&self) -> Result<(), Box<dyn StdError>> {
        self.conn.close().await;
        Ok(())
    }

    fn user(&self) -> &dyn user::UserModel {
        self.user.as_ref()
    }

    fn client(&self) -> &dyn client::ClientModel {
        self.client.as_ref()
    }

    fn login_session(&self) -> &dyn login_session::LoginSessionModel {
        self.login_session.as_ref()
    }

    fn authorization_code(&self) -> &dyn authorization_code::AuthorizationCodeModel {
        self.authorization_code.as_ref()
    }

    fn access_token(&self) -> &dyn access_token::AccessTokenModel {
        self.access_token.as_ref()
    }

    fn refresh_token(&self) -> &dyn refresh_token::RefreshTokenModel {
        self.refresh_token.as_ref()
    }
}