Spaces:
Sleeping

studiq-backend / scripts /cleanup_db.py
StudIQ Deploy Bot
Deploy from GitHub ff5763204b7b0701f17c2727db612c59ce660cce
da24374
Raw History Blame Contribute Delete
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())