From 350c9750e29ec5ad5bebc18227f9d8a4675c25d2 Mon Sep 17 00:00:00 2001 From: Jordi Jolink Date: Sun, 20 Feb 2022 21:25:02 +0100 Subject: [PATCH] Add the possibility to force using an index --- .../DatabaseTypeTraits/MySQLTrait.php | 19 +++++++++++++++++-- Soneritics/Database/Query/QueryAbstract.php | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Soneritics/Database/DatabaseConnection/DatabaseTypeTraits/MySQLTrait.php b/Soneritics/Database/DatabaseConnection/DatabaseTypeTraits/MySQLTrait.php index b9857ca..e3c7cb4 100644 --- a/Soneritics/Database/DatabaseConnection/DatabaseTypeTraits/MySQLTrait.php +++ b/Soneritics/Database/DatabaseConnection/DatabaseTypeTraits/MySQLTrait.php @@ -161,8 +161,8 @@ protected function getTable(array $queryParts) $from = (isset($queryParts['fields']) && !empty($queryParts['fields'])) || strtoupper($queryParts['type']) === 'DELETE' ? - 'FROM ' : - ''; + 'FROM ' : + ''; if (is_a($queryParts['table'], 'Database\Table')) { $select = !empty($from) ? $from . '%s' : '%s'; @@ -304,6 +304,20 @@ protected function getGroup(array $queryParts) return null; } + /** + * Get a forced index. + * @param array $queryParts + * @return string|null + */ + protected function getIndex(array $queryParts) + { + if (!empty($queryParts['index'])) { + return 'USE INDEX (' . $this->quoteIdentifier($queryParts['index']) . ')'; + } + + return null; + } + /** * Prepare the order for use in the MySQL query. * @param array $queryParts @@ -360,6 +374,7 @@ public function buildQuery(QueryAbstract $query) $queryParts['type'], $this->getFields($queryParts), $this->getTable($queryParts), + $this->getIndex($queryParts), $this->getSet($queryParts), $this->getValues($queryParts), $this->getJoins($queryParts), diff --git a/Soneritics/Database/Query/QueryAbstract.php b/Soneritics/Database/Query/QueryAbstract.php index 0b2f10c..1059c90 100644 --- a/Soneritics/Database/Query/QueryAbstract.php +++ b/Soneritics/Database/Query/QueryAbstract.php @@ -49,6 +49,7 @@ abstract class QueryAbstract protected $group = []; protected $order = []; protected $limit = []; + protected $index = ""; protected $queryType = self::MODE_QUERY; /** @@ -114,6 +115,17 @@ public function execute() */ abstract public function getQueryType(); + /** + * Force an index. + * @param $index + * @return $this + */ + public function index($index) + { + $this->index = $index; + return $this; + } + /** * Set the fields to use in the query. * @@ -285,6 +297,10 @@ public function getQueryParts() $result['set'] = $this->set; } + if (!empty($this->index)) { + $result['index'] = $this->index; + } + if (!empty($this->joins)) { $result['join'] = $this->joins; }