Introduction to GaussDB database transactions

Table of contents

I. Introduction

2. Definition and application scenarios of GaussDB transactions

3. Management of GaussDB transactions

Four, GaussDB transaction statement

Five, GaussDB transaction isolation

Six, GaussDB transaction monitoring

7. Summary

I. Introduction

With the continuous development of big data and Internet technology, the role of database management system is becoming more and more important. Realizing fast data reading and writing and ensuring data security and integrity have become one of the most concerned issues when enterprises choose database technology. Transaction is one of the key mechanisms to ensure data consistency and integrity, so transaction management occupies an extremely important position in database technology. Here we will focus on the transaction support and management of Huawei Cloud Database GaussDB, including transaction application scenarios, transaction management, transaction statements, transaction isolation, transaction monitoring, etc.

2. Definition and application scenarios of GaussDB transactions

Transaction is an important concept in the database system. Generally speaking, a transaction is a group of database operations considered as a whole, and the whole is either executed successfully or cancelled.

Transactions can be applied to maintain data consistency when accessing the database concurrently. Some common application scenarios include transfer operations, order modification, bank transactions, etc. In these scenarios, the function of the transaction is to ensure the atomicity of the operation, that is, either all the operations are executed successfully, and the values ​​of the database are updated correctly, that is, in a "consistent state", or an exception or system failure occurs, and all roll back to the previous operation status to ensure the accuracy and completeness of the data.

GaussDB supports ACID transactions, namely Atomicity, Consistency, Isolation and Durability. In GaussDB, a transaction is a set of database operations that either all succeed or all fail. When a transaction commits, all modifications are permanently saved. If the transaction fails, all modifications will be rolled back, and the database state will be restored to the state before the transaction started. GaussDB also supports distributed transactions (cluster transactions), which can involve transactions of multiple nodes (this time I will not focus on it).

  • Atomicity: A transaction is the logical unit of work of the database, and the operations in the transaction are either done or not done.
  • Consistency: The execution result of the transaction must be to make the database change from one consistent state to another.
  • Isolation: The execution of a transaction in the database cannot be interfered with by other transactions. That is, the internal operations and data used by a transaction are isolated from other transactions, and the concurrently executed transactions cannot interfere with each other.
  • Durability: Once a transaction is committed, the changes to the data in the database are permanent. Committed operations or failures will not have any impact on the transaction's operational results.

 

3. Management of GaussDB transactions

Transaction management refers to the management of transaction opening, submission, rollback, savepoint, distributed transaction, etc. when using the database system:

  • Start a transaction: GaussDB starts a transaction through START TRANSACTION and BEGIN syntax
  • Set transaction: GaussDB sets transaction through SET TRANSACTION or SET LOCAL TRANSACTION syntax
  • Commit transaction: GaussDB can complete the function of submitting a transaction through COMMIT or END, that is, all operations of submitting a transaction
  • Rollback transaction: Rollback means that some kind of failure occurs during the operation of the transaction, the transaction cannot continue to execute, and the system cancels all completed operations on the database in the transaction

The stored procedure itself is in a transaction. When the outermost stored procedure is called, a transaction will be automatically opened, and it will be automatically committed at the end of the call or rolled back when an exception occurs. In addition to the system's automatic transaction control, COMMIT/ROLLBACK can also be used to control transactions in stored procedures. Calling the COMMIT/ROLLBACK command in the stored procedure will commit/rollback the current transaction and automatically open a new transaction, and all subsequent operations will run in this new transaction.

Example 1: Start a transaction

-- Start a transaction by default.

START TRANSACTION;

SELECT * FROM tpcds.reason;

END;

-- Start a transaction by default.

BEGIN;

SELECT * FROM tpcds.reason;

END;

-- Start the transaction with the isolation level as READ COMMITTED and read/write mode.

START TRANSACTION ISOLATION LEVEL READ COMMITTED READ WRITE;

SELECT * FROM tpcds.reason;

COMMIT;

Example 2: Setting up a transaction

--Start a transaction, set the isolation level of the transaction to READ COMMITTED, and the access mode to READ ONLY.

START TRANSACTION;

SET LOCAL TRANSACTION ISOLATION LEVEL READ COMMITTED READ ONLY;

COMMIT;

Example 3: Support the use of COMMIT/ROLLBACK in PLSQL stored procedures.

CREATE TABLE EXAMPLE1(COL1 INT);

CREATE OR REPLACE PROCEDURE TRANSACTION_EXAMPLE()

AS

BEGIN

    FOR i IN 0..20 LOOP

        INSERT INTO EXAMPLE1(COL1) VALUES (i);

        IF i % 2 = 0 THEN

            COMMIT;

        ELSE

            ROLLBACK;

        END IF;

    END LOOP;

END;

/

operation result:

In GaussDB, two methods can be used to control management transactions: atomicity and isolation. Atomicity means that a set of operations are either all performed or none of them are performed. Isolation means that the operation of a transaction is not interfered by other transactions, ensuring data consistency during concurrent execution.

For more usage scenarios in the transaction management process (contexts that support/do not support calls), please refer to the official website example:

Transaction Management_ApsaraDB for GaussDB_Development Guide (Master/Standby Version_Version 2.x)_Stored Procedure_HUAWEI CLOUD

Four, GaussDB transaction statement

A transaction statement can be regarded as a group of statements executed in a transaction. Common transaction statements include insert, update, delete, and so on.

GaussDB supports transaction statements, which are combined into a set of atomic, isolated and consistent operations. For example, all of the queries below are contained within the same transaction slice. If any one query fails, the entire transaction will be rolled back. The following are examples of transaction statements:

BEGIN;

SELECT balance FROM account WHERE id = 1  FOR UPDATE;

UPDATE account SET balance = balance - 100 WHERE id = 1;

COMMIT;

五、GaussDB事务隔离

GaussDB支持的事务隔离级别包括:Read Uncommitted(读未提交)、Read Committed(读提交)、Repeatable Read(重复读)、Serializable(序列化,Serializable 是最高的事务隔离级别,在该级别下,事务串行化顺序执行,可以避免脏读、不可重复读与幻读。但是这种事务隔离级别效率低下,比较耗数据库性能,一般不建议使用)。

语法:

{
        SET [ LOCAL ] TRANSACTION|SET SESSION CHARACTERISTICS AS TRANSACTION }
  {
        ISOLATION LEVEL {
        READ COMMITTED | READ UNCOMMITTED | SERIALIZABLE | REPEATABLE READ }
  | {
        READ WRITE | READ ONLY } } [, ...]

1. Read Uncommitted 隔离级别:最低的隔离级别,它允许提交了但尚未被写入磁盘的事务修改的数据被其他事务所读取。

SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

2. Read Committed 隔离级别:这个级别保证一个事务所见到的数据,要么是提交事务所修改的(已经将数据更新至磁盘),要么就是其他提交事务所修改的。

SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED;

3. Repeatable Read 隔离级别:保证在一个事务内重复执行的查询返回的结果集是一样的。特别地,在这个级别的情况下,在事务中第一次读表时就会自动获取到所有被查询记录的共享锁,直到关闭连接为止。

SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ;

4. Serializable 隔离级别:这个级别最高,实现方法是对数据进行锁定,以保证在写操作(INSERT、DELETE 和 UPDATE 等)期间数据不会被访问。

SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE;

六、GaussDB事务监控

事务监控是指对事务进行实时的监控,包括事务的状态、执行时间、执行语句、执行结果等。

事务监控可以对数据库操作进行记录和追踪,包括事务开始和结束的时间、事务中执行的语句、事务提交或回滚的状态等。可以通过这些信息来监控事务的执行情况,优化性能和调整配置。

华为云数据库GaussDB支持ACID事务,事务隔离级别支持读已提交、可重复读、序列化三种,并具有分布式事务支持功能。在实际应用中,GaussDB的事务机制可适用于金融账务、电商订单、物流管理等多种场景。

例如,在电商订单场景中,可以在一个事务中包含插入订单、更新库存、生成支付信息等相关操作,确保这些操作全部成功或全部失败,而不会出现其中某个操作提交,其他操作失败的情况。

而在日常开发中,要注意对事务的合理使用,避免在一个事务中执行过多的操作,尽可能缩小事务的范围,减少事务的执行时间,从而提高系统的并发性能。

事务监控可以对数据库操作进行记录和追踪,包括事务开始和结束的时间、事务中执行的语句、事务提交或回滚的状态等。可以通过这些信息来监控事务的执行情况,优化性能和调整配置。以下是事务监控的示例:

1. 查看活动事务信息(PG_PREPARED_XACTS视图显示当前准备好进行两阶段提交的事务的信息

select * from pg_prepared_xacts;

2. 查看事务状态(PG_STAT_ACTIVITY视图显示和当前用户查询相关的信息。

select pid, datname, usename, query, query_start, state from pg_stat_activity where state != 'idle' and state != 'idle in transaction';

七、总结

事务是保证数据一致性和完整性的核心机制之一,对于一个数据库来说,事务的支持和管理是必须的。GaussDB通过支持手动和自动管理事务、事务隔离级别以及事务监控等功能,满足了企业对数据一致性和完整性的需求。在日常开发中,需要特别注意事务的控制和隔离,以保证事务的正确执行,从而提高数据的可靠性和安全性。

本文介绍到此结束,更多操作可在实际应用中参考官方文档,欢迎交流、学习!

{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/gaussdb/blog/8657347