Skip to content

Instantly share code, notes, and snippets.

@edwinlab
Last active June 28, 2018 09:45
Show Gist options
  • Save edwinlab/87e87248c31be2eb6194d7d75f030d2e to your computer and use it in GitHub Desktop.
Save edwinlab/87e87248c31be2eb6194d7d75f030d2e to your computer and use it in GitHub Desktop.
# Takes a table name, and an array of hashes where keys are column names and values are values.
# Expects hashes to all contain the same keys.
def bulk_insert(table, rows)
columns = rows.first.keys
to_insert = rows.map do |d|
vals = columns.map {|k| d[k] }
ActiveRecord::Base.send(:replace_bind_variables, "(#{vals.length.times.collect {'?'}.join(',')})", vals)
end
ActiveRecord::Base.connection.execute(<<-SQL)
INSERT INTO
#{table}
(#{columns.join(',')})
VALUES #{to_insert.join(",")}
SQL
end
SQL = <<-SQL
update test as t set
column_a = c.column_a,
column_c = c.column_c
from (values
('123', 1, '---'),
('345', 2, '+++')
) as c(column_b, column_a, column_c)
where c.column_b = t.column_b;
SQL
Book.connection.execute(SQL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment