Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Created February 28, 2012 22:25
Show Gist options
  • Save maxjustus/1935698 to your computer and use it in GitHub Desktop.
Save maxjustus/1935698 to your computer and use it in GitHub Desktop.
Using Postgres cursors to iterate through a table
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