import aiosqlite

class Database:
    def __init__(self, db_path: str):
        self.db_path = db_path
        self._connection = None

    async def get_connection(self):
        if self._connection is None:
            self._connection = await aiosqlite.connect(self.db_path)
            self._connection.row_factory = aiosqlite.Row
        return self._connection

    async def execute(self,query: str, params: tuple = (), return_lastrowid: bool = False):
        conn = await self.get_connection()
        async with conn.execute(query, params) as cursor:
            if return_lastrowid:
                await conn.commit()
                return cursor.lastrowid
            else:
                await conn.commit()

    async def fetchone(self, query: str, params: tuple = ()):
        conn = await self.get_connection()
        async with conn.execute(query, params) as cursor:
            return await cursor.fetchone()

    async def fetchall(self, query: str, params: tuple = ()):
        conn = await self.get_connection()
        async with conn.execute(query, params) as cursor:
            return await cursor.fetchall()

    async def close(self):
        if self._connection:
            await self._connection.close()
            self._connection = None
