forked from TheRonzor/DATA302_StoreDBCodeExamples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.py
131 lines (110 loc) · 3.29 KB
/
store.py
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import sqlite3
import pandas as pd
from traceback import print_exc as pe
def Connect():
conn = sqlite3.connect('../databases/store.db')
curs = conn.cursor()
curs.execute("PRAGMA foreign_keys=ON;")
return conn, curs
def RunAction(sql, params=None):
conn, curs = Connect()
if params is not None:
curs.execute(sql, params)
else:
curs.execute(sql)
conn.close()
return
def RunQuery(sql, params=None):
conn, curs = Connect()
if params is not None:
results = pd.read_sql(sql, conn, params=params)
else:
results = pd.read_sql(sql, conn)
conn.close()
return results
def RebuildTables():
RunAction("DROP TABLE IF EXISTS tOrderDetail;")
RunAction("DROP TABLE IF EXISTS tOrder;")
RunAction("DROP TABLE IF EXISTS tCust;")
RunAction("DROP TABLE IF EXISTS tZip;")
RunAction("DROP TABLE IF EXISTS tState;")
RunAction("DROP TABLE IF EXISTS tProd;")
sql = """
CREATE TABLE tCust (
cust_id INTEGER PRIMARY KEY AUTOINCREMENT,
first TEXT NOT NULL,
last TEXT NOT NULL,
address TEXT NOT NULL,
zip TEXT NOT NULL REFERENCES tZip(zip)
);"""
RunAction(sql)
sql = """
CREATE TABLE tZip (
zip TEXT PRIMARY KEY CHECK(length(zip)==5),
city TEXT NOT NULL,
st TEXT NOT NULL REFERENCES tState(st)
);"""
RunAction(sql)
sql = """
CREATE TABLE tState (
st TEXT PRIMARY KEY CHECK(length(st)==2),
state TEXT NOT NULL
);"""
RunAction(sql)
sql = """
CREATE TABLE tOrder (
order_id INTEGER PRIMARY KEY AUTOINCREMENT,
cust_id INTEGER NOT NULL REFERENCES tCust(cust_id),
date TEXT NOT NULL CHECK(date LIKE '____-__-__')
);"""
RunAction(sql)
sql = """
CREATE TABLE tOrderDetail (
order_id INTEGER NOT NULL REFERENCES tOrder(order_id),
prod_id INTEGER NOT NULL REFERENCES tProd(prod_id),
qty INTEGER NOT NULL CHECK(qty>0),
PRIMARY KEY (order_id, prod_id)
);"""
RunAction(sql)
sql = """
CREATE TABLE tProd (
prod_id INTEGER PRIMARY KEY,
prod_desc TEXT NOT NULL,
unit_price REAL NOT NULL
);"""
RunAction(sql)
return
def LoadTable(df, table_name):
'''df should have the same column names as the database table does
add more detailed documentation
'''
conn, curs = Connect()
sql = "INSERT INTO " + table_name + ' (' + ','.join(list(df.columns)) + \
') VALUES (:' + ',:'.join(list(df.columns)) + ');'
try:
for i, row in enumerate(df.to_dict(orient='records')):
curs.execute(sql, row)
except:
print(i)
print(row)
pe()
conn.rollback()
conn.close()
return False
conn.commit()
conn.close()
return True
def LoadLookups():
tProd = pd.read_csv('data/lookups/prods.csv')
tState = pd.read_csv('data/lookups/states.csv')
tZip = pd.read_csv('data/lookups/zips.csv', dtype={'zip':str})
tProd.columns = ['prod_id', 'prod_desc', 'unit_price']
tZip.columns = ['zip', 'city', 'st']
LoadTable(tProd, 'tProd')
LoadTable(tState, 'tState')
LoadTable(tZip, 'tZip')
return
def RebuildDB():
RebuildTables()
LoadLookups()
return