write_tool_rs/src/services/sqlite_service.rs

57 lines
1.5 KiB
Rust
Raw Normal View History

use anyhow::Result;
use crate::models::write_result::WriteResult;
use rusqlite::{Connection};
pub(crate) struct SqliteService {
conn: Connection,
}
impl Default for SqliteService {
fn default() -> Self {
//TODO: fix cant use path to create service
return match Self::new(".data.db".to_string()){
Ok(service) => service,
Err(err) => panic!("{}", err.to_string())
}
}
}
impl SqliteService {
pub fn new(conn_str: String) -> Result<Self> {
let conn = Connection::open(conn_str)?;
Ok(Self { conn })
}
pub fn create_table(&self) -> Result<()> {
self.conn.execute(
"CREATE TABLE IF NOT EXISTS write_results (
id INTEGER PRIMARY KEY,
imei TEXT NOT NULL,
sn TEXT NOT NULL,
write_date TEXT NOT NULL
)",
[],
)?;
Ok(())
}
pub fn insert(&self, write_result: WriteResult) -> Result<()> {
self.conn.execute(
"INSERT INTO write_results (imei, sn, write_date) VALUES (?1, ?2, ?3)",
&[&write_result.imei, &write_result.sn, &write_result.write_date],
)?;
Ok(())
}
pub fn check_sn(&self, sn: &str) -> Result<bool> {
let mut stmt = self.conn.prepare("SELECT sn FROM write_results WHERE sn = ?1")?;
let mut rows = stmt.query(&[&sn])?;
Ok(rows.next()?.is_some())
}
}
#[test]
fn create_sql_service_test() {
let service = SqliteService::default();
}