forked from ahmedfgad/GeneticAlgorithmPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_manager.py
More file actions
184 lines (145 loc) · 5.35 KB
/
db_manager.py
File metadata and controls
184 lines (145 loc) · 5.35 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
175
176
177
178
179
180
181
182
183
184
"""
SQLite connection management and user CRUD.
All application data lives in a single SQLite file (config.DATABASE_PATH).
Per-user encrypted data can use get_user_connection(user_id) when you attach
user-specific databases later; for now it returns the shared connection scoped
to the authenticated user context.
"""
from __future__ import annotations
import sqlite3
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Generator, Iterator
import config
from database.models.users import (
CREATE_EMAIL_INDEX,
CREATE_USERNAME_INDEX,
USERS_TABLE_SQL,
UserRecord,
utc_now_iso,
)
from utils.encryption import encrypt_for_storage, generate_user_fernet_key
def _db_path() -> Path:
return Path(config.DATABASE_PATH)
def get_connection(*, row_factory: bool = True) -> sqlite3.Connection:
"""
Open (and initialize) the shared SQLite database.
row_factory=True enables dict-like row access via conn.row_factory.
"""
path = _db_path()
path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(path), check_same_thread=False)
if row_factory:
conn.row_factory = sqlite3.Row
initialize_schema(conn)
return conn
@contextmanager
def db_session() -> Generator[sqlite3.Connection, None, None]:
"""Context manager that commits on success and rolls back on error."""
conn = get_connection()
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
def initialize_schema(conn: sqlite3.Connection) -> None:
"""Create tables and indexes if they do not exist."""
conn.executescript(USERS_TABLE_SQL)
conn.executescript(CREATE_USERNAME_INDEX)
conn.executescript(CREATE_EMAIL_INDEX)
conn.commit()
def get_user_connection(user_id: int) -> sqlite3.Connection:
"""
Return a database connection for operations scoped to a user.
Currently uses the shared app database; extend this to open per-user
SQLite files (e.g. data/users/{user_id}.db) when needed.
"""
conn = get_connection()
conn.execute("PRAGMA foreign_keys = ON")
# Store user context for optional query helpers
conn.execute("SELECT 1") # no-op; placeholder for future per-user DB split
conn._app_user_id = user_id # type: ignore[attr-defined]
return conn
# ---------------------------------------------------------------------------
# User CRUD
# ---------------------------------------------------------------------------
_USER_COLUMNS = (
"user_id, username, email, name, password_hash, "
"encryption_key, created_at, is_active"
)
def _row_to_user(row: sqlite3.Row | tuple[Any, ...]) -> UserRecord:
if isinstance(row, sqlite3.Row):
return UserRecord.from_row(tuple(row))
return UserRecord.from_row(row)
def get_user_by_id(user_id: int) -> UserRecord | None:
with db_session() as conn:
cur = conn.execute(
f"SELECT {_USER_COLUMNS} FROM users WHERE user_id = ? AND is_active = 1",
(user_id,),
)
row = cur.fetchone()
return _row_to_user(row) if row else None
def get_user_by_username(username: str) -> UserRecord | None:
with db_session() as conn:
cur = conn.execute(
f"SELECT {_USER_COLUMNS} FROM users WHERE username = ? AND is_active = 1",
(username.lower(),),
)
row = cur.fetchone()
return _row_to_user(row) if row else None
def get_user_by_email(email: str) -> UserRecord | None:
with db_session() as conn:
cur = conn.execute(
f"SELECT {_USER_COLUMNS} FROM users WHERE email = ? AND is_active = 1",
(email.lower(),),
)
row = cur.fetchone()
return _row_to_user(row) if row else None
def list_active_users() -> list[UserRecord]:
with db_session() as conn:
cur = conn.execute(
f"SELECT {_USER_COLUMNS} FROM users WHERE is_active = 1 ORDER BY username"
)
return [_row_to_user(r) for r in cur.fetchall()]
def create_user(
*,
username: str,
email: str,
name: str,
password_hash: str,
encryption_key_plain: str | None = None,
) -> UserRecord:
"""
Insert a new user. encryption_key is generated and stored encrypted unless
a plaintext key is supplied (e.g. migration).
"""
username = username.strip().lower()
email = email.strip().lower()
plain_key = encryption_key_plain or generate_user_fernet_key()
encrypted_key = encrypt_for_storage(plain_key)
with db_session() as conn:
cur = conn.execute(
"""
INSERT INTO users (username, email, name, password_hash, encryption_key, created_at, is_active)
VALUES (?, ?, ?, ?, ?, ?, 1)
""",
(username, email, name, password_hash, encrypted_key, utc_now_iso()),
)
user_id = int(cur.lastrowid)
user = get_user_by_id(user_id)
if user is None:
raise RuntimeError("Failed to load user after insert.")
return user
def deactivate_user(user_id: int) -> None:
with db_session() as conn:
conn.execute(
"UPDATE users SET is_active = 0 WHERE user_id = ?",
(user_id,),
)
def username_exists(username: str) -> bool:
return get_user_by_username(username) is not None
def email_exists(email: str) -> bool:
return get_user_by_email(email) is not None