11use bytes:: BytesMut ;
22use jiff_01:: {
33 civil:: { Date , DateTime , Time } ,
4- Span , Timestamp ,
4+ Span , SpanRound , Timestamp , Unit ,
55} ;
66use postgres_protocol:: types;
77use std:: error:: Error ;
@@ -12,13 +12,17 @@ const fn base() -> DateTime {
1212 DateTime :: constant ( 2000 , 1 , 1 , 0 , 0 , 0 , 0 )
1313}
1414
15- /// The number of seconds from the Unix epoch to 2000-01-01 00:00:00 UTC.
15+ /// The number of seconds from the Unix epoch to 2000-01-01 00:00:00 UTC.
1616const PG_EPOCH : i64 = 946684800 ;
1717
1818fn base_ts ( ) -> Timestamp {
1919 Timestamp :: new ( PG_EPOCH , 0 ) . unwrap ( )
2020}
2121
22+ fn round_us < ' a > ( ) -> SpanRound < ' a > {
23+ SpanRound :: new ( ) . largest ( Unit :: Microsecond )
24+ }
25+
2226impl < ' a > FromSql < ' a > for DateTime {
2327 fn from_sql ( _: & Type , raw : & [ u8 ] ) -> Result < DateTime , Box < dyn Error + Sync + Send > > {
2428 let t = types:: timestamp_from_sql ( raw) ?;
@@ -30,7 +34,8 @@ impl<'a> FromSql<'a> for DateTime {
3034
3135impl ToSql for DateTime {
3236 fn to_sql ( & self , _: & Type , w : & mut BytesMut ) -> Result < IsNull , Box < dyn Error + Sync + Send > > {
33- types:: timestamp_to_sql ( self . since ( base ( ) ) ?. get_microseconds ( ) , w) ;
37+ let span = self . since ( base ( ) ) ?. round ( round_us ( ) ) ?;
38+ types:: timestamp_to_sql ( span. get_microseconds ( ) , w) ;
3439 Ok ( IsNull :: No )
3540 }
3641
@@ -49,7 +54,8 @@ impl<'a> FromSql<'a> for Timestamp {
4954
5055impl ToSql for Timestamp {
5156 fn to_sql ( & self , _: & Type , w : & mut BytesMut ) -> Result < IsNull , Box < dyn Error + Sync + Send > > {
52- types:: timestamp_to_sql ( self . since ( base_ts ( ) ) ?. get_microseconds ( ) , w) ;
57+ let span = self . since ( base_ts ( ) ) ?. round ( round_us ( ) ) ?;
58+ types:: timestamp_to_sql ( span. get_microseconds ( ) , w) ;
5359 Ok ( IsNull :: No )
5460 }
5561
@@ -88,8 +94,8 @@ impl<'a> FromSql<'a> for Time {
8894
8995impl ToSql for Time {
9096 fn to_sql ( & self , _: & Type , w : & mut BytesMut ) -> Result < IsNull , Box < dyn Error + Sync + Send > > {
91- let delta = self . since ( Time :: midnight ( ) ) ?;
92- types:: time_to_sql ( delta . get_microseconds ( ) , w) ;
97+ let span = self . since ( Time :: midnight ( ) ) ? . round ( round_us ( ) ) ?;
98+ types:: time_to_sql ( span . get_microseconds ( ) , w) ;
9399 Ok ( IsNull :: No )
94100 }
95101
0 commit comments