1use uqa_core::Value;
10
11use crate::ast::{FunctionBinding, FunctionDispatch};
12use crate::error::{Result, SQLError};
13
14use super::call_arguments::normalized_function_name;
15use super::call_dispatch::eval_selected_builtin_function_call;
16use super::context::EvalContext;
17use super::{random, scalar_array, scalar_postgres, scalar_range};
18
19#[expect(
20 clippy::too_many_lines,
21 reason = "builtin dispatch preserves arity, NULL, and error precedence"
22)]
23pub fn builtin_scalar_function_strictness(name: &str, argument_count: usize) -> Option<bool> {
24 let normalized = normalized_function_name(name);
25 match normalized.as_ref() {
26 "int4range" | "int8range" | "numrange" | "daterange" | "tsrange" | "tstzrange"
27 if matches!(argument_count, 2 | 3) =>
28 {
29 Some(false)
30 }
31 "int4multirange" | "int8multirange" | "nummultirange" | "datemultirange"
32 | "tsmultirange" | "tstzmultirange"
33 if argument_count <= 1 =>
34 {
35 Some(true)
36 }
37 "multirange" if argument_count == 1 => Some(true),
38 "int4range_subdiff" | "int8range_subdiff" | "numrange_subdiff" | "daterange_subdiff"
39 | "tsrange_subdiff" | "tstzrange_subdiff"
40 if argument_count == 2 =>
41 {
42 Some(true)
43 }
44 "coalesce" | "greatest" | "least" if argument_count >= 1 => Some(false),
45 "nullif" | "concat_op" if argument_count == 2 => Some(false),
46 "concat" | "format" | "json_build_array" | "jsonb_build_array" | "json_build_object"
47 | "jsonb_build_object" | "num_nulls" | "num_nonnulls" => Some(false),
48 "concat_ws" if argument_count >= 1 => Some(false),
49 "quote_nullable" | "pg_typeof" | "typeof" | "pg_collation_for" if argument_count == 1 => {
50 Some(false)
51 }
52 "array_cat" | "array_append" | "array_prepend" | "array_remove" | "array_positions"
53 if argument_count == 2 =>
54 {
55 Some(false)
56 }
57 "array_position" if matches!(argument_count, 2 | 3) => Some(false),
58 "array_replace" if argument_count == 3 => Some(false),
59 "array_fill" if matches!(argument_count, 2 | 3) => Some(false),
60 "array_to_string" if argument_count == 3 => Some(false),
61 "string_to_array" | "string_to_table" if matches!(argument_count, 2 | 3) => Some(false),
62 "pg_has_role" if matches!(argument_count, 2 | 3) => Some(true),
63 "pg_get_userbyid" if argument_count == 1 => Some(true),
64 "current_setting" if matches!(argument_count, 1 | 2) => Some(true),
65 "set_config" if argument_count == 3 => Some(false),
66 "pg_sleep" | "pg_sleep_for" | "pg_sleep_until" if argument_count == 1 => Some(true),
67 "has_table_privilege" if matches!(argument_count, 2 | 3) => Some(true),
68 "has_column_privilege" if matches!(argument_count, 3 | 4) => Some(true),
69 "has_database_privilege" if matches!(argument_count, 2 | 3) => Some(true),
70 "has_schema_privilege" if matches!(argument_count, 2 | 3) => Some(true),
71 "has_sequence_privilege" | "has_function_privilege" | "has_type_privilege"
72 if matches!(argument_count, 2 | 3) =>
73 {
74 Some(true)
75 }
76 "pg_get_constraintdef" if matches!(argument_count, 1 | 2) => Some(true),
77 "pg_get_function_arguments"
78 | "pg_get_function_identity_arguments"
79 | "pg_get_function_result"
80 | "pg_get_functiondef"
81 | "pg_get_function_sqlbody"
82 if argument_count == 1 =>
83 {
84 Some(true)
85 }
86 "pg_get_sequence_data" | "pg_sequence_last_value" | "pg_sequence_parameters"
87 if argument_count == 1 =>
88 {
89 Some(true)
90 }
91 "nextval" | "currval" if argument_count == 1 => Some(true),
92 "lastval" if argument_count == 0 => Some(true),
93 "setval" if matches!(argument_count, 2 | 3) => Some(true),
94 "overlaps" if argument_count == 4 => Some(false),
95 "abs"
96 | "acos"
97 | "array_dims"
98 | "array_ndims"
99 | "array_reverse"
100 | "ascii"
101 | "asin"
102 | "atan"
103 | "bit_length"
104 | "cardinality"
105 | "casefold"
106 | "cbrt"
107 | "ceil"
108 | "ceiling"
109 | "char_length"
110 | "character_length"
111 | "chr"
112 | "cos"
113 | "cosh"
114 | "current_schemas"
115 | "degrees"
116 | "exp"
117 | "factorial"
118 | "floor"
119 | "gamma"
120 | "initcap"
121 | "isfinite"
122 | "json_array_length"
123 | "jsonb_array_length"
124 | "json_typeof"
125 | "jsonb_typeof"
126 | "jsonb_pretty"
127 | "justify_days"
128 | "justify_hours"
129 | "justify_interval"
130 | "length"
131 | "lgamma"
132 | "ln"
133 | "log10"
134 | "log2"
135 | "lower"
136 | "md5"
137 | "octet_length"
138 | "quote_ident"
139 | "quote_literal"
140 | "radians"
141 | "reverse"
142 | "row_to_json"
143 | "sign"
144 | "sin"
145 | "sinh"
146 | "sqrt"
147 | "tan"
148 | "tanh"
149 | "to_bin"
150 | "to_hex"
151 | "to_oct"
152 | "to_json"
153 | "to_jsonb"
154 | "to_regclass"
155 | "to_regcollation"
156 | "to_regnamespace"
157 | "to_regproc"
158 | "to_regprocedure"
159 | "to_regrole"
160 | "to_regtype"
161 | "to_timestamp"
162 | "upper"
163 | "uuid_extract_timestamp"
164 | "uuid_extract_version"
165 if argument_count == 1 =>
166 {
167 Some(true)
168 }
169 "random" if argument_count == 2 => Some(true),
170 "age" | "timezone" | "btrim" | "ltrim" | "rtrim" | "trim" | "log" | "round" | "trunc"
171 | "json_strip_nulls" | "jsonb_strip_nulls"
172 if matches!(argument_count, 1 | 2) =>
173 {
174 Some(true)
175 }
176 "array_sort" if matches!(argument_count, 1..=3) => Some(true),
177 "date_trunc" if matches!(argument_count, 2 | 3) => Some(true),
178 "array_length" | "array_lower" | "array_upper" | "atan2" | "date_part" | "decode"
179 | "encode" | "extract" | "gcd" | "get_byte" | "lcm" | "left" | "mod" | "power" | "pow"
180 | "repeat" | "right" | "starts_with" | "position" | "strpos" | "to_char" | "to_date"
181 | "to_number" | "trim_array" | "point" | "st_distance" | "st_within"
182 if argument_count == 2 =>
183 {
184 Some(true)
185 }
186 "like_escape" if argument_count == 2 => Some(true),
187 "similar_to_escape" if matches!(argument_count, 1 | 2) => Some(true),
188 "like" | "ilike" | "similar_to" | "regex_match_op" | "regex_imatch_op"
189 if argument_count == 2 =>
190 {
191 Some(true)
192 }
193 "like" | "ilike" | "similar_to" if argument_count == 3 => Some(false),
194 "array_to_string" if argument_count == 2 => Some(true),
195 "substring" | "substr" | "lpad" | "rpad" if matches!(argument_count, 2 | 3) => Some(true),
196 "regexp_count" if matches!(argument_count, 2..=4) => Some(true),
197 "regexp_instr" if matches!(argument_count, 2..=7) => Some(true),
198 "regexp_like" | "regexp_match" | "regexp_matches" | "regexp_split_to_array"
199 if matches!(argument_count, 2 | 3) =>
200 {
201 Some(true)
202 }
203 "regexp_replace" if matches!(argument_count, 3..=6) => Some(true),
204 "regexp_substr" if matches!(argument_count, 2..=6) => Some(true),
205 "replace" | "split_part" | "translate" | "make_date" if argument_count == 3 => Some(true),
206 "overlay" | "jsonb_set" | "jsonb_insert" if matches!(argument_count, 3 | 4) => Some(true),
207 "json_extract_path"
208 | "jsonb_extract_path"
209 | "json_extract_path_text"
210 | "jsonb_extract_path_text"
211 if argument_count >= 2 =>
212 {
213 Some(true)
214 }
215 "json_contains" | "json_contained_by" | "json_delete_path" | "json_has_key"
216 | "json_has_any_key" | "json_has_all_keys" | "jsonb_path_exists" | "jsonpath_exists"
217 | "jsonb_path_match" | "jsonpath_match"
218 if argument_count == 2 =>
219 {
220 Some(true)
221 }
222 "make_timestamp" if matches!(argument_count, 6 | 7) => Some(true),
223 "make_interval" if argument_count <= 7 => Some(true),
224 "width_bucket" if argument_count == 4 => Some(true),
225 "st_dwithin" if matches!(argument_count, 2 | 3) => Some(true),
226 _ => None,
227 }
228}
229
230#[must_use]
232pub fn bound_scalar_function_strictness(
233 name: &str,
234 binding: Option<&FunctionBinding>,
235 argument_count: usize,
236) -> Option<bool> {
237 let Some(binding) = binding else {
238 return builtin_scalar_function_strictness(name, argument_count);
239 };
240 if let Some(dispatch) = binding.dispatch {
241 return match dispatch {
242 FunctionDispatch::Concat { oid } => oid.map_or(Some(false), |oid| {
243 crate::type_resolution::binary_operator_by_oid(i64::from(oid))
244 .filter(|operator| operator.name == "||")
245 .map(|operator| !matches!(operator.oid, 349 | 374 | 375))
246 }),
247 FunctionDispatch::NumericOperator(_) => Some(true),
248 FunctionDispatch::Pattern { .. } | FunctionDispatch::PatternEscape { .. } => Some(true),
249 FunctionDispatch::Collate { .. } => None,
250 FunctionDispatch::MergeAction => Some(false),
251 FunctionDispatch::Subscript
252 | FunctionDispatch::FieldSelect
253 | FunctionDispatch::BetweenSymmetric
254 | FunctionDispatch::ToBinInt4
255 | FunctionDispatch::ToBinInt8
256 | FunctionDispatch::ToHexInt4
257 | FunctionDispatch::ToHexInt8
258 | FunctionDispatch::ToOctInt4
259 | FunctionDispatch::ToOctInt8
260 | FunctionDispatch::RandomInt4Range
261 | FunctionDispatch::RandomInt8Range
262 | FunctionDispatch::RandomNumericRange
263 | FunctionDispatch::RegexSubstring
264 | FunctionDispatch::SimilarSubstring
265 | FunctionDispatch::ArraySortJson
266 | FunctionDispatch::JsonPath { .. }
267 | FunctionDispatch::JsonExtract { .. }
268 | FunctionDispatch::Range { .. } => Some(true),
269 FunctionDispatch::ArraySubscripts
270 | FunctionDispatch::ArraySlices
271 | FunctionDispatch::ArraySlicesWithBounds(_)
272 | FunctionDispatch::CollationFor { .. }
273 | FunctionDispatch::ArrayConcat
274 | FunctionDispatch::ArrayAppend
275 | FunctionDispatch::ArrayPrepend
276 | FunctionDispatch::Slice
277 | FunctionDispatch::AnyOperator
278 | FunctionDispatch::AllOperator
279 | FunctionDispatch::ValueNullTest { .. }
280 | FunctionDispatch::BooleanTest(_)
281 | FunctionDispatch::DistinctNot
282 | FunctionDispatch::RowDistinct
283 | FunctionDispatch::ValueIsDistinct
284 | FunctionDispatch::IsDistinct => Some(false),
285 FunctionDispatch::Enum { operation, .. } => Some(operation.is_strict()),
286 FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => None,
287 };
288 }
289 binding
290 .builtin
291 .then(|| builtin_scalar_function_strictness(&binding.name, argument_count))
292 .flatten()
293}
294
295pub fn eval_bound_builtin_function_call(
297 binding: &FunctionBinding,
298 call_args: Vec<(Option<String>, Value)>,
299 ctx: &EvalContext<'_>,
300) -> Result<Value> {
301 if let Some(error) = &binding.resolution_error {
302 return Err(error.sql_error());
303 }
304 if let Some(hook) = ctx.engine {
305 hook.require_builtin_execute(binding)?;
306 }
307 let Some(dispatch) = binding.dispatch else {
308 let value = eval_selected_builtin_function_call(
309 &binding.name,
310 call_args,
311 ctx,
312 FunctionBinding::selected_input_collation(Some(binding)),
313 )?;
314 if matches!(value, Value::Int(_) | Value::Float(_)) {
316 if let Some(
317 ty @ (crate::ColumnType::SmallInteger
318 | crate::ColumnType::Integer
319 | crate::ColumnType::Real),
320 ) = crate::fixed_builtin_return_type(binding)
321 {
322 return super::cast_value(&value, &ty.sql_name());
323 }
324 }
325 return Ok(value);
326 };
327 if let Some(result) = random::eval_dispatched_random_function(dispatch, &call_args, ctx) {
328 return result;
329 }
330 if call_args.iter().any(|(name, _)| name.is_some()) {
331 return Err(SQLError::Internal(format!(
332 "bound {} expression retained a named argument",
333 dispatch.label()
334 )));
335 }
336 let evaluated = call_args
337 .into_iter()
338 .map(|(_, value)| value)
339 .collect::<Vec<_>>();
340 if let FunctionDispatch::Enum {
341 operation,
342 type_oid,
343 } = dispatch
344 {
345 return super::enums::enum_function_value_with_state(
346 ctx.engine.and_then(super::EngineHook::enum_labels),
347 operation,
348 type_oid,
349 &evaluated,
350 ctx.enum_comparison_state(),
351 );
352 }
353 if let Some(result) = scalar_postgres::eval_comparison_with_context(
354 dispatch,
355 &evaluated,
356 &uqa_core::memory::ProductionControl::uncontrolled(),
357 ctx,
358 ) {
359 return result.map(|value| {
360 value
361 .into_uncontrolled()
362 .expect("ordinary comparison result")
363 });
364 }
365 eval_dispatched_builtin_with_control(
366 binding,
367 dispatch,
368 &evaluated,
369 &uqa_core::memory::ProductionControl::uncontrolled(),
370 ctx,
371 )
372 .map(|value| {
373 value
374 .into_uncontrolled()
375 .expect("ordinary dispatched builtin result")
376 })
377}
378
379pub(super) fn eval_dispatched_builtin_with_control(
380 binding: &FunctionBinding,
381 dispatch: FunctionDispatch,
382 evaluated: &[Value],
383 control: &uqa_core::memory::ProductionControl<'_>,
384 context: &EvalContext<'_>,
385) -> Result<uqa_core::memory::Produced<Value>> {
386 if dispatch == FunctionDispatch::FieldSelect {
387 if let Some(field) = &binding.composite_field {
388 return super::composites::fields::select_with_control(
390 field,
391 evaluated,
392 context.engine,
393 control,
394 );
395 }
396 }
397 let collation = FunctionBinding::selected_input_collation(Some(binding));
398 if let Some(result) = scalar_postgres::eval_dispatched_postgres_function_with_control(
399 dispatch, evaluated, collation, control,
400 ) {
401 return result;
402 }
403 match dispatch {
404 FunctionDispatch::MergeAction => {
405 crate::semantics::runtime_scalars::merge_action_value_with_control(
406 evaluated.len(),
407 context.row_lookup()?,
408 control,
409 )
410 }
411 FunctionDispatch::CollationFor {
412 collation_oid,
413 noncollatable_type_oid,
414 } => super::collation_for::evaluate(
415 collation_oid,
416 noncollatable_type_oid,
417 context.engine,
418 control,
419 ),
420 FunctionDispatch::NumericOperator(operator) => {
421 super::numeric_operator::eval_bound_operator_with_control(
422 operator, binding, evaluated, control,
423 )
424 }
425 FunctionDispatch::JsonPath { as_text, jsonb } => {
426 super::json::json_path_function_with_control(evaluated, as_text, jsonb, control)
427 }
428 FunctionDispatch::Concat { oid } => {
429 super::concatenation::evaluate(binding, oid, evaluated, control, context)
430 }
431 FunctionDispatch::Pattern { operator, .. } => {
432 super::pattern::evaluate(operator, evaluated, collation, control)
433 }
434 FunctionDispatch::PatternEscape { similar } => {
435 super::pattern::escape(similar, evaluated, control)
436 }
437 FunctionDispatch::JsonExtract { as_text, path } => {
438 super::json::json_extract_operator_with_control(evaluated, as_text, path, control)
439 }
440 FunctionDispatch::ArraySortJson => {
441 let catalog = context.engine.map(super::EngineValueCatalog);
442 scalar_array::eval_dispatched_json_array_sort_with_control(
443 evaluated,
444 control,
445 catalog
446 .as_ref()
447 .map(|catalog| catalog as &dyn super::SQLValueCatalog),
448 )
449 }
450 FunctionDispatch::ArrayConcat
451 | FunctionDispatch::ArrayAppend
452 | FunctionDispatch::ArrayPrepend => {
453 let name = match dispatch {
454 FunctionDispatch::ArrayConcat => "array_cat",
455 FunctionDispatch::ArrayAppend => "array_append",
456 _ => "array_prepend",
457 };
458 scalar_array::eval_array_functions_with_control(name, evaluated, control)
459 .expect("registered array concatenation operation")
460 }
461 FunctionDispatch::Range {
462 operation,
463 subtype,
464 multirange,
465 } => scalar_range::eval_dispatched_range_function_with_control(
466 operation, subtype, multirange, evaluated, control,
467 ),
468 FunctionDispatch::Enum {
470 operation,
471 type_oid,
472 } => super::enums::enum_function_value_with_control(
473 None, operation, type_oid, evaluated, None, control,
474 ),
475 FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => Err(
476 SQLError::Internal("call-argument syntax marker reached scalar execution".into()),
477 ),
478 _ => Err(SQLError::Internal(format!(
479 "{} has no scalar executor",
480 dispatch.label()
481 ))),
482 }
483}