4

Rails avoids queries when performing calculations on contradictory relation

 2 years ago
source link: https://blog.saeloun.com/2022/07/20/rails-avoid-query-for-contradictory-relation
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Rails avoids queries when performing calculations on contradictory relation

Jul 20, 2022 , by Murtaza Bagwala

1 minute read

Previously, relation calculations such as count would make a query even when passed a contradiction, contradiction relation means passing an empty array for eg:-

  User.where(id: []).count

It does not make sense to call a database for such contradictory relations.

Before

So, before Rails 7 was introduced, the database was called if the relation used for count, sum, average, minimum and maximum would be contradictory.

  => Product.where(title: []).count
  Product Count (4.7ms)  SELECT COUNT(*) FROM "products" WHERE 1=0
  => 0 


  => Product.where(title: []).sum(:price)
  Product Sum (17.5ms)  SELECT SUM("products"."price") FROM "products" WHERE 1=0
  => 0 


  => Product.where(title: []).average(:price)
  Product Average (3.5ms)  SELECT AVG("products"."price") FROM "products" WHERE 1=0
  => nil 


  => Product.where(title: []).minimum(:id)
  Product Minimum (5.0ms)  SELECT MIN("products"."id") FROM "products" WHERE 1=0
  => nil 


  => Product.where(title: []).maximum(:id)
  Product Minimum (5.0ms)  SELECT MAX("products"."id") FROM "products" WHERE 1=0
  => nil 

As it can be seen, it would make a query to the database even when passed a contradiction.

After

Now after Rails 7, it avoids making a query to the database.

  => Product.where(title: []).count
  => 0 


  => Product.where(title: []).sum(:price)
  => 0 


  => Product.where(title: []).average(:price)
  => nil 


  => Product.where(title: []).minimum(:id)
  => nil 


  => Product.where(title: []).maximum(:id)
  => nil  

Check out the PR for more details.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK