Lot of thing
[recipes.git] / backend / src / db.rs
1 use std::path::Path;
2 use std::fs;
3
4 //use rusqlite::types::ToSql;
5 //use rusqlite::{Connection, Result, NO_PARAMS};
6
7 //extern crate r2d2;
8 //extern crate r2d2_sqlite;
9 //extern crate rusqlite;
10
11 use r2d2_sqlite::SqliteConnectionManager;
12 use r2d2::Pool;
13
14
15 use super::consts;
16
17 const CURRENT_DB_VERSION: u32 = 1;
18
19 pub struct Connection {
20 //con: rusqlite::Connection
21 pool: Pool<SqliteConnectionManager>
22 }
23
24 pub struct Recipe {
25 pub title: String,
26 pub id: i32,
27 }
28
29 impl Connection {
30 pub fn new() -> Connection {
31
32 let data_dir = Path::new(consts::DB_DIRECTORY);
33
34 if !data_dir.exists() {
35 fs::DirBuilder::new().create(data_dir).unwrap();
36 }
37
38 let manager = SqliteConnectionManager::file("file.db");
39 let pool = r2d2::Pool::new(manager).unwrap();
40
41 let connection = Connection { pool };
42 connection.create_or_update();
43 connection
44 }
45
46 fn create_or_update(self: &Self) {
47 // let connection = Connection::new();
48 // let mut stmt = connection.sqlite_con.prepare("SELECT * FROM versions ORDER BY date").unwrap();
49 // let mut stmt = connection.sqlite_con..prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'").unwrap();
50
51 // Check the Database version.
52 let con = self.pool.get().unwrap();
53
54 let version = {
55 match
56 con.query_row(
57 "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",
58 rusqlite::NO_PARAMS,
59 |row| row.get::<usize, String>(0)
60 ) {
61
62 Ok(_) => con.query_row("SELECT [version] FROM [Version]", rusqlite::NO_PARAMS, |row| row.get(0)).unwrap_or_default(),
63 Err(_) => 0
64 }
65 };
66
67 match version {
68 0 => {
69 println!("Update to version 1...");
70 con.execute(
71 "
72 CREATE TABLE [Version] (
73 [id] INTEGER PRIMARY KEY,
74 [version] INTEGER NOT NULL,
75 [datetime] INTEGER DATETIME
76 )
77 ",
78 rusqlite::NO_PARAMS
79 );
80 con.execute(
81 "
82 CREATE TABLE [Recipe] (
83 [id] INTEGER PRIMARY KEY,
84 [title] INTEGER NOT NULL,
85 [description] INTEGER DATETIME
86 )
87 ",
88 rusqlite::NO_PARAMS
89 );
90 ()
91 }
92 v =>
93 panic!("Unsupported database version: {}", v)
94 };
95 }
96
97 pub fn get_all_recipes() {
98
99 }
100 }