ZennyKenny commited on
Commit
716c2a2
ยท
verified ยท
1 Parent(s): 026bf2e

presist database

Browse files
Files changed (1) hide show
  1. database.py +16 -14
database.py CHANGED
@@ -9,8 +9,8 @@ from sqlalchemy import (
9
  insert,
10
  )
11
 
12
- # Initialize in-memory SQLite database
13
- engine = create_engine("sqlite:///:memory:")
14
  metadata_obj = MetaData()
15
 
16
  # Define 'receipts' table
@@ -18,12 +18,12 @@ receipts = Table(
18
  "receipts",
19
  metadata_obj,
20
  Column("receipt_id", Integer, primary_key=True),
21
- Column("customer_name", String(16), primary_key=True),
22
  Column("price", Float),
23
  Column("tip", Float),
24
  )
25
 
26
- # Create the table
27
  metadata_obj.create_all(engine)
28
 
29
  # Function to insert rows into the table
@@ -31,13 +31,15 @@ def insert_rows_into_table(rows, table):
31
  with engine.begin() as connection:
32
  connection.execute(insert(table), rows)
33
 
34
- # Insert sample data
35
- rows = [
36
- {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
37
- {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
38
- {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
39
- {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
40
- ]
41
-
42
- # Populate the database
43
- insert_rows_into_table(rows, receipts)
 
 
 
9
  insert,
10
  )
11
 
12
+ # Use a persistent SQLite database file
13
+ engine = create_engine("sqlite:///database.db")
14
  metadata_obj = MetaData()
15
 
16
  # Define 'receipts' table
 
18
  "receipts",
19
  metadata_obj,
20
  Column("receipt_id", Integer, primary_key=True),
21
+ Column("customer_name", String(16)),
22
  Column("price", Float),
23
  Column("tip", Float),
24
  )
25
 
26
+ # Create the table if it doesn't exist
27
  metadata_obj.create_all(engine)
28
 
29
  # Function to insert rows into the table
 
31
  with engine.begin() as connection:
32
  connection.execute(insert(table), rows)
33
 
34
+ # Insert sample data if table is empty
35
+ with engine.connect() as conn:
36
+ result = conn.execute(text("SELECT COUNT(*) FROM receipts"))
37
+ count = result.scalar()
38
+ if count == 0:
39
+ rows = [
40
+ {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
41
+ {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
42
+ {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
43
+ {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
44
+ ]
45
+ insert_rows_into_table(rows, receipts)