A brief introduction to the transaction mechanism in MySQL

start with a question

 

There has been a lot of trouble with the bank recently. Many depositors put their money in the bank and disappear, and the bank doesn't care about it. socialism". Let's complain less, have more trees, and don't talk about state affairs.

 

When it comes to depositing money in the bank, we have to talk about the matter of withdrawing money from the bank. The simple matter of withdrawing money from an ATM machine is actually mainly divided into the following steps:

 

  1.     Log in to the ATM machine and enter the password;
  2.     Connect to the database and verify the password;
  3.     After successful verification, obtain user information, such as deposit balance, etc.;
  4.     The user enters the amount to be withdrawn and presses the confirm button;
  5.     Deduct the corresponding amount on the user's account from the backend database;
  6.     ATM spit out money;
  7.     The user takes the money.

 

A simple withdrawal of money is mainly divided into the above steps. I don't know if you have "naively" thought, if in step 5, the money has been deducted from the background database, but the ATM still does not spit out the money (although it has actually happened, but it is a low-probability event after all) ,How to do this?

 

The developers of the banking system have long thought about this problem, so how did they solve this problem? This is about the concept of affairs summarized today.
simple business affairs

 

For the above withdrawal of money, if there is an error in one step, then the entire withdrawal of money will be canceled; in simple terms, the 7 steps of withdrawing money, either complete or do nothing. In a database, the same is true for transactions.

 

A transaction consists of one or more sql statements. For operations in a transaction, these sql statements are either executed or none of them are executed. This is the purpose of the transaction.

 

For a transaction, it needs to meet the ACID characteristics. The following briefly talks about the ACID characteristics of the transaction.

 

    A, represents atomicity; atomicity means that the entire database transaction is an indivisible unit of work. The execution of the entire transaction is successful only if all database operations in the transaction are executed successfully. If any sql statement in the transaction fails to be executed, the sql statement that has been successfully executed must also be cancelled, and the database state should return to the state before the transaction is executed;
    C means consistency; that is to say, consistency means that the transaction changes the database from a state Change to another consistent state, before the transaction starts and after the transaction ends, the integrity constraints of the database are not destroyed;
    I, for isolation; isolation is also called concurrency control, serializability, or locks. The isolation of transactions requires that the objects of each read-write transaction and the operation objects of other transactions can be separated from each other, that is, the transaction is not visible to other transactions until it is committed, which is usually achieved by using locks;
    D, persistence, means that once the transaction is committed The result is permanent, that is, the data has been written to the database. If an accident such as downtime occurs, the database can also restore the data.

 

Summarized some basic concepts of transactions. In MySQL, transactions are still divided into many types. Let's take a look at what transactions there are.
what business

 

Can you imagine it? Just such a broken transaction will be divided into the following types:

 

  1.     flat business;
  2.     flat transactions with savepoints;
  3.     chain transaction;
  4.     nested transactions;
  5.     Distributed transactions.

 

Now let's briefly summarize these transactions at the conceptual level.

 

    Flat transaction
    Flat transaction is the simplest and the most used transaction in actual development. In this kind of transaction, all operations are at the same level, the most common way is as follows:

 

?
1
2
3
4
5
6
7
BEGIN WORK
   Operation 1
   Operation 2
   Operation 3
   ...
   Operation N
COMMIT WORK

 

    or this:

 

?
1
2
3
4
5
6
7
8
BEGIN WORK
   Operation 1
   Operation 2
   Operation 3
   ...
   Operation N
   (Error Occured)
ROLLBACK WORK

 

    The main disadvantage of flat transactions is the inability to commit or rollback part of the transaction, or to commit in several separate steps. For example, there is such an example, I go to Shenzhen from Hohhot, for the sake of cheap, I may do this:

 

?
1
2
3
4
BEGIN WORK
   Operation1:呼和浩特 ---火车--->北京
   Operation2:北京 ---飞机--->深圳
ROLLBACK WORK

 

    But what if Operation 1, the train from Hohhot to Beijing is delayed and the flight is missed? I feel the characteristics of flat transactions, then I need to roll back, and then I go back to Hohhot, so the cost is too high, so there is the following second transaction - flat transaction with save point.
    Flat transactions with savepoints
    This type of transaction, in addition to supporting operations supported by flat transactions, allows rollback to an earlier state in the same transaction during transaction execution, because some transactions may occur during execution Errors do not invalidate all operations, and abandoning the entire transaction is undesirable and expensive. Savepoints are used to inform the system that the current state of the transaction should be remembered so that the transaction can return to that state in the event of a later error.
    Chain transaction
    Chain transaction means that when rolling back, only the most recent savepoint can be restored; while a flat transaction with a savepoint can be rolled back to any correct savepoint.
    Nested transactions
    Look at the following, you can understand what is a nested transaction:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
BEGIN WORK
   SubTransaction1:
       BEGIN WORK
         SubOperationX
       COMMIT WORK
   SubTransaction2:
       BEGIN WORK
         SubOperationY
       COMMIT WORK
   ...
   SubTransactionN:
       BEGIN WORK
         SubOperationN
       COMMIT WORK
COMMIT WORK

 

    This is the nested transaction, and the transaction is nested in the transaction, and the transaction at the root node is called the top-level transaction. The predecessors of a transaction are called parent transactions, and other transactions are called child transactions. The predecessor of the transaction is called the parent transaction, and the next level of the transaction is called the child transaction.

 

    A child transaction can be committed or rolled back, but its commit operation does not take effect immediately unless committed by its parent transaction. Therefore, it can be determined that any sub-transactions are actually committed after the top-level transaction is committed. Similarly, the rollback of any transaction will cause all its sub-transactions to be rolled back together.
    Distributed transactions
    Distributed transactions usually refer to flat transactions running in a distributed environment, so it is necessary to access different nodes in the network according to the location of the data, for example: transfer money to China Merchants Bank through China Construction Bank, China Construction Bank and China Merchants Bank must use The two databases are not the same database, and the two databases are not on the same network node, so when users transfer money across banks, the ACID of the data is guaranteed through distributed transactions.

 

Transactions in MySQL

 

No matter how good the theory is, it must be understood through practice. Let's talk about how transactions are used in MySQL.

 

Under the default settings of the MySQL command line, transactions are automatically committed, that is, the COMMIT operation will be executed immediately after the SQL statement is executed. Therefore, to open a transaction explicitly, use the command BEGIN or START TRANSACTION, or execute the command SET AUTOCOMMIT=0, to disable the use of automatic commit for the current session.

 

Let's see what transaction control statements we can use.

 

  1.     BEGIN or START TRANSACTION; explicitly start a transaction;
  2.     COMMIT; COMMIT WORK can also be used, but the two are equivalent. COMMIT commits the transaction and makes all modifications made to the database permanent;
  3.     ROLLBACK; it is possible to use ROLLBACK WORK, but the two are equivalent. Rollback ends the user's transaction and undoes all uncommitted modifications in progress;
  4.     SAVEPOINT identifier; SAVEPOINT allows to create a savepoint in a transaction, and there can be multiple SAVEPOINTs in a transaction;
  5.     RELEASE SAVEPOINT identifier; delete a savepoint of a transaction, when there is no specified savepoint, executing the statement will throw an exception;
  6.     ROLLBACK TO identifier; roll back the transaction to the point;
  7.     SET TRANSACTION; used to set the isolation level of the transaction. The transaction isolation levels provided by the InnoDB storage engine are READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.

 

You don't need to "control" these

 

Sometimes some SQL statements will generate an implicit commit operation, that is, after executing these statements, there will be an implicit COMMIT operation. There are the following SQL statements, you don't need to "manage":

 

  •     DDL语句,ALTER DATABASE、ALTER EVENT、ALTER PROCEDURE、ALTER TABLE、ALTER VIEW、CREATE TABLE、DROP TABLE、RENAME TABLE、TRUNCATE TABLE等;
  •     Modify the MYSQL schema statement, CREATE USER, DROP USER, GRANT, RENAME USER, REVOKE, SET PASSWORD;
  •     管理语句,ANALYZE TABLE、CACHE INDEX、CHECK TABLE、LOAD INDEX INTO CACHE、OPTIMIZE TABLE、REPAIR TABLE等。

 

The above SQL operations are all implicit commit operations and do not need to be manually and explicitly committed.
transaction isolation level

 

The above also mentioned that SET TRANSACTION is used to set the isolation level of the transaction. What is the isolation level of the transaction?

 

    In database operation, in order to effectively ensure the correctness of concurrently read data, the proposed transaction isolation level.

 

The transaction isolation levels provided by the InnoDB storage engine are READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE. The differences between these isolation levels are as follows:

 

2015413170207554.jpg (782×217)

 

  •     Dirty read: A transaction reads data that is not committed by another transaction;
  •     For example, transaction T1 updates the content of a row of records, but does not commit the changes. Transaction T2 reads the updated row of T1, and then T1 performs a rollback operation to cancel the modification just made. Now the line read by T2 is invalid;
  •     Non-repeatable read: In the same transaction, the same data is read twice, and the content is different;
  •     For example, transaction T1 reads a row of records, and then transaction T2 modifies the row of records that T1 just read. Then T1 reads this row of records again, and finds that the results are different from those just read. This is called a "non-repeatable" read, because the row that T1 originally read has changed;
  •     Phantom read: In the same transaction, the same operation is used to read twice, and the number of records obtained is different;
  •     For example, transaction T1 reads the result set returned by a specified WHERE clause. Then transaction T2 inserts a new row of records, which just meets the conditions of the WHERE clause in the query conditions used by T1. T1 then uses the same query to retrieve the table again, but now sees the new row that transaction T2 just inserted. This new row is called a "phantom" because it appears to T1 to appear suddenly.

 

The lower the isolation level, the fewer locks the transaction requests or the less time the locks are held. The default isolation level supported by the InnoDB storage engine is REPEATABLE READ; under this default transaction isolation level, the isolation requirements of the transaction can be fully guaranteed, that is, the SERIALIZABLE level isolation of the SQL standard is achieved.

 

We can use the SET TRANSACTION statement to change the isolation level for a single session or for all incoming connections. Its syntax is as follows:

 

?
1
SET [SESSION | GLOBAL ] TRANSACTION ISOLATION LEVEL { READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE }

 

Note: The default behavior (without session and global) is to set the isolation level for the next (unstarted) transaction. If the GLOBAL keyword is used, the statement globally sets the default transaction level for all new connections (except non-existing connections) created from that point on. You need SUPER permission to do this. Use the SESSION keyword to set the default transaction level for future transactions performed on the current connection. Any client is free to change the session isolation level (even in the middle of a transaction), or set the isolation level for the next transaction.

 

?
1
2
3
4
5
6
7
8
9
10
mysql> set session transaction isolation level repeatable read ;
Query OK, 0 rows affected (0.00 sec)
 
mysql> select @@tx_isolation;
+ -----------------+
| @@tx_isolation |
+ -----------------+
| REPEATABLE - READ |
+ -----------------+
1 row in set (0.00 sec)

 

Summarize

This article is basically the accumulation of theoretical concepts, and there are basically no practical things. But none of that is a problem, and that doesn't stop this article from being a reader favorite, does it. Well, this is the end of this article about transactions in MySQL. If there are new things in the future, I will continue to summarize.

 

http://www.jb51.net/article/64005.htm

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326990930&siteId=291194637