2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /** SQL Parser Functions for phpMyAdmin
5 * These functions define an SQL parser system, capable of understanding and
6 * extracting data from a MySQL type SQL query.
8 * The basic procedure for using the new SQL parser:
9 * On any page that needs to extract data from a query or to pretty-print a
10 * query, you need code like this up at the top:
12 * ($sql contains the query)
13 * $parsed_sql = PMA_SQP_parse($sql);
15 * If you want to extract data from it then, you just need to run
16 * $sql_info = PMA_SQP_analyze($parsed_sql);
18 * See comments in PMA_SQP_analyze for the returned info
21 * If you want a pretty-printed version of the query, do:
22 * $string = PMA_SQP_format($parsed_sql);
23 * (note that that you need to have syntax.css.php included somehow in your
24 * page for it to work, I recommend '<link rel="stylesheet" type="text/css"
25 * href="syntax.css.php" />' at the moment.)
29 if (! defined('PHPMYADMIN')) {
34 * Include the string library as we use it heavily
36 require_once './libraries/string.lib.php';
39 * Include data for the SQL Parser
41 require_once './libraries/sqlparser.data.php';
46 if (!defined('TESTSUITE')) {
47 include_once './libraries/mysql_charsets.inc.php';
49 if (! isset($mysql_charsets)) {
50 $mysql_charsets = array();
51 $mysql_collations_flat = array();
55 * Stores parsed elemented of query to array.
57 * Currently we don't need the $pos (token position in query)
58 * for other purposes than LIMIT clause verification,
59 * so many calls to this function do not include the 4th parameter
61 * @param array &$arr Array to store element
62 * @param string $type Type of element
63 * @param string $data Data (text) of element
64 * @param int &$arrsize Size of array
65 * @param int $pos Position of an element
69 function PMA_SQP_arrayAdd(&$arr, $type, $data, &$arrsize, $pos = 0)
71 $arr[] = array('type' => $type, 'data' => $data, 'pos' => $pos);
73 } // end of the "PMA_SQP_arrayAdd()" function
76 * Reset the error variable for the SQL parser
82 function PMA_SQP_resetError()
84 global $SQP_errorString;
85 $SQP_errorString = '';
86 unset($SQP_errorString);
90 * Get the contents of the error variable for the SQL parser
92 * @return string Error string from SQL parser
96 function PMA_SQP_getErrorString()
98 global $SQP_errorString;
99 return isset($SQP_errorString) ?
$SQP_errorString : '';
103 * Check if the SQL parser hit an error
105 * @return boolean error state
109 function PMA_SQP_isError()
111 global $SQP_errorString;
112 return isset($SQP_errorString) && !empty($SQP_errorString);
116 * Set an error message for the system
118 * @param string $message The error message
119 * @param string $sql The failing SQL query
124 * @scope SQL Parser internal
126 function PMA_SQP_throwError($message, $sql)
128 global $SQP_errorString;
129 $SQP_errorString = '<p>'
131 'There seems to be an error in your SQL query. The MySQL server '
132 . 'error output below, if there is any, may also help you in '
133 . 'diagnosing the problem'
137 . 'ERROR: ' . $message . "\n"
138 . 'SQL: ' . htmlspecialchars($sql) . "\n"
141 } // end of the "PMA_SQP_throwError()" function
145 * Do display the bug report
147 * @param string $message The error message
148 * @param string $sql The failing SQL query
154 function PMA_SQP_bug($message, $sql)
156 global $SQP_errorString;
157 $debugstr = 'ERROR: ' . $message . "\n";
158 $debugstr .= 'MySQL: '.PMA_MYSQL_STR_VERSION
. "\n";
159 $debugstr .= 'USR OS, AGENT, VER: ' . PMA_USR_OS
. ' ';
160 $debugstr .= PMA_USR_BROWSER_AGENT
. ' ' . PMA_USR_BROWSER_VER
. "\n";
161 $debugstr .= 'PMA: ' . PMA_VERSION
. "\n";
162 $debugstr .= 'PHP VER,OS: ' . PMA_PHP_STR_VERSION
. ' ' . PHP_OS
. "\n";
163 $debugstr .= 'LANG: ' . $GLOBALS['lang'] . "\n";
164 $debugstr .= 'SQL: ' . htmlspecialchars($sql);
166 $encodedstr = $debugstr;
167 if (@function_exists
('gzcompress')) {
168 $encodedstr = gzcompress($debugstr, 9);
170 $encodedstr = preg_replace(
171 "/(\015\012)|(\015)|(\012)/",
173 chunk_split(base64_encode($encodedstr))
177 $SQP_errorString .= __(
178 'There is a chance that you may have found a bug in the SQL parser. '
179 . 'Please examine your query closely, and check that the quotes are '
180 . 'correct and not mis-matched. Other possible failure causes may be '
181 . 'that you are uploading a file with binary outside of a quoted text '
182 . 'area. You can also try your query on the MySQL command line '
183 . 'interface. The MySQL server error output below, if there is any, '
184 . 'may also help you in diagnosing the problem. If you still have '
185 . 'problems or if the parser fails where the command line interface '
186 . 'succeeds, please reduce your SQL query input to the single query '
187 . 'that causes problems, and submit a bug report with the data chunk '
188 . 'in the CUT section below:'
190 $SQP_errorString .= '<br />' . "\n"
191 . '----' . __('BEGIN CUT') . '----' . '<br />' . "\n"
193 . '----' . __('END CUT') . '----' . '<br />' . "\n";
195 $SQP_errorString .= '----' . __('BEGIN RAW') . '----<br />' . "\n"
199 . '----' . __('END RAW') . '----<br />' . "\n";
201 } // end of the "PMA_SQP_bug()" function
205 * Parses the SQL queries
207 * @param string $sql The SQL query list
209 * @return mixed Most of times, nothing...
211 * @global array The current PMA configuration
212 * @global array MySQL column attributes
213 * @global array MySQL reserved words
214 * @global array MySQL column types
215 * @global array MySQL function names
216 * @global array List of available character sets
217 * @global array List of available collations
221 function PMA_SQP_parse($sql)
223 static $PMA_SQPdata_column_attrib, $PMA_SQPdata_reserved_word;
224 static $PMA_SQPdata_column_type;
225 static $PMA_SQPdata_function_name, $PMA_SQPdata_forbidden_word;
226 global $mysql_charsets, $mysql_collations_flat;
228 // Convert all line feeds to Unix style
229 $sql = str_replace("\r\n", "\n", $sql);
230 $sql = str_replace("\r", "\n", $sql);
232 $len = PMA_strlen($sql);
237 // Create local hashtables
238 if (!isset($PMA_SQPdata_column_attrib)) {
239 $PMA_SQPdata_column_attrib = array_flip(
240 $GLOBALS['PMA_SQPdata_column_attrib']
242 $PMA_SQPdata_function_name = array_flip(
243 $GLOBALS['PMA_SQPdata_function_name']
245 $PMA_SQPdata_reserved_word = array_flip(
246 $GLOBALS['PMA_SQPdata_reserved_word']
248 $PMA_SQPdata_forbidden_word = array_flip(
249 $GLOBALS['PMA_SQPdata_forbidden_word']
251 $PMA_SQPdata_column_type = array_flip(
252 $GLOBALS['PMA_SQPdata_column_type']
256 $sql_array = array();
257 $sql_array['raw'] = $sql;
260 $punct_queryend = ';';
261 $punct_qualifier = '.';
262 $punct_listsep = ',';
263 $punct_level_plus = '(';
264 $punct_level_minus = ')';
266 $digit_floatdecimal = '.';
268 $bracket_list = '()[]{}';
269 $allpunct_list = '-,;:!?/.^~\*&%+<=>|';
270 $allpunct_list_pair = array(
283 $quote_list = '\'"`';
286 $previous_was_space = false;
287 $this_was_space = false;
288 $previous_was_bracket = false;
289 $this_was_bracket = false;
290 $previous_was_punct = false;
291 $this_was_punct = false;
292 $previous_was_listsep = false;
293 $this_was_listsep = false;
294 $previous_was_quote = false;
295 $this_was_quote = false;
297 while ($count2 < $len) {
298 $c = PMA_substr($sql, $count2, 1);
301 $previous_was_space = $this_was_space;
302 $this_was_space = false;
303 $previous_was_bracket = $this_was_bracket;
304 $this_was_bracket = false;
305 $previous_was_punct = $this_was_punct;
306 $this_was_punct = false;
307 $previous_was_listsep = $this_was_listsep;
308 $this_was_listsep = false;
309 $previous_was_quote = $this_was_quote;
310 $this_was_quote = false;
313 $this_was_space = true;
315 PMA_SQP_arrayAdd($sql_array, 'white_newline', '', $arraysize);
319 // Checks for white space
320 if (PMA_STR_isSpace($c)) {
321 $this_was_space = true;
326 // Checks for comment lines.
330 $next_c = PMA_substr($sql, $count2 +
1, 1);
332 ||
(($count2 +
1 < $len) && ($c == '/') && ($next_c == '*'))
333 ||
(($count2 +
2 == $len) && ($c == '-') && ($next_c == '-'))
334 ||
(($count2 +
2 < $len) && ($c == '-') && ($next_c == '-') && ((PMA_substr($sql, $count2 +
2, 1) <= ' ')))
344 $pos = PMA_strpos($sql, "\n", $count2);
348 $pos = PMA_strpos($sql, '*/', $count2);
354 $count2 = ($pos < $count2) ?
$len : $pos;
355 $str = PMA_substr($sql, $count1, $count2 - $count1);
356 PMA_SQP_arrayAdd($sql_array, 'comment_' . $type, $str, $arraysize);
360 // Checks for something inside quotation marks
361 if (PMA_strpos($quote_list, $c) !== false) {
362 $startquotepos = $count2;
369 $pos = PMA_strpos(' ' . $sql, $quotetype, $oldpos +
1) - 1;
374 * Behave same as MySQL and accept end of query as end
376 * I know this is sick, but MySQL behaves like this:
378 * SELECT * FROM `table
382 * SELECT * FROM `table`
384 $pos_quote_separator = PMA_strpos(
385 ' ' . $sql, $GLOBALS['sql_delimiter'], $oldpos +
1
387 if ($pos_quote_separator < 0) {
390 $sql_array['raw'] .= '`';
394 $sql = PMA_substr($sql, 0, $pos_quote_separator)
395 . '`' . PMA_substr($sql, $pos_quote_separator);
396 $sql_array['raw'] = $sql;
397 $pos = $pos_quote_separator;
399 if (class_exists('PMA_Message')
400 && $GLOBALS['is_ajax_request'] != true
403 __('Automatically appended backtick to the end of query!')
407 $debugstr = __('Unclosed quote')
408 . ' @ ' . $startquotepos. "\n"
409 . 'STR: ' . htmlspecialchars($quotetype);
410 PMA_SQP_throwError($debugstr, $sql);
415 // If the quote is the first character, it can't be
416 // escaped, so don't do the rest of the code
421 // Checks for MySQL escaping using a \
422 // And checks for ANSI escaping using the $quotetype character
424 && PMA_STR_charIsEscaped($sql, $pos)
429 } elseif (($pos +
1 < $len)
430 && (PMA_substr($sql, $pos, 1) == $quotetype)
431 && (PMA_substr($sql, $pos +
1, 1) == $quotetype)
438 } while ($len > $pos); // end do
443 switch ($quotetype) {
446 $this_was_quote = true;
450 $this_was_quote = true;
454 $this_was_quote = true;
459 $data = PMA_substr($sql, $count1, $count2 - $count1);
460 PMA_SQP_arrayAdd($sql_array, $type, $data, $arraysize);
464 // Checks for brackets
465 if (PMA_strpos($bracket_list, $c) !== false) {
466 // All bracket tokens are only one item long
467 $this_was_bracket = true;
470 if (PMA_strpos('([{', $c) !== false) {
473 $type_type = 'close';
477 if (PMA_strpos('()', $c) !== false) {
478 $type_style = 'round';
479 } elseif (PMA_strpos('[]', $c) !== false) {
480 $type_style = 'square';
482 $type_style = 'curly';
485 $type = 'punct_bracket_' . $type_type . '_' . $type_style;
486 PMA_SQP_arrayAdd($sql_array, $type, $c, $arraysize);
492 var_dump(PMA_STR_isSqlIdentifier($c, false));
495 var_dump(PMA_STR_isDigit(PMA_substr($sql, $count2 + 1, 1)));
496 var_dump($previous_was_space);
497 var_dump($previous_was_bracket);
498 var_dump($previous_was_listsep);
502 // Checks for identifier (alpha or numeric)
503 if (PMA_STR_isSqlIdentifier($c, false)
506 && PMA_STR_isDigit(PMA_substr($sql, $count2 +
1, 1))
507 && ($previous_was_space ||
$previous_was_bracket ||
$previous_was_listsep))
510 echo PMA_substr($sql, $count2);
517 * @todo a @ can also be present in expressions like
518 * FROM 'user'@'%' or TO 'user'@'%'
519 * in this case, the @ is wrongly marked as alpha_variable
521 $is_identifier = $previous_was_punct;
522 $is_sql_variable = $c == '@' && ! $previous_was_quote;
523 $is_user = $c == '@' && $previous_was_quote;
527 && PMA_STR_isDigit($c)
533 && PMA_substr($sql, $count2, 1) == 'x'
535 $is_float_digit = $c == '.';
536 $is_float_digit_exponent = false;
540 var_dump($is_identifier);
541 var_dump($is_sql_variable);
543 var_dump($is_float_digit);
547 // Fast skip is especially needed for huge BLOB data
550 $pos = strspn($sql, '0123456789abcdefABCDEF', $count2);
551 if ($pos > $count2) {
555 } elseif ($is_digit) {
556 $pos = strspn($sql, '0123456789', $count2);
557 if ($pos > $count2) {
563 while (($count2 < $len) && PMA_STR_isSqlIdentifier(PMA_substr($sql, $count2, 1), ($is_sql_variable ||
$is_digit))) {
564 $c2 = PMA_substr($sql, $count2, 1);
565 if ($is_sql_variable && ($c2 == '.')) {
569 if ($is_digit && (!$is_hex_digit) && ($c2 == '.')) {
571 if (!$is_float_digit) {
572 $is_float_digit = true;
575 $debugstr = __('Invalid Identifer')
576 . ' @ ' . ($count1+
1) . "\n"
577 . 'STR: ' . htmlspecialchars(
578 PMA_substr($sql, $count1, $count2 - $count1)
580 PMA_SQP_throwError($debugstr, $sql);
584 if ($is_digit && (!$is_hex_digit) && (($c2 == 'e') ||
($c2 == 'E'))) {
585 if (!$is_float_digit_exponent) {
586 $is_float_digit_exponent = true;
587 $is_float_digit = true;
592 $is_float_digit = false;
595 if (($is_hex_digit && PMA_STR_isHexDigit($c2)) ||
($is_digit && PMA_STR_isDigit($c2))) {
600 $is_hex_digit = false;
606 $l = $count2 - $count1;
607 $str = PMA_substr($sql, $count1, $l);
610 if ($is_digit ||
$is_float_digit ||
$is_hex_digit) {
612 if ($is_float_digit) {
614 } elseif ($is_hex_digit) {
619 } elseif ($is_user) {
620 $type = 'punct_user';
621 } elseif ($is_sql_variable != false) {
622 $type = 'alpha_variable';
625 } // end if... else....
626 PMA_SQP_arrayAdd($sql_array, $type, $str, $arraysize, $count2);
632 if (PMA_strpos($allpunct_list, $c) !== false) {
633 while (($count2 < $len) && PMA_strpos($allpunct_list, PMA_substr($sql, $count2, 1)) !== false) {
636 $l = $count2 - $count1;
640 $punct_data = PMA_substr($sql, $count1, $l);
643 // Special case, sometimes, althought two characters are
644 // adjectent directly, they ACTUALLY need to be seperate
648 var_dump($punct_data);
654 switch ($punct_data) {
655 case $punct_queryend:
656 $t_suffix = '_queryend';
658 case $punct_qualifier:
659 $t_suffix = '_qualifier';
660 $this_was_punct = true;
663 $this_was_listsep = true;
664 $t_suffix = '_listsep';
669 PMA_SQP_arrayAdd($sql_array, 'punct' . $t_suffix, $punct_data, $arraysize);
670 } elseif ($punct_data == $GLOBALS['sql_delimiter'] ||
isset($allpunct_list_pair[$punct_data])) {
671 // Ok, we have one of the valid combined punct expressions
672 PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize);
674 // Bad luck, lets split it up more
675 $first = $punct_data[0];
676 $last2 = $punct_data[$l - 2] . $punct_data[$l - 1];
677 $last = $punct_data[$l - 1];
678 if (($first == ',') ||
($first == ';') ||
($first == '.') ||
($first == '*')) {
679 $count2 = $count1 +
1;
680 $punct_data = $first;
681 } elseif (($last2 == '/*') ||
(($last2 == '--') && ($count2 == $len ||
PMA_substr($sql, $count2, 1) <= ' '))) {
683 $punct_data = PMA_substr($sql, $count1, $count2 - $count1);
684 } elseif (($last == '-') ||
($last == '+') ||
($last == '!')) {
686 $punct_data = PMA_substr($sql, $count1, $count2 - $count1);
687 } elseif ($last != '~') {
689 * @todo for negation operator, split in 2 tokens ?
690 * "select x&~1 from t"
691 * becomes "select x & ~ 1 from t" ?
693 $debugstr = __('Unknown Punctuation String')
694 . ' @ ' . ($count1+
1) . "\n"
695 . 'STR: ' . htmlspecialchars($punct_data);
696 PMA_SQP_throwError($debugstr, $sql);
699 PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize);
701 } // end if... elseif... else
708 $debugstr = 'C1 C2 LEN: ' . $count1 . ' ' . $count2 . ' ' . $len . "\n"
709 . 'STR: ' . PMA_substr($sql, $count1, $count2 - $count1) . "\n";
710 PMA_SQP_bug($debugstr, $sql);
713 } // end while ($count2 < $len)
721 if ($arraysize > 0) {
722 $t_next = $sql_array[0]['type'];
726 $d_next = $sql_array[0]['data'];
730 $d_next_upper = $t_next == 'alpha' ?
strtoupper($d_next) : $d_next;
732 $d_bef_prev_upper = '';
736 for ($i = 0; $i < $arraysize; $i++
) {
737 $t_bef_prev = $t_prev;
740 $d_bef_prev = $d_prev;
743 $d_bef_prev_upper = $d_prev_upper;
744 $d_prev_upper = $d_cur_upper;
745 $d_cur_upper = $d_next_upper;
746 if (($i +
1) < $arraysize) {
747 $t_next = $sql_array[$i +
1]['type'];
748 $d_next = $sql_array[$i +
1]['data'];
749 $d_next_upper = $t_next == 'alpha' ?
strtoupper($d_next) : $d_next;
756 //DEBUG echo "[prev: <strong>".$d_prev."</strong> ".$t_prev."][cur: <strong>".$d_cur."</strong> ".$t_cur."][next: <strong>".$d_next."</strong> ".$t_next."]<br />";
758 if ($t_cur == 'alpha') {
759 $t_suffix = '_identifier';
760 // for example: `thebit` bit(8) NOT NULL DEFAULT b'0'
761 if ($t_prev == 'alpha' && $d_prev == 'DEFAULT' && $d_cur == 'b' && $t_next == 'quote_single') {
762 $t_suffix = '_bitfield_constant_introducer';
763 } elseif (($t_next == 'punct_qualifier') ||
($t_prev == 'punct_qualifier')) {
764 $t_suffix = '_identifier';
765 } elseif (($t_next == 'punct_bracket_open_round')
766 && isset($PMA_SQPdata_function_name[$d_cur_upper])) {
768 * @todo 2005-10-16: in the case of a CREATE TABLE containing
769 * a TIMESTAMP, since TIMESTAMP() is also a function, it's
770 * found here and the token is wrongly marked as alpha_functionName.
771 * But we compensate for this when analysing for timestamp_not_null
772 * later in this script.
774 * Same applies to CHAR vs. CHAR() function.
776 $t_suffix = '_functionName';
777 /* There are functions which might be as well column types */
778 } elseif (isset($PMA_SQPdata_column_type[$d_cur_upper])) {
779 $t_suffix = '_columnType';
782 * Temporary fix for bugs #621357 and #2027720
784 * @todo FIX PROPERLY NEEDS OVERHAUL OF SQL TOKENIZER
786 if (($d_cur_upper == 'SET' ||
$d_cur_upper == 'BINARY') && $t_next != 'punct_bracket_open_round') {
787 $t_suffix = '_reservedWord';
789 //END OF TEMPORARY FIX
791 // CHARACTER is a synonym for CHAR, but can also be meant as
792 // CHARACTER SET. In this case, we have a reserved word.
793 if ($d_cur_upper == 'CHARACTER' && $d_next_upper == 'SET') {
794 $t_suffix = '_reservedWord';
798 // current is a column type, so previous must not be
799 // a reserved word but an identifier
800 // CREATE TABLE SG_Persons (first varchar(64))
802 //if ($sql_array[$i-1]['type'] =='alpha_reservedWord') {
803 // $sql_array[$i-1]['type'] = 'alpha_identifier';
806 } elseif (isset($PMA_SQPdata_reserved_word[$d_cur_upper])) {
807 $t_suffix = '_reservedWord';
808 } elseif (isset($PMA_SQPdata_column_attrib[$d_cur_upper])) {
809 $t_suffix = '_columnAttrib';
810 // INNODB is a MySQL table type, but in "SHOW INNODB STATUS",
811 // it should be regarded as a reserved word.
812 if ($d_cur_upper == 'INNODB'
813 && $d_prev_upper == 'SHOW'
814 && $d_next_upper == 'STATUS'
816 $t_suffix = '_reservedWord';
819 if ($d_cur_upper == 'DEFAULT' && $d_next_upper == 'CHARACTER') {
820 $t_suffix = '_reservedWord';
822 // Binary as character set
823 if ($d_cur_upper == 'BINARY'
824 && (($d_bef_prev_upper == 'CHARACTER' && $d_prev_upper == 'SET')
825 ||
($d_bef_prev_upper == 'SET' && $d_prev_upper == '=')
826 ||
($d_bef_prev_upper == 'CHARSET' && $d_prev_upper == '=')
827 ||
$d_prev_upper == 'CHARSET')
828 && in_array($d_cur, $mysql_charsets)
830 $t_suffix = '_charset';
832 } elseif (in_array($d_cur, $mysql_charsets)
833 ||
in_array($d_cur, $mysql_collations_flat)
834 ||
($d_cur{0} == '_' && in_array(substr($d_cur, 1), $mysql_charsets))) {
835 $t_suffix = '_charset';
839 // check if present in the list of forbidden words
840 if ($t_suffix == '_reservedWord'
841 && isset($PMA_SQPdata_forbidden_word[$d_cur_upper])
843 $sql_array[$i]['forbidden'] = true;
845 $sql_array[$i]['forbidden'] = false;
847 $sql_array[$i]['type'] .= $t_suffix;
851 // Stores the size of the array inside the array, as count() is a slow
853 $sql_array['len'] = $arraysize;
855 // DEBUG echo 'After parsing<pre>'; print_r($sql_array); echo '</pre>';
856 // Sends the data back
858 } // end of the "PMA_SQP_parse()" function
861 * Checks for token types being what we want...
863 * @param string $toCheck String of type that we have
864 * @param string $whatWeWant String of type that we want
866 * @return boolean result of check
870 function PMA_SQP_typeCheck($toCheck, $whatWeWant)
872 $typeSeparator = '_';
873 if (strcmp($whatWeWant, $toCheck) == 0) {
876 if (strpos($whatWeWant, $typeSeparator) === false) {
878 $whatWeWant, $toCheck,
879 strpos($toCheck, $typeSeparator)
889 * Analyzes SQL queries
891 * @param array $arr The SQL queries
893 * @return array The analyzed SQL queries
897 function PMA_SQP_analyze($arr)
899 if ($arr == array() ||
! isset($arr['len'])) {
906 'select_expr_clause'=> '', // the whole stuff between SELECT and FROM , except DISTINCT
907 'position_of_first_select' => '', // the array index
909 'group_by_clause'=> '',
910 'order_by_clause'=> '',
911 'having_clause' => '',
912 'limit_clause' => '',
913 'where_clause' => '',
914 'where_clause_identifiers' => array(),
915 'unsorted_query' => '',
916 'queryflags' => array(),
917 'select_expr' => array(),
918 'table_ref' => array(),
919 'foreign_keys' => array(),
920 'create_table_fields' => array()
922 $subresult_empty = $subresult;
923 $seek_queryend = false;
924 $seen_end_of_table_ref = false;
925 $number_of_brackets_in_extract = 0;
926 $number_of_brackets_in_group_concat = 0;
928 $number_of_brackets = 0;
929 $in_subquery = false;
930 $seen_subquery = false;
933 // for SELECT EXTRACT(YEAR_MONTH FROM CURDATE())
934 // we must not use CURDATE as a table_ref
935 // so we track whether we are in the EXTRACT()
938 // for GROUP_CONCAT(...)
939 $in_group_concat = false;
941 /* Description of analyzer results
943 * db, table, column, alias
944 * ------------------------
946 * Inside the $subresult array, we create ['select_expr'] and ['table_ref']
949 * The SELECT syntax (simplified) is
952 * select_expression,...
953 * [FROM [table_references]
956 * ['select_expr'] is filled with each expression, the key represents the
957 * expression position in the list (0-based) (so we don't lose track of
958 * multiple occurences of the same column).
960 * ['table_ref'] is filled with each table ref, same thing for the key.
962 * I create all sub-values empty, even if they are
963 * not present (for example no select_expression alias).
965 * There is a debug section at the end of loop #1, if you want to
966 * see the exact contents of select_expr and table_ref
971 * In $subresult, array 'queryflags' is filled, according to what we
974 * Currently, those are generated:
976 * ['queryflags']['select_from'] = 1; if this is a real SELECT...FROM
977 * ['queryflags']['drop_database'] = 1;if this is a DROP DATABASE
978 * ['queryflags']['reload'] = 1; for the purpose of reloading the
980 * ['queryflags']['distinct'] = 1; for a DISTINCT
981 * ['queryflags']['union'] = 1; for a UNION
982 * ['queryflags']['join'] = 1; for a JOIN
983 * ['queryflags']['offset'] = 1; for the presence of OFFSET
984 * ['queryflags']['procedure'] = 1; for the presence of PROCEDURE
985 * ['queryflags']['is_explain'] = 1; for the presence of EXPLAIN
986 * ['queryflags']['is_delete'] = 1; for the presence of DELETE
987 * ['queryflags']['is_affected'] = 1; for the presence of UPDATE, DELETE
988 * or INSERT|LOAD DATA|REPLACE
989 * ['queryflags']['is_replace'] = 1; for the presence of REPLACE
990 * ['queryflags']['is_insert'] = 1; for the presence of INSERT
991 * ['queryflags']['is_maint'] = 1; for the presence of CHECK|ANALYZE
992 * |REPAIR|OPTIMIZE TABLE
993 * ['queryflags']['is_show'] = 1; for the presence of SHOW
994 * ['queryflags']['is_analyse'] = 1; for the presence of PRRCEDURE ANALYSE
995 * ['queryflags']['is_export'] = 1; for the presence of INTO OUTFILE
996 * ['queryflags']['is_group'] = 1; for the presence of GROUP BY|HAVING|
998 * ['queryflags']['is_func'] = 1; for the presence of SUM|AVG|STD|STDDEV
999 * |MIN|MAX|BIT_OR|BIT_AND
1000 * ['queryflags']['is_count'] = 1; for the presence of SELECT COUNT
1005 * The select is splitted in those clauses:
1006 * ['select_expr_clause']
1008 * ['group_by_clause']
1009 * ['order_by_clause']
1014 * The identifiers of the WHERE clause are put into the array
1015 * ['where_clause_identifier']
1017 * For a SELECT, the whole query without the ORDER BY clause is put into
1018 * ['unsorted_query']
1022 * The CREATE TABLE may contain FOREIGN KEY clauses, so they get
1023 * analyzed and ['foreign_keys'] is an array filled with
1024 * the constraint name, the index list,
1025 * the REFERENCES table name and REFERENCES index list,
1026 * and ON UPDATE | ON DELETE clauses
1028 * position_of_first_select
1029 * ------------------------
1031 * The array index of the first SELECT we find. Will be used to
1032 * insert a SQL_CALC_FOUND_ROWS.
1034 * create_table_fields
1035 * -------------------
1037 * Used to detect the DEFAULT CURRENT_TIMESTAMP and
1038 * ON UPDATE CURRENT_TIMESTAMP clauses of the CREATE TABLE query.
1039 * Also used to store the default value of the field.
1040 * An array, each element is the identifier name.
1041 * Note that for now, the timestamp_not_null element is created
1042 * even for non-TIMESTAMP fields.
1044 * Sub-elements: ['type'] which contains the column type
1045 * optional (currently they are never false but can be absent):
1046 * ['default_current_timestamp'] boolean
1047 * ['on_update_current_timestamp'] boolean
1048 * ['timestamp_not_null'] boolean
1050 * section_before_limit, section_after_limit
1051 * -----------------------------------------
1053 * Marks the point of the query where we can insert a LIMIT clause;
1054 * so the section_before_limit will contain the left part before
1055 * a possible LIMIT clause
1058 * End of description of analyzer results
1062 // TODO: current logic checks for only one word, so I put only the
1063 // first word of the reserved expressions that end a table ref;
1064 // maybe this is not ok (the first word might mean something else)
1065 // $words_ending_table_ref = array(
1070 // 'LOCK IN SHARE MODE',
1076 $words_ending_table_ref = array(
1088 $words_ending_clauses = array(
1096 $supported_query_types = array(
1099 // Support for these additional query types will come later on.
1114 // loop #1 for each token: select_expr, table_ref for SELECT
1116 for ($i = 0; $i < $size; $i++
) {
1117 //DEBUG echo "Loop1 <strong>" . $arr[$i]['data']
1118 //. "</strong> (" . $arr[$i]['type'] . ")<br />";
1120 // High speed seek for locating the end of the current query
1121 if ($seek_queryend == true) {
1122 if ($arr[$i]['type'] == 'punct_queryend') {
1123 $seek_queryend = false;
1126 } // end if (type == punct_queryend)
1127 } // end if ($seek_queryend)
1130 * Note: do not split if this is a punct_queryend for the first and only
1132 * @todo when we find a UNION, should we split in another subresult?
1134 if ($arr[$i]['type'] == 'punct_queryend' && ($i +
1 != $size)) {
1135 $result[] = $subresult;
1136 $subresult = $subresult_empty;
1138 } // end if (type == punct_queryend)
1140 // ==============================================================
1141 if ($arr[$i]['type'] == 'punct_bracket_open_round') {
1142 $number_of_brackets++
;
1144 $number_of_brackets_in_extract++
;
1146 if ($in_group_concat) {
1147 $number_of_brackets_in_group_concat++
;
1150 // ==============================================================
1151 if ($arr[$i]['type'] == 'punct_bracket_close_round') {
1152 $number_of_brackets--;
1153 if ($number_of_brackets == 0) {
1154 $in_subquery = false;
1157 $number_of_brackets_in_extract--;
1158 if ($number_of_brackets_in_extract == 0) {
1159 $in_extract = false;
1162 if ($in_group_concat) {
1163 $number_of_brackets_in_group_concat--;
1164 if ($number_of_brackets_in_group_concat == 0) {
1165 $in_group_concat = false;
1172 * skip the subquery to avoid setting
1173 * select_expr or table_ref with the contents
1174 * of this subquery; this is to avoid a bug when
1175 * trying to edit the results of
1176 * select * from child where not exists (select id from
1177 * parent where child.parent_id = parent.id);
1181 // ==============================================================
1182 if ($arr[$i]['type'] == 'alpha_functionName') {
1183 $upper_data = strtoupper($arr[$i]['data']);
1184 if ($upper_data =='EXTRACT') {
1186 $number_of_brackets_in_extract = 0;
1188 if ($upper_data =='GROUP_CONCAT') {
1189 $in_group_concat = true;
1190 $number_of_brackets_in_group_concat = 0;
1194 // ==============================================================
1195 if ($arr[$i]['type'] == 'alpha_reservedWord') {
1196 // We don't know what type of query yet, so run this
1197 if ($subresult['querytype'] == '') {
1198 $subresult['querytype'] = strtoupper($arr[$i]['data']);
1199 } // end if (querytype was empty)
1201 // Check if we support this type of query
1202 if (!isset($supported_query_types[$subresult['querytype']])) {
1203 // Skip ahead to the next one if we don't
1204 $seek_queryend = true;
1206 } // end if (query not supported)
1209 $upper_data = strtoupper($arr[$i]['data']);
1211 * @todo reset for each query?
1214 if ($upper_data == 'SELECT') {
1215 if ($number_of_brackets > 0) {
1216 $in_subquery = true;
1217 $seen_subquery = true;
1218 // this is a subquery so do not analyze inside it
1222 $previous_was_identifier = false;
1223 $current_select_expr = -1;
1224 $seen_end_of_table_ref = false;
1225 } // end if (data == SELECT)
1227 if ($upper_data =='FROM' && !$in_extract) {
1228 $current_table_ref = -1;
1230 $previous_was_identifier = false;
1231 $save_table_ref = true;
1232 } // end if (data == FROM)
1234 // here, do not 'continue' the loop, as we have more work for
1235 // reserved words below
1236 } // end if (type == alpha_reservedWord)
1238 // ==============================
1239 if ($arr[$i]['type'] == 'quote_backtick'
1240 ||
$arr[$i]['type'] == 'quote_double'
1241 ||
$arr[$i]['type'] == 'quote_single'
1242 ||
$arr[$i]['type'] == 'alpha_identifier'
1243 ||
($arr[$i]['type'] == 'alpha_reservedWord'
1244 && $arr[$i]['forbidden'] == false)
1246 switch ($arr[$i]['type']) {
1247 case 'alpha_identifier':
1248 case 'alpha_reservedWord':
1250 * this is not a real reservedWord, because it's not
1251 * present in the list of forbidden words, for example
1252 * "storage" which can be used as an identifier
1255 $identifier = $arr[$i]['data'];
1258 case 'quote_backtick':
1259 case 'quote_double':
1260 case 'quote_single':
1261 $identifier = PMA_Util
::unQuote($arr[$i]['data']);
1265 if ($subresult['querytype'] == 'SELECT'
1266 && ! $in_group_concat
1267 && ! ($seen_subquery && $arr[$i - 1]['type'] == 'punct_bracket_close_round')
1270 if ($previous_was_identifier && isset($chain)) {
1271 // found alias for this select_expr, save it
1272 // but only if we got something in $chain
1273 // (for example, SELECT COUNT(*) AS cnt
1274 // puts nothing in $chain, so we avoid
1275 // setting the alias)
1276 $alias_for_select_expr = $identifier;
1278 $chain[] = $identifier;
1279 $previous_was_identifier = true;
1281 } // end if !$previous_was_identifier
1284 if ($save_table_ref && !$seen_end_of_table_ref) {
1285 if ($previous_was_identifier) {
1286 // found alias for table ref
1287 // save it for later
1288 $alias_for_table_ref = $identifier;
1290 $chain[] = $identifier;
1291 $previous_was_identifier = true;
1293 } // end if ($previous_was_identifier)
1294 } // end if ($save_table_ref &&!$seen_end_of_table_ref)
1295 } // end if (!$seen_from)
1296 } // end if (querytype SELECT)
1297 } // end if (quote_backtick or double quote or alpha_identifier)
1299 // ===================================
1300 if ($arr[$i]['type'] == 'punct_qualifier') {
1301 // to be able to detect an identifier following another
1302 $previous_was_identifier = false;
1304 } // end if (punct_qualifier)
1307 * @todo check if 3 identifiers following one another -> error
1310 // s a v e a s e l e c t e x p r
1311 // finding a list separator or FROM
1312 // means that we must save the current chain of identifiers
1313 // into a select expression
1315 // for now, we only save a select expression if it contains
1316 // at least one identifier, as we are interested in checking
1317 // the columns and table names, so in "select * from persons",
1318 // the "*" is not saved
1320 if (isset($chain) && !$seen_end_of_table_ref
1321 && ((!$seen_from && $arr[$i]['type'] == 'punct_listsep')
1322 ||
($arr[$i]['type'] == 'alpha_reservedWord' && $upper_data == 'FROM'))
1324 $size_chain = count($chain);
1325 $current_select_expr++
;
1326 $subresult['select_expr'][$current_select_expr] = array(
1331 'table_true_name' => '',
1335 if (isset($alias_for_select_expr) && strlen($alias_for_select_expr)) {
1336 // we had found an alias for this select expression
1337 $subresult['select_expr'][$current_select_expr]['alias'] = $alias_for_select_expr;
1338 unset($alias_for_select_expr);
1340 // there is at least a column
1341 $subresult['select_expr'][$current_select_expr]['column'] = $chain[$size_chain - 1];
1342 $subresult['select_expr'][$current_select_expr]['expr'] = $chain[$size_chain - 1];
1345 if ($size_chain > 1) {
1346 $subresult['select_expr'][$current_select_expr]['table_name'] = $chain[$size_chain - 2];
1347 // we assume for now that this is also the true name
1348 $subresult['select_expr'][$current_select_expr]['table_true_name'] = $chain[$size_chain - 2];
1349 $subresult['select_expr'][$current_select_expr]['expr']
1350 = $subresult['select_expr'][$current_select_expr]['table_name']
1351 . '.' . $subresult['select_expr'][$current_select_expr]['expr'];
1352 } // end if ($size_chain > 1)
1355 if ($size_chain > 2) {
1356 $subresult['select_expr'][$current_select_expr]['db'] = $chain[$size_chain - 3];
1357 $subresult['select_expr'][$current_select_expr]['expr']
1358 = $subresult['select_expr'][$current_select_expr]['db']
1359 . '.' . $subresult['select_expr'][$current_select_expr]['expr'];
1360 } // end if ($size_chain > 2)
1364 * @todo explain this:
1366 if (($arr[$i]['type'] == 'alpha_reservedWord')
1367 && ($upper_data != 'FROM')
1369 $previous_was_identifier = true;
1372 } // end if (save a select expr)
1375 //======================================
1376 // s a v e a t a b l e r e f
1377 //======================================
1379 // maybe we just saw the end of table refs
1380 // but the last table ref has to be saved
1381 // or we are at the last token
1382 // or we just got a reserved word
1384 * @todo there could be another query after this one
1387 if (isset($chain) && $seen_from && $save_table_ref
1388 && ($arr[$i]['type'] == 'punct_listsep'
1389 ||
($arr[$i]['type'] == 'alpha_reservedWord' && $upper_data != "AS")
1390 ||
$seen_end_of_table_ref
1394 $size_chain = count($chain);
1395 $current_table_ref++
;
1396 $subresult['table_ref'][$current_table_ref] = array(
1400 'table_alias' => '',
1401 'table_true_name' => ''
1403 if (isset($alias_for_table_ref) && strlen($alias_for_table_ref)) {
1404 $subresult['table_ref'][$current_table_ref]['table_alias'] = $alias_for_table_ref;
1405 unset($alias_for_table_ref);
1407 $subresult['table_ref'][$current_table_ref]['table_name'] = $chain[$size_chain - 1];
1408 // we assume for now that this is also the true name
1409 $subresult['table_ref'][$current_table_ref]['table_true_name'] = $chain[$size_chain - 1];
1410 $subresult['table_ref'][$current_table_ref]['expr']
1411 = $subresult['table_ref'][$current_table_ref]['table_name'];
1413 if ($size_chain > 1) {
1414 $subresult['table_ref'][$current_table_ref]['db'] = $chain[$size_chain - 2];
1415 $subresult['table_ref'][$current_table_ref]['expr']
1416 = $subresult['table_ref'][$current_table_ref]['db']
1417 . '.' . $subresult['table_ref'][$current_table_ref]['expr'];
1418 } // end if ($size_chain > 1)
1420 // add the table alias into the whole expression
1421 $subresult['table_ref'][$current_table_ref]['expr']
1422 .= ' ' . $subresult['table_ref'][$current_table_ref]['table_alias'];
1425 $previous_was_identifier = true;
1428 } // end if (save a table ref)
1431 // when we have found all table refs,
1432 // for each table_ref alias, put the true name of the table
1433 // in the corresponding select expressions
1435 if (isset($current_table_ref)
1436 && ($seen_end_of_table_ref ||
$i == $size-1)
1437 && $subresult != $subresult_empty
1439 for ($tr=0; $tr <= $current_table_ref; $tr++
) {
1440 $alias = $subresult['table_ref'][$tr]['table_alias'];
1441 $truename = $subresult['table_ref'][$tr]['table_true_name'];
1442 for ($se=0; $se <= $current_select_expr; $se++
) {
1445 && $subresult['select_expr'][$se]['table_true_name'] == $alias
1447 $subresult['select_expr'][$se]['table_true_name'] = $truename;
1448 } // end if (found the alias)
1449 } // end for (select expressions)
1451 } // end for (table refs)
1452 } // end if (set the true names)
1455 // e n d i n g l o o p #1
1456 // set the $previous_was_identifier to false if the current
1457 // token is not an identifier
1458 if (($arr[$i]['type'] != 'alpha_identifier')
1459 && ($arr[$i]['type'] != 'quote_double')
1460 && ($arr[$i]['type'] != 'quote_single')
1461 && ($arr[$i]['type'] != 'quote_backtick')
1463 $previous_was_identifier = false;
1466 // however, if we are on AS, we must keep the $previous_was_identifier
1467 if (($arr[$i]['type'] == 'alpha_reservedWord')
1468 && ($upper_data == 'AS')
1470 $previous_was_identifier = true;
1473 if (($arr[$i]['type'] == 'alpha_reservedWord')
1474 && ($upper_data =='ON' ||
$upper_data =='USING')
1476 $save_table_ref = false;
1477 } // end if (data == ON)
1479 if (($arr[$i]['type'] == 'alpha_reservedWord')
1480 && ($upper_data =='JOIN' ||
$upper_data =='FROM')
1482 $save_table_ref = true;
1483 } // end if (data == JOIN)
1486 * no need to check the end of table ref if we already did
1488 * @todo maybe add "&& $seen_from"
1490 if (!$seen_end_of_table_ref) {
1491 // if this is the last token, it implies that we have
1492 // seen the end of table references
1493 // Check for the end of table references
1495 // Note: if we are analyzing a GROUP_CONCAT clause,
1496 // we might find a word that seems to indicate that
1497 // we have found the end of table refs (like ORDER)
1498 // but it's a modifier of the GROUP_CONCAT so
1499 // it's not the real end of table refs
1501 ||
($arr[$i]['type'] == 'alpha_reservedWord'
1502 && !$in_group_concat
1503 && isset($words_ending_table_ref[$upper_data]))
1505 $seen_end_of_table_ref = true;
1506 // to be able to save the last table ref, but do not
1507 // set it true if we found a word like "ON" that has
1508 // already set it to false
1509 if (isset($save_table_ref) && $save_table_ref != false) {
1510 $save_table_ref = true;
1513 } // end if (check for end of table ref)
1514 } //end if (!$seen_end_of_table_ref)
1516 if ($seen_end_of_table_ref) {
1517 $save_table_ref = false;
1520 } // end for $i (loop #1)
1524 if (isset($current_select_expr)) {
1525 for ($trace=0; $trace<=$current_select_expr; $trace++) {
1527 reset ($subresult['select_expr'][$trace]);
1528 while (list ($key, $val) = each ($subresult['select_expr'][$trace]))
1529 echo "sel expr $trace $key => $val<br />\n";
1533 if (isset($current_table_ref)) {
1534 echo "current_table_ref = " . $current_table_ref . "<br>";
1535 for ($trace=0; $trace<=$current_table_ref; $trace++) {
1538 reset ($subresult['table_ref'][$trace]);
1539 while (list ($key, $val) = each ($subresult['table_ref'][$trace]))
1540 echo "table ref $trace $key => $val<br />\n";
1544 // -------------------------------------------------------
1547 // loop #2: - queryflags
1548 // - querytype (for queries != 'SELECT')
1549 // - section_before_limit, section_after_limit
1551 // we will also need this queryflag in loop 2
1553 if (isset($current_table_ref) && $current_table_ref > -1) {
1554 $subresult['queryflags']['select_from'] = 1;
1557 $section_before_limit = '';
1558 $section_after_limit = ''; // truly the section after the limit clause
1559 $seen_reserved_word = false;
1560 $seen_group = false;
1561 $seen_order = false;
1562 $seen_order_by = false;
1563 $in_group_by = false; // true when we are inside the GROUP BY clause
1564 $in_order_by = false; // true when we are inside the ORDER BY clause
1565 $in_having = false; // true when we are inside the HAVING clause
1566 $in_select_expr = false; // true when we are inside the select expr clause
1567 $in_where = false; // true when we are inside the WHERE clause
1568 $seen_limit = false; // true if we have seen a LIMIT clause
1569 $in_limit = false; // true when we are inside the LIMIT clause
1570 $after_limit = false; // true when we are after the LIMIT clause
1571 $in_from = false; // true when we are in the FROM clause
1572 $in_group_concat = false;
1573 $first_reserved_word = '';
1574 $current_identifier = '';
1575 $unsorted_query = $arr['raw']; // in case there is no ORDER BY
1576 $number_of_brackets = 0;
1577 $in_subquery = false;
1579 for ($i = 0; $i < $size; $i++
) {
1580 //DEBUG echo "Loop2 <strong>" . $arr[$i]['data']
1581 //. "</strong> (" . $arr[$i]['type'] . ")<br />";
1583 if ($arr[$i]['type'] == 'punct_bracket_open_round') {
1584 $number_of_brackets++
;
1587 if ($arr[$i]['type'] == 'punct_bracket_close_round') {
1588 $number_of_brackets--;
1589 if ($number_of_brackets == 0) {
1590 $in_subquery = false;
1594 if ($arr[$i]['type'] == 'alpha_reservedWord') {
1595 $upper_data = strtoupper($arr[$i]['data']);
1597 if ($upper_data == 'SELECT' && $number_of_brackets > 0) {
1598 $in_subquery = true;
1601 if (!$seen_reserved_word) {
1602 $first_reserved_word = $upper_data;
1603 $subresult['querytype'] = $upper_data;
1604 $seen_reserved_word = true;
1606 if ($first_reserved_word == 'SELECT') {
1607 $position_of_first_select = $i;
1610 if ($first_reserved_word == 'EXPLAIN') {
1611 $subresult['queryflags']['is_explain'] = 1;
1614 if ($first_reserved_word == 'DELETE') {
1615 $subresult['queryflags']['is_delete'] = 1;
1616 $subresult['queryflags']['is_affected'] = 1;
1619 if ($first_reserved_word == 'UPDATE') {
1620 $subresult['queryflags']['is_affected'] = 1;
1623 if ($first_reserved_word == 'REPLACE') {
1624 $subresult['queryflags']['is_replace'] = 1;
1627 if ($first_reserved_word == 'SHOW') {
1628 $subresult['queryflags']['is_show'] = 1;
1632 // for the presence of DROP DATABASE
1633 if ($first_reserved_word == 'DROP' && $upper_data == 'DATABASE') {
1634 $subresult['queryflags']['drop_database'] = 1;
1636 // A table has to be created, renamed, dropped -> navi panel
1637 // should be reloaded
1638 if (in_array($first_reserved_word, array("CREATE", "ALTER", "DROP"))
1640 $upper_data, array("VIEW", "TABLE", "DATABASE", "SCHEMA"))
1642 $subresult['queryflags']['reload'] = 1;
1645 // for the presence of INSERT|LOAD DATA
1646 if (in_array($first_reserved_word, array("INSERT", "LOAD"))
1647 && $upper_data == 'REPLACE'
1649 $subresult['queryflags']['is_insert'] = 1;
1650 $subresult['queryflags']['is_affected'] = 1;
1653 // for the presence of CHECK|ANALYZE|REPAIR|OPTIMIZE TABLE
1654 if (in_array($first_reserved_word, array("CHECK","ANALYZE","REPAIR","OPTIMIZE"))
1655 && $upper_data == 'TABLE'
1657 $subresult['queryflags']['is_maint'] = 1;
1661 if ($upper_data == 'LIMIT' && ! $in_subquery) {
1662 $section_before_limit = substr($arr['raw'], 0, $arr[$i]['pos'] - 5);
1666 $in_order_by = false; // @todo maybe others to set false
1669 if ($upper_data == 'PROCEDURE') {
1670 $subresult['queryflags']['procedure'] = 1;
1672 $after_limit = true;
1674 // for the presnece of PROCEDURE ANALYSE
1675 if (isset($subresult['queryflags']['select_from'])
1676 && $subresult['queryflags']['select_from'] == 1
1678 && $arr[$i +
1]['type'] == 'alpha_reservedWord'
1679 && strtoupper($arr[$i +
1]['data']) == 'ANALYSE'
1681 $subresult['queryflags']['is_analyse'] = 1;
1685 // for the presnece of INTO OUTFILE
1686 if ($upper_data == 'INTO'
1687 && isset($subresult['queryflags']['select_from'])
1688 && $subresult['queryflags']['select_from'] == 1
1690 && $arr[$i +
1]['type'] == 'alpha_reservedWord'
1691 && strtoupper($arr[$i +
1]['data']) == 'OUTFILE'
1693 $subresult['queryflags']['is_export'] = 1;
1696 * @todo set also to false if we find FOR UPDATE or LOCK IN SHARE MODE
1698 if ($upper_data == 'SELECT') {
1699 $in_select_expr = true;
1700 $select_expr_clause = '';
1702 // for the presence of SELECT COUNT
1703 if (isset($subresult['queryflags']['select_from'])
1704 && $subresult['queryflags']['select_from'] == 1
1705 && !isset($subresult['queryflags']['is_group'])
1707 && $arr[$i +
1]['type'] == 'alpha_functionName'
1708 && strtoupper($arr[$i +
1]['data']) == 'COUNT'
1710 $subresult['queryflags']['is_count'] = 1;
1714 if ($upper_data == 'DISTINCT' && !$in_group_concat) {
1715 $subresult['queryflags']['distinct'] = 1;
1718 if ($upper_data == 'UNION') {
1719 $subresult['queryflags']['union'] = 1;
1722 if ($upper_data == 'JOIN') {
1723 $subresult['queryflags']['join'] = 1;
1726 if ($upper_data == 'OFFSET') {
1727 $subresult['queryflags']['offset'] = 1;
1730 // if this is a real SELECT...FROM
1731 if ($upper_data == 'FROM'
1732 && isset($subresult['queryflags']['select_from'])
1733 && $subresult['queryflags']['select_from'] == 1
1737 $in_select_expr = false;
1741 // (we could have less resetting of variables to false
1742 // if we trust that the query respects the standard
1743 // MySQL order for clauses)
1745 // we use $seen_group and $seen_order because we are looking
1747 if ($upper_data == 'GROUP') {
1749 $seen_order = false;
1751 $in_order_by = false;
1753 $in_select_expr = false;
1756 // for the presence of GROUP BY|HAVING|SELECT DISTINCT
1757 if (isset($subresult['queryflags']['select_from'])
1758 && $subresult['queryflags']['select_from'] == 1
1760 && $arr[$i +
1]['type'] == 'alpha_reservedWord'
1761 && in_array(strtoupper($arr[$i +
1]['data']), array("BY", "HAVING", "SELECT"))
1763 && $arr[$i +
2]['type'] == 'alpha_reservedWord'
1764 && strtoupper($arr[$i +
2]['data']) == 'DISTINCT'
1766 $subresult['queryflags']['is_group'] = 1;
1769 if ($upper_data == 'ORDER' && !$in_group_concat) {
1771 $seen_group = false;
1773 $in_group_by = false;
1775 $in_select_expr = false;
1778 if ($upper_data == 'HAVING') {
1780 $having_clause = '';
1781 $seen_group = false;
1782 $seen_order = false;
1783 $in_group_by = false;
1784 $in_order_by = false;
1786 $in_select_expr = false;
1790 if ($upper_data == 'WHERE') {
1793 $where_clause_identifiers = array();
1794 $seen_group = false;
1795 $seen_order = false;
1796 $in_group_by = false;
1797 $in_order_by = false;
1799 $in_select_expr = false;
1803 if ($upper_data == 'BY') {
1805 $in_group_by = true;
1806 $group_by_clause = '';
1809 $seen_order_by = true;
1810 // Here we assume that the ORDER BY keywords took
1811 // exactly 8 characters.
1812 // We use PMA_substr() to be charset-safe; otherwise
1813 // if the table name contains accents, the unsorted
1814 // query would be missing some characters.
1815 $unsorted_query = PMA_substr(
1816 $arr['raw'], 0, $arr[$i]['pos'] - 8
1818 $in_order_by = true;
1819 $order_by_clause = '';
1823 // if we find one of the words that could end the clause
1824 if (isset($words_ending_clauses[$upper_data])) {
1826 $in_group_by = false;
1827 $in_order_by = false;
1830 $in_select_expr = false;
1834 } // endif (reservedWord)
1836 // do not add a space after a function name
1838 * @todo can we combine loop 2 and loop 1? some code is repeated here...
1842 if ($arr[$i]['type'] == 'alpha_functionName') {
1844 $upper_data = strtoupper($arr[$i]['data']);
1845 if ($upper_data =='GROUP_CONCAT') {
1846 $in_group_concat = true;
1847 $number_of_brackets_in_group_concat = 0;
1851 if ($arr[$i]['type'] == 'punct_bracket_open_round') {
1852 if ($in_group_concat) {
1853 $number_of_brackets_in_group_concat++
;
1856 if ($arr[$i]['type'] == 'punct_bracket_close_round') {
1857 if ($in_group_concat) {
1858 $number_of_brackets_in_group_concat--;
1859 if ($number_of_brackets_in_group_concat == 0) {
1860 $in_group_concat = false;
1866 // do not add a space after an identifier if followed by a dot
1867 if ($arr[$i]['type'] == 'alpha_identifier'
1868 && $i < $size - 1 && $arr[$i +
1]['data'] == '.'
1873 // do not add a space after a dot if followed by an identifier
1874 if ($arr[$i]['data'] == '.' && $i < $size - 1
1875 && $arr[$i +
1]['type'] == 'alpha_identifier'
1880 // for the presence of INSERT|LOAD DATA
1881 if ($arr[$i]['type'] == 'alpha_identifier'
1882 && strtoupper($arr[$i]['data']) == 'DATA'
1884 && $arr[$i - 1]['type'] == 'alpha_reservedWord'
1885 && in_array(strtoupper($arr[$i - 1]['data']), array("INSERT", "LOAD"))
1887 $subresult['queryflags']['is_insert'] = 1;
1888 $subresult['queryflags']['is_affected'] = 1;
1891 // for the presence of SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND
1892 if ($arr[$i]['type'] == 'alpha_functionName'
1893 && in_array(strtoupper($arr[$i]['data']), array(
1894 "SUM","AVG","STD","STDDEV","MIN","MAX","BIT_OR","BIT_AND"))
1895 && isset($subresult['queryflags']['select_from'])
1896 && $subresult['queryflags']['select_from'] == 1
1897 && !isset($subresult['queryflags']['is_group'])
1899 $subresult['queryflags']['is_func'] = 1;
1902 if ($in_select_expr && $upper_data != 'SELECT'
1903 && $upper_data != 'DISTINCT'
1905 $select_expr_clause .= $arr[$i]['data'] . $sep;
1907 if ($in_from && $upper_data != 'FROM') {
1908 $from_clause .= $arr[$i]['data'] . $sep;
1910 if ($in_group_by && $upper_data != 'GROUP' && $upper_data != 'BY') {
1911 $group_by_clause .= $arr[$i]['data'] . $sep;
1913 if ($in_order_by && $upper_data != 'ORDER' && $upper_data != 'BY') {
1914 // add a space only before ASC or DESC
1915 // not around the dot between dbname and tablename
1916 if ($arr[$i]['type'] == 'alpha_reservedWord') {
1917 $order_by_clause .= $sep;
1919 $order_by_clause .= $arr[$i]['data'];
1921 if ($in_having && $upper_data != 'HAVING') {
1922 $having_clause .= $arr[$i]['data'] . $sep;
1924 if ($in_where && $upper_data != 'WHERE') {
1925 $where_clause .= $arr[$i]['data'] . $sep;
1927 if (($arr[$i]['type'] == 'quote_backtick')
1928 ||
($arr[$i]['type'] == 'alpha_identifier')
1930 $where_clause_identifiers[] = $arr[$i]['data'];
1934 // to grab the rest of the query after the ORDER BY clause
1935 if (isset($subresult['queryflags']['select_from'])
1936 && $subresult['queryflags']['select_from'] == 1
1939 && $upper_data != 'BY'
1941 $unsorted_query .= $arr[$i]['data'];
1942 if ($arr[$i]['type'] != 'punct_bracket_open_round'
1943 && $arr[$i]['type'] != 'punct_bracket_close_round'
1944 && $arr[$i]['type'] != 'punct'
1946 $unsorted_query .= $sep;
1951 if ($upper_data == 'OFFSET') {
1952 $limit_clause .= $sep;
1954 $limit_clause .= $arr[$i]['data'];
1955 if ($upper_data == 'LIMIT' ||
$upper_data == 'OFFSET') {
1956 $limit_clause .= $sep;
1959 if ($after_limit && $seen_limit) {
1960 $section_after_limit .= $arr[$i]['data'] . $sep;
1963 // clear $upper_data for next iteration
1965 } // end for $i (loop #2)
1966 if (empty($section_before_limit)) {
1967 $section_before_limit = $arr['raw'];
1970 // -----------------------------------------------------
1971 // loop #3: foreign keys and MySQL 4.1.2+ TIMESTAMP options
1972 // (for now, check only the first query)
1973 // (for now, identifiers are assumed to be backquoted)
1975 // If we find that we are dealing with a CREATE TABLE query,
1976 // we look for the next punct_bracket_open_round, which
1977 // introduces the fields list. Then, when we find a
1978 // quote_backtick, it must be a field, so we put it into
1979 // the create_table_fields array. Even if this field is
1980 // not a timestamp, it will be useful when logic has been
1981 // added for complete field attributes analysis.
1983 $seen_foreign = false;
1984 $seen_references = false;
1985 $seen_constraint = false;
1986 $foreign_key_number = -1;
1987 $seen_create_table = false;
1988 $seen_create = false;
1989 $seen_alter = false;
1990 $in_create_table_fields = false;
1991 $brackets_level = 0;
1992 $in_timestamp_options = false;
1993 $seen_default = false;
1995 for ($i = 0; $i < $size; $i++
) {
1996 if ($arr[$i]['type'] == 'alpha_reservedWord') {
1997 $upper_data = strtoupper($arr[$i]['data']);
1999 if ($upper_data == 'NOT' && $in_timestamp_options) {
2000 $create_table_fields[$current_identifier]['timestamp_not_null'] = true;
2004 if ($upper_data == 'CREATE') {
2005 $seen_create = true;
2008 if ($upper_data == 'ALTER') {
2012 if ($upper_data == 'TABLE' && $seen_create) {
2013 $seen_create_table = true;
2014 $create_table_fields = array();
2017 if ($upper_data == 'CURRENT_TIMESTAMP') {
2018 if ($in_timestamp_options) {
2019 if ($seen_default) {
2020 $create_table_fields[$current_identifier]['default_current_timestamp'] = true;
2025 if ($upper_data == 'CONSTRAINT') {
2026 $foreign_key_number++
;
2027 $seen_foreign = false;
2028 $seen_references = false;
2029 $seen_constraint = true;
2031 if ($upper_data == 'FOREIGN') {
2032 $seen_foreign = true;
2033 $seen_references = false;
2034 $seen_constraint = false;
2036 if ($upper_data == 'REFERENCES') {
2037 $seen_foreign = false;
2038 $seen_references = true;
2039 $seen_constraint = false;
2045 // [ON DELETE {CASCADE | SET NULL | NO ACTION | RESTRICT}]
2046 // [ON UPDATE {CASCADE | SET NULL | NO ACTION | RESTRICT}]
2048 // but we set ['on_delete'] or ['on_cascade'] to
2049 // CASCADE | SET_NULL | NO_ACTION | RESTRICT
2051 // ON UPDATE CURRENT_TIMESTAMP
2053 if ($upper_data == 'ON') {
2054 if (isset($arr[$i+
1]) && $arr[$i+
1]['type'] == 'alpha_reservedWord') {
2055 $second_upper_data = strtoupper($arr[$i+
1]['data']);
2056 if ($second_upper_data == 'DELETE') {
2057 $clause = 'on_delete';
2059 if ($second_upper_data == 'UPDATE') {
2060 $clause = 'on_update';
2063 && ($arr[$i+
2]['type'] == 'alpha_reservedWord'
2064 // ugly workaround because currently, NO is not
2065 // in the list of reserved words in sqlparser.data
2066 // (we got a bug report about not being able to use
2067 // 'no' as an identifier)
2068 ||
($arr[$i+
2]['type'] == 'alpha_identifier'
2069 && strtoupper($arr[$i+
2]['data'])=='NO'))
2071 $third_upper_data = strtoupper($arr[$i+
2]['data']);
2072 if ($third_upper_data == 'CASCADE'
2073 ||
$third_upper_data == 'RESTRICT'
2075 $value = $third_upper_data;
2076 } elseif ($third_upper_data == 'SET'
2077 ||
$third_upper_data == 'NO'
2079 if ($arr[$i+
3]['type'] == 'alpha_reservedWord') {
2080 $value = $third_upper_data . '_'
2081 . strtoupper($arr[$i+
3]['data']);
2083 } elseif ($third_upper_data == 'CURRENT_TIMESTAMP') {
2084 if ($clause == 'on_update'
2085 && $in_timestamp_options
2087 $create_table_fields[$current_identifier]['on_update_current_timestamp'] = true;
2088 $seen_default = false;
2094 if (!empty($value)) {
2095 $foreign[$foreign_key_number][$clause] = $value;
2098 } // endif (isset($clause))
2102 } // end of reserved words analysis
2105 if ($arr[$i]['type'] == 'punct_bracket_open_round') {
2107 if ($seen_create_table && $brackets_level == 1) {
2108 $in_create_table_fields = true;
2113 if ($arr[$i]['type'] == 'punct_bracket_close_round') {
2115 if ($seen_references) {
2116 $seen_references = false;
2118 if ($seen_create_table && $brackets_level == 0) {
2119 $in_create_table_fields = false;
2123 if (($arr[$i]['type'] == 'alpha_columnAttrib')) {
2124 $upper_data = strtoupper($arr[$i]['data']);
2125 if ($seen_create_table && $in_create_table_fields) {
2126 if ($upper_data == 'DEFAULT') {
2127 $seen_default = true;
2128 $create_table_fields[$current_identifier]['default_value'] = $arr[$i +
1]['data'];
2134 * @see @todo 2005-10-16 note: the "or" part here is a workaround for a bug
2136 if (($arr[$i]['type'] == 'alpha_columnType')
2137 ||
($arr[$i]['type'] == 'alpha_functionName' && $seen_create_table)
2139 $upper_data = strtoupper($arr[$i]['data']);
2140 if ($seen_create_table && $in_create_table_fields
2141 && isset($current_identifier)
2143 $create_table_fields[$current_identifier]['type'] = $upper_data;
2144 if ($upper_data == 'TIMESTAMP') {
2145 $arr[$i]['type'] = 'alpha_columnType';
2146 $in_timestamp_options = true;
2148 $in_timestamp_options = false;
2149 if ($upper_data == 'CHAR') {
2150 $arr[$i]['type'] = 'alpha_columnType';
2157 if ($arr[$i]['type'] == 'quote_backtick'
2158 ||
$arr[$i]['type'] == 'alpha_identifier'
2161 if ($arr[$i]['type'] == 'quote_backtick') {
2162 // remove backquotes
2163 $identifier = PMA_Util
::unQuote($arr[$i]['data']);
2165 $identifier = $arr[$i]['data'];
2168 if ($seen_create_table && $in_create_table_fields) {
2169 $current_identifier = $identifier;
2170 // we set this one even for non TIMESTAMP type
2171 $create_table_fields[$current_identifier]['timestamp_not_null'] = false;
2174 if ($seen_constraint) {
2175 $foreign[$foreign_key_number]['constraint'] = $identifier;
2178 if ($seen_foreign && $brackets_level > 0) {
2179 $foreign[$foreign_key_number]['index_list'][] = $identifier;
2182 if ($seen_references) {
2183 if ($seen_alter && $brackets_level > 0) {
2184 $foreign[$foreign_key_number]['ref_index_list'][] = $identifier;
2185 // here, the first bracket level corresponds to the
2186 // bracket of CREATE TABLE
2187 // so if we are on level 2, it must be the index list
2188 // of the foreign key REFERENCES
2189 } elseif ($brackets_level > 1) {
2190 $foreign[$foreign_key_number]['ref_index_list'][] = $identifier;
2191 } elseif ($arr[$i+
1]['type'] == 'punct_qualifier') {
2192 // identifier is `db`.`table`
2193 // the first pass will pick the db name
2194 // the next pass will pick the table name
2195 $foreign[$foreign_key_number]['ref_db_name'] = $identifier;
2197 // identifier is `table`
2198 $foreign[$foreign_key_number]['ref_table_name'] = $identifier;
2202 } // end for $i (loop #3)
2205 // Fill the $subresult array
2207 if (isset($create_table_fields)) {
2208 $subresult['create_table_fields'] = $create_table_fields;
2211 if (isset($foreign)) {
2212 $subresult['foreign_keys'] = $foreign;
2215 if (isset($select_expr_clause)) {
2216 $subresult['select_expr_clause'] = $select_expr_clause;
2218 if (isset($from_clause)) {
2219 $subresult['from_clause'] = $from_clause;
2221 if (isset($group_by_clause)) {
2222 $subresult['group_by_clause'] = $group_by_clause;
2224 if (isset($order_by_clause)) {
2225 $subresult['order_by_clause'] = $order_by_clause;
2227 if (isset($having_clause)) {
2228 $subresult['having_clause'] = $having_clause;
2230 if (isset($limit_clause)) {
2231 $subresult['limit_clause'] = $limit_clause;
2233 if (isset($where_clause)) {
2234 $subresult['where_clause'] = $where_clause;
2236 if (isset($unsorted_query) && !empty($unsorted_query)) {
2237 $subresult['unsorted_query'] = $unsorted_query;
2239 if (isset($where_clause_identifiers)) {
2240 $subresult['where_clause_identifiers'] = $where_clause_identifiers;
2243 if (isset($position_of_first_select)) {
2244 $subresult['position_of_first_select'] = $position_of_first_select;
2245 $subresult['section_before_limit'] = $section_before_limit;
2246 $subresult['section_after_limit'] = $section_after_limit;
2249 // They are naughty and didn't have a trailing semi-colon,
2250 // then still handle it properly
2251 if ($subresult['querytype'] != '') {
2252 $result[] = $subresult;
2255 } // end of the "PMA_SQP_analyze()" function
2259 * Formats SQL queries
2261 * @param array $arr The SQL queries
2262 * @param string $mode formatting mode
2263 * @param integer $start_token starting token
2264 * @param integer $number_of_tokens number of tokens to format, -1 = all
2266 * @return string The formatted SQL queries
2270 function PMA_SQP_format(
2271 $arr, $mode='text', $start_token=0,
2272 $number_of_tokens=-1
2274 global $PMA_SQPdata_operators_docs, $PMA_SQPdata_functions_docs;
2276 //DEBUG echo 'in Format<pre>'; print_r($arr); echo '</pre>';
2277 // then check for an array
2278 if (! is_array($arr)) {
2279 return htmlspecialchars($arr);
2281 // first check for the SQL parser having hit an error
2282 if (PMA_SQP_isError()) {
2283 return htmlspecialchars($arr['raw']);
2285 // else do it properly
2289 $html_line_break = "\n";
2294 $html_line_break = '<br />';
2298 // inner_sql is a span that exists for all cases, except query_only
2299 // of $cfg['SQP']['fmtType'] to make possible a replacement
2300 // for inline editing
2301 if ($mode!='query_only') {
2302 $str .= '<span class="inner_sql">';
2304 $close_docu_link = false;
2308 $infunction = false;
2309 $space_punct_listsep = ' ';
2310 $space_punct_listsep_function_name = ' ';
2311 // $space_alpha_reserved_word = '<br />'."\n";
2312 $space_alpha_reserved_word = ' ';
2314 $keywords_with_brackets_1before = array(
2321 $keywords_with_brackets_2before = array(
2333 // These reserved words do NOT get a newline placed near them.
2334 $keywords_no_newline = array(
2350 // These reserved words introduce a privilege list
2351 $keywords_priv_list = array(
2356 if ($number_of_tokens == -1) {
2357 $number_of_tokens = $arr['len'];
2360 if ($number_of_tokens >= 0) {
2364 $typearr[3] = $arr[$start_token]['type'];
2367 $in_priv_list = false;
2368 for ($i = $start_token; $i < $number_of_tokens; $i++
) {
2369 // DEBUG echo "Loop format <strong>" . $arr[$i]['data']
2370 // . "</strong> " . $arr[$i]['type'] . "<br />";
2373 // array_shift($typearr);
2380 if (($i +
1) < $number_of_tokens) {
2381 $typearr[4] = $arr[$i +
1]['type'];
2386 for ($j=0; $j<4; $j++
) {
2387 $typearr[$j] = $typearr[$j +
1];
2390 switch ($typearr[2]) {
2391 case 'alpha_bitfield_constant_introducer':
2395 case 'white_newline':
2398 case 'punct_bracket_open_round':
2400 $infunction = false;
2401 $keyword_brackets_2before = isset(
2402 $keywords_with_brackets_2before[strtoupper($arr[$i - 2]['data'])]
2404 $keyword_brackets_1before = isset(
2405 $keywords_with_brackets_1before[strtoupper($arr[$i - 1]['data'])]
2407 // Make sure this array is sorted!
2408 if (($typearr[1] == 'alpha_functionName')
2409 ||
($typearr[1] == 'alpha_columnType') ||
($typearr[1] == 'punct')
2410 ||
($typearr[3] == 'digit_integer') ||
($typearr[3] == 'digit_hex')
2411 ||
($typearr[3] == 'digit_float')
2412 ||
($typearr[0] == 'alpha_reservedWord' && $keyword_brackets_2before)
2413 ||
($typearr[1] == 'alpha_reservedWord' && $keyword_brackets_1before)
2420 if ($mode != 'query_only') {
2421 $after .= '<div class="syntax_indent' . $indent . '">';
2427 case 'alpha_identifier':
2428 if (($typearr[1] == 'punct_qualifier')
2429 ||
($typearr[3] == 'punct_qualifier')
2434 // for example SELECT 1 somealias
2435 if ($typearr[1] == 'digit_integer') {
2438 if (($typearr[3] == 'alpha_columnType')
2439 ||
($typearr[3] == 'alpha_identifier')
2445 case 'punct_qualifier':
2449 case 'punct_listsep':
2450 if ($infunction == true) {
2451 $after .= $space_punct_listsep_function_name;
2453 $after .= $space_punct_listsep;
2456 case 'punct_queryend':
2457 if (($typearr[3] != 'comment_mysql')
2458 && ($typearr[3] != 'comment_ansi')
2459 && $typearr[3] != 'comment_c'
2461 $after .= $html_line_break;
2462 $after .= $html_line_break;
2464 $space_punct_listsep = ' ';
2465 $space_punct_listsep_function_name = ' ';
2466 $space_alpha_reserved_word = ' ';
2467 $in_priv_list = false;
2469 case 'comment_mysql':
2470 case 'comment_ansi':
2471 $after .= $html_line_break;
2475 if ($docu && isset($PMA_SQPdata_operators_docs[$arr[$i]['data']])
2476 && ($arr[$i]['data'] != '*' ||
in_array($arr[$i]['type'], array('digit_integer','digit_float','digit_hex')))
2478 $before .= PMA_Util
::showMySQLDocu(
2480 $PMA_SQPdata_operators_docs[$arr[$i]['data']]['link'],
2482 $PMA_SQPdata_operators_docs[$arr[$i]['data']]['anchor'],
2489 // select * from mytable limit 0,-1
2490 // (a side effect of this workaround is that
2495 if ($typearr[3] != 'digit_integer') {
2499 case 'punct_bracket_close_round':
2500 // only close bracket level when it was opened before
2501 if ($bracketlevel > 0) {
2503 if ($infunction == true) {
2509 $before .= ($mode != 'query_only' ?
'</div>' : ' ');
2511 $infunction = ($functionlevel > 0) ?
true : false;
2514 case 'alpha_columnType':
2516 switch ($arr[$i]['data']) {
2529 $before .= PMA_Util
::showMySQLDocu(
2536 $after = '</a>' . $after;
2543 $before .= PMA_Util
::showMySQLDocu(
2545 'date-and-time-types',
2550 $after = '</a>' . $after;
2566 $before .= PMA_Util
::showMySQLDocu(
2573 $after = '</a>' . $after;
2577 if ($typearr[3] == 'alpha_columnAttrib') {
2580 if ($typearr[1] == 'alpha_columnType') {
2584 case 'alpha_columnAttrib':
2586 // ALTER TABLE tbl_name AUTO_INCREMENT = 1
2587 // COLLATE LATIN1_GENERAL_CI DEFAULT
2588 if ($typearr[1] == 'alpha_identifier'
2589 ||
$typearr[1] == 'alpha_charset'
2593 if (($typearr[3] == 'alpha_columnAttrib')
2594 ||
($typearr[3] == 'quote_single')
2595 ||
($typearr[3] == 'digit_integer')
2600 // AUTO_INCREMENT = 31DEFAULT_CHARSET = utf-8
2602 if ($typearr[2] == 'alpha_columnAttrib'
2603 && $typearr[3] == 'alpha_reservedWord'
2608 // select * from mysql.user where binary user="root"
2609 // binary is marked as alpha_columnAttrib
2610 // but should be marked as a reserved word
2611 if (strtoupper($arr[$i]['data']) == 'BINARY'
2612 && $typearr[3] == 'alpha_identifier'
2617 case 'alpha_functionName':
2618 $funcname = strtoupper($arr[$i]['data']);
2619 if ($docu && isset($PMA_SQPdata_functions_docs[$funcname])) {
2620 $before .= PMA_Util
::showMySQLDocu(
2622 $PMA_SQPdata_functions_docs[$funcname]['link'],
2624 $PMA_SQPdata_functions_docs[$funcname]['anchor'],
2630 case 'alpha_reservedWord':
2631 // do not uppercase the reserved word if we are calling
2632 // this function in query_only mode, because we need
2633 // the original query (otherwise we get problems with
2634 // semi-reserved words like "storage" which is legal
2635 // as an identifier name)
2637 if ($mode != 'query_only') {
2638 $arr[$i]['data'] = strtoupper($arr[$i]['data']);
2641 if ((($typearr[1] != 'alpha_reservedWord')
2642 ||
(($typearr[1] == 'alpha_reservedWord')
2643 && isset($keywords_no_newline[strtoupper($arr[$i - 1]['data'])])))
2644 && ($typearr[1] != 'punct_level_plus')
2645 && (!isset($keywords_no_newline[$arr[$i]['data']]))
2647 // do not put a space before the first token, because
2648 // we use a lot of pattern matching checking for the
2649 // first reserved word at beginning of query
2650 // so do not put a newline before
2652 // also we must not be inside a privilege list
2654 // the alpha_identifier exception is there to
2656 // GRANT SELECT ON mydb.mytable TO myuser@localhost
2657 // (else, we get mydb.mytableTO)
2659 // the quote_single exception is there to
2661 // GRANT ... TO 'marc'@'domain.com' IDENTIFIED...
2663 * @todo fix all cases and find why this happens
2667 ||
$typearr[1] == 'alpha_identifier'
2668 ||
$typearr[1] == 'quote_single'
2669 ||
$typearr[1] == 'white_newline'
2671 $before .= $space_alpha_reserved_word;
2674 // on first keyword, check if it introduces a
2676 if (isset($keywords_priv_list[$arr[$i]['data']])) {
2677 $in_priv_list = true;
2684 switch ($arr[$i]['data']) {
2694 switch ($arr[$i +
1]['data']) {
2705 $before .= PMA_Util
::showMySQLDocu(
2707 $arr[$i]['data'] . '_' . $arr[$i +
1]['data'],
2712 $close_docu_link = true;
2715 if ($arr[$i +
1]['data'] == 'LOGFILE'
2716 && $arr[$i +
2]['data'] == 'GROUP'
2718 $before .= PMA_Util
::showMySQLDocu(
2720 $arr[$i]['data'] . '_LOGFILE_GROUP',
2725 $close_docu_link = true;
2728 if (!$in_priv_list) {
2729 $space_punct_listsep = $html_line_break;
2730 $space_alpha_reserved_word = ' ';
2744 if ($close_docu_link) {
2745 $after = '</a>' . $after;
2746 $close_docu_link = false;
2751 && ($i == 0 ||
$arr[$i - 1]['data'] != 'CHARACTER')
2753 $before .= PMA_Util
::showMySQLDocu(
2760 $after = '</a>' . $after;
2762 if (!$in_priv_list) {
2763 $space_punct_listsep = $html_line_break;
2764 $space_alpha_reserved_word = ' ';
2773 $before .= PMA_Util
::showMySQLDocu(
2780 $after = '</a>' . $after;
2782 if (!$in_priv_list) {
2783 $space_punct_listsep = $html_line_break;
2784 $space_alpha_reserved_word = ' ';
2790 $before .= PMA_Util
::showMySQLDocu(
2797 $after = '</a>' . $after;
2799 if (!$in_priv_list) {
2800 $space_punct_listsep = $html_line_break;
2801 $space_alpha_reserved_word = $html_line_break;
2805 $space_punct_listsep = ' ';
2806 $space_alpha_reserved_word = $html_line_break;
2810 $before .= PMA_Util
::showMySQLDocu(
2817 $after = '</a>' . $after;
2819 $space_punct_listsep = ' ';
2820 $space_alpha_reserved_word = $html_line_break;
2826 $before .= PMA_Util
::showMySQLDocu(
2833 $after = '</a>' . $after;
2837 if ($close_docu_link
2840 array('LIKE', 'NOT', 'IN', 'REGEXP', 'NULL')
2844 $close_docu_link = false;
2846 && isset($PMA_SQPdata_functions_docs[$arr[$i]['data']])
2848 /* Handle multi word statements first */
2849 if (isset($typearr[4])
2850 && $typearr[4] == 'alpha_reservedWord'
2851 && $typearr[3] == 'alpha_reservedWord'
2852 && isset($PMA_SQPdata_functions_docs[strtoupper(
2853 $arr[$i]['data'] . '_'
2854 . $arr[$i +
1]['data'] . '_'
2855 . $arr[$i +
2]['data']
2858 $tempname = strtoupper(
2859 $arr[$i]['data'] . '_'
2860 . $arr[$i +
1]['data'] . '_'
2861 . $arr[$i +
2]['data']
2863 $before .= PMA_Util
::showMySQLDocu(
2865 $PMA_SQPdata_functions_docs[$tempname]['link'],
2867 $PMA_SQPdata_functions_docs[$tempname]['anchor'],
2870 $close_docu_link = true;
2871 } else if (isset($typearr[3])
2872 && $typearr[3] == 'alpha_reservedWord'
2873 && isset($PMA_SQPdata_functions_docs[strtoupper(
2874 $arr[$i]['data'] . '_' . $arr[$i +
1]['data']
2877 $tempname = strtoupper(
2878 $arr[$i]['data'] . '_' . $arr[$i +
1]['data']
2880 $before .= PMA_Util
::showMySQLDocu(
2882 $PMA_SQPdata_functions_docs[$tempname]['link'],
2884 $PMA_SQPdata_functions_docs[$tempname]['anchor'],
2887 $close_docu_link = true;
2889 $before .= PMA_Util
::showMySQLDocu(
2891 $PMA_SQPdata_functions_docs[$arr[$i]['data']]['link'],
2893 $PMA_SQPdata_functions_docs[$arr[$i]['data']]['anchor'],
2900 } // end switch ($arr[$i]['data'])
2904 case 'digit_integer':
2908 * @todo could there be other types preceding a digit?
2910 if ($typearr[1] == 'alpha_reservedWord') {
2913 if ($infunction && $typearr[3] == 'punct_bracket_close_round') {
2916 if ($typearr[1] == 'alpha_columnAttrib') {
2920 case 'alpha_variable':
2923 case 'quote_double':
2924 case 'quote_single':
2925 // workaround: for the query
2926 // REVOKE SELECT ON `base2\_db`.* FROM 'user'@'%'
2927 // the @ is incorrectly marked as alpha_variable
2928 // in the parser, and here, the '%' gets a blank before,
2929 // which is a syntax error
2930 if ($typearr[1] != 'punct_user'
2931 && $typearr[1] != 'alpha_bitfield_constant_introducer'
2935 if ($infunction && $typearr[3] == 'punct_bracket_close_round') {
2939 case 'quote_backtick':
2940 // here we check for punct_user to handle correctly
2941 // DEFINER = `username`@`%`
2942 // where @ is the punct_user and `%` is the quote_backtick
2943 if ($typearr[3] != 'punct_qualifier'
2944 && $typearr[3] != 'alpha_variable'
2945 && $typearr[3] != 'punct_user'
2949 if ($typearr[1] != 'punct_qualifier'
2950 && $typearr[1] != 'alpha_variable'
2951 && $typearr[1] != 'punct_user'
2958 } // end switch ($typearr[2])
2961 if ($typearr[3] != 'punct_qualifier') {
2967 if ($mode == 'text') {
2968 $str .= htmlspecialchars($arr[$i]['data']);
2970 $str .= $arr[$i]['data'];
2974 // close unclosed indent levels
2975 while ($indent > 0) {
2977 $str .= ($mode != 'query_only' ?
'</div>' : ' ');
2979 /* End possibly unclosed documentation link */
2980 if ($close_docu_link) {
2982 $close_docu_link = false;
2984 if ($mode!='query_only') {
2985 // close inner_sql span
2990 } // end of the "PMA_SQP_format()" function
2993 * Gets SQL queries with no format
2995 * @param array $arr The SQL queries list
2997 * @return string The SQL queries with no format
3001 function PMA_SQP_formatNone($arr)
3003 $formatted_sql = htmlspecialchars($arr['raw']);
3004 $formatted_sql = preg_replace(
3005 "@((\015\012)|(\015)|(\012)){3,}@",
3010 return $formatted_sql;
3011 } // end of the "PMA_SQP_formatNone()" function
3014 * Checks whether a given name is MySQL reserved word
3016 * @param string $column The word to be checked
3018 * @return boolean whether true or false
3020 function PMA_SQP_isKeyWord($column)
3022 global $PMA_SQPdata_forbidden_word;
3023 return in_array(strtoupper($column), $PMA_SQPdata_forbidden_word);