Skip to main content

risingwave_frontend/handler/
create_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 anyhow::Context;
16use either::Either;
17use risingwave_common::catalog::FunctionId;
18use risingwave_expr::sig::{CreateOptions, UdfKind};
19use risingwave_pb::catalog::PbFunction;
20use risingwave_pb::catalog::function::{Kind, ScalarFunction, TableFunction};
21
22use super::*;
23use crate::binder::bind_struct_type;
24use crate::{Binder, bind_data_type};
25
26/// Non-SQL UDFs exchange data via Arrow, which does not support VARIANT yet.
27pub(crate) fn reject_variant_in_udf_signature(
28    return_type: &risingwave_common::types::DataType,
29    arg_types: &[risingwave_common::types::DataType],
30    kind: &str,
31) -> Result<()> {
32    if return_type.contains_variant() || arg_types.iter().any(|t| t.contains_variant()) {
33        return Err(ErrorCode::NotSupported(
34            format!("VARIANT type in {kind} signature"),
35            "VARIANT is not supported in UDFs yet".to_owned(),
36        )
37        .into());
38    }
39    Ok(())
40}
41
42/// `IMMUTABLE` is currently supported only for scalar UDFs, so every other kind of function
43/// rejects it. `STABLE` and `VOLATILE` are always treated as no-ops and pass through unchanged.
44///
45/// TODO: revisit `STABLE` and `VOLATILE` once they get a meaning in RisingWave.
46pub(crate) fn should_reject_function_behavior(behavior: &FunctionBehavior, kind: UdfKind) -> bool {
47    match (behavior, kind) {
48        (FunctionBehavior::Immutable, UdfKind::Table | UdfKind::Aggregate) => true,
49        (FunctionBehavior::Immutable, UdfKind::Scalar) => false,
50        (FunctionBehavior::Stable | FunctionBehavior::Volatile, _) => false,
51    }
52}
53
54/// `unsafe_skip_materializing_exprs` is read only when a scalar UDF call is planned, so every
55/// other kind of function rejects it instead of ignoring it.
56pub(crate) fn should_reject_unsafe_skip_materializing_exprs(kind: UdfKind) -> bool {
57    match kind {
58        UdfKind::Scalar => false,
59        UdfKind::Table | UdfKind::Aggregate => true,
60    }
61}
62
63pub async fn handle_create_function(
64    handler_args: HandlerArgs,
65    or_replace: bool,
66    temporary: bool,
67    if_not_exists: bool,
68    name: ObjectName,
69    args: Option<Vec<OperateFunctionArg>>,
70    returns: Option<CreateFunctionReturns>,
71    params: CreateFunctionBody,
72    with_options: CreateFunctionWithOptions,
73) -> Result<RwPgResponse> {
74    if or_replace {
75        bail_not_implemented!("CREATE OR REPLACE FUNCTION");
76    }
77    if temporary {
78        bail_not_implemented!("CREATE TEMPORARY FUNCTION");
79    }
80
81    let udf_config = handler_args.session.env().udf_config();
82
83    // e.g., `language [ python / javascript / ...etc]`
84    let language = match params.language {
85        Some(lang) => {
86            let lang = lang.real_value().to_lowercase();
87            match &*lang {
88                "java" => lang, // only support external UDF for Java
89                "python" if udf_config.enable_embedded_python_udf => lang,
90                "javascript" if udf_config.enable_embedded_javascript_udf => lang,
91                "rust" | "wasm" if udf_config.enable_embedded_wasm_udf => lang,
92                "python" | "javascript" | "rust" | "wasm" => {
93                    return Err(ErrorCode::InvalidParameterValue(format!(
94                        "{} UDF is not enabled in configuration",
95                        lang
96                    ))
97                    .into());
98                }
99                _ => {
100                    return Err(ErrorCode::InvalidParameterValue(format!(
101                        "language {} is not supported",
102                        lang
103                    ))
104                    .into());
105                }
106            }
107        }
108        // Empty language is acceptable since we only require the external server implements the
109        // correct protocol.
110        None => "".to_owned(),
111    };
112
113    let runtime = match params.runtime {
114        Some(_) => {
115            return Err(ErrorCode::InvalidParameterValue(
116                "runtime selection is currently not supported".to_owned(),
117            )
118            .into());
119        }
120        None => None,
121    };
122
123    let return_type;
124    let kind = match returns {
125        Some(CreateFunctionReturns::Value(data_type)) => {
126            return_type = bind_data_type(&data_type)?;
127            Kind::Scalar(ScalarFunction {})
128        }
129        Some(CreateFunctionReturns::Table(columns)) => {
130            if columns.len() == 1 {
131                // return type is the original type for single column
132                return_type = bind_data_type(&columns[0].data_type)?;
133            } else {
134                // return type is a struct for multiple columns
135                let it = columns
136                    .into_iter()
137                    .map(|c| bind_data_type(&c.data_type).map(|ty| (c.name.real_value(), ty)));
138                let fields = it.try_collect::<_, Vec<_>, _>()?;
139                return_type = bind_struct_type(fields)?.into();
140            }
141            Kind::Table(TableFunction {})
142        }
143        None => {
144            return Err(ErrorCode::InvalidParameterValue(
145                "return type must be specified".to_owned(),
146            )
147            .into());
148        }
149    };
150
151    let udf_kind = match kind {
152        Kind::Scalar(_) => UdfKind::Scalar,
153        Kind::Table(_) => UdfKind::Table,
154        // Aggregate UDFs are created through `CREATE AGGREGATE` and
155        // `handle_create_aggregate`, not this `CREATE FUNCTION` handler.
156        Kind::Aggregate(_) => unreachable!(),
157    };
158    if let Some(behavior) = &params.behavior
159        && should_reject_function_behavior(behavior, udf_kind)
160    {
161        return Err(ErrorCode::InvalidParameterValue(format!(
162            "`{behavior}` is not supported for table functions"
163        ))
164        .into());
165    }
166    if with_options.unsafe_skip_materializing_exprs.is_some()
167        && should_reject_unsafe_skip_materializing_exprs(udf_kind)
168    {
169        return Err(ErrorCode::InvalidParameterValue(
170            "`unsafe_skip_materializing_exprs` is not supported for table functions".to_owned(),
171        )
172        .into());
173    }
174    let is_immutable = matches!(params.behavior, Some(FunctionBehavior::Immutable));
175    let unsafe_skip_materializing_exprs = with_options
176        .unsafe_skip_materializing_exprs
177        .unwrap_or_default();
178    if unsafe_skip_materializing_exprs && !is_immutable {
179        return Err(ErrorCode::InvalidParameterValue(
180            "`IMMUTABLE` must be specified when `unsafe_skip_materializing_exprs` is true"
181                .to_owned(),
182        )
183        .into());
184    }
185
186    let mut arg_names = vec![];
187    let mut arg_types = vec![];
188    for arg in args.unwrap_or_default() {
189        arg_names.push(arg.name.map_or("".to_owned(), |n| n.real_value()));
190        arg_types.push(bind_data_type(&arg.data_type)?);
191    }
192
193    reject_variant_in_udf_signature(&return_type, &arg_types, "function")?;
194
195    // resolve database and schema id
196    let session = &handler_args.session;
197    let db_name = &session.database();
198    let (schema_name, function_name) = Binder::resolve_schema_qualified_name(db_name, &name)?;
199    let (database_id, schema_id) = session.get_database_and_schema_id_for_create(schema_name)?;
200
201    // check if the function exists in the catalog
202    if let Either::Right(resp) = session.check_function_name_duplicated(
203        StatementType::CREATE_FUNCTION,
204        name,
205        &arg_types,
206        if_not_exists,
207    )? {
208        return Ok(resp);
209    }
210
211    let link = match &params.using {
212        Some(CreateFunctionUsing::Link(l)) => Some(l.as_str()),
213        _ => None,
214    };
215    let base64_decoded = match &params.using {
216        Some(CreateFunctionUsing::Base64(encoded)) => {
217            use base64::prelude::{BASE64_STANDARD, Engine};
218            let bytes = BASE64_STANDARD
219                .decode(encoded)
220                .context("invalid base64 encoding")?;
221            Some(bytes)
222        }
223        _ => None,
224    };
225
226    let udf_impl = risingwave_expr::sig::find_udf_impl(&language, runtime.as_deref(), link)?;
227    let always_retry_on_network_error = with_options
228        .always_retry_on_network_error
229        .unwrap_or_default();
230    let supports_always_retry_on_network_error =
231        (udf_impl.supports_always_retry_on_network_error)(udf_kind);
232    if always_retry_on_network_error && !supports_always_retry_on_network_error {
233        return Err(ErrorCode::InvalidParameterValue(
234            "`always_retry_on_network_error` is not supported by this UDF implementation"
235                .to_owned(),
236        )
237        .into());
238    }
239    if is_immutable && supports_always_retry_on_network_error && !always_retry_on_network_error {
240        return Err(ErrorCode::InvalidParameterValue(
241            "`always_retry_on_network_error` must be true for an `IMMUTABLE` UDF whose implementation supports it"
242                .to_owned(),
243        )
244        .into());
245    }
246    let output = (udf_impl.create_fn)(CreateOptions {
247        kind: udf_kind,
248        name: &function_name,
249        arg_names: &arg_names,
250        arg_types: &arg_types,
251        return_type: &return_type,
252        as_: params.as_.as_ref().map(|s| s.as_str()),
253        using_link: link,
254        using_base64_decoded: base64_decoded.as_deref(),
255    })?;
256
257    let function = PbFunction {
258        id: FunctionId::placeholder(),
259        schema_id,
260        database_id,
261        name: function_name,
262        kind: Some(kind),
263        arg_names,
264        arg_types: arg_types.into_iter().map(|t| t.into()).collect(),
265        return_type: Some(return_type.into()),
266        language,
267        runtime,
268        name_in_runtime: Some(output.name_in_runtime),
269        link: link.map(|s| s.to_owned()),
270        body: output.body,
271        compressed_binary: output.compressed_binary,
272        owner: session.user_id(),
273        always_retry_on_network_error,
274        unsafe_skip_materializing_exprs,
275        is_immutable,
276        is_async: with_options.r#async,
277        is_batched: with_options.batch,
278        created_at_epoch: None,
279        created_at_cluster_version: None,
280    };
281
282    let catalog_writer = session.catalog_writer()?;
283    catalog_writer.create_function(function).await?;
284
285    Ok(PgResponse::empty_result(StatementType::CREATE_FUNCTION))
286}