summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorjakka <jakkadoujin@gmail.com>2025-07-07 13:02:58 +0300
committerjakka <jakkadoujin@gmail.com>2025-07-07 13:02:58 +0300
commitc8c1c4daa8579fe0462bdbd8f5437cca78d3348e (patch)
treeef3e586116c8518dccf2e76cacd8f50ea5bb3622
parent8d172e80396efe81174e0f1f2cf356194fc25aa2 (diff)
removed unneeded deps, cleaned up code a bit
-rw-r--r--Cargo.lock198
-rw-r--r--Cargo.toml7
-rw-r--r--src/db.rs130
-rw-r--r--src/files.rs108
-rw-r--r--src/main.rs17
5 files changed, 122 insertions, 338 deletions
diff --git a/Cargo.lock b/Cargo.lock
index e08c108..ecb3970 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -325,8 +325,6 @@ dependencies = [
"indicatif",
"md-5",
"metaflac",
- "r2d2",
- "r2d2_sqlite",
"rayon",
"rusqlite",
"walkdir",
@@ -356,19 +354,7 @@ checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [
"cfg-if",
"libc",
- "wasi 0.11.1+wasi-snapshot-preview1",
-]
-
-[[package]]
-name = "getrandom"
-version = "0.3.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
-dependencies = [
- "cfg-if",
- "libc",
- "r-efi",
- "wasi 0.14.2+wasi-0.2.4",
+ "wasi",
]
[[package]]
@@ -473,16 +459,6 @@ dependencies = [
]
[[package]]
-name = "lock_api"
-version = "0.4.13"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765"
-dependencies = [
- "autocfg",
- "scopeguard",
-]
-
-[[package]]
name = "log"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -548,29 +524,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
-name = "parking_lot"
-version = "0.12.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13"
-dependencies = [
- "lock_api",
- "parking_lot_core",
-]
-
-[[package]]
-name = "parking_lot_core"
-version = "0.9.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5"
-dependencies = [
- "cfg-if",
- "libc",
- "redox_syscall",
- "smallvec",
- "windows-targets 0.52.6",
-]
-
-[[package]]
name = "pkg-config"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -583,15 +536,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
[[package]]
-name = "ppv-lite86"
-version = "0.2.21"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
-dependencies = [
- "zerocopy",
-]
-
-[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -610,63 +554,6 @@ dependencies = [
]
[[package]]
-name = "r-efi"
-version = "5.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
-
-[[package]]
-name = "r2d2"
-version = "0.8.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "51de85fb3fb6524929c8a2eb85e6b6d363de4e8c48f9e2c2eac4944abc181c93"
-dependencies = [
- "log",
- "parking_lot",
- "scheduled-thread-pool",
-]
-
-[[package]]
-name = "r2d2_sqlite"
-version = "0.30.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06cc23a61faf4643d8b59ed52c27ed434476dd7aa6f39e1eff7d6bbd35985093"
-dependencies = [
- "r2d2",
- "rusqlite",
- "uuid",
-]
-
-[[package]]
-name = "rand"
-version = "0.9.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
-dependencies = [
- "rand_chacha",
- "rand_core",
-]
-
-[[package]]
-name = "rand_chacha"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
-dependencies = [
- "ppv-lite86",
- "rand_core",
-]
-
-[[package]]
-name = "rand_core"
-version = "0.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
-dependencies = [
- "getrandom 0.3.3",
-]
-
-[[package]]
name = "rayon"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -687,21 +574,12 @@ dependencies = [
]
[[package]]
-name = "redox_syscall"
-version = "0.5.13"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6"
-dependencies = [
- "bitflags",
-]
-
-[[package]]
name = "redox_users"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b"
dependencies = [
- "getrandom 0.2.16",
+ "getrandom",
"libredox",
"thiserror",
]
@@ -721,12 +599,6 @@ dependencies = [
]
[[package]]
-name = "rustversion"
-version = "1.0.21"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a0d197bd2c9dc6e53b84da9556a69ba4cdfab8619eb41a8bd1cc2027a0f6b1d"
-
-[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -736,21 +608,6 @@ dependencies = [
]
[[package]]
-name = "scheduled-thread-pool"
-version = "0.2.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3cbc66816425a074528352f5789333ecff06ca41b36b0b0efdfbb29edc391a19"
-dependencies = [
- "parking_lot",
-]
-
-[[package]]
-name = "scopeguard"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
-
-[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -836,18 +693,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
-name = "uuid"
-version = "1.17.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3cf4199d1e5d15ddd86a694e4d0dffa9c323ce759fea589f00fef9d81cc1931d"
-dependencies = [
- "getrandom 0.3.3",
- "js-sys",
- "rand",
- "wasm-bindgen",
-]
-
-[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -876,15 +721,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
-name = "wasi"
-version = "0.14.2+wasi-0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
-dependencies = [
- "wit-bindgen-rt",
-]
-
-[[package]]
name = "wasm-bindgen"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -892,7 +728,6 @@ checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
dependencies = [
"cfg-if",
"once_cell",
- "rustversion",
"wasm-bindgen-macro",
]
@@ -1106,32 +941,3 @@ name = "windows_x86_64_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
-
-[[package]]
-name = "wit-bindgen-rt"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
-dependencies = [
- "bitflags",
-]
-
-[[package]]
-name = "zerocopy"
-version = "0.8.26"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
-dependencies = [
- "zerocopy-derive",
-]
-
-[[package]]
-name = "zerocopy-derive"
-version = "0.8.26"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
diff --git a/Cargo.toml b/Cargo.toml
index 3df04de..a06d20b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -26,16 +26,17 @@ rayon = "1.10.0"
rusqlite = { version = "0.36.0", default-features = false, features = [
"modern_sqlite",
] }
-r2d2_sqlite = "0.30.0"
-r2d2 = "0.8.10"
ctrlc = "3.4.7"
[features]
+default = ["bundled"]
bundled = ["rusqlite/bundled", "flac-bound/libflac-noogg"]
linked = ["flac-bound/libflac-nobuild"]
[dev-dependencies]
-flac-bound = { version = "0.5.0", default-features = false, features = ["libflac-nobuild"] }
+flac-bound = { version = "0.5.0", default-features = false, features = [
+ "libflac-nobuild",
+] }
[target.'cfg(windows)'.dependencies]
rusqlite = { version = "0.36.0", default-features = false, features = [
diff --git a/src/db.rs b/src/db.rs
index 86f2083..92bfecd 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -1,8 +1,6 @@
use anyhow::{Result, anyhow};
use directories::BaseDirs;
-use r2d2::{Pool, PooledConnection};
-use r2d2_sqlite::SqliteConnectionManager;
-use rusqlite::params;
+use rusqlite::{Connection, params};
use std::{
path::{Path, PathBuf},
time::UNIX_EPOCH,
@@ -22,36 +20,36 @@ 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 fn open_db(
- path: Option<impl AsRef<Path>>,
- threads: usize,
-) -> Result<Pool<SqliteConnectionManager>> {
- if let Some(file) = path {
- let manager = SqliteConnectionManager::file(file);
- let pool = Pool::builder().max_size(threads as u32).build(manager)?;
- let conn = pool.get()?;
- conn.execute(TABLE_CREATE, ())?;
- Ok(pool)
- } else if let Some(base_dir) = BaseDirs::new() {
- let file = Path::new(base_dir.data_dir()).join("reencoder.db");
- let manager = SqliteConnectionManager::file(file);
- let pool = Pool::builder().max_size(threads as u32).build(manager)?;
- let conn = pool.get()?;
- conn.execute(TABLE_CREATE, ())?;
- Ok(pool)
- } else {
- Err(anyhow!("Failed to locate data directory"))
- }
+pub trait Database {
+ type Conn;
+ fn new(path: Option<impl AsRef<Path>>) -> Result<Self::Conn>;
+ fn insert_file(&self, filename: impl AsRef<Path>) -> Result<()>;
+ fn update_file(&self, filename: impl AsRef<Path>) -> Result<()>;
+ fn check_file(&self, filename: impl AsRef<Path>) -> Result<bool>;
+ fn init_clean_files(&self) -> Result<Vec<PathBuf>, rusqlite::Error>;
+ fn remove_file(&self, filename: impl AsRef<Path>) -> Result<()>;
+ fn get_toencode_files(&self) -> Result<Vec<PathBuf>, rusqlite::Error>;
+ fn get_toencode_number(&self) -> Result<u64, rusqlite::Error>;
+ fn get_modtime(&self, file: impl AsRef<Path>) -> Result<u64>;
+ fn vacuum(&self) -> Result<()>;
}
-pub struct Database(pub PooledConnection<SqliteConnectionManager>);
-
-impl Database {
- pub fn new(conn: PooledConnection<SqliteConnectionManager>) -> Self {
- Database(conn)
+impl Database for Connection {
+ type Conn = Connection;
+ fn new(path: Option<impl AsRef<Path>>) -> Result<Self> {
+ let conn = if let Some(file) = path {
+ Connection::open(file)?
+ } else if let Some(base_dir) = BaseDirs::new() {
+ let file = Path::new(base_dir.data_dir()).join("reencoder.db");
+ Connection::open(file)?
+ } else {
+ return Err(anyhow!("Failed to locate data directory"));
+ };
+ conn.execute(TABLE_CREATE, ())?;
+ Ok(conn)
}
- pub fn insert_file(&self, filename: impl AsRef<Path>) -> Result<()> {
+ fn insert_file(&self, filename: impl AsRef<Path>) -> Result<()> {
let toencode = !matches!(get_vendor(&filename)?.as_str(), CURRENT_VENDOR);
let modtime = filename
@@ -61,7 +59,7 @@ impl Database {
.duration_since(UNIX_EPOCH)?
.as_secs();
- self.0.execute(
+ self.execute(
ADD_NEW_ITEM,
params![filename.as_ref().to_str().unwrap(), toencode, modtime],
)?;
@@ -69,7 +67,7 @@ impl Database {
Ok(())
}
- pub fn update_file(&self, filename: impl AsRef<Path>) -> Result<()> {
+ fn update_file(&self, filename: impl AsRef<Path>) -> Result<()> {
let modtime = filename
.as_ref()
.metadata()?
@@ -77,7 +75,7 @@ impl Database {
.duration_since(UNIX_EPOCH)?
.as_secs();
- self.0.execute(
+ self.execute(
REPLACE_ITEM,
params![filename.as_ref().to_str().unwrap(), false, modtime],
)?;
@@ -85,8 +83,8 @@ impl Database {
Ok(())
}
- pub fn check_file(&self, filename: impl AsRef<Path>) -> Result<bool> {
- if self.0.query_one(
+ fn check_file(&self, filename: impl AsRef<Path>) -> Result<bool> {
+ if self.query_one(
CHECK_FILE,
params!(filename.as_ref().to_str().unwrap()),
|row| {
@@ -100,9 +98,9 @@ impl Database {
}
}
- pub fn init_clean_files(&self) -> Result<Vec<PathBuf>, rusqlite::Error> {
- self.0.execute(DEDUPE_DB, ())?;
- let mut stmt = self.0.prepare(FETCH_FILES)?;
+ fn init_clean_files(&self) -> Result<Vec<PathBuf>, rusqlite::Error> {
+ self.execute(DEDUPE_DB, ())?;
+ let mut stmt = self.prepare(FETCH_FILES)?;
let mut rows = stmt.query(())?;
let mut files = Vec::new();
while let Ok(Some(row)) = rows.next() {
@@ -112,14 +110,13 @@ impl Database {
Ok(files)
}
- pub fn remove_file(&self, filename: impl AsRef<Path>) -> Result<()> {
- self.0
- .execute(REMOVE_FILE, params!(filename.as_ref().to_str().unwrap()))?;
+ fn remove_file(&self, filename: impl AsRef<Path>) -> Result<()> {
+ self.execute(REMOVE_FILE, params!(filename.as_ref().to_str().unwrap()))?;
Ok(())
}
- pub fn get_toencode_files(&self) -> Result<Vec<PathBuf>, rusqlite::Error> {
- let mut stmt = self.0.prepare(TOENCODE_QUERY)?;
+ fn get_toencode_files(&self) -> Result<Vec<PathBuf>, rusqlite::Error> {
+ let mut stmt = self.prepare(TOENCODE_QUERY)?;
let mut rows = stmt.query(())?;
let mut files: Vec<PathBuf> = Vec::new();
while let Ok(Some(row)) = rows.next() {
@@ -129,15 +126,15 @@ impl Database {
Ok(files)
}
- pub fn get_toencode_number(&self) -> Result<u64, rusqlite::Error> {
- self.0.query_one(TOENCODE_NUMBER, (), |row| {
+ fn get_toencode_number(&self) -> Result<u64, rusqlite::Error> {
+ self.query_one(TOENCODE_NUMBER, (), |row| {
let num: u64 = row.get(0)?;
Ok(num)
})
}
- pub fn get_modtime(&self, file: impl AsRef<Path>) -> Result<u64> {
- Ok(self.0.query_one(
+ fn get_modtime(&self, file: impl AsRef<Path>) -> Result<u64> {
+ Ok(self.query_one(
GET_MODTIME,
params![file.as_ref().to_str().unwrap()],
|row| {
@@ -147,8 +144,8 @@ impl Database {
)?)
}
- pub fn vaccum(&self) -> Result<()> {
- self.0.execute("VACUUM", ())?;
+ fn vacuum(&self) -> Result<()> {
+ self.execute("VACUUM", ())?;
Ok(())
}
}
@@ -163,12 +160,11 @@ mod tests {
let dbname = String::from("temp1.db");
let filenames = ["16bit.flac", "24bit.flac", "32bit.flac"];
let mut counter = 0;
- let pool = open_db(Some(&dbname), 10).unwrap();
- let conn = Database::new(pool.get().unwrap());
+ let conn = Connection::new(Some(&dbname)).unwrap();
for file in filenames {
conn.insert_file(&file.to_string()).unwrap();
}
- let mut stmt = conn.0.prepare(TOENCODE_QUERY).unwrap();
+ let mut stmt = conn.prepare(TOENCODE_QUERY).unwrap();
let mut returned = stmt.query(()).unwrap();
while let Ok(Some(_)) = returned.next() {
@@ -182,27 +178,25 @@ mod tests {
fn check_update() {
let dbname = String::from("temp2.db");
let filenames = ["16bit.flac", "24bit.flac", "32bit.flac"];
- let pool = open_db(Some(&dbname), 10).unwrap();
- let conn = Database::new(pool.get().unwrap());
+ let conn = Connection::new(Some(&dbname)).unwrap();
for file in filenames {
conn.insert_file(Path::new(file).canonicalize().unwrap())
.unwrap();
}
- conn.0
- .execute(
- REPLACE_ITEM,
- params![
- Path::new("16bit.flac")
- .canonicalize()
- .unwrap()
- .to_str()
- .unwrap(),
- true,
- ""
- ],
- )
- .unwrap();
+ conn.execute(
+ REPLACE_ITEM,
+ params![
+ Path::new("16bit.flac")
+ .canonicalize()
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ true,
+ ""
+ ],
+ )
+ .unwrap();
conn.update_file(
Path::new("16bit.flac")
@@ -213,7 +207,7 @@ mod tests {
)
.unwrap();
- let mut stmt = conn.0.prepare(TOENCODE_QUERY).unwrap();
+ let mut stmt = conn.prepare(TOENCODE_QUERY).unwrap();
let mut returned = stmt.query(()).unwrap();
let mut counter = 0;
while let Ok(Some(_)) = returned.next() {
diff --git a/src/files.rs b/src/files.rs
index 46d7727..6b5c20e 100644
--- a/src/files.rs
+++ b/src/files.rs
@@ -1,15 +1,13 @@
use anyhow::{Result, anyhow};
#[cfg(not(test))]
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
-use r2d2::Pool;
-use r2d2_sqlite::SqliteConnectionManager;
-use rayon::prelude::*;
+use rusqlite::Connection;
use std::{
error::Error,
fmt::Display,
path::{Path, PathBuf},
sync::{
- Arc,
+ Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
time::UNIX_EPOCH,
@@ -51,7 +49,7 @@ impl Display for FileError {
impl Error for FileError {}
-fn handle_file(file: impl AsRef<Path>, conn: &Database) -> Result<()> {
+fn handle_file(file: impl AsRef<Path>, conn: &Connection) -> Result<()> {
if conn.check_file(&file)? {
let modtime = file
.as_ref()
@@ -77,7 +75,7 @@ fn handle_file(file: impl AsRef<Path>, conn: &Database) -> Result<()> {
pub fn index_files_recursively(
path: impl AsRef<Path>,
- pool: &Pool<SqliteConnectionManager>,
+ conn: &Connection,
handler: Arc<AtomicBool>,
) -> Result<()> {
if !path.as_ref().is_dir() {
@@ -105,7 +103,6 @@ pub fn index_files_recursively(
}
}
- let conn = Database::new(pool.get()?);
for entry in WalkDir::new(abspath) {
if handler.load(Ordering::SeqCst) {
let path = entry.unwrap().into_path();
@@ -113,7 +110,7 @@ pub fn index_files_recursively(
continue;
}
if path.extension().is_some_and(|x| x == "flac") {
- if let Err(error) = handle_file(&path, &conn) {
+ if let Err(error) = handle_file(&path, conn) {
eprintln!("{}", FileError::new(path, error));
} else {
#[cfg(not(test))]
@@ -136,11 +133,7 @@ pub fn index_files_recursively(
Ok(())
}
-pub fn reencode_files(
- pool: &Pool<SqliteConnectionManager>,
- handler: Arc<AtomicBool>,
-) -> Result<()> {
- let conn = Database::new(pool.get()?);
+pub fn reencode_files(conn: Connection, handler: Arc<AtomicBool>, threads: usize) -> Result<()> {
#[cfg(not(test))]
let bar = ProgressBar::with_draw_target(
Some(conn.get_toencode_number()?),
@@ -150,33 +143,42 @@ pub fn reencode_files(
.with_message("Reencoding");
let files = conn.get_toencode_files()?;
- drop(conn);
- files.par_iter().for_each(|file| {
- if handler.load(Ordering::SeqCst) {
- let conn = match pool.get() {
- Ok(conn) => Database::new(conn),
- Err(error) => {
- eprintln!("{}", FileError::new(file, error.into()));
- return;
- }
- };
+ let pool = rayon::ThreadPoolBuilder::new()
+ .num_threads(threads)
+ .build()?;
- if !file.exists() {
- let _ = conn.remove_file(file);
- #[cfg(not(test))]
- bar.dec_length(1);
- return;
- }
+ let lock = Arc::new(Mutex::new(conn));
+
+ pool.scope(|scope| {
+ for file in files {
+ if handler.load(Ordering::SeqCst) {
+ scope.spawn(|_| {
+ let newconn = if let Ok(conn) = lock.lock() {
+ conn
+ } else {
+ eprintln!("Error setting up lock on file:\t{}", file.to_string_lossy());
+ return;
+ };
+ if !file.exists() {
+ let _ = newconn.remove_file(&file);
+ #[cfg(not(test))]
+ bar.dec_length(1);
+ return;
+ }
- if let Err(error) = handle_encode(file) {
- eprintln!("{}", FileError::new(file, error));
+ if let Err(error) = handle_encode(&file) {
+ eprintln!("{}", FileError::new(&file, error));
+ } else {
+ if let Err(error) = newconn.update_file(&file) {
+ eprintln!("{}", FileError::new(file, error));
+ }
+ #[cfg(not(test))]
+ bar.inc(1)
+ }
+ });
} else {
- if let Err(error) = conn.update_file(file) {
- eprintln!("{}", FileError::new(file, error));
- }
- #[cfg(not(test))]
- bar.inc(1)
+ break;
}
}
});
@@ -192,10 +194,8 @@ pub fn reencode_files(
Ok(())
}
-pub fn clean_files(pool: &Pool<SqliteConnectionManager>, handler: Arc<AtomicBool>) -> Result<()> {
- let conn = Database::new(pool.get()?);
+pub fn clean_files(conn: &Connection, handler: Arc<AtomicBool>) -> Result<()> {
let files = conn.init_clean_files()?;
- drop(conn);
#[cfg(not(test))]
let spinner = ProgressBar::with_draw_target(None, ProgressDrawTarget::stdout_with_hz(60))
@@ -203,13 +203,6 @@ pub fn clean_files(pool: &Pool<SqliteConnectionManager>, handler: Arc<AtomicBool
files.iter().for_each(|file| {
if handler.load(Ordering::SeqCst) && !file.exists() {
- let conn = match pool.get() {
- Ok(conn) => Database::new(conn),
- Err(error) => {
- eprintln!("{}", FileError::new(file, error.into()));
- return;
- }
- };
if let Err(error) = conn.remove_file(file) {
eprintln!("{}", FileError::new(file, error))
};
@@ -220,8 +213,7 @@ pub fn clean_files(pool: &Pool<SqliteConnectionManager>, handler: Arc<AtomicBool
#[cfg(not(test))]
spinner.finish();
- let conn = Database::new(pool.get()?);
- conn.vaccum()?;
+ conn.vacuum()?;
Ok(())
}
@@ -229,14 +221,13 @@ pub fn clean_files(pool: &Pool<SqliteConnectionManager>, handler: Arc<AtomicBool
#[cfg(test)]
mod tests {
use super::*;
- use crate::db::*;
#[test]
fn test_index_lots_of_files() {
let dbname = "temp3.db";
let handler = Arc::new(AtomicBool::new(true));
- let pool = open_db(Some(dbname), 10).unwrap();
- index_files_recursively(Path::new("./testfiles"), &pool, handler).unwrap();
+ let conn = Connection::new(Some(&dbname)).unwrap();
+ index_files_recursively(Path::new("./testfiles"), &conn, handler).unwrap();
std::fs::remove_file(dbname).unwrap();
}
@@ -244,8 +235,7 @@ mod tests {
fn test_clean_files() {
let dbname = "temp4.db";
let handler = Arc::new(AtomicBool::new(true));
- let pool = open_db(Some(dbname), 10).unwrap();
- let conn = Database::new(pool.get().unwrap());
+ let conn = Connection::new(Some(&dbname)).unwrap();
let filenames = ["16bit.flac", "24bit.flac", "32bit.flac", "nonexisting.flac"];
std::fs::copy("32bit.flac", "nonexisting.flac").unwrap();
for file in filenames {
@@ -254,7 +244,7 @@ mod tests {
std::fs::remove_file("nonexisting.flac").unwrap();
- clean_files(&pool, handler).unwrap();
+ clean_files(&conn, handler).unwrap();
let counter = conn.init_clean_files().unwrap().len();
std::fs::remove_file(dbname).unwrap();
assert!(counter == 3)
@@ -264,14 +254,12 @@ mod tests {
fn test_reencode_lots_of_files() {
let dbname = "temp5.db";
let handler = Arc::new(AtomicBool::new(true));
- let pool = open_db(Some(dbname), 10).unwrap();
+ let conn = Connection::new(Some(&dbname)).unwrap();
let temp = handler.clone();
- index_files_recursively(Path::new("./testfiles"), &pool, temp).unwrap();
- let conn = Database::new(pool.get().unwrap());
+ index_files_recursively(Path::new("./testfiles"), &conn, temp).unwrap();
println!("\n{}", conn.get_toencode_number().unwrap());
- drop(conn);
- reencode_files(&pool, handler).unwrap();
- let conn = Database::new(pool.get().unwrap());
+ reencode_files(conn, handler, 2).unwrap();
+ let conn = Connection::new(Some(&dbname)).unwrap();
println!("\n{}", conn.get_toencode_number().unwrap());
std::fs::remove_file(dbname).unwrap();
}
diff --git a/src/main.rs b/src/main.rs
index 1363a77..d1e4562 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,6 +5,7 @@ use anyhow::Result;
use clap::{Arg, ArgAction, Command, ValueHint, command, value_parser};
use clap_complete::{Generator, Shell, generate};
use console::style;
+use rusqlite::Connection;
use std::{
path::PathBuf,
sync::{
@@ -92,36 +93,30 @@ fn main() -> Result<()> {
r.store(false, Ordering::SeqCst);
})?;
- let threads = *args.get_one::<usize>("threads").unwrap();
-
- let dbpool = db::open_db(args.get_one::<PathBuf>("db"), threads)?;
+ let conn = Connection::new(args.get_one::<PathBuf>("db"))?;
let path = args.get_one::<PathBuf>("path");
if path.is_none() && !args.get_flag("clean") && !args.get_flag("doit") {
- let conn = Database::new(dbpool.get()?);
let count = conn.get_toencode_number()?;
println!("Files to reencode:\t{}", style(count).green());
return Ok(());
}
- let pool = rayon::ThreadPoolBuilder::new()
- .num_threads(threads)
- .build()?;
-
if let Some(realpath) = path {
let hanlder = running.clone();
- files::index_files_recursively(realpath, &dbpool, hanlder)?;
+ files::index_files_recursively(realpath, &conn, hanlder)?;
}
if args.get_flag("clean") {
let handler = running.clone();
- pool.install(|| files::clean_files(&dbpool, handler))?;
+ files::clean_files(&conn, handler)?;
}
if args.get_flag("doit") {
let hanlder = running.clone();
- pool.install(|| files::reencode_files(&dbpool, hanlder))?;
+ let threads = *args.get_one::<usize>("threads").unwrap();
+ files::reencode_files(conn, hanlder, threads)?;
}
Ok::<(), anyhow::Error>(())
}