AstrBot-Desktop/src-tauri/src/database/mod.rs

269 行
7.7 KiB
Rust

use std::{path::Path, sync::Mutex, time::Duration};
use rusqlite::{Connection, OptionalExtension, params};
use thiserror::Error;
pub const CURRENT_SCHEMA_VERSION: u32 = 1;
pub struct ApplicationDatabase {
store: Mutex<ProfileMessageStore>,
}
impl ApplicationDatabase {
pub fn open(path: impl AsRef<Path>) -> Result<Self, DatabaseError> {
Ok(Self {
store: Mutex::new(ProfileMessageStore::open(path)?),
})
}
pub fn schema_version(&self) -> Result<u32, DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.schema_version()
}
}
pub struct ProfileMessageStore {
connection: Connection,
}
impl ProfileMessageStore {
pub fn open(path: impl AsRef<Path>) -> Result<Self, DatabaseError> {
Self::from_connection(Connection::open(path)?, true)
}
pub fn in_memory() -> Result<Self, DatabaseError> {
Self::from_connection(Connection::open_in_memory()?, false)
}
fn from_connection(
mut connection: Connection,
persistent: bool,
) -> Result<Self, DatabaseError> {
configure_connection(&connection, persistent)?;
migrate(&mut connection)?;
Ok(Self { connection })
}
pub fn schema_version(&self) -> Result<u32, DatabaseError> {
Ok(self
.connection
.pragma_query_value(None, "user_version", |row| row.get(0))?)
}
pub fn insert_message(
&self,
profile_id: &str,
server_instance_id: &str,
conversation_id: &str,
message_id: &str,
content: &str,
) -> Result<(), DatabaseError> {
self.connection.execute(
"
INSERT INTO messages (
profile_id,
server_instance_id,
conversation_id,
message_id,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
",
params![
profile_id,
server_instance_id,
conversation_id,
message_id,
content
],
)?;
Ok(())
}
pub fn message_content(
&self,
profile_id: &str,
server_instance_id: &str,
conversation_id: &str,
message_id: &str,
) -> Result<Option<String>, DatabaseError> {
Ok(self
.connection
.query_row(
"
SELECT content
FROM messages
WHERE profile_id = ?1
AND server_instance_id = ?2
AND conversation_id = ?3
AND message_id = ?4
",
params![profile_id, server_instance_id, conversation_id, message_id],
|row| row.get(0),
)
.optional()?)
}
}
fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> {
connection.pragma_update(None, "foreign_keys", "ON")?;
connection.busy_timeout(Duration::from_secs(5))?;
if persistent {
connection.pragma_update(None, "journal_mode", "WAL")?;
}
Ok(())
}
fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
let found: u32 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?;
if found > CURRENT_SCHEMA_VERSION {
return Err(DatabaseError::UnsupportedSchemaVersion {
found,
supported: CURRENT_SCHEMA_VERSION,
});
}
if found == 0 {
let transaction = connection.transaction()?;
transaction.execute_batch(
"
CREATE TABLE messages (
profile_id TEXT NOT NULL,
server_instance_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
message_id TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id)
);
PRAGMA user_version = 1;
",
)?;
transaction.commit()?;
}
Ok(())
}
#[derive(Debug, Error)]
pub enum DatabaseError {
#[error("SQLite operation failed")]
Sqlite(#[from] rusqlite::Error),
#[error("database schema version {found} is newer than supported version {supported}")]
UnsupportedSchemaVersion { found: u32, supported: u32 },
#[error("database state lock is unavailable")]
LockPoisoned,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn creates_and_reopens_a_persistent_migrated_database() {
let directory = tempfile::tempdir().expect("temporary directory");
let path = directory.path().join("desktop.sqlite3");
{
let store = ProfileMessageStore::open(&path).expect("open database");
assert_eq!(
store.schema_version().expect("schema version"),
CURRENT_SCHEMA_VERSION
);
store
.insert_message(
"profile-a",
"server-a",
"conversation-a",
"message-a",
"persisted",
)
.expect("insert message");
}
let reopened = ProfileMessageStore::open(&path).expect("reopen database");
assert_eq!(
reopened.schema_version().expect("schema version"),
CURRENT_SCHEMA_VERSION
);
assert_eq!(
reopened
.message_content("profile-a", "server-a", "conversation-a", "message-a")
.expect("query message")
.as_deref(),
Some("persisted")
);
}
#[test]
fn refuses_a_database_from_a_newer_schema_version() {
let directory = tempfile::tempdir().expect("temporary directory");
let path = directory.path().join("future.sqlite3");
let connection = Connection::open(&path).expect("create database");
connection
.pragma_update(None, "user_version", CURRENT_SCHEMA_VERSION + 1)
.expect("set future version");
drop(connection);
assert!(matches!(
ProfileMessageStore::open(path),
Err(DatabaseError::UnsupportedSchemaVersion {
found: 2,
supported: CURRENT_SCHEMA_VERSION
})
));
}
#[test]
fn repeated_migration_is_idempotent() {
let store = ProfileMessageStore::in_memory().expect("store");
assert_eq!(
store.schema_version().expect("schema version"),
CURRENT_SCHEMA_VERSION
);
assert_eq!(
store.schema_version().expect("schema version"),
CURRENT_SCHEMA_VERSION
);
}
#[test]
fn identical_remote_ids_remain_isolated_by_profile_and_server() {
let store = ProfileMessageStore::in_memory().expect("store");
store
.insert_message(
"profile-a",
"server-a",
"same-conversation",
"same-message",
"A",
)
.expect("insert A");
store
.insert_message(
"profile-b",
"server-b",
"same-conversation",
"same-message",
"B",
)
.expect("insert B");
assert_eq!(
store
.message_content("profile-a", "server-a", "same-conversation", "same-message")
.expect("query A")
.as_deref(),
Some("A")
);
assert_eq!(
store
.message_content("profile-b", "server-b", "same-conversation", "same-message")
.expect("query B")
.as_deref(),
Some("B")
);
}
}