/
DataBase.py
161 lines (143 loc) · 4.79 KB
/
DataBase.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# -*- coding: utf-8 -*-
import sqlite3
import config
class DataBase:
"""
Класс взаимодействия с базой данных
Create statement:
CREATE TABLE "users" (
`id` INTEGER,
`tags` TEXT DEFAULT "",
`is_stop` INTEGER DEFAULT 0,
PRIMARY KEY(`id`) )
"""
def __init__(self, main_log):
"""
:param main_log: экземпляр класса Log
"""
self.connection = sqlite3.connect(config.DB_NAME, check_same_thread=False)
self.cursor = self.connection.cursor()
self.log = main_log
def add_user(self, id):
"""
Добавляет пользователя. Если пользователь существует, то вкючает рассылку
:param id: id пользователя
:return: True, если рассылка была отключена, иначе - None
"""
try:
self.cursor.execute("""INSERT OR IGNORE
INTO users (id, tags)
VALUES (:id, :empty)""", {"id": id, "empty": ""},)
self.cursor.execute("UPDATE users SET is_stop=0 WHERE id=:id", {"id": id})
self.connection.commit()
return True
except Exception as e:
self.log.error(str(e))
return None
def add_tags(self, id, message):
"""
Добавляет теги
:param id: id пользователя
:param message: список тегов в виде текста
:return: list, содержащий обновлённый список тегов, в случае ошибки - None
"""
try:
self.cursor.execute("SELECT tags FROM users WHERE id=:id", {"id": id})
old_tags = self.cursor.fetchall()[0][0]
old_tags = set(old_tags.split())
old_tags.update(set(message.split()))
self.cursor.execute("UPDATE users SET tags=:newTags WHERE id=:id",
{"newTags": " ".join(list(old_tags)), "id": id})
self.connection.commit()
return list(old_tags)
except Exception as e:
self.log.error(str(e))
return None
def del_tags(self, id, message):
"""
Удаляет теги
:param id: id пользователя
:param message: список тегов в виде текста
:return: list, содержащий обновлённый список тегов, в случае ошибки - None
"""
try:
self.cursor.execute("SELECT tags FROM users WHERE id=:id", {"id": id})
old_tags = self.cursor.fetchall()[0][0]
old_tags = set(old_tags.split())
old_tags.difference_update(set(message.split()))
self.cursor.execute("UPDATE users SET tags=:new_tags WHERE id=:id",
{"new_tags": " ".join(list(old_tags)), "id": id})
self.connection.commit()
return list(old_tags)
except Exception as e:
self.log.error(str(e))
return None
def get_tags(self, id):
"""
Возвращет теги пользователя
:param id: id пользователя
:return: list, содержащий список тегов, в случае ошибки - None
"""
try:
self.cursor.execute("SELECT tags FROM users WHERE id=:id", {"id": id})
tags = self.cursor.fetchall()[0][0]
tags = list(tags.split())
return tags
except Exception as e:
self.log.error(str(e))
return None
def get_all_users(self):
"""
:return: dict вида {"id": ["tag"]},в случае ошибки - None
"""
try:
self.cursor.execute("SELECT id, tags FROM users WHERE is_stop=0")
data = self.cursor.fetchall()
users = {}
for i in data:
users[i[0]] = i[1].split()
return users
except Exception as e:
self.log.error(str(e))
return None
def del_all_tags(self, id):
"""
Удаляет ВСЕ теги
:param id: id пользователя
:return: в случае ошибки - None, иначе - True
"""
try:
self.cursor.execute("UPDATE users SET tags='' WHERE id=:id", {"id": id})
self.connection.commit()
return True
except Exception as e:
self.log.error(str(e))
return None
def refresh_tags(self, id, tags):
"""
Обновляет теги. Старые при этом стираются
:param id: id пользователя
:param tags: list, содержащий теги
:return: list, содержащий список тегов, в случае ошибки - None
"""
try:
self.cursor.execute("UPDATE users SET tags=:new_tags WHERE id=:id",
{"new_tags": " ".join(tags), "id": id})
self.connection.commit()
return tags
except Exception as e:
self.log.error(str(e))
return None
def turn_mailout_off(self, id):
"""
Выключает рассылку
:param id: id пользователя
:return: возвращает True, если рассылка была отключена, иначе - None
"""
try:
self.cursor.execute("UPDATE users SET is_stop=1 WHERE id=:id", {"id": id})
self.connection.commit()
return True
except Exception as e:
self.log.error(str(e))
return None