This repository has been archived on 2022-07-24. You can view files and clone it, but cannot push or open issues or pull requests.
itconfig/examples/diesel/main.rs

52 lines
1.1 KiB
Rust
Raw Normal View History

2019-12-29 01:11:34 +03:00
#[macro_use]
extern crate diesel;
mod schema;
2020-07-02 20:54:17 +03:00
use diesel::prelude::*;
use dotenv::dotenv;
2019-12-29 01:11:34 +03:00
2022-07-21 20:10:31 +03:00
itconfig::config! {
2020-02-08 22:11:37 +03:00
DATABASE_URL,
2019-12-29 01:11:34 +03:00
}
fn main() {
2020-07-08 16:50:41 +03:00
dotenv().expect("dotenv setup to be successful");
2020-03-12 23:20:34 +03:00
config::init();
2019-12-29 01:11:34 +03:00
2022-07-21 20:10:31 +03:00
let connection = establish_connection();
2019-12-29 01:11:34 +03:00
let posts = get_posts(&connection);
println!("Displaying {} posts", posts.len());
for post in posts {
println!();
2019-12-29 01:11:34 +03:00
println!("{}", post.title);
println!("----------");
println!("{}", post.body);
}
}
fn get_posts(connection: &PgConnection) -> Vec<Post> {
use crate::schema::posts::dsl::*;
2020-07-02 20:54:17 +03:00
posts
.filter(published.eq(true))
2019-12-29 01:11:34 +03:00
.limit(5)
.get_results::<Post>(connection)
.expect("Error loading posts")
2020-07-02 20:54:17 +03:00
}
2022-07-21 20:10:31 +03:00
fn establish_connection() -> PgConnection {
let database_url = config::DATABASE_URL();
PgConnection::establish(database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}
#[derive(Queryable)]
struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}