MountainRoseHerbs/spree — pull request #41 by mbj (2014-12-10 01:40:15+00:00)
Title: Fix backend order query only to use distinct when needed

* This fixes most of the cases for redundant distinct usage. There may
be more. But these are most common and most pressing on the DB size we
have.

Before:

```
(325.6ms) SELECT DISTINCT COUNT(DISTINCT "spree_orders"."id") FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NOT NULL
(0.9ms) SELECT COUNT(DISTINCT count_column) FROM (SELECT DISTINCT "spree_orders"."id" AS count_column FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NOT NULL LIMIT 15 OFFSET 0) subquery_for_count
Spree::Order Load (596.3ms) SELECT DISTINCT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NOT NULL ORDER BY "spree_orders"."completed_at" DESC LIMIT 15 OFFSET 0
```

After:

```
(156.6ms) SELECT COUNT(*) FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NOT NULL
(0.5ms) SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NOT NULL LIMIT 15 OFFSET 0) subquery_for_count
Spree::Order Load (0.6ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NOT NULL ORDER BY "spree_orders"."completed_at" DESC LIMIT 15 OFFSET 0
```

As there is no semantic change cannot right now think about a meaningful test we could add. Asseting the generation of SQL queries comes in mind, but AR is not really prepered for this. With an in-memory adapter we might be able to do this in an ideal way.