-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
140 lines (112 loc) · 3.59 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
"""DB Helper code"""
import sqlite3
import threading
from typing import List, Tuple
from config import DB_PATH
BulkItemStructure = List[Tuple[str, str, int]]
class DB:
"""Wrapper for common DB actions"""
_instance = None
_lock = threading.Lock()
def __init__(self, dbname="rashan.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(database=DB_PATH)
def __new__(cls, *args, **kwargs):
with cls._lock:
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
def setup(self):
"""DB setup"""
stmt = """
CREATE TABLE IF NOT EXISTS items (
name text NOT NULL,
quantity text NOT NULL,
price integer NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP
)
"""
self.conn.execute(stmt)
self.conn.commit()
def add_item(self, item_data):
"""Add items"""
stmt = "INSERT INTO items (name, quantity, price) VALUES (?,?,?)"
name = item_data["item"]
quantity = item_data["quantity"]
price = item_data["price"]
args = (name, quantity, price)
c = self.conn.cursor()
try:
c.execute(stmt, args)
self.conn.commit()
except sqlite3.Error as e:
raise e
c.close()
def add_bulk_items(self, all_items: BulkItemStructure):
"""
Add items in bulk
- all_items: List[Tuple[name, quantity, price]]
"""
stmt = "INSERT INTO items (name, quantity, price) VALUES (?,?,?)"
c = self.conn.cursor()
try:
c.executemany(stmt, all_items)
self.conn.commit()
except sqlite3.Error as e:
raise e
c.close()
def delete_item(self, item_text):
"""Delete items"""
stmt = "DELETE FROM items WHERE description = (?)"
args = (item_text,)
self.conn.execute(stmt, args)
self.conn.commit()
def recent_items(self):
"""Get recent items"""
stmt = "SELECT * FROM items ORDER BY created_at DESC LIMIT 5"
c = self.conn.cursor()
items = None
try:
c.execute(stmt)
items = c.fetchall()
c.close()
except sqlite3.Error as e:
raise e
if not items:
return "No items exists!!"
return items
def search_item(self, item_name):
"""Return last entry of an item"""
stmt = f"SELECT * FROM items WHERE name LIKE '%{item_name}%' ORDER BY created_at DESC LIMIT 1"
c = self.conn.cursor()
item_data = None
try:
c.execute(stmt)
item_data = c.fetchall()
c.close()
except sqlite3.Error as e:
raise e
if not item_data:
return "No item with this name exists!!"
return item_data
def get_monthly_usage(self, month: str, year: str):
"""Gets monthly quantity used of all items"""
stmt = """
SELECT name, sum(quantity), sum(price)
FROM items
where strftime('%Y', created_at) = (?)
and strftime('%m', created_at) = (?)
GROUP BY name
"""
c = self.conn.cursor()
result = None
args = (year, month)
try:
c.execute(stmt, args)
result = c.fetchall()
c.close()
except sqlite3.Error as e:
raise e
if not result:
return f"No items purchased for this {month}."
return result