no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::idents::{ident_key, unwrap_expr};
use sqlparser::ast::{
    ArrayElemTypeDef, DataType, ExactNumberInfo, Expr, Function, FunctionArguments, ObjectName,
    Query, Select, SelectItem, SelectItemQualifiedWildcardKind, SetExpr, TableFactor,
    TableWithJoins, TimezoneInfo,
};

pub(super) fn scalar_subquery(query: &Query) -> Option<(String, bool)> {
    let mut body = query.body.as_ref();
    loop {
        match body {
            SetExpr::Query(query) => body = query.body.as_ref(),
            SetExpr::SetOperation { left, .. } => body = left,
            _ => break,
        }
    }
    if let SetExpr::Values(values) = body {
        return values
            .rows
            .first()
            .is_some_and(|row| row.len() == 1)
            .then(|| ("column1".to_owned(), true));
    }
    let select = body.as_select()?;
    match select.projection.as_slice() {
        [SelectItem::ExprWithAlias { alias, .. }] => Some((super::idents::ident_key(alias), true)),
        [SelectItem::UnnamedExpr(expr)] => output_label(expr).map(|(name, _)| (name, true)),
        [SelectItem::Wildcard(options)] if *options == Default::default() => {
            single_values_label(select, None).map(|name| (name, true))
        }
        [SelectItem::QualifiedWildcard(
            SelectItemQualifiedWildcardKind::ObjectName(name),
            options,
        )] if *options == Default::default() => {
            single_values_label(select, Some(name)).map(|name| (name, true))
        }
        _ => None,
    }
}

fn single_values_label(select: &Select, qualifier: Option<&ObjectName>) -> Option<String> {
    let [TableWithJoins { relation, joins }] = select.from.as_slice() else {
        return None;
    };
    let TableFactor::Derived {
        subquery, alias, ..
    } = relation
    else {
        return None;
    };
    let SetExpr::Values(values) = subquery.body.as_ref() else {
        return None;
    };
    if !joins.is_empty() || values.rows.first()?.len() != 1 {
        return None;
    }
    if let Some(qualifier) = qualifier {
        let [part] = qualifier.0.as_slice() else {
            return None;
        };
        if ident_key(part.as_ident()?) != ident_key(&alias.as_ref()?.name) {
            return None;
        }
    }
    Some(
        alias
            .as_ref()
            .and_then(|alias| alias.columns.first())
            .map_or_else(
                || "column1".to_owned(),
                |column| super::idents::ident_key(&column.name),
            ),
    )
}

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::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",
        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::Bytea => "bytea",
        _ => return None,
    };
    Some(name.to_owned())
}

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

fn output_label(expr: &Expr) -> Option<(String, bool)> {
    match unwrap_expr(expr) {
        Expr::Cast {
            expr, data_type, ..
        } => output_label(expr)
            .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::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::Case { else_result, .. } => {
            let Some(fallback) = else_result.as_deref() else {
                return Some(("case".into(), false));
            };
            let (name, strong) = output_label(fallback)?;
            Some(if strong {
                (name, true)
            } else {
                ("case".into(), false)
            })
        }
        Expr::Value(_)
        | Expr::BinaryOp { .. }
        | Expr::UnaryOp { .. }
        | 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),
        _ => None,
    }
}

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