Skip to main content

risingwave_frontend/expr/
user_defined_function.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
15use std::sync::Arc;
16
17use itertools::Itertools;
18use risingwave_common::catalog::{FunctionId, Schema};
19use risingwave_common::types::DataType;
20
21use super::{Expr, ExprDisplay, ExprImpl};
22use crate::catalog::function_catalog::{FunctionCatalog, FunctionKind};
23
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25pub struct UserDefinedFunction {
26    pub args: Vec<ExprImpl>,
27    pub catalog: Arc<FunctionCatalog>,
28}
29
30impl UserDefinedFunction {
31    pub fn new(catalog: Arc<FunctionCatalog>, args: Vec<ExprImpl>) -> Self {
32        Self { args, catalog }
33    }
34
35    pub(super) fn from_expr_proto(
36        udf: &risingwave_pb::expr::UserDefinedFunction,
37        return_type: DataType,
38    ) -> crate::error::Result<Self> {
39        let args: Vec<_> = udf
40            .get_children()
41            .iter()
42            .map(ExprImpl::from_expr_proto)
43            .try_collect()?;
44
45        // function catalog
46        let arg_types = udf.get_arg_types().iter().map_into().collect_vec();
47        let catalog = FunctionCatalog {
48            // FIXME(yuhao): function id is not in udf proto.
49            id: FunctionId::placeholder(),
50            name: udf.name.clone(),
51            // FIXME(yuhao): owner is not in udf proto.
52            owner: (u32::MAX - 1).into(),
53            kind: FunctionKind::Scalar,
54            arg_names: udf.arg_names.clone(),
55            arg_types,
56            return_type,
57            language: udf.language.clone(),
58            runtime: udf.runtime.clone(),
59            name_in_runtime: udf.name_in_runtime().map(|x| x.to_owned()),
60            body: udf.body.clone(),
61            link: udf.link.clone(),
62            compressed_binary: udf.compressed_binary.clone(),
63            always_retry_on_network_error: udf.always_retry_on_network_error,
64            unsafe_skip_materializing_exprs: udf.unsafe_skip_materializing_exprs,
65            is_immutable: udf.is_immutable,
66            is_batched: udf.is_batched,
67            is_async: udf.is_async,
68            created_at_epoch: None,
69            created_at_cluster_version: None,
70        };
71
72        Ok(Self {
73            args,
74            catalog: Arc::new(catalog),
75        })
76    }
77}
78
79impl Expr for UserDefinedFunction {
80    fn return_type(&self) -> DataType {
81        self.catalog.return_type.clone()
82    }
83
84    fn try_to_expr_proto(&self) -> Result<risingwave_pb::expr::ExprNode, String> {
85        use risingwave_pb::expr::expr_node::*;
86        use risingwave_pb::expr::*;
87
88        let children = self
89            .args
90            .iter()
91            .map(|arg| arg.try_to_expr_proto())
92            .try_collect()?;
93
94        Ok(ExprNode {
95            function_type: Type::Unspecified.into(),
96            return_type: Some(self.return_type().to_protobuf()),
97            rex_node: Some(RexNode::Udf(Box::new(UserDefinedFunction {
98                children,
99                name: self.catalog.name.clone(),
100                arg_names: self.catalog.arg_names.clone(),
101                arg_types: self
102                    .catalog
103                    .arg_types
104                    .iter()
105                    .map(|t| t.to_protobuf())
106                    .collect(),
107                language: self.catalog.language.clone(),
108                runtime: self.catalog.runtime.clone(),
109                identifier: self.catalog.name_in_runtime.clone(),
110                link: self.catalog.link.clone(),
111                body: self.catalog.body.clone(),
112                compressed_binary: self.catalog.compressed_binary.clone(),
113                always_retry_on_network_error: self.catalog.always_retry_on_network_error,
114                unsafe_skip_materializing_exprs: self.catalog.unsafe_skip_materializing_exprs,
115                is_immutable: self.catalog.is_immutable,
116                is_async: self.catalog.is_async,
117                is_batched: self.catalog.is_batched,
118                version: PbUdfExprVersion::LATEST as _,
119            }))),
120        })
121    }
122}
123
124pub struct UserDefinedFunctionDisplay<'a> {
125    pub func_call: &'a UserDefinedFunction,
126    pub input_schema: &'a Schema,
127}
128
129impl std::fmt::Debug for UserDefinedFunctionDisplay<'_> {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        let that = self.func_call;
132        let mut builder = f.debug_tuple(&that.catalog.name);
133        for arg in &that.args {
134            builder.field(&ExprDisplay {
135                expr: arg,
136                input_schema: self.input_schema,
137            });
138        }
139        builder.finish()
140    }
141}