Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert postgres hstore sql to Arel

I have a hstore column in the users table named properties.

How can I convert the static sql string inside the where condition to aRel syntax?

User.where("properties -> 'is_robber' = 'true'") #=> ...some users

I have tried:

ut = User.arel_table
condition = ut["properties -> 'is_robber'"].eq('true')
User.where(condition) #=> throws pg error

And that produces wrong sql:

 SELECT "users".* FROM "users" WHERE "users"."properties -> 'is_robber'" = 'true'

Compared to what i need:

SELECT "users".* FROM "users" WHERE "users".properties -> 'is_robber' = 'true'
like image 725
shuriu Avatar asked Apr 10 '26 19:04

shuriu


1 Answers

You can accomplish this with Arel by creating your own Arel::Nodes::InfixOperation:

ut = Arel::Table.new(:user)
hstore_key = Arel::Nodes::InfixOperation.new("->", ut[:properties], 'is_robber')
User.where(hstore_key.eq('true'))

Will produce:

SELECT "users".* FROM "users" WHERE "users"."properties" -> 'is_robber' = 'true'

If you've never heard of infix notation, Wikipedia gives a good explaination:

Infix notation is the common arithmetic and logical formula notation, in which operators are written infix-style between the operands they act on (e.g. 2 + 2). It is not as simple to parse by computers as prefix notation ( e.g. + 2 2 ) or postfix notation ( e.g. 2 2 + ), but many programming languages use it due to its familiarity.

Unfortunately, there's not much documentation for Arel, and none for the InfixOperation node, so it can be frustrating to start out with. When you're looking for how to perform particular SQL operations with Arel, your best bet is to look through the nodes directory in the source code.

like image 64
k8orade Avatar answered Apr 12 '26 10:04

k8orade



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!