Skip to content
  • Petrik's avatar
    1f83af38
    Add `explain` support for methods like `last`, `pluck` and `count` · 1f83af38
    Petrik authored
    
    
    `explain` can be called on a relation to explain how the database would
    execute a query. Currently `explain` doesn't work for queries using
    `last`, `pluck` or `count`, as these return the actual result instead of
    a relation. This makes it difficult to optimize these queries.
    
    By letting `explain` return a proxy instead, we can support these
    methods.
    
    ```ruby
    User.all.explain.count
    \# => "EXPLAIN SELECT COUNT(*) FROM `users`"
    
    User.all.explain.maximum(:id)
    \# => "EXPLAIN SELECT MAX(`users`.`id`) FROM `users`"
    ```
    
    This breaks the existing behaviour in that it requires calling inspect
    after explain.
    
    ```ruby
    User.all.explain.inspect
    \# => "EXPLAIN SELECT `users`.* FROM `users`"
    ```
    
    However, as `explain` is mostly used from the commandline, this won't be a
    problem as inspect is called automatically in IRB.
    
    Co-authored-by: default avatarRafael Mendonça França <rafael@rubyonrails.org>
    1f83af38
    Add `explain` support for methods like `last`, `pluck` and `count`
    Petrik authored
    
    
    `explain` can be called on a relation to explain how the database would
    execute a query. Currently `explain` doesn't work for queries using
    `last`, `pluck` or `count`, as these return the actual result instead of
    a relation. This makes it difficult to optimize these queries.
    
    By letting `explain` return a proxy instead, we can support these
    methods.
    
    ```ruby
    User.all.explain.count
    \# => "EXPLAIN SELECT COUNT(*) FROM `users`"
    
    User.all.explain.maximum(:id)
    \# => "EXPLAIN SELECT MAX(`users`.`id`) FROM `users`"
    ```
    
    This breaks the existing behaviour in that it requires calling inspect
    after explain.
    
    ```ruby
    User.all.explain.inspect
    \# => "EXPLAIN SELECT `users`.* FROM `users`"
    ```
    
    However, as `explain` is mostly used from the commandline, this won't be a
    problem as inspect is called automatically in IRB.
    
    Co-authored-by: default avatarRafael Mendonça França <rafael@rubyonrails.org>
Loading