Skip to content

Instantly share code, notes, and snippets.

@skojin
Last active July 23, 2017 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skojin/7dfe2dda09b61e1505f42440b92e00b1 to your computer and use it in GitHub Desktop.
Save skojin/7dfe2dda09b61e1505f42440b92e00b1 to your computer and use it in GitHub Desktop.
export AR model to sql
# 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