Skip to content

Commit

Permalink
Add the possibility to force using an index
Browse files Browse the repository at this point in the history
  • Loading branch information
Soneritics committed Feb 20, 2022
1 parent 20cb74f commit 350c975
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down
16 changes: 16 additions & 0 deletions Soneritics/Database/Query/QueryAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ abstract class QueryAbstract
protected $group = [];
protected $order = [];
protected $limit = [];
protected $index = "";
protected $queryType = self::MODE_QUERY;

/**
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
}
Expand Down

0 comments on commit 350c975

Please sign in to comment.