77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
from collections.abc import Callable, Iterator
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
from sqlalchemy import create_engine, pool, text
|
|
|
|
from app.config import BACKEND_ROOT, data_dir, database_url, installed
|
|
|
|
logger = logging.getLogger("decom")
|
|
INSTALL_LOCK = 7_316_501_842
|
|
|
|
|
|
@contextmanager
|
|
def _install_lock() -> Iterator[None]:
|
|
"""接口和排队进程可能同时启动,建表和初始化依次进行。"""
|
|
url = database_url()
|
|
if not url.startswith("postgresql"):
|
|
yield
|
|
return
|
|
engine = create_engine(url, poolclass=pool.NullPool, isolation_level="AUTOCOMMIT")
|
|
try:
|
|
with engine.connect() as connection:
|
|
connection.execute(text("SELECT pg_advisory_lock(:key)"), {"key": INSTALL_LOCK})
|
|
try:
|
|
yield
|
|
finally:
|
|
connection.execute(text("SELECT pg_advisory_unlock(:key)"), {"key": INSTALL_LOCK})
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
def _ensure_queue_schema() -> None:
|
|
from app.config import postgres_conninfo
|
|
|
|
conninfo = postgres_conninfo()
|
|
if not conninfo:
|
|
return
|
|
import psycopg
|
|
from procrastinate.schema import SchemaManager
|
|
|
|
with psycopg.connect(conninfo) as connection:
|
|
exists = connection.execute("SELECT to_regclass('procrastinate_jobs')").fetchone()
|
|
if exists and exists[0]:
|
|
return
|
|
connection.execute(SchemaManager.get_schema())
|
|
logger.info("已建立排队表")
|
|
|
|
|
|
def migrate(then: Callable[[], None] | None = None) -> None:
|
|
data_dir().mkdir(parents=True, exist_ok=True)
|
|
config = Config(str(Path(BACKEND_ROOT) / "alembic.ini"))
|
|
config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic"))
|
|
config.attributes["configure_logger"] = False
|
|
with _install_lock():
|
|
command.upgrade(config, "head")
|
|
_ensure_queue_schema()
|
|
if then is not None:
|
|
then()
|
|
|
|
|
|
def init_db() -> bool:
|
|
"""准备数据库。返回数据库是否已可用。"""
|
|
from app.install import auto_install
|
|
|
|
if auto_install():
|
|
return True
|
|
if not installed():
|
|
logger.info("尚未安装,等待安装页")
|
|
return False
|
|
migrate()
|
|
return True
|