class CursorWrapper:
    """
    Wrapper around database cursor that fetches results immediately
    so they remain accessible after the connection is returned to the pool.
    """

    def __init__(self, cursor):
        self._cursor = cursor
        # Fetch all results immediately while cursor is still valid
        try:
            self._all_results = cursor.fetchall()
        except Exception:
            self._all_results = []
        self._current_index = 0
        self.lastrowid = getattr(cursor, "lastrowid", None)
        self.rowcount = getattr(cursor, "rowcount", -1)
        self.description = getattr(cursor, "description", None)

    def fetchone(self):
        """Fetch the next row from the cached results."""
        if self._current_index < len(self._all_results):
            result = self._all_results[self._current_index]
            self._current_index += 1
            return result
        return None

    def fetchall(self):
        """Return all remaining rows from the cached results."""
        result = self._all_results[self._current_index :]
        self._current_index = len(self._all_results)
        return result

    def fetchmany(self, size=1):
        """Fetch the next set of rows from the cached results."""
        result = self._all_results[self._current_index : self._current_index + size]
        self._current_index += len(result)
        return result

    def __getitem__(self, index):
        """Allow subscript access to results."""
        return self._all_results[index]

    def __iter__(self):
        """Allow iteration over results."""
        return iter(self._all_results)
