Skip to content

Commit

Permalink
Add failsafe to delete the database in the case of a problem during u…
Browse files Browse the repository at this point in the history
…pgrade
  • Loading branch information
jfeil committed Aug 18, 2022
1 parent 7b7000d commit 05d9c08
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import sys
from typing import List, Tuple

import sqlalchemy
from alembic import command
from alembic.config import Config
from alembic.runtime.migration import MigrationContext
Expand All @@ -14,12 +15,13 @@
from src.basic_config import database_name, Base, is_bundled, app_dirs
from src.datatypes import QuestionGroup, Question, MultipleChoice

database_path = os.path.join(app_dirs.user_data_dir, database_name)


class DatabaseConnector:
engine = None

def __init__(self):
database_path = os.path.join(app_dirs.user_data_dir, database_name)
def __init__(self, database_path):
logging.debug(app_dirs.user_data_dir)
self.initialized = True
if not os.path.isdir(app_dirs.user_data_dir):
Expand All @@ -42,7 +44,12 @@ def __init__(self):
self._init_database()

self.session = Session(self.engine)
self._upgrade_database()
try:
self._upgrade_database()
except sqlalchemy.exc.OperationalError as err:
self.session.close()
self.engine.dispose()
raise err

def _init_database(self):
# Create database based on basis and stamp with alembic for future migrations
Expand Down Expand Up @@ -165,4 +172,9 @@ def get_question_group_config(self) -> List[Tuple[QuestionGroup, int, int]]:
question_groups]


db = DatabaseConnector()
try:
db = DatabaseConnector(database_path)
except sqlalchemy.exc.OperationalError as err:
logging.error(f"{err}\n\nDatabase is corrupt. Deleting the data and recreate it.")
os.remove(database_path)
db = DatabaseConnector(database_path)

0 comments on commit 05d9c08

Please sign in to comment.