1use rusqlite::{Connection, Result};
2
3pub mod prayers_times_db;
4
5pub use rusqlite::Error;
6
7struct DB {
8 pub conn: Connection,
9 pub db_path: String,
10 pub tables: Vec<Table>,
11}
12
13struct Table {
14 pub name: String,
15 pub schema: String,
16}
17
18impl Table {
19 pub fn new(name: String, schema: String) -> Self {
20 Self { name, schema }
21 }
22}
23
24impl DB {
25 pub fn new(db_path: String, tables: Vec<Table>) -> Result<Self> {
26 let conn = Connection::open(db_path.clone())?;
27 let mut db = DB {
28 conn,
29 db_path,
30 tables,
31 };
32 db.make_schema()?;
33 Ok(db)
34 }
35
36 fn make_schema(&mut self) -> Result<()> {
37 for table in &self.tables {
38 let sql = format!(
39 "CREATE TABLE IF NOT EXISTS {} ({})",
40 table.name, table.schema
41 );
42 self.conn.execute(&sql, [])?;
43 }
44 Ok(())
45 }
46
47 pub fn push(&mut self, table_name: String, data: &[(&str, &dyn rusqlite::ToSql)]) -> Result<()> {
48 let columns: Vec<&str> = data.iter().map(|(col, _)| *col).collect();
49 let placeholders: Vec<String> = (0..data.len()).map(|i| format!("?{}", i + 1)).collect();
50
51 let sql = format!(
52 "INSERT INTO {} ({}) VALUES ({})",
53 table_name,
54 columns.join(", "),
55 placeholders.join(", ")
56 );
57
58 let values: Vec<&dyn rusqlite::ToSql> = data.iter().map(|(_, val)| *val).collect();
59 self.conn.execute(&sql, &values[..])?;
60
61 Ok(())
62 }
63}