from collections.abc import Iterator

import psycopg
from src.__types.index import Tenant
from src.infrastructure.database.execute_tenant_rls import execute_tenant_rls
from src.settings import Settings
from src.tracer import tracer

settings = Settings()


@tracer.capture_method
def get_connection() -> Iterator[psycopg.Connection]:
    # 処理終了時に接続を自動的にクローズする
    with psycopg.connect(conninfo=settings.postgres_url) as connection:
        connection.autocommit = True  # 全てのトランザクションを自動コミットする
        yield connection


def set_session_variables(tenant: Tenant, connection: psycopg.Connection) -> None:
    execute_tenant_rls(connection=connection, tenant_id=tenant.id)
