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)

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");

pub fn insert_data(conn: &mut PgConnection, content: &str) {
    let new_post = NewPost { content };
        .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.content);

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

pub struct Post {
    pub id: i32,
    pub content: String,

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

# TODO: Add text about this in Cargo.toml

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