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