How do I use functions like CONCAT(), etc. in ARel?
Asked Answered
T

2

11

Is there a way to have ARel write (sanitized, possibly aliased, etc.) column names into CONCAT() and other SQL functions?

Here's how to do it with AVG()...

?> name = Arel::Attribute.new(Arel::Table.new(:countries), :name)
=> #<struct Arel::Attributes::Attribute [...]
?> population = Arel::Attribute.new(Arel::Table.new(:countries), :population)
=> #<struct Arel::Attributes::Attribute [...]
?> Country.select([name, population.average]).to_sql
=> "SELECT `countries`.`name`, AVG(`countries`.`population`) AS avg_id FROM `countries`"

(yes, I know that avg_id would be the same in every row, just trying to illustrate my question)

So what if I wanted a different function?

?> Country.select(xyz).to_sql # Arel::Concat.new(name, population) or something?
=> "SELECT CONCAT(`countries`.`name`, ' ', `countries`.`population`) AS concat_id FROM `countries`"

Thanks!

Tote answered 16/2, 2012 at 2:34 Comment(2)
Sequel has a way of selecting columns as "...".lit meaning "literal SQL" instead of being interpreted as a string for situations like this. That disables SQL escaping so you can inject whatever you want. Not sure what the AREL equivalent is, but maybe that's an idea.Qatar
I have written a bit more detail on this myself here <mrpunkin.com/post/18919379925/using-arel-for-sql-functions>Rosenkranz
G
18

Use NamedFunction:

name = Arel::Attribute.new(Arel::Table.new(:countries), :name)
func = Arel::Nodes::NamedFunction.new 'zomg', [name]
Country.select([name, func]).to_sql
Gorden answered 16/2, 2012 at 19:3 Comment(2)
It looks like NamedFunction need to be attached to an attribute? e.g. if I want to group things by dates, could I do .group(arel_table[:created_at].date), without attaching the "date" function directly on "created_at" so I can reuse it elsewhere? (sql: GROUP BY DATE(created_at))Duenas
@AaronPatterson Using your code, func.to_sql gives zomg('countries', 'name'). I think, the code should be ...Function.new 'zomg', [name] (with square brackets).Derekderelict
E
0

You can also use the Arel Extensions gem to have simpler access to functions.

> User.where((User[:login] + User[:first_name]).length.in 2..10).to_sql
"SELECT `users`.* FROM `users` 
 WHERE LENGTH(CONCAT(CAST(`users`.`login` AS char),
                     CAST(`users`.`first_name` AS char)))
         BETWEEN (2) AND (10)"
Exegesis answered 26/1, 2021 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.