import sqlite3 class UserRepository: conn = None def __init__(self, db_path): self.__initialize() def __initialize(self): cur = self.__getConnection().cursor() cur.execute("CREATE TABLE IF NOT EXISTS user(chat_id INT, alias TEXT)") cur.execute("CREATE UNIQUE INDEX IF NOT EXISTS chat_id_idx ON user(chat_id)") def __getConnection(self): return sqlite3.connect('db.sqlite') def getUser(self, chat_id): connection = self.__getConnection() cur = connection.cursor() query = "select * from user where chat_id = {chat_id}".format(chat_id = chat_id) cur.execute(query) return cur.fetchone() def getAllUsers(self): connection = self.__getConnection() cur = connection.cursor() query = "select * from user" cur.execute(query) return cur.fetchall() def removeChat(self, chat_id): connection = self.__getConnection() cur = connection.cursor() query = "DELETE FROM user where chat_id = {chat_id}".format( chat_id = chat_id) cur.execute(query) connection.commit() def putChat(self, chat_id, alias): if not self.getUser(chat_id): connection = self.__getConnection() cur = connection.cursor() query = "INSERT INTO user(chat_id, alias) VALUES({chat_id}, '{text}')".format( chat_id = chat_id, text = alias) cur.execute(query) connection.commit()