Four isolation types of MYSQL transactions and source code interpretation and practical application in PHP framework Yii2

Posted by ankrah on Sun, 19 Dec 2021 14:17:25 +0100

There are no weak people in life, only those who are unwilling to work hard.


1, What is a transaction

Transaction is the basic unit of concurrency control. The so-called transaction is a sequence of operations. These operations are either executed or not executed. It is an inseparable work unit. Transaction is the unit for maintaining data consistency in the database. At the end of each transaction, data consistency can be maintained.

2, Characteristics of transactions

ACID refers to atomicity, consistency, isolation and persistence.

1. Atomicity

All operations in a transaction are either completed or not completed, and will not end at an intermediate stage. If an error occurs during the execution of the transaction, it will be rolled back to the state before the transaction starts, as if the transaction had never been executed.

2. Consistency

Before and after the transaction, the integrity of the database is not destroyed. This means that the written data must fully comply with all preset rules, including the accuracy and serialization of the data, and the subsequent database can spontaneously complete the predetermined work.

3. Isolation

The database allows multiple concurrent transactions to read, write and modify their data at the same time. Isolation can prevent data inconsistency caused by cross execution when multiple transactions are executed concurrently. Transaction isolation is divided into different levels, including Read uncommitted, read committed, repeatable read, and Serializable.

4. Persistence

After the transaction is completed, the data modification is permanent and will not be lost even if the system fails.

3, Isolation level of transaction

The severity of transaction isolation level is from top to bottom

  1. Read uncommitted
  2. read committed
  3. repeatable read
  4. Serializable

1. Read uncommitted

One transaction reads uncommitted data from other transactions, which is the lowest level isolation mechanism.

2. read committed

One transaction reads the data committed by other transactions

3. repeatable read

A transaction reads the same data from the same copy, regardless of the modification of data by other transactions

4. Serializable

The transaction is executed serially, with the highest isolation level, sacrificing the concurrency of the system

5, Because of possible problems with transactions

1. Dirty reading

Transaction A reads the data updated by transaction B, and then transaction B rolls back the operation. Then the data read by transaction A is dirty data.

2. Non repeatable reading

Transaction A reads the same data multiple times, and transaction B updates and commits the data during the multiple reads of transaction A, resulting in inconsistent results when transaction A reads the same data multiple times.

3. Unreal reading

Reading data in the same range in the same transaction results in more or less data, which is called phantom reading. (for the same transaction, the range with ID < 10 is queried twice. Two pieces of data with id=8 and 9 appear for the first time and three pieces of data with id=7, 8 and 9 appear for the second time).

6, Effects of four isolation levels on dirty reading, unrepeatable reading and phantom reading

Dirty readingNon repeatable readingUnreal reading
Read uncommitted***
read committed**
repeatable read*
Serializable

7, How to use transactions in Yii2

1. Source location and interpretation

The location of Yii2's transaction related code is vendor / yiisoft / Yii2 / db / connection php

    /**
     * Starts a transaction.
     * @param string|null $isolationLevel The isolation level to use for this transaction.
     * See [[Transaction::begin()]] for details.
     * @return Transaction the transaction initiated
     */
    public function beginTransaction($isolationLevel = null)
    {
        $this->open();

        if (($transaction = $this->getTransaction()) === null) {
            $transaction = $this->_transaction = new Transaction(['db' => $this]);
        }
        $transaction->begin($isolationLevel);

        return $transaction;
    }

The method to set the transaction isolation type is as follows

    /**
     * Sets the isolation level of the current transaction.
     * @param string $level The transaction isolation level to use for this transaction.
     * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]], [[Transaction::REPEATABLE_READ]]
     * and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific syntax to be used
     * after `SET TRANSACTION ISOLATION LEVEL`.
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
     */
    public function setTransactionIsolationLevel($level)
    {
        $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
    }

Through annotation, we can find that the four isolation types are set by constants respectively

  • Transaction::READ_UNCOMMITTED
  • Transaction::READ_COMMITTED
  • Transaction::REPEATABLE_READ
  • Transaction::SERIALIZABLE

Constant location: vendor / yiisoft / yii2 / db / transaction php

    /**
     * A constant representing the transaction isolation level `READ UNCOMMITTED`.
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
     */
    const READ_UNCOMMITTED = 'READ UNCOMMITTED';
    /**
     * A constant representing the transaction isolation level `READ COMMITTED`.
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
     */
    const READ_COMMITTED = 'READ COMMITTED';
    /**
     * A constant representing the transaction isolation level `REPEATABLE READ`.
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
     */
    const REPEATABLE_READ = 'REPEATABLE READ';
    /**
     * A constant representing the transaction isolation level `SERIALIZABLE`.
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
     */
    const SERIALIZABLE = 'SERIALIZABLE';

be careful! The method of setting isolation type has no default value, so you must bring parameters when starting a transaction!

2. Start transaction in business logic

Start with the code. The following is the basic usage of general business opening transactions.

      $transaction = Yii::$app->db->beginTransaction();
        try {
          //Here you can read and write the model
          
          $transaction->commit();
            return true;
        }catch(\Exception $e) {
            $transaction->rollBack();
            return false;
        }

The basic logic is

  1. Open transaction
  2. try catch to catch exceptions
  3. If there is no catch exception, the last call is submitted to $transaction->commit ();
  4. If an exception is caught, roll back $transaction - > rollback();

8, Summary

It is necessary for developers to master and understand transactions, and also master the usage of transactions in complex businesses, so as to ensure the consistency of business data.

Topics: PHP Database MySQL