no-mistakes-postgres-sql 0.109.130

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::idents::{ident_key, unwrap_expr};
use sqlparser::ast::{
    AccessExpr, ArrayElemTypeDef, DataType, ExactNumberInfo, Expr, Function, FunctionArguments,
    TableWithJoins, TimezoneInfo,
};
mod syntax;

mod scalar;
pub(crate) use scalar::{
    cte_single_outputs, leftmost_output, query_projection_labels_with_ctes,
    query_select_labels_with_ctes, select_projection_labels_with_ctes, OuterCteOutputs,
    SingleOutput,
};
use scalar::{scalar_subquery, Ctes, LayoutCache};

pub(crate) type EnclosingColumnName<'a> = &'a dyn Fn(&str) -> Option<String>;

pub(super) fn function_label(function: &Function) -> Option<String> {
    let name = super::idents::object_name_ident(&function.name)?;
    // sqlparser represents a parenthesized single-row VALUES expression as a call.
    if function.name.0.len() == 1
        && name.quote_style.is_none()
        && name.value.eq_ignore_ascii_case("values")
        && matches!(&function.args, FunctionArguments::List(list) if list.args.len() == 1)
    {
        return Some("column1".to_owned());
    }
    Some(super::idents::ident_key(name))
}

pub(super) fn type_label(data_type: &DataType) -> Option<String> {
    let name = match data_type {
        DataType::Custom(name, _) => {
            return super::idents::object_name_ident(name).map(super::idents::ident_key)
        }
        DataType::Array(
            ArrayElemTypeDef::SquareBracket(inner, _) | ArrayElemTypeDef::Qualified(inner, _),
        ) => return type_label(inner),
        DataType::Bool | DataType::Boolean => "bool",
        DataType::Char(_) | DataType::Character(_) => "bpchar",
        DataType::Varchar(_) | DataType::CharVarying(_) | DataType::CharacterVarying(_) => {
            "varchar"
        }
        DataType::Timestamp(_, TimezoneInfo::WithTimeZone | TimezoneInfo::Tz) => "timestamptz",
        DataType::Timestamp(..) => "timestamp",
        DataType::Time(_, TimezoneInfo::WithTimeZone | TimezoneInfo::Tz) => "timetz",
        DataType::Time(..) => "time",
        DataType::Interval { .. } => "interval",
        DataType::Text => "text",
        DataType::Date => "date",
        DataType::Uuid => "uuid",
        DataType::JSON => "json",
        DataType::JSONB => "jsonb",
        DataType::Regclass => "regclass",
        DataType::TsVector => "tsvector",
        DataType::TsQuery => "tsquery",
        DataType::GeometricType(kind) => return Some(kind.to_string()),
        DataType::Bytea => "bytea",
        DataType::Bit(_) => "bit",
        DataType::BitVarying(_) | DataType::VarBit(_) => "varbit",
        other => numeric_type_label(other)?,
    };
    Some(name.to_owned())
}

fn numeric_type_label(data_type: &DataType) -> Option<&'static str> {
    Some(match data_type {
        DataType::SmallInt(_) | DataType::Int2(_) => "int2",
        DataType::Int(_) | DataType::Integer(_) | DataType::Int4(_) => "int4",
        DataType::BigInt(_) | DataType::Int8(_) => "int8",
        DataType::Numeric(_) | DataType::Decimal(_) | DataType::Dec(_) => "numeric",
        DataType::Float(ExactNumberInfo::Precision(bits)) if *bits <= 24 => "float4",
        DataType::Real | DataType::Float4 => "float4",
        DataType::DoublePrecision | DataType::Float8 | DataType::Float(_) => "float8",
        _ => return None,
    })
}

/// The output name PostgreSQL gives an unaliased select item.
pub(crate) fn implicit_output_label(expr: &Expr) -> Option<String> {
    output_label(expr, None).map(|(name, _)| name)
}

pub(crate) fn implicit_label_in_from(expr: &Expr, from: &[TableWithJoins]) -> Option<String> {
    implicit_label_in_visible_from(expr, from, None)
}

pub(crate) fn implicit_label_in_visible_from(
    expr: &Expr,
    from: &[TableWithJoins],
    external: Option<EnclosingColumnName<'_>>,
) -> Option<String> {
    let cache = LayoutCache::default();
    output_label(expr, Some(&Ctes::for_from(from, external, None, &cache))).map(|(name, _)| name)
}

fn output_label(expr: &Expr, ctes: Option<&Ctes<'_>>) -> Option<(String, bool)> {
    match unwrap_expr(expr) {
        Expr::Cast {
            expr, data_type, ..
        } => output_label(expr, ctes)
            .filter(|(_, strong)| *strong)
            .or_else(|| type_label(data_type).map(|name| (name, false))),
        Expr::TypedString(typed) => type_label(&typed.data_type).map(|name| (name, false)),
        Expr::Interval(_) => Some(("interval".into(), false)),
        Expr::Function(function) => function_label(function).map(|name| (name, true)),
        Expr::Identifier(ident) => Some((ident_key(ident), true)),
        Expr::CompoundIdentifier(parts) => parts.last().map(|ident| (ident_key(ident), true)),
        Expr::CompoundFieldAccess { root, access_chain } => access_chain
            .iter()
            .rev()
            .find_map(|access| match access {
                AccessExpr::Dot(Expr::Identifier(name)) => Some((ident_key(name), true)),
                _ => None,
            })
            .or_else(|| output_label(root, ctes)),
        Expr::Collate { expr, .. } => output_label(expr, ctes),
        Expr::IsNormalized { negated: false, .. } => Some(("is_normalized".into(), true)),
        Expr::Case { else_result, .. } => {
            let Some(fallback) = else_result.as_deref() else {
                return Some(("case".into(), false));
            };
            let (name, strong) = output_label(fallback, ctes)?;
            Some(if strong {
                (name, true)
            } else {
                ("case".into(), false)
            })
        }
        Expr::Value(_)
        | Expr::BinaryOp { .. }
        | Expr::UnaryOp { .. }
        | Expr::Between { .. }
        | Expr::In { .. }
        | Expr::Like { .. }
        | Expr::ILike { .. }
        | Expr::SimilarTo { .. }
        | Expr::AnyOp { .. }
        | Expr::AllOp { .. }
        | Expr::IsNull(_)
        | Expr::IsNotNull(_)
        | Expr::IsTrue(_)
        | Expr::IsNotTrue(_)
        | Expr::IsFalse(_)
        | Expr::IsNotFalse(_)
        | Expr::IsUnknown(_)
        | Expr::IsNotUnknown(_)
        | Expr::IsDistinctFrom(..)
        | Expr::IsNotDistinctFrom(..)
        | Expr::IsJson { .. }
        | Expr::IsNormalized { .. }
        | Expr::Exists { negated: true, .. } => Some(("?column?".into(), false)),
        Expr::Array(_) => Some(("array".into(), true)),
        Expr::Tuple(_) => Some(("row".into(), true)),
        Expr::Exists { .. } => Some(("exists".into(), true)),
        Expr::Subquery(query) => scalar_subquery(query, ctes),
        expr => syntax::label(expr).map(|name| (name.into(), true)),
    }
}

#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
mod tests;