no-mistakes-postgres-sql 0.109.130

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::{lateral::RowDependencies, nested::JoinOutput};
use crate::fx::{FxHashMap, FxHashSet};
use crate::statement_facts::{SqlAliasedViewPeer, SqlBareViewRowScope, SqlViewKeyCondition};
use sqlparser::ast::{Expr, TableFactor};
use std::sync::Arc;

#[derive(Default)]
pub(in super::super) struct Scope {
    pub(in super::super) unqualified_columns: std::collections::BTreeSet<String>,
    pub(in super::super) candidates: Vec<usize>,
    pub(in super::super) join_outputs: FxHashMap<String, JoinOutput>,
    pub(in super::super) nested_joins: FxHashMap<*const TableFactor, Scope>,
    pub(in super::super) predicates: FxHashMap<*const Expr, Scope>,
    pub(in super::super) preceding: FxHashMap<*const TableFactor, Scope>,
    pub(super) lateral_outputs: FxHashMap<String, Arc<super::lateral::LateralDependencies>>,
    pub(in super::super) using_aliases:
        FxHashMap<String, std::sync::Arc<super::using::UsingSources>>,
    pub(in super::super) merged_using: super::using::UsingSources,
    pub(super) merged_value_dependencies: FxHashMap<String, super::lateral::RowDependencies>,
    pub(in super::super) derived_columns: FxHashMap<String, Vec<String>>,
    pub(super) explicit_columns: FxHashMap<String, Vec<String>>,
    pub(super) possible_scalar_functions: FxHashSet<String>,
    pub(in super::super) physical_inputs: Vec<PhysicalInput>,
    pub(in super::super) bindings: FxHashMap<String, Option<usize>>,
    pub(in super::super) distinct_names: FxHashSet<*const Expr>,
    pub(in super::super) group_names: FxHashSet<*const Expr>,
    pub(in super::super) wildcard_relations: SqlBareViewRowScope,
    pub(in super::super) output_aliases: FxHashSet<String>,
    pub(in super::super) inputs: usize,
    pub(in super::super) known_inputs: usize,
    pub(in super::super) known_columns: FxHashSet<String>,
    pub(super) row_selecting_join: bool,
    pub(super) merged_column_layout: bool,
    pub(super) null_extended: FxHashSet<String>,
    pub(super) null_matches: FxHashMap<String, RowDependencies>,
    pub(super) unbound_lateral: RowDependencies,
    pub(super) opaque_lateral_columns: RowDependencies,
    pub(super) unbound_columns: FxHashMap<String, RowDependencies>,
}

impl Scope {
    pub(super) fn visible_single_column(
        &self,
        ancestors: &[Self],
        outer: &[Self],
        qualifier: &str,
    ) -> Option<String> {
        let scope = std::iter::once(self)
            .chain(ancestors.iter().rev())
            .chain(outer.iter().rev())
            .find(|scope| scope.bindings.contains_key(qualifier))?;
        let [column] = scope.derived_columns.get(qualifier)?.as_slice() else {
            return None;
        };
        Some(column.clone())
    }

    pub(super) fn visible_physical_inputs(&self) -> impl Iterator<Item = &PhysicalInput> {
        self.physical_inputs.iter().chain(
            self.join_outputs
                .values()
                .filter(|output| !output.renamed)
                .flat_map(|output| &output.physical_inputs),
        )
    }

    pub(super) fn values_width(&self) -> crate::statement_facts::SqlViewValuesWidth {
        use crate::statement_facts::SqlViewValuesWidth;
        if self.merged_column_layout {
            return SqlViewValuesWidth {
                known: self.known_columns.len(),
                unknown: true,
                ..SqlViewValuesWidth::default()
            };
        }
        let mut width = SqlViewValuesWidth {
            known: self.derived_columns.values().map(Vec::len).sum(),
            relations: self
                .physical_inputs
                .iter()
                .map(|input| input.relation.clone())
                .collect(),
            unknown: self.known_inputs > self.derived_columns.len()
                || self.inputs
                    > self.known_inputs + self.physical_inputs.len() + self.join_outputs.len(),
        };
        for output in self.join_outputs.values() {
            width.known += output.values_width.known;
            width
                .relations
                .extend(output.values_width.relations.iter().cloned());
            width.unknown |= output.values_width.unknown;
        }
        width.relations.sort_unstable();
        width
    }
}

#[derive(Clone)]
pub(in super::super) struct PhysicalInput {
    pub(in super::super) qualifier: String,
    pub(in super::super) candidate: Option<usize>,
    pub(in super::super) relation: String,
    pub(in super::super) column_aliases: Vec<String>,
    pub(in super::super) unqualified: bool,
    pub(in super::super) bare_system_columns: bool,
}

impl PhysicalInput {
    pub(in super::super) fn matches_qualifier(&self, key: &str) -> bool {
        self.qualifier == key
            || self.relation == key && self.qualifier == crate::idents::relation_suffix_key(key)
    }

    pub(super) fn column_condition(&self, column: &str, present: bool) -> SqlViewKeyCondition {
        SqlViewKeyCondition::Column {
            peer: SqlAliasedViewPeer {
                relation: self.relation.clone(),
                column_aliases: self.column_aliases.clone(),
            },
            column: column.to_owned(),
            present,
        }
    }

    pub(in super::super) fn record_peer(&self, scope: &mut SqlBareViewRowScope) {
        if self.column_aliases.is_empty() {
            scope.peers.push(self.relation.clone());
        } else {
            scope.aliased_peers.push(SqlAliasedViewPeer {
                relation: self.relation.clone(),
                column_aliases: self.column_aliases.clone(),
            });
        }
    }
}

impl Scope {
    pub(super) fn snapshot(&self) -> Self {
        Self {
            candidates: self.candidates.clone(),
            join_outputs: self.join_outputs.clone(),
            using_aliases: self.using_aliases.clone(),
            merged_using: self.merged_using.clone(),
            merged_value_dependencies: self.merged_value_dependencies.clone(),
            lateral_outputs: self.lateral_outputs.clone(),
            derived_columns: self.derived_columns.clone(),
            explicit_columns: self.explicit_columns.clone(),
            possible_scalar_functions: self.possible_scalar_functions.clone(),
            physical_inputs: self.physical_inputs.clone(),
            bindings: self.bindings.clone(),
            inputs: self.inputs,
            known_inputs: self.known_inputs,
            known_columns: self.known_columns.clone(),
            row_selecting_join: self.row_selecting_join,
            merged_column_layout: self.merged_column_layout,
            null_extended: self.null_extended.clone(),
            null_matches: self.null_matches.clone(),
            unbound_lateral: self.unbound_lateral.clone(),
            opaque_lateral_columns: self.opaque_lateral_columns.clone(),
            unbound_columns: self.unbound_columns.clone(),
            ..Self::default()
        }
    }

    pub(super) fn merge(&mut self, other: Self) {
        self.candidates.extend(other.candidates);
        self.join_outputs.extend(other.join_outputs);
        self.nested_joins.extend(other.nested_joins);
        self.preceding.extend(other.preceding);
        self.predicates.extend(other.predicates);
        self.using_aliases.extend(other.using_aliases);
        super::using::append_outputs(&mut self.merged_using, other.merged_using);
        self.merged_value_dependencies
            .extend(other.merged_value_dependencies);
        self.lateral_outputs.extend(other.lateral_outputs);
        self.derived_columns.extend(other.derived_columns);
        self.explicit_columns.extend(other.explicit_columns);
        self.possible_scalar_functions
            .extend(other.possible_scalar_functions);
        self.physical_inputs.extend(other.physical_inputs);
        self.bindings.extend(other.bindings);
        self.inputs += other.inputs;
        self.known_inputs += other.known_inputs;
        self.known_columns.extend(other.known_columns);
        self.row_selecting_join |= other.row_selecting_join;
        self.merged_column_layout |= other.merged_column_layout;
        self.null_extended.extend(other.null_extended);
        self.null_matches.extend(other.null_matches);
        self.unbound_lateral.extend(other.unbound_lateral);
        self.opaque_lateral_columns
            .extend(other.opaque_lateral_columns);
        for (column, dependencies) in other.unbound_columns {
            self.unbound_columns
                .entry(column)
                .or_default()
                .extend(dependencies);
        }
    }
}