no-mistakes-postgres-engine 0.109.131

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use no_mistakes_postgres_sql::idents::{ident_key, unwrap_expr};
use sqlparser::ast::{Expr, Ident, ObjectName, SelectItem, SelectItemQualifiedWildcardKind};
use std::collections::BTreeMap;

pub(super) fn map_columns(
    projection: &[SelectItem],
    written: &[String],
    qualifier: &str,
    source_name: &ObjectName,
    has_alias: bool,
) -> Option<Vec<String>> {
    let mut explicit: BTreeMap<String, Option<String>> = BTreeMap::new();
    let mut has_wildcard = false;
    for item in projection {
        match item {
            SelectItem::Wildcard(_) => has_wildcard = true,
            SelectItem::QualifiedWildcard(kind, _) => {
                if !wildcard_matches(kind, qualifier, source_name, has_alias) {
                    return None;
                }
                has_wildcard = true;
            }
            SelectItem::UnnamedExpr(expr) => {
                if let Some(column) = plain_column(expr, qualifier, source_name, has_alias) {
                    record_mapping(&mut explicit, column.clone(), Some(column));
                }
            }
            SelectItem::ExprWithAlias { expr, alias } => {
                let mapped = plain_column(expr, qualifier, source_name, has_alias);
                record_mapping(&mut explicit, ident_key(alias), mapped);
            }
            SelectItem::ExprWithAliases { .. } => return None,
        }
    }
    written
        .iter()
        .map(|column| match explicit.get(column) {
            Some(Some(base)) => Some(base.clone()),
            Some(None) => None,
            None if has_wildcard => Some(column.clone()),
            None => None,
        })
        .collect()
}

fn record_mapping(
    explicit: &mut BTreeMap<String, Option<String>>,
    output: String,
    mapped: Option<String>,
) {
    explicit
        .entry(output)
        .and_modify(|existing| *existing = None)
        .or_insert(mapped);
}

fn plain_column(
    expr: &Expr,
    qualifier: &str,
    source_name: &ObjectName,
    has_alias: bool,
) -> Option<String> {
    match unwrap_expr(expr) {
        Expr::Identifier(ident) => Some(ident_key(ident)),
        Expr::CompoundIdentifier(parts) => match parts.as_slice() {
            [owner, col] if ident_key(owner) == qualifier => Some(ident_key(col)),
            [schema, table, col] if !has_alias && matches_qualified(schema, table, source_name) => {
                Some(ident_key(col))
            }
            _ => None,
        },
        _ => None,
    }
}

fn wildcard_matches(
    kind: &SelectItemQualifiedWildcardKind,
    qualifier: &str,
    source_name: &ObjectName,
    has_alias: bool,
) -> bool {
    let SelectItemQualifiedWildcardKind::ObjectName(obj) = kind else {
        return false;
    };
    match obj.0.as_slice() {
        [single] => single
            .as_ident()
            .is_some_and(|id| ident_key(id) == qualifier),
        [schema, table] if !has_alias => schema
            .as_ident()
            .zip(table.as_ident())
            .is_some_and(|(s, t)| matches_qualified(s, t, source_name)),
        _ => false,
    }
}

fn matches_qualified(schema: &Ident, table: &Ident, source_name: &ObjectName) -> bool {
    let [src_schema, src_table] = source_name.0.as_slice() else {
        return false;
    };
    src_schema
        .as_ident()
        .is_some_and(|id| ident_key(id) == ident_key(schema))
        && src_table
            .as_ident()
            .is_some_and(|id| ident_key(id) == ident_key(table))
}