Rust Diesel Crate Basic Query Example

This is just a quick copy of working code that does a basic database insert and query on a Postgres database from the Diesel crate in Rust.

(All the other tutorails I've seen do a bunch of other unrelated stuff that's hard to parse though)

Code
use diesel::pg::PgConnection;
use diesel::prelude::*;
use diesel_test_4::schema::posts as posts_table;
use diesel_test_4::schema::posts::dsl::posts;
use dotenvy::dotenv;
use std::env;

fn main() {
    let conn = &mut establish_connection();
    insert_data(conn, "the quick brown fox");
    query_posts(conn);
}

pub fn insert_data(conn: &mut PgConnection, content: &str) {
    let new_post = NewPost { content };
    diesel::insert_into(posts_table::table)
        .values(&new_post)
        .execute(conn)
        .expect("Error saving new post");
}

pub fn query_posts(conn: &mut PgConnection) {
    let results = posts.load::<Post>(conn).expect("Error loading posts");
    for post in results {
        println!("{} - {}", post.id, post.content);
    }
}

pub fn establish_connection() -> PgConnection {
    dotenv().ok();
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    PgConnection::establish(&database_url)
        .unwrap_or_else(|_| panic!("Error connecting to database"))
}

#[derive(Queryable)]
pub struct Post {
    pub id: i32,
    pub content: String,
}

#[derive(Insertable)]
#[diesel(table_name = posts_table)]
pub struct NewPost<'a> {
    pub content: &'a str,
}
Notes
  • The migration needs to have been run to create the table and the _schema.rs__ file that's auto generated. TODO: document that

Code
# TODO: Add text about this in Cargo.toml

[dependencies]
diesel = { version = "2.0.0", features = ["postgres"] }
dotenvy = "0.15"