Skip to main content

risingwave_frontend/binder/expr/function/
mod.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 std::collections::{HashMap, HashSet};
16use std::str::FromStr;
17use std::sync::Arc;
18
19use anyhow::Context;
20use itertools::Itertools;
21use risingwave_common::acl::AclMode;
22use risingwave_common::bail_not_implemented;
23use risingwave_common::catalog::INFORMATION_SCHEMA_SCHEMA_NAME;
24use risingwave_common::license::Feature;
25use risingwave_common::secret::LocalSecretManager;
26use risingwave_common::types::{DataType, MapType, StructType};
27use risingwave_common::util::iter_util::ZipEqFast;
28use risingwave_expr::aggregate::AggType;
29use risingwave_expr::window_function::WindowFuncKind;
30use risingwave_sqlparser::ast::{
31    self, Expr as AstExpr, Function, FunctionArg, FunctionArgExpr, FunctionArgList, Ident,
32    OrderByExpr, SecretRefAsType, Statement, Window,
33};
34use risingwave_sqlparser::parser::Parser;
35
36use crate::binder::Binder;
37use crate::binder::bind_context::Clause;
38use crate::catalog::OwnedByUserCatalog;
39use crate::catalog::function_catalog::FunctionCatalog;
40use crate::error::{ErrorCode, Result, RwError};
41use crate::expr::{
42    Expr, ExprImpl, ExprType, FunctionCall, FunctionCallWithLambda, InputRef,
43    MSSQL_QUERY_ARG_COUNT, TableFunction, TableFunctionType, UserDefinedFunction,
44    expr_impl_to_string_fn,
45};
46use crate::handler::privilege::ObjectCheckItem;
47
48mod aggregate;
49mod ai_decide;
50mod builtin_scalar;
51mod window;
52
53// Defines system functions that without args, ref: https://www.postgresql.org/docs/current/functions-info.html
54const SYS_FUNCTION_WITHOUT_ARGS: &[&str] = &[
55    "session_user",
56    "user",
57    "current_user",
58    "current_role",
59    "current_catalog",
60    "current_schema",
61    "current_timestamp",
62];
63
64const INLINE_QUERY_ARG_LEN: usize = 6;
65const CDC_SOURCE_QUERY_ARG_LEN: usize = 2;
66
67pub(super) fn is_sys_function_without_args(ident: &Ident) -> bool {
68    SYS_FUNCTION_WITHOUT_ARGS
69        .iter()
70        .any(|e| ident.real_value().as_str() == *e && ident.quote_style().is_none())
71}
72
73macro_rules! reject_syntax {
74    ($pred:expr, $msg:expr) => {
75        if $pred {
76            return Err(ErrorCode::InvalidInputSyntax($msg.to_string()).into());
77        }
78    };
79
80    ($pred:expr, $fmt:expr, $($arg:tt)*) => {
81        if $pred {
82            return Err(ErrorCode::InvalidInputSyntax(
83                format!($fmt, $($arg)*)
84            ).into());
85        }
86    };
87}
88
89impl Binder {
90    /// Validate and resolve the args for the external-database `_query`
91    /// table-valued functions (`postgres_query`, `mysql_query`, and
92    /// `mssql_query`).
93    ///
94    /// Two calling forms are supported:
95    /// * **Inline form** (`inline_arg_len` args): each argument is cast to
96    ///   `varchar` and returned verbatim. The caller picks `inline_arg_len`
97    ///   because the per-connector inline signature differs (`postgres` /
98    ///   `mysql` = 6 args; `sqlserver` = 8 args to carry `encrypt` /
99    ///   `trust_cert`).
100    /// * **Source-reference form** (2 args: `cdc_source_name, query`): the
101    ///   named source's connection parameters and secrets are resolved,
102    ///   expanded into the inline shape, and the per-connector TLS flags
103    ///   are appended. **Crucially, this path enforces `AclMode::Select` on
104    ///   the source before the secrets are expanded.** Without this check,
105    ///   a non-owner caller could use
106    ///   `mssql_query('my_source', 'SELECT ...')` to query the external
107    ///   database using the source's elevated credentials.
108    fn bind_external_db_query_args(
109        &self,
110        schema_name: Option<&str>,
111        args: Vec<ExprImpl>,
112        inline_arg_len: usize,
113        expected_connector_name: &str,
114    ) -> Result<Vec<ExprImpl>> {
115        match args.len() {
116            n if n == inline_arg_len => {
117                let mut cast_args = Vec::with_capacity(n);
118                for arg in args {
119                    cast_args.push(arg.cast_implicit(&DataType::Varchar)?);
120                }
121                Ok(cast_args)
122            }
123            CDC_SOURCE_QUERY_ARG_LEN => {
124                use thiserror_ext::AsReport as _;
125
126                use crate::catalog::root_catalog::SchemaPath;
127
128                let schema_path = self.bind_schema_path(schema_name);
129                let raw_source_name = expr_impl_to_string_fn(&args[0])?;
130                // Accept `schema.source` and quoted identifiers, matching every other SQL surface.
131                // Historical behavior fed the whole string (dot included) into the catalog lookup,
132                // so a qualified name could never match and an unqualified name only searched the
133                // session `search_path` — which broke sources created in non-default schemas.
134                let object_name = Parser::parse_object_name_str(&raw_source_name).map_err(|e| {
135                    ErrorCode::BindError(format!(
136                        "invalid source name `{}`: {}",
137                        raw_source_name,
138                        e.to_report_string(),
139                    ))
140                })?;
141                let (explicit_schema, source_name) =
142                    Binder::resolve_schema_qualified_name(&self.db_name, &object_name)?;
143                let source_schema_path = match explicit_schema.as_deref() {
144                    Some(schema) => SchemaPath::Name(schema),
145                    None => schema_path,
146                };
147                let source_catalog = self
148                    .catalog
149                    .get_source_by_name(&self.db_name, source_schema_path, &source_name)?
150                    .0;
151
152                // Enforce the source's SELECT privilege *before* expanding
153                // secrets or doing schema discovery, so a non-owner caller
154                // cannot read the external database using a source they
155                // have no grant on. Same ordering as the inline-form arg
156                // cast above: refuse early, leak nothing.
157                self.check_privilege(
158                    ObjectCheckItem::new(
159                        source_catalog.owner,
160                        AclMode::Select,
161                        source_catalog.name.clone(),
162                        source_catalog.id,
163                    ),
164                    source_catalog.database_id,
165                )?;
166
167                if source_catalog.is_cdc_table_source() {
168                    return Err(ErrorCode::BindError(
169                        "mysql_query and postgres_query only accept shared CDC sources, not CDC table sources"
170                            .to_owned(),
171                    )
172                    .into());
173                }
174
175                if !source_catalog
176                    .connector_name()
177                    .eq_ignore_ascii_case(expected_connector_name)
178                {
179                    return Err(ErrorCode::BindError(format!(
180                        "TVF function only accepts `mysql-cdc`, `postgres-cdc` and `sqlserver-cdc` source. Expected: {}, but got: {}",
181                        expected_connector_name,
182                        source_catalog.connector_name()
183                    ))
184                    .into());
185                }
186
187                let (props, secret_refs) = source_catalog.with_properties.clone().into_parts();
188                let secret_resolved =
189                    LocalSecretManager::global().fill_secrets(props, secret_refs)?;
190
191                let mut args_vec = vec![
192                    ExprImpl::literal_varchar(secret_resolved["hostname"].clone()),
193                    ExprImpl::literal_varchar(secret_resolved["port"].clone()),
194                    ExprImpl::literal_varchar(secret_resolved["username"].clone()),
195                    ExprImpl::literal_varchar(secret_resolved["password"].clone()),
196                    ExprImpl::literal_varchar(secret_resolved["database.name"].clone()),
197                    args[1].clone().cast_implicit(&DataType::Varchar)?,
198                ];
199
200                if expected_connector_name.eq_ignore_ascii_case("postgres-cdc") {
201                    args_vec.push(ExprImpl::literal_varchar(
202                        secret_resolved.get("ssl.mode").cloned().unwrap_or_default(),
203                    ));
204                    args_vec.push(ExprImpl::literal_varchar(
205                        secret_resolved
206                            .get("ssl.root.cert")
207                            .cloned()
208                            .unwrap_or_default(),
209                    ));
210                } else if expected_connector_name.eq_ignore_ascii_case("sqlserver-cdc") {
211                    // The CDC source is the source of truth for whether the
212                    // SQL Server connection requires TLS. Normalize the
213                    // source property to the public TVF's string argument;
214                    // `TableFunction::new_mssql_query` parses it once and
215                    // carries a boolean through the internal plan.
216                    let encrypt = secret_resolved
217                        .get("database.encrypt")
218                        .map(|v| v.eq_ignore_ascii_case("true").to_string())
219                        .unwrap_or_else(|| "false".to_owned());
220                    args_vec.push(ExprImpl::literal_varchar(encrypt));
221                    // The CDC implementation sets `trust_cert`
222                    // unconditionally (see
223                    // `connector::sink::sqlserver::SqlServerClient::new`),
224                    // so the source-reference form mirrors that.
225                    args_vec.push(ExprImpl::literal_varchar("true".to_owned()));
226                }
227
228                Ok(args_vec)
229            }
230            _ => {
231                let func_name = match expected_connector_name.to_ascii_lowercase().as_str() {
232                    "postgres-cdc" => "postgres_query",
233                    "mysql-cdc" => "mysql_query",
234                    "sqlserver-cdc" => "mssql_query",
235                    _ => "external _query",
236                };
237                Err(ErrorCode::BindError(format!(
238                    "{func_name} function accepts either 2 arguments: \
239                     (cdc_source_name varchar, query varchar) or {inline_arg_len} arguments \
240                     for the inline form (see mssql_query / postgres_query / mysql_query \
241                     documentation)"
242                ))
243                .into())
244            }
245        }
246    }
247
248    pub(in crate::binder) fn bind_function(
249        &mut self,
250        Function {
251            scalar_as_agg,
252            name,
253            arg_list,
254            within_group,
255            filter,
256            over,
257        }: &Function,
258    ) -> Result<ExprImpl> {
259        let (schema_name, func_name) = match name.0.as_slice() {
260            [name] => (None, name.real_value()),
261            [schema, name] => {
262                let schema_name = schema.real_value();
263                let func_name = if schema_name == INFORMATION_SCHEMA_SCHEMA_NAME {
264                    // definition of information_schema: https://github.com/postgres/postgres/blob/e0b2eed047df9045664da6f724cb42c10f8b12f0/src/backend/catalog/information_schema.sql
265                    //
266                    // FIXME: handle schema correctly, so that the functions are hidden if the schema is not in the search path.
267                    let function_name = name.real_value();
268                    if function_name != "_pg_expandarray" {
269                        bail_not_implemented!(
270                            issue = 12422,
271                            "Unsupported function name under schema: {}",
272                            schema_name
273                        );
274                    }
275                    function_name
276                } else {
277                    name.real_value()
278                };
279                (Some(schema_name), func_name)
280            }
281            [database, schema, name] => {
282                // Support database.schema.function qualified names when database matches current database
283                let database_name = database.real_value();
284                if database_name != self.db_name {
285                    return Err(ErrorCode::BindError(format!(
286                        "Cross-database function call is not supported: {}",
287                        name
288                    ))
289                    .into());
290                }
291                let schema_name = schema.real_value();
292                let func_name = name.real_value();
293                (Some(schema_name), func_name)
294            }
295            _ => bail_not_implemented!(issue = 112, "qualified function {}", name),
296        };
297
298        // FIXME: This is a hack to support [Bytebase queries](https://github.com/TennyZhuang/bytebase/blob/4a26f7c62b80e86e58ad2f77063138dc2f420623/backend/plugin/db/pg/sync.go#L549).
299        // Bytebase widely used the pattern like `obj_description(format('%s.%s',
300        // quote_ident(idx.schemaname), quote_ident(idx.indexname))::regclass) AS comment` to
301        // retrieve object comment, however we don't support casting a non-literal expression to
302        // regclass. We just hack the `obj_description` and `col_description` here, to disable it to
303        // bind its arguments.
304        if func_name == "obj_description" || func_name == "col_description" {
305            return Ok(ExprImpl::literal_varchar("".to_owned()));
306        }
307
308        // special binding logic for `array_transform` and `map_filter`
309        if func_name == "array_transform" || func_name == "map_filter" {
310            return self.validate_and_bind_special_function_params(
311                &func_name,
312                *scalar_as_agg,
313                arg_list,
314                within_group.as_deref(),
315                filter.as_deref(),
316                over.as_ref(),
317            );
318        }
319
320        // Bind function arguments. Secret references are bound as ExprImpl::SecretRef first,
321        // and then restricted to UDF calls below.
322        let has_secret_ref_arg = arg_list.args.iter().any(|arg| {
323            matches!(
324                arg,
325                FunctionArg::Unnamed(FunctionArgExpr::SecretRef(_))
326                    | FunctionArg::Named {
327                        arg: FunctionArgExpr::SecretRef(_),
328                        ..
329                    }
330            )
331        });
332
333        // Return a clear usage error before secret lookup when there is no UDF candidate by name.
334        // This avoids leaking "not found" for secret refs used in clearly invalid contexts.
335        if has_secret_ref_arg {
336            let has_udf_candidate = self
337                .catalog
338                .get_functions_by_name(
339                    &self.db_name,
340                    self.bind_schema_path(schema_name.as_deref()),
341                    &func_name,
342                )
343                .map(|(funcs, _)| !funcs.is_empty())
344                .unwrap_or(false);
345            if !has_udf_candidate {
346                return Err(ErrorCode::InvalidInputSyntax(
347                    "secret reference is only allowed in user-defined function arguments"
348                        .to_owned(),
349                )
350                .into());
351            }
352        }
353
354        let bind_arg = if func_name.eq_ignore_ascii_case("jsonb_agg") {
355            Self::bind_jsonb_agg_arg
356        } else {
357            Self::bind_function_arg
358        };
359        let mut args: Vec<ExprImpl> = arg_list
360            .args
361            .iter()
362            .map(|arg| bind_arg(self, arg))
363            .flatten_ok()
364            .try_collect()?;
365
366        let mut referred_udfs = HashSet::new();
367        let mut is_udf_call = false;
368
369        let wrapped_agg_type = if *scalar_as_agg {
370            // Let's firstly try to apply the `AGGREGATE:` prefix.
371            // We will reject functions that are not able to be wrapped as aggregate function.
372            let mut array_args = args
373                .iter()
374                .enumerate()
375                .map(|(i, expr)| InputRef::new(i, DataType::list(expr.return_type())).into())
376                .collect_vec();
377            let schema_path = self.bind_schema_path(schema_name.as_deref());
378            let scalar_func_expr = if let Ok((func, _)) = self.catalog.get_function_by_name_inputs(
379                &self.db_name,
380                schema_path,
381                &func_name,
382                &mut array_args,
383            ) {
384                // record the dependency upon the UDF
385                referred_udfs.insert(func.id);
386                is_udf_call = true;
387                self.check_privilege(
388                    ObjectCheckItem::new(func.owner, AclMode::Execute, func.name.clone(), func.id),
389                    self.database_id,
390                )?;
391
392                if !func.kind.is_scalar() {
393                    return Err(ErrorCode::InvalidInputSyntax(
394                        "expect a scalar function after `AGGREGATE:`".to_owned(),
395                    )
396                    .into());
397                }
398
399                if func.language == "sql" {
400                    self.bind_sql_udf(func.clone(), array_args)?
401                } else {
402                    UserDefinedFunction::new(func.clone(), array_args).into()
403                }
404            } else {
405                self.bind_builtin_scalar_function(&func_name, array_args, arg_list.variadic)?
406            };
407
408            // `AggType::WrapScalar` requires the inner expression to be convertible to `ExprNode`
409            // and directly executable. If there's any subquery in the expression, this will fail.
410            let expr_node = match scalar_func_expr.try_to_expr_proto() {
411                Ok(expr_node) => expr_node,
412                Err(e) => {
413                    return Err(ErrorCode::InvalidInputSyntax(format!(
414                        "function {func_name} cannot be used after `AGGREGATE:`: {e}",
415                    ))
416                    .into());
417                }
418            };
419
420            // now this is either an aggregate/window function call
421            Some(AggType::WrapScalar(expr_node))
422        } else {
423            None
424        };
425
426        let schema_path = self.bind_schema_path(schema_name.as_deref());
427        let udf = if wrapped_agg_type.is_none()
428            && let Ok((func, _)) = self.catalog.get_function_by_name_inputs(
429                &self.db_name,
430                schema_path,
431                &func_name,
432                &mut args,
433            ) {
434            // record the dependency upon the UDF
435            referred_udfs.insert(func.id);
436            is_udf_call = true;
437            self.check_privilege(
438                ObjectCheckItem::new(func.owner, AclMode::Execute, func.name.clone(), func.id),
439                self.database_id,
440            )?;
441            Some(func.clone())
442        } else {
443            None
444        };
445
446        if has_secret_ref_arg && !is_udf_call {
447            return Err(ErrorCode::InvalidInputSyntax(
448                "secret reference is only allowed in user-defined function arguments".to_owned(),
449            )
450            .into());
451        }
452
453        self.included_udfs.extend(referred_udfs);
454
455        let agg_type = if wrapped_agg_type.is_some() {
456            wrapped_agg_type
457        } else if let Some(ref udf) = udf
458            && udf.kind.is_aggregate()
459        {
460            assert_ne!(udf.language, "sql", "SQL UDAF is not supported yet");
461            Some(AggType::UserDefined(udf.as_ref().into()))
462        } else {
463            AggType::from_str(&func_name).ok()
464        };
465
466        // try to bind it as a window function call
467        if let Some(over) = over {
468            reject_syntax!(
469                arg_list.distinct,
470                "`DISTINCT` is not allowed in window function call"
471            );
472            reject_syntax!(
473                arg_list.variadic,
474                "`VARIADIC` is not allowed in window function call"
475            );
476            reject_syntax!(
477                !arg_list.order_by.is_empty(),
478                "`ORDER BY` is not allowed in window function call argument list"
479            );
480            reject_syntax!(
481                within_group.is_some(),
482                "`WITHIN GROUP` is not allowed in window function call"
483            );
484
485            let kind = if let Some(agg_type) = agg_type {
486                // aggregate as window function
487                WindowFuncKind::Aggregate(agg_type)
488            } else if let Ok(kind) = WindowFuncKind::from_str(&func_name) {
489                kind
490            } else {
491                bail_not_implemented!(issue = 8961, "Unrecognized window function: {}", func_name);
492            };
493            return self.bind_window_function(
494                kind,
495                args,
496                arg_list.ignore_nulls,
497                filter.as_deref(),
498                over,
499            );
500        }
501
502        // now it's an aggregate/scalar/table function call
503        reject_syntax!(
504            arg_list.ignore_nulls,
505            "`IGNORE NULLS` is not allowed in aggregate/scalar/table function call"
506        );
507
508        // try to bind it as an aggregate function call
509        if let Some(agg_type) = agg_type {
510            reject_syntax!(
511                arg_list.variadic,
512                "`VARIADIC` is not allowed in aggregate function call"
513            );
514            return self.bind_aggregate_function(
515                agg_type,
516                arg_list.distinct,
517                args,
518                &arg_list.order_by,
519                within_group.as_deref(),
520                filter.as_deref(),
521            );
522        }
523
524        // now it's a scalar/table function call
525        reject_syntax!(
526            arg_list.distinct,
527            "`DISTINCT` is not allowed in scalar/table function call"
528        );
529        reject_syntax!(
530            !arg_list.order_by.is_empty(),
531            "`ORDER BY` is not allowed in scalar/table function call"
532        );
533        reject_syntax!(
534            within_group.is_some(),
535            "`WITHIN GROUP` is not allowed in scalar/table function call"
536        );
537        reject_syntax!(
538            filter.is_some(),
539            "`FILTER` is not allowed in scalar/table function call"
540        );
541
542        // try to bind it as a table function call
543        {
544            // `file_scan` table function
545            if func_name.eq_ignore_ascii_case("file_scan") {
546                reject_syntax!(
547                    arg_list.variadic,
548                    "`VARIADIC` is not allowed in table function call"
549                );
550                self.ensure_table_function_allowed()?;
551                return Ok(TableFunction::new_file_scan(args)?.into());
552            }
553            // `postgres_query` table function
554            if func_name.eq("postgres_query") {
555                reject_syntax!(
556                    arg_list.variadic,
557                    "`VARIADIC` is not allowed in table function call"
558                );
559                self.ensure_table_function_allowed()?;
560                let args = self
561                    .bind_external_db_query_args(
562                        schema_name.as_deref(),
563                        args,
564                        INLINE_QUERY_ARG_LEN,
565                        "postgres-cdc",
566                    )
567                    .context("postgres_query error")?;
568                return Ok(TableFunction::new_postgres_query(args)
569                    .context("postgres_query error")?
570                    .into());
571            }
572            // `mysql_query` table function
573            if func_name.eq("mysql_query") {
574                reject_syntax!(
575                    arg_list.variadic,
576                    "`VARIADIC` is not allowed in table function call"
577                );
578                self.ensure_table_function_allowed()?;
579                let args = self
580                    .bind_external_db_query_args(
581                        schema_name.as_deref(),
582                        args,
583                        INLINE_QUERY_ARG_LEN,
584                        "mysql-cdc",
585                    )
586                    .context("mysql_query error")?;
587                return Ok(TableFunction::new_mysql_query(args)
588                    .context("mysql_query error")?
589                    .into());
590            }
591            // `mssql_query` table function (enterprise feature)
592            if func_name.eq("mssql_query") {
593                reject_syntax!(
594                    arg_list.variadic,
595                    "`VARIADIC` is not allowed in table function call"
596                );
597                self.ensure_table_function_allowed()?;
598
599                // Reuse the SQL Server CDC source entitlement instead of
600                // introducing a separate license gate for this query surface.
601                Feature::SqlServerCdcSource.check_available()?;
602
603                let args = self
604                    .bind_external_db_query_args(
605                        schema_name.as_deref(),
606                        args,
607                        MSSQL_QUERY_ARG_COUNT,
608                        "sqlserver-cdc",
609                    )
610                    .context("mssql_query error")?;
611                return Ok(TableFunction::new_mssql_query(args)
612                    .context("mssql_query error")?
613                    .into());
614            }
615            // `internal_backfill_progress` table function
616            if func_name.eq("internal_backfill_progress") {
617                reject_syntax!(
618                    arg_list.variadic,
619                    "`VARIADIC` is not allowed in table function call"
620                );
621                self.ensure_table_function_allowed()?;
622                return Ok(TableFunction::new_internal_backfill_progress().into());
623            }
624            // `internal_source_backfill_progress` table function
625            if func_name.eq("internal_source_backfill_progress") {
626                reject_syntax!(
627                    arg_list.variadic,
628                    "`VARIADIC` is not allowed in table function call"
629                );
630                self.ensure_table_function_allowed()?;
631                return Ok(TableFunction::new_internal_source_backfill_progress().into());
632            }
633            // `internal_get_channel_delta_stats` table function
634            if func_name.eq("internal_get_channel_delta_stats") {
635                reject_syntax!(
636                    arg_list.variadic,
637                    "`VARIADIC` is not allowed in table function call"
638                );
639                self.ensure_table_function_allowed()?;
640
641                return Ok(TableFunction::new_internal_get_channel_delta_stats(args).into());
642            }
643            // UDTF
644            if let Some(ref udf) = udf
645                && udf.kind.is_table()
646            {
647                reject_syntax!(
648                    arg_list.variadic,
649                    "`VARIADIC` is not allowed in table function call"
650                );
651                self.ensure_table_function_allowed()?;
652                if udf.language == "sql" {
653                    return self.bind_sql_udf(udf.clone(), args);
654                }
655                return Ok(TableFunction::new_user_defined(udf.clone(), args).into());
656            }
657            // builtin table function
658            if let Ok(function_type) = TableFunctionType::from_str(&func_name) {
659                reject_syntax!(
660                    arg_list.variadic,
661                    "`VARIADIC` is not allowed in table function call"
662                );
663                self.ensure_table_function_allowed()?;
664                return Ok(TableFunction::new(function_type, args)?.into());
665            }
666        }
667
668        // try to bind it as a scalar function call
669        if let Some(ref udf) = udf {
670            assert!(udf.kind.is_scalar());
671            reject_syntax!(
672                arg_list.variadic,
673                "`VARIADIC` is not allowed in user-defined function call"
674            );
675            if udf.language == "sql" {
676                return self.bind_sql_udf(udf.clone(), args);
677            }
678            return Ok(UserDefinedFunction::new(udf.clone(), args).into());
679        }
680
681        self.bind_builtin_scalar_function(&func_name, args, arg_list.variadic)
682    }
683
684    fn validate_and_bind_special_function_params(
685        &mut self,
686        func_name: &str,
687        scalar_as_agg: bool,
688        arg_list: &FunctionArgList,
689        within_group: Option<&OrderByExpr>,
690        filter: Option<&risingwave_sqlparser::ast::Expr>,
691        over: Option<&Window>,
692    ) -> Result<ExprImpl> {
693        assert!(["array_transform", "map_filter"].contains(&func_name));
694
695        reject_syntax!(
696            scalar_as_agg,
697            "`AGGREGATE:` prefix is not allowed for `{}`",
698            func_name
699        );
700        reject_syntax!(
701            !arg_list.is_args_only(),
702            "keywords like `DISTINCT`, `ORDER BY` are not allowed in `{}` argument list",
703            func_name
704        );
705        reject_syntax!(
706            within_group.is_some(),
707            "`WITHIN GROUP` is not allowed in `{}` call",
708            func_name
709        );
710        reject_syntax!(
711            filter.is_some(),
712            "`FILTER` is not allowed in `{}` call",
713            func_name
714        );
715        reject_syntax!(
716            over.is_some(),
717            "`OVER` is not allowed in `{}` call",
718            func_name
719        );
720        if func_name == "array_transform" {
721            self.bind_array_transform(&arg_list.args)
722        } else {
723            self.bind_map_filter(&arg_list.args)
724        }
725    }
726
727    fn bind_array_transform(&mut self, args: &[FunctionArg]) -> Result<ExprImpl> {
728        let [array, lambda] = args else {
729            return Err(ErrorCode::BindError(format!(
730                "`array_transform` expect two inputs `array` and `lambda`, but {} were given",
731                args.len()
732            ))
733            .into());
734        };
735
736        let bound_array = self.bind_function_arg(array)?;
737        let [bound_array] = <[ExprImpl; 1]>::try_from(bound_array).map_err(|bound_array| -> RwError {
738            ErrorCode::BindError(format!("The `array` argument for `array_transform` should be bound to one argument, but {} were got", bound_array.len()))
739                .into()
740        })?;
741
742        let inner_ty = match bound_array.return_type() {
743            DataType::List(ty) => ty.into_elem(),
744            real_type => return Err(ErrorCode::BindError(format!(
745                "The `array` argument for `array_transform` should be an array, but {} were got",
746                real_type
747            ))
748            .into()),
749        };
750
751        let ast::FunctionArgExpr::Expr(ast::Expr::LambdaFunction {
752            args: lambda_args,
753            body: lambda_body,
754        }) = lambda.get_expr()
755        else {
756            return Err(ErrorCode::BindError(
757                "The `lambda` argument for `array_transform` should be a lambda function"
758                    .to_owned(),
759            )
760            .into());
761        };
762
763        let [lambda_arg] = <[Ident; 1]>::try_from(lambda_args).map_err(|args| -> RwError {
764            ErrorCode::BindError(format!(
765                "The `lambda` argument for `array_transform` should be a lambda function with one argument, but {} were given",
766                args.len()
767            ))
768            .into()
769        })?;
770
771        let bound_lambda = self.bind_unary_lambda_function(inner_ty, lambda_arg, *lambda_body)?;
772
773        let lambda_ret_type = bound_lambda.return_type();
774        let transform_ret_type = DataType::list(lambda_ret_type);
775
776        Ok(ExprImpl::FunctionCallWithLambda(Box::new(
777            FunctionCallWithLambda::new_unchecked(
778                ExprType::ArrayTransform,
779                vec![bound_array],
780                bound_lambda,
781                transform_ret_type,
782            ),
783        )))
784    }
785
786    fn bind_unary_lambda_function(
787        &mut self,
788        input_ty: DataType,
789        arg: Ident,
790        body: ast::Expr,
791    ) -> Result<ExprImpl> {
792        let lambda_args = HashMap::from([(arg.real_value(), (0usize, input_ty))]);
793        let orig_lambda_args = self.context.lambda_args.replace(lambda_args);
794        let body = self.bind_expr_inner(&body)?;
795        self.context.lambda_args = orig_lambda_args;
796
797        Ok(body)
798    }
799
800    fn bind_map_filter(&mut self, args: &[FunctionArg]) -> Result<ExprImpl> {
801        let [input, lambda] = args else {
802            return Err(ErrorCode::BindError(format!(
803                "`map_filter` requires two arguments (input_map and lambda), got {}",
804                args.len()
805            ))
806            .into());
807        };
808
809        let bound_input = self.bind_function_arg(input)?;
810        let [bound_input] = <[ExprImpl; 1]>::try_from(bound_input).map_err(|e| {
811            ErrorCode::BindError(format!(
812                "Input argument should resolve to single expression, got {}",
813                e.len()
814            ))
815        })?;
816
817        let (key_type, value_type) = match bound_input.return_type() {
818            DataType::Map(map_type) => (map_type.key().clone(), map_type.value().clone()),
819            t => {
820                return Err(
821                    ErrorCode::BindError(format!("Input must be Map type, got {}", t)).into(),
822                );
823            }
824        };
825
826        let ast::FunctionArgExpr::Expr(ast::Expr::LambdaFunction {
827            args: lambda_args,
828            body: lambda_body,
829        }) = lambda.get_expr()
830        else {
831            return Err(ErrorCode::BindError(
832                "Second argument must be a lambda function".to_owned(),
833            )
834            .into());
835        };
836
837        let [key_arg, value_arg] = <[Ident; 2]>::try_from(lambda_args).map_err(|args| {
838            ErrorCode::BindError(format!(
839                "Lambda must have exactly two parameters (key, value), got {}",
840                args.len()
841            ))
842        })?;
843
844        let bound_lambda = self.bind_binary_lambda_function(
845            key_arg,
846            key_type.clone(),
847            value_arg,
848            value_type.clone(),
849            *lambda_body,
850        )?;
851
852        let lambda_ret_type = bound_lambda.return_type();
853        if lambda_ret_type != DataType::Boolean {
854            return Err(ErrorCode::BindError(format!(
855                "Lambda must return Boolean type, got {}",
856                lambda_ret_type
857            ))
858            .into());
859        }
860
861        let map_type = MapType::from_kv(key_type, value_type);
862        let return_type = DataType::Map(map_type);
863
864        Ok(ExprImpl::FunctionCallWithLambda(Box::new(
865            FunctionCallWithLambda::new_unchecked(
866                ExprType::MapFilter,
867                vec![bound_input],
868                bound_lambda,
869                return_type,
870            ),
871        )))
872    }
873
874    fn bind_binary_lambda_function(
875        &mut self,
876        first_arg: Ident,
877        first_ty: DataType,
878        second_arg: Ident,
879        second_ty: DataType,
880        body: ast::Expr,
881    ) -> Result<ExprImpl> {
882        let lambda_args = HashMap::from([
883            (first_arg.real_value(), (0usize, first_ty)),
884            (second_arg.real_value(), (1usize, second_ty)),
885        ]);
886
887        let orig_ctx = self.context.lambda_args.replace(lambda_args);
888        let bound_body = self.bind_expr_inner(&body)?;
889        self.context.lambda_args = orig_ctx;
890
891        Ok(bound_body)
892    }
893
894    fn ensure_table_function_allowed(&self) -> Result<()> {
895        if let Some(clause) = self.context.clause {
896            match clause {
897                Clause::JoinOn
898                | Clause::Where
899                | Clause::Having
900                | Clause::Filter
901                | Clause::Values
902                | Clause::Insert
903                | Clause::GeneratedColumn => {
904                    return Err(ErrorCode::InvalidInputSyntax(format!(
905                        "table functions are not allowed in {}",
906                        clause
907                    ))
908                    .into());
909                }
910                Clause::GroupBy | Clause::From => {}
911            }
912        }
913        Ok(())
914    }
915
916    /// A common utility function to extract sql udf expression out from the input `ast`.
917    pub(crate) fn extract_udf_expr(ast: Vec<Statement>) -> Result<AstExpr> {
918        if ast.len() != 1 {
919            return Err(ErrorCode::InvalidInputSyntax(
920                "the query for sql udf should contain only one statement".to_owned(),
921            )
922            .into());
923        }
924
925        // Extract the expression out
926        let Statement::Query(query) = ast.into_iter().next().unwrap() else {
927            return Err(ErrorCode::InvalidInputSyntax(
928                "invalid function definition, please recheck the syntax".to_owned(),
929            )
930            .into());
931        };
932
933        if let Some(expr) = query.as_single_select_item() {
934            // Inline SQL UDF.
935            Ok(expr.clone())
936        } else {
937            // Subquery SQL UDF.
938            Ok(AstExpr::Subquery(query))
939        }
940    }
941
942    pub fn bind_sql_udf_inner(
943        &mut self,
944        body: &str,
945        arg_names: &[String],
946        args: Vec<ExprImpl>,
947    ) -> Result<ExprImpl> {
948        // This represents the current user defined function is `language sql`
949        let ast = Parser::parse_sql(body)?;
950
951        // Stash the current arguments.
952        // For subquery SQL UDF, as we always push a new context, there should be no arguments to stash.
953        // For inline SQL UDF, we need to stash the arguments in case of nesting.
954        let stashed_arguments = self.context.sql_udf_arguments.take();
955
956        // The actual inline logic for sql udf.
957        let mut arguments = HashMap::new();
958        for (i, arg) in args.into_iter().enumerate() {
959            if arg_names[i].is_empty() {
960                // unnamed argument, use `$1`, `$2` as the name
961                arguments.insert(format!("${}", i + 1), arg);
962            } else {
963                // named argument
964                arguments.insert(arg_names[i].clone(), arg);
965            }
966        }
967        self.context.sql_udf_arguments = Some(arguments);
968
969        let Ok(expr) = Self::extract_udf_expr(ast) else {
970            return Err(ErrorCode::InvalidInputSyntax(
971                "failed to parse the input query and extract the udf expression, \
972                please recheck the syntax"
973                    .to_owned(),
974            )
975            .into());
976        };
977
978        let bind_result = self.bind_expr(&expr);
979        // Restore arguments information for subsequent binding.
980        self.context.sql_udf_arguments = stashed_arguments;
981
982        bind_result
983    }
984
985    fn bind_sql_udf(
986        &mut self,
987        func: Arc<FunctionCatalog>,
988        args: Vec<ExprImpl>,
989    ) -> Result<ExprImpl> {
990        let Some(body) = &func.body else {
991            return Err(
992                ErrorCode::InvalidInputSyntax("`body` must exist for sql udf".to_owned()).into(),
993            );
994        };
995
996        self.bind_sql_udf_inner(body, &func.arg_names, args)
997    }
998
999    pub(in crate::binder) fn bind_function_expr_arg(
1000        &mut self,
1001        arg_expr: &FunctionArgExpr,
1002    ) -> Result<Vec<ExprImpl>> {
1003        match arg_expr {
1004            FunctionArgExpr::Expr(expr) => Ok(vec![self.bind_expr_inner(expr)?]),
1005            FunctionArgExpr::QualifiedWildcard(_, _)
1006            | FunctionArgExpr::ExprQualifiedWildcard(_, _) => Err(ErrorCode::InvalidInputSyntax(
1007                format!("unexpected wildcard {}", arg_expr),
1008            )
1009            .into()),
1010            FunctionArgExpr::Wildcard(None) => Ok(vec![]),
1011            FunctionArgExpr::Wildcard(Some(_)) => unreachable!(),
1012            FunctionArgExpr::SecretRef(secret_ref_value) => {
1013                let (schema_name, secret_name) = Binder::resolve_schema_qualified_name(
1014                    &self.db_name,
1015                    &secret_ref_value.secret_name,
1016                )?;
1017                let schema_path = self.bind_schema_path(schema_name.as_deref());
1018                let (secret_catalog, _) =
1019                    self.catalog
1020                        .get_secret_by_name(&self.db_name, schema_path, &secret_name)?;
1021
1022                self.check_privilege(
1023                    ObjectCheckItem::new(
1024                        secret_catalog.owner(),
1025                        AclMode::Usage,
1026                        secret_catalog.name.clone(),
1027                        secret_catalog.id,
1028                    ),
1029                    self.database_id,
1030                )?;
1031
1032                self.included_secrets.insert(secret_catalog.id);
1033
1034                let ref_as = match secret_ref_value.ref_as {
1035                    SecretRefAsType::Text => risingwave_pb::secret::secret_ref::RefAsType::Text,
1036                    SecretRefAsType::File => risingwave_pb::secret::secret_ref::RefAsType::File,
1037                };
1038
1039                Ok(vec![
1040                    crate::expr::SecretRef {
1041                        secret_id: secret_catalog.id,
1042                        ref_as,
1043                        secret_name: secret_catalog.name.clone(),
1044                    }
1045                    .into(),
1046                ])
1047            }
1048        }
1049    }
1050
1051    pub(in crate::binder) fn bind_function_arg(
1052        &mut self,
1053        arg: &FunctionArg,
1054    ) -> Result<Vec<ExprImpl>> {
1055        match arg {
1056            FunctionArg::Unnamed(expr) => self.bind_function_expr_arg(expr),
1057            FunctionArg::Named { .. } => Err(ErrorCode::InvalidInputSyntax(
1058                "named function arguments are not supported yet".to_owned(),
1059            )
1060            .into()),
1061        }
1062    }
1063
1064    fn bind_jsonb_agg_arg(&mut self, arg: &FunctionArg) -> Result<Vec<ExprImpl>> {
1065        match arg {
1066            FunctionArg::Unnamed(FunctionArgExpr::QualifiedWildcard(prefix, except)) => {
1067                let (schema_name, table_name) =
1068                    Binder::resolve_schema_qualified_name(&self.db_name, prefix)?;
1069                let except_indices = self.generate_except_indices(except.as_deref())?;
1070                let (begin, end) = self
1071                    .context
1072                    .resolve_relation_range(&table_name, &schema_name)?;
1073                let (exprs, names) = Self::iter_bound_columns(
1074                    self.context.columns[begin..end]
1075                        .iter()
1076                        .filter(|c| !c.is_hidden && !except_indices.contains(&c.index)),
1077                );
1078                self.wrap_wildcard_exprs_as_named_row(exprs, names)
1079            }
1080            FunctionArg::Unnamed(FunctionArgExpr::ExprQualifiedWildcard(expr, prefix)) => {
1081                let (exprs, names) = self.bind_wildcard_field_column(expr, prefix)?;
1082                self.wrap_wildcard_exprs_as_named_row(exprs, names)
1083            }
1084            _ => self.bind_function_arg(arg),
1085        }
1086    }
1087
1088    fn wrap_wildcard_exprs_as_named_row(
1089        &self,
1090        exprs: Vec<ExprImpl>,
1091        names: Vec<Option<String>>,
1092    ) -> Result<Vec<ExprImpl>> {
1093        let return_type =
1094            DataType::Struct(StructType::new(
1095                names.into_iter().zip_eq_fast(exprs.iter()).enumerate().map(
1096                    |(idx, (name, expr))| {
1097                        (
1098                            name.unwrap_or_else(|| format!("f{}", idx + 1)),
1099                            expr.return_type(),
1100                        )
1101                    },
1102                ),
1103            ));
1104        Ok(vec![
1105            FunctionCall::new_unchecked(ExprType::Row, exprs, return_type).into(),
1106        ])
1107    }
1108}