Skip to content

Commit

Permalink
Fix ambiguous column in search with ORDER BY
Browse files Browse the repository at this point in the history
This fixes an issue where columns whose names are not unique in a
search query cause a DB error when they're used as a sort column.
The issue can be observed in the contribution search when sorting
by contribution status.

The issue is resolved by using the where field of the column spec,
which holds the fully-qualified name of the column.
  • Loading branch information
pfigel committed Nov 21, 2019
1 parent 448b2c0 commit 452a21f
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion CRM/Contact/BAO/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -6477,7 +6477,10 @@ protected function prepareOrderBy($sort, $sortOrder) {
// Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
// this might give some early warning.
CRM_Utils_Type::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
$order = str_replace("$field", "field({$fieldSpec['name']},$fieldIDsInOrder)", $order);
// use where if it's set to fully qualify ambiguous column names
// i.e. civicrm_contribution.contribution_status_id instead of contribution_status_id
$pseudoColumnName = $fieldSpec['where'] ?? $fieldSpec['name'];
$order = str_replace("$field", "field($pseudoColumnName,$fieldIDsInOrder)", $order);
}
//CRM-12565 add "`" around $field if it is a pseudo constant
// This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
Expand Down

0 comments on commit 452a21f

Please sign in to comment.