risingwave_frontend/handler/
create_sql_function.rs1use 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 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 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 let body = match ¶ms.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 format!("select {}", params.return_.unwrap())
83 }
84 };
85
86 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 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 = bind_data_type(&columns[0].data_type)?;
105 } else {
106 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 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 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 {
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() )
154 .collect();
155
156 let expr = binder.bind_sql_udf_inner(&body, &arg_names, args)?;
157
158 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 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, body: Some(body),
183 compressed_binary: None,
184 link: None,
185 owner: session.user_id(),
186 always_retry_on_network_error: false,
187 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}