-
-
Save kitchen/6556414 to your computer and use it in GitHub Desktop.
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
Originally posted on http://pastie.org/pastes/26489 (8 December 2006) | |
COPY FROM STDIN / LOAD DATA INFILE method for Rails PostgreSQL and MySQL Adapters. | |
The mysql adapter is completely untested. It is self-explanatory, isn't it? :) | |
Public domain, or DWTFWYW License, at your option. | |
[email protected] |
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 ActiveRecord::Base | |
class << self | |
def copy(columns, rows, name = nil) | |
connection.copy table_name, columns, rows, name | |
end | |
def indexes | |
connection.indexes table_name | |
end | |
end | |
end | |
class ActiveRecord::ConnectionAdapters::AbstractAdapter | |
def disable_indexes(table_name, &block) | |
raise ArgumentError, 'block missing' unless block | |
indexes = indexes(table_name) | |
# Drop indexes | |
indexes.each do |index| | |
remove_index index.table, :name => index.name | |
end | |
# Call the block | |
block.call | |
# Recreate indexes | |
indexes.each do |index| | |
add_index index.table, index.columns, :name => index.name | |
end | |
end | |
end |
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 ActiveRecord::ConnectionAdapters::PostgreSQLAdapter | |
def copy(table_name, columns, io, name = nil) | |
transaction do | |
disable_indexes(table_name) do | |
sql = "COPY #{table_name} (#{columns.join ','}) FROM STDIN" | |
log(sql, name) { | |
@connection.exec sql | |
io.each do |line| | |
@connection.putline line | |
end | |
@connection.endcopy | |
} | |
end | |
end | |
@connection.exec "VACUUM ANALYZE #{table_name}" | |
true | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment