From ea50af892c4268ae06f6df40ee435eadd076228d Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Sun, 6 Nov 2022 23:06:54 +0100 Subject: halfswitch to rusqlite; db tests --- src/db.rs | 297 +++++++++++++++++++++++++++++++++++++------------------------- 1 file changed, 176 insertions(+), 121 deletions(-) (limited to 'src/db.rs') diff --git a/src/db.rs b/src/db.rs index 88a104d..86e697e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,122 +1,124 @@ -use std::io::ErrorKind; +use std::io::{Error, ErrorKind}; -use crate::{Modloader, config::Cfg, List, modrinth::Version, get_modloader}; +use rusqlite::Connection; -//TODO use prepared statements / change to rusqlite +use crate::{Modloader, config::Cfg, List}; //MODS -pub fn insert_mod(config: Cfg, id: String, name: String, versions: Vec) -> Result<(), sqlite::Error> { +pub fn mods_insert(config: Cfg, id: String, name: String, versions: Vec) -> Result<(), Box> { - println!("Inserting into modlist"); + println!("Inserting mod {}({}) into database", name, id); let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); - - let sql = format!("INSERT INTO mods VALUES ('{}', '{}', '{}')", id, name.replace('\'', ""), versions.join("|")); + let connection = Connection::open(data)?; - dbg!(&sql); + connection.execute( + "INSERT INTO mods (id, name, versions) VALUES (?1, ?2, ?3)", + [id, name.replace('\'', ""), versions.join("|")] + )?; - connection.execute(sql) + Ok(()) } -pub fn insert_mod_in_list(config: Cfg, list: List, id: String, current_version: String, applicable_versions: Vec, current_link: String) -> Result<(), sqlite::Error> { - - println!("Inserting into current list"); - +pub fn mods_get_all_ids(config: Cfg) -> Result, Box> { let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); + let connection = Connection::open(data).unwrap(); + + let mut mods: Vec = Vec::new(); - let mut applicable_versions_vec = vec![]; + let mut stmt = connection.prepare("SELECT id FROM mods")?; + let id_iter = stmt.query_map([], |row| { + row.get::(0) + })?; - for ver in applicable_versions { - applicable_versions_vec.push(ver.id); + for id in id_iter { + println!("Found id {:?}", id.as_ref().unwrap()); + mods.push(id?); } - let sql = format!("INSERT INTO {} VALUES ('{}', '{}', '{}', '{}')", list.id, id, current_version, applicable_versions_vec.join("|"), current_link); + match mods.is_empty() { + true => Err(Box::new(Error::new(ErrorKind::NotFound, "NO_MODS"))), + false => Ok(mods), + } +} + +pub fn mods_get_id(config: Cfg, name: String) -> Result> { + let data = format!("{}/data.db", config.data); + let connection = Connection::open(data)?; - connection.execute(sql) + let mut mod_id = String::new(); + let mut stmt = connection.prepare("SELECT id FROM mods WHERE name = ?")?; + let id_iter = stmt.query_map([name], |row| { + row.get::(0) + })?; + + for id in id_iter { + println!("Found id {:?}", id.as_ref().unwrap()); + mod_id = id?; + }; + + match mod_id.is_empty() { + true => Err(Box::new(Error::new(ErrorKind::NotFound, "MOD_NOT_FOUND"))), + false => Ok(mod_id), + } } -pub fn remove_mod_from_list(config: Cfg, list: List, mod_id: String) -> Result<(), sqlite::Error> { +pub fn mods_remove(config: Cfg, id: String) -> Result<(), Box> { + + println!("Removing mod {} from database", id); + let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); + let connection = Connection::open(data)?; - let sql = format!("DELETE FROM {} WHERE mod_id = '{}'", list.id, mod_id); - - dbg!(&sql); + connection.execute("DELETE FROM mods WHERE id = ?", [id])?; - connection.execute(sql) + Ok(()) } -pub fn get_mods(config: Cfg) -> Result, Box> { +//userlist +pub fn userlist_insert(config: Cfg, list_id: String, mod_id: String, current_version: String, applicable_versions: Vec, current_link: String) -> Result<(), Box> { + println!("Inserting {} into current list({})", mod_id, list_id); let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); + let connection = Connection::open(data)?; - let sql = "SELECT id FROM mods"; - let mut mods: Vec = Vec::new(); - //TODO catch sql errors better - connection.iterate(sql, |ids| { - if ids.is_empty() { return false; }; - for &(_column, value) in ids.iter() { - mods.push(String::from(value.unwrap())); - } - true - }).unwrap(); - match mods.is_empty() { - true => Err(Box::new(std::io::Error::new(ErrorKind::NotFound, "NO_MODS"))), - false => Ok(mods), - } + connection.execute(format!("INSERT INTO {} VALUES (?1, ?2, ?3, ?4)", list_id).as_str(), [mod_id, current_version, applicable_versions.join("|"), current_link])?; + + Ok(()) } -pub fn get_mods_from_list(config: Cfg, list: List) -> Result, Box> { +pub fn userlist_get_all_ids(config: Cfg, list_id: String) -> Result, Box> { let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); + let connection = Connection::open(data).unwrap(); - let sql = format!("SELECT mod_id FROM {}", list.id); + let mut mod_ids: Vec = Vec::new(); + let mut stmt = connection.prepare(format!("SELECT mod_id FROM {}", list_id).as_str())?; + let id_iter = stmt.query_map([], |row| { + row.get::(0) + })?; - let mut mods: Vec = Vec::new(); - //TODO catch sql errors better - connection.iterate(sql, |ids| { - if ids.is_empty() { return false; }; - for &(_column, value) in ids.iter() { - mods.push(String::from(value.unwrap())); - } - true - }).unwrap(); - match mods.is_empty() { + for id in id_iter { + println!("Found id {:?}", id.as_ref().unwrap()); + mod_ids.push(id?) + }; + + match mod_ids.is_empty() { true => Err(Box::new(std::io::Error::new(ErrorKind::NotFound, "NO_MODS"))), - false => Ok(mods), + false => Ok(mod_ids), } } -pub fn get_mod_id(config: Cfg, name: String) -> Result> { - let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); - let sql = format!("SELECT id FROM mods WHERE name = '{}'", name); - - dbg!(&sql); - - let mut modification = String::new(); - //TODO catch sql errors better - connection.iterate(sql, |id| { - if id.is_empty() { return false; }; - for &(_column, value) in id.iter() { - dbg!(&(_column, value)); - modification = String::from(value.unwrap()); - } - true - }).unwrap(); - - dbg!(&modification); +pub fn userlist_remove(config: Cfg, list_id: String, mod_id: String) -> Result<(), Box> { + let data = format!("{}/data.db", config.data); + let connection = Connection::open(data)?; - if modification.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::NotFound, "MOD_NOT_IN_DATABASE"))) }; - - Ok(modification) + connection.execute(format!("DELETE FROM {} WHERE mod_id = ?", list_id).as_str(), [mod_id])?; + Ok(()) } + #[derive(Debug, Clone)] pub struct DBModlistVersions { pub mod_id: String, @@ -124,36 +126,40 @@ pub struct DBModlistVersions { } pub fn get_versions(config: Cfg, mods: Vec) -> Result, Box> { -let data = format!("{}/data.db", config.data); -let connection = sqlite::open(data).unwrap(); - -let mut wherestr = String::from("WHERE"); -for (i, id) in mods.iter().enumerate() { - let mut or = " OR"; - if i == mods.len() - 1 { or = "" } - println!("Pushing {}({}) | OR: '{}'", id, i, or); - wherestr = format!("{} id = '{}'{}", wherestr, id, or); -} + /* + let data = format!("{}/data.db", config.data); + let connection = sqlite::open(data).unwrap(); -let sql = format!("SELECT id, versions FROM mods {}", wherestr); + let mut wherestr = String::from("WHERE"); + for (i, id) in mods.iter().enumerate() { + let mut or = " OR"; + if i == mods.len() - 1 { or = "" } + println!("Pushing {}({}) | OR: '{}'", id, i, or); + wherestr = format!("{} id = '{}'{}", wherestr, id, or); + } -dbg!(&sql); + let sql = format!("SELECT id, versions FROM mods {}", wherestr); -let mut versionmaps: Vec = Vec::new(); -//TODO catch sql errors better -let mut cursor = connection.prepare(sql).unwrap().into_cursor(); + dbg!(&sql); -while let Some(Ok(row)) = cursor.next() { - println!("{}: {}", row.get::(0), row.get::(1)); - versionmaps.push(DBModlistVersions { mod_id: row.get::(0), versions: row.get::(1) }) -}; + let mut versionmaps: Vec = Vec::new(); + //TODO catch sql errors better + let mut cursor = connection.prepare(sql).unwrap().into_cursor(); -if versionmaps.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_MODS_ON_LIST"))); }; + while let Some(Ok(row)) = cursor.next() { + println!("{}: {}", row.get::(0), row.get::(1)); + versionmaps.push(DBModlistVersions { mod_id: row.get::(0), versions: row.get::(1) }) + }; -Ok(versionmaps) + if versionmaps.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_MODS_ON_LIST"))); }; + + Ok(versionmaps) + */ + Ok(vec![DBModlistVersions { mod_id: String::new(), versions: String::new() }]) } pub fn get_list_version(config: Cfg, list: List, mod_id: String) -> Result> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -172,22 +178,26 @@ pub fn get_list_version(config: Cfg, list: List, mod_id: String) -> Result Result<(), sqlite::Error> { +//lists +pub fn lists_insert(config: Cfg, id: String, mc_version: String, mod_loader: Modloader) -> Result<(), Box> { + println!("Creating list {}", id); + let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); - - let sql_list = format!("INSERT INTO lists VALUES ('{}', '{}', '{}')", id, mc_version, mod_loader.stringify()); - let sql_table = format!("CREATE TABLE '{}' ( 'mod_id' TEXT, 'current_version' TEXT, 'applicable_versions' BLOB, 'current_download' TEXT)", id); - let sql = format!("{};{};", sql_list, sql_table); + let connection = Connection::open(data)?; - connection.execute(sql) + connection.execute("INSERT INTO lists VALUES (?1, ?2, ?3)", [id.clone(), mc_version, mod_loader.stringify()])?; + connection.execute(format!("CREATE TABLE {}( 'mod_id' TEXT, 'current_version' TEXT, 'applicable_versions' BLOB, 'current_download' TEXT)", id).as_str(), [])?; + + Ok(()) } -pub fn remove_list(config: Cfg, id: String) -> Result<(), sqlite::Error> { +pub fn remove_list(config: Cfg, id: String) -> Result<(), Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -196,9 +206,12 @@ pub fn remove_list(config: Cfg, id: String) -> Result<(), sqlite::Error> { let sql = format!("{};{};", sql_list, sql_table); connection.execute(sql) + */ + Ok(()) } pub fn get_lists(config: Cfg) -> Result, Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -217,9 +230,12 @@ pub fn get_lists(config: Cfg) -> Result, Box> true => Err(Box::new(std::io::Error::new(ErrorKind::NotFound, "NO_LISTS"))), false => Ok(list), } + */ + Ok(vec![String::new()]) } pub fn get_current_versions(config: Cfg, list: List) -> Result, Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -238,9 +254,12 @@ pub fn get_current_versions(config: Cfg, list: List) -> Result, Box< if versions.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_MODS_ON_LIST"))); }; Ok(versions) + */ + Ok(vec![String::new()]) } pub fn get_list(config: Cfg, id: String) -> Result> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -259,29 +278,38 @@ pub fn get_list(config: Cfg, id: String) -> Result, mod_id: String) -> Result<(), sqlite::Error> { +pub fn change_list_versions(config: Cfg, list: List, current_version: String, versions: Vec, mod_id: String) -> Result<(), Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); let sql = format!("UPDATE {} SET current_version = '{}', applicable_versions = '{}' WHERE mod_id = '{}'", list.id, current_version, versions.join("|"), mod_id); connection.execute(sql) + */ + Ok(()) } //DOWNLOAD -pub fn insert_dl_link(config: Cfg, list: List, mod_id: String, link: String) -> Result<(), sqlite::Error> { +pub fn insert_dl_link(config: Cfg, list: List, mod_id: String, link: String) -> Result<(), Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); let sql = format!("UPDATE {} SET current_download = '{}' WHERE mod_id = '{}'", list.id, link, mod_id); connection.execute(sql) + */ + Ok(()) } pub fn get_dl_links(config: Cfg, list: List) -> Result, Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -300,19 +328,25 @@ pub fn get_dl_links(config: Cfg, list: List) -> Result, Box Result<(), sqlite::Error> { +pub fn change_list(config: Cfg, id: String) -> Result<(), Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); let sql = format!("UPDATE user_config SET value = '{}' WHERE id = 'current_list'", id); connection.execute(sql) + */ + Ok(()) } pub fn get_current_list_id(config: Cfg) -> Result> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -332,25 +366,34 @@ pub fn get_current_list_id(config: Cfg) -> Result Result<(), sqlite::Error> { +pub fn update_dbversion(config: Cfg, ver: String) -> Result<(), Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); let sql = format!("UPDATE user_config SET value = '{}' WHERE id = 'db_version'", ver); connection.execute(sql) + */ + Ok(()) } -pub fn create_dbversion(config: Cfg) -> Result<(), sqlite::Error> { +pub fn create_dbversion(config: Cfg) -> Result<(), Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); let sql = "INSERT INTO 'user_config' VALUES ( 'db_version', '0.2' );"; connection.execute(sql) + */ + Ok(()) } -pub fn get_dbversion(config: Cfg) -> Result> { +pub fn user_dbversion(config: Cfg) -> Result> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -367,20 +410,30 @@ pub fn get_dbversion(config: Cfg) -> Result> })?; if ver.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_DBVERSION"))); }; Ok(ver) + */ + Ok(String::from("0.2")) } -pub fn db_setup(config: Cfg) -> Result<(), sqlite::Error> { +pub fn db_setup(config: Cfg) -> Result<(), Box> { + println!("Initiating database"); let data = format!("{}/data.db", config.data); - let connection = sqlite::open(data).unwrap(); - - let sql = "CREATE TABLE 'user_config' ( 'id' TEXT, 'value' TEXT ); CREATE TABLE 'mods' ( 'id' TEXT, 'name' TEXT, 'versions' TEXT ); CREATE TABLE 'lists' ( 'id' TEXT, 'mc_version' TEXT, 'modloader' TEXT ); INSERT INTO 'user_config' VALUES ( 'db_version', '0.2' ); INSERT INTO 'user_config' VALUES ( 'current_list', '...' )"; - - connection.execute(sql) + let connection = Connection::open(data)?; + + connection.execute_batch( + "CREATE TABLE 'user_config' ( 'id' TEXT, 'value' TEXT ); + CREATE TABLE 'mods' ( 'id' TEXT, 'name' TEXT, 'versions' TEXT ); + CREATE TABLE 'lists' ( 'id' TEXT, 'mc_version' TEXT, 'modloader' TEXT ); + INSERT INTO 'user_config' VALUES ( 'db_version', '0.2' ); + INSERT INTO 'user_config' VALUES ( 'current_list', '...' )", + )?; + + Ok(()) } -pub fn insert_column(config: Cfg, table: String, column: String, c_type: sqlite::Type) -> Result<(), sqlite::Error> { +pub fn insert_column(config: Cfg, table: String, column: String, c_type: String) -> Result<(), Box> { + /* let data = format!("{}/data.db", config.data); let connection = sqlite::open(data).unwrap(); @@ -394,4 +447,6 @@ pub fn insert_column(config: Cfg, table: String, column: String, c_type: sqlite: let sql = format!("ALTER TABLE {} ADD '{}' {}", table, column, ct); connection.execute(sql) + */ + Ok(()) } -- cgit v1.2.3