The 'distinct' and 'add_order_by_for_association_limiting' methods in the PostgreSQL adaptor assume that incoming 'order by' clauses can be parsed simply by splitting on commas. This fails whenever a more complex expression is passed involving multiple columns with one or more function calls having multiple arguments.
For example, the code
Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => "COALESCE(UPPER(posts.title), 'No Title') DESC, posts.id", :limit => 2, :offset => 1)
will result in broken SQL as ActiveRecord tries to associate aliases with all the "columns" that it finds including the arguments to COALESCE which it will see as two columns instead of one column that is modified by a function.
I have documented the issue and submitted a patch that resolves it here: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2622-postgresql-adapter-breaks-on-complex-order-by-clauses
I now need feedback for the patch.
Thanks!