import sqlite3
import logging
import os
from datetime import datetime
from typing import List, Tuple, Optional
from threading import Lock
from contextlib import contextmanager
from enum import Enum
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('datastorage.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class DataCategory(Enum):
"""Enum for valid data categories"""
USER = "user"
PRODUCT = "product"
ORDER = "order"
TRANSACTION = "transaction"
EVENT = "event"
LOG = "log"
METRIC = "metric"
class DataStorage:
"""
A thread-safe and process-safe data storage class that allows storing and retrieving
data with categories, keys, associated values, additional data, and timestamps using SQLite as the backend.
"""
def __init__(self, db_path: str = "datastorage.db"):
"""
Initialize the DataStorage with a SQLite database.
Args:
db_path (str): Path to the SQLite database file
"""
self.db_path = db_path
self._lock = Lock() # Thread safety
self._initialize_database()
logger.info(f"DataStorage initialized with database at {db_path}")
def _initialize_database(self) -> None:
"""Initialize the database schema if it doesn't exist."""
try:
with self._get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS data_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
additional_data TEXT NOT NULL,
timestamp DATETIME NOT NULL,
UNIQUE(category, key)
)
""")
conn.commit()
except sqlite3.Error as e:
logger.error(f"Failed to initialize database: {e}")
raise RuntimeError(f"Database initialization failed: {e}")
@contextmanager
def _get_db_connection(self):
"""
Context manager for database connections with proper error handling
and connection management.
"""
conn = None
try:
conn = sqlite3.connect(
self.db_path,
timeout=10, # Wait up to 10 seconds for database lock
check_same_thread=False # Allow access from multiple threads
)
conn.execute('PRAGMA journal_mode=WAL') # Enable Write-Ahead Logging for better concurrency
yield conn
except sqlite3.Error as e:
logger.error(f"Database connection error: {e}")
raise
finally:
if conn:
conn.close()
def store(self, category: str, key: str, value: str, additional_data: str) -> bool:
"""
Store a data entry with an associated value, additional data, and the current timestamp.
Args:
category (str): One of the valid DataCategory values
key (str): The key to store the value under
value (str): The primary value to store
additional_data (str): Additional data associated with the key-value pair
Returns:
bool: True if successful, False otherwise
"""
try:
# Validate category
if category not in [cat.value for cat in DataCategory]:
raise ValueError(f"Invalid category. Must be one of {[cat.value for cat in DataCategory]}")
timestamp = datetime.utcnow().isoformat()
with self._lock: # Ensure thread safety
with self._get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
INSERT OR REPLACE INTO data_entries (category, key, value, additional_data, timestamp)
VALUES (?, ?, ?, ?, ?)
""", (category, key, value, additional_data, timestamp))
conn.commit()
logger.info(f"Stored data: category={category}, key={key}")
return True
except (sqlite3.Error, ValueError) as e:
logger.error(f"Failed to store data: {e}")
return False
def retrieve(self, category: str, key: str) -> Optional[Tuple[str, str, str]]:
"""
Retrieve a single data entry with its associated value, additional data, and timestamp.
Args:
category (str): The category to search in
key (str): The key to look up
Returns:
Optional[Tuple[str, str, str]]: (value, additional_data, timestamp) if found, None otherwise
"""
try:
# Validate category
if category not in [cat.value for cat in DataCategory]:
raise ValueError(f"Invalid category. Must be one of {[cat.value for cat in DataCategory]}")
with self._lock: # Ensure thread safety
with self._get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT value, additional_data, timestamp FROM data_entries
WHERE category = ? AND key = ?
""", (category, key))
result = cursor.fetchone()
if result:
logger.info(f"Retrieved data: category={category}, key={key}")
return (result[0], result[1], result[2])
return None
except (sqlite3.Error, ValueError) as e:
logger.error(f"Failed to retrieve data: {e}")
return None
def retrieve_by_category(self, category: str) -> List[Tuple[str, str, str, str]]:
"""
Retrieve all entries for a given category with their associated values, additional data, and timestamps.
Args:
category (str): The category to search in
Returns:
List[Tuple[str, str, str, str]]: List of (key, value, additional_data, timestamp) tuples
"""
try:
# Validate category
if category not in [cat.value for cat in DataCategory]:
raise ValueError(f"Invalid category. Must be one of {[cat.value for cat in DataCategory]}")
with self._lock: # Ensure thread safety
with self._get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT key, value, additional_data, timestamp FROM data_entries
WHERE category = ?
ORDER BY timestamp DESC
""", (category,))
results = cursor.fetchall()
logger.info(f"Retrieved {len(results)} entries for category={category}")
return results
except (sqlite3.Error, ValueError) as e:
logger.error(f"Failed to retrieve data by category: {e}")
return []
def cleanup(self) -> None:
"""Clean up resources and close any open connections."""
try:
if os.path.exists(self.db_path):
logger.info("Cleaning up database resources")
except Exception as e:
logger.error(f"Error during cleanup: {e}")
# Example usage
if __name__ == "__main__":
# Create storage instance
storage = DataStorage("example.db")
# Store some data with additional values
storage.store(DataCategory.USER.value, "user1", "John Doe", "john@example.com")
storage.store(DataCategory.USER.value, "user2", "Jane Smith", "jane@example.com")
storage.store(DataCategory.PRODUCT.value, "prod1", "Widget", "100 units")
# Retrieve single entry
result = storage.retrieve(DataCategory.USER.value, "user1")
if result:
value, additional_data, timestamp = result
print(f"Retrieved: {value}, Additional Data: {additional_data} (stored at {timestamp})")
# Retrieve all entries in a category
user_entries = storage.retrieve_by_category(DataCategory.USER.value)
print("\nAll user entries:")
for key, value, additional_data, timestamp in user_entries:
print(f"Key: {key}, Value: {value}, Additional Data: {additional_data}, Timestamp: {timestamp}")