Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

APIv4 - Automatically coalesce potentially null field values in equations #21647

Merged
merged 1 commit into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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']);
}

}