fraiseql_cli/schema/pg_catalog.rs
1//! Live-PostgreSQL catalog access for the `--against-db` checks.
2//!
3//! A thin wrapper over a [`deadpool_postgres`] pool that answers the two
4//! questions the `validate --against-db` (#397) and `doctor --against-db`
5//! (#409) checks need:
6//!
7//! - **Function resolution / signature** — for a `sql_source` name, which overloads exist, what are
8//! their *input* argument types/names (in call order), and what columns does each return?
9//! (`resolve_functions`)
10//! - **PL/pgSQL body resolution** — does the `plpgsql_check` extension exist, and which managed
11//! functions call something the catalog can't resolve? (`plpgsql_check_available` /
12//! `plpgsql_check_unresolved_calls`)
13//!
14//! All catalog queries are PostgreSQL-specific (`pg_proc`, `pg_type`,
15//! `pg_attribute`, `plpgsql_check`); the surrounding logic in
16//! [`super::mutation_contract`] is database-agnostic and unit-tested without a
17//! connection.
18
19use anyhow::{Context, Result};
20use deadpool_postgres::{Config, ManagerConfig, Pool, RecyclingMethod, Runtime};
21use tokio_postgres::NoTls;
22
23/// A single output column of a PostgreSQL function's result row.
24///
25/// Populated from either the `OUT`/`TABLE` parameters of a `RETURNS TABLE(…)`
26/// function or the attributes of a composite `RETURNS <type>` — both are how
27/// FraiseQL mutation functions declare the row the server decodes into
28/// `MutationResponse`.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct OutColumn {
31 /// Column name as it appears in the result row (matched against the
32 /// `MutationResponse` field names).
33 pub name: String,
34 /// `format_type` rendering of the column type (e.g. `"boolean"`,
35 /// `"jsonb"`, `"text[]"`, `"app.mutation_error_class"`).
36 pub type_name: String,
37 /// Whether the column type is a PostgreSQL `enum` (`pg_type.typtype = 'e'`).
38 /// Mutation functions legitimately type `error_class` as either `text` or a
39 /// project-specific enum, so the contract check accepts both.
40 pub is_enum: bool,
41}
42
43/// One overload of a PostgreSQL function, reduced to what the mutation-contract
44/// check needs: the *input* arguments (in positional call order, excluding
45/// `OUT`/`TABLE` columns) and the output columns.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct PgFunction {
48 /// Schema the function lives in.
49 pub schema: String,
50 /// Function name (unqualified).
51 pub name: String,
52 /// Input argument types in call order (`format_type`), modes `IN`/`INOUT`/
53 /// `VARIADIC` only — these are the positions the server binds.
54 pub in_types: Vec<String>,
55 /// Input argument names in call order; `None` for unnamed positions.
56 pub in_names: Vec<Option<String>>,
57 /// Output columns of the result row (see [`OutColumn`]). Empty when the
58 /// function returns a scalar / `record` the catalog cannot expand.
59 pub out_columns: Vec<OutColumn>,
60 /// Whether the function returns a set (`RETURNS SETOF …` / `RETURNS
61 /// TABLE(…)`). Informational only.
62 pub returns_set: bool,
63}
64
65/// A single unresolved internal call surfaced by `plpgsql_check` (#409).
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct BodyError {
68 /// Calling function, rendered as `schema.fn(argtypes)` (`regprocedure`).
69 pub caller: String,
70 /// Line number within the function body, when reported.
71 pub lineno: Option<i32>,
72 /// The `plpgsql_check` diagnostic message.
73 pub message: String,
74}
75
76/// A single live column of a table, as the change-log contract drift check
77/// (#380) reads it from `information_schema.columns`.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct LiveColumn {
80 /// Column name (`information_schema.columns.column_name`).
81 pub name: String,
82 /// PostgreSQL base type (`information_schema.columns.udt_name`): the
83 /// lower-case underlying type, e.g. `"uuid"`, `"int8"`, `"text"`, `"jsonb"`,
84 /// `"timestamptz"`, `"_text"` (the element form of `text[]`). Compared
85 /// against [`fraiseql_observers::migrations::ContractColumn::udt`].
86 pub udt_name: String,
87}
88
89/// Outcome of the PL/pgSQL body-resolution pass.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum PlpgsqlCheckOutcome {
92 /// `plpgsql_check` is not available on this server — the pass was skipped.
93 Unavailable,
94 /// The pass ran; `errors` is empty when every internal call resolved.
95 Ran {
96 /// Unresolved internal calls found.
97 errors: Vec<BodyError>,
98 },
99}
100
101/// A live PostgreSQL connection pool for catalog introspection.
102pub struct PgCatalog {
103 pool: Pool,
104}
105
106impl PgCatalog {
107 /// Connect to `db_url` (PostgreSQL only) for catalog introspection.
108 ///
109 /// # Errors
110 ///
111 /// Returns an error if `db_url` is not a `postgres://` URL or the pool
112 /// cannot be created. (Connection failures surface lazily on first query.)
113 pub fn connect(db_url: &str) -> Result<Self> {
114 if !db_url.starts_with("postgres") {
115 anyhow::bail!(
116 "--against-db requires a PostgreSQL connection URL (postgres://…); got: {db_url}"
117 );
118 }
119 let mut cfg = Config::new();
120 cfg.url = Some(db_url.to_string());
121 cfg.manager = Some(ManagerConfig {
122 recycling_method: RecyclingMethod::Fast,
123 });
124 cfg.pool = Some(deadpool_postgres::PoolConfig::new(2));
125 let pool = cfg
126 .create_pool(Some(Runtime::Tokio1), NoTls)
127 .context("failed to create PostgreSQL connection pool for --against-db")?;
128 Ok(Self { pool })
129 }
130
131 /// Resolve all overloads of a (possibly schema-qualified) function name.
132 ///
133 /// Unqualified names resolve against the connection's `search_path`
134 /// (`current_schemas(false)`), mirroring how the runtime resolves an
135 /// unqualified `sql_source`. Matching is case-sensitive — the runtime quotes
136 /// each identifier component, so `proname` is compared verbatim.
137 ///
138 /// Returns an empty vec when no function of that name is visible.
139 ///
140 /// # Errors
141 ///
142 /// Returns an error if the connection or any catalog query fails.
143 pub async fn resolve_functions(&self, sql_source: &str) -> Result<Vec<PgFunction>> {
144 // One row per overload: input-arg types/names (modes IN/INOUT/VARIADIC
145 // only — OUT/TABLE columns are excluded so the count matches what the
146 // server binds positionally) plus oid + proretset for follow-up.
147 const BASE: &str = "\
148 SELECT p.oid, n.nspname, p.proname, p.proretset, \
149 COALESCE((SELECT array_agg(format_type(t, NULL) ORDER BY ord) \
150 FROM unnest(COALESCE(p.proallargtypes, p.proargtypes::oid[])) \
151 WITH ORDINALITY AS a(t, ord) \
152 LEFT JOIN unnest(p.proargmodes) WITH ORDINALITY AS m(mode, mord) ON mord = ord \
153 WHERE COALESCE(m.mode, 'i') IN ('i','b','v')), ARRAY[]::text[]) AS in_types, \
154 COALESCE((SELECT array_agg(COALESCE(nm, '') ORDER BY ord) \
155 FROM unnest(COALESCE(p.proallargtypes, p.proargtypes::oid[])) \
156 WITH ORDINALITY AS a(t, ord) \
157 LEFT JOIN unnest(p.proargmodes) WITH ORDINALITY AS m(mode, mord) ON mord = ord \
158 LEFT JOIN unnest(p.proargnames) WITH ORDINALITY AS nmt(nm, nord) ON nord = ord \
159 WHERE COALESCE(m.mode, 'i') IN ('i','b','v')), ARRAY[]::text[]) AS in_names \
160 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace ";
161
162 let client = self.pool.get().await.context("failed to acquire DB connection")?;
163 let (schema, name) = split_qualified(sql_source);
164
165 let rows = if let Some(schema) = schema {
166 client
167 .query(
168 &format!("{BASE} WHERE n.nspname = $1 AND p.proname = $2"),
169 &[&schema, &name],
170 )
171 .await
172 } else {
173 client
174 .query(
175 &format!(
176 "{BASE} WHERE p.proname = $1 AND n.nspname = ANY(current_schemas(false))"
177 ),
178 &[&name],
179 )
180 .await
181 }
182 .context("failed to query pg_proc for function resolution")?;
183
184 let mut functions = Vec::with_capacity(rows.len());
185 for row in rows {
186 let oid: u32 = row.get("oid");
187 let in_names: Vec<String> = row.get("in_names");
188 functions.push(PgFunction {
189 schema: row.get("nspname"),
190 name: row.get("proname"),
191 in_types: row.get("in_types"),
192 in_names: in_names
193 .into_iter()
194 .map(|n| if n.is_empty() { None } else { Some(n) })
195 .collect(),
196 out_columns: self.out_columns(oid).await?,
197 returns_set: row.get("proretset"),
198 });
199 }
200 Ok(functions)
201 }
202
203 /// Output columns of one function (by oid).
204 ///
205 /// Tries the `OUT`/`TABLE` parameter path first (`RETURNS TABLE(…)`); if the
206 /// function has none, falls back to the attributes of a composite return
207 /// type (`RETURNS <composite>` / `RETURNS SETOF <composite>`). A scalar or
208 /// bare-`record` return yields an empty vec.
209 async fn out_columns(&self, oid: u32) -> Result<Vec<OutColumn>> {
210 let client = self.pool.get().await.context("failed to acquire DB connection")?;
211
212 // Path 1: OUT/TABLE output parameters.
213 let table_rows = client
214 .query(
215 "SELECT COALESCE(nm, '') AS name, format_type(t, NULL) AS type_name, \
216 (tt.typtype = 'e') AS is_enum \
217 FROM pg_proc p, \
218 unnest(p.proallargtypes) WITH ORDINALITY AS a(t, ord) \
219 JOIN unnest(p.proargmodes) WITH ORDINALITY AS m(mode, mord) ON mord = ord \
220 LEFT JOIN unnest(p.proargnames) WITH ORDINALITY AS nmt(nm, nord) ON nord = ord \
221 JOIN pg_type tt ON tt.oid = t \
222 WHERE p.oid = $1 AND m.mode IN ('o','b','t') ORDER BY ord",
223 &[&oid],
224 )
225 .await
226 .context("failed to query OUT/TABLE result columns")?;
227 if !table_rows.is_empty() {
228 return Ok(table_rows.iter().map(row_to_out_column).collect());
229 }
230
231 // Path 2: composite return type attributes.
232 let comp_rows = client
233 .query(
234 "SELECT att.attname AS name, \
235 format_type(att.atttypid, att.atttypmod) AS type_name, \
236 (at.typtype = 'e') AS is_enum \
237 FROM pg_proc p \
238 JOIN pg_type rt ON rt.oid = p.prorettype \
239 JOIN pg_attribute att ON att.attrelid = rt.typrelid \
240 AND att.attnum > 0 AND NOT att.attisdropped \
241 JOIN pg_type at ON at.oid = att.atttypid \
242 WHERE p.oid = $1 ORDER BY att.attnum",
243 &[&oid],
244 )
245 .await
246 .context("failed to query composite result columns")?;
247 Ok(comp_rows.iter().map(row_to_out_column).collect())
248 }
249
250 /// Whether the `plpgsql_check` extension is installable (present in
251 /// `pg_available_extensions`).
252 ///
253 /// # Errors
254 ///
255 /// Returns an error if the catalog query fails.
256 pub async fn plpgsql_check_available(&self) -> Result<bool> {
257 let client = self.pool.get().await.context("failed to acquire DB connection")?;
258 let row = client
259 .query_one(
260 "SELECT EXISTS(SELECT 1 FROM pg_available_extensions WHERE name = 'plpgsql_check')",
261 &[],
262 )
263 .await
264 .context("failed to probe for the plpgsql_check extension")?;
265 Ok(row.get(0))
266 }
267
268 /// Run the PL/pgSQL body-resolution pass over `schemas` and return every
269 /// unresolved internal call (#409).
270 ///
271 /// Skips gracefully when `plpgsql_check` is unavailable
272 /// ([`PlpgsqlCheckOutcome::Unavailable`]). Trigger functions are excluded
273 /// (they need a relation OID to analyse), and only `error`-level
274 /// `function … does not exist` diagnostics are reported — warnings and
275 /// runtime-only temp-table references are not contract breakage.
276 ///
277 /// # Errors
278 ///
279 /// Returns an error if `CREATE EXTENSION` or the analysis query fails (e.g.
280 /// insufficient privileges to create the extension).
281 pub async fn plpgsql_check_unresolved_calls(
282 &self,
283 schemas: &[String],
284 ) -> Result<PlpgsqlCheckOutcome> {
285 if !self.plpgsql_check_available().await? {
286 return Ok(PlpgsqlCheckOutcome::Unavailable);
287 }
288 let client = self.pool.get().await.context("failed to acquire DB connection")?;
289 client
290 .batch_execute("CREATE EXTENSION IF NOT EXISTS plpgsql_check")
291 .await
292 .context("failed to CREATE EXTENSION plpgsql_check")?;
293
294 let rows = client
295 .query(
296 "SELECT (p.oid::regprocedure)::text AS caller, t.lineno, t.message \
297 FROM pg_proc p \
298 JOIN pg_namespace n ON n.oid = p.pronamespace \
299 JOIN pg_language l ON l.oid = p.prolang AND l.lanname = 'plpgsql' \
300 CROSS JOIN LATERAL plpgsql_check_function_tb(p.oid, fatal_errors := false) t \
301 WHERE n.nspname = ANY($1) \
302 AND p.prorettype <> 'trigger'::regtype \
303 AND t.level = 'error' \
304 AND t.message ~* 'function .* does not exist' \
305 ORDER BY 1, 2",
306 &[&schemas],
307 )
308 .await
309 .context("failed to run the plpgsql_check body-resolution pass")?;
310
311 let errors = rows
312 .iter()
313 .map(|row| BodyError {
314 caller: row.get("caller"),
315 lineno: row.get("lineno"),
316 message: row.get("message"),
317 })
318 .collect();
319 Ok(PlpgsqlCheckOutcome::Ran { errors })
320 }
321
322 /// Read the columns of `schema.table` from `information_schema.columns`
323 /// (name + `udt_name`), in declaration order.
324 ///
325 /// Returns an **empty** vec when the table does not exist (or is invisible to
326 /// the connecting role) — the change-log contract drift check (#380) reads
327 /// that as "table absent, the migration will install it" rather than an
328 /// error.
329 ///
330 /// # Errors
331 ///
332 /// Returns an error if the connection or the catalog query fails.
333 pub async fn table_columns(&self, schema: &str, table: &str) -> Result<Vec<LiveColumn>> {
334 let client = self.pool.get().await.context("failed to acquire DB connection")?;
335 let rows = client
336 .query(
337 "SELECT column_name, udt_name FROM information_schema.columns \
338 WHERE table_schema = $1 AND table_name = $2 ORDER BY ordinal_position",
339 &[&schema, &table],
340 )
341 .await
342 .context("failed to query information_schema.columns")?;
343 Ok(rows
344 .iter()
345 .map(|row| LiveColumn {
346 name: row.get("column_name"),
347 udt_name: row.get("udt_name"),
348 })
349 .collect())
350 }
351}
352
353/// Build an [`OutColumn`] from a `(name, type_name, is_enum)` catalog row.
354fn row_to_out_column(row: &tokio_postgres::Row) -> OutColumn {
355 OutColumn {
356 name: row.get("name"),
357 type_name: row.get("type_name"),
358 is_enum: row.get("is_enum"),
359 }
360}
361
362/// Split a possibly schema-qualified function name into `(schema, name)`.
363///
364/// Mirrors the runtime's identifier handling: an unqualified name (no `.`)
365/// resolves via `search_path`; a `schema.fn` name pins the schema. Split on the
366/// first `.` so `schema.fn` → `(Some("schema"), "fn")`.
367fn split_qualified(sql_source: &str) -> (Option<String>, String) {
368 match sql_source.split_once('.') {
369 Some((schema, name)) => (Some(schema.to_string()), name.to_string()),
370 None => (None, sql_source.to_string()),
371 }
372}