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 const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
pub struct Database { pub struct Database {
pub connection: SqliteConnection, connection: SqliteConnection,
} }
impl Database { impl Database {
@@ -24,11 +24,19 @@ impl Database {
Self::new(":memory:") Self::new(":memory:")
} }
pub fn get_repository(&mut self) -> Repository { pub fn with_repository<F, R>(&mut self, f: F) -> R
Repository::new(self) where
F: FnOnce(&mut Repository) -> R,
{
let mut repository = Repository::new(&mut self.connection);
f(&mut repository)
} }
pub fn get_settings(&mut self) -> Settings { pub fn with_settings<F, R>(&mut self, f: F) -> R
Settings::new(self) 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 diesel::query_dsl::BelongingToDsl;
use crate::{ use crate::{
database::Database,
models::{ models::{
Conversation, Conversation,
Message, Message,
@@ -20,12 +19,12 @@ use crate::{
}; };
pub struct Repository<'a> { pub struct Repository<'a> {
db: &'a mut Database, connection: &'a mut SqliteConnection,
} }
impl<'a> Repository<'a> { impl<'a> Repository<'a> {
pub fn new(db: &'a mut Database) -> Self { pub fn new(connection: &'a mut SqliteConnection) -> Self {
Self { db } Self { connection }
} }
pub fn insert_conversation(&mut self, conversation: Conversation) -> Result<()> { pub fn insert_conversation(&mut self, conversation: Conversation) -> Result<()> {
@@ -37,25 +36,25 @@ impl<'a> Repository<'a> {
diesel::replace_into(conversations) diesel::replace_into(conversations)
.values(&db_conversation) .values(&db_conversation)
.execute(&mut self.db.connection)?; .execute(self.connection)?;
diesel::replace_into(participants) diesel::replace_into(participants)
.values(&db_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 // Sqlite backend doesn't support batch insert, so we have to do this manually
for participant in db_participants { for participant in db_participants {
let pid = participants let pid = participants
.select(schema::participants::id) .select(schema::participants::id)
.filter(schema::participants::display_name.eq(&participant.display_name)) .filter(schema::participants::display_name.eq(&participant.display_name))
.first::<i32>(&mut self.db.connection)?; .first::<i32>(self.connection)?;
diesel::replace_into(conversation_participants) diesel::replace_into(conversation_participants)
.values(( .values((
conversation_id.eq(&db_conversation.id), conversation_id.eq(&db_conversation.id),
participant_id.eq(pid), participant_id.eq(pid),
)) ))
.execute(&mut self.db.connection)?; .execute(self.connection)?;
} }
Ok(()) Ok(())
@@ -67,14 +66,14 @@ impl<'a> Repository<'a> {
let result = conversations let result = conversations
.find(match_guid) .find(match_guid)
.first::<ConversationRecord>(&mut self.db.connection) .first::<ConversationRecord>(self.connection)
.optional()?; .optional()?;
if let Some(conversation) = result { if let Some(conversation) = result {
let db_participants = ConversationParticipant::belonging_to(&conversation) let db_participants = ConversationParticipant::belonging_to(&conversation)
.inner_join(participants) .inner_join(participants)
.select(ParticipantRecord::as_select()) .select(ParticipantRecord::as_select())
.load::<ParticipantRecord>(&mut self.db.connection)?; .load::<ParticipantRecord>(self.connection)?;
let mut model_conversation: Conversation = conversation.into(); let mut model_conversation: Conversation = conversation.into();
model_conversation.participants = db_participants.into_iter().map(|p| p.into()).collect(); 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::*; use crate::schema::participants::dsl::*;
let db_conversations = conversations let db_conversations = conversations
.load::<ConversationRecord>(&mut self.db.connection)?; .load::<ConversationRecord>(self.connection)?;
let mut result = Vec::new(); let mut result = Vec::new();
for db_conversation in db_conversations { for db_conversation in db_conversations {
let db_participants = ConversationParticipant::belonging_to(&db_conversation) let db_participants = ConversationParticipant::belonging_to(&db_conversation)
.inner_join(participants) .inner_join(participants)
.select(ParticipantRecord::as_select()) .select(ParticipantRecord::as_select())
.load::<ParticipantRecord>(&mut self.db.connection)?; .load::<ParticipantRecord>(self.connection)?;
let mut model_conversation: Conversation = db_conversation.into(); let mut model_conversation: Conversation = db_conversation.into();
model_conversation.participants = db_participants.into_iter().map(|p| p.into()).collect(); model_conversation.participants = db_participants.into_iter().map(|p| p.into()).collect();
@@ -119,14 +118,14 @@ impl<'a> Repository<'a> {
diesel::replace_into(messages) diesel::replace_into(messages)
.values(&db_message) .values(&db_message)
.execute(&mut self.db.connection)?; .execute(self.connection)?;
diesel::replace_into(conversation_messages) diesel::replace_into(conversation_messages)
.values(( .values((
conversation_id.eq(conversation_guid), conversation_id.eq(conversation_guid),
message_id.eq(&db_message.id), message_id.eq(&db_message.id),
)) ))
.execute(&mut self.db.connection)?; .execute(self.connection)?;
Ok(()) Ok(())
} }
@@ -141,7 +140,7 @@ impl<'a> Repository<'a> {
.inner_join(messages) .inner_join(messages)
.select(MessageRecord::as_select()) .select(MessageRecord::as_select())
.order_by(schema::messages::date.asc()) .order_by(schema::messages::date.asc())
.load::<MessageRecord>(&mut self.db.connection)?; .load::<MessageRecord>(self.connection)?;
let mut result = Vec::new(); let mut result = Vec::new();
for message_record in message_records { for message_record in message_records {
@@ -151,7 +150,7 @@ impl<'a> Repository<'a> {
if let Some(pid) = message_record.sender_participant_id { if let Some(pid) = message_record.sender_participant_id {
let participant = participants let participant = participants
.find(pid) .find(pid)
.first::<ParticipantRecord>(&mut self.db.connection)?; .first::<ParticipantRecord>(self.connection)?;
message.sender = participant.into(); 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. // 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> { fn last_insert_id(&mut self) -> Result<i32> {
Ok(diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("last_insert_rowid()")) 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> { fn get_or_create_participant(&mut self, participant: &Participant) -> Option<i32> {
@@ -177,7 +176,7 @@ impl<'a> Repository<'a> {
let existing_participant = participants let existing_participant = participants
.filter(display_name.eq(p_name)) .filter(display_name.eq(p_name))
.first::<ParticipantRecord>(&mut self.db.connection) .first::<ParticipantRecord>(self.connection)
.optional() .optional()
.unwrap(); .unwrap();
@@ -192,7 +191,7 @@ impl<'a> Repository<'a> {
diesel::insert_into(participants) diesel::insert_into(participants)
.values(&participant_record) .values(&participant_record)
.execute(&mut self.db.connection) .execute(self.connection)
.unwrap(); .unwrap();
self.last_insert_id().ok() self.last_insert_id().ok()

View File

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

View File

@@ -28,222 +28,221 @@ fn participants_vec_equal_ignoring_id(a: &[Participant], b: &[Participant]) -> b
#[test] #[test]
fn test_database_init() { fn test_database_init() {
let mut db = Database::new_in_memory().unwrap(); let _ = Database::new_in_memory().unwrap();
let _ = Repository::new(&mut db);
} }
#[test] #[test]
fn test_add_conversation() { fn test_add_conversation() {
let mut db = Database::new_in_memory().unwrap(); 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)
.unread_count(2)
.display_name("Test Conversation")
.build();
let guid = "test"; repository.insert_conversation(test_conversation.clone()).unwrap();
let test_conversation = Conversation::builder()
.guid(guid)
.unread_count(2)
.display_name("Test Conversation")
.build();
repository.insert_conversation(test_conversation.clone()).unwrap(); // Try to fetch with id now
let conversation = repository.get_conversation_by_guid(guid).unwrap().unwrap();
assert_eq!(conversation.guid, "test");
// Try to fetch with id now // Modify the conversation and update it
let conversation = repository.get_conversation_by_guid(guid).unwrap().unwrap(); let modified_conversation = test_conversation.into_builder()
assert_eq!(conversation.guid, "test"); .display_name("Modified Conversation")
.build();
// Modify the conversation and update it repository.insert_conversation(modified_conversation.clone()).unwrap();
let modified_conversation = test_conversation.into_builder()
.display_name("Modified Conversation")
.build();
repository.insert_conversation(modified_conversation.clone()).unwrap(); // Make sure we still only have one conversation.
let all_conversations = repository.all_conversations().unwrap();
assert_eq!(all_conversations.len(), 1);
// Make sure we still only have one conversation. // And make sure the display name was updated
let all_conversations = repository.all_conversations().unwrap(); let conversation = repository.get_conversation_by_guid(guid).unwrap().unwrap();
assert_eq!(all_conversations.len(), 1); assert_eq!(conversation.display_name.unwrap(), "Modified 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] #[test]
fn test_conversation_participants() { fn test_conversation_participants() {
let mut db = Database::new_in_memory().unwrap(); 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 participants: Vec<Participant> = vec!["one".into(), "two".into()]; let guid = uuid::Uuid::new_v4().to_string();
let conversation = ConversationBuilder::new()
.guid(&guid)
.display_name("Test")
.participants(participants.clone())
.build();
let guid = uuid::Uuid::new_v4().to_string(); repository.insert_conversation(conversation).unwrap();
let conversation = ConversationBuilder::new()
.guid(&guid)
.display_name("Test")
.participants(participants.clone())
.build();
repository.insert_conversation(conversation).unwrap(); let read_conversation = repository.get_conversation_by_guid(&guid).unwrap().unwrap();
let read_participants = read_conversation.participants;
let read_conversation = repository.get_conversation_by_guid(&guid).unwrap().unwrap(); assert!(participants_vec_equal_ignoring_id(&participants, &read_participants));
let read_participants = read_conversation.participants;
assert!(participants_vec_equal_ignoring_id(&participants, &read_participants)); // Try making another conversation with the same participants
let conversation = ConversationBuilder::new()
.display_name("A Different Test")
.participants(participants.clone())
.build();
// Try making another conversation with the same participants repository.insert_conversation(conversation).unwrap();
let conversation = ConversationBuilder::new()
.display_name("A Different Test")
.participants(participants.clone())
.build();
repository.insert_conversation(conversation).unwrap(); let read_conversation = repository.get_conversation_by_guid(&guid).unwrap().unwrap();
let read_participants: Vec<Participant> = read_conversation.participants;
let read_conversation = repository.get_conversation_by_guid(&guid).unwrap().unwrap(); assert!(participants_vec_equal_ignoring_id(&participants, &read_participants));
let read_participants: Vec<Participant> = read_conversation.participants; });
assert!(participants_vec_equal_ignoring_id(&participants, &read_participants));
} }
#[test] #[test]
fn test_all_conversations_with_participants() { fn test_all_conversations_with_participants() {
let mut db = Database::new_in_memory().unwrap(); 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()];
// Create two conversations with different participants let guid1 = uuid::Uuid::new_v4().to_string();
let participants1: Vec<Participant> = vec!["one".into(), "two".into()]; let conversation1 = ConversationBuilder::new()
let participants2: Vec<Participant> = vec!["three".into(), "four".into()]; .guid(&guid1)
.display_name("Test 1")
.participants(participants1.clone())
.build();
let guid1 = uuid::Uuid::new_v4().to_string(); let guid2 = uuid::Uuid::new_v4().to_string();
let conversation1 = ConversationBuilder::new() let conversation2 = ConversationBuilder::new()
.guid(&guid1) .guid(&guid2)
.display_name("Test 1") .display_name("Test 2")
.participants(participants1.clone()) .participants(participants2.clone())
.build(); .build();
let guid2 = uuid::Uuid::new_v4().to_string(); // Insert both conversations
let conversation2 = ConversationBuilder::new() repository.insert_conversation(conversation1).unwrap();
.guid(&guid2) repository.insert_conversation(conversation2).unwrap();
.display_name("Test 2")
.participants(participants2.clone())
.build();
// Insert both conversations // Get all conversations and verify the results
repository.insert_conversation(conversation1).unwrap(); let all_conversations = repository.all_conversations().unwrap();
repository.insert_conversation(conversation2).unwrap(); assert_eq!(all_conversations.len(), 2);
// Get all conversations and verify the results // Find and verify each conversation's participants
let all_conversations = repository.all_conversations().unwrap(); let conv1 = all_conversations.iter().find(|c| c.guid == guid1).unwrap();
assert_eq!(all_conversations.len(), 2); let conv2 = all_conversations.iter().find(|c| c.guid == guid2).unwrap();
// Find and verify each conversation's participants assert!(participants_vec_equal_ignoring_id(&conv1.participants, &participants1));
let conv1 = all_conversations.iter().find(|c| c.guid == guid1).unwrap(); assert!(participants_vec_equal_ignoring_id(&conv2.participants, &participants2));
let conv2 = all_conversations.iter().find(|c| c.guid == guid2).unwrap(); });
assert!(participants_vec_equal_ignoring_id(&conv1.participants, &participants1));
assert!(participants_vec_equal_ignoring_id(&conv2.participants, &participants2));
} }
#[test] #[test]
fn test_messages() { fn test_messages() {
let mut db = Database::new_in_memory().unwrap(); 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()
.display_name("Test Chat")
.participants(participants)
.build();
let conversation_id = conversation.guid.clone();
// First create a conversation with participants repository.insert_conversation(conversation).unwrap();
let participants = vec!["Alice".into(), "Bob".into()];
let conversation = ConversationBuilder::new()
.display_name("Test Chat")
.participants(participants)
.build();
let conversation_id = conversation.guid.clone();
repository.insert_conversation(conversation).unwrap(); // Create and insert a message from Me
let message1 = Message::builder()
.text("Hello everyone!".to_string())
.build();
// Create and insert a message from Me // Create and insert a message from a remote participant
let message1 = Message::builder() let message2 = Message::builder()
.text("Hello everyone!".to_string()) .text("Hi there!".to_string())
.build(); .sender("Alice".into())
.build();
// Create and insert a message from a remote participant // Insert both messages
let message2 = Message::builder() repository.insert_message(&conversation_id, message1.clone()).unwrap();
.text("Hi there!".to_string()) repository.insert_message(&conversation_id, message2.clone()).unwrap();
.sender("Alice".into())
.build();
// Insert both messages // Retrieve messages
repository.insert_message(&conversation_id, message1.clone()).unwrap(); let messages = repository.get_messages_for_conversation(&conversation_id).unwrap();
repository.insert_message(&conversation_id, message2.clone()).unwrap(); assert_eq!(messages.len(), 2);
// Retrieve messages // Verify first message (from Me)
let messages = repository.get_messages_for_conversation(&conversation_id).unwrap(); let retrieved_message1 = messages.iter().find(|m| m.id == message1.id).unwrap();
assert_eq!(messages.len(), 2); assert_eq!(retrieved_message1.text, "Hello everyone!");
assert!(matches!(retrieved_message1.sender, Participant::Me));
// Verify first message (from Me) // Verify second message (from Alice)
let retrieved_message1 = messages.iter().find(|m| m.id == message1.id).unwrap(); let retrieved_message2 = messages.iter().find(|m| m.id == message2.id).unwrap();
assert_eq!(retrieved_message1.text, "Hello everyone!"); assert_eq!(retrieved_message2.text, "Hi there!");
assert!(matches!(retrieved_message1.sender, Participant::Me)); if let Participant::Remote { display_name, .. } = &retrieved_message2.sender {
assert_eq!(display_name, "Alice");
// Verify second message (from Alice) } else {
let retrieved_message2 = messages.iter().find(|m| m.id == message2.id).unwrap(); panic!("Expected Remote participant. Got: {:?}", retrieved_message2.sender);
assert_eq!(retrieved_message2.text, "Hi there!"); }
if let Participant::Remote { display_name, .. } = &retrieved_message2.sender { });
assert_eq!(display_name, "Alice");
} else {
panic!("Expected Remote participant. Got: {:?}", retrieved_message2.sender);
}
} }
#[test] #[test]
fn test_message_ordering() { fn test_message_ordering() {
let mut db = Database::new_in_memory().unwrap(); 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")
.build();
let conversation_id = conversation.guid.clone();
repository.insert_conversation(conversation).unwrap();
// Create a conversation // Create messages with specific timestamps
let conversation = ConversationBuilder::new() let now = chrono::Utc::now().naive_utc();
.display_name("Test Chat") let message1 = Message::builder()
.build(); .text("First message".to_string())
let conversation_id = conversation.guid.clone(); .date(now)
repository.insert_conversation(conversation).unwrap(); .build();
// Create messages with specific timestamps let message2 = Message::builder()
let now = chrono::Utc::now().naive_utc(); .text("Second message".to_string())
let message1 = Message::builder() .date(now + chrono::Duration::minutes(1))
.text("First message".to_string()) .build();
.date(now)
.build();
let message2 = Message::builder() let message3 = Message::builder()
.text("Second message".to_string()) .text("Third message".to_string())
.date(now + chrono::Duration::minutes(1)) .date(now + chrono::Duration::minutes(2))
.build(); .build();
let message3 = Message::builder() // Insert messages
.text("Third message".to_string()) repository.insert_message(&conversation_id, message1).unwrap();
.date(now + chrono::Duration::minutes(2)) repository.insert_message(&conversation_id, message2).unwrap();
.build(); repository.insert_message(&conversation_id, message3).unwrap();
// Insert messages // Retrieve messages and verify order
repository.insert_message(&conversation_id, message1).unwrap(); let messages = repository.get_messages_for_conversation(&conversation_id).unwrap();
repository.insert_message(&conversation_id, message2).unwrap(); assert_eq!(messages.len(), 3);
repository.insert_message(&conversation_id, message3).unwrap();
// Retrieve messages and verify order // Messages should be ordered by date
let messages = repository.get_messages_for_conversation(&conversation_id).unwrap(); for i in 1..messages.len() {
assert_eq!(messages.len(), 3); assert!(messages[i].date > messages[i-1].date);
}
// Messages should be ordered by date });
for i in 1..messages.len() {
assert!(messages[i].date > messages[i-1].date);
}
} }
#[test] #[test]
fn test_settings() { fn test_settings() {
let mut db = Database::new_in_memory().unwrap(); 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");
settings.put("test", &"test".to_string()).unwrap(); settings.del("test").unwrap();
assert_eq!(settings.get::<String>("test").unwrap().unwrap(), "test"); assert!(settings.get::<String>("test").unwrap().is_none());
settings.del("test").unwrap(); let keys = settings.list_keys().unwrap();
assert!(settings.get::<String>("test").unwrap().is_none()); assert_eq!(keys.len(), 0);
});
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<()> { 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()); println!("{} Conversations: ", all_conversations.len());
for conversation in all_conversations { for conversation in all_conversations {
@@ -119,7 +121,10 @@ impl DbClient {
} }
pub async fn print_messages(&mut self, conversation_id: &str) -> Result<()> { 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 { for message in messages {
println!("{}", MessagePrinter::new(&message.into())); println!("{}", MessagePrinter::new(&message.into()));
} }
@@ -133,10 +138,14 @@ impl DbClient {
.map(|c| kordophone_db::models::Conversation::from(c)) .map(|c| kordophone_db::models::Conversation::from(c))
.collect(); .collect();
let mut repository = self.database.get_repository(); // Process each conversation
for conversation in db_conversations { for conversation in db_conversations {
let conversation_id = conversation.guid.clone(); 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 // Fetch and sync messages for this conversation
let messages = client.get_messages(&conversation_id).await?; let messages = client.get_messages(&conversation_id).await?;
@@ -144,59 +153,66 @@ impl DbClient {
.map(|m| kordophone_db::models::Message::from(m)) .map(|m| kordophone_db::models::Message::from(m))
.collect(); .collect();
for message in db_messages { // Insert each message
repository.insert_message(&conversation_id, message)?; self.database.with_repository(|repository| -> Result<()> {
} for message in db_messages {
repository.insert_message(&conversation_id, message)?;
}
Ok(())
})?;
} }
Ok(()) Ok(())
} }
pub fn get_setting(&mut self, key: Option<String>) -> Result<()> { pub fn get_setting(&mut self, key: Option<String>) -> Result<()> {
let mut settings = self.database.get_settings(); self.database.with_settings(|settings| {
match key {
match key { Some(key) => {
Some(key) => { // Get a specific setting
// Get a specific setting let value: Option<String> = settings.get(&key)?;
let value: Option<String> = settings.get(&key)?; match value {
match value { Some(v) => println!("{} = {}", key, v),
Some(v) => println!("{} = {}", key, v), None => println!("Setting '{}' not found", key),
None => println!("Setting '{}' not found", key), }
} },
}, None => {
None => { // List all settings
// List all settings let keys = settings.list_keys()?;
let keys = settings.list_keys()?; if keys.is_empty() {
if keys.is_empty() { println!("No settings found");
println!("No settings found"); } else {
} else { println!("Settings:");
println!("Settings:"); for key in keys {
for key in keys { let value: Option<String> = settings.get(&key)?;
let value: Option<String> = settings.get(&key)?; match value {
match value { Some(v) => println!(" {} = {}", key, v),
Some(v) => println!(" {} = {}", key, v), None => println!(" {} = <error reading value>", key),
None => println!(" {} = <error reading value>", key), }
} }
} }
} }
} }
}
Ok(())
Ok(()) })
} }
pub fn put_setting(&mut self, key: String, value: String) -> Result<()> { 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)?; settings.put(&key, &value)?;
Ok(()) Ok(())
})
} }
pub fn delete_setting(&mut self, key: String) -> Result<()> { 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)?; let count = settings.del(&key)?;
if count == 0 { if count == 0 {
println!("Setting '{}' not found", key); println!("Setting '{}' not found", key);
} }
Ok(()) Ok(())
})
} }
} }