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