-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdb.py
More file actions
139 lines (113 loc) · 4.19 KB
/
db.py
File metadata and controls
139 lines (113 loc) · 4.19 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
"""Module for connecting to a database."""
from peewee import Database, DatabaseError, MySQLDatabase, SqliteDatabase
from playhouse.shortcuts import ReconnectMixin
from utils import ensure_database_exists, get_configs
from logutils import get_logger
logger = get_logger(__name__)
DATABASE_CONFIGS = {
"mode": get_configs("MODE", default_value="development"),
"mysql": {
"database": get_configs("MYSQL_DATABASE"),
"host": get_configs("MYSQL_HOST"),
"password": get_configs("MYSQL_PASSWORD"),
"user": get_configs("MYSQL_USER"),
},
"sqlite": {
"database_path": get_configs("SQLITE_DATABASE_PATH"),
},
}
class ReconnectMySQLDatabase(ReconnectMixin, MySQLDatabase):
"""
A custom MySQLDatabase class with automatic reconnection capability.
This class inherits from both ReconnectMixin and MySQLDatabase
to provide automatic reconnection functionality in case the database
connection is lost.
"""
def is_mysql_config_complete() -> bool:
"""
Checks if all required MySQL configurations are present.
Returns:
bool: True if all MySQL configurations are complete, False otherwise.
"""
logger.debug("Checking if MySQL configuration is complete...")
mysql_config = DATABASE_CONFIGS["mysql"]
required_keys = ["database", "host", "password", "user"]
return all(mysql_config.get(key) for key in required_keys)
def connect() -> Database:
"""
Connects to the appropriate database based on the mode.
If the mode is 'testing', it returns None.
If the mode is 'development', it checks if MySQL credentials
are complete. If they are, it connects to the MySQL database,
otherwise, it falls back to the SQLite database.
If the mode is not 'testing' or 'development', it connects
to the MySQL database.
Returns:
Database: The connected database object.
"""
mode = DATABASE_CONFIGS["mode"]
logger.debug("Database connection mode: %s", mode)
if mode == "testing":
logger.debug("Mode is 'testing'. No database connection will be made.")
return None
if mode == "development":
if is_mysql_config_complete():
return connect_to_mysql()
logger.warning(
"MySQL configuration is incomplete. Falling back to SQLite database."
)
return connect_to_sqlite()
return connect_to_mysql()
@ensure_database_exists(
DATABASE_CONFIGS["mysql"]["host"],
DATABASE_CONFIGS["mysql"]["user"],
DATABASE_CONFIGS["mysql"]["password"],
DATABASE_CONFIGS["mysql"]["database"],
)
def connect_to_mysql() -> ReconnectMySQLDatabase:
"""
Connects to the MySQL database.
Returns:
ReconnectMySQLDatabase: The connected MySQL database object with reconnection capability.
Raises:
DatabaseError: If failed to connect to the database.
"""
logger.debug(
"Attempting to connect to MySQL database '%s' at '%s'...",
DATABASE_CONFIGS["mysql"]["database"],
DATABASE_CONFIGS["mysql"]["host"],
)
try:
db = ReconnectMySQLDatabase(
DATABASE_CONFIGS["mysql"]["database"],
user=DATABASE_CONFIGS["mysql"]["user"],
password=DATABASE_CONFIGS["mysql"]["password"],
host=DATABASE_CONFIGS["mysql"]["host"],
)
db.connect()
return db
except DatabaseError as error:
logger.error(
"Failed to connect to MySQL database '%s' at '%s': %s",
DATABASE_CONFIGS["mysql"]["database"],
DATABASE_CONFIGS["mysql"]["host"],
error,
)
raise error
def connect_to_sqlite() -> SqliteDatabase:
"""
Connects to the SQLite database.
Returns:
SqliteDatabase: The connected SQLite database object.
Raises:
DatabaseError: If failed to connect to the database.
"""
db_path = DATABASE_CONFIGS["sqlite"]["database_path"]
logger.debug("Attempting to connect to SQLite database at '%s'...", db_path)
try:
db = SqliteDatabase(db_path)
db.connect()
return db
except DatabaseError as error:
logger.error("Failed to connect to SQLite database at '%s': %s", db_path, error)
raise error