reifydb_function/math/scalar/
sign.rs1use num_traits::ToPrimitive;
5use reifydb_core::value::column::data::ColumnData;
6use reifydb_type::value::r#type::Type;
7
8use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
9
10pub struct Sign;
11
12impl Sign {
13 pub fn new() -> Self {
14 Self
15 }
16}
17
18fn numeric_to_f64(data: &ColumnData, i: usize) -> Option<f64> {
19 match data {
20 ColumnData::Int1(c) => c.get(i).map(|&v| v as f64),
21 ColumnData::Int2(c) => c.get(i).map(|&v| v as f64),
22 ColumnData::Int4(c) => c.get(i).map(|&v| v as f64),
23 ColumnData::Int8(c) => c.get(i).map(|&v| v as f64),
24 ColumnData::Int16(c) => c.get(i).map(|&v| v as f64),
25 ColumnData::Uint1(c) => c.get(i).map(|&v| v as f64),
26 ColumnData::Uint2(c) => c.get(i).map(|&v| v as f64),
27 ColumnData::Uint4(c) => c.get(i).map(|&v| v as f64),
28 ColumnData::Uint8(c) => c.get(i).map(|&v| v as f64),
29 ColumnData::Uint16(c) => c.get(i).map(|&v| v as f64),
30 ColumnData::Float4(c) => c.get(i).map(|&v| v as f64),
31 ColumnData::Float8(c) => c.get(i).copied(),
32 ColumnData::Int {
33 container,
34 ..
35 } => container.get(i).map(|v| v.0.to_f64().unwrap_or(0.0)),
36 ColumnData::Uint {
37 container,
38 ..
39 } => container.get(i).map(|v| v.0.to_f64().unwrap_or(0.0)),
40 ColumnData::Decimal {
41 container,
42 ..
43 } => container.get(i).map(|v| v.0.to_f64().unwrap_or(0.0)),
44 _ => None,
45 }
46}
47
48impl ScalarFunction for Sign {
49 fn scalar(&self, ctx: ScalarFunctionContext) -> crate::error::ScalarFunctionResult<ColumnData> {
50 if let Some(result) = propagate_options(self, &ctx) {
51 return result;
52 }
53 let columns = ctx.columns;
54 let row_count = ctx.row_count;
55
56 if columns.len() != 1 {
57 return Err(ScalarFunctionError::ArityMismatch {
58 function: ctx.fragment.clone(),
59 expected: 1,
60 actual: columns.len(),
61 });
62 }
63
64 let column = columns.get(0).unwrap();
65
66 if !column.data().get_type().is_number() {
67 return Err(ScalarFunctionError::InvalidArgumentType {
68 function: ctx.fragment.clone(),
69 argument_index: 0,
70 expected: vec![
71 Type::Int1,
72 Type::Int2,
73 Type::Int4,
74 Type::Int8,
75 Type::Int16,
76 Type::Uint1,
77 Type::Uint2,
78 Type::Uint4,
79 Type::Uint8,
80 Type::Uint16,
81 Type::Float4,
82 Type::Float8,
83 Type::Int,
84 Type::Uint,
85 Type::Decimal,
86 ],
87 actual: column.data().get_type(),
88 });
89 }
90
91 let mut result = Vec::with_capacity(row_count);
92 let mut bitvec = Vec::with_capacity(row_count);
93
94 for i in 0..row_count {
95 match numeric_to_f64(column.data(), i) {
96 Some(v) => {
97 let sign = if v > 0.0 {
98 1i32
99 } else if v < 0.0 {
100 -1i32
101 } else {
102 0i32
103 };
104 result.push(sign);
105 bitvec.push(true);
106 }
107 None => {
108 result.push(0);
109 bitvec.push(false);
110 }
111 }
112 }
113
114 Ok(ColumnData::int4_with_bitvec(result, bitvec))
115 }
116
117 fn return_type(&self, _input_types: &[Type]) -> Type {
118 Type::Float8
119 }
120}