2

I am using Ruby to call postgresql through the shell via a command like:

%x[ psql -A -F "," -o feeds/tmp.csv -f lib/sql/query.sql -v id_list="#{id_list}" ]

query.sql looks like but can be changed:

Select *
From tbl_test
Where id in (:id_list)

The query should resolve to:

Select *
From tbl_test
Where id in ('a','b','c')

Thanks in advance.

0

1 Answer 1

2
# before
-v id_list="#{id_list}"

# after
# `join` will separate the values in an array with the string provided
# `map...` the block given to map will surround each item with single quotes
-v id_list="#{id_list.map { |i| "'#{i}'" }.join(', ') }"

# When `id` is an INTEGER you want the `IN` list specified without quotes
# SELECT * FROM tbl_test WHERE id IN (1, 2, 3);
-v id_list="#{id_list.map(&:to_i).join(', ') }"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, much simpler than I was expecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.