This repository was archived by the owner on Jul 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
54 lines (49 loc) · 1.5 KB
/
db.py
File metadata and controls
54 lines (49 loc) · 1.5 KB
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
"""
Database related functions
"""
import sqlite3
conn = sqlite3.connect("quakes.db")
cur = conn.cursor()
def handle(func):
"""
Handles passing around the cursor and committing changes
"""
def wrapper(*args, **kwargs):
"""
The wrapper for the decorated function
"""
result = func(cur, *args, **kwargs)
conn.commit()
return result
return wrapper
@handle
def initialize_db(cur):
"""
Initializes the data base
:param cur a cursor for the database, provided by handle
"""
# Create the database if it doesn't exist
cur.execute(
"CREATE TABLE IF NOT EXISTS Quake("
"QuakeID varchar(11) NOT NULL PRIMARY KEY , "
"Name varchar(255) NOT NULL, "
"Magnitude float(3) NOT NULL, "
"Timestamp int(8) NOT NULL)"
)
cur.execute(
"CREATE TABLE IF NOT EXISTS User("
"UserID INTEGER NOT NULL PRIMARY KEY,"
"Username varchar(60) NOT NULL UNIQUE,"
"Password varchar(60) NOT NULL)"
)
cur.execute(
"CREATE TABLE IF NOT EXISTS Game("
"UserID int NOT NULL,"
"QuakeID int NOT NULL,"
"Guess int NOT NULL,"
"Correct boolean," # later evaluted
"PRIMARY KEY (UserID, QuakeID)," # a composite primary key to allow only one guess
"FOREIGN KEY (UserID) REFERENCES User(UserID) ON DELETE CASCADE ON UPDATE CASCADE,"
"FOREIGN KEY (QuakeID) REFERENCES Quake(QuakeID) ON DELETE CASCADE ON UPDATE CASCADE"
")"
)