NOTE

1.33 InnoDB Transactions

InnoDB transactions begin with begin or start transaction and finish with commit or rollback. These notes cover transaction operations and their implementation.

DatabasesCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is a Transaction

Database Transactions.md

2. Using Transactions

  • Start a transaction: begin or start transaction.
  • Commit a transaction: commit.
    • Automatically committed transactions:
      • SHOW VARIABLES LIKE 'autocommit'
      • By default, each statement is an independent transaction.
  • Roll back a transaction: rollback.

3. Consistency

3.1. How It Is Implemented

4. Durability

4.1. How It Is Implemented

5. Atomicity

  • In MySQL, executing a statement happens inside a transaction, and the statement is atomic. If we want to define our own atomic operation, multiple SQL statements can be wrapped in a transaction.

5.1. How It Is Implemented

6. Isolation

6.1. Isolation Levels

6.1.1. Read Uncommitted

  • Prevents dirty writes; dirty reads, non-repeatable reads, and phantom reads can occur.

6.1.2. Read Committed

  • Prevents dirty writes and dirty reads; non-repeatable reads can occur.

6.1.3. Repeatable Read

  • Prevents dirty writes, dirty reads, non-repeatable reads, and phantom reads.

6.1.4. Serializable

  • Prevents dirty writes, dirty reads, non-repeatable reads, and phantom reads.

6.2. How It Is Implemented

6.2.1. Read Uncommitted

  • MVCC: because records modified by uncommitted transactions can be read, just read the latest version of the record directly.

6.2.2. Read Committed

  • MVCC: create a ReadView when each SQL statement starts executing. For example, each select generates an independent ReadView.

6.2.3. Repeatable Read

  • MVCC + GapLock
    • The ReadView is created when the transaction starts and is used throughout the lifetime of the transaction.
      • For example, a ReadView is generated during the first select.
    • MySQL solves the phantom-read problem under the RR level through GapLock.
  • The core of repeatable read is a consistent read; when a transaction updates data, it can only use a current read. If another transaction holds the row lock on the current record, the transaction must wait for the lock.

6.2.4. Serializable

Gap Lock

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub