phpmysqldoctrine-orm

Index hinting in Doctrine2


Is there a way to hint the use of an index in Doctrine2? The equivalent of the MySQL USE INDEX syntax:

SELECT * FROM user u USE INDEX(my_super_index) ...

Solution

  • I found a gist with working code using a custom tree walker: https://gist.github.com/arnaud-lb/2704404

    Thanks to the author!

    It will not work for RDBMS using a different syntax than MySQL though.

    Update: The previous code does not work for queries with multiple tables in the FROM clause. So here is my updated version of the previous walker:

    <?php
    
    namespace __YOUR_NAMESPACE_;
    
    use Doctrine\ORM\Query\SqlWalker;
    
    class UseIndexWalker extends SqlWalker
    {
        const HINT_USE_INDEX = 'UseIndexWalker.UseIndex';
    
        public function walkFromClause($fromClause)
        {
            $sql = parent::walkFromClause($fromClause);
            $index = $this->getQuery()->getHint(self::HINT_USE_INDEX);
    
            return preg_replace('/( INNER JOIN| LEFT JOIN|$)/', sprintf(' USE INDEX(%s)\1', $index), $sql, 1);
        }
    }