Skip to content

Instantly share code, notes, and snippets.

@kitchen
Forked from vjt/description.txt
Last active December 23, 2015 00:49
Show Gist options
  • Save kitchen/6556414 to your computer and use it in GitHub Desktop.
Save kitchen/6556414 to your computer and use it in GitHub Desktop.
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]
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
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