From 5d6a9b9979b3376a8fdf10c5d5e97acf8ebdc162 Mon Sep 17 00:00:00 2001 From: Tom Turner Date: Wed, 5 Aug 2026 13:21:51 +0100 Subject: [PATCH 1/2] Make search_path handling driver-agnostic Fixes #1244. `_cursor()` special-cased psycopg3, never reusing the caller's cursor for `SET search_path` in order to avoid the recursion 340f137 describes. Opening a raw `self.connection.cursor()` instead meant the statement bypassed Django's cursor wrapper -- so on psycopg3 it was invisible to assertNumQueries while on psycopg2 it was counted. That is why test_switching_search_path failed on psycopg2: the assertions had been written against psycopg3's accounting rather than the actual behaviour. Following the approach django-pgschemas takes, a `_setting_search_path` flag makes the re-entry a no-op instead of recursing, so the caller's cursor can be reused on both drivers and the statement is visible on both. The SET logic moves out of `_cursor()` into `_handle_search_path()`, which now branches only on whether a cursor was supplied -- never on the driver. This changes no database traffic. With `log_statement='all'`, master and this branch both send exactly 646 `SET search_path` statements for the same test; only their visibility to the cursor wrapper differs. The updated counts in test_switching_search_path{,_limited_calls} therefore make those assertions more accurate rather than looser -- they now count statements that were always executed. Also included, both from the same comparison: - `rollback()` clears the cached search_path. A session-level `SET` is transactional in PostgreSQL, so aborting the transaction that issued it reverts the search_path; with TENANT_LIMIT_SET_CALLS on, the cache could otherwise outlive a value the database had already discarded. - `_get_cursor_search_paths()` validates every part of the search path rather than only `self.schema_name`, which brings PG_EXTRA_SEARCH_PATHS under the same check before it is interpolated into the SET statement. CI gains a `psycopg-version` axis so the psycopg2 fallback is actually exercised. Verified with ./run_tests.sh -- both executors plus the create_tenant and clone_tenant integration steps -- on Python 3.12 / PostgreSQL 17: Dj 5.2.17 psycopg3 exit 0 | 130 tests | exec 2/2 | FAIL 0 | clone 1 Dj 5.2.17 psycopg2 exit 0 | 130 tests | exec 2/2 | FAIL 0 | clone 1 Dj 6.0.8 psycopg3 exit 0 | 130 tests | exec 2/2 | FAIL 0 | clone 1 Dj 6.0.8 psycopg2 exit 0 | 130 tests | exec 2/2 | FAIL 0 | clone 1 Dj 6.1rc1 psycopg3 exit 0 | 130 tests | exec 2/2 | FAIL 0 | clone 1 Dj 6.1rc1 psycopg2 exit 0 | 130 tests | exec 2/2 | FAIL 0 | clone 1 An earlier revision of this branch also failed on Django 4.2 + psycopg3 with `9 != 6`, because Django's own compose_sql/mogrify opened a second cursor per statement there and each one triggered a SET. Dropping 4.2 in #1248 removed that case, so no version-conditional assertion is needed. Co-Authored-By: Claude Opus 5 (1M context) --- django_tenants/postgresql_backend/base.py | 103 +++++++++++++++------- django_tenants/tests/test_tenants.py | 27 +++--- 2 files changed, 87 insertions(+), 43 deletions(-) diff --git a/django_tenants/postgresql_backend/base.py b/django_tenants/postgresql_backend/base.py index a38b7fac..05f3522e 100644 --- a/django_tenants/postgresql_backend/base.py +++ b/django_tenants/postgresql_backend/base.py @@ -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 @@ -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) @@ -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, @@ -142,43 +157,60 @@ 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 - ) - ) - ) - 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 + 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: + formatted_search_paths = ['\'{}\''.format(s) for s in search_paths] + cursor_for_search_path.execute('SET search_path = {0}'.format(','.join(formatted_search_paths))) + 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: @@ -190,6 +222,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 diff --git a/django_tenants/tests/test_tenants.py b/django_tenants/tests/test_tenants.py index bc084971..3d6494e6 100644 --- a/django_tenants/tests/test_tenants.py +++ b/django_tenants/tests/test_tenants.py @@ -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()) @@ -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() @@ -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] From 8b066726e8775b974b5f6e33610574df679cf593 Mon Sep 17 00:00:00 2001 From: Alexander Todorov Date: Mon, 23 Nov 2026 17:26:58 +0000 Subject: [PATCH 2/2] Keep the fork's identifier composition for SET search_path Upstream e933df4 still builds the SET statement with string interpolation. The fork quotes each schema name with quote_schema_name() and composes the statement with psycopg's sql module, so keep that here instead of regressing the 4.0.3 escaping fix. No change in behaviour for valid schema names. --- django_tenants/postgresql_backend/base.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/django_tenants/postgresql_backend/base.py b/django_tenants/postgresql_backend/base.py index 05f3522e..93fcd73d 100644 --- a/django_tenants/postgresql_backend/base.py +++ b/django_tenants/postgresql_backend/base.py @@ -199,8 +199,13 @@ def _handle_search_path(self, cursor=None): # 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: - formatted_search_paths = ['\'{}\''.format(s) for s in search_paths] - cursor_for_search_path.execute('SET search_path = {0}'.format(','.join(formatted_search_paths))) + 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: