SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Arel and Rails 3
Relational algebra meets ActiveRecord
What!?
•       Relational Algebra deals with sets of finite relations, which are closed under
        certain operators. These operators operate on one or more relations to yield a
        relation.

•       Relation (table) - Data structure composed of a heading (columns) and an
        unordered set of tuples (rows) that share the same type.

•       Closure - A set is said to be closed under some operation if the result of that
        operation is a member of the set.

    •    e.g.: Real numbers are closed under subtraction but natural numbers are not.
         Although 3 and 7 are natural numbers the result of 3 - 7 is not.
Operators
      Primitive             Derived
  Selection (WHERE)      Set Intersection
  Projection (SELECT)       Division
      Cross Join           Natural Join
      Set Union
    Set Difference
Rename (SELECT A as B)
ActiveRecord::Relation Example
       Pub.select(:name).where(:city => 'Sydney')
    #yields an ActiveRecord::Relation instance. No SQL ran.



                 but prior to Rails 3...

Pub.find(:all, :select => "name",
                 :conditions => { :city => 'Sydney' })
               #yields an Array with the results
Ok, but now what?
Build more interesting queries by combining relations...

> syd_pubs = Pub.select('pubs.name').where(:city => 'Sydney')

> squire = Pub.joins(:beers).where(:beers =>
                                   {:name => 'James Squire'})

Now get me all the pubs in sydney that sell James Squire!

> (syd_pubs & squire).all
# yields an Array
Arel in Action
> (syd_pubs & squire).all

This causes ActiveRecord::Relation to ask Arel to build the SQL
query below, corresponding to the combined relations:

                 SELECT pubs.name
                 FROM pubs
                 INNER JOIN beers_pubs
                   ON beers_pubs.pub_id = pubs.id
                 INNER JOIN beers
                   ON beers.id = beers_pubs.beer_id
                 WHERE (pubs.city = 'Sydney') AND
              (beers.name = 'James Squire')
Grouping and sorting data
  > pubs_beers = Pub.joins(:beers)
  > pubs = pubs_beers.select('pubs.name, count(*) as
beers_count').group('pubs.name')

 > pubs.all[0].beers_count
 # 2

  > pubs.order('beers_count').all
Range Conditions
> today = Time.now.at_beginning_of_day
> tomorrow = Time.now.tomorrow.at_beginning_of_day
> Pub.where(:created_at => today..tomorrow).all

Arel takes care of ranges as well...

                 SELECT pubs.*
                 FROM pubs
                 WHERE (pubs.created_at BETWEEN
                 '2010-10-05 00:00:00.000000'
                 AND '2010-10-06 00:00:00.000000')
Scopes: Reusable Relations
class Beer < ActiveRecord::Base
  scope :stout, where(:flavor => "Stout")
end


> Beer.stout.all
# gives back an Array with the results
Eager Loading Associations
Associations are lazily loaded by default and as such...

> pubs = Pub.all
> pubs[0].beers
> pubs[1].beers

...produces these queries to be executed:
                   SELECT pubs.* FROM pubs
                   SELECT * FROM beers
                   INNER JOIN beers_pubs
                      ON beers.id = beers_pubs.beer_id
                   WHERE (beers_pubs.pub_id = 1 )
                   SELECT * FROM beers
                   INNER JOIN beers_pubs
                      ON beers.id = beers_pubs.beer_id
                   WHERE (beers_pubs.pub_id = 2 )
Eager Loading Associations
Eager load what you need using the new relations syntax:

> pubs = Pub.includes(:beers).all
> pubs[0].beers
> pubs[1].beers

Note that only one query is used to load the Beers info:

              SELECT pubs.* FROM pubs
              SELECT beers.*, t0.pub_id as the_parent_record_id
              FROM beers
              INNER JOIN beers_pubs t0
                 ON beers.id = t0.beer_id
              WHERE (t0.pub_id IN (1,2,3))
Thank you!
Q&A
References
• Arel - http://github.com/rails/arel
• Rails - http://github.com/rails/rails
• Rails Guides - http://guides.rubyonrails.org/
• Relational Algebra - http://en.wikipedia.org/wiki/Relational_algebra

Weitere ähnliche Inhalte

Ähnlich wie Arel in Rails 3

What\'s new in Rails 2.1
What\'s new in Rails 2.1What\'s new in Rails 2.1
What\'s new in Rails 2.1Keith Pitty
 
Relational Algebra
Relational AlgebraRelational Algebra
Relational Algebraguest20b0b3
 
database-querry-student-note
database-querry-student-notedatabase-querry-student-note
database-querry-student-noteLeerpiny Makouach
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queriesPRAKHAR JHA
 
1.1 Intro to WinDDI.pdf
1.1 Intro to WinDDI.pdf1.1 Intro to WinDDI.pdf
1.1 Intro to WinDDI.pdfssuser8b6c85
 
Migration from mysql to elasticsearch
Migration from mysql to elasticsearchMigration from mysql to elasticsearch
Migration from mysql to elasticsearchRyosuke Nakamura
 
Tour of Ecto March 2017 Dave Lucia
Tour of Ecto March 2017 Dave LuciaTour of Ecto March 2017 Dave Lucia
Tour of Ecto March 2017 Dave LuciaDavid Lucia
 
Market Basket Analysis in R
Market Basket Analysis in RMarket Basket Analysis in R
Market Basket Analysis in RRsquared Academy
 
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...Matt Gauger
 
Ruby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersRuby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersAaron Patterson
 

Ähnlich wie Arel in Rails 3 (15)

What\'s new in Rails 2.1
What\'s new in Rails 2.1What\'s new in Rails 2.1
What\'s new in Rails 2.1
 
Relational Algebra
Relational AlgebraRelational Algebra
Relational Algebra
 
database-querry-student-note
database-querry-student-notedatabase-querry-student-note
database-querry-student-note
 
Using Mysql.pptx
Using Mysql.pptxUsing Mysql.pptx
Using Mysql.pptx
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
1.1 Intro to WinDDI.pdf
1.1 Intro to WinDDI.pdf1.1 Intro to WinDDI.pdf
1.1 Intro to WinDDI.pdf
 
04.SQL.ppt
04.SQL.ppt04.SQL.ppt
04.SQL.ppt
 
Migration from mysql to elasticsearch
Migration from mysql to elasticsearchMigration from mysql to elasticsearch
Migration from mysql to elasticsearch
 
Sequel
SequelSequel
Sequel
 
Tour of Ecto March 2017 Dave Lucia
Tour of Ecto March 2017 Dave LuciaTour of Ecto March 2017 Dave Lucia
Tour of Ecto March 2017 Dave Lucia
 
Market Basket Analysis in R
Market Basket Analysis in RMarket Basket Analysis in R
Market Basket Analysis in R
 
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
SQL
SQLSQL
SQL
 
Ruby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersRuby on Rails: Tasty Burgers
Ruby on Rails: Tasty Burgers
 

Mehr von Leonardo Borges

Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015Leonardo Borges
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Leonardo Borges
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019Leonardo Borges
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library designLeonardo Borges
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptLeonardo Borges
 
Programação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncronoProgramação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncronoLeonardo Borges
 
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013Leonardo Borges
 
Intro to Clojure's core.async
Intro to Clojure's core.asyncIntro to Clojure's core.async
Intro to Clojure's core.asyncLeonardo Borges
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptLeonardo Borges
 
Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Leonardo Borges
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptLeonardo Borges
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Leonardo Borges
 

Mehr von Leonardo Borges (15)

Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
Programação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncronoProgramação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncrono
 
Monads in Clojure
Monads in ClojureMonads in Clojure
Monads in Clojure
 
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
 
Intro to Clojure's core.async
Intro to Clojure's core.asyncIntro to Clojure's core.async
Intro to Clojure's core.async
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
 
Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 

Arel in Rails 3

  • 1. Arel and Rails 3 Relational algebra meets ActiveRecord
  • 2. What!? • Relational Algebra deals with sets of finite relations, which are closed under certain operators. These operators operate on one or more relations to yield a relation. • Relation (table) - Data structure composed of a heading (columns) and an unordered set of tuples (rows) that share the same type. • Closure - A set is said to be closed under some operation if the result of that operation is a member of the set. • e.g.: Real numbers are closed under subtraction but natural numbers are not. Although 3 and 7 are natural numbers the result of 3 - 7 is not.
  • 3. Operators Primitive Derived Selection (WHERE) Set Intersection Projection (SELECT) Division Cross Join Natural Join Set Union Set Difference Rename (SELECT A as B)
  • 4. ActiveRecord::Relation Example Pub.select(:name).where(:city => 'Sydney') #yields an ActiveRecord::Relation instance. No SQL ran. but prior to Rails 3... Pub.find(:all, :select => "name", :conditions => { :city => 'Sydney' }) #yields an Array with the results
  • 5. Ok, but now what? Build more interesting queries by combining relations... > syd_pubs = Pub.select('pubs.name').where(:city => 'Sydney') > squire = Pub.joins(:beers).where(:beers => {:name => 'James Squire'}) Now get me all the pubs in sydney that sell James Squire! > (syd_pubs & squire).all # yields an Array
  • 6. Arel in Action > (syd_pubs & squire).all This causes ActiveRecord::Relation to ask Arel to build the SQL query below, corresponding to the combined relations: SELECT pubs.name FROM pubs INNER JOIN beers_pubs ON beers_pubs.pub_id = pubs.id INNER JOIN beers ON beers.id = beers_pubs.beer_id WHERE (pubs.city = 'Sydney') AND (beers.name = 'James Squire')
  • 7. Grouping and sorting data > pubs_beers = Pub.joins(:beers) > pubs = pubs_beers.select('pubs.name, count(*) as beers_count').group('pubs.name') > pubs.all[0].beers_count # 2 > pubs.order('beers_count').all
  • 8. Range Conditions > today = Time.now.at_beginning_of_day > tomorrow = Time.now.tomorrow.at_beginning_of_day > Pub.where(:created_at => today..tomorrow).all Arel takes care of ranges as well... SELECT pubs.* FROM pubs WHERE (pubs.created_at BETWEEN '2010-10-05 00:00:00.000000' AND '2010-10-06 00:00:00.000000')
  • 9. Scopes: Reusable Relations class Beer < ActiveRecord::Base scope :stout, where(:flavor => "Stout") end > Beer.stout.all # gives back an Array with the results
  • 10. Eager Loading Associations Associations are lazily loaded by default and as such... > pubs = Pub.all > pubs[0].beers > pubs[1].beers ...produces these queries to be executed: SELECT pubs.* FROM pubs SELECT * FROM beers INNER JOIN beers_pubs ON beers.id = beers_pubs.beer_id WHERE (beers_pubs.pub_id = 1 ) SELECT * FROM beers INNER JOIN beers_pubs ON beers.id = beers_pubs.beer_id WHERE (beers_pubs.pub_id = 2 )
  • 11. Eager Loading Associations Eager load what you need using the new relations syntax: > pubs = Pub.includes(:beers).all > pubs[0].beers > pubs[1].beers Note that only one query is used to load the Beers info: SELECT pubs.* FROM pubs SELECT beers.*, t0.pub_id as the_parent_record_id FROM beers INNER JOIN beers_pubs t0 ON beers.id = t0.beer_id WHERE (t0.pub_id IN (1,2,3))
  • 13. Q&A
  • 14. References • Arel - http://github.com/rails/arel • Rails - http://github.com/rails/rails • Rails Guides - http://guides.rubyonrails.org/ • Relational Algebra - http://en.wikipedia.org/wiki/Relational_algebra

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n