1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
|
import logging
import types
from importlib.machinery import SourceFileLoader
from pathlib import Path
from typing import List, Optional, Type
from motor.motor_asyncio import AsyncIOMotorClientSession, AsyncIOMotorDatabase
from beanie.migrations.controllers.iterative import BaseMigrationController
from beanie.migrations.database import DBHandler
from beanie.migrations.models import (
MigrationLog,
RunningDirections,
RunningMode,
)
from beanie.odm.documents import Document
from beanie.odm.utils.init import init_beanie
logger = logging.getLogger(__name__)
class MigrationNode:
def __init__(
self,
name: str,
forward_class: Optional[Type[Document]] = None,
backward_class: Optional[Type[Document]] = None,
next_migration: Optional["MigrationNode"] = None,
prev_migration: Optional["MigrationNode"] = None,
):
"""
Node of the migration linked list
:param name: name of the migration
:param forward_class: Forward class of the migration
:param backward_class: Backward class of the migration
:param next_migration: link to the next migration
:param prev_migration: link to the previous migration
"""
self.name = name
self.forward_class = forward_class
self.backward_class = backward_class
self.next_migration = next_migration
self.prev_migration = prev_migration
@staticmethod
async def clean_current_migration():
await MigrationLog.find(
{"is_current": True},
).update({"$set": {"is_current": False}})
async def update_current_migration(self):
"""
Set sel as a current migration
:return:
"""
await self.clean_current_migration()
await MigrationLog(is_current=True, name=self.name).insert()
async def run(
self,
mode: RunningMode,
allow_index_dropping: bool,
use_transaction: bool,
):
"""
Migrate
:param mode: RunningMode
:param allow_index_dropping: if index dropping is allowed
:return: None
"""
if mode.direction == RunningDirections.FORWARD:
migration_node = self.next_migration
if migration_node is None:
return None
if mode.distance == 0:
logger.info("Running migrations forward without limit")
while True:
await migration_node.run_forward(
allow_index_dropping=allow_index_dropping,
use_transaction=use_transaction,
)
migration_node = migration_node.next_migration
if migration_node is None:
break
else:
logger.info(f"Running {mode.distance} migrations forward")
for i in range(mode.distance):
await migration_node.run_forward(
allow_index_dropping=allow_index_dropping,
use_transaction=use_transaction,
)
migration_node = migration_node.next_migration
if migration_node is None:
break
elif mode.direction == RunningDirections.BACKWARD:
migration_node = self
if mode.distance == 0:
logger.info("Running migrations backward without limit")
while True:
await migration_node.run_backward(
allow_index_dropping=allow_index_dropping,
use_transaction=use_transaction,
)
migration_node = migration_node.prev_migration
if migration_node is None:
break
else:
logger.info(f"Running {mode.distance} migrations backward")
for i in range(mode.distance):
await migration_node.run_backward(
allow_index_dropping=allow_index_dropping,
use_transaction=use_transaction,
)
migration_node = migration_node.prev_migration
if migration_node is None:
break
async def run_forward(
self, allow_index_dropping: bool, use_transaction: bool
):
if self.forward_class is not None:
await self.run_migration_class(
self.forward_class,
allow_index_dropping=allow_index_dropping,
use_transaction=use_transaction,
)
await self.update_current_migration()
async def run_backward(
self, allow_index_dropping: bool, use_transaction: bool
):
if self.backward_class is not None:
await self.run_migration_class(
self.backward_class,
allow_index_dropping=allow_index_dropping,
use_transaction=use_transaction,
)
if self.prev_migration is not None:
await self.prev_migration.update_current_migration()
else:
await self.clean_current_migration()
async def run_migration_class(
self, cls: Type, allow_index_dropping: bool, use_transaction: bool
):
"""
Run Backward or Forward migration class
:param cls:
:param allow_index_dropping: if index dropping is allowed
:return:
"""
migrations = [
getattr(cls, migration)
for migration in dir(cls)
if isinstance(getattr(cls, migration), BaseMigrationController)
]
client = DBHandler.get_cli()
db = DBHandler.get_db()
if client is None:
raise RuntimeError("client must not be None")
async with await client.start_session() as s:
if use_transaction:
async with s.start_transaction():
await self.run_migrations(
migrations, db, allow_index_dropping, s
)
else:
await self.run_migrations(
migrations, db, allow_index_dropping, s
)
async def run_migrations(
self,
migrations: List[BaseMigrationController],
db: AsyncIOMotorDatabase,
allow_index_dropping: bool,
session: AsyncIOMotorClientSession,
) -> None:
for migration in migrations:
for model in migration.models:
await init_beanie(
database=db,
document_models=[model], # type: ignore
allow_index_dropping=allow_index_dropping,
) # TODO this is slow
logger.info(
f"Running migration {migration.function.__name__} "
f"from module {self.name}"
)
await migration.run(session=session)
@classmethod
async def build(cls, path: Path):
"""
Build the migrations linked list
:param path: Relative path to the migrations directory
:return:
"""
logger.info("Building migration list")
names = []
for modulepath in path.glob("*.py"):
names.append(modulepath.name)
names.sort()
db = DBHandler.get_db()
await init_beanie(
database=db,
document_models=[MigrationLog], # type: ignore
)
current_migration = await MigrationLog.find_one({"is_current": True})
root_migration_node = cls("root")
prev_migration_node = root_migration_node
for name in names:
loader = SourceFileLoader(
(path / name).stem, str((path / name).absolute())
)
module = types.ModuleType(loader.name)
loader.exec_module(module)
forward_class = getattr(module, "Forward", None)
backward_class = getattr(module, "Backward", None)
migration_node = cls(
name=name,
prev_migration=prev_migration_node,
forward_class=forward_class,
backward_class=backward_class,
)
prev_migration_node.next_migration = migration_node
prev_migration_node = migration_node
if (
current_migration is not None
and current_migration.name == name
):
root_migration_node = migration_node
return root_migration_node
|