1use std::collections::HashMap;
16use std::sync::LazyLock;
17
18use bk_tree::{BKTree, metrics};
19use itertools::Itertools;
20use risingwave_common::session_config::USER_NAME_WILD_CARD;
21use risingwave_common::types::{DataType, ListValue, ScalarImpl, Timestamptz};
22use risingwave_common::{bail_not_implemented, current_cluster_version, no_function};
23use thiserror_ext::AsReport;
24
25use crate::Binder;
26use crate::binder::Clause;
27use crate::error::{ErrorCode, Result};
28use crate::expr::{CastContext, Expr, ExprImpl, ExprType, FunctionCall, Literal, Now};
29
30impl Binder {
31 pub(super) fn bind_builtin_scalar_function(
32 &mut self,
33 function_name: &str,
34 inputs: Vec<ExprImpl>,
35 variadic: bool,
36 ) -> Result<ExprImpl> {
37 type Inputs = Vec<ExprImpl>;
38
39 type Handle = Box<dyn Fn(&mut Binder, Inputs) -> Result<ExprImpl> + Sync + Send>;
40
41 fn rewrite(r#type: ExprType, rewriter: fn(Inputs) -> Result<Inputs>) -> Handle {
42 Box::new(move |_binder, mut inputs| {
43 inputs = (rewriter)(inputs)?;
44 Ok(FunctionCall::new(r#type, inputs)?.into())
45 })
46 }
47
48 fn raw_call(r#type: ExprType) -> Handle {
49 rewrite(r#type, Ok)
50 }
51
52 fn guard_by_len(expected_len: usize, handle: Handle) -> Handle {
53 Box::new(move |binder, inputs| {
54 if inputs.len() == expected_len {
55 handle(binder, inputs)
56 } else {
57 Err(ErrorCode::ExprError("unexpected arguments number".into()).into())
58 }
59 })
60 }
61
62 fn raw<F: Fn(&mut Binder, Inputs) -> Result<ExprImpl> + Sync + Send + 'static>(
63 f: F,
64 ) -> Handle {
65 Box::new(f)
66 }
67
68 fn dispatch_by_len(mapping: Vec<(usize, Handle)>) -> Handle {
69 Box::new(move |binder, inputs| {
70 for (len, handle) in &mapping {
71 if inputs.len() == *len {
72 return handle(binder, inputs);
73 }
74 }
75 Err(ErrorCode::ExprError("unexpected arguments number".into()).into())
76 })
77 }
78
79 fn raw_literal(literal: ExprImpl) -> Handle {
80 Box::new(move |_binder, _inputs| Ok(literal.clone()))
81 }
82
83 fn now() -> Handle {
84 guard_by_len(
85 0,
86 raw(move |binder, _inputs| {
87 binder.ensure_now_function_allowed()?;
88 Ok(Now.into())
91 }),
92 )
93 }
94
95 fn pi() -> Handle {
96 raw_literal(ExprImpl::literal_f64(std::f64::consts::PI))
97 }
98
99 fn proctime() -> Handle {
100 Box::new(move |binder, inputs| {
101 binder.ensure_proctime_function_allowed()?;
102 raw_call(ExprType::Proctime)(binder, inputs)
103 })
104 }
105
106 fn session_user() -> Handle {
108 guard_by_len(
109 0,
110 raw(|binder, _inputs| {
111 Ok(ExprImpl::literal_varchar(
112 binder.auth_context.user_name.clone(),
113 ))
114 }),
115 )
116 }
117
118 fn current_user() -> Handle {
122 guard_by_len(
123 0,
124 raw(|binder, _inputs| {
125 Ok(ExprImpl::literal_varchar(
126 binder.auth_context.user_name.clone(),
127 ))
128 }),
129 )
130 }
131
132 fn current_database() -> Handle {
135 guard_by_len(
136 0,
137 raw(|binder, _inputs| Ok(ExprImpl::literal_varchar(binder.db_name.clone()))),
138 )
139 }
140
141 static HANDLES: LazyLock<HashMap<&'static str, Handle>> = LazyLock::new(|| {
145 [
146 (
147 "booleq",
148 rewrite(ExprType::Equal, rewrite_two_bool_inputs),
149 ),
150 (
151 "boolne",
152 rewrite(ExprType::NotEqual, rewrite_two_bool_inputs),
153 ),
154 ("coalesce", rewrite(ExprType::Coalesce, |inputs| {
155 if inputs.iter().any(ExprImpl::has_table_function) {
156 return Err(ErrorCode::BindError("table functions are not allowed in COALESCE".into()).into());
157 }
158 Ok(inputs)
159 })),
160 (
161 "nullif",
162 rewrite(ExprType::Case, rewrite_nullif_to_case_when),
163 ),
164 (
165 "round",
166 dispatch_by_len(vec![
167 (2, raw_call(ExprType::RoundDigit)),
168 (1, raw_call(ExprType::Round)),
169 ]),
170 ),
171 ("pow", raw_call(ExprType::Pow)),
172 ("power", raw_call(ExprType::Pow)),
174 ("ceil", raw_call(ExprType::Ceil)),
175 ("ceiling", raw_call(ExprType::Ceil)),
176 ("floor", raw_call(ExprType::Floor)),
177 ("trunc", raw_call(ExprType::Trunc)),
178 ("abs", raw_call(ExprType::Abs)),
179 ("exp", raw_call(ExprType::Exp)),
180 ("ln", raw_call(ExprType::Ln)),
181 ("log", raw_call(ExprType::Log10)),
182 ("log10", raw_call(ExprType::Log10)),
183 ("mod", raw_call(ExprType::Modulus)),
184 ("sin", raw_call(ExprType::Sin)),
185 ("cos", raw_call(ExprType::Cos)),
186 ("tan", raw_call(ExprType::Tan)),
187 ("cot", raw_call(ExprType::Cot)),
188 ("asin", raw_call(ExprType::Asin)),
189 ("acos", raw_call(ExprType::Acos)),
190 ("atan", raw_call(ExprType::Atan)),
191 ("atan2", raw_call(ExprType::Atan2)),
192 ("sind", raw_call(ExprType::Sind)),
193 ("cosd", raw_call(ExprType::Cosd)),
194 ("cotd", raw_call(ExprType::Cotd)),
195 ("tand", raw_call(ExprType::Tand)),
196 ("sinh", raw_call(ExprType::Sinh)),
197 ("cosh", raw_call(ExprType::Cosh)),
198 ("tanh", raw_call(ExprType::Tanh)),
199 ("coth", raw_call(ExprType::Coth)),
200 ("asinh", raw_call(ExprType::Asinh)),
201 ("acosh", raw_call(ExprType::Acosh)),
202 ("atanh", raw_call(ExprType::Atanh)),
203 ("asind", raw_call(ExprType::Asind)),
204 ("acosd", raw_call(ExprType::Acosd)),
205 ("atand", raw_call(ExprType::Atand)),
206 ("atan2d", raw_call(ExprType::Atan2d)),
207 ("degrees", raw_call(ExprType::Degrees)),
208 ("radians", raw_call(ExprType::Radians)),
209 ("sqrt", raw_call(ExprType::Sqrt)),
210 ("cbrt", raw_call(ExprType::Cbrt)),
211 ("sign", raw_call(ExprType::Sign)),
212 ("scale", raw_call(ExprType::Scale)),
213 ("min_scale", raw_call(ExprType::MinScale)),
214 ("trim_scale", raw_call(ExprType::TrimScale)),
215 (
217 "to_timestamp",
218 dispatch_by_len(vec![
219 (1, raw_call(ExprType::SecToTimestamptz)),
220 (2, raw_call(ExprType::CharToTimestamptz)),
221 ]),
222 ),
223 ("date_trunc", raw_call(ExprType::DateTrunc)),
224 ("date_part", raw_call(ExprType::DatePart)),
225 ("make_date", raw_call(ExprType::MakeDate)),
226 ("make_time", raw_call(ExprType::MakeTime)),
227 ("make_timestamp", raw_call(ExprType::MakeTimestamp)),
228 ("make_timestamptz", raw_call(ExprType::MakeTimestamptz)),
229 ("timezone", rewrite(ExprType::AtTimeZone, |mut inputs| {
230 if inputs.len() == 2 {
231 inputs.swap(0, 1);
232 Ok(inputs)
233 } else {
234 Err(ErrorCode::ExprError("unexpected arguments number".into()).into())
235 }
236 })),
237 ("to_date", raw_call(ExprType::CharToDate)),
238 ("substr", raw_call(ExprType::Substr)),
240 ("length", raw_call(ExprType::Length)),
241 ("upper", raw_call(ExprType::Upper)),
242 ("lower", raw_call(ExprType::Lower)),
243 ("trim", raw_call(ExprType::Trim)),
244 ("replace", raw_call(ExprType::Replace)),
245 ("overlay", raw_call(ExprType::Overlay)),
246 ("btrim", raw_call(ExprType::Trim)),
247 ("ltrim", raw_call(ExprType::Ltrim)),
248 ("rtrim", raw_call(ExprType::Rtrim)),
249 ("md5", raw_call(ExprType::Md5)),
250 ("to_char", raw_call(ExprType::ToChar)),
251 (
252 "concat",
253 rewrite(ExprType::ConcatWs, rewrite_concat_to_concat_ws),
254 ),
255 ("concat_ws", raw_call(ExprType::ConcatWs)),
256 ("format", raw_call(ExprType::Format)),
257 ("translate", raw_call(ExprType::Translate)),
258 ("split_part", raw_call(ExprType::SplitPart)),
259 ("char_length", raw_call(ExprType::CharLength)),
260 ("character_length", raw_call(ExprType::CharLength)),
261 ("repeat", raw_call(ExprType::Repeat)),
262 ("ascii", raw_call(ExprType::Ascii)),
263 ("octet_length", raw_call(ExprType::OctetLength)),
264 ("bit_length", raw_call(ExprType::BitLength)),
265 ("regexp_match", raw_call(ExprType::RegexpMatch)),
266 ("regexp_replace", raw_call(ExprType::RegexpReplace)),
267 ("regexp_count", raw_call(ExprType::RegexpCount)),
268 ("regexp_split_to_array", raw_call(ExprType::RegexpSplitToArray)),
269 ("chr", raw_call(ExprType::Chr)),
270 ("starts_with", raw_call(ExprType::StartsWith)),
271 ("initcap", raw_call(ExprType::Initcap)),
272 ("lpad", raw_call(ExprType::Lpad)),
273 ("rpad", raw_call(ExprType::Rpad)),
274 ("reverse", raw_call(ExprType::Reverse)),
275 ("strpos", raw_call(ExprType::Position)),
276 ("to_ascii", raw_call(ExprType::ToAscii)),
277 ("to_hex", raw_call(ExprType::ToHex)),
278 ("quote_ident", raw_call(ExprType::QuoteIdent)),
279 ("quote_literal", guard_by_len(1, raw(|_binder, mut inputs| {
280 if inputs[0].return_type() != DataType::Varchar {
281 FunctionCall::cast_mut(&mut inputs[0], DataType::Varchar, CastContext::Explicit)?;
284 }
285 Ok(FunctionCall::new_unchecked(ExprType::QuoteLiteral, inputs, DataType::Varchar).into())
286 }))),
287 ("quote_nullable", guard_by_len(1, raw(|_binder, mut inputs| {
288 if inputs[0].return_type() != DataType::Varchar {
289 FunctionCall::cast_mut(&mut inputs[0], DataType::Varchar, CastContext::Explicit)?;
292 }
293 Ok(FunctionCall::new_unchecked(ExprType::QuoteNullable, inputs, DataType::Varchar).into())
294 }))),
295 ("string_to_array", raw_call(ExprType::StringToArray)),
296 ("encode", raw_call(ExprType::Encode)),
297 ("decode", raw_call(ExprType::Decode)),
298 ("convert_from", raw_call(ExprType::ConvertFrom)),
299 ("convert_to", raw_call(ExprType::ConvertTo)),
300 ("sha1", raw_call(ExprType::Sha1)),
301 ("sha224", raw_call(ExprType::Sha224)),
302 ("sha256", raw_call(ExprType::Sha256)),
303 ("sha384", raw_call(ExprType::Sha384)),
304 ("sha512", raw_call(ExprType::Sha512)),
305 ("encrypt", raw_call(ExprType::Encrypt)),
306 ("decrypt", raw_call(ExprType::Decrypt)),
307 ("hmac", raw_call(ExprType::Hmac)),
308 ("secure_compare", raw_call(ExprType::SecureCompare)),
309 ("left", raw_call(ExprType::Left)),
310 ("right", raw_call(ExprType::Right)),
311 ("inet_aton", raw_call(ExprType::InetAton)),
312 ("inet_ntoa", raw_call(ExprType::InetNtoa)),
313 ("int8send", raw_call(ExprType::PgwireSend)),
314 ("int8recv", guard_by_len(1, raw(|_binder, mut inputs| {
315 let hint = if !inputs[0].is_untyped() && inputs[0].return_type() == DataType::Varchar {
317 " Consider `decode` or cast."
318 } else {
319 ""
320 };
321 inputs[0].cast_implicit_mut(DataType::Bytea).map_err(|e| {
322 ErrorCode::BindError(format!("{} in `recv`.{hint}", e.as_report()))
323 })?;
324 Ok(FunctionCall::new_unchecked(ExprType::PgwireRecv, inputs, DataType::Int64).into())
325 }))),
326 ("array_cat", raw_call(ExprType::ArrayCat)),
328 ("array_append", raw_call(ExprType::ArrayAppend)),
329 ("array_join", raw_call(ExprType::ArrayToString)),
330 ("array_prepend", raw_call(ExprType::ArrayPrepend)),
331 ("array_to_string", raw_call(ExprType::ArrayToString)),
332 ("array_distinct", raw_call(ExprType::ArrayDistinct)),
333 ("array_min", raw_call(ExprType::ArrayMin)),
334 ("array_sort", raw_call(ExprType::ArraySort)),
335 ("array_length", raw_call(ExprType::ArrayLength)),
336 ("cardinality", raw_call(ExprType::Cardinality)),
337 ("array_remove", raw_call(ExprType::ArrayRemove)),
338 ("array_replace", raw_call(ExprType::ArrayReplace)),
339 ("array_max", raw_call(ExprType::ArrayMax)),
340 ("array_sum", raw_call(ExprType::ArraySum)),
341 ("array_position", raw_call(ExprType::ArrayPosition)),
342 ("array_positions", raw_call(ExprType::ArrayPositions)),
343 ("array_contains", raw_call(ExprType::ArrayContains)),
344 ("arraycontains", raw_call(ExprType::ArrayContains)),
345 ("array_contained", raw_call(ExprType::ArrayContained)),
346 ("arraycontained", raw_call(ExprType::ArrayContained)),
347 ("trim_array", raw_call(ExprType::TrimArray)),
348 (
349 "array_ndims",
350 guard_by_len(1, raw(|_binder, inputs| {
351 inputs[0].ensure_array_type()?;
352
353 let n = inputs[0].return_type().array_ndims()
354 .try_into().map_err(|_| ErrorCode::BindError("array_ndims integer overflow".into()))?;
355 Ok(ExprImpl::literal_int(n))
356 })),
357 ),
358 (
359 "array_lower",
360 guard_by_len(2, raw(|binder, inputs| {
361 let (arg0, arg1) = inputs.into_iter().next_tuple().unwrap();
362 let ndims_expr = binder.bind_builtin_scalar_function("array_ndims", vec![arg0], false)?;
364 let arg1 = arg1.cast_implicit(DataType::Int32)?;
365
366 FunctionCall::new(
367 ExprType::Case,
368 vec![
369 FunctionCall::new(
370 ExprType::And,
371 vec![
372 FunctionCall::new(ExprType::LessThan, vec![ExprImpl::literal_int(0), arg1.clone()])?.into(),
373 FunctionCall::new(ExprType::LessThanOrEqual, vec![arg1, ndims_expr])?.into(),
374 ],
375 )?.into(),
376 ExprImpl::literal_int(1),
377 ],
378 ).map(Into::into)
379 })),
380 ),
381 ("array_upper", raw_call(ExprType::ArrayLength)), ("array_dims", raw_call(ExprType::ArrayDims)),
383 ("hex_to_int256", raw_call(ExprType::HexToInt256)),
385 ("jsonb_object_field", raw_call(ExprType::JsonbAccess)),
387 ("jsonb_array_element", raw_call(ExprType::JsonbAccess)),
388 ("jsonb_object_field_text", raw_call(ExprType::JsonbAccessStr)),
389 ("jsonb_array_element_text", raw_call(ExprType::JsonbAccessStr)),
390 ("jsonb_extract_path", raw_call(ExprType::JsonbExtractPath)),
391 ("jsonb_extract_path_text", raw_call(ExprType::JsonbExtractPathText)),
392 ("jsonb_typeof", raw_call(ExprType::JsonbTypeof)),
393 ("jsonb_array_length", raw_call(ExprType::JsonbArrayLength)),
394 ("jsonb_concat", raw_call(ExprType::JsonbConcat)),
395 ("jsonb_object", raw_call(ExprType::JsonbObject)),
396 ("jsonb_pretty", raw_call(ExprType::JsonbPretty)),
397 ("jsonb_contains", raw_call(ExprType::JsonbContains)),
398 ("jsonb_contained", raw_call(ExprType::JsonbContained)),
399 ("jsonb_exists", raw_call(ExprType::JsonbExists)),
400 ("jsonb_exists_any", raw_call(ExprType::JsonbExistsAny)),
401 ("jsonb_exists_all", raw_call(ExprType::JsonbExistsAll)),
402 ("jsonb_delete", raw_call(ExprType::Subtract)),
403 ("jsonb_delete_path", raw_call(ExprType::JsonbDeletePath)),
404 ("jsonb_strip_nulls", raw_call(ExprType::JsonbStripNulls)),
405 ("to_jsonb", raw_call(ExprType::ToJsonb)),
406 ("jsonb_build_array", raw_call(ExprType::JsonbBuildArray)),
407 ("jsonb_build_object", raw_call(ExprType::JsonbBuildObject)),
408 ("jsonb_populate_record", raw_call(ExprType::JsonbPopulateRecord)),
409 ("jsonb_path_match", raw_call(ExprType::JsonbPathMatch)),
410 ("jsonb_path_exists", raw_call(ExprType::JsonbPathExists)),
411 ("jsonb_path_query_array", raw_call(ExprType::JsonbPathQueryArray)),
412 ("jsonb_path_query_first", raw_call(ExprType::JsonbPathQueryFirst)),
413 ("jsonb_set", raw_call(ExprType::JsonbSet)),
414 ("jsonb_populate_map", raw_call(ExprType::JsonbPopulateMap)),
415 ("map_from_entries", raw_call(ExprType::MapFromEntries)),
417 ("map_access", raw_call(ExprType::MapAccess)),
418 ("map_keys", raw_call(ExprType::MapKeys)),
419 ("map_values", raw_call(ExprType::MapValues)),
420 ("map_entries", raw_call(ExprType::MapEntries)),
421 ("map_from_key_values", raw_call(ExprType::MapFromKeyValues)),
422 ("map_cat", raw_call(ExprType::MapCat)),
423 ("map_contains", raw_call(ExprType::MapContains)),
424 ("map_delete", raw_call(ExprType::MapDelete)),
425 ("map_insert", raw_call(ExprType::MapInsert)),
426 ("map_length", raw_call(ExprType::MapLength)),
427 ("pi", pi()),
429 ("greatest", raw_call(ExprType::Greatest)),
431 ("least", raw_call(ExprType::Least)),
432 (
434 "pg_typeof",
435 guard_by_len(1, raw(|_binder, inputs| {
436 let input = &inputs[0];
437 let v = match input.is_untyped() {
438 true => "unknown".into(),
439 false => input.return_type().to_string(),
440 };
441 Ok(ExprImpl::literal_varchar(v))
442 })),
443 ),
444 ("current_catalog", current_database()),
445 ("current_database", current_database()),
446 ("current_schema", guard_by_len(0, raw(|binder, _inputs| {
447 Ok(binder
448 .first_valid_schema()
449 .map(|schema| ExprImpl::literal_varchar(schema.name()))
450 .unwrap_or_else(|_| ExprImpl::literal_null(DataType::Varchar)))
451 }))),
452 ("current_schemas", raw(|binder, mut inputs| {
453 let no_match_err = ErrorCode::ExprError(
454 "No function matches the given name and argument types. You might need to add explicit type casts.".into()
455 );
456 if inputs.len() != 1 {
457 return Err(no_match_err.into());
458 }
459 let input = inputs
460 .pop()
461 .unwrap()
462 .enforce_bool_clause("current_schemas")
463 .map_err(|_| no_match_err)?;
464
465 let ExprImpl::Literal(literal) = &input else {
466 bail_not_implemented!("Only boolean literals are supported in `current_schemas`.");
467 };
468
469 let Some(bool) = literal.get_data().as_ref().map(|bool| bool.clone().into_bool()) else {
470 return Ok(ExprImpl::literal_null(DataType::List(Box::new(DataType::Varchar))));
471 };
472
473 let paths = if bool {
474 binder.search_path.path()
475 } else {
476 binder.search_path.real_path()
477 };
478
479 let mut schema_names = vec![];
480 for path in paths {
481 let mut schema_name = path;
482 if schema_name == USER_NAME_WILD_CARD {
483 schema_name = &binder.auth_context.user_name;
484 }
485
486 if binder
487 .catalog
488 .get_schema_by_name(&binder.db_name, schema_name)
489 .is_ok()
490 {
491 schema_names.push(schema_name.as_str());
492 }
493 }
494
495 Ok(ExprImpl::literal_list(
496 ListValue::from_iter(schema_names),
497 DataType::Varchar,
498 ))
499 })),
500 ("session_user", session_user()),
501 ("current_role", current_user()),
502 ("current_user", current_user()),
503 ("user", current_user()),
504 ("pg_get_userbyid", raw_call(ExprType::PgGetUserbyid)),
505 ("pg_get_indexdef", raw_call(ExprType::PgGetIndexdef)),
506 ("pg_get_viewdef", raw_call(ExprType::PgGetViewdef)),
507 ("pg_index_column_has_property", raw_call(ExprType::PgIndexColumnHasProperty)),
508 ("pg_relation_size", raw(|_binder, mut inputs| {
509 if inputs.is_empty() {
510 return Err(ErrorCode::ExprError(
511 "function pg_relation_size() does not exist".into(),
512 )
513 .into());
514 }
515 inputs[0].cast_to_regclass_mut()?;
516 Ok(FunctionCall::new(ExprType::PgRelationSize, inputs)?.into())
517 })),
518 ("pg_get_serial_sequence", raw_literal(ExprImpl::literal_null(DataType::Varchar))),
519 ("pg_table_size", guard_by_len(1, raw(|_binder, mut inputs| {
520 inputs[0].cast_to_regclass_mut()?;
521 Ok(FunctionCall::new(ExprType::PgRelationSize, inputs)?.into())
522 }))),
523 ("pg_indexes_size", guard_by_len(1, raw(|_binder, mut inputs| {
524 inputs[0].cast_to_regclass_mut()?;
525 Ok(FunctionCall::new(ExprType::PgIndexesSize, inputs)?.into())
526 }))),
527 ("pg_get_expr", raw(|_binder, inputs| {
528 if inputs.len() == 2 || inputs.len() == 3 {
529 Ok(ExprImpl::literal_varchar("".into()))
531 } else {
532 Err(ErrorCode::ExprError(
533 "Too many/few arguments for pg_catalog.pg_get_expr()".into(),
534 )
535 .into())
536 }
537 })),
538 ("pg_my_temp_schema", guard_by_len(0, raw(|_binder, _inputs| {
539 Ok(ExprImpl::literal_int(
541 0,
543 ))
544 }))),
545 ("current_setting", guard_by_len(1, raw(|binder, inputs| {
546 let input = &inputs[0];
547 let input = if let ExprImpl::Literal(literal) = input &&
548 let Some(ScalarImpl::Utf8(input)) = literal.get_data()
549 {
550 input
551 } else {
552 return Err(ErrorCode::ExprError(
553 "Only literal is supported in `setting_name`.".into(),
554 )
555 .into());
556 };
557 let session_config = binder.session_config.read();
558 Ok(ExprImpl::literal_varchar(session_config.get(input.as_ref())?))
559 }))),
560 ("set_config", guard_by_len(3, raw(|binder, inputs| {
561 let setting_name = if let ExprImpl::Literal(literal) = &inputs[0] && let Some(ScalarImpl::Utf8(input)) = literal.get_data() {
562 input
563 } else {
564 return Err(ErrorCode::ExprError(
565 "Only string literal is supported in `setting_name`.".into(),
566 )
567 .into());
568 };
569
570 let new_value = if let ExprImpl::Literal(literal) = &inputs[1] && let Some(ScalarImpl::Utf8(input)) = literal.get_data() {
571 input
572 } else {
573 return Err(ErrorCode::ExprError(
574 "Only string literal is supported in `setting_name`.".into(),
575 )
576 .into());
577 };
578
579 let is_local = if let ExprImpl::Literal(literal) = &inputs[2] && let Some(ScalarImpl::Bool(input)) = literal.get_data() {
580 input
581 } else {
582 return Err(ErrorCode::ExprError(
583 "Only bool literal is supported in `is_local`.".into(),
584 )
585 .into());
586 };
587
588 if *is_local {
589 return Err(ErrorCode::ExprError(
590 "`is_local = true` is not supported now.".into(),
591 )
592 .into());
593 }
594
595 let mut session_config = binder.session_config.write();
596
597 session_config.set(setting_name, new_value.to_string(), &mut ())?;
599
600 Ok(ExprImpl::literal_varchar(new_value.to_string()))
601 }))),
602 ("format_type", raw_call(ExprType::FormatType)),
603 ("pg_table_is_visible", raw_call(ExprType::PgTableIsVisible)),
604 ("pg_type_is_visible", raw_literal(ExprImpl::literal_bool(true))),
605 ("pg_get_constraintdef", raw_literal(ExprImpl::literal_null(DataType::Varchar))),
606 ("pg_get_partkeydef", raw_literal(ExprImpl::literal_null(DataType::Varchar))),
607 ("pg_encoding_to_char", raw_literal(ExprImpl::literal_varchar("UTF8".into()))),
608 ("has_database_privilege", raw_literal(ExprImpl::literal_bool(true))),
609 ("has_table_privilege", raw(|binder, mut inputs| {
610 if inputs.len() == 2 {
611 inputs.insert(0, ExprImpl::literal_varchar(binder.auth_context.user_name.clone()));
612 }
613 if inputs.len() == 3 {
614 if inputs[1].return_type() == DataType::Varchar {
615 inputs[1].cast_to_regclass_mut()?;
616 }
617 Ok(FunctionCall::new(ExprType::HasTablePrivilege, inputs)?.into())
618 } else {
619 Err(ErrorCode::ExprError(
620 "Too many/few arguments for pg_catalog.has_table_privilege()".into(),
621 )
622 .into())
623 }
624 })),
625 ("has_any_column_privilege", raw(|binder, mut inputs| {
626 if inputs.len() == 2 {
627 inputs.insert(0, ExprImpl::literal_varchar(binder.auth_context.user_name.clone()));
628 }
629 if inputs.len() == 3 {
630 if inputs[1].return_type() == DataType::Varchar {
631 inputs[1].cast_to_regclass_mut()?;
632 }
633 Ok(FunctionCall::new(ExprType::HasAnyColumnPrivilege, inputs)?.into())
634 } else {
635 Err(ErrorCode::ExprError(
636 "Too many/few arguments for pg_catalog.has_any_column_privilege()".into(),
637 )
638 .into())
639 }
640 })),
641 ("has_schema_privilege", raw(|binder, mut inputs| {
642 if inputs.len() == 2 {
643 inputs.insert(0, ExprImpl::literal_varchar(binder.auth_context.user_name.clone()));
644 }
645 if inputs.len() == 3 {
646 Ok(FunctionCall::new(ExprType::HasSchemaPrivilege, inputs)?.into())
647 } else {
648 Err(ErrorCode::ExprError(
649 "Too many/few arguments for pg_catalog.has_schema_privilege()".into(),
650 )
651 .into())
652 }
653 })),
654 ("has_function_privilege", raw(|binder, mut inputs| {
655 if inputs.len() == 2 {
656 inputs.insert(0, ExprImpl::literal_varchar(binder.auth_context.user_name.clone()));
657 }
658 if inputs.len() == 3 {
659 Ok(FunctionCall::new(ExprType::HasFunctionPrivilege, inputs)?.into())
660 } else {
661 Err(ErrorCode::ExprError(
662 "Too many/few arguments for pg_catalog.has_function_privilege()".into(),
663 )
664 .into())
665 }
666 })),
667 ("pg_stat_get_numscans", raw_literal(ExprImpl::literal_bigint(0))),
668 ("pg_backend_pid", raw(|binder, _inputs| {
669 Ok(ExprImpl::literal_int(binder.session_id.0))
671 })),
672 ("pg_cancel_backend", guard_by_len(1, raw(|_binder, _inputs| {
673 Ok(ExprImpl::literal_bool(false))
675 }))),
676 ("pg_terminate_backend", guard_by_len(1, raw(|_binder, _inputs| {
677 Ok(ExprImpl::literal_bool(false))
680 }))),
681 ("pg_tablespace_location", guard_by_len(1, raw_literal(ExprImpl::literal_null(DataType::Varchar)))),
682 ("pg_postmaster_start_time", guard_by_len(0, raw(|_binder, _inputs| {
683 let server_start_time = risingwave_variables::get_server_start_time();
684 let datum = server_start_time.map(Timestamptz::from).map(ScalarImpl::from);
685 let literal = Literal::new(datum, DataType::Timestamptz);
686 Ok(literal.into())
687 }))),
688 ("col_description", raw_call(ExprType::ColDescription)),
692 ("obj_description", raw_literal(ExprImpl::literal_varchar("".to_owned()))),
693 ("shobj_description", raw_literal(ExprImpl::literal_varchar("".to_owned()))),
694 ("pg_is_in_recovery", raw_call(ExprType::PgIsInRecovery)),
695 ("rw_recovery_status", raw_call(ExprType::RwRecoveryStatus)),
696 ("rw_epoch_to_ts", raw_call(ExprType::RwEpochToTs)),
697 ("rw_vnode", raw_call(ExprType::VnodeUser)),
699 ("rw_license", raw_call(ExprType::License)),
700 ("rw_test_paid_tier", raw_call(ExprType::TestPaidTier)), ("version", raw_literal(ExprImpl::literal_varchar(current_cluster_version()))),
703 ("now", now()),
705 ("current_timestamp", now()),
706 ("proctime", proctime()),
707 ("pg_sleep", raw_call(ExprType::PgSleep)),
708 ("pg_sleep_for", raw_call(ExprType::PgSleepFor)),
709 ("date", guard_by_len(1, raw(|_binder, inputs| {
715 inputs[0].clone().cast_explicit(DataType::Date).map_err(Into::into)
716 }))),
717 ]
718 .into_iter()
719 .collect()
720 });
721
722 static FUNCTIONS_BKTREE: LazyLock<BKTree<&str>> = LazyLock::new(|| {
723 let mut tree = BKTree::new(metrics::Levenshtein);
724
725 for k in HANDLES.keys() {
727 tree.add(*k);
728 }
729
730 tree
731 });
732
733 if variadic {
734 let func = match function_name {
735 "format" => ExprType::FormatVariadic,
736 "concat" => ExprType::ConcatVariadic,
737 "concat_ws" => ExprType::ConcatWsVariadic,
738 "jsonb_build_array" => ExprType::JsonbBuildArrayVariadic,
739 "jsonb_build_object" => ExprType::JsonbBuildObjectVariadic,
740 "jsonb_extract_path" => ExprType::JsonbExtractPathVariadic,
741 "jsonb_extract_path_text" => ExprType::JsonbExtractPathTextVariadic,
742 _ => {
743 return Err(ErrorCode::BindError(format!(
744 "VARIADIC argument is not allowed in function \"{}\"",
745 function_name
746 ))
747 .into());
748 }
749 };
750 return Ok(FunctionCall::new(func, inputs)?.into());
751 }
752
753 match HANDLES.get(function_name) {
755 Some(handle) => handle(self, inputs),
756 None => {
757 let allowed_distance = if function_name.len() > 3 { 2 } else { 1 };
758
759 let candidates = FUNCTIONS_BKTREE
760 .find(function_name, allowed_distance)
761 .map(|(_idx, c)| c)
762 .join(" or ");
763
764 Err(no_function!(
765 candidates = (!candidates.is_empty()).then_some(candidates),
766 "{}({})",
767 function_name,
768 inputs.iter().map(|e| e.return_type()).join(", ")
769 )
770 .into())
771 }
772 }
773 }
774
775 fn ensure_now_function_allowed(&self) -> Result<()> {
776 if self.is_for_stream()
777 && !matches!(
778 self.context.clause,
779 Some(Clause::Where)
780 | Some(Clause::Having)
781 | Some(Clause::JoinOn)
782 | Some(Clause::From)
783 )
784 {
785 return Err(ErrorCode::InvalidInputSyntax(format!(
786 "For streaming queries, `NOW()` function is only allowed in `WHERE`, `HAVING`, `ON` and `FROM`. Found in clause: {:?}. \
787 Please please refer to https://www.risingwave.dev/docs/current/sql-pattern-temporal-filters/ for more information",
788 self.context.clause
789 ))
790 .into());
791 }
792 if matches!(self.context.clause, Some(Clause::GeneratedColumn)) {
793 return Err(ErrorCode::InvalidInputSyntax(
794 "Cannot use `NOW()` function in generated columns. Do you want `PROCTIME()`?"
795 .to_owned(),
796 )
797 .into());
798 }
799 Ok(())
800 }
801
802 fn ensure_proctime_function_allowed(&self) -> Result<()> {
803 if !self.is_for_ddl() {
804 return Err(ErrorCode::InvalidInputSyntax(
805 "Function `PROCTIME()` is only allowed in CREATE TABLE/SOURCE. Is `NOW()` what you want?".to_owned(),
806 )
807 .into());
808 }
809 Ok(())
810 }
811}
812
813fn rewrite_concat_to_concat_ws(inputs: Vec<ExprImpl>) -> Result<Vec<ExprImpl>> {
814 if inputs.is_empty() {
815 Err(ErrorCode::BindError(
816 "Function `concat` takes at least 1 arguments (0 given)".to_owned(),
817 )
818 .into())
819 } else {
820 let inputs = std::iter::once(ExprImpl::literal_varchar("".to_owned()))
821 .chain(inputs)
822 .collect();
823 Ok(inputs)
824 }
825}
826
827fn rewrite_nullif_to_case_when(inputs: Vec<ExprImpl>) -> Result<Vec<ExprImpl>> {
830 if inputs.len() != 2 {
831 Err(ErrorCode::BindError("Function `nullif` must contain 2 arguments".to_owned()).into())
832 } else {
833 let inputs = vec![
834 FunctionCall::new(ExprType::Equal, inputs.clone())?.into(),
835 Literal::new(None, inputs[0].return_type()).into(),
836 inputs[0].clone(),
837 ];
838 Ok(inputs)
839 }
840}
841
842fn rewrite_two_bool_inputs(mut inputs: Vec<ExprImpl>) -> Result<Vec<ExprImpl>> {
843 if inputs.len() != 2 {
844 return Err(
845 ErrorCode::BindError("function must contain only 2 arguments".to_owned()).into(),
846 );
847 }
848 let left = inputs.pop().unwrap();
849 let right = inputs.pop().unwrap();
850 Ok(vec![
851 left.cast_implicit(DataType::Boolean)?,
852 right.cast_implicit(DataType::Boolean)?,
853 ])
854}