-
Notifications
You must be signed in to change notification settings - Fork 24.9k
Expand file tree
/
Copy pathdatabase.py
More file actions
73 lines (63 loc) · 1.88 KB
/
database.py
File metadata and controls
73 lines (63 loc) · 1.88 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import sqlite3
import os
def get_db_connection():
db_name = 'test_shopping_list.db' if os.environ.get('TESTING') else 'shopping_list.db'
conn = sqlite3.connect(db_name)
conn.row_factory = sqlite3.Row
return conn
def create_tables():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category_id INTEGER,
FOREIGN KEY (category_id) REFERENCES categories (id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS shopping_lists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
user_id INTEGER,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS shopping_list_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
shopping_list_id INTEGER,
product_id INTEGER,
quantity INTEGER NOT NULL,
FOREIGN KEY (shopping_list_id) REFERENCES shopping_lists (id),
FOREIGN KEY (product_id) REFERENCES products (id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS stock (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
product_id INTEGER,
quantity INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (product_id) REFERENCES products (id)
)
''')
conn.commit()
conn.close()
if __name__ == '__main__':
create_tables()