Created
February 28, 2012 22:25
-
-
Save maxjustus/1935698 to your computer and use it in GitHub Desktop.
Using Postgres cursors to iterate through a table
This file contains hidden or 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
class YrModel < ActiveRecord::Base | |
has_many :derps | |
def self.find_with_cursor(query, &blk) | |
cursor_name = "cursor_#{(rand * 1000000).ceil}" | |
self.transaction do | |
self.connection.execute("DECLARE #{cursor_name} CURSOR FOR #{query.to_sql}") | |
while !(records = self.find_by_sql("FETCH FORWARD 1000 FROM #{cursor_name}")).empty? | |
#FIXME I think this method is deprecated in 3.1 in favor of #preload | |
preload_associations(records, [:derps]) | |
blk.call(records) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment