Skip to main content

postgres_mcp/tools/timescale/
probe.rs

1//! Probes which TimescaleDB views, columns and extension functions a database has, so queries name only what exists.
2
3use std::collections::HashSet;
4
5use tokio_util::sync::CancellationToken;
6
7use super::parse::quote_ident;
8use super::{query, text_of};
9use crate::server::AppState;
10use crate::tools::ToolError;
11
12const EXTENSION_SQL: &str = "SELECT e.extversion::text AS version, n.nspname::text AS schema \
13    FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace \
14    WHERE e.extname = 'timescaledb'";
15const COLUMNS_SQL: &str = "SELECT c.relname::text AS relation, a.attname::text AS column_name \
16    FROM pg_catalog.pg_attribute a \
17    JOIN pg_catalog.pg_class c ON c.oid = a.attrelid \
18    JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
19    WHERE n.nspname = 'timescaledb_information' AND a.attnum > 0 AND NOT a.attisdropped";
20const FUNCTIONS_SQL: &str = "SELECT n.nspname::text AS schema, p.proname::text AS name \
21    FROM pg_catalog.pg_proc p \
22    JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
23    JOIN pg_catalog.pg_depend d ON d.classid = 'pg_catalog.pg_proc'::regclass::oid AND d.objid = p.oid AND d.deptype = 'e' \
24    JOIN pg_catalog.pg_extension e ON e.oid = d.refobjid AND e.extname = 'timescaledb'";
25
26/// What one database offers: the TimescaleDB version, its functions and the columns of its information views.
27#[derive(Debug, Clone)]
28pub struct Features {
29    pub database: String,
30    pub version: Option<String>,
31    pub extension_schema: Option<String>,
32    columns: HashSet<(String, String)>,
33    functions: HashSet<(String, String)>,
34}
35
36impl Features {
37    /// Features from probed names; `version` and `extension_schema` are None when TimescaleDB is absent.
38    pub fn new(
39        database: &str,
40        version: Option<&str>,
41        extension_schema: Option<&str>,
42        columns: &[(&str, &str)],
43        functions: &[(&str, &str)],
44    ) -> Features {
45        Features {
46            database: database.to_owned(),
47            version: version.map(str::to_owned),
48            extension_schema: extension_schema.map(str::to_owned),
49            columns: columns
50                .iter()
51                .map(|(view, column)| ((*view).to_owned(), (*column).to_owned()))
52                .collect(),
53            functions: functions
54                .iter()
55                .map(|(schema, name)| ((*schema).to_owned(), (*name).to_owned()))
56                .collect(),
57        }
58    }
59
60    pub fn installed(&self) -> bool {
61        self.version.is_some()
62    }
63
64    /// True when the timescaledb_information view has the column.
65    pub fn has(&self, view: &str, column: &str) -> bool {
66        self.columns.contains(&(view.to_owned(), column.to_owned()))
67    }
68
69    /// True when the timescaledb_information view has every listed column.
70    pub fn has_all(&self, view: &str, columns: &[&str]) -> bool {
71        columns.iter().all(|column| self.has(view, column))
72    }
73
74    /// Fails with an internal error naming the first view column the query needs and this version lacks.
75    pub fn require(&self, view: &str, columns: &[&str]) -> Result<(), ToolError> {
76        match columns.iter().find(|column| !self.has(view, column)) {
77            None => Ok(()),
78            Some(column) => Err(ToolError::Internal(format!(
79                "TimescaleDB {} has no {view}.{column}, which this tool needs.",
80                self.version.as_deref().unwrap_or("(absent)")
81            ))),
82        }
83    }
84
85    /// The function as a qualified call prefix when the schema holds it.
86    pub fn function(&self, schema: &str, name: &str) -> Option<String> {
87        self.functions
88            .contains(&(schema.to_owned(), name.to_owned()))
89            .then(|| format!("{}.{name}", quote_ident(schema)))
90    }
91
92    /// The function as a qualified call prefix when the extension's schema holds it.
93    pub fn extension_function(&self, name: &str) -> Option<String> {
94        let schema = self.extension_schema.as_deref()?;
95        self.function(schema, name)
96    }
97}
98
99/// Which catalog sources this database offers for each concept, newest name first.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct Sources {
102    /// hypertables column that says whether the columnstore is on.
103    pub hypertable_flag: Option<&'static str>,
104    /// chunks column that says whether a chunk is in the columnstore.
105    pub chunk_flag: Option<&'static str>,
106    /// continuous_aggregates column that says whether the columnstore is on.
107    pub cagg_flag: Option<&'static str>,
108    /// View of columnstore settings: segmentby and orderby per hypertable.
109    pub settings_view: Option<&'static str>,
110    /// Function with columnstore totals per hypertable.
111    pub stats_function: Option<&'static str>,
112    pub cagg_finalized: bool,
113    pub chunk_tablespace: bool,
114    pub job_fixed_schedule: bool,
115}
116
117impl Sources {
118    pub fn choose(features: &Features) -> Sources {
119        Sources {
120            hypertable_flag: first_column(
121                features,
122                "hypertables",
123                &["columnstore_enabled", "compression_enabled"],
124            ),
125            chunk_flag: first_column(features, "chunks", &["is_columnstore", "is_compressed"]),
126            cagg_flag: first_column(
127                features,
128                "continuous_aggregates",
129                &["columnstore_enabled", "compression_enabled"],
130            ),
131            settings_view: first_settings_view(
132                features,
133                &[
134                    "hypertable_columnstore_settings",
135                    "hypertable_compression_settings",
136                ],
137            ),
138            stats_function: first_function(
139                features,
140                &[
141                    "hypertable_columnstore_stats",
142                    "hypertable_compression_stats",
143                ],
144            ),
145            cagg_finalized: features.has("continuous_aggregates", "finalized"),
146            chunk_tablespace: features.has("chunks", "chunk_tablespace"),
147            job_fixed_schedule: features.has("jobs", "fixed_schedule"),
148        }
149    }
150}
151
152fn first_column(
153    features: &Features,
154    view: &str,
155    candidates: &[&'static str],
156) -> Option<&'static str> {
157    candidates
158        .iter()
159        .copied()
160        .find(|column| features.has(view, column))
161}
162
163fn first_settings_view(features: &Features, candidates: &[&'static str]) -> Option<&'static str> {
164    candidates.iter().copied().find(|view| {
165        ["hypertable", "segmentby", "orderby"]
166            .iter()
167            .all(|column| features.has(view, column))
168    })
169}
170
171fn first_function(features: &Features, candidates: &[&'static str]) -> Option<&'static str> {
172    candidates
173        .iter()
174        .copied()
175        .find(|name| features.extension_function(name).is_some())
176}
177
178/// Probes one database: the extension, the columns of timescaledb_information and the extension's functions.
179/// Without the extension the result is not installed and holds nothing else.
180pub async fn load(
181    state: &AppState,
182    database: Option<&str>,
183    ct: &CancellationToken,
184) -> Result<Features, ToolError> {
185    let extension = query(state, database, EXTENSION_SQL, &[], ct).await?;
186    let name = extension.database.clone();
187    let Some(row) = extension.rows.first() else {
188        return Ok(Features::new(&name, None, None, &[], &[]));
189    };
190    let version = text_of(row, "version");
191    let schema = text_of(row, "schema");
192    let target = Some(name.as_str());
193    let columns = query(state, target, COLUMNS_SQL, &[], ct).await?;
194    let functions = query(state, target, FUNCTIONS_SQL, &[], ct).await?;
195    let column_pairs: Vec<(&str, &str)> = columns
196        .rows
197        .iter()
198        .filter_map(|row| {
199            Some((
200                row.get("relation")?.as_str()?,
201                row.get("column_name")?.as_str()?,
202            ))
203        })
204        .collect();
205    let function_pairs: Vec<(&str, &str)> = functions
206        .rows
207        .iter()
208        .filter_map(|row| Some((row.get("schema")?.as_str()?, row.get("name")?.as_str()?)))
209        .collect();
210    Ok(Features::new(
211        &name,
212        version.as_deref(),
213        schema.as_deref(),
214        &column_pairs,
215        &function_pairs,
216    ))
217}