When I call the function, it must execute 2000 rows and then stop. Then when calling it again, it must start from 2001 to 4000, and so on
You can do this is with plain sql with the help of a CTE. Insert into + Select ... limit 2000 returning id. Migration done. Put that in a CTE. In the outer query perform the update by referencing the returned rows from the CTE.
David J.