Added database

This commit is contained in:
2025-09-13 12:37:18 +02:00
parent 642fe6cfcb
commit 3613d0bfdc
6 changed files with 190 additions and 9 deletions
+83
View File
@@ -0,0 +1,83 @@
use crate::ServerConfig;
use rusqlite::{Connection, Result, params};
pub struct Database {
pub messages_db: MessagesDb,
}
impl Database {
pub fn new(config: &ServerConfig) -> Option<Self> {
let conn = Connection::open("main.db").ok()?;
let messages_db = MessagesDb(conn);
messages_db.init(config)?;
Some(Self { messages_db })
}
}
unsafe impl Send for Database {}
unsafe impl Sync for Database {}
pub struct MessagesDb(pub Connection);
impl MessagesDb {
pub fn init(&self, _config: &ServerConfig) -> Option<usize> {
self.0
.execute(
"CREATE TABLE IF NOT EXISTS chat (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id TEXT NOT NULL,
user_id TEXT NOT NULL,
contents TEXT NOT NULL,
timestamp INTEGER NOT NULL
)",
[],
)
.ok()
}
/// Insert a message into the DB
pub fn insert(
&self,
channel_id: &str,
user_id: &str,
contents: &str,
timestamp: i64,
) -> Result<usize> {
self.0.execute(
"INSERT INTO chat (channel_id, user_id, contents, timestamp)
VALUES (?1, ?2, ?3, ?4)",
params![channel_id, user_id, contents, timestamp],
)
}
/// Fetch the latest N messages for a channel
pub fn fetch_recent(
&self,
channel_id: &str,
limit: usize,
) -> Result<Vec<(i64, String, String, String, i64)>> {
let mut stmt = self.0.prepare(
"SELECT id, channel_id, user_id, contents, timestamp
FROM chat
WHERE channel_id = ?1
ORDER BY timestamp DESC
LIMIT ?2",
)?;
let rows = stmt.query_map(params![channel_id, limit], |row| {
Ok((
row.get::<_, i64>(0)?, // id
row.get::<_, String>(1)?, // channel_id
row.get::<_, String>(2)?, // user_id
row.get::<_, String>(3)?, // contents
row.get::<_, i64>(4)?, // timestamp
))
})?;
let mut results = Vec::new();
for row in rows {
results.push(row?);
}
Ok(results)
}
}
+18 -7
View File
@@ -6,6 +6,7 @@ use std::{
};
pub mod client;
pub mod database;
#[cfg(feature = "loader")]
pub mod loader;
pub mod logger;
@@ -27,6 +28,7 @@ pub use once_cell;
#[derive(serde::Serialize, serde::Deserialize)]
pub struct ServerConfig {
port: u16,
channels: Vec<types::data::Channel>,
}
#[allow(dead_code)]
@@ -35,11 +37,15 @@ pub struct Server {
config: ServerConfig,
plugins: Mutex<Vec<DynPlugin>>,
clients: Mutex<HashSet<Client>>,
pub db: database::Database,
}
impl Default for ServerConfig {
fn default() -> Self {
Self { port: 7080 }
Self {
port: 7080,
channels: Vec::new(),
}
}
}
@@ -53,16 +59,12 @@ impl Server {
logger!(LOGGER "Server");
pub fn new(root: &Path) -> Arc<Self> {
Arc::new(Self {
plugins: Mutex::new(Vec::new()),
root: root.to_path_buf(),
config: ServerConfig::default(),
clients: Mutex::new(HashSet::new()),
})
Self::new_config(root, ServerConfig::default())
}
pub fn new_config(root: &Path, config: ServerConfig) -> Arc<Self> {
Arc::new(Self {
db: database::Database::new(&config).unwrap(),
plugins: Mutex::new(Vec::new()),
root: root.to_path_buf(),
config,
@@ -128,6 +130,15 @@ impl Server {
contents,
} => {
Self::LOGGER.info(format!("SendMessage to {channel_id}: {contents}"));
self.wrap_err(
&client,
self.db.messages_db.insert(
&channel_id,
"idk",
&contents,
chrono::Utc::now().timestamp(),
),
)?;
}
ClientMessage::EditMessage {
+1 -1
View File
@@ -77,7 +77,7 @@ pub mod data {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Channel {
pub id: usize,
pub id: String,
pub name: String,
pub kind: ChannelKind,
}