Skip to content

Commit

Permalink
feat: Logging DB queries (#363)
Browse files Browse the repository at this point in the history
* feat: Logging DB queries

* fixes
  • Loading branch information
Wulf authored Jan 15, 2024
1 parent e8fe1e7 commit e3d81d9
Show file tree
Hide file tree
Showing 19 changed files with 79 additions and 1,343 deletions.
15 changes: 13 additions & 2 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion create-rust-app/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "create-rust-app"
description = "Set up a modern rust+react web app by running one command."
version = "10.0.0"
version = "11.0.0"
edition = "2018"
authors = ["Haris <4259838+Wulf@users.noreply.github.com>"]
readme = "../README.md"
Expand Down 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
2 changes: 1 addition & 1 deletion create-rust-app_cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "create-rust-app_cli"
description = "Set up a modern rust+react web app by running one command."
version = "10.0.0"
version = "11.0.0"
authors = ["Haris <4259838+Wulf@users.noreply.github.com>"]
edition = "2018"
readme = "../README.md"
Expand Down
3 changes: 2 additions & 1 deletion create-rust-app_cli/src/content/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ struct Asset;
// version.to_string()
// }
fn get_current_cra_lib_version() -> String {
"10.0.0".to_string()
"11.0.0".to_string()
}

#[derive(Clone)]
Expand Down Expand Up @@ -411,6 +411,7 @@ pub fn create(project_name: &str, creation_options: CreationOptions) -> Result<(
)?;
}
}
add_dependency(&project_dir, "simple_logger", r#"simple_logger = "4.3.3""#)?;
add_dependency(&project_dir, "futures-util", r#"futures-util = "0.3.21""#)?;
add_dependency(
&project_dir,
Expand Down
6 changes: 3 additions & 3 deletions create-rust-app_cli/src/plugins/graphql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ ReactDOM.createRoot"#,
"frontend/package.json",
r#""dependencies": {"#,
r#""dependencies": {
"@apollo/client": "^3.5.10",
"graphql-ws": "^5.6.4",
"graphql": "^16.3.0","#,
"@apollo/client": "^5.14.3",
"graphql-ws": "^5.14.3",
"graphql": "^16.8.1","#,
)?;

fs::replace("backend/main.rs", "mod mail;", "mod mail;\nmod graphql;")?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct FileInfo {

#[actix_web::get("")]
async fn all(db: Data<Database>, storage: Data<Storage>) -> HttpResponse {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();
let files = Attachment::find_all_for_record(&mut db, "file".to_string(), "NULL".to_string(), 0).unwrap_or_default();
let blob_ids = files.iter().map(|f| f.blob_id).collect::<Vec<_>>();
let blobs = AttachmentBlob::find_all_by_id(&mut db, blob_ids).unwrap_or_default();
Expand All @@ -42,7 +42,7 @@ async fn all(db: Data<Database>, storage: Data<Storage>) -> HttpResponse {

#[actix_web::delete("/{id}")]
async fn delete(db: Data<Database>, storage: Data<Storage>, file_id: Path<i32>) -> HttpResponse {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();
let file_id = file_id.into_inner();

let detach_op = Attachment::detach(&mut db, &storage, file_id).await;
Expand All @@ -56,7 +56,7 @@ async fn delete(db: Data<Database>, storage: Data<Storage>, file_id: Path<i32>)

#[actix_web::post("")]
async fn create(db: Data<Database>, store: Data<Storage>, mut payload: Multipart) -> HttpResponse {
let mut db = db.pool.get().unwrap();
let mut db = db.get_connection().unwrap();

while let Some(item) = payload.next().await {
let mut field = if item.is_ok() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use create_rust_app::Connection;
use fang::{FangError, Queueable, Scheduled};
use fang::PgConnection;
use fang::Runnable;
use fang::serde::{Deserialize, Serialize};
use fang::typetag;
use fang::PgConnection;
use fang::Runnable;
use fang::{FangError, Queueable, Scheduled};

use crate::models::todos::{CreateTodo, Todo};

Expand All @@ -19,11 +19,15 @@ impl Runnable for DailyTodo {
println!("Adding daily todo {}", self.text);
let db = create_rust_app::Database::new();

let con = &mut db.get_connection();
let con = &mut db.get_connection().unwrap();

Todo::create(con, &CreateTodo {
text: self.text.clone(),
}).unwrap();
Todo::create(
con,
&CreateTodo {
text: self.text.clone(),
},
)
.unwrap();

Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use fang::{AsyncRunnable, FangError, Scheduled, typetag};
use fang::async_trait;
use fang::asynk::async_queue::AsyncQueueable;
use fang::serde::{Deserialize, Serialize};
use fang::async_trait;
use fang::{typetag, AsyncRunnable, FangError, Scheduled};

use crate::models::todos::{CreateTodo, Todo};

Expand All @@ -18,11 +18,15 @@ impl AsyncRunnable for DailyTodoAsync {
println!("(async) Adding daily todo {}", self.text);
let db = create_rust_app::Database::new();

let con = &mut db.get_connection();
let con = &mut db.get_connection().unwrap();

Todo::create(con, &CreateTodo {
text: self.text.clone(),
}).unwrap();
Todo::create(
con,
&CreateTodo {
text: self.text.clone(),
},
)
.unwrap();

Ok(())
}
Expand All @@ -33,7 +37,6 @@ impl AsyncRunnable for DailyTodoAsync {
"async".to_string()
}


// If `uniq` is set to true and the task is already in the storage, it won't be inserted again
// The existing record will be returned for for any insertions operation
fn uniq(&self) -> bool {
Expand Down
1 change: 1 addition & 0 deletions create-rust-app_cli/template/.env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
RUST_LOG=debug
SECRET_KEY=secret
DATABASE_URL=postgres://postgres:postgres@localhost/database
RUST_BACKTRACE=1
Expand Down
1 change: 1 addition & 0 deletions create-rust-app_cli/template/backend/main.rs+actix_web
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ mod mail;
async fn main() -> std::io::Result<()> {
#[cfg(debug_assertions)] create_rust_app::setup_development().await;
let app_data = create_rust_app::setup();
simple_logger::init_with_env().unwrap();

HttpServer::new(move || {
let mut app = App::new()
Expand Down
1 change: 1 addition & 0 deletions create-rust-app_cli/template/backend/main.rs+poem
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ async fn main() -> Result<(), std::io::Error> {
tracing_subscriber::fmt::init();

let data = create_rust_app::setup();
simple_logger::init_with_env().unwrap();

let mut api_routes = Route::new();
api_routes = api_routes.nest("/todos", services::todo::api());
Expand Down
Loading

0 comments on commit e3d81d9

Please sign in to comment.