using arel to refactor big queries

Post on 14-Aug-2015

4.104 Views

Category:

Technology

6 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

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

top related