Private
Public Access
1
0

kordophone-db: participants, but still need to "upsert" these

Might move to SeaORM instead of trying to do this with microrm
This commit is contained in:
2024-12-14 12:53:44 -08:00
parent fac9b1ffe6
commit 86601b027a
5 changed files with 165 additions and 51 deletions

View File

@@ -1,7 +1,14 @@
use std::error::Error;
use microrm::prelude::*;
use microrm::Stored;
use crate::models::conversation::{self, Conversation, ConversationID};
use std::error::Error;
use crate::models::participant::ParticipantID;
use crate::models::{
participant::Participant,
conversation::{
self, Conversation, ConversationID, PendingConversation
}
};
pub struct ChatDatabase {
db: DB,
@@ -10,6 +17,7 @@ pub struct ChatDatabase {
#[derive(Database)]
struct DB {
conversations: microrm::IDMap<Conversation>,
participants: microrm::IDMap<Participant>,
}
impl ChatDatabase {
@@ -20,20 +28,27 @@ impl ChatDatabase {
})
}
pub fn insert_conversation(&self, conversation: Conversation) -> Result<ConversationID, microrm::Error> {
pub fn insert_conversation(&self, conversation: PendingConversation) -> Result<ConversationID, microrm::Error> {
// First see if conversation guid already exists, update it if so
let guid = &conversation.guid;
let mut existing = self.db.conversations
.with(Conversation::Guid, guid)
.get()?;
let guid = conversation.guid();
let mut existing = self.stored_conversation_by_guid(guid)?;
if let Some(existing) = existing.first_mut() {
existing.display_name = conversation.display_name;
if let Some(existing) = existing.as_mut() {
conversation.update(existing);
existing.sync();
return Ok(existing.id());
} else {
// Otherwise, insert.
return self.db.conversations.insert(conversation);
let inserted = self.db.conversations.insert_and_return(conversation.get_conversation())?;
// Insert participants
let participants = conversation.get_participants();
let inserted_participants = participants.iter()
.map(|p| self.db.participants.insert(p.clone()).unwrap())
.collect::<Vec<_>>();
inserted.connect_participants(inserted_participants);
return Ok(inserted.id());
}
}
@@ -66,6 +81,26 @@ impl ChatDatabase {
)
}
fn upsert_participants(&self, participants: Vec<Participant>) -> Vec<ParticipantID> {
// Filter existing participants and add to result
let existing_participants = participants.iter()
.filter_map(|p| self.db.participants
.with(Participant::DisplayName, &p.display_name)
.get()
.ok()
.and_then(|v| v
.into_iter()
.last()
.map(|p| p.id())
)
)
.collect::<Vec<_>>();
participants.iter()
.map(|p| self.db.participants.insert(p.clone()).unwrap())
.collect()
}
fn stored_conversation_by_guid(&self, guid: &str) -> Result<Option<Stored<Conversation>>, microrm::Error> {
self.db.conversations
.with(Conversation::Guid, guid)

View File

@@ -3,9 +3,13 @@ pub mod chat_database;
#[cfg(test)]
mod tests {
use microrm::prelude::Queryable;
use crate::{chat_database::{self, ChatDatabase}, models::conversation::{Conversation, ConversationBuilder, Participant}};
use crate::{
chat_database::ChatDatabase,
models::{
conversation::{Conversation, ConversationBuilder},
participant::Participant
}
};
#[test]
fn test_database_init() {
@@ -48,7 +52,8 @@ mod tests {
fn test_conversation_participants() {
let db = ChatDatabase::new_in_memory().unwrap();
let participants: Vec<String> = vec!["one".into(), "two".into()];
let participants: Vec<Participant> = vec!["one".into(), "two".into()];
let conversation = ConversationBuilder::new()
.display_name("Test")
.participant_display_names(participants.clone())
@@ -57,12 +62,20 @@ mod tests {
let id = db.insert_conversation(conversation).unwrap();
let read_conversation = db.get_conversation_by_id(id).unwrap().unwrap();
let read_participants: Vec<String> = read_conversation.participant_display_names
.get()
.unwrap()
.into_iter()
.map(|p| p.wrapped().display_name)
.collect();
let read_participants: Vec<Participant> = read_conversation.get_participant_display_names();
assert_eq!(participants, read_participants);
// Try making another conversation with the same participants
let conversation = ConversationBuilder::new()
.display_name("A Different Test")
.participant_display_names(participants.clone())
.build();
let id = db.insert_conversation(conversation).unwrap();
let read_conversation = db.get_conversation_by_id(id).unwrap().unwrap();
let read_participants: Vec<Participant> = read_conversation.get_participant_display_names();
assert_eq!(participants, read_participants);
}

View File

@@ -1,9 +1,14 @@
use microrm::prelude::*;
use chrono::{DateTime, Local, Utc};
use microrm::Stored;
use time::OffsetDateTime;
use uuid::Uuid;
use crate::models::date::Date;
use crate::models::{
date::Date,
participant::Participant,
};
use super::participant::ParticipantID;
#[derive(Entity, Clone)]
pub struct Conversation {
@@ -14,19 +19,8 @@ pub struct Conversation {
pub display_name: Option<String>,
pub last_message_preview: Option<String>,
pub date: OffsetDateTime,
pub participant_display_names: microrm::RelationMap<Participant>,
}
#[derive(Entity, Clone)]
pub struct Participant {
#[unique]
pub display_name: String
}
impl Into<Participant> for String {
fn into(self) -> Participant {
Participant { display_name: self }
}
participant_display_names: microrm::RelationMap<Participant>,
}
impl Conversation {
@@ -44,6 +38,60 @@ impl Conversation {
display_name: self.display_name.clone(),
}
}
pub fn get_participant_display_names(&self) -> Vec<Participant> {
self.participant_display_names
.get()
.unwrap()
.into_iter()
.map(|p| p.wrapped())
.collect()
}
pub fn update(&self, stored_conversation: &mut Stored<Conversation>) {
*stored_conversation.as_mut() = self.clone();
}
pub fn connect_participants(&self, participant_ids: Vec<ParticipantID>) {
participant_ids.iter().for_each(|id| {
self.participant_display_names.connect_to(*id).unwrap();
});
}
}
#[derive(Clone)]
pub struct PendingConversation {
conversation: Conversation,
participants: Vec<Participant>,
}
impl PendingConversation {
pub fn guid(&self) -> &String {
&self.conversation.guid
}
pub fn into_builder(self) -> ConversationBuilder {
ConversationBuilder {
guid: Some(self.conversation.guid),
date: Date::new(self.conversation.date),
participant_display_names: Some(self.participants),
unread_count: Some(self.conversation.unread_count),
last_message_preview: self.conversation.last_message_preview,
display_name: self.conversation.display_name,
}
}
pub fn update(&self, stored_conversation: &mut microrm::Stored<Conversation>) {
self.conversation.update(stored_conversation);
}
pub fn get_participants(&self) -> &Vec<Participant> {
&self.participants
}
pub fn get_conversation(&self) -> Conversation {
self.conversation.clone()
}
}
#[derive(Default)]
@@ -52,7 +100,7 @@ pub struct ConversationBuilder {
date: Date,
unread_count: Option<i64>,
last_message_preview: Option<String>,
participant_display_names: Option<Vec<String>>,
participant_display_names: Option<Vec<Participant>>,
display_name: Option<String>,
}
@@ -81,7 +129,7 @@ impl ConversationBuilder {
self
}
pub fn participant_display_names(mut self, participant_display_names: Vec<String>) -> Self {
pub fn participant_display_names(mut self, participant_display_names: Vec<Participant>) -> Self {
self.participant_display_names = Some(participant_display_names);
self
}
@@ -91,23 +139,21 @@ impl ConversationBuilder {
self
}
pub fn build(self) -> Conversation {
let result = Conversation {
guid: self.guid.unwrap_or(Uuid::new_v4().to_string()),
fn build_conversation(&self) -> Conversation {
Conversation {
guid: self.guid.clone().unwrap_or(Uuid::new_v4().to_string()),
unread_count: self.unread_count.unwrap_or(0),
last_message_preview: self.last_message_preview,
display_name: self.display_name,
last_message_preview: self.last_message_preview.clone(),
display_name: self.display_name.clone(),
date: self.date.dt,
participant_display_names: Default::default(),
};
// TODO: this isn't right... this is crashing the test.
if let Some(participants) = self.participant_display_names {
for participant in participants {
result.participant_display_names.insert(participant.into()).unwrap();
}
}
result
pub fn build(self) -> PendingConversation {
PendingConversation {
conversation: self.build_conversation(),
participants: self.participant_display_names.unwrap_or_default(),
}
}
}

View File

@@ -1,2 +1,3 @@
pub mod conversation;
pub mod date;
pub mod participant;

View File

@@ -0,0 +1,19 @@
use microrm::prelude::*;
#[derive(Entity, Clone, PartialEq)]
pub struct Participant {
#[unique]
pub display_name: String
}
impl Into<Participant> for String {
fn into(self) -> Participant {
Participant { display_name: self }
}
}
impl From<&str> for Participant {
fn from(s: &str) -> Self {
Participant { display_name: s.into() }
}
}