Spender / clear_prod_data.py
EliramShemesh's picture
ci: deploy backend from 8203f3c92ab51cd68871e27aefbdf0f1d018dfb1
9b64783 verified
Raw History Blame Contribute Delete
7.05 kB
#!/usr/bin/env python3
"""
Clear all transaction data from production database.
Run this script to start fresh while keeping categories, subcategories,
payment methods, and users intact.
Usage:
python clear_prod_data.py
Requirements:
pip install psycopg2-binary python-dotenv
"""
import os
import sys
# Check dependencies
try:
import psycopg2
from dotenv import load_dotenv
except ImportError as e:
print("="*60)
print("MISSING DEPENDENCIES")
print("="*60)
print(f"\nError: {e}")
print("\nPlease install required packages:")
print(" pip install psycopg2-binary python-dotenv")
print("\nOr activate your virtual environment:")
print(" source .venv/bin/activate # macOS/Linux")
print(" .venv\\Scripts\\activate # Windows")
print("="*60)
sys.exit(1)
# Load environment variables from .env.remote (production)
env_path = os.path.join(os.path.dirname(__file__), ".env.remote")
if os.path.exists(env_path):
load_dotenv(env_path)
print(f"Loaded environment from {env_path}")
else:
load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))
print("Loaded environment from .env")
database_url = os.getenv("DATABASE_URL")
if not database_url:
print("ERROR: DATABASE_URL not set")
sys.exit(1)
def parse_db_url(url):
"""Parse PostgreSQL URL into connection parameters."""
# Handle postgres:// and postgresql://
url = url.replace("postgres://", "postgresql://", 1)
# Remove postgresql:// prefix
url = url.replace("postgresql://", "")
# Split user:password@host:port/dbname
if "@" in url:
creds, host_part = url.split("@", 1)
user, password = creds.split(":", 1) if ":" in creds else (creds, "")
else:
user, password = "", ""
host_part = url
# Split host:port/dbname
if "/" in host_part:
host_port, dbname = host_part.split("/", 1)
# Remove query params from dbname
if "?" in dbname:
dbname = dbname.split("?")[0]
else:
host_port = host_part
dbname = "postgres"
if ":" in host_port:
host, port = host_port.rsplit(":", 1)
port = int(port)
else:
host = host_port
port = 5432
return {
"host": host,
"port": port,
"dbname": dbname,
"user": user,
"password": password
}
print(f"\nConnecting to database...")
conn_params = parse_db_url(database_url)
print(f"Host: {conn_params['host']}")
print(f"Database: {conn_params['dbname']}\n")
def clear_data():
"""Clear all transaction data from the database."""
conn = None
try:
conn = psycopg2.connect(**conn_params)
conn.autocommit = False # Use explicit transactions
cur = conn.cursor()
# Get counts before deletion
cur.execute("SELECT COUNT(*) FROM transaction")
tx_count = cur.fetchone()[0]
print(f"Found {tx_count} transactions to delete")
# Show sample transactions
if tx_count > 0:
cur.execute("SELECT id, amount, notes, date FROM transaction ORDER BY date DESC LIMIT 3")
rows = cur.fetchall()
print("\nSample transactions:")
for r in rows:
notes = r[2][:30] + "..." if r[2] and len(r[2]) > 30 else (r[2] or "(no notes)")
print(f" ID:{r[0]} ₪{r[1]} - {notes} - {r[3]}")
if tx_count == 0:
print("\nNo transactions found. Database is already clean.")
conn.commit()
return
# Ask for confirmation
print("\n" + "="*50)
print("WARNING: This will PERMANENTLY DELETE all transactions!")
print("Categories, subcategories, payment methods, and users")
print("will be preserved.")
print("="*50)
confirm = input("\nType 'DELETE' to confirm: ")
if confirm != "DELETE":
print("\nAborted. No data was deleted.")
conn.rollback()
return
# Delete transactions with verification loop
max_attempts = 3
total_deleted = 0
for attempt in range(max_attempts):
print(f"\nDeleting transactions (attempt {attempt + 1}/{max_attempts})...")
cur.execute("DELETE FROM transaction")
deleted = cur.rowcount
total_deleted += deleted
conn.commit()
# Verify deletion
cur.execute("SELECT COUNT(*) FROM transaction")
remaining = cur.fetchone()[0]
print(f" Deleted: {deleted}, Remaining: {remaining}")
if remaining == 0:
break
elif attempt < max_attempts - 1:
print(f" ⚠ New transaction appeared! Retrying...")
# Optionally clear budget history (skip if table doesn't exist)
try:
cur.execute("SELECT COUNT(*) FROM budget_history")
history_count = cur.fetchone()[0]
if history_count > 0:
print(f"\nFound {history_count} budget history records")
confirm_history = input("Delete budget history too? (yes/no): ")
if confirm_history.lower() == "yes":
cur.execute("DELETE FROM budget_history")
conn.commit()
print("Budget history cleared.")
except psycopg2.errors.UndefinedTable:
conn.rollback() # Reset transaction after error
print("(budget_history table not found - skipping)")
# Final verification
cur.execute("SELECT COUNT(*) FROM transaction")
final_count = cur.fetchone()[0]
print("\n" + "="*50)
if final_count == 0:
print(f"✓ SUCCESS: Deleted {total_deleted} transactions!")
print("="*50)
print("\nThe following data has been preserved:")
print(" - Categories")
print(" - SubCategories")
print(" - Payment Methods")
print(" - Users")
print("\n⚠ IMPORTANT: Close all browser tabs with the app open")
print(" before refreshing, or the data may re-sync.")
else:
print(f"⚠ WARNING: {final_count} transactions still remain!")
print("="*50)
print("\nPossible causes:")
print(" - An open browser/app is re-adding data")
print(" - Multiple users are adding transactions")
print("\nClose all app instances and run again.")
except psycopg2.Error as e:
if conn:
conn.rollback()
print(f"\nDatabase Error: {e}")
sys.exit(1)
except Exception as e:
if conn:
conn.rollback()
print(f"\nERROR: {e}")
sys.exit(1)
finally:
if conn:
conn.close()
print("\nDatabase connection closed.")
if __name__ == "__main__":
clear_data()