39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
from __future__ import annotations
|
|
import fcntl
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from flask import Flask
|
|
from .database_init import initialize_database
|
|
from .database_migrations import migrate_database
|
|
|
|
|
|
@contextmanager
|
|
def _startup_lock(app: Flask):
|
|
lock_path = Path(app.instance_path) / ".database-startup.lock"
|
|
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
with lock_path.open("w") as lock_file:
|
|
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
try:
|
|
yield
|
|
finally:
|
|
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
|
|
|
|
def prepare_database(app: Flask) -> list[str]:
|
|
with app.app_context(), _startup_lock(app):
|
|
initialize_database()
|
|
applied = migrate_database()
|
|
from .extensions import db
|
|
from .models import FuelEntry
|
|
from .settlement import freeze
|
|
pending = FuelEntry.query.filter_by(settlement_frozen=False).all()
|
|
for entry in pending:
|
|
freeze(entry, source="Migracja istniejącego wpisu", migration_note="Warunki odtworzono z ustawień dostępnych podczas migracji; wymagają weryfikacji.")
|
|
if pending:
|
|
db.session.commit()
|
|
return applied
|
|
|
|
|
|
__all__ = ["initialize_database", "migrate_database", "prepare_database"]
|