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::TypeOf { .. }
274 | FunctionDispatch::ArrayConcat
275 | FunctionDispatch::ArrayAppend
276 | FunctionDispatch::ArrayPrepend
277 | FunctionDispatch::Slice
278 | FunctionDispatch::AnyOperator
279 | FunctionDispatch::AllOperator
280 | FunctionDispatch::ValueNullTest { .. }
281 | FunctionDispatch::BooleanTest(_)
282 | FunctionDispatch::DistinctNot
283 | FunctionDispatch::RowDistinct
284 | FunctionDispatch::ValueIsDistinct
285 | FunctionDispatch::IsDistinct => Some(false),
286 FunctionDispatch::Enum { operation, .. } => Some(operation.is_strict()),
287 FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => None,
288 };
289 }
290 binding
291 .builtin
292 .then(|| builtin_scalar_function_strictness(&binding.name, argument_count))
293 .flatten()
294}
295
296pub fn eval_bound_builtin_function_call(
298 binding: &FunctionBinding,
299 call_args: Vec<(Option<String>, Value)>,
300 ctx: &EvalContext<'_>,
301) -> Result<Value> {
302 if let Some(error) = &binding.resolution_error {
303 return Err(error.sql_error());
304 }
305 if let Some(hook) = ctx.engine {
306 hook.require_builtin_execute(binding)?;
307 }
308 let Some(dispatch) = binding.dispatch else {
309 let value = eval_selected_builtin_function_call(
310 &binding.name,
311 call_args,
312 ctx,
313 FunctionBinding::selected_input_collation(Some(binding)),
314 )?;
315 if matches!(value, Value::Int(_) | Value::Float(_)) {
317 if let Some(
318 ty @ (crate::ColumnType::SmallInteger
319 | crate::ColumnType::Integer
320 | crate::ColumnType::Real),
321 ) = crate::fixed_builtin_return_type(binding)
322 {
323 return super::cast_value(&value, &ty.sql_name());
324 }
325 }
326 return Ok(value);
327 };
328 if let Some(result) = random::eval_dispatched_random_function(dispatch, &call_args, ctx) {
329 return result;
330 }
331 if call_args.iter().any(|(name, _)| name.is_some()) {
332 return Err(SQLError::Internal(format!(
333 "bound {} expression retained a named argument",
334 dispatch.label()
335 )));
336 }
337 let evaluated = call_args
338 .into_iter()
339 .map(|(_, value)| value)
340 .collect::<Vec<_>>();
341 if let FunctionDispatch::Enum {
342 operation,
343 type_oid,
344 } = dispatch
345 {
346 return super::enums::enum_function_value_with_state(
347 ctx.engine.and_then(super::EngineHook::enum_labels),
348 operation,
349 type_oid,
350 &evaluated,
351 ctx.enum_comparison_state(),
352 );
353 }
354 if let Some(result) = scalar_postgres::eval_comparison_with_context(
355 dispatch,
356 &evaluated,
357 &uqa_core::memory::ProductionControl::uncontrolled(),
358 ctx,
359 ) {
360 return result.map(|value| {
361 value
362 .into_uncontrolled()
363 .expect("ordinary comparison result")
364 });
365 }
366 eval_dispatched_builtin_with_control(
367 binding,
368 dispatch,
369 &evaluated,
370 &uqa_core::memory::ProductionControl::uncontrolled(),
371 ctx,
372 )
373 .map(|value| {
374 value
375 .into_uncontrolled()
376 .expect("ordinary dispatched builtin result")
377 })
378}
379
380pub(super) fn eval_dispatched_builtin_with_control(
381 binding: &FunctionBinding,
382 dispatch: FunctionDispatch,
383 evaluated: &[Value],
384 control: &uqa_core::memory::ProductionControl<'_>,
385 context: &EvalContext<'_>,
386) -> Result<uqa_core::memory::Produced<Value>> {
387 if dispatch == FunctionDispatch::FieldSelect {
388 if let Some(field) = &binding.composite_field {
389 return super::composites::fields::select_with_control(
391 field,
392 evaluated,
393 context.engine,
394 control,
395 );
396 }
397 }
398 let collation = FunctionBinding::selected_input_collation(Some(binding));
399 if let Some(result) = scalar_postgres::eval_dispatched_postgres_function_with_control(
400 dispatch, evaluated, collation, control,
401 ) {
402 return result;
403 }
404 match dispatch {
405 FunctionDispatch::MergeAction => {
406 crate::semantics::runtime_scalars::merge_action_value_with_control(
407 evaluated.len(),
408 context.row_lookup()?,
409 control,
410 )
411 }
412 FunctionDispatch::CollationFor {
413 collation_oid,
414 noncollatable_type_oid,
415 } => super::collation_for::evaluate(
416 collation_oid,
417 noncollatable_type_oid,
418 context.engine,
419 control,
420 ),
421 FunctionDispatch::TypeOf { type_oid } => {
422 Ok(control.finish(Value::Int(i64::from(type_oid)), control.empty_reservation())?)
423 }
424 FunctionDispatch::NumericOperator(operator) => {
425 super::numeric_operator::eval_bound_operator_with_control(
426 operator, binding, evaluated, control,
427 )
428 }
429 FunctionDispatch::JsonPath { as_text, jsonb } => {
430 super::json::json_path_function_with_control(evaluated, as_text, jsonb, control)
431 }
432 FunctionDispatch::Concat { oid } => {
433 super::concatenation::evaluate(binding, oid, evaluated, control, context)
434 }
435 FunctionDispatch::Pattern { operator, .. } => {
436 super::pattern::evaluate(operator, evaluated, collation, control)
437 }
438 FunctionDispatch::PatternEscape { similar } => {
439 super::pattern::escape(similar, evaluated, control)
440 }
441 FunctionDispatch::JsonExtract { as_text, path } => {
442 super::json::json_extract_operator_with_control(evaluated, as_text, path, control)
443 }
444 FunctionDispatch::ArraySortJson => {
445 let catalog = context.engine.map(super::EngineValueCatalog);
446 scalar_array::eval_dispatched_json_array_sort_with_control(
447 evaluated,
448 control,
449 catalog
450 .as_ref()
451 .map(|catalog| catalog as &dyn super::SQLValueCatalog),
452 )
453 }
454 FunctionDispatch::ArrayConcat
455 | FunctionDispatch::ArrayAppend
456 | FunctionDispatch::ArrayPrepend => {
457 let name = match dispatch {
458 FunctionDispatch::ArrayConcat => "array_cat",
459 FunctionDispatch::ArrayAppend => "array_append",
460 _ => "array_prepend",
461 };
462 scalar_array::eval_array_functions_with_control(name, evaluated, control)
463 .expect("registered array concatenation operation")
464 }
465 FunctionDispatch::Range {
466 operation,
467 subtype,
468 multirange,
469 } => scalar_range::eval_dispatched_range_function_with_control(
470 operation, subtype, multirange, evaluated, control,
471 ),
472 FunctionDispatch::Enum {
474 operation,
475 type_oid,
476 } => super::enums::enum_function_value_with_control(
477 None, operation, type_oid, evaluated, None, control,
478 ),
479 FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => Err(
480 SQLError::Internal("call-argument syntax marker reached scalar execution".into()),
481 ),
482 _ => Err(SQLError::Internal(format!(
483 "{} has no scalar executor",
484 dispatch.label()
485 ))),
486 }
487}