Skip to content

Commit

Permalink
Adding NaiveDate to ParamaterValue
Browse files Browse the repository at this point in the history
There was no way of implementing Date for postgres databases. This adds support for handling dates so that postgres is happy. 

Signed-off-by: tyler-harpool <102192378+tyler-harpool@users.noreply.github.com>
  • Loading branch information
tyler-harpool authored Sep 23, 2024
1 parent 1f07acf commit d7e9ec7
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/pg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
//! | `f64` | floating64(float64) | DOUBLE PRECISION, FLOAT8 |
//! | `String` | str(string) | VARCHAR, CHAR(N), TEXT |
//! | `Vec<u8>` | binary(list\<u8\>) | BYTEA |
//! | `NaiveDate`| date | Date |
#[doc(inline)]
pub use super::wit::v2::postgres::{Connection, Error as PgError};
#[doc(inline)]
pub use super::wit::v2::rdbms_types::*;

use chrono::NaiveDate;
/// A pg error
#[derive(Debug, thiserror::Error)]
pub enum Error {
Expand Down Expand Up @@ -122,14 +124,23 @@ impl Decode for String {
}
}

impl Decode for NaiveDate {
fn decode(value: &DbValue) -> Result<Self, Error> {
match value {
DbValue::Date(date) => Ok(*date),
_ => Err(Error::Decode(format_decode_err("DATE", value))),
}
}
}

fn format_decode_err(types: &str, value: &DbValue) -> String {
format!("Expected {} from the DB but got {:?}", types, value)
}

#[cfg(test)]
mod tests {
use super::*;

use chrono::NaiveDate;
#[test]
fn boolean() {
assert!(bool::decode(&DbValue::Boolean(true)).unwrap());
Expand Down Expand Up @@ -193,4 +204,12 @@ mod tests {
.unwrap()
.is_none());
}

#[test]
fn date() {
let date = NaiveDate::from_ymd(2023, 9, 21);
assert_eq!(NaiveDate::decode(&DbValue::Date(date)).unwrap(), date);
assert!(NaiveDate::decode(&DbValue::Int32(0)).is_err());
assert!(Option::<NaiveDate>::decode(&DbValue::DbNull).unwrap().is_none());
}
}

0 comments on commit d7e9ec7

Please sign in to comment.