Skip to main content

zu_vector/kernels/
temporal.rs

1//! The length of time between two instants, GF of ISO 20.28.
2//!
3//! Both spellings are here, the one that counts in days and smaller and
4//! the one that counts in months and larger, and they are not the same
5//! kind of work. A day-time duration is a subtraction: every operand is
6//! a count of nanoseconds once a date has been multiplied out to one,
7//! so the answer is the difference of two words and the loop is the
8//! loop a subtraction of two numbers gets. A year-month duration is a
9//! walk over the calendar, because the count it wants is a number of
10//! months and months are of different lengths, so there is no scaling
11//! that turns one into the other and the answer has to be read off the
12//! civil date and then corrected by a step.
13//!
14//! What both have in common is that the type is settled before the loop
15//! starts. The op carries the type both operands hold, so the choice
16//! between a scale of one and a scale of a day's worth of nanoseconds
17//! is made once a chunk rather than once a row, and no value in the
18//! loop carries a tag for the loop to read.
19//!
20//! The conditions are the row engine's, in the row engine's words. A
21//! pair with no duration between them raises `22G03`, and that is not
22//! an edge case reached only by absurd input: a date is days and a
23//! day-time duration is nanoseconds, so any date more than about two
24//! hundred and ninety years from the epoch has no day-time duration to
25//! anything at all. The compute loop uses checked arithmetic and notes
26//! that some row had no answer; only then does a second walk go over
27//! the selection to find which row it was, since a row the selection
28//! dropped is a row the row engine never evaluated and has no condition
29//! to raise.
30
31use zu_common::types::LogicalType;
32use zu_common::{DurationKind, Result, Temporal, ZuError, gqlstatus::codes};
33
34use crate::arena::MorselArena;
35use crate::bitmap::Bitmap;
36use crate::sel::SelVector;
37use crate::vector::{PhysType, ValueVector, VecEncoding};
38
39/// The words of an operand, however it is encoded.
40///
41/// A constant is one word standing for the whole chunk, which is what a
42/// literal instant arrives as, and it is worth reading through the same
43/// hole as a stored column rather than writing the loop twice for it:
44/// the branch is on a value that does not change across the chunk, so
45/// it costs a prediction and nothing else, and this loop is doing
46/// checked arithmetic rather than something a branch would spoil.
47#[derive(Clone, Copy)]
48enum Words<'a> {
49    Flat(&'a [i64]),
50    Const(i64),
51}
52
53impl Words<'_> {
54    #[inline(always)]
55    fn at(self, row: usize) -> i64 {
56        match self {
57            Words::Flat(v) => v[row],
58            Words::Const(c) => c,
59        }
60    }
61}
62
63fn words<'a>(v: &'a ValueVector, len: usize) -> Result<Words<'a>> {
64    match v.encoding {
65        VecEncoding::Flat => Ok(Words::Flat(&v.values::<i64>()[..len])),
66        VecEncoding::Constant => Ok(Words::Const(v.constant_value::<i64>())),
67        VecEncoding::Dict { .. } => Err(ZuError::InvalidArgument(
68            "a dictionary holds strings and an instant is not one".into(),
69        )),
70    }
71}
72
73/// How many nanoseconds one of this type's words is worth, for the
74/// types whose words are a count of something a day-time duration also
75/// counts.
76///
77/// A date is days and everything else here is nanoseconds already, so
78/// this is a day or it is one. It is the whole of the difference
79/// between the three day-time loops, which is why there is one loop
80/// rather than three.
81fn scale(of: &LogicalType) -> Option<i64> {
82    match of {
83        LogicalType::Date => Some(zu_common::temporal::NANOS_PER_DAY),
84        LogicalType::LocalTime | LogicalType::LocalDatetime => Some(1),
85        _ => None,
86    }
87}
88
89/// The value one word stands for, at the type the operands hold.
90fn maker(of: &LogicalType) -> Option<fn(i64) -> Temporal> {
91    match of {
92        LogicalType::Date => Some(|w| Temporal::Date(w as i32)),
93        LogicalType::LocalTime => Some(Temporal::LocalTime),
94        LogicalType::LocalDatetime => Some(Temporal::LocalDatetime),
95        _ => None,
96    }
97}
98
99/// The duration that carries `from` to `to`, over two vectors of the
100/// same temporal type.
101///
102/// `of` is that type, which the compiler read off the columns and both
103/// operands share. `sel` is the chunk's selection, which is what the
104/// conditions are raised over and nothing else reads.
105pub fn duration_between(
106    arena: &mut MorselArena,
107    of: &LogicalType,
108    kind: DurationKind,
109    from: &ValueVector,
110    to: &ValueVector,
111    sel: Option<&SelVector>,
112) -> Result<ValueVector> {
113    debug_assert_eq!(from.len, to.len);
114    if from.phys != to.phys {
115        return Err(ZuError::InvalidArgument(format!(
116            "no duration between {:?} and {:?}",
117            from.phys, to.phys
118        )));
119    }
120    let len = from.len as usize;
121    let (a, b) = (words(from, len)?, words(to, len)?);
122    let mut out = ValueVector::flat_uninit(arena, PhysType::Interval, len);
123    let mut short = false;
124    {
125        let dst = out.values_mut::<i64>();
126        match kind {
127            DurationKind::DayTime => {
128                let Some(scale) = scale(of) else {
129                    return Err(ZuError::InvalidArgument(format!(
130                        "no day-time duration kernel over {of:?}"
131                    )));
132                };
133                for (row, out) in dst.iter_mut().enumerate().take(len) {
134                    match count_nanos(a.at(row), b.at(row), scale) {
135                        Some(n) => *out = n,
136                        None => {
137                            *out = 0;
138                            short = true;
139                        }
140                    }
141                }
142            }
143            DurationKind::YearMonth => {
144                let Some(make) = maker(of) else {
145                    return Err(ZuError::InvalidArgument(format!(
146                        "no year-month duration kernel over {of:?}"
147                    )));
148                };
149                for (row, out) in dst.iter_mut().enumerate().take(len) {
150                    match count_months(make, a.at(row), b.at(row)) {
151                        Some(n) => *out = n,
152                        None => {
153                            *out = 0;
154                            short = true;
155                        }
156                    }
157                }
158            }
159        }
160    }
161    out.validity = merged(arena, from, to, len);
162    if short {
163        raise(of, kind, a, b, &out, sel, len)?;
164    }
165    Ok(out)
166}
167
168/// The nanoseconds from one word to another, both counts of `scale`
169/// nanoseconds apiece.
170///
171/// Each side is scaled before the subtraction rather than the
172/// difference being scaled after it, which matters and is not a
173/// rearrangement: a date in the year nine thousand is not a number of
174/// nanoseconds at all, so the pair has no day-time duration between
175/// them even where the gap between the two would have fitted. That is
176/// what the row engine answers, and scaling the difference would have
177/// answered a number instead.
178#[inline(always)]
179fn count_nanos(from: i64, to: i64, scale: i64) -> Option<i64> {
180    to.checked_mul(scale)?.checked_sub(from.checked_mul(scale)?)
181}
182
183/// The months from one word to another, off the calendar.
184#[inline(always)]
185fn count_months(make: fn(i64) -> Temporal, from: i64, to: i64) -> Option<i64> {
186    match Temporal::between(make(from), make(to), DurationKind::YearMonth) {
187        Some(Temporal::Duration(_, months)) => Some(months),
188        _ => None,
189    }
190}
191
192/// The condition, once the compute loop has said that some row had no
193/// answer.
194///
195/// Which row it was is found by walking the selection, because a row
196/// outside it was computed for the loop's sake and is none of the
197/// query's business. Where every row that had no answer is a row nobody
198/// selected, or is null, there is no condition and this returns.
199fn raise(
200    of: &LogicalType,
201    kind: DurationKind,
202    a: Words<'_>,
203    b: Words<'_>,
204    out: &ValueVector,
205    sel: Option<&SelVector>,
206    len: usize,
207) -> Result<()> {
208    let make = maker(of).ok_or_else(|| {
209        ZuError::InvalidArgument(format!("no duration between two values of {of:?}"))
210    })?;
211    let scale = scale(of);
212    let check = |row: usize| -> Result<()> {
213        if out.validity.as_ref().is_some_and(|v| !v.get(row)) {
214            return Ok(());
215        }
216        let (from, to) = (a.at(row), b.at(row));
217        let answered = match kind {
218            DurationKind::DayTime => count_nanos(from, to, scale.unwrap_or(1)).is_some(),
219            DurationKind::YearMonth => count_months(make, from, to).is_some(),
220        };
221        if answered {
222            return Ok(());
223        }
224        let (from, to) = (make(from), make(to));
225        Err(ZuError::gql(
226            codes::C22G03,
227            format!(
228                "there is no {} from {from} to {to}",
229                LogicalType::Duration(kind)
230            ),
231        ))
232    };
233    match sel {
234        Some(sel) => {
235            for &row in sel.as_slice() {
236                check(row as usize)?;
237            }
238        }
239        None => {
240            for row in 0..len {
241                check(row)?;
242            }
243        }
244    }
245    Ok(())
246}
247
248/// Valid where both operands are, which is where a null answers a null.
249fn merged(arena: &mut MorselArena, l: &ValueVector, r: &ValueVector, len: usize) -> Option<Bitmap> {
250    match (&l.validity, &r.validity) {
251        (None, None) => None,
252        (a, b) => {
253            let mut v = Bitmap::new_in(arena, len, true);
254            if let Some(a) = a {
255                v.and_with(a);
256            }
257            if let Some(b) = b {
258                v.and_with(b);
259            }
260            Some(v)
261        }
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    const DAY: i64 = 86_400_000_000_000;
270
271    fn between(of: &LogicalType, kind: DurationKind, from: &[i64], to: &[i64]) -> Result<Vec<i64>> {
272        let mut arena = MorselArena::new();
273        let a = ValueVector::flat_from(&mut arena, PhysType::Date, from);
274        let b = ValueVector::flat_from(&mut arena, PhysType::Date, to);
275        let out = duration_between(&mut arena, of, kind, &a, &b, None)?;
276        Ok(out.values::<i64>()[..from.len()].to_vec())
277    }
278
279    #[test]
280    fn a_day_time_duration_between_two_dates_is_the_days_in_nanoseconds() {
281        let got = between(
282            &LogicalType::Date,
283            DurationKind::DayTime,
284            &[0, 10, -5],
285            &[1, 3, 5],
286        )
287        .unwrap();
288        assert_eq!(got, vec![DAY, -7 * DAY, 10 * DAY]);
289    }
290
291    #[test]
292    fn a_day_time_duration_between_two_datetimes_is_the_difference() {
293        let got = between(
294            &LogicalType::LocalDatetime,
295            DurationKind::DayTime,
296            &[0, 1_000],
297            &[DAY, 400],
298        )
299        .unwrap();
300        assert_eq!(got, vec![DAY, -600]);
301    }
302
303    /// A date the calendar has and a day-time duration cannot reach.
304    /// The gap between the two below is one day, and the answer is
305    /// still a condition, because neither of them is a number of
306    /// nanoseconds on its own.
307    #[test]
308    fn a_date_too_far_out_has_no_day_time_duration_to_anything() {
309        let err = between(
310            &LogicalType::Date,
311            DurationKind::DayTime,
312            &[2_000_000],
313            &[2_000_001],
314        )
315        .unwrap_err();
316        assert!(
317            err.to_string().contains("there is no"),
318            "expected a 22G03, got {err}"
319        );
320    }
321
322    #[test]
323    fn a_year_month_duration_counts_whole_months() {
324        // 1970-01-01 to 1971-03-01 is fourteen months, and one day
325        // short of it is thirteen, since the count is of whole months.
326        let got = between(
327            &LogicalType::Date,
328            DurationKind::YearMonth,
329            &[0, 0],
330            &[424, 423],
331        )
332        .unwrap();
333        assert_eq!(got, vec![14, 13]);
334    }
335
336    /// A row the selection dropped was computed and is not the query's,
337    /// so a pair with no answer there raises nothing.
338    #[test]
339    fn a_row_outside_the_selection_raises_nothing() {
340        let mut arena = MorselArena::new();
341        let a = ValueVector::flat_from(&mut arena, PhysType::Date, &[0i64, 2_000_000]);
342        let b = ValueVector::flat_from(&mut arena, PhysType::Date, &[1i64, 2_000_001]);
343        let mut sel = SelVector::with_capacity(&mut arena, 1);
344        sel.push(0);
345        let out = duration_between(
346            &mut arena,
347            &LogicalType::Date,
348            DurationKind::DayTime,
349            &a,
350            &b,
351            Some(&sel),
352        )
353        .expect("the selected row has an answer");
354        assert_eq!(out.values::<i64>()[0], DAY);
355    }
356}