| 1 |
from contextlib import contextmanager |
| 2 |
from contextvars import ContextVar, Token |
| 3 |
from functools import lru_cache |
| 4 |
from typing import Iterator |
| 5 |
|
| 6 |
from django_pgschemas.routing.info import RoutingInfo |
| 7 |
from django_pgschemas.signals import schema_activate |
| 8 |
|
| 9 |
|
| 10 |
class Schema: |
| 11 |
schema_name: str |
| 12 |
routing: RoutingInfo = None |
| 13 |
|
| 14 |
is_dynamic = False |
| 15 |
|
| 16 |
_context_tokens: list[Token["Schema"] | None] |
| 17 |
|
| 18 |
def __init__(self, *args: object, **kwargs: object) -> None: |
| 19 |
super().__init__(*args, **kwargs) |
| 20 |
self._context_tokens = [] |
| 21 |
|
| 22 |
@staticmethod |
| 23 |
def create(schema_name: str, routing: RoutingInfo | None = None) -> "Schema": |
| 24 |
schema = Schema() |
| 25 |
schema.schema_name = schema_name |
| 26 |
schema.routing = routing |
| 27 |
return schema |
| 28 |
|
| 29 |
def __enter__(self) -> None: |
| 30 |
self._context_tokens.append(push(self)) |
| 31 |
|
| 32 |
def __exit__(self, *args: object) -> None: |
| 33 |
if self._context_tokens: |
| 34 |
token = self._context_tokens.pop() |
| 35 |
if token is not None: |
| 36 |
active.reset(token) |
| 37 |
|
| 38 |
|
| 39 |
def shallow_equal(schema1: Schema, schema2: Schema) -> bool: |
| 40 |
return schema1.schema_name == schema2.schema_name and schema1.routing == schema2.routing |
| 41 |
|
| 42 |
|
| 43 |
@lru_cache |
| 44 |
def get_default_schema() -> Schema: |
| 45 |
return Schema.create("public") |
| 46 |
|
| 47 |
|
| 48 |
active: ContextVar["Schema"] = ContextVar("active_schema", default=get_default_schema()) |
| 49 |
|
| 50 |
|
| 51 |
def get_current_schema() -> Schema: |
| 52 |
return active.get() |
| 53 |
|
| 54 |
|
| 55 |
def push(schema: Schema) -> Token[Schema] | None: |
| 56 |
if shallow_equal(get_current_schema(), schema): |
| 57 |
return None |
| 58 |
|
| 59 |
token = active.set(schema) |
| 60 |
|
| 61 |
schema_activate.send(sender=Schema, schema=schema) |
| 62 |
|
| 63 |
return token |
| 64 |
|
| 65 |
|
| 66 |
def activate(schema: Schema) -> None: |
| 67 |
push(schema) |
| 68 |
|
| 69 |
|
| 70 |
def deactivate() -> None: |
| 71 |
push(get_default_schema()) |
| 72 |
|
| 73 |
|
| 74 |
activate_public = deactivate |
| 75 |
|
| 76 |
|
| 77 |
@contextmanager |
| 78 |
def override(schema: Schema) -> Iterator[None]: |
| 79 |
token = push(schema) |
| 80 |
|
| 81 |
yield |
| 82 |
|
| 83 |
if token is not None: |
| 84 |
active.reset(token) |