Skip to main content

uqa_sql/expr/
builtin.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Built-in strictness policy and structurally bound execution.
8
9use 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/// Return the `PostgreSQL` 18 strictness contract selected by a structural function binding. Parser-owned syntax and overload-specific built-ins must be classified by [`FunctionDispatch`], never by their diagnostic display label.
231#[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::AssignmentStore
271            | FunctionDispatch::ArraySlices
272            | FunctionDispatch::ArraySlicesWithBounds(_)
273            | FunctionDispatch::CollationFor { .. }
274            | FunctionDispatch::TypeOf { .. }
275            | FunctionDispatch::ArrayConcat
276            | FunctionDispatch::ArrayAppend
277            | FunctionDispatch::ArrayPrepend
278            | FunctionDispatch::Slice
279            | FunctionDispatch::AnyOperator
280            | FunctionDispatch::AllOperator
281            | FunctionDispatch::ValueNullTest { .. }
282            | FunctionDispatch::BooleanTest(_)
283            | FunctionDispatch::DistinctNot
284            | FunctionDispatch::RowDistinct
285            | FunctionDispatch::ValueIsDistinct
286            | FunctionDispatch::IsDistinct => Some(false),
287            FunctionDispatch::Enum { operation, .. } => Some(operation.is_strict()),
288            FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => None,
289        };
290    }
291    binding
292        .builtin
293        .then(|| builtin_scalar_function_strictness(&binding.name, argument_count))
294        .flatten()
295}
296
297/// Evaluate a call's argument list, unwrapping `name => value`
298pub fn eval_bound_builtin_function_call(
299    binding: &FunctionBinding,
300    call_args: Vec<(Option<String>, Value)>,
301    ctx: &EvalContext<'_>,
302) -> Result<Value> {
303    if let Some(error) = &binding.resolution_error {
304        return Err(error.sql_error());
305    }
306    if let Some(hook) = ctx.engine {
307        hook.require_builtin_execute(binding)?;
308    }
309    let Some(dispatch) = binding.dispatch else {
310        let value = eval_selected_builtin_function_call(
311            &binding.name,
312            call_args,
313            ctx,
314            FunctionBinding::selected_input_collation(Some(binding)),
315        )?;
316        // Fixed signatures retain widths that the shared integer and floating carriers cannot enforce on their own.
317        if matches!(value, Value::Int(_) | Value::Float(_)) {
318            if let Some(
319                ty @ (crate::ColumnType::SmallInteger
320                | crate::ColumnType::Integer
321                | crate::ColumnType::Real),
322            ) = crate::fixed_builtin_return_type(binding)
323            {
324                return super::cast_value(&value, &ty.sql_name());
325            }
326        }
327        return Ok(value);
328    };
329    if let Some(result) = random::eval_dispatched_random_function(dispatch, &call_args, ctx) {
330        return result;
331    }
332    if call_args.iter().any(|(name, _)| name.is_some()) {
333        return Err(SQLError::Internal(format!(
334            "bound {} expression retained a named argument",
335            dispatch.label()
336        )));
337    }
338    let evaluated = call_args
339        .into_iter()
340        .map(|(_, value)| value)
341        .collect::<Vec<_>>();
342    if let FunctionDispatch::Enum {
343        operation,
344        type_oid,
345    } = dispatch
346    {
347        return super::enums::enum_function_value_with_state(
348            ctx.engine.and_then(super::EngineHook::enum_labels),
349            operation,
350            type_oid,
351            &evaluated,
352            ctx.enum_comparison_state(),
353        );
354    }
355    if let Some(result) = scalar_postgres::eval_comparison_with_context(
356        dispatch,
357        &evaluated,
358        &uqa_core::memory::ProductionControl::uncontrolled(),
359        ctx,
360    ) {
361        return result.map(|value| {
362            value
363                .into_uncontrolled()
364                .expect("ordinary comparison result")
365        });
366    }
367    eval_dispatched_builtin_with_control(
368        binding,
369        dispatch,
370        &evaluated,
371        &uqa_core::memory::ProductionControl::uncontrolled(),
372        ctx,
373    )
374    .map(|value| {
375        value
376            .into_uncontrolled()
377            .expect("ordinary dispatched builtin result")
378    })
379}
380
381pub(super) fn eval_dispatched_builtin_with_control(
382    binding: &FunctionBinding,
383    dispatch: FunctionDispatch,
384    evaluated: &[Value],
385    control: &uqa_core::memory::ProductionControl<'_>,
386    context: &EvalContext<'_>,
387) -> Result<uqa_core::memory::Produced<Value>> {
388    if dispatch == FunctionDispatch::FieldSelect {
389        if let Some(field) = binding.composite_field() {
390            // Arguments have already run: descriptor changes must not suppress their observable effects.
391            return super::composites::fields::select_with_control(
392                field,
393                evaluated,
394                context.engine,
395                control,
396            );
397        }
398    }
399    let collation = FunctionBinding::selected_input_collation(Some(binding));
400    let catalog = context.engine.map(super::EngineValueCatalog);
401    let catalog = catalog
402        .as_ref()
403        .map(|catalog| catalog as &dyn super::SQLValueCatalog);
404    if dispatch == FunctionDispatch::AssignmentStore {
405        return eval_assignment_arguments(binding, evaluated, catalog, control);
406    }
407    if let Some(result) = scalar_postgres::eval_dispatched_postgres_function_with_control(
408        dispatch, evaluated, collation, catalog, control,
409    ) {
410        return result;
411    }
412    match dispatch {
413        FunctionDispatch::MergeAction => {
414            crate::semantics::runtime_scalars::merge_action_value_with_control(
415                evaluated.len(),
416                context.row_lookup()?,
417                control,
418            )
419        }
420        FunctionDispatch::CollationFor {
421            collation_oid,
422            noncollatable_type_oid,
423        } => super::collation_for::evaluate(
424            collation_oid,
425            noncollatable_type_oid,
426            context.engine,
427            control,
428        ),
429        FunctionDispatch::TypeOf { type_oid } => {
430            Ok(control.finish(Value::Int(i64::from(type_oid)), control.empty_reservation())?)
431        }
432        FunctionDispatch::NumericOperator(operator) => {
433            super::numeric_operator::eval_bound_operator_with_control(
434                operator, binding, evaluated, control,
435            )
436        }
437        FunctionDispatch::JsonPath { as_text, jsonb } => {
438            super::json::json_path_function_with_control(evaluated, as_text, jsonb, control)
439        }
440        FunctionDispatch::Concat { oid } => {
441            super::concatenation::evaluate(binding, oid, evaluated, control, context)
442        }
443        FunctionDispatch::Pattern { operator, .. } => {
444            super::pattern::evaluate(operator, evaluated, collation, control)
445        }
446        FunctionDispatch::PatternEscape { similar } => {
447            super::pattern::escape(similar, evaluated, control)
448        }
449        FunctionDispatch::JsonExtract { as_text, path } => {
450            super::json::json_extract_operator_with_control(evaluated, as_text, path, control)
451        }
452        FunctionDispatch::ArraySortJson => {
453            scalar_array::eval_dispatched_json_array_sort_with_control(evaluated, control, catalog)
454        }
455        FunctionDispatch::ArrayConcat
456        | FunctionDispatch::ArrayAppend
457        | FunctionDispatch::ArrayPrepend => {
458            let name = match dispatch {
459                FunctionDispatch::ArrayConcat => "array_cat",
460                FunctionDispatch::ArrayAppend => "array_append",
461                _ => "array_prepend",
462            };
463            scalar_array::eval_array_functions_with_control(name, evaluated, control)
464                .expect("registered array concatenation operation")
465        }
466        FunctionDispatch::Range {
467            operation,
468            subtype,
469            multirange,
470        } => scalar_range::eval_dispatched_range_function_with_control(
471            operation, subtype, multirange, evaluated, control,
472        ),
473        // Catalog-free evaluation: comparisons use label keys; label lookups report the missing catalog.
474        FunctionDispatch::Enum {
475            operation,
476            type_oid,
477        } => super::enums::enum_function_value_with_control(
478            None, operation, type_oid, evaluated, None, control,
479        ),
480        FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => Err(
481            SQLError::Internal("call-argument syntax marker reached scalar execution".into()),
482        ),
483        _ => Err(SQLError::Internal(format!(
484            "{} has no scalar executor",
485            dispatch.label()
486        ))),
487    }
488}
489
490fn eval_assignment_arguments(
491    binding: &FunctionBinding,
492    evaluated: &[Value],
493    catalog: Option<&dyn super::SQLValueCatalog>,
494    control: &uqa_core::memory::ProductionControl<'_>,
495) -> Result<uqa_core::memory::Produced<Value>> {
496    let assignment = binding
497        .assignment()
498        .ok_or_else(|| SQLError::Internal("partial assignment lost its bound path".into()))?;
499    crate::assignment::path::evaluate(assignment, evaluated.len(), catalog, control, |index| {
500        Ok(&evaluated[index])
501    })
502}