File size: 4,830 Bytes
c82da72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sqlite3
from datetime import datetime
import os
import time
from contextlib import contextmanager

class Database:
    def __init__(self, db_name="requests.db"):
        self.db_name = db_name
        self.max_retries = 3
        self.retry_delay = 1
        self.initialize_database()
    
    @contextmanager
    def get_connection(self):
        """Create a new connection for each operation"""
        conn = sqlite3.connect(self.db_name)
        try:
            yield conn
        finally:
            conn.close()
    
    def initialize_database(self):
        """Initialize the database and create tables"""
        for attempt in range(self.max_retries):
            try:
                with self.get_connection() as conn:
                    conn.execute('PRAGMA encoding="UTF-8"')
                    cursor = conn.cursor()
                    
                    # Check if table exists
                    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='requests'")
                    if not cursor.fetchone():
                        self.create_table(conn)
                    else:
                        # Verify columns
                        cursor.execute('PRAGMA table_info(requests)')
                        columns = [col[1] for col in cursor.fetchall()]
                        required_columns = ['id', 'timestamp', 'project_number', 'project_name', 'amount', 'reason', 'original_text']
                        
                        if not all(col in columns for col in required_columns):
                            # Backup existing data
                            cursor.execute('ALTER TABLE requests RENAME TO requests_old')
                            self.create_table(conn)
                            # Copy data from old table
                            cursor.execute('''
                                INSERT INTO requests (timestamp, project_number, project_name, amount, reason)
                                SELECT timestamp, project_number, project_name, amount, reason
                                FROM requests_old
                            ''')
                            cursor.execute('DROP TABLE requests_old')
                            conn.commit()
                return
            except sqlite3.OperationalError as e:
                if attempt < self.max_retries - 1:
                    time.sleep(self.retry_delay)
                    continue
                raise Exception(f"Could not initialize database after {self.max_retries} attempts: {str(e)}")
    
    def create_table(self, conn):
        """Create the requests table"""
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS requests (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp DATETIME,
                project_number TEXT,
                project_name TEXT,
                amount REAL,
                reason TEXT,
                original_text TEXT
            )
        ''')
        conn.commit()
    
    def add_request(self, project_number, project_name, amount, reason, original_text=""):
        """Add a new request to the database"""
        for attempt in range(self.max_retries):
            try:
                with self.get_connection() as conn:
                    cursor = conn.cursor()
                    cursor.execute('''
                        INSERT INTO requests (timestamp, project_number, project_name, amount, reason, original_text)
                        VALUES (?, ?, ?, ?, ?, ?)
                    ''', (datetime.now(), project_number, project_name, amount, reason, original_text))
                    conn.commit()
                return
            except sqlite3.OperationalError as e:
                if attempt < self.max_retries - 1:
                    time.sleep(self.retry_delay)
                    continue
                raise Exception(f"Could not add request after {self.max_retries} attempts: {str(e)}")
    
    def get_all_requests(self):
        """Get all requests from the database"""
        for attempt in range(self.max_retries):
            try:
                with self.get_connection() as conn:
                    cursor = conn.cursor()
                    cursor.execute('SELECT * FROM requests ORDER BY timestamp DESC')
                    columns = [description[0] for description in cursor.description]
                    results = cursor.fetchall()
                    return [dict(zip(columns, row)) for row in results]
            except sqlite3.OperationalError as e:
                if attempt < self.max_retries - 1:
                    time.sleep(self.retry_delay)
                    continue
                raise Exception(f"Could not fetch requests after {self.max_retries} attempts: {str(e)}")