Skip to main content

vortex_functions/
timestamp_to_date.rs

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