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
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db;
use yii\base\Component;
use yii\base\InvalidArgumentException;
/**
* SqlTokenizer splits an SQL query into individual SQL tokens.
*
* It can be used to obtain an addition information from an SQL code.
*
* Usage example:
*
* ```php
* $tokenizer = new SqlTokenizer("SELECT * FROM user WHERE id = 1");
* $root = $tokeinzer->tokenize();
* $sqlTokens = $root->getChildren();
* ```
*
* Tokens are instances of [[SqlToken]].
*
* @author Sergey Makinen <sergey@makinen.ru>
* @since 2.0.13
*/
abstract class SqlTokenizer extends Component
{
/**
* @var string SQL code.
*/
public $sql;
/**
* @var int SQL code string length.
*/
protected $length;
/**
* @var int SQL code string current offset.
*/
protected $offset;
/**
* @var \SplStack stack of active tokens.
*/
private $_tokenStack;
/**
* @var SqlToken active token. It's usually a top of the token stack.
*/
private $_currentToken;
/**
* @var string[] cached substrings.
*/
private $_substrings;
/**
* @var string current buffer value.
*/
private $_buffer = '';
/**
* @var SqlToken resulting token of a last [[tokenize()]] call.
*/
private $_token;
/**
* Constructor.
* @param string $sql SQL code to be tokenized.
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($sql, $config = [])
{
$this->sql = $sql;
parent::__construct($config);
}
/**
* Tokenizes and returns a code type token.
* @return SqlToken code type token.
*/
public function tokenize()
{
$this->length = mb_strlen($this->sql, 'UTF-8');
$this->offset = 0;
$this->_substrings = [];
$this->_buffer = '';
$this->_token = new SqlToken([
'type' => SqlToken::TYPE_CODE,
'content' => $this->sql,
]);
$this->_tokenStack = new \SplStack();
$this->_tokenStack->push($this->_token);
$this->_token[] = new SqlToken(['type' => SqlToken::TYPE_STATEMENT]);
$this->_tokenStack->push($this->_token[0]);
$this->_currentToken = $this->_tokenStack->top();
while (!$this->isEof()) {
if ($this->isWhitespace($length) || $this->isComment($length)) {
$this->addTokenFromBuffer();
$this->advance($length);
continue;
}
if ($this->tokenizeOperator($length) || $this->tokenizeDelimitedString($length)) {
$this->advance($length);
continue;
}
$this->_buffer .= $this->substring(1);
$this->advance(1);
}
$this->addTokenFromBuffer();
if ($this->_token->getHasChildren() && !$this->_token[-1]->getHasChildren()) {
unset($this->_token[-1]);
}
return $this->_token;
}
/**
* Returns whether there's a whitespace at the current offset.
* If this methos returns `true`, it has to set the `$length` parameter to the length of the matched string.
* @param int $length length of the matched string.
* @return bool whether there's a whitespace at the current offset.
*/
abstract protected function isWhitespace(&$length);
/**
* Returns whether there's a commentary at the current offset.
* If this methos returns `true`, it has to set the `$length` parameter to the length of the matched string.
* @param int $length length of the matched string.
* @return bool whether there's a commentary at the current offset.
*/
abstract protected function isComment(&$length);
/**
* Returns whether there's an operator at the current offset.
* If this methos returns `true`, it has to set the `$length` parameter to the length of the matched string.
* It may also set `$content` to a string that will be used as a token content.
* @param int $length length of the matched string.
* @param string $content optional content instead of the matched string.
* @return bool whether there's an operator at the current offset.
*/
abstract protected function isOperator(&$length, &$content);
/**
* Returns whether there's an identifier at the current offset.
* If this methos returns `true`, it has to set the `$length` parameter to the length of the matched string.
* It may also set `$content` to a string that will be used as a token content.
* @param int $length length of the matched string.
* @param string $content optional content instead of the matched string.
* @return bool whether there's an identifier at the current offset.
*/
abstract protected function isIdentifier(&$length, &$content);
/**
* Returns whether there's a string literal at the current offset.
* If this methos returns `true`, it has to set the `$length` parameter to the length of the matched string.
* It may also set `$content` to a string that will be used as a token content.
* @param int $length length of the matched string.
* @param string $content optional content instead of the matched string.
* @return bool whether there's a string literal at the current offset.
*/
abstract protected function isStringLiteral(&$length, &$content);
/**
* Returns whether the given string is a keyword.
* The method may set `$content` to a string that will be used as a token content.
* @param string $string string to be matched.
* @param string $content optional content instead of the matched string.
* @return bool whether the given string is a keyword.
*/
abstract protected function isKeyword($string, &$content);
/**
* Returns whether the longest common prefix equals to the SQL code of the same length at the current offset.
* @param string[] $with strings to be tested.
* The method **will** modify this parameter to speed up lookups.
* @param bool $caseSensitive whether to perform a case sensitive comparison.
* @param int|null $length length of the matched string.
* @param string|null $content matched string.
* @return bool whether a match is found.
*/
protected function startsWithAnyLongest(array &$with, $caseSensitive, &$length = null, &$content = null)
{
if (empty($with)) {
return false;
}
if (!is_array(reset($with))) {
usort($with, function ($string1, $string2) {
return mb_strlen($string2, 'UTF-8') - mb_strlen($string1, 'UTF-8');
});
$map = [];
foreach ($with as $string) {
$map[mb_strlen($string, 'UTF-8')][$caseSensitive ? $string : mb_strtoupper($string, 'UTF-8')] = true;
}
$with = $map;
}
foreach ($with as $testLength => $testValues) {
$content = $this->substring($testLength, $caseSensitive);
if (isset($testValues[$content])) {
$length = $testLength;
return true;
}
}
return false;
}
/**
* Returns a string of the given length starting with the specified offset.
* @param int $length string length to be returned.
* @param bool $caseSensitive if it's `false`, the string will be uppercased.
* @param int|null $offset SQL code offset, defaults to current if `null` is passed.
* @return string result string, it may be empty if there's nothing to return.
*/
protected function substring($length, $caseSensitive = true, $offset = null)
{
if ($offset === null) {
$offset = $this->offset;
}
if ($offset + $length > $this->length) {
return '';
}
$cacheKey = $offset . ',' . $length;
if (!isset($this->_substrings[$cacheKey . ',1'])) {
$this->_substrings[$cacheKey . ',1'] = mb_substr($this->sql, $offset, $length, 'UTF-8');
}
if (!$caseSensitive && !isset($this->_substrings[$cacheKey . ',0'])) {
$this->_substrings[$cacheKey . ',0'] = mb_strtoupper($this->_substrings[$cacheKey . ',1'], 'UTF-8');
}
return $this->_substrings[$cacheKey . ',' . (int) $caseSensitive];
}
/**
* Returns an index after the given string in the SQL code starting with the specified offset.
* @param string $string string to be found.
* @param int|null $offset SQL code offset, defaults to current if `null` is passed.
* @return int index after the given string or end of string index.
*/
protected function indexAfter($string, $offset = null)
{
if ($offset === null) {
$offset = $this->offset;
}
if ($offset + mb_strlen($string, 'UTF-8') > $this->length) {
return $this->length;
}
$afterIndexOf = mb_strpos($this->sql, $string, $offset, 'UTF-8');
if ($afterIndexOf === false) {
$afterIndexOf = $this->length;
} else {
$afterIndexOf += mb_strlen($string, 'UTF-8');
}
return $afterIndexOf;
}
/**
* Determines whether there is a delimited string at the current offset and adds it to the token children.
* @param int $length
* @return bool
*/
private function tokenizeDelimitedString(&$length)
{
$isIdentifier = $this->isIdentifier($length, $content);
$isStringLiteral = !$isIdentifier && $this->isStringLiteral($length, $content);
if (!$isIdentifier && !$isStringLiteral) {
return false;
}
$this->addTokenFromBuffer();
$this->_currentToken[] = new SqlToken([
'type' => $isIdentifier ? SqlToken::TYPE_IDENTIFIER : SqlToken::TYPE_STRING_LITERAL,
'content' => is_string($content) ? $content : $this->substring($length),
'startOffset' => $this->offset,
'endOffset' => $this->offset + $length,
]);
return true;
}
/**
* Determines whether there is an operator at the current offset and adds it to the token children.
* @param int $length
* @return bool
*/
private function tokenizeOperator(&$length)
{
if (!$this->isOperator($length, $content)) {
return false;
}
$this->addTokenFromBuffer();
switch ($this->substring($length)) {
case '(':
$this->_currentToken[] = new SqlToken([
'type' => SqlToken::TYPE_OPERATOR,
'content' => is_string($content) ? $content : $this->substring($length),
'startOffset' => $this->offset,
'endOffset' => $this->offset + $length,
]);
$this->_currentToken[] = new SqlToken(['type' => SqlToken::TYPE_PARENTHESIS]);
$this->_tokenStack->push($this->_currentToken[-1]);
$this->_currentToken = $this->_tokenStack->top();
break;
case ')':
$this->_tokenStack->pop();
$this->_currentToken = $this->_tokenStack->top();
$this->_currentToken[] = new SqlToken([
'type' => SqlToken::TYPE_OPERATOR,
'content' => ')',
'startOffset' => $this->offset,
'endOffset' => $this->offset + $length,
]);
break;
case ';':
if (!$this->_currentToken->getHasChildren()) {
break;
}
$this->_currentToken[] = new SqlToken([
'type' => SqlToken::TYPE_OPERATOR,
'content' => is_string($content) ? $content : $this->substring($length),
'startOffset' => $this->offset,
'endOffset' => $this->offset + $length,
]);
$this->_tokenStack->pop();
$this->_currentToken = $this->_tokenStack->top();
$this->_currentToken[] = new SqlToken(['type' => SqlToken::TYPE_STATEMENT]);
$this->_tokenStack->push($this->_currentToken[-1]);
$this->_currentToken = $this->_tokenStack->top();
break;
default:
$this->_currentToken[] = new SqlToken([
'type' => SqlToken::TYPE_OPERATOR,
'content' => is_string($content) ? $content : $this->substring($length),
'startOffset' => $this->offset,
'endOffset' => $this->offset + $length,
]);
break;
}
return true;
}
/**
* Determines a type of text in the buffer, tokenizes it and adds it to the token children.
*/
private function addTokenFromBuffer()
{
if ($this->_buffer === '') {
return;
}
$isKeyword = $this->isKeyword($this->_buffer, $content);
$this->_currentToken[] = new SqlToken([
'type' => $isKeyword ? SqlToken::TYPE_KEYWORD : SqlToken::TYPE_TOKEN,
'content' => is_string($content) ? $content : $this->_buffer,
'startOffset' => $this->offset - mb_strlen($this->_buffer, 'UTF-8'),
'endOffset' => $this->offset,
]);
$this->_buffer = '';
}
/**
* Adds the specified length to the current offset.
* @param int $length
* @throws InvalidArgumentException
*/
private function advance($length)
{
if ($length <= 0) {
throw new InvalidArgumentException('Length must be greater than 0.');
}
$this->offset += $length;
$this->_substrings = [];
}
/**
* Returns whether the SQL code is completely traversed.
* @return bool
*/
private function isEof()
{
return $this->offset >= $this->length;
}
}