-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnection.py
86 lines (73 loc) · 3.08 KB
/
Connection.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
import sqlite3
from typing import Any
class Connection:
"""Класс подключения к базе данных."""
def __init__(self):
"""Конструктор класса."""
self.connection = sqlite3.connect("database/books.db")
self.cursor = self.connection.cursor()
self.cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
userID INTEGER PRIMARY KEY,
username TEXT NOT NULL,
balance REAL DEFAULT 0,
chatID INTEGER UNIQUE
)
"""
)
self.cursor.execute(
"""
CREATE TABLE IF NOT EXISTS selected_books (
selectionID INTEGER PRIMARY KEY AUTOINCREMENT,
userID INTEGER,
bookName TEXT,
bookAuthor TEXT,
bookGenre TEXT,
bookCount INTEGER,
bookPrice REAL,
bookVendor TEXT,
FOREIGN KEY (userID) REFERENCES users(userID)
)
"""
)
self.connection.commit()
def add_user(self, user_id: int, username, chat_id) -> None:
"""Добавить пользователя в базу."""
self.cursor.execute(
"INSERT OR IGNORE INTO users (userID, username, chatID) VALUES (?, ?, ?)",
(user_id, username, chat_id,)
)
self.connection.commit()
def update_balance(self, sum, user_id) -> None:
"""Обновить баланс пользователя."""
self.cursor.execute(
"UPDATE users SET balance = balance + ? WHERE userID = ?", (sum, user_id)
)
self.connection.commit()
def get_balance(self, user_id) -> Any:
"""Получить баланс пользователя."""
balance = self.cursor.execute(
"SELECT balance FROM users WHERE userID = ?", (user_id,)
)
return balance.fetchone()[0]
def get_whole_price(self, userID) -> int:
"""Получить полную цену корзины."""
prices = self.cursor.execute(
"SELECT bookPrice FROM selected_books WHERE userID = ?", (userID,)
)
final_price = 0
for price in prices.fetchall():
final_price += price[0]
return final_price
def pay_whole_price(self, user_id, final_price) -> None:
"""Оплата всей стоимости корзины."""
self.cursor.execute(
"UPDATE users SET balance = balance - ? WHERE userID = ?",
(final_price, user_id,)
)
self.cursor.execute("DELETE FROM selected_books WHERE userID = ?", (user_id,))
self.connection.cursor()
def __del__(self):
"""Закрытие базы данных."""
self.connection.close()