valis_core/modules/db/
mod.rs1use std::fmt::Error;
2
3use rusqlite::{Connection, Row};
4
5pub mod serializers;
6
7pub trait DatabaseOperations<T> {
8 fn save(&self, db: &str) -> Result<(), Error>;
9 fn get(id: T, db: &str) -> Result<Self, rusqlite::Error> where Self: Sized;
10 fn get_all(db: &str) -> Result<Vec<Self>, rusqlite::Error>
11 where
12 Self: Sized;
13 fn map(row: &Row<'_>) -> Result<Self, rusqlite::Error> where Self: Sized;
14}
15
16fn get_sql_schema() -> Vec<String> {
17 include_str!("tables.sql").split("---").map(|s| s.to_string()).collect::<Vec<String>>()
18}
19
20pub fn init_db(db: &str) -> Result<(), rusqlite::Error> {
21 let conn = Connection::open(db)?;
22
23 get_sql_schema().into_iter().for_each(|sql| {
24 conn.execute(&sql, []).ok().unwrap();
25 });
26
27 Ok(())
28}
29
30pub fn get_connection(db: &str) -> Connection {
31 match Connection::open(db) {
32 Ok(conn) => conn,
33 Err(e) => {
34 println!("Failed to open database: {}", e);
35 std::process::exit(1);
36 }
37 }
38}