Skip to content

Commit

Permalink
feat: Logging DB queries
Browse files Browse the repository at this point in the history
  • Loading branch information
Wulf committed Jan 15, 2024
1 parent e8fe1e7 commit 34bf6c0
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 17 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions create-rust-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ diesel = { version = "2.1.0", default-features = false, features = [
"chrono",
] } # + plugin_dev, plugin_auth
once_cell = "1.17.1"
diesel_logger = "0.3.0"

##
## Database
Expand Down
22 changes: 11 additions & 11 deletions create-rust-app/src/auth/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ pub fn get_sessions(
auth: &Auth,
info: &PaginationParams,
) -> Result<UserSessionResponse, (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

let sessions = UserSession::read_all(&mut db, info, auth.user_id);

Expand Down Expand Up @@ -178,7 +178,7 @@ pub fn destroy_session(
auth: &Auth,
item_id: ID,
) -> Result<(), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

let user_session = UserSession::read(&mut db, item_id);

Expand Down Expand Up @@ -208,7 +208,7 @@ pub fn destroy_session(
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn destroy_sessions(db: &Database, auth: &Auth) -> Result<(), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

if UserSession::delete_all_for_user(&mut db, auth.user_id).is_err() {
return Err((500, "Could not delete sessions."));
Expand All @@ -234,7 +234,7 @@ pub fn login(
db: &Database,
item: &LoginInput,
) -> Result<(AccessToken, RefreshToken), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

// verify device
let mut device = None;
Expand Down Expand Up @@ -364,7 +364,7 @@ pub fn create_user_session(
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn logout(db: &Database, refresh_token: Option<&'_ str>) -> Result<(), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

if refresh_token.is_none() {
return Err((401, "Invalid session."));
Expand Down Expand Up @@ -402,7 +402,7 @@ pub fn refresh(
db: &Database,
refresh_token_str: Option<&'_ str>,
) -> Result<(AccessToken, RefreshToken), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

if refresh_token_str.is_none() {
return Err((401, "Invalid session."));
Expand Down Expand Up @@ -512,7 +512,7 @@ pub fn register(
item: &RegisterInput,
mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

let user = User::find_by_email(&mut db, item.email.to_string());

Expand Down Expand Up @@ -569,7 +569,7 @@ pub fn activate(
item: &ActivationInput,
mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

let token = decode::<RegistrationClaims>(
&item.activation_token,
Expand Down Expand Up @@ -639,7 +639,7 @@ pub fn forgot_password(
item: &ForgotInput,
mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

let user_result = User::find_by_email(&mut db, item.email.clone());

Expand Down Expand Up @@ -697,7 +697,7 @@ pub fn change_password(
return Err((400, "The new password must be different"));
}

let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

let user = User::read(&mut db, auth.user_id);

Expand Down Expand Up @@ -765,7 +765,7 @@ pub fn reset_password(
item: &ResetInput,
mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

if item.new_password.is_empty() {
return Err((400, "Missing password"));
Expand Down
4 changes: 2 additions & 2 deletions create-rust-app/src/auth/oidc/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub async fn oidc_login_url(
auth_config: &AuthConfig,
provider_name: String,
) -> Result<Option<String>> {
let mut db = db.get_connection();
let mut db = db.get_connection().unwrap();

let provider_config: Option<_> = auth_config
.clone()
Expand Down Expand Up @@ -102,7 +102,7 @@ pub async fn oauth_login(
query_param_error: Option<String>,
query_param_state: Option<String>,
) -> Result<(AccessToken, RefreshToken), (StatusCode, Message)> {
let db = &mut db.get_connection();
let db = &mut db.get_connection().unwrap();

// 1. Make sure this provider is setup
let provider_config = auth_config
Expand Down
7 changes: 4 additions & 3 deletions create-rust-app/src/database/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use diesel::r2d2::{self, ConnectionManager, PooledConnection};
use diesel_logger::LoggingConnection;
use once_cell::sync::OnceCell;

#[cfg(feature = "database_postgres")]
Expand All @@ -16,7 +17,7 @@ pub type DieselBackend = diesel::pg::Pg;
pub type DieselBackend = diesel::sqlite::Sqlite;

pub type Pool = r2d2::Pool<ConnectionManager<DbCon>>;
pub type Connection = PooledConnection<ConnectionManager<DbCon>>;
pub type Connection = LoggingConnection<PooledConnection<ConnectionManager<DbCon>>>;

#[derive(Clone)]
/// wrapper function for a database pool
Expand All @@ -39,8 +40,8 @@ impl Database {
}

/// get a [`Connection`] to a database
pub fn get_connection(&self) -> Connection {
self.pool.get().unwrap()
pub fn get_connection(&self) -> Result<Connection, anyhow::Error> {
Ok(LoggingConnection::new(self.pool.get()?))
}

fn get_or_init_pool() -> &'static Pool {
Expand Down
2 changes: 1 addition & 1 deletion create-rust-app/src/dev/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct HealthCheckResponse {
/// /db/query
pub fn query_db(db: &Database, body: &MySqlQuery) -> Result<String, diesel::result::Error> {
let q = format!("SELECT json_agg(q) as json FROM ({}) q;", body.query);
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

Ok(sql_query(q.as_str())
.get_result::<MyQueryResult>(&mut db)?
Expand Down

0 comments on commit 34bf6c0

Please sign in to comment.