From f9026a1c115a53d650425fd54c7a774faa4155c0 Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Thu, 2 Feb 2023 21:27:47 +0800 Subject: [PATCH] Added `execute_unprepared` method to `DatabaseConnection` and `DatabaseTransaction` (SeaQL/sea-orm#1327) --- .../docs/03-migration/02-writing-migration.md | 36 +++++++++++++------ SeaORM/docs/05-basic-crud/08-raw-sql.md | 9 +++++ 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/SeaORM/docs/03-migration/02-writing-migration.md b/SeaORM/docs/03-migration/02-writing-migration.md index c3c58ce7dea..1f8ff74c373 100644 --- a/SeaORM/docs/03-migration/02-writing-migration.md +++ b/SeaORM/docs/03-migration/02-writing-migration.md @@ -215,19 +215,35 @@ pub struct Migration; #[async_trait::async_trait] impl MigrationTrait for Migration { async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { - let sql = r#" - CREATE TABLE `cake` ( - `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, - `name` varchar(255) NOT NULL - )"#; - let stmt = Statement::from_string(manager.get_database_backend(), sql.to_owned()); - manager.get_connection().execute(stmt).await.map(|_| ()) + let db = manager.get_connection(); + + // Use `execute_unprepared` if the SQL statement doesn't have value bindings + db.execute_unprepared( + "CREATE TABLE `cake` ( + `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, + `name` varchar(255) NOT NULL + )" + ) + .await?; + + // Construct a `Statement` if the SQL contains value bindings + let stmt = Statement::from_sql_and_values( + manager.get_database_backend(), + r#"INSERT INTO `cake` (`name`) VALUES (?)"#, + ["Cheese Cake".into()] + ); + db.execute(stmt).await?; + + Ok(()) } async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { - let sql = "DROP TABLE `cake`"; - let stmt = Statement::from_string(manager.get_database_backend(), sql.to_owned()); - manager.get_connection().execute(stmt).await.map(|_| ()) + manager + .get_connection() + .execute_unprepared("DROP TABLE `cake`") + .await?; + + Ok(()) } } ``` diff --git a/SeaORM/docs/05-basic-crud/08-raw-sql.md b/SeaORM/docs/05-basic-crud/08-raw-sql.md index 72ce686b2a7..28be5eafafe 100644 --- a/SeaORM/docs/05-basic-crud/08-raw-sql.md +++ b/SeaORM/docs/05-basic-crud/08-raw-sql.md @@ -113,3 +113,12 @@ let exec_res: ExecResult = db .await?; assert_eq!(exec_res.rows_affected(), 1); ``` + +## Execute Unprepared SQL Statement + +You can execute an unprepared SQL statement with `ConnectionTrait::execute_unprepared()` method. + +```rust +let exec_res: ExecResult = + db.execute_unprepared("CREATE EXTENSION IF NOT EXISTS citext").await?; +```