Skip to main content

gaman_core/migration_engine/
execution_diagnostic.rs

1//! Bounded SQL context used when a database rejects one statement.
2
3use std::fmt::{self, Display, Formatter};
4
5/// Maximum number of characters included in one statement signature.
6const MAX_SIGNATURE_CHARS: usize = 160;
7/// Maximum number of characters included in one highlighted source line.
8const MAX_EXCERPT_CHARS: usize = 200;
9
10/// Stable database error information supplied by an executor.
11///
12/// Executors preserve only fields emitted directly by their database driver. They never attach
13/// the submitted SQL text, which can be arbitrarily large or sensitive.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct DatabaseFailure {
16    /// Concise database-provided failure message.
17    pub message: String,
18    /// Optional database error code, such as a PostgreSQL SQLSTATE.
19    pub code: Option<String>,
20    /// Optional driver-provided character position.
21    pub position: Option<DatabasePosition>,
22}
23
24impl DatabaseFailure {
25    /// Creates a database failure without a database-specific code or position.
26    pub fn message(message: impl Into<String>) -> Self {
27        Self {
28            message: message.into(),
29            code: None,
30            position: None,
31        }
32    }
33
34    /// Adds a stable database error code.
35    pub fn with_code(mut self, code: impl Into<String>) -> Self {
36        self.code = Some(code.into());
37        self
38    }
39
40    /// Adds a driver-provided character position.
41    pub fn with_position(mut self, position: DatabasePosition) -> Self {
42        self.position = Some(position);
43        self
44    }
45}
46
47impl Display for DatabaseFailure {
48    /// Renders only stable message and code, never an internal query body.
49    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/// A character position reported directly by a database driver.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum DatabasePosition {
60    /// One-based character position in the submitted statement.
61    Statement(usize),
62    /// One-based character position in a database-provided internal query.
63    Internal {
64        /// One-based character position in [`Self::query`].
65        position: usize,
66        /// Query text supplied by the database driver.
67        query: String,
68    },
69}
70
71/// Compact, display-safe context for one rendered SQL statement.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct StatementDiagnostic {
74    /// Bounded first-line identity of the statement.
75    pub signature: String,
76    /// Optional source location supplied by the database.
77    pub location: Option<StatementLocation>,
78}
79
80/// One bounded source location rendered from a database-provided position.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct StatementLocation {
83    /// Whether the location refers to submitted or database-internal SQL.
84    pub source: StatementLocationSource,
85    /// One-based line number in the database-provided source text.
86    pub line: usize,
87    /// One-based column number in the database-provided source text.
88    pub column: usize,
89    /// Bounded line excerpt containing the reported position.
90    pub excerpt: String,
91    /// Zero-based display offset for a caret below [`Self::excerpt`].
92    pub caret_offset: usize,
93}
94
95/// The source text to which a database-reported position applies.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum StatementLocationSource {
98    /// The SQL statement submitted by Gaman.
99    Statement,
100    /// An internal query returned by the database, such as a SQL-function body.
101    Internal,
102}
103
104impl StatementLocationSource {
105    /// Returns the concise label used in host diagnostics.
106    pub fn label(self) -> &'static str {
107        match self {
108            Self::Statement => "SQL",
109            Self::Internal => "internal SQL",
110        }
111    }
112}
113
114/// Builds bounded statement context from one rendered statement and stable driver information.
115pub(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
134/// Returns the first non-empty SQL line in a bounded, single-line form.
135fn 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
144/// Converts a one-based character position into a bounded source line and caret offset.
145fn 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
173/// Resolves a one-based character position without assuming UTF-8 bytes equal characters.
174fn 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
180/// Trims a source line around a one-based column while preserving a caret-safe display offset.
181fn 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
209/// Shortens text on character boundaries and marks omitted content with one ellipsis.
210fn 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    /// Verifies statement positions preserve UTF-8 character columns and source lines.
224    #[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    /// Verifies internal-query positions use database-provided source rather than submitted DDL.
236    #[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    /// Verifies long statements and source lines never exceed their diagnostic bounds.
250    #[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    /// Verifies unavailable database positions do not create guessed locations.
268    #[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}