|
| 1 | +use crate::schema_cache::SchemaCacheItem; |
| 2 | + |
| 3 | +#[derive(Debug, PartialEq, Eq)] |
| 4 | +pub struct Role { |
| 5 | + pub name: String, |
| 6 | + pub is_super_user: bool, |
| 7 | + pub can_create_db: bool, |
| 8 | + pub can_login: bool, |
| 9 | + pub can_bypass_rls: bool, |
| 10 | +} |
| 11 | + |
| 12 | +impl SchemaCacheItem for Role { |
| 13 | + type Item = Role; |
| 14 | + |
| 15 | + async fn load(pool: &sqlx::PgPool) -> Result<Vec<Self::Item>, sqlx::Error> { |
| 16 | + sqlx::query_file_as!(Role, "src/queries/roles.sql") |
| 17 | + .fetch_all(pool) |
| 18 | + .await |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +#[cfg(test)] |
| 23 | +mod tests { |
| 24 | + use crate::SchemaCache; |
| 25 | + use pgt_test_utils::test_database::get_new_test_db; |
| 26 | + use sqlx::Executor; |
| 27 | + |
| 28 | + #[tokio::test] |
| 29 | + async fn loads_roles() { |
| 30 | + let test_db = get_new_test_db().await; |
| 31 | + |
| 32 | + let setup = r#" |
| 33 | + do $$ |
| 34 | + begin |
| 35 | + if not exists ( |
| 36 | + select from pg_catalog.pg_roles |
| 37 | + where rolname = 'test_super' |
| 38 | + ) then |
| 39 | + create role test_super superuser createdb login bypassrls; |
| 40 | + end if; |
| 41 | + if not exists ( |
| 42 | + select from pg_catalog.pg_roles |
| 43 | + where rolname = 'test_nologin' |
| 44 | + ) then |
| 45 | + create role test_nologin; |
| 46 | + end if; |
| 47 | + if not exists ( |
| 48 | + select from pg_catalog.pg_roles |
| 49 | + where rolname = 'test_login' |
| 50 | + ) then |
| 51 | + create role test_login login; |
| 52 | + end if; |
| 53 | + end $$; |
| 54 | + "#; |
| 55 | + |
| 56 | + test_db |
| 57 | + .execute(setup) |
| 58 | + .await |
| 59 | + .expect("Failed to setup test database"); |
| 60 | + |
| 61 | + let cache = SchemaCache::load(&test_db) |
| 62 | + .await |
| 63 | + .expect("Failed to load Schema Cache"); |
| 64 | + |
| 65 | + let roles = &cache.roles; |
| 66 | + |
| 67 | + let super_role = roles.iter().find(|r| r.name == "test_super").unwrap(); |
| 68 | + assert!(super_role.is_super_user); |
| 69 | + assert!(super_role.can_create_db); |
| 70 | + assert!(super_role.can_login); |
| 71 | + assert!(super_role.can_bypass_rls); |
| 72 | + |
| 73 | + let nologin_role = roles.iter().find(|r| r.name == "test_nologin").unwrap(); |
| 74 | + assert!(!nologin_role.is_super_user); |
| 75 | + assert!(!nologin_role.can_create_db); |
| 76 | + assert!(!nologin_role.can_login); |
| 77 | + assert!(!nologin_role.can_bypass_rls); |
| 78 | + |
| 79 | + let login_role = roles.iter().find(|r| r.name == "test_login").unwrap(); |
| 80 | + assert!(!login_role.is_super_user); |
| 81 | + assert!(!login_role.can_create_db); |
| 82 | + assert!(login_role.can_login); |
| 83 | + assert!(!login_role.can_bypass_rls); |
| 84 | + } |
| 85 | +} |
0 commit comments