Skip to content

Commit

Permalink
refactor: combine if statement + unwrap_or_else into one match
Browse files Browse the repository at this point in the history
  • Loading branch information
bonsairobo committed Dec 3, 2024
1 parent 6a78180 commit 2705f20
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 15 deletions.
11 changes: 7 additions & 4 deletions sqlx-mysql/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ impl TransactionManager for MySqlTransactionManager {
) -> BoxFuture<'conn, Result<(), Error>> {
Box::pin(async move {
let depth = conn.inner.transaction_depth;
if statement.is_some() && depth > 0 {
return Err(Error::InvalidSavePointStatement);
}
let statement = statement.unwrap_or_else(|| begin_ansi_transaction_sql(depth));
let statement = match statement {
// custom `BEGIN` statements are not allowed if we're already in a transaction
// (we need to issue a `SAVEPOINT` instead)
Some(_) if depth > 0 => return Err(Error::InvalidSavePointStatement),
Some(statement) => statement,
None => begin_ansi_transaction_sql(depth),
};
conn.execute(&*statement).await?;
if !conn.in_transaction() {
return Err(Error::BeginFailed);
Expand Down
11 changes: 7 additions & 4 deletions sqlx-postgres/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@ impl TransactionManager for PgTransactionManager {
) -> BoxFuture<'conn, Result<(), Error>> {
Box::pin(async move {
let depth = conn.inner.transaction_depth;
if statement.is_some() && depth > 0 {
return Err(Error::InvalidSavePointStatement);
}
let statement = statement.unwrap_or_else(|| begin_ansi_transaction_sql(depth));
let statement = match statement {
// custom `BEGIN` statements are not allowed if we're already in
// a transaction (we need to issue a `SAVEPOINT` instead)
Some(_) if depth > 0 => return Err(Error::InvalidSavePointStatement),
Some(statement) => statement,
None => begin_ansi_transaction_sql(depth),
};

let rollback = Rollback::new(conn);
rollback.conn.queue_simple_query(&statement)?;
Expand Down
15 changes: 8 additions & 7 deletions sqlx-sqlite/src/connection/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,17 +184,18 @@ impl ConnectionWorker {
Command::Begin { tx, statement } => {
let depth = conn.transaction_depth;

let statement = if depth == 0 {
statement.unwrap_or_else(|| begin_ansi_transaction_sql(depth))
} else {
if statement.is_some() {
let statement = match statement {
// custom `BEGIN` statements are not allowed if
// we're already in a transaction (we need to
// issue a `SAVEPOINT` instead)
Some(_) if depth > 0 => {
if tx.blocking_send(Err(Error::InvalidSavePointStatement)).is_err() {
break;
}
continue;
}

begin_ansi_transaction_sql(depth)
},
Some(statement) => statement,
None => begin_ansi_transaction_sql(depth),
};

let res =
Expand Down

0 comments on commit 2705f20

Please sign in to comment.