1use 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#[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
73fn 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
89fn 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
99pub 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#[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#[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
192fn 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
248fn 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 #[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 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 #[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}