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