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

22
.idea/dataSources.xml generated
View File

@@ -15,5 +15,27 @@
<jdbc-url>jdbc:sqlite:D:\dev\code\mine\home-api\database.sqlite</jdbc-url> <jdbc-url>jdbc:sqlite:D:\dev\code\mine\home-api\database.sqlite</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir> <working-dir>$ProjectFileDir$</working-dir>
</data-source> </data-source>
<data-source source="LOCAL" name="test" uuid="ad5ecc9e-100e-44c4-85b1-6c01457609e4">
<driver-ref>sqlite.xerial</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:D:\code\mine\rust\home-api\packages\gotify-ws\test.sqlite</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="database [2]" uuid="c8e748c5-b9c8-4754-93eb-af293ce1bbdc">
<driver-ref>sqlite.xerial</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:D:\code\mine\rust\home-api\database.sqlite</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
<libraries>
<library>
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/xerial/sqlite-jdbc/3.45.1.0/sqlite-jdbc-3.45.1.0.jar</url>
</library>
<library>
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/slf4j/slf4j-api/1.7.36/slf4j-api-1.7.36.jar</url>
</library>
</libraries>
</data-source>
</component> </component>
</project> </project>

7
.idea/dictionaries/project.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<component name="ProjectDictionaryState">
<dictionary name="project">
<words>
<w>gotify</w>
</words>
</dictionary>
</component>

2
.idea/serv.iml generated
View File

@@ -2,6 +2,8 @@
<module type="EMPTY_MODULE" version="4"> <module type="EMPTY_MODULE" version="4">
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/packages/gotify-ws/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/packages/home-api/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" /> <excludeFolder url="file://$MODULE_DIR$/target" />
</content> </content>

View File

@@ -1,5 +1,9 @@
{ {
"cSpell.words": [ "cSpell.words": [
"actix" "actix",
"gotify",
"hzer",
"serde",
"tungstenite"
] ]
} }

View File

View File

@@ -4,13 +4,14 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
diesel = { version = "2.2.12", features = ["r2d2", "serde_json", "sqlite"] }
env_logger = "0.11.8" env_logger = "0.11.8"
futures = "0.3.31" futures = "0.3.31"
log = "0.4.27" log = "0.4.27"
r2d2 = "0.8.10" r2d2 = "0.8.10"
r2d2_sqlite = "0.31.0" #r2d2_sqlite = "0.31.0"
rusqlite = { version = "0.37.0", features = ["bundled"] } rusqlite = { version = "0.37.0", features = ["bundled"] }
serde = { version = "1.0.219", features = ["derive"] } serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.133" serde_json = "1.0.142"
tokio = { version = "1.47.0", features = ["full"] } tokio = { version = "1.47.0", features = ["full"] }
tokio-tungstenite = { version = "0.27.0", features = ["native-tls"] } tokio-tungstenite = { version = "0.27.0", features = ["native-tls"] }

View File

@@ -6,20 +6,20 @@ use futures::StreamExt;
use log::info; use log::info;
use serde_json; use serde_json;
use tokio_tungstenite::connect_async; use tokio_tungstenite::connect_async;
use utils::{logger, sql};
use utils::sql::sqlite::SqliteDB; use utils::sql::sqlite::SqliteDB;
use utils::{logger, sql};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
logger::init_logger(); logger::init_logger();
const WS: &str = "wss://home.hzer.xyz/gotify/stream?token=CDIwYlYJuxWxVr5"; const ADDR: &str = "wss://home.hzer.xyz/gotify/stream?token=CDIwYlYJuxWxVr5";
let (stream, _) = connect_async(WS).await.unwrap(); let (stream, _) = connect_async(ADDR).await.unwrap();
info!("Connected to Gotify server {WS}"); info!("Connected to Gotify server {ADDR}");
let (_, mut read) = stream.split(); let (_, mut read) = stream.split();
while let Some(msg) = read.next().await { while let Some(msg) = read.next().await {
match msg { match msg {
Ok(msg) => { Ok(msg) => {
let str = msg.to_text().unwrap().to_string(); let str = msg.to_text().unwrap();
match serde_json::from_str::<WsMessage>(&str) { match serde_json::from_str::<WsMessage>(&str) {
Ok(ws) => { Ok(ws) => {
info!("Got {} from Gotify", ws.message); info!("Got {} from Gotify", ws.message);
@@ -27,7 +27,7 @@ async fn main() {
db.create_table(); db.create_table();
} }
Err(_) => { Err(_) => {
info!("监听到心跳{}", &str) info!("监听到心跳{}", &msg)
} }
} }
} }

View File

@@ -1,9 +1,12 @@
#[derive(Debug, serde::Deserialize)] use diesel::Queryable;
use serde::Deserialize;
#[derive(Debug, Deserialize, Queryable)]
pub struct WsMessage { pub struct WsMessage {
id: u64, id: u64,
appid: u64, appid: u64,
pub message: String, pub message: String,
title: String, title: String,
priority: u64, priority: u64,
date: String, date: String,
} }

View File

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

View File

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

View File

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

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();
}
}
}