Using AREL to refactor big queries
-
Upload
hieu-nguyen-trung -
Category
Technology
-
view
4.100 -
download
6
Transcript of Using AREL to refactor big queries
APPLICATION OF ARELIN REFACTORING BIG QUERY
About me
• Nguyen Trung Hieu• Ruby on Rails developer at PLZ• Github: hieuk09
You may have seen this
Or this
How can we make it better?
AREL come to rescue!
• Stands for Arel Relational algEbra Library• Is an abstract syntax tree (AST) manager• Is the engine of Activerecord
WHY USING AREL?
RAW SQL• Coupling with database• String interpolation &
concatenation -> security issue
• Hard to maintain• Hard to test and refactor• Access to full SQL power• Faster
AREL• Coupling with activerecord• Fewer string interpolation &
concatenation• Easier to maintain• Easier to test and refactor• The AREL API may miss
some SQL feature• Slower
Typical activerecord query
AREL API
• arel_table• or, and, in, eq, …• matches• project, join, having, count, …
LET’S TRY IT OUT
Typical activerecord query
Pros & Cons
• Pros:– short– fast
• Cons:– join table– duplication
Using AREL
Pros & Cons
• Pros:– DRY– Avoid ambiguity
• Cons:– verbose code– not as fast
A more typical Rails code
Using raw SQL
Using Arel
Source code
• https://github.com/hieuk09/profiling-sample
RESOURCES
• http://radar.oreilly.com/2014/03/just-enough-arel.html
• https://robots.thoughtbot.com/using-arel-to-compose-sql-queries
• http://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html
• http://www.slideshare.net/camerondutro/advanced-arel-when-activerecord-just-isnt-enough
RESOURCES
• http://pivotallabs.com/using-arel-to-build-complex-sql-expressions/
• http://ben.hoskings.net/2012-07-04-arel-merge-a-hidden-gem
• http://asciicasts.com/episodes/215-advanced-queries-in-rails-3
• http://viget.com/extend/composable-sql-queries-in-rails-using-arel