Last active
August 29, 2015 13:57
-
-
Save jah2488/9815563 to your computer and use it in GitHub Desktop.
Speed up test db transactions with optimized-ish SQL queries!
This file contains 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
def clean!(*classes) | |
execute!(classes.map { |klass| "DELETE FROM #{klass.table_name}" }.join('; ')) | |
end | |
def create!(klass, keys, values) | |
query = make_mass_query(klass, keys, values) | |
execute!(query).map { |row| klass.new(row) } | |
end | |
private | |
def execute!(query) | |
ActiveRecord::Base.connection.execute(query) | |
end | |
def make_mass_query(klass, keys, values) | |
"WITH rows AS (INSERT into #{klass.table_name} (#{keys.join(', ')}) | |
VALUES #{values.map { |*vals| "(#{escape_values(vals)})"}.join(', ')} RETURNING *) SELECT * FROM rows" | |
end | |
def escape_values(vals) | |
vals.map do |val| | |
if val.is_a?(Array) | |
escape_values(val) | |
elsif val.is_a?(Fixnum) | |
val | |
else | |
"'#{val}'" | |
end | |
end.join(', ') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A friend and former colleague of mine has a gem, activerecord-import, that might help, especially for larger sets of data.