Change to peewee DatabaseProxy to handle different DB types
This commit is contained in:
@@ -7,6 +7,7 @@ from . import utc_now
|
||||
from peewee import (
|
||||
AutoField,
|
||||
CharField,
|
||||
DatabaseProxy,
|
||||
DateTimeField,
|
||||
DoesNotExist,
|
||||
fn,
|
||||
@@ -17,8 +18,8 @@ from peewee import (
|
||||
SqliteDatabase,
|
||||
)
|
||||
|
||||
# Database instance (initialized later)
|
||||
db = SqliteDatabase(None)
|
||||
# Database proxy (initialized later with actual backend)
|
||||
db = DatabaseProxy()
|
||||
|
||||
# Current database schema version
|
||||
DATABASE_VERSION = 2
|
||||
@@ -110,7 +111,6 @@ def init_database(config: dict):
|
||||
Raises:
|
||||
ValueError: If unknown database backend.
|
||||
"""
|
||||
global db
|
||||
|
||||
backend = config["database"].get("backend", "sqlite")
|
||||
|
||||
@@ -119,21 +119,19 @@ def init_database(config: dict):
|
||||
db_dir = os.path.dirname(db_path)
|
||||
if db_dir:
|
||||
os.makedirs(db_dir, exist_ok=True)
|
||||
db.init(db_path)
|
||||
actual_db = SqliteDatabase(db_path)
|
||||
db.initialize(actual_db)
|
||||
logging.debug(f"Database backend: SQLite path={db_path}")
|
||||
|
||||
elif backend == "mariadb":
|
||||
db = MySQLDatabase(
|
||||
actual_db = MySQLDatabase(
|
||||
config["database"]["database"],
|
||||
host=config["database"].get("host", "localhost"),
|
||||
port=config["database"].get("port", 3306),
|
||||
user=config["database"]["user"],
|
||||
password=config["database"]["password"],
|
||||
)
|
||||
# Re-bind models to new database
|
||||
User._meta.database = db
|
||||
Hostname._meta.database = db
|
||||
Version._meta.database = db
|
||||
db.initialize(actual_db)
|
||||
db_name = config['database']['database']
|
||||
logging.debug(f"Database backend: MariaDB db={db_name}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user