Analysis of mysql transaction-ACID characteristics

concept

A transaction is a set of atomic SQL queries, or an independent unit of work. If the database engine can successfully apply all the statements of the group of queries to the database, then execute the group of queries. If any of the statements cannot be executed because of a crash or other reasons, then all the statements will not be executed. In other words, all the statements in the transaction are executed successfully or all execution fails.

Life example

What we transfer is generally: deduct 100 yuan from your account, and then add 100 yuan to someone else's account. But if in the middle, due to some reasons (network problems), the deduction was made in your account, but it was not increased in your friend's account, then did we directly lose one hundred yuan? Did we find a bank? .

Therefore, in this case, you can put these two steps into one transaction. Either all succeeded, one hundred deducted from your account, and one hundred added to your friend's account; or all failed, and the operations that have been performed were returned and restored to the original state, my account was not deducted 100, and my friend's account was not added 100.

mysql architecture

Note : The transaction is implemented by the storage engine, and there is no special description below. The default innodb

Submit rollback

mysql> start transaction;#手动开启事务
mysql> update t21 set b = 77 where b = 7;
Query OK, 3 rows affected (0.00 sec)
mysql> commit;#commit之后即可改变底层数据库数据
mysql> select * from t_user;
| id | a | b  |
+----+---+----+
|  1 | 1 |  1 |
|  2 | 2 |  2 |
|  3 | 3 | 33 |
|  4 | 4 |  4 |
|  6 | 5 |  5 |
|  7 | 7 |  7 |
|  8 | 8 |  8 |
|  9 | 8 |  7 |
| 10 | 2 |  7 |
+----+---+----+
9 rows in set (0.00 sec)


mysql> start transaction;
mysql> insert into t21(a,b) values(3,3);
mysql> rollback;
mysql> select * from t_user;
| id | a | b  |
+----+---+----+
|  1 | 1 |  1 |
|  2 | 2 |  2 |
|  3 | 3 | 33 |
|  4 | 4 |  4 |
|  6 | 5 |  5 |
|  7 | 7 |  7 |
|  8 | 8 |  8 |
|  9 | 8 |  7 |
| 10 | 2 |  7 |
+----+---+----+
9 rows in set (0.00 sec)

Auto-commit is supported by default in mysql. In auto-commit mode, if there is no start transaction to explicitly start a transaction, then each SQL statement will be treated as a transaction to perform the commit operation.

Four characteristics of transaction

  1. ​ Atomicity (atomicity): Either perform all or none;
  2. ​ consistency (consistency): at the beginning and completion of the transaction, the data must be in a consistent state;
  3. ​Isolation (isolation): the intermediate state in the transaction process is invisible to the outside;
  4. ​Durability (durability): After the transaction is completed, its modification to the data is permanent.

Atomicity

definition

Atomicity means that a transaction is an indivisible unit of work, in which operations are either done or not done; if a SQL statement in the transaction fails, the executed statement must also be rolled back, and the database returns to before the transaction status.

Realization principle

The atomicity of mysql is achieved through the undo log . Next, let's briefly talk about the undo log.

Undo log is a logical log , which logically restores the database to its original appearance, and all modifications are logically cancelled.

That is, if it is an insert operation, the corresponding rollback operation is delete;

If it is delete, the corresponding rollback operation is insert;

If it is an update, the corresponding rollback operation is a reverse update operation.

Durability (durability)

definition

Persistence means that once a transaction is committed, its changes to the database should be permanent.

Realization principle

The durability of the transaction is achieved through the redo log . Let's briefly introduce the redo log below.

In contrast to the undo log, the redo log is a backup of new data. Before the transaction is committed, as long as the redo log is persisted, there is no need to persist the data. When the system crashes, just restore the data to the latest state according to the content of the redo log. For the specific content of the redo log, please refer to: mysql log file summary , I won’t talk about it here

Isolation

definition

Unlike atomicity and persistence, which focus on studying the affairs themselves, isolation studies the mutual influence between different affairs. Isolation means that the operations within a transaction are isolated from other transactions, and concurrent transactions cannot interfere with each other. Strict isolation corresponds to the Serializable in the transaction isolation level, but serializable is rarely used for performance considerations in practical applications.

Realization principle

The basic principle of the lock mechanism can be summarized as follows: the transaction needs to obtain the corresponding lock before modifying the data; after the lock is obtained, the transaction can modify the data; during the transaction operation, this part of the data is locked, and other transactions need to modify the data , You need to wait for the current transaction to commit or roll back and release the lock.

Row lock and table lock

According to granularity, locks can be divided into table locks, row locks, and other locks in between. Table lock locks the entire table when operating data, and the concurrency performance is poor; row lock only locks the data that needs to be operated, and has good concurrency performance. However, because the lock itself needs to consume resources (acquiring locks, checking locks, releasing locks, etc. all need to consume resources), using table locks can save a lot of resources when there are more locked data. The locks supported by different storage engines in MySQL are different. For example, MyIsam only supports table locks, while InnoDB supports table locks and row locks. For performance reasons, row locks are used in most cases.

How to view lock information

There are many ways to view the lock status in InnoDB, for example:

select * from information_schema.innodb_locks; #锁的概况
show engine innodb status; #InnoDB整体状态,其中包括锁的情况

Here is an example:

# 第一个客户端
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> update t21 set b = 77 where b = 7;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0


# 第二个客户端
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> update t21 set b = 77 where b = 7;

# 查询锁的情况
mysql> select * from information_schema.innodb_locks; 
+--------------+-------------+-----------+-----------+--------------+------------+------------+-----------+----------+-----------+
| lock_id      | lock_trx_id | lock_mode | lock_type | lock_table   | lock_index | lock_space | lock_page | lock_rec | lock_data |
+--------------+-------------+-----------+-----------+--------------+------------+------------+-----------+----------+-----------+
| 33048:41:3:2 | 33048       | X         | RECORD    | `muke`.`t21` | PRIMARY    |         41 |         3 |        2 | 1         |
| 33047:41:3:2 | 33047       | X         | RECORD    | `muke`.`t21` | PRIMARY    |         41 |         3 |        2 | 1         |
+--------------+-------------+-----------+-----------+--------------+------------+------------+-----------+----------+-----------+
2 rows in set, 1 warning (0.00 sec)

Through the above command, you can view the lock status of transactions 33048 and 33047; where lock_type is RECORD, which means that the lock is a row lock (record lock); lock_mode is X, which means an exclusive lock (write lock).

In addition to exclusive locks (write locks), there is also the concept of shared locks (read locks) in MySQL

Consistency

definition

Consistency means that after the transaction is executed, the integrity constraints of the database are not destroyed, and the data state is legal before and after the transaction is executed. The integrity constraints of the database include but are not limited to: entity integrity (such as the existence and uniqueness of the primary key of the row), column integrity (such as the type, size, and length of the field to meet the requirements), foreign key constraints, user-defined integrity ( For example, before and after the transfer, the sum of the balances of the two accounts should remain unchanged)

Realization principle

It can be said that consistency is the ultimate goal pursued by transactions: the atomicity, durability, and isolation mentioned earlier are all to ensure the consistency of the database state. In addition, in addition to guarantees at the database level, the realization of consistency also needs to be guaranteed at the application level.

Measures to achieve consistency include:

  • To ensure atomicity, durability and isolation, if these characteristics cannot be guaranteed, the consistency of the transaction cannot be guaranteed
  • The database itself provides guarantees, for example, it is not allowed to insert string values ​​into integer columns, and the string length cannot exceed the column limit, etc.
  • Application level protection, for example, if the transfer operation only deducts the balance of the transferor without increasing the balance of the recipient, no matter how perfect the database is implemented, the consistency of the state cannot be guaranteed.

Learning link

The mysql log can be viewed at this address: mysql log file summary

The mysql transaction isolation level can be seen at this address:  mysql transaction-four isolation levels

 

Books are ships of thought sailing in the waves of the times. They carefully transport precious goods to generation after generation. ----Bacon

Guess you like

Origin blog.csdn.net/lin_keys/article/details/108902819