diff --git a/tests/conftest.py b/tests/conftest.py index 9867720..cc5b7a5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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(