Skip to content

Commit

Permalink
Remove empty dataset from graph export file (centreon#11680)
Browse files Browse the repository at this point in the history
* Remove empty dataset from graph export file

* Optimize data_bin request for metrics extraction
  • Loading branch information
TamazC authored Sep 6, 2022
1 parent cd9f73f commit 3231348
Showing 1 changed file with 27 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,8 @@ public function findDataByMetricsAndDates(
$this->db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$this->db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);

$columns = ['ctime AS time'];
$pattern = 'AVG(CASE WHEN id_metric = %d THEN `value` end) AS %s';
foreach ($metrics as $metric) {
$columns[] = sprintf($pattern, $metric->getId(), $metric->getName());
}

$query = sprintf(
'SELECT %s FROM `:dbstg`.data_bin WHERE ctime >= :start AND ctime < :end GROUP BY time',
join(',', $columns)
);

$query = $this->generateDataBinQuery($metrics);
$statement = $this->db->prepare($this->translateDbName($query));

$statement->bindValue(':start', $startDate->getTimestamp(), PDO::PARAM_INT);
$statement->bindValue(':end', $endDate->getTimestamp(), PDO::PARAM_INT);
$statement->execute();
Expand All @@ -80,6 +69,32 @@ public function findDataByMetricsAndDates(
$statement->closeCursor();
}

/**
* Generates SQL query statement to extract metric data from table data_bin
*
* @param array<Metric> $metrics
* @return string
*/
private function generateDataBinQuery(array $metrics): string
{
$metricIds = [];
$subQueryColumns = [];
$subQueryPattern = 'AVG(CASE WHEN id_metric = %d THEN `value` end) AS %s';
foreach ($metrics as $metric) {
$subQueryColumns[] = sprintf($subQueryPattern, $metric->getId(), $metric->getName());
$metricIds[] = $metric->getId();
}

$pattern = 'SELECT %s FROM `:dbstg`.data_bin WHERE ';
$pattern .= ' ctime >= :start AND ctime < :end AND id_metric IN (%s) GROUP BY time';

return sprintf(
$pattern,
join(', ', ['ctime AS time', ...$subQueryColumns]),
join(',', $metricIds)
);
}

/**
* @param array<string, int|string> $dataBin
*/
Expand Down

0 comments on commit 3231348

Please sign in to comment.