rails/arel — pull request #300 by jpcody (2014-07-27 03:49:29+00:00)
Title: Allow for alias omission in aggregate expressions

This fix should be backwards-compatible, but I'm not confident it's being fixed at the appropriate level.

When using aggregate expressions in a `HAVING` claus, an alias was forced, causing a syntax error in Postgres. The following Arel:

```RUBY
posts.
join(comments).on(posts[:id].eq(comments[:post_id])).
having(comments[:rating].average.gt(90)).
project(Arel.star).
to_sql
```

Produces:

```SQL
SELECT * FROM "posts" INNER JOIN "comments" ON "posts"."id" = "comments"."post_id" HAVING AVG("comments"."rating") AS avg_id > 90
```

Which leads to the following error: `ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "AS"` because Postgres (and maybe others?) disallows aliases in `HAVING` clauses.

This fix allows these aggregate functions to take an optional argument that can either override the `avg_id` default string or be nil to skip the alias altogether, while maintaining the default behavior.