feat: 使用 diesel 替代 r2d2_sqlite

This commit is contained in:
2025-08-01 14:13:41 +08:00
parent 668c9d5b9b
commit 709b743676
13 changed files with 116 additions and 44 deletions

View File

@@ -1 +1,2 @@
pub mod sqlite;
pub mod sqlite;
mod tests;

View File

@@ -1,21 +1,23 @@
mod sql_line;
use crate::utils::sql::sqlite::sql_line::CREATE_TABLE;
use diesel::RunQueryDsl;
use diesel::r2d2::ConnectionManager;
use diesel::sqlite::SqliteConnection;
use log::warn;
use r2d2::{Pool};
use r2d2_sqlite::SqliteConnectionManager;
use crate::utils::sql::sqlite::sql_line::{generate_sql_line};
use r2d2::Pool;
#[derive(Debug)]
// #[derive(Debug)]
pub struct SqliteDB {
pub connection_pool: Pool<SqliteConnectionManager>,
pub connection_pool: Pool<ConnectionManager<SqliteConnection>>,
}
impl SqliteDB {
pub fn new(address: &str) -> Option<Self> {
let manager = SqliteConnectionManager::file(address);
let manager = ConnectionManager::<SqliteConnection>::new(address);
match Pool::builder().build(manager) {
Ok(pool) => Some(SqliteDB {
connection_pool: pool
connection_pool: pool,
}),
Err(e) => {
warn!("Failed to create connection pool: {}", e);
@@ -23,9 +25,15 @@ impl SqliteDB {
}
}
}
pub fn create_table(&self) {
let conn = self.connection_pool.get().unwrap();
let line = generate_sql_line();
conn.execute(line.get("create_table").unwrap(), []).expect(&format!("Failed to create db table: {:?}", self));
let mut conn = self
.connection_pool
.get()
.expect("无法连接,数据库连接池未初始化");
diesel::sql_query(CREATE_TABLE)
.execute(&mut conn)
.expect("创建表失败");
}
}
}

View File

@@ -1,15 +1,6 @@
use std::collections::HashMap;
pub fn generate_sql_line() -> HashMap<&'static str, &'static str> {
let mut line = HashMap::new();
line.insert("create_table", "
CREATE TABLE IF NOT EXISTS gotify (
id INTEGER PRIMARY KEY,
appid INTEGER,
message TEXT,
title TEXT,
priority INTEGER,
date TEXT
");
line
}
pub static CREATE_TABLE: &'static str = r#"CREATE TABLE IF NOT EXISTS gotify (
id INTEGER PRIMARY KEY,
appid INTEGER,
message TEXT,
title TEXT,
priority INTEGER, date TEXT)"#;

View File

@@ -0,0 +1 @@
mod sqlite;

View File

@@ -0,0 +1,32 @@
#[cfg(test)]
mod sqlite_test {
use std::fs::remove_file;
use std::path::Path;
use crate::utils::sql::sqlite::SqliteDB;
#[test]
fn new_database() {
let file_path: &str = "test.sqlite";
SqliteDB::new(&file_path).unwrap();
let file = Path::new(&file_path);
assert!(file.exists());
if file.exists() {
remove_file(file).unwrap();
}
}
#[test]
fn create_table() {
let file_path: &str = "test.sqlite";
let db = SqliteDB::new(&file_path).unwrap();
db.create_table();
drop(db.connection_pool);
if Path::new(&file_path).exists() {
remove_file(file_path).unwrap();
}
}
}