leaf icon indicating copy to clipboard operation
leaf copied to clipboard

Database Rollback Not Triggered on Exception

Open WAZIRI123 opened this issue 1 year ago • 0 comments

Description

I am encountering an issue where database transactions are not rolling back when an exception occurs, which i think it may be a bug in the framework . Specifically, I am using db()->beginTransaction() to start a transaction, when an exception is thrown within the try block, the db()->rollBack() call in the catch block is not triggered, and the changes made within the transaction are still committed.

Steps to reproduce the behavior:

  1. Start a transaction with db()->beginTransaction().
  2. Perform multiple database operations inside a try block.
  3. Throw an exception within the try block (e.g., manually throw an exception or allow an error to occur).
  4. Call db()->rollBack() in the catch block.
  5. Check the database and observe that the changes have been committed instead of being rolled back.

Expected behavior

When an exception is thrown within a transaction, the db()->rollBack() function should be called, and no changes made within the transaction should be committed to the database. All changes should be undone.

Additional context

code sample: `public function addProject() { db()->beginTransaction(); // Start the transaction

try {
    // Simulate some database operations (e.g., creating a project)
    $project = Project::create([
        'name' => 'Test Project',
        'client_id' => 1,
    ]);

    // Intentionally throw an exception
    throw new \Exception("Simulated error");

    // Commit the transaction (won't be reached due to the exception)
    db()->commit();

} catch (\Exception $e) {
    // Rollback the transaction on error
    db()->rollBack();

    // Return the error message for debugging
    return response()->json([
        'status' => 'error',
        'message' => 'An error occurred: ' . $e->getMessage(),
    ]);
}

}

` environment : Leaf version: 3.3v PHP : 8.3.6v

WAZIRI123 avatar Oct 16 '24 13:10 WAZIRI123