use crate::types::SqlSchemaFileFacts;
use sqlparser::{
ast::Statement,
tokenizer::{Location, Span, TokenWithSpan},
};
enum Transaction {
Outside,
Started(Location),
OneStatement(Location),
Other,
}
type Sources<'a> = (
&'a [Statement],
&'a [&'a [TokenWithSpan]],
Option<&'a [Location]>,
);
pub(in crate::migration) fn record_migration_policy(
sql: &str,
facts: &mut SqlSchemaFileFacts,
sources: Option<Sources<'_>>,
) -> Vec<Span> {
let do_spans = super::record_new(sql, facts);
if let Some((statements, tokens, locations)) = sources {
record_transactions(facts, statements, tokens, locations, &do_spans);
}
do_spans
}
fn record_transactions(
facts: &mut SqlSchemaFileFacts,
statements: &[Statement],
tokens: &[&[TokenWithSpan]],
locations: Option<&[Location]>,
do_spans: &[Span],
) {
use Transaction::{OneStatement, Other, Outside, Started};
let statement_position = |index: usize, statement: &Statement| {
crate::migration::locating::Locations::new(tokens.get(index).copied().unwrap_or_default())
.statement_position(
statement,
locations
.and_then(|positions| positions.get(index))
.copied(),
)
};
let mut state = Outside;
for (index, statement) in statements.iter().enumerate() {
state = match (state, statement) {
(
Outside,
Statement::StartTransaction {
modes,
modifier: None,
statements,
exception: None,
has_end_keyword: false,
..
},
) if modes.is_empty() && statements.is_empty() => {
Started(statement_position(index, statement))
}
(
Started(start),
Statement::Query(_)
| Statement::Insert(_)
| Statement::Update(_)
| Statement::Delete(_),
) => OneStatement(start),
(
OneStatement(start),
Statement::Commit {
chain: false,
modifier: None,
..
},
) => {
let commit = statement_position(index, statement);
let next_do = do_spans.get(do_spans.partition_point(|span| span.start < start));
if next_do.is_none_or(|span| span.start > commit) {
facts
.single_statement_transactions
.push(start.line.max(1) as usize);
}
Outside
}
(Outside, Statement::StartTransaction { .. }) => Other,
(
_,
Statement::Commit {
chain: false,
modifier: None,
..
}
| Statement::Rollback {
chain: false,
savepoint: None,
},
) => Outside,
(Outside, _) => Outside,
(_, _) => Other,
};
}
}