35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
import sqlite3
|
|
from dataclasses import dataclass
|
|
|
|
from backend.database.connection import Database
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class DatabaseStatus:
|
|
available: bool
|
|
schema_version: int
|
|
|
|
|
|
class DatabaseStatusRepository:
|
|
def __init__(self, database: Database) -> None:
|
|
self._database = database
|
|
|
|
def get(self) -> DatabaseStatus:
|
|
try:
|
|
with self._database.read() as connection:
|
|
connection.execute("SELECT 1").fetchone()
|
|
schema_exists = connection.execute(
|
|
"""SELECT 1 FROM sqlite_master
|
|
WHERE type='table' AND name='schema_migrations'"""
|
|
).fetchone()
|
|
if schema_exists is None:
|
|
return DatabaseStatus(available=True, schema_version=0)
|
|
row = connection.execute(
|
|
"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations"
|
|
).fetchone()
|
|
return DatabaseStatus(available=True, schema_version=int(row["version"]))
|
|
except (OSError, sqlite3.Error):
|
|
return DatabaseStatus(available=False, schema_version=0)
|