summaryrefslogtreecommitdiff
path: root/src/db.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs219
1 files changed, 119 insertions, 100 deletions
diff --git a/src/db.rs b/src/db.rs
index ba14c1a..a899ac3 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -1,16 +1,15 @@
+use crate::flac::{CURRENT_VENDOR, get_vendor};
use anyhow::{Result, anyhow};
use directories::BaseDirs;
-use rusqlite::{Connection, params};
use std::{
path::{Path, PathBuf},
time::UNIX_EPOCH,
};
-
-use crate::flac::{CURRENT_VENDOR, get_vendor};
+use turso::{Connection, params};
const TABLE_CREATE: &str = "CREATE TABLE IF NOT EXISTS flacs (path TEXT PRIMARY KEY UNIQUE, toencode BOOLEAN NOT NULL, modtime INTEGER)";
-const ADD_ITEM: &str = "INSERT INTO flacs (path, toencode, modtime) VALUES (?1, ?2, ?3)";
-const UPDATE_ITEM: &str = "UPDATE flacs SET toencode = ?2, modtime = ?3 WHERE path = ?1";
+const ADD_FILE: &str = "INSERT INTO flacs (path, toencode, modtime) VALUES (?1, ?2, ?3)";
+const UPDATE_FILE: &str = "UPDATE flacs SET toencode = ?2, modtime = ?3 WHERE path = ?1";
const TOENCODE_PATHS: &str = "SELECT path FROM flacs WHERE toencode";
const TOENCODE_NUMBER: &str = "SELECT COUNT(*) from flacs WHERE toencode";
const CHECK_FILE: &str = "SELECT exists(SELECT 1 FROM flacs WHERE path = ?1)";
@@ -20,20 +19,25 @@ const DEDUPE_DB: &str =
"DELETE FROM flacs WHERE rowid NOT IN (SELECT MAX(rowid) FROM flacs GROUP BY path)";
const GET_MODTIME: &str = "SELECT modtime FROM flacs WHERE path = ?1";
-pub(crate) fn init_connection(path: Option<&PathBuf>) -> Result<Connection> {
- let conn = if let Some(file) = path {
- Connection::open(file)?
+pub(crate) async fn init_db(path: Option<&PathBuf>) -> Result<turso::Database> {
+ let db = if let Some(file) = path {
+ turso::Builder::new_local(file.to_str().unwrap())
+ .build()
+ .await?
} else if let Some(base_dir) = BaseDirs::new() {
- let file = Path::new(base_dir.data_dir()).join("reencoder.db");
- Connection::open(file)?
+ let file = base_dir.data_dir().join("reencoder.db");
+ turso::Builder::new_local(file.to_str().unwrap())
+ .build()
+ .await?
} else {
return Err(anyhow!("Failed to locate data directory"));
};
- conn.execute(TABLE_CREATE, ())?;
- Ok(conn)
+ let conn = db.connect()?;
+ conn.execute(TABLE_CREATE, ()).await?;
+ Ok(db)
}
-pub(crate) fn insert_file(conn: &Connection, filename: &Path) -> Result<()> {
+pub(crate) async fn insert_file(conn: &Connection, filename: &Path) -> Result<()> {
let toencode = !matches!(get_vendor(filename)?.as_str(), CURRENT_VENDOR);
let modtime = filename
@@ -43,14 +47,15 @@ pub(crate) fn insert_file(conn: &Connection, filename: &Path) -> Result<()> {
.as_secs();
conn.execute(
- ADD_ITEM,
+ ADD_FILE,
params![filename.to_str().unwrap(), toencode, modtime],
- )?;
+ )
+ .await?;
Ok(())
}
-pub(crate) fn update_file(conn: &Connection, filename: &Path) -> Result<()> {
+pub(crate) async fn update_file(conn: &Connection, filename: &Path) -> Result<()> {
let modtime = filename
.metadata()?
.modified()?
@@ -58,70 +63,74 @@ pub(crate) fn update_file(conn: &Connection, filename: &Path) -> Result<()> {
.as_secs();
conn.execute(
- UPDATE_ITEM,
+ UPDATE_FILE,
params![filename.to_str().unwrap(), false, modtime],
- )?;
+ )
+ .await?;
Ok(())
}
-pub(crate) fn check_file(conn: &Connection, filename: &Path) -> Result<bool> {
- if conn.query_one(CHECK_FILE, params!(filename.to_str().unwrap()), |row| {
- let num: bool = row.get(0)?;
- Ok(num)
- })? {
- Ok(true)
- } else {
- Ok(false)
- }
+pub(crate) async fn check_file(conn: &Connection, filename: &Path) -> Result<bool> {
+ Ok(conn
+ .query(CHECK_FILE, params!(filename.to_str().unwrap()))
+ .await?
+ .next()
+ .await?
+ .unwrap()
+ .get::<bool>(0)?)
}
-pub(crate) fn init_clean_files(conn: &Connection) -> Result<Vec<PathBuf>, rusqlite::Error> {
- conn.execute(DEDUPE_DB, ())?;
- let mut stmt = conn.prepare(FETCH_FILES)?;
- let mut rows = stmt.query(())?;
+pub(crate) async fn init_clean_files(conn: &Connection) -> Result<Vec<PathBuf>, turso::Error> {
+ conn.execute(DEDUPE_DB, ()).await?;
+ let mut rows = conn.query(FETCH_FILES, ()).await?;
let mut files = Vec::new();
- while let Ok(Some(row)) = rows.next() {
+ while let Ok(Some(row)) = rows.next().await {
let path: String = row.get(0)?;
files.push(PathBuf::from(path));
}
+
Ok(files)
}
-pub(crate) fn remove_file(conn: &Connection, filename: &Path) -> Result<()> {
- conn.execute(REMOVE_FILE, params!(filename.to_str().unwrap()))?;
+pub(crate) async fn remove_file(conn: &Connection, filename: &Path) -> Result<()> {
+ conn.execute(REMOVE_FILE, params!(filename.to_str().unwrap()))
+ .await?;
Ok(())
}
-pub(crate) fn get_toencode_files(conn: &Connection) -> Result<Vec<PathBuf>, rusqlite::Error> {
- let mut stmt = conn.prepare(TOENCODE_PATHS)?;
- let mut rows = stmt.query(())?;
+pub(crate) async fn get_toencode_files(conn: &Connection) -> Result<Vec<PathBuf>, turso::Error> {
+ let mut rows = conn.query(TOENCODE_PATHS, ()).await?;
let mut files: Vec<PathBuf> = Vec::new();
- while let Ok(Some(row)) = rows.next() {
+ while let Ok(Some(row)) = rows.next().await {
let path: String = row.get(0)?;
files.push(PathBuf::from(path));
}
+
Ok(files)
}
-pub(crate) fn get_toencode_number(conn: &Connection) -> Result<u64, rusqlite::Error> {
- conn.query_one(TOENCODE_NUMBER, (), |row| {
- let num: u64 = row.get(0)?;
- Ok(num)
- })
+pub(crate) async fn get_toencode_number(conn: &Connection) -> Result<u64, turso::Error> {
+ conn.query(TOENCODE_NUMBER, ())
+ .await?
+ .next()
+ .await?
+ .unwrap()
+ .get::<u64>(0)
}
-pub(crate) fn get_modtime(conn: &Connection, file: &Path) -> Result<u64> {
- Ok(
- conn.query_one(GET_MODTIME, params![file.to_str().unwrap()], |row| {
- let modtime: u64 = row.get(0)?;
- Ok(modtime)
- })?,
- )
+pub(crate) async fn get_modtime(conn: &Connection, file: &Path) -> Result<u64> {
+ Ok(conn
+ .query(GET_MODTIME, params![file.to_str().unwrap()])
+ .await?
+ .next()
+ .await?
+ .unwrap()
+ .get::<u64>(0)?)
}
-pub(crate) fn vacuum(conn: &Connection) -> Result<()> {
- conn.execute("VACUUM", ())?;
+pub(crate) async fn vacuum(conn: &Connection) -> Result<()> {
+ conn.execute("VACUUM", ()).await?;
Ok(())
}
@@ -129,9 +138,11 @@ pub(crate) fn vacuum(conn: &Connection) -> Result<()> {
mod tests {
use super::*;
+ use macro_rules_attribute::apply;
+ use smol_macros::{Executor, test};
- #[test]
- fn check_localfiles() {
+ #[apply(test!)]
+ async fn check_localfiles(ex: &Executor<'_>) {
let dbname = PathBuf::from("temp1.db");
let filenames = [
"./samples/16bit.flac",
@@ -139,61 +150,69 @@ mod tests {
"./samples/32bit.flac",
];
let mut counter = 0;
- let conn = init_connection(Some(&dbname)).unwrap();
- for file in filenames {
- let filename = PathBuf::from(file);
- insert_file(&conn, &filename).unwrap();
- }
- let mut stmt = conn.prepare(TOENCODE_PATHS).unwrap();
- let mut returned = stmt.query(()).unwrap();
-
- while let Ok(Some(_)) = returned.next() {
- counter += 1
- }
- std::fs::remove_file(dbname).unwrap();
- assert!(counter == 0)
+ ex.spawn(async move {
+ let db = init_db(Some(&dbname)).await.unwrap();
+ let conn = db.connect().unwrap();
+ for file in filenames {
+ let path = PathBuf::from(file);
+ insert_file(&conn, &path).await.unwrap();
+ }
+ let mut returned = conn.query(TOENCODE_PATHS, ()).await.unwrap();
+ while let Ok(Some(_)) = returned.next().await {
+ counter += 1
+ }
+ std::fs::remove_file(dbname).unwrap();
+ assert!(counter == 0)
+ })
+ .await;
}
- #[test]
- fn check_update() {
+ #[apply(test!)]
+ async fn check_update(ex: &Executor<'_>) {
let dbname = PathBuf::from("temp2.db");
let filenames = [
"./samples/16bit.flac",
"./samples/24bit.flac",
"./samples/32bit.flac",
];
- let conn = init_connection(Some(&dbname)).unwrap();
- for file in filenames {
- insert_file(&conn, &Path::new(file).canonicalize().unwrap()).unwrap();
- }
-
- conn.execute(
- UPDATE_ITEM,
- params![
- Path::new("./samples/16bit.flac")
- .canonicalize()
- .unwrap()
- .to_str()
- .unwrap(),
- true,
- ""
- ],
- )
- .unwrap();
+ ex.spawn(async move {
+ let db = init_db(Some(&dbname)).await.unwrap();
+ let conn = db.connect().unwrap();
+ for file in filenames {
+ insert_file(&conn, &Path::new(file).canonicalize().unwrap())
+ .await
+ .unwrap();
+ }
+ conn.execute(
+ UPDATE_FILE,
+ params![
+ Path::new("./samples/16bit.flac")
+ .canonicalize()
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ true,
+ ""
+ ],
+ )
+ .await
+ .unwrap();
- update_file(
- &conn,
- &Path::new("./samples/16bit.flac").canonicalize().unwrap(),
- )
- .unwrap();
+ update_file(
+ &conn,
+ &Path::new("./samples/16bit.flac").canonicalize().unwrap(),
+ )
+ .await
+ .unwrap();
- let mut stmt = conn.prepare(TOENCODE_PATHS).unwrap();
- let mut returned = stmt.query(()).unwrap();
- let mut counter = 0;
- while let Ok(Some(_)) = returned.next() {
- counter += 1
- }
- std::fs::remove_file(dbname).unwrap();
- assert!(counter == 0)
+ let mut returned = conn.query(TOENCODE_PATHS, ()).await.unwrap();
+ let mut counter = 0;
+ while let Ok(Some(_)) = returned.next().await {
+ counter += 1
+ }
+ std::fs::remove_file(dbname).unwrap();
+ assert!(counter == 0)
+ })
+ .await;
}
}