packages/sql-semantics-mysql/src/Lowering/Dispatch/OptimizerHints.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Lowering\Dispatch;
6
7use SqlParser\Lexer\Token;
8use SqlParser\Parser\Node;
9
10/**
11 * Finds optimizer hint comments, which the parser delivers as trivia and no rule can read yet.
12 *
13 * Rule: MYSQL-OPTIMIZER-HINTS-001. From MySQL 5.7.7 on, the server reads a
14 * comment that starts with `/*+` and follows, after whitespace only, one of
15 * the keywords SELECT, INSERT, REPLACE, UPDATE or DELETE as a list of
16 * optimizer hints of the statement; a hint changes the request, for example
17 * `SET_VAR` or `MAX_EXECUTION_TIME`. The parser of this library has no hint
18 * grammar: the comment is part of the whitespace before the next token. A
19 * statement with such a comment therefore has a part no rule structures,
20 * and the lowering reports it as a missing rule instead of dropping it. In
21 * MySQL 5.6 the comment is an ordinary comment. Terminates: one iterative
22 * pass over the tokens.
23 * Source: https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html.
24 * Status: Specified.
25 *
26 * @visibility SqlSemantics\Platform\MySql
27 */
28final class OptimizerHints
29{
30    /**
31     * The terminals after which the server reads a hint comment, in every release.
32     */
33    private const KEYWORDS = ['SELECT_SYM' => true, 'INSERT' => true, 'INSERT_SYM' => true, 'REPLACE' => true, 'REPLACE_SYM' => true, 'UPDATE_SYM' => true, 'DELETE_SYM' => true];
34
35    /**
36     * Answers the first hint comment of a parse tree, or null when it has none.
37     */
38    public function first(Node $tree): ?string
39    {
40        $pending = [$tree];
41        $previous = null;
42        while ($pending !== []) {
43            $current = array_pop($pending);
44            if ($current instanceof Node) {
45                for ($index = count($current->children) - 1; $index >= 0; $index--) {
46                    $pending[] = $current->children[$index];
47                }
48                continue;
49            }
50            if ($previous instanceof Token && isset(self::KEYWORDS[$previous->name]) && str_starts_with(ltrim($current->leading), '/*+')) {
51                return ltrim($current->leading);
52            }
53            $previous = $current;
54        }
55
56        return null;
57    }
58}
59