Mobilizon-Reshare-condividi.../mobilizon_reshare/storage/db.py

87 lines
2.5 KiB
Python
Raw Normal View History

import logging
2021-12-07 12:10:32 +01:00
import sys
2021-05-02 16:51:54 +02:00
from pathlib import Path
from tortoise import Tortoise
2021-12-05 18:37:35 +01:00
from aerich import Command
from mobilizon_reshare.config.publishers import publisher_names
from mobilizon_reshare.storage.query.write import update_publishers
2021-12-05 18:37:35 +01:00
from mobilizon_reshare.config.config import get_settings
logger = logging.getLogger(__name__)
2021-05-02 16:51:54 +02:00
2021-12-05 18:37:35 +01:00
def get_db_url():
"""gets db url from settings
Returns:
str : db url
"""
settings = get_settings()
db_path = Path(settings.db_path)
db_url = f"sqlite:///{db_path}"
return db_url
TORTOISE_ORM = {
"connections": {"default": get_db_url()},
"apps": {
"models": {
"models": ["mobilizon_reshare.models.event",
"mobilizon_reshare.models.notification",
"mobilizon_reshare.models.publication",
"mobilizon_reshare.models.publisher", "aerich.models"],
"default_connection": "default",
},
},
}
class MoReDB:
2021-05-31 01:11:50 +02:00
def __init__(self, path: Path):
2021-05-02 16:51:54 +02:00
self.path = path
2021-05-31 01:11:50 +02:00
# TODO: Check if DB is openable/"queriable"
self.is_init = self.path.exists() and (not self.path.is_dir())
if not self.is_init:
self.path.parent.mkdir(parents=True, exist_ok=True)
2021-05-02 16:51:54 +02:00
async def _implement_db_changes(self):
logging.info("Updating database to latest version")
2021-12-07 12:10:32 +01:00
try:
command = Command(tortoise_config=TORTOISE_ORM, app='models',
location='./migrations')
await command.init()
await command.upgrade()
except FileNotFoundError:
logging.critical("aerich configuration not found, fatal error")
# raise
sys.exit(1)
2021-12-04 17:55:43 +01:00
2021-05-02 16:51:54 +02:00
async def setup(self):
await self._implement_db_changes()
2021-05-02 16:51:54 +02:00
await Tortoise.init(
2021-12-05 18:37:35 +01:00
db_url=get_db_url(),
2021-05-31 01:11:50 +02:00
modules={
"models": [
"mobilizon_reshare.models.event",
"mobilizon_reshare.models.notification",
"mobilizon_reshare.models.publication",
"mobilizon_reshare.models.publisher",
2021-05-31 01:11:50 +02:00
]
},
# always store UTC time in database
use_tz=True,
2021-05-02 16:51:54 +02:00
)
2021-05-31 01:11:50 +02:00
if not self.is_init:
2021-05-02 16:51:54 +02:00
await Tortoise.generate_schemas()
2021-05-31 01:11:50 +02:00
self.is_init = True
logger.info(f"Successfully initialized database at {self.path}")
2021-05-31 01:19:24 +02:00
await update_publishers(publisher_names)
2021-05-31 01:19:24 +02:00
2021-07-21 09:08:19 +02:00
async def tear_down():
return await Tortoise.close_connections()