-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_manager.py
More file actions
104 lines (90 loc) · 2.91 KB
/
database_manager.py
File metadata and controls
104 lines (90 loc) · 2.91 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
import sqlite3
class DatabaseManager:
"""
Handles SQLite connection management and common database operations.
Returns rows as dictionary-like sqlite3.Row objects.
"""
def __init__(self, db_name="rides.db"):
self.db_name = db_name
self.conn = None
def connect(self):
"""
Open a database connection if one is not already open.
Enables foreign key enforcement and dictionary-like row access.
"""
if self.conn is None:
self.conn = sqlite3.connect(self.db_name)
self.conn.row_factory = sqlite3.Row
self.conn.execute("PRAGMA foreign_keys = ON;")
def close(self):
"""
Close the database connection if it is open.
"""
if self.conn is not None:
self.conn.close()
self.conn = None
def execute(self, query, params=()):
"""
Execute a query that changes the database
(INSERT, UPDATE, DELETE, CREATE, etc.).
Returns the cursor so caller can inspect lastrowid if needed.
"""
self.connect()
cursor = self.conn.cursor()
cursor.execute(query, params)
self.conn.commit()
return cursor
def fetchone(self, query, params=()):
"""
Execute a SELECT query and return one row.
Returns None if no row matches.
"""
self.connect()
cursor = self.conn.cursor()
cursor.execute(query, params)
return cursor.fetchone()
def fetchall(self, query, params=()):
"""
Execute a SELECT query and return all matching rows.
"""
self.connect()
cursor = self.conn.cursor()
cursor.execute(query, params)
return cursor.fetchall()
def create_tables(self, schema_file="schema.sql"):
"""
Create all tables using SQL statements stored in a schema file.
Uses executescript because the schema file contains multiple
CREATE TABLE statements.
"""
self.connect()
with open(schema_file, "r", encoding="utf-8") as f:
schema_sql = f.read()
self.conn.executescript(schema_sql)
self.conn.commit()
def row_to_dict(self, row):
"""
Convert a sqlite3.Row into a regular Python dictionary.
Returns None if row is None.
"""
if row is None:
return None
return dict(row)
def rows_to_dicts(self, rows):
"""
Convert a list of sqlite3.Row objects into a list of dictionaries.
"""
return [dict(row) for row in rows]
def __enter__(self):
"""
Support use in a context manager:
with DatabaseManager() as db:
...
"""
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Always close the connection when leaving a with-block.
"""
self.close()