diff --git a/sqlx-data.json b/sqlx-data.json index e80528e..cd3f69f 100644 --- a/sqlx-data.json +++ b/sqlx-data.json @@ -77,6 +77,26 @@ }, "query": "UPDATE librepages_users set name = $1\n WHERE name = $2" }, + "3705b8869aab99d749c08d9c9633931f0b74216957b6a2881bd56a33c33a8c47": { + "describe": { + "columns": [ + { + "name": "exists", + "ordinal": 0, + "type_info": "Bool" + } + ], + "nullable": [ + null + ], + "parameters": { + "Left": [ + "Text" + ] + } + }, + "query": "SELECT EXISTS (SELECT 1 from librepages_sites WHERE hostname = $1)" + }, "416b9f0412f0d7ee05d4a350839c5a6d1e06c1d7f8942744f6d806ddc47084c2": { "describe": { "columns": [], diff --git a/src/db.rs b/src/db.rs index d69c2d3..72379e0 100644 --- a/src/db.rs +++ b/src/db.rs @@ -365,6 +365,24 @@ impl Database { .map_err(|e| map_row_not_found_err(e, ServiceError::WebsiteNotFound))?; Ok(()) } + + /// check if hostname exists + pub async fn hostname_exists(&self, hostname: &str) -> ServiceResult { + let res = sqlx::query!( + "SELECT EXISTS (SELECT 1 from librepages_sites WHERE hostname = $1)", + hostname, + ) + .fetch_one(&self.pool) + .await + .map_err(map_register_err)?; + + let mut resp = false; + if let Some(x) = res.exists { + resp = x; + } + + Ok(resp) + } } struct InnerSite { site_secret: String, @@ -635,7 +653,6 @@ mod tests { db.register(&p).await.unwrap(); - // testing adding site let site = Site { site_secret: "foobar".into(), repo_url: "https://git.batsense.net/LibrePages/librepages.git".into(), @@ -643,8 +660,16 @@ mod tests { hostname: "db_works.tests.librepages.librepages.org".into(), owner: p.username.into(), }; + + // test if hostname exists. Should be false + assert!(!db.hostname_exists(&site.hostname).await.unwrap()); + + // testing adding site db.add_site(&site).await.unwrap(); + // test if hostname exists. Should be true + assert!(db.hostname_exists(&site.hostname).await.unwrap()); + // get site let db_site = db.get_site(p.username, &site.hostname).await.unwrap(); assert_eq!(db_site, site); @@ -662,6 +687,8 @@ mod tests { // delete site db.delete_site(p.username, &site.hostname).await.unwrap(); - assert!(db.list_all_sites(p.username).await.unwrap().is_empty()); + + // test if hostname exists. Should be false + assert!(!db.hostname_exists(&site.hostname).await.unwrap()); } }