from collections.abc import Sequence
from typing import Optional

import psycopg


class PostgresClient:
    def __init__(self, dsn: str):
        self.dsn = dsn

    def execute(self, query: str, params: Optional[Sequence] = None) -> None:
        with psycopg.connect(self.dsn) as connection:
            with connection.cursor() as cursor:
                cursor.execute(query, params)
                connection.commit()

    def fetch_all(self, query: str, params: Optional[Sequence] = None) -> list[tuple]:
        with psycopg.connect(self.dsn) as connection:
            with connection.cursor() as cursor:
                cursor.execute(query, params)
                return cursor.fetchall()

    def fetch_one(self, query: str, params: Optional[Sequence] = None) -> Optional[tuple]:
        with psycopg.connect(self.dsn) as connection:
            with connection.cursor() as cursor:
                cursor.execute(query, params)
                return cursor.fetchone()
