diff options
Diffstat (limited to 'src/db.rs')
-rw-r--r-- | src/db.rs | 47 |
1 files changed, 46 insertions, 1 deletions
@@ -1,8 +1,53 @@ | |||
1 | use std::env; | ||
2 | |||
1 | use serde::Serialize; | 3 | use serde::Serialize; |
4 | use sqlx::{PgPool, postgres::PgPoolOptions}; | ||
5 | use tracing::{debug, info}; | ||
6 | |||
7 | use crate::error::WebolError; | ||
2 | 8 | ||
3 | #[derive(Serialize)] | 9 | #[derive(Serialize)] |
4 | pub struct Device { | 10 | pub struct Device { |
5 | pub id: String, | 11 | pub id: String, |
6 | pub mac: String, | 12 | pub mac: String, |
7 | pub broadcast_addr: String | 13 | pub broadcast_addr: String |
8 | } \ No newline at end of file | 14 | } |
15 | |||
16 | impl Device { | ||
17 | async fn init(db: &PgPool) -> Result<(), WebolError> { | ||
18 | sqlx::query!(r#" | ||
19 | CREATE TABLE IF NOT EXISTS "devices" | ||
20 | ( | ||
21 | "id" TEXT PRIMARY KEY NOT NULL, | ||
22 | "mac" TEXT NOT NULL, | ||
23 | "broadcast_addr" TEXT NOT NULL | ||
24 | );"# | ||
25 | ).execute(db).await.map_err(|err| WebolError::Server(Box::new(err)))?; | ||
26 | |||
27 | Ok(()) | ||
28 | } | ||
29 | } | ||
30 | |||
31 | pub async fn setup_db(db: &PgPool) -> Result<(), WebolError> { | ||
32 | Device::init(db).await | ||
33 | } | ||
34 | |||
35 | pub async fn init_db_pool() -> PgPool { | ||
36 | #[cfg(not(debug_assertions))] | ||
37 | let db_url = SETTINGS.get_string("database.url").unwrap(); | ||
38 | |||
39 | #[cfg(debug_assertions)] | ||
40 | let db_url = env::var("DATABASE_URL").unwrap(); | ||
41 | |||
42 | debug!("attempt to connect dbPool to '{}'", db_url); | ||
43 | |||
44 | let pool = PgPoolOptions::new() | ||
45 | .max_connections(5) | ||
46 | .connect(&db_url) | ||
47 | .await | ||
48 | .unwrap(); | ||
49 | |||
50 | info!("dbPool successfully connected to '{}'", db_url); | ||
51 | |||
52 | pool | ||
53 | } | ||