import sqlite3 def create_database(): """ Connects to the SQLite database and creates the 'clients' and 'time_tracking' tables if they do not already exist. """ db_file = 'time_tracker.db' # Define the database file name conn = None # Initialize the connection variable to None try: # Connect to the database. This will create the file if it doesn't exist. conn = sqlite3.connect(db_file) cursor = conn.cursor() # Create the 'clients' table. The 'address' field has been split into # separate fields for better data organization. cursor.execute(''' CREATE TABLE IF NOT EXISTS clients ( client_id INTEGER PRIMARY KEY, client_name TEXT NOT NULL UNIQUE, street_address_1 TEXT, street_address_2 TEXT, city TEXT, state TEXT, zip_code TEXT, billing_rate REAL, balance REAL, active INTEGER NOT NULL DEFAULT 1 ); ''') # Create the 'time_tracking' table with new fields for date and hours. # The 'invoiced' field is an INTEGER where 0 is false and 1 is true. # The 'client_id' is a foreign key that references the 'clients' table. cursor.execute(''' CREATE TABLE IF NOT EXISTS time_tracking ( entry_id INTEGER PRIMARY KEY, project TEXT NOT NULL, description TEXT, invoiced INTEGER NOT NULL DEFAULT 0 CHECK(invoiced IN (0, 1)), date TEXT NOT NULL, hours REAL NOT NULL, client_id INTEGER, FOREIGN KEY (client_id) REFERENCES clients (client_id) ); ''') # Commit the changes to the database. conn.commit() print(f"Successfully created tables 'clients' and 'time_tracking' in '{db_file}'") except sqlite3.Error as e: # Print an error message if something goes wrong. print(f"An error occurred: {e}") finally: # Ensure the database connection is always closed, even if an error occurs. if conn: conn.close() print("Database connection closed.") if __name__ == "__main__": # Call the function to create the database when the script is run directly. create_database()