Skip to main content

pgevolve_core/catalog/
mod.rs

1//! Catalog reader: live Postgres `pg_catalog` → [`crate::ir::catalog::Catalog`].
2//!
3//! The reader is split into:
4//!
5//! - [`CatalogQuerier`] — a sync, driver-agnostic trait. Adapters (the binary
6//!   uses `tokio-postgres`) execute parameterized SQL and return [`rows::Row`]
7//!   values.
8//! - Per-version SQL strings in [`queries`].
9//! - [`filter::CatalogFilter`] — managed-schema list + ignore globs.
10//! - [`read_catalog`] — top-level entry point that orchestrates the queries
11//!   and assembles their rows into IR.
12
13pub mod cluster;
14pub mod error;
15pub mod filter;
16pub mod queries;
17pub mod rows;
18pub mod version;
19
20pub use error::CatalogError;
21pub use filter::CatalogFilter;
22pub use rows::{Row, Value};
23pub use version::PgVersion;
24
25mod assemble;
26pub(crate) mod grants;
27pub(crate) mod publications;
28pub(crate) mod reloptions;
29pub(crate) mod subscriptions;
30
31use crate::identifier::{Identifier, QualifiedName};
32use crate::ir::catalog::Catalog;
33
34/// Drift detected between the canonical catalog IR and the live Postgres state.
35///
36/// The catalog reader always surfaces all constraints and indexes in the IR
37/// regardless of their validation state. This report captures the *extra*
38/// observation that some of them are in a transitional / incomplete state:
39/// - `pending_validation`: constraints with `pg_constraint.convalidated = false`
40///   (added `NOT VALID`, never validated).
41/// - `invalid_indexes`: indexes with `pg_index.indisvalid = false` (e.g., a
42///   `CREATE INDEX CONCURRENTLY` that failed and left an INVALID index).
43/// - `unmanaged_language_routines`: routines whose `LANGUAGE` is neither `sql`
44///   nor `plpgsql` (e.g., `plperl`, `python3u`). pgevolve v0.2 does not
45///   manage these; they are surfaced in the drift report so callers can
46///   inspect them. The associated row is skipped and never appears in
47///   `catalog.functions` / `catalog.procedures`.
48/// - `unreadable_subscriptions`: the connection used for the catalog read had
49///   insufficient privilege to query `pg_subscription` (sqlstate 42501). The
50///   subscription list in the returned catalog is empty; the operator must use
51///   a superuser connection to get subscription data.
52///
53/// The differ consumes this report and emits [`crate::diff::change::Change::ValidateConstraint`]
54/// and [`crate::diff::change::Change::RecreateIndex`] to recover automatically.
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct DriftReport {
57    /// Constraints present in the catalog but with `convalidated = false`.
58    /// Identified by `(table_qname, constraint_name)`.
59    pub pending_validation: Vec<(QualifiedName, Identifier)>,
60    /// Indexes present in the catalog but with `indisvalid = false`.
61    /// Identified by index qname.
62    pub invalid_indexes: Vec<QualifiedName>,
63    /// Routines whose `LANGUAGE` is not `sql` or `plpgsql`.
64    /// Identified by `(qname, language_name)`.
65    pub unmanaged_language_routines: Vec<(QualifiedName, String)>,
66    /// `pg_subscription` was unreadable due to insufficient privilege (sqlstate
67    /// 42501). `catalog.subscriptions` will be empty when this is `true`.
68    pub unreadable_subscriptions: bool,
69}
70
71/// Identifier for each catalog query the reader runs. Adapters dispatch on
72/// this enum to pick the per-version SQL string.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub enum CatalogQuery {
75    /// `SHOW server_version_num`.
76    PgVersion,
77    /// `pg_namespace` rows for managed schemas.
78    Schemas,
79    /// `pg_class` (relkind='r') for managed tables.
80    Tables,
81    /// `pg_attribute` joined with `pg_attrdef`/`pg_type` for managed tables.
82    Columns,
83    /// `pg_constraint` for managed tables (PK/UNIQUE/FK/CHECK).
84    Constraints,
85    /// `pg_index` for managed tables (excluding constraint-backing indexes).
86    Indexes,
87    /// `pg_class` (relkind='S') joined with `pg_sequence`.
88    Sequences,
89    /// `pg_description` (currently inlined into the per-object queries).
90    Comments,
91    /// `pg_depend` rows linking sequences to their owning columns.
92    Dependencies,
93    /// `pg_class` (relkind IN ('v','m')) joined with `pg_get_viewdef`.
94    ViewsAndMvs,
95    /// `pg_attribute` for view and materialized view columns.
96    ViewColumns,
97    /// `pg_type` filtered to `typtype IN ('e','d','c')` for user-defined types.
98    UserTypes,
99    /// `pg_enum` labels for enum types.
100    EnumValues,
101    /// Base-type and nullability details for domain types.
102    DomainDetails,
103    /// Named CHECK constraints attached to domain types.
104    DomainChecks,
105    /// Attributes (fields) of composite types.
106    CompositeAttributes,
107    /// `pg_proc` rows for functions and procedures (prokind IN 'f','p').
108    Functions,
109    /// `pg_extension` rows for installed extensions.
110    Extensions,
111    /// `pg_trigger` rows for user triggers (excluding internal + extension-owned).
112    Triggers,
113    /// `pg_class` (relkind='p') rows for partitioned-table parents.
114    PartitionedTables,
115    /// `pg_class` (relispartition=true) rows for child partitions.
116    Partitions,
117    /// `pg_authid` rows for cluster roles (with `pg_shdescription` for comments).
118    ///
119    /// Uses `$1::text[]` as the bootstrap-role filter (names to exclude), not a
120    /// managed-schema list. `takes_text_array_param` returns `true` so the adapter
121    /// passes the parameter; the cluster reader supplies bootstrap role names.
122    ClusterRoles,
123    /// `pg_auth_members` edges joined to `pg_authid` for role names.
124    ///
125    /// Same `$1::text[]` bootstrap-role filter as [`Self::ClusterRoles`].
126    ClusterMembers,
127    /// `pg_default_acl` rows joined to `pg_authid` and `pg_namespace`.
128    ///
129    /// Returns one row per (`target_role`, schema, `object_type`) tuple. Rows for
130    /// predefined `pg_*` roles are filtered out. Takes **no** `$1::text[]`
131    /// parameter; `takes_text_array_param` returns `false` for this variant.
132    DefaultPrivileges,
133    /// `pg_policies` rows for managed schemas.
134    ///
135    /// Returns one row per policy, scoped to `schemaname = ANY($1::text[])`.
136    /// Decoded into [`crate::ir::policy::Policy`] and attached to their
137    /// owning `Table` by the assembler. Policies on unmanaged tables are
138    /// silently dropped.
139    Policies,
140    /// `pg_publication` rows for all publications in the database.
141    ///
142    /// Publications are database-global (not schema-scoped); takes **no**
143    /// `$1::text[]` parameter (`takes_text_array_param` returns `false`).
144    Publications,
145    /// `pg_publication_rel` rows — one per (publication, table) membership.
146    ///
147    /// PG 15+ includes `prqual` (row filter) and `prattrs` (column list);
148    /// PG 14 variant substitutes `NULL` for both. Takes **no** parameter.
149    PublicationRel,
150    /// `pg_publication_namespace` rows — one per (publication, schema)
151    /// membership (PG 15+ only). PG 14 variant returns zero rows.
152    /// Takes **no** parameter.
153    PublicationNamespace,
154    /// `pg_attribute` rows for every column of every table referenced by
155    /// any publication. Used to resolve column attnums to names. Takes **no**
156    /// parameter.
157    PublicationAttributes,
158    /// `pg_subscription` rows for all subscriptions in the database.
159    ///
160    /// Subscriptions are database-global (not schema-scoped). Takes **no**
161    /// `$1::text[]` parameter (`takes_text_array_param` returns `false`).
162    ///
163    /// `pg_subscription` is superuser-readable only. Non-super connections
164    /// will receive an empty result or a permission error; the assembler
165    /// catches the error and sets `DriftReport::unreadable_subscriptions`.
166    Subscriptions,
167}
168
169impl CatalogQuery {
170    /// Whether this query accepts a `$1::text[]` argument.
171    ///
172    /// The semantic meaning of the array varies by variant: managed-schema
173    /// names for per-DB queries, bootstrap-role names for cluster queries.
174    /// The adapter is responsible for passing the right slice to the right
175    /// variant.
176    ///
177    /// A few variants (`PgVersion`, `Extensions`) take no parameters at all;
178    /// this method returns `false` for those.
179    #[must_use]
180    pub const fn takes_text_array_param(self) -> bool {
181        !matches!(
182            self,
183            Self::PgVersion
184                | Self::Extensions
185                | Self::DefaultPrivileges
186                | Self::Publications
187                | Self::PublicationRel
188                | Self::PublicationNamespace
189                | Self::PublicationAttributes
190                | Self::Subscriptions
191        )
192    }
193
194    // Note: `Policies` takes `$1::text[]` (managed schemas), so it is NOT in
195    // the exclusion list above — `takes_text_array_param` returns `true` for it.
196}
197
198/// Sync, driver-agnostic catalog query interface.
199///
200/// Interface implemented by callers (typically the binary) to execute catalog
201/// queries against a live database. Implementations are expected to be sync —
202/// async drivers can wrap their runtime in [`fetch`](Self::fetch).
203pub trait CatalogQuerier {
204    /// Execute the named query with the supplied `$1::text[]` parameter (when
205    /// applicable; see [`CatalogQuery::takes_text_array_param`]).
206    ///
207    /// The semantic meaning of `text_array_param` varies by variant:
208    /// managed-schema names for per-DB queries, bootstrap-role names for
209    /// cluster queries. Pass an empty slice for queries that take no parameter.
210    fn fetch(
211        &self,
212        query: CatalogQuery,
213        text_array_param: &[&str],
214    ) -> Result<Vec<Row>, CatalogError>;
215}
216
217/// Read every catalog query, assemble the IR, and canonicalize.
218///
219/// Returns a `(Catalog, DriftReport)` tuple. The catalog contains all objects
220/// including those in transitional states (NOT VALID constraints, INVALID
221/// indexes). The drift report captures which objects are in those states so the
222/// differ can emit recovery changes.
223pub fn read_catalog(
224    querier: &dyn CatalogQuerier,
225    filter: &CatalogFilter,
226) -> Result<(Catalog, DriftReport), CatalogError> {
227    let version = PgVersion::detect(querier)?;
228    let managed: Vec<&str> = filter.managed_schemas_param();
229
230    let schemas_rows = querier.fetch(CatalogQuery::Schemas, &managed)?;
231    let tables_rows = querier.fetch(CatalogQuery::Tables, &managed)?;
232    let columns_rows = querier.fetch(CatalogQuery::Columns, &managed)?;
233    let constraints_rows = querier.fetch(CatalogQuery::Constraints, &managed)?;
234    let indexes_rows = querier.fetch(CatalogQuery::Indexes, &managed)?;
235    let sequences_rows = querier.fetch(CatalogQuery::Sequences, &managed)?;
236    let dependencies_rows = querier.fetch(CatalogQuery::Dependencies, &managed)?;
237    let views_and_mvs_rows = querier.fetch(CatalogQuery::ViewsAndMvs, &managed)?;
238    let view_columns_rows = querier.fetch(CatalogQuery::ViewColumns, &managed)?;
239    let user_types_rows = querier.fetch(CatalogQuery::UserTypes, &managed)?;
240    let enum_values_rows = querier.fetch(CatalogQuery::EnumValues, &managed)?;
241    let domain_details_rows = querier.fetch(CatalogQuery::DomainDetails, &managed)?;
242    let domain_checks_rows = querier.fetch(CatalogQuery::DomainChecks, &managed)?;
243    let composite_attributes_rows = querier.fetch(CatalogQuery::CompositeAttributes, &managed)?;
244    let functions_rows = querier.fetch(CatalogQuery::Functions, &managed)?;
245    let extensions_rows = querier.fetch(CatalogQuery::Extensions, &managed)?;
246    let triggers_rows = querier.fetch(CatalogQuery::Triggers, &managed)?;
247    let partitioned_tables_rows = querier.fetch(CatalogQuery::PartitionedTables, &managed)?;
248    let partitions_rows = querier.fetch(CatalogQuery::Partitions, &managed)?;
249    let default_privileges_rows = querier.fetch(CatalogQuery::DefaultPrivileges, &[])?;
250    let policies_rows = querier.fetch(CatalogQuery::Policies, &managed)?;
251    let publications_rows = querier.fetch(CatalogQuery::Publications, &[])?;
252    let publication_rels_rows = querier.fetch(CatalogQuery::PublicationRel, &[])?;
253    let publication_namespaces_rows = querier.fetch(CatalogQuery::PublicationNamespace, &[])?;
254    let publication_attributes_rows = querier.fetch(CatalogQuery::PublicationAttributes, &[])?;
255
256    // `pg_subscription` is superuser-only. If the querier returns a
257    // `QueryFailed` error whose message contains the PG sqlstate 42501
258    // (insufficient_privilege), we silently return empty rows and record the
259    // gap in the drift report. Any other error is propagated normally.
260    let (subscriptions_rows, unreadable_subscriptions) =
261        match querier.fetch(CatalogQuery::Subscriptions, &[]) {
262            Ok(rows) => (rows, false),
263            Err(CatalogError::QueryFailed { message, .. })
264                if message.contains("42501") || message.contains("insufficient_privilege") =>
265            {
266                (vec![], true)
267            }
268            Err(e) => return Err(e),
269        };
270
271    let raw = assemble::RawRows {
272        version,
273        schemas: schemas_rows,
274        tables: tables_rows,
275        columns: columns_rows,
276        constraints: constraints_rows,
277        indexes: indexes_rows,
278        sequences: sequences_rows,
279        dependencies: dependencies_rows,
280        views_and_mvs: views_and_mvs_rows,
281        view_columns: view_columns_rows,
282        user_types: user_types_rows,
283        enum_values: enum_values_rows,
284        domain_details: domain_details_rows,
285        domain_checks: domain_checks_rows,
286        composite_attributes: composite_attributes_rows,
287        functions: functions_rows,
288        extensions: extensions_rows,
289        triggers: triggers_rows,
290        partitioned_tables: partitioned_tables_rows,
291        partitions: partitions_rows,
292        default_privileges: default_privileges_rows,
293        policies: policies_rows,
294        publications: publications_rows,
295        publication_rels: publication_rels_rows,
296        publication_namespaces: publication_namespaces_rows,
297        publication_attributes: publication_attributes_rows,
298        subscriptions: subscriptions_rows,
299    };
300    let (catalog, mut drift) = assemble::assemble(raw, filter)?;
301    drift.unreadable_subscriptions = unreadable_subscriptions;
302    Ok((catalog.canonicalize()?, drift))
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use std::cell::RefCell;
309    use std::collections::HashMap;
310
311    /// Mock querier that returns canned rows by query name.
312    struct MockQuerier {
313        rows: RefCell<HashMap<CatalogQuery, Vec<Row>>>,
314    }
315
316    impl MockQuerier {
317        fn new() -> Self {
318            Self {
319                rows: RefCell::new(HashMap::new()),
320            }
321        }
322        fn set(&self, q: CatalogQuery, rows: Vec<Row>) {
323            self.rows.borrow_mut().insert(q, rows);
324        }
325    }
326
327    impl CatalogQuerier for MockQuerier {
328        fn fetch(
329            &self,
330            q: CatalogQuery,
331            _text_array_param: &[&str],
332        ) -> Result<Vec<Row>, CatalogError> {
333            Ok(self.rows.borrow().get(&q).cloned().unwrap_or_default())
334        }
335    }
336
337    #[test]
338    fn empty_catalog_round_trips() {
339        let m = MockQuerier::new();
340        m.set(
341            CatalogQuery::PgVersion,
342            vec![Row::new().with("server_version_num", Value::Integer(160_000))],
343        );
344        let filter = CatalogFilter::new(vec![], vec![]).unwrap();
345        let (cat, drift) = read_catalog(&m, &filter).expect("reads");
346        assert!(cat.tables.is_empty());
347        assert!(cat.schemas.is_empty());
348        assert!(drift.pending_validation.is_empty());
349        assert!(drift.invalid_indexes.is_empty());
350    }
351}