From 452a21f77a2c57dddcb21aa60d8d6791542fed70 Mon Sep 17 00:00:00 2001 From: Patrick Figel Date: Thu, 21 Nov 2019 00:47:18 +0100 Subject: [PATCH] Fix ambiguous column in search with ORDER BY 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. --- CRM/Contact/BAO/Query.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CRM/Contact/BAO/Query.php b/CRM/Contact/BAO/Query.php index 6601418650..71b5dfbb79 100644 --- a/CRM/Contact/BAO/Query.php +++ b/CRM/Contact/BAO/Query.php @@ -6477,7 +6477,10 @@ AND displayRelType.is_active = 1 // 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. -- 2.25.1