Spaces:
Sleeping
Sleeping
Download scripts/cleanup_db.py from baljot07/studiq-backend: direct link, hf CLI and curl.
- Browser
- Download file 4.79 kB
-
https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/scripts/cleanup_db.py
- Command line
-
hf download hf://spaces/baljot07/studiq-backend/scripts/cleanup_db.py
-
curl -L -o cleanup_db.py https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/scripts/cleanup_db.py
4.79 kB
| import asyncio | |
| import os | |
| import sys | |
| from sqlalchemy.ext.asyncio import create_async_engine | |
| from sqlalchemy import text | |
| # Add parent dir to path | |
| sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from app.config import settings | |
| async def cleanup_database(db_url: str): | |
| print(f"Connecting to database: {db_url.split('@')[-1] if '@' in db_url else db_url}") | |
| # Ensure connection string uses asyncpg | |
| if db_url.startswith("postgresql://"): | |
| db_url = db_url.replace("postgresql://", "postgresql+asyncpg://", 1) | |
| engine = create_async_engine(db_url) | |
| async with engine.connect() as conn: | |
| # 1. Find the target user to keep: chohanjatt07@gmail.com | |
| user_res = await conn.execute( | |
| text("SELECT id FROM users WHERE LOWER(email) = 'chohanjatt07@gmail.com'") | |
| ) | |
| user_row = user_res.first() | |
| if not user_row: | |
| print("WARNING: User chohanjatt07@gmail.com not found in DB! We will keep RAG chunks but all users might be deleted if not carefully handled.") | |
| keep_user_id = None | |
| else: | |
| keep_user_id = user_row[0] | |
| print(f"Found user to keep: chohanjatt07@gmail.com (ID: {keep_user_id})") | |
| print("Starting data cleanup...") | |
| # 2. Delete non-essential tables for ALL users | |
| tables_to_clear = [ | |
| "messages", | |
| "conversations", | |
| "study_plans", | |
| "user_progress", | |
| "daily_memories", | |
| "user_documents" | |
| ] | |
| for table in tables_to_clear: | |
| try: | |
| res = await conn.execute(text(f"DELETE FROM {table}")) | |
| print(f" - Deleted all rows from table '{table}' ({res.rowcount} rows affected)") | |
| except Exception as e: | |
| print(f" - Error clearing table '{table}': {e}") | |
| # 3. Delete other users (if we have a user to keep) | |
| if keep_user_id: | |
| try: | |
| # Delete RAG chunks not belonging to the kept user | |
| res_rag = await conn.execute( | |
| text("DELETE FROM rag_chunks WHERE user_id != :uid"), | |
| {"uid": keep_user_id} | |
| ) | |
| print(f" - Deleted RAG chunks of other users ({res_rag.rowcount} rows affected)") | |
| # Delete other users | |
| res_users = await conn.execute( | |
| text("DELETE FROM users WHERE id != :uid"), | |
| {"uid": keep_user_id} | |
| ) | |
| print(f" - Deleted other users ({res_users.rowcount} rows affected)") | |
| # 4. Reset profile fields for the kept user | |
| await conn.execute( | |
| text(""" | |
| UPDATE users | |
| SET university_name = NULL, | |
| course = NULL, | |
| semester = NULL, | |
| has_syllabus = FALSE, | |
| syllabus_data = NULL, | |
| onboarding_complete = FALSE, | |
| bio = NULL, | |
| daily_message_count = 0, | |
| tokens_consumed = 0, | |
| total_messages_sent = 0, | |
| streak_days = 0, | |
| user_facts = NULL, | |
| updated_at = NOW() | |
| WHERE id = :uid | |
| """), | |
| {"uid": keep_user_id} | |
| ) | |
| print(" - Reset profile fields for chohanjatt07@gmail.com to start fresh.") | |
| except Exception as e: | |
| print(f" - Error during user deletion/reset: {e}") | |
| else: | |
| # If no user found, just clear all users (RAG chunks will cascade delete if user_id is foreign key) | |
| try: | |
| res_users = await conn.execute(text("DELETE FROM users")) | |
| print(f" - Deleted all users ({res_users.rowcount} rows affected)") | |
| except Exception as e: | |
| print(f" - Error clearing users table: {e}") | |
| await conn.commit() | |
| print("Database cleanup committed successfully!") | |
| await engine.dispose() | |
| async def main(): | |
| # Local cleanup | |
| print("=== Running Local DB Cleanup ===") | |
| await cleanup_database(settings.database_url) | |
| # Prod cleanup (using Supabase URI) | |
| print("\n=== Running Production DB Cleanup ===") | |
| PROD_DB_URL = "postgresql+asyncpg://postgres.gpzngqnvcmosomlbpwgt:vykruh-4mybwu-patXef@aws-1-ap-northeast-1.pooler.supabase.com:5432/postgres" | |
| await cleanup_database(PROD_DB_URL) | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |