Debian Codegraph @

django_pgschemas/routers.py

raw
1 from typing import Iterable
2
3 from django.apps import apps
4 from django.conf import settings
5
6 from django_pgschemas.schema import get_current_schema
7 from django_pgschemas.utils import get_tenant_database_alias
8
9
10 class TenantAppsRouter:
11 """
12 A router to control which applications will be actually migrated depending on the schema.
13 """
14
15 def app_in_list(self, app_label: str, app_list: Iterable) -> bool:
16 app_config = apps.get_app_config(app_label)
17 app_config_full_name = f"{app_config.__module__}.{app_config.__class__.__name__}"
18 return (app_config.name in app_list) or (app_config_full_name in app_list)
19
20 def allow_migrate(
21 self, db: str, app_label: str, model_name: str | None = None, **hints: object
22 ) -> bool | None:
23 current_schema = get_current_schema()
24 if db != get_tenant_database_alias() or current_schema is None:
25 return False
26 app_list = []
27 if current_schema.schema_name == "public":
28 app_list = settings.TENANTS["public"]["APPS"]
29 elif current_schema.schema_name in settings.TENANTS:
30 app_list = settings.TENANTS[current_schema.schema_name]["APPS"]
31 else:
32 app_list = settings.TENANTS["default"]["APPS"]
33 if not app_list:
34 return None
35 return self.app_in_list(app_label, app_list)