no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::{cte_delete, helpers, simple_select_table, PlaceholderPositions, StatementLockCheck};
use crate::erased_visit::VisitErased;
use crate::idents::{ident_key, unwrap_expr};
use sqlparser::ast::{Expr, Ident, ObjectName, Query, SelectItem, SetExpr, TableFactor, Visitor};
use std::ops::ControlFlow;

pub(super) fn redundancy(
    query: &Query,
    relation: &str,
    column: String,
    only: bool,
) -> StatementLockCheck {
    StatementLockCheck::RedundantSubquery {
        relation: relation.to_owned(),
        requires_non_null: !explicit_non_null(query, &column),
        column,
        only,
    }
}

pub(super) fn explicit_non_null(query: &Query, column: &str) -> bool {
    let Some(table) = simple_select_table(query) else {
        return false;
    };
    matches!(query.body.as_ref(), SetExpr::Select(select)
    if select.selection.as_ref().is_some_and(|selection|
        cte_delete::proves_non_null(selection, &|expr| {
            local_column(expr, &table.relation, None).as_deref() == Some(column)
        })))
}

pub(super) fn uncorrelated(query: &Query, table: &TableFactor, outer: Option<&str>) -> bool {
    helpers::qualifier(table).is_some_and(|name| {
        let outer = outer.filter(|outer| *outer != name);
        query
            .visit_erased(&mut Local {
                query,
                name: &name,
                outer,
                qualified: unaliased_name(table),
            })
            .is_continue()
    })
}

struct Local<'a> {
    query: &'a Query,
    name: &'a str,
    outer: Option<&'a str>,
    qualified: Option<&'a ObjectName>,
}

impl Visitor for Local<'_> {
    type Break = ();

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        if std::ptr::eq(query, self.query) {
            ControlFlow::Continue(())
        } else {
            ControlFlow::Break(())
        }
    }

    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
        match expr {
            Expr::CompoundIdentifier(parts)
                if !matches!(parts.as_slice(), [table, _] if ident_key(table) == self.name)
                    && !schema_qualified(parts, self.qualified) =>
            {
                ControlFlow::Break(())
            }
            Expr::Identifier(name) if self.outer.is_some_and(|outer| ident_key(name) == outer) => {
                ControlFlow::Break(())
            }
            _ => ControlFlow::Continue(()),
        }
    }
}

pub(super) fn projected_key(
    query: &Query,
    key: &str,
    positions: PlaceholderPositions<'_>,
) -> Option<String> {
    let SetExpr::Select(select) = query.body.as_ref() else {
        return None;
    };
    let (expr, alias) = match select.projection.as_slice() {
        [SelectItem::UnnamedExpr(expr)] => (expr, None),
        [SelectItem::ExprWithAlias { expr, alias }] => (expr, Some(alias)),
        _ => return None,
    };
    let column = local_column(expr, &simple_select_table(query)?.relation, positions)?;
    (column == key).then(|| alias.map_or(column, ident_key))
}

pub(super) fn local_column(
    expr: &Expr,
    table: &TableFactor,
    positions: PlaceholderPositions<'_>,
) -> Option<String> {
    let qualifier = helpers::qualifier(table);
    helpers::column(expr, qualifier.as_deref(), positions).or_else(|| {
        let Expr::CompoundIdentifier(parts) = unwrap_expr(expr) else {
            return None;
        };
        (schema_qualified(parts, unaliased_name(table))
            && !parts.iter().any(|part| helpers::generated(part, positions)))
        .then(|| ident_key(&parts[2]))
    })
}

fn unaliased_name(table: &TableFactor) -> Option<&ObjectName> {
    match table {
        TableFactor::Table {
            name, alias: None, ..
        } => Some(name),
        _ => None,
    }
}

fn schema_qualified(parts: &[Ident], name: Option<&ObjectName>) -> bool {
    let ([schema, table, _], Some(name)) = (parts, name) else {
        return false;
    };
    let [local_schema, local_table] = name.0.as_slice() else {
        return false;
    };
    local_schema
        .as_ident()
        .is_some_and(|ident| ident_key(ident) == ident_key(schema))
        && local_table
            .as_ident()
            .is_some_and(|ident| ident_key(ident) == ident_key(table))
}

pub(super) fn cte_projection<'a>(
    query: &Query,
    ctes: &std::collections::BTreeMap<String, super::VisibleCte<'a>>,
    positions: PlaceholderPositions<'_>,
) -> Option<super::VisibleCte<'a>> {
    if query.with.is_some() || !query.locks.is_empty() {
        return None;
    }
    let table = simple_select_table(query)?;
    let relation = helpers::access(&table.relation, None, positions).relation?;
    ctes.get(&relation).copied()
}