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

44 lines
1.3 KiB
Python
Raw Normal View History

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
from mobilizon_reshare.config.publishers import publisher_names
from mobilizon_reshare.storage.query.write import update_publishers
logger = logging.getLogger(__name__)
2021-05-02 16:51:54 +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
async def setup(self):
await Tortoise.init(
db_url=f"sqlite:///{self.path}",
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()