aboutsummaryrefslogtreecommitdiff
path: root/src/client/sqldb.rs
blob: 6ad0cc1320572c7f24b3d1fbd91906c075af3c57 (plain)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use log::{debug, error};
use uuid::Uuid;

use crate::{util, Identity};

use super::{Store, StoreError};

pub struct SqliteClient {
    pool: sqlx::Pool<sqlx::Sqlite>,
}

impl SqliteClient {
    pub async fn new(pool: sqlx::Pool<sqlx::Sqlite>) -> Self {
        sqlx::migrate!("store/sqlite/migrations")
            .run(&pool)
            .await
            .expect(
                "Failed to execute migrations. This appears to be a secd issue. File a bug at https://www.github.com/secd-lib"
            );

        sqlx::query("pragma foreign_keys = on")
            .execute(&pool)
            .await
            .expect(
                "Failed to initialize FK pragma. File a bug at https://www.github.com/secd-lib",
            );

        SqliteClient { pool }
    }
}

impl SqliteClient {
    async fn read_identity_raw_id(&self, id: &Uuid) -> Result<i64, StoreError> {
        Ok(sqlx::query_as::<_, (i64,)>(
            "
select identity_id from identity where identity_public_id = ?",
        )
        .bind(id)
        .fetch_one(&self.pool)
        .await
        .map_err(util::log_err)?
        .0)
    }

    async fn read_email_raw_id(&self, address: &str) -> Result<i64, StoreError> {
        Ok(sqlx::query_as::<_, (i64,)>(
            "
select email_id from email where address = ?",
        )
        .bind(address)
        .fetch_one(&self.pool)
        .await
        .map_err(util::log_err)?
        .0)
    }
}

#[async_trait::async_trait]
impl Store for SqliteClient {
    async fn write_email(&self, identity_id: Uuid, email_address: &str) -> Result<(), StoreError> {
        let mut tx = self.pool.begin().await?;

        let identity_id = self.read_identity_raw_id(&identity_id).await?;

        let email_id: (i64,) = sqlx::query_as(
            "
insert into email (address) values (?) returning email_id",
        )
        .bind(email_address)
        .fetch_one(&mut tx)
        .await
        .map_err(util::log_err)?;

        debug!("identity: {}, email: {}", identity_id, email_id.0);

        sqlx::query(
            "
insert into identity_email (identity_id, email_id) values (?,?);",
        )
        .bind(identity_id)
        .bind(email_id.0)
        .execute(&mut tx)
        .await
        .map_err(util::log_err)?;

        tx.commit().await?;

        Ok(())
    }

    async fn write_email_validation_request(
        &self,
        identity_id: Uuid,
        email_address: &str,
    ) -> Result<Uuid, StoreError> {
        let identity_id = self.read_identity_raw_id(&identity_id).await?;
        let email_id = self.read_email_raw_id(email_address).await?;

        let request_id = Uuid::new_v4();
        sqlx::query("
insert into email_validation_request (email_validation_request_public_id, identity_email_id, is_validated)
values (?, (select identity_email_id from identity_email where identity_id = ? and email_id =?), ?)",
        )
            .bind(request_id)
            .bind(identity_id)
            .bind(email_id)
            .bind(false)
            .execute(&self.pool)
            .await
            .map_err(util::log_err)?;

        Ok(request_id)
    }

    async fn write_identity(&self, i: &Identity) -> Result<(), StoreError> {
        sqlx::query(
            "
insert into identity (identity_public_id, data, created_at) values (?, ?, ?)",
        )
        .bind(i.id)
        .bind(i.data.clone())
        .bind(i.created_at)
        .execute(&self.pool)
        .await
        .map_err(|e| {
            error!("{:?}", e);
            e
        })?;

        Ok(())
    }

    async fn read_identity(&self, id: &Uuid) -> Result<Identity, StoreError> {
        Ok(sqlx::query_as::<_, Identity>(
            "
select identity_public_id, data, created_at from identity where identity_public_id = ?",
        )
        .bind(id)
        .fetch_one(&self.pool)
        .await
        .map_err(util::log_err)?)
    }

    async fn find_identity(
        &self,
        id: Option<&Uuid>,
        email: Option<&str>,
    ) -> Result<Option<Identity>, StoreError> {
        Ok(
            match sqlx::query_as::<_, Identity>(
                "
select identity_public_id, data, i.created_at
from identity       i
join identity_email ie using (identity_id)
join email          e  using (email_id)
where ((? is null) or (i.identity_public_id = ?))
and   ((? is null) or (e.address = ?));",
            )
            .bind(id)
            .bind(id)
            .bind(email)
            .bind(email)
            .fetch_one(&self.pool)
            .await
            {
                Ok(i) => Some(i),
                Err(sqlx::Error::RowNotFound) => None,
                Err(e) => return Err(StoreError::SqlxError(e)),
            },
        )
    }
}