crablog/site/src/db.rs

54 lines
1.4 KiB
Rust
Raw Normal View History

2020-10-22 00:17:52 +02:00
mod models;
mod schema;
2020-10-22 23:51:20 +02:00
use crate::config;
2020-10-22 00:17:52 +02:00
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use models::*;
fn establish_connection() -> SqliteConnection {
2020-10-22 23:51:20 +02:00
let root_path = config::get_from_env("ROOT_PATH", true);
let db_path = root_path + "/db.sqlite3";
2020-10-22 00:17:52 +02:00
SqliteConnection::establish(&db_path)
2020-10-22 01:38:43 +02:00
.unwrap_or_else(|_| panic!("Error, connection to {} failed.", &db_path))
2020-10-22 00:17:52 +02:00
}
pub fn get_posts() -> std::vec::Vec<Post> {
use crate::db::schema::posts::dsl::*;
let connection = establish_connection();
posts
.filter(published.eq(true))
2020-10-22 01:38:43 +02:00
.order(id.desc())
.limit(5)
2020-10-22 00:17:52 +02:00
.load::<Post>(&connection)
2020-10-22 01:38:43 +02:00
.expect("Error, couldn't load posts.")
2020-10-22 00:17:52 +02:00
}
2020-10-23 01:03:59 +02:00
pub fn get_post_by_id(_id: i32) -> Post {
2020-10-22 00:17:52 +02:00
use crate::db::schema::posts::dsl::*;
let connection = establish_connection();
posts
2020-10-23 01:03:59 +02:00
.find(_id)
2020-10-22 00:17:52 +02:00
.get_result(&connection)
2020-10-22 01:38:43 +02:00
.expect("Error, couldn't find post")
2020-10-22 00:17:52 +02:00
}
pub fn add_post(title: &str, body: &str) {
use chrono::prelude::*;
use schema::posts;
let connection = establish_connection();
let new_post = NewPost {
title,
body,
published: &true,
publish_date: &Utc::now().naive_utc(),
};
diesel::insert_into(posts::table)
.values(&new_post)
.execute(&connection)
2020-10-22 01:38:43 +02:00
.unwrap_or_else(|_| panic!("Error, couldn't insert new Post."));
2020-10-22 00:17:52 +02:00
}