Skip to main content

demesne_postgres/
lib.rs

1#![doc = "Live-database support for demesne: introspection into a `Schema`, the drift `diff` reports, the schema traps, the global-assignment audit and the RLS role check."]
2
3mod connect;
4mod drift;
5mod dsn;
6mod error;
7mod goerr;
8mod lint;
9
10pub use connect::connect;
11pub use drift::{Drift, DriftKind, Finding, drift};
12pub use dsn::parse_config_dump;
13pub use error::Error;
14pub use lint::{Severity, Trap, schema_traps};
15
16use demesne_model::{Nullability, Schema};
17use postgres::Client;
18use std::collections::BTreeSet;
19
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21pub struct IntrospectMeta {
22    pub tables: usize,
23    pub columns: usize,
24    pub fks: usize,
25}
26
27#[must_use]
28pub fn query_error(e: &postgres::Error) -> String {
29    if let Some(db) = e.as_db_error() {
30        return format!("{}: {} (SQLSTATE {})", db.severity(), db.message(), db.code().code());
31    }
32    let mut out = e.to_string();
33    let mut cur = std::error::Error::source(e);
34    while let Some(c) = cur {
35        out.push_str(": ");
36        out.push_str(&c.to_string());
37        cur = c.source();
38    }
39    out
40}
41
42/// Reads the `public` schema's tables, columns, keys and foreign keys.
43///
44/// # Errors
45///
46/// A catalog query fails.
47pub fn introspect(client: &mut Client) -> Result<(Schema, IntrospectMeta), Error> {
48    read_schema(client).map_err(Error::query)
49}
50
51fn read_schema(client: &mut Client) -> Result<(Schema, IntrospectMeta), String> {
52    let mut sc = Schema::new();
53    let mut meta = IntrospectMeta::default();
54    let mut tables = BTreeSet::new();
55    let rows = client
56        .query(
57            "SELECT table_name::text, column_name::text, data_type::text, (is_nullable = 'YES')
58             FROM information_schema.columns WHERE table_schema = 'public'",
59            &[],
60        )
61        .map_err(|e| query_error(&e))?;
62    for row in rows {
63        let (table, col, typ, nullable): (String, String, String, bool) = (row.get(0), row.get(1), row.get(2), row.get(3));
64        sc.add_column(&table, &col, &typ, if nullable { Nullability::Nullable } else { Nullability::NotNull });
65        meta.columns += 1;
66        tables.insert(table);
67    }
68    meta.tables = tables.len();
69    let fks = client
70        .query(
71            "SELECT tc.table_name::text, kcu.column_name::text, ccu.table_name::text, ccu.column_name::text
72             FROM information_schema.table_constraints tc
73             JOIN information_schema.key_column_usage kcu
74               ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
75             JOIN information_schema.constraint_column_usage ccu
76               ON tc.constraint_name = ccu.constraint_name
77             WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public'",
78            &[],
79        )
80        .map_err(|e| query_error(&e))?;
81    for row in fks {
82        let (table, col, ref_table, ref_col): (String, String, String, String) = (row.get(0), row.get(1), row.get(2), row.get(3));
83        sc.add_foreign_key(&table, &col, &ref_table, &ref_col);
84        meta.fks += 1;
85    }
86    Ok((sc, meta))
87}
88
89/// Returns whether `role` exists and, if it does, whether it bypasses row-level security.
90///
91/// # Errors
92///
93/// The catalog query fails.
94pub fn role_bypasses_rls(client: &mut Client, role: &str) -> Result<(bool, bool), Error> {
95    read_role_bypass(client, role).map_err(Error::query)
96}
97
98fn read_role_bypass(client: &mut Client, role: &str) -> Result<(bool, bool), String> {
99    let rows = client.query("SELECT rolbypassrls FROM pg_roles WHERE rolname = $1", &[&role]).map_err(|e| query_error(&e))?;
100    match rows.first() {
101        Some(row) => Ok((true, row.get(0))),
102        None => Ok((false, false)),
103    }
104}
105
106/// Counts the rows `query` returns.
107///
108/// # Errors
109///
110/// The query fails.
111pub fn count_global_assignments(client: &mut Client, query: &str) -> Result<i64, Error> {
112    read_global_assignments(client, query).map_err(Error::query)
113}
114
115fn read_global_assignments(client: &mut Client, query: &str) -> Result<i64, String> {
116    let row = client.query_one(&format!("SELECT count(*) FROM ({query}) q"), &[]).map_err(|e| query_error(&e))?;
117    Ok(row.get(0))
118}