gaman_core/migration_engine/
execution_diagnostic.rs1use std::fmt::{self, Display, Formatter};
4
5const MAX_SIGNATURE_CHARS: usize = 160;
7const MAX_EXCERPT_CHARS: usize = 200;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct DatabaseFailure {
16 pub message: String,
18 pub code: Option<String>,
20 pub position: Option<DatabasePosition>,
22}
23
24impl DatabaseFailure {
25 pub fn message(message: impl Into<String>) -> Self {
27 Self {
28 message: message.into(),
29 code: None,
30 position: None,
31 }
32 }
33
34 pub fn with_code(mut self, code: impl Into<String>) -> Self {
36 self.code = Some(code.into());
37 self
38 }
39
40 pub fn with_position(mut self, position: DatabasePosition) -> Self {
42 self.position = Some(position);
43 self
44 }
45}
46
47impl Display for DatabaseFailure {
48 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
50 match &self.code {
51 Some(code) => write!(formatter, "[{code}] {}", self.message),
52 None => formatter.write_str(&self.message),
53 }
54 }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum DatabasePosition {
60 Statement(usize),
62 Internal {
64 position: usize,
66 query: String,
68 },
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct StatementDiagnostic {
74 pub signature: String,
76 pub location: Option<StatementLocation>,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct StatementLocation {
83 pub source: StatementLocationSource,
85 pub line: usize,
87 pub column: usize,
89 pub excerpt: String,
91 pub caret_offset: usize,
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum StatementLocationSource {
98 Statement,
100 Internal,
102}
103
104impl StatementLocationSource {
105 pub fn label(self) -> &'static str {
107 match self {
108 Self::Statement => "SQL",
109 Self::Internal => "internal SQL",
110 }
111 }
112}
113
114pub(crate) fn statement_diagnostic(
116 statement: &str,
117 position: Option<&DatabasePosition>,
118) -> StatementDiagnostic {
119 let location = match position {
120 Some(DatabasePosition::Statement(position)) => {
121 statement_location(statement, *position, StatementLocationSource::Statement)
122 }
123 Some(DatabasePosition::Internal { position, query }) => {
124 statement_location(query, *position, StatementLocationSource::Internal)
125 }
126 None => None,
127 };
128 StatementDiagnostic {
129 signature: statement_signature(statement),
130 location,
131 }
132}
133
134fn statement_signature(statement: &str) -> String {
136 let line = statement
137 .lines()
138 .find(|line| !line.trim().is_empty())
139 .unwrap_or("");
140 let compact = line.split_whitespace().collect::<Vec<_>>().join(" ");
141 truncate_chars(&compact, MAX_SIGNATURE_CHARS)
142}
143
144fn statement_location(
146 source: &str,
147 position: usize,
148 source_kind: StatementLocationSource,
149) -> Option<StatementLocation> {
150 let byte_index = character_byte_index(source, position)?;
151 let before = &source[..byte_index];
152 let line_start = before.rfind('\n').map_or(0, |index| index + 1);
153 let line_end = source[byte_index..]
154 .find('\n')
155 .map_or(source.len(), |index| byte_index + index);
156 let line = source[line_start..line_end].replace('\t', " ");
157 let column = source[line_start..byte_index].chars().count() + 1;
158 let line_number = source[..line_start]
159 .chars()
160 .filter(|character| *character == '\n')
161 .count()
162 + 1;
163 let (excerpt, caret_offset) = bounded_excerpt(&line, column)?;
164 Some(StatementLocation {
165 source: source_kind,
166 line: line_number,
167 column,
168 excerpt,
169 caret_offset,
170 })
171}
172
173fn character_byte_index(source: &str, position: usize) -> Option<usize> {
175 position
176 .checked_sub(1)
177 .and_then(|index| source.char_indices().nth(index).map(|(byte, _)| byte))
178}
179
180fn bounded_excerpt(line: &str, column: usize) -> Option<(String, usize)> {
182 let characters: Vec<char> = line.chars().collect();
183 let cursor = column.checked_sub(1)?;
184 if cursor >= characters.len() {
185 return None;
186 }
187 if characters.len() <= MAX_EXCERPT_CHARS {
188 return Some((line.to_string(), cursor));
189 }
190 let content_limit = MAX_EXCERPT_CHARS.saturating_sub(4);
191 let mut start = cursor.saturating_sub(content_limit / 2);
192 let end = (start + content_limit).min(characters.len());
193 if end == characters.len() {
194 start = end.saturating_sub(content_limit);
195 }
196 let prefix = usize::from(start > 0);
197 let suffix = usize::from(end < characters.len());
198 let mut excerpt = String::new();
199 if prefix > 0 {
200 excerpt.push('…');
201 }
202 excerpt.extend(characters[start..end].iter());
203 if suffix > 0 {
204 excerpt.push('…');
205 }
206 Some((excerpt, prefix + cursor - start))
207}
208
209fn truncate_chars(value: &str, limit: usize) -> String {
211 if value.chars().count() <= limit {
212 return value.to_string();
213 }
214 let mut result: String = value.chars().take(limit.saturating_sub(1)).collect();
215 result.push('…');
216 result
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 #[test]
225 fn statement_position_uses_character_columns() {
226 let statement = "SELECT café\nFROM reports";
227 let diagnostic = statement_diagnostic(statement, Some(&DatabasePosition::Statement(11)));
228 let location = diagnostic.location.expect("location");
229 assert_eq!(location.line, 1);
230 assert_eq!(location.column, 11);
231 assert_eq!(location.excerpt, "SELECT café");
232 assert_eq!(location.caret_offset, 10);
233 }
234
235 #[test]
237 fn internal_position_uses_internal_query() {
238 let position = DatabasePosition::Internal {
239 position: 8,
240 query: "SELECT ambiguous_column FROM one JOIN two ON true".to_string(),
241 };
242 let diagnostic = statement_diagnostic("CREATE FUNCTION ...", Some(&position));
243 let location = diagnostic.location.expect("location");
244 assert_eq!(location.source, StatementLocationSource::Internal);
245 assert_eq!(location.column, 8);
246 assert!(location.excerpt.starts_with("SELECT"));
247 }
248
249 #[test]
251 fn diagnostics_bound_statement_and_excerpt_sizes() {
252 let statement = format!("{}\n{}", "CREATE ".repeat(80), "x".repeat(400));
253 let position = DatabasePosition::Statement(statement.chars().count() - 50);
254 let diagnostic = statement_diagnostic(&statement, Some(&position));
255 assert!(diagnostic.signature.chars().count() <= MAX_SIGNATURE_CHARS);
256 assert!(
257 diagnostic
258 .location
259 .expect("location")
260 .excerpt
261 .chars()
262 .count()
263 <= MAX_EXCERPT_CHARS
264 );
265 }
266
267 #[test]
269 fn missing_position_has_no_location() {
270 assert!(
271 statement_diagnostic("CREATE TABLE reports", None)
272 .location
273 .is_none()
274 );
275 }
276}