Skip to main content

schema_reverse_engineer/postgres/
constraints.rs

1use crate::error::SchemaReverseEngineerError;
2use schema_model::model::constraint::Constraint;
3use schema_model::model::types::DatabaseType;
4use sqlx::PgPool;
5use std::collections::{HashMap, HashSet};
6
7/// Check ('c') and exclusion ('x') constraints, grouped by owning table name.
8/// Primary key ('p') and unique ('u') constraints are intentionally excluded here since
9/// they are represented via table keys instead (see `keys.rs`).
10pub async fn list_constraints(
11    pool: &PgPool,
12    db_schema: &str,
13) -> Result<HashMap<String, Vec<Constraint>>, SchemaReverseEngineerError> {
14    let rows = raw_constraint_rows(pool, db_schema).await?;
15
16    let mut by_table: HashMap<String, Vec<Constraint>> = HashMap::new();
17    for row in rows {
18        by_table
19            .entry(row.table_name)
20            .or_default()
21            .push(Constraint::new(row.name, row.definition, DatabaseType::Postgresql));
22    }
23    Ok(by_table)
24}
25
26/// Names of exclusion constraints ('x'), keyed by (table_name, constraint_name), so that
27/// `keys.rs` can skip the unique index that merely backs an exclusion constraint.
28pub async fn list_exclusion_constraint_names(
29    pool: &PgPool,
30    db_schema: &str,
31) -> Result<HashSet<(String, String)>, SchemaReverseEngineerError> {
32    let rows = raw_constraint_rows(pool, db_schema).await?;
33    Ok(rows
34        .into_iter()
35        .filter(|r| r.contype == "x")
36        .map(|r| (r.table_name, r.name))
37        .collect())
38}
39
40#[derive(Debug, sqlx::FromRow)]
41struct ConstraintRow {
42    table_name: String,
43    name: String,
44    contype: String,
45    definition: String,
46}
47
48async fn raw_constraint_rows(pool: &PgPool, db_schema: &str) -> Result<Vec<ConstraintRow>, SchemaReverseEngineerError> {
49    sqlx::query_as::<_, ConstraintRow>(
50        "SELECT c.relname AS table_name, con.conname AS name, con.contype::text AS contype, \
51                pg_get_constraintdef(con.oid) AS definition \
52         FROM pg_constraint con \
53         JOIN pg_class c ON c.oid = con.conrelid \
54         JOIN pg_namespace n ON n.oid = c.relnamespace \
55         WHERE n.nspname = $1 AND con.contype IN ('x', 'c') \
56         ORDER BY c.relname, con.conname",
57    )
58    .bind(db_schema)
59    .fetch_all(pool)
60    .await
61    .map_err(|e| SchemaReverseEngineerError::Introspection(e.to_string()))
62}