Files
jap_learn/src/data_provider/sqlite.rs
T
2026-08-31 11:23:41 +03:00

87 lines
2.7 KiB
Rust

use crate::fs::*;
use rusqlite::Connection;
pub fn create_db() {
let db_file = db_path();
if !db_file.exists() {
std::fs::File::create(&db_file).expect("Database file creation failed");
let connection = Connection::open(&db_file).expect("Connection open failed");
connection
.execute("PRAGMA foreign_keys = ON;", [])
.expect("Failed to set PRAGMA");
create_tables(&connection);
}
}
fn create_tables(conn: &Connection) {
make_card_set(conn).expect("Failed to init table");
make_settings(conn).expect("Failed to init table");
make_word_group(conn).expect("Failed to init table");
make_words(conn).expect("Failed to init table");
make_card_stats(conn).expect("Failed to init table");
make_history(conn).expect("Failed to init table");
make_custom_fields(conn).expect("Failed to init table");
}
fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/settings.sql");
conn.execute(query, ())?;
Ok(())
}
fn make_card_set(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/decks.sql");
conn.execute(query, ())?;
Ok(())
}
fn make_word_group(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/word_groups.sql");
conn.execute(query, ())?;
conn.execute("insert into word_groups (name) values (\"Слова\");", ())?;
Ok(())
}
fn make_words(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/words.sql");
conn.execute(query, ())?;
Ok(())
}
fn make_card_stats(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/states.sql");
conn.execute(query, ())?;
Ok(())
}
fn make_history(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/history.sql");
conn.execute(query, ())?;
Ok(())
}
fn make_custom_fields(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/custom_fields.sql");
conn.execute(query, ())?;
Ok(())
}
pub fn default_connection() -> Connection {
let db_file = db_path();
let connection = Connection::open(db_file).expect("Failed to open database");
connection
.execute("PRAGMA foreign_keys = ON;", [])
.expect("Failed to set PRAGMA");
connection
.query_one("PRAGMA journal_mode = WAL;", [], |row| {
println!("{:?}", row);
Ok(())
})
.unwrap_or_else(|e| {
println!("{}", e);
});
connection
.execute("PRAGMA synchronous = NORMAL;", [])
.expect("Failed to set PRAGMA");
connection
}