wip: punkt 2 (test-DB) — conftest.py optimized (skip DROP SCHEMA if tables exist, exclude alembic_version from TRUNCATE, 30s lock_timeout), deadlock issue with clean_tables fixture identified

This commit is contained in:
Agent Zero
2026-08-20 12:15:25 +02:00
parent f1040c1749
commit 5c62f49e6d
+16 -1
View File
@@ -113,8 +113,24 @@ def db_setup():
Uses SET lock_timeout to prevent deadlocks when multiple test processes
try to DROP SCHEMA simultaneously. Falls back to TRUNCATE if DROP fails.
"""
# Check if tables already exist — skip DROP/CREATE if they do
sync_eng = _get_sync_engine()
with sync_eng.connect() as conn:
result = conn.execute(text("SELECT count(*) FROM pg_tables WHERE schemaname='public';"))
table_count = result.scalar()
if table_count and table_count > 10:
# Tables already exist — just TRUNCATE (exclude alembic_version)
conn.execute(text("SET lock_timeout = '30s';"))
conn.execute(text(
"DO $$ DECLARE r RECORD; BEGIN "
"FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname='public' AND tablename != 'alembic_version') "
"LOOP EXECUTE 'TRUNCATE TABLE public.' || quote_ident(r.tablename) || ' CASCADE'; "
"END LOOP; END $$;"
))
conn.commit()
sync_eng.dispose()
yield
return
# Create crm_user role if missing (needed by some migrations)
conn.execute(text("DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'crm_user') THEN CREATE ROLE crm_user LOGIN PASSWORD 'leocrm'; END IF; END $$;"))
# Set a short lock timeout to prevent deadlocks
@@ -124,7 +140,6 @@ def db_setup():
conn.execute(text("CREATE SCHEMA public;"))
conn.execute(text("GRANT ALL ON SCHEMA public TO leocrm;"))
except Exception:
# If DROP SCHEMA deadlocks, fall back to TRUNCATE all tables
conn.rollback()
conn.execute(text("SET lock_timeout = '5s';"))
conn.execute(text(