cytsunny
cytsunny

Reputation: 5030

What would happen if DB::beginTransaction is called without DB::commit() in laravel5?

Normall, when using DB::beginTransaction(), it is used with DB::rollBack()

Something like this:

DB::beginTrnsaction();
try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

However, what if I forget to add the try catch loop?

i.e.

DB::beginTrnsaction();
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();

Will the database be changed if one of the insert goes wrong? Or it will automatically rollback?

Upvotes: 3

Views: 2956

Answers (2)

patricus
patricus

Reputation: 62368

If you start a transaction, but never commit or rollback, the transaction will automatically rollback when the connection to the database is closed.

For most PHP pages, this won't be a big deal, as the connection is usually closed once the request is complete.

However, if you are using persistent connections, this becomes a problem. With a persistent connection, the connection to the database does not end when the request is complete. The connection goes back into the connection pool, alive and well, and with the transaction still open. With the transaction still open, the locks on the records are still active, and this may block access to those records on following requests, until the connection is terminated and the rogue transaction can rollback.

When it comes to transactions, the shorter lived they are, the better. You want the transaction to be alive long enough to complete your unit of work, but you don't want it alive any longer than that. As soon as you can commit or rollback to complete the transaction, the less time other processes have to wait to get locks on those records. This can really affect high volume sites.

One thing you can do to take the responsibility away from yourself is to do your work inside of a Closure that is passed to the transaction() method. This will automatically take care of the start and commit/rollback of the transaction.

DB::transaction(function () {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);
});

If any Exception is thrown inside the Closure, the transaction is rolled back. Otherwise, the transaction will commit.

Upvotes: 3

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

Try to understand the concept:

BEGIN TRANSACTION -> Start from the last consist state of DB

Your code

if($condition)
{
    // ROLLBACK
}
else
{
    // COMMIT
}

ROLLBACK means to undo all the changes you have done and start from the last consistent state.

COMMIT means every thing is fine and you want to save the changes to make it persistent.

NOTE: If you do not commit than all the change are dropped.

Upvotes: 0

Related Questions