Skip to main content

no_mistakes_postgres_sql/
migration.rs

1use super::schema::relation_name;
2use super::types::SqlSchemaFileFacts;
3use sqlparser::ast::{ObjectName, ObjectType, Statement};
4mod constraints;
5mod definitions;
6mod dynamic;
7mod dynamic_merge;
8mod identifiers;
9mod indexes;
10mod locating;
11pub(super) use locating::qualified_relation;
12pub(crate) use locating::statement_keyword_position;
13mod predicate;
14mod recovery;
15mod statements;
16mod table_events;
17#[doc(hidden)]
18pub use recovery::recovery_failures;
19pub fn extract_migration_facts(sql: &str) -> SqlSchemaFileFacts {
20    let parsed = super::parse::parse_postgres_sql_with_function_sources(sql);
21    recovery::extract_located_migration_facts(sql, parsed, false)
22}
23
24pub(super) fn extract_migration_body_facts(sql: &str) -> SqlSchemaFileFacts {
25    let parsed = super::parse::parse_postgres_body_with_function_sources(sql);
26    recovery::extract_located_migration_facts(sql, parsed, true)
27}
28
29#[doc(hidden)]
30pub fn extract_from_parsed_with_failures(
31    sql: &str,
32    statements: &[Statement],
33    functions: &[super::SqlFunctionCallFact],
34    failures: &[super::types::SqlUnanalyzableStatement],
35    tokens: &[&[sqlparser::tokenizer::TokenWithSpan]],
36    statement_locations: Option<&[sqlparser::tokenizer::Location]>,
37) -> SqlSchemaFileFacts {
38    let mut facts = extract_parsed_migration_facts(
39        sql,
40        statements,
41        failures,
42        tokens,
43        statement_locations,
44        false,
45    );
46    facts.function_calls.extend_from_slice(functions);
47    facts
48}
49
50pub(crate) use statements::policy_facts_with_locations;
51#[doc(hidden)]
52pub use statements::{collect_query_complexity, SUPPORTED_KINDS, TRANSACTION_CONTROL_KINDS};
53
54fn extract_parsed_migration_facts(
55    sql: &str,
56    statements: &[Statement],
57    failures: &[super::types::SqlUnanalyzableStatement],
58    tokens: &[&[sqlparser::tokenizer::TokenWithSpan]],
59    statement_locations: Option<&[sqlparser::tokenizer::Location]>,
60    procedural_body: bool,
61) -> SqlSchemaFileFacts {
62    let mut facts = SqlSchemaFileFacts {
63        unanalyzable_statements: failures
64            .iter()
65            .filter(|failure| failure.schema_unanalyzable)
66            .cloned()
67            .collect(),
68        table_events_collected: true,
69        tables: statements
70            .iter()
71            .filter_map(|statement| match statement {
72                Statement::CreateTable(table) => Some(super::schema::table_metadata(table)),
73                _ => None,
74            })
75            .collect(),
76        ..Default::default()
77    };
78    let transactions = (!procedural_body && failures.is_empty()).then_some((
79        statements,
80        tokens,
81        statement_locations,
82    ));
83    let mut barriers = definitions::Barriers::new(statements::record_migration_policy(
84        sql,
85        &mut facts,
86        transactions,
87    ));
88    let mut identifier_locations = identifiers::Locations::new(sql);
89    facts
90        .declared_identifiers
91        .extend(identifier_locations.unparsed_declarations());
92    let mut table_positions = table_events::Positions::new(sql);
93    for (ordinal, statement) in statements.iter().enumerate() {
94        let tokens = tokens.get(ordinal).copied().unwrap_or_default();
95        let locations = locating::Locations::new(tokens);
96        facts
97            .declared_identifiers
98            .extend(identifiers::collect(&mut identifier_locations, statement));
99        let position = locations.statement_position(
100            statement,
101            statement_locations
102                .and_then(|locs| locs.get(ordinal))
103                .copied(),
104        );
105        let line = position.line.max(1) as usize;
106        statements::record(line, statement, tokens, procedural_body, &mut facts);
107        if !procedural_body {
108            barriers.record(statement, position, &mut facts.definition_events);
109        }
110        table_events::record(statement, &mut table_positions, &mut facts.table_events);
111        match statement {
112            Statement::CreateIndex(index) => {
113                facts
114                    .indexes
115                    .push(indexes::from_create_index(line, ordinal, index));
116            }
117            Statement::Drop {
118                object_type: ObjectType::Index,
119                names,
120                ..
121            } => {
122                facts
123                    .dropped_indexes
124                    .extend(indexes::from_drop_index(line, ordinal, names));
125            }
126            Statement::Drop {
127                object_type: ObjectType::Table,
128                names,
129                ..
130            } => {
131                facts
132                    .dropped_tables
133                    .extend(indexes::from_drop_table(line, ordinal, names));
134            }
135            Statement::CreateTable(table) => {
136                let table_name = relation_name(&table.name);
137                facts.indexes.extend(indexes::covering_from_table(
138                    &qualified_relation(&table.name),
139                    table,
140                ));
141                constraints::collect_create_table_fks(
142                    line,
143                    &table_name,
144                    table,
145                    &mut facts.foreign_keys,
146                );
147            }
148            Statement::AlterTable(alter) => {
149                constraints::collect_alter_table(line, alter, &mut facts)
150            }
151            _ => {}
152        }
153    }
154    if !procedural_body {
155        barriers.finish(&mut facts.definition_events);
156    }
157    dynamic_merge::append(sql, &mut facts);
158    if let Some(ddl) = &mut facts.ddl_projection {
159        ddl.unanalyzable_statements.sort_by_key(|item| item.line);
160        table_positions.apply_transaction_projection(&mut ddl.table_events);
161    }
162    facts.unanalyzable_statements.sort_by_key(|item| item.line);
163    table_positions.apply_transaction_projection(&mut facts.table_events);
164    facts
165}
166
167pub(super) fn relation(name: &ObjectName) -> String {
168    relation_name(name)
169}
170
171#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
172mod tests;