2021-05-20 01:57:40 +02:00
|
|
|
import logging
|
2021-05-02 16:51:54 +02:00
|
|
|
from pathlib import Path
|
2021-05-05 14:29:13 +02:00
|
|
|
|
2021-05-02 16:51:54 +02:00
|
|
|
from tortoise import Tortoise
|
|
|
|
|
2021-08-16 10:49:52 +02:00
|
|
|
from mobilizon_reshare.config.publishers import publisher_names
|
2021-11-24 23:58:06 +01:00
|
|
|
from mobilizon_reshare.storage.query.write import update_publishers
|
2021-12-04 17:55:43 +01:00
|
|
|
from aerich import Command
|
|
|
|
from mobilizon_reshare.aerich_conf.database import TORTOISE_ORM
|
2021-07-05 23:07:12 +02:00
|
|
|
|
2021-05-20 01:57:40 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2021-05-02 16:51:54 +02:00
|
|
|
|
2021-08-16 10:49:52 +02:00
|
|
|
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
|
|
|
|
2021-12-04 17:55:43 +01:00
|
|
|
async def __implement_db_changes__(self):
|
2021-12-04 19:34:00 +01:00
|
|
|
# return
|
2021-12-04 17:55:43 +01:00
|
|
|
print('implementing db changes')
|
|
|
|
command = Command(tortoise_config=TORTOISE_ORM, app='models',
|
2021-12-04 19:34:00 +01:00
|
|
|
location='./migrations'
|
|
|
|
)
|
2021-12-04 17:55:43 +01:00
|
|
|
await command.init()
|
|
|
|
await command.upgrade()
|
|
|
|
|
|
|
|
|
2021-05-02 16:51:54 +02:00
|
|
|
async def setup(self):
|
2021-12-04 17:55:43 +01:00
|
|
|
await self.__implement_db_changes__()
|
2021-05-02 16:51:54 +02:00
|
|
|
await Tortoise.init(
|
|
|
|
db_url=f"sqlite:///{self.path}",
|
2021-05-31 01:11:50 +02:00
|
|
|
modules={
|
|
|
|
"models": [
|
2021-08-16 10:49:52 +02:00
|
|
|
"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
|
2021-11-11 15:18:04 +01:00
|
|
|
logger.info(f"Successfully initialized database at {self.path}")
|
2021-05-31 01:19:24 +02:00
|
|
|
|
2021-08-05 00:29:50 +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()
|