Skip to main content

vortex_functions/
timestamp_to_time.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Extract the local time of day of a timestamp.
5//!
6//! The time zone applies as in [`timestamp_to_date`](crate::expr::timestamp_to_date), so the time of
7//! day is the local clock time.
8
9use vortex_array::ArrayRef;
10use vortex_array::ExecutionCtx;
11use vortex_array::dtype::DType;
12use vortex_array::extension::datetime::Time;
13use vortex_array::extension::datetime::Timestamp;
14use vortex_array::extension::datetime::local_count;
15use vortex_array::extension::datetime::map_counts;
16use vortex_array::extension::datetime::resolve_time_zone;
17use vortex_array::scalar_fn::Arity;
18use vortex_array::scalar_fn::ChildName;
19use vortex_array::scalar_fn::EmptyOptions;
20use vortex_array::scalar_fn::ExecutionArgs;
21use vortex_array::scalar_fn::ScalarFnId;
22use vortex_array::scalar_fn::ScalarFnVTable;
23use vortex_error::VortexExpect;
24use vortex_error::VortexResult;
25use vortex_error::vortex_bail;
26use vortex_session::VortexSession;
27use vortex_session::registry::CachedId;
28
29/// Extract the local time of day of a [`Timestamp`] as a [`Time`] in the same unit.
30///
31/// See [`timestamp_to_time`](crate::expr::timestamp_to_time) for the contract.
32#[derive(Clone)]
33pub struct TimestampToTime;
34
35impl ScalarFnVTable for TimestampToTime {
36    type Options = EmptyOptions;
37
38    fn id(&self) -> ScalarFnId {
39        static ID: CachedId = CachedId::new("vortex.timestamp_to_time");
40        *ID
41    }
42
43    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
44        Ok(Some(vec![]))
45    }
46
47    fn deserialize(
48        &self,
49        _metadata: &[u8],
50        _session: &VortexSession,
51    ) -> VortexResult<Self::Options> {
52        Ok(EmptyOptions)
53    }
54
55    fn arity(&self, _options: &Self::Options) -> Arity {
56        Arity::Exact(1)
57    }
58
59    fn child_name(&self, _options: &Self::Options, _child_idx: usize) -> ChildName {
60        ChildName::from("input")
61    }
62
63    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
64        let input = &arg_dtypes[0];
65        let Some(timestamp) = input
66            .as_extension_opt()
67            .and_then(|ext| ext.metadata_opt::<Timestamp>())
68        else {
69            vortex_bail!("Expected a timestamp, got {input}");
70        };
71
72        Ok(DType::Extension(
73            Time::try_new(timestamp.unit, input.nullability())?.erased(),
74        ))
75    }
76
77    fn execute(
78        &self,
79        options: &Self::Options,
80        args: &dyn ExecutionArgs,
81        ctx: &mut ExecutionCtx,
82    ) -> VortexResult<ArrayRef> {
83        let input = args.get(0)?;
84        let target = self.return_dtype(options, std::slice::from_ref(input.dtype()))?;
85        let timestamp = input
86            .dtype()
87            .as_extension_opt()
88            .and_then(|ext| ext.metadata_opt::<Timestamp>())
89            .vortex_expect("`return_dtype` above accepts only timestamps");
90        let unit = timestamp.unit;
91        let zone = timestamp
92            .tz
93            .as_deref()
94            .map(|zone| resolve_time_zone(Some(zone)))
95            .transpose()?;
96        let units_per_day = i128::from(unit.units_per_day());
97
98        map_counts(input, &target, ctx, |value| {
99            let local = local_count(value, unit, zone.as_ref())?;
100            Ok(i64::try_from(local.rem_euclid(units_per_day))?)
101        })
102    }
103
104    fn is_strict(&self, _options: &Self::Options) -> bool {
105        true
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use vortex_array::IntoArray;
112    use vortex_array::VortexSessionExecute;
113    use vortex_array::arrays::ExtensionArray;
114    use vortex_array::dtype::Nullability;
115    use vortex_array::extension::datetime::Time;
116    use vortex_array::extension::datetime::TimeUnit;
117    use vortex_array::extension::datetime::Timestamp;
118    use vortex_array::test_harness::ExpectedOutcome;
119    use vortex_array::test_harness::assert_execution_paths;
120    use vortex_buffer::buffer;
121    use vortex_error::VortexResult;
122    use vortex_expr::ArrayExprExt;
123    use vortex_expr::Expression;
124    use vortex_expr::proto::ExprSerializeProtoExt;
125    use vortex_expr::root;
126    use vortex_session::VortexSession;
127
128    use crate::expr::timestamp_to_time;
129
130    #[test]
131    fn test_timestamp_to_time_uses_zone_offset() -> VortexResult<()> {
132        let input = ExtensionArray::try_new(
133            Timestamp::new_with_tz(
134                TimeUnit::Seconds,
135                Some("America/New_York".into()),
136                Nullability::NonNullable,
137            )
138            .erased(),
139            buffer![
140                0i64,          // The epoch, which is 1969-12-31 19:00:00 EST in New York.
141                1_710_053_999, // 2024-03-10 01:59:59 EST, the last second before DST starts.
142                1_710_054_000, // 2024-03-10 03:00:00 EDT, after the offset moves from -5h to -4h.
143            ]
144            .into_array(),
145        )?;
146        let expected = ExtensionArray::try_new(
147            Time::new(TimeUnit::Seconds, Nullability::NonNullable).erased(),
148            buffer![68_400i32, 7_199, 10_800].into_array(),
149        )?;
150        let session = VortexSession::empty();
151        crate::initialize(&session);
152        let operation = timestamp_to_time(root());
153        let restored = Expression::from_proto(&operation.serialize_proto()?, &session)?;
154
155        assert_execution_paths(
156            &[input.into_array()],
157            |inputs| inputs[0].clone().apply(&restored),
158            ExpectedOutcome::Array(expected.into_array()),
159            &mut session.create_execution_ctx(),
160        );
161        Ok(())
162    }
163}