uqa-sql 0.6.2

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

//! Resolve consumed values against their lexical query and preceding-source scopes.

mod substitution;
pub use substitution::substitute_outer_columns;

use crate::plan::{AnalyzedSource, QueryPlan, RelationalPlan, SourcePlan};
use crate::{RowSchema, ScalarExpr};

/// Visit input references not provided by a nested query or preceding LATERAL input. Analysis must have retained every required source layout.
pub struct ScopedReferences<'a> {
    visitor: &'a mut dyn FnMut(&ScalarExpr),
    complete: bool,
    scopes: Vec<RowSchema>,
}

impl<'a> ScopedReferences<'a> {
    pub fn new(visitor: &'a mut dyn FnMut(&ScalarExpr)) -> Self {
        Self {
            visitor,
            complete: true,
            scopes: Vec::new(),
        }
    }

    pub fn expression(&mut self, expression: &ScalarExpr, subqueries: &[QueryPlan]) {
        crate::semantics::visit_input_values(expression, &mut |part| {
            let index = match part {
                ScalarExpr::ScalarSubquery(index)
                | ScalarExpr::Exists {
                    subquery: index, ..
                }
                | ScalarExpr::InSubquery {
                    subquery: index, ..
                } => Some(*index),
                _ => None,
            };
            if let Some(index) = index {
                if let Some(query) = subqueries.get(index) {
                    self.query(query);
                } else {
                    self.complete = false;
                }
            } else if !self.scopes.iter().rev().any(|schema| {
                let reference = crate::type_resolution::field_selection::field_reference(part)
                    .map_or(part, |(base, _)| base);
                locally_resolved(reference, schema)
            }) {
                (self.visitor)(part);
            }
        });
    }

    pub fn is_complete(&self) -> bool {
        self.complete
    }

    pub fn query(&mut self, query: &QueryPlan) {
        for cte in &query.ctes {
            if let Some(query) = cte.body.query() {
                self.query(query);
            } else {
                self.complete = false;
            }
        }
        match &query.root {
            RelationalPlan::QueryBlock(block) => {
                if let Some(input) = &block.from {
                    self.complete &= query.analyzed_source.is_some();
                    self.source(
                        input,
                        query.analyzed_source.as_deref(),
                        &block.subqueries,
                        &[],
                        false,
                    );
                }
                let length = self.scopes.len();
                self.scopes.push(
                    query
                        .analyzed_source
                        .as_ref()
                        .map(|source| source.schema.clone())
                        .unwrap_or_default(),
                );
                for expr in query_inputs(block) {
                    self.expression(expr, &block.subqueries);
                }
                self.scopes.truncate(length);
            }
            RelationalPlan::SetOp {
                left,
                right,
                order_by,
                limit,
                offset,
                subqueries,
                ..
            } => {
                self.query(left);
                self.query(right);
                self.complete &= query.analyzed_output.is_some();
                let length = self.scopes.len();
                self.scopes
                    .push(query.analyzed_output.clone().unwrap_or_default());
                for expr in order_by
                    .iter()
                    .map(|order| &order.expr)
                    .chain(limit.as_deref())
                    .chain(offset.as_deref())
                {
                    self.expression(expr, subqueries);
                }
                self.scopes.truncate(length);
            }
            RelationalPlan::Values { rows, subqueries } => {
                for expr in rows.iter().flatten() {
                    self.expression(expr, subqueries);
                }
            }
        }
    }

    pub fn source(
        &mut self,
        source: &SourcePlan,
        analysis: Option<&AnalyzedSource>,
        subqueries: &[QueryPlan],
        preceding: &[RowSchema],
        inherited_lateral: bool,
    ) {
        let length = self.scopes.len();
        if inherited_lateral
            || source.is_explicitly_lateral()
            || matches!(
                source,
                SourcePlan::Function { .. } | SourcePlan::FunctionGroup { .. }
            )
        {
            self.scopes.extend_from_slice(preceding);
        }
        match source {
            SourcePlan::Join {
                left,
                right,
                on,
                lateral,
                ..
            } => {
                if let Some(children) = analysis.and_then(|source| source.children.as_deref()) {
                    self.source(left, Some(&children.0), subqueries, preceding, false);
                    let mut right_preceding = preceding.to_vec();
                    right_preceding.push(children.0.schema.clone());
                    self.source(
                        right,
                        Some(&children.1),
                        subqueries,
                        &right_preceding,
                        *lateral,
                    );
                    if let Some(on) = on {
                        self.scopes.push(children.0.schema.clone());
                        self.scopes.push(children.1.schema.clone());
                        self.expression(on, subqueries);
                    }
                } else {
                    self.complete = false;
                }
            }
            SourcePlan::Subquery { body, .. }
            | SourcePlan::Table {
                executable_query: Some(body),
                ..
            } => self.query(body),
            SourcePlan::Values { rows, .. } => {
                for expr in rows.iter().flatten() {
                    self.expression(expr, subqueries);
                }
            }
            SourcePlan::Function { args, .. } => {
                for expr in args {
                    self.expression(expr, subqueries);
                }
            }
            SourcePlan::FunctionGroup { functions, .. } => {
                for expr in functions.iter().flat_map(|function| &function.args) {
                    self.expression(expr, subqueries);
                }
            }
            SourcePlan::RetainedRows(_) | SourcePlan::Table { .. } => {}
        }
        self.scopes.truncate(length);
    }
}

fn locally_resolved(expression: &ScalarExpr, schema: &RowSchema) -> bool {
    match expression {
        ScalarExpr::Column(name) => {
            schema.resolves_local_column(None, name) || schema.has_qualifier(name)
        }
        ScalarExpr::QualifiedColumn { qualifier, .. } => schema.has_qualifier(qualifier),
        ScalarExpr::QualifiedStar(qualifier) => schema.has_qualifier(qualifier),
        ScalarExpr::InternalColumn(column) => schema.internal_slot(*column).is_some(),
        ScalarExpr::Star | ScalarExpr::Position(_) => true,
        _ => false,
    }
}

/// SQL92 ORDER BY and DISTINCT ON names and positions observe an output already included in projection demand; expressions inside those clauses still resolve against the input namespace.
pub fn query_inputs(block: &crate::plan::QueryBlockPlan) -> impl Iterator<Item = &ScalarExpr> {
    block.query_expressions().filter(|expression| {
        let ordering = block
            .order_by
            .iter()
            .map(|order| &order.expr)
            .chain(&block.distinct_on)
            .any(|order| std::ptr::eq(order, *expression));
        !ordering || !ordering_uses_output(expression, &block.projections)
    })
}

/// SQL92 output names and ordinals bind to the selected output, while compound ordering expressions use the input namespace.
pub fn ordering_uses_output(
    expression: &ScalarExpr,
    projections: &[crate::plan::ProjectionPlan],
) -> bool {
    match expression {
        ScalarExpr::Position(_) | ScalarExpr::Literal(uqa_core::Value::Int(_)) => true,
        ScalarExpr::Column(name) => projections
            .iter()
            .any(|projection| crate::semantics::projection_label_at(projection) == name.as_str()),
        _ => false,
    }
}