Skip to content

Commit

Permalink
FIX Ambiguous column SQL error
Browse files Browse the repository at this point in the history
Specify the table for the field we’re fetching, in case a joined table has a field with the same name
  • Loading branch information
jonom committed Oct 19, 2016
1 parent 4c7ba73 commit b0445f7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
12 changes: 8 additions & 4 deletions model/DataQuery.php
Expand Up @@ -392,7 +392,8 @@ public function count() {
* automatically so must not contain double quotes.
*/
public function max($field) {
return $this->aggregate("MAX(\"$field\")");
$table = ClassInfo::table_for_object_field($this->dataClass, $field);
return $this->aggregate("MAX(\"$table\".\"$field\")");
}

/**
Expand All @@ -402,7 +403,8 @@ public function max($field) {
* automatically so must not contain double quotes.
*/
public function min($field) {
return $this->aggregate("MIN(\"$field\")");
$table = ClassInfo::table_for_object_field($this->dataClass, $field);
return $this->aggregate("MIN(\"$table\".\"$field\")");
}

/**
Expand All @@ -412,7 +414,8 @@ public function min($field) {
* automatically so must not contain double quotes.
*/
public function avg($field) {
return $this->aggregate("AVG(\"$field\")");
$table = ClassInfo::table_for_object_field($this->dataClass, $field);
return $this->aggregate("AVG(\"$table\".\"$field\")");
}

/**
Expand All @@ -422,7 +425,8 @@ public function avg($field) {
* automatically so must not contain double quotes.
*/
public function sum($field) {
return $this->aggregate("SUM(\"$field\")");
$table = ClassInfo::table_for_object_field($this->dataClass, $field);
return $this->aggregate("SUM(\"$table\".\"$field\")");
}

/**
Expand Down
11 changes: 11 additions & 0 deletions tests/model/DataListTest.php
Expand Up @@ -363,6 +363,17 @@ public function testMap() {
$this->assertEquals($otherExpected, $otherMap);
}

public function testAmbiguousAggregate() {
// Test that we avoid ambiguity error when a field exists on two joined tables
// Fetch the sponsors in a round-about way to simulate this
$teamID = $this->idFromFixture('DataObjectTest_Team','team2');
$sponsors = DataObjectTest_EquipmentCompany::get()->filter('SponsoredTeams.ID', $teamID);
$this->assertNotNull($sponsors->Max('ID'));
$this->assertNotNull($sponsors->Min('ID'));
$this->assertNotNull($sponsors->Avg('ID'));
$this->assertNotNull($sponsors->Sum('ID'));
}

public function testEach() {
$list = DataObjectTest_TeamComment::get();

Expand Down

0 comments on commit b0445f7

Please sign in to comment.