2022-12-22 16:30:37 +02:00
|
|
|
import importlib
|
|
|
|
import re
|
2023-01-20 17:08:44 +02:00
|
|
|
from typing import Any
|
2022-12-22 16:30:37 +02:00
|
|
|
|
|
|
|
from loguru import logger
|
|
|
|
|
2023-01-20 17:08:44 +02:00
|
|
|
from lnbits.db import Connection
|
2023-01-20 10:06:32 +02:00
|
|
|
from lnbits.extension_manager import Extension
|
2023-01-11 10:57:19 +02:00
|
|
|
|
2022-12-22 16:30:37 +02:00
|
|
|
from . import db as core_db
|
|
|
|
from .crud import update_migration_version
|
|
|
|
|
|
|
|
|
2023-01-11 10:57:19 +02:00
|
|
|
async def migrate_extension_database(ext: Extension, current_version):
|
2022-12-22 16:30:37 +02:00
|
|
|
try:
|
2022-11-30 10:56:23 +02:00
|
|
|
ext_migrations = importlib.import_module(f"{ext.module_name}.migrations")
|
|
|
|
ext_db = importlib.import_module(ext.module_name).db
|
2022-12-22 17:18:53 +02:00
|
|
|
except ImportError as e:
|
|
|
|
logger.error(e)
|
2022-12-22 16:30:37 +02:00
|
|
|
raise ImportError(
|
|
|
|
f"Please make sure that the extension `{ext.code}` has a migrations file."
|
|
|
|
)
|
|
|
|
|
|
|
|
async with ext_db.connect() as ext_conn:
|
|
|
|
await run_migration(ext_conn, ext_migrations, current_version)
|
|
|
|
|
|
|
|
|
2023-01-20 17:08:44 +02:00
|
|
|
async def run_migration(db: Connection, migrations_module: Any, current_version: int):
|
2022-12-22 16:30:37 +02:00
|
|
|
matcher = re.compile(r"^m(\d\d\d)_")
|
|
|
|
db_name = migrations_module.__name__.split(".")[-2]
|
|
|
|
for key, migrate in migrations_module.__dict__.items():
|
2023-01-20 16:11:51 +02:00
|
|
|
match = matcher.match(key)
|
2022-12-22 16:30:37 +02:00
|
|
|
if match:
|
|
|
|
version = int(match.group(1))
|
|
|
|
if version > current_version:
|
|
|
|
logger.debug(f"running migration {db_name}.{version}")
|
|
|
|
print(f"running migration {db_name}.{version}")
|
|
|
|
await migrate(db)
|
|
|
|
|
2023-01-21 15:08:59 +00:00
|
|
|
if db.schema is None:
|
2022-12-22 16:30:37 +02:00
|
|
|
await update_migration_version(db, db_name, version)
|
|
|
|
else:
|
|
|
|
async with core_db.connect() as conn:
|
|
|
|
await update_migration_version(conn, db_name, version)
|