Spender / clear_local_data.py
EliramShemesh's picture
ci: deploy backend from 8203f3c92ab51cd68871e27aefbdf0f1d018dfb1
9b64783 verified
Raw History Blame Contribute Delete
3.5 kB
#!/usr/bin/env python3
"""
Clear all transaction data from local SQLite database.
Run this script to start fresh on local development.
Usage:
python clear_local_data.py
Requirements:
pip install sqlalchemy
"""
import os
import sys
from pathlib import Path
# Check dependencies
try:
from sqlalchemy import create_engine, text
except ImportError as e:
print("="*60)
print("MISSING DEPENDENCIES")
print("="*60)
print(f"\nError: {e}")
print("\nPlease install required package:")
print(" pip install sqlalchemy")
print("\nOr activate your virtual environment:")
print(" source .venv/bin/activate # macOS/Linux")
print(" .venv\\Scripts\\activate # Windows")
print("="*60)
sys.exit(1)
# Local SQLite database path
db_path = Path(__file__).parent / "database.db"
if not db_path.exists():
print(f"Local database not found at: {db_path}")
print("Nothing to clear.")
sys.exit(0)
print(f"Local database: {db_path}")
print(f"Connecting to SQLite...\n")
engine = create_engine(f"sqlite:///{db_path}", connect_args={"check_same_thread": False})
def clear_data():
"""Clear all transaction data from the local database."""
with engine.begin() as conn:
# Get counts before deletion
result = conn.execute(text('SELECT COUNT(*) FROM "transaction"'))
tx_count = result.scalar()
print(f"Found {tx_count} transactions to delete")
if tx_count == 0:
print("\nNo transactions found. Database is already clean.")
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.")
return
# Delete transactions
print("\nDeleting transactions...")
result = conn.execute(text('DELETE FROM "transaction"'))
deleted = result.rowcount
# Optionally clear budget history (skip if table doesn't exist)
try:
result = conn.execute(text('SELECT COUNT(*) FROM "budget_history"'))
history_count = result.scalar()
if history_count > 0:
print(f"Found {history_count} budget history records")
confirm_history = input("Delete budget history too? (yes/no): ")
if confirm_history.lower() == "yes":
conn.execute(text('DELETE FROM "budget_history"'))
print("Budget history cleared.")
except Exception as e:
if "budget_history" in str(e).lower():
print("(budget_history table not found - skipping)")
else:
raise
print("\n" + "="*50)
print(f"✓ SUCCESS: Deleted {deleted} transactions!")
print("="*50)
print("\nThe following data has been preserved:")
print(" - Categories")
print(" - SubCategories")
print(" - Payment Methods")
print(" - Users")
print("\nYou can now start fresh with empty transaction history.")
if __name__ == "__main__":
try:
clear_data()
except Exception as e:
print(f"\nERROR: {e}")
sys.exit(1)