From 1767eb2dafbab8b19cc4cf0a9a890539ce2948c1 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Sun, 1 Oct 2017 22:38:55 +0200 Subject: Add schema for posts, and display them on index page. --- migrations/2017-10-01-193613_create_posts/down.sql | 2 ++ migrations/2017-10-01-193613_create_posts/up.sql | 7 +++++++ src/lib.rs | 7 +++++-- src/main.rs | 21 +++++++++++++++++++-- src/models.rs | 7 +++++++ src/schema.rs | 1 + 6 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 migrations/2017-10-01-193613_create_posts/down.sql create mode 100644 migrations/2017-10-01-193613_create_posts/up.sql create mode 100644 src/models.rs create mode 100644 src/schema.rs diff --git a/migrations/2017-10-01-193613_create_posts/down.sql b/migrations/2017-10-01-193613_create_posts/down.sql new file mode 100644 index 0000000..e1d6323 --- /dev/null +++ b/migrations/2017-10-01-193613_create_posts/down.sql @@ -0,0 +1,2 @@ +-- Drop posts table +DROP TABLE posts diff --git a/migrations/2017-10-01-193613_create_posts/up.sql b/migrations/2017-10-01-193613_create_posts/up.sql new file mode 100644 index 0000000..c0c36e5 --- /dev/null +++ b/migrations/2017-10-01-193613_create_posts/up.sql @@ -0,0 +1,7 @@ +-- Create posts table +CREATE TABLE posts ( + id SERIAL PRIMARY KEY, + title VARCHAR NOT NULL, + body TEXT NOT NULL, + published BOOLEAN NOT NULL DEFAULT 'f' +) diff --git a/src/lib.rs b/src/lib.rs index 0c2d440..8f51d10 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,10 @@ #[macro_use] -extern crate diesel; -#[macro_use] extern crate diesel_codegen; +pub mod models; +pub mod schema; + +#[macro_use] +extern crate diesel; extern crate dotenv; extern crate r2d2_diesel; extern crate r2d2; diff --git a/src/main.rs b/src/main.rs index 711c343..622ac1c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,9 +4,26 @@ extern crate rocket; extern crate rocket_blog; +extern crate diesel; +use self::diesel::prelude::*; + #[get("/")] -fn index(conn: rocket_blog::DbConn) -> &'static str { - "Hallo, for faen!" +fn index(conn: rocket_blog::DbConn) -> String { + use rocket_blog::schema::posts::dsl::*; + let results = posts.filter(published.eq(false)) + .limit(5) + .load::(&*conn) + .expect("Error loading posts"); + + let mut output = String::from("Hallo, for faen!\n\n"); + + for post in results { + output += &format!("{}\n", post.title); + output += "================\n"; + output += &format!("{}\n", post.body); + } + + output } fn main() { diff --git a/src/models.rs b/src/models.rs new file mode 100644 index 0000000..110cabe --- /dev/null +++ b/src/models.rs @@ -0,0 +1,7 @@ +#[derive(Queryable)] +pub struct Post { + pub id: i32, + pub title: String, + pub body: String, + pub published: bool, +} diff --git a/src/schema.rs b/src/schema.rs new file mode 100644 index 0000000..236bbc9 --- /dev/null +++ b/src/schema.rs @@ -0,0 +1 @@ +infer_schema!("dotenv:DATABASE_URL"); -- cgit v1.2.3