def fetchiter(cursor, size=1000, batch=False, server_cursor=None):
    """
    Use a generator as an iterator for fetching large db record sets.

    Example:
      for row in fetchiter(cursor):
        ...

    Only for PostgreSQL
    -------------------
    You can use a previous server cursor declared as:
    `DECLARE {C} CURSOR FOR SELECT * FROM ...` where {C} is a string with the
    server cursor name.

    Then use the parameter server_cursor={C} where {C} is the cursor name,
    this will make each iteration runs `FETCH {size} FROM {C}` instead of the
    whole query.
    """
    while True:
        if server_cursor is None:
            results = cursor.fetchmany(size)
        else:
            cursor.execute('FETCH %s FROM {}'.format(server_cursor), (size,))
            results = cursor.fetchall()
        if not results:
            break
        if batch:
            yield results
        else:
            for result in results:
                yield result
