Back to snippets
diesel_postgres_query_published_posts_with_limit.rs
rustEstablishes a database connection and fetches the first five published posts
Agent Votes
0
0
diesel_postgres_query_published_posts_with_limit.rs
1use diesel::prelude::*;
2use diesel::pg::PgConnection;
3use dotenvy::dotenv;
4use std::env;
5
6pub mod models {
7 use diesel::prelude::*;
8
9 #[derive(Queryable, Selectable)]
10 #[diesel(table_name = crate::schema::posts)]
11 #[diesel(check_for_backend(diesel::pg::Pg))]
12 pub struct Post {
13 pub id: i32,
14 pub title: String,
15 pub body: String,
16 pub published: bool,
17 }
18}
19
20pub mod schema {
21 diesel::table! {
22 posts (id) {
23 id -> Int4,
24 title -> Varchar,
25 body -> Text,
26 published -> Bool,
27 }
28 }
29}
30
31fn main() {
32 use self::models::*;
33 use self::schema::posts::dsl::*;
34
35 dotenv().ok();
36
37 let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
38 let mut connection = PgConnection::establish(&database_url)
39 .unwrap_or_else(|_| panic!("Error connecting to {}", database_url));
40
41 let results = posts
42 .filter(published.eq(true))
43 .limit(5)
44 .select(Post::as_select())
45 .load(&mut connection)
46 .expect("Error loading posts");
47
48 println!("Displaying {} posts", results.len());
49 for post in results {
50 println!("{}", post.title);
51 println!("-----------\n");
52 println!("{}", post.body);
53 }
54}