From 78f3062f6db551d4641d9062026a99d713495776 Mon Sep 17 00:00:00 2001 From: Bat Date: Tue, 1 May 2018 14:06:31 +0100 Subject: [PATCH] Add a follow model --- .../2018-05-01-124607_create_follow/down.sql | 2 ++ .../2018-05-01-124607_create_follow/up.sql | 6 ++++ src/models/follows.rs | 34 +++++++++++++++++++ src/models/mod.rs | 1 + src/schema.rs | 9 +++++ 5 files changed, 52 insertions(+) create mode 100644 migrations/2018-05-01-124607_create_follow/down.sql create mode 100644 migrations/2018-05-01-124607_create_follow/up.sql create mode 100644 src/models/follows.rs diff --git a/migrations/2018-05-01-124607_create_follow/down.sql b/migrations/2018-05-01-124607_create_follow/down.sql new file mode 100644 index 00000000..eee3b972 --- /dev/null +++ b/migrations/2018-05-01-124607_create_follow/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +DROP TABLE follows; diff --git a/migrations/2018-05-01-124607_create_follow/up.sql b/migrations/2018-05-01-124607_create_follow/up.sql new file mode 100644 index 00000000..d5298f25 --- /dev/null +++ b/migrations/2018-05-01-124607_create_follow/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +CREATE TABLE follows ( + id SERIAL PRIMARY KEY, + follower_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL, + following_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL +) diff --git a/src/models/follows.rs b/src/models/follows.rs new file mode 100644 index 00000000..23aae984 --- /dev/null +++ b/src/models/follows.rs @@ -0,0 +1,34 @@ +use diesel::{self, PgConnection, ExpressionMethods, QueryDsl, RunQueryDsl}; + +use schema::follows; + +#[derive(Queryable, Identifiable)] +pub struct Follow { + pub id: i32, + pub follower_id: i32, + pub following_id: i32 +} + +#[derive(Insertable)] +#[table_name = "follows"] +pub struct NewFollow { + pub follower_id: i32, + pub following_id: i32 +} + +impl Follow { + pub fn insert(conn: &PgConnection, new: NewFollow) -> Follow { + diesel::insert_into(follows::table) + .values(new) + .get_result(conn) + .expect("Unable to insert new follow") + } + + pub fn get(conn: &PgConnection, id: i32) -> Option { + follows::table.filter(follows::id.eq(id)) + .limit(1) + .load::(conn) + .expect("Unable to load follow by id") + .into_iter().nth(0) + } +} diff --git a/src/models/mod.rs b/src/models/mod.rs index 9ff6a8b6..265f3dc0 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -1,5 +1,6 @@ pub mod blog_authors; pub mod blogs; +pub mod follows; pub mod instance; pub mod post_authors; pub mod posts; diff --git a/src/schema.rs b/src/schema.rs index f61f6bc5..5b6b254d 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -20,6 +20,14 @@ table! { } } +table! { + follows (id) { + id -> Int4, + follower_id -> Int4, + following_id -> Int4, + } +} + table! { instances (id) { id -> Int4, @@ -80,6 +88,7 @@ joinable!(users -> instances (instance_id)); allow_tables_to_appear_in_same_query!( blog_authors, blogs, + follows, instances, post_authors, posts,