Skip to content

Instantly share code, notes, and snippets.

@jah2488
Last active August 29, 2015 13:57
Show Gist options
  • Save jah2488/9815563 to your computer and use it in GitHub Desktop.
Save jah2488/9815563 to your computer and use it in GitHub Desktop.
Speed up test db transactions with optimized-ish SQL queries!
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
@cdemyanovich
Copy link

A friend and former colleague of mine has a gem, activerecord-import, that might help, especially for larger sets of data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment