1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use super::{InformationSchema, SchemaQueryBuilder};
use crate::sqlx_types::postgres::PgRow;
use sea_query::{Expr, Iden, Query, SeaRc, SelectStatement};

#[derive(Debug, sea_query::Iden)]
/// Ref: https://www.postgresql.org/docs/13/infoschema-tables.html
pub enum TablesFields {
    TableCatalog,
    TableSchema,
    TableName,
    TableType,
    UserDefinedTypeSchema,
    UserDefinedTypeName,
    // IsInsertableInto is always true for BASE TABLEs
    IsInsertableInto,
    IsTyped,
}

#[derive(Debug, sea_query::Iden)]
pub enum TableType {
    #[iden = "BASE TABLE"]
    BaseTable,
    #[iden = "VIEW"]
    View,
    #[iden = "FOREIGN"]
    Foreign,
    #[iden = "LOCAL TEMPORARY"]
    Temporary,
}

#[derive(Debug, Default)]
pub struct TableQueryResult {
    pub table_name: String,
    pub user_defined_type_schema: Option<String>,
    pub user_defined_type_name: Option<String>,
}

impl SchemaQueryBuilder {
    pub fn query_tables(&self, schema: SeaRc<dyn Iden>) -> SelectStatement {
        Query::select()
            .columns(vec![
                TablesFields::TableName,
                TablesFields::UserDefinedTypeSchema,
                TablesFields::UserDefinedTypeName,
            ])
            .from((InformationSchema::Schema, InformationSchema::Tables))
            .and_where(Expr::col(TablesFields::TableSchema).eq(schema.to_string()))
            .and_where(Expr::col(TablesFields::TableType).eq(TableType::BaseTable.to_string()))
            .take()
    }
}

#[cfg(feature = "sqlx-postgres")]
impl From<&PgRow> for TableQueryResult {
    fn from(row: &PgRow) -> Self {
        use crate::sqlx_types::Row;
        Self {
            table_name: row.get(0),
            user_defined_type_schema: row.get(1),
            user_defined_type_name: row.get(2),
        }
    }
}

#[cfg(not(feature = "sqlx-postgres"))]
impl From<&PgRow> for TableQueryResult {
    fn from(row: &PgRow) -> Self {
        Self::default()
    }
}