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
|
<?php
/**
* Statement utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\Statements\AlterStatement;
use SqlParser\Statements\AnalyzeStatement;
use SqlParser\Statements\CallStatement;
use SqlParser\Statements\CheckStatement;
use SqlParser\Statements\ChecksumStatement;
use SqlParser\Statements\CreateStatement;
use SqlParser\Statements\DeleteStatement;
use SqlParser\Statements\DropStatement;
use SqlParser\Statements\ExplainStatement;
use SqlParser\Statements\InsertStatement;
use SqlParser\Statements\OptimizeStatement;
use SqlParser\Statements\RepairStatement;
use SqlParser\Statements\ReplaceStatement;
use SqlParser\Statements\SelectStatement;
use SqlParser\Statements\ShowStatement;
use SqlParser\Statements\UpdateStatement;
/**
* Statement utilities.
*
* @category Routines
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Query
{
/**
* Functions that set the flag `is_func`.
*
* @var array
*/
public static $FUNCTIONS = array(
'SUM','AVG','STD','STDDEV','MIN','MAX','BIT_OR','BIT_AND'
);
/**
* Gets an array with flags this statement has.
*
* @param Statement $statement The statement to be processed.
* @param bool $all If `false`, false values will not be included.
*
* @return array
*/
public static function getFlags($statement, $all = false)
{
$flags = array();
if ($all) {
$flags = array(
/**
* select ... DISTINCT ...
*/
'distinct' => false,
/**
* drop ... DATABASE ...
*/
'drop_database' => false,
/**
* ... GROUP BY ...
*/
'group' => false,
/**
* ... HAVING ...
*/
'having' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* DELETE ...
*/
'is_affected' => false,
/**
* select ... PROCEDURE ANALYSE( ... ) ...
*/
'is_analyse' => false,
/**
* select COUNT( ... ) ...
*/
'is_count' => false,
/**
* DELETE ...
*/
'is_delete' => false, // @deprecated; use `querytype`
/**
* EXPLAIN ...
*/
'is_explain' => false, // @deprecated; use `querytype`
/**
* select ... INTO OUTFILE ...
*/
'is_export' => false,
/**
* select FUNC( ... ) ...
*/
'is_func' => false,
/**
* select ... GROUP BY ...
* or
* select ... HAVING ...
*/
'is_group' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* TODO: LOAD DATA ...
*/
'is_insert' => false,
/**
* ANALYZE ...
* or
* CHECK ...
* or
* CHECKSUM ...
* or
* OPTIMIZE ...
* or
* REPAIR ...
*/
'is_maint' => false,
/**
* CALL ...
*/
'is_procedure' => false,
/**
* REPLACE ...
*/
'is_replace' => false, // @deprecated; use `querytype`
/**
* SELECT ...
*/
'is_select' => false, // @deprecated; use `querytype`
/**
* SHOW ...
*/
'is_show' => false, // @deprecated; use `querytype`
/**
* Contains a subquery.
*/
'is_subquery' => false,
/**
* ... JOIN ...
*/
'join' => false,
/**
* ... LIMIT ...
*/
'limit' => false,
/**
* TODO
*/
'offset' => false,
/**
* ... ORDER ...
*/
'order' => false,
/**
* The type of the query (which is usually the first keyword of
* the statement).
*/
'querytype' => false,
/**
* Whether a page reload is required.
*/
'reload' => false,
/**
* SELECT ... FROM ...
*/
'select_from' => false,
/**
* ... UNION ...
*/
'union' => false
);
}
if ($statement instanceof AlterStatement) {
$flags['querytype'] = 'ALTER';
$flags['reload'] = true;
} elseif ($statement instanceof CreateStatement) {
$flags['querytype'] = 'CREATE';
$flags['reload'] = true;
} elseif ($statement instanceof AnalyzeStatement) {
$flags['querytype'] = 'ANALYZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof CheckStatement) {
$flags['querytype'] = 'CHECK';
$flags['is_maint'] = true;
} elseif ($statement instanceof ChecksumStatement) {
$flags['querytype'] = 'CHECKSUM';
$flags['is_maint'] = true;
} elseif ($statement instanceof OptimizeStatement) {
$flags['querytype'] = 'OPTIMIZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof RepairStatement) {
$flags['querytype'] = 'REPAIR';
$flags['is_maint'] = true;
} elseif ($statement instanceof CallStatement) {
$flags['querytype'] = 'CALL';
$flags['is_procedure'] = true;
} elseif ($statement instanceof DeleteStatement) {
$flags['querytype'] = 'DELETE';
$flags['is_delete'] = true;
$flags['is_affected'] = true;
} elseif ($statement instanceof DropStatement) {
$flags['querytype'] = 'DROP';
$flags['reload'] = true;
if (($statement->options->has('DATABASE')
|| ($statement->options->has('SCHEMA')))
) {
$flags['drop_database'] = true;
}
} elseif ($statement instanceof ExplainStatement) {
$flags['querytype'] = 'EXPLAIN';
$flags['is_explain'] = true;
} elseif ($statement instanceof InsertStatement) {
$flags['querytype'] = 'INSERT';
$flags['is_affected'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof ReplaceStatement) {
$flags['querytype'] = 'REPLACE';
$flags['is_affected'] = true;
$flags['is_replace'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof SelectStatement) {
$flags['querytype'] = 'SELECT';
$flags['is_select'] = true;
if (!empty($statement->from)) {
$flags['select_from'] = true;
}
if ($statement->options->has('DISTINCT')) {
$flags['distinct'] = true;
}
if ((!empty($statement->group)) || (!empty($statement->having))) {
$flags['is_group'] = true;
}
if ((!empty($statement->into))
&& ($statement->into->type === 'OUTFILE')
) {
$flags['is_export'] = true;
}
foreach ($statement->expr as $expr) {
if (!empty($expr->function)) {
if ($expr->function === 'COUNT') {
$flags['is_count'] = true;
} elseif (in_array($expr->function, static::$FUNCTIONS)) {
$flags['is_func'] = true;
}
}
if (!empty($expr->subquery)) {
$flags['is_subquery'] = true;
}
}
if ((!empty($statement->procedure))
&& ($statement->procedure->name === 'ANALYSE')
) {
$flags['is_analyse'] = true;
}
if (!empty($statement->group)) {
$flags['group'] = true;
}
if (!empty($statement->having)) {
$flags['having'] = true;
}
if (!empty($statement->union)) {
$flags['union'] = true;
}
if (!empty($statement->join)) {
$flags['join'] = true;
}
} elseif ($statement instanceof ShowStatement) {
$flags['querytype'] = 'SHOW';
$flags['is_show'] = true;
} elseif ($statement instanceof UpdateStatement) {
$flags['querytype'] = 'UPDATE';
$flags['is_affected'] = true;
}
if (($statement instanceof SelectStatement)
|| ($statement instanceof UpdateStatement)
|| ($statement instanceof DeleteStatement)
) {
if (!empty($statement->limit)) {
$flags['limit'] = true;
}
if (!empty($statement->order)) {
$flags['order'] = true;
}
}
return $flags;
}
/**
* Parses a query and gets all information about it.
*
* @param string $query The query to be parsed.
*
* @return array
*/
public static function getAll($query)
{
$parser = new Parser($query);
if (!isset($parser->statements[0])) {
return array();
}
$statement = $parser->statements[0];
$ret = static::getFlags($statement, true);
$ret['parser'] = $parser;
$ret['statement'] = $statement;
if ($statement instanceof SelectStatement) {
$ret['select_tables'] = array();
$ret['select_expr'] = array();
// Trying to find selected tables only from the select expression.
// Sometimes, this is not possible because the tables aren't defined
// explicitly (e.g. SELECT * FROM film, SELECT film_id FROM film).
foreach ($statement->expr as $expr) {
if (!empty($expr->table)) {
$ret['select_tables'][] = array(
$expr->table,
!empty($expr->database) ? $expr->database : null
);
} else {
$ret['select_expr'][] = $expr->expr;
}
}
// If no tables names were found in the SELECT clause or if there
// are expressions like * or COUNT(*), etc. tables names should be
// extracted from the FROM clause as well.
if ((empty($ret['select_tables'])) || (!$ret['select_expr'])) {
foreach ($statement->from as $expr) {
if (!empty($expr->table)) {
$ret['select_tables'][] = array(
$expr->table,
!empty($expr->database) ? $expr->database : null
);
}
}
}
}
return $ret;
}
/**
* Gets a specific clause.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param string $clause The clause to be returned.
* @param int $type The type of the search.
* -1 for everything that was before
* 0 only for the clause
* 1 for everything after
* @param bool $skipFirst Whether to skip the first keyword in clause.
*
* @return string
*/
public static function getClause($statement, $list, $clause, $type = 0, $skipFirst = true)
{
/**
* The index of the current clause.
* @var int
*/
$currIdx = 0;
/**
* The count of brackets.
* We keep track of them so we won't insert the clause in a subquery.
* @var int
*/
$brackets = 0;
/**
* The string to be returned.
* @var string
*/
$ret = '';
/**
* The clauses of this type of statement and their index.
* @var array
*/
$clauses = array_flip(array_keys($statement::$CLAUSES));
/**
* Lexer used for lexing the clause.
* @var Lexer
*/
$lexer = new Lexer($clause);
/**
* The type of this clause.
* @var string
*/
$clauseType = $lexer->list->getNextOfType(Token::TYPE_KEYWORD)->value;
/**
* The index of this clause.
* @var int
*/
$clauseIdx = $clauses[$clauseType];
for ($i = $statement->first; $i <= $statement->last; ++$i) {
$token = $list->tokens[$i];
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
}
}
if ($brackets == 0) {
// Checking if we changed sections.
if (($token->type === Token::TYPE_KEYWORD)
&& (isset($clauses[$token->value]))
&& ($clauses[$token->value] >= $currIdx)
) {
$currIdx = $clauses[$token->value];
if (($skipFirst) && ($currIdx == $clauseIdx)) {
// This token is skipped (not added to the old
// clause) because it will be replaced.
continue;
}
}
}
if ((($type === -1) && ($currIdx < $clauseIdx))
|| (($type === 0) && ($currIdx === $clauseIdx))
|| (($type === 1) && ($currIdx > $clauseIdx))
) {
$ret .= $token->token;
}
}
return trim($ret);
}
/**
* Builds a query by rebuilding the statement from the tokens list supplied
* and replaces a clause.
*
* It is a very basic version of a query builder.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param string $old The type of the clause that should be
* replaced. This can be an entire clause.
* @param string $new The new clause. If this parameter is omitted
* it is considered to be equal with `$old`.
* @param bool $onlyType Whether only the type of the clause should
* be replaced or the entire clause.
*
* @return string
*/
public static function replaceClause($statement, $list, $old, $new = null, $onlyType = false)
{
// TODO: Update the tokens list and the statement.
if ($new === null) {
$new = $old;
}
if ($onlyType) {
return static::getClause($statement, $list, $old, -1, false) . ' ' .
$new . ' ' . static::getCLause($statement, $list, $old, 0) . ' ' .
static::getClause($statement, $list, $old, 1, false);
}
return static::getClause($statement, $list, $old, -1, false) . ' ' .
$new . ' ' . static::getClause($statement, $list, $old, 1, false);
}
}
|