Database Transactions

12002

Introduction to This Lesson

This lesson will delve into the fundamental concepts of MySQL transaction processing, particularly the use of transactions in application development. We will understand the usage scenarios of transactions in application development through the case of jianghuknex transaction processing for bills, and familiarize ourselves with transaction commit and rollback operations by reading documentation.

1. Basic Concepts of Transaction Processing

What is Transaction Processing

Transaction processing is a key component of database management systems, used to manage sequences of operations within a database. When we need to execute a series of database operations, such as inserting, updating, or deleting data, we treat these operations as a whole. Transactions ensure that these operations either all succeed or all fail, thereby maintaining data integrity and consistency.

For example, when you withdraw money from a bank, you need to take a certain amount from one account. If there is an issue with the banking system or you enter an incorrect amount during this process, you may need to cancel the withdrawal and redo the operation. The withdrawal process can be viewed as a transaction, and transaction processing ensures that your withdrawal operation either succeeds entirely or fails entirely, maintaining the accuracy and consistency of the account balance.

MySQL Transaction Processing

The methods of transaction processing may vary depending on the type of database. In relational databases, MySQL transaction processing is a critical feature.

MySQL transaction processing is a key function that ensures the consistency and integrity of data operations. By using transactions, a series of database operations can be executed as an atomic operation, either all successfully committed or all rolled back, thus avoiding data inconsistency. MySQL transactions adhere to the ACID properties (Atomicity, Consistency, Isolation, Durability), which ensure the correctness and reliability of data in concurrent operations. In application development, effectively utilizing MySQL transaction processing can ensure data security, especially when dealing with complex operations or multi-table operations.

2. The Use of Transaction Processing in Application Development

Understanding Common Application Scenarios and Importance of Transaction Processing in Application Development

The importance of transaction processing in enterprise applications is self-evident, especially in scenarios where data integrity and consistency must be guaranteed. Here are several common application scenarios that demonstrate the critical role of transaction processing in application development:

  • Transfer Operations:

In a transfer process, it is essential to ensure that the operations of deducting money from one account and depositing it into another account are atomic—either all succeed or all fail—to avoid data loss or duplicate deductions.

  • Order Processing:

During order processing, multiple operations may be involved, such as reducing inventory and generating shipping orders. Using transactions can ensure the consistency of these operations, preventing issues like insufficient inventory or failed shipping order generation.

  • Database Backup:

When performing database backups, it is necessary to ensure that the backed-up data is in a consistent state. Using transactions can ensure the atomicity of the backup operation, preventing changes during the backup process from affecting the backup results.

  • Batch Operations:

When executing a series of operations, using transactions can guarantee the atomicity and consistency of these operations. If any step fails, the entire transaction can be rolled back, avoiding an inconsistent state.

Through transaction processing, developers can ensure the safety and consistency of data operations, enhancing system reliability. Transaction processing effectively addresses issues in data operations, ensuring the correctness of data operations and allowing applications to run stably under various conditions.

Case Study: jianghuknex Transaction Processing for Bills

In JianghuJS, we use jianghuknex to handle data transactions. jianghuKnex is a wrapper that adds data history features on top of Knex, simplifying interactions between developers and common databases. In terms of transaction processing, jianghuKnex leverages Knex's transaction features, making database transaction handling more convenient. Compared to native Knex, jianghuKnex provides a more straightforward approach to transaction processing, eliminating the need for explicit commit and rollback operations.

When using jianghuKnex for transaction processing, developers can utilize its encapsulated methods to execute a series of database operations and commit the transaction using COMMIT to ensure all changes take effect permanently; or roll back the transaction using ROLLBACK to undo all changes, maintaining database consistency.

Taking bill processing as an example, we can understand jianghuknex transactions:

    // Transaction processing
    await jianghuKnex.transaction(async trx => {
      // Write bill
      if(dataArray.length > 0){
      // Check if there is bill data
        await trx(tableEnum.payment_record, ctx).jhInsert(dataArray);
         // Insert data from dataArray into payment_record table
      }
      
      // Update bill
      for(const item of updateArray){
       // Iterate through the array of bills to be updated
        await trx(tableEnum.bill, ctx).where({ billId: item.billId }).jhUpdate(item);
        // Update the corresponding bill data based on bill ID
      }

This example uses the jianghuKnex.transaction method for transaction processing, including two operations: writing bills and updating bills:

  1. await jianghuKnex.transaction(async trx => { ... });: Here, a transaction object trx is created through the jianghuKnex.transaction method, executing a series of database operations within this transaction. All operations either succeed and are committed or are rolled back.

  2. if(dataArray.length > 0){ await trx(tableEnum.payment_record, ctx).jhInsert(dataArray); }: This part of the code writes bill data within the transaction. It first checks if the dataArray has data, and if so, it performs a bulk insert operation in the payment_record table using the jhInsert method to insert data from the dataArray into the database.

  3. for(const item of updateArray){ await trx(tableEnum.bill, ctx).where({ billId: item.billId }).jhUpdate(item); }: This part of the code updates bill data within the transaction. It iterates through each element item in the billUpdateData array, then uses the trx object to match the current element's billId value in the bill table and updates the corresponding bill data using the jhUpdate method.

By placing these operations in the same transaction, we can ensure that both writing and updating bills either succeed entirely and are committed or, in the event of an error, are all rolled back, thus maintaining the consistency and integrity of database operations. This method of transaction processing is particularly useful for handling complex database operations, effectively managing the data change process.

3. Reading Documentation to Learn About MySQL Transaction Commit and Rollback

After understanding the concept of transaction processing and its application scenarios in development, we can further explore the usage of MySQL transactions, particularly commit and rollback operations, by reading documentation.

The Role of the BEGIN Statement

The BEGIN statement is used to explicitly start a transaction. In MySQL, when the BEGIN statement is executed, it marks the starting point of the transaction. All operations between BEGIN and COMMIT (or ROLLBACK) will be treated as a single transaction until it is explicitly committed or rolled back.

BEGIN; 
-- Execute a series of database operations here
COMMIT;

Committing a Transaction: The COMMIT Statement

The COMMIT statement is used to permanently save all operations in the transaction to the database. When the COMMIT statement is executed, all operations in the transaction will be committed, and even if a database failure occurs, the committed changes will not be lost. Once a transaction is committed, it cannot be rolled back to the state before the transaction began.

BEGIN;
-- Execute a series of database operations here, such as inserting data
INSERT INTO student (studentId, studentName, gender) VALUES (101, 'Xiao Cao', 'Female');
COMMIT;

In this example, we start a transaction (BEGIN) and then insert a record into the student table, including studentId 101, name Xiao Cao, and gender Female. When we execute COMMIT, this insert operation will be permanently saved to the database.

Rolling Back a Transaction: The ROLLBACK Statement

The ROLLBACK statement is used to undo all operations in the transaction, restoring the database to the state before the transaction began. When the ROLLBACK statement is executed, all operations in the transaction will be undone, and the database will not save any changes made during that transaction.

BEGIN;
-- Execute a series of database operations here, such as inserting data
INSERT INTO student (studentId, studentName, gender) VALUES (101, 'Xiao Hua', 'Female');
ROLLBACK;

In this example, we start a transaction (BEGIN) and then insert a record into the student table, including studentId 101, name Xiao Hua, and gender Female. However, if a record with ID 1 already exists, the insert operation will fail. By executing ROLLBACK, we can undo this insert operation, and the database will revert to the state before the transaction began, ensuring data integrity.

By using the BEGIN, COMMIT, and ROLLBACK statements, we can effectively manage transactions in MySQL, ensuring the consistency and integrity of data operations.

Reference: MySQL Transactions