kordophone-db: switch to diesel for more features
This commit is contained in:
@@ -1,113 +1,100 @@
|
||||
use std::error::Error;
|
||||
use microrm::prelude::*;
|
||||
use microrm::Stored;
|
||||
use anyhow::Result;
|
||||
use diesel::prelude::*;
|
||||
use diesel::query_dsl::BelongingToDsl;
|
||||
|
||||
use crate::models::participant::ParticipantID;
|
||||
use crate::models::{
|
||||
participant::Participant,
|
||||
use crate::{models::{
|
||||
conversation::{
|
||||
self, Conversation, ConversationID, PendingConversation
|
||||
}
|
||||
};
|
||||
self, Conversation, DbConversation
|
||||
}, participant::{ConversationParticipant, DbParticipant, Participant}
|
||||
}, schema};
|
||||
|
||||
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
||||
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
||||
|
||||
pub struct ChatDatabase {
|
||||
db: DB,
|
||||
}
|
||||
|
||||
#[derive(Database)]
|
||||
struct DB {
|
||||
conversations: microrm::IDMap<Conversation>,
|
||||
participants: microrm::IDMap<Participant>,
|
||||
db: SqliteConnection,
|
||||
}
|
||||
|
||||
impl ChatDatabase {
|
||||
pub fn new_in_memory() -> Result<Self, Box<dyn Error + Send + Sync>> {
|
||||
let db = DB::open_path(":memory:")?;
|
||||
pub fn new_in_memory() -> Result<Self> {
|
||||
let mut db = SqliteConnection::establish(":memory:")?;
|
||||
db.run_pending_migrations(MIGRATIONS)
|
||||
.map_err(|e| anyhow::anyhow!("Error running migrations: {}", e))?;
|
||||
|
||||
return Ok(Self {
|
||||
db: db,
|
||||
})
|
||||
}
|
||||
|
||||
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.stored_conversation_by_guid(guid)?;
|
||||
pub fn insert_conversation(&mut self, conversation: Conversation) -> Result<()> {
|
||||
use crate::schema::conversations::dsl::*;
|
||||
use crate::schema::participants::dsl::*;
|
||||
use crate::schema::conversation_participants::dsl::*;
|
||||
|
||||
if let Some(existing) = existing.as_mut() {
|
||||
conversation.update(existing);
|
||||
existing.sync();
|
||||
return Ok(existing.id());
|
||||
} else {
|
||||
// Otherwise, insert.
|
||||
let inserted = self.db.conversations.insert_and_return(conversation.get_conversation())?;
|
||||
let (db_conversation, db_participants) = conversation.into();
|
||||
|
||||
// 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());
|
||||
diesel::replace_into(conversations)
|
||||
.values(&db_conversation)
|
||||
.execute(&mut self.db)?;
|
||||
|
||||
diesel::replace_into(participants)
|
||||
.values(&db_participants)
|
||||
.execute(&mut self.db)?;
|
||||
|
||||
// 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)?;
|
||||
|
||||
diesel::replace_into(conversation_participants)
|
||||
.values((
|
||||
conversation_id.eq(&db_conversation.id),
|
||||
participant_id.eq(pid),
|
||||
))
|
||||
.execute(&mut self.db)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_conversation_by_id(&self, id: ConversationID) -> Result<Option<Conversation>, microrm::Error> {
|
||||
self.db.conversations
|
||||
.by_id(id)
|
||||
.map(|stored_conversation| stored_conversation
|
||||
.map(|stored| stored.wrapped())
|
||||
)
|
||||
pub fn get_conversation_by_guid(&mut self, match_guid: &str) -> Result<Option<Conversation>> {
|
||||
use crate::schema::conversations::dsl::*;
|
||||
use crate::schema::participants::dsl::*;
|
||||
|
||||
let result = conversations
|
||||
.find(match_guid)
|
||||
.first::<DbConversation>(&mut self.db)
|
||||
.optional()?;
|
||||
|
||||
if let Some(conversation) = result {
|
||||
let dbParticipants = ConversationParticipant::belonging_to(&conversation)
|
||||
.inner_join(participants)
|
||||
.select(DbParticipant::as_select())
|
||||
.load::<DbParticipant>(&mut self.db)?;
|
||||
|
||||
let mut modelConversation: Conversation = conversation.into();
|
||||
modelConversation.participants = dbParticipants.into_iter().map(|p| p.into()).collect();
|
||||
|
||||
return Ok(Some(modelConversation));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn get_conversation_by_guid(&self, guid: &str) -> Result<Option<Conversation>, microrm::Error> {
|
||||
self.db.conversations
|
||||
.with(Conversation::Guid, guid)
|
||||
.get()
|
||||
.and_then(|v| Ok(v
|
||||
.into_iter()
|
||||
.map(|c| c.wrapped())
|
||||
.last()
|
||||
))
|
||||
}
|
||||
pub fn all_conversations(&mut self) -> Result<Vec<Conversation>> {
|
||||
use crate::schema::conversations::dsl::*;
|
||||
|
||||
pub fn all_conversations(&self) -> Result<Vec<Conversation>, microrm::Error> {
|
||||
self.db.conversations
|
||||
.get()
|
||||
.map(|v| v
|
||||
.into_iter()
|
||||
.map(|c| c.wrapped())
|
||||
.collect()
|
||||
)
|
||||
}
|
||||
let result = conversations
|
||||
.load::<DbConversation>(&mut self.db)?
|
||||
.into_iter()
|
||||
.map(|c| c.into())
|
||||
.collect();
|
||||
|
||||
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<_>>();
|
||||
// TODO: Need to resolve participants here also somehow...
|
||||
|
||||
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)
|
||||
.get()
|
||||
.map(|v| v
|
||||
.into_iter()
|
||||
.last()
|
||||
)
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user