File size: 3,501 Bytes
9b64783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)