From 04de5a4e4ff646071267c0272cf2cfabfdb4f0fc Mon Sep 17 00:00:00 2001 From: trivernis Date: Sat, 12 Sep 2020 12:03:22 +0200 Subject: [PATCH] Change permission creation to return permissions even if they exist Signed-off-by: trivernis --- src/database/permissions.rs | 7 +++++-- src/database/roles.rs | 30 ++++++++++++++++++++++-------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/database/permissions.rs b/src/database/permissions.rs index f7e356b..62c9ba3 100644 --- a/src/database/permissions.rs +++ b/src/database/permissions.rs @@ -42,8 +42,8 @@ impl Permissions { let _: Vec> = permissions .iter() .map(|CreatePermissionsEntry { name, description }| { - let exists = transaction - .query_opt("SELECT id FROM permissions WHERE name = $1", &[&name])?; + let exists = + transaction.query_opt("SELECT * FROM permissions WHERE name = $1", &[&name])?; if exists.is_none() { let row = transaction.query_one( @@ -52,12 +52,15 @@ impl Permissions { )?; created_permissions.push(serde_postgres::from_row(&row)?); + } else { + created_permissions.push(serde_postgres::from_row(&exists.unwrap())?); } Ok(()) }) .collect(); transaction.commit()?; + Ok(created_permissions) } } diff --git a/src/database/roles.rs b/src/database/roles.rs index 05118ab..b1c303c 100644 --- a/src/database/roles.rs +++ b/src/database/roles.rs @@ -62,17 +62,31 @@ impl Roles { &[&role.id, &permission], )?; } + if let Err(e) = transaction.execute( + "INSERT INTO user_roles (user_id, role_id) VALUES ($1, $2)", + &[&1, &role.id], + ) { + log::debug!("Failed to add role to admin user: {}", e); + } Ok(role) }; - if let Err(_) = result { - log::trace!("Rollback"); - transaction.rollback()?; - } else { - log::trace!("Commit"); - transaction.commit()?; - } + match result { + Err(e) => { + log::warn!("Failed to create role {}: {}", name, e); + log::trace!("Rolling back..."); + transaction.rollback()?; + log::trace!("Rolled back!"); + Err(e) + } + Ok(role) => { + log::debug!("Successfully created role {} with id {}", name, role.id); + log::trace!("Committing..."); + transaction.commit()?; + log::trace!("Committed!"); - result + Ok(role) + } + } } }