-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
52 lines (42 loc) · 2.4 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
import sqlite3
class BotDB:
def __init__(self, db_file):
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
def user_exists(self, user_id):
"""Проверяем, есть ли юзер в базе"""
result = self.cursor.execute("SELECT `id` FROM `users` WHERE `user_id` = ?", (user_id,))
return bool(len(result.fetchall()))
def get_user_id(self, user_id):
"""Достаем id юзера в базе по его user_id"""
result = self.cursor.execute("SELECT `id` FROM `users` WHERE `user_id` = ?", (user_id,))
return result.fetchone()[0]
def add_user(self, user_id):
"""Добавляем юзера в базу"""
self.cursor.execute("INSERT INTO `users` (`user_id`) VALUES (?)", (user_id,))
return self.conn.commit()
def add_record(self, user_id, operation, value):
"""Создаем запись о доходах/расходах"""
self.cursor.execute("INSERT INTO `court` (`users_id`, `operation`, `time`) VALUES (?, ?, ?)",
(self.get_user_id(user_id),
operation == "+",
value))
return self.conn.commit()
def get_records(self, user_id, within = "all"):
"""Получаем историю о доходах/расходах"""
if(within == "day"):
result = self.cursor.execute("SELECT * FROM `records` WHERE `users_id` = ? AND `date` BETWEEN datetime('now', 'start of day') AND datetime('now', 'localtime') ORDER BY `date`",
(self.get_user_id(user_id),))
elif(within == "week"):
result = self.cursor.execute("SELECT * FROM `records` WHERE `users_id` = ? AND `date` BETWEEN datetime('now', '-6 days') AND datetime('now', 'localtime') ORDER BY `date`",
(self.get_user_id(user_id),))
elif(within == "month"):
result = self.cursor.execute("SELECT * FROM `records` WHERE `users_id` = ? AND `date` BETWEEN datetime('now', 'start of month') AND datetime('now', 'localtime') ORDER BY `date`",
(self.get_user_id(user_id),))
else:
result = self.cursor.execute("SELECT * FROM `records` WHERE `users_id` = ? ORDER BY `date`",
(self.get_user_id(user_id),))
return result.fetchall()
def close(self):
"""Закрываем соединение с БД"""
self.connection.close()