use zu_common::types::LogicalType;
use zu_common::{DurationKind, Result, Temporal, ZuError, gqlstatus::codes};
use crate::arena::MorselArena;
use crate::bitmap::Bitmap;
use crate::sel::SelVector;
use crate::vector::{PhysType, ValueVector, VecEncoding};
#[derive(Clone, Copy)]
enum Words<'a> {
Flat(&'a [i64]),
Const(i64),
}
impl Words<'_> {
#[inline(always)]
fn at(self, row: usize) -> i64 {
match self {
Words::Flat(v) => v[row],
Words::Const(c) => c,
}
}
}
fn words<'a>(v: &'a ValueVector, len: usize) -> Result<Words<'a>> {
match v.encoding {
VecEncoding::Flat => Ok(Words::Flat(&v.values::<i64>()[..len])),
VecEncoding::Constant => Ok(Words::Const(v.constant_value::<i64>())),
VecEncoding::Dict { .. } => Err(ZuError::InvalidArgument(
"a dictionary holds strings and an instant is not one".into(),
)),
}
}
fn scale(of: &LogicalType) -> Option<i64> {
match of {
LogicalType::Date => Some(zu_common::temporal::NANOS_PER_DAY),
LogicalType::LocalTime | LogicalType::LocalDatetime => Some(1),
_ => None,
}
}
fn maker(of: &LogicalType) -> Option<fn(i64) -> Temporal> {
match of {
LogicalType::Date => Some(|w| Temporal::Date(w as i32)),
LogicalType::LocalTime => Some(Temporal::LocalTime),
LogicalType::LocalDatetime => Some(Temporal::LocalDatetime),
_ => None,
}
}
pub fn duration_between(
arena: &mut MorselArena,
of: &LogicalType,
kind: DurationKind,
from: &ValueVector,
to: &ValueVector,
sel: Option<&SelVector>,
) -> Result<ValueVector> {
debug_assert_eq!(from.len, to.len);
if from.phys != to.phys {
return Err(ZuError::InvalidArgument(format!(
"no duration between {:?} and {:?}",
from.phys, to.phys
)));
}
let len = from.len as usize;
let (a, b) = (words(from, len)?, words(to, len)?);
let mut out = ValueVector::flat_uninit(arena, PhysType::Interval, len);
let mut short = false;
{
let dst = out.values_mut::<i64>();
match kind {
DurationKind::DayTime => {
let Some(scale) = scale(of) else {
return Err(ZuError::InvalidArgument(format!(
"no day-time duration kernel over {of:?}"
)));
};
for (row, out) in dst.iter_mut().enumerate().take(len) {
match count_nanos(a.at(row), b.at(row), scale) {
Some(n) => *out = n,
None => {
*out = 0;
short = true;
}
}
}
}
DurationKind::YearMonth => {
let Some(make) = maker(of) else {
return Err(ZuError::InvalidArgument(format!(
"no year-month duration kernel over {of:?}"
)));
};
for (row, out) in dst.iter_mut().enumerate().take(len) {
match count_months(make, a.at(row), b.at(row)) {
Some(n) => *out = n,
None => {
*out = 0;
short = true;
}
}
}
}
}
}
out.validity = merged(arena, from, to, len);
if short {
raise(of, kind, a, b, &out, sel, len)?;
}
Ok(out)
}
#[inline(always)]
fn count_nanos(from: i64, to: i64, scale: i64) -> Option<i64> {
to.checked_mul(scale)?.checked_sub(from.checked_mul(scale)?)
}
#[inline(always)]
fn count_months(make: fn(i64) -> Temporal, from: i64, to: i64) -> Option<i64> {
match Temporal::between(make(from), make(to), DurationKind::YearMonth) {
Some(Temporal::Duration(_, months)) => Some(months),
_ => None,
}
}
fn raise(
of: &LogicalType,
kind: DurationKind,
a: Words<'_>,
b: Words<'_>,
out: &ValueVector,
sel: Option<&SelVector>,
len: usize,
) -> Result<()> {
let make = maker(of).ok_or_else(|| {
ZuError::InvalidArgument(format!("no duration between two values of {of:?}"))
})?;
let scale = scale(of);
let check = |row: usize| -> Result<()> {
if out.validity.as_ref().is_some_and(|v| !v.get(row)) {
return Ok(());
}
let (from, to) = (a.at(row), b.at(row));
let answered = match kind {
DurationKind::DayTime => count_nanos(from, to, scale.unwrap_or(1)).is_some(),
DurationKind::YearMonth => count_months(make, from, to).is_some(),
};
if answered {
return Ok(());
}
let (from, to) = (make(from), make(to));
Err(ZuError::gql(
codes::C22G03,
format!(
"there is no {} from {from} to {to}",
LogicalType::Duration(kind)
),
))
};
match sel {
Some(sel) => {
for &row in sel.as_slice() {
check(row as usize)?;
}
}
None => {
for row in 0..len {
check(row)?;
}
}
}
Ok(())
}
fn merged(arena: &mut MorselArena, l: &ValueVector, r: &ValueVector, len: usize) -> Option<Bitmap> {
match (&l.validity, &r.validity) {
(None, None) => None,
(a, b) => {
let mut v = Bitmap::new_in(arena, len, true);
if let Some(a) = a {
v.and_with(a);
}
if let Some(b) = b {
v.and_with(b);
}
Some(v)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const DAY: i64 = 86_400_000_000_000;
fn between(of: &LogicalType, kind: DurationKind, from: &[i64], to: &[i64]) -> Result<Vec<i64>> {
let mut arena = MorselArena::new();
let a = ValueVector::flat_from(&mut arena, PhysType::Date, from);
let b = ValueVector::flat_from(&mut arena, PhysType::Date, to);
let out = duration_between(&mut arena, of, kind, &a, &b, None)?;
Ok(out.values::<i64>()[..from.len()].to_vec())
}
#[test]
fn a_day_time_duration_between_two_dates_is_the_days_in_nanoseconds() {
let got = between(
&LogicalType::Date,
DurationKind::DayTime,
&[0, 10, -5],
&[1, 3, 5],
)
.unwrap();
assert_eq!(got, vec![DAY, -7 * DAY, 10 * DAY]);
}
#[test]
fn a_day_time_duration_between_two_datetimes_is_the_difference() {
let got = between(
&LogicalType::LocalDatetime,
DurationKind::DayTime,
&[0, 1_000],
&[DAY, 400],
)
.unwrap();
assert_eq!(got, vec![DAY, -600]);
}
#[test]
fn a_date_too_far_out_has_no_day_time_duration_to_anything() {
let err = between(
&LogicalType::Date,
DurationKind::DayTime,
&[2_000_000],
&[2_000_001],
)
.unwrap_err();
assert!(
err.to_string().contains("there is no"),
"expected a 22G03, got {err}"
);
}
#[test]
fn a_year_month_duration_counts_whole_months() {
let got = between(
&LogicalType::Date,
DurationKind::YearMonth,
&[0, 0],
&[424, 423],
)
.unwrap();
assert_eq!(got, vec![14, 13]);
}
#[test]
fn a_row_outside_the_selection_raises_nothing() {
let mut arena = MorselArena::new();
let a = ValueVector::flat_from(&mut arena, PhysType::Date, &[0i64, 2_000_000]);
let b = ValueVector::flat_from(&mut arena, PhysType::Date, &[1i64, 2_000_001]);
let mut sel = SelVector::with_capacity(&mut arena, 1);
sel.push(0);
let out = duration_between(
&mut arena,
&LogicalType::Date,
DurationKind::DayTime,
&a,
&b,
Some(&sel),
)
.expect("the selected row has an answer");
assert_eq!(out.values::<i64>()[0], DAY);
}
}