-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathlib.rs
More file actions
36 lines (28 loc) · 925 Bytes
/
Copy pathlib.rs
File metadata and controls
36 lines (28 loc) · 925 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
pub mod models;
pub mod schema;
use diesel::prelude::*;
use dotenvy::dotenv;
use std::env;
use self::models::{NewPost, Post};
pub fn establish_connection() -> MysqlConnection {
dotenv().ok();
let database_url = env::var("MYSQL_DATABASE_URL")
.or_else(|_| env::var("DATABASE_URL"))
.expect("DATABASE_URL must be set");
MysqlConnection::establish(&database_url)
.unwrap_or_else(|e| panic!("Failed to connect, error: {e}"))
}
pub fn create_post(conn: &mut MysqlConnection, title: &str, body: &str) -> Post {
use crate::schema::posts;
let new_post = NewPost { title, body };
conn.transaction(|conn| {
diesel::insert_into(posts::table)
.values(&new_post)
.execute(conn)?;
posts::table
.order(posts::id.desc())
.select(Post::as_select())
.first(conn)
})
.expect("Error while saving post")
}