Skip to main content

postgres_lsp_analysis/
index.rs

1use std::sync::Arc;
2
3use dashmap::DashMap;
4use tree_sitter::Tree;
5
6use postgres_lsp_parse::injection::InjectedRegion;
7
8use crate::symbols::{self, QualifiedName, Symbol, SymbolKind, SymbolRef};
9
10/// A concurrent workspace-wide symbol index.
11///
12/// Stores definitions and references keyed by file URI, with lookup
13/// by qualified name. Uses `DashMap` for lock-free concurrent reads.
14pub struct WorkspaceIndex {
15    /// Definitions grouped by URI.
16    definitions: DashMap<String, Vec<Arc<Symbol>>>,
17    /// References grouped by URI.
18    references: DashMap<String, Vec<Arc<SymbolRef>>>,
19    /// Definitions keyed by (kind, name) for fast lookup.
20    by_name: DashMap<(SymbolKind, String), Vec<Arc<Symbol>>>,
21}
22
23impl WorkspaceIndex {
24    pub fn new() -> Self {
25        Self {
26            definitions: DashMap::new(),
27            references: DashMap::new(),
28            by_name: DashMap::new(),
29        }
30    }
31
32    /// Re-index a file: remove old entries and extract new ones from the tree.
33    ///
34    /// Also extracts PL/pgSQL symbols from any injected regions.
35    pub fn update_file(&self, uri: &str, tree: &Tree, source: &str, injections: &[InjectedRegion]) {
36        let mut all_symbols = symbols::extract_symbols(tree, source, uri);
37        let refs = symbols::extract_references(tree, source, uri);
38
39        // Extract PL/pgSQL symbols from injected regions.
40        for region in injections {
41            let (parent_line, parent_col) = region.parent_position(source);
42
43            let plpgsql_syms = symbols::extract_plpgsql_symbols(
44                &region.tree,
45                &region.text,
46                uri,
47                parent_line,
48                parent_col,
49            );
50            all_symbols.extend(plpgsql_syms);
51        }
52
53        let symbol_arcs: Vec<Arc<Symbol>> = all_symbols.into_iter().map(Arc::new).collect();
54        let ref_arcs: Vec<Arc<SymbolRef>> = refs.into_iter().map(Arc::new).collect();
55
56        // Remove old entries, then insert new ones.
57        self.remove_file(uri);
58        self.index_by_name(&symbol_arcs);
59        self.definitions.insert(uri.to_string(), symbol_arcs);
60        self.references.insert(uri.to_string(), ref_arcs);
61    }
62
63    /// Insert pre-built symbols (e.g., from database introspection).
64    /// Uses the provided URI to group them, allowing removal via `remove_file`.
65    pub fn load_symbols(&self, uri: &str, symbols: Vec<Symbol>) {
66        self.remove_file(uri);
67        let symbol_arcs: Vec<Arc<Symbol>> = symbols.into_iter().map(Arc::new).collect();
68        self.index_by_name(&symbol_arcs);
69        self.definitions.insert(uri.to_string(), symbol_arcs);
70    }
71
72    fn index_by_name(&self, symbols: &[Arc<Symbol>]) {
73        for sym in symbols {
74            let key = (sym.kind, sym.name.name.to_lowercase());
75            self.by_name.entry(key).or_default().push(Arc::clone(sym));
76
77            for child in &sym.children {
78                let child_arc = Arc::new(child.clone());
79                let child_key = (child.kind, child.name.name.to_lowercase());
80                self.by_name.entry(child_key).or_default().push(child_arc);
81            }
82        }
83    }
84
85    /// Remove all entries for a file.
86    pub fn remove_file(&self, uri: &str) {
87        if let Some((_, old_symbols)) = self.definitions.remove(uri) {
88            let mut keys_to_check = Vec::new();
89            for sym in &old_symbols {
90                let key = (sym.kind, sym.name.name.to_lowercase());
91                self.by_name.entry(key.clone()).and_modify(|v| {
92                    v.retain(|s| s.uri != uri);
93                });
94                keys_to_check.push(key);
95                for child in &sym.children {
96                    let child_key = (child.kind, child.name.name.to_lowercase());
97                    self.by_name.entry(child_key.clone()).and_modify(|v| {
98                        v.retain(|s| s.uri != uri);
99                    });
100                    keys_to_check.push(child_key);
101                }
102            }
103            // Clean up empty entries.
104            for key in keys_to_check {
105                self.by_name.remove_if(&key, |_, v| v.is_empty());
106            }
107        }
108        self.references.remove(uri);
109    }
110
111    /// Find definitions by kind and name (case-insensitive).
112    pub fn find_definitions(&self, kind: SymbolKind, name: &str) -> Vec<Arc<Symbol>> {
113        let key = (kind, name.to_lowercase());
114        self.by_name
115            .get(&key)
116            .map(|v| v.value().clone())
117            .unwrap_or_default()
118    }
119
120    /// Find any definition matching a name (case-insensitive), regardless of kind.
121    pub fn find_by_name(&self, name: &str) -> Vec<Arc<Symbol>> {
122        let lower = name.to_lowercase();
123        let mut results = Vec::new();
124        for entry in self.by_name.iter() {
125            if entry.key().1 == lower {
126                results.extend(entry.value().iter().cloned());
127            }
128        }
129        results
130    }
131
132    /// Find definitions matching a qualified name (with schema resolution).
133    pub fn resolve(&self, name: &QualifiedName) -> Vec<Arc<Symbol>> {
134        let lower = name.name.to_lowercase();
135        let mut results = Vec::new();
136
137        for entry in self.by_name.iter() {
138            if entry.key().1 != lower {
139                continue;
140            }
141            for sym in entry.value() {
142                if let Some(ref schema) = name.schema {
143                    if sym.name.schema.as_ref().map(|s| s.to_lowercase())
144                        == Some(schema.to_lowercase())
145                    {
146                        results.push(Arc::clone(sym));
147                    }
148                } else {
149                    // No schema specified — match any
150                    results.push(Arc::clone(sym));
151                }
152            }
153        }
154        results
155    }
156
157    /// Find all references to a name across the workspace.
158    pub fn find_references(&self, name: &str) -> Vec<Arc<SymbolRef>> {
159        let lower = name.to_lowercase();
160        let mut results = Vec::new();
161        for entry in self.references.iter() {
162            for r in entry.value() {
163                if r.name.name.to_lowercase() == lower {
164                    results.push(Arc::clone(r));
165                }
166            }
167        }
168        results
169    }
170
171    /// Get all definitions in a specific file.
172    pub fn file_symbols(&self, uri: &str) -> Vec<Arc<Symbol>> {
173        self.definitions
174            .get(uri)
175            .map(|v| v.value().clone())
176            .unwrap_or_default()
177    }
178
179    /// Get all definitions across the workspace.
180    pub fn all_symbols(&self) -> Vec<Arc<Symbol>> {
181        let mut all = Vec::new();
182        for entry in self.definitions.iter() {
183            all.extend(entry.value().iter().cloned());
184        }
185        all
186    }
187
188    /// Search for symbols matching a query string (for workspace/symbol).
189    pub fn search(&self, query: &str) -> Vec<Arc<Symbol>> {
190        let lower = query.to_lowercase();
191        let mut results = Vec::new();
192        for entry in self.by_name.iter() {
193            if entry.key().1.contains(&lower) {
194                results.extend(entry.value().iter().cloned());
195            }
196        }
197        results
198    }
199}
200
201impl Default for WorkspaceIndex {
202    fn default() -> Self {
203        Self::new()
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use postgres_lsp_parse::ParserPool;
210
211    use super::*;
212
213    #[test]
214    fn index_and_lookup() {
215        let pool = ParserPool::new();
216        let index = WorkspaceIndex::new();
217
218        let sql = "CREATE TABLE users (id int, name text);";
219        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
220        let tree = guard.parser_mut().parse(sql, None).unwrap();
221        drop(guard);
222
223        index.update_file("file:///test.sql", &tree, sql, &[]);
224
225        let results = index.find_definitions(SymbolKind::Table, "users");
226        assert_eq!(results.len(), 1);
227        assert_eq!(results[0].name.name, "users");
228    }
229
230    #[test]
231    fn remove_file_cleans_index() {
232        let pool = ParserPool::new();
233        let index = WorkspaceIndex::new();
234
235        let sql = "CREATE TABLE users (id int);";
236        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
237        let tree = guard.parser_mut().parse(sql, None).unwrap();
238        drop(guard);
239
240        index.update_file("file:///test.sql", &tree, sql, &[]);
241        assert!(
242            !index
243                .find_definitions(SymbolKind::Table, "users")
244                .is_empty()
245        );
246
247        index.remove_file("file:///test.sql");
248        assert!(
249            index
250                .find_definitions(SymbolKind::Table, "users")
251                .is_empty()
252        );
253    }
254
255    #[test]
256    fn search_by_query() {
257        let pool = ParserPool::new();
258        let index = WorkspaceIndex::new();
259
260        let sql = "CREATE TABLE user_accounts (id int);\nCREATE TABLE user_profiles (id int);";
261        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
262        let tree = guard.parser_mut().parse(sql, None).unwrap();
263        drop(guard);
264
265        index.update_file("file:///test.sql", &tree, sql, &[]);
266
267        let results = index.search("user");
268        assert!(results.len() >= 2);
269    }
270}