Skip to content

Commit

Permalink
Added execute_unprepared method to DatabaseConnection and `Databa…
Browse files Browse the repository at this point in the history
…seTransaction` (SeaQL/sea-orm#1327)
  • Loading branch information
billy1624 committed Feb 2, 2023
1 parent ca2a9b6 commit f9026a1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
36 changes: 26 additions & 10 deletions SeaORM/docs/03-migration/02-writing-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
}
```
Expand Down
9 changes: 9 additions & 0 deletions SeaORM/docs/05-basic-crud/08-raw-sql.md
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
```

0 comments on commit f9026a1

Please sign in to comment.