Skip to main content

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    /// Implementation language (`pg_language.lanname`, e.g. `plpgsql`, `sql`,
64    /// `c`). The payload-key consumption scan (#384) only reads `plpgsql`/`sql`
65    /// bodies — for other languages `source` is a symbol, not scannable text.
66    pub language:    String,
67    /// Function body (`pg_proc.prosrc`). For `plpgsql`/`sql` functions this is
68    /// the actual source text.
69    pub source:      String,
70}
71
72/// A single unresolved internal call surfaced by `plpgsql_check` (#409).
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct BodyError {
75    /// Calling function, rendered as `schema.fn(argtypes)` (`regprocedure`).
76    pub caller:  String,
77    /// Line number within the function body, when reported.
78    pub lineno:  Option<i32>,
79    /// The `plpgsql_check` diagnostic message.
80    pub message: String,
81}
82
83/// A single live column of a table, as the change-log contract drift check
84/// (#380) reads it from `information_schema.columns`.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct LiveColumn {
87    /// Column name (`information_schema.columns.column_name`).
88    pub name:     String,
89    /// `PostgreSQL` base type (`information_schema.columns.udt_name`): the
90    /// lower-case underlying type, e.g. `"uuid"`, `"int8"`, `"text"`, `"jsonb"`,
91    /// `"timestamptz"`, `"_text"` (the element form of `text[]`). Compared
92    /// against [`fraiseql_observers::migrations::ContractColumn::udt`].
93    pub udt_name: String,
94}
95
96/// Outcome of the PL/pgSQL body-resolution pass.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum PlpgsqlCheckOutcome {
99    /// `plpgsql_check` is not available on this server — the pass was skipped.
100    Unavailable,
101    /// The pass ran; `errors` is empty when every internal call resolved.
102    Ran {
103        /// Unresolved internal calls found.
104        errors: Vec<BodyError>,
105    },
106}
107
108/// Live Row-Level Security posture of `core.tb_entity_change_log` and whether the
109/// connecting role can read it under that posture (for the `fraiseql doctor`
110/// change-log RLS check, #437 F6 / #443).
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct ChangeLogRlsStatus {
113    /// Whether `ENABLE ROW LEVEL SECURITY` is active on the table.
114    pub rls_enabled: bool,
115    /// Whether the connecting role bypasses RLS (`BYPASSRLS` or superuser).
116    pub can_bypass:  bool,
117    /// Whether the connecting role owns the table (owners are exempt under `ENABLE`).
118    pub is_owner:    bool,
119    /// The connecting role name (for the diagnostic message).
120    pub role_name:   String,
121}
122
123/// PUBLIC-held privileges on one change-log relation, for the `fraiseql doctor`
124/// least-privilege check (#443).
125///
126/// Migration 12 `REVOKE ALL … FROM PUBLIC` keeps the change-log — every tenant's
127/// before/after payload — off the world-readable `PUBLIC` pseudo-role; a non-empty
128/// `privileges` means that REVOKE is not in force and the relation is
129/// world-accessible.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct PublicGrant {
132    /// Relation name (`tb_entity_change_log` / `v_entity_change_log` /
133    /// `v_entity_change_log_debezium`).
134    pub relname:    String,
135    /// Privilege types currently granted to PUBLIC (e.g. `["SELECT"]`); empty when
136    /// the least-privilege baseline is intact.
137    pub privileges: Vec<String>,
138}
139
140/// Live actor-attribution posture of `core.tb_entity_change_log` for the
141/// `fraiseql doctor` actor check (#390).
142///
143/// The actor model stamps every mutation-runner write with a canonical
144/// [`fraiseql_core::security::ActorType`] token; migration 08's
145/// `chk_entity_change_log_actor_type` refuses anything else on new writes. This
146/// introspection reports what the *live* table actually holds, so the doctor can
147/// surface pre-constraint rogue values and unattributed rows.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct ChangeLogActorStats {
150    /// Rows whose `actor_type` is NULL — pre-actor-model rows, or writes made
151    /// without an authenticated security context.
152    pub null_rows:            i64,
153    /// Distinct non-NULL `actor_type` values outside the canonical token set —
154    /// evidence of a rogue writer (only possible before the CHECK constraint, or
155    /// while it is missing).
156    pub unknown_values:       Vec<String>,
157    /// Whether `chk_entity_change_log_actor_type` is installed on the table.
158    pub constraint_installed: bool,
159}
160
161/// Security posture of `core.fn_entity_change_log_capture()` for the
162/// `fraiseql doctor` capture-function check (#443 / #437 F6).
163///
164/// The external-write capture function must be `SECURITY DEFINER` (so it runs as
165/// the table owner, exempt under change-log RLS) **with a pinned `search_path`** (a
166/// DEFINER function with a mutable `search_path` is a privilege-escalation vector).
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct CaptureFnSecurity {
169    /// Whether the function is `SECURITY DEFINER` (`pg_proc.prosecdef`).
170    pub security_definer: bool,
171    /// The pinned `search_path` value from `pg_proc.proconfig` (the text after
172    /// `search_path=`), or `None` when no `search_path` is pinned.
173    pub search_path:      Option<String>,
174}
175
176/// Result of auditing `sql_source` views for the `security_invoker` requirement.
177#[derive(Debug)]
178pub struct SecurityInvokerAudit {
179    /// Whether any RLS policy exists in the database (RLS is in use at all).
180    pub rls_in_use:            bool,
181    /// The audited views (by bare relname) that are NOT `security_invoker`.
182    pub views_without_invoker: Vec<String>,
183}
184
185/// A live `PostgreSQL` connection pool for catalog introspection.
186pub struct PgCatalog {
187    pool: Pool,
188}
189
190impl PgCatalog {
191    /// Connect to `db_url` (`PostgreSQL` only) for catalog introspection.
192    ///
193    /// # Errors
194    ///
195    /// Returns an error if `db_url` is not a `postgres://` URL or the pool
196    /// cannot be created. (Connection failures surface lazily on first query.)
197    pub fn connect(db_url: &str) -> Result<Self> {
198        if !db_url.starts_with("postgres") {
199            anyhow::bail!(
200                "--against-db requires a PostgreSQL connection URL (postgres://…); got: {db_url}"
201            );
202        }
203        let mut cfg = Config::new();
204        cfg.url = Some(db_url.to_string());
205        cfg.manager = Some(ManagerConfig {
206            recycling_method: RecyclingMethod::Fast,
207        });
208        cfg.pool = Some(deadpool_postgres::PoolConfig::new(2));
209        let pool = cfg
210            .create_pool(Some(Runtime::Tokio1), NoTls)
211            .context("failed to create PostgreSQL connection pool for --against-db")?;
212        Ok(Self { pool })
213    }
214
215    /// Resolve all overloads of a (possibly schema-qualified) function name.
216    ///
217    /// Unqualified names resolve against the connection's `search_path`
218    /// (`current_schemas(false)`), mirroring how the runtime resolves an
219    /// unqualified `sql_source`. Matching is case-sensitive — the runtime quotes
220    /// each identifier component, so `proname` is compared verbatim.
221    ///
222    /// Returns an empty vec when no function of that name is visible.
223    ///
224    /// # Errors
225    ///
226    /// Returns an error if the connection or any catalog query fails.
227    pub async fn resolve_functions(&self, sql_source: &str) -> Result<Vec<PgFunction>> {
228        // One row per overload: input-arg types/names (modes IN/INOUT/VARIADIC
229        // only — OUT/TABLE columns are excluded so the count matches what the
230        // server binds positionally) plus oid + proretset for follow-up.
231        const BASE: &str = "\
232            SELECT p.oid, n.nspname, p.proname, p.proretset, \
233              l.lanname, COALESCE(p.prosrc, '') AS prosrc, \
234              COALESCE((SELECT array_agg(format_type(t, NULL) ORDER BY ord) \
235                FROM unnest(COALESCE(p.proallargtypes, p.proargtypes::oid[])) \
236                  WITH ORDINALITY AS a(t, ord) \
237                LEFT JOIN unnest(p.proargmodes) WITH ORDINALITY AS m(mode, mord) ON mord = ord \
238                WHERE COALESCE(m.mode, 'i') IN ('i','b','v')), ARRAY[]::text[]) AS in_types, \
239              COALESCE((SELECT array_agg(COALESCE(nm, '') ORDER BY ord) \
240                FROM unnest(COALESCE(p.proallargtypes, p.proargtypes::oid[])) \
241                  WITH ORDINALITY AS a(t, ord) \
242                LEFT JOIN unnest(p.proargmodes) WITH ORDINALITY AS m(mode, mord) ON mord = ord \
243                LEFT JOIN unnest(p.proargnames) WITH ORDINALITY AS nmt(nm, nord) ON nord = ord \
244                WHERE COALESCE(m.mode, 'i') IN ('i','b','v')), ARRAY[]::text[]) AS in_names \
245            FROM pg_proc p \
246              JOIN pg_namespace n ON n.oid = p.pronamespace \
247              JOIN pg_language l ON l.oid = p.prolang ";
248
249        let client = self.pool.get().await.context("failed to acquire DB connection")?;
250        let (schema, name) = split_qualified(sql_source);
251
252        let rows = if let Some(schema) = schema {
253            client
254                .query(
255                    &format!("{BASE} WHERE n.nspname = $1 AND p.proname = $2"),
256                    &[&schema, &name],
257                )
258                .await
259        } else {
260            client
261                .query(
262                    &format!(
263                        "{BASE} WHERE p.proname = $1 AND n.nspname = ANY(current_schemas(false))"
264                    ),
265                    &[&name],
266                )
267                .await
268        }
269        .context("failed to query pg_proc for function resolution")?;
270
271        let mut functions = Vec::with_capacity(rows.len());
272        for row in rows {
273            let oid: u32 = row.get("oid");
274            let in_names: Vec<String> = row.get("in_names");
275            functions.push(PgFunction {
276                schema:      row.get("nspname"),
277                name:        row.get("proname"),
278                in_types:    row.get("in_types"),
279                in_names:    in_names
280                    .into_iter()
281                    .map(|n| if n.is_empty() { None } else { Some(n) })
282                    .collect(),
283                out_columns: self.out_columns(oid).await?,
284                returns_set: row.get("proretset"),
285                language:    row.get("lanname"),
286                source:      row.get("prosrc"),
287            });
288        }
289        Ok(functions)
290    }
291
292    /// Output columns of one function (by oid).
293    ///
294    /// Tries the `OUT`/`TABLE` parameter path first (`RETURNS TABLE(…)`); if the
295    /// function has none, falls back to the attributes of a composite return
296    /// type (`RETURNS <composite>` / `RETURNS SETOF <composite>`). A scalar or
297    /// bare-`record` return yields an empty vec.
298    async fn out_columns(&self, oid: u32) -> Result<Vec<OutColumn>> {
299        let client = self.pool.get().await.context("failed to acquire DB connection")?;
300
301        // Path 1: OUT/TABLE output parameters.
302        let table_rows = client
303            .query(
304                "SELECT COALESCE(nm, '') AS name, format_type(t, NULL) AS type_name, \
305                   (tt.typtype = 'e') AS is_enum \
306                 FROM pg_proc p, \
307                   unnest(p.proallargtypes) WITH ORDINALITY AS a(t, ord) \
308                   JOIN unnest(p.proargmodes) WITH ORDINALITY AS m(mode, mord) ON mord = ord \
309                   LEFT JOIN unnest(p.proargnames) WITH ORDINALITY AS nmt(nm, nord) ON nord = ord \
310                   JOIN pg_type tt ON tt.oid = t \
311                 WHERE p.oid = $1 AND m.mode IN ('o','b','t') ORDER BY ord",
312                &[&oid],
313            )
314            .await
315            .context("failed to query OUT/TABLE result columns")?;
316        if !table_rows.is_empty() {
317            return Ok(table_rows.iter().map(row_to_out_column).collect());
318        }
319
320        // Path 2: composite return type attributes.
321        let comp_rows = client
322            .query(
323                "SELECT att.attname AS name, \
324                   format_type(att.atttypid, att.atttypmod) AS type_name, \
325                   (at.typtype = 'e') AS is_enum \
326                 FROM pg_proc p \
327                   JOIN pg_type rt ON rt.oid = p.prorettype \
328                   JOIN pg_attribute att ON att.attrelid = rt.typrelid \
329                     AND att.attnum > 0 AND NOT att.attisdropped \
330                   JOIN pg_type at ON at.oid = att.atttypid \
331                 WHERE p.oid = $1 ORDER BY att.attnum",
332                &[&oid],
333            )
334            .await
335            .context("failed to query composite result columns")?;
336        Ok(comp_rows.iter().map(row_to_out_column).collect())
337    }
338
339    /// Whether the `plpgsql_check` extension is installable (present in
340    /// `pg_available_extensions`).
341    ///
342    /// # Errors
343    ///
344    /// Returns an error if the catalog query fails.
345    pub async fn plpgsql_check_available(&self) -> Result<bool> {
346        let client = self.pool.get().await.context("failed to acquire DB connection")?;
347        let row = client
348            .query_one(
349                "SELECT EXISTS(SELECT 1 FROM pg_available_extensions WHERE name = 'plpgsql_check')",
350                &[],
351            )
352            .await
353            .context("failed to probe for the plpgsql_check extension")?;
354        Ok(row.get(0))
355    }
356
357    /// Run the PL/pgSQL body-resolution pass over `schemas` and return every
358    /// unresolved internal call (#409).
359    ///
360    /// Skips gracefully when `plpgsql_check` is unavailable
361    /// ([`PlpgsqlCheckOutcome::Unavailable`]). Trigger functions are excluded
362    /// (they need a relation OID to analyse), and only `error`-level
363    /// `function … does not exist` diagnostics are reported — warnings and
364    /// runtime-only temp-table references are not contract breakage.
365    ///
366    /// # Errors
367    ///
368    /// Returns an error if `CREATE EXTENSION` or the analysis query fails (e.g.
369    /// insufficient privileges to create the extension).
370    pub async fn plpgsql_check_unresolved_calls(
371        &self,
372        schemas: &[String],
373    ) -> Result<PlpgsqlCheckOutcome> {
374        if !self.plpgsql_check_available().await? {
375            return Ok(PlpgsqlCheckOutcome::Unavailable);
376        }
377        let client = self.pool.get().await.context("failed to acquire DB connection")?;
378        client
379            .batch_execute("CREATE EXTENSION IF NOT EXISTS plpgsql_check")
380            .await
381            .context("failed to CREATE EXTENSION plpgsql_check")?;
382
383        let rows = client
384            .query(
385                "SELECT (p.oid::regprocedure)::text AS caller, t.lineno, t.message \
386                 FROM pg_proc p \
387                   JOIN pg_namespace n ON n.oid = p.pronamespace \
388                   JOIN pg_language  l ON l.oid = p.prolang AND l.lanname = 'plpgsql' \
389                   CROSS JOIN LATERAL plpgsql_check_function_tb(p.oid, fatal_errors := false) t \
390                 WHERE n.nspname = ANY($1) \
391                   AND p.prorettype <> 'trigger'::regtype \
392                   AND t.level = 'error' \
393                   AND t.message ~* 'function .* does not exist' \
394                 ORDER BY 1, 2",
395                &[&schemas],
396            )
397            .await
398            .context("failed to run the plpgsql_check body-resolution pass")?;
399
400        let errors = rows
401            .iter()
402            .map(|row| BodyError {
403                caller:  row.get("caller"),
404                lineno:  row.get("lineno"),
405                message: row.get("message"),
406            })
407            .collect();
408        Ok(PlpgsqlCheckOutcome::Ran { errors })
409    }
410
411    /// Read the columns of `schema.table` from `information_schema.columns`
412    /// (name + `udt_name`), in declaration order.
413    ///
414    /// Returns an **empty** vec when the table does not exist (or is invisible to
415    /// the connecting role) — the change-log contract drift check (#380) reads
416    /// that as "table absent, the migration will install it" rather than an
417    /// error.
418    ///
419    /// # Errors
420    ///
421    /// Returns an error if the connection or the catalog query fails.
422    pub async fn table_columns(&self, schema: &str, table: &str) -> Result<Vec<LiveColumn>> {
423        let client = self.pool.get().await.context("failed to acquire DB connection")?;
424        let rows = client
425            .query(
426                "SELECT column_name, udt_name FROM information_schema.columns \
427                 WHERE table_schema = $1 AND table_name = $2 ORDER BY ordinal_position",
428                &[&schema, &table],
429            )
430            .await
431            .context("failed to query information_schema.columns")?;
432        Ok(rows
433            .iter()
434            .map(|row| LiveColumn {
435                name:     row.get("column_name"),
436                udt_name: row.get("udt_name"),
437            })
438            .collect())
439    }
440
441    /// Read the live RLS posture of `core.tb_entity_change_log` and whether the
442    /// connecting role can read it under that posture (#437 F6 / #443).
443    ///
444    /// Returns `None` when the table is absent (or invisible to the connecting
445    /// role) — the doctor check reads that as "not present, skipped".
446    ///
447    /// # Errors
448    ///
449    /// Returns an error if the connection or the catalog query fails.
450    pub async fn change_log_rls_status(&self) -> Result<Option<ChangeLogRlsStatus>> {
451        let client = self.pool.get().await.context("failed to acquire DB connection")?;
452        let rows = client
453            .query(
454                "SELECT c.relrowsecurity AS rls_enabled, \
455                        (r.rolbypassrls OR r.rolsuper) AS can_bypass, \
456                        (pg_get_userbyid(c.relowner) = current_user) AS is_owner, \
457                        current_user::text AS role_name \
458                 FROM pg_class c \
459                   JOIN pg_namespace n ON n.oid = c.relnamespace \
460                   JOIN pg_roles r ON r.rolname = current_user \
461                 WHERE n.nspname = 'core' AND c.relname = 'tb_entity_change_log'",
462                &[],
463            )
464            .await
465            .context("failed to query change-log RLS status from pg_class/pg_roles")?;
466        Ok(rows.first().map(|row| ChangeLogRlsStatus {
467            rls_enabled: row.get("rls_enabled"),
468            can_bypass:  row.get("can_bypass"),
469            is_owner:    row.get("is_owner"),
470            role_name:   row.get("role_name"),
471        }))
472    }
473
474    /// Audit the given `sql_source` views (bare relnames) for `security_invoker`.
475    ///
476    /// A *default* view runs with the view owner's privileges and bypasses the
477    /// caller's RLS; only a `security_invoker` view (PG 15+) honours base-table RLS
478    /// — the requirement the cascade RLS boundary (and the query path) rely on.
479    /// Returns which audited views lack the option, plus whether any RLS policy
480    /// exists at all (the requirement only bites under RLS).
481    ///
482    /// # Errors
483    ///
484    /// Returns an error if the connection or a catalog query fails.
485    pub async fn security_invoker_audit(&self, views: &[String]) -> Result<SecurityInvokerAudit> {
486        let client = self.pool.get().await.context("failed to acquire DB connection")?;
487        let rls_in_use: bool = client
488            .query_one("SELECT EXISTS (SELECT 1 FROM pg_policies) AS in_use", &[])
489            .await
490            .context("failed to query pg_policies for RLS usage")?
491            .get("in_use");
492        let rows = client
493            .query(
494                "SELECT c.relname \
495                 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
496                 WHERE c.relkind = 'v' AND c.relname = ANY($1) \
497                   AND NOT EXISTS ( \
498                     SELECT 1 FROM pg_options_to_table(c.reloptions) o \
499                     WHERE o.option_name = 'security_invoker' \
500                       AND lower(o.option_value) IN ('true', 'on', '1'))",
501                &[&views],
502            )
503            .await
504            .context("failed to audit view security_invoker options from pg_class")?;
505        Ok(SecurityInvokerAudit {
506            rls_in_use,
507            views_without_invoker: rows.iter().map(|r| r.get::<_, String>("relname")).collect(),
508        })
509    }
510
511    /// Read the privileges granted to the `PUBLIC` pseudo-role on the three
512    /// change-log relations (the table + its two views) that exist in `core`
513    /// (#443).
514    ///
515    /// Returns one [`PublicGrant`] per *present* relation, listing the privileges
516    /// PUBLIC currently holds (empty when none). An empty vec means none of the
517    /// three relations exist — the doctor check reads that as "not present,
518    /// skipped". PUBLIC grants are read from `pg_class.relacl` via `aclexplode`
519    /// (the PUBLIC grantee has OID `0`); a `NULL` ACL (the default for a fresh
520    /// relation) explodes to no rows, i.e. PUBLIC holds nothing.
521    ///
522    /// # Errors
523    ///
524    /// Returns an error if the connection or the catalog query fails.
525    pub async fn change_log_public_grants(&self) -> Result<Vec<PublicGrant>> {
526        let client = self.pool.get().await.context("failed to acquire DB connection")?;
527        let rows = client
528            .query(
529                "SELECT c.relname, \
530                        COALESCE( \
531                          array_agg(DISTINCT a.privilege_type) FILTER (WHERE a.grantee = 0), \
532                          ARRAY[]::text[]) AS public_privs \
533                 FROM pg_class c \
534                   JOIN pg_namespace n ON n.oid = c.relnamespace \
535                   LEFT JOIN LATERAL aclexplode(c.relacl) a ON true \
536                 WHERE n.nspname = 'core' \
537                   AND c.relname IN ('tb_entity_change_log', 'v_entity_change_log', \
538                                     'v_entity_change_log_debezium') \
539                 GROUP BY c.relname \
540                 ORDER BY c.relname",
541                &[],
542            )
543            .await
544            .context("failed to query change-log PUBLIC grants from pg_class.relacl")?;
545        Ok(rows
546            .iter()
547            .map(|row| PublicGrant {
548                relname:    row.get("relname"),
549                privileges: row.get("public_privs"),
550            })
551            .collect())
552    }
553
554    /// Read the live actor-attribution posture of `core.tb_entity_change_log`
555    /// (#390): how many rows carry no `actor_type`, which out-of-contract values
556    /// exist, and whether the domain CHECK constraint is installed.
557    ///
558    /// `valid_tokens` is the canonical roster (built from
559    /// [`fraiseql_core::security::ActorType::ALL`] by the caller). Returns `None`
560    /// when the table is absent — the doctor check reads that as "not present,
561    /// skipped".
562    ///
563    /// # Errors
564    ///
565    /// Returns an error if the connection or a catalog query fails.
566    pub async fn change_log_actor_stats(
567        &self,
568        valid_tokens: &[String],
569    ) -> Result<Option<ChangeLogActorStats>> {
570        let client = self.pool.get().await.context("failed to acquire DB connection")?;
571        let table_exists: bool = client
572            .query_one(
573                "SELECT EXISTS (SELECT 1 FROM pg_class c \
574                   JOIN pg_namespace n ON n.oid = c.relnamespace \
575                 WHERE n.nspname = 'core' AND c.relname = 'tb_entity_change_log') AS present",
576                &[],
577            )
578            .await
579            .context("failed to check for core.tb_entity_change_log in pg_class")?
580            .get("present");
581        if !table_exists {
582            return Ok(None);
583        }
584
585        let row = client
586            .query_one(
587                "SELECT \
588                   (SELECT count(*) FROM core.tb_entity_change_log \
589                     WHERE actor_type IS NULL) AS null_rows, \
590                   (SELECT COALESCE(array_agg(DISTINCT actor_type ORDER BY actor_type), \
591                                    ARRAY[]::text[]) \
592                      FROM core.tb_entity_change_log \
593                     WHERE actor_type IS NOT NULL AND actor_type <> ALL($1)) AS unknown_values, \
594                   EXISTS (SELECT 1 FROM pg_constraint con \
595                             JOIN pg_class c ON c.oid = con.conrelid \
596                             JOIN pg_namespace n ON n.oid = c.relnamespace \
597                           WHERE n.nspname = 'core' AND c.relname = 'tb_entity_change_log' \
598                             AND con.conname = 'chk_entity_change_log_actor_type') \
599                     AS constraint_installed",
600                &[&valid_tokens],
601            )
602            .await
603            .context("failed to query change-log actor attribution stats")?;
604        Ok(Some(ChangeLogActorStats {
605            null_rows:            row.get("null_rows"),
606            unknown_values:       row.get("unknown_values"),
607            constraint_installed: row.get("constraint_installed"),
608        }))
609    }
610
611    /// Read the security posture of `core.fn_entity_change_log_capture()` (#443 /
612    /// #437 F6): whether it is `SECURITY DEFINER` (`pg_proc.prosecdef`) and the
613    /// pinned `search_path` from `pg_proc.proconfig`, if any.
614    ///
615    /// Returns `None` when the function is absent — the doctor check reads that as
616    /// "not present, skipped".
617    ///
618    /// # Errors
619    ///
620    /// Returns an error if the connection or the catalog query fails.
621    pub async fn capture_fn_security(&self) -> Result<Option<CaptureFnSecurity>> {
622        let client = self.pool.get().await.context("failed to acquire DB connection")?;
623        let rows = client
624            .query(
625                "SELECT p.prosecdef AS security_definer, \
626                        (SELECT cfg FROM unnest(p.proconfig) AS cfg \
627                          WHERE cfg LIKE 'search_path=%' LIMIT 1) AS search_path_cfg \
628                 FROM pg_proc p \
629                   JOIN pg_namespace n ON n.oid = p.pronamespace \
630                 WHERE n.nspname = 'core' AND p.proname = 'fn_entity_change_log_capture' \
631                 LIMIT 1",
632                &[],
633            )
634            .await
635            .context("failed to query capture-function security from pg_proc")?;
636        Ok(rows.first().map(|row| {
637            let raw: Option<String> = row.get("search_path_cfg");
638            CaptureFnSecurity {
639                security_definer: row.get("security_definer"),
640                search_path:      raw
641                    .map(|s| s.strip_prefix("search_path=").unwrap_or(&s).to_string()),
642            }
643        }))
644    }
645}
646
647/// Build an [`OutColumn`] from a `(name, type_name, is_enum)` catalog row.
648fn row_to_out_column(row: &tokio_postgres::Row) -> OutColumn {
649    OutColumn {
650        name:      row.get("name"),
651        type_name: row.get("type_name"),
652        is_enum:   row.get("is_enum"),
653    }
654}
655
656/// Split a possibly schema-qualified function name into `(schema, name)`.
657///
658/// Mirrors the runtime's identifier handling: an unqualified name (no `.`)
659/// resolves via `search_path`; a `schema.fn` name pins the schema. Split on the
660/// first `.` so `schema.fn` → `(Some("schema"), "fn")`.
661fn split_qualified(sql_source: &str) -> (Option<String>, String) {
662    match sql_source.split_once('.') {
663        Some((schema, name)) => (Some(schema.to_string()), name.to_string()),
664        None => (None, sql_source.to_string()),
665    }
666}