| 1 |
from typing import Any |
| 2 |
|
| 3 |
from django.conf import settings |
| 4 |
from django.contrib.auth import get_user_model |
| 5 |
from django.contrib.sessions.base_session import AbstractBaseSession |
| 6 |
from django.core import checks |
| 7 |
from django.core.exceptions import ImproperlyConfigured |
| 8 |
from django.db import connection |
| 9 |
from django.db.utils import ProgrammingError |
| 10 |
from django.utils.module_loading import import_module |
| 11 |
|
| 12 |
from django_pgschemas.settings import get_extra_search_paths |
| 13 |
from django_pgschemas.utils import ( |
| 14 |
get_clone_reference, |
| 15 |
get_domain_model, |
| 16 |
get_tenant_model, |
| 17 |
is_valid_schema_name, |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
def get_tenant_app() -> str | None: |
| 22 |
model = get_tenant_model() |
| 23 |
|
| 24 |
if model is None: |
| 25 |
return None |
| 26 |
|
| 27 |
return model._meta.app_config.name |
| 28 |
|
| 29 |
|
| 30 |
def get_domain_app() -> str | None: |
| 31 |
model = get_domain_model() |
| 32 |
|
| 33 |
if model is None: |
| 34 |
return None |
| 35 |
|
| 36 |
return model._meta.app_config.name |
| 37 |
|
| 38 |
|
| 39 |
def get_user_app() -> str | None: |
| 40 |
try: |
| 41 |
return get_user_model()._meta.app_config.name |
| 42 |
except (AttributeError, ImproperlyConfigured): |
| 43 |
return None |
| 44 |
|
| 45 |
|
| 46 |
def get_session_app() -> str | None: |
| 47 |
engine = import_module(settings.SESSION_ENGINE) |
| 48 |
store = engine.SessionStore |
| 49 |
if hasattr(store, "get_model_class"): |
| 50 |
session_model = store.get_model_class() |
| 51 |
if issubclass(session_model, AbstractBaseSession): |
| 52 |
return session_model._meta.app_config.name |
| 53 |
return None |
| 54 |
|
| 55 |
|
| 56 |
def ensure_tenant_dict() -> None: |
| 57 |
if not isinstance(getattr(settings, "TENANTS", None), dict): |
| 58 |
raise ImproperlyConfigured("TENANTS dict setting not set.") |
| 59 |
|
| 60 |
|
| 61 |
def ensure_public_schema() -> None: |
| 62 |
if not isinstance(settings.TENANTS.get("public"), dict): |
| 63 |
raise ImproperlyConfigured("TENANTS must contain a 'public' dict.") |
| 64 |
|
| 65 |
tenants_public = settings.TENANTS["public"] |
| 66 |
|
| 67 |
if "URLCONF" in tenants_public: |
| 68 |
raise ImproperlyConfigured("TENANTS['public'] cannot contain a 'URLCONF' key.") |
| 69 |
if "WS_URLCONF" in tenants_public: |
| 70 |
raise ImproperlyConfigured("TENANTS['public'] cannot contain a 'WS_URLCONF' key.") |
| 71 |
if "DOMAINS" in tenants_public: |
| 72 |
raise ImproperlyConfigured("TENANTS['public'] cannot contain a 'DOMAINS' key.") |
| 73 |
if "SESSION_KEY" in tenants_public: |
| 74 |
raise ImproperlyConfigured("TENANTS['public'] cannot contain a 'SESSION_KEY' key.") |
| 75 |
if "HEADER" in tenants_public: |
| 76 |
raise ImproperlyConfigured("TENANTS['public'] cannot contain a 'HEADER' key.") |
| 77 |
if "FALLBACK_DOMAINS" in tenants_public: |
| 78 |
raise ImproperlyConfigured("TENANTS['public'] cannot contain a 'FALLBACK_DOMAINS' key.") |
| 79 |
|
| 80 |
|
| 81 |
def ensure_default_schemas() -> None: |
| 82 |
if "default" not in settings.TENANTS: |
| 83 |
return # Escape hatch for static only configs |
| 84 |
|
| 85 |
if not isinstance(settings.TENANTS["default"], dict): |
| 86 |
raise ImproperlyConfigured("TENANTS must contain a 'default' dict.") |
| 87 |
|
| 88 |
tenants_default = settings.TENANTS["default"] |
| 89 |
|
| 90 |
if "TENANT_MODEL" not in tenants_default: |
| 91 |
raise ImproperlyConfigured("TENANTS['default'] must contain a 'TENANT_MODEL' key.") |
| 92 |
if "URLCONF" not in tenants_default: |
| 93 |
raise ImproperlyConfigured("TENANTS['default'] must contain a 'URLCONF' key.") |
| 94 |
if "DOMAINS" in tenants_default: |
| 95 |
raise ImproperlyConfigured("TENANTS['default'] cannot contain a 'DOMAINS' key.") |
| 96 |
if "SESSION_KEY" in tenants_default: |
| 97 |
raise ImproperlyConfigured("TENANTS['default'] cannot contain a 'SESSION_KEY' key.") |
| 98 |
if "HEADER" in tenants_default: |
| 99 |
raise ImproperlyConfigured("TENANTS['default'] cannot contain a 'HEADER' key.") |
| 100 |
if "FALLBACK_DOMAINS" in tenants_default: |
| 101 |
raise ImproperlyConfigured("TENANTS['default'] cannot contain a 'FALLBACK_DOMAINS' key.") |
| 102 |
if tenants_default.get("CLONE_REFERENCE") in settings.TENANTS: |
| 103 |
raise ImproperlyConfigured( |
| 104 |
"TENANTS['default']['CLONE_REFERENCE'] must be a unique schema name." |
| 105 |
) |
| 106 |
|
| 107 |
|
| 108 |
def ensure_overall_schemas() -> None: |
| 109 |
for schema in settings.TENANTS: |
| 110 |
if schema not in ["public", "default"]: |
| 111 |
if not is_valid_schema_name(schema): |
| 112 |
raise ImproperlyConfigured(f"'{schema}' is not a valid schema name.") |
| 113 |
|
| 114 |
|
| 115 |
def ensure_extra_search_paths() -> None: |
| 116 |
if not (extra_search_paths := get_extra_search_paths()): |
| 117 |
return |
| 118 |
|
| 119 |
TenantModel = get_tenant_model() |
| 120 |
|
| 121 |
dynamic_tenants = [] |
| 122 |
|
| 123 |
if "default" in settings.TENANTS and "CLONE_REFERENCE" in settings.TENANTS["default"]: |
| 124 |
dynamic_tenants.append(settings.TENANTS["default"]["CLONE_REFERENCE"]) |
| 125 |
|
| 126 |
if TenantModel is not None: |
| 127 |
with connection.cursor() as cursor: |
| 128 |
cursor.execute( |
| 129 |
"SELECT 1 FROM information_schema.tables WHERE table_name = %s;", |
| 130 |
[TenantModel._meta.db_table], |
| 131 |
) |
| 132 |
if cursor.fetchone(): |
| 133 |
dynamic_tenants += list(TenantModel.objects.values_list("schema_name", flat=True)) |
| 134 |
|
| 135 |
invalid_schemas = set(extra_search_paths) & ( |
| 136 |
set(settings.TENANTS.keys()) | set(dynamic_tenants) |
| 137 |
) |
| 138 |
|
| 139 |
if invalid_schemas: |
| 140 |
invalid = ", ".join(invalid_schemas) |
| 141 |
raise ImproperlyConfigured(f"Do not include '{invalid}' on PGSCHEMAS_EXTRA_SEARCH_PATHS.") |
| 142 |
|
| 143 |
|
| 144 |
@checks.register() |
| 145 |
def check_principal_apps(app_configs: Any, **kwargs: Any) -> list: |
| 146 |
errors = [] |
| 147 |
tenant_app = get_tenant_app() |
| 148 |
domain_app = get_domain_app() |
| 149 |
|
| 150 |
tenants_public = settings.TENANTS["public"] |
| 151 |
|
| 152 |
if tenant_app is not None and tenant_app not in tenants_public.get("APPS", []): |
| 153 |
errors.append( |
| 154 |
checks.Error( |
| 155 |
f"Your tenant app '{tenant_app}' must be on the 'public' schema.", |
| 156 |
id="pgschemas.W001", |
| 157 |
) |
| 158 |
) |
| 159 |
if domain_app is not None and domain_app not in tenants_public.get("APPS", []): |
| 160 |
errors.append( |
| 161 |
checks.Error( |
| 162 |
f"Your domain app '{domain_app}' must be on the 'public' schema.", |
| 163 |
id="pgschemas.W001", |
| 164 |
) |
| 165 |
) |
| 166 |
|
| 167 |
for schema in settings.TENANTS: |
| 168 |
schema_apps = settings.TENANTS[schema].get("APPS", []) |
| 169 |
if schema == "public": |
| 170 |
continue |
| 171 |
if tenant_app is not None and tenant_app in schema_apps: |
| 172 |
errors.append( |
| 173 |
checks.Error( |
| 174 |
f"Your tenant app '{tenant_app}' in TENANTS['{schema}']['APPS'] " |
| 175 |
"must be on the 'public' schema only.", |
| 176 |
id="pgschemas.W001", |
| 177 |
) |
| 178 |
) |
| 179 |
if domain_app is not None and domain_app in schema_apps: |
| 180 |
errors.append( |
| 181 |
checks.Error( |
| 182 |
f"Your domain app '{domain_app}' in TENANTS['{schema}']['APPS'] " |
| 183 |
"must be on the 'public' schema only.", |
| 184 |
id="pgschemas.W001", |
| 185 |
) |
| 186 |
) |
| 187 |
|
| 188 |
return errors |
| 189 |
|
| 190 |
|
| 191 |
@checks.register() |
| 192 |
def check_other_apps(app_configs: Any, **kwargs: Any) -> list: |
| 193 |
errors = [] |
| 194 |
user_app = get_user_app() |
| 195 |
session_app = get_session_app() |
| 196 |
|
| 197 |
if "django.contrib.contenttypes" in settings.TENANTS.get("default", {}).get("APPS", []): |
| 198 |
errors.append( |
| 199 |
checks.Warning( |
| 200 |
"'django.contrib.contenttypes' in TENANTS['default']['APPS'] " |
| 201 |
"must be on 'public' schema only.", |
| 202 |
id="pgschemas.W002", |
| 203 |
) |
| 204 |
) |
| 205 |
|
| 206 |
for schema in settings.TENANTS: |
| 207 |
schema_apps = settings.TENANTS[schema].get("APPS", []) |
| 208 |
if schema not in ["public", "default"]: |
| 209 |
if "django.contrib.contenttypes" in schema_apps: |
| 210 |
errors.append( |
| 211 |
checks.Warning( |
| 212 |
f"'django.contrib.contenttypes' in TENANTS['{schema}']['APPS'] " |
| 213 |
"must be on 'public' schema only.", |
| 214 |
id="pgschemas.W002", |
| 215 |
) |
| 216 |
) |
| 217 |
if user_app and session_app: |
| 218 |
if session_app in schema_apps and user_app not in schema_apps: |
| 219 |
errors.append( |
| 220 |
checks.Warning( |
| 221 |
f"'{user_app}' must be together with '{session_app}' in " |
| 222 |
f"TENANTS['{schema}']['APPS'].", |
| 223 |
id="pgschemas.W003", |
| 224 |
) |
| 225 |
) |
| 226 |
elif ( |
| 227 |
user_app in schema_apps |
| 228 |
and session_app not in schema_apps |
| 229 |
and session_app in settings.INSTALLED_APPS |
| 230 |
): |
| 231 |
errors.append( |
| 232 |
checks.Warning( |
| 233 |
f"'{session_app}' must be together with '{user_app}' in " |
| 234 |
f"TENANTS['{schema}']['APPS'].", |
| 235 |
id="pgschemas.W003", |
| 236 |
) |
| 237 |
) |
| 238 |
|
| 239 |
return errors |
| 240 |
|
| 241 |
|
| 242 |
@checks.register(checks.Tags.database) |
| 243 |
def check_schema_names(app_configs: Any, **kwargs: Any) -> list: |
| 244 |
errors = [] |
| 245 |
static_names = set(settings.TENANTS.keys()) |
| 246 |
clone_reference = get_clone_reference() |
| 247 |
TenantModel = get_tenant_model() |
| 248 |
|
| 249 |
if TenantModel is None: |
| 250 |
return [] |
| 251 |
|
| 252 |
if clone_reference: |
| 253 |
static_names.add(clone_reference) |
| 254 |
try: |
| 255 |
dynamic_names = set(TenantModel.objects.values_list("schema_name", flat=True)) |
| 256 |
except ProgrammingError: |
| 257 |
# This happens on the first run of migrate, with empty database. |
| 258 |
# It can also happen when the tenant model contains unapplied migrations that break. |
| 259 |
dynamic_names = set() |
| 260 |
|
| 261 |
intersection = static_names & dynamic_names |
| 262 |
|
| 263 |
if intersection: |
| 264 |
errors.append( |
| 265 |
checks.Critical( |
| 266 |
f"Name clash found between static and dynamic tenants: {intersection}", |
| 267 |
id="pgschemas.W004", |
| 268 |
) |
| 269 |
) |
| 270 |
|
| 271 |
return errors |