Private
Public Access
1
0

kordophone-db: switch to diesel for more features

This commit is contained in:
2024-12-14 19:03:27 -08:00
parent 86601b027a
commit f79cbbbc85
12 changed files with 432 additions and 249 deletions

241
Cargo.lock generated
View File

@@ -92,9 +92,9 @@ dependencies = [
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.93" version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7"
[[package]] [[package]]
name = "arrayvec" name = "arrayvec"
@@ -110,7 +110,7 @@ checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
] ]
[[package]] [[package]]
@@ -221,7 +221,7 @@ dependencies = [
"heck", "heck",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
] ]
[[package]] [[package]]
@@ -236,12 +236,6 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "convert_case"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb4a24b1aaf0fd0ce8b45161144d6f42cd91677fd5940fd431183eb023b3a2b8"
[[package]] [[package]]
name = "core-foundation" name = "core-foundation"
version = "0.9.4" version = "0.9.4"
@@ -265,7 +259,42 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edb49164822f3ee45b17acd4a208cfc1251410cf0cad9a833234c9890774dd9f" checksum = "edb49164822f3ee45b17acd4a208cfc1251410cf0cad9a833234c9890774dd9f"
dependencies = [ dependencies = [
"quote", "quote",
"syn 2.0.90", "syn",
]
[[package]]
name = "darling"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"
dependencies = [
"darling_core",
"quote",
"syn",
] ]
[[package]] [[package]]
@@ -278,12 +307,71 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "diesel"
version = "2.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf1bedf64cdb9643204a36dd15b19a6ce8e7aa7f7b105868e9f1fad5ffa7d12"
dependencies = [
"chrono",
"diesel_derives",
"libsqlite3-sys",
"time",
]
[[package]]
name = "diesel_derives"
version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7f2c3de51e2ba6bf2a648285696137aaf0f5f487bcbea93972fe8a364e131a4"
dependencies = [
"diesel_table_macro_syntax",
"dsl_auto_type",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "diesel_migrations"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a73ce704bad4231f001bff3314d91dce4aba0770cee8b233991859abc15c1f6"
dependencies = [
"diesel",
"migrations_internals",
"migrations_macros",
]
[[package]]
name = "diesel_table_macro_syntax"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "209c735641a413bc68c4923a9d6ad4bcb3ca306b794edaa7eb0b3228a99ffb25"
dependencies = [
"syn",
]
[[package]] [[package]]
name = "dotenv" name = "dotenv"
version = "0.15.0" version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
[[package]]
name = "dsl_auto_type"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5d9abe6314103864cc2d8901b7ae224e0ab1a103a0a416661b4097b0779b607"
dependencies = [
"darling",
"either",
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "either" name = "either"
version = "1.13.0" version = "1.13.0"
@@ -433,9 +521,9 @@ dependencies = [
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.14.3" version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
[[package]] [[package]]
name = "heck" name = "heck"
@@ -550,10 +638,16 @@ dependencies = [
] ]
[[package]] [[package]]
name = "indexmap" name = "ident_case"
version = "2.2.6" version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indexmap"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown", "hashbrown",
@@ -565,15 +659,6 @@ version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "itertools"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
dependencies = [
"either",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.11" version = "1.0.11"
@@ -613,8 +698,10 @@ dependencies = [
name = "kordophone-db" name = "kordophone-db"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow",
"chrono", "chrono",
"microrm", "diesel",
"diesel_migrations",
"serde", "serde",
"time", "time",
"uuid", "uuid",
@@ -647,9 +734,9 @@ checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]] [[package]]
name = "libsqlite3-sys" name = "libsqlite3-sys"
version = "0.28.0" version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f" checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
dependencies = [ dependencies = [
"pkg-config", "pkg-config",
"vcpkg", "vcpkg",
@@ -684,30 +771,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]] [[package]]
name = "microrm" name = "migrations_internals"
version = "0.4.4" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7119c145e9ee33d8a79a2c7e15c4f429d681079cea976692a55c78aaae34f5ae" checksum = "fd01039851e82f8799046eabbb354056283fb265c8ec0996af940f4e85a380ff"
dependencies = [ dependencies = [
"itertools",
"libsqlite3-sys",
"log",
"microrm-macros",
"serde", "serde",
"serde_json", "toml",
"time",
] ]
[[package]] [[package]]
name = "microrm-macros" name = "migrations_macros"
version = "0.4.1" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c3e29bc1b3c1dc742de1b3a23f11e472a2adc936a967dc5d769c26a809326b8" checksum = "ffb161cc72176cb37aa47f1fc520d3ef02263d67d661f44f05d05a079e1237fd"
dependencies = [ dependencies = [
"convert_case", "migrations_internals",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 1.0.109",
] ]
[[package]] [[package]]
@@ -802,7 +883,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
] ]
[[package]] [[package]]
@@ -1054,7 +1135,7 @@ checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
] ]
[[package]] [[package]]
@@ -1077,6 +1158,15 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_spanned"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "signal-hook-registry" name = "signal-hook-registry"
version = "1.4.1" version = "1.4.1"
@@ -1117,17 +1207,6 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.90" version = "2.0.90"
@@ -1167,6 +1246,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21" checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21"
dependencies = [ dependencies = [
"deranged", "deranged",
"itoa",
"num-conv", "num-conv",
"powerfmt", "powerfmt",
"serde", "serde",
@@ -1216,7 +1296,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
] ]
[[package]] [[package]]
@@ -1243,6 +1323,40 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "toml"
version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e"
dependencies = [
"serde",
"serde_spanned",
"toml_datetime",
"toml_edit",
]
[[package]]
name = "toml_datetime"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41"
dependencies = [
"serde",
]
[[package]]
name = "toml_edit"
version = "0.22.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5"
dependencies = [
"indexmap",
"serde",
"serde_spanned",
"toml_datetime",
"winnow",
]
[[package]] [[package]]
name = "tower-service" name = "tower-service"
version = "0.3.2" version = "0.3.2"
@@ -1317,7 +1431,7 @@ checksum = "6b91f57fe13a38d0ce9e28a03463d8d3c2468ed03d75375110ec71d93b449a08"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
] ]
[[package]] [[package]]
@@ -1363,7 +1477,7 @@ dependencies = [
"once_cell", "once_cell",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@@ -1385,7 +1499,7 @@ checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.90", "syn",
"wasm-bindgen-backend", "wasm-bindgen-backend",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@@ -1536,3 +1650,12 @@ name = "windows_x86_64_msvc"
version = "0.52.4" version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8"
[[package]]
name = "winnow"
version = "0.6.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b"
dependencies = [
"memchr",
]

View File

@@ -4,8 +4,10 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
anyhow = "1.0.94"
chrono = "0.4.38" chrono = "0.4.38"
microrm = "0.4.4" diesel = { version = "2.2.6", features = ["chrono", "sqlite", "time"] }
diesel_migrations = { version = "2.2.0", features = ["sqlite"] }
serde = { version = "1.0.215", features = ["derive"] } serde = { version = "1.0.215", features = ["derive"] }
time = "0.3.37" time = "0.3.37"
uuid = { version = "1.11.0", features = ["v4"] } uuid = { version = "1.11.0", features = ["v4"] }

View File

@@ -0,0 +1,9 @@
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/schema.rs"
custom_type_derives = ["diesel::query_builder::QueryId"]
[migrations_directory]
dir = "migrations"

View File

View File

@@ -0,0 +1,4 @@
-- This file should undo anything in `up.sql`
DROP TABLE IF EXISTS `participants`;
DROP TABLE IF EXISTS `conversation_participants`;
DROP TABLE IF EXISTS `conversations`;

View File

@@ -0,0 +1,20 @@
-- Your SQL goes here
CREATE TABLE `participants`(
`id` INTEGER NOT NULL PRIMARY KEY,
`display_name` TEXT NOT NULL
);
CREATE TABLE `conversation_participants`(
`conversation_id` TEXT NOT NULL,
`participant_id` INTEGER NOT NULL,
PRIMARY KEY(`conversation_id`, `participant_id`)
);
CREATE TABLE `conversations`(
`id` TEXT NOT NULL PRIMARY KEY,
`unread_count` BIGINT NOT NULL,
`display_name` TEXT,
`last_message_preview` TEXT,
`date` TIMESTAMP NOT NULL
);

View File

@@ -1,113 +1,100 @@
use std::error::Error; use std::error::Error;
use microrm::prelude::*; use anyhow::Result;
use microrm::Stored; use diesel::prelude::*;
use diesel::query_dsl::BelongingToDsl;
use crate::models::participant::ParticipantID; use crate::{models::{
use crate::models::{
participant::Participant,
conversation::{ 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 { pub struct ChatDatabase {
db: DB, db: SqliteConnection,
}
#[derive(Database)]
struct DB {
conversations: microrm::IDMap<Conversation>,
participants: microrm::IDMap<Participant>,
} }
impl ChatDatabase { impl ChatDatabase {
pub fn new_in_memory() -> Result<Self, Box<dyn Error + Send + Sync>> { pub fn new_in_memory() -> Result<Self> {
let db = DB::open_path(":memory:")?; let mut db = SqliteConnection::establish(":memory:")?;
db.run_pending_migrations(MIGRATIONS)
.map_err(|e| anyhow::anyhow!("Error running migrations: {}", e))?;
return Ok(Self { return Ok(Self {
db: db, db: db,
}) })
} }
pub fn insert_conversation(&self, conversation: PendingConversation) -> Result<ConversationID, microrm::Error> { pub fn insert_conversation(&mut self, conversation: Conversation) -> Result<()> {
// First see if conversation guid already exists, update it if so use crate::schema::conversations::dsl::*;
let guid = conversation.guid(); use crate::schema::participants::dsl::*;
let mut existing = self.stored_conversation_by_guid(guid)?; use crate::schema::conversation_participants::dsl::*;
if let Some(existing) = existing.as_mut() { let (db_conversation, db_participants) = conversation.into();
conversation.update(existing);
existing.sync();
return Ok(existing.id());
} else {
// Otherwise, insert.
let inserted = self.db.conversations.insert_and_return(conversation.get_conversation())?;
// Insert participants diesel::replace_into(conversations)
let participants = conversation.get_participants(); .values(&db_conversation)
let inserted_participants = participants.iter() .execute(&mut self.db)?;
.map(|p| self.db.participants.insert(p.clone()).unwrap())
.collect::<Vec<_>>();
inserted.connect_participants(inserted_participants);
return Ok(inserted.id()); diesel::replace_into(participants)
} .values(&db_participants)
} .execute(&mut self.db)?;
pub fn get_conversation_by_id(&self, id: ConversationID) -> Result<Option<Conversation>, microrm::Error> { // Sqlite backend doesn't support batch insert, so we have to do this manually
self.db.conversations for participant in db_participants {
.by_id(id) let pid = participants
.map(|stored_conversation| stored_conversation .select(schema::participants::id)
.map(|stored| stored.wrapped()) .filter(schema::participants::display_name.eq(&participant.display_name))
) .first::<i32>(&mut self.db)?;
}
pub fn get_conversation_by_guid(&self, guid: &str) -> Result<Option<Conversation>, microrm::Error> { diesel::replace_into(conversation_participants)
self.db.conversations .values((
.with(Conversation::Guid, guid) conversation_id.eq(&db_conversation.id),
.get() participant_id.eq(pid),
.and_then(|v| Ok(v
.into_iter()
.map(|c| c.wrapped())
.last()
)) ))
.execute(&mut self.db)?;
} }
pub fn all_conversations(&self) -> Result<Vec<Conversation>, microrm::Error> { Ok(())
self.db.conversations
.get()
.map(|v| v
.into_iter()
.map(|c| c.wrapped())
.collect()
)
} }
fn upsert_participants(&self, participants: Vec<Participant>) -> Vec<ParticipantID> { pub fn get_conversation_by_guid(&mut self, match_guid: &str) -> Result<Option<Conversation>> {
// Filter existing participants and add to result use crate::schema::conversations::dsl::*;
let existing_participants = participants.iter() use crate::schema::participants::dsl::*;
.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() let result = conversations
.map(|p| self.db.participants.insert(p.clone()).unwrap()) .find(match_guid)
.collect() .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));
} }
fn stored_conversation_by_guid(&self, guid: &str) -> Result<Option<Stored<Conversation>>, microrm::Error> { Ok(None)
self.db.conversations }
.with(Conversation::Guid, guid)
.get() pub fn all_conversations(&mut self) -> Result<Vec<Conversation>> {
.map(|v| v use crate::schema::conversations::dsl::*;
let result = conversations
.load::<DbConversation>(&mut self.db)?
.into_iter() .into_iter()
.last() .map(|c| c.into())
) .collect();
// TODO: Need to resolve participants here also somehow...
Ok(result)
} }
} }

View File

@@ -1,5 +1,6 @@
pub mod models; pub mod models;
pub mod chat_database; pub mod chat_database;
pub mod schema;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@@ -18,18 +19,19 @@ mod tests {
#[test] #[test]
fn test_add_conversation() { fn test_add_conversation() {
let db = ChatDatabase::new_in_memory().unwrap(); let mut db = ChatDatabase::new_in_memory().unwrap();
let guid = "test";
let test_conversation = Conversation::builder() let test_conversation = Conversation::builder()
.guid("test") .guid(guid)
.unread_count(2) .unread_count(2)
.display_name("Test Conversation") .display_name("Test Conversation")
.build(); .build();
let id = db.insert_conversation(test_conversation.clone()).unwrap(); db.insert_conversation(test_conversation.clone()).unwrap();
// Try to fetch with id now // Try to fetch with id now
let conversation = db.get_conversation_by_id(id).unwrap().unwrap(); let conversation = db.get_conversation_by_guid(guid).unwrap().unwrap();
assert_eq!(conversation.guid, "test"); assert_eq!(conversation.guid, "test");
// Modify the conversation and update it // Modify the conversation and update it
@@ -44,38 +46,40 @@ mod tests {
assert_eq!(all_conversations.len(), 1); assert_eq!(all_conversations.len(), 1);
// And make sure the display name was updated // And make sure the display name was updated
let conversation = db.get_conversation_by_id(id).unwrap().unwrap(); let conversation = db.get_conversation_by_guid(guid).unwrap().unwrap();
assert_eq!(conversation.display_name.unwrap(), "Modified Conversation"); assert_eq!(conversation.display_name.unwrap(), "Modified Conversation");
} }
#[test] #[test]
fn test_conversation_participants() { fn test_conversation_participants() {
let db = ChatDatabase::new_in_memory().unwrap(); let mut db = ChatDatabase::new_in_memory().unwrap();
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() let conversation = ConversationBuilder::new()
.guid(&guid)
.display_name("Test") .display_name("Test")
.participant_display_names(participants.clone()) .participants(participants.clone())
.build(); .build();
let id = db.insert_conversation(conversation).unwrap(); db.insert_conversation(conversation).unwrap();
let read_conversation = db.get_conversation_by_id(id).unwrap().unwrap(); let read_conversation = db.get_conversation_by_guid(&guid).unwrap().unwrap();
let read_participants: Vec<Participant> = read_conversation.get_participant_display_names(); let read_participants = read_conversation.participants;
assert_eq!(participants, read_participants); assert_eq!(participants, read_participants);
// Try making another conversation with the same participants // Try making another conversation with the same participants
let conversation = ConversationBuilder::new() let conversation = ConversationBuilder::new()
.display_name("A Different Test") .display_name("A Different Test")
.participant_display_names(participants.clone()) .participants(participants.clone())
.build(); .build();
let id = db.insert_conversation(conversation).unwrap(); db.insert_conversation(conversation).unwrap();
let read_conversation = db.get_conversation_by_id(id).unwrap().unwrap(); let read_conversation = db.get_conversation_by_guid(&guid).unwrap().unwrap();
let read_participants: Vec<Participant> = read_conversation.get_participant_display_names(); let read_participants: Vec<Participant> = read_conversation.participants;
assert_eq!(participants, read_participants); assert_eq!(participants, read_participants);
} }

View File

@@ -1,26 +1,58 @@
use microrm::prelude::*; use diesel::prelude::*;
use microrm::Stored; use chrono::NaiveDateTime;
use time::OffsetDateTime;
use uuid::Uuid; use uuid::Uuid;
use crate::models::{ use crate::models::{
date::Date,
participant::Participant, participant::Participant,
}; };
use super::participant::ParticipantID; #[derive(Queryable, Selectable, Insertable, AsChangeset, Clone, Identifiable)]
#[diesel(table_name = crate::schema::conversations)]
#[derive(Entity, Clone)] #[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct Conversation { pub struct DbConversation {
#[unique] pub id: String,
pub guid: String,
pub unread_count: i64, pub unread_count: i64,
pub display_name: Option<String>, pub display_name: Option<String>,
pub last_message_preview: Option<String>, pub last_message_preview: Option<String>,
pub date: OffsetDateTime, pub date: NaiveDateTime,
}
participant_display_names: microrm::RelationMap<Participant>, impl From<Conversation> for DbConversation {
fn from(conversation: Conversation) -> Self {
Self {
id: conversation.guid,
unread_count: conversation.unread_count as i64,
display_name: conversation.display_name,
last_message_preview: conversation.last_message_preview,
date: conversation.date,
}
}
}
impl From<Conversation> for (DbConversation, Vec<Participant>) {
fn from(conversation: Conversation) -> Self {
(
DbConversation {
id: conversation.guid,
unread_count: conversation.unread_count as i64,
display_name: conversation.display_name,
last_message_preview: conversation.last_message_preview,
date: conversation.date,
},
conversation.participants
)
}
}
#[derive(Clone, Debug)]
pub struct Conversation {
pub guid: String,
pub unread_count: u16,
pub display_name: Option<String>,
pub last_message_preview: Option<String>,
pub date: NaiveDateTime,
pub participants: Vec<Participant>,
} }
impl Conversation { impl Conversation {
@@ -31,76 +63,35 @@ impl Conversation {
pub fn into_builder(&self) -> ConversationBuilder { pub fn into_builder(&self) -> ConversationBuilder {
ConversationBuilder { ConversationBuilder {
guid: Some(self.guid.clone()), guid: Some(self.guid.clone()),
date: Date::new(self.date), date: self.date,
participant_display_names: None, participants: None,
unread_count: Some(self.unread_count), unread_count: Some(self.unread_count),
last_message_preview: self.last_message_preview.clone(), last_message_preview: self.last_message_preview.clone(),
display_name: self.display_name.clone(), 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)] impl From<DbConversation> for Conversation {
pub struct PendingConversation { fn from(db_conversation: DbConversation) -> Self {
conversation: Conversation, Self {
participants: Vec<Participant>, guid: db_conversation.id,
} unread_count: db_conversation.unread_count as u16,
display_name: db_conversation.display_name,
impl PendingConversation { last_message_preview: db_conversation.last_message_preview,
pub fn guid(&self) -> &String { date: db_conversation.date,
&self.conversation.guid participants: vec![],
} }
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)] #[derive(Default)]
pub struct ConversationBuilder { pub struct ConversationBuilder {
guid: Option<String>, guid: Option<String>,
date: Date, date: NaiveDateTime,
unread_count: Option<i64>, unread_count: Option<u16>,
last_message_preview: Option<String>, last_message_preview: Option<String>,
participant_display_names: Option<Vec<Participant>>, participants: Option<Vec<Participant>>,
display_name: Option<String>, display_name: Option<String>,
} }
@@ -114,12 +105,12 @@ impl ConversationBuilder {
self self
} }
pub fn date(mut self, date: Date) -> Self { pub fn date(mut self, date: NaiveDateTime) -> Self {
self.date = date; self.date = date;
self self
} }
pub fn unread_count(mut self, unread_count: i64) -> Self { pub fn unread_count(mut self, unread_count: u16) -> Self {
self.unread_count = Some(unread_count); self.unread_count = Some(unread_count);
self self
} }
@@ -129,8 +120,8 @@ impl ConversationBuilder {
self self
} }
pub fn participant_display_names(mut self, participant_display_names: Vec<Participant>) -> Self { pub fn participants(mut self, participants: Vec<Participant>) -> Self {
self.participant_display_names = Some(participant_display_names); self.participants = Some(participants);
self self
} }
@@ -139,21 +130,14 @@ impl ConversationBuilder {
self self
} }
fn build_conversation(&self) -> Conversation { pub fn build(&self) -> Conversation {
Conversation { Conversation {
guid: self.guid.clone().unwrap_or(Uuid::new_v4().to_string()), guid: self.guid.clone().unwrap_or(Uuid::new_v4().to_string()),
unread_count: self.unread_count.unwrap_or(0), unread_count: self.unread_count.unwrap_or(0),
last_message_preview: self.last_message_preview.clone(), last_message_preview: self.last_message_preview.clone(),
display_name: self.display_name.clone(), display_name: self.display_name.clone(),
date: self.date.dt, date: self.date,
participant_display_names: Default::default(), participants: self.participants.clone().unwrap_or_default(),
}
}
pub fn build(self) -> PendingConversation {
PendingConversation {
conversation: self.build_conversation(),
participants: self.participant_display_names.unwrap_or_default(),
} }
} }
} }

View File

@@ -1,4 +1,3 @@
use chrono::{DateTime, Local, Utc};
use time::OffsetDateTime; use time::OffsetDateTime;
pub struct Date { pub struct Date {

View File

@@ -1,11 +1,35 @@
use microrm::prelude::*; use diesel::prelude::*;
use crate::{models::conversation::DbConversation, schema::conversation_participants};
#[derive(Entity, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Insertable)]
#[diesel(table_name = crate::schema::participants)]
pub struct Participant { pub struct Participant {
#[unique] pub display_name: String,
}
impl From<DbParticipant> for Participant {
fn from(participant: DbParticipant) -> Self {
Participant { display_name: participant.display_name }
}
}
#[derive(Queryable, Selectable, Insertable, AsChangeset, Clone, PartialEq, Debug, Identifiable)]
#[diesel(table_name = crate::schema::participants)]
pub struct DbParticipant {
pub id: i32,
pub display_name: String pub display_name: String
} }
#[derive(Identifiable, Selectable, Queryable, Associations, Debug)]
#[diesel(belongs_to(DbConversation, foreign_key = conversation_id))]
#[diesel(belongs_to(DbParticipant, foreign_key = participant_id))]
#[diesel(table_name = conversation_participants)]
#[diesel(primary_key(conversation_id, participant_id))]
pub struct ConversationParticipant {
pub conversation_id: String,
pub participant_id: i32,
}
impl Into<Participant> for String { impl Into<Participant> for String {
fn into(self) -> Participant { fn into(self) -> Participant {
Participant { display_name: self } Participant { display_name: self }

View File

@@ -0,0 +1,27 @@
diesel::table! {
conversations (id) {
id -> Text,
unread_count -> BigInt,
display_name -> Nullable<Text>,
last_message_preview -> Nullable<Text>,
date -> Timestamp,
}
}
diesel::table! {
participants (id) {
id -> Integer,
display_name -> Text,
}
}
diesel::table! {
conversation_participants (conversation_id, participant_id) {
conversation_id -> Text,
participant_id -> Integer,
}
}
diesel::joinable!(conversation_participants -> conversations (conversation_id));
diesel::joinable!(conversation_participants -> participants (participant_id));
diesel::allow_tables_to_appear_in_same_query!(conversations, participants, conversation_participants);