Skip to content

Commit

Permalink
Add checks in case of database update
Browse files Browse the repository at this point in the history
  • Loading branch information
Raymo111 committed Aug 21, 2023
1 parent b819dc3 commit 1f9084b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/nexus/Freqlog/Freqlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@ def _log_and_reset_word(min_length: int = 1) -> None:
break

def __init__(self, db_path: str = Defaults.DEFAULT_DB_PATH, loggable: bool = True):
"""
Initialize Freqlog
:param db_path: Path to database file
:param loggable: Whether to create listeners
:raises ValueError: If the database version is newer than the current version
"""
self.backend: Backend = SQLiteBackend(db_path)
self.q: Queue = Queue()
self.listener: kbd.Listener | None = None
Expand Down
19 changes: 18 additions & 1 deletion src/nexus/Freqlog/backends/SQLite/SQLiteBackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,26 @@
class SQLiteBackend(Backend):

def __init__(self, db_path: str) -> None:
"""
Initialize the SQLite backend
:param db_path: Path to the database file
:raises ValueError: If the database version is newer than the current version
"""
self.db_path = db_path
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()

# Versioning
# old_version = self._fetchone("PRAGMA user_version")
old_version = self._fetchone("PRAGMA user_version")[0]

# Encode major, minor and patch version into a single 4-byte integer
sql_version: int = int(__version__.split(".")[0]) << 16 | int(__version__.split(".")[1]) << 8 | int(
__version__.split(".")[2])
if old_version < sql_version:
self._upgrade_database(sql_version)
elif old_version > sql_version:
raise ValueError(f"Database version {old_version} is newer than the current version {sql_version}")

self._execute(f"PRAGMA user_version = {sql_version}")

# Freqloq table
Expand Down Expand Up @@ -60,6 +71,12 @@ def _fetchall(self, query: str, params=None) -> list[tuple]:
self.cursor.execute(query)
return self.cursor.fetchall()

def _upgrade_database(self, sql_version: int) -> None:
"""Upgrade database to current version"""
# TODO: populate this function when changing DDL
# Remember to warn users to back up their database before upgrading
pass

def get_word_metadata(self, word: str, case: CaseSensitivity) -> WordMetadata | None:
"""
Get metadata for a word
Expand Down

0 comments on commit 1f9084b

Please sign in to comment.