This repository has been archived on 2023-01-19. You can view files and clone it, but cannot push or open issues or pull requests.
MirrorTea/mirrortea/repository/sqlite_repository.py

110 lines
3 KiB
Python

import sqlite3
from typing import Optional
from collections import namedtuple
from mirrortea.repository.abstract_db_repository import AbstractDatabaseRepository
from mirrortea.models.matrix_room import MatrixRoom
from mirrortea.models.user import User
from mirrortea.repository.exceptions import (
UserNotFoundError,
MatrixRoomAlreadyExistError,
MatrixRoomNotFoundError,
UserAlreadyExistError,
)
from mirrortea.repository.sqlite_init_tables import (
# PLATFORM_USER_MATRIX_CHATS_SQL,
PLATFORMS_USERS_SQL,
MATRIX_ROOMS_SQL,
)
TABLES_LIST = [
# PLATFORM_USER_MATRIX_CHATS_SQL,
PLATFORMS_USERS_SQL,
MATRIX_ROOMS_SQL,
]
PATH_TO_DB = "database.db"
class SQLiteDatabaseRepository(AbstractDatabaseRepository):
def __init__(self, path=PATH_TO_DB):
self.path = path
self.conn = sqlite3.connect(self.path)
self.cursor = self.conn.cursor()
def _namedtuple_factory(row, cursor, raw_tuples):
fields = [column[0] for column in cursor.description]
cls = namedtuple("Row", fields)
return cls._make(raw_tuples)
def create_tables(self) -> None:
"""Init tables in database"""
for table in TABLES_LIST:
self.conn.execute(table)
self.conn.commit()
def get_user_by_id(self, user_id: str) -> User:
"""Get user by user id"""
self.conn.row_factory = self._namedtuple_factory
self.cur_userdata = self.conn.execute(
"SELECT user_id AS user_id, first_name AS first_name, last_name AS last_name, username AS username, avatar_hash AS avatar_hash FROM platforms_users WHERE user_id = (?)",
(user_id,)
)
self.userdata = self.cur_userdata.fetchone()
if self.userdata == ():
return UserNotFoundError("User not found!")
return User(
user_id=self.userdata.user_id,
first_name=self.userdata.first_name,
last_name=self.userdata.last_name,
username=self.userdata.username,
avatar_hash=self.userdata.avatar_hash,
)
def create_user(self, user: User) -> User:
"""Create user"""
try:
self.cursor.execute(
"INSERT INTO platforms_users VALUES (?, ?, ?, ?, ?)",
(
user.user_id,
user.first_name,
user.last_name,
user.username,
user.avatar_hash,
),
)
except sqlite3.IntegrityError:
return UserAlreadyExistError("User already exist!")
self.conn.commit()
return self.get_user_by_id(user_id=user.user_id)
def update_user(self) -> None:
""""""
def delete_user(self) -> None:
""""""
def create_matrix_room(self) -> MatrixRoom:
""""""
def get_matrix_room(self) -> MatrixRoom:
""""""
def update_matrix_room(self) -> MatrixRoom:
""""""
def delete_matrix_room(self) -> None:
""""""