Transactions & ACID
What are ACID Transactions?
Section titled “What are ACID Transactions?”ACID transactions ensure data integrity and consistency in HaruDB:
- Atomicity: All operations in a transaction succeed or all fail
- Consistency: Database remains in a valid state before and after transactions
- Isolation: Concurrent transactions don’t interfere with each other
- Durability: Committed changes persist even after system crashes
Basic Transaction Commands
Section titled “Basic Transaction Commands”BEGIN TRANSACTION
Section titled “BEGIN TRANSACTION”Start a new transaction. All subsequent operations will be part of this transaction until committed or rolled back.
-- Start a transactionBEGIN TRANSACTION;
-- Or use the shorter formBEGIN;
COMMIT
Section titled “COMMIT”Commit all changes made within the current transaction, making them permanent.
-- Commit the transactionCOMMIT;
ROLLBACK
Section titled “ROLLBACK”Undo all changes made within the current transaction, returning the database to its state before the transaction began.
-- Rollback the transactionROLLBACK;
Complete Transaction Example
Section titled “Complete Transaction Example”-- Create sample tablesCREATE TABLE accounts (id, name, balance);CREATE TABLE transactions (id, from_account, to_account, amount, timestamp);
-- Insert initial dataINSERT INTO accounts VALUES (1, 'Alice', '1000');INSERT INTO accounts VALUES (2, 'Bob', '500');
-- Begin transactionBEGIN TRANSACTION;
-- Transfer money from Alice to BobUPDATE accounts SET balance = '900' ROW 0; -- Alice: 1000 -> 900UPDATE accounts SET balance = '600' ROW 1; -- Bob: 500 -> 600
-- Record the transactionINSERT INTO transactions VALUES (1, 1, 2, '100', '2024-01-15 10:30:00');
-- Commit the transactionCOMMIT;
-- Verify the changesSELECT * FROM accounts;SELECT * FROM transactions;
Savepoints
Section titled “Savepoints”Savepoints allow you to create intermediate checkpoints within a transaction, enabling partial rollbacks.
SAVEPOINT
Section titled “SAVEPOINT”Create a named savepoint within the current transaction.
SAVEPOINT savepoint_name;
ROLLBACK TO SAVEPOINT
Section titled “ROLLBACK TO SAVEPOINT”Rollback to a specific savepoint, undoing all changes made after that savepoint.
ROLLBACK TO SAVEPOINT savepoint_name;
Savepoint Example
Section titled “Savepoint Example”-- Create tableCREATE TABLE orders (id, customer_id, product_id, quantity, total);
-- Begin transactionBEGIN TRANSACTION;
-- Insert first orderINSERT INTO orders VALUES (1, 1, 1, 2, '199.98');SAVEPOINT sp1;
-- Insert second orderINSERT INTO orders VALUES (2, 1, 2, 1, '29.99');SAVEPOINT sp2;
-- Insert third orderINSERT INTO orders VALUES (3, 2, 1, 1, '99.99');
-- Check current stateSELECT * FROM orders;
-- Rollback to second savepoint (undoes third order)ROLLBACK TO SAVEPOINT sp2;SELECT * FROM orders;
-- Rollback to first savepoint (undoes second and third orders)ROLLBACK TO SAVEPOINT sp1;SELECT * FROM orders;
-- Commit remaining changesCOMMIT;
Isolation Levels
Section titled “Isolation Levels”HaruDB supports different isolation levels to control how transactions interact with each other.
READ COMMITTED
Section titled “READ COMMITTED”Default isolation level. Allows reading committed data from other transactions.
BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;-- Transaction operationsCOMMIT;
REPEATABLE READ
Section titled “REPEATABLE READ”Ensures that repeated reads within the same transaction return the same data.
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;-- Transaction operationsCOMMIT;
SERIALIZABLE
Section titled “SERIALIZABLE”Highest isolation level. Ensures complete isolation from other transactions.
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;-- Transaction operationsCOMMIT;
Isolation Level Example
Section titled “Isolation Level Example”-- Create tableCREATE TABLE inventory (id, product_name, stock);
-- Insert dataINSERT INTO inventory VALUES (1, 'Laptop', '10');INSERT INTO inventory VALUES (2, 'Mouse', '50');
-- Transaction 1 (Serializable)BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;SELECT * FROM inventory WHERE product_name = 'Laptop';-- Process order...UPDATE inventory SET stock = '9' ROW 0;COMMIT;
-- Transaction 2 (Read Committed)BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;SELECT * FROM inventory WHERE product_name = 'Laptop';-- Process another order...UPDATE inventory SET stock = '8' ROW 0;COMMIT;
Multi-Table Transactions
Section titled “Multi-Table Transactions”Transactions can span multiple tables, ensuring data consistency across related operations.
E-commerce Example
Section titled “E-commerce Example”-- Create tablesCREATE TABLE customers (id, name, email, balance);CREATE TABLE products (id, name, price, stock);CREATE TABLE orders (id, customer_id, product_id, quantity, total, order_date);CREATE TABLE order_items (id, order_id, product_id, quantity, price);
-- Insert sample dataINSERT INTO customers VALUES (1, 'Alice', 'alice@example.com', '1000');INSERT INTO products VALUES (1, 'Laptop', '999.99', '5');INSERT INTO products VALUES (2, 'Mouse', '29.99', '20');
-- Multi-table transactionBEGIN TRANSACTION;
-- Create orderINSERT INTO orders VALUES (1, 1, 1, 1, '999.99', '2024-01-15');INSERT INTO order_items VALUES (1, 1, 1, 1, '999.99');
-- Update inventoryUPDATE products SET stock = '4' ROW 0;
-- Update customer balanceUPDATE customers SET balance = '0.01' ROW 0;
-- Commit all changesCOMMIT;
-- Verify consistencySELECT * FROM customers;SELECT * FROM products;SELECT * FROM orders;SELECT * FROM order_items;
Error Handling in Transactions
Section titled “Error Handling in Transactions”HaruDB provides robust error handling within transactions, allowing you to gracefully handle failures.
Error Handling Example
Section titled “Error Handling Example”-- Create tableCREATE TABLE users (id, name, email, age);
-- Insert valid dataINSERT INTO users VALUES (1, 'Alice', 'alice@example.com', '25');
-- Transaction with error handlingBEGIN TRANSACTION;
-- Valid operationINSERT INTO users VALUES (2, 'Bob', 'bob@example.com', '30');
-- This will fail (invalid row index)UPDATE users SET age = '31' ROW 10;
-- Check if we should rollback-- In a real application, you'd check the error and decideROLLBACK;
-- Verify rollback workedSELECT * FROM users;
Conditional Transaction Logic
Section titled “Conditional Transaction Logic”-- Create tableCREATE TABLE accounts (id, name, balance);
-- Insert dataINSERT INTO accounts VALUES (1, 'Alice', '1000');INSERT INTO accounts VALUES (2, 'Bob', '500');
-- Transaction with conditional logicBEGIN TRANSACTION;
-- Check if Alice has enough balanceSELECT * FROM accounts WHERE id = '1' AND balance >= '100';
-- If balance is sufficient, proceed with transferUPDATE accounts SET balance = '900' ROW 0; -- Alice: 1000 -> 900UPDATE accounts SET balance = '600' ROW 1; -- Bob: 500 -> 600
-- Commit if all operations succeededCOMMIT;
-- Verify the transferSELECT * FROM accounts;
Large Transaction Performance
Section titled “Large Transaction Performance”HaruDB efficiently handles bulk operations within transactions.
Bulk Insert Example
Section titled “Bulk Insert Example”-- Create tableCREATE TABLE logs (id, timestamp, level, message);
-- Begin transactionBEGIN TRANSACTION;
-- Bulk insert many log entriesINSERT INTO logs VALUES (1, '2024-01-15 10:00:00', 'INFO', 'Application started');INSERT INTO logs VALUES (2, '2024-01-15 10:01:00', 'INFO', 'User login: alice');INSERT INTO logs VALUES (3, '2024-01-15 10:02:00', 'INFO', 'User login: bob');INSERT INTO logs VALUES (4, '2024-01-15 10:03:00', 'WARN', 'High memory usage');INSERT INTO logs VALUES (5, '2024-01-15 10:04:00', 'INFO', 'User logout: alice');INSERT INTO logs VALUES (6, '2024-01-15 10:05:00', 'ERROR', 'Database connection failed');INSERT INTO logs VALUES (7, '2024-01-15 10:06:00', 'INFO', 'Database reconnected');INSERT INTO logs VALUES (8, '2024-01-15 10:07:00', 'INFO', 'User logout: bob');
-- Commit all log entries at onceCOMMIT;
-- Verify bulk insertSELECT COUNT(*) FROM logs;SELECT * FROM logs WHERE level = 'ERROR';
Bulk Update Example
Section titled “Bulk Update Example”-- Create tableCREATE TABLE products (id, name, price, category, discount);
-- Insert dataINSERT INTO products VALUES (1, 'Laptop', '999.99', 'Electronics', '0');INSERT INTO products VALUES (2, 'Mouse', '29.99', 'Electronics', '0');INSERT INTO products VALUES (3, 'Keyboard', '79.99', 'Electronics', '0');INSERT INTO products VALUES (4, 'Desk', '199.99', 'Furniture', '0');INSERT INTO products VALUES (5, 'Chair', '149.99', 'Furniture', '0');
-- Begin transactionBEGIN TRANSACTION;
-- Apply 10% discount to all electronicsUPDATE products SET discount = '10' ROW 0; -- LaptopUPDATE products SET discount = '10' ROW 1; -- MouseUPDATE products SET discount = '10' ROW 2; -- Keyboard
-- Apply 15% discount to all furnitureUPDATE products SET discount = '15' ROW 3; -- DeskUPDATE products SET discount = '15' ROW 4; -- Chair
-- Commit all updatesCOMMIT;
-- Verify bulk updatesSELECT * FROM products WHERE category = 'Electronics';SELECT * FROM products WHERE category = 'Furniture';
WAL Integration
Section titled “WAL Integration”All transaction operations are automatically logged to the Write-Ahead Log (WAL) for crash recovery.
WAL Benefits
Section titled “WAL Benefits”- Crash Recovery: If the system crashes during a transaction, WAL ensures data integrity
- Atomicity: All transaction operations are logged before being applied
- Durability: Committed changes are guaranteed to persist
WAL Example
Section titled “WAL Example”-- Create tableCREATE TABLE critical_data (id, value, timestamp);
-- Begin transactionBEGIN TRANSACTION;
-- Insert critical dataINSERT INTO critical_data VALUES (1, 'Important Value 1', '2024-01-15 10:00:00');INSERT INTO critical_data VALUES (2, 'Important Value 2', '2024-01-15 10:01:00');
-- Update dataUPDATE critical_data SET value = 'Updated Value 1' ROW 0;
-- Commit (all operations logged to WAL)COMMIT;
-- Even if system crashes now, data is safeSELECT * FROM critical_data;
Best Practices
Section titled “Best Practices”Transaction Design
Section titled “Transaction Design”- Keep transactions short: Long transactions can cause performance issues
- Use appropriate isolation levels: Choose the lowest isolation level that meets your needs
- Handle errors gracefully: Always check for errors and rollback when necessary
Performance Optimization
Section titled “Performance Optimization”- Batch operations: Group related operations in single transactions
- Avoid unnecessary locks: Use appropriate isolation levels
- Monitor transaction duration: Long transactions can impact performance
Data Consistency
Section titled “Data Consistency”- Validate data before transactions: Check constraints before beginning
- Use savepoints for complex operations: Allow partial rollbacks when needed
- Test error scenarios: Ensure your application handles transaction failures correctly
Common Transaction Patterns
Section titled “Common Transaction Patterns”Account Transfer Pattern
Section titled “Account Transfer Pattern”-- Transfer money between accountsBEGIN TRANSACTION;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;COMMIT;
Order Processing Pattern
Section titled “Order Processing Pattern”-- Process an orderBEGIN TRANSACTION;INSERT INTO orders VALUES (1, 1, 1, 1, '99.99', '2024-01-15');UPDATE inventory SET stock = stock - 1 WHERE id = 1;UPDATE customers SET balance = balance - 99.99 WHERE id = 1;COMMIT;
Audit Trail Pattern
Section titled “Audit Trail Pattern”-- Create audit trailBEGIN TRANSACTION;UPDATE users SET last_login = '2024-01-15 10:00:00' ROW 0;INSERT INTO audit_log VALUES (1, 'LOGIN', 'user_id=1', '2024-01-15 10:00:00');COMMIT;
For more information about HaruDB’s architecture, see the WAL documentation and Storage Engine documentation.