no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::{output_label, EnclosingColumnName};
use crate::idents::{ident_key, unwrap_expr};
use sqlparser::ast::{Expr, Query, Select, SelectItem, SelectItemQualifiedWildcardKind, SetExpr};

mod ctes;
mod relation;

pub(crate) use ctes::{cte_single_outputs, OuterCteOutputs, SingleOutput};
use ctes::{query_scope, root_scope};
pub(super) use ctes::{Ctes, LayoutCache};
use relation::single_relation_label;

pub(super) fn scalar_subquery(query: &Query, parent: Option<&Ctes<'_>>) -> Option<(String, bool)> {
    let SingleOutput::Named(label) = single_output(query, parent)? else {
        return None;
    };
    Some((label, true))
}

fn single_output(query: &Query, parent: Option<&Ctes<'_>>) -> Option<SingleOutput> {
    let cache = LayoutCache::default();
    let scope = match parent {
        Some(parent) => query_scope(query, parent),
        None => root_scope(query, None, &cache),
    };
    single_body_output(&query.body, &scope)
}

pub(crate) fn query_projection_labels_with_ctes(
    query: &Query,
    external_ctes: Option<OuterCteOutputs<'_>>,
    external: Option<EnclosingColumnName<'_>>,
) -> Option<Vec<Option<String>>> {
    let cache = LayoutCache::default();
    let mut visible = root_scope(query, external_ctes, &cache);
    visible.external = external;
    projection_labels(&query.body, &visible)
}

pub(crate) fn select_projection_labels_with_ctes(
    select: &Select,
    external_ctes: Option<OuterCteOutputs<'_>>,
    external: Option<EnclosingColumnName<'_>>,
) -> Vec<Option<String>> {
    let cache = LayoutCache::default();
    let visible = Ctes::for_from(&select.from, external, external_ctes, &cache);
    select
        .projection
        .iter()
        .map(|item| select_item_label(item, &visible).flatten())
        .collect()
}

pub(crate) fn query_select_labels_with_ctes(
    query: &Query,
    select: &Select,
    external_ctes: Option<OuterCteOutputs<'_>>,
    external: Option<EnclosingColumnName<'_>>,
) -> Vec<Option<String>> {
    let cache = LayoutCache::default();
    let mut visible = root_scope(query, external_ctes, &cache);
    visible.relations = &select.from;
    visible.external = external;
    select
        .projection
        .iter()
        .map(|item| select_item_label(item, &visible).flatten())
        .collect()
}

fn select_item_label(item: &SelectItem, visible: &Ctes<'_>) -> Option<Option<String>> {
    let (expr, alias) = match item {
        SelectItem::ExprWithAlias { expr, alias } => (expr, Some(alias)),
        SelectItem::UnnamedExpr(expr) => (expr, None),
        _ => return None,
    };
    if matches!(
        unwrap_expr(expr),
        Expr::Wildcard(_) | Expr::QualifiedWildcard(_, _)
    ) {
        return None;
    }
    Some(
        alias
            .map(ident_key)
            .or_else(|| output_label(expr, Some(visible)).map(|(name, _)| name)),
    )
}

pub(super) fn projection_labels(body: &SetExpr, ctes: &Ctes<'_>) -> Option<Vec<Option<String>>> {
    match body {
        SetExpr::Query(query) => return projection_labels(&query.body, &query_scope(query, ctes)),
        SetExpr::SetOperation { left, .. } => return projection_labels(left, ctes),
        _ => {}
    }
    let select = body.as_select()?;
    let visible = Ctes {
        relations: &select.from,
        ..*ctes
    };
    select
        .projection
        .iter()
        .map(|item| select_item_label(item, &visible))
        .collect()
}

fn single_body_output(body: &SetExpr, ctes: &Ctes<'_>) -> Option<SingleOutput> {
    match body {
        SetExpr::Query(query) => return single_output(query, Some(ctes)),
        SetExpr::SetOperation { left, .. } => return single_body_output(left, ctes),
        _ => {}
    }
    if let SetExpr::Values(values) = body {
        return values
            .rows
            .first()
            .is_some_and(|row| row.len() == 1)
            .then(|| SingleOutput::Named("column1".to_owned()));
    }
    let select = body.as_select()?;
    let visible = Ctes {
        relations: &select.from,
        ..*ctes
    };
    match select.projection.as_slice() {
        [SelectItem::ExprWithAlias { expr, .. } | SelectItem::UnnamedExpr(expr)]
            if matches!(
                unwrap_expr(expr),
                Expr::Wildcard(_) | Expr::QualifiedWildcard(_, _)
            ) =>
        {
            let qualifier = match unwrap_expr(expr) {
                Expr::QualifiedWildcard(name, _) => Some(name),
                _ => None,
            };
            single_relation_label(select, qualifier, &visible)
        }
        [SelectItem::ExprWithAlias { alias, .. }] => Some(SingleOutput::Named(ident_key(alias))),
        [SelectItem::UnnamedExpr(expr)] => Some(
            output_label(expr, Some(&visible))
                .map_or(SingleOutput::Unnamed, |(name, _)| SingleOutput::Named(name)),
        ),
        [SelectItem::Wildcard(options)] if *options == Default::default() => {
            single_relation_label(select, None, &visible)
        }
        [SelectItem::QualifiedWildcard(
            SelectItemQualifiedWildcardKind::ObjectName(name),
            options,
        )] if *options == Default::default() => single_relation_label(select, Some(name), &visible),
        _ => None,
    }
}

pub(crate) fn leftmost_output(mut body: &SetExpr) -> &SetExpr {
    loop {
        match body {
            SetExpr::Query(query) => body = &query.body,
            SetExpr::SetOperation { left, .. } => body = left,
            _ => return body,
        }
    }
}