silverstripe/silverstripe-framework — pull request #2477 by tractorcow (2013-10-03 01:31:01+00:00)
Title: BUG Sort column order maintained correctly when using expressions

When an expression (such as `MAX(Name)` or `MID(Title, 0, 1)`) is used in a sort column (and is substituted with a _SortColumn0 alias) then the precendence of sort SQL fragments is not maintained. This causes unexpected behaviour when multiple sorts are used.

Both `SQLQuery` and `DataQuery` have this bug, although each were broken in different ways. `DataQuery` would move basic sorts to the end of the list (by unsetting the key and setting it again). `SQLQuery` would perform the same, but with the expression sort.

The problem is that simply setting a key and resetting immediately after in an array does not maintain order.

The below solution uses temporary arrays to maintain the precedence of sort fragments.

Tests included.