Private
Public Access
1
0

refactor: with_repository/with_settings

This commit is contained in:
2025-04-25 16:34:00 -07:00
parent 89c9ffc187
commit b1f171136a
5 changed files with 249 additions and 227 deletions

View File

@@ -8,7 +8,7 @@ use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
pub struct Database {
pub connection: SqliteConnection,
connection: SqliteConnection,
}
impl Database {
@@ -24,11 +24,19 @@ impl Database {
Self::new(":memory:")
}
pub fn get_repository(&mut self) -> Repository {
Repository::new(self)
pub fn with_repository<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Repository) -> R,
{
let mut repository = Repository::new(&mut self.connection);
f(&mut repository)
}
pub fn get_settings(&mut self) -> Settings {
Settings::new(self)
pub fn with_settings<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Settings) -> R,
{
let mut settings = Settings::new(&mut self.connection);
f(&mut settings)
}
}

View File

@@ -3,7 +3,6 @@ use diesel::prelude::*;
use diesel::query_dsl::BelongingToDsl;
use crate::{
database::Database,
models::{
Conversation,
Message,
@@ -20,12 +19,12 @@ use crate::{
};
pub struct Repository<'a> {
db: &'a mut Database,
connection: &'a mut SqliteConnection,
}
impl<'a> Repository<'a> {
pub fn new(db: &'a mut Database) -> Self {
Self { db }
pub fn new(connection: &'a mut SqliteConnection) -> Self {
Self { connection }
}
pub fn insert_conversation(&mut self, conversation: Conversation) -> Result<()> {
@@ -37,25 +36,25 @@ impl<'a> Repository<'a> {
diesel::replace_into(conversations)
.values(&db_conversation)
.execute(&mut self.db.connection)?;
.execute(self.connection)?;
diesel::replace_into(participants)
.values(&db_participants)
.execute(&mut self.db.connection)?;
.execute(self.connection)?;
// Sqlite backend doesn't support batch insert, so we have to do this manually
for participant in db_participants {
let pid = participants
.select(schema::participants::id)
.filter(schema::participants::display_name.eq(&participant.display_name))
.first::<i32>(&mut self.db.connection)?;
.first::<i32>(self.connection)?;
diesel::replace_into(conversation_participants)
.values((
conversation_id.eq(&db_conversation.id),
participant_id.eq(pid),
))
.execute(&mut self.db.connection)?;
.execute(self.connection)?;
}
Ok(())
@@ -67,14 +66,14 @@ impl<'a> Repository<'a> {
let result = conversations
.find(match_guid)
.first::<ConversationRecord>(&mut self.db.connection)
.first::<ConversationRecord>(self.connection)
.optional()?;
if let Some(conversation) = result {
let db_participants = ConversationParticipant::belonging_to(&conversation)
.inner_join(participants)
.select(ParticipantRecord::as_select())
.load::<ParticipantRecord>(&mut self.db.connection)?;
.load::<ParticipantRecord>(self.connection)?;
let mut model_conversation: Conversation = conversation.into();
model_conversation.participants = db_participants.into_iter().map(|p| p.into()).collect();
@@ -90,14 +89,14 @@ impl<'a> Repository<'a> {
use crate::schema::participants::dsl::*;
let db_conversations = conversations
.load::<ConversationRecord>(&mut self.db.connection)?;
.load::<ConversationRecord>(self.connection)?;
let mut result = Vec::new();
for db_conversation in db_conversations {
let db_participants = ConversationParticipant::belonging_to(&db_conversation)
.inner_join(participants)
.select(ParticipantRecord::as_select())
.load::<ParticipantRecord>(&mut self.db.connection)?;
.load::<ParticipantRecord>(self.connection)?;
let mut model_conversation: Conversation = db_conversation.into();
model_conversation.participants = db_participants.into_iter().map(|p| p.into()).collect();
@@ -119,14 +118,14 @@ impl<'a> Repository<'a> {
diesel::replace_into(messages)
.values(&db_message)
.execute(&mut self.db.connection)?;
.execute(self.connection)?;
diesel::replace_into(conversation_messages)
.values((
conversation_id.eq(conversation_guid),
message_id.eq(&db_message.id),
))
.execute(&mut self.db.connection)?;
.execute(self.connection)?;
Ok(())
}
@@ -141,7 +140,7 @@ impl<'a> Repository<'a> {
.inner_join(messages)
.select(MessageRecord::as_select())
.order_by(schema::messages::date.asc())
.load::<MessageRecord>(&mut self.db.connection)?;
.load::<MessageRecord>(self.connection)?;
let mut result = Vec::new();
for message_record in message_records {
@@ -151,7 +150,7 @@ impl<'a> Repository<'a> {
if let Some(pid) = message_record.sender_participant_id {
let participant = participants
.find(pid)
.first::<ParticipantRecord>(&mut self.db.connection)?;
.first::<ParticipantRecord>(self.connection)?;
message.sender = participant.into();
}
@@ -166,7 +165,7 @@ impl<'a> Repository<'a> {
// Huge caveat with this is that it depends on whatever the last insert was, prevents concurrent inserts.
fn last_insert_id(&mut self) -> Result<i32> {
Ok(diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("last_insert_rowid()"))
.get_result(&mut self.db.connection)?)
.get_result(self.connection)?)
}
fn get_or_create_participant(&mut self, participant: &Participant) -> Option<i32> {
@@ -177,7 +176,7 @@ impl<'a> Repository<'a> {
let existing_participant = participants
.filter(display_name.eq(p_name))
.first::<ParticipantRecord>(&mut self.db.connection)
.first::<ParticipantRecord>(self.connection)
.optional()
.unwrap();
@@ -192,7 +191,7 @@ impl<'a> Repository<'a> {
diesel::insert_into(participants)
.values(&participant_record)
.execute(&mut self.db.connection)
.execute(self.connection)
.unwrap();
self.last_insert_id().ok()

View File

@@ -1,7 +1,7 @@
use diesel::*;
use serde::{Serialize, de::DeserializeOwned};
use anyhow::Result;
use crate::database::Database;
#[derive(Insertable, Queryable, AsChangeset)]
#[diesel(table_name = crate::schema::settings)]
struct SettingsRow<'a> {
@@ -10,12 +10,12 @@ struct SettingsRow<'a> {
}
pub struct Settings<'a> {
db: &'a mut Database,
connection: &'a mut SqliteConnection,
}
impl<'a> Settings<'a> {
pub fn new(db: &'a mut Database) -> Self {
Self { db }
pub fn new(connection: &'a mut SqliteConnection) -> Self {
Self { connection }
}
pub fn put<T: Serialize>(
@@ -31,7 +31,7 @@ impl<'a> Settings<'a> {
.on_conflict(key)
.do_update()
.set(value.eq(&bytes))
.execute(&mut self.db.connection)?;
.execute(self.connection)?;
Ok(())
}
@@ -44,7 +44,7 @@ impl<'a> Settings<'a> {
let blob: Option<Vec<u8>> = settings
.select(value)
.filter(key.eq(k))
.first(&mut self.db.connection)
.first(self.connection)
.optional()?;
Ok(match blob {
@@ -55,14 +55,14 @@ impl<'a> Settings<'a> {
pub fn del(&mut self, k: &str) -> Result<usize> {
use crate::schema::settings::dsl::*;
Ok(diesel::delete(settings.filter(key.eq(k))).execute(&mut self.db.connection)?)
Ok(diesel::delete(settings.filter(key.eq(k))).execute(self.connection)?)
}
pub fn list_keys(&mut self) -> Result<Vec<String>> {
use crate::schema::settings::dsl::*;
let keys: Vec<String> = settings
.select(key)
.load(&mut self.db.connection)?;
.load(self.connection)?;
Ok(keys)
}

View File

@@ -28,15 +28,13 @@ fn participants_vec_equal_ignoring_id(a: &[Participant], b: &[Participant]) -> b
#[test]
fn test_database_init() {
let mut db = Database::new_in_memory().unwrap();
let _ = Repository::new(&mut db);
let _ = Database::new_in_memory().unwrap();
}
#[test]
fn test_add_conversation() {
let mut db = Database::new_in_memory().unwrap();
let mut repository = db.get_repository();
db.with_repository(|repository| {
let guid = "test";
let test_conversation = Conversation::builder()
.guid(guid)
@@ -64,13 +62,13 @@ fn test_add_conversation() {
// And make sure the display name was updated
let conversation = repository.get_conversation_by_guid(guid).unwrap().unwrap();
assert_eq!(conversation.display_name.unwrap(), "Modified Conversation");
});
}
#[test]
fn test_conversation_participants() {
let mut db = Database::new_in_memory().unwrap();
let mut repository = db.get_repository();
db.with_repository(|repository| {
let participants: Vec<Participant> = vec!["one".into(), "two".into()];
let guid = uuid::Uuid::new_v4().to_string();
@@ -99,13 +97,13 @@ fn test_conversation_participants() {
let read_participants: Vec<Participant> = read_conversation.participants;
assert!(participants_vec_equal_ignoring_id(&participants, &read_participants));
});
}
#[test]
fn test_all_conversations_with_participants() {
let mut db = Database::new_in_memory().unwrap();
let mut repository = db.get_repository();
db.with_repository(|repository| {
// Create two conversations with different participants
let participants1: Vec<Participant> = vec!["one".into(), "two".into()];
let participants2: Vec<Participant> = vec!["three".into(), "four".into()];
@@ -138,13 +136,13 @@ fn test_all_conversations_with_participants() {
assert!(participants_vec_equal_ignoring_id(&conv1.participants, &participants1));
assert!(participants_vec_equal_ignoring_id(&conv2.participants, &participants2));
});
}
#[test]
fn test_messages() {
let mut db = Database::new_in_memory().unwrap();
let mut repository = db.get_repository();
db.with_repository(|repository| {
// First create a conversation with participants
let participants = vec!["Alice".into(), "Bob".into()];
let conversation = ConversationBuilder::new()
@@ -187,13 +185,13 @@ fn test_messages() {
} else {
panic!("Expected Remote participant. Got: {:?}", retrieved_message2.sender);
}
});
}
#[test]
fn test_message_ordering() {
let mut db = Database::new_in_memory().unwrap();
let mut repository = db.get_repository();
db.with_repository(|repository| {
// Create a conversation
let conversation = ConversationBuilder::new()
.display_name("Test Chat")
@@ -231,13 +229,13 @@ fn test_message_ordering() {
for i in 1..messages.len() {
assert!(messages[i].date > messages[i-1].date);
}
});
}
#[test]
fn test_settings() {
let mut db = Database::new_in_memory().unwrap();
let mut settings = db.get_settings();
db.with_settings(|settings| {
settings.put("test", &"test".to_string()).unwrap();
assert_eq!(settings.get::<String>("test").unwrap().unwrap(), "test");
@@ -246,4 +244,5 @@ fn test_settings() {
let keys = settings.list_keys().unwrap();
assert_eq!(keys.len(), 0);
});
}

View File

@@ -108,7 +108,9 @@ impl DbClient {
}
pub fn print_conversations(&mut self) -> Result<()> {
let all_conversations = self.database.get_repository().all_conversations()?;
let all_conversations = self.database.with_repository(|repository| {
repository.all_conversations()
})?;
println!("{} Conversations: ", all_conversations.len());
for conversation in all_conversations {
@@ -119,7 +121,10 @@ impl DbClient {
}
pub async fn print_messages(&mut self, conversation_id: &str) -> Result<()> {
let messages = self.database.get_repository().get_messages_for_conversation(conversation_id)?;
let messages = self.database.with_repository(|repository| {
repository.get_messages_for_conversation(conversation_id)
})?;
for message in messages {
println!("{}", MessagePrinter::new(&message.into()));
}
@@ -133,10 +138,14 @@ impl DbClient {
.map(|c| kordophone_db::models::Conversation::from(c))
.collect();
let mut repository = self.database.get_repository();
// Process each conversation
for conversation in db_conversations {
let conversation_id = conversation.guid.clone();
repository.insert_conversation(conversation)?;
// Insert the conversation
self.database.with_repository(|repository| {
repository.insert_conversation(conversation)
})?;
// Fetch and sync messages for this conversation
let messages = client.get_messages(&conversation_id).await?;
@@ -144,17 +153,21 @@ impl DbClient {
.map(|m| kordophone_db::models::Message::from(m))
.collect();
// Insert each message
self.database.with_repository(|repository| -> Result<()> {
for message in db_messages {
repository.insert_message(&conversation_id, message)?;
}
Ok(())
})?;
}
Ok(())
}
pub fn get_setting(&mut self, key: Option<String>) -> Result<()> {
let mut settings = self.database.get_settings();
self.database.with_settings(|settings| {
match key {
Some(key) => {
// Get a specific setting
@@ -183,20 +196,23 @@ impl DbClient {
}
Ok(())
})
}
pub fn put_setting(&mut self, key: String, value: String) -> Result<()> {
let mut settings = self.database.get_settings();
self.database.with_settings(|settings| {
settings.put(&key, &value)?;
Ok(())
})
}
pub fn delete_setting(&mut self, key: String) -> Result<()> {
let mut settings = self.database.get_settings();
self.database.with_settings(|settings| {
let count = settings.del(&key)?;
if count == 0 {
println!("Setting '{}' not found", key);
}
Ok(())
})
}
}