-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
101 lines (87 loc) · 2.69 KB
/
database.py
File metadata and controls
101 lines (87 loc) · 2.69 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
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
import os
from datamodels import UserInDb
from fastapi import HTTPException
from mysql import connector as sql
from mysql.connector import errorcode
TABLES = {}
TABLES[
"user"
] = """CREATE TABLE `user`(
`user_id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(20) NOT NULL UNIQUE,
`password` TEXT NOT NULL,
`dob` DATE NOT NULL,
`disabled` BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB"""
TABLES[
"post"
] = """CREATE TABLE `post`(
`post_id` INT(11) NOT NULL AUTO_INCREMENT,
`title` TEXT NOT NULL,
`user_id` INT(11) NOT NULL,
`created_on` DATETIME NOT NULL,
PRIMARY KEY (`post_id`),
FOREIGN KEY(`user_id`) REFERENCES user(`user_id`)
) ENGINE=InnoDB"""
TABLES[
"comment"
] = """CREATE TABLE `comment`(
`comment_id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`post_id` INT(11) NOT NULL,
`comment` TEXT NOT NULL,
`commented_on` DATETIME NOT NULL,
PRIMARY KEY(`comment_id`),
FOREIGN KEY(`user_id`) REFERENCES user(`user_id`),
FOREIGN KEY(`post_id`) REFERENCES post(`post_id`)
) ENGINE=InnoDB"""
DB_NAME = "DUMMY"
def create_db(cursor) -> None:
try:
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {DB_NAME}")
except sql.Error as err:
print(f"Failed creating database: {err}")
exit(1)
def init_db(cnx):
cursor = cnx.cursor()
try:
cursor.execute(f"USE {DB_NAME}")
except sql.Error as err:
print(f"Database {DB_NAME} does not exists.")
if err.errno == errorcode.ER_BAD_DB_ERROR:
create_db(cursor)
print(f"Database {DB_NAME} created successfully!")
cnx.database = DB_NAME
else:
print(err)
exit(1)
for table_name in TABLES:
table_description = TABLES[table_name]
try:
print("Creating table {}: ".format(table_name), end="")
cursor.execute(table_description)
except sql.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")
cursor.close()
cnx = sql.connect(
host="localhost",
user=os.environ.get("MYSQL_USER"),
password=os.environ.get("MYSQL_PASSWORD"),
)
def fetch_user(username: str) -> UserInDb:
cursor = cnx.cursor()
cursor.execute(
"SELECT username, dob, password, disabled FROM user WHERE username=%s",
(username,),
)
for username, dob, password, disabled in cursor:
return UserInDb(
username=username, hashed_password=password, dob=dob, disabled=disabled
)
raise HTTPException(status_code=404, detail="User not found!")