use sqlx::{PgExecutor, postgres::types::Oid, query_as};

use crate::pg_acl::PgAclItem;

#[derive(Clone, Debug)]
pub struct PgNamespace {
    /// Row identifier
    pub oid: Oid,
    /// Name of the namespace
    pub nspname: String,
    /// Owner of the namespace
    pub nspowner: Oid,
    /// Access privileges; see Section 5.8 for details
    pub nspacl: Option<Vec<PgAclItem>>,
}

impl PgNamespace {
    pub async fn fetch_by_oid<'a, E: PgExecutor<'a>>(
        oid: Oid,
        client: E,
    ) -> Result<Option<PgNamespace>, sqlx::Error> {
        query_as!(
            PgNamespace,
            r#"
select
    oid,
    nspname,
    nspowner,
    nspacl::text[] as "nspacl: Vec<PgAclItem>"
from pg_namespace
where
    oid = $1
"#,
            oid,
        )
        .fetch_optional(client)
        .await
    }
}
