Spaces:
Sleeping

studiq-backend / scripts /clean_all_data.py
baljot07's picture
fix: deploy latest backend with updated alembic migrations and connection resilience
aec5479
Raw History Blame Contribute Delete
3.22 kB
"""Clean all collected user data, conversations, progress, chunks, and sessions from Supabase.
Preserves database schema and migrations (alembic_version) so the system is ready for fresh data.
"""
import asyncio
import os
from pathlib import Path
import asyncpg
from dotenv import load_dotenv
# Load backend .env
env_path = Path(__file__).parent.parent / ".env"
load_dotenv(env_path)
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
raise RuntimeError("DATABASE_URL not found in .env")
# Convert SQLAlchemy URL to raw asyncpg URL if necessary
if DATABASE_URL.startswith("postgresql+asyncpg://"):
DATABASE_URL = DATABASE_URL.replace("postgresql+asyncpg://", "postgresql://", 1)
TABLES_TO_CLEAN = [
"otp_sessions",
"messages",
"conversations",
"daily_memories",
"study_plans",
"user_generations",
"user_progress",
"flashcard_items",
"flashcard_decks",
"study_notes",
"subject_attendance",
"user_documents",
"users",
]
async def clean_supabase_data():
print("=" * 60)
print("🧹 Cleaning Supabase Database...")
print("=" * 60)
conn = await asyncpg.connect(DATABASE_URL)
try:
# Check existing row counts before wipe
print("Pre-cleanup row counts:")
for table in TABLES_TO_CLEAN:
try:
cnt = await conn.fetchval(f"SELECT COUNT(*) FROM {table}")
print(f" - {table}: {cnt} rows")
except Exception as e:
print(f" - {table}: table missing or error ({e})")
print("\nTruncating tables...")
# Use CASCADE to cleanly handle all foreign key constraints
table_list = ", ".join(f'"{t}"' for t in TABLES_TO_CLEAN)
await conn.execute(f"TRUNCATE TABLE {table_list} CASCADE;")
print("✅ TRUNCATE CASCADE executed successfully.")
print("\nPost-cleanup verification:")
all_zero = True
for table in TABLES_TO_CLEAN:
try:
cnt = await conn.fetchval(f"SELECT COUNT(*) FROM {table}")
print(f" - {table}: {cnt} rows")
if cnt != 0:
all_zero = False
except Exception as e:
print(f" - {table}: error ({e})")
if all_zero:
print("\n🎉 ALL USER & APPLICATION DATA IN SUPABASE HAS BEEN WIPED CLEAN (0 ROWS)!")
else:
print("\n⚠️ Some rows remain, please check foreign key constraints.")
finally:
await conn.close()
def clean_local_db_files():
print("\n" + "=" * 60)
print("🧹 Cleaning local test/demo database files...")
print("=" * 60)
backend_dir = Path(__file__).parent.parent
root_dir = backend_dir.parent
files_to_remove = [
backend_dir / "test.db",
backend_dir / "demo.db",
root_dir / "test.db",
]
for f in files_to_remove:
if f.exists():
f.unlink()
print(f" - Deleted {f}")
else:
print(f" - Not present: {f.name}")
print("✅ Local database files cleaned.")
async def main():
await clean_supabase_data()
clean_local_db_files()
if __name__ == "__main__":
asyncio.run(main())