Showing posts with label copy command in postgres rails. Show all posts
Showing posts with label copy command in postgres rails. Show all posts

Wednesday, November 23, 2011

copy command in postgres rails

 Use copy SQL command instead of large insert query in postgres and also improved performance.

   query=<<-SQL
      SELECT brands1.id, #{self.id}
      FROM brands brands1
      LEFT OUTER JOIN brands brands2
        ON brands1.parent_id = brands2.id
      WHERE (#{name_conditions})
      AND #{specialty_conditions}
    SQL

search_contacts_bulk_insert_via_copy(query,"brands_searches (brand_id, search_id)")


  private

def search_contacts_bulk_insert_via_copy(query,iquery)
search_contacts_path="#{RAILS_ROOT}/tmp/bulk_insert/search_contacts_#{self.id}.copy"
File.delete(search_contacts_path) if FileTest.exists?(search_contacts_path)
search_contacts_path1 = File.new(search_contacts_path, "w")
File.chmod(0777, search_contacts_path)
query ="COPY (#{query}) TO '#{search_contacts_path}'"
ActiveRecord::Base.connection.execute(query)
   logger.error(query)
clinsert_query="COPY #{iquery} FROM '#{search_contacts_path}';"
connection.execute(clinsert_query)
logger.error(clinsert_query)
File.delete(search_contacts_path) if FileTest.exists?(search_contacts_path)
end