-
Notifications
You must be signed in to change notification settings - Fork 18
/
php-sql-parser.php
1624 lines (1377 loc) · 58.8 KB
/
php-sql-parser.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
/**
* php-sql-parser.php
*
* A pure PHP SQL (non validating) parser w/ focus on MySQL dialect of SQL
*
* Copyright (c) 2010-2012, Justin Swanhart
* with contributions by André Rothe <[email protected], [email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
if (!defined('HAVE_PHP_SQL_PARSER')) {
require_once(dirname(__FILE__) . '/classes/expression-types.php');
require_once(dirname(__FILE__) . '/classes/expression-token.php');
require_once(dirname(__FILE__) . '/classes/parser-utils.php');
require_once(dirname(__FILE__) . '/classes/lexer.php');
require_once(dirname(__FILE__) . '/classes/position-calculator.php');
/**
* This class implements the parser functionality.
* @author [email protected]
* @author [email protected]
*/
class PHPSQLParser extends PHPSQLParserUtils {
private $lexer;
public function __construct($sql = false, $calcPositions = false) {
$this->lexer = new PHPSQLLexer();
if ($sql) {
$this->parse($sql, $calcPositions);
}
}
public function parse($sql, $calcPositions = false) {
#lex the SQL statement
$inputArray = $this->splitSQLIntoTokens($sql);
#This is the highest level lexical analysis. This is the part of the
#code which finds UNION and UNION ALL query parts
$queries = $this->processUnion($inputArray);
# If there was no UNION or UNION ALL in the query, then the query is
# stored at $queries[0].
if (!$this->isUnion($queries)) {
$queries = $this->processSQL($queries[0]);
}
# calc the positions of some important tokens
if ($calcPositions) {
$calculator = new PositionCalculator();
$queries = $calculator->setPositionsWithinSQL($sql, $queries);
}
# store the parsed queries
$this->parsed = $queries;
return $this->parsed;
}
private function processUnion($inputArray) {
$outputArray = array();
#sometimes the parser needs to skip ahead until a particular
#token is found
$skipUntilToken = false;
#This is the last type of union used (UNION or UNION ALL)
#indicates a) presence of at least one union in this query
# b) the type of union if this is the first or last query
$unionType = false;
#Sometimes a "query" consists of more than one query (like a UNION query)
#this array holds all the queries
$queries = array();
foreach ($inputArray as $key => $token) {
$trim = trim($token);
# overread all tokens till that given token
if ($skipUntilToken) {
if ($trim === "") {
continue; # read the next token
}
if (strtoupper($trim) === $skipUntilToken) {
$skipUntilToken = false;
continue; # read the next token
}
}
if (strtoupper($trim) !== "UNION") {
$outputArray[] = $token; # here we get empty tokens, if we remove these, we get problems in parse_sql()
continue;
}
$unionType = "UNION";
# we are looking for an ALL token right after UNION
for ($i = $key + 1; $i < count($inputArray); ++$i) {
if (trim($inputArray[$i]) === "") {
continue;
}
if (strtoupper($inputArray[$i]) !== "ALL") {
break;
}
# the other for-loop should overread till "ALL"
$skipUntilToken = "ALL";
$unionType = "UNION ALL";
}
# store the tokens related to the unionType
$queries[$unionType][] = $outputArray;
$outputArray = array();
}
# the query tokens after the last UNION or UNION ALL
# or we don't have an UNION/UNION ALL
if (!empty($outputArray)) {
if ($unionType) {
$queries[$unionType][] = $outputArray;
} else {
$queries[] = $outputArray;
}
}
return $this->processMySQLUnion($queries);
}
/** MySQL supports a special form of UNION:
* (select ...)
* union
* (select ...)
*
* This function handles this query syntax. Only one such subquery
* is supported in each UNION block. (select)(select)union(select) is not legal.
* The extra queries will be silently ignored.
*/
private function processMySQLUnion($queries) {
$unionTypes = array('UNION', 'UNION ALL');
foreach ($unionTypes as $unionType) {
if (empty($queries[$unionType])) {
continue;
}
foreach ($queries[$unionType] as $key => $tokenList) {
foreach ($tokenList as $z => $token) {
$token = trim($token);
if ($token === "") {
continue;
}
# starts with "(select"
if (preg_match("/^\\(\\s*select\\s*/i", $token)) {
$queries[$unionType][$key] = $this->parse($this->removeParenthesisFromStart($token));
break;
}
$queries[$unionType][$key] = $this->processSQL($queries[$unionType][$key]);
break;
}
}
}
# it can be parsed or not
return $queries;
}
private function isUnion($queries) {
$unionTypes = array('UNION', 'UNION ALL');
foreach ($unionTypes as $unionType) {
if (!empty($queries[$unionType])) {
return true;
}
}
return false;
}
#this function splits up a SQL statement into easy to "parse"
#tokens for the SQL processor
private function splitSQLIntoTokens($sql) {
return $this->lexer->split($sql);
}
/* This function breaks up the SQL statement into logical sections.
Some sections are then further handled by specialized functions.
*/
private function processSQL(&$tokens) {
$prev_category = "";
$token_category = "";
$skip_next = false;
$out = false;
$tokenCount = count($tokens);
for ($tokenNumber = 0; $tokenNumber < $tokenCount; ++$tokenNumber) {
$token = $tokens[$tokenNumber];
$trim = trim($token); # this removes also \n and \t!
# if it starts with an "(", it should follow a SELECT
if ($trim !== "" && $trim[0] === "(" && $token_category === "") {
$token_category = 'SELECT';
}
/* If it isn't obvious, when $skip_next is set, then we ignore the next real
token, that is we ignore whitespace.
*/
if ($skip_next) {
if ($trim === "") {
if ($token_category !== "") { # is this correct??
$out[$token_category][] = $token;
}
continue;
}
#to skip the token we replace it with whitespace
$trim = "";
$token = "";
$skip_next = false;
}
$upper = strtoupper($trim);
switch ($upper) {
/* Tokens that get their own sections. These keywords have subclauses. */
case 'SELECT':
case 'ORDER':
case 'LIMIT':
case 'SET':
case 'DUPLICATE':
case 'VALUES':
case 'GROUP':
case 'HAVING':
case 'WHERE':
case 'RENAME':
case 'CALL':
case 'PROCEDURE':
case 'FUNCTION':
case 'SERVER':
case 'LOGFILE':
case 'DEFINER':
case 'RETURNS':
case 'TABLESPACE':
case 'TRIGGER':
case 'DO':
case 'PLUGIN':
case 'FROM':
case 'FLUSH':
case 'KILL':
case 'RESET':
case 'START':
case 'STOP':
case 'PURGE':
case 'EXECUTE':
case 'PREPARE':
case 'DEALLOCATE':
if ($trim === 'DEALLOCATE') {
$skip_next = true;
}
/* this FROM is different from FROM in other DML (not join related) */
if ($token_category === 'PREPARE' && $upper === 'FROM') {
continue 2;
}
$token_category = $upper;
break;
case 'DATABASE':
case 'SCHEMA':
if ($prev_category === 'DROP') {
continue;
}
$token_category = $upper;
break;
case 'EVENT':
# issue 71
if ($prev_category === 'DROP' || $prev_category === 'ALTER' || $prev_category === 'CREATE') {
$token_category = $upper;
}
break;
case 'DATA':
# prevent wrong handling of DATA as keyword
if ($prev_category === 'LOAD') {
$token_category = $upper;
}
break;
case 'INTO':
# prevent wrong handling of CACHE within LOAD INDEX INTO CACHE...
if ($prev_category === 'LOAD') {
$out[$prev_category][] = $upper;
continue 2;
}
$token_category = $upper;
break;
case 'USER':
# prevent wrong processing as keyword
if ($prev_category === 'CREATE' || $prev_category === 'RENAME' || $prev_category === 'DROP') {
$token_category = $upper;
}
break;
case 'VIEW':
# prevent wrong processing as keyword
if ($prev_category === 'CREATE' || $prev_category === 'ALTER' || $prev_category === 'DROP') {
$token_category = $upper;
}
break;
/* These tokens get their own section, but have no subclauses.
These tokens identify the statement but have no specific subclauses of their own. */
case 'DELETE':
case 'ALTER':
case 'INSERT':
case 'REPLACE':
case 'TRUNCATE':
case 'CREATE':
case 'TRUNCATE':
case 'OPTIMIZE':
case 'GRANT':
case 'REVOKE':
case 'SHOW':
case 'HANDLER':
case 'LOAD':
case 'ROLLBACK':
case 'SAVEPOINT':
case 'UNLOCK':
case 'INSTALL':
case 'UNINSTALL':
case 'ANALZYE':
case 'BACKUP':
case 'CHECK':
case 'CHECKSUM':
case 'REPAIR':
case 'RESTORE':
case 'DESCRIBE':
case 'EXPLAIN':
case 'USE':
case 'HELP':
$token_category = $upper; /* set the category in case these get subclauses
in a future version of MySQL */
$out[$upper][0] = $upper;
continue 2;
break;
case 'CACHE':
if ($prev_category === "" || $prev_category === 'RESET' || $prev_category === 'FLUSH'
|| $prev_category === 'LOAD') {
$token_category = $upper;
continue 2;
}
break;
/* This is either LOCK TABLES or SELECT ... LOCK IN SHARE MODE*/
case 'LOCK':
if ($token_category === "") {
$token_category = $upper;
$out[$upper][0] = $upper;
} else {
$trim = 'LOCK IN SHARE MODE';
$skip_next = true;
$out['OPTIONS'][] = $trim;
}
continue 2;
break;
case 'USING': /* USING in FROM clause is different from USING w/ prepared statement*/
if ($token_category === 'EXECUTE') {
$token_category = $upper;
continue 2;
}
if ($token_category === 'FROM' && !empty($out['DELETE'])) {
$token_category = $upper;
continue 2;
}
break;
/* DROP TABLE is different from ALTER TABLE DROP ... */
case 'DROP':
if ($token_category !== 'ALTER') {
$token_category = $upper;
continue 2;
}
break;
case 'FOR':
$skip_next = true;
$out['OPTIONS'][] = 'FOR UPDATE';
continue 2;
break;
case 'UPDATE':
if ($token_category === "") {
$token_category = $upper;
continue 2;
}
if ($token_category === 'DUPLICATE') {
continue 2;
}
break;
case 'START':
$trim = "BEGIN";
$out[$upper][0] = $upper;
$skip_next = true;
break;
/* These tokens are ignored. */
case 'BY':
case 'ALL':
case 'SHARE':
case 'MODE':
case 'TO':
case ';':
continue 2;
break;
case 'KEY':
if ($token_category === 'DUPLICATE') {
continue 2;
}
break;
/* These tokens set particular options for the statement. They never stand alone.*/
case 'DISTINCTROW':
$trim = 'DISTINCT';
case 'DISTINCT':
case 'HIGH_PRIORITY':
case 'LOW_PRIORITY':
case 'DELAYED':
case 'IGNORE':
case 'FORCE':
case 'STRAIGHT_JOIN':
case 'SQL_SMALL_RESULT':
case 'SQL_BIG_RESULT':
case 'QUICK':
case 'SQL_BUFFER_RESULT':
case 'SQL_CACHE':
case 'SQL_NO_CACHE':
case 'SQL_CALC_FOUND_ROWS':
$out['OPTIONS'][] = $upper;
continue 2;
break;
case 'WITH':
if ($token_category === 'GROUP') {
$skip_next = true;
$out['OPTIONS'][] = 'WITH ROLLUP';
continue 2;
}
break;
case 'AS':
break;
case '':
case ',':
case ';':
break;
default:
break;
}
# remove obsolete category after union (empty category because of
# empty token before select)
if ($token_category !== "" && ($prev_category === $token_category)) {
$out[$token_category][] = $token;
}
$prev_category = $token_category;
}
return $this->processSQLParts($out);
}
private function processSQLParts($out) {
if (!$out) {
return false;
}
if (!empty($out['SELECT'])) {
$out['SELECT'] = $this->process_select($out['SELECT']);
}
if (!empty($out['FROM'])) {
$out['FROM'] = $this->process_from($out['FROM']);
}
if (!empty($out['USING'])) {
$out['USING'] = $this->process_from($out['USING']);
}
if (!empty($out['UPDATE'])) {
$out['UPDATE'] = $this->processUpdate($out['UPDATE']);
}
if (!empty($out['GROUP'])) {
# set empty array if we have partial SQL statement
$out['GROUP'] = $this->process_group($out['GROUP'], isset($out['SELECT']) ? $out['SELECT'] : array());
}
if (!empty($out['ORDER'])) {
# set empty array if we have partial SQL statement
$out['ORDER'] = $this->process_order($out['ORDER'], isset($out['SELECT']) ? $out['SELECT'] : array());
}
if (!empty($out['LIMIT'])) {
$out['LIMIT'] = $this->process_limit($out['LIMIT']);
}
if (!empty($out['WHERE'])) {
$out['WHERE'] = $this->process_expr_list($out['WHERE']);
}
if (!empty($out['HAVING'])) {
$out['HAVING'] = $this->process_expr_list($out['HAVING']);
}
if (!empty($out['SET'])) {
$out['SET'] = $this->process_set_list($out['SET'], isset($out['UPDATE']));
}
if (!empty($out['DUPLICATE'])) {
$out['ON DUPLICATE KEY UPDATE'] = $this->process_set_list($out['DUPLICATE']);
unset($out['DUPLICATE']);
}
if (!empty($out['INSERT'])) {
$out = $this->processInsert($out);
}
if (!empty($out['REPLACE'])) {
$out = $this->processReplace($out);
}
if (!empty($out['DELETE'])) {
$out = $this->process_delete($out);
}
if (!empty($out['VALUES'])) {
$out = $this->process_values($out);
}
if (!empty($out['INTO'])) {
$out = $this->processInto($out);
}
if (!empty($out['DROP'])) {
$out['DROP'] = $this->processDrop($out['DROP']);
}
return $out;
}
/**
* A SET list is simply a list of key = value expressions separated by comma (,).
* This function produces a list of the key/value expressions.
*/
private function getAssignment($base_expr) {
$assignment = $this->process_expr_list($this->splitSQLIntoTokens($base_expr));
return array('expr_type' => ExpressionType::EXPRESSION, 'base_expr' => trim($base_expr),
'sub_tree' => $assignment);
}
private function getVariableType($expression) {
// $expression must contain only upper-case characters
if ($expression[1] !== "@") {
return ExpressionType::USER_VARIABLE;
}
$type = substr($expression, 2, strpos($expression, ".", 2));
switch ($type) {
case 'GLOBAL':
$type = ExpressionType::GLOBAL_VARIABLE;
break;
case 'LOCAL':
$type = ExpressionType::LOCAL_VARIABLE;
break;
case 'SESSION':
default:
$type = ExpressionType::SESSION_VARIABLE;
break;
}
return $type;
}
/**
* It can be UPDATE SET or SET alone
*/
private function process_set_list($tokens, $isUpdate) {
$result = array();
$baseExpr = "";
$assignment = false;
$varType = false;
foreach ($tokens as $token) {
$upper = strtoupper(trim($token));
switch ($upper) {
case 'LOCAL':
case 'SESSION':
case 'GLOBAL':
if (!$isUpdate) {
$varType = $this->getVariableType("@@" . $upper . ".");
$baseExpr = "";
continue 2;
}
break;
case ',':
$assignment = $this->getAssignment($baseExpr);
if (!$isUpdate && $varType !== false) {
$assignment['sub_tree'][0]['expr_type'] = $varType;
}
$result[] = $assignment;
$baseExpr = "";
$varType = false;
continue 2;
default:
}
$baseExpr .= $token;
}
if (trim($baseExpr) !== "") {
$assignment = $this->getAssignment($baseExpr);
if (!$isUpdate && $varType !== false) {
$assignment['sub_tree'][0]['expr_type'] = $varType;
}
$result[] = $assignment;
}
return $result;
}
/**
* This function processes the LIMIT section.
* start,end are set. If only end is provided in the query
* then start is set to 0.
*/
private function process_limit($tokens) {
$rowcount = "";
$offset = "";
$comma = -1;
$exchange = false;
for ($i = 0; $i < count($tokens); ++$i) {
$trim = trim($tokens[$i]);
if ($trim === ",") {
$comma = $i;
break;
}
if ($trim === "OFFSET") {
$comma = $i;
$exchange = true;
break;
}
}
for ($i = 0; $i < $comma; ++$i) {
if ($exchange) {
$rowcount .= $tokens[$i];
} else {
$offset .= $tokens[$i];
}
}
for ($i = $comma + 1; $i < count($tokens); ++$i) {
if ($exchange) {
$offset .= $tokens[$i];
} else {
$rowcount .= $tokens[$i];
}
}
return array('offset' => trim($offset), 'rowcount' => trim($rowcount));
}
/**
* This function processes the SELECT section. It splits the clauses at the commas.
* Each clause is then processed by process_select_expr() and the results are added to
* the expression list.
*
* Finally, at the end, the epxression list is returned.
*/
private function process_select(&$tokens) {
$expression = "";
$expressionList = array();
foreach ($tokens as $token) {
if ($this->isCommaToken($token)) {
$expressionList[] = $this->process_select_expr(trim($expression));
$expression = "";
} else {
$expression .= $token;
}
}
if ($expression) {
$expressionList[] = $this->process_select_expr(trim($expression));
}
return $expressionList;
}
private function isCommaToken($token) {
return (trim($token) === ",");
}
private function isWhitespaceToken($token) {
return (trim($token) === "");
}
private function isCommentToken($token) {
return isset($token[0]) && isset($token[1])
&& (($token[0] === '-' && $token[1] === '-') || ($token[0] === '/' && $token[1] === '*'));
}
private function isColumnReference($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::COLREF);
}
private function isReserved($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::RESERVED);
}
private function isConstant($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::CONSTANT);
}
private function isAggregateFunction($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::AGGREGATE_FUNCTION);
}
private function isFunction($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::SIMPLE_FUNCTION);
}
private function isExpression($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::EXPRESSION);
}
private function isBracketExpression($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::BRACKET_EXPRESSION);
}
private function isSubQuery($out) {
return (isset($out['expr_type']) && $out['expr_type'] === ExpressionType::SUBQUERY);
}
/**
* This fuction processes each SELECT clause. We determine what (if any) alias
* is provided, and we set the type of expression.
*/
private function process_select_expr($expression) {
$tokens = $this->splitSQLIntoTokens($expression);
$token_count = count($tokens);
/* Determine if there is an explicit alias after the AS clause.
If AS is found, then the next non-whitespace token is captured as the alias.
The tokens after (and including) the AS are removed.
*/
$base_expr = "";
$stripped = array();
$capture = false;
$alias = false;
$processed = false;
for ($i = 0; $i < $token_count; ++$i) {
$token = $tokens[$i];
$upper = strtoupper($token);
if ($upper === 'AS') {
$alias = array('as' => true, "name" => "", "base_expr" => $token);
$tokens[$i] = "";
$capture = true;
continue;
}
if (!$this->isWhitespaceToken($upper)) {
$stripped[] = $token;
}
// we have an explicit AS, next one can be the alias
// but also a comment!
if ($capture) {
if (!$this->isWhitespaceToken($upper) && !$this->isCommentToken($upper)) {
$alias['name'] .= $token;
array_pop($stripped);
}
$alias['base_expr'] .= $token;
$tokens[$i] = "";
continue;
}
$base_expr .= $token;
}
$stripped = $this->process_expr_list($stripped);
# TODO: the last part can also be a comment, don't use array_pop
# we remove the last token, if it is a colref,
# it can be an alias without an AS
$last = array_pop($stripped);
if (!$alias && $this->isColumnReference($last)) {
# TODO: it can be a comment, don't use array_pop
# check the token before the colref
$prev = array_pop($stripped);
if ($this->isReserved($prev) || $this->isConstant($prev) || $this->isAggregateFunction($prev)
|| $this->isFunction($prev) || $this->isExpression($prev) || $this->isSubQuery($prev)
|| $this->isColumnReference($prev) || $this->isBracketExpression($prev)) {
$alias = array('as' => false, 'name' => trim($last['base_expr']),
'base_expr' => trim($last['base_expr']));
#remove the last token
array_pop($tokens);
$base_expr = join("", $tokens);
}
}
if (!$alias) {
$base_expr = join("", $tokens);
} else {
/* remove escape from the alias */
$alias['name'] = $this->revokeEscaping(trim($alias['name']));
$alias['base_expr'] = trim($alias['base_expr']);
}
# TODO: this is always done with $stripped, how we do it twice?
$processed = $this->process_expr_list($tokens);
# if there is only one part, we copy the expr_type
# in all other cases we use "expression" as global type
$type = ExpressionType::EXPRESSION;
if (count($processed) === 1) {
if (!$this->isSubQuery($processed[0])) {
$type = $processed[0]['expr_type'];
$base_expr = $processed[0]['base_expr'];
$processed = $processed[0]['sub_tree']; // it can be FALSE
}
}
return array('expr_type' => $type, 'alias' => $alias, 'base_expr' => trim($base_expr),
'sub_tree' => $processed);
}
/**
* This method handles the FROM clause.
*/
private function process_from(&$tokens) {
$parseInfo = $this->initParseInfoForFrom();
$expr = array();
$skip_next = false;
$i = 0;
foreach ($tokens as $token) {
$upper = strtoupper(trim($token));
if ($skip_next && $token !== "") {
$parseInfo['token_count']++;
$skip_next = false;
continue;
} else {
if ($skip_next) {
continue;
}
}
switch ($upper) {
case 'OUTER':
case 'LEFT':
case 'RIGHT':
case 'NATURAL':
case 'CROSS':
case ',':
case 'JOIN':
case 'INNER':
break;
default:
$parseInfo['expression'] .= $token;
if ($parseInfo['ref_type'] !== false) { # all after ON / USING
$parseInfo['ref_expr'] .= $token;
}
break;
}
switch ($upper) {
case 'AS':
$parseInfo['alias'] = array('as' => true, 'name' => "", 'base_expr' => $token);
$parseInfo['token_count']++;
$n = 1;
$str = "";
while ($str == "") {
$parseInfo['alias']['base_expr'] .= ($tokens[$i + $n] === "" ? " " : $tokens[$i + $n]);
$str = trim($tokens[$i + $n]);
++$n;
}
$parseInfo['alias']['name'] = $str;
$parseInfo['alias']['base_expr'] = trim($parseInfo['alias']['base_expr']);
continue;
case 'INDEX':
if ($token_category == 'CREATE') {
$token_category = $upper;
continue 2;
}
break;
case 'USING':
case 'ON':
$parseInfo['ref_type'] = $upper;
$parseInfo['ref_expr'] = "";
case 'CROSS':
case 'USE':
case 'FORCE':
case 'IGNORE':
case 'INNER':
case 'OUTER':
$parseInfo['token_count']++;
continue;
break;
case 'FOR':
$parseInfo['token_count']++;
$skip_next = true;
continue;
break;
case 'LEFT':
case 'RIGHT':
case 'STRAIGHT_JOIN':
$parseInfo['next_join_type'] = $upper;
break;
case ',':
$parseInfo['next_join_type'] = 'CROSS';
case 'JOIN':
if ($parseInfo['subquery']) {
$parseInfo['sub_tree'] = $this->parse($this->removeParenthesisFromStart($parseInfo['subquery']));
$parseInfo['expression'] = $parseInfo['subquery'];
}
$expr[] = $this->processFromExpression($parseInfo);
$parseInfo = $this->initParseInfoForFrom($parseInfo);
break;
default:
if ($upper === "") {
continue; # ends the switch statement!
}
if ($parseInfo['token_count'] === 0) {
if ($parseInfo['table'] === "") {
$parseInfo['table'] = $token;
}
} else if ($parseInfo['token_count'] === 1) {
$parseInfo['alias'] = array('as' => false, 'name' => trim($token), 'base_expr' => trim($token));
}
$parseInfo['token_count']++;
break;
}
++$i;
}
$expr[] = $this->processFromExpression($parseInfo);
return $expr;
}
private function initParseInfoForFrom($parseInfo = false) {
# first init
if ($parseInfo === false) {
$parseInfo = array('join_type' => "", 'saved_join_type' => "JOIN");
}
# loop init
return array('expression' => "", 'token_count' => 0, 'table' => "", 'alias' => false, 'join_type' => "",
'next_join_type' => "", 'saved_join_type' => $parseInfo['saved_join_type'],
'ref_type' => false, 'ref_expr' => false, 'base_expr' => false, 'sub_tree' => false,
'subquery' => "");
}
private function processFromExpression(&$parseInfo) {
$res = array();