Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple insert in parametrized statement with PG gem

Using the Ruby PG gem, I am trying to insert several rows at the same time with exec_params.

What I would like to acheive is:

INSERT INTO public.my_things (col1, col2)
VALUES
    ('value11', 'value12'),
    ('value21', 'value22'),
    ('value31', 'value32');

I tried this (and other combinations):

connection.exec_params(
  'INSERT INTO public.my_things (col1, col2) VALUES ($1, $2)',
  [['value11', 'value12'], ['value21', 'value22'], ['value31', 'value32']],
)
like image 826
Daniel Avatar asked Mar 30 '26 16:03

Daniel


1 Answers

There are two things to note:

  1. You need the right number of placeholders.
  2. #exec_params wants a flat array for the parameters.

So you want to say:

connection.exec_params(
  'INSERT INTO public.my_things (col1, col2) VALUES ($1, $2), ($3, $4), ($5, $6)',
  ['value11', 'value12', 'value21', 'value22', 'value31', 'value32']
)

Or, if you have an array-of-arrays and you don't know how long it will be until runtime:

aoa = [['value11', 'value12'], ['value21', 'value22'], ['value31', 'value32'], ... ]
values = aoa.length.times.map { |i| "($#{2*i+1}, $#{2*i+2})" }.join(',')
connection.exec_params(
  "INSERT INTO public.my_things (col1, col2) VALUES #{values}",
  aoa.flatten
)
like image 149
mu is too short Avatar answered Apr 02 '26 07:04

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!