@@ -45,7 +45,7 @@ def _build_worker_url(original_url: str, schema_name: str) -> str:
4545
4646
4747@pytest .fixture (scope = "session" )
48- def worker_sql_connection () -> Optional [str ]:
48+ def worker_sql_connection (request : pytest . FixtureRequest ) -> Optional [str ]:
4949 """Create the worker-specific PostgreSQL schema once per xdist worker session.
5050
5151 Returns the worker-specific connection URL, or None when schema isolation is not
@@ -58,6 +58,11 @@ def worker_sql_connection() -> Optional[str]:
5858 that depend on the schema will fail at the DB level with a diagnostic error.
5959
6060 """
61+ # Avoid touching SQL backends entirely when no SQL tests are collected.
62+ has_sql_tests = any ("sql" in item .keywords for item in request .session .items )
63+ if not has_sql_tests :
64+ return None
65+
6166 worker_id = os .environ .get ("PYTEST_XDIST_WORKER" , "master" )
6267 if worker_id == "master" :
6368 return None
@@ -73,16 +78,19 @@ def worker_sql_connection() -> Optional[str]:
7378
7479 new_url = _build_worker_url (original_url , schema_name )
7580
81+ engine = None
7682 try :
7783 from sqlalchemy import create_engine , text
7884
7985 engine = create_engine (original_url )
8086 with engine .connect () as conn :
8187 conn .execute (text (f"CREATE SCHEMA IF NOT EXISTS { schema_name } " ))
8288 conn .commit ()
83- engine .dispose ()
8489 except Exception as e :
8590 logger .debug ("Failed to create schema %s: %s" , schema_name , e )
91+ finally :
92+ if engine is not None :
93+ engine .dispose ()
8694
8795 return new_url
8896
0 commit comments