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