-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
95 lines (74 loc) · 3.04 KB
/
model.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
import sqlite3
class Schema:
def __init__(self):
self.conn = sqlite3.connect('todo.db')
self.create_user_table()
self.create_to_do_table()
# Why are we calling user table before to_do table
# what happens if we swap them?
def __del__(self):
# body of destructor
self.conn.commit()
self.conn.close()
def create_to_do_table(self):
query ="CREATE TABLE IF NOT EXISTS 'Todo' (id INTEGER PRIMARY KEY,Title TEXT,Description TEXT,_is_done boolean DEFAULT 0,_is_deleted boolean DEFAULT 0,CreatedOn Date DEFAULT CURRENT_DATE,DueDate Date,UserId INTEGER FOREIGNKEY REFERENCES User(_id));"
self.conn.execute(query)
def create_user_table(self):
query = "CREATE TABLE IF NOT EXISTS 'User' (_id INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT NOT NULL, Email TEXT, CreatedOn Date default CURRENT_DATE);"
self.conn.execute(query)
class ToDoModel:
TABLENAME = "Todo"
def __init__(self):
self.conn = sqlite3.connect('todo.db')
self.conn.row_factory = sqlite3.Row
def __del__(self):
# body of destructor
self.conn.commit()
self.conn.close()
def get_by_id(self, _id):
where_clause = f"AND id={_id}"
return self.list_items(where_clause)
def create(self, params):
print (params)
query = f'insert into {self.TABLENAME} ' \
f'(Title, Description, DueDate, UserId) ' \
f'values ("{params.get("Title")}","{params.get("Description")}",' \
f'"{params.get("DueDate")}","{params.get("UserId")}")'
result = self.conn.execute(query)
return self.get_by_id(result.lastrowid)
def delete(self, item_id):
query = f"UPDATE {self.TABLENAME} " \
f"SET _is_deleted = {1} " \
f"WHERE id = {item_id}"
print (query)
self.conn.execute(query)
return self.list_items()
def update(self, item_id, update_dict):
"""
column: value
Title: new title
"""
set_query = " ".join([f'{column} = {value}'
for column, value in update_dict.items()])
query = f"UPDATE {self.TABLENAME} " \
f"SET {set_query} " \
f"WHERE id = {item_id}"
self.conn.execute(query)
return self.get_by_id(item_id)
def list_items(self, where_clause=""):
query = f"SELECT id, Title, Description, DueDate, _is_done " \
f"from {self.TABLENAME} WHERE _is_deleted != {1} " + where_clause
print (query)
result_set = self.conn.execute(query).fetchall()
result = [{column: row[i]
for i, column in enumerate(result_set[0].keys())}
for row in result_set]
return result
class User:
TABLENAME = "User"
def create(self, name, email):
query = f'insert into {self.TABLENAME} ' \
f'(Name, Email) ' \
f'values ({name},{email})'
result = self.conn.execute(query)
return result