schema_reverse_engineer/postgres/
relations.rs1use crate::error::SchemaReverseEngineerError;
2use schema_model::model::relation::Relation;
3use schema_model::model::types::RelationType;
4use sqlx::PgPool;
5use std::collections::HashMap;
6
7#[derive(Debug, sqlx::FromRow)]
8struct ForeignKeyRow {
9 from_table: String,
10 from_column: String,
11 to_table: String,
12 to_column: String,
13 delete_rule: String,
14}
15
16pub async fn list_foreign_keys(
25 pool: &PgPool,
26 db_schema: &str,
27) -> Result<HashMap<String, Vec<Relation>>, SchemaReverseEngineerError> {
28 let rows: Vec<ForeignKeyRow> = sqlx::query_as(
29 "SELECT tc.table_name AS from_table, fkcu.column_name AS from_column, \
30 ucu.table_name AS to_table, ucu.column_name AS to_column, \
31 rc.delete_rule AS delete_rule \
32 FROM information_schema.table_constraints tc \
33 JOIN information_schema.referential_constraints rc \
34 ON rc.constraint_name = tc.constraint_name AND rc.constraint_schema = tc.table_schema \
35 JOIN information_schema.key_column_usage fkcu \
36 ON fkcu.constraint_name = tc.constraint_name AND fkcu.table_schema = tc.table_schema \
37 JOIN information_schema.key_column_usage ucu \
38 ON ucu.constraint_name = rc.unique_constraint_name \
39 AND ucu.constraint_schema = rc.unique_constraint_schema \
40 AND ucu.ordinal_position = fkcu.position_in_unique_constraint \
41 WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY' \
42 ORDER BY tc.constraint_name, fkcu.ordinal_position",
43 )
44 .bind(db_schema)
45 .fetch_all(pool)
46 .await
47 .map_err(|e| SchemaReverseEngineerError::Introspection(e.to_string()))?;
48
49 let mut by_table: HashMap<String, Vec<Relation>> = HashMap::new();
50 for row in rows {
51 let relation_type = map_delete_rule(&row.delete_rule);
52 let relation = Relation::new(
53 row.to_table,
54 row.to_column,
55 row.from_table.clone(),
56 row.from_column,
57 relation_type,
58 false,
59 );
60 by_table.entry(row.from_table).or_default().push(relation);
61 }
62
63 Ok(by_table)
64}
65
66fn map_delete_rule(delete_rule: &str) -> RelationType {
67 match delete_rule {
68 "CASCADE" => RelationType::Cascade,
69 "SET NULL" | "SET DEFAULT" => RelationType::SetNull,
70 "RESTRICT" | "NO ACTION" => RelationType::Enforce,
71 _ => RelationType::DoNothing,
72 }
73}