diff --git a/migrations/2018-05-10-154336_create_likes/down.sql b/migrations/2018-05-10-154336_create_likes/down.sql new file mode 100644 index 0000000..2232ad5 --- /dev/null +++ b/migrations/2018-05-10-154336_create_likes/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +DROP TABLE likes; diff --git a/migrations/2018-05-10-154336_create_likes/up.sql b/migrations/2018-05-10-154336_create_likes/up.sql new file mode 100644 index 0000000..3c5f119 --- /dev/null +++ b/migrations/2018-05-10-154336_create_likes/up.sql @@ -0,0 +1,7 @@ +-- Your SQL goes here +CREATE TABLE likes ( + id SERIAL PRIMARY KEY, + user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL, + post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE NOT NULL, + creation_date TIMESTAMP NOT NULL DEFAULT now() +) diff --git a/src/models/likes.rs b/src/models/likes.rs new file mode 100644 index 0000000..1c2bc45 --- /dev/null +++ b/src/models/likes.rs @@ -0,0 +1,29 @@ +use chrono; +use diesel::{PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods}; + +use schema::likes; + +#[derive(Queryable)] +pub struct Like { + id: i32, + user_id: i32, + post_id: i32, + creation_date: chrono::NaiveDateTime +} + +#[derive(Insertable)] +#[table_name = "likes"] +pub struct NewLike { + user_id: i32, + post_id: i32 +} + +impl Like { + pub fn get(conn: &PgConnection, id: i32) -> Option { + likes::table.filter(likes::id.eq(id)) + .limit(1) + .load::(conn) + .expect("Error loading like by ID") + .into_iter().nth(0) + } +} diff --git a/src/models/mod.rs b/src/models/mod.rs index 00df02a..eb093a1 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -3,6 +3,7 @@ pub mod blogs; pub mod comments; pub mod follows; pub mod instance; +pub mod likes; pub mod post_authors; pub mod posts; pub mod users; diff --git a/src/schema.rs b/src/schema.rs index 5b30da1..ad07691 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -56,6 +56,15 @@ table! { } } +table! { + likes (id) { + id -> Int4, + user_id -> Int4, + post_id -> Int4, + creation_date -> Timestamp, + } +} + table! { post_authors (id) { id -> Int4, @@ -102,6 +111,8 @@ joinable!(blog_authors -> users (author_id)); joinable!(blogs -> instances (instance_id)); joinable!(comments -> posts (post_id)); joinable!(comments -> users (author_id)); +joinable!(likes -> posts (post_id)); +joinable!(likes -> users (user_id)); joinable!(post_authors -> posts (post_id)); joinable!(post_authors -> users (author_id)); joinable!(posts -> blogs (blog_id)); @@ -113,6 +124,7 @@ allow_tables_to_appear_in_same_query!( comments, follows, instances, + likes, post_authors, posts, users,