/
db.py
539 lines (455 loc) · 15.7 KB
/
db.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# name: db.py
# author: Jordan Stremming
#
# Provides methods for database connection
# also, creates database tables
#
import os
import sqlite3
from flask import g
from models import ItemCategory, Purchase, ShoppingCartItem, Address, ShoppingCart
from models import InventoryItem
from models import User
# database file location
DATABASE = "./data.db"
def create_db(force=False):
"""
Automatically creates database, if needed.
:param force: if True, creates the database anyways. NOTE: does not delete existing db. Renames
renames old database to DATABASE_FILE.db.old.
"""
if force:
try:
print("attempting to archive existing database.")
os.rename(DATABASE, DATABASE + ".old")
except OSError as ose:
print("error archiving database file:", ose)
# if database does not exist, create tables
if not os.path.exists(DATABASE) or force:
db = sqlite3.connect("./data.db")
cur = db.cursor()
# create User table
cur.execute("""
CREATE TABLE User (
UserID INTEGER PRIMARY KEY AUTOINCREMENT,
Username TEXT,
Password TEXT
);
""")
# create InventoryItem table
cur.execute("""
CREATE TABLE InventoryItem (
ItemID INTEGER PRIMARY KEY AUTOINCREMENT,
ItemName TEXT,
Description TEXT,
Price FLOAT,
Category TEXT,
Quantity INTEGER
);
""")
db.commit()
# create Purchase table
cur.execute("""
CREATE TABLE Purchase (
PurchaseID INTEGER PRIMARY KEY AUTOINCREMENT,
Username TEXT,
TotalPrice FLOAT,
CreditCard TEXT,
Address TEXT
);
""")
db.commit()
# create PurchaseItem table
cur.execute("""
CREATE TABLE PurchaseItem (
PurchaseID INTEGER,
InventoryItemID INTEGER,
Price FLOAT,
Quantity INTEGER,
FOREIGN KEY (PurchaseID) REFERENCES Purchase (PurchaseID),
FOREIGN KEY (InventoryItemID) REFERENCES InventoryItem (ItemID)
);
""")
db.commit()
# create ShoppingCartItem table
cur.execute("""
CREATE TABLE ShoppingCartItem (
UserID INTEGER,
InventoryItemID INTEGER,
Price FLOAT,
Quantity INTEGER,
FOREIGN KEY (UserID) REFERENCES User (UserID),
FOREIGN KEY (InventoryItemID) REFERENCES InventoryItem (ItemID)
);
""")
db.commit()
# insert Admin user
add_user(User(username="admin", password="password"), db)
# insert Sample Inventory items
add_item(InventoryItem(name="Apple", description="One a day is 19g of sugar!", price=1.25,
category=ItemCategory.TOYS, qty=23), db)
add_item(InventoryItem(name="Teddy Bear", description="Missing his head, but he still loves you!", price=9.99,
category=ItemCategory.TOYS, qty=6), db)
add_item(InventoryItem(name="Book", description="That's a nice cover. I might read that.", price=42.11,
category=ItemCategory.BOOKS, qty=2), db)
add_item(InventoryItem(name="The Great Gatsby", description="Every girls dream love story.", price=18.50,
category=ItemCategory.BOOKS, qty=30), db)
add_item(InventoryItem(name="Twilight", description="Spurkle Purty", price=0.99,
category=ItemCategory.BOOKS, qty=88), db)
add_item(InventoryItem(name="Raspberry Pi", description="What do you do with this?", price=3.14,
category=ItemCategory.SMALL_ELECTRONICS, qty=99), db)
add_item(InventoryItem(name="Apple Pi", description="Raspberry pi, but tastier!", price=5.55,
category=ItemCategory.SMALL_ELECTRONICS, qty=99), db)
add_item(InventoryItem(name="Toothpaste", description="Minty Fresh", price=500.99,
category=ItemCategory.HOUSEHOLD_ITEMS, qty=10), db)
db.commit()
cur.close()
db.close()
def get_db():
"""
Gets the database connection.
"""
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect("./data.db")
return db
def add_user(user, db=None):
"""
Adds a user to the database.
:param user: User of user to insert
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
cur.execute("INSERT INTO User (Username, Password) VALUES (?, ?)",
[user.username, user.password])
db.commit()
cur.close()
def update_user_password(user, db=None):
"""
Updates password for a User.
If User does not exist, will Insert user.
:param user: User of user to update
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
cur.execute("UPDATE User SET Password=? WHERE UserID=?",
[user.password, user.id_])
db.commit()
cur.close()
# if the update failed, insert it
if cur.rowcount == 0:
add_user(user, db)
def get_user(user, db=None):
"""
Attempts to find a user with provided username and password.
:param user: User of user to find
:param db: optional, the database connection to commit to
:return: User, if the user exists. Otherwise, None.
"""
db = db or get_db()
cur = db.cursor()
query = "SELECT UserID, Username, Password FROM User "
if user.id_ is not None:
# Find by ID
cur.execute(query + "WHERE UserID=?",
[user.id_])
elif user.username is not None and user.password is None:
# Find by Username
cur.execute(query + "WHERE Username=?",
[user.username])
else:
# Find by Username and Password
cur.execute(query + "WHERE Username=? AND Password=?",
[user.username, user.password])
result = None
row = cur.fetchone()
if row is not None:
# fetch the user
result = User(id_=row[0], username=row[1], password=row[2])
cur.close()
return result
def get_inventory_item(item, db=None):
"""
Gets a singular InventoryItem
:param item: InventoryItem
:param db: optional
:return: InventoryItem
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
SELECT ItemID, ItemName, Description, Price, Category, Quantity
FROM InventoryItem
WHERE ItemID=?
""", [item.id_])
row = cur.fetchone()
if row is not None:
return InventoryItem(id_=row[0], name=row[1], description=row[2],
price=row[3], category=ItemCategory[row[4]], qty=row[5])
return None
def get_inventory(db=None):
"""
Gets all InventoryItems.
:param db: optional, the database connection to commit to
:returns: list, all items in Inventory as InventoryItems
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
SELECT ItemID, ItemName, Description, Price, Category, Quantity
FROM InventoryItem
""")
result = []
for row in cur.fetchall():
try:
if row[5] > 0:
result.append(InventoryItem(id_=row[0], name=row[1], description=row[2],
price=row[3], category=ItemCategory[row[4]], qty=row[5]))
except Exception as e:
print("invalid inventory item:", e)
cur.close()
return result
def add_item(item, db=None):
"""
Adds an InventoryItem to the database.
:param item: InventoryItem to insert
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
print("Adding", [item.name, item.description, item.price, item.category.value, item.quantity])
cur.execute("""
INSERT INTO InventoryItem (ItemName, Description, Price, Category, Quantity)
VALUES (?, ?, ?, ?, ?)
""", [item.name, item.description, item.price, str(item.category), item.quantity])
db.commit()
cur.close()
def add_to_cart(user, item, qty=1, db=None):
"""
Adds an InventoryItem to user's shopping cart.
:param user: User
:param item: InventoryItem to insert
:param qty: int, quantity to insert
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
UPDATE ShoppingCartItem
SET Quantity = Quantity + ?
WHERE UserID=?
AND InventoryItemID=?
""", [qty, user.id_, item.id_])
if cur.rowcount == 0:
cur.execute("""
INSERT INTO ShoppingCartItem (UserID, InventoryItemID, Price, Quantity)
VALUES (?, ?, ?, ?)
""", [user.id_, item.id_, item.price, qty])
db.commit()
cur.close()
def remove_from_cart(user, item, qty=1, db=None):
"""
Removes a ShoppingCartItem from user's shopping cart.
:param user: User
:param item: ShoppingCartItem to remove
:param qty: int, quantity to remove
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
UPDATE ShoppingCartItem
SET Quantity = Quantity - ?
WHERE UserID=?
AND InventoryItemID=?
""", [qty, user.id_, item.item.id_])
cur.execute("""
DELETE FROM ShoppingCartItem
WHERE Quantity < 1
""")
db.commit()
cur.close()
def update_cart(user, item, qty=1, db=None):
"""
Updates a ShoppingCartItem in user's shopping cart.
:param user: User
:param item: ShoppingCartItem to update
:param qty: int, new quantity
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
UPDATE ShoppingCartItem
SET Quantity = ?
WHERE UserID=?
AND InventoryItemID=?
""", [qty, user.id_, item.item.id_])
cur.execute("""
DELETE FROM ShoppingCartItem
WHERE Quantity < 1
""")
db.commit()
cur.close()
def update_item(item, db=None):
"""
Updates attributes for an InventoryItem.
If InventoryItem does not exist, inserts instead.
:param item: InventoryItem to update
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
UPDATE InventoryItem
SET ItemName = ?,
Description = ?,
Price = ?,
Category = ?,
Quantity = ?
WHERE ItemID = ?
""", [item.name, item.description, item.price, str(item.category), item.quantity, item.id_])
db.commit()
cur.close()
# if the update failed, insert it
if cur.rowcount == 0:
add_item(item, db)
def remove_item(item, qty=1, db=None):
"""
Removes qty of InventoryItem from db.
:param item: InventoryItem to update
:param qty: int, quantity to remove. Defaults to 1.
:param db: optional, the database connection to commit to
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
UPDATE InventoryItem
SET Quantity = Quantity - ?
WHERE ItemID = ?
""", [qty, item.id_])
db.commit()
cur.close()
def get_shopping_cart(user, db=None):
"""
Gets all ShoppingCartItems for user
:param user: User, the user to request for
:param db: optional, the database connection
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
SELECT InventoryItemID, Price, Quantity
FROM ShoppingCartItem
WHERE UserID = ?
""", [user.id_])
cart = ShoppingCart(user)
for row in cur.fetchall():
try:
item = get_inventory_item(InventoryItem(id_=row[0]), db)
cart.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2]))
except Exception as e:
print("invalid purchase item:", e)
cur.close()
return cart
def clear_shopping_cart(user, db=None):
"""
Removes all ShoppingCartItems for user
:param user: User, the user to request for
:param db: optional, the database connection
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
DELETE FROM ShoppingCartItem
WHERE UserID=?
""", [user.id_])
db.commit()
cur.close()
def get_purchase(purchase, db=None):
"""
Gets a purchase from the database based on PurchaseID
:param purchase: Purchase, must have id
:param db: optional, the database connection
"""
db = db or get_db()
cur = db.cursor()
cur.execute("""
SELECT Username, TotalPrice, CreditCard, Address
FROM Purchase
WHERE PurchaseID = ?
""", [purchase.id_])
row = cur.fetchone()
try:
purchase = Purchase(id_=purchase.id_, username=row[0], total_price=row[1],
credit_card=row[2], address=Address().from_str(row[3]))
except Exception as e:
print("invalid purchase:", e)
cur.execute("""
SELECT InventoryItemID, Price, Quantity
FROM PurchaseItem
WHERE pi.PurchaseID = ?
""", [purchase.id_])
for row in cur.fetchall():
try:
item = get_inventory_item(InventoryItem(id_=row[0]), db)
purchase.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2]))
except Exception as e:
print("invalid purchase item:", e)
cur.close()
return purchase
def add_purchase(purchase, db=None):
"""
Inserts a purchase into the database.
:param purchase: Purchase, what to insert
:param db: optional, the database connection
"""
db = db or get_db()
cur = db.cursor()
# insert the purchase
cur.execute("""
INSERT INTO Purchase (Username, TotalPrice, CreditCard, Address)
VALUES (?, ?, ?, ?)
""", [purchase.username, purchase.total_price, purchase.credit_card, purchase.address.to_str()])
purchase.id_ = cur.lastrowid
# insert all the items for the purchase
for item in purchase.items:
cur.execute("""
INSERT INTO PurchaseItem (PurchaseID, InventoryItemID, Price, Quantity)
VALUES (?, ?, ?, ?)
""", [purchase.id_, item.item.id_, item.price, item.qty])
# remove from stock
remove_item(item.item, item.qty, db)
db.commit()
cur.close()
def get_user_purchases(user, db=None):
"""
Gets all purchases by user.
:param user: User, the user to find purchases for
:param db: optional, the database connection
"""
db = db or get_db()
cur = db.cursor()
# insert the purchase
cur.execute("""
SELECT PurchaseID, TotalPrice, CreditCard, Address
FROM Purchase
WHERE Username=?
""", [user.username])
purchases = []
for row1 in cur.fetchall():
purchase = Purchase(username=user.username, id_=row1[0], total_price=row1[1],
credit_card=row1[2], address=Address().from_str(row1[3]))
cur.execute("""
SELECT InventoryItemID, Price, Quantity
FROM PurchaseItem
WHERE PurchaseID=?
""", [purchase.id_])
for row2 in cur.fetchall():
item = get_inventory_item(InventoryItem(row2[0]), db)
purchase.items.append(ShoppingCartItem(item=item, price=row2[1], qty=row2[2]))
purchases.append(purchase)
cur.close()
return purchases