uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Ordinary WITHIN GROUP lookup keeps declared signatures and modifier checks separate from input coercion.

mod catalog;
mod production;
pub(super) use production::resolve_with_control;

use crate::ast::{ColumnType, FunctionBinding, FunctionOrderSyntax};
use crate::type_resolution::ResolvedFunctionOverload;
use crate::{FunctionTypeResolver, SQLError};

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Kind {
    Ordinary,
    Aggregate,
    OrderedSet { direct: usize, polymorphic: bool },
    Hypothetical,
    Window,
}

pub(super) fn uses_ordered_arguments(
    syntax: FunctionOrderSyntax,
    name: &str,
    binding: Option<&FunctionBinding>,
    ordered: usize,
) -> bool {
    syntax == FunctionOrderSyntax::WithinGroup
        || (syntax == FunctionOrderSyntax::Legacy
            && ordered > 0
            && binding.is_none_or(|binding| binding.builtin)
            && is_ordered_set(name))
}

pub(super) fn is_ordered_set(name: &str) -> bool {
    matches!(
        crate::semantics::builtin_function_dispatch_name(name).as_ref(),
        "mode" | "percentile_cont" | "percentile_disc"
    )
}

/// Resolve declared signatures together with SQL catalog routines. Ordered inputs
/// are already in `types`; they remain separate in the actual expression tree.
pub(super) fn resolve(
    name: &str,
    binding: Option<&FunctionBinding>,
    names: &[Option<String>],
    types: &[Option<ColumnType>],
    variadic: bool,
    resolver: &dyn FunctionTypeResolver,
) -> Result<Option<(ResolvedFunctionOverload, Kind)>, SQLError> {
    Ok(resolve_with_control(
        name,
        binding,
        names,
        types,
        variadic,
        resolver,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )?
    .map(|(selected, kind)| {
        (
            selected
                .into_uncontrolled()
                .expect("ordinary ordered call selection"),
            kind,
        )
    }))
}

pub(super) fn is_polymorphic(name: &str) -> bool {
    matches!(
        name,
        "any" | "anyelement" | "anyarray" | "anynonarray" | "anyenum" | "anycompatible"
    )
}

#[derive(Clone, Copy)]
pub(super) enum DirectArguments {
    Values(usize),
    Star,
}

impl From<&[crate::ScalarExpr]> for DirectArguments {
    fn from(arguments: &[crate::ScalarExpr]) -> Self {
        if matches!(arguments, [crate::ScalarExpr::Star]) {
            Self::Star
        } else {
            Self::Values(arguments.len())
        }
    }
}

#[derive(Clone, Copy)]
pub(super) struct Modifiers {
    pub direct: DirectArguments,
    pub ordered: usize,
    pub within_group: bool,
    pub distinct: bool,
    pub filtered: bool,
}

pub(super) fn validate(
    name: &str,
    kind: Kind,
    modifiers: Modifiers,
    names: &[Option<String>],
    types: &[Option<ColumnType>],
) -> Result<(), SQLError> {
    let Modifiers {
        direct,
        ordered,
        within_group,
        distinct,
        filtered,
    } = modifiers;
    let bare_star = matches!(direct, DirectArguments::Star);
    let direct = match direct {
        DirectArguments::Values(count) => count,
        DirectArguments::Star => 0,
    };
    let wrong = |message| SQLError::Routine {
        sqlstate: "42809".into(),
        message,
    };
    match kind {
        Kind::Ordinary => {
            if bare_star {
                return Err(wrong(format!("{name}(*) specified, but {name} is not an aggregate function")));
            }
            let modifier = if distinct { Some("DISTINCT") }
            else if within_group { Some("WITHIN GROUP") }
            else if ordered > 0 { Some("ORDER BY") }
            else if filtered { Some("FILTER") } else { None };
            if let Some(modifier) = modifier {
                return Err(wrong(format!("{modifier} specified, but {name} is not an aggregate function")));
            }
        }
        Kind::Aggregate if within_group => return Err(wrong(format!(
            "{name} is not an ordered-set aggregate, so it cannot have WITHIN GROUP"
        ))),
        Kind::OrderedSet { .. } | Kind::Hypothetical if !within_group => return Err(wrong(format!(
            "WITHIN GROUP is required for ordered-set aggregate {name}"
        ))),
        Kind::OrderedSet { direct: expected, .. } if direct != expected => return Err(invalid_split(name, names, types, format!(
            "There is an ordered-set aggregate {name}, but it requires {expected} direct argument{}, not {direct}.", if expected == 1 { "" } else { "s" }
        ))),
        Kind::Hypothetical if direct != ordered => return Err(invalid_split(name, names, types, format!(
            "To use the hypothetical-set aggregate {name}, the number of hypothetical direct arguments (here {direct}) must match the number of ordering columns (here {ordered})."
        ))),
        Kind::Window => return Err(wrong(format!("window function {name} requires an OVER clause"))),
        _ => {},
    }
    // ParseFuncOrColumn checks the selected routine's modifiers before
    // enforce_generic_type_consistency, and reads implicit inputs afterwards.
    if matches!(
        kind,
        Kind::OrderedSet {
            polymorphic: true,
            ..
        }
    ) && types.last().is_some_and(Option::is_none)
    {
        return Err(SQLError::Routine {
            sqlstate: "42804".into(),
            message: "could not determine polymorphic type because input has type unknown".into(),
        });
    }
    Ok(())
}

fn invalid_split(
    name: &str,
    names: &[Option<String>],
    types: &[Option<ColumnType>],
    hint: String,
) -> SQLError {
    let mut error = crate::type_resolution::function_resolution_error(
        "42883",
        name,
        names,
        types,
        "does not exist",
    );
    if let SQLError::Diagnostic {
        hint: selected_hint,
        ..
    } = &mut error
    {
        *selected_hint = Some(hint);
    }
    error
}

/// Validate an ordinary built-in aggregate's selected signature before inferring its result or evaluating an input conversion. A bare star is not an unknown-typed argument.
pub(super) fn validate_builtin_aggregate_arguments(
    name: &str,
    binding: Option<&FunctionBinding>,
    arguments: &[crate::ScalarExpr],
    missing_signature: impl FnOnce() -> SQLError,
) -> Result<(), SQLError> {
    let selected = binding.map_or(name, |binding| binding.name.as_str());
    if !crate::semantics::is_builtin_aggregate_call(name, binding) || is_ordered_set(selected) {
        return Ok(());
    }
    let local = crate::semantics::builtin_aggregate_dispatch_name(selected);
    let argument_count = match DirectArguments::from(arguments) {
        DirectArguments::Values(count) => count,
        DirectArguments::Star => 0,
    };
    let accepts = if local.eq_ignore_ascii_case("count") {
        argument_count <= 1
    } else if ["string_agg", "json_object_agg", "jsonb_object_agg"]
        .iter()
        .any(|expected| local.eq_ignore_ascii_case(expected))
    {
        argument_count == 2
    } else {
        argument_count == 1
    };
    if !accepts {
        return Err(missing_signature());
    }
    if argument_count == 0 && !matches!(arguments, [crate::ScalarExpr::Star]) {
        return Err(SQLError::Routine {
            sqlstate: "42809".into(),
            message: format!("{name}(*) must be used to call a parameterless aggregate function"),
        });
    }
    Ok(())
}

impl super::SchemaScope {
    pub(super) fn bind_ordered_function_for_storage(
        &mut self,
        routines: &dyn crate::routines::RoutineResolution,
        expression: &mut crate::ScalarExpr,
        schema: &crate::RowSchema,
        subqueries: &[crate::plan::QueryPlan],
        params: &[crate::SQLParam],
    ) -> Result<(), SQLError> {
        let resolver =
            self.query_function_type_resolver(routines, expression, schema, subqueries, params)?;
        let crate::ScalarExpr::Func {
            name,
            binding,
            args,
            order_syntax,
            order_by,
            distinct,
            filter,
        } = expression
        else {
            unreachable!("function binding")
        };
        let within_group =
            uses_ordered_arguments(*order_syntax, name, binding.as_ref(), order_by.len());
        let (mut names, mut types, variadic) =
            crate::function_call_argument_signature(args, schema, params, Some(&resolver))?;
        if within_group {
            for order in order_by.iter() {
                names.push(None);
                types.push(
                    crate::common_context_expression_type(
                        &order.expr,
                        schema,
                        params,
                        Some(&resolver),
                    )?
                    .and_then(|ty| {
                        crate::effective_overload_argument_type_with_params(
                            &order.expr,
                            Some(ty),
                            params,
                        )
                    }),
                );
            }
        }
        if let Some((selected, kind)) =
            resolve(name, binding.as_ref(), &names, &types, variadic, &resolver)?
        {
            validate(
                name,
                kind,
                Modifiers {
                    direct: DirectArguments::from(args.as_slice()),
                    ordered: order_by.len(),
                    within_group,
                    distinct: *distinct,
                    filtered: filter.is_some(),
                },
                &names,
                &types,
            )?;
            self.record_routine_dependency(&selected.binding)?;
            FunctionBinding::rebind(binding, selected.binding);
            if within_group && *order_syntax == FunctionOrderSyntax::Legacy {
                *order_syntax = FunctionOrderSyntax::WithinGroup;
            }
        }
        Ok(())
    }
}