reifydb_routine/function/time/
age.rs1use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{container::temporal::TemporalContainer, duration::Duration, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct TimeAge {
10 info: FunctionInfo,
11}
12
13impl Default for TimeAge {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl TimeAge {
20 pub fn new() -> Self {
21 Self {
22 info: FunctionInfo::new("time::age"),
23 }
24 }
25}
26
27impl Function for TimeAge {
28 fn info(&self) -> &FunctionInfo {
29 &self.info
30 }
31
32 fn capabilities(&self) -> &[FunctionCapability] {
33 &[FunctionCapability::Scalar]
34 }
35
36 fn return_type(&self, _input_types: &[Type]) -> Type {
37 Type::Duration
38 }
39
40 fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
41 if args.len() != 2 {
42 return Err(FunctionError::ArityMismatch {
43 function: ctx.fragment.clone(),
44 expected: 2,
45 actual: args.len(),
46 });
47 }
48
49 let col1 = &args[0];
50 let col2 = &args[1];
51
52 let (data1, bv1) = col1.data().unwrap_option();
53 let (data2, bv2) = col2.data().unwrap_option();
54
55 match (data1, data2) {
56 (ColumnData::Time(container1), ColumnData::Time(container2)) => {
57 let row_count = data1.len();
58 let mut container = TemporalContainer::with_capacity(row_count);
59
60 for i in 0..row_count {
61 match (container1.get(i), container2.get(i)) {
62 (Some(t1), Some(t2)) => {
63 let diff_nanos = t1.to_nanos_since_midnight() as i64
64 - t2.to_nanos_since_midnight() as i64;
65 container.push(Duration::from_nanoseconds(diff_nanos)?);
66 }
67 _ => container.push_default(),
68 }
69 }
70
71 let mut result_data = ColumnData::Duration(container);
72 if let Some(bv) = bv1 {
73 result_data = ColumnData::Option {
74 inner: Box::new(result_data),
75 bitvec: bv.clone(),
76 };
77 } else if let Some(bv) = bv2 {
78 result_data = ColumnData::Option {
79 inner: Box::new(result_data),
80 bitvec: bv.clone(),
81 };
82 }
83 Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), result_data)]))
84 }
85 (ColumnData::Time(_), other) => Err(FunctionError::InvalidArgumentType {
86 function: ctx.fragment.clone(),
87 argument_index: 1,
88 expected: vec![Type::Time],
89 actual: other.get_type(),
90 }),
91 (other, _) => Err(FunctionError::InvalidArgumentType {
92 function: ctx.fragment.clone(),
93 argument_index: 0,
94 expected: vec![Type::Time],
95 actual: other.get_type(),
96 }),
97 }
98 }
99}