Skip to main content

postgres_lsp_schema/
catalog.rs

1use std::collections::HashMap;
2
3use postgres_lsp_analysis::symbols::{QualifiedName, Symbol, SymbolKind};
4use tokio_postgres::Client;
5
6/// The synthetic URI used for database-sourced symbols.
7pub const DB_URI: &str = "pg-catalog://database";
8
9/// Namespace exclusion filter — skip system and information_schema namespaces.
10const NS_FILTER: &str = "n.nspname NOT LIKE 'pg_%' AND n.nspname != 'information_schema'";
11
12/// Load all schemas, tables, columns, functions, types, and sequences
13/// from a live PostgreSQL database via `pg_catalog` queries.
14pub async fn load_catalog(client: &Client) -> Result<Vec<Symbol>, CatalogError> {
15    let mut symbols = Vec::new();
16
17    load_schemas(client, &mut symbols).await?;
18    load_tables_and_columns(client, &mut symbols).await?;
19    load_functions(client, &mut symbols).await?;
20    load_types(client, &mut symbols).await?;
21    load_sequences(client, &mut symbols).await?;
22
23    Ok(symbols)
24}
25
26async fn load_schemas(client: &Client, symbols: &mut Vec<Symbol>) -> Result<(), CatalogError> {
27    let query = format!("SELECT nspname FROM pg_catalog.pg_namespace n WHERE {NS_FILTER}");
28    let rows = client.query(&query, &[]).await?;
29
30    for row in rows {
31        let name: String = row.get(0);
32        symbols.push(make_symbol(SymbolKind::Schema, None, &name, ""));
33    }
34
35    Ok(())
36}
37
38async fn load_tables_and_columns(
39    client: &Client,
40    symbols: &mut Vec<Symbol>,
41) -> Result<(), CatalogError> {
42    // Single batch query for tables/views and their columns (avoids N+1).
43    let query = format!(
44        "SELECT n.nspname, c.relname, c.relkind, \
45                a.attname, format_type(a.atttypid, a.atttypmod) \
46         FROM pg_catalog.pg_class c \
47         JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
48         LEFT JOIN pg_catalog.pg_attribute a \
49           ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped \
50         WHERE c.relkind IN ('r', 'v', 'm', 'f') AND {NS_FILTER} \
51         ORDER BY n.nspname, c.relname, a.attnum"
52    );
53    let rows = client.query(&query, &[]).await?;
54
55    // Group columns by (schema, table).
56    let mut tables: Vec<(String, String, SymbolKind)> = Vec::new();
57    let mut columns: HashMap<(String, String), Vec<Symbol>> = HashMap::new();
58
59    for row in &rows {
60        let schema: String = row.get(0);
61        let name: String = row.get(1);
62        // PostgreSQL "char" type maps to i8 in tokio_postgres; all relkind values are ASCII.
63        let relkind: i8 = row.get(2);
64        let col_name: Option<String> = row.get(3);
65        let col_type: Option<String> = row.get(4);
66
67        let kind = match relkind as u8 as char {
68            'r' => SymbolKind::Table,
69            'v' => SymbolKind::View,
70            'm' => SymbolKind::MaterializedView,
71            'f' => SymbolKind::ForeignTable,
72            _ => continue,
73        };
74
75        let key = (schema.clone(), name.clone());
76        if !columns.contains_key(&key) {
77            tables.push((schema.clone(), name.clone(), kind));
78            columns.insert(key.clone(), Vec::new());
79        }
80
81        if let (Some(cn), Some(ct)) = (col_name, col_type) {
82            let col_def = format!("{cn} {ct}");
83            columns.get_mut(&key).unwrap().push(make_symbol(
84                SymbolKind::Column,
85                None,
86                &cn,
87                &col_def,
88            ));
89        }
90    }
91
92    for (schema, name, kind) in tables {
93        let def_text = format!("{kind_label} {schema}.{name}", kind_label = kind.label());
94        let mut sym = make_symbol(kind, Some(&schema), &name, &def_text);
95        sym.children = columns.remove(&(schema, name)).unwrap_or_default();
96        symbols.push(sym);
97    }
98
99    Ok(())
100}
101
102async fn load_functions(client: &Client, symbols: &mut Vec<Symbol>) -> Result<(), CatalogError> {
103    let query = format!(
104        "SELECT n.nspname, p.proname, \
105                pg_catalog.pg_get_function_arguments(p.oid), \
106                pg_catalog.pg_get_function_result(p.oid), \
107                p.prokind \
108         FROM pg_catalog.pg_proc p \
109         JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
110         WHERE {NS_FILTER}"
111    );
112    let rows = client.query(&query, &[]).await?;
113
114    for row in rows {
115        let schema: String = row.get(0);
116        let name: String = row.get(1);
117        let args: String = row.get(2);
118        let ret: String = row.get(3);
119        let prokind: i8 = row.get(4);
120
121        let kind = match prokind as u8 as char {
122            'p' => SymbolKind::Procedure,
123            _ => SymbolKind::Function,
124        };
125
126        let def_text = format!(
127            "{kind_label} {schema}.{name}({args}) RETURNS {ret}",
128            kind_label = kind.label()
129        );
130        symbols.push(make_symbol(kind, Some(&schema), &name, &def_text));
131    }
132
133    Ok(())
134}
135
136async fn load_types(client: &Client, symbols: &mut Vec<Symbol>) -> Result<(), CatalogError> {
137    let query = format!(
138        "SELECT n.nspname, t.typname, t.typtype \
139         FROM pg_catalog.pg_type t \
140         JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace \
141         WHERE {NS_FILTER} \
142           AND t.typtype IN ('c', 'e', 'r', 'd') \
143           AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class c WHERE c.reltype = t.oid)"
144    );
145    let rows = client.query(&query, &[]).await?;
146
147    for row in rows {
148        let schema: String = row.get(0);
149        let name: String = row.get(1);
150        let typtype: i8 = row.get(2);
151
152        let kind = match typtype as u8 as char {
153            'd' => SymbolKind::Domain,
154            _ => SymbolKind::Type,
155        };
156
157        let def_text = format!("{kind_label} {schema}.{name}", kind_label = kind.label());
158        symbols.push(make_symbol(kind, Some(&schema), &name, &def_text));
159    }
160
161    Ok(())
162}
163
164async fn load_sequences(client: &Client, symbols: &mut Vec<Symbol>) -> Result<(), CatalogError> {
165    let query = format!(
166        "SELECT n.nspname, c.relname \
167         FROM pg_catalog.pg_class c \
168         JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
169         WHERE c.relkind = 'S' AND {NS_FILTER}"
170    );
171    let rows = client.query(&query, &[]).await?;
172
173    for row in rows {
174        let schema: String = row.get(0);
175        let name: String = row.get(1);
176        let def_text = format!("sequence {schema}.{name}");
177        symbols.push(make_symbol(
178            SymbolKind::Sequence,
179            Some(&schema),
180            &name,
181            &def_text,
182        ));
183    }
184
185    Ok(())
186}
187
188fn make_symbol(
189    kind: SymbolKind,
190    schema: Option<&str>,
191    name: &str,
192    definition_text: &str,
193) -> Symbol {
194    let qname = match schema {
195        Some(s) => QualifiedName::with_schema(s.to_string(), name.to_string()),
196        None => QualifiedName::new(name.to_string()),
197    };
198    Symbol {
199        kind,
200        name: qname,
201        uri: DB_URI.to_string(),
202        start_byte: 0,
203        end_byte: 0,
204        start_line: 0,
205        start_col: 0,
206        end_line: 0,
207        end_col: 0,
208        name_start_line: 0,
209        name_start_col: 0,
210        name_end_line: 0,
211        name_end_col: 0,
212        definition_text: definition_text.to_string(),
213        children: Vec::new(),
214    }
215}
216
217#[derive(Debug, thiserror::Error)]
218pub enum CatalogError {
219    #[error("database error: {0}")]
220    Database(#[from] tokio_postgres::Error),
221}