mirror of
https://framagit.org/veretcle/scootaloo.git
synced 2025-07-20 17:11:19 +02:00
102 lines
2.3 KiB
Rust
102 lines
2.3 KiB
Rust
// auto-imports
|
|
use crate::config::ScootalooConfig;
|
|
|
|
// std
|
|
use std::{
|
|
fs::{read_to_string, write},
|
|
error::Error,
|
|
};
|
|
|
|
// log
|
|
use log::debug;
|
|
|
|
// rusqlite
|
|
use rusqlite::{Connection, OpenFlags, params};
|
|
|
|
/// Reads last tweet id from a file
|
|
pub fn read_state(s: &str) -> Option<u64> {
|
|
let state = read_to_string(s);
|
|
|
|
if let Ok(s) = state {
|
|
debug!("Last Tweet ID (from file): {}", &s);
|
|
return s.parse::<u64>().ok();
|
|
}
|
|
|
|
None
|
|
}
|
|
|
|
/// Writes last treated tweet id to a file
|
|
pub fn write_state(f: &str, s: u64) -> Result<(), std::io::Error> {
|
|
write(f, format!("{}", s))
|
|
}
|
|
|
|
/*********
|
|
* Main functions
|
|
*********/
|
|
/// Initiates the DB from path
|
|
pub fn init_db(config: &ScootalooConfig) -> Result<(), Box<dyn Error>> {
|
|
let conn = Connection::open(&config.db_path)?;
|
|
|
|
conn.execute(
|
|
"CREATE TABLE IF NOT EXISTS tweet_to_toot (
|
|
tweet_id INTEGER PRIMARY KEY,
|
|
toot_id TEXT UNIQUE
|
|
)",
|
|
[],
|
|
)?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::{
|
|
fs::remove_file,
|
|
path::Path,
|
|
};
|
|
|
|
#[test]
|
|
fn test_init_db() {
|
|
let scootaloo_config = ScootalooConfig {
|
|
db_path: String::from("/tmp/test_init_db.sqlite"),
|
|
cache_path: String::from("/tmp/scootaloo"),
|
|
};
|
|
|
|
init_db(&scootaloo_config).unwrap();
|
|
|
|
// check that file exist
|
|
assert!(Path::new(&scootaloo_config.db_path).exists());
|
|
|
|
// open said file
|
|
let conn = Connection::open_with_flags(&scootaloo_config.db_path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
|
|
|
|
conn.execute(
|
|
"SELECT * from tweet_to_toot;",
|
|
[],
|
|
).unwrap();
|
|
|
|
conn.close().unwrap();
|
|
remove_file(&scootaloo_config.db_path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn test_read_state() {
|
|
let scootaloo_config = ScootalooConfig {
|
|
db_path: String::from("/tmp/test_read_state.sqlite"),
|
|
cache_path: String::from("/tmp/scootaloo"),
|
|
};
|
|
|
|
init_db(&scootaloo_config).unwrap();
|
|
|
|
let conn = Connection::open(&scootaloo_config.db_path).unwrap();
|
|
|
|
conn.execute(
|
|
"INSERT INTO tweet_to_toot (tweet_id, toot_id) VALUES (?1, ?2)",
|
|
params![123456789 as u64, String::from("987654321")],
|
|
).unwrap();
|
|
|
|
|
|
}
|
|
}
|