about summary refs log tree commit diff
path: root/src/db.rs
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@gmail.com>2018-04-14T14·33+0200
committerVincent Ambo <tazjin@gmail.com>2018-04-14T14·33+0200
commit8c30ef92f652f411679408344031706745346f02 (patch)
treef15ab0ebead519c105c03c128ae7f04c4194074b /src/db.rs
parenta90d1cc1a41e405ea397b06a3bc1907291c98b65 (diff)
refactor(db): Store thread body in the posts table
This is a simplification over the previous approach. The OP of a
thread is just a normal post like any other in this model, which
allows some code simplifications (and future query convenience).
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs31
1 files changed, 26 insertions, 5 deletions
diff --git a/src/db.rs b/src/db.rs
index 0ff716f708f1..35d7a6b3545a 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -5,7 +5,7 @@ use diesel;
 use diesel::prelude::*;
 use diesel::r2d2::{Pool, ConnectionManager};
 use models::*;
-use errors::Result;
+use errors::{ConverseError, Result};
 
 /// The DB actor itself. Several of these will be run in parallel by
 /// `SyncArbiter`.
@@ -62,7 +62,10 @@ impl Handler<GetThread> for DbExecutor {
 }
 
 /// Message used to create a new thread
-pub struct CreateThread(pub NewThread);
+pub struct CreateThread {
+    pub new_thread: NewThread,
+    pub body: String,
+}
 
 impl Message for CreateThread {
     type Result = Result<Thread>;
@@ -73,12 +76,30 @@ impl Handler<CreateThread> for DbExecutor {
 
     fn handle(&mut self, msg: CreateThread, _: &mut Self::Context) -> Self::Result {
         use schema::threads;
+        use schema::posts;
 
         let conn = self.0.get()?;
 
-        Ok(diesel::insert_into(threads::table)
-           .values(&msg.0)
-           .get_result(&conn)?)
+        conn.transaction::<Thread, ConverseError, _>(|| {
+            // First insert the thread structure itself
+            let thread: Thread = diesel::insert_into(threads::table)
+                .values(&msg.new_thread)
+                .get_result(&conn)?;
+
+            // ... then create the first post in the thread.
+            let new_post = NewPost {
+                thread_id: thread.id,
+                body: msg.body,
+                author_name: msg.new_thread.author_name.clone(),
+                author_email: msg.new_thread.author_email.clone(),
+            };
+
+            diesel::insert_into(posts::table)
+                .values(&new_post)
+                .execute(&conn)?;
+
+            Ok(thread)
+        })
     }
 }