|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use dashmap::DashMap; |
| 4 | +use pgt_lexer::{SyntaxKind, WHITESPACE_TOKENS}; |
| 5 | + |
| 6 | +use super::statement_identifier::StatementId; |
| 7 | + |
| 8 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 9 | +pub struct StatementAnnotations { |
| 10 | + ends_with_semicolon: bool, |
| 11 | +} |
| 12 | + |
| 13 | +pub struct AnnotationStore { |
| 14 | + db: DashMap<StatementId, Option<Arc<StatementAnnotations>>>, |
| 15 | +} |
| 16 | + |
| 17 | +impl AnnotationStore { |
| 18 | + pub fn new() -> AnnotationStore { |
| 19 | + AnnotationStore { db: DashMap::new() } |
| 20 | + } |
| 21 | + |
| 22 | + #[allow(unused)] |
| 23 | + pub fn get_annotations( |
| 24 | + &self, |
| 25 | + statement: &StatementId, |
| 26 | + content: &str, |
| 27 | + ) -> Option<Arc<StatementAnnotations>> { |
| 28 | + if let Some(existing) = self.db.get(statement).map(|x| x.clone()) { |
| 29 | + return existing; |
| 30 | + } |
| 31 | + |
| 32 | + // we swallow the error here because the lexing within the document would have already |
| 33 | + // thrown and we wont even get here if that happened. |
| 34 | + let annotations = pgt_lexer::lex(content).ok().map(|tokens| { |
| 35 | + let ends_with_semicolon = tokens |
| 36 | + .iter() |
| 37 | + .rev() |
| 38 | + .find(|token| !WHITESPACE_TOKENS.contains(&token.kind)) |
| 39 | + .is_some_and(|token| token.kind == SyntaxKind::Ascii59); |
| 40 | + |
| 41 | + Arc::new(StatementAnnotations { |
| 42 | + ends_with_semicolon, |
| 43 | + }) |
| 44 | + }); |
| 45 | + |
| 46 | + self.db.insert(statement.clone(), None); |
| 47 | + annotations |
| 48 | + } |
| 49 | + |
| 50 | + #[allow(unused)] |
| 51 | + pub fn clear_statement(&self, id: &StatementId) { |
| 52 | + self.db.remove(id); |
| 53 | + |
| 54 | + if let Some(child_id) = id.get_child_id() { |
| 55 | + self.db.remove(&child_id); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +#[cfg(test)] |
| 61 | +mod tests { |
| 62 | + use crate::workspace::StatementId; |
| 63 | + |
| 64 | + use super::AnnotationStore; |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn annotates_correctly() { |
| 68 | + let store = AnnotationStore::new(); |
| 69 | + |
| 70 | + let test_cases = [ |
| 71 | + ("SELECT * FROM foo", false), |
| 72 | + ("SELECT * FROM foo;", true), |
| 73 | + ("SELECT * FROM foo ;", true), |
| 74 | + ("SELECT * FROM foo ; ", true), |
| 75 | + ("SELECT * FROM foo ;\n", true), |
| 76 | + ("SELECT * FROM foo\n", false), |
| 77 | + ]; |
| 78 | + |
| 79 | + for (idx, (content, expected)) in test_cases.iter().enumerate() { |
| 80 | + let statement_id = StatementId::Root(idx.into()); |
| 81 | + |
| 82 | + let annotations = store.get_annotations(&statement_id, content); |
| 83 | + |
| 84 | + assert!(annotations.is_some()); |
| 85 | + assert_eq!(annotations.unwrap().ends_with_semicolon, *expected); |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments