MySQL transaction, isolation level

A transaction is a unit of program execution that accesses and updates various data items in a database. The operations in the transaction are either modified or not executed. This is the purpose of the transaction, and it is also one of the important characteristics of the transaction model that is different from the file system.

Strictly speaking, a transaction must satisfy four properties at the same time, which are commonly referred to as the ACID properties of a transaction. While strict transaction requirements are theoretically defined, database vendors do not strictly meet the ACID standard for transactions for various purposes. For example, for the NDB Cluster engine of MYSQL, although it supports transactions, it does not meet the requirements of D, that is, the requirements of persistence. For the Oracle database, its default transaction isolation level is READ COMMITTED, which does not meet the requirements of I, that is, the requirements of isolation. For the InnoDB storage engine, the default transaction isolation level is READ REPRATABLE, which fully complies with and satisfies the ACID characteristics of transactions.

A (atomicity), 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 execute, the SQL statement that has been successfully executed must also be cancelled, and the database state should return to the state before the transaction.

C (consistency), consistency. Consistency is when a transaction moves a database from one state to another. The integrity constraints of the database are not violated before the transaction begins and after the transaction ends.

I (isolation), isolation. Isolation has other names, such as concurrency control, serializability, 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. The database system provides a granular locking strategy that allows transactions to lock only a subset of entity objects, thereby improving the concurrency between transactions. (If it is a full table lock, there is basically no concurrency between transactions, but if only the rows processed in the table are locked, the concurrency of the transaction can be improved)

D (durability), persistence. Once a transaction is committed, its results are permanent. Even in the event of a failure such as downtime, the database can recover data. It should be noted that persistence can only guarantee the permanence of the results from the perspective of the transaction itself. For example, after the transaction is committed, all changes are permanent. Even when the database needs to be recovered due to a crash, it can also be guaranteed to be committed after recovery. data will not be lost.

The (ACID) nature of transactions is implemented by relational database management systems (RDBMS, database systems). Database management systems use logs to ensure atomicity, consistency, and durability of transactions. The log records the updates made by the transaction to the database. If an error occurs during the execution of a transaction, the update that the transaction has made to the database can be undone according to the log, so that the database returns to the initial state before executing the transaction. The database management system uses a locking mechanism to achieve transaction isolation. When multiple transactions update the same data in the database at the same time, only the transaction holding the lock is allowed to update the data, and other transactions must wait until the previous transaction releases the lock before other transactions have the opportunity to update the data.

Transaction classification

  • Flat transactions, the simplest, most frequently used transactions. In a flat transaction, all operations are at a level that starts with a BEGIN WORK and ends with a COMMIT WORK or ROLLBACK WORK. Operations in between are atomic, either all executed or all rolled back.
  • Flat transactions with savepoints, in addition to operations supported by flat transactions, allow rollback to an earlier state in the same transaction during transaction execution, because some transactions may have errors during execution that do not It is invalid for some operations, abandoning the entire transaction is not satisfactory, and the overhead is too high. 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 transactions can be viewed as a variant of the savepoint pattern.
  • Nested transactions are a hierarchical framework.
  • Distributed transaction

transaction control statement

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, you must use the commands BEGIN and START TRANSACTION, or execute the command SET AUTOCOMMIT = 0, to disable autocommit for the current session. The transaction control statement is as follows:

  • START TRANSACTION | BEGIN:显示的开启一个事务。在存储过程中,MYSQL数据库的分析器会自动将BEGIN识别为BEGIN...END,因此在存储过程中只能使用START TRANSACTION语句来开启一个事务。
  • COMMIT:要想使用这个语句的最简形式,只需发出COMMIT。COMMIT会提交事务,并使已对数据库进行的所有修改成为永久性的。COMMIT和COMMIT WORK语句基本上是一致的,都是用来提交事务。不同的是COMMIT WORK用来控制事务结束后的行为是CHAIN还是RELEASE的。如果是CHAIN方式,那么事务就变成了链事务。用户可以通过参数completion_type来进行控制,默认该参数是0,表示没有任何操作。在这种设置下,COMMIT和COMMIT WORK是完全等价的。当参数值为1时,COMMIT WORK等价于COMMIT AND CHAIN,表示马上自动开启一个相同隔离级别的事务。当参数值为1时,COMMIT WORK等价于COMMIT AND RELEASE。当提交事务后会自动断开与服务器连接。
  • ROLLBACK:回滚会结束用户的事务,并撤销正在进行的所有未提交的修改。
  • SAVEPOINT identifiter:SAVEPOINT允许用户在事务中创建一个保存点,一个事务可以有很多个保存点。
  • RELEASE SAVEPOINT identifier:删除一个事务的保存点,当没有一个保存点执行这语句时,会抛出一个异常。
  • ROLLBACK to [SAVEPOINT] identifier:这个语句与SAVEPOINT命令一起使用。可以把事务回滚到标记点,而不回滚到此标记点之前的任何工作。注意:虽然有ROLLBACK,但是它并没有真正的结束一个事务,因此即使执行了ROLLBACK TO SAVEPOINT,之后也需要显示的运行COMMIT或ROLLBACK命令。
  • SET TRANSACTION:这个语句用来设置事务的隔离级别。InnoDB存储引擎提供的事务隔离级别有READ UNCOMMITTED、READ COMMITTED、REPEATABLE READ和SERIALIZABLE。

事务的隔离级别

ANSI SQL标准定义的四个隔离级别为:

  1. READ UNCOMMITTED(未提交读),事务中的修改,即使没有提交,在其他事务也都是可见的。事务可以读取未提交的数据,这也被称为脏读。
  2. READ COMMITTED(提交读),一个事务从开始直到提交之前,所做的任何修改对其他事务都是不可见的。这个级别有时候也叫做不可重复读,因为两次执行相同的查询,可能会得到不一样的结果。因为在这2次读之间可能有其他事务更改这个数据,每次读到的数据都是已经提交的。
  3. REPEATABLE READ(可重复读),解决了脏读,也保证了在同一个事务中多次读取同样记录的结果是一致的。但是理论上,可重读读隔离级别还是无法解决另外一个幻读的问题,指的是当某个事务在读取某个范围内的记录时,另外一个事务也在该范围内插入了新的记录,当之前的事务再次读取该范围内的记录时,会产生幻行。
  4. SERIALIZABLE(可串行化),它通过强制事务串行执行,避免了前面说的幻读的问题。

1、脏读(dirty read):一个事务可以读取另一个尚未提交事务的修改数据。

2、不可重复读(nonrepeatable read):在同一个事务中,同一个查询在T1时间读取某一行,在T2时间重新读取这一行时候,这一行的数据已经发生修改,可能被更新了(update),也可能被删除了(delete)。

3、幻像读(phantom read):在同一事务中,同一查询多次进行时候,由于其他插入操作(insert)的事务提交,导致每次返回不同的结果集。

InnoDB采用MVCC来支持高并发,并实现了四个标准的隔离级别。其默认级别是REPEATABLE READ(可重复读),并且通过间隙锁(next-key locking)策略防止幻读的出现。间隙锁使得InnoDB不仅仅锁定查询涉及的行,还会对索引中的间隙进行锁定,以防止幻影的插入。

隔离级别越低,事务请求的锁越少或保持锁的时间就越短。所以很多数据库系统默认的事务隔离级别是READ COMMITTED。质疑SERIALIZABLE隔离级别的性能,但是InnoDB存储引擎认为两者的开销是一样的,所以默认隔离级别使用REPEATABLE READ。

用命令设置当前会话或全局会话的事务隔离级别。

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

如果想启动时就设置事务的默认隔离级别,修改MYSQL的配置文件,在[mysqld]中添加如下行:

[mysqld]
transaction-isolation = READ-COMMITTED

分布式事务编程

InnoDB存储引擎提供了对于XA事务的支持,并通过XA事务来支持分布式事务的实现。分布式事务指的是允许多个独立的事务资源参与到一个全局的事务中。事务资源通常是关系型数据库系统,也可以是其他类型的资源。全局事务要求在其中的所有参与的事务要么都提交,要么都回滚,这对于事务的ACID要求又有了提高。在使用分布式事务时,InnoDB存储引擎的事务隔离级别必须设置成SERIALIZALE。

XA事务由一个或多个资源管理器、一个事务管理器、以及一个应用程序组成。

  • 资源管理器:提供访问事务资源的方法。通常一个数据库就是一个资源管理器。
  • 事务管理器:协调参与全局事务中的各个事务。需要和参与到全局事务中的所有资源管理器进行通信。
  • 应用程序:定义事务的边界,指定全局事务中的操作。

在MYSQL数据库的分布式事务中,资源管理器就是MYSQL数据库,事务管理器为连接到MYSQL服务器的客户端。

分布式事务使用两段式提交(two-phase commit)的方式。在第一阶段,所有参与全局事务的节点都会开始准备(PREPARE),告诉事务管理器他们准备好了。第二阶段,事务管理器告诉资源管理器执行ROLLBACK或COMMIT。如果任何一个节点显示不能提交,则所有的节点都会被告知需要回滚。与本地事务不同的是,需要多一次的PREPARE操作,待收到所有节点的同意信息后,再进行COMMIT或ROLLBACK操作。

出处:http://www.cnblogs.com/wxw16/p/6128582.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325856843&siteId=291194637