1use std::borrow::Cow;
18use std::collections::HashMap;
19use std::fmt;
20use std::sync::LazyLock;
21
22use itertools::Itertools;
23use risingwave_common::types::DataType;
24use risingwave_pb::expr::agg_call::PbKind as PbAggKind;
25use risingwave_pb::expr::expr_node::PbType as ScalarFunctionType;
26use risingwave_pb::expr::table_function::PbType as TableFunctionType;
27
28use crate::ExprError;
29use crate::aggregate::{AggCall, BoxedAggregateFunction};
30use crate::error::Result;
31use crate::expr::BoxedExpression;
32use crate::table_function::BoxedTableFunction;
33
34mod udf;
35
36pub use self::udf::*;
37
38pub static FUNCTION_REGISTRY: LazyLock<FunctionRegistry> = LazyLock::new(|| {
40 let mut map = FunctionRegistry::default();
41 tracing::info!("found {} functions", FUNCTIONS.len());
42 for f in FUNCTIONS {
43 map.insert(f());
44 }
45 map
46});
47
48#[derive(Default, Clone, Debug)]
50pub struct FunctionRegistry(HashMap<FuncName, Vec<FuncSign>>);
51
52impl FunctionRegistry {
53 pub fn insert(&mut self, sig: FuncSign) {
55 let list = self.0.entry(sig.name.clone()).or_default();
56 if sig.is_aggregate() {
57 if let Some(existing) = list
59 .iter_mut()
60 .find(|d| d.inputs_type == sig.inputs_type && d.ret_type == sig.ret_type)
61 {
62 let (
63 FuncBuilder::Aggregate {
64 retractable,
65 append_only,
66 retractable_state_type,
67 append_only_state_type,
68 },
69 FuncBuilder::Aggregate {
70 retractable: r1,
71 append_only: a1,
72 retractable_state_type: rs1,
73 append_only_state_type: as1,
74 },
75 ) = (&mut existing.build, sig.build)
76 else {
77 panic!("expected aggregate function")
78 };
79 if let Some(f) = r1 {
80 *retractable = Some(f);
81 *retractable_state_type = rs1;
82 }
83 if let Some(f) = a1 {
84 *append_only = Some(f);
85 *append_only_state_type = as1;
86 }
87 return;
88 }
89 }
90 list.push(sig);
91 }
92
93 pub fn remove(&mut self, sig: FuncSign) -> Option<FuncSign> {
95 let pos = self
96 .0
97 .get_mut(&sig.name)?
98 .iter()
99 .positions(|s| s.inputs_type == sig.inputs_type && s.ret_type == sig.ret_type)
100 .rev()
101 .collect_vec();
102 let mut ret = None;
103 for p in pos {
104 ret = Some(self.0.get_mut(&sig.name)?.swap_remove(p));
105 }
106 ret
107 }
108
109 pub fn get(
112 &self,
113 name: impl Into<FuncName>,
114 args: &[DataType],
115 ret: &DataType,
116 ) -> Result<&FuncSign, ExprError> {
117 let name = name.into();
118 let err = |candidates: &Vec<FuncSign>| {
119 ExprError::UnsupportedFunction(format!(
122 "{}({}) -> {}{}",
123 name,
124 args.iter().format(", "),
125 ret,
126 if candidates.is_empty() {
127 "".to_owned()
128 } else {
129 format!(
130 "\nHINT: Supported functions:\n{}",
131 candidates
132 .iter()
133 .map(|d| format!(
134 " {}({}) -> {}",
135 d.name,
136 d.inputs_type.iter().format(", "),
137 d.ret_type
138 ))
139 .format("\n")
140 )
141 }
142 ))
143 };
144 let v = self.0.get(&name).ok_or_else(|| err(&vec![]))?;
145 v.iter()
146 .find(|d| d.match_args_ret(args, ret))
147 .ok_or_else(|| err(v))
148 }
149
150 pub fn get_with_arg_nums(&self, name: impl Into<FuncName>, nargs: usize) -> Vec<&FuncSign> {
153 match self.0.get(&name.into()) {
154 Some(v) => v
155 .iter()
156 .filter(|d| d.match_number_of_args(nargs) && !d.deprecated)
157 .collect(),
158 None => vec![],
159 }
160 }
161
162 pub fn get_return_type(
165 &self,
166 name: impl Into<FuncName>,
167 args: &[DataType],
168 ) -> Result<DataType> {
169 let name = name.into();
170 let v = self
171 .0
172 .get(&name)
173 .ok_or_else(|| ExprError::UnsupportedFunction(name.to_string()))?;
174 let sig = v
175 .iter()
176 .find(|d| d.match_args(args) && !d.deprecated)
177 .ok_or_else(|| ExprError::UnsupportedFunction(name.to_string()))?;
178 (sig.type_infer)(args)
179 }
180
181 pub fn iter(&self) -> impl Iterator<Item = &FuncSign> {
183 self.0.values().flatten()
184 }
185
186 pub fn iter_scalars(&self) -> impl Iterator<Item = &FuncSign> {
188 self.iter().filter(|d| d.is_scalar())
189 }
190
191 pub fn iter_aggregates(&self) -> impl Iterator<Item = &FuncSign> {
193 self.iter().filter(|d| d.is_aggregate())
194 }
195}
196
197#[derive(Clone)]
199pub struct FuncSign {
200 pub name: FuncName,
202
203 pub inputs_type: Vec<SigDataType>,
205
206 pub variadic: bool,
208
209 pub ret_type: SigDataType,
211
212 pub is_async: bool,
214
215 pub build: FuncBuilder,
217
218 pub type_infer: fn(args: &[DataType]) -> Result<DataType>,
220
221 pub deprecated: bool,
224}
225
226impl fmt::Debug for FuncSign {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 write!(
229 f,
230 "{}({}{}) -> {}{}",
231 self.name.as_str_name().to_ascii_lowercase(),
232 self.inputs_type.iter().format(", "),
233 if self.variadic {
234 if self.inputs_type.is_empty() {
235 "..."
236 } else {
237 ", ..."
238 }
239 } else {
240 ""
241 },
242 if self.name.is_table() { "setof " } else { "" },
243 self.ret_type,
244 )?;
245 if self.deprecated {
246 write!(f, " [deprecated]")?;
247 }
248 Ok(())
249 }
250}
251
252impl FuncSign {
253 pub fn match_args(&self, args: &[DataType]) -> bool {
255 if !self.match_number_of_args(args.len()) {
256 return false;
257 }
258 #[expect(clippy::disallowed_methods)]
260 self.inputs_type
261 .iter()
262 .zip(args.iter())
263 .all(|(matcher, arg)| matcher.matches(arg))
264 }
265
266 fn match_args_ret(&self, args: &[DataType], ret: &DataType) -> bool {
268 self.match_args(args) && self.ret_type.matches(ret)
269 }
270
271 fn match_number_of_args(&self, n: usize) -> bool {
273 if self.variadic {
274 n >= self.inputs_type.len()
275 } else {
276 n == self.inputs_type.len()
277 }
278 }
279
280 pub const fn is_scalar(&self) -> bool {
282 matches!(self.name, FuncName::Scalar(_))
283 }
284
285 pub const fn is_table_function(&self) -> bool {
287 matches!(self.name, FuncName::Table(_))
288 }
289
290 pub const fn is_aggregate(&self) -> bool {
292 matches!(self.name, FuncName::Aggregate(_))
293 }
294
295 pub const fn is_append_only(&self) -> bool {
297 matches!(
298 self.build,
299 FuncBuilder::Aggregate {
300 retractable: None,
301 ..
302 }
303 )
304 }
305
306 pub const fn is_retractable(&self) -> bool {
308 matches!(
309 self.build,
310 FuncBuilder::Aggregate {
311 retractable: Some(_),
312 ..
313 }
314 )
315 }
316
317 pub fn build_scalar(
319 &self,
320 return_type: DataType,
321 children: Vec<BoxedExpression>,
322 ) -> Result<BoxedExpression> {
323 match self.build {
324 FuncBuilder::Scalar(f) => f(return_type, children),
325 _ => panic!("Expected a scalar function"),
326 }
327 }
328
329 pub fn build_table(
331 &self,
332 return_type: DataType,
333 chunk_size: usize,
334 children: Vec<BoxedExpression>,
335 ) -> Result<BoxedTableFunction> {
336 match self.build {
337 FuncBuilder::Table(f) => f(return_type, chunk_size, children),
338 _ => panic!("Expected a table function"),
339 }
340 }
341
342 pub fn build_aggregate(&self, agg: &AggCall) -> Result<BoxedAggregateFunction> {
345 match self.build {
346 FuncBuilder::Aggregate {
347 retractable,
348 append_only,
349 ..
350 } => retractable.or(append_only).unwrap()(agg),
351 _ => panic!("Expected an aggregate function"),
352 }
353 }
354}
355
356#[derive(Debug, Clone, PartialEq, Eq, Hash)]
357pub enum FuncName {
358 Scalar(ScalarFunctionType),
359 Table(TableFunctionType),
360 Aggregate(PbAggKind),
361 Udf(String),
362}
363
364impl From<ScalarFunctionType> for FuncName {
365 fn from(ty: ScalarFunctionType) -> Self {
366 Self::Scalar(ty)
367 }
368}
369
370impl From<TableFunctionType> for FuncName {
371 fn from(ty: TableFunctionType) -> Self {
372 Self::Table(ty)
373 }
374}
375
376impl From<PbAggKind> for FuncName {
377 fn from(ty: PbAggKind) -> Self {
378 Self::Aggregate(ty)
379 }
380}
381
382impl fmt::Display for FuncName {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 write!(f, "{}", self.as_str_name().to_ascii_lowercase())
385 }
386}
387
388impl FuncName {
389 pub fn as_str_name(&self) -> Cow<'static, str> {
391 match self {
392 Self::Scalar(ty) => ty.as_str_name().into(),
393 Self::Table(ty) => ty.as_str_name().into(),
394 Self::Aggregate(ty) => ty.as_str_name().into(),
395 Self::Udf(name) => name.clone().into(),
396 }
397 }
398
399 const fn is_table(&self) -> bool {
401 matches!(self, Self::Table(_))
402 }
403
404 pub fn as_scalar(&self) -> ScalarFunctionType {
405 match self {
406 Self::Scalar(ty) => *ty,
407 _ => panic!("Expected a scalar function"),
408 }
409 }
410
411 pub fn as_aggregate(&self) -> PbAggKind {
412 match self {
413 Self::Aggregate(kind) => *kind,
414 _ => panic!("Expected an aggregate function"),
415 }
416 }
417}
418
419#[derive(Debug, Clone, PartialEq, Eq, Hash)]
421pub enum SigDataType {
422 Exact(DataType),
424 Any,
426 AnyArray,
428 AnyStruct,
430 AnyMap,
432 Vector,
435}
436
437impl From<DataType> for SigDataType {
438 fn from(dt: DataType) -> Self {
439 SigDataType::Exact(dt)
440 }
441}
442
443impl std::fmt::Display for SigDataType {
444 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445 match self {
446 Self::Exact(dt) => write!(f, "{}", dt),
447 Self::Any => write!(f, "any"),
448 Self::AnyArray => write!(f, "anyarray"),
449 Self::AnyStruct => write!(f, "anystruct"),
450 Self::AnyMap => write!(f, "anymap"),
451 Self::Vector => write!(f, "vector"),
452 }
453 }
454}
455
456impl SigDataType {
457 pub fn matches(&self, dt: &DataType) -> bool {
459 match self {
460 Self::Exact(ty) => ty == dt,
461 Self::Any => true,
462 Self::AnyArray => dt.is_array(),
463 Self::AnyStruct => dt.is_struct(),
464 Self::AnyMap => dt.is_map(),
465 Self::Vector => matches!(dt, DataType::Vector(_)),
466 }
467 }
468
469 pub fn as_exact(&self) -> &DataType {
471 match self {
472 Self::Exact(ty) => ty,
473 t => panic!("expected data type, but got: {t}"),
474 }
475 }
476
477 pub fn is_exact(&self) -> bool {
479 matches!(self, Self::Exact(_))
480 }
481}
482
483#[derive(Clone)]
484pub enum FuncBuilder {
485 Scalar(fn(return_type: DataType, children: Vec<BoxedExpression>) -> Result<BoxedExpression>),
486 Table(
487 fn(
488 return_type: DataType,
489 chunk_size: usize,
490 children: Vec<BoxedExpression>,
491 ) -> Result<BoxedTableFunction>,
492 ),
493 Aggregate {
495 retractable: Option<fn(agg: &AggCall) -> Result<BoxedAggregateFunction>>,
496 append_only: Option<fn(agg: &AggCall) -> Result<BoxedAggregateFunction>>,
497 retractable_state_type: Option<DataType>,
500 append_only_state_type: Option<DataType>,
503 },
504 Udf,
505}
506
507#[linkme::distributed_slice]
509pub static FUNCTIONS: [fn() -> FuncSign];