Skip to main content

risingwave_expr/sig/
mod.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Metadata of expressions.
16
17use 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
38/// The global registry of all function signatures.
39pub 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/// A set of function signatures.
49#[derive(Default, Clone, Debug)]
50pub struct FunctionRegistry(HashMap<FuncName, Vec<FuncSign>>);
51
52impl FunctionRegistry {
53    /// Inserts a function signature.
54    pub fn insert(&mut self, sig: FuncSign) {
55        let list = self.0.entry(sig.name.clone()).or_default();
56        if sig.is_aggregate() {
57            // merge retractable and append-only aggregate
58            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    /// Remove a function signature from registry.
94    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    /// Returns a function signature with the same type, argument types and return type.
110    /// Deprecated functions are included.
111    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            // Note: if we return error here, it probably means there is a bug in frontend type inference,
120            // because such error should be caught in the frontend.
121            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    /// Returns all function signatures with the same type and number of arguments.
151    /// Deprecated functions are excluded.
152    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    /// Returns the return type for the given function and arguments.
163    /// Deprecated functions are excluded.
164    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    /// Returns an iterator of all function signatures.
182    pub fn iter(&self) -> impl Iterator<Item = &FuncSign> {
183        self.0.values().flatten()
184    }
185
186    /// Returns an iterator of all scalar functions.
187    pub fn iter_scalars(&self) -> impl Iterator<Item = &FuncSign> {
188        self.iter().filter(|d| d.is_scalar())
189    }
190
191    /// Returns an iterator of all aggregate functions.
192    pub fn iter_aggregates(&self) -> impl Iterator<Item = &FuncSign> {
193        self.iter().filter(|d| d.is_aggregate())
194    }
195}
196
197/// A function signature.
198#[derive(Clone)]
199pub struct FuncSign {
200    /// The name of the function.
201    pub name: FuncName,
202
203    /// The argument types.
204    pub inputs_type: Vec<SigDataType>,
205
206    /// Whether the function is variadic.
207    pub variadic: bool,
208
209    /// The return type.
210    pub ret_type: SigDataType,
211
212    /// Whether this scalar function is asynchronous even when all its inputs are synchronous.
213    pub is_async: bool,
214
215    /// A function to build the expression.
216    pub build: FuncBuilder,
217
218    /// A function to infer the return type from argument types.
219    pub type_infer: fn(args: &[DataType]) -> Result<DataType>,
220
221    /// Whether the function is deprecated and should not be used in the frontend.
222    /// For backward compatibility, it is still available in the backend.
223    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    /// Returns true if the argument types match the function signature.
254    pub fn match_args(&self, args: &[DataType]) -> bool {
255        if !self.match_number_of_args(args.len()) {
256            return false;
257        }
258        // allow `zip` as the length of `args` may be larger than `inputs_type`
259        #[expect(clippy::disallowed_methods)]
260        self.inputs_type
261            .iter()
262            .zip(args.iter())
263            .all(|(matcher, arg)| matcher.matches(arg))
264    }
265
266    /// Returns true if the argument types match the function signature.
267    fn match_args_ret(&self, args: &[DataType], ret: &DataType) -> bool {
268        self.match_args(args) && self.ret_type.matches(ret)
269    }
270
271    /// Returns true if the number of arguments matches the function signature.
272    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    /// Returns true if the function is a scalar function.
281    pub const fn is_scalar(&self) -> bool {
282        matches!(self.name, FuncName::Scalar(_))
283    }
284
285    /// Returns true if the function is a table function.
286    pub const fn is_table_function(&self) -> bool {
287        matches!(self.name, FuncName::Table(_))
288    }
289
290    /// Returns true if the function is a aggregate function.
291    pub const fn is_aggregate(&self) -> bool {
292        matches!(self.name, FuncName::Aggregate(_))
293    }
294
295    /// Returns true if the aggregate function is append-only.
296    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    /// Returns true if the aggregate function has a retractable version.
307    pub const fn is_retractable(&self) -> bool {
308        matches!(
309            self.build,
310            FuncBuilder::Aggregate {
311                retractable: Some(_),
312                ..
313            }
314        )
315    }
316
317    /// Builds the scalar function.
318    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    /// Builds the table function.
330    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    /// Builds the aggregate function. If both retractable and append-only versions exist, the
343    /// retractable version will be built.
344    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    /// Returns the name of the function in `UPPER_CASE` style.
390    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    /// Returns true if the function is a table function.
400    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/// An extended data type that can be used to declare a function's argument or result type.
420#[derive(Debug, Clone, PartialEq, Eq, Hash)]
421pub enum SigDataType {
422    /// Exact data type
423    Exact(DataType),
424    /// Accepts any data type
425    Any,
426    /// Accepts any array data type
427    AnyArray,
428    /// Accepts any struct data type
429    AnyStruct,
430    /// TODO: not all type can be used as a map key.
431    AnyMap,
432    /// Vector of a certain size
433    /// Named without `Any` prefix to align with PostgreSQL
434    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    /// Returns true if the data type matches.
458    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    /// Returns the exact data type.
470    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    /// Returns true if the data type is exact.
478    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    // An aggregate function may contain both or either one of retractable and append-only versions.
494    Aggregate {
495        retractable: Option<fn(agg: &AggCall) -> Result<BoxedAggregateFunction>>,
496        append_only: Option<fn(agg: &AggCall) -> Result<BoxedAggregateFunction>>,
497        /// The state type of the retractable aggregate function.
498        /// `None` means equal to the return type.
499        retractable_state_type: Option<DataType>,
500        /// The state type of the append-only aggregate function.
501        /// `None` means equal to the return type.
502        append_only_state_type: Option<DataType>,
503    },
504    Udf,
505}
506
507/// A static distributed slice of functions defined by `#[function]`.
508#[linkme::distributed_slice]
509pub static FUNCTIONS: [fn() -> FuncSign];