X-Git-Url: http://git.euphorik.ch/?p=rup.git;a=blobdiff_plain;f=backend%2Fsrc%2Fdb.rs;fp=backend%2Fsrc%2Fdb.rs;h=2bae4fd59c0599fc166ee6182171325ed7c96c18;hp=0000000000000000000000000000000000000000;hb=863db0d616f952ceac10b92dde703bef5093469a;hpb=a44ff4555b6f08fce20f95ab4fae370012caa0aa diff --git a/backend/src/db.rs b/backend/src/db.rs new file mode 100644 index 0000000..2bae4fd --- /dev/null +++ b/backend/src/db.rs @@ -0,0 +1,93 @@ +use std::path::Path; +use std::fs; + +use r2d2_sqlite::SqliteConnectionManager; +use r2d2::Pool; + +use super::consts; + +const CURRENT_DB_VERSION: u32 = 1; + +pub struct Connection { + //con: rusqlite::Connection + pool: Pool +} + +pub struct Recipe { + pub title: String, + pub id: i32, +} + +impl Connection { + pub fn new() -> Connection { + + let data_dir = Path::new(consts::DB_DIRECTORY); + + if !data_dir.exists() { + fs::DirBuilder::new().create(data_dir).unwrap(); + } + + let manager = SqliteConnectionManager::file(consts::DB_FILENAME); + let pool = r2d2::Pool::new(manager).unwrap(); + + let connection = Connection { pool }; + connection.create_or_update(); + connection + } + + fn create_or_update(self: &Self) { + // let connection = Connection::new(); + // let mut stmt = connection.sqlite_con.prepare("SELECT * FROM versions ORDER BY date").unwrap(); + // let mut stmt = connection.sqlite_con..prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'").unwrap(); + + // Check the Database version. + let con = self.pool.get().unwrap(); + + let version = { + match + con.query_row( + "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'", + rusqlite::NO_PARAMS, + |row| row.get::(0) + ) { + Ok(_) => con.query_row("SELECT [version] FROM [Version]", rusqlite::NO_PARAMS, |row| row.get(0)).unwrap_or_default(), + Err(_) => 0 + } + }; + + match version { + 0 => { + println!("Update to version 1..."); + con.execute( + " + CREATE TABLE [Version] ( + [id] INTEGER PRIMARY KEY, + [version] INTEGER NOT NULL, + [datetime] INTEGER DATETIME + ) + ", + rusqlite::NO_PARAMS + ); + con.execute( + " + CREATE TABLE [SetLetterCommand] ( + [id] INTEGER PRIMARY KEY, + [pos_i] INTEGER NOT NULL, + [pos_j] INTEGER NOT NULL, + [color] INTEGER NULL, + [letter] INTEGER NOT NULL, + ) + ", + rusqlite::NO_PARAMS + ); + () + } + v => + panic!("Unsupported database version: {}", v) + }; + } + + pub fn insert_set_letter_command() { + + } +} \ No newline at end of file