Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Rust Diesel Single File MySQL Example

Code

use self::schema::widgets;
use self::schema::widgets::dsl::*;
use diesel::prelude::*;
use dotenvy::dotenv;
use std::env;

mod schema;

fn main() {
    println!("Hello world");
    let conn = &mut establish_connection();

    let new_widget = NewWidget {
        content: Some("quick brown fox"),
    };

    diesel::insert_into(widgets::table)
        .values(&new_widget)
        .execute(conn)
        .expect("Error inserting new post");

    let results = widgets.load::<Widget>(conn).expect("Error loading posts");
    for widget in results {
        println!("{} {}", widget.id, widget.content.unwrap());
    }
}

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

#[derive(Queryable)]
pub struct Widget {
    pub id: String,
    pub content: Option<String>,
}

#[derive(Insertable)]
#[diesel(table_name = widgets)]
pub struct NewWidget<'a> {
    pub content: Option<&'a str>,
}