Last active
July 23, 2017 12:28
-
-
Save skojin/7dfe2dda09b61e1505f42440b92e00b1 to your computer and use it in GitHub Desktop.
export AR model to sql
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
# export AR model to sql | |
# example: | |
# SqlDump.new( KeyValue.where(..) ).export{ |sql| puts sql } | |
# SqlDump.new( KeyValue.where(..) ).export(file: "key_values_dump.sql") | |
class SqlDump | |
def initialize(scope) | |
@scope = scope | |
@count = 0 | |
end | |
def export(file: nil) # &block | |
if file | |
open(file, 'wb') do |f| | |
each_block {|sql| f.write(sql); f.write("\n")} | |
end | |
else | |
each_block {|sql| yield sql} | |
end | |
@count | |
end | |
def each_block | |
@count = 0 | |
insert_base = nil | |
@scope.find_in_batches do |records| | |
record = records.first | |
insert_base ||= "INSERT INTO #{@scope.quoted_table_name} (#{ record.attributes.keys.map {|n| @scope.connection.quote_column_name(n)}.join(', ') }) VALUES" | |
values_sql = records.map do |r| | |
"(#{r.attributes.values.map {|v| @scope.connection.quote(v)}.join(',') })" | |
end.join(', ') | |
yield "#{insert_base} #{values_sql};" | |
@count += records.size | |
puts @count | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment