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