Skip to main content

uqa_sql/expr/
call_dispatch.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Scalar call dispatch after arguments have been normalized and evaluated.
8
9use uqa_core::{ArrayValue, Value};
10
11use crate::error::{Result, SQLError};
12
13use super::call_arguments::normalized_function_name;
14use super::context::EvalContext;
15use super::conversion::to_f64;
16use super::diagnostics::{unknown_function_error, value_type_name};
17use super::json::{jsonpath_candidate, jsonpath_match};
18use super::random;
19use super::scalar_dispatch::{eval_scalar_function_with_context, eval_sequence_function};
20
21mod named;
22mod production;
23mod temporal;
24pub use named::builtin_named_args;
25pub use production::{
26    eval_builtin_function_call_with_control, eval_generated_function_call_with_control,
27};
28
29/// Execute a scalar function after its argument expressions have already been evaluated.
30///
31/// This is the shared SQL-semantics kernel used by both the parser AST evaluator and the physical scalar IR evaluator. Keeping dispatch here avoids converting a physical expression back into an AST [`crate::ast::Expr`] merely to reuse built-in, sequence, registered, or user-defined function behavior.
32///
33/// An unbound call recorded no input collation, so collation-dependent built-ins use the database default collation.
34pub fn eval_function_call(
35    name: &str,
36    call_args: Vec<(Option<String>, Value)>,
37    ctx: &EvalContext<'_>,
38) -> Result<Value> {
39    eval_function_call_inner(name, call_args, ctx, true, default_collation())
40}
41
42/// Execute a call whose stored binding selects a built-in routine. Dynamic
43/// runtime callbacks and SQL routines must not override this stable binding.
44pub fn eval_builtin_function_call(
45    name: &str,
46    call_args: Vec<(Option<String>, Value)>,
47    ctx: &EvalContext<'_>,
48) -> Result<Value> {
49    eval_function_call_inner(name, call_args, ctx, false, default_collation())
50}
51
52/// Execute a bound built-in with the input collation its binding retained, `PostgreSQL`'s `inputcollid`.
53pub(super) fn eval_selected_builtin_function_call(
54    name: &str,
55    call_args: Vec<(Option<String>, Value)>,
56    ctx: &EvalContext<'_>,
57    collation: u32,
58) -> Result<Value> {
59    eval_function_call_inner(name, call_args, ctx, false, collation)
60}
61
62fn default_collation() -> u32 {
63    crate::ast::FunctionBinding::selected_input_collation(None)
64}
65
66#[expect(
67    clippy::too_many_lines,
68    reason = "builtin dispatch preserves arity, NULL, and error precedence"
69)]
70fn eval_function_call_inner(
71    name: &str,
72    call_args: Vec<(Option<String>, Value)>,
73    ctx: &EvalContext<'_>,
74    allow_dynamic_dispatch: bool,
75    collation: u32,
76) -> Result<Value> {
77    let lower = normalized_function_name(name);
78    let lower = lower.as_ref();
79    let _interval_style = super::interval_style::call_scope(
80        lower,
81        &call_args,
82        ctx.engine,
83        &uqa_core::memory::ProductionControl::uncontrolled(),
84    )?;
85    let call_args = if super::enums::call_applies_output_functions(lower, &call_args)
86        && call_args
87            .iter()
88            .any(|(_, value)| super::enums::contains_enum_carrier(value))
89    {
90        super::enums::render_call_arguments(
91            ctx.engine.and_then(super::EngineHook::enum_labels),
92            call_args,
93        )?
94    } else {
95        call_args
96    };
97    let evaluated: Vec<Value> = call_args.iter().map(|(_, value)| value.clone()).collect();
98
99    if let Some(result) = super::current_time::eval_current_time(lower, &evaluated, Some(ctx)) {
100        return result;
101    }
102
103    if lower == "current_setting" {
104        return super::session_settings::current_setting(&evaluated, ctx);
105    }
106    if lower == "set_config" {
107        return super::session_settings::set_config(&evaluated, ctx);
108    }
109    if let Some(result) = super::session_sleep::eval_session_sleep(lower, &evaluated, ctx) {
110        return result;
111    }
112
113    if let Some(result) = random::eval_random_function(lower, &call_args, ctx) {
114        return result;
115    }
116    if lower == "random" && !evaluated.is_empty() {
117        return Err(SQLError::TypeMismatch("random takes no arguments".into()));
118    }
119    if lower == "setseed" {
120        let [value] = evaluated.as_slice() else {
121            return Err(SQLError::TypeMismatch("setseed takes 1 arg".into()));
122        };
123        let seed = to_f64(value)?;
124        if !seed.is_finite() || !(-1.0..=1.0).contains(&seed) {
125            return Err(SQLError::Routine {
126                sqlstate: "22023".into(),
127                message: format!("setseed parameter {seed} is out of allowed range [-1,1]"),
128            });
129        }
130        let engine = ctx.engine.ok_or_else(|| {
131            SQLError::Unsupported("setseed requires a logical engine session".into())
132        })?;
133        if !engine.set_random_seed(seed).map_err(SQLError::Internal)? {
134            return Err(SQLError::Unsupported(
135                "engine hook does not provide a session random stream".into(),
136            ));
137        }
138        return Ok(Value::Str(String::new()));
139    }
140
141    if lower == "current_schema" {
142        if !evaluated.is_empty() {
143            return Err(SQLError::TypeMismatch(
144                "current_schema takes no arguments".into(),
145            ));
146        }
147        let schema = match ctx.engine {
148            Some(engine) => engine.current_schema().map_err(SQLError::Internal)?,
149            None => Some("public".to_string()),
150        };
151        return Ok(schema.map_or(Value::Null, Value::Str));
152    }
153    if lower == "current_schemas" {
154        let [Value::Bool(include_implicit)] = evaluated.as_slice() else {
155            return Err(SQLError::TypeMismatch(
156                "current_schemas takes one boolean argument".into(),
157            ));
158        };
159        let schemas = ctx
160            .engine
161            .map(|engine| engine.current_schemas(*include_implicit))
162            .transpose()
163            .map_err(SQLError::Internal)?
164            .flatten()
165            .unwrap_or_else(|| {
166                let mut schemas = Vec::new();
167                if *include_implicit {
168                    schemas.push("pg_catalog".to_string());
169                }
170                schemas.push("public".to_string());
171                schemas
172            });
173        return ArrayValue::try_new(schemas.into_iter().map(Value::Str).collect())
174            .map(Value::Array)
175            .ok_or_else(|| SQLError::TypeMismatch("invalid current_schemas result".into()));
176    }
177    if matches!(lower, "current_user" | "session_user") {
178        if !evaluated.is_empty() {
179            return Err(SQLError::TypeMismatch(format!(
180                "{lower} takes no arguments"
181            )));
182        }
183        let user = ctx
184            .engine
185            .map(|engine| {
186                if lower == "current_user" {
187                    engine.current_user()
188                } else {
189                    engine.session_user()
190                }
191            })
192            .transpose()?
193            .flatten()
194            .unwrap_or_else(|| "uqa".to_string());
195        return Ok(Value::Str(user));
196    }
197    let regobject_type = match lower {
198        "to_regproc" => Some(crate::ast::ColumnType::Regproc),
199        "to_regprocedure" => Some(crate::ast::ColumnType::Regprocedure),
200        "to_regclass" => Some(crate::ast::ColumnType::Regclass),
201        "to_regcollation" => Some(crate::ast::ColumnType::Regcollation),
202        "to_regnamespace" => Some(crate::ast::ColumnType::Regnamespace),
203        "to_regrole" => Some(crate::ast::ColumnType::Regrole),
204        "to_regtype" => Some(crate::ast::ColumnType::Regtype),
205        _ => None,
206    };
207    if let Some(regobject_type) = regobject_type {
208        let [value] = evaluated.as_slice() else {
209            return Err(SQLError::BadArity {
210                name: lower.into(),
211                expected: "1".into(),
212                actual: evaluated.len(),
213            });
214        };
215        let name = match value {
216            Value::Null => return Ok(Value::Null),
217            Value::Str(name) | Value::FixedChar(name) => name,
218            value => {
219                return Err(SQLError::TypeMismatch(format!(
220                    "{lower} requires text, got {}",
221                    value_type_name(value)
222                )));
223            }
224        };
225        let oid = ctx
226            .engine
227            .map(|engine| engine.resolve_regobject(&regobject_type, name))
228            .transpose()?
229            .flatten();
230        return Ok(oid.map_or(Value::Null, Value::Int));
231    }
232
233    // Functions registered in the operator registry (text_match,
234    // knn_match, ...) are dispatched by the relational/access-path
235    // executor. JSONPath fts_match is the scalar exception.
236    if crate::registry::is_registered(lower) {
237        if lower == "fts_match" && jsonpath_candidate(&evaluated) {
238            return jsonpath_match(&evaluated);
239        }
240        return Err(SQLError::Unsupported(format!(
241            "scalar evaluation of `{name}` is not supported (use the function registry)"
242        )));
243    }
244
245    let returns_set = crate::semantics::sets::validation::builtin_returns_set(lower);
246    if call_args.iter().any(|(name, _)| name.is_some()) {
247        if !returns_set {
248            if let Some(positional) = builtin_named_args(
249                lower,
250                &call_args,
251                &uqa_core::memory::ProductionControl::uncontrolled(),
252            )? {
253                return eval_scalar_function_with_context(lower, &positional, ctx, collation);
254            }
255        }
256        if let Some(engine) = ctx.engine.filter(|_| allow_dynamic_dispatch) {
257            if let Some(result) = engine.call_user_function(lower, &call_args) {
258                return result;
259            }
260        }
261        return Err(unresolved_call_error(lower, &call_args, returns_set));
262    }
263
264    // Sequence functions use engine-owned session state and therefore precede pure built-in dispatch.
265    if matches!(lower, "nextval" | "currval" | "lastval" | "setval") {
266        return eval_sequence_function(lower, &evaluated, ctx);
267    }
268    if let Some(engine) = ctx
269        .engine
270        .filter(|engine| allow_dynamic_dispatch && engine.has_scalar_functions())
271    {
272        if let Some(result) = engine.call_scalar_function(lower, &evaluated) {
273            return result;
274        }
275    }
276    if lower == "date_trunc" {
277        if let Some(result) = super::time::truncate_session_zone(&evaluated, ctx) {
278            return result;
279        }
280    }
281    if let Some(result) = temporal::extract_session_zone(lower, &evaluated, ctx) {
282        return result;
283    }
284    if matches!(lower, "coalesce" | "nullif" | "greatest" | "least") {
285        return super::scalar_core::selection_with_context(
286            lower,
287            &evaluated,
288            &uqa_core::memory::ProductionControl::uncontrolled(),
289            ctx,
290        )
291        .map(|value| {
292            value
293                .into_uncontrolled()
294                .expect("ordinary selection result")
295        });
296    }
297    match eval_scalar_function_with_context(lower, &evaluated, ctx, collation) {
298        // Unknown built-in: fall through to user-defined functions,
299        // mirroring PostgreSQL's search-path order.
300        Err(SQLError::UnknownFunction(_)) => {
301            if let Some(engine) = ctx.engine.filter(|_| allow_dynamic_dispatch) {
302                if let Some(result) = engine.call_user_function(lower, &call_args) {
303                    return result;
304                }
305            }
306            Err(unresolved_call_error(lower, &call_args, returns_set))
307        }
308        other => other,
309    }
310}
311
312/// A call no scalar routine evaluated. A set-returning built-in exists but cannot produce the one value a scalar expression needs.
313fn unresolved_call_error(
314    name: &str,
315    call_args: &[(Option<String>, Value)],
316    returns_set: bool,
317) -> SQLError {
318    if returns_set {
319        crate::semantics::sets::placement::set_valued_call_error()
320    } else {
321        unknown_function_error(name, call_args)
322    }
323}