This repository has been archived by the owner. It is now read-only.
Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
56 lines (44 sloc) 1.37 KB
mod schema;
mod models;
#[macro_use]
extern crate diesel;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use std::env;
pub fn establish_connection() -> PgConnection {
dotenv().ok();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
PgConnection::establish(&database_url)
.expect(&format!("Error connecting to {}", database_url))
}
pub fn create_post<'a>(conn: &PgConnection, title: &String) -> models::Post {
use crate::schema::posts;
let new_post = models::NewPost {
title: *title,
body: models::Body{
text1: String::from("hey1"),
text2: String::from("hey2"),
},
};
diesel::insert_into(posts::table)
.values(&new_post)
.get_result(conn)
.expect("Error saving new post")
}
fn main() {
use crate::schema::posts::dsl::*;
let connection = establish_connection();
let results = posts.limit(5)
.load::<models::Post>(&connection)
.expect("Error loading posts");
create_post(&connection, &String::from("hey1"));
println!("Displaying {} posts", results.len());
for post in results {
println!("{}", post.title);
println!("----------");
println!("{:?}\n", post.body);
// println!("{:?}\n", serde_json::from_value::<models::Body>(post.body).unwrap());
}
}