Add version table in preparation for future DB upgrades
This commit is contained in:
@@ -19,6 +19,9 @@ from peewee import (
|
|||||||
# Database instance (initialized later)
|
# Database instance (initialized later)
|
||||||
db = SqliteDatabase(None)
|
db = SqliteDatabase(None)
|
||||||
|
|
||||||
|
# Current database schema version
|
||||||
|
DATABASE_VERSION = 1
|
||||||
|
|
||||||
|
|
||||||
class BaseModel(Model):
|
class BaseModel(Model):
|
||||||
"""Base model with database binding."""
|
"""Base model with database binding."""
|
||||||
@@ -58,6 +61,15 @@ class Hostname(BaseModel):
|
|||||||
table_name = "hostnames"
|
table_name = "hostnames"
|
||||||
|
|
||||||
|
|
||||||
|
class Version(BaseModel):
|
||||||
|
"""Database schema version for migrations."""
|
||||||
|
|
||||||
|
version = IntegerField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
table_name = "version"
|
||||||
|
|
||||||
|
|
||||||
def init_database(config: dict):
|
def init_database(config: dict):
|
||||||
"""
|
"""
|
||||||
Initialize database connection based on config.
|
Initialize database connection based on config.
|
||||||
@@ -91,6 +103,7 @@ def init_database(config: dict):
|
|||||||
# Re-bind models to new database
|
# Re-bind models to new database
|
||||||
User._meta.database = db
|
User._meta.database = db
|
||||||
Hostname._meta.database = db
|
Hostname._meta.database = db
|
||||||
|
Version._meta.database = db
|
||||||
logging.info(f"Database backend: MariaDB db={config['database']['database']}")
|
logging.info(f"Database backend: MariaDB db={config['database']['database']}")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@@ -101,7 +114,9 @@ def init_database(config: dict):
|
|||||||
|
|
||||||
def create_tables():
|
def create_tables():
|
||||||
"""Create database tables if they don't exist."""
|
"""Create database tables if they don't exist."""
|
||||||
db.create_tables([User, Hostname])
|
db.create_tables([User, Hostname, Version])
|
||||||
|
if Version.select().count() == 0:
|
||||||
|
Version.create(version=DATABASE_VERSION)
|
||||||
logging.info("Database tables created")
|
logging.info("Database tables created")
|
||||||
|
|
||||||
|
|
||||||
@@ -159,8 +174,10 @@ def get_hostname_for_user(hostname: str, user: User):
|
|||||||
# Re-export DoesNotExist for convenience
|
# Re-export DoesNotExist for convenience
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'db',
|
'db',
|
||||||
|
'DATABASE_VERSION',
|
||||||
'User',
|
'User',
|
||||||
'Hostname',
|
'Hostname',
|
||||||
|
'Version',
|
||||||
'init_database',
|
'init_database',
|
||||||
'create_tables',
|
'create_tables',
|
||||||
'get_user',
|
'get_user',
|
||||||
|
|||||||
Reference in New Issue
Block a user