From df1e2ffd7b26311432309cb161cf2cd259ac87ad Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Wed, 8 Jul 2020 13:33:55 +0200 Subject: [PATCH] Can log select queries --- config.yaml | 5 ++++- src/data/config.rs | 2 ++ src/helpers/database.rs | 39 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/config.yaml b/config.yaml index da08c06..497ff6e 100644 --- a/config.yaml +++ b/config.yaml @@ -26,4 +26,7 @@ database: host: localhost name: comunic username: pierre - password: pierre \ No newline at end of file + password: pierre + + # If set to true, every requests made on the database will be shown on the terminal + log_all_queries: true \ No newline at end of file diff --git a/src/data/config.rs b/src/data/config.rs index 93278b3..2beb71a 100644 --- a/src/data/config.rs +++ b/src/data/config.rs @@ -11,6 +11,7 @@ pub struct DatabaseConfig { pub name: String, pub username: String, pub password: String, + pub log_all_queries: bool, } #[derive(Debug)] @@ -59,6 +60,7 @@ impl Config { name: Config::yaml_str(parsed_db, "name"), username: Config::yaml_str(parsed_db, "username"), password: Config::yaml_str(parsed_db, "password"), + log_all_queries: Config::yaml_bool(parsed_db, "log_all_queries"), }; let proxy = Config::yaml_str(parsed, "proxy"); diff --git a/src/helpers/database.rs b/src/helpers/database.rs index d3ecca5..aa6174a 100644 --- a/src/helpers/database.rs +++ b/src/helpers/database.rs @@ -8,7 +8,7 @@ use chrono::{TimeZone, Utc}; use mysql::{Binary, Pool, ResultSet, Value}; use mysql::prelude::Queryable; -use crate::data::config::DatabaseConfig; +use crate::data::config::{conf, DatabaseConfig}; use crate::data::error::{ExecError, ResultBoxError}; use crate::data::group_id::GroupID; use crate::data::user::UserID; @@ -477,6 +477,11 @@ pub fn query ProcessRowResult>(info: QueryInfo, proce query = query.add(&format!(" LIMIT {}", info.limit)); } + // Log query, if required + if conf().database.log_all_queries { + watcher::ExecDatabaseQuery::new(&query, ¶ms).display() + } + // Execute query let mut con = get_connection()?; let stmt = con.prep(&query).or_else(|err| { @@ -859,4 +864,36 @@ pub fn update(u: UpdateInfo) -> ResultBoxError<()> { )?; Ok(()) +} + + +/// Private module used to watch what is going on the database +mod watcher { + /// Database logging & optimisation + pub struct ExecDatabaseQuery { + query: String, + values: Vec, + } + + impl ExecDatabaseQuery { + /// Construct a new instance of this structure + pub fn new(query: &str, values: &Vec) -> ExecDatabaseQuery { + ExecDatabaseQuery { + query: query.to_string(), + values: values.clone(), + } + } + + /// Display the values stored inside this query + pub fn display(&self) { + println!("=================="); + println!("DB: {}", self.query); + println!("Arguments:"); + + for arg in &self.values { + println!("* {:?} ", arg); + } + println!() + } + } } \ No newline at end of file