Skip to main content

risingwave_frontend/handler/
create_sql_function.rs

1// Copyright 2024 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 either::Either;
16use risingwave_common::catalog::FunctionId;
17use risingwave_pb::catalog::PbFunction;
18use risingwave_pb::catalog::function::{Kind, ScalarFunction, TableFunction};
19
20use super::*;
21use crate::binder::bind_struct_type;
22use crate::expr::{Expr, Literal};
23use crate::{Binder, bind_data_type};
24
25pub async fn handle_create_sql_function(
26    handler_args: HandlerArgs,
27    or_replace: bool,
28    temporary: bool,
29    if_not_exists: bool,
30    name: ObjectName,
31    args: Option<Vec<OperateFunctionArg>>,
32    returns: Option<CreateFunctionReturns>,
33    params: CreateFunctionBody,
34    with_options: CreateFunctionWithOptions,
35) -> Result<RwPgResponse> {
36    if or_replace {
37        bail_not_implemented!("CREATE OR REPLACE FUNCTION");
38    }
39
40    if temporary {
41        bail_not_implemented!("CREATE TEMPORARY FUNCTION");
42    }
43
44    // TODO: `UdfKind` has no variant for SQL functions, so the shared `should_reject_function_behavior`
45    // and `should_reject_unsafe_skip_materializing_exprs` predicates cannot be used here yet. Once SQL
46    // functions are representable there, replace this check with calls to both of them.
47    if with_options.unsafe_skip_materializing_exprs.is_some() {
48        return Err(ErrorCode::InvalidParameterValue(
49            "`unsafe_skip_materializing_exprs` is not supported for SQL functions".to_owned(),
50        )
51        .into());
52    }
53
54    let language = "sql".to_owned();
55
56    // Just a basic sanity check for `language`
57    if !matches!(params.language, Some(lang) if lang.real_value().to_lowercase() == "sql") {
58        return Err(ErrorCode::InvalidParameterValue(
59            "`language` for sql udf must be `sql`".to_owned(),
60        )
61        .into());
62    }
63
64    // SQL udf function supports both single quote (i.e., as 'select $1 + $2')
65    // and double dollar (i.e., as $$select $1 + $2$$) for as clause
66    let body = match &params.as_ {
67        Some(FunctionDefinition::SingleQuotedDef(s)) => s.clone(),
68        Some(FunctionDefinition::DoubleDollarDef(s)) => s.clone(),
69        Some(FunctionDefinition::Identifier(_)) => {
70            return Err(ErrorCode::InvalidParameterValue("expect quoted string".to_owned()).into());
71        }
72        None => {
73            if params.return_.is_none() {
74                return Err(ErrorCode::InvalidParameterValue(
75                    "AS or RETURN must be specified".to_owned(),
76                )
77                .into());
78            }
79            // Otherwise this is a return expression
80            // Note: this is a current work around, and we are assuming return sql udf
81            // will NOT involve complex syntax, so just reuse the logic for select definition
82            format!("select {}", params.return_.unwrap())
83        }
84    };
85
86    // Sanity check for link, this must be none with sql udf function
87    if let Some(CreateFunctionUsing::Link(_)) = params.using {
88        return Err(ErrorCode::InvalidParameterValue(
89            "USING must NOT be specified with sql udf function".to_owned(),
90        )
91        .into());
92    };
93
94    // Get return type for the current sql udf function
95    let return_type;
96    let kind = match returns {
97        Some(CreateFunctionReturns::Value(data_type)) => {
98            return_type = bind_data_type(&data_type)?;
99            Kind::Scalar(ScalarFunction {})
100        }
101        Some(CreateFunctionReturns::Table(columns)) => {
102            if columns.len() == 1 {
103                // return type is the original type for single column
104                return_type = bind_data_type(&columns[0].data_type)?;
105            } else {
106                // return type is a struct for multiple columns
107                let fields = columns
108                    .iter()
109                    .map(|c| Ok((c.name.real_value(), bind_data_type(&c.data_type)?)))
110                    .collect::<Result<Vec<_>>>()?;
111                return_type = bind_struct_type(fields)?.into();
112            }
113            Kind::Table(TableFunction {})
114        }
115        None => {
116            return Err(ErrorCode::InvalidParameterValue(
117                "return type must be specified".to_owned(),
118            )
119            .into());
120        }
121    };
122
123    let mut arg_names = vec![];
124    let mut arg_types = vec![];
125    for arg in args.unwrap_or_default() {
126        arg_names.push(arg.name.map_or("".to_owned(), |n| n.real_value()));
127        arg_types.push(bind_data_type(&arg.data_type)?);
128    }
129
130    // resolve database and schema id
131    let session = &handler_args.session;
132    let db_name = &session.database();
133    let (schema_name, function_name) = Binder::resolve_schema_qualified_name(db_name, &name)?;
134    let (database_id, schema_id) = session.get_database_and_schema_id_for_create(schema_name)?;
135
136    // check if function exists
137    if let Either::Right(resp) = session.check_function_name_duplicated(
138        StatementType::CREATE_FUNCTION,
139        name,
140        &arg_types,
141        if_not_exists,
142    )? {
143        return Ok(resp);
144    }
145
146    // Try bind the function call with mock arguments.
147    // Note that the parsing here is just basic syntax / semantic check, the result will NOT be stored
148    // e.g., The provided function body contains invalid syntax, return type mismatch, ..., etc.
149    {
150        let mut binder = Binder::new_for_system(session);
151        let args = arg_types
152            .iter()
153            .map(|ty| Literal::new(None, ty.clone()).into() /* NULL */)
154            .collect();
155
156        let expr = binder.bind_sql_udf_inner(&body, &arg_names, args)?;
157
158        // Check if the return type mismatches
159        if expr.return_type() != return_type {
160            return Err(ErrorCode::InvalidInputSyntax(format!(
161                "return type mismatch detected\nexpected: [{}]\nactual: [{}]\nplease adjust your function definition accordingly",
162                return_type,
163                expr.return_type()
164            ))
165            .into());
166        }
167    }
168
169    // Create the actual function, will be stored in function catalog
170    let function = PbFunction {
171        id: FunctionId::placeholder(),
172        schema_id,
173        database_id,
174        name: function_name,
175        kind: Some(kind),
176        arg_names,
177        arg_types: arg_types.into_iter().map(|t| t.into()).collect(),
178        return_type: Some(return_type.into()),
179        language,
180        runtime: None,
181        name_in_runtime: None, // None for SQL UDF
182        body: Some(body),
183        compressed_binary: None,
184        link: None,
185        owner: session.user_id(),
186        always_retry_on_network_error: false,
187        // SQL UDF calls are inlined at bind time, so their purity is derived from the bound body
188        // and neither of these fields is ever read.
189        unsafe_skip_materializing_exprs: false,
190        is_immutable: false,
191        is_async: None,
192        is_batched: None,
193        created_at_epoch: None,
194        created_at_cluster_version: None,
195    };
196
197    let catalog_writer = session.catalog_writer()?;
198    catalog_writer.create_function(function).await?;
199
200    Ok(PgResponse::empty_result(StatementType::CREATE_FUNCTION))
201}