Skip to main content

arrow_schema/extension/canonical/
timestamp_with_offset.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Timestamp with an offset in minutes
6//!
7//! <https://arrow.apache.org/docs/format/CanonicalExtensions.html#timestamp-with-offset>
8
9use crate::{ArrowError, DataType, extension::ExtensionType};
10
11/// The extension type for `TimestampWithOffset`.
12///
13/// Extension name: `arrow.timestamp_with_offset`.
14///
15/// This type represents a timestamp column that stores potentially different timezone offsets per
16/// value. The timestamp is stored in UTC alongside the original timezone offset in minutes. This
17/// extension type is intended to be compatible with ANSI SQL's `TIMESTAMP WITH TIME ZONE`, which
18/// is supported by multiple database engines.
19///
20/// The storage type of the extension is a `Struct` with 2 fields, in order: - `timestamp`: a
21/// non-nullable `Timestamp(time_unit, "UTC")`, where `time_unit` is any Arrow `TimeUnit` (s, ms,
22/// us or ns). - `offset_minutes`: a non-nullable signed 16-bit integer (`Int16`) representing the
23/// offset in minutes from the UTC timezone. Negative offsets represent time zones west of UTC,
24/// while positive offsets represent east. Offsets normally range from -779 (-12:59) to +780
25/// (+13:00).
26///
27/// This type has no type parameters.
28///
29/// Metadata is either empty or an empty string.
30///
31/// It is also *permissible* for the `offset_minutes` field to be dictionary-encoded with a
32/// preferred (*but not required*) index type of `int8`, or run-end-encoded with a preferred (*but
33/// not required*) runs type of `int8`.
34///
35/// It's worth noting that the data source needs to resolve timezone strings such as `UTC` or
36/// `Americas/Los_Angeles` into an offset in minutes in order to construct a `TimestampWithOffset`.
37/// This makes `TimestampWithOffset` type "lossy" in the sense that any original "unresolved"
38/// timezone string gets lost in this conversion. It's a tradeoff for optimizing the row
39/// representation and simplifying the client code, which does not need to know how to convert from
40/// timezone string to its corresponding offset in minutes.
41///
42/// <https://arrow.apache.org/docs/format/CanonicalExtensions.html#timestamp-with-offset>
43#[derive(Debug, Default, Clone, Copy, PartialEq)]
44pub struct TimestampWithOffset;
45
46const TIMESTAMP_FIELD_NAME: &str = "timestamp";
47const OFFSET_FIELD_NAME: &str = "offset_minutes";
48
49impl ExtensionType for TimestampWithOffset {
50    const NAME: &'static str = "arrow.timestamp_with_offset";
51
52    type Metadata = ();
53
54    fn metadata(&self) -> &Self::Metadata {
55        &()
56    }
57
58    fn serialize_metadata(&self) -> Option<String> {
59        None
60    }
61
62    fn deserialize_metadata(metadata: Option<&str>) -> Result<Self::Metadata, ArrowError> {
63        metadata.map_or_else(
64            || Ok(()),
65            |v| {
66                if !v.is_empty() {
67                    Err(ArrowError::InvalidArgumentError(
68                        "TimestampWithOffset extension type expects no metadata".to_owned(),
69                    ))
70                } else {
71                    Ok(())
72                }
73            },
74        )
75    }
76
77    fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> {
78        let ok = match data_type {
79            DataType::Struct(fields) => match fields.len() {
80                2 => {
81                    let maybe_timestamp = fields.first().unwrap();
82                    let maybe_offset = fields.get(1).unwrap();
83
84                    let timestamp_type_ok = matches!(maybe_timestamp.data_type(), DataType::Timestamp(_, tz) if {
85                        match tz {
86                            Some(tz) => {
87                                tz.as_ref() == "UTC"
88                            },
89                            None => false
90                        }
91                    });
92
93                    let offset_type_ok = match maybe_offset.data_type() {
94                        DataType::Int16 => true,
95                        DataType::Dictionary(key_type, value_type) => {
96                            key_type.is_dictionary_key_type()
97                                && matches!(value_type.as_ref(), DataType::Int16)
98                        }
99                        DataType::RunEndEncoded(run_ends, values) => {
100                            run_ends.data_type().is_run_ends_type()
101                                && matches!(values.data_type(), DataType::Int16)
102                        }
103                        _ => false,
104                    };
105
106                    maybe_timestamp.name() == TIMESTAMP_FIELD_NAME
107                        && timestamp_type_ok
108                        && !maybe_timestamp.is_nullable()
109                        && maybe_offset.name() == OFFSET_FIELD_NAME
110                        && offset_type_ok
111                        && !maybe_offset.is_nullable()
112                }
113                _ => false,
114            },
115            _ => false,
116        };
117
118        match ok {
119            true => Ok(()),
120            false => Err(ArrowError::InvalidArgumentError(format!(
121                "TimestampWithOffset data type mismatch, expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found {data_type}"
122            ))),
123        }
124    }
125
126    fn try_new(data_type: &DataType, _metadata: Self::Metadata) -> Result<Self, ArrowError> {
127        Self.supports_data_type(data_type).map(|()| Self)
128    }
129
130    fn validate(data_type: &DataType, _metadata: Self::Metadata) -> Result<(), ArrowError> {
131        Self.supports_data_type(data_type)
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use std::sync::Arc;
138
139    #[cfg(feature = "canonical_extension_types")]
140    use crate::extension::CanonicalExtensionType;
141    use crate::{
142        Field, Fields, TimeUnit,
143        extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY},
144    };
145
146    use super::*;
147    use rstest::rstest;
148
149    fn make_valid_field_primitive(time_unit: TimeUnit) -> Field {
150        Field::new(
151            "",
152            DataType::Struct(Fields::from_iter([
153                Field::new(
154                    TIMESTAMP_FIELD_NAME,
155                    DataType::Timestamp(time_unit, Some("UTC".into())),
156                    false,
157                ),
158                Field::new(OFFSET_FIELD_NAME, DataType::Int16, false),
159            ])),
160            false,
161        )
162    }
163
164    fn make_valid_field_dict_encoded(time_unit: TimeUnit, key_type: DataType) -> Field {
165        assert!(key_type.is_dictionary_key_type());
166
167        Field::new(
168            "",
169            DataType::Struct(Fields::from_iter([
170                Field::new(
171                    TIMESTAMP_FIELD_NAME,
172                    DataType::Timestamp(time_unit, Some("UTC".into())),
173                    false,
174                ),
175                Field::new(
176                    OFFSET_FIELD_NAME,
177                    DataType::Dictionary(Box::new(key_type), Box::new(DataType::Int16)),
178                    false,
179                ),
180            ])),
181            false,
182        )
183    }
184
185    fn make_valid_field_run_end_encoded(time_unit: TimeUnit, run_ends_type: DataType) -> Field {
186        assert!(run_ends_type.is_run_ends_type());
187        Field::new(
188            "",
189            DataType::Struct(Fields::from_iter([
190                Field::new(
191                    TIMESTAMP_FIELD_NAME,
192                    DataType::Timestamp(time_unit, Some("UTC".into())),
193                    false,
194                ),
195                Field::new(
196                    OFFSET_FIELD_NAME,
197                    DataType::RunEndEncoded(
198                        Arc::new(Field::new(
199                            Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
200                            run_ends_type,
201                            false,
202                        )),
203                        Arc::new(Field::new(
204                            Field::REE_VALUES_FIELD_DEFAULT_NAME,
205                            DataType::Int16,
206                            false,
207                        )),
208                    ),
209                    false,
210                ),
211            ])),
212            false,
213        )
214    }
215
216    #[test]
217    fn valid_primitive_offsets() -> Result<(), ArrowError> {
218        let time_units = [
219            TimeUnit::Second,
220            TimeUnit::Millisecond,
221            TimeUnit::Microsecond,
222            TimeUnit::Nanosecond,
223        ];
224
225        for time_unit in time_units {
226            let mut field = make_valid_field_primitive(time_unit);
227            field.try_with_extension_type(TimestampWithOffset)?;
228            field.try_extension_type::<TimestampWithOffset>()?;
229            #[cfg(feature = "canonical_extension_types")]
230            assert_eq!(
231                field.try_canonical_extension_type()?,
232                CanonicalExtensionType::TimestampWithOffset(TimestampWithOffset)
233            );
234        }
235
236        Ok(())
237    }
238
239    #[test]
240    fn valid_dict_encoded_offsets() -> Result<(), ArrowError> {
241        let time_units = [
242            TimeUnit::Second,
243            TimeUnit::Millisecond,
244            TimeUnit::Microsecond,
245            TimeUnit::Nanosecond,
246        ];
247
248        let key_types = [
249            DataType::UInt8,
250            DataType::UInt16,
251            DataType::UInt32,
252            DataType::UInt64,
253            DataType::Int8,
254            DataType::Int16,
255            DataType::Int32,
256            DataType::Int64,
257        ];
258
259        for time_unit in time_units {
260            for key_type in &key_types {
261                let mut field = make_valid_field_dict_encoded(time_unit, key_type.clone());
262                field.try_with_extension_type(TimestampWithOffset)?;
263                field.try_extension_type::<TimestampWithOffset>()?;
264                #[cfg(feature = "canonical_extension_types")]
265                assert_eq!(
266                    field.try_canonical_extension_type()?,
267                    CanonicalExtensionType::TimestampWithOffset(TimestampWithOffset)
268                );
269            }
270        }
271
272        Ok(())
273    }
274
275    #[test]
276    fn valid_run_end_encoded_offsets() -> Result<(), ArrowError> {
277        let time_units = [
278            TimeUnit::Second,
279            TimeUnit::Millisecond,
280            TimeUnit::Microsecond,
281            TimeUnit::Nanosecond,
282        ];
283
284        let run_ends_types = [DataType::Int16, DataType::Int32, DataType::Int64];
285
286        for time_unit in time_units {
287            for run_ends_type in &run_ends_types {
288                let mut field = make_valid_field_run_end_encoded(time_unit, run_ends_type.clone());
289                field.try_with_extension_type(TimestampWithOffset)?;
290                field.try_extension_type::<TimestampWithOffset>()?;
291                #[cfg(feature = "canonical_extension_types")]
292                assert_eq!(
293                    field.try_canonical_extension_type()?,
294                    CanonicalExtensionType::TimestampWithOffset(TimestampWithOffset)
295                );
296            }
297        }
298
299        Ok(())
300    }
301
302    #[test]
303    #[should_panic(expected = "Extension type name missing")]
304    fn missing_name() {
305        let field = make_valid_field_primitive(TimeUnit::Second)
306            .with_metadata([(EXTENSION_TYPE_METADATA_KEY, "")]);
307        field.extension_type::<TimestampWithOffset>();
308    }
309
310    #[test]
311    #[should_panic(
312        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Boolean"
313    )]
314    fn invalid_type_top_level() {
315        Field::new("", DataType::Boolean, false).with_extension_type(TimestampWithOffset);
316    }
317
318    #[test]
319    #[should_panic(
320        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Struct"
321    )]
322    fn invalid_type_struct_field_count() {
323        let data_type =
324            DataType::Struct(Fields::from_iter([Field::new("", DataType::Int16, false)]));
325        Field::new("", data_type, false).with_extension_type(TimestampWithOffset);
326    }
327
328    #[test]
329    #[should_panic(
330        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Struct"
331    )]
332    fn invalid_type_wrong_timestamp_type() {
333        let data_type = DataType::Struct(Fields::from_iter([
334            Field::new(TIMESTAMP_FIELD_NAME, DataType::Int16, false),
335            Field::new(OFFSET_FIELD_NAME, DataType::Int16, false),
336        ]));
337        Field::new("", data_type, false).with_extension_type(TimestampWithOffset);
338    }
339
340    #[rstest]
341    #[case::primitive(DataType::UInt64)]
342    #[case::dictionary_key(DataType::Dictionary(
343        Box::new(DataType::Boolean),
344        Box::new(DataType::Int16)
345    ))]
346    #[case::dictionary_value(DataType::Dictionary(
347        Box::new(DataType::UInt8),
348        Box::new(DataType::Int32)
349    ))]
350    #[should_panic(
351        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Struct"
352    )]
353    fn invalid_type_wrong_offset_type(#[case] offset_type: DataType) {
354        let data_type = DataType::Struct(Fields::from_iter([
355            Field::new(
356                TIMESTAMP_FIELD_NAME,
357                DataType::Timestamp(TimeUnit::Second, Some("UTC".into())),
358                false,
359            ),
360            Field::new(OFFSET_FIELD_NAME, offset_type, false),
361        ]));
362        Field::new("", data_type, false).with_extension_type(TimestampWithOffset);
363    }
364
365    #[test]
366    #[should_panic(
367        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Struct"
368    )]
369    fn invalid_type_wrong_run_ends_run_end_encoded() {
370        let data_type = DataType::Struct(Fields::from_iter([
371            Field::new(
372                TIMESTAMP_FIELD_NAME,
373                DataType::Timestamp(TimeUnit::Second, Some("UTC".into())),
374                false,
375            ),
376            Field::new(
377                OFFSET_FIELD_NAME,
378                DataType::RunEndEncoded(
379                    Arc::new(Field::new(
380                        Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
381                        DataType::Boolean,
382                        false,
383                    )),
384                    Arc::new(Field::new(
385                        Field::REE_VALUES_FIELD_DEFAULT_NAME,
386                        DataType::Int16,
387                        false,
388                    )),
389                ),
390                false,
391            ),
392        ]));
393        Field::new("", data_type, false).with_extension_type(TimestampWithOffset);
394    }
395
396    #[test]
397    #[should_panic(
398        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Struct"
399    )]
400    fn invalid_type_wrong_values_run_end_encoded() {
401        let data_type = DataType::Struct(Fields::from_iter([
402            Field::new(
403                TIMESTAMP_FIELD_NAME,
404                DataType::Timestamp(TimeUnit::Second, Some("UTC".into())),
405                false,
406            ),
407            Field::new(
408                OFFSET_FIELD_NAME,
409                DataType::RunEndEncoded(
410                    Arc::new(Field::new(
411                        Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
412                        DataType::UInt16,
413                        false,
414                    )),
415                    Arc::new(Field::new(
416                        Field::REE_VALUES_FIELD_DEFAULT_NAME,
417                        DataType::Int32,
418                        false,
419                    )),
420                ),
421                false,
422            ),
423        ]));
424        Field::new("", data_type, false).with_extension_type(TimestampWithOffset);
425    }
426
427    #[rstest]
428    #[case::timestamp(true, false)]
429    #[case::offset(false, true)]
430    #[should_panic(
431        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Struct"
432    )]
433    fn invalid_type_nullable_field(
434        #[case] timestamp_nullable: bool,
435        #[case] offset_nullable: bool,
436    ) {
437        let data_type = DataType::Struct(Fields::from_iter([
438            Field::new(
439                TIMESTAMP_FIELD_NAME,
440                DataType::Timestamp(TimeUnit::Second, Some("UTC".into())),
441                timestamp_nullable,
442            ),
443            Field::new(OFFSET_FIELD_NAME, DataType::Int16, offset_nullable),
444        ]));
445        Field::new("", data_type, false).with_extension_type(TimestampWithOffset);
446    }
447
448    #[rstest]
449    #[case::missing(None)]
450    #[case::non_utc(Some("Americas/Sao_Paulo".into()))]
451    #[should_panic(
452        expected = "expected Struct(\"timestamp\": Timestamp(_, Some(\"UTC\")), \"offset_minutes\": Int16), found Struct"
453    )]
454    fn invalid_type_timezone(#[case] timezone: Option<Arc<str>>) {
455        let data_type = DataType::Struct(Fields::from_iter([
456            Field::new(
457                TIMESTAMP_FIELD_NAME,
458                DataType::Timestamp(TimeUnit::Second, timezone),
459                false,
460            ),
461            Field::new(OFFSET_FIELD_NAME, DataType::Int16, false),
462        ]));
463        Field::new("", data_type, false).with_extension_type(TimestampWithOffset);
464    }
465
466    #[test]
467    fn no_metadata() {
468        let field = make_valid_field_primitive(TimeUnit::Second)
469            .with_metadata([(EXTENSION_TYPE_NAME_KEY, TimestampWithOffset::NAME)]);
470        field.extension_type::<TimestampWithOffset>();
471    }
472
473    #[test]
474    fn empty_metadata() {
475        let field = make_valid_field_primitive(TimeUnit::Second).with_metadata([
476            (EXTENSION_TYPE_NAME_KEY, TimestampWithOffset::NAME),
477            (EXTENSION_TYPE_METADATA_KEY, ""),
478        ]);
479        field.extension_type::<TimestampWithOffset>();
480    }
481}