From 316036b0a89a428e850ea33e07f5fe2362f833c9 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Sun, 8 Apr 2018 18:27:15 +0200 Subject: [PATCH] refactor(db): Establish Post->Thread association This makes it possible to query posts by thread via Diesel. --- migrations/2018-04-08-161017_joinable_posts/down.sql | 1 + migrations/2018-04-08-161017_joinable_posts/up.sql | 1 + src/db.rs | 8 ++++++-- src/models.rs | 8 +++++--- src/schema.rs | 4 ++-- 5 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 migrations/2018-04-08-161017_joinable_posts/down.sql create mode 100644 migrations/2018-04-08-161017_joinable_posts/up.sql diff --git a/migrations/2018-04-08-161017_joinable_posts/down.sql b/migrations/2018-04-08-161017_joinable_posts/down.sql new file mode 100644 index 000000000..cc7874b41 --- /dev/null +++ b/migrations/2018-04-08-161017_joinable_posts/down.sql @@ -0,0 +1 @@ +ALTER TABLE posts RENAME COLUMN thread_id TO thread; diff --git a/migrations/2018-04-08-161017_joinable_posts/up.sql b/migrations/2018-04-08-161017_joinable_posts/up.sql new file mode 100644 index 000000000..9713de6cf --- /dev/null +++ b/migrations/2018-04-08-161017_joinable_posts/up.sql @@ -0,0 +1 @@ +ALTER TABLE posts RENAME COLUMN thread TO thread_id; diff --git a/src/db.rs b/src/db.rs index c3a05a323..1aa6ff73c 100644 --- a/src/db.rs +++ b/src/db.rs @@ -47,11 +47,15 @@ impl Handler for DbExecutor { fn handle(&mut self, msg: GetThread, _: &mut Self::Context) -> Self::Result { use schema::threads::dsl::*; + let conn = self.0.get().unwrap(); - let result: Thread = threads + let thread_result: Thread = threads .find(msg.0).first(&conn) .expect("Error loading thread"); - Ok((result, vec![])) + let post_list = Post::belonging_to(&thread_result) + .load::(&conn).expect("Error loading posts for thread"); + + Ok((thread_result, post_list)) } } diff --git a/src/models.rs b/src/models.rs index 74b386a19..42d8d1164 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,6 +1,7 @@ use chrono::prelude::{DateTime, Utc}; +use schema::{threads, posts}; -#[derive(Queryable, Serialize)] +#[derive(Identifiable, Queryable, Serialize)] pub struct Thread { pub id: i32, pub title: String, @@ -8,10 +9,11 @@ pub struct Thread { pub posted: DateTime, } -#[derive(Queryable, Serialize)] +#[derive(Identifiable, Queryable, Serialize, Associations)] +#[belongs_to(Thread)] pub struct Post { pub id: i32, - pub thread: i32, + pub thread_id: i32, pub body: String, pub posted: DateTime, } diff --git a/src/schema.rs b/src/schema.rs index a899f52ac..8b05eb546 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -1,7 +1,7 @@ table! { posts (id) { id -> Int4, - thread -> Int4, + thread_id -> Int4, body -> Text, posted -> Timestamptz, } @@ -16,7 +16,7 @@ table! { } } -joinable!(posts -> threads (thread)); +joinable!(posts -> threads (thread_id)); allow_tables_to_appear_in_same_query!( posts,