import threading
import time
import json
import os
class ACIDDatabase:
def __init__(self, db_name='acid_db'):
self.db_name = db_name
self.store = {} # In-memory storage
self.lock = threading.Lock() # Global lock for Isolation
self.log_file = f"{db_name}.wal"
# Recover state from previous run (Durability)
self._recover()
def _recover(self):
"""Reads the WAL to restore the state of the database."""
if not os.path.exists(self.log_file):
return
print("[SYSTEM] Recovering state from WAL...")
with open(self.log_file, 'r') as f:
for line in f:
if line.strip():
entry = json.loads(line)
op = entry['op']
key = entry['key']
if op == 'SET':
self.store[key] = entry['value']
elif op == 'DEL':
if key in self.store:
del self.store[key]
print(f"[SYSTEM] Recovery complete. Keys loaded: {len(self.store)}")
def _persist_op(self, op, key, value=None):
"""Appends an operation to the Write-Ahead Log (Durability)."""
entry = {'op': op, 'key': key, 'value': value}
with open(self.log_file, 'a') as f:
f.write(json.dumps(entry) + '\n')
# Ensure data is physically written to disk
f.flush()
os.fsync(f.fileno())
def get(self, key):
"""Read operation (needs lock for isolation)."""
with self.lock:
return self.store.get(key)
def set(self, key, value):
"""Write operation."""
with self.lock:
# 1. Write to Log (Atomicity/Durability)
self._persist_op('SET', key, value)
# 2. Apply to memory
self.store[key] = value
return True
def delete(self, key):
"""Delete operation."""
with self.lock:
if key in self.store:
# 1. Write to Log
self._persist_op('DEL', key)
# 2. Apply to memory
del self.store[key]
return True
return False
def begin_transaction(self):
"""Returns a Transaction object."""
return Transaction(self)
class Transaction:
"""
Implements Atomicity and Isolation for a sequence of operations.
"""
def __init__(self, db):
self.db = db
self.local_buffer = {} # Uncommitted changes
self.deleted_keys = set() # Keys marked for deletion
self.committed = False
def set(self, key, value):
"""Stage a set operation."""
self.local_buffer[key] = value
if key in self.deleted_keys:
self.deleted_keys.remove(key)
def get(self, key):
"""
Read operation checks local buffer first (Read Your Own Writes),
then checks the global store.
"""
if key in self.deleted_keys:
return None
if key in self.local_buffer:
return self.local_buffer[key]
# We need to lock the main DB to read consistently
# (In a real DB, we might take a 'read lock' here)
with self.db.lock:
return self.db.store.get(key)
def delete(self, key):
"""Stage a delete operation."""
self.deleted_keys.add(key)
if key in self.local_buffer:
del self.local_buffer[key]
def commit(self):
"""
Apply all changes to the global DB.
Uses a Global Lock for Strict Isolation.
"""
if self.committed:
raise Exception("Transaction already committed")
print(f"[TX] Attempting commit with {len(self.local_buffer)} sets and {len(self.deleted_keys)} deletes...")
# ACID: Isolation
# Acquire the global lock so no one else can read/write
with self.db.lock:
# ACID: Durability & Atomicity
# We apply changes to the log and memory inside the lock.
# Apply Deletes
for key in self.deleted_keys:
if key in self.db.store:
self.db._persist_op('DEL', key)
del self.db.store[key]
# Apply Sets
for key, value in self.local_buffer.items():
self.db._persist_op('SET', key, value)
self.db.store[key] = value
self.committed = True
print("[TX] Commit Successful.")
def rollback(self):
"""
Discard changes (Atomicity).
"""
print("[TX] Rolling back transaction...")
self.local_buffer.clear()
self.deleted_keys.clear()
self.committed = True # Mark as finished
# --- Demonstration Script ---
def worker_thread(db, key, value):
"""Simulates a client doing a transaction."""
try:
t = db.begin_transaction()
print(f"Thread {threading.current_thread().name} starting transaction...")
# Simulate some logic
current = t.get(key)
print(f"Thread {threading.current_thread().name} read {key}: {current}")
time.sleep(0.1) # Simulate delay to force concurrency conflict
t.set(key, value)
print(f"Thread {threading.current_thread().name} updated {key} to {value}")
t.commit()
except Exception as e:
print(f"Error in thread: {e}")
if __name__ == "__main__":
# Clean up old files for demo
if os.path.exists("acid_db.wal"):
os.remove("acid_db.wal")
print("--- 1. Basic ACID Demo ---")
db = ACIDDatabase()
# Transaction 1: Simple Set
t1 = db.begin_transaction()
t1.set("account_a", 100)
t1.set("account_b", 50)
t1.commit()
print(f"Value of account_a: {db.get('account_a')}")
print("\n--- 2. Atomicity & Rollback Demo ---")
t2 = db.begin_transaction()
t2.set("account_a", 9999) # Change value
# Check uncommitted read within transaction
print(f"Inside T2 (before rollback): {t2.get('account_a')}")
t2.rollback() # Cancel changes
# Check committed value
print(f"Inside Main (after rollback): {db.get('account_a')}")
print("\n--- 3. Durability Demo (Crash Simulation) ---")
# We kill the object (simulating crash) and create a new one.
# The new one should read the WAL and restore data.
del db
print("Re-instantiating database (Simulating restart)...")
new_db = ACIDDatabase()
print(f"Value of account_a after recovery: {new_db.get('account_a')}")
print("\n--- 4. Isolation Demo (Concurrency) ---")
# Create a race condition scenario
new_db.set("counter", 0)
threads = []
# Create 5 threads trying to increment the counter
# Note: Without proper locking in the logic below, we'd get race conditions.
# But our Transaction class takes a global lock on commit.
def increment_logic():
t = new_db.begin_transaction()
val = t.get("counter")
# If we sleep here, we verify that the global lock on commit prevents
# the "Lost Update" problem effectively because the reads are fast,
# but commits are serialized.
val += 1
t.set("counter", val)
t.commit()
for i in range(5):
th = threading.Thread(target=increment_logic)
threads.append(th)
th.start()
for th in threads:
th.join()
print(f"Final counter value (expected 5): {new_db.get('counter')}")