Initial commit.
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
use rusqlite::Connection as RusqliteConnection;
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
use diesel::{Connection, SqliteConnection};
|
||||
|
||||
pub struct DatabaseConnection {
|
||||
pub connection: RusqliteConnection,
|
||||
pub diesel_connection: SqliteConnection,
|
||||
pub database_has_been_created: bool,
|
||||
}
|
||||
|
||||
impl DatabaseConnection {
|
||||
pub fn init() -> Self {
|
||||
let sqlite_database_name = env::var("SQLITE_DATABASE_NAME").expect("SQLITE_DATABASE_NAME must be set.");
|
||||
|
||||
let database_existed_before_connection_initialisation = does_database_exist(&sqlite_database_name);
|
||||
|
||||
let connection = RusqliteConnection::open(sqlite_database_name.clone())
|
||||
.expect("Unable to connect to SQLite database…");
|
||||
|
||||
let diesel_connection = SqliteConnection::establish(&sqlite_database_name.clone())
|
||||
.unwrap_or_else(|_| panic!("Error connecting to {}", sqlite_database_name.clone()));
|
||||
|
||||
Self {
|
||||
connection,
|
||||
diesel_connection,
|
||||
database_has_been_created: !database_existed_before_connection_initialisation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn does_database_exist(database_name: &String) -> bool {
|
||||
Path::new(database_name).exists()
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
use rusqlite::{Connection, Error};
|
||||
|
||||
pub fn initialise_database_tables(connection: &Arc<Mutex<Connection>>) -> Result<(), Error> {
|
||||
connection.lock()
|
||||
.unwrap()
|
||||
.execute_batch(
|
||||
"
|
||||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS configuration (
|
||||
id TEXT PRIMARY KEY,
|
||||
initialisation_code VARCHAR
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS system_resources (
|
||||
id TEXT PRIMARY KEY,
|
||||
datetime INTEGER NOT NULL,
|
||||
cpu_usage INTEGER NOT NULL,
|
||||
total_memory INTEGER NOT NULL,
|
||||
used_memory INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS \"user\" (
|
||||
id TEXT PRIMARY KEY,
|
||||
username VARCHAR NOT NULL,
|
||||
encrypted_password VARCHAR NOT NULL
|
||||
);
|
||||
COMMIT;
|
||||
"
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod database_connection;
|
||||
pub mod database_initialisation;
|
||||
Reference in New Issue
Block a user