|
1 | | -use std::{collections::HashMap, sync::Arc}; |
| 1 | +use std::{path::Path, sync::Arc}; |
2 | 2 |
|
3 | 3 | use serde::Deserialize; |
4 | | -use serde_json::Value; |
| 4 | +use sqlx::{migrate::Migrator, PgPool}; |
5 | 5 | use sword::prelude::*; |
6 | | -use tokio::sync::RwLock; |
7 | | - |
8 | | -pub type Store = Arc<RwLock<HashMap<String, Vec<Value>>>>; |
9 | 6 |
|
10 | 7 | #[derive(Clone, Deserialize)] |
11 | 8 | #[config(key = "db-config")] |
12 | 9 | pub struct DatabaseConfig { |
13 | | - collection_name: String, |
| 10 | + uri: String, |
| 11 | + migrations_path: String, |
14 | 12 | } |
15 | 13 |
|
16 | | -#[injectable(kind = "provider")] |
| 14 | +#[injectable(provider)] |
17 | 15 | pub struct Database { |
18 | | - db: Store, |
| 16 | + pool: Arc<PgPool>, |
19 | 17 | } |
20 | 18 |
|
21 | 19 | impl Database { |
22 | 20 | pub async fn new(db_conf: DatabaseConfig) -> Self { |
23 | | - let db = Arc::new(RwLock::new(HashMap::new())); |
24 | | - |
25 | | - db.write().await.insert(db_conf.collection_name, Vec::new()); |
| 21 | + let pool = PgPool::connect(&db_conf.uri) |
| 22 | + .await |
| 23 | + .expect("Failed to create Postgres connection pool"); |
26 | 24 |
|
27 | | - Self { db } |
28 | | - } |
| 25 | + let migrator = Migrator::new(Path::new(&db_conf.migrations_path)) |
| 26 | + .await |
| 27 | + .unwrap(); |
29 | 28 |
|
30 | | - pub async fn insert(&self, table: &'static str, record: Value) { |
31 | | - let mut db = self.db.write().await; |
| 29 | + migrator |
| 30 | + .run(&pool) |
| 31 | + .await |
| 32 | + .expect("Failed to run database migrations"); |
32 | 33 |
|
33 | | - if let Some(table_data) = db.get_mut(table) { |
34 | | - table_data.push(record); |
| 34 | + Self { |
| 35 | + pool: Arc::new(pool), |
35 | 36 | } |
36 | 37 | } |
37 | 38 |
|
38 | | - pub async fn get_all(&self, table: &'static str) -> Option<Vec<Value>> { |
39 | | - let db = self.db.read().await; |
40 | | - |
41 | | - db.get(table).cloned() |
| 39 | + pub fn get_pool(&self) -> &PgPool { |
| 40 | + &self.pool |
42 | 41 | } |
43 | 42 | } |
0 commit comments