reifydb_routine/function/duration/
subtract.rs1use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{container::temporal::TemporalContainer, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct DurationSubtract {
10 info: FunctionInfo,
11}
12
13impl Default for DurationSubtract {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl DurationSubtract {
20 pub fn new() -> Self {
21 Self {
22 info: FunctionInfo::new("duration::subtract"),
23 }
24 }
25}
26
27impl Function for DurationSubtract {
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 lhs_col = &args[0];
50 let rhs_col = &args[1];
51
52 let (lhs_data, lhs_bv) = lhs_col.data().unwrap_option();
53 let (rhs_data, rhs_bv) = rhs_col.data().unwrap_option();
54
55 match (lhs_data, rhs_data) {
56 (ColumnData::Duration(lhs_container), ColumnData::Duration(rhs_container)) => {
57 let row_count = lhs_data.len();
58 let mut container = TemporalContainer::with_capacity(row_count);
59
60 for i in 0..row_count {
61 match (lhs_container.get(i), rhs_container.get(i)) {
62 (Some(lv), Some(rv)) => {
63 container.push(*lv - *rv);
64 }
65 _ => container.push_default(),
66 }
67 }
68
69 let mut result_data = ColumnData::Duration(container);
70 if let Some(bv) = lhs_bv {
71 result_data = ColumnData::Option {
72 inner: Box::new(result_data),
73 bitvec: bv.clone(),
74 };
75 } else if let Some(bv) = rhs_bv {
76 result_data = ColumnData::Option {
77 inner: Box::new(result_data),
78 bitvec: bv.clone(),
79 };
80 }
81 Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), result_data)]))
82 }
83 (ColumnData::Duration(_), other) => Err(FunctionError::InvalidArgumentType {
84 function: ctx.fragment.clone(),
85 argument_index: 1,
86 expected: vec![Type::Duration],
87 actual: other.get_type(),
88 }),
89 (other, _) => Err(FunctionError::InvalidArgumentType {
90 function: ctx.fragment.clone(),
91 argument_index: 0,
92 expected: vec![Type::Duration],
93 actual: other.get_type(),
94 }),
95 }
96 }
97}