learn-hieroglyphs/src/db.rs

43 lines
1.5 KiB
Rust
Raw Normal View History

2024-04-05 19:04:46 +03:00
use rusqlite::Connection;
use std::{sync::RwLock, path::PathBuf, process::Command};
pub static PROGRAM_HOME_PATH: RwLock<std::string::String> = RwLock::new(String::new());
2024-04-05 15:01:24 +03:00
pub fn init() {
let program_home_path = if cfg!(target_os = "windows") {
let binding = std::env::var("APP_DATA").expect("No APP_DATA directory");
let mut appdata = PathBuf::from(&binding);
appdata = appdata.join("learn-hieroglyph");
2024-04-05 19:32:10 +03:00
Command::new("mkdir").arg(&appdata).spawn().expect(&format!("Cannot create program's home: {}", &appdata.to_str().unwrap())).wait().unwrap();
2024-04-05 15:01:24 +03:00
appdata
} else {
let binding = std::env::var("HOME").expect("No HOME directory");
let mut home = PathBuf::from(&binding);
home = home.join(".config/learn-hieroglyph");
2024-04-05 19:32:10 +03:00
Command::new("mkdir").args(["-p", &home.to_str().unwrap()]).spawn().expect(&format!("Cannot create program's home: {}", &home.to_str().unwrap())).wait().unwrap();
2024-04-05 15:01:24 +03:00
home
};
2024-04-05 19:04:46 +03:00
let mut p = PROGRAM_HOME_PATH.write().unwrap();
*p = program_home_path.as_path().to_str().unwrap().to_string();
2024-04-05 15:01:24 +03:00
2024-04-05 19:32:10 +03:00
let db_path = program_home_path.join("db.sqlite");
2024-04-05 15:01:24 +03:00
2024-04-05 19:32:10 +03:00
let connection = Connection::open(db_path).unwrap();
2024-04-05 15:01:24 +03:00
connection.execute("CREATE TABLE IF NOT EXISTS cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
image_hash CHAR(64),
hieroglyph VARCHAR(2),
translation VARCHAR(128)
2024-04-05 19:04:46 +03:00
)",(),).unwrap();
2024-04-05 15:01:24 +03:00
}
2024-04-05 19:04:46 +03:00
pub fn get_program_home_path() -> &'static RwLock<String> {
&PROGRAM_HOME_PATH
}