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_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        "coalesce" | "greatest" | "least" if argument_count >= 1 => Some(false),
39        "nullif" | "concat_op" if argument_count == 2 => Some(false),
40        "concat" | "format" | "json_build_array" | "jsonb_build_array" | "json_build_object"
41        | "jsonb_build_object" | "num_nulls" | "num_nonnulls" => Some(false),
42        "concat_ws" if argument_count >= 1 => Some(false),
43        "quote_nullable" | "pg_typeof" | "typeof" if argument_count == 1 => Some(false),
44        "array_cat" | "array_append" | "array_prepend" | "array_remove" | "array_positions"
45            if argument_count == 2 =>
46        {
47            Some(false)
48        }
49        "array_position" if matches!(argument_count, 2 | 3) => Some(false),
50        "array_replace" if argument_count == 3 => Some(false),
51        "array_fill" if matches!(argument_count, 2 | 3) => Some(false),
52        "array_to_string" if argument_count == 3 => Some(false),
53        "string_to_array" | "string_to_table" if matches!(argument_count, 2 | 3) => Some(false),
54        "pg_has_role" if matches!(argument_count, 2 | 3) => Some(true),
55        "pg_get_userbyid" if argument_count == 1 => Some(true),
56        "current_setting" if matches!(argument_count, 1 | 2) => Some(true),
57        "set_config" if argument_count == 3 => Some(false),
58        "pg_sleep" | "pg_sleep_for" | "pg_sleep_until" if argument_count == 1 => Some(true),
59        "has_table_privilege" if matches!(argument_count, 2 | 3) => Some(true),
60        "has_column_privilege" if matches!(argument_count, 3 | 4) => Some(true),
61        "has_database_privilege" if matches!(argument_count, 2 | 3) => Some(true),
62        "has_schema_privilege" if matches!(argument_count, 2 | 3) => Some(true),
63        "has_sequence_privilege" | "has_function_privilege" | "has_type_privilege"
64            if matches!(argument_count, 2 | 3) =>
65        {
66            Some(true)
67        }
68        "pg_get_constraintdef" if matches!(argument_count, 1 | 2) => Some(true),
69        "pg_get_function_arguments"
70        | "pg_get_function_identity_arguments"
71        | "pg_get_function_result"
72        | "pg_get_functiondef"
73        | "pg_get_function_sqlbody"
74            if argument_count == 1 =>
75        {
76            Some(true)
77        }
78        "pg_get_sequence_data" | "pg_sequence_last_value" | "pg_sequence_parameters"
79            if argument_count == 1 =>
80        {
81            Some(true)
82        }
83        "nextval" | "currval" if argument_count == 1 => Some(true),
84        "lastval" if argument_count == 0 => Some(true),
85        "setval" if matches!(argument_count, 2 | 3) => Some(true),
86        "overlaps" if argument_count == 4 => Some(false),
87        "abs"
88        | "acos"
89        | "array_dims"
90        | "array_ndims"
91        | "array_reverse"
92        | "ascii"
93        | "asin"
94        | "atan"
95        | "bit_length"
96        | "cardinality"
97        | "casefold"
98        | "cbrt"
99        | "ceil"
100        | "ceiling"
101        | "char_length"
102        | "character_length"
103        | "chr"
104        | "cos"
105        | "cosh"
106        | "current_schemas"
107        | "degrees"
108        | "exp"
109        | "factorial"
110        | "floor"
111        | "gamma"
112        | "initcap"
113        | "isfinite"
114        | "json_array_length"
115        | "jsonb_array_length"
116        | "json_typeof"
117        | "jsonb_typeof"
118        | "jsonb_pretty"
119        | "justify_days"
120        | "justify_hours"
121        | "justify_interval"
122        | "length"
123        | "lgamma"
124        | "ln"
125        | "log10"
126        | "log2"
127        | "lower"
128        | "md5"
129        | "octet_length"
130        | "quote_ident"
131        | "quote_literal"
132        | "radians"
133        | "reverse"
134        | "row_to_json"
135        | "sign"
136        | "sin"
137        | "sinh"
138        | "sqrt"
139        | "tan"
140        | "tanh"
141        | "to_bin"
142        | "to_hex"
143        | "to_oct"
144        | "to_json"
145        | "to_jsonb"
146        | "to_regclass"
147        | "to_regnamespace"
148        | "to_regproc"
149        | "to_regprocedure"
150        | "to_regrole"
151        | "to_regtype"
152        | "to_timestamp"
153        | "upper"
154        | "uuid_extract_timestamp"
155        | "uuid_extract_version"
156            if argument_count == 1 =>
157        {
158            Some(true)
159        }
160        "random" if argument_count == 2 => Some(true),
161        "age" | "btrim" | "ltrim" | "rtrim" | "trim" | "log" | "round" | "trunc"
162        | "json_strip_nulls" | "jsonb_strip_nulls"
163            if matches!(argument_count, 1 | 2) =>
164        {
165            Some(true)
166        }
167        "array_sort" if matches!(argument_count, 1..=3) => Some(true),
168        "date_trunc" if matches!(argument_count, 2 | 3) => Some(true),
169        "array_length" | "array_lower" | "array_upper" | "atan2" | "date_part" | "decode"
170        | "encode" | "extract" | "gcd" | "lcm" | "left" | "mod" | "power" | "pow" | "repeat"
171        | "right" | "starts_with" | "position" | "strpos" | "to_char" | "to_date" | "to_number"
172        | "trim_array" | "point" | "st_distance" | "st_within"
173            if argument_count == 2 =>
174        {
175            Some(true)
176        }
177        "like" | "ilike" | "similar_to" | "regex_match_op" | "regex_imatch_op"
178            if argument_count == 2 =>
179        {
180            Some(true)
181        }
182        "like" | "ilike" | "similar_to" if argument_count == 3 => Some(false),
183        "array_to_string" if argument_count == 2 => Some(true),
184        "substring" | "substr" | "lpad" | "rpad" if matches!(argument_count, 2 | 3) => Some(true),
185        "regexp_count" if matches!(argument_count, 2..=4) => Some(true),
186        "regexp_instr" if matches!(argument_count, 2..=7) => Some(true),
187        "regexp_like" | "regexp_match" | "regexp_matches" if matches!(argument_count, 2 | 3) => {
188            Some(true)
189        }
190        "regexp_replace" if matches!(argument_count, 3..=6) => Some(true),
191        "regexp_substr" if matches!(argument_count, 2..=6) => Some(true),
192        "replace" | "split_part" | "translate" | "make_date" if argument_count == 3 => Some(true),
193        "overlay" | "jsonb_set" | "jsonb_insert" if matches!(argument_count, 3 | 4) => Some(true),
194        "json_extract_path"
195        | "jsonb_extract_path"
196        | "json_extract_path_text"
197        | "jsonb_extract_path_text"
198            if argument_count >= 2 =>
199        {
200            Some(true)
201        }
202        "json_contains" | "json_contained_by" | "json_delete_path" | "json_has_key"
203        | "json_has_any_key" | "json_has_all_keys" | "jsonb_path_exists" | "jsonpath_exists"
204        | "jsonb_path_match" | "jsonpath_match"
205            if argument_count == 2 =>
206        {
207            Some(true)
208        }
209        "make_timestamp" if matches!(argument_count, 6 | 7) => Some(true),
210        "make_interval" if argument_count <= 7 => Some(true),
211        "width_bucket" if argument_count == 4 => Some(true),
212        "st_dwithin" if matches!(argument_count, 2 | 3) => Some(true),
213        _ => None,
214    }
215}
216
217/// 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.
218#[must_use]
219pub fn bound_scalar_function_strictness(
220    name: &str,
221    binding: Option<&FunctionBinding>,
222    argument_count: usize,
223) -> Option<bool> {
224    let Some(binding) = binding else {
225        return builtin_scalar_function_strictness(name, argument_count);
226    };
227    if let Some(dispatch) = binding.dispatch {
228        return match dispatch {
229            FunctionDispatch::NumericOperator(_) => Some(true),
230            FunctionDispatch::ArraySubscripts
231            | FunctionDispatch::Subscript
232            | FunctionDispatch::FieldSelect
233            | FunctionDispatch::BetweenSymmetric
234            | FunctionDispatch::ToBinInt4
235            | FunctionDispatch::ToBinInt8
236            | FunctionDispatch::ToHexInt4
237            | FunctionDispatch::ToHexInt8
238            | FunctionDispatch::ToOctInt4
239            | FunctionDispatch::ToOctInt8
240            | FunctionDispatch::RandomInt4Range
241            | FunctionDispatch::RandomInt8Range
242            | FunctionDispatch::RandomNumericRange
243            | FunctionDispatch::ArraySortJson
244            | FunctionDispatch::JsonExtract { .. }
245            | FunctionDispatch::Range { .. } => Some(true),
246            FunctionDispatch::ArraySlices
247            | FunctionDispatch::ArrayConcat
248            | FunctionDispatch::ArrayAppend
249            | FunctionDispatch::ArrayPrepend
250            | FunctionDispatch::Slice
251            | FunctionDispatch::AnyOperator
252            | FunctionDispatch::AllOperator
253            | FunctionDispatch::IsDistinct => Some(false),
254            FunctionDispatch::Enum { operation, .. } => Some(operation.is_strict()),
255            FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => None,
256        };
257    }
258    binding
259        .builtin
260        .then(|| builtin_scalar_function_strictness(&binding.name, argument_count))
261        .flatten()
262}
263
264/// Evaluate a call's argument list, unwrapping `name => value`
265pub fn eval_bound_builtin_function_call(
266    binding: &FunctionBinding,
267    call_args: Vec<(Option<String>, Value)>,
268    ctx: &EvalContext<'_>,
269) -> Result<Value> {
270    if let Some(error) = &binding.resolution_error {
271        return Err(error.sql_error());
272    }
273    if let Some(hook) = ctx.engine {
274        hook.require_builtin_execute(binding)?;
275    }
276    let Some(dispatch) = binding.dispatch else {
277        let value = eval_builtin_function_call(&binding.name, call_args, ctx)?;
278        // Fixed signatures retain widths that the shared integer and floating carriers cannot enforce on their own.
279        if matches!(value, Value::Int(_) | Value::Float(_)) {
280            if let Some(
281                ty @ (crate::ColumnType::SmallInteger
282                | crate::ColumnType::Integer
283                | crate::ColumnType::Real),
284            ) = crate::fixed_builtin_return_type(binding)
285            {
286                return super::cast_value(&value, &ty.sql_name());
287            }
288        }
289        return Ok(value);
290    };
291    if let Some(result) = random::eval_dispatched_random_function(dispatch, &call_args, ctx) {
292        return result;
293    }
294    if call_args.iter().any(|(name, _)| name.is_some()) {
295        return Err(SQLError::Internal(format!(
296            "bound {} expression retained a named argument",
297            dispatch.label()
298        )));
299    }
300    let evaluated = call_args
301        .into_iter()
302        .map(|(_, value)| value)
303        .collect::<Vec<_>>();
304    if let FunctionDispatch::Enum {
305        operation,
306        type_oid,
307    } = dispatch
308    {
309        return super::enums::enum_function_value(
310            ctx.engine.and_then(super::EngineHook::enum_labels),
311            operation,
312            type_oid,
313            &evaluated,
314        );
315    }
316    eval_dispatched_builtin_with_control(
317        binding,
318        dispatch,
319        &evaluated,
320        &uqa_core::memory::ProductionControl::uncontrolled(),
321    )
322    .map(|value| {
323        value
324            .into_uncontrolled()
325            .expect("ordinary dispatched builtin result")
326    })
327}
328
329pub(super) fn eval_dispatched_builtin_with_control(
330    binding: &FunctionBinding,
331    dispatch: FunctionDispatch,
332    evaluated: &[Value],
333    control: &uqa_core::memory::ProductionControl<'_>,
334) -> Result<uqa_core::memory::Produced<Value>> {
335    if let Some(result) = scalar_postgres::eval_dispatched_postgres_function_with_control(
336        dispatch, evaluated, control,
337    ) {
338        return result;
339    }
340    match dispatch {
341        FunctionDispatch::NumericOperator(operator) => {
342            super::numeric_operator::eval_bound_operator_with_control(
343                operator, binding, evaluated, control,
344            )
345        }
346        FunctionDispatch::JsonExtract { as_text, path } => {
347            super::json::json_extract_operator_with_control(evaluated, as_text, path, control)
348        }
349        FunctionDispatch::ArraySortJson => {
350            scalar_array::eval_dispatched_json_array_sort_with_control(evaluated, control)
351        }
352        FunctionDispatch::ArrayConcat
353        | FunctionDispatch::ArrayAppend
354        | FunctionDispatch::ArrayPrepend => {
355            let name = match dispatch {
356                FunctionDispatch::ArrayConcat => "array_cat",
357                FunctionDispatch::ArrayAppend => "array_append",
358                _ => "array_prepend",
359            };
360            scalar_array::eval_array_functions_with_control(name, evaluated, control)
361                .expect("registered array concatenation operation")
362        }
363        FunctionDispatch::Range {
364            operation,
365            subtype,
366            multirange,
367        } => scalar_range::eval_dispatched_range_function_with_control(
368            operation, subtype, multirange, evaluated, control,
369        ),
370        // Catalog-free evaluation: comparisons use label keys; label lookups report the missing catalog.
371        FunctionDispatch::Enum {
372            operation,
373            type_oid,
374        } => Ok(
375            control.retain_external_value(super::enums::enum_function_value(
376                None, operation, type_oid, evaluated,
377            )?)?,
378        ),
379        FunctionDispatch::NamedArgument | FunctionDispatch::VariadicArgument => Err(
380            SQLError::Internal("call-argument syntax marker reached scalar execution".into()),
381        ),
382        _ => Err(SQLError::Internal(format!(
383            "{} has no scalar executor",
384            dispatch.label()
385        ))),
386    }
387}