2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Analyzes a query and gives user feedback.
8 if (! defined('PHPMYADMIN')) {
21 * Gets the starting position of each line.
23 * @param string $str String to be analyzed.
27 public static function getLines($str)
31 // The reason for using the '8bit' parameter is that the length
32 // required is the length in bytes, not characters.
34 // Given the following string: `????+`, where `?` represents a
35 // multi-byte character (lets assume that every `?` is a 2-byte
36 // character) and `+` is a newline, the first value of `$i` is `0` and
37 // the last one is `4` (because there are 5 characters). Bytes `$str[0]`
38 // and `$str[1]` are the first character, `$str[2]` and `$str[3]` are
39 // the second one and `$str[4]` is going to be the first byte of the
40 // third character. The fourth and the last one (which is actually a new
41 // line) aren't going to be processed at all.
42 for ($i = 0, $len = /*overload*/mb_strlen($str, '8bit'); $i < $len; ++
$i) {
43 if ($str[$i] === "\n") {
51 * Computes the number of the line and column given an absolute position.
53 * @param array $lines The starting position of each line.
54 * @param int $pos The absolute position
58 public static function findLineNumberAndColumn($lines, $pos)
61 foreach ($lines as $lineNo => $lineStart) {
62 if ($lineStart > $pos) {
67 return array($line, $pos - $lines[$line]);
71 * Runs the linting process.
73 * @param string $query The query to be checked.
77 public static function lint($query)
79 // Disabling lint for huge queries to save some resources.
80 if (/*overload*/mb_strlen($query) > 10000) {
83 'message' => __('Linting is disabled for this query because it exceeds the maximum length.'),
88 'severity' => 'warning',
94 * Lexer used for tokenizing the query.
96 * @var SqlParser\Lexer
98 $lexer = new SqlParser\
Lexer($query);
101 * Parsed used for analysing the query.
103 * @var SqlParser\Parser
105 $parser = new SqlParser\
Parser($lexer->list);
108 * Array containing all errors.
112 $errors = SqlParser\Utils\Error
::get(array($lexer, $parser));
115 * The response containing of all errors.
122 * The starting position for each line.
124 * CodeMirror requires relative position to line, but the parser stores
125 * only the absolute position of the character in string.
129 $lines = static::getLines($query);
131 // Building the response.
132 foreach ($errors as $idx => $error) {
134 // Starting position of the string that caused the error.
135 list($fromLine, $fromColumn) = static::findLineNumberAndColumn(
139 // Ending position of the string that caused the error.
140 list($toLine, $toColumn) = static::findLineNumberAndColumn(
141 $lines, $error[3] +
/*overload*/mb_strlen($error[2])
144 // Building the response.
146 'message' => sprintf(
147 __('%1$s (near <code>%2$s</code>)'),
150 'fromLine' => $fromLine,
151 'fromColumn' => $fromColumn,
153 'toColumn' => $toColumn,
154 'severity' => 'error',
158 // Sending back the answer.