diff --git a/src/identity/adapters/output/db/postgres/username_exists.rs b/src/identity/adapters/output/db/postgres/username_exists.rs new file mode 100644 index 0000000..3e5b04e --- /dev/null +++ b/src/identity/adapters/output/db/postgres/username_exists.rs @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2024 Aravinth Manivannan +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::DBOutPostgresAdapter; +use crate::identity::application::port::output::db::{ + errors::*, username_exists::UsernameExistsOutDBPort, +}; + +#[async_trait::async_trait] +impl UsernameExistsOutDBPort for DBOutPostgresAdapter { + async fn username_exists(&self, username: &str) -> OutDBPortResult { + let res = sqlx::query!( + "SELECT EXISTS ( + SELECT 1 + FROM user_query + WHERE + username = $1 + );", + username + ) + .fetch_one(&self.pool) + .await?; + if let Some(x) = res.exists { + Ok(x) + } else { + Ok(false) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[actix_rt::test] + async fn test_postgres_username_exists() { + let username = "foo@exmaple.com"; + let settings = crate::settings::tests::get_settings().await; + let db = super::DBOutPostgresAdapter::new( + sqlx::postgres::PgPool::connect(&settings.database.url) + .await + .unwrap(), + ); + + // state doesn't exist + assert!(!db.username_exists(username).await.unwrap()); + + sqlx::query!( + "INSERT INTO user_query + (view_id, version, username, email, hashed_password) + VALUES ($1, $2, $3, $4, $5);", + "1", + 1, + username, + "foo", + "passwd" + ) + .execute(&db.pool) + .await + .unwrap(); + + // state exists + assert!(db.username_exists(username).await.unwrap()); + + settings.drop_db().await; + } +}