Created
July 14, 2024 05:44
-
-
Save haseebeqx/589f5cc5a5837ad6ff0a1e605b4c7e7f to your computer and use it in GitHub Desktop.
Pluck in batches - combines the efficiency of pluck with the memory-friendly approach of find_in_batches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ActiveRecord | |
class Relation | |
def pluck_in_batches(*columns, batch_size: 1000, start: nil) | |
relation = self | |
relation = relation.where(table[primary_key].gteq(start)) if start | |
batch_order = "#{table.name}.#{primary_key} ASC" | |
relation = relation.reorder(batch_order) | |
loop do | |
batch = relation.limit(batch_size).pluck(*columns, primary_key) | |
break if batch.empty? | |
yield batch | |
break if batch.size < batch_size | |
last_value = batch.last.last | |
relation = relation.where(table[primary_key].gt(last_value)) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment