forked from phpmyadmin/phpmyadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlparser.lib.php
2682 lines (2436 loc) · 108 KB
/
sqlparser.lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/** SQL Parser Functions for phpMyAdmin
*
* These functions define an SQL parser system, capable of understanding and
* extracting data from a MySQL type SQL query.
*
* The basic procedure for using the new SQL parser:
* On any page that needs to extract data from a query or to pretty-print a
* query, you need code like this up at the top:
*
* ($sql contains the query)
* $parsed_sql = PMA_SQP_parse($sql);
*
* If you want to extract data from it then, you just need to run
* $sql_info = PMA_SQP_analyze($parsed_sql);
*
* See comments in PMA_SQP_analyze for the returned info
* from the analyzer.
*
* If you want a pretty-printed version of the query, do:
* $string = PMA_SQP_formatHtml($parsed_sql);
* (note that that you need to have syntax.css.php included somehow in your
* page for it to work, I recommend '<link rel="stylesheet" type="text/css"
* href="syntax.css.php" />' at the moment.)
*
* @package phpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Minimum inclusion? (i.e. for the stylesheet builder)
*/
if (! defined('PMA_MINIMUM_COMMON')) {
/**
* Include the string library as we use it heavily
*/
require_once './libraries/string.lib.php';
/**
* Include data for the SQL Parser
*/
require_once './libraries/sqlparser.data.php';
require_once './libraries/mysql_charsets.lib.php';
if (!isset($mysql_charsets)) {
$mysql_charsets = array();
$mysql_charsets_count = 0;
$mysql_collations_flat = array();
$mysql_collations_count = 0;
}
if (!defined('DEBUG_TIMING')) {
/**
* currently we don't need the $pos (token position in query)
* for other purposes than LIMIT clause verification,
* so many calls to this function do not include the 4th parameter
*/
function PMA_SQP_arrayAdd(&$arr, $type, $data, &$arrsize, $pos = 0)
{
$arr[] = array('type' => $type, 'data' => $data, 'pos' => $pos);
$arrsize++;
} // end of the "PMA_SQP_arrayAdd()" function
} else {
/**
* This is debug variant of above.
* @ignore
*/
function PMA_SQP_arrayAdd(&$arr, $type, $data, &$arrsize, $pos = 0)
{
global $timer;
$t = $timer;
$arr[] = array('type' => $type, 'data' => $data, 'pos' => $pos, 'time' => $t);
$timer = microtime();
$arrsize++;
} // end of the "PMA_SQP_arrayAdd()" function
} // end if... else...
/**
* Reset the error variable for the SQL parser
*
* @access public
*/
// Added, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_resetError()
{
global $SQP_errorString;
$SQP_errorString = '';
unset($SQP_errorString);
}
/**
* Get the contents of the error variable for the SQL parser
*
* @return string Error string from SQL parser
*
* @access public
*/
// Added, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_getErrorString()
{
global $SQP_errorString;
return isset($SQP_errorString) ? $SQP_errorString : '';
}
/**
* Check if the SQL parser hit an error
*
* @return boolean error state
*
* @access public
*/
// Added, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_isError()
{
global $SQP_errorString;
return isset($SQP_errorString) && !empty($SQP_errorString);
}
/**
* Set an error message for the system
*
* @param string The error message
* @param string The failing SQL query
*
* @access private
* @scope SQL Parser internal
*/
// Revised, Robbat2 - 13 Janurary 2003, 2:59PM
function PMA_SQP_throwError($message, $sql)
{
global $SQP_errorString;
$SQP_errorString = '<p>'.__('There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem') . '</p>' . "\n"
. '<pre>' . "\n"
. 'ERROR: ' . $message . "\n"
. 'SQL: ' . htmlspecialchars($sql) . "\n"
. '</pre>' . "\n";
} // end of the "PMA_SQP_throwError()" function
/**
* Do display the bug report
*
* @param string The error message
* @param string The failing SQL query
*
* @access public
*/
function PMA_SQP_bug($message, $sql)
{
global $SQP_errorString;
$debugstr = 'ERROR: ' . $message . "\n";
$debugstr .= 'SVN: $Id$' . "\n";
$debugstr .= 'MySQL: '.PMA_MYSQL_STR_VERSION . "\n";
$debugstr .= 'USR OS, AGENT, VER: ' . PMA_USR_OS . ' ' . PMA_USR_BROWSER_AGENT . ' ' . PMA_USR_BROWSER_VER . "\n";
$debugstr .= 'PMA: ' . PMA_VERSION . "\n";
$debugstr .= 'PHP VER,OS: ' . PMA_PHP_STR_VERSION . ' ' . PHP_OS . "\n";
$debugstr .= 'LANG: ' . $GLOBALS['lang'] . "\n";
$debugstr .= 'SQL: ' . htmlspecialchars($sql);
$encodedstr = $debugstr;
if (@function_exists('gzcompress')) {
$encodedstr = gzcompress($debugstr, 9);
}
$encodedstr = preg_replace("/(\015\012)|(\015)|(\012)/", '<br />' . "\n", chunk_split(base64_encode($encodedstr)));
$SQP_errorString .= __('There is a chance that you may have found a bug in the SQL parser. Please examine your query closely, and check that the quotes are correct and not mis-matched. Other possible failure causes may be that you are uploading a file with binary outside of a quoted text area. You can also try your query on the MySQL command line interface. The MySQL server error output below, if there is any, may also help you in diagnosing the problem. If you still have problems or if the parser fails where the command line interface succeeds, please reduce your SQL query input to the single query that causes problems, and submit a bug report with the data chunk in the CUT section below:')
. '<br />' . "\n"
. '----' . __('BEGIN CUT') . '----' . '<br />' . "\n"
. $encodedstr . "\n"
. '----' . __('END CUT') . '----' . '<br />' . "\n";
$SQP_errorString .= '----' . __('BEGIN RAW') . '----<br />' . "\n"
. '<pre>' . "\n"
. $debugstr
. '</pre>' . "\n"
. '----' . __('END RAW') . '----<br />' . "\n";
} // end of the "PMA_SQP_bug()" function
/**
* Parses the SQL queries
*
* @param string The SQL query list
*
* @return mixed Most of times, nothing...
*
* @global array The current PMA configuration
* @global array MySQL column attributes
* @global array MySQL reserved words
* @global array MySQL column types
* @global array MySQL function names
* @global integer MySQL column attributes count
* @global integer MySQL reserved words count
* @global integer MySQL column types count
* @global integer MySQL function names count
* @global array List of available character sets
* @global array List of available collations
* @global integer Character sets count
* @global integer Collations count
*
* @access public
*/
function PMA_SQP_parse($sql)
{
global $cfg;
global $PMA_SQPdata_column_attrib, $PMA_SQPdata_reserved_word, $PMA_SQPdata_column_type, $PMA_SQPdata_function_name,
$PMA_SQPdata_column_attrib_cnt, $PMA_SQPdata_reserved_word_cnt, $PMA_SQPdata_column_type_cnt, $PMA_SQPdata_function_name_cnt;
global $mysql_charsets, $mysql_collations_flat, $mysql_charsets_count, $mysql_collations_count;
global $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt;
// Convert all line feeds to Unix style
$sql = str_replace("\r\n", "\n", $sql);
$sql = str_replace("\r", "\n", $sql);
$len = PMA_strlen($sql);
if ($len == 0) {
return array();
}
$sql_array = array();
$sql_array['raw'] = $sql;
$count1 = 0;
$count2 = 0;
$punct_queryend = ';';
$punct_qualifier = '.';
$punct_listsep = ',';
$punct_level_plus = '(';
$punct_level_minus = ')';
$punct_user = '@';
$digit_floatdecimal = '.';
$digit_hexset = 'x';
$bracket_list = '()[]{}';
$allpunct_list = '-,;:!?/.^~\*&%+<=>|';
$allpunct_list_pair = array (
0 => '!=',
1 => '&&',
2 => ':=',
3 => '<<',
4 => '<=',
5 => '<=>',
6 => '<>',
7 => '>=',
8 => '>>',
9 => '||'
);
$allpunct_list_pair_size = 10; //count($allpunct_list_pair);
$quote_list = '\'"`';
$arraysize = 0;
$previous_was_space = false;
$this_was_space = false;
$previous_was_bracket = false;
$this_was_bracket = false;
$previous_was_punct = false;
$this_was_punct = false;
$previous_was_listsep = false;
$this_was_listsep = false;
$previous_was_quote = false;
$this_was_quote = false;
while ($count2 < $len) {
$c = $GLOBALS['PMA_substr']($sql, $count2, 1);
$count1 = $count2;
$previous_was_space = $this_was_space;
$this_was_space = false;
$previous_was_bracket = $this_was_bracket;
$this_was_bracket = false;
$previous_was_punct = $this_was_punct;
$this_was_punct = false;
$previous_was_listsep = $this_was_listsep;
$this_was_listsep = false;
$previous_was_quote = $this_was_quote;
$this_was_quote = false;
if (($c == "\n")) {
$this_was_space = true;
$count2++;
PMA_SQP_arrayAdd($sql_array, 'white_newline', '', $arraysize);
continue;
}
// Checks for white space
if ($GLOBALS['PMA_STR_isSpace']($c)) {
$this_was_space = true;
$count2++;
continue;
}
// Checks for comment lines.
// MySQL style #
// C style /* */
// ANSI style --
if (($c == '#')
|| (($count2 + 1 < $len) && ($c == '/') && ($GLOBALS['PMA_substr']($sql, $count2 + 1, 1) == '*'))
|| (($count2 + 2 == $len) && ($c == '-') && ($GLOBALS['PMA_substr']($sql, $count2 + 1, 1) == '-'))
|| (($count2 + 2 < $len) && ($c == '-') && ($GLOBALS['PMA_substr']($sql, $count2 + 1, 1) == '-') && (($GLOBALS['PMA_substr']($sql, $count2 + 2, 1) <= ' ')))) {
$count2++;
$pos = 0;
$type = 'bad';
switch ($c) {
case '#':
$type = 'mysql';
case '-':
$type = 'ansi';
$pos = $GLOBALS['PMA_strpos']($sql, "\n", $count2);
break;
case '/':
$type = 'c';
$pos = $GLOBALS['PMA_strpos']($sql, '*/', $count2);
$pos += 2;
break;
default:
break;
} // end switch
$count2 = ($pos < $count2) ? $len : $pos;
$str = $GLOBALS['PMA_substr']($sql, $count1, $count2 - $count1);
PMA_SQP_arrayAdd($sql_array, 'comment_' . $type, $str, $arraysize);
continue;
} // end if
// Checks for something inside quotation marks
if ($GLOBALS['PMA_strpos']($quote_list, $c) !== false) {
$startquotepos = $count2;
$quotetype = $c;
$count2++;
$escaped = FALSE;
$escaped_escaped = FALSE;
$pos = $count2;
$oldpos = 0;
do {
$oldpos = $pos;
$pos = $GLOBALS['PMA_strpos'](' ' . $sql, $quotetype, $oldpos + 1) - 1;
// ($pos === FALSE)
if ($pos < 0) {
$debugstr = __('Unclosed quote') . ' @ ' . $startquotepos. "\n"
. 'STR: ' . htmlspecialchars($quotetype);
PMA_SQP_throwError($debugstr, $sql);
return $sql_array;
}
// If the quote is the first character, it can't be
// escaped, so don't do the rest of the code
if ($pos == 0) {
break;
}
// Checks for MySQL escaping using a \
// And checks for ANSI escaping using the $quotetype character
if (($pos < $len) && PMA_STR_charIsEscaped($sql, $pos)) {
$pos ++;
continue;
} elseif (($pos + 1 < $len) && ($GLOBALS['PMA_substr']($sql, $pos, 1) == $quotetype) && ($GLOBALS['PMA_substr']($sql, $pos + 1, 1) == $quotetype)) {
$pos = $pos + 2;
continue;
} else {
break;
}
} while ($len > $pos); // end do
$count2 = $pos;
$count2++;
$type = 'quote_';
switch ($quotetype) {
case '\'':
$type .= 'single';
$this_was_quote = true;
break;
case '"':
$type .= 'double';
$this_was_quote = true;
break;
case '`':
$type .= 'backtick';
$this_was_quote = true;
break;
default:
break;
} // end switch
$data = $GLOBALS['PMA_substr']($sql, $count1, $count2 - $count1);
PMA_SQP_arrayAdd($sql_array, $type, $data, $arraysize);
continue;
}
// Checks for brackets
if ($GLOBALS['PMA_strpos']($bracket_list, $c) !== false) {
// All bracket tokens are only one item long
$this_was_bracket = true;
$count2++;
$type_type = '';
if ($GLOBALS['PMA_strpos']('([{', $c) !== false) {
$type_type = 'open';
} else {
$type_type = 'close';
}
$type_style = '';
if ($GLOBALS['PMA_strpos']('()', $c) !== false) {
$type_style = 'round';
} elseif ($GLOBALS['PMA_strpos']('[]', $c) !== false) {
$type_style = 'square';
} else {
$type_style = 'curly';
}
$type = 'punct_bracket_' . $type_type . '_' . $type_style;
PMA_SQP_arrayAdd($sql_array, $type, $c, $arraysize);
continue;
}
/* DEBUG
echo '<pre>1';
var_dump(PMA_STR_isSqlIdentifier($c, false));
var_dump($c == '@');
var_dump($c == '.');
var_dump(PMA_STR_isDigit(PMA_substr($sql, $count2 + 1, 1)));
var_dump($previous_was_space);
var_dump($previous_was_bracket);
var_dump($previous_was_listsep);
echo '</pre>';
*/
// Checks for identifier (alpha or numeric)
if (PMA_STR_isSqlIdentifier($c, false)
|| $c == '@'
|| ($c == '.'
&& $GLOBALS['PMA_STR_isDigit']($GLOBALS['PMA_substr']($sql, $count2 + 1, 1))
&& ($previous_was_space || $previous_was_bracket || $previous_was_listsep))) {
/* DEBUG
echo PMA_substr($sql, $count2);
echo '<hr />';
*/
$count2++;
/**
* @todo a @ can also be present in expressions like
* FROM 'user'@'%' or TO 'user'@'%'
* in this case, the @ is wrongly marked as alpha_variable
*/
$is_identifier = $previous_was_punct;
$is_sql_variable = $c == '@' && ! $previous_was_quote;
$is_user = $c == '@' && $previous_was_quote;
$is_digit = !$is_identifier && !$is_sql_variable && $GLOBALS['PMA_STR_isDigit']($c);
$is_hex_digit = $is_digit && $c == '0' && $count2 < $len && $GLOBALS['PMA_substr']($sql, $count2, 1) == 'x';
$is_float_digit = $c == '.';
$is_float_digit_exponent = FALSE;
/* DEBUG
echo '<pre>2';
var_dump($is_identifier);
var_dump($is_sql_variable);
var_dump($is_digit);
var_dump($is_float_digit);
echo '</pre>';
*/
// Nijel: Fast skip is especially needed for huge BLOB data, requires PHP at least 4.3.0:
if ($is_hex_digit) {
$count2++;
$pos = strspn($sql, '0123456789abcdefABCDEF', $count2);
if ($pos > $count2) {
$count2 = $pos;
}
unset($pos);
} elseif ($is_digit) {
$pos = strspn($sql, '0123456789', $count2);
if ($pos > $count2) {
$count2 = $pos;
}
unset($pos);
}
while (($count2 < $len) && PMA_STR_isSqlIdentifier($GLOBALS['PMA_substr']($sql, $count2, 1), ($is_sql_variable || $is_digit))) {
$c2 = $GLOBALS['PMA_substr']($sql, $count2, 1);
if ($is_sql_variable && ($c2 == '.')) {
$count2++;
continue;
}
if ($is_digit && (!$is_hex_digit) && ($c2 == '.')) {
$count2++;
if (!$is_float_digit) {
$is_float_digit = TRUE;
continue;
} else {
$debugstr = __('Invalid Identifer') . ' @ ' . ($count1+1) . "\n"
. 'STR: ' . htmlspecialchars(PMA_substr($sql, $count1, $count2 - $count1));
PMA_SQP_throwError($debugstr, $sql);
return $sql_array;
}
}
if ($is_digit && (!$is_hex_digit) && (($c2 == 'e') || ($c2 == 'E'))) {
if (!$is_float_digit_exponent) {
$is_float_digit_exponent = TRUE;
$is_float_digit = TRUE;
$count2++;
continue;
} else {
$is_digit = FALSE;
$is_float_digit = FALSE;
}
}
if (($is_hex_digit && PMA_STR_isHexDigit($c2)) || ($is_digit && $GLOBALS['PMA_STR_isDigit']($c2))) {
$count2++;
continue;
} else {
$is_digit = FALSE;
$is_hex_digit = FALSE;
}
$count2++;
} // end while
$l = $count2 - $count1;
$str = $GLOBALS['PMA_substr']($sql, $count1, $l);
$type = '';
if ($is_digit || $is_float_digit || $is_hex_digit) {
$type = 'digit';
if ($is_float_digit) {
$type .= '_float';
} elseif ($is_hex_digit) {
$type .= '_hex';
} else {
$type .= '_integer';
}
} elseif ($is_user) {
$type = 'punct_user';
} elseif ($is_sql_variable != FALSE) {
$type = 'alpha_variable';
} else {
$type = 'alpha';
} // end if... else....
PMA_SQP_arrayAdd($sql_array, $type, $str, $arraysize, $count2);
continue;
}
// Checks for punct
if ($GLOBALS['PMA_strpos']($allpunct_list, $c) !== false) {
while (($count2 < $len) && $GLOBALS['PMA_strpos']($allpunct_list, $GLOBALS['PMA_substr']($sql, $count2, 1)) !== false) {
$count2++;
}
$l = $count2 - $count1;
if ($l == 1) {
$punct_data = $c;
} else {
$punct_data = $GLOBALS['PMA_substr']($sql, $count1, $l);
}
// Special case, sometimes, althought two characters are
// adjectent directly, they ACTUALLY need to be seperate
/* DEBUG
echo '<pre>';
var_dump($l);
var_dump($punct_data);
echo '</pre>';
*/
if ($l == 1) {
$t_suffix = '';
switch ($punct_data) {
case $punct_queryend:
$t_suffix = '_queryend';
break;
case $punct_qualifier:
$t_suffix = '_qualifier';
$this_was_punct = true;
break;
case $punct_listsep:
$this_was_listsep = true;
$t_suffix = '_listsep';
break;
default:
break;
}
PMA_SQP_arrayAdd($sql_array, 'punct' . $t_suffix, $punct_data, $arraysize);
} elseif ($punct_data == $GLOBALS['sql_delimiter'] || PMA_STR_binarySearchInArr($punct_data, $allpunct_list_pair, $allpunct_list_pair_size)) {
// Ok, we have one of the valid combined punct expressions
PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize);
} else {
// Bad luck, lets split it up more
$first = $punct_data[0];
$first2 = $punct_data[0] . $punct_data[1];
$last2 = $punct_data[$l - 2] . $punct_data[$l - 1];
$last = $punct_data[$l - 1];
if (($first == ',') || ($first == ';') || ($first == '.') || ($first == '*')) {
$count2 = $count1 + 1;
$punct_data = $first;
} elseif (($last2 == '/*') || (($last2 == '--') && ($count2 == $len || $GLOBALS['PMA_substr']($sql, $count2, 1) <= ' '))) {
$count2 -= 2;
$punct_data = $GLOBALS['PMA_substr']($sql, $count1, $count2 - $count1);
} elseif (($last == '-') || ($last == '+') || ($last == '!')) {
$count2--;
$punct_data = $GLOBALS['PMA_substr']($sql, $count1, $count2 - $count1);
/**
* @todo for negation operator, split in 2 tokens ?
* "select x&~1 from t"
* becomes "select x & ~ 1 from t" ?
*/
} elseif ($last != '~') {
$debugstr = __('Unknown Punctuation String') . ' @ ' . ($count1+1) . "\n"
. 'STR: ' . htmlspecialchars($punct_data);
PMA_SQP_throwError($debugstr, $sql);
return $sql_array;
}
PMA_SQP_arrayAdd($sql_array, 'punct', $punct_data, $arraysize);
continue;
} // end if... elseif... else
continue;
}
// DEBUG
$count2++;
$debugstr = 'C1 C2 LEN: ' . $count1 . ' ' . $count2 . ' ' . $len . "\n"
. 'STR: ' . $GLOBALS['PMA_substr']($sql, $count1, $count2 - $count1) . "\n";
PMA_SQP_bug($debugstr, $sql);
return $sql_array;
} // end while ($count2 < $len)
/*
echo '<pre>';
print_r($sql_array);
echo '</pre>';
*/
if ($arraysize > 0) {
$t_next = $sql_array[0]['type'];
$t_prev = '';
$t_bef_prev = '';
$t_cur = '';
$d_next = $sql_array[0]['data'];
$d_prev = '';
$d_bef_prev = '';
$d_cur = '';
$d_next_upper = $t_next == 'alpha' ? strtoupper($d_next) : $d_next;
$d_prev_upper = '';
$d_bef_prev_upper = '';
$d_cur_upper = '';
}
for ($i = 0; $i < $arraysize; $i++) {
$t_bef_prev = $t_prev;
$t_prev = $t_cur;
$t_cur = $t_next;
$d_bef_prev = $d_prev;
$d_prev = $d_cur;
$d_cur = $d_next;
$d_bef_prev_upper = $d_prev_upper;
$d_prev_upper = $d_cur_upper;
$d_cur_upper = $d_next_upper;
if (($i + 1) < $arraysize) {
$t_next = $sql_array[$i + 1]['type'];
$d_next = $sql_array[$i + 1]['data'];
$d_next_upper = $t_next == 'alpha' ? strtoupper($d_next) : $d_next;
} else {
$t_next = '';
$d_next = '';
$d_next_upper = '';
}
//DEBUG echo "[prev: <strong>".$d_prev."</strong> ".$t_prev."][cur: <strong>".$d_cur."</strong> ".$t_cur."][next: <strong>".$d_next."</strong> ".$t_next."]<br />";
if ($t_cur == 'alpha') {
$t_suffix = '_identifier';
// for example: `thebit` bit(8) NOT NULL DEFAULT b'0'
if ($t_prev == 'alpha' && $d_prev == 'DEFAULT' && $d_cur == 'b' && $t_next == 'quote_single') {
$t_suffix = '_bitfield_constant_introducer';
} elseif (($t_next == 'punct_qualifier') || ($t_prev == 'punct_qualifier')) {
$t_suffix = '_identifier';
} elseif (($t_next == 'punct_bracket_open_round')
&& PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_function_name, $PMA_SQPdata_function_name_cnt)) {
/**
* @todo 2005-10-16: in the case of a CREATE TABLE containing
* a TIMESTAMP, since TIMESTAMP() is also a function, it's
* found here and the token is wrongly marked as alpha_functionName.
* But we compensate for this when analysing for timestamp_not_null
* later in this script.
*
* Same applies to CHAR vs. CHAR() function.
*/
$t_suffix = '_functionName';
/* There are functions which might be as well column types */
} elseif (PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_column_type, $PMA_SQPdata_column_type_cnt)) {
$t_suffix = '_columnType';
/**
* Temporary fix for BUG #621357 and #2027720
*
* @todo FIX PROPERLY NEEDS OVERHAUL OF SQL TOKENIZER
*/
if (($d_cur_upper == 'SET' || $d_cur_upper == 'BINARY') && $t_next != 'punct_bracket_open_round') {
$t_suffix = '_reservedWord';
}
//END OF TEMPORARY FIX
// CHARACTER is a synonym for CHAR, but can also be meant as
// CHARACTER SET. In this case, we have a reserved word.
if ($d_cur_upper == 'CHARACTER' && $d_next_upper == 'SET') {
$t_suffix = '_reservedWord';
}
// experimental
// current is a column type, so previous must not be
// a reserved word but an identifier
// CREATE TABLE SG_Persons (first varchar(64))
//if ($sql_array[$i-1]['type'] =='alpha_reservedWord') {
// $sql_array[$i-1]['type'] = 'alpha_identifier';
//}
} elseif (PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_reserved_word, $PMA_SQPdata_reserved_word_cnt)) {
$t_suffix = '_reservedWord';
} elseif (PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_column_attrib, $PMA_SQPdata_column_attrib_cnt)) {
$t_suffix = '_columnAttrib';
// INNODB is a MySQL table type, but in "SHOW INNODB STATUS",
// it should be regarded as a reserved word.
if ($d_cur_upper == 'INNODB' && $d_prev_upper == 'SHOW' && $d_next_upper == 'STATUS') {
$t_suffix = '_reservedWord';
}
if ($d_cur_upper == 'DEFAULT' && $d_next_upper == 'CHARACTER') {
$t_suffix = '_reservedWord';
}
// Binary as character set
if ($d_cur_upper == 'BINARY' && (
($d_bef_prev_upper == 'CHARACTER' && $d_prev_upper == 'SET')
|| ($d_bef_prev_upper == 'SET' && $d_prev_upper == '=')
|| ($d_bef_prev_upper == 'CHARSET' && $d_prev_upper == '=')
|| $d_prev_upper == 'CHARSET'
) && PMA_STR_binarySearchInArr($d_cur, $mysql_charsets, count($mysql_charsets))) {
$t_suffix = '_charset';
}
} elseif (PMA_STR_binarySearchInArr($d_cur, $mysql_charsets, $mysql_charsets_count)
|| PMA_STR_binarySearchInArr($d_cur, $mysql_collations_flat, $mysql_collations_count)
|| ($d_cur{0} == '_' && PMA_STR_binarySearchInArr(substr($d_cur, 1), $mysql_charsets, $mysql_charsets_count))) {
$t_suffix = '_charset';
} else {
// Do nothing
}
// check if present in the list of forbidden words
if ($t_suffix == '_reservedWord' && PMA_STR_binarySearchInArr($d_cur_upper, $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
$sql_array[$i]['forbidden'] = TRUE;
} else {
$sql_array[$i]['forbidden'] = FALSE;
}
$sql_array[$i]['type'] .= $t_suffix;
}
} // end for
// Stores the size of the array inside the array, as count() is a slow
// operation.
$sql_array['len'] = $arraysize;
// DEBUG echo 'After parsing<pre>'; print_r($sql_array); echo '</pre>';
// Sends the data back
return $sql_array;
} // end of the "PMA_SQP_parse()" function
/**
* Checks for token types being what we want...
*
* @param string String of type that we have
* @param string String of type that we want
*
* @return boolean result of check
*
* @access private
*/
function PMA_SQP_typeCheck($toCheck, $whatWeWant)
{
$typeSeperator = '_';
if (strcmp($whatWeWant, $toCheck) == 0) {
return TRUE;
} else {
if (strpos($whatWeWant, $typeSeperator) === FALSE) {
return strncmp($whatWeWant, $toCheck, strpos($toCheck, $typeSeperator)) == 0;
} else {
return FALSE;
}
}
}
/**
* Analyzes SQL queries
*
* @param array The SQL queries
*
* @return array The analyzed SQL queries
*
* @access public
*/
function PMA_SQP_analyze($arr)
{
if ($arr == array()) {
return array();
}
$result = array();
$size = $arr['len'];
$subresult = array(
'querytype' => '',
'select_expr_clause'=> '', // the whole stuff between SELECT and FROM , except DISTINCT
'position_of_first_select' => '', // the array index
'from_clause'=> '',
'group_by_clause'=> '',
'order_by_clause'=> '',
'having_clause' => '',
'limit_clause' => '',
'where_clause' => '',
'where_clause_identifiers' => array(),
'unsorted_query' => '',
'queryflags' => array(),
'select_expr' => array(),
'table_ref' => array(),
'foreign_keys' => array(),
'create_table_fields' => array()
);
$subresult_empty = $subresult;
$seek_queryend = FALSE;
$seen_end_of_table_ref = FALSE;
$number_of_brackets_in_extract = 0;
$number_of_brackets_in_group_concat = 0;
$number_of_brackets = 0;
$in_subquery = false;
$seen_subquery = false;
$seen_from = false;
// for SELECT EXTRACT(YEAR_MONTH FROM CURDATE())
// we must not use CURDATE as a table_ref
// so we track whether we are in the EXTRACT()
$in_extract = FALSE;
// for GROUP_CONCAT(...)
$in_group_concat = FALSE;
/* Description of analyzer results
*
* db, table, column, alias
* ------------------------
*
* Inside the $subresult array, we create ['select_expr'] and ['table_ref'] arrays.
*
* The SELECT syntax (simplified) is
*
* SELECT
* select_expression,...
* [FROM [table_references]
*
*
* ['select_expr'] is filled with each expression, the key represents the
* expression position in the list (0-based) (so we don't lose track of
* multiple occurences of the same column).
*
* ['table_ref'] is filled with each table ref, same thing for the key.
*
* I create all sub-values empty, even if they are
* not present (for example no select_expression alias).
*
* There is a debug section at the end of loop #1, if you want to
* see the exact contents of select_expr and table_ref
*
* queryflags
* ----------
*
* In $subresult, array 'queryflags' is filled, according to what we
* find in the query.
*
* Currently, those are generated:
*
* ['queryflags']['need_confirm'] = 1; if the query needs confirmation
* ['queryflags']['select_from'] = 1; if this is a real SELECT...FROM
* ['queryflags']['distinct'] = 1; for a DISTINCT
* ['queryflags']['union'] = 1; for a UNION
* ['queryflags']['join'] = 1; for a JOIN
* ['queryflags']['offset'] = 1; for the presence of OFFSET
* ['queryflags']['procedure'] = 1; for the presence of PROCEDURE
*
* query clauses
* -------------
*
* The select is splitted in those clauses:
* ['select_expr_clause']
* ['from_clause']
* ['group_by_clause']
* ['order_by_clause']
* ['having_clause']
* ['limit_clause']
* ['where_clause']
*
* The identifiers of the WHERE clause are put into the array
* ['where_clause_identifier']
*
* For a SELECT, the whole query without the ORDER BY clause is put into
* ['unsorted_query']
*
* foreign keys
* ------------
* The CREATE TABLE may contain FOREIGN KEY clauses, so they get
* analyzed and ['foreign_keys'] is an array filled with
* the constraint name, the index list,
* the REFERENCES table name and REFERENCES index list,
* and ON UPDATE | ON DELETE clauses
*
* position_of_first_select
* ------------------------
*
* The array index of the first SELECT we find. Will be used to
* insert a SQL_CALC_FOUND_ROWS.
*
* create_table_fields
* -------------------
*
* Used to detect the DEFAULT CURRENT_TIMESTAMP and
* ON UPDATE CURRENT_TIMESTAMP clauses of the CREATE TABLE query.
* Also used to store the default value of the field.
* An array, each element is the identifier name.
* Note that for now, the timestamp_not_null element is created
* even for non-TIMESTAMP fields.
*
* Sub-elements: ['type'] which contains the column type
* optional (currently they are never false but can be absent):
* ['default_current_timestamp'] boolean
* ['on_update_current_timestamp'] boolean
* ['timestamp_not_null'] boolean
*
* section_before_limit, section_after_limit
* -----------------------------------------
*
* Marks the point of the query where we can insert a LIMIT clause;
* so the section_before_limit will contain the left part before
* a possible LIMIT clause
*
*
* End of description of analyzer results
*/
// must be sorted
// TODO: current logic checks for only one word, so I put only the
// first word of the reserved expressions that end a table ref;
// maybe this is not ok (the first word might mean something else)
// $words_ending_table_ref = array(
// 'FOR UPDATE',
// 'GROUP BY',
// 'HAVING',
// 'LIMIT',
// 'LOCK IN SHARE MODE',
// 'ORDER BY',
// 'PROCEDURE',
// 'UNION',
// 'WHERE'
// );
$words_ending_table_ref = array(
'FOR',
'GROUP',
'HAVING',
'LIMIT',
'LOCK',
'ORDER',
'PROCEDURE',
'UNION',
'WHERE'
);
$words_ending_table_ref_cnt = 9; //count($words_ending_table_ref);
$words_ending_clauses = array(
'FOR',
'LIMIT',
'LOCK',
'PROCEDURE',
'UNION'
);
$words_ending_clauses_cnt = 5; //count($words_ending_clauses);
// must be sorted
$supported_query_types = array(
'SELECT'
/*
// Support for these additional query types will come later on.
'DELETE',
'INSERT',
'REPLACE',
'TRUNCATE',
'UPDATE'
'EXPLAIN',