Skip to content

Commit

Permalink
APIv4 - Automatically coalesce potentially null field values in equat…
Browse files Browse the repository at this point in the history
…ions
  • Loading branch information
colemanw committed Sep 28, 2021
1 parent fec18e1 commit a2086e2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
12 changes: 11 additions & 1 deletion Civi/Api4/Query/SqlEquation.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,17 @@ protected function initialize() {
public function render(array $fieldList): string {
$output = [];
foreach ($this->args as $arg) {
$output[] = is_string($arg) ? $arg : $arg->render($fieldList);
// Just an operator
if (is_string($arg)) {
$output[] = $arg;
}
// Surround fields with COALESCE to handle null values
elseif (is_a($arg, SqlField::class)) {
$output[] = 'COALESCE(' . $arg->render($fieldList) . ', 0)';
}
else {
$output[] = $arg->render($fieldList);
}
}
return '(' . implode(' ', $output) . ')';
}
Expand Down
4 changes: 4 additions & 0 deletions tests/phpunit/api/v4/Action/SqlExpressionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,10 @@ public function testSelectEquations() {
'(5 > 11) AS five_greater_eleven',
'(5 <= 11) AS five_less_eleven',
'(1 BETWEEN 0 AND contact_id) AS is_between',
// These fields don't exist
'(illegal * stuff) AS illegal_stuff',
// This field will be null
'(hold_date + 5) AS null_plus_five',
])
->addWhere('contact_id', '=', $contact['id'])
->setLimit(1)
Expand All @@ -121,6 +124,7 @@ public function testSelectEquations() {
$this->assertTrue($result['five_less_eleven']);
$this->assertTrue($result['is_between']);
$this->assertArrayNotHasKey('illegal_stuff', $result);
$this->assertEquals('5', $result['null_plus_five']);
}

}

0 comments on commit a2086e2

Please sign in to comment.