Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add debug_query macro make get raw_sql becomes simply. #189

Merged
merged 27 commits into from
Oct 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
4377bd4
add debug_query make get raw_sql becomes simply.
baoyachi Sep 23, 2021
8f08529
refactor code with macro debug_query!
baoyachi Sep 23, 2021
aa7e053
update doc
baoyachi Sep 23, 2021
10eeca1
add DbConnection with DebugQuey build overload method. Working for #145
baoyachi Sep 23, 2021
536a900
all rename with DbBackEnd
baoyachi Sep 24, 2021
9af9637
define IntoDbBackEnd trait
baoyachi Sep 24, 2021
849ffeb
fix build error
baoyachi Sep 24, 2021
a1bbb72
fix build error
baoyachi Sep 24, 2021
55ecf46
refactor code IntoDbBackend
baoyachi Sep 25, 2021
08f19cc
cargo fmt
baoyachi Sep 26, 2021
ba6d2d9
rename marco
baoyachi Sep 26, 2021
de0fd2a
Merge branch 'master' of github.com:SeaQL/sea-orm
baoyachi Sep 26, 2021
ece6b62
cargo fmt
baoyachi Sep 26, 2021
d2702dd
fix build test error
baoyachi Sep 27, 2021
fae268a
fix example build error
baoyachi Sep 27, 2021
b2bb259
remove warning
baoyachi Sep 27, 2021
9afd7dd
Merge branch 'adapter_url_scheme'
baoyachi Sep 27, 2021
37133d0
Merge branch 'master' of github.com:SeaQL/sea-orm
baoyachi Sep 27, 2021
1c0be92
Merge branch 'master' of github.com:SeaQL/sea-orm
baoyachi Sep 30, 2021
1083844
remove IntoDbBackend
baoyachi Oct 2, 2021
806f20b
Merge branch 'master' of github.com:SeaQL/sea-orm
baoyachi Oct 2, 2021
f987d3e
cargo fmt
baoyachi Oct 2, 2021
fa9999d
cargo fmt code
baoyachi Oct 2, 2021
bad6d0d
add DbBackend ref with DebugQuery
baoyachi Oct 2, 2021
1b3b5c4
update
baoyachi Oct 2, 2021
897a385
refactor code
baoyachi Oct 2, 2021
0c9334b
refactor code
baoyachi Oct 2, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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