Spaces:
Sleeping
Sleeping
File size: 3,224 Bytes
aec5479 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | """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())
|