This repository has been archived on 2022-10-22. You can view files and clone it, but cannot push or open issues or pull requests.
it-volunteers-for-peace/services/repositories.py

52 lines
1.4 KiB
Python

from loguru import logger
from typing import Type, TypeVar
from asyncpg.connection import Connection
from asyncpg import Record
class BaseRepo:
def __init__(self, conn: Connection):
self.conn = conn
T = TypeVar("T", bound=BaseRepo)
class Repos(BaseRepo):
def get_repo(self, Repo: Type[T]) -> T:
return Repo(self.conn)
class UserRepo(BaseRepo):
async def add(self, user_id: int, chat_id: int):
await self.conn.execute(
"INSERT INTO users (user_id, chat_id) "
"VALUES ($1, $2) ON CONFLICT (user_id) DO NOTHING",
user_id,
chat_id,
)
async def get(self, user_id: int) -> Record:
return await self.conn.fetchrow(
"SELECT user_id, chat_id FROM users WHERE user_id = $1", user_id
)
class ProjectRepo(BaseRepo):
async def add(self, *args, user_id: int):
await self.conn.execute(
"INSERT INTO projects "
"(creator, name, description, contacts, "
"contributors, status, tag, category) "
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
user_id, *args
)
async def get(self, name: str, chat_id: int) -> Record:
return await self.conn.fetch(
"SELECT id, name, description FROM projects "
"INNER JOIN users ON projects.creator = users.user_id "
"WHERE users.chat_id = $1 AND name LIKE $2",
chat_id, f"%{name}%"
)