no-mistakes-postgres-sql 0.109.125

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::SqlValueForm;
use crate::idents::{ident_key, unwrap_expr};
use sqlparser::ast::{
    Expr, Function, FunctionArg, FunctionArgExpr, FunctionArguments, Ident, ObjectNamePart,
    UnaryOperator, Value, ValueWithSpan,
};
pub(crate) type PlaceholderPositions<'a> = Option<&'a [(u32, u32)]>;

/// Whether this identifier is a bind for the current source mode.
///
/// Standalone SQL has only the legacy spelling heuristic. Embedded SQL has exact recovered
/// positions, so a marker-shaped user identifier is a column unless its source location was
/// generated. Quoted identifiers are never interpolation binds.
pub(crate) fn is_placeholder_ident_at(ident: &Ident, positions: PlaceholderPositions<'_>) -> bool {
    if let Some(positions) = positions {
        return ident.quote_style.is_none()
            && is_placeholder_ident(&ident.value)
            && positions.contains(&(ident.span.start.line as u32, ident.span.start.column as u32));
    }
    is_placeholder_ident(&ident.value)
}

#[rustfmt::skip]
const VOLATILE: &[&str] = &[
    "gen_random_uuid", "random", "nextval", "uuidv7", "uuid_generate_v1",
    "uuid_generate_v1mc", "uuid_generate_v4", "now", "clock_timestamp",
    "statement_timestamp", "transaction_timestamp", "current_timestamp",
    "current_date", "current_time", "localtime", "localtimestamp",
];

pub(super) fn from_expr_at(expr: &Expr, positions: PlaceholderPositions<'_>) -> SqlValueForm {
    match unwrap_expr(expr) {
        Expr::Value(value) => from_value(value),
        Expr::Identifier(ident) => ident_form(ident, positions),
        Expr::CompoundIdentifier(parts) => compound_form(parts),
        Expr::Function(function) => from_function(function, positions),
        Expr::UnaryOp {
            op: UnaryOperator::Plus | UnaryOperator::Minus,
            expr,
        } => signed_literal(expr, positions),
        inner if super::value_form::is_subquery_value(inner) => SqlValueForm::Subquery,
        _ => SqlValueForm::Other,
    }
}

fn from_value(value: &ValueWithSpan) -> SqlValueForm {
    match &value.value {
        Value::Null => SqlValueForm::Null,
        Value::Placeholder(_) => SqlValueForm::Placeholder,
        Value::SingleQuotedString(text)
        | Value::EscapedStringLiteral(text)
        | Value::UnicodeStringLiteral(text)
        | Value::NationalStringLiteral(text)
            if is_relative_datetime(text) =>
        {
            SqlValueForm::Other
        }
        Value::DollarQuotedString(quoted) if is_relative_datetime(&quoted.value) => {
            SqlValueForm::Other
        }
        _ => SqlValueForm::Literal,
    }
}

fn ident_form(ident: &Ident, positions: PlaceholderPositions<'_>) -> SqlValueForm {
    if ident.quote_style.is_some() {
        return SqlValueForm::SelfRef {
            column: ident.value.clone(),
        };
    }
    if is_placeholder_ident_at(ident, positions) {
        return SqlValueForm::Placeholder;
    }
    if is_volatile_name(&ident.value) {
        return SqlValueForm::Volatile {
            name: ident.value.to_ascii_lowercase(),
        };
    }
    if ident.value.eq_ignore_ascii_case("default") {
        return SqlValueForm::Other;
    }
    SqlValueForm::SelfRef {
        column: ident.value.clone(),
    }
}

fn signed_literal(expr: &Expr, positions: PlaceholderPositions<'_>) -> SqlValueForm {
    match from_expr_at(expr, positions) {
        SqlValueForm::Literal | SqlValueForm::Null => SqlValueForm::Literal,
        form => form,
    }
}

#[rustfmt::skip]
const RELATIVE_DATETIME: &[&str] = &["now", "today", "tomorrow", "yesterday"];

fn is_relative_datetime(text: &str) -> bool {
    RELATIVE_DATETIME.contains(&text.trim().to_ascii_lowercase().as_str())
}

fn compound_form(parts: &[sqlparser::ast::Ident]) -> SqlValueForm {
    if parts.len() >= 2 && ident_key(&parts[0]) == "excluded" {
        return SqlValueForm::Excluded {
            column: ident_key(&parts[parts.len() - 1]),
        };
    }
    SqlValueForm::SelfRef {
        column: parts[parts.len() - 1].value.clone(),
    }
}

fn from_function(function: &Function, positions: PlaceholderPositions<'_>) -> SqlValueForm {
    let Some(ident) = builtin_function_ident(function) else {
        return SqlValueForm::Other;
    };
    let name = ident.value.to_ascii_lowercase();
    if is_volatile_name(&name) {
        return SqlValueForm::Volatile { name };
    }
    let args = function_arg_exprs(function)
        .into_iter()
        .map(|expr| from_expr_at(expr, positions))
        .collect();
    match name.as_str() {
        "coalesce" => SqlValueForm::Coalesce { args },
        "greatest" => SqlValueForm::Greatest { args },
        "least" => SqlValueForm::Least { args },
        _ => SqlValueForm::Other,
    }
}

fn builtin_function_ident(function: &Function) -> Option<&Ident> {
    match function.name.0.as_slice() {
        [ObjectNamePart::Identifier(ident)] if ident.quote_style.is_none() => Some(ident),
        _ => None,
    }
}

fn function_arg_exprs(function: &Function) -> Vec<&Expr> {
    let FunctionArguments::List(list) = &function.args else {
        return Vec::new();
    };
    list.args.iter().filter_map(named_or_unnamed_expr).collect()
}

fn named_or_unnamed_expr(arg: &FunctionArg) -> Option<&Expr> {
    match arg {
        FunctionArg::Unnamed(FunctionArgExpr::Expr(expr))
        | FunctionArg::Named {
            arg: FunctionArgExpr::Expr(expr),
            ..
        }
        | FunctionArg::ExprNamed {
            arg: FunctionArgExpr::Expr(expr),
            ..
        } => Some(expr),
        _ => None,
    }
}

pub(super) fn self_ref_column_at(
    expr: &Expr,
    positions: PlaceholderPositions<'_>,
) -> Option<String> {
    match from_expr_at(expr, positions) {
        SqlValueForm::SelfRef { column } => Some(column),
        _ => None,
    }
}

pub(super) fn excluded_column_at(
    expr: &Expr,
    positions: PlaceholderPositions<'_>,
) -> Option<String> {
    match from_expr_at(expr, positions) {
        SqlValueForm::Excluded { column } => Some(column),
        _ => None,
    }
}

pub(super) fn is_placeholder_ident(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower.starts_with('$') || lower.starts_with("sql_placeholder_")
}

fn is_volatile_name(name: &str) -> bool {
    VOLATILE.iter().any(|item| name.eq_ignore_ascii_case(item))
}

pub fn form_is_stable(form: &SqlValueForm) -> bool {
    match form {
        SqlValueForm::Literal | SqlValueForm::Null | SqlValueForm::Placeholder => true,
        SqlValueForm::Coalesce { args }
        | SqlValueForm::Greatest { args }
        | SqlValueForm::Least { args } => args.iter().all(form_is_stable),
        _ => false,
    }
}
mod conflict_assignment;
pub(super) use conflict_assignment::{column_name, from_assignment_at, overwritten_columns};