|
| 1 | +<?php |
| 2 | + |
| 3 | +/* Icinga DB Web | (c) 2025 Icinga GmbH | GPLv2 */ |
| 4 | + |
| 5 | +namespace Icinga\Module\Icingadb\Util; |
| 6 | + |
| 7 | +use Icinga\Application\Config; |
| 8 | +use ipl\Orm\Query; |
| 9 | +use ipl\Sql\Adapter\Mysql; |
| 10 | +use ipl\Sql\Select; |
| 11 | +use ipl\Stdlib\Str; |
| 12 | + |
| 13 | +/** |
| 14 | + * Helper class to allow disabling the MySQL/MariaDB query optimizer for history queries. |
| 15 | + * Some versions of these RDBMS perform poorly with history queries, |
| 16 | + * particularly when the optimizer changes join order or uses block nested loop joins. |
| 17 | + * Ideally, testing across all RDBMS versions to identify when the optimizer fails and adjusting queries or |
| 18 | + * using optimizer switches would be preferable, but this level of effort is not justified at the moment. |
| 19 | + */ |
| 20 | +readonly class OptimizerHints |
| 21 | +{ |
| 22 | + public const DISABLE_OPTIMIZER_HINT = '/*+ NO_BNL() */ STRAIGHT_JOIN'; |
| 23 | + |
| 24 | + /** |
| 25 | + * If optimizer disabling is enabled for history queries, |
| 26 | + * injects an optimizer hint into SELECT queries for a MySQL/MariaDB Query object, |
| 27 | + * forcing the RDBMS to disable the optimizer |
| 28 | + * |
| 29 | + * @param Query $q |
| 30 | + * |
| 31 | + * @return void |
| 32 | + */ |
| 33 | + public static function disableOptimizerForHistoryQueries(Query $q): void |
| 34 | + { |
| 35 | + if (static::shouldDisableOptimizerForHistoryQueries() && $q->getDb()->getAdapter() instanceof Mysql) { |
| 36 | + // Locates the first string column, prepends the optimizer hint, |
| 37 | + // and resets columns to ensure it appears first in the SELECT statement: |
| 38 | + $q->on(Query::ON_SELECT_ASSEMBLED, static function (Select $select) { |
| 39 | + $columns = $select->getColumns(); |
| 40 | + foreach ($columns as $alias => $column) { |
| 41 | + if (is_string($column)) { |
| 42 | + if (Str::startsWith($column, static::DISABLE_OPTIMIZER_HINT)) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + unset($columns[$alias]); |
| 47 | + $select->resetColumns(); |
| 48 | + |
| 49 | + if (is_int($alias)) { |
| 50 | + array_unshift($columns, static::DISABLE_OPTIMIZER_HINT . " $column"); |
| 51 | + } else { |
| 52 | + $columns = [$alias => static::DISABLE_OPTIMIZER_HINT . " $column"] + $columns; |
| 53 | + } |
| 54 | + |
| 55 | + $select->resetColumns()->columns($columns); |
| 56 | + |
| 57 | + return; |
| 58 | + } |
| 59 | + } |
| 60 | + }); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Determines whether to disable the query optimizer for history queries. |
| 66 | + * |
| 67 | + * @return bool |
| 68 | + */ |
| 69 | + protected static function shouldDisableOptimizerForHistoryQueries(): bool |
| 70 | + { |
| 71 | + return Config::module('icingadb')->get('icingadb', 'disable_optimizer_for_history_queries', false); |
| 72 | + } |
| 73 | +} |
0 commit comments