Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
}
Loading