def fetch()

in asfpy/sqlite.py [0:0]


    def fetch(self, table: str, limit: int = 1, **params) -> typing.Iterator[dict]:
        """
        Searches a table for matching params, returns up to $limit items that match, as dicts in an iterator.
        If no limit is specified, returns all matches.
        @param table: Table to fetch rows from
        @param limit: The maximum number of rows to fetch. Can be None, for all rows
        @param params: Search parameters as key/value pairs
        @return: An iterator with all the found rows as dicts
        """
        if params:
            items = params.items()  # Use the same ordering for keys/values
            search = " AND ".join("`%s` = ?" % uk for uk, uv in items)
            values = [uv for uk, uv in items]
        else:
            search = "1"
            values = []
        statement = f'SELECT * FROM {table} WHERE {search}'
        if limit:
            statement += f' LIMIT {limit}'
            rows_left = limit
        self.cursor.execute(statement, values)
        while True:
            rowset = self.cursor.fetchmany()
            if not rowset:
                return  # break iteration
            for row in rowset:
                yield dict(row)
            if limit:
                rows_left -= len(rowset)
                assert rows_left >= 0
                if rows_left == 0:
                    return  # break iteration