Skip to main content

jiff_sqlx/
wrappers.rs

1/// A trait for convenient conversions from Jiff types to SQLx types.
2///
3/// # Example
4///
5/// This shows how to convert a [`jiff::Timestamp`] to a [`Timestamp`]:
6///
7/// ```
8/// use jiff_sqlx::ToSqlx;
9///
10/// let ts: jiff::Timestamp = "2025-02-20T17:00-05".parse()?;
11/// let wrapper = ts.to_sqlx();
12/// assert_eq!(format!("{wrapper:?}"), "Timestamp(2025-02-20T22:00:00Z)");
13///
14/// # Ok::<(), Box<dyn std::error::Error>>(())
15/// ```
16pub trait ToSqlx {
17    /// The wrapper type to convert to.
18    type Target;
19
20    /// A conversion method that converts a Jiff type to a SQLx wrapper type.
21    fn to_sqlx(self) -> Self::Target;
22}
23
24// We currently don't support `ZonedDateTime` integration in this wrapper
25// crate. To briefly explain why, a `ZonedDateTime` is _both_ a timestamp and a
26// time zone. And it isn't necessarily a dumb time zone like `-05:00`. It is
27// intended to be a real time zone like `America/New_York` or
28// `Australia/Hobart`.
29//
30// However, PostgreSQL doesn't really have a primitive type that specifically
31// supports "timestamp with time zone." Comically, it does have a `TIMESTAMP
32// WITH TIME ZONE` type (from the SQL standard, as I understand it), but it's
33// actually just a timestamp. It doesn't store any other data than a timestamp.
34// The difference between `TIMESTAMP WITHOUT TIME ZONE` and `TIMESTAMP WITH
35// TIME ZONE` is, principally, that fixed offsets are respected in the former
36// but completely ignored in the latter. (PostgreSQL's documentation refers
37// to fixed offsets as "time zones," which is rather antiquated IMO.) And,
38// conventionally, `TIMESTAMP WITHOUT TIME ZONE` is civil (local) time.
39//
40// So what's the problem? Well, if we try to stuff a `ZonedDateTime` into a
41// `TIMESTAMP WITH TIME ZONE`, then the *only* thing that actually gets stored
42// is a timestamp. No time zone. No offset. Nothing. That means the time zone
43// attached to `ZonedDateTime` gets dropped. So if you put
44// `2025-02-15T17:00-05[America/New_york]` into the database, then you'll
45// always get `2025-02-15T22:00+00[UTC]` out. That's a silent dropping of the
46// time zone data. I personally think this would be extremely surprising, and
47// it could lead to bugs if you assume the time zone is correctly
48// round-tripped. (For example, DST safe arithmetic would no longer apply.) And
49// indeed, this is a principle design goal of Jiff: `ZonedDateTime` values can
50// be losslessly transmitted.
51//
52// An alternative here is to provide a `ZonedDateTime` wrapper, but store it in
53// a `TEXT` field as an RFC 9557 timestamp. This would permit lossless
54// round-tripping. The problem is that this may also violate user expectations
55// because a datetime is not stored in a datetime field. Thus, you won't be
56// able to use PostgreSQL native functionality to handle it as a date.
57//
58// So for now, I opted to take the conservative choice and just not provide a
59// `ZonedDateTime` impl. This way, we can gather use cases and make a better
60// informed decision of what to do. Plus, the maintainer of `sqlx` seemed
61// unconvinced that a `ZonedDateTime` impl that drops time zone data was a
62// problem, so out of deference there, I started with this more conservative
63// strategy.
64//
65// Of course, if you want to store something in `TIMESTAMP WITHOUT TIME ZONE`,
66// then you can just use `Timestamp`.
67//
68// Ref: https://github.com/launchbadge/sqlx/issues/3487#issuecomment-2636542379
69/*
70#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
71pub struct ZonedDateTime(jiff::ZonedDateTime);
72
73impl ZonedDateTime {
74    pub fn to_jiff(&self) -> jiff::ZonedDateTime {
75        self.0.clone()
76    }
77}
78
79impl<'a> ToSqlx for &'a jiff::ZonedDateTime {
80    type Target = ZonedDateTime;
81
82    fn to_sqlx(self) -> ZonedDateTime {
83        ZonedDateTime(self.clone())
84    }
85}
86
87impl From<jiff::ZonedDateTime> for ZonedDateTime {
88    fn from(x: jiff::ZonedDateTime) -> ZonedDateTime {
89        ZonedDateTime(x)
90    }
91}
92
93impl From<ZonedDateTime> for jiff::ZonedDateTime {
94    fn from(x: ZonedDateTime) -> jiff::ZonedDateTime {
95        x.0
96    }
97}
98
99impl core::ops::Deref for ZonedDateTime {
100    type Target = jiff::ZonedDateTime;
101
102    fn deref(&self) -> &jiff::ZonedDateTime {
103        &self.0
104    }
105}
106*/
107
108/// A wrapper type for [`jiff::Timestamp`].
109#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
110pub struct Timestamp(jiff::Timestamp);
111
112impl Timestamp {
113    /// Converts this wrapper to a [`jiff::Timestamp`].
114    pub fn to_jiff(self) -> jiff::Timestamp {
115        self.0
116    }
117}
118
119impl ToSqlx for jiff::Timestamp {
120    type Target = Timestamp;
121
122    fn to_sqlx(self) -> Timestamp {
123        Timestamp(self)
124    }
125}
126
127impl From<jiff::Timestamp> for Timestamp {
128    fn from(x: jiff::Timestamp) -> Timestamp {
129        Timestamp(x)
130    }
131}
132
133impl From<Timestamp> for jiff::Timestamp {
134    fn from(x: Timestamp) -> jiff::Timestamp {
135        x.0
136    }
137}
138
139/// A wrapper type for [`jiff::civil::DateTime`].
140#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
141pub struct DateTime(jiff::civil::DateTime);
142
143impl DateTime {
144    /// Converts this wrapper to a [`jiff::civil::DateTime`].
145    pub fn to_jiff(self) -> jiff::civil::DateTime {
146        self.0
147    }
148}
149
150impl ToSqlx for jiff::civil::DateTime {
151    type Target = DateTime;
152
153    fn to_sqlx(self) -> DateTime {
154        DateTime(self)
155    }
156}
157
158impl From<jiff::civil::DateTime> for DateTime {
159    fn from(x: jiff::civil::DateTime) -> DateTime {
160        DateTime(x)
161    }
162}
163
164impl From<DateTime> for jiff::civil::DateTime {
165    fn from(x: DateTime) -> jiff::civil::DateTime {
166        x.0
167    }
168}
169
170/// A wrapper type for [`jiff::civil::Date`].
171#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
172pub struct Date(jiff::civil::Date);
173
174impl Date {
175    /// Converts this wrapper to a [`jiff::civil::Date`].
176    pub fn to_jiff(self) -> jiff::civil::Date {
177        self.0
178    }
179}
180
181impl ToSqlx for jiff::civil::Date {
182    type Target = Date;
183
184    fn to_sqlx(self) -> Date {
185        Date(self)
186    }
187}
188
189impl From<jiff::civil::Date> for Date {
190    fn from(x: jiff::civil::Date) -> Date {
191        Date(x)
192    }
193}
194
195impl From<Date> for jiff::civil::Date {
196    fn from(x: Date) -> jiff::civil::Date {
197        x.0
198    }
199}
200
201/// A wrapper type for [`jiff::civil::Time`].
202#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
203pub struct Time(jiff::civil::Time);
204
205impl Time {
206    /// Converts this wrapper to a [`jiff::civil::Time`].
207    pub fn to_jiff(self) -> jiff::civil::Time {
208        self.0
209    }
210}
211
212impl ToSqlx for jiff::civil::Time {
213    type Target = Time;
214
215    fn to_sqlx(self) -> Time {
216        Time(self)
217    }
218}
219
220impl From<jiff::civil::Time> for Time {
221    fn from(x: jiff::civil::Time) -> Time {
222        Time(x)
223    }
224}
225
226impl From<Time> for jiff::civil::Time {
227    fn from(x: Time) -> jiff::civil::Time {
228        x.0
229    }
230}
231
232/// A wrapper type for [`jiff::Span`].
233///
234/// # PostgreSQL: Limited support
235///
236/// This type _only_ has a [`sqlx::decode::Decode`] trait implementation
237/// for PostgreSQL. The reason for this is that encoding an arbitrary
238/// `Span` into a PostgreSQL interval requires a relative datetime.
239/// Therefore, users wanting to store a `Span` will need to explicitly use a
240/// `sqlx::postgres::types::PgInterval` at least at encoding time.
241#[derive(Clone, Copy, Debug)]
242pub struct Span(jiff::Span);
243
244impl Span {
245    /// Converts this wrapper to a [`jiff::Span`].
246    pub fn to_jiff(self) -> jiff::Span {
247        self.0
248    }
249}
250
251impl ToSqlx for jiff::Span {
252    type Target = Span;
253
254    fn to_sqlx(self) -> Span {
255        Span(self)
256    }
257}
258
259impl From<jiff::Span> for Span {
260    fn from(x: jiff::Span) -> Span {
261        Span(x)
262    }
263}
264
265impl From<Span> for jiff::Span {
266    fn from(x: Span) -> jiff::Span {
267        x.0
268    }
269}
270
271/// Give the wrapper types a Serialize and a Deserialize implementation to use
272/// with Serde.
273///
274/// Under the hood, we use the Serde implementation of the original types
275/// directly.
276#[cfg(feature = "serde")]
277mod serde_impl {
278    use serde::{Deserialize, Deserializer, Serialize, Serializer};
279
280    use super::{Date, DateTime, Span, Time, Timestamp};
281
282    macro_rules! impl_serde {
283        ($wrapper:ident, $jiff:ty) => {
284            impl Serialize for $wrapper {
285                fn serialize<S>(
286                    &self,
287                    serializer: S,
288                ) -> Result<S::Ok, S::Error>
289                where
290                    S: Serializer,
291                {
292                    Serialize::serialize(&self.0, serializer)
293                }
294            }
295
296            impl<'de> Deserialize<'de> for $wrapper {
297                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
298                where
299                    D: Deserializer<'de>,
300                {
301                    <$jiff as Deserialize<'de>>::deserialize(deserializer)
302                        .map($wrapper)
303                }
304            }
305        };
306    }
307
308    impl_serde!(Timestamp, jiff::Timestamp);
309    impl_serde!(DateTime, jiff::civil::DateTime);
310    impl_serde!(Date, jiff::civil::Date);
311    impl_serde!(Time, jiff::civil::Time);
312    impl_serde!(Span, jiff::Span);
313}