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 = select(sql::<Timestamp>(&format!("'{s}'"))).get_result(connection);
324            assert_eq!(Ok(time), epoch_from_sql, "format {s} failed");
325        }
326    }
327
328    #[test]
329    fn times_relative_to_now_encode_correctly() {
330        let connection = &mut connection();
331        let time = Utc::now().naive_utc() + Duration::try_seconds(60).unwrap();
332        let query = select(now.lt(time));
333        assert_eq!(Ok(true), query.get_result(connection));
334
335        let time = Utc::now().naive_utc() - Duration::try_seconds(600).unwrap();
336        let query = select(now.gt(time));
337        assert_eq!(Ok(true), query.get_result(connection));
338    }
339
340    #[test]
341    fn times_of_day_encode_correctly() {
342        let connection = &mut connection();
343
344        let midnight = NaiveTime::from_hms_opt(0, 0, 0).unwrap();
345        let query = select(time("00:00:00.000000").eq(midnight));
346        assert!(query.get_result::<bool>(connection).unwrap());
347
348        let noon = NaiveTime::from_hms_opt(12, 0, 0).unwrap();
349        let query = select(time("12:00:00.000000").eq(noon));
350        assert!(query.get_result::<bool>(connection).unwrap());
351
352        let roughly_half_past_eleven = NaiveTime::from_hms_micro_opt(23, 37, 4, 2200).unwrap();
353        let query = select(sql::<Time>("'23:37:04.002200'").eq(roughly_half_past_eleven));
354        assert!(query.get_result::<bool>(connection).unwrap());
355    }
356
357    #[test]
358    fn times_of_day_decode_correctly() {
359        let connection = &mut connection();
360        let midnight = NaiveTime::from_hms_opt(0, 0, 0).unwrap();
361        let valid_midnight_formats = &[
362            "00:00",
363            "00:00:00",
364            "00:00:00.000",
365            "00:00:00.000000",
366            "00:00Z",
367            "00:00:00Z",
368            "00:00:00.000Z",
369            "00:00:00.000000Z",
370            "00:00+00:00",
371            "00:00:00+00:00",
372            "00:00:00.000+00:00",
373            "00:00:00.000000+00:00",
374            "00:00+01:00",
375            "00:00:00+01:00",
376            "00:00:00.000+01:00",
377            "00:00:00.000000+01:00",
378            "00:00-01:00",
379            "00:00:00-01:00",
380            "00:00:00.000-01:00",
381            "00:00:00.000000-01:00",
382        ];
383        for format in valid_midnight_formats {
384            let query = select(sql::<Time>(&format!("'{format}'")));
385            assert_eq!(
386                Ok(midnight),
387                query.get_result::<NaiveTime>(connection),
388                "format {format} failed"
389            );
390        }
391
392        let noon = NaiveTime::from_hms_opt(12, 0, 0).unwrap();
393        let query = select(sql::<Time>("'12:00:00'"));
394        assert_eq!(Ok(noon), query.get_result::<NaiveTime>(connection));
395
396        let roughly_half_past_eleven = NaiveTime::from_hms_micro_opt(23, 37, 4, 2200).unwrap();
397        let query = select(sql::<Time>("'23:37:04.002200'"));
398        assert_eq!(
399            Ok(roughly_half_past_eleven),
400            query.get_result::<NaiveTime>(connection)
401        );
402    }
403
404    #[test]
405    fn dates_encode_correctly() {
406        let connection = &mut connection();
407        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
408        let query = select(date("2000-01-01").eq(january_first_2000));
409        assert!(query.get_result::<bool>(connection).unwrap());
410
411        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11).unwrap();
412        let query = select(date("0000-04-11").eq(distant_past));
413        assert!(query.get_result::<bool>(connection).unwrap());
414
415        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1).unwrap();
416        let query = select(date("2018-01-01").eq(january_first_2018));
417        assert!(query.get_result::<bool>(connection).unwrap());
418
419        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8).unwrap();
420        let query = select(date("9999-01-08").eq(distant_future));
421        assert!(query.get_result::<bool>(connection).unwrap());
422    }
423
424    #[test]
425    fn dates_decode_correctly() {
426        let connection = &mut connection();
427        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
428        let query = select(date("2000-01-01"));
429        assert_eq!(
430            Ok(january_first_2000),
431            query.get_result::<NaiveDate>(connection)
432        );
433
434        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11).unwrap();
435        let query = select(date("0000-04-11"));
436        assert_eq!(Ok(distant_past), query.get_result::<NaiveDate>(connection));
437
438        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1).unwrap();
439        let query = select(date("2018-01-01"));
440        assert_eq!(
441            Ok(january_first_2018),
442            query.get_result::<NaiveDate>(connection)
443        );
444
445        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8).unwrap();
446        let query = select(date("9999-01-08"));
447        assert_eq!(
448            Ok(distant_future),
449            query.get_result::<NaiveDate>(connection)
450        );
451    }
452
453    #[test]
454    fn datetimes_decode_correctly() {
455        let connection = &mut connection();
456        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1)
457            .unwrap()
458            .and_hms_opt(1, 1, 1)
459            .unwrap();
460        let query = select(datetime("2000-01-01 01:01:01.000000"));
461        assert_eq!(
462            Ok(january_first_2000),
463            query.get_result::<NaiveDateTime>(connection)
464        );
465
466        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11)
467            .unwrap()
468            .and_hms_opt(2, 2, 2)
469            .unwrap();
470        let query = select(datetime("0000-04-11 02:02:02.000000"));
471        assert_eq!(
472            Ok(distant_past),
473            query.get_result::<NaiveDateTime>(connection)
474        );
475
476        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1).unwrap();
477        let query = select(date("2018-01-01"));
478        assert_eq!(
479            Ok(january_first_2018),
480            query.get_result::<NaiveDate>(connection)
481        );
482
483        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8)
484            .unwrap()
485            .and_hms_opt(23, 59, 59)
486            .unwrap()
487            .with_nanosecond(100_000)
488            .unwrap();
489        let query = select(sql::<Timestamp>("'9999-01-08 23:59:59.000100'"));
490        assert_eq!(
491            Ok(distant_future),
492            query.get_result::<NaiveDateTime>(connection)
493        );
494    }
495
496    #[test]
497    fn datetimes_encode_correctly() {
498        let connection = &mut connection();
499        let january_first_2000 = NaiveDate::from_ymd_opt(2000, 1, 1)
500            .unwrap()
501            .and_hms_opt(0, 0, 0)
502            .unwrap();
503        let query = select(datetime("2000-01-01 00:00:00.000000").eq(january_first_2000));
504        assert!(query.get_result::<bool>(connection).unwrap());
505
506        let distant_past = NaiveDate::from_ymd_opt(0, 4, 11)
507            .unwrap()
508            .and_hms_opt(20, 00, 20)
509            .unwrap();
510        let query = select(datetime("0000-04-11 20:00:20.000000").eq(distant_past));
511        assert!(query.get_result::<bool>(connection).unwrap());
512
513        let january_first_2018 = NaiveDate::from_ymd_opt(2018, 1, 1)
514            .unwrap()
515            .and_hms_opt(12, 00, 00)
516            .unwrap()
517            .with_nanosecond(500_000)
518            .unwrap();
519        let query = select(sql::<Timestamp>("'2018-01-01 12:00:00.000500'").eq(january_first_2018));
520        assert!(query.get_result::<bool>(connection).unwrap());
521
522        let distant_future = NaiveDate::from_ymd_opt(9999, 1, 8)
523            .unwrap()
524            .and_hms_opt(0, 0, 0)
525            .unwrap();
526        let query = select(datetime("9999-01-08 00:00:00.000000").eq(distant_future));
527        assert!(query.get_result::<bool>(connection).unwrap());
528    }
529
530    #[test]
531    fn insert_timestamptz_into_table_as_text() {
532        crate::table! {
533            #[allow(unused_parens)]
534            test_insert_timestamptz_into_table_as_text(id) {
535                id -> Integer,
536                timestamp_with_tz -> TimestamptzSqlite,
537            }
538        }
539        let conn = &mut connection();
540        crate::sql_query(
541            "CREATE TABLE test_insert_timestamptz_into_table_as_text(id INTEGER PRIMARY KEY, timestamp_with_tz TEXT);",
542        )
543        .execute(conn)
544        .unwrap();
545
546        let time: DateTime<Utc> = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap();
547
548        crate::insert_into(test_insert_timestamptz_into_table_as_text::table)
549            .values(vec![(
550                test_insert_timestamptz_into_table_as_text::id.eq(1),
551                test_insert_timestamptz_into_table_as_text::timestamp_with_tz.eq(sql::<
552                    TimestamptzSqlite,
553                >(
554                    "'1970-01-01 00:00:00.000000+00:00'",
555                )),
556            )])
557            .execute(conn)
558            .unwrap();
559
560        let result = test_insert_timestamptz_into_table_as_text::table
561            .select(test_insert_timestamptz_into_table_as_text::timestamp_with_tz)
562            .get_result::<DateTime<Utc>>(conn)
563            .unwrap();
564        assert_eq!(result, time);
565    }
566
567    #[test]
568    fn can_query_timestamptz_column_with_between() {
569        crate::table! {
570            #[allow(unused_parens)]
571            test_query_timestamptz_column_with_between(id) {
572                id -> Integer,
573                timestamp_with_tz -> TimestamptzSqlite,
574            }
575        }
576        let conn = &mut connection();
577        crate::sql_query(
578            "CREATE TABLE test_query_timestamptz_column_with_between(id INTEGER PRIMARY KEY, timestamp_with_tz TEXT);",
579        )
580        .execute(conn)
581        .unwrap();
582
583        crate::insert_into(test_query_timestamptz_column_with_between::table)
584            .values(vec![
585                (
586                    test_query_timestamptz_column_with_between::id.eq(1),
587                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
588                        TimestamptzSqlite,
589                    >(
590                        "'1970-01-01 00:00:01.000000+00:00'",
591                    )),
592                ),
593                (
594                    test_query_timestamptz_column_with_between::id.eq(2),
595                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
596                        TimestamptzSqlite,
597                    >(
598                        "'1970-01-01 00:00:02.000000+00:00'",
599                    )),
600                ),
601                (
602                    test_query_timestamptz_column_with_between::id.eq(3),
603                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
604                        TimestamptzSqlite,
605                    >(
606                        "'1970-01-01 00:00:03.000000+00:00'",
607                    )),
608                ),
609                (
610                    test_query_timestamptz_column_with_between::id.eq(4),
611                    test_query_timestamptz_column_with_between::timestamp_with_tz.eq(sql::<
612                        TimestamptzSqlite,
613                    >(
614                        "'1970-01-01 00:00:04.000000+00:00'",
615                    )),
616                ),
617            ])
618            .execute(conn)
619            .unwrap();
620
621        let result = test_query_timestamptz_column_with_between::table
622            .select(test_query_timestamptz_column_with_between::timestamp_with_tz)
623            .filter(
624                test_query_timestamptz_column_with_between::timestamp_with_tz
625                    .gt(Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap()),
626            )
627            .filter(
628                test_query_timestamptz_column_with_between::timestamp_with_tz
629                    .lt(Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 4).single().unwrap()),
630            )
631            .count()
632            .get_result::<_>(conn);
633        assert_eq!(result, Ok(3));
634    }
635
636    #[test]
637    fn unix_epoch_encodes_correctly_with_timezone() {
638        let connection = &mut connection();
639        // West one hour is negative offset
640        let time = FixedOffset::west_opt(3600)
641            .unwrap()
642            .with_ymd_and_hms(1970, 1, 1, 0, 0, 0)
643            .single()
644            .unwrap()
645            // 1ms
646            .with_nanosecond(1_000_000)
647            .unwrap();
648        let query = select(sql::<TimestamptzSqlite>("'1970-01-01 01:00:00.001+00:00'").eq(time));
649        assert!(query.get_result::<bool>(connection).unwrap());
650    }
651
652    #[test]
653    fn unix_epoch_encodes_correctly_with_utc_timezone() {
654        let connection = &mut connection();
655        let time: DateTime<Utc> = Utc
656            .with_ymd_and_hms(1970, 1, 1, 0, 0, 0)
657            .single()
658            .unwrap()
659            // 1ms
660            .with_nanosecond(1_000_000)
661            .unwrap();
662        let query = select(sql::<TimestamptzSqlite>("'1970-01-01 00:00:00.001+00:00'").eq(time));
663        assert!(query.get_result::<bool>(connection).unwrap());
664
665        // and without millisecond
666        let time: DateTime<Utc> = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap();
667        let query = select(sql::<TimestamptzSqlite>("'1970-01-01 00:00:00+00:00'").eq(time));
668        assert!(query.get_result::<bool>(connection).unwrap());
669    }
670
671    #[test]
672    fn unix_epoch_decodes_correctly_with_utc_timezone_in_all_possible_formats() {
673        let connection = &mut connection();
674        let time: DateTime<Utc> = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).single().unwrap();
675        let valid_epoch_formats = vec![
676            "1970-01-01 00:00Z",
677            "1970-01-01 00:00:00Z",
678            "1970-01-01 00:00:00.000Z",
679            "1970-01-01 00:00:00.000000Z",
680            "1970-01-01T00:00Z",
681            "1970-01-01T00:00:00Z",
682            "1970-01-01T00:00:00.000Z",
683            "1970-01-01T00:00:00.000000Z",
684            "1970-01-01 00:00+00:00",
685            "1970-01-01 00:00:00+00:00",
686            "1970-01-01 00:00:00.000+00:00",
687            "1970-01-01 00:00:00.000000+00:00",
688            "1970-01-01T00:00+00:00",
689            "1970-01-01T00:00:00+00:00",
690            "1970-01-01T00:00:00.000+00:00",
691            "1970-01-01T00:00:00.000000+00:00",
692            "2440587.5",
693        ];
694
695        for s in valid_epoch_formats {
696            let epoch_from_sql =
697                select(sql::<TimestamptzSqlite>(&format!("'{s}'"))).get_result(connection);
698            assert_eq!(Ok(time), epoch_from_sql, "format {s} failed");
699        }
700    }
701}