1

I have a class User that has an hstore attribute :preferences. If I want to find all Users where the startpage key in their preferences is nil I can do:

User.where("preferences @> 'startpage=>NULL'")

How can I structure that query so it avoids SQL query injection?

Tried:

User.where("preferences @> :key '=>NULL'", key: 'startpage')
User.where("preferences @> :key IS 'NULL'", key: 'startpage')
User.where("preferences @> :key IS NULL", key: 'startpage')
User.where("preferences @> ? IS NULL", 'startpage')

Without luck. Anyone know how to do this?

1 Answer 1

1

The @> operator expects hstores on both sides. When you say:

some_hstore @> 'startpage=>NULL'

PostgreSQL will implicitly add the ::hstore cast as if you had said:

some_hstore @> 'startpage=>NULL'::hstore

But there are other ways to create an hstore. From the fine manual:

Function: hstore(text, text)
Return Type: hstore
Description: make single-item hstore

So you can switch to the more explicit hstore(text, text) function and let ActiveRecord do its normal thing with placeholders and strings:

User.where("preferences @> hstore(:key, null)", :key => 'start page')
Sign up to request clarification or add additional context in comments.

Comments

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.