diesel/sqlite/types/date_and_time/
chrono.rs

1extern crate chrono;
2
3use self::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
4
5use crate::backend::Backend;
6use crate::deserialize::{self, FromSql};
7use crate::serialize::{self, IsNull, Output, ToSql};
8use crate::sql_types::{Date, Time, Timestamp, TimestamptzSqlite};
9use crate::sqlite::Sqlite;
10
11/// Warning to future editors:
12/// Changes in the following formats need to be kept in sync
13/// with the formats of the ["time"](super::time) module.
14/// We do not need a distinction between whole second and
15/// subsecond since %.f will only print the dot if needed.
16/// We always print as many subsecond as his given to us,
17/// this means the subsecond part can be 3, 6 or 9 digits.
18const DATE_FORMAT: &str = "%F";
19
20const ENCODE_TIME_FORMAT: &str = "%T%.f";
21
22const TIME_FORMATS: [&str; 9] = [
23    // Most likely formats
24    "%T%.f", "%T", // All other valid formats in order of increasing specificity
25    "%R", "%RZ", "%R%:z", "%TZ", "%T%:z", "%T%.fZ", "%T%.f%:z",
26];
27
28const ENCODE_NAIVE_DATETIME_FORMAT: &str = "%F %T%.f";
29
30const ENCODE_DATETIME_FORMAT: &str = "%F %T%.f%:z";
31
32const NAIVE_DATETIME_FORMATS: [&str; 18] = [
33    // Most likely formats
34    "%F %T%.f",
35    "%F %T%.f%:z",
36    "%F %T",
37    "%F %T%:z",
38    // All other formats in order of increasing specificity
39    "%F %R",
40    "%F %RZ",
41    "%F %R%:z",
42    "%F %TZ",
43    "%F %T%.fZ",
44    "%FT%R",
45    "%FT%RZ",
46    "%FT%R%:z",
47    "%FT%T",
48    "%FT%TZ",
49    "%FT%T%:z",
50    "%FT%T%.f",
51    "%FT%T%.fZ",
52    "%FT%T%.f%:z",
53];
54
55const DATETIME_FORMATS: [&str; 12] = [
56    // Most likely formats
57    "%F %T%.f%:z",
58    "%F %T%:z",
59    // All other formats in order of increasing specificity
60    "%F %RZ",
61    "%F %R%:z",
62    "%F %TZ",
63    "%F %T%.fZ",
64    "%FT%RZ",
65    "%FT%R%:z",
66    "%FT%TZ",
67    "%FT%T%:z",
68    "%FT%T%.fZ",
69    "%FT%T%.f%:z",
70];
71
72fn parse_julian(julian_days: f64) -> Option<NaiveDateTime> {
73    const EPOCH_IN_JULIAN_DAYS: f64 = 2_440_587.5;
74    const SECONDS_IN_DAY: f64 = 86400.0;
75    let timestamp = (julian_days - EPOCH_IN_JULIAN_DAYS) * SECONDS_IN_DAY;
76    #[allow(clippy::cast_possible_truncation)] // we want to truncate
77    let seconds = timestamp.trunc() as i64;
78    // that's not true, `fract` is always > 0
79    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
80    let nanos = (timestamp.fract() * 1E9) as u32;
81    #[allow(deprecated)] // otherwise we would need to bump our minimal chrono version
82    NaiveDateTime::from_timestamp_opt(seconds, nanos)
83}
84
85#[cfg(all(feature = "sqlite", feature = "chrono"))]
86impl FromSql<Date, Sqlite> for NaiveDate {
87    fn from_sql(mut value: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
88        value
89            .parse_string(|s| Self::parse_from_str(s, DATE_FORMAT))
90            .map_err(Into::into)
91    }
92}
93
94#[cfg(all(feature = "sqlite", feature = "chrono"))]
95impl ToSql<Date, Sqlite> for NaiveDate {
96    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
97        out.set_value(self.format(DATE_FORMAT).to_string());
98        Ok(IsNull::No)
99    }
100}
101
102#[cfg(all(feature = "sqlite", feature = "chrono"))]
103impl FromSql<Time, Sqlite> for NaiveTime {
104    fn from_sql(mut value: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
105        value.parse_string(|text| {
106            for format in TIME_FORMATS {
107                if let Ok(time) = Self::parse_from_str(text, format) {
108                    return Ok(time);
109                }
110            }
111
112            Err(format!("Invalid time {text}").into())
113        })
114    }
115}
116
117#[cfg(all(feature = "sqlite", feature = "chrono"))]
118impl ToSql<Time, Sqlite> for NaiveTime {
119    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
120        out.set_value(self.format(ENCODE_TIME_FORMAT).to_string());
121        Ok(IsNull::No)
122    }
123}
124
125#[cfg(all(feature = "sqlite", feature = "chrono"))]
126impl FromSql<Timestamp, Sqlite> for NaiveDateTime {
127    fn from_sql(mut value: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
128        value.parse_string(|text| {
129            for format in NAIVE_DATETIME_FORMATS {
130                if let Ok(dt) = Self::parse_from_str(text, format) {
131                    return Ok(dt);
132                }
133            }
134
135            if let Ok(julian_days) = text.parse::<f64>() {
136                if let Some(timestamp) = parse_julian(julian_days) {
137                    return Ok(timestamp);
138                }
139            }
140
141            Err(format!("Invalid datetime {text}").into())
142        })
143    }
144}
145
146#[cfg(all(feature = "sqlite", feature = "chrono"))]
147impl ToSql<Timestamp, Sqlite> for NaiveDateTime {
148    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
149        out.set_value(self.format(ENCODE_NAIVE_DATETIME_FORMAT).to_string());
150        Ok(IsNull::No)
151    }
152}
153
154#[cfg(all(feature = "sqlite", feature = "chrono"))]
155impl FromSql<TimestamptzSqlite, Sqlite> for NaiveDateTime {
156    fn from_sql(mut value: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
157        value.parse_string(|text| {
158            for format in NAIVE_DATETIME_FORMATS {
159                if let Ok(dt) = Self::parse_from_str(text, format) {
160                    return Ok(dt);
161                }
162            }
163
164            if let Ok(julian_days) = text.parse::<f64>() {
165                if let Some(timestamp) = parse_julian(julian_days) {
166                    return Ok(timestamp);
167                }
168            }
169
170            Err(format!("Invalid datetime {text}").into())
171        })
172    }
173}
174
175#[cfg(all(feature = "sqlite", feature = "chrono"))]
176impl ToSql<TimestamptzSqlite, Sqlite> for NaiveDateTime {
177    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
178        out.set_value(self.format(ENCODE_NAIVE_DATETIME_FORMAT).to_string());
179        Ok(IsNull::No)
180    }
181}
182
183#[cfg(all(feature = "sqlite", feature = "chrono"))]
184impl FromSql<TimestamptzSqlite, Sqlite> for DateTime<Utc> {
185    fn from_sql(mut value: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
186        // First try to parse the timezone
187        if let Ok(dt) = value.parse_string(|text| {
188            for format in DATETIME_FORMATS {
189                if let Ok(dt) = DateTime::parse_from_str(text, format) {
190                    return Ok(dt.with_timezone(&Utc));
191                }
192            }
193
194            Err(())
195        }) {
196            return Ok(dt);
197        }
198
199        // Fallback on assuming Utc
200        let naive_date_time =
201            <NaiveDateTime as FromSql<TimestamptzSqlite, Sqlite>>::from_sql(value)?;
202        Ok(Utc.from_utc_datetime(&naive_date_time))
203    }
204}
205
206#[cfg(all(feature = "sqlite", feature = "chrono"))]
207impl FromSql<TimestamptzSqlite, Sqlite> for DateTime<Local> {
208    fn from_sql(mut value: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
209        // First try to parse the timezone
210        if let Ok(dt) = value.parse_string(|text| {
211            for format in DATETIME_FORMATS {
212                if let Ok(dt) = DateTime::parse_from_str(text, format) {
213                    return Ok(dt.with_timezone(&Local));
214                }
215            }
216
217            Err(())
218        }) {
219            return Ok(dt);
220        }
221
222        // Fallback on assuming Local
223        let naive_date_time =
224            <NaiveDateTime as FromSql<TimestamptzSqlite, Sqlite>>::from_sql(value)?;
225        Ok(Local::from_utc_datetime(&Local, &naive_date_time))
226    }
227}
228
229#[cfg(all(feature = "sqlite", feature = "chrono"))]
230impl<TZ: TimeZone> ToSql<TimestamptzSqlite, Sqlite> for DateTime<TZ> {
231    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
232        // Converting to UTC ensures consistency
233        let dt_utc = self.with_timezone(&Utc);
234        out.set_value(dt_utc.format(ENCODE_DATETIME_FORMAT).to_string());
235        Ok(IsNull::No)
236    }
237}
238
239#[cfg(test)]
240#[allow(clippy::unwrap_used)]
241mod tests {
242    extern crate chrono;
243    extern crate dotenvy;
244
245    use self::chrono::{
246        DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike,
247        Utc,
248    };
249
250    use crate::dsl::{now, sql};
251    use crate::prelude::*;
252    use crate::select;
253    use crate::sql_types::{Text, Time, Timestamp, TimestamptzSqlite};
254    use crate::test_helpers::connection;
255
256    define_sql_function!(fn datetime(x: Text) -> Timestamp);
257    define_sql_function!(fn time(x: Text) -> Time);
258    define_sql_function!(fn date(x: Text) -> Date);
259
260    #[test]
261    fn unix_epoch_encodes_correctly() {
262        let connection = &mut connection();
263        let time = NaiveDate::from_ymd_opt(1970, 1, 1)
264            .unwrap()
265            .and_hms_opt(0, 0, 0)
266            .unwrap();
267        let query = select(datetime("1970-01-01 00:00:00.000000").eq(time));
268        assert_eq!(Ok(true), query.get_result(connection));
269    }
270
271    #[test]
272    fn unix_epoch_decodes_correctly_in_all_possible_formats() {
273        let connection = &mut connection();
274        let time = NaiveDate::from_ymd_opt(1970, 1, 1)
275            .unwrap()
276            .and_hms_opt(0, 0, 0)
277            .unwrap();
278        let valid_epoch_formats = vec![
279            "1970-01-01 00:00",
280            "1970-01-01 00:00:00",
281            "1970-01-01 00:00:00.000",
282            "1970-01-01 00:00:00.000000",
283            "1970-01-01T00:00",
284            "1970-01-01T00:00:00",
285            "1970-01-01T00:00:00.000",
286            "1970-01-01T00:00:00.000000",
287            "1970-01-01 00:00Z",
288            "1970-01-01 00:00:00Z",
289            "1970-01-01 00:00:00.000Z",
290            "1970-01-01 00:00:00.000000Z",
291            "1970-01-01T00:00Z",
292            "1970-01-01T00:00:00Z",
293            "1970-01-01T00:00:00.000Z",
294            "1970-01-01T00:00:00.000000Z",
295            "1970-01-01 00:00+00:00",
296            "1970-01-01 00:00:00+00:00",
297            "1970-01-01 00:00:00.000+00:00",
298            "1970-01-01 00:00:00.000000+00:00",
299            "1970-01-01T00:00+00:00",
300            "1970-01-01T00:00:00+00:00",
301            "1970-01-01T00:00:00.000+00:00",
302            "1970-01-01T00:00:00.000000+00:00",
303            "1970-01-01 00:00+01:00",
304            "1970-01-01 00:00:00+01:00",
305            "1970-01-01 00:00:00.000+01:00",
306            "1970-01-01 00:00:00.000000+01:00",
307            "1970-01-01T00:00+01:00",
308            "1970-01-01T00:00:00+01:00",
309            "1970-01-01T00:00:00.000+01:00",
310            "1970-01-01T00:00:00.000000+01:00",
311            "1970-01-01T00:00-01:00",
312            "1970-01-01T00:00:00-01:00",
313            "1970-01-01T00:00:00.000-01:00",
314            "1970-01-01T00:00:00.000000-01:00",
315            "1970-01-01T00:00-01:00",
316            "1970-01-01T00:00:00-01:00",
317            "1970-01-01T00:00:00.000-01:00",
318            "1970-01-01T00:00:00.000000-01:00",
319            "2440587.5",
320        ];
321
322        for s in valid_epoch_formats {
323            let epoch_from_sql =
324                select(sql::<Timestamp>(&format!("'{}'", s))).get_result(connection);
325            assert_eq!(Ok(time), epoch_from_sql, "format {} failed", s);
326        }
327    }
328
329    #[test]
330    fn times_relative_to_now_encode_correctly() {
331        let connection = &mut connection();
332        let time = Utc::now().naive_utc() + Duration::try_seconds(60).unwrap();
333        let query = select(now.lt(time));
334        assert_eq!(Ok(true), query.get_result(connection));
335
336        let time = Utc::now().naive_utc() - Duration::try_seconds(600).unwrap();
337        let query = select(now.gt(time));
338        assert_eq!(Ok(true), query.get_result(connection));
339    }
340
341    #[test]
342    fn times_of_day_encode_correctly() {
343        let connection = &mut connection();
344
345        let midnight = NaiveTime::from_hms_opt(0, 0, 0).unwrap();
346        let query = select(time("00:00:00.000000").eq(midnight));
347        assert!(query.get_result::<bool>(connection).unwrap());
348
349        let noon = NaiveTime::from_hms_opt(12, 0, 0).unwrap();
350        let query = select(time("12:00:00.000000").eq(noon));
351        assert!(query.get_result::<bool>(connection).unwrap());
352
353        let roughly_half_past_eleven = NaiveTime::from_hms_micro_opt(23, 37, 4, 2200).unwrap();
354        let query = select(sql::<Time>("'23:37:04.002200'").eq(roughly_half_past_eleven));
355        assert!(query.get_result::<bool>(connection).unwrap());
356    }
357
358    #[test]
359    fn times_of_day_decode_correctly() {
360        let connection = &mut connection();
361        let midnight = NaiveTime::from_hms_opt(0, 0, 0).unwrap();
362        let valid_midnight_formats = &[
363            "00:00",
364            "00:00:00",
365            "00:00:00.000",
366            "00:00:00.000000",
367            "00:00Z",
368            "00:00:00Z",
369            "00:00:00.000Z",
370            "00:00:00.000000Z",
371            "00:00+00:00",
372            "00:00:00+00:00",
373            "00:00:00.000+00:00",
374            "00:00:00.000000+00:00",
375            "00:00+01:00",
376            "00:00:00+01:00",
377            "00:00:00.000+01:00",
378            "00:00:00.000000+01:00",
379            "00:00-01:00",
380            "00:00:00-01:00",
381            "00:00:00.000-01:00",
382            "00:00:00.000000-01:00",
383        ];
384        for format in valid_midnight_formats {
385            let query = select(sql::<Time>(&format!("'{}'", format)));
386            assert_eq!(
387                Ok(midnight),
388                query.get_result::<NaiveTime>(connection),
389                "format {} failed",
390                format
391            );
392        }
393
394        let noon = NaiveTime::from_hms_opt(12, 0, 0).unwrap();
395        let query = select(sql::<Time>("'12:00:00'"));
396        assert_eq!(Ok(noon), query.get_result::<NaiveTime>(connection));
397
398        let roughly_half_past_eleven = NaiveTime::from_hms_micro_opt(23, 37, 4, 2200).unwrap();
399        let query = select(sql::<Time>("'23:37:04.002200'"));
400        assert_eq!(
401            Ok(roughly_half_past_eleven),
402            query.get_result::<NaiveTime>(connection)
403        );
404    }
405
406    #[test]
407    fn dates_encode_correctly() {
408        let connection = &mut connection();
409        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
410        let query = select(date("2000-01-01").eq(january_first_2000));
411        assert!(query.get_result::<bool>(connection).unwrap());
412
413        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11).unwrap();
414        let query = select(date("0000-04-11").eq(distant_past));
415        assert!(query.get_result::<bool>(connection).unwrap());
416
417        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1).unwrap();
418        let query = select(date("2018-01-01").eq(january_first_2018));
419        assert!(query.get_result::<bool>(connection).unwrap());
420
421        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8).unwrap();
422        let query = select(date("9999-01-08").eq(distant_future));
423        assert!(query.get_result::<bool>(connection).unwrap());
424    }
425
426    #[test]
427    fn dates_decode_correctly() {
428        let connection = &mut connection();
429        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
430        let query = select(date("2000-01-01"));
431        assert_eq!(
432            Ok(january_first_2000),
433            query.get_result::<NaiveDate>(connection)
434        );
435
436        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11).unwrap();
437        let query = select(date("0000-04-11"));
438        assert_eq!(Ok(distant_past), query.get_result::<NaiveDate>(connection));
439
440        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1).unwrap();
441        let query = select(date("2018-01-01"));
442        assert_eq!(
443            Ok(january_first_2018),
444            query.get_result::<NaiveDate>(connection)
445        );
446
447        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8).unwrap();
448        let query = select(date("9999-01-08"));
449        assert_eq!(
450            Ok(distant_future),
451            query.get_result::<NaiveDate>(connection)
452        );
453    }
454
455    #[test]
456    fn datetimes_decode_correctly() {
457        let connection = &mut connection();
458        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1)
459            .unwrap()
460            .and_hms_opt(1, 1, 1)
461            .unwrap();
462        let query = select(datetime("2000-01-01 01:01:01.000000"));
463        assert_eq!(
464            Ok(january_first_2000),
465            query.get_result::<NaiveDateTime>(connection)
466        );
467
468        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11)
469            .unwrap()
470            .and_hms_opt(2, 2, 2)
471            .unwrap();
472        let query = select(datetime("0000-04-11 02:02:02.000000"));
473        assert_eq!(
474            Ok(distant_past),
475            query.get_result::<NaiveDateTime>(connection)
476        );
477
478        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1).unwrap();
479        let query = select(date("2018-01-01"));
480        assert_eq!(
481            Ok(january_first_2018),
482            query.get_result::<NaiveDate>(connection)
483        );
484
485        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8)
486            .unwrap()
487            .and_hms_opt(23, 59, 59)
488            .unwrap()
489            .with_nanosecond(100_000)
490            .unwrap();
491        let query = select(sql::<Timestamp>("'9999-01-08 23:59:59.000100'"));
492        assert_eq!(
493            Ok(distant_future),
494            query.get_result::<NaiveDateTime>(connection)
495        );
496    }
497
498    #[test]
499    fn datetimes_encode_correctly() {
500        let connection = &mut connection();
501        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1)
502            .unwrap()
503            .and_hms_opt(0, 0, 0)
504            .unwrap();
505        let query = select(datetime("2000-01-01 00:00:00.000000").eq(january_first_2000));
506        assert!(query.get_result::<bool>(connection).unwrap());
507
508        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11)
509            .unwrap()
510            .and_hms_opt(20, 00, 20)
511            .unwrap();
512        let query = select(datetime("0000-04-11 20:00:20.000000").eq(distant_past));
513        assert!(query.get_result::<bool>(connection).unwrap());
514
515        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1)
516            .unwrap()
517            .and_hms_opt(12, 00, 00)
518            .unwrap()
519            .with_nanosecond(500_000)
520            .unwrap();
521        let query = select(sql::<Timestamp>("'2018-01-01 12:00:00.000500'").eq(january_first_2018));
522        assert!(query.get_result::<bool>(connection).unwrap());
523
524        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8)
525            .unwrap()
526            .and_hms_opt(0, 0, 0)
527            .unwrap();
528        let query = select(datetime("9999-01-08 00:00:00.000000").eq(distant_future));
529        assert!(query.get_result::<bool>(connection).unwrap());
530    }
531
532    #[test]
533    fn insert_timestamptz_into_table_as_text() {
534        crate::table! {
535            #[allow(unused_parens)]
536            test_insert_timestamptz_into_table_as_text(id) {
537                id -> Integer,
538                timestamp_with_tz -> TimestamptzSqlite,
539            }
540        }
541        let conn = &mut connection();
542        crate::sql_query(
543            "CREATE TABLE test_insert_timestamptz_into_table_as_text(id INTEGER PRIMARY KEY, timestamp_with_tz TEXT);",
544        )
545        .execute(conn)
546        .unwrap();
547
548        let time: DateTime<Utc> = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap();
549
550        crate::insert_into(test_insert_timestamptz_into_table_as_text::table)
551            .values(vec![(
552                test_insert_timestamptz_into_table_as_text::id.eq(1),
553                test_insert_timestamptz_into_table_as_text::timestamp_with_tz.eq(sql::<
554                    TimestamptzSqlite,
555                >(
556                    "'1970-01-01 00:00:00.000000+00:00'",
557                )),
558            )])
559            .execute(conn)
560            .unwrap();
561
562        let result = test_insert_timestamptz_into_table_as_text::table
563            .select(test_insert_timestamptz_into_table_as_text::timestamp_with_tz)
564            .get_result::<DateTime<Utc>>(conn)
565            .unwrap();
566        assert_eq!(result, time);
567    }
568
569    #[test]
570    fn can_query_timestamptz_column_with_between() {
571        crate::table! {
572            #[allow(unused_parens)]
573            test_query_timestamptz_column_with_between(id) {
574                id -> Integer,
575                timestamp_with_tz -> TimestamptzSqlite,
576            }
577        }
578        let conn = &mut connection();
579        crate::sql_query(
580            "CREATE TABLE test_query_timestamptz_column_with_between(id INTEGER PRIMARY KEY, timestamp_with_tz TEXT);",
581        )
582        .execute(conn)
583        .unwrap();
584
585        crate::insert_into(test_query_timestamptz_column_with_between::table)
586            .values(vec![
587                (
588                    test_query_timestamptz_column_with_between::id.eq(1),
589                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
590                        TimestamptzSqlite,
591                    >(
592                        "'1970-01-01 00:00:01.000000+00:00'",
593                    )),
594                ),
595                (
596                    test_query_timestamptz_column_with_between::id.eq(2),
597                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
598                        TimestamptzSqlite,
599                    >(
600                        "'1970-01-01 00:00:02.000000+00:00'",
601                    )),
602                ),
603                (
604                    test_query_timestamptz_column_with_between::id.eq(3),
605                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
606                        TimestamptzSqlite,
607                    >(
608                        "'1970-01-01 00:00:03.000000+00:00'",
609                    )),
610                ),
611                (
612                    test_query_timestamptz_column_with_between::id.eq(4),
613                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
614                        TimestamptzSqlite,
615                    >(
616                        "'1970-01-01 00:00:04.000000+00:00'",
617                    )),
618                ),
619            ])
620            .execute(conn)
621            .unwrap();
622
623        let result = test_query_timestamptz_column_with_between::table
624            .select(test_query_timestamptz_column_with_between::timestamp_with_tz)
625            .filter(
626                test_query_timestamptz_column_with_between::timestamp_with_tz
627                    .gt(Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap()),
628            )
629            .filter(
630                test_query_timestamptz_column_with_between::timestamp_with_tz
631                    .lt(Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 4).single().unwrap()),
632            )
633            .count()
634            .get_result::<_>(conn);
635        assert_eq!(result, Ok(3));
636    }
637
638    #[test]
639    fn unix_epoch_encodes_correctly_with_timezone() {
640        let connection = &mut connection();
641        // West one hour is negative offset
642        let time = FixedOffset::west_opt(3600)
643            .unwrap()
644            .with_ymd_and_hms(1970, 1, 1, 0, 0, 0)
645            .single()
646            .unwrap()
647            // 1ms
648            .with_nanosecond(1_000_000)
649            .unwrap();
650        let query = select(sql::<TimestamptzSqlite>("'1970-01-01 01:00:00.001+00:00'").eq(time));
651        assert!(query.get_result::<bool>(connection).unwrap());
652    }
653
654    #[test]
655    fn unix_epoch_encodes_correctly_with_utc_timezone() {
656        let connection = &mut connection();
657        let time: DateTime<Utc> = Utc
658            .with_ymd_and_hms(1970, 1, 1, 0, 0, 0)
659            .single()
660            .unwrap()
661            // 1ms
662            .with_nanosecond(1_000_000)
663            .unwrap();
664        let query = select(sql::<TimestamptzSqlite>("'1970-01-01 00:00:00.001+00:00'").eq(time));
665        assert!(query.get_result::<bool>(connection).unwrap());
666
667        // and without millisecond
668        let time: DateTime<Utc> = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap();
669        let query = select(sql::<TimestamptzSqlite>("'1970-01-01 00:00:00+00:00'").eq(time));
670        assert!(query.get_result::<bool>(connection).unwrap());
671    }
672
673    #[test]
674    fn unix_epoch_decodes_correctly_with_utc_timezone_in_all_possible_formats() {
675        let connection = &mut connection();
676        let time: DateTime<Utc> = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap();
677        let valid_epoch_formats = vec![
678            "1970-01-01 00:00Z",
679            "1970-01-01 00:00:00Z",
680            "1970-01-01 00:00:00.000Z",
681            "1970-01-01 00:00:00.000000Z",
682            "1970-01-01T00:00Z",
683            "1970-01-01T00:00:00Z",
684            "1970-01-01T00:00:00.000Z",
685            "1970-01-01T00:00:00.000000Z",
686            "1970-01-01 00:00+00:00",
687            "1970-01-01 00:00:00+00:00",
688            "1970-01-01 00:00:00.000+00:00",
689            "1970-01-01 00:00:00.000000+00:00",
690            "1970-01-01T00:00+00:00",
691            "1970-01-01T00:00:00+00:00",
692            "1970-01-01T00:00:00.000+00:00",
693            "1970-01-01T00:00:00.000000+00:00",
694            "2440587.5",
695        ];
696
697        for s in valid_epoch_formats {
698            let epoch_from_sql =
699                select(sql::<TimestamptzSqlite>(&format!("'{}'", s))).get_result(connection);
700            assert_eq!(Ok(time), epoch_from_sql, "format {} failed", s);
701        }
702    }
703}