Using AREL to refactor big queries

21
APPLICATION OF AREL IN REFACTORING BIG QUERY

Transcript of Using AREL to refactor big queries

Page 1: Using AREL to refactor big queries

APPLICATION OF ARELIN REFACTORING BIG QUERY

Page 2: Using AREL to refactor big queries

About me

• Nguyen Trung Hieu• Ruby on Rails developer at PLZ• Github: hieuk09

Page 3: Using AREL to refactor big queries

You may have seen this

Page 4: Using AREL to refactor big queries

Or this

Page 5: Using AREL to refactor big queries

How can we make it better?

Page 6: Using AREL to refactor big queries

AREL come to rescue!

• Stands for Arel Relational algEbra Library• Is an abstract syntax tree (AST) manager• Is the engine of Activerecord

Page 7: Using AREL to refactor big queries
Page 8: Using AREL to refactor big queries

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

Page 9: Using AREL to refactor big queries

Typical activerecord query

Page 10: Using AREL to refactor big queries

AREL API

• arel_table• or, and, in, eq, …• matches• project, join, having, count, …

Page 11: Using AREL to refactor big queries

LET’S TRY IT OUT

Page 12: Using AREL to refactor big queries

Typical activerecord query

Page 13: Using AREL to refactor big queries

Pros & Cons

• Pros:– short– fast

• Cons:– join table– duplication

Page 14: Using AREL to refactor big queries

Using AREL

Page 15: Using AREL to refactor big queries

Pros & Cons

• Pros:– DRY– Avoid ambiguity

• Cons:– verbose code– not as fast

Page 16: Using AREL to refactor big queries

A more typical Rails code

Page 17: Using AREL to refactor big queries

Using raw SQL

Page 18: Using AREL to refactor big queries

Using Arel

Page 20: Using AREL to refactor big queries

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