-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.py
More file actions
174 lines (154 loc) · 4.66 KB
/
db.py
File metadata and controls
174 lines (154 loc) · 4.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import os
import sqlite3
import logging
# Setup logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Get the directory where db.py is located
_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Define the path to the database directory and ensure it exists
_database_directory = os.path.join(_BASE_DIR, "database")
os.makedirs(_database_directory, exist_ok=True)
# Define the full path to the SQLite database file
_database_path = os.path.join(_database_directory, "CRUD.db")
def get_db_connection():
"""Connect to the SQLite database."""
try:
logger.debug(f"Connecting to database at {_database_path}")
connection = sqlite3.connect(_database_path)
connection.row_factory = sqlite3.Row # Enables name-based access to columns
return connection
except sqlite3.Error as e:
logger.error(f"Error connecting to the database: {e}")
raise
def get_total_changes():
"""Get the total number of changes in the database."""
try:
connection = get_db_connection()
total_changes = connection.total_changes
return total_changes
except sqlite3.Error as e:
logger.error(f"Error retrieving total changes: {e}")
raise
finally:
if connection:
connection.close()
def initialize_database():
"""Initialize the database with necessary tables."""
try:
logger.debug("Initializing database...")
connection = get_db_connection()
cursor = connection.cursor()
# Example table creation
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
)
"""
)
# Add other table creations as needed
connection.commit()
logger.debug("Database initialized.")
except sqlite3.Error as e:
logger.error(f"Error initializing the database: {e}")
raise
finally:
if connection:
connection.close()
def create_user(name, email):
"""Create a new user in the database."""
try:
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute(
"""
INSERT INTO users (name, email) VALUES (?, ?)
""",
(name, email),
)
connection.commit()
except sqlite3.IntegrityError as e:
logger.warning(f"Integrity error: {e}")
raise # Reraise to be handled by the calling code
except sqlite3.Error as e:
logger.error(f"Error creating user: {e}")
raise
finally:
if connection:
connection.close()
def get_user(user_id):
"""Get a user by ID."""
try:
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute(
"""
SELECT * FROM users WHERE id = ?
""",
(user_id,),
)
user = cursor.fetchone()
return user
except sqlite3.Error as e:
logger.error(f"Error retrieving user with ID {user_id}: {e}")
raise
finally:
if connection:
connection.close()
def get_all_users():
"""Get all users."""
try:
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute(
"""
SELECT * FROM users
"""
)
users = cursor.fetchall()
return users
except sqlite3.Error as e:
logger.error(f"Error retrieving all users: {e}")
raise
finally:
if connection:
connection.close()
def update_user(user_id, name, email):
"""Update user details."""
try:
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute(
"""
UPDATE users SET name = ?, email = ? WHERE id = ?
""",
(name, email, user_id),
)
connection.commit()
except sqlite3.Error as e:
logger.error(f"Error updating user with ID {user_id}: {e}")
raise
finally:
if connection:
connection.close()
def delete_user(user_id):
"""Delete a user."""
try:
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute(
"""
DELETE FROM users WHERE id = ?
""",
(user_id,),
)
connection.commit()
except sqlite3.Error as e:
logger.error(f"Error deleting user with ID {user_id}: {e}")
raise
finally:
if connection:
connection.close()