-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdb.py
More file actions
62 lines (52 loc) · 2.51 KB
/
db.py
File metadata and controls
62 lines (52 loc) · 2.51 KB
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
import psycopg2
import psycopg2.extras
import json
class DBh:
def __init__(self, database, user, password, host, port):
"""Connecting to DB and saving connection cursor"""
self.database = database
self.user = user
self.password = password
self.host = host
self.port = port
self.connection = psycopg2.connect(database=self.database, user=self.user, password=self.password, host=self.host, port=self.port)
self.connection.autocommit = True
self.cursor = self.connection.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
def load_user(self, user_id):
"""load user if exists"""
with self.connection:
user = self.cursor.execute("SELECT * FROM users WHERE user_id = %s", (user_id,))
user = self.cursor.fetchall()
if user:
user = [{k: item[k] for k in item.keys()} for item in user]
return user[0]
return False
def load_statistics(self, user_id):
"""load statistics if user exists"""
with self.connection:
stat = self.cursor.execute("SELECT user_name, games_played, games_won, games_lost, games_tied, last_played, lang, all_in_games_count, max_win, max_loss, all_in_win, all_in_loss, all_in_tie, blackjack_count FROM users WHERE user_id = %s", (user_id,))
stat = self.cursor.fetchall()
if (stat):
stat = [{k: item[k] for k in item.keys()} for item in stat]
return stat[0]
return False
def add_user(self, user_id, user_name, user_lastname, deck):
"""register user"""
with self.connection:
return self.cursor.execute("INSERT INTO users (user_id, user_name, user_lastname, deck) VALUES (%s,%s,%s,%s)", (user_id, user_name, user_lastname,json.dumps(deck),))
def update(self, table, set, where, values):
"""update data"""
with self.connection:
return self.cursor.execute(f"UPDATE {table} SET {set} WHERE {where}", values)
def get(self, what, user_id):
"""select specific data"""
with self.connection:
data = self.cursor.execute(f"SELECT {what} FROM users WHERE user_id = %s", (user_id,))
data = self.cursor.fetchall()
if data:
data = [{k: item[k] for k in item.keys()} for item in data]
return data[0]
return False
def close(self):
"""Close connection with DB"""
self.connection.close()