-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.py
143 lines (117 loc) · 4.38 KB
/
db.py
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
"""
This program is free software: you can redistribute it under the terms
of the GNU General Public License, v. 3.0. If a copy of the GNU General
Public License was not distributed with this file, see <https://www.gnu.org/licenses/>.
"""
from peewee import Database, DatabaseError, MySQLDatabase, SqliteDatabase
from playhouse.shortcuts import ReconnectMixin
from utils import ensure_database_exists, get_env_var
from logutils import get_logger
logger = get_logger(__name__)
DATABASE_CONFIGS = {
"mode": get_env_var("MODE", default_value="development"),
"mysql": {
"database": get_env_var("MYSQL_DATABASE"),
"host": get_env_var("MYSQL_HOST"),
"password": get_env_var("MYSQL_PASSWORD"),
"user": get_env_var("MYSQL_USER"),
},
"sqlite": {
"database_path": get_env_var("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