Skip to content

Commit

Permalink
add debug_query macro make get raw_sql becomes simply. (#189)
Browse files Browse the repository at this point in the history
* add debug_query make get raw_sql becomes simply.

* refactor code with macro debug_query!
ref:#145

* update doc

* add DbConnection with DebugQuey build overload method. Working for #145

* all rename with DbBackEnd

* define IntoDbBackEnd trait

* fix build error

* fix build error

* refactor code IntoDbBackend

* cargo fmt

* rename marco

* cargo fmt

* fix build test error

* fix example build error

* remove warning

* remove IntoDbBackend

* cargo fmt

* cargo fmt code

* add DbBackend ref with DebugQuery

* update

* refactor code

* refactor code
  • Loading branch information
baoyachi authored Oct 4, 2021
1 parent af93ea4 commit 49efca7
Show file tree
Hide file tree
Showing 8 changed files with 137 additions and 19 deletions.
12 changes: 9 additions & 3 deletions examples/actix4_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ async fn create(
.await
.expect("could not insert post");

Ok(HttpResponse::Found().append_header(("location", "/")).finish())
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}

#[get("/{id}")]
Expand Down Expand Up @@ -133,7 +135,9 @@ async fn update(
.await
.expect("could not edit post");

Ok(HttpResponse::Found().append_header(("location", "/")).finish())
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}

#[post("/delete/{id}")]
Expand All @@ -149,7 +153,9 @@ async fn delete(data: web::Data<AppState>, id: web::Path<i32>) -> Result<HttpRes

post.delete(conn).await.unwrap();

Ok(HttpResponse::Found().append_header(("location", "/")).finish())
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}

#[actix_web::main]
Expand Down
2 changes: 1 addition & 1 deletion examples/async-std/src/operation.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::*;
use sea_orm::{entity::*, error::*, query::*, DbConn};
use sea_orm::{entity::*, error::*, DbConn};

pub async fn all_about_operation(db: &DbConn) -> Result<(), DbErr> {
insert_and_update(db).await?;
Expand Down
4 changes: 1 addition & 3 deletions examples/rocket_example/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ impl rocket_db_pools::Pool for RocketDbPool {
let config = figment.extract::<Config>().unwrap();
let conn = sea_orm::Database::connect(&config.url).await.unwrap();

Ok(RocketDbPool {
conn,
})
Ok(RocketDbPool { conn })
}

async fn get(&self) -> Result<Self::Connection, Self::Error> {
Expand Down
5 changes: 3 additions & 2 deletions examples/tokio/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@ pub async fn main() {
tokio::spawn(async move {
cake::Entity::find().one(&db).await.unwrap();
})
.await.unwrap();
}
.await
.unwrap();
}
2 changes: 1 addition & 1 deletion src/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,4 @@
//! },
//! )
//! }
//! ```
//! ```
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@
)]

mod database;
mod docs;
mod driver;
pub mod entity;
pub mod error;
Expand All @@ -273,7 +274,6 @@ pub mod query;
pub mod schema;
#[doc(hidden)]
pub mod tests_cfg;
mod docs;
mod util;

pub use database::*;
Expand Down
115 changes: 114 additions & 1 deletion src/query/traits.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{DbBackend, Statement};
use crate::{DatabaseConnection, DbBackend, Statement};
use sea_query::QueryStatementBuilder;

pub trait QueryTrait {
Expand All @@ -22,3 +22,116 @@ pub trait QueryTrait {
)
}
}

#[derive(Debug)]
pub struct DebugQuery<'a, Q, T> {
pub query: &'a Q,
pub value: T,
}

macro_rules! debug_query_build {
($impl_obj:ty,$db_expr:tt) => {
impl<'a, Q> DebugQuery<'a, Q, $impl_obj>
where
Q: QueryTrait,
{
pub fn build(&self) -> Statement {
let db_backend = $db_expr(self);
self.query.build(db_backend)
}
}
};
}

debug_query_build!(DbBackend, (|x: &DebugQuery<_, DbBackend>| x.value));
debug_query_build!(&DbBackend, (|x: &DebugQuery<_, &DbBackend>| *x.value));
debug_query_build!(
DatabaseConnection,
(|x: &DebugQuery<_, DatabaseConnection>| x.value.get_database_backend())
);
debug_query_build!(
&DatabaseConnection,
(|x: &DebugQuery<_, &DatabaseConnection>| x.value.get_database_backend())
);

/// Make get raw_sql becomes simply. It does not need to specify a specific `DbBackend`,
/// but can be obtained through `get_database_backend` with `DatabaseConnection`.
/// Return a Statement type.
///
///
/// # Example
///
/// ```
/// # #[cfg(feature = "mock")]
/// # use sea_orm::{error::*, tests_cfg::*, MockDatabase, MockExecResult, Transaction, DbBackend};
/// #
/// # let conn = MockDatabase::new(DbBackend::Postgres)
/// # .into_connection();
/// #
/// use sea_orm::{entity::*, query::*, tests_cfg::cake,gen_statement};
///
/// let c = cake::Entity::insert(
/// cake::ActiveModel {
/// id: ActiveValue::set(1),
/// name: ActiveValue::set("Apple Pie".to_owned()),
/// });
///
/// let raw_sql = gen_statement!(&c,&conn).to_string();
/// assert_eq!(raw_sql,r#"INSERT INTO "cake" ("id", "name") VALUES (1, 'Apple Pie')"#);
///
/// let raw_sql = gen_statement!(&c,conn).to_string();
/// assert_eq!(raw_sql,r#"INSERT INTO "cake" ("id", "name") VALUES (1, 'Apple Pie')"#);
///
/// let raw_sql = gen_statement!(&c,DbBackend::MySql).to_string();
/// assert_eq!(raw_sql,r#"INSERT INTO `cake` (`id`, `name`) VALUES (1, 'Apple Pie')"#);
///
/// let raw_sql = gen_statement!(&c,&DbBackend::MySql).to_string();
/// assert_eq!(raw_sql,r#"INSERT INTO `cake` (`id`, `name`) VALUES (1, 'Apple Pie')"#);
///
/// ```
#[macro_export]
macro_rules! gen_statement {
($query:expr,$value:expr) => {
$crate::DebugQuery {
query: $query,
value: $value,
}
.build();
};
}

/// Use `debug_query` macro get raw_sql.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "mock")]
/// # use sea_orm::{error::*, tests_cfg::*, MockDatabase, MockExecResult, Transaction, DbBackend};
/// #
/// # let conn = MockDatabase::new(DbBackend::Postgres)
/// # .into_connection();
/// #
/// use sea_orm::{entity::*, query::*, tests_cfg::cake,debug_query};
///
/// let c = cake::Entity::insert(
/// cake::ActiveModel {
/// id: ActiveValue::set(1),
/// name: ActiveValue::set("Apple Pie".to_owned()),
/// });
///
/// let raw_sql = debug_query!(&c,&conn);
/// assert_eq!(raw_sql,r#"INSERT INTO "cake" ("id", "name") VALUES (1, 'Apple Pie')"#);
///
/// let raw_sql = debug_query!(&c,conn);
/// assert_eq!(raw_sql,r#"INSERT INTO "cake" ("id", "name") VALUES (1, 'Apple Pie')"#);
///
/// let raw_sql = debug_query!(&c,DbBackend::Sqlite);
/// assert_eq!(raw_sql,r#"INSERT INTO `cake` (`id`, `name`) VALUES (1, 'Apple Pie')"#);
///
/// ```
#[macro_export]
macro_rules! debug_query {
($query:expr,$value:expr) => {
$crate::gen_statement!($query, $value).to_string();
};
}
14 changes: 7 additions & 7 deletions tests/common/setup/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use sea_orm::{Database, DatabaseBackend, DatabaseConnection, Statement};
use sea_orm::{Database, DatabaseConnection, DbBackend, Statement};
pub mod schema;
pub use schema::*;

Expand All @@ -8,14 +8,14 @@ pub async fn setup(base_url: &str, db_name: &str) -> DatabaseConnection {
let db = Database::connect(&url).await.unwrap();
let _drop_db_result = db
.execute(Statement::from_string(
DatabaseBackend::MySql,
DbBackend::MySql,
format!("DROP DATABASE IF EXISTS `{}`;", db_name),
))
.await;

let _create_db_result = db
.execute(Statement::from_string(
DatabaseBackend::MySql,
DbBackend::MySql,
format!("CREATE DATABASE `{}`;", db_name),
))
.await;
Expand All @@ -27,14 +27,14 @@ pub async fn setup(base_url: &str, db_name: &str) -> DatabaseConnection {
let db = Database::connect(&url).await.unwrap();
let _drop_db_result = db
.execute(Statement::from_string(
DatabaseBackend::Postgres,
DbBackend::Postgres,
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
))
.await;

let _create_db_result = db
.execute(Statement::from_string(
DatabaseBackend::Postgres,
DbBackend::Postgres,
format!("CREATE DATABASE \"{}\";", db_name),
))
.await;
Expand Down Expand Up @@ -63,7 +63,7 @@ pub async fn tear_down(base_url: &str, db_name: &str) {
let db = Database::connect(&url).await.unwrap();
let _ = db
.execute(Statement::from_string(
DatabaseBackend::MySql,
DbBackend::MySql,
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
))
.await;
Expand All @@ -72,7 +72,7 @@ pub async fn tear_down(base_url: &str, db_name: &str) {
let db = Database::connect(&url).await.unwrap();
let _ = db
.execute(Statement::from_string(
DatabaseBackend::Postgres,
DbBackend::Postgres,
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
))
.await;
Expand Down

0 comments on commit 49efca7

Please sign in to comment.