Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Rust Diesel Single File MySQL Example

rust
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>,
}