Debian Codegraph @

django_pgschemas/postgresql/base.py

raw
1 from typing import Any
2
3 from django.core.exceptions import ImproperlyConfigured
4 from django.db.utils import DatabaseError
5 from django.utils.asyncio import async_unsafe
6
7 from django_pgschemas.schema import Schema, get_current_schema, get_default_schema
8 from django_pgschemas.settings import (
9 get_base_backend_module,
10 get_extra_search_paths,
11 get_original_backend_module,
12 )
13 from django_pgschemas.utils import check_schema_name, get_limit_set_calls
14
15 from .introspection import DatabaseSchemaIntrospection
16
17 try:
18 try:
19 import psycopg as _psycopg
20 except ImportError:
21 import psycopg2 as _psycopg # type: ignore[no-redef]
22 except ImportError:
23 raise ImproperlyConfigured("Error loading psycopg2 or psycopg module")
24
25 try:
26 module = get_original_backend_module("base")
27 except AttributeError:
28 module = get_base_backend_module("base")
29
30
31 def get_search_path(schema: Schema | None = None) -> str:
32 if schema is None:
33 schema = get_default_schema()
34
35 search_path = ["public"] if schema.schema_name == "public" else [schema.schema_name, "public"]
36 search_path.extend(get_extra_search_paths())
37
38 for part in search_path:
39 check_schema_name(part)
40
41 return ", ".join(search_path)
42
43
44 class DatabaseWrapper(module.DatabaseWrapper): # type: ignore[name-defined]
45 def __init__(self, *args: Any, **kwargs: Any) -> None:
46 self._search_path: str | None = None
47 self._setting_search_path = False
48 super().__init__(*args, **kwargs)
49
50 # Patched version of DatabaseIntrospection that only returns the table list for the currently selected schema
51 self.introspection = DatabaseSchemaIntrospection(self)
52
53 @async_unsafe
54 def close(self) -> None:
55 self._search_path = None
56 self._setting_search_path = False
57 super().close()
58
59 @async_unsafe
60 def rollback(self) -> None:
61 self._search_path = None
62 self._setting_search_path = False
63 super().rollback()
64
65 def _handle_search_path(self, cursor: Any | None = None) -> None:
66 search_path_for_current_schema = get_search_path(get_current_schema())
67
68 skip = self._setting_search_path or (
69 self._search_path == search_path_for_current_schema and get_limit_set_calls()
70 )
71
72 if not skip:
73 self._setting_search_path = True
74 cursor_for_search_path = self.connection.cursor() if cursor is None else cursor
75
76 try:
77 cursor_for_search_path.execute(
78 f"SET search_path = {search_path_for_current_schema}"
79 )
80 except (DatabaseError, _psycopg.InternalError):
81 self._search_path = None
82 else:
83 self._search_path = search_path_for_current_schema
84 finally:
85 self._setting_search_path = False
86
87 if cursor is None:
88 cursor_for_search_path.close()
89
90 def _cursor(self, name: str | None = None) -> Any:
91 cursor = super()._cursor(name=name)
92
93 cursor_for_search_path = cursor if name is None else None # Named cursors cannot be reused
94 self._handle_search_path(cursor_for_search_path)
95
96 return cursor