no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::idents::ident_key;
use crate::types::{SqlMigrationDefinition, SqlMigrationDefinitionEvent as Event};
use sqlparser::ast::{
    AlterTypeOperation, AlterViewOperation, CreateFunction, DropBehavior, DropFunction, ObjectName,
    ObjectType, OnCommit, ReferentialAction, Statement,
};

mod alter_table;
mod barriers;
mod session;
mod signature;
pub(super) use barriers::Barriers;
use signature::function_identity;

pub(super) fn record(statement: &Statement, line: usize, out: &mut Vec<Event>) {
    if let Some(event) = session::record(statement) {
        out.push(event);
        return;
    }
    match statement {
        Statement::CreateIndex(index) => {
            let Some([schema, table]) = qualified_name(&index.table_name) else {
                return;
            };
            if temporary_schema(&schema) {
                return;
            }
            if let Some([name]) = index.name.as_ref().and_then(identifier_parts) {
                out.push(Event::Create {
                    definition: SqlMigrationDefinition {
                        name: vec![schema.clone(), name],
                        argument_types: None,
                    },
                    unqualified_index_table: (index.table_name.0.len() == 1).then(|| table.clone()),
                    index_owner: Some(alter_table::index_owner(index, [schema, table])),
                    line,
                });
            }
        }
        Statement::AlterTable(alter) => alter_table::record(alter, out),
        Statement::CreateTable(table) => {
            if let Some([schema, name]) = qualified_name(&table.name) {
                if table.temporary || temporary_schema(&schema) {
                    out.push(Event::TemporaryTable {
                        name,
                        on_commit_drop: table.on_commit == Some(OnCommit::Drop),
                    });
                } else {
                    alter_table::record_parents(table, [schema, name], out);
                }
            }
        }
        Statement::CreateFunction(function) if !function.temporary => {
            record_create_function(function, line, out);
        }
        Statement::DropFunction(drop) => record_drop_function(drop, out),
        Statement::Drop {
            object_type: ObjectType::Index,
            names,
            ..
        } => out.extend(names.iter().map(|name| {
            qualified_name(name).map_or(Event::Reset, |name| Event::DropIndex(name.into()))
        })),
        Statement::Drop {
            object_type: ObjectType::Table,
            names,
            cascade: false,
            ..
        } => {
            out.extend(names.iter().map(|name| {
                qualified_name(name).map_or(Event::Reset, |table| Event::DropTable {
                    table,
                    qualified: name.0.len() == 2,
                })
            }));
        }
        Statement::AlterFunction(_) => out.push(Event::ResetFunctions),
        Statement::AlterIndex { .. } => out.push(Event::ResetIndexes),
        Statement::DropExtension(drop)
            if drop.cascade_or_restrict == Some(ReferentialAction::Cascade) =>
        {
            out.push(Event::Reset);
        }
        Statement::DropDomain(drop) if drop.drop_behavior == Some(DropBehavior::Cascade) => {
            out.push(Event::Reset);
        }
        Statement::DropOperator(drop) if drop.drop_behavior == Some(DropBehavior::Cascade) => {
            out.push(Event::Reset);
        }
        Statement::DropOperatorClass(drop) if drop.drop_behavior == Some(DropBehavior::Cascade) => {
            out.push(Event::Reset);
        }
        Statement::DropOperatorFamily(drop)
            if drop.drop_behavior == Some(DropBehavior::Cascade) =>
        {
            out.push(Event::Reset);
        }
        Statement::AlterType(alter) if matches!(alter.operation, AlterTypeOperation::Rename(_)) => {
            out.push(Event::ResetDefinitions);
        }
        Statement::AlterView(alter)
            if matches!(
                alter.operation,
                AlterViewOperation::RenameTo { .. } | AlterViewOperation::SetSchema { .. }
            ) =>
        {
            out.push(Event::ResetDefinitions);
        }
        Statement::Drop {
            object_type: ObjectType::View | ObjectType::MaterializedView | ObjectType::Type,
            cascade: false,
            ..
        } => out.push(Event::ResetDefinitions),
        Statement::Drop {
            object_type:
                ObjectType::Schema
                | ObjectType::Table
                | ObjectType::MaterializedView
                | ObjectType::Type
                | ObjectType::View,
            ..
        }
        | Statement::AlterSchema(_)
        | Statement::Rollback { .. }
        | Statement::Execute { .. }
        | Statement::Call(_) => out.push(Event::Reset),
        _ => {}
    }
}

fn record_create_function(function: &CreateFunction, line: usize, out: &mut Vec<Event>) {
    let Some(definition) =
        function_identity(&function.name, function.args.as_deref().unwrap_or(&[]))
    else {
        return;
    };
    if !temporary_schema(&definition.name[0]) {
        out.push(Event::Create {
            definition,
            unqualified_index_table: None,
            index_owner: None,
            line,
        });
    }
}

fn record_drop_function(drop: &DropFunction, out: &mut Vec<Event>) {
    if drop.drop_behavior == Some(DropBehavior::Cascade) {
        out.push(Event::Reset);
        return;
    }
    for function in &drop.func_desc {
        if qualified_name(&function.name).is_some_and(|[schema, _]| temporary_schema(&schema)) {
            continue;
        }
        match &function.args {
            Some(args) => {
                out.push(function_identity(&function.name, args).map_or(Event::Reset, Event::Drop))
            }
            None => out.push(
                qualified_name(&function.name)
                    .map_or(Event::Reset, |name| Event::DropFunction(name.into())),
            ),
        }
    }
}

fn temporary_schema(schema: &str) -> bool {
    schema == "pg_temp"
        || schema.strip_prefix("pg_temp_").is_some_and(|suffix| {
            !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_digit())
        })
}

fn identifier_parts<const N: usize>(name: &ObjectName) -> Option<[String; N]> {
    name.0
        .iter()
        .map(|part| part.as_ident().map(ident_key))
        .collect::<Option<Vec<_>>>()?
        .try_into()
        .ok()
}

fn qualified_name(name: &ObjectName) -> Option<[String; 2]> {
    match name.0.len() {
        1 => identifier_parts(name).map(|[name]| ["public".into(), name]),
        2 => identifier_parts(name),
        _ => None,
    }
}

#[cfg(test)]
mod tests;