Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 73 additions & 31 deletions django_tenants/postgresql_backend/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from django_tenants.utils import get_public_schema_name, get_limit_set_calls, quote_schema_name
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils.asyncio import async_unsafe
import django.db.utils

import psycopg
Expand Down Expand Up @@ -67,6 +68,9 @@ class DatabaseWrapper(original_backend.DatabaseWrapper):

def __init__(self, *args, **kwargs):
self.search_path_set_schemas = None
# Guards against re-entering _cursor() while we are obtaining a cursor to
# set the search_path with. See _handle_search_path().
self._setting_search_path = False
self.tenant = None
self.schema_name = None
super().__init__(*args, **kwargs)
Expand All @@ -79,8 +83,19 @@ def __init__(self, *args, **kwargs):

def close(self):
self.search_path_set_schemas = None
self._setting_search_path = False
super().close()

@async_unsafe
def rollback(self):
# A session-level `SET` is transactional in PostgreSQL: aborting the
# transaction that issued it reverts the search_path. Forget the cached
# value so the next cursor re-issues it rather than trusting a setting the
# database has already discarded.
self.search_path_set_schemas = None
self._setting_search_path = False
super().rollback()

def set_tenant(self, tenant, include_public=True):
"""
Main API method to current database schema,
Expand Down Expand Up @@ -142,43 +157,65 @@ def _cursor(self, name=None):
else:
cursor = super()._cursor()

# A named cursor can only execute one statement, so it cannot carry the
# `SET search_path` and we have to open a throwaway cursor for it. An
# unnamed one can, and reusing it keeps the statement visible to Django's
# cursor wrapper -- and therefore to assertNumQueries -- on every driver.
self._handle_search_path(cursor if name is None else None)

return cursor

def _handle_search_path(self, cursor=None):
"""
Issue `SET search_path` for the currently selected schema. Database will
search schemata from left to right when looking for the object
(table, index, sequence, etc.).

Pass the cursor to run it on, or None to have one opened and closed here.
"""
# Obtaining a cursor below can re-enter _cursor(); this flag makes that
# re-entry a no-op instead of infinite recursion. Previously this was
# avoided by never reusing the caller's cursor on psycopg3, which made the
# statement invisible to Django's cursor wrapper on that driver only.
if self._setting_search_path:
return

# optionally limit the number of executions - under load, the execution
# of `set search_path` can be quite time consuming
if (not get_limit_set_calls()) or not self.search_path_set_schemas:
# Actual search_path modification for the cursor. Database will
# search schemata from left to right when looking for the object
# (table, index, sequence, etc.).
if not self.schema_name:
raise ImproperlyConfigured("Database schema not set. Did you forget "
"to call set_schema() or set_tenant()?")

search_paths = self._get_cursor_search_paths()

# Named cursor can only be used once and Django 4 has a recursion
# issue, so always open a separate cursor for the search path.
cursor_for_search_path = self.connection.cursor()

# In the event that an error already happened in this transaction and we are going
# to rollback we should just ignore database error when setting the search_path
# if the next instruction is not a rollback it will just fail also, so
# we do not have to worry that it's not the good one
try:
cursor_for_search_path.execute(
sql.SQL('SET search_path = {0}').format(
sql.SQL(', ').join(
quote_schema_name(name) for name in search_paths
)
if get_limit_set_calls() and self.search_path_set_schemas:
return

if not self.schema_name:
raise ImproperlyConfigured("Database schema not set. Did you forget "
"to call set_schema() or set_tenant()?")

search_paths = self._get_cursor_search_paths()

self._setting_search_path = True
cursor_for_search_path = self.connection.cursor() if cursor is None else cursor

# In the event that an error already happened in this transaction and we are going
# to rollback we should just ignore database error when setting the search_path
# if the next instruction is not a rollback it will just fail also, so
# we do not have to worry that it's not the good one
try:
cursor_for_search_path.execute(
sql.SQL('SET search_path = {0}').format(
sql.SQL(', ').join(
quote_schema_name(name) for name in search_paths
)
)
except (django.db.utils.DatabaseError, psycopg.InternalError):
self.search_path_set_schemas = None
else:
self.search_path_set_schemas = search_paths
cursor_for_search_path.close()
return cursor
)
except (django.db.utils.DatabaseError, psycopg.InternalError):
self.search_path_set_schemas = None
else:
self.search_path_set_schemas = search_paths
finally:
self._setting_search_path = False
if cursor is None:
cursor_for_search_path.close()

def _get_cursor_search_paths(self):
_check_schema_name(self.schema_name)
public_schema_name = get_public_schema_name()

if self.schema_name == public_schema_name:
Expand All @@ -190,6 +227,11 @@ def _get_cursor_search_paths(self):

search_paths.extend(EXTRA_SEARCH_PATHS)

# Every part is interpolated into the SET statement, so validate all of
# them -- not just self.schema_name -- including PG_EXTRA_SEARCH_PATHS.
for search_path in search_paths:
_check_schema_name(search_path)

return search_paths


Expand Down
27 changes: 17 additions & 10 deletions django_tenants/tests/test_tenants.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,20 +194,23 @@ def test_switching_search_path(self):
DummyModel(name="Schemas are").save()
DummyModel(name="awesome!").save()

# switch temporarily to tenant2's path
with self.assertNumQueries(3):
# switch temporarily to tenant2's path.
# TENANT_LIMIT_SET_CALLS is off, so each of the 3 inserts is preceded by its
# own `SET search_path` -- 6 statements, not 3. The SET was always issued;
# it is now run on the caller's cursor on every driver, so it is counted.
with self.assertNumQueries(6):
with tenant_context(tenant2):
# add some data, 3 DummyModels for tenant2
DummyModel(name="Man,").save()
DummyModel(name="testing").save()
DummyModel(name="is great!").save()

# we should be back to tenant1's path, test what we have
with self.assertNumQueries(1):
# we should be back to tenant1's path, test what we have (SET + COUNT)
with self.assertNumQueries(2):
self.assertEqual(2, DummyModel.objects.count())

# switch back to tenant2's path
with self.assertNumQueries(1):
# switch back to tenant2's path (SET + COUNT)
with self.assertNumQueries(2):
with tenant_context(tenant2):
self.assertEqual(3, DummyModel.objects.count())

Expand All @@ -233,8 +236,10 @@ def test_switching_search_path_limited_calls(self):
with self.assertNumQueries(0):
connection.set_tenant(tenant1)

# switch temporarily to tenant2's path
with self.assertNumQueries(3):
# switch temporarily to tenant2's path.
# TENANT_LIMIT_SET_CALLS is on, so the SET runs once for the first cursor
# after set_tenant cleared the cache, then the 3 inserts: 4 statements.
with self.assertNumQueries(4):
with tenant_context(tenant2):
DummyModel(name="Man,").save()
DummyModel(name="testing").save()
Expand All @@ -244,14 +249,16 @@ def test_switching_search_path_limited_calls(self):
with self.assertNumQueries(0):
connection.set_tenant(tenant1)

with self.assertNumQueries(1):
# set_tenant cleared the cache, so this re-issues the SET (SET + COUNT)
with self.assertNumQueries(2):
self.assertEqual(0, DummyModel.objects.count())

# 0 queries as search path not set here
with self.assertNumQueries(0):
connection.set_tenant(tenant2)

with self.assertNumQueries(1):
# as above: SET + COUNT
with self.assertNumQueries(2):
self.assertEqual(3, DummyModel.objects.count())

self.created = [domain2, domain1, tenant2, tenant1]
Expand Down