from sqlalchemy import text
from .database import async_session

async def exec_procedure(proc_name, params:dict = None, database: str = None):
    async with async_session() as session:
        sql_params = ""
        if params:
            sql_params = ",".join([f"@{key} = :{key}"
                            for key, value in params.items()])
        dbstr = ""
        if database:
            dbstr = f"[{database}]."
        sql_string = text(f'''
            DECLARE @return_value int;
            EXEC    @return_value = {dbstr}[dbo].[{proc_name}] {sql_params};
            SELECT 'Return Value' = @return_value;
        ''')
        datas = await session.execute(
            sql_string, params)
        await session.commit()
        return [dict(data._mapping) for data in datas.fetchall()]
    

