Skip to main content

reifydb_routine/function/is/
type.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
5use reifydb_type::value::{Value, r#type::Type};
6
7use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
8
9pub struct IsType {
10	info: RoutineInfo,
11}
12
13impl Default for IsType {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl IsType {
20	pub fn new() -> Self {
21		Self {
22			info: RoutineInfo::new("is::type"),
23		}
24	}
25}
26
27impl<'a> Routine<FunctionContext<'a>> for IsType {
28	fn info(&self) -> &RoutineInfo {
29		&self.info
30	}
31
32	fn return_type(&self, _input_types: &[Type]) -> Type {
33		Type::Boolean
34	}
35
36	fn propagates_options(&self) -> bool {
37		false
38	}
39
40	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
41		if args.len() != 2 {
42			return Err(RoutineError::FunctionArityMismatch {
43				function: ctx.fragment.clone(),
44				expected: 2,
45				actual: args.len(),
46			});
47		}
48
49		let value_column = &args[0];
50		let type_column = &args[1];
51		let row_count = value_column.len();
52
53		let target_type = match type_column.get_value(0) {
54			Value::Any(boxed) => match boxed.as_ref() {
55				Value::Type(t) => t.clone(),
56				_ => {
57					return Err(RoutineError::FunctionInvalidArgumentType {
58						function: ctx.fragment.clone(),
59						argument_index: 1,
60						expected: vec![Type::Any],
61						actual: boxed.get_type(),
62					});
63				}
64			},
65			Value::None {
66				..
67			} => Type::Option(Box::new(Type::Any)),
68			other => {
69				return Err(RoutineError::FunctionInvalidArgumentType {
70					function: ctx.fragment.clone(),
71					argument_index: 1,
72					expected: vec![Type::Any],
73					actual: other.get_type(),
74				});
75			}
76		};
77
78		let data: Vec<bool> = (0..row_count)
79			.map(|i| {
80				let vtype = value_column.get_value(i).get_type();
81				if target_type == Type::Option(Box::new(Type::Any)) {
82					vtype.is_option()
83				} else {
84					!vtype.is_option() && vtype.inner_type() == target_type.inner_type()
85				}
86			})
87			.collect();
88
89		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), ColumnBuffer::bool(data))]))
90	}
91}
92
93impl Function for IsType {
94	fn kinds(&self) -> &[FunctionKind] {
95		&[FunctionKind::Scalar]
96	}
97}