Database Transactions, ACID Integrity & Automated Triggers
In this laboratory session, you will build directly upon your existing retail inventory database schema (categories, suppliers, and products) established in the previous activity. You will transition from read-only analytical queries to high-concurrency data modification workflows, mastering transaction boundaries (BEGIN TRANSACTION, COMMIT, ROLLBACK, SAVEPOINT) and autonomous database triggers (CREATE TRIGGER).
Continue using your existing SQLiteOnline workspace from the previous activity (Advanced SQL Queries – Subqueries, Views, and Filtering). All existing tables, views, and product records will be retained.
Learning Objectives
BEGIN TRANSACTION, COMMIT, and ROLLBACK.SAVEPOINT and roll back partial batches without aborting the entire sequence.AFTER INSERT triggers to automatically deduct physical stock inventory whenever customer orders are logged.BEFORE INSERT triggers with RAISE(ABORT) to prevent overselling and negative inventory balances.Schema Extension & Preparation
Ensure foreign keys are active. To support enterprise sales and transaction tracking, we will extend the existing retail inventory schema by creating two new related tables: orders and order_items, as well as an inventory_audit_log table for automated change tracking.
-- Step 1: Ensure Foreign Key Enforcement is Enabled
PRAGMA foreign_keys = ON;
-- Step 1.2: Create Orders Table
CREATE TABLE IF NOT EXISTS orders (
order_id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_name TEXT NOT NULL,
order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
total_amount DECIMAL(10, 2) DEFAULT 0.00,
status TEXT CHECK(status IN ('PENDING', 'COMPLETED', 'CANCELLED')) DEFAULT 'PENDING'
);
-- Step 1.3: Create Order Items Line Table (Linked to Products)
CREATE TABLE IF NOT EXISTS order_items (
item_id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity_ordered INTEGER NOT NULL CHECK(quantity_ordered > 0),
unit_price DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
-- Step 1.4: Create Inventory Audit Log Table
CREATE TABLE IF NOT EXISTS inventory_audit_log (
log_id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL,
action_type TEXT NOT NULL,
old_quantity INTEGER,
new_quantity INTEGER,
logged_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);Student Hands-On Tasks
Task 1Atomic Transaction Processing (BEGIN, COMMIT & ROLLBACK)
In enterprise systems, sales orders involve multiple interrelated operations: creating the order header, recording the line items, and deducting physical stock from the warehouse. If any step fails (e.g. invalid payment or server crash), Atomicity ensures that the entire batch is discarded via ROLLBACK, leaving no partial records.
Query 1.1: Successful Multi-Table Sale Execution (COMMIT)
Process an order for customer 'TechCorp Solutions' purchasing 2 units of product ID 1. Group the order creation, item addition, and stock deduction into a single atomic transaction block.
BEGIN TRANSACTION;
-- 1. Create order header
INSERT INTO orders (customer_name, total_amount, status)
VALUES ('TechCorp Solutions', 1500.00, 'COMPLETED');
-- 2. Insert line item for Product ID 1 (2 units @ 750.00 each)
INSERT INTO order_items (order_id, product_id, quantity_ordered, unit_price)
VALUES (last_insert_rowid(), 1, 2, 750.00);
-- 3. Deduct 2 units from products inventory
UPDATE products
SET quantity = quantity - 2
WHERE product_id = 1;
-- 4. Persist all changes atomically
COMMIT;
-- Verification Queries:
SELECT order_id, customer_name, total_amount, status FROM orders;
SELECT product_id, product_name, quantity FROM products WHERE product_id = 1;Query 1.2: Simulated Payment Failure & Atomicity Rollback (ROLLBACK)
Simulate a scenario where an order is placed and stock is decremented, but a simulated payment gateway timeout occurs. Issue a ROLLBACK to verify that neither the order nor the inventory deduction persists.
-- Check initial quantity before starting
SELECT product_id, product_name, quantity FROM products WHERE product_id = 2;
BEGIN TRANSACTION;
-- Step A: Insert a pending order
INSERT INTO orders (customer_name, total_amount, status)
VALUES ('Apex Dynamics', 4800.00, 'PENDING');
-- Step B: Insert order items
INSERT INTO order_items (order_id, product_id, quantity_ordered, unit_price)
VALUES (last_insert_rowid(), 2, 4, 1200.00);
-- Step C: Tentatively decrement inventory
UPDATE products
SET quantity = quantity - 4
WHERE product_id = 2;
-- SIMULATED FAILURE: Payment authorization was DECLINED by bank.
-- Abort all tentative changes:
ROLLBACK;
-- Verification Queries:
SELECT * FROM orders WHERE customer_name = 'Apex Dynamics';
SELECT product_id, product_name, quantity FROM products WHERE product_id = 2;Task 2Granular Transaction Control with SAVEPOINT
A SAVEPOINT allows a transaction to be partially rolled back without canceling preceding valid operations. This is essential for long-running batch jobs or multi-item carts where one item is out of stock but the rest should still be preserved.
Query 2.1: Partial Rollback Using Savepoints
Create a master transaction, process an initial order item, establish a savepoint, attempt an invalid experimental update, roll back to the savepoint, and finally commit the primary order.
SAVEPOINT sp_batch_order;
-- 1. Create order for Nexus Logistics
INSERT INTO orders (customer_name, total_amount, status)
VALUES ('Nexus Logistics', 600.00, 'COMPLETED');
-- 2. Mark an intermediate checkpoint
SAVEPOINT sp_line_item;
-- 3. Tentative invalid action: Updating non-existent product or accidental bad data
UPDATE products SET quantity = 9999 WHERE product_id = 999;
-- 4. Rollback only the invalid update, preserving the Nexus Logistics order!
ROLLBACK TO SAVEPOINT sp_line_item;
-- 5. Release and commit the outer transaction
RELEASE SAVEPOINT sp_batch_order;
-- Verification Query:
SELECT * FROM orders WHERE customer_name = 'Nexus Logistics';Task 3Automated Business Logic with Database Triggers (CREATE TRIGGER)
Manually issuing UPDATE products SET quantity = quantity - X with every purchase is vulnerable to developer error. A Database Trigger automatically fires server-side logic in response to INSERT, UPDATE, or DELETE events.
Task 3.1: Automatic Stock Deduction Trigger (AFTER INSERT)
Create a trigger named trg_deduct_inventory_after_sale that automatically decrements the corresponding product's quantity whenever a new record is inserted into order_items.
CREATE TRIGGER IF NOT EXISTS trg_deduct_inventory_after_sale
AFTER INSERT ON order_items
FOR EACH ROW
BEGIN
UPDATE products
SET quantity = quantity - NEW.quantity_ordered
WHERE product_id = NEW.product_id;
END;Task 3.2: Automated Audit Logging Trigger (AFTER UPDATE)
Create a trigger named trg_audit_inventory_changes that captures every inventory quantity modification on products and appends a row to inventory_audit_log recording OLD.quantity and NEW.quantity.
CREATE TRIGGER IF NOT EXISTS trg_audit_inventory_changes
AFTER UPDATE OF quantity ON products
FOR EACH ROW
WHEN OLD.quantity != NEW.quantity
BEGIN
INSERT INTO inventory_audit_log (product_id, action_type, old_quantity, new_quantity)
VALUES (
NEW.product_id,
CASE
WHEN NEW.quantity < OLD.quantity THEN 'SALE_DEDUCTION'
ELSE 'RESTOCK'
END,
OLD.quantity,
NEW.quantity
);
END;Task 3.3: Testing the Automated Trigger Pipeline
Insert a single line item into order_items without running any manual UPDATE statement. Observe how both triggers fire in sequence to deduct stock and log the audit trail.
-- Step 1: Check existing stock for Product ID 3
SELECT product_id, product_name, quantity FROM products WHERE product_id = 3;
-- Step 2: Insert order and order_item (Notice: NO manual UPDATE on products!)
INSERT INTO orders (customer_name, total_amount, status)
VALUES ('CyberLabs Inc.', 300.00, 'COMPLETED');
INSERT INTO order_items (order_id, product_id, quantity_ordered, unit_price)
VALUES (last_insert_rowid(), 3, 1, 300.00);
-- Step 3: Verify the automated cascade
SELECT product_id, product_name, quantity FROM products WHERE product_id = 3;
SELECT * FROM inventory_audit_log WHERE product_id = 3;Task 4Enforcing Constraints & Preventing Overselling (RAISE(ABORT))
What happens if a customer orders 50 units of a product when only 10 are in stock? Without defensive triggers, inventory quantities can drop into negative numbers. Using SQLite's RAISE(ABORT, 'message'), we can actively intercept and cancel bad operations before they corrupt data.
Task 4.1: Creating the Stock Underflow Prevention Trigger
Create a BEFORE INSERT ON order_items trigger named trg_prevent_negative_stock that checks if the ordered quantity exceeds available inventory and halts the query with an error.
CREATE TRIGGER IF NOT EXISTS trg_prevent_negative_stock
BEFORE INSERT ON order_items
FOR EACH ROW
WHEN (SELECT quantity FROM products WHERE product_id = NEW.product_id) < NEW.quantity_ordered
BEGIN
SELECT RAISE(ABORT, 'Transaction Aborted: Insufficient stock available for the requested product.');
END;Task 4.2: Testing the Abort Trigger Violation
Attempt to insert an order requesting 999 units for Product ID 1. Verify that SQLite blocks the transaction and displays your custom error message.
INSERT INTO orders (customer_name, total_amount, status)
VALUES ('Greedy Buyer LLC', 749250.00, 'PENDING');
-- This statement WILL FAIL and trigger RAISE(ABORT):
INSERT INTO order_items (order_id, product_id, quantity_ordered, unit_price)
VALUES (last_insert_rowid(), 1, 999, 750.00);Submission Deliverables
Compile your work into a PDF document named [LastName]_[FirstName]_Transactions_Triggers.pdf containing screenshots of the following outputs executed in SQLiteOnline:
Output showing the persisted record in orders and the corresponding deducted quantity in products.
Query output confirming that the simulated failed transaction for 'Apex Dynamics' left zero orphaned orders and no stock deduction.
Demonstration of ROLLBACK TO SAVEPOINT preserving the legitimate order while cleanly neutralizing the erroneous operation.
Output showing inventory_audit_log populated automatically alongside the decremented products.quantity without any manual update statements.
Output window showing SQLite halting the over-quantity insertion with the custom error message: Transaction Aborted: Insufficient stock available...