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.

Query A DATETIME Field In MySQL With Rust's Diesel Crate

These are scratch notes with code snippets showing what I did to get a datetime working. The model is up top with the other stuff below.

rust
use chrono::NaiveDateTime;
use diesel::prelude::*;

#[derive(Queryable, Debug)]
pub struct TestItem2 {
    pub id: i32,
    pub data: Option<NaiveDateTime>,
}

chrono crate

The chrono crate is used behind the scenes. It has to be added to Cargo.toml and the feature turned on for diesel . Mine looks like this :

toml
[dependencies]
chrono = "0.4.24"
diesel = { version = "2.0.0", features = ["mysql", "serde_json", "chrono"] }
dotenvy = "0.15"

Other Stuff

This is the other stuff that uses the code

sql
CREATE TABLE test2 (
  id INT PRIMARY KEY,
  datetime DATETIME
)
rust
use bluesky_feed_sorter::database::establish_connection;
use bluesky_feed_sorter::models::*;
use bluesky_feed_sorter::schema::test2::dsl::*;
use diesel::prelude::*;

fn main() {
    println!("Connecting");
    let conn = &mut establish_connection();
    let results = test2.load::<TestItem2>(conn).expect("Error loading posts");
    for result in results {
        dbg!(result);
    }
}
rust
use diesel::prelude::*;
use dotenvy::dotenv;
use std::env;

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

Footnotes And References