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