Transaction¶
Transactions in SQL are a series of queries that are executed as a single unit of work. In GlueSQL, transactions help to ensure the consistency and integrity of the database. They follow the ACID properties: Atomicity, Consistency, Isolation, and Durability.
Note: In GlueSQL, transactions are an optional feature. Support for transactions depends on the storage engine being used. Currently, both SledStorage and RedbStorage support transactions, and additional storages may add support in the future. Transaction isolation levels may also vary depending on the storage engine. For example, the current transaction isolation level for SledStorage is SNAPSHOT ISOLATION.
BEGIN TRANSACTION¶
To start a new transaction, use the BEGIN keyword:
COMMIT TRANSACTION¶
To permanently save the changes made during the transaction, use the COMMIT keyword:
ROLLBACK TRANSACTION¶
To undo the changes made during the transaction and revert the database to its state before the transaction started, use the ROLLBACK keyword:
Example¶
Consider the following table TxTest with columns id (INTEGER) and name (TEXT):
Insert sample data into the table:
Inserting Data¶
Start a new transaction and insert a new row:
Rollback the transaction to undo the insertion:
Now, start a new transaction and insert a new row with different data:
Deleting Data¶
Start a new transaction and delete a row:
The deletion will be undone due to the rollback. To permanently delete the row, commit the transaction:
Updating Data¶
Start a new transaction and update a row:
The update will be undone due to the rollback. To permanently update the row, commit the transaction: