Skip to main content

schema_reverse_engineer/postgres/
views.rs

1use crate::error::SchemaReverseEngineerError;
2use schema_model::model::types::DatabaseType;
3use schema_model::model::view::View;
4use sqlx::PgPool;
5
6pub async fn list_views(
7    pool: &PgPool,
8    db_schema: &str,
9) -> Result<Vec<View>, SchemaReverseEngineerError> {
10    // `view_definition` is NULL for a role that doesn't own the view.
11    let rows: Vec<(String, Option<String>)> = sqlx::query_as(
12        "SELECT table_name, view_definition \
13         FROM information_schema.views \
14         WHERE table_schema = $1 \
15         ORDER BY table_name",
16    )
17    .bind(db_schema)
18    .fetch_all(pool)
19    .await
20    .map_err(|e| SchemaReverseEngineerError::Introspection(e.to_string()))?;
21
22    // `information_schema.views` omits materialized views, and the model has no such concept.
23    let materialized: Vec<(String,)> = sqlx::query_as(
24        "SELECT matviewname FROM pg_matviews WHERE schemaname = $1 ORDER BY matviewname",
25    )
26    .bind(db_schema)
27    .fetch_all(pool)
28    .await
29    .map_err(|e| SchemaReverseEngineerError::Introspection(e.to_string()))?;
30    for (name,) in materialized {
31        eprintln!(
32            "warning: {name} is a materialized view, which the schema model can't represent -- skipping it"
33        );
34    }
35
36    Ok(rows
37        .into_iter()
38        .filter_map(|(name, sql)| match sql {
39            Some(sql) => Some(View::new(
40                None,
41                name.as_str(),
42                sql.trim(),
43                Some(DatabaseType::Postgresql),
44            )),
45            None => {
46                eprintln!(
47                    "warning: definition of view {name} is not visible to this role -- skipping it"
48                );
49                None
50            }
51        })
52        .collect())
53}