no_mistakes_postgres_sql/
lock_inventory.rs1use super::{parse::PreparedSql, SqlFunctionCallFact, SqlStatementFileFacts};
2use crate::erased_visit::VisitErased;
3use crate::fx::FxHashMap;
4use crate::statement_facts::SqlIsolationChanges;
5use sqlparser::ast::{Query, Spanned, Statement, Visitor};
6use sqlparser::tokenizer::{Location, Span, TokenWithSpan};
7use std::ops::ControlFlow;
8use std::sync::Arc;
9
10mod fact;
11pub use fact::InventoryLockFact;
12pub(super) mod tokens;
13use tokens::Segments;
14
15pub(super) fn unanalyzed_routines(statements: &[Statement]) -> Vec<usize> {
16 statements
17 .iter()
18 .filter_map(|statement| {
19 let name = match statement {
20 Statement::CreateFunction(function) => &function.name,
21 Statement::CreateProcedure { name, .. } => name,
22 _ => return None,
23 };
24 Some(name.span().start.line.max(1) as usize)
25 })
26 .collect()
27}
28
29pub(super) struct Collector<'sql> {
30 primary: Segments<'sql>,
31 recovery: FxHashMap<(*const TokenWithSpan, usize), Segments<'sql>>,
32 inventory: Vec<InventoryLockFact>,
33 isolation: SqlIsolationChanges,
34}
35
36pub(super) fn recovery_tokens<'a>(
37 sources: Option<&'a [Option<Arc<[TokenWithSpan]>>]>,
38 policy: Option<&'a [Option<Arc<[TokenWithSpan]>>]>,
39) -> impl Fn(usize) -> Option<&'a [TokenWithSpan]> {
40 move |index| {
41 sources
42 .and_then(|sources| sources.get(index)?.as_deref())
43 .or_else(|| policy.and_then(|sources| sources.get(index)?.as_deref()))
44 }
45}
46
47impl<'sql> Collector<'sql> {
48 pub(super) fn new(
49 prepared: &'sql PreparedSql<'_>,
50 statements: &[Statement],
51 locations: Option<&[Location]>,
52 batch: bool,
53 ) -> Self {
54 let tokens = prepared.tokens();
55 Self {
56 primary: Segments::new(tokens),
57 recovery: FxHashMap::default(),
58 inventory: Vec::new(),
59 isolation: SqlIsolationChanges::collect(statements, locations, tokens, batch),
60 }
61 }
62
63 pub(super) fn segments(&self) -> &Segments<'sql> {
64 &self.primary
65 }
66
67 pub(super) fn collect(
68 &mut self,
69 statement: &Statement,
70 recovery: Option<&'sql [TokenWithSpan]>,
71 source_at: impl Fn(Span) -> Option<&'sql str>,
72 ) {
73 let fallback = recovery.map(|tokens| {
74 &*self
75 .recovery
76 .entry((tokens.as_ptr(), tokens.len()))
77 .or_insert_with(|| Segments::recovered(tokens, &source_at))
78 });
79 let start = statement.span().start;
80 if self.primary.has_candidates_at(start)
81 || fallback.is_some_and(|source| source.has_candidates_at(start))
82 {
83 let _ = statement.visit_erased(&mut Scan {
84 primary: &self.primary,
85 fallback,
86 inventory: &mut self.inventory,
87 });
88 }
89 }
90
91 pub(super) fn finish_projection(
92 collector: Option<Self>,
93 facts: &mut SqlStatementFileFacts,
94 statements: &[Statement],
95 ) {
96 if let Some(mut collector) = collector {
97 facts.lock_isolation = std::mem::take(&mut collector.isolation);
98 facts.lock_inventory = collector.finish(&facts.function_calls);
99 facts.lock_inventory_unanalyzed = unanalyzed_routines(statements);
100 }
101 }
102
103 fn finish<'call>(
104 mut self,
105 calls: impl IntoIterator<Item = &'call SqlFunctionCallFact>,
106 ) -> Vec<InventoryLockFact> {
107 let mut pending: Vec<_> = calls
108 .into_iter()
109 .filter(|call| {
110 call.name_parts
111 .last()
112 .is_some_and(|name| advisory_name(name))
113 })
114 .filter(|call| !self.primary.advisory(call, &mut self.inventory))
115 .collect();
116 if !pending.is_empty() {
117 pending.sort_unstable_by_key(|call| (call.line, call.column));
118 for source in self.recovery.values() {
119 source.advisories(&pending, &mut self.inventory);
120 }
121 }
122 self.inventory.sort_unstable_by(|left, right| {
123 (left.line, left.column, &left.category, &left.fingerprint).cmp(&(
124 right.line,
125 right.column,
126 &right.category,
127 &right.fingerprint,
128 ))
129 });
130 self.inventory.dedup_by(|duplicate, kept| {
131 let same_site = (duplicate.line, duplicate.column, &duplicate.category)
132 == (kept.line, kept.column, &kept.category);
133 if same_site {
134 kept.in_stored_routine |= duplicate.in_stored_routine;
135 }
136 same_site
137 });
138 self.inventory
139 }
140}
141
142struct Scan<'a, 'sql> {
143 primary: &'a Segments<'sql>,
144 fallback: Option<&'a Segments<'sql>>,
145 inventory: &'a mut Vec<InventoryLockFact>,
146}
147
148impl Visitor for Scan<'_, '_> {
149 type Break = ();
150
151 fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<()> {
152 if let Statement::Lock(lock) = statement {
153 if self.primary.table_lock(lock, self.inventory).is_none() {
154 if let Some(fallback) = self.fallback {
155 fallback.table_lock(lock, self.inventory);
156 }
157 }
158 }
159 ControlFlow::Continue(())
160 }
161
162 fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
163 if !query.locks.is_empty() && !self.primary.row_locks(query, self.inventory) {
164 if let Some(fallback) = self.fallback {
165 fallback.row_locks(query, self.inventory);
166 }
167 }
168 ControlFlow::Continue(())
169 }
170}
171
172fn advisory_name(name: &str) -> bool {
173 name.starts_with("pg_advisory_") || name.starts_with("pg_try_advisory_")
174}
175
176#[cfg(test)]
177mod tests;