Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby PG gem use array as param with exec_params

I want to pass a ruby array value like so:

sql = "SELECT $1"
User.connection.raw_connection.exec_params(sql, [[1,2]])

This returns

PG::IndeterminateDatatype: ERROR:  could not determine data type of parameter $1

If I change sql to "SELECT $1::int[]" I get PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "[1, 2]".

Is there a way to pass a ruby array into exec_params and have it transformed into a PostgreSQL array?

like image 301
Reed G. Law Avatar asked Oct 24 '25 17:10

Reed G. Law


1 Answers

You can use the encoders to do that:

raw_connection.exec(
  "select $1::int[]",
  [PG::TextEncoder::Array.new.encode([1, 2])]
)
like image 87
Benjie Avatar answered Oct 26 '25 08:10

Benjie



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!