Below is an updated version of the SQLiteDB class based on your requests. I'll explain the changes and improvements first, then provide the full code.
Key Changes and Improvements:
-
Finding User ID by Name (or Any Key):
- Added a new method
get_id_by_key(table_name, key, value): This retrieves the ID of an item based on any key-value pair (e.g., find ID by name). It returns the ID (int) if found, or None if not. This is more general than limiting it to just "name," but you can use it for that purpose (e.g., get_id_by_key('users', 'name', 'John Doe')).
- This builds on
find_item() but simplifies to return only the ID, avoiding the need to fetch the full item and extract the ID manually.
-
Simplifying Schema Definition (More Pythonic):
- Instead of a raw
Dict[str, str], I've introduced a Column dataclass (using Python's dataclasses module) for defining columns in a more structured, type-safe, and Pythonic way.
- Example:
Column(name='id', type='INTEGER', primary_key=True, auto_increment=True)
- This is easier to read/write and less error-prone than strings.
- Supports extras like
not_null, default, and foreign_key (see below).
- The
create_db_with_table method now accepts a list of Column objects (e.g., [Column(...), Column(...)]).
- It automatically generates the SQL column definition string from the
Column objects, making it more intuitive and Python-native.
-
Adding Foreign Key Support:
- Added a
foreign_key parameter to the Column dataclass, which accepts a tuple like ('referenced_table', 'referenced_column') (e.g., foreign_key=('users', 'id')).
- This automatically appends
REFERENCES referenced_table(referenced_column) to the column definition in SQL.
- You can also add
on_delete or on_update actions (e.g., on_delete='CASCADE' for cascading deletes).
-
Extra Type Hints:
- Enhanced type hints throughout the class for better IDE support and static type checking (e.g., using
Optional, List, Union).
- The
Column dataclass has full type hints.
-
Auto-Commit and Auto-Close:
- Auto-Commit: Already handled in the original code (commits after every successful
_execute_query). I've made it more explicit by adding an optional auto_commit parameter to methods that modify data (defaults to True). If set to False, you can manually call commit() for batch operations.
- Auto-Close: Already supported via the context manager (
with statement). I've added an explicit auto_close flag in the constructor (defaults to True), which closes the connection automatically when the object is garbage-collected (via __del__). However, using with is still recommended for safety.
-
Other Improvements:
- Added a
commit() method for manual commits (useful if auto_commit=False).
- Added a
delete_item(table_name, item_id) method to complete the CRUD (Delete was missing).
- Improved error messages and handling.
- Kept dictionary-based data handling for CRUD operations (easy for JSON-like data).
- Example usage updated to demonstrate the new features, including foreign keys and ID lookup by name.
Full Updated Code
import sqlite3
from typing import Any, Dict, List, Optional, Tuple, Union
from dataclasses import dataclass, field
@dataclass
class Column:
name: str
type: str # e.g., 'INTEGER', 'TEXT', 'REAL'
primary_key: bool = False
auto_increment: bool = False
not_null: bool = False
default: Optional[Union[str, int, float]] = None
foreign_key: Optional[Tuple[str, str]] = None # (referenced_table, referenced_column)
on_delete: Optional[str] = None # e.g., 'CASCADE', 'SET NULL'
on_update: Optional[str] = None # e.g., 'CASCADE'
def to_sql(self) -> str:
parts = [f"{self.name} {self.type}"]
if self.primary_key:
parts.append("PRIMARY KEY")
if self.auto_increment:
parts.append("AUTOINCREMENT")
if self.not_null:
parts.append("NOT NULL")
if self.default is not None:
parts.append(f"DEFAULT {self.default}")
if self.foreign_key:
ref_table, ref_col = self.foreign_key
fk_clause = f"REFERENCES {ref_table}({ref_col})"
if self.on_delete:
fk_clause += f" ON DELETE {self.on_delete}"
if self.on_update:
fk_clause += f" ON UPDATE {self.on_update}"
parts.append(fk_clause)
return " ".join(parts)
class SQLiteDB:
def __init__(self, db_name: str, auto_close: bool = True, auto_commit: bool = True):
"""Initialize the database connection."""
self.db_name = db_name
self.auto_close = auto_close
self.auto_commit = auto_commit
self.conn: Optional[sqlite3.Connection] = None
self.cursor: Optional[sqlite3.Cursor] = None
self._connect()
def _connect(self) -> None:
"""Establish database connection."""
try:
self.conn = sqlite3.connect(self.db_name)
self.cursor = self.conn.cursor()
except sqlite3.Error as e:
raise Exception(f"Database connection error: {str(e)}")
def _execute_query(self, query: str, params: tuple = (), auto_commit: Optional[bool] = None) -> None:
"""Execute a query with parameters."""
commit = auto_commit if auto_commit is not None else self.auto_commit
try:
self.cursor.execute(query, params)
if commit:
self.conn.commit()
except sqlite3.Error as e:
self.conn.rollback()
raise Exception(f"Query execution error: {str(e)}")
def _fetch_query(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
"""Execute a query and fetch results."""
try:
self.cursor.execute(query, params)
columns = [desc[0] for desc in self.cursor.description]
results = self.cursor.fetchall()
return [dict(zip(columns, row)) for row in results]
except sqlite3.Error as e:
raise Exception(f"Query fetch error: {str(e)}")
def commit(self) -> None:
"""Manually commit changes."""
if self.conn:
self.conn.commit()
def create_db_with_table(self, table_name: str, columns: List[Column]) -> None:
"""
Create a new table with the specified columns (list of Column objects).
Example: columns = [Column('id', 'INTEGER', primary_key=True, auto_increment=True), ...]
"""
try:
columns_def = ', '.join(col.to_sql() for col in columns)
create_query = f"CREATE TABLE IF NOT EXISTS {table_name} ({columns_def})"
self._execute_query(create_query)
except Exception as e:
raise Exception(f"Table creation error: {str(e)}")
def add_item(self, table_name: str, data: Dict[str, Any], auto_commit: Optional[bool] = None) -> int:
"""
Add a new item to the specified table.
Returns the ID of the inserted item.
"""
try:
columns = ', '.join(data.keys())
placeholders = ', '.join('?' * len(data))
query = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
self._execute_query(query, tuple(data.values()), auto_commit=auto_commit)
return self.cursor.lastrowid
except Exception as e:
raise Exception(f"Item insertion error: {str(e)}")
def get_item(self, table_name: str, item_id: int) -> Optional[Dict[str, Any]]:
"""
Retrieve an item by its ID.
"""
try:
query = f"SELECT * FROM {table_name} WHERE id = ?"
results = self._fetch_query(query, (item_id,))
return results[0] if results else None
except Exception as e:
raise Exception(f"Item retrieval error: {str(e)}")
def find_item(self, table_name: str, key: str, value: Any) -> Optional[Dict[str, Any]]:
"""
Find an item by a specific key-value pair.
"""
try:
query = f"SELECT * FROM {table_name} WHERE {key} = ?"
results = self._fetch_query(query, (value,))
return results[0] if results else None
except Exception as e:
raise Exception(f"Item find error: {str(e)}")
def get_id_by_key(self, table_name: str, key: str, value: Any) -> Optional[int]:
"""
Retrieve the ID of an item by a specific key-value pair (e.g., by name).
Returns None if not found.
"""
try:
query = f"SELECT id FROM {table_name} WHERE {key} = ?"
results = self._fetch_query(query, (value,))
return results[0]['id'] if results else None
except Exception as e:
raise Exception(f"ID retrieval by key error: {str(e)}")
def update_item(self, table_name: str, item_id: int, data: Dict[str, Any], auto_commit: Optional[bool] = None) -> bool:
"""
Update an item by its ID.
Returns True if update was successful, False if item not found.
"""
try:
set_clause = ', '.join(f"{k} = ?" for k in data.keys())
query = f"UPDATE {table_name} SET {set_clause} WHERE id = ?"
params = tuple(data.values()) + (item_id,)
self._execute_query(query, params, auto_commit=auto_commit)
return self.cursor.rowcount > 0
except Exception as e:
raise Exception(f"Item update error: {str(e)}")
def delete_item(self, table_name: str, item_id: int, auto_commit: Optional[bool] = None) -> bool:
"""
Delete an item by its ID.
Returns True if deletion was successful, False if item not found.
"""
try:
query = f"DELETE FROM {table_name} WHERE id = ?"
self._execute_query(query, (item_id,), auto_commit=auto_commit)
return self.cursor.rowcount > 0
except Exception as e:
raise Exception(f"Item deletion error: {str(e)}")
def get_all_items(self, table_name: str) -> List[Dict[str, Any]]:
"""
Retrieve all items from the specified table.
"""
try:
query = f"SELECT * FROM {table_name}"
return self._fetch_query(query)
except Exception as e:
raise Exception(f"Get all items error: {str(e)}")
def get_page(self, table_name: str, page_number: int = 1, items_per_page: int = 10) -> Tuple[List[Dict[str, Any]], int]:
"""
Retrieve paginated items from the specified table.
Returns a tuple of (items, total_pages).
"""
try:
# Count total items
count_query = f"SELECT COUNT(*) as total FROM {table_name}"
total_items = self._fetch_query(count_query)[0]['total']
total_pages = (total_items + items_per_page - 1) // items_per_page
# Calculate offset
offset = (page_number - 1) * items_per_page
query = f"SELECT * FROM {table_name} LIMIT ? OFFSET ?"
items = self._fetch_query(query, (items_per_page, offset))
return items, total_pages
except Exception as e:
raise Exception(f"Pagination error: {str(e)}")
def close(self) -> None:
"""Close the database connection."""
if self.conn:
self.conn.close()
self.conn = None
self.cursor = None
def __enter__(self):
"""Context manager enter."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
self.close()
def __del__(self):
"""Auto-close on object destruction if enabled."""
if self.auto_close:
self.close()
# Example usage:
if __name__ == "__main__":
try:
with SQLiteDB("example.db") as db:
# Define users table schema (more Pythonic with Column dataclass)
users_columns = [
Column('id', 'INTEGER', primary_key=True, auto_increment=True),
Column('name', 'TEXT', not_null=True),
Column('age', 'INTEGER'),
Column('email', 'TEXT')
]
db.create_db_with_table('users', users_columns)
# Define orders table with foreign key to users (demonstrates foreign key support)
orders_columns = [
Column('order_id', 'INTEGER', primary_key=True, auto_increment=True),
Column('user_id', 'INTEGER', not_null=True, foreign_key=('users', 'id'), on_delete='CASCADE'),
Column('product', 'TEXT', not_null=True),
Column('quantity', 'INTEGER', default=1)
]
db.create_db_with_table('orders', orders_columns)
# Add users
user1 = {'name': 'John Doe', 'age': 30, 'email': 'john@example.com'}
user2 = {'name': 'Jane Smith', 'age': 25, 'email': 'jane@example.com'}
user1_id = db.add_item('users', user1)
user2_id = db.add_item('users', user2)
print(f"Added users with IDs: {user1_id}, {user2_id}")
# Get ID by name (new feature)
john_id = db.get_id_by_key('users', 'name', 'John Doe')
print(f"John Doe's ID: {john_id}")
# Add order with foreign key
order = {'user_id': john_id, 'product': 'Laptop', 'quantity': 2}
order_id = db.add_item('orders', order)
print(f"Added order with ID: {order_id}")
# Update user (with auto_commit=True by default)
update_data = {'age': 31}
db.update_item('users', user1_id, update_data)
# Delete item
db.delete_item('users', user2_id)
# Get all users
all_users = db.get_all_items('users')
print(f"All users: {all_users}")
# Pagination
page_items, total_pages = db.get_page('users', page_number=1, items_per_page=10)
print(f"Page 1 items: {page_items}, Total pages: {total_pages}")
except Exception as e:
print(f"Error: {str(e)}")
How to Use the New Features
- Schema Definition: Use
Column objects for clarity. It's more Pythonic and handles foreign keys automatically.
- Finding ID by Name:
db.get_id_by_key('users', 'name', 'John Doe') – returns the ID or None.
- Foreign Keys: See the
orders table example – deleting a user will cascade to orders if on_delete='CASCADE'.
- Auto-Commit: Pass
auto_commit=False to methods like add_item for batch ops, then call db.commit().
- Auto-Close: Use
with for safety, or rely on __del__ if auto_close=True.
This should make the API even easier to use while adding the requested functionality. If you need further tweaks (e.g., bulk operations), let me know!