Skip to content

Commit

Permalink
Merge pull request #1197 from allan2/time-overflow
Browse files Browse the repository at this point in the history
Fix time 0.3 infinity panics
  • Loading branch information
sfackler authored Feb 2, 2025
2 parents f1c5c4f + 9754f13 commit 924d0e5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
9 changes: 7 additions & 2 deletions postgres-types/src/time_03.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ fn base() -> PrimitiveDateTime {
impl<'a> FromSql<'a> for PrimitiveDateTime {
fn from_sql(_: &Type, raw: &[u8]) -> Result<PrimitiveDateTime, Box<dyn Error + Sync + Send>> {
let t = types::timestamp_from_sql(raw)?;
Ok(base() + Duration::microseconds(t))
Ok(base()
.checked_add(Duration::microseconds(t))
.ok_or("value too large to decode")?)
}

accepts!(TIMESTAMP);
Expand Down Expand Up @@ -62,7 +64,10 @@ impl ToSql for OffsetDateTime {
impl<'a> FromSql<'a> for Date {
fn from_sql(_: &Type, raw: &[u8]) -> Result<Date, Box<dyn Error + Sync + Send>> {
let jd = types::date_from_sql(raw)?;
Ok(base().date() + Duration::days(i64::from(jd)))
Ok(base()
.date()
.checked_add(Duration::days(i64::from(jd)))
.ok_or("value too large to decode")?)
}

accepts!(DATE);
Expand Down
38 changes: 37 additions & 1 deletion tokio-postgres/tests/test/types/time_03.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
use std::fmt;

use postgres_types::FromSqlOwned;
use time_03::{format_description, OffsetDateTime, PrimitiveDateTime};
use tokio_postgres::types::{Date, Timestamp};
use tokio_postgres::{
types::{Date, Timestamp},
Client,
};

use crate::types::test_type;

Expand Down Expand Up @@ -147,3 +153,33 @@ async fn test_time_params() {
)
.await;
}

#[tokio::test]
async fn test_special_params_without_wrapper() {
async fn assert_overflows<T>(client: &mut Client, val: &str, sql_type: &str)
where
T: FromSqlOwned + fmt::Debug,
{
let err = client
.query_one(&*format!("SELECT {}::{}", val, sql_type), &[])
.await
.unwrap()
.try_get::<_, T>(0)
.unwrap_err();
assert_eq!(
err.to_string(),
"error deserializing column 0: value too large to decode"
);
}

let mut client = crate::connect("user=postgres").await;

assert_overflows::<OffsetDateTime>(&mut client, "'-infinity'", "timestamptz").await;
assert_overflows::<OffsetDateTime>(&mut client, "'infinity'", "timestamptz").await;

assert_overflows::<PrimitiveDateTime>(&mut client, "'-infinity'", "timestamp").await;
assert_overflows::<PrimitiveDateTime>(&mut client, "'infinity'", "timestamp").await;

assert_overflows::<time_03::Date>(&mut client, "'-infinity'", "date").await;
assert_overflows::<time_03::Date>(&mut client, "'infinity'", "date").await;
}

0 comments on commit 924d0e5

Please sign in to comment.