|
| 1 | +"""Database storage implementation using sqlite3""" |
| 2 | + |
| 3 | +import sqlite3 |
| 4 | + |
| 5 | +from cost_sharing.models import User |
| 6 | +from cost_sharing.exceptions import ( |
| 7 | + DuplicateEmailError, |
| 8 | + UserNotFoundError, |
| 9 | + StorageException |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +class DatabaseCostStorage: |
| 14 | + """ |
| 15 | + Database storage implementation using sqlite3. |
| 16 | +
|
| 17 | + Uses SQLite database (in-memory or file-based) for persistence. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, connection): |
| 21 | + """ |
| 22 | + Initialize database storage with a database connection. |
| 23 | +
|
| 24 | + Args: |
| 25 | + connection: A sqlite3.Connection object (e.g., sqlite3.connect(':memory:') |
| 26 | + or sqlite3.connect('costsharing.db')) |
| 27 | + """ |
| 28 | + self._conn = connection |
| 29 | + |
| 30 | + # Use Row factory for dict-like access to rows |
| 31 | + self._conn.row_factory = sqlite3.Row |
| 32 | + # Enable foreign key constraints |
| 33 | + self._conn.execute('PRAGMA foreign_keys = ON') |
| 34 | + |
| 35 | + def is_user(self, email): |
| 36 | + """ |
| 37 | + Check if a user exists with the given email. |
| 38 | +
|
| 39 | + Args: |
| 40 | + email: User's email address |
| 41 | +
|
| 42 | + Returns: |
| 43 | + bool: True if user exists, False otherwise |
| 44 | +
|
| 45 | + Raises: |
| 46 | + StorageException: If a database error occurs |
| 47 | + """ |
| 48 | + try: |
| 49 | + cursor = self._conn.execute( |
| 50 | + 'SELECT 1 FROM users WHERE email = ?', |
| 51 | + (email,) |
| 52 | + ) |
| 53 | + return cursor.fetchone() is not None |
| 54 | + except sqlite3.Error as e: |
| 55 | + raise StorageException(f"Database error checking user existence: {e}") from e |
| 56 | + |
| 57 | + def get_user_by_email(self, email): |
| 58 | + """ |
| 59 | + Get user by email address. |
| 60 | +
|
| 61 | + Args: |
| 62 | + email: User's email address |
| 63 | +
|
| 64 | + Returns: |
| 65 | + User if found |
| 66 | +
|
| 67 | + Raises: |
| 68 | + UserNotFoundError: If user with the given email is not found |
| 69 | + StorageException: If a database error occurs |
| 70 | + """ |
| 71 | + try: |
| 72 | + cursor = self._conn.execute( |
| 73 | + 'SELECT id, email, name FROM users WHERE email = ?', |
| 74 | + (email,) |
| 75 | + ) |
| 76 | + row = cursor.fetchone() |
| 77 | + if row is None: |
| 78 | + raise UserNotFoundError(f"User with email '{email}' not found") |
| 79 | + return User(id=row['id'], email=row['email'], name=row['name']) |
| 80 | + except sqlite3.Error as e: |
| 81 | + raise StorageException(f"Database error retrieving user by email: {e}") from e |
| 82 | + |
| 83 | + def create_user(self, email, name): |
| 84 | + """ |
| 85 | + Create a new user. |
| 86 | +
|
| 87 | + Args: |
| 88 | + email: User's email address |
| 89 | + name: User's name |
| 90 | +
|
| 91 | + Returns: |
| 92 | + Newly created User object |
| 93 | +
|
| 94 | + Raises: |
| 95 | + DuplicateEmailError: If email already exists |
| 96 | + StorageException: If a database error occurs |
| 97 | + """ |
| 98 | + try: |
| 99 | + cursor = self._conn.execute( |
| 100 | + 'INSERT INTO users (email, name) VALUES (?, ?)', |
| 101 | + (email, name) |
| 102 | + ) |
| 103 | + self._conn.commit() |
| 104 | + user_id = cursor.lastrowid |
| 105 | + return User(id=user_id, email=email, name=name) |
| 106 | + except sqlite3.IntegrityError as e: |
| 107 | + self._conn.rollback() |
| 108 | + # IntegrityError on users table insert is always a duplicate email |
| 109 | + raise DuplicateEmailError() from e |
| 110 | + except sqlite3.Error as e: |
| 111 | + self._conn.rollback() |
| 112 | + raise StorageException(f"Database error creating user: {e}") from e |
| 113 | + |
| 114 | + def get_user_by_id(self, user_id): |
| 115 | + """ |
| 116 | + Get user by ID. |
| 117 | +
|
| 118 | + Args: |
| 119 | + user_id: User ID |
| 120 | +
|
| 121 | + Returns: |
| 122 | + User if found |
| 123 | +
|
| 124 | + Raises: |
| 125 | + UserNotFoundError: If user with the given ID is not found |
| 126 | + StorageException: If a database error occurs |
| 127 | + """ |
| 128 | + try: |
| 129 | + cursor = self._conn.execute( |
| 130 | + 'SELECT id, email, name FROM users WHERE id = ?', |
| 131 | + (user_id,) |
| 132 | + ) |
| 133 | + row = cursor.fetchone() |
| 134 | + if row is None: |
| 135 | + raise UserNotFoundError(f"User with ID {user_id} not found") |
| 136 | + return User(id=row['id'], email=row['email'], name=row['name']) |
| 137 | + except sqlite3.Error as e: |
| 138 | + raise StorageException(f"Database error retrieving user by ID: {e}") from e |
0 commit comments