Skip to main content

sea_schema/postgres/query/
enumeration.rs

1use super::SchemaQueryBuilder;
2use crate::{postgres::query::PgNamespace, sqlx_types::SqlxRow};
3use sea_query::{DynIden, Expr, ExprTrait, Order, Query, SelectStatement};
4
5#[derive(Debug, sea_query::Iden)]
6pub enum PgCatalog {
7    #[iden = "pg_catalog"]
8    Schema,
9}
10
11#[derive(Debug, sea_query::Iden)]
12pub enum PgType {
13    #[iden = "pg_type"]
14    Table,
15    #[iden = "typname"]
16    TypeName,
17    #[iden = "oid"]
18    Oid,
19    #[iden = "typnamespace"]
20    TypeNamespace,
21}
22
23#[derive(Debug, sea_query::Iden)]
24pub enum PgEnum {
25    #[iden = "pg_enum"]
26    Table,
27    #[iden = "enumlabel"]
28    EnumLabel,
29    #[iden = "enumtypid"]
30    EnumTypeId,
31    #[iden = "enumsortorder"]
32    EnumSortOrder,
33}
34
35#[derive(Debug, Default)]
36pub struct EnumQueryResult {
37    pub typename: String,
38    pub enumlabel: String,
39}
40
41impl SchemaQueryBuilder {
42    pub fn query_enums(&self, schema: DynIden) -> SelectStatement {
43        Query::select()
44            .column((PgType::Table, PgType::TypeName))
45            .column((PgEnum::Table, PgEnum::EnumLabel))
46            .from((PgCatalog::Schema, PgType::Table))
47            .inner_join(
48                (PgCatalog::Schema, PgEnum::Table),
49                Expr::col((PgEnum::Table, PgEnum::EnumTypeId)).equals((PgType::Table, PgType::Oid)),
50            )
51            .inner_join(
52                (PgCatalog::Schema, PgNamespace::Table),
53                Expr::col((PgNamespace::Table, PgNamespace::Oid))
54                    .equals((PgType::Table, PgType::TypeNamespace)),
55            )
56            .and_where(Expr::col((PgNamespace::Table, PgNamespace::NspName)).eq(schema.to_string()))
57            .order_by((PgType::Table, PgType::TypeName), Order::Asc)
58            .order_by((PgEnum::Table, PgEnum::EnumSortOrder), Order::Asc)
59            .order_by((PgEnum::Table, PgEnum::EnumLabel), Order::Asc)
60            .take()
61    }
62}
63
64#[cfg(feature = "sqlx-postgres")]
65impl From<SqlxRow> for EnumQueryResult {
66    fn from(row: SqlxRow) -> Self {
67        use crate::sqlx_types::Row;
68        let row = row.postgres();
69        Self {
70            typename: row.get(0),
71            enumlabel: row.get(1),
72        }
73    }
74}
75
76#[cfg(not(feature = "sqlx-postgres"))]
77impl From<SqlxRow> for EnumQueryResult {
78    fn from(_: SqlxRow) -> Self {
79        Self::default()
80    }
81}