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

107 lines
2.9 KiB
Python
Raw Normal View History

import logging
from logging.config import dictConfig
2021-05-02 16:51:54 +02:00
from pathlib import Path
import pkg_resources
import urllib3.util
2021-12-05 18:37:35 +01:00
from aerich import Command
from tortoise import Tortoise
from mobilizon_reshare.config.config import (
get_settings,
get_settings_without_validation,
)
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
logger = logging.getLogger(__name__)
2021-05-02 16:51:54 +02:00
def get_db_url() -> urllib3.util.Url:
return urllib3.util.parse_url(get_settings_without_validation().db_url)
2021-12-05 18:37:35 +01:00
2021-12-14 22:37:49 +01:00
def get_tortoise_orm():
2021-12-14 22:37:49 +01:00
return {
"connections": {"default": get_db_url().url},
2021-12-14 22:37:49 +01:00
"apps": {
"models": {
"models": [
"mobilizon_reshare.models.event",
"mobilizon_reshare.models.notification",
"mobilizon_reshare.models.publication",
"mobilizon_reshare.models.publisher",
"aerich.models",
],
"default_connection": "default",
},
2021-12-05 18:37:35 +01:00
},
# always store UTC time in database
"use_tz": True,
2021-12-14 22:37:49 +01:00
}
2021-12-07 16:58:12 +01:00
TORTOISE_ORM = get_tortoise_orm()
class MoReDB:
def get_migration_location(self):
scheme = get_db_url().scheme
return pkg_resources.resource_filename(
"mobilizon_reshare", f"migrations/{scheme}"
)
2021-05-02 16:51:54 +02:00
async def _implement_db_changes(self):
logging.info("Performing aerich migrations.")
command = Command(
tortoise_config=get_tortoise_orm(),
app="models",
location=self.get_migration_location(),
)
await command.init()
migrations = await command.upgrade()
if migrations:
logging.info("Updated database to latest version")
2021-12-04 17:55:43 +01:00
2021-05-02 16:51:54 +02:00
async def setup(self):
tortoise_config = get_tortoise_orm()
Tortoise.init_models(
tortoise_config["apps"]["models"]["models"], "models", _init_relations=True
)
2021-12-14 22:37:49 +01:00
await self._implement_db_changes()
await Tortoise.init(config=tortoise_config)
await Tortoise.generate_schemas()
await update_publishers(publisher_names)
2021-05-31 01:19:24 +02:00
class MoReSQLiteDB(MoReDB):
def __init__(self):
if (
get_db_url().path
): # if in-memory sqlite there's no path so nothing has to be initialized
self.path = Path(get_db_url().path)
# 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-07-21 09:08:19 +02:00
async def tear_down():
return await Tortoise.close_connections()
async def init(init_logging=True):
if init_logging:
dictConfig(get_settings()["logging"])
# init storage
url = get_db_url()
if url.scheme == "sqlite":
db = MoReSQLiteDB()
else:
db = MoReDB()
await db.setup()