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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use crate::Error;

use async_trait::async_trait;
use deadpool_postgres::Pool;
use houseflow_config::postgres::Config;
use houseflow_types::{Device, DeviceID, User, UserID, UserStructure};
use semver::Version;
use tokio_postgres::NoTls;

use refinery::embed_migrations;
embed_migrations!("migrations");

#[derive(Debug, thiserror::Error)]
pub enum InternalError {
    #[error("Error when sending query: `{0}`")]
    QueryError(#[from] tokio_postgres::Error),

    #[error("pool error: {0}")]
    PoolError(#[from] deadpool_postgres::PoolError),

    #[error("Column `{column}` is invalid: `{error}`")]
    InvalidColumn {
        column: &'static str,
        error: Box<dyn std::error::Error + Send + Sync>,
    },

    #[error("Error when running migrations: `{0}`")]
    MigrationError(#[from] refinery::Error),
}

use crate::DatabaseInternalError;

impl DatabaseInternalError for InternalError {}
impl DatabaseInternalError for deadpool_postgres::PoolError {}
impl DatabaseInternalError for tokio_postgres::Error {}
impl DatabaseInternalError for refinery::Error {}

#[derive(Clone)]
pub struct Database {
    pool: Pool,
}

impl Database {
    fn get_pool_config(cfg: &Config) -> deadpool_postgres::Config {
        let mut dpcfg = deadpool_postgres::Config::new();
        dpcfg.user = Some(cfg.user.to_string());
        dpcfg.password = Some(cfg.password.to_string());
        dpcfg.host = Some(cfg.address.ip().to_string());
        dpcfg.port = Some(cfg.address.port());
        dpcfg.dbname = Some(cfg.database_name.to_string());
        dpcfg
    }

    /// This function connect with database and runs migrations on it, after doing so it's fully
    /// ready for operations
    pub async fn new(opts: &Config) -> Result<Self, Error> {
        use std::ops::DerefMut;

        let pool_config = Self::get_pool_config(&opts);
        let pool = pool_config
            .create_pool(NoTls)
            .expect("invalid pool configuration");
        let mut obj = pool.get().await?;
        let client = obj.deref_mut().deref_mut();
        migrations::runner().run_async(client).await?;
        Ok(Self { pool })
    }
}

#[async_trait]
impl crate::Database for Database {
    async fn add_structure(&self, structure: &houseflow_types::Structure) -> Result<(), Error> {
        let connection = self.pool.get().await?;
        let insert_statement = connection
            .prepare(
                r#"
            INSERT INTO structures (id, name) 
            VALUES ($1, $2)
            "#,
            )
            .await?;

        let n = connection
            .execute(&insert_statement, &[&structure.id, &structure.name])
            .await?;

        match n {
            0 => Err(Error::NotModified),
            1 => Ok(()),
            _ => unreachable!(),
        }
    }

    async fn add_room(&self, room: &houseflow_types::Room) -> Result<(), Error> {
        let connection = self.pool.get().await?;
        let insert_statement = connection
            .prepare(
                r#"
            INSERT INTO rooms (id, structure_id, name) 
            VALUES ($1, $2, $3)
            "#,
            )
            .await?;

        let n = connection
            .execute(
                &insert_statement,
                &[&room.id, &room.structure_id, &room.name],
            )
            .await?;

        match n {
            0 => Err(Error::NotModified),
            1 => Ok(()),
            _ => unreachable!(),
        }
    }

    async fn add_device(&self, device: &Device) -> Result<(), Error> {
        let connection = self.pool.get().await?;
        let insert_statement = connection.prepare(
            r#"
            INSERT INTO devices(
                id, room_id, password_hash, type, traits, name, will_push_state, model, hw_version, sw_version, attributes
            ) 
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
            "#,
        ).await?;

        let n = connection
            .execute(
                &insert_statement,
                &[
                    &device.id,
                    &device.room_id,
                    &device.password_hash,
                    &device.device_type.to_string(),
                    &device
                        .traits
                        .iter()
                        .map(|t| t.to_string())
                        .collect::<Vec<String>>(),
                    &device.name,
                    &device.will_push_state,
                    &device.model,
                    &device.hw_version.to_string(),
                    &device.sw_version.to_string(),
                    &device.attributes,
                ],
            )
            .await?;

        match n {
            0 => Err(Error::NotModified),
            1 => Ok(()),
            _ => unreachable!(),
        }
    }

    async fn add_user_structure(&self, user_structure: &UserStructure) -> Result<(), Error> {
        let connection = self.pool.get().await?;
        let insert_statement = connection
            .prepare(
                r#"
            INSERT INTO user_structures (structure_id, user_id, is_manager) 
            VALUES ($1, $2, $3)
            "#,
            )
            .await?;

        let n = connection
            .execute(
                &insert_statement,
                &[
                    &user_structure.structure_id,
                    &user_structure.user_id,
                    &user_structure.is_manager,
                ],
            )
            .await?;

        match n {
            0 => Err(Error::NotModified),
            1 => Ok(()),
            _ => unreachable!(),
        }
    }

    async fn add_user(&self, user: &User) -> Result<(), Error> {
        let connection = self.pool.get().await?;
        let check_exists_statement = connection.prepare(
            r#"
            SELECT 1
            FROM users 
            WHERE email = $1
            OR username = $2
            "#,
        );

        let insert_statement = connection.prepare(
            r#"
            INSERT INTO users(id, username, email, password_hash) 
            VALUES ($1, $2, $3, $4)
            "#,
        );

        let (check_exists_statement, insert_statement) =
            tokio::join!(check_exists_statement, insert_statement);

        let (check_exists_statement, insert_statement) =
            (check_exists_statement?, insert_statement?);

        let exists = connection
            .query_opt(&check_exists_statement, &[&user.email, &user.username])
            .await?
            .is_some();

        if exists {
            return Err(Error::AlreadyExists);
        }

        let n = connection
            .execute(
                &insert_statement,
                &[&user.id, &user.username, &user.email, &user.password_hash],
            )
            .await?;

        match n {
            0 => Err(Error::NotModified),
            1 => Ok(()),
            _ => unreachable!(),
        }
    }

    async fn get_device(&self, device_id: &DeviceID) -> Result<Option<Device>, Error> {
        const QUERY: &str = "
            SELECT * 
            FROM devices 
            WHERE id = $1";
        let connection = self.pool.get().await?;
        let row = match connection.query_opt(QUERY, &[&device_id]).await? {
            Some(row) => row,
            None => return Ok(None),
        };

        let device = Device {
            id: row.try_get("id")?,
            password_hash: row.try_get("password_hash")?,
            device_type: row.try_get("type")?,
            traits: row.try_get("traits")?,
            name: row.try_get("name")?,
            will_push_state: row.try_get("will_push_state")?,
            room_id: row.try_get("room_id")?,
            model: row.try_get("model")?,
            hw_version: Version::parse(row.try_get("hw_version")?).map_err(|err| {
                InternalError::InvalidColumn {
                    column: "hw_version",
                    error: Box::new(err),
                }
            })?,
            sw_version: Version::parse(row.try_get("sw_version")?).map_err(|err| {
                InternalError::InvalidColumn {
                    column: "sw_version",
                    error: Box::new(err),
                }
            })?,
            attributes: row.try_get("attributes")?,
        };

        Ok(Some(device))
    }

    async fn get_user_devices(&self, user_id: &UserID) -> Result<Vec<Device>, Error> {
        let connection = self.pool.get().await?;
        let query_statement = connection
            .prepare(
                r#"
            SELECT *
            FROM devices
            WHERE room_id = (
                SELECT id 
                FROM rooms 
                WHERE structure_id = (
                    SELECT structure_id
                    FROM user_structures
                    WHERE user_id = $1
                )
            )
            "#,
            )
            .await?;
        let row = connection.query(&query_statement, &[&user_id]).await?;
        let devices = row.iter().map(|row| {
            Ok::<Device, Error>(Device {
                id: row.try_get("id")?,
                room_id: row.try_get("room_id")?,
                password_hash: row.try_get("password_hash")?,
                device_type: row.try_get("type")?,
                traits: row.try_get("traits")?,
                name: row.try_get("name")?,
                will_push_state: row.try_get("will_push_state")?,
                model: row.try_get("model")?,
                hw_version: Version::parse(row.try_get("hw_version")?).map_err(|err| {
                    InternalError::InvalidColumn {
                        column: "hw_version",
                        error: Box::new(err),
                    }
                })?,
                sw_version: Version::parse(row.try_get("sw_version")?).map_err(|err| {
                    InternalError::InvalidColumn {
                        column: "sw_version",
                        error: Box::new(err),
                    }
                })?,
                attributes: row.try_get("attributes")?,
            })
        });
        let devices: Result<Vec<Device>, Error> = devices.collect();
        devices
    }

    async fn get_user(&self, user_id: &UserID) -> Result<Option<User>, Error> {
        const QUERY: &str = "SELECT * FROM users WHERE id = $1";
        let connection = self.pool.get().await?;
        let row = match connection.query_opt(QUERY, &[&user_id]).await? {
            Some(row) => row,
            None => return Ok(None),
        };
        let user = User {
            id: row.try_get("id")?,
            username: row.try_get("username")?,
            email: row.try_get("email")?,
            password_hash: row.try_get("password_hash")?,
        };

        Ok(Some(user))
    }

    async fn get_user_by_email(&self, email: &str) -> Result<Option<User>, Error> {
        const QUERY: &str = "SELECT * FROM users WHERE email = $1";
        let connection = self.pool.get().await?;
        let row = match connection.query_opt(QUERY, &[&email.to_string()]).await? {
            Some(row) => row,
            None => return Ok(None),
        };
        let user = User {
            id: row.try_get("id")?,
            username: row.try_get("username")?,
            email: row.try_get("email")?,
            password_hash: row.try_get("password_hash")?,
        };

        Ok(Some(user))
    }

    async fn check_user_device_access(
        &self,
        user_id: &UserID,
        device_id: &DeviceID,
    ) -> Result<bool, Error> {
        let connection = self.pool.get().await?;
        let query_statement = connection
            .prepare(
                r#"
            SELECT 1
            FROM devices
            WHERE id = $1
            AND room_id = ( 
                SELECT id 
                FROM rooms 
                WHERE structure_id = (
                    SELECT structure_id
                    FROM user_structures
                    WHERE user_id = $2
                )
            )
            "#,
            )
            .await?;
        let result = connection
            .query_opt(&query_statement, &[&device_id, &user_id])
            .await?;

        Ok(result.is_some())
    }

    async fn check_user_device_manager_access(
        &self,
        user_id: &UserID,
        device_id: &DeviceID,
    ) -> Result<bool, Error> {
        let connection = self.pool.get().await?;
        let query_statement = connection
            .prepare(
                r#"
            SELECT 1
            FROM devices
            WHERE id = $1
            AND room_id = ( 
                SELECT id 
                FROM rooms 
                WHERE structure_id = (
                    SELECT structure_id
                    FROM user_structures
                    WHERE user_id = $2
                    AND is_manager = true
                )
            )
            "#,
            )
            .await?;
        let result = connection
            .query_opt(&query_statement, &[&device_id, &user_id])
            .await?;

        Ok(result.is_some())
    }

    async fn check_user_admin(&self, user_id: &UserID) -> Result<bool, Error> {
        let connection = self.pool.get().await?;
        let query_statement = connection
            .prepare(
                r#"
            SELECT 1
            FROM admins
            WHERE user_id = $1
            "#,
            )
            .await?;

        let result = connection.query_opt(&query_statement, &[&user_id]).await?;

        Ok(result.is_some())
    }

    async fn delete_user(&self, user_id: &UserID) -> Result<(), Error> {
        const QUERY: &str = "DELETE FROM users WHERE id = $1";
        let connection = self.pool.get().await?;
        let n = connection.execute(QUERY, &[&user_id]).await?;
        match n {
            0 => Err(Error::NotModified),
            1 => Ok(()),
            _ => unreachable!(),
        }
    }
}