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 --- .gitignore | 1 + Cargo.lock | 80 +++++++----- Cargo.toml | 5 +- data.db | Bin 24576 -> 24576 bytes src/commands/list.rs | 10 +- src/commands/modification.rs | 28 ++-- src/commands/setup.rs | 6 +- src/commands/update.rs | 4 +- src/db.rs | 297 +++++++++++++++++++++++++------------------ tests/db/mod.rs | 3 - tests/db_integration.rs | 115 ++++++++++++++++- 11 files changed, 367 insertions(+), 182 deletions(-) delete mode 100644 tests/db/mod.rs diff --git a/.gitignore b/.gitignore index c91ef38..fbc8fea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /target /api-tests /dl +/test_tmp .planmodlist.autosave.xopp diff --git a/Cargo.lock b/Cargo.lock index 29e309e..8a0d2fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -232,6 +232,18 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "1.8.0" @@ -372,6 +384,15 @@ dependencies = [ "ahash", ] +[[package]] +name = "hashlink" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69fe1fcf8b4278d860ad0548329f892a3631fb63f82574df68275f34cdbe0ffa" +dependencies = [ + "hashbrown", +] + [[package]] name = "hermit-abi" version = "0.1.19" @@ -549,6 +570,17 @@ version = "0.2.137" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" +[[package]] +name = "libsqlite3-sys" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29f835d03d717946d28b1d1ed632eb6f0e24a299388ee623d0c23118d3e8a7fa" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "link-cplusplus" version = "1.0.7" @@ -615,15 +647,15 @@ dependencies = [ [[package]] name = "modlist" -version = "0.1.0" +version = "0.2.1" dependencies = [ "chrono", "config", "futures-util", "reqwest", + "rusqlite", "serde", "serde_json", - "sqlite", "tokio", ] @@ -927,6 +959,20 @@ dependencies = [ "serde", ] +[[package]] +name = "rusqlite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e213bc3ecb39ac32e81e51ebe31fd888a940515173e3a18a35f8c6e896422a" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rust-ini" version = "0.18.0" @@ -1076,36 +1122,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "sqlite" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "125b4c6f5428ee2fc895b6c3633f7761084028481bca9a02dce6477d80eff083" -dependencies = [ - "libc", - "sqlite3-sys", -] - -[[package]] -name = "sqlite3-src" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1815a7a02c996eb8e5c64f61fcb6fd9b12e593ce265c512c5853b2513635691" -dependencies = [ - "cc", - "pkg-config", -] - -[[package]] -name = "sqlite3-sys" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d47c99824fc55360ba00caf28de0b8a0458369b832e016a64c13af0ad9fbb9ee" -dependencies = [ - "libc", - "sqlite3-src", -] - [[package]] name = "syn" version = "1.0.103" diff --git a/Cargo.toml b/Cargo.toml index d5c39d2..336c8e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "modlist" -version = "0.1.0" +version = "0.2.1" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -11,6 +11,7 @@ tokio = { version = "1", features = ["full"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0.87" config = "0.13.2" -sqlite = "0.28.0" +rusqlite = { version = "0.28.0", features = ["bundled"] } +# sqlite = "0.28.0" futures-util = "0.3.14" chrono = "0.4.22" diff --git a/data.db b/data.db index f878ca1..07e57ad 100644 Binary files a/data.db and b/data.db differ diff --git a/src/commands/list.rs b/src/commands/list.rs index 3dfe1ad..ffa5926 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,6 +1,6 @@ use std::io::{Error, ErrorKind}; -use crate::{db::{insert_list, remove_list, change_list, get_lists, get_current_list_id, get_list}, Modloader, config::Cfg, input::Input}; +use crate::{db::{lists_insert, remove_list, change_list, get_lists, get_current_list_id, get_list}, Modloader, config::Cfg, input::Input}; #[derive(Clone)] pub struct List { @@ -52,8 +52,8 @@ fn add(config: Cfg, args: Vec) -> Result<(), Box> "fabric" => Modloader::Fabric, _ => return Err(Box::new(Error::new(ErrorKind::InvalidInput, "UNKNOWN_MODLOADER"))) }; - match insert_list(config, id, mc_version, mod_loader) { - Err(err) => { Err(Box::new(err)) }, + match lists_insert(config, id, mc_version, mod_loader) { + Err(err) => { Err(Box::new(Error::new(ErrorKind::Other, "TBD"))) }, Ok(()) => Ok(()), } }, @@ -69,7 +69,7 @@ fn change(config: Cfg, args: Vec) -> Result<(), Box { Err(Box::new(err)) }, + Err(err) => { Err(Box::new(Error::new(ErrorKind::Other, "TBD"))) }, Ok(()) => Ok(()), } }, @@ -82,7 +82,7 @@ fn remove(config: Cfg, args: Vec) -> Result<(), Box { match remove_list(config, String::from(&args[0])) { - Err(err) => { Err(Box::new(err)) }, + Err(err) => { Err(Box::new(Error::new(ErrorKind::Other, "TBD"))) }, Ok(()) => Ok(()), } }, diff --git a/src/commands/modification.rs b/src/commands/modification.rs index e877a63..7836735 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -1,6 +1,6 @@ use std::io::{Error, ErrorKind}; -use crate::{modrinth::{project, versions, extract_current_version}, config::Cfg, db::{insert_mod, remove_mod_from_list, get_mod_id, insert_mod_in_list, get_mods, get_mods_from_list}, input::Input, get_current_list}; +use crate::{modrinth::{project, versions, extract_current_version}, config::Cfg, db::{mods_insert, userlist_remove, mods_get_id, userlist_insert, mods_get_all_ids, userlist_get_all_ids}, input::Input, get_current_list}; pub async fn modification(config: Cfg, args: Option>) -> Result<(), Box> { @@ -40,31 +40,37 @@ async fn add(config: Cfg, args: Vec) -> Result<(), Box = Vec::new(); + for ver in available_versions { + available_versions_vec.push(ver.id); + } //add to current list and mod table - match get_mods_from_list(config.clone(), current_list.clone()) { + match userlist_get_all_ids(config.clone(), current_list.clone().id) { Ok(mods) => { dbg!(&mods); if mods.contains(&project.id) { return Err(Box::new(Error::new(ErrorKind::Other, "MOD_ALREADY_ON_LIST"))); } else { - insert_mod_in_list(config.clone(), current_list.clone(), String::from(&project.id), current_version.id, available_versions, file)?; + userlist_insert(config.clone(), current_list.id, String::from(&project.id), current_version.id, available_versions_vec, file)?; } }, - Err(..) => insert_mod_in_list(config.clone(), current_list, String::from(&project.id), current_version.id, available_versions, file)?, + Err(..) => userlist_insert(config.clone(), current_list.id, String::from(&project.id), current_version.id, available_versions_vec, file)?, }; - match get_mods(config.clone()) { + match mods_get_all_ids(config.clone()) { Ok(mods) => { dbg!(&mods); if mods.contains(&project.id) { return Err(Box::new(Error::new(ErrorKind::Other, "MOD_ALREADY_IN_DATABASE"))) } else { - insert_mod(config.clone(), String::from(&project.id), String::from(&project.title), project.versions)?; + mods_insert(config.clone(), String::from(&project.id), String::from(&project.title), project.versions)?; } }, - Err(..) => insert_mod(config.clone(), String::from(&project.id), String::from(&project.title), project.versions)?, + Err(..) => { + mods_insert(config.clone(), String::from(&project.id), String::from(&project.title), project.versions)?; + }, }; - Ok(()) } @@ -72,11 +78,11 @@ fn remove(config: Cfg, args: Vec) -> Result<(), Box { Err(Box::new(err)) }, + match userlist_remove(config, current_list.id, mod_id) { + Err(..) => { Err(Box::new(Error::new(ErrorKind::Other, "TBD"))) }, Ok(()) => Ok(()), } } diff --git a/src/commands/setup.rs b/src/commands/setup.rs index 0223a21..0940959 100644 --- a/src/commands/setup.rs +++ b/src/commands/setup.rs @@ -1,6 +1,6 @@ use std::{fs::File, path::Path, io::{Error, ErrorKind}}; -use crate::{config::Cfg, db::{db_setup, get_dbversion, create_dbversion, insert_column, get_lists, get_list, get_current_versions, insert_dl_link}, modrinth::get_raw_versions}; +use crate::{config::Cfg, db::{db_setup, user_dbversion, create_dbversion, insert_column, get_lists, get_list, get_current_versions, insert_dl_link}, modrinth::get_raw_versions}; pub async fn setup(config: Cfg) -> Result<(), Box> { @@ -10,7 +10,7 @@ pub async fn setup(config: Cfg) -> Result<(), Box> { return create(config, db_file); } - match get_dbversion(config.clone()) { + match user_dbversion(config.clone()) { Ok(ver) => { match ver.as_str() { _ => return Err(Box::new(Error::new(ErrorKind::Other, "UNKNOWN_VERSION"))) @@ -33,7 +33,7 @@ async fn to_02(config: Cfg) -> Result<(), Box> { for list in lists { println!("Updating {}", list); - insert_column(config.clone(), String::from(&list), String::from("current_download"), sqlite::Type::String)?; + insert_column(config.clone(), String::from(&list), String::from("current_download"), String::new())?; let full_list = get_list(config.clone(), String::from(&list))?; diff --git a/src/commands/update.rs b/src/commands/update.rs index 284d289..d278a78 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -4,13 +4,13 @@ use reqwest::Client; use futures_util::StreamExt; -use crate::{config::Cfg, modrinth::{projects, Project, versions, extract_current_version, Version}, get_current_list, db::{get_mods_from_list, get_versions, get_list_version, change_list_versions}, List}; +use crate::{config::Cfg, modrinth::{projects, Project, versions, extract_current_version, Version}, get_current_list, db::{userlist_get_all_ids, get_versions, get_list_version, change_list_versions}, List}; pub async fn update(config: Cfg) -> Result<(), Box> { let current_list = get_current_list(config.clone())?; - let mods = get_mods_from_list(config.clone(), current_list.clone())?; + let mods = userlist_get_all_ids(config.clone(), current_list.clone().id)?; let mut versions = get_versions(config.clone(), mods.clone())?; versions.sort_by_key(|ver| ver.mod_id.clone()); 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(()) } diff --git a/tests/db/mod.rs b/tests/db/mod.rs deleted file mode 100644 index 50e6887..0000000 --- a/tests/db/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub fn setup() { - //File::create("./setuptests").unwrap(); -} diff --git a/tests/db_integration.rs b/tests/db_integration.rs index f580595..8c3d194 100644 --- a/tests/db_integration.rs +++ b/tests/db_integration.rs @@ -1,6 +1,115 @@ -mod db; +use std::{fs::{File, create_dir_all}, path::Path, sync::Once}; + +use modlist::{config::{Cfg, Apis}, db::{mods_insert, db_setup, user_dbversion, mods_get_all_ids, mods_get_id, mods_remove, userlist_insert, lists_insert, userlist_get_all_ids, userlist_remove}, Modloader}; + +static INIT: Once = Once::new(); + +fn setup() -> Cfg { + let db_pathstr = "./test_tmp/db"; + + let config = Cfg { data: String::from(db_pathstr), downloads: String::from("-"), clean_remove: false, apis: Apis { modrinth: String::from("-") } }; + + INIT.call_once(|| { + let db_path = Path::new(db_pathstr); + create_dir_all(db_path).unwrap(); + let db_filestr = format!("{}/data.db", db_pathstr); + File::create(db_filestr).unwrap(); + println!("INIT TEST DB"); + db_setup(config.clone()).unwrap(); + }); + config +} + +#[test] +fn test_user_dbversion() { + let config = setup(); + + assert_eq!(user_dbversion(config).unwrap(), "0.2"); +} + +#[test] +fn test_mods_insert() { + let config = setup(); + + mods_insert(config.clone(), String::from("I"), String::from("INSERT_TEST"), vec![String::from("INSERT_VER1"), String::from("INSERT_VER2")]).unwrap(); + let ids = mods_get_all_ids(config).unwrap(); + + assert!(ids.contains(&String::from("I"))); +} + +#[test] +fn test_mods_get_all_ids() { + let config = setup(); + + mods_insert(config.clone(), String::from("GAI1"), String::from("GETALLIDS_TEST1"), vec![String::from("GAI1_VER1"), String::from("GAI1_VER2")]).unwrap(); + mods_insert(config.clone(), String::from("GAI2"), String::from("GETALLIDS_TEST2"), vec![String::from("GAI2_VER1"), String::from("GAI2_VER2")]).unwrap(); + let ids = mods_get_all_ids(config).unwrap(); + + assert!(ids.contains(&String::from("GAI1"))); + assert!(ids.contains(&String::from("GAI2"))); +} + +#[test] +fn test_mods_get_id() { + let config = setup(); + + mods_insert(config.clone(), String::from("GI"), String::from("GETID_TEST"), vec![String::from("GI_VER1"), String::from("GI_VER2")]).unwrap(); + let id = mods_get_id(config, String::from("GETID_TEST")).unwrap(); + + assert_eq!(id, String::from("GI")); +} + +#[test] +fn test_mods_remove() { + let config = setup(); + + mods_insert(config.clone(), String::from("R"), String::from("REMOVE_TEST"), vec![String::from("R_VER1"), String::from("R_VER2")]).unwrap(); + let ids = mods_get_all_ids(config.clone()).unwrap(); + assert!(ids.contains(&String::from("R"))); + mods_remove(config.clone(), String::from("R")).unwrap(); + assert!(mods_get_id(config, String::from("REMOVE_TEST")).is_err()); +} + +//user_list +#[test] +fn test_userlist_insert() { + let config = setup(); + + lists_insert(config.clone(), String::from("UL_I_LIST"), String::from("UL_I_MC"), Modloader::Fabric).unwrap(); + userlist_insert(config, String::from("UL_I_LIST"), String::from("UL_I"), String::from("UL_I_VER1"), vec![String::from("UL_I_VER1"), String::from("UL_I_VER2")], String::from("localhost:8080/dl/UL_I_VER1.test")).unwrap(); + //let list = mods_get_all_ids(config).unwrap(); + + //assert!(ids.contains(&String::from("I"))); +} + +#[test] +fn test_userlist_get_all_ids() { + let config = setup(); + + lists_insert(config.clone(), String::from("UL_GAI_LIST"), String::from("UL_GAI_MC"), Modloader::Fabric).unwrap(); + userlist_insert(config.clone(), String::from("UL_GAI_LIST"), String::from("UL_GAI1"), String::from("UL_GAI1_VER1"), vec![String::from("UL_GAI2_VER1"), String::from("UL_GAI1_VER2")], String::from("localhost:8080/dl/UL_GAI1_VER1.test")).unwrap(); + userlist_insert(config.clone(), String::from("UL_GAI_LIST"), String::from("UL_GAI2"), String::from("UL_GAI2_VER1"), vec![String::from("UL_GAI2_VER1"), String::from("UL_GAI2_VER2")], String::from("localhost:8080/dl/UL_GAI2_VER1.test")).unwrap(); + let ids = userlist_get_all_ids(config, String::from("UL_GAI_LIST")).unwrap(); + + assert!(ids.contains(&String::from("UL_GAI1"))); + assert!(ids.contains(&String::from("UL_GAI2"))); +} #[test] -fn test_add() { - db::setup(); +fn test_userlist_remove() { + let config = setup(); + + lists_insert(config.clone(), String::from("UL_R_LIST"), String::from("UL_R_MC"), Modloader::Fabric).unwrap(); + userlist_insert(config.clone(), String::from("UL_R_LIST"), String::from("UL_R"), String::from("UL_R_VER1"), vec![String::from("UL_R_VER1"), String::from("UL_R_VER2")], String::from("localhost:8080/dl/UL_R_VER1.test")).unwrap(); + let ids = userlist_get_all_ids(config.clone(), String::from("UL_R_LIST")).unwrap(); + assert!(ids.contains(&String::from("UL_R"))); + userlist_remove(config.clone(), String::from("UL_R_LIST"), String::from("UL_R")).unwrap(); + assert!(userlist_get_all_ids(config, String::from("UL_R_LIST")).is_err()) +} +//lists +#[test] +fn test_lists_insert() { + let config = setup(); + + lists_insert(config, String::from("TESTLIST"), String::from("L_I_LIST"), Modloader::Fabric).unwrap(); } -- cgit v1.2.3