forked from phpmyadmin/sql-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlterOperation.php
More file actions
596 lines (541 loc) · 17.5 KB
/
AlterOperation.php
File metadata and controls
596 lines (541 loc) · 17.5 KB
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
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function array_key_exists;
use function in_array;
use function is_numeric;
use function is_string;
use function trim;
/**
* Parses an alter operation.
*/
final class AlterOperation implements Component
{
/**
* All database options.
*
* @var array<string, int|array<int, int|string>>
* @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
*/
public static $databaseOptions = [
'CHARACTER SET' => [
1,
'var',
],
'CHARSET' => [
1,
'var',
],
'DEFAULT CHARACTER SET' => [
1,
'var',
],
'DEFAULT CHARSET' => [
1,
'var',
],
'UPGRADE' => [
1,
'var',
],
'COLLATE' => [
2,
'var',
],
'DEFAULT COLLATE' => [
2,
'var',
],
];
/**
* All table options.
*
* @var array<string, int|array<int, int|string>>
* @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
*/
public static $tableOptions = [
'ENGINE' => [
1,
'var=',
],
'ALGORITHM' => [
1,
'var=',
],
'AUTO_INCREMENT' => [
1,
'var=',
],
'AVG_ROW_LENGTH' => [
1,
'var',
],
'COALESCE PARTITION' => [
1,
'var',
],
'LOCK' => [
1,
'var=',
],
'MAX_ROWS' => [
1,
'var',
],
'ROW_FORMAT' => [
1,
'var',
],
'COMMENT' => [
1,
'var',
],
'ADD' => 1,
'ALTER' => 1,
'ANALYZE' => 1,
'CHANGE' => 1,
'CHARSET' => 1,
'CHECK' => 1,
'CONVERT' => 1,
'DEFAULT CHARSET' => 1,
'DISABLE' => 1,
'DISCARD' => 1,
'DROP' => 1,
'ENABLE' => 1,
'IMPORT' => 1,
'MODIFY' => 1,
'OPTIMIZE' => 1,
'ORDER' => 1,
'REBUILD' => 1,
'REMOVE' => 1,
'RENAME' => 1,
'REORGANIZE' => 1,
'REPAIR' => 1,
'UPGRADE' => 1,
'COLUMN' => 2,
'CONSTRAINT' => 2,
'DEFAULT' => 2,
'BY' => 2,
'FOREIGN' => 2,
'FULLTEXT' => 2,
'KEY' => 2,
'KEYS' => 2,
'PARTITION' => 2,
'PARTITION BY' => 2,
'PARTITIONING' => 2,
'PRIMARY KEY' => 2,
'SPATIAL' => 2,
'TABLESPACE' => 2,
'INDEX' => [
2,
'var',
],
'CHARACTER SET' => 3,
'TO' => [
3,
'var',
],
];
/**
* All user options.
*
* @var array<string, int|array<int, int|string>>
* @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
*/
public static $userOptions = [
'ATTRIBUTE' => [
1,
'var',
],
'COMMENT' => [
1,
'var',
],
'REQUIRE' => [
1,
'var',
],
'IDENTIFIED VIA' => [
2,
'var',
],
'IDENTIFIED WITH' => [
2,
'var',
],
'PASSWORD' => [
2,
'var',
],
'WITH' => [
2,
'var',
],
'BY' => [
4,
'expr',
],
'ACCOUNT' => 1,
'DEFAULT' => 1,
'LOCK' => 2,
'UNLOCK' => 2,
'IDENTIFIED' => 3,
];
/**
* All view options.
*
* @var array<string, int|array<int, int|string>>
* @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
*/
public static $viewOptions = ['AS' => 1];
/**
* All event options.
*
* @var array<string, int|array<int, int|string>>
* @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
*/
public static $eventOptions = [
'ON SCHEDULE' => 1,
'EVERY' => [
2,
'expr',
],
'AT' => [
2,
'expr',
],
'STARTS' => [
3,
'expr',
],
'ENDS' => [
4,
'expr',
],
'ON COMPLETION PRESERVE' => 5,
'ON COMPLETION NOT PRESERVE' => 5,
'RENAME' => 6,
'TO' => [
7,
'expr',
['parseField' => 'table'],
],
'ENABLE' => 8,
'DISABLE' => 8,
'DISABLE ON SLAVE' => 8,
'COMMENT' => [
9,
'var',
],
'DO' => 10,
];
/**
* Options of this operation.
*
* @var OptionsArray
*/
public $options;
/**
* The altered field.
*
* @var Expression|string|null
*/
public $field;
/**
* The partitions.
*
* @var Component[]|ArrayObj|null
*/
public $partitions;
/**
* Unparsed tokens.
*
* @var Token[]|string
*/
public $unknown = [];
/**
* @param OptionsArray $options options of alter operation
* @param Expression|string|null $field altered field
* @param Component[]|ArrayObj|null $partitions partitions definition found in the operation
* @param Token[] $unknown unparsed tokens found at the end of operation
*/
public function __construct(
$options = null,
$field = null,
$partitions = null,
$unknown = []
) {
$this->partitions = $partitions;
$this->options = $options;
$this->field = $field;
$this->unknown = $unknown;
}
/**
* @param Parser $parser the parser that serves as context
* @param TokensList $list the list of tokens that are being parsed
* @param array<string, mixed> $options parameters for parsing
*
* @return AlterOperation
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
{
$ret = new static();
/**
* Counts brackets.
*
* @var int
*/
$brackets = 0;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------[ options ]---------------------> 1
*
* 1 ----------------------[ field ]----------------------> 2
*
* 1 -------------[ PARTITION / PARTITION BY ]------------> 3
*
* 2 -------------------------[ , ]-----------------------> 0
*
* @var int
*/
$state = 0;
/**
* partition state.
*
* @var int
*/
$partitionState = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
// Skipping whitespaces.
if ($token->type === Token::TYPE_WHITESPACE) {
if ($state === 2) {
// When parsing the unknown part, the whitespaces are
// included to not break anything.
$ret->unknown[] = $token;
continue;
}
}
if ($state === 0) {
$ret->options = OptionsArray::parse($parser, $list, $options);
// Not only when aliasing but also when parsing the body of an event, we just list the tokens of the
// body in the unknown tokens list, as they define their own statements.
if ($ret->options->has('AS') || $ret->options->has('DO')) {
for (; $list->idx < $list->count; ++$list->idx) {
if ($list->tokens[$list->idx]->type === Token::TYPE_DELIMITER) {
break;
}
$ret->unknown[] = $list->tokens[$list->idx];
}
break;
}
$state = 1;
if ($ret->options->has('PARTITION') || $token->value === 'PARTITION BY') {
$state = 3;
$list->getPrevious(); // in order to check whether it's partition or partition by.
}
} elseif ($state === 1) {
$ret->field = Expression::parse(
$parser,
$list,
[
'breakOnAlias' => true,
'parseField' => 'column',
]
);
if ($ret->field === null) {
// No field was read. We go back one token so the next
// iteration will parse the same token, but in state 2.
--$list->idx;
}
// If the operation is a RENAME COLUMN, now we have detected the field to rename, we need to parse
// again the options to get the new name of the column.
if ($ret->options->has('RENAME') && $ret->options->has('COLUMN')) {
$nextOptions = OptionsArray::parse($parser, $list, $options);
$ret->options->merge($nextOptions);
}
$state = 2;
} elseif ($state === 2) {
if (is_string($token->value) || is_numeric($token->value)) {
$arrayKey = $token->value;
} else {
$arrayKey = $token->token;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
} elseif (($token->value === ',') && ($brackets === 0)) {
break;
}
} elseif (! self::checkIfTokenQuotedSymbol($token)) {
// If the current token is "SET" or "ENUM", we want to avoid the token between their parenthesis in
// the unknown tokens.
if (in_array($token->value, ['SET', 'ENUM'], true)) {
$list->idx++; // Ignore the current token
$nextToken = $list->getNext();
if ($nextToken !== null && $nextToken->value === '(') {
$list->getNextOfTypeAndValue(Token::TYPE_OPERATOR, ')');
} elseif ($nextToken !== null && $nextToken->value === 'DEFAULT') {
// to avoid adding the `DEFAULT` token to the unknown tokens.
++$list->idx;
} else {
$parser->error(
'A new statement was found, but no delimiter between it and the previous one.',
$token
);
break;
}
} elseif (! empty(Parser::$statementParsers[$token->value])) {
// We have reached the end of ALTER operation and suddenly found
// a start to new statement, but have not found a delimiter between them
$parser->error(
'A new statement was found, but no delimiter between it and the previous one.',
$token
);
break;
} elseif (
(array_key_exists($arrayKey, self::$databaseOptions)
|| array_key_exists($arrayKey, self::$tableOptions))
&& ! self::checkIfColumnDefinitionKeyword($arrayKey)
) {
// This alter operation has finished, which means a comma
// was missing before start of new alter operation
$parser->error('Missing comma before start of a new alter operation.', $token);
break;
}
}
$ret->unknown[] = $token;
} elseif ($state === 3) {
if ($partitionState === 0) {
$list->idx++; // Ignore the current token
$nextToken = $list->getNext();
if (
($token->type === Token::TYPE_KEYWORD)
&& (($token->keyword === 'PARTITION BY')
|| ($token->keyword === 'PARTITION' && $nextToken && $nextToken->value !== '('))
) {
$partitionState = 1;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->keyword === 'PARTITION')) {
$partitionState = 2;
}
--$list->idx; // to decrease the idx by one, because the last getNext returned and increased it.
// reverting the effect of the getNext
$list->getPrevious();
$list->getPrevious();
++$list->idx; // to index the idx by one, because the last getPrevious returned and decreased it.
} elseif ($partitionState === 1) {
// Fetch the next token in a way the current index is reset to manage whitespaces in "field".
$currIdx = $list->idx;
++$list->idx;
$nextToken = $list->getNext();
$list->idx = $currIdx;
// Building the expression used for partitioning.
if (empty($ret->field)) {
$ret->field = '';
}
if (
$token->type === Token::TYPE_OPERATOR
&& $token->value === '('
&& $nextToken
&& $nextToken->keyword === 'PARTITION'
) {
$partitionState = 2;
--$list->idx; // Current idx is on "(". We need a step back for ArrayObj::parse incoming.
} else {
$ret->field .= $token->type === Token::TYPE_WHITESPACE ? ' ' : $token->token;
}
} elseif ($partitionState === 2) {
$ret->partitions = ArrayObj::parse(
$parser,
$list,
['type' => PartitionDefinition::class]
);
}
}
}
if ($ret->options->isEmpty()) {
$parser->error('Unrecognized alter operation.', $list->tokens[$list->idx]);
}
--$list->idx;
return $ret;
}
/**
* @param AlterOperation $component the component to be built
*/
public static function build($component): string
{
// Specific case of RENAME COLUMN that insert the field between 2 options.
$afterFieldsOptions = new OptionsArray();
if ($component->options->has('RENAME') && $component->options->has('COLUMN')) {
$afterFieldsOptions = clone $component->options;
$afterFieldsOptions->remove('RENAME');
$afterFieldsOptions->remove('COLUMN');
$component->options->remove('TO');
}
$ret = $component->options . ' ';
if (isset($component->field) && ($component->field !== '')) {
$ret .= $component->field . ' ';
}
$ret .= $afterFieldsOptions . TokensList::build($component->unknown);
if (isset($component->partitions)) {
$ret .= PartitionDefinition::build($component->partitions);
}
return trim($ret);
}
/**
* Check if token's value is one of the common keywords
* between column and table alteration
*
* @param string $tokenValue Value of current token
*/
private static function checkIfColumnDefinitionKeyword($tokenValue): bool
{
$commonOptions = [
'AUTO_INCREMENT',
'COMMENT',
'DEFAULT',
'CHARACTER SET',
'COLLATE',
'PRIMARY',
'UNIQUE',
'PRIMARY KEY',
'UNIQUE KEY',
];
// Since these options can be used for
// both table as well as a specific column in the table
return in_array($tokenValue, $commonOptions);
}
/**
* Check if token is symbol and quoted with backtick
*
* @param Token $token token to check
*/
private static function checkIfTokenQuotedSymbol($token): bool
{
return $token->type === Token::TYPE_SYMBOL && $token->flags === Token::FLAG_SYMBOL_BACKTICK;
}
public function __toString(): string
{
return static::build($this);
}
}