* Support php 5.3 for sql parser lib.

This commit is contained in:
qixinzhi
2023-02-10 11:24:24 +08:00
parent 7c2e937eda
commit 7c122a0b29
648 changed files with 13815 additions and 279048 deletions
+13 -12
View File
@@ -1,4 +1,5 @@
<?php
/**
* Defines a component that is later extended to parse specialized components or
* keywords.
@@ -8,15 +9,15 @@
* count on the *Component classes to do their job.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use Exception;
/**
* A component (of a statement) is a part of a statement that is common to
* multiple query types.
*
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
abstract class Component
{
@@ -28,18 +29,18 @@ abstract class Component
* @param TokensList $list the list of tokens that are being parsed
* @param array $options parameters for parsing
*
* @return mixed
* @throws \Exception not implemented yet
*
* @throws Exception not implemented yet.
* @return mixed
*/
public static function parse(
Parser $parser,
TokensList $list,
array $options = []
array $options = array()
) {
// This method should be abstract, but it can't be both static and
// abstract.
throw new Exception(Translator::gettext('Not implemented yet.'));
throw new \Exception(Translator::gettext('Not implemented yet.'));
}
/**
@@ -51,15 +52,15 @@ abstract class Component
* @param mixed $component the component to be built
* @param array $options parameters for building
*
* @return mixed
* @throws \Exception not implemented yet
*
* @throws Exception not implemented yet.
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
// This method should be abstract, but it can't be both static and
// abstract.
throw new Exception(Translator::gettext('Not implemented yet.'));
throw new \Exception(Translator::gettext('Not implemented yet.'));
}
/**
@@ -1,10 +1,9 @@
<?php
/**
* Parses an alter operation.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,15 +11,12 @@ 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;
/**
* Parses an alter operation.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class AlterOperation extends Component
{
@@ -29,67 +25,67 @@ class AlterOperation extends Component
*
* @var array
*/
public static $DB_OPTIONS = [
'CHARACTER SET' => [
public static $DB_OPTIONS = array(
'CHARACTER SET' => array(
1,
'var',
],
'CHARSET' => [
'var'
),
'CHARSET' => array(
1,
'var',
],
'DEFAULT CHARACTER SET' => [
'var'
),
'DEFAULT CHARACTER SET' => array(
1,
'var',
],
'DEFAULT CHARSET' => [
'var'
),
'DEFAULT CHARSET' => array(
1,
'var',
],
'UPGRADE' => [
'var'
),
'UPGRADE' => array(
1,
'var',
],
'COLLATE' => [
'var'
),
'COLLATE' => array(
2,
'var',
],
'DEFAULT COLLATE' => [
'var'
),
'DEFAULT COLLATE' => array(
2,
'var',
],
];
'var'
)
);
/**
* All table options.
*
* @var array
*/
public static $TABLE_OPTIONS = [
'ENGINE' => [
public static $TABLE_OPTIONS = array(
'ENGINE' => array(
1,
'var=',
],
'AUTO_INCREMENT' => [
'var='
),
'AUTO_INCREMENT' => array(
1,
'var=',
],
'AVG_ROW_LENGTH' => [
'var='
),
'AVG_ROW_LENGTH' => array(
1,
'var',
],
'MAX_ROWS' => [
'var'
),
'MAX_ROWS' => array(
1,
'var',
],
'ROW_FORMAT' => [
'var'
),
'ROW_FORMAT' => array(
1,
'var',
],
'COMMENT' => [
'var'
),
'COMMENT' => array(
1,
'var',
],
'var'
),
'ADD' => 1,
'ALTER' => 1,
'ANALYZE' => 1,
@@ -131,54 +127,56 @@ class AlterOperation extends Component
'INDEX' => 2,
'CHARACTER SET' => 3,
];
);
/**
* All user options.
*
* @var array
*/
public static $USER_OPTIONS = [
'ATTRIBUTE' => [
public static $USER_OPTIONS = array(
'ATTRIBUTE' => array(
1,
'var',
],
'COMMENT' => [
'var'
),
'COMMENT' => array(
1,
'var',
],
'REQUIRE' => [
'var'
),
'REQUIRE' => array(
1,
'var',
],
'BY' => [
'var'
),
'BY' => array(
2,
'expr',
],
'PASSWORD' => [
'expr'
),
'PASSWORD' => array(
2,
'var',
],
'WITH' => [
'var'
),
'WITH' => array(
2,
'var',
],
'var'
),
'ACCOUNT' => 1,
'DEFAULT' => 1,
'LOCK' => 2,
'UNLOCK' => 2,
'UNLOCK' => 2,
'IDENTIFIED' => 3,
];
);
/**
* All view options.
*
* @var array
*/
public static $VIEW_OPTIONS = ['AS' => 1];
public static $VIEW_OPTIONS = array(
'AS' => 1,
);
/**
* Options of this operation.
@@ -199,9 +197,11 @@ class AlterOperation extends Component
*
* @var Token[]|string
*/
public $unknown = [];
public $unknown = array();
/**
* Constructor.
*
* @param OptionsArray $options options of alter operation
* @param Expression $field altered field
* @param array $unknown unparsed tokens found at the end of operation
@@ -209,7 +209,7 @@ class AlterOperation extends Component
public function __construct(
$options = null,
$field = null,
$unknown = []
$unknown = array()
) {
$this->options = $options;
$this->field = $field;
@@ -223,9 +223,9 @@ class AlterOperation extends Component
*
* @return AlterOperation
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* Counts brackets.
@@ -274,7 +274,6 @@ class AlterOperation extends Component
// included to not break anything.
$ret->unknown[] = $token;
}
continue;
}
@@ -286,10 +285,8 @@ class AlterOperation extends Component
if ($list->tokens[$list->idx]->type === Token::TYPE_DELIMITER) {
break;
}
$ret->unknown[] = $list->tokens[$list->idx];
}
break;
}
@@ -298,26 +295,24 @@ class AlterOperation extends Component
$ret->field = Expression::parse(
$parser,
$list,
[
array(
'breakOnAlias' => true,
'parseField' => 'column',
]
'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;
}
$state = 2;
} elseif ($state === 2) {
$arrayKey = '';
$array_key = '';
if (is_string($token->value) || is_numeric($token->value)) {
$arrayKey = $token->value;
$array_key = $token->value;
} else {
$arrayKey = $token->token;
$array_key = $token->token;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
@@ -351,24 +346,27 @@ class AlterOperation extends Component
);
break;
}
} elseif (
(array_key_exists($arrayKey, self::$DB_OPTIONS)
|| array_key_exists($arrayKey, self::$TABLE_OPTIONS))
&& ! self::checkIfColumnDefinitionKeyword($arrayKey)
} elseif ((array_key_exists($array_key, self::$DB_OPTIONS)
|| array_key_exists($array_key, self::$TABLE_OPTIONS))
&& ! self::checkIfColumnDefinitionKeyword($array_key)
) {
// 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);
// 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;
}
}
if ($ret->options->isEmpty()) {
$parser->error('Unrecognized alter operation.', $list->tokens[$list->idx]);
$parser->error(
'Unrecognized alter operation.',
$list->tokens[$list->idx]
);
}
--$list->idx;
@@ -382,13 +380,12 @@ class AlterOperation extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
$ret = $component->options . ' ';
if (isset($component->field) && ($component->field !== '')) {
if ((isset($component->field)) && ($component->field !== '')) {
$ret .= $component->field . ' ';
}
$ret .= TokensList::build($component->unknown);
return $ret;
@@ -399,12 +396,11 @@ class AlterOperation extends Component
* between column and table alteration
*
* @param string $tokenValue Value of current token
*
* @return bool
*/
private static function checkIfColumnDefinitionKeyword($tokenValue)
{
$commonOptions = [
$common_options = array(
'AUTO_INCREMENT',
'COMMENT',
'DEFAULT',
@@ -413,23 +409,20 @@ class AlterOperation extends Component
'PRIMARY',
'UNIQUE',
'PRIMARY KEY',
'UNIQUE 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);
return in_array($tokenValue, $common_options);
}
/**
* Check if token is symbol and quoted with backtick
*
*
* @param Token $token token to check
*
* @return bool
*/
private static function checkIfTokenQuotedSymbol($token)
{
private static function checkIfTokenQuotedSymbol($token) {
return $token->type === Token::TYPE_SYMBOL && $token->flags === Token::FLAG_SYMBOL_BACKTICK;
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `VALUES` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -13,13 +12,12 @@ use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use PhpMyAdmin\SqlParser\Translator;
use function count;
use function sprintf;
/**
* `VALUES` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Array2d extends Component
{
@@ -30,9 +28,9 @@ class Array2d extends Component
*
* @return ArrayObj[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
/**
* The number of values in each set.
@@ -79,38 +77,40 @@ class Array2d extends Component
}
if ($state === 0) {
if ($token->value !== '(') {
if ($token->value === '(') {
$arr = ArrayObj::parse($parser, $list, $options);
$arrCount = count($arr->values);
if ($count === -1) {
$count = $arrCount;
} elseif ($arrCount !== $count) {
$parser->error(
sprintf(
Translator::gettext('%1$d values were expected, but found %2$d.'),
$count,
$arrCount
),
$token
);
}
$ret[] = $arr;
$state = 1;
} else {
break;
}
$arr = ArrayObj::parse($parser, $list, $options);
$arrCount = count($arr->values);
if ($count === -1) {
$count = $arrCount;
} elseif ($arrCount !== $count) {
$parser->error(
sprintf(
Translator::gettext('%1$d values were expected, but found %2$d.'),
$count,
$arrCount
),
$token
);
}
$ret[] = $arr;
$state = 1;
} elseif ($state === 1) {
if ($token->value !== ',') {
if ($token->value === ',') {
$state = 0;
} else {
break;
}
$state = 0;
}
}
if ($state === 0) {
$parser->error('An opening bracket followed by a set of values was expected.', $list->tokens[$list->idx]);
$parser->error(
'An opening bracket followed by a set of values was expected.',
$list->tokens[$list->idx]
);
}
--$list->idx;
@@ -124,7 +124,7 @@ class Array2d extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
return ArrayObj::build($component);
}
@@ -1,10 +1,9 @@
<?php
/**
* Parses an array.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,15 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
use function strlen;
use function trim;
/**
* Parses an array.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ArrayObj extends Component
{
@@ -29,20 +25,22 @@ class ArrayObj extends Component
*
* @var array
*/
public $raw = [];
public $raw = array();
/**
* The array that contains the processed value of each token.
*
* @var array
*/
public $values = [];
public $values = array();
/**
* Constructor.
*
* @param array $raw the unprocessed values
* @param array $values the processed values
*/
public function __construct(array $raw = [], array $values = [])
public function __construct(array $raw = array(), array $values = array())
{
$this->raw = $raw;
$this->values = $values;
@@ -55,9 +53,9 @@ class ArrayObj extends Component
*
* @return ArrayObj|Component[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = empty($options['type']) ? new static() : [];
$ret = empty($options['type']) ? new self() : array();
/**
* The last raw expression.
@@ -101,13 +99,18 @@ class ArrayObj extends Component
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
if (($token->type === Token::TYPE_WHITESPACE)
|| ($token->type === Token::TYPE_COMMENT)
) {
$lastRaw .= $token->token;
$lastValue = trim($lastValue) . ' ';
continue;
}
if (($brackets === 0) && (($token->type !== Token::TYPE_OPERATOR) || ($token->value !== '('))) {
if (($brackets === 0)
&& (($token->type !== Token::TYPE_OPERATOR)
|| ($token->value !== '('))
) {
$parser->error('An opening bracket was expected.', $token);
break;
}
@@ -130,7 +133,6 @@ class ArrayObj extends Component
$lastRaw = $lastValue = '';
}
}
continue;
}
}
@@ -142,7 +144,7 @@ class ArrayObj extends Component
$ret[] = $options['type']::parse(
$parser,
$list,
empty($options['typeOptions']) ? [] : $options['typeOptions']
empty($options['typeOptions']) ? array() : $options['typeOptions']
);
}
}
@@ -151,13 +153,16 @@ class ArrayObj extends Component
//
// This is treated differently to treat the following cases:
//
// => []
// [,] => ['', '']
// [] => []
// [a,] => ['a', '']
// [a] => ['a']
// => array()
// (,) => array('', '')
// () => array()
// (a,) => array('a', '')
// (a) => array('a')
//
$lastRaw = trim($lastRaw);
if (empty($options['type']) && ((strlen($lastRaw) > 0) || ($isCommaLast))) {
if ((empty($options['type']))
&& ((strlen($lastRaw) > 0) || ($isCommaLast))
) {
$ret->raw[] = $lastRaw;
$ret->values[] = trim($lastValue);
}
@@ -171,13 +176,11 @@ class ArrayObj extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
}
if (! empty($component->raw)) {
} elseif (! empty($component->raw)) {
return '(' . implode(', ', $component->raw) . ')';
}
@@ -1,10 +1,9 @@
<?php
/**
* Parses a reference to a CASE expression.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -13,12 +12,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function count;
/**
* Parses a reference to a CASE expression.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CaseExpression extends Component
{
@@ -34,21 +33,21 @@ class CaseExpression extends Component
*
* @var array
*/
public $conditions = [];
public $conditions = array();
/**
* The results matching with the WHEN clauses.
*
* @var array
*/
public $results = [];
public $results = array();
/**
* The values to be compared against.
*
* @var array
*/
public $compare_values = [];
public $compare_values = array();
/**
* The result in ELSE section of expr.
@@ -71,6 +70,9 @@ class CaseExpression extends Component
*/
public $expr = '';
/**
* Constructor.
*/
public function __construct()
{
}
@@ -82,9 +84,9 @@ class CaseExpression extends Component
*
* @return CaseExpression
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* State of parser.
@@ -111,7 +113,9 @@ class CaseExpression extends Component
$token = $list->tokens[$list->idx];
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
if (($token->type === Token::TYPE_WHITESPACE)
|| ($token->type === Token::TYPE_COMMENT)
) {
continue;
}
@@ -120,10 +124,10 @@ class CaseExpression extends Component
switch ($token->keyword) {
case 'WHEN':
++$list->idx; // Skip 'WHEN'
$newCondition = Condition::parse($parser, $list);
$new_condition = Condition::parse($parser, $list);
$type = 1;
$state = 1;
$ret->conditions[] = $newCondition;
$ret->conditions[] = $new_condition;
break;
case 'ELSE':
++$list->idx; // Skip 'ELSE'
@@ -149,9 +153,9 @@ class CaseExpression extends Component
switch ($token->keyword) {
case 'WHEN':
++$list->idx; // Skip 'WHEN'
$newValue = Expression::parse($parser, $list);
$new_value = Expression::parse($parser, $list);
$state = 2;
$ret->compare_values[] = $newValue;
$ret->compare_values[] = $new_value;
break;
case 'ELSE':
++$list->idx; // Skip 'ELSE'
@@ -168,11 +172,13 @@ class CaseExpression extends Component
}
}
} else {
if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'THEN') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->keyword === 'THEN'
) {
++$list->idx; // Skip 'THEN'
$newResult = Expression::parse($parser, $list);
$new_result = Expression::parse($parser, $list);
$state = 0;
$ret->results[] = $newResult;
$ret->results[] = $new_result;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error('Unexpected keyword.', $token);
break;
@@ -180,10 +186,12 @@ class CaseExpression extends Component
}
} elseif ($state === 2) {
if ($type === 0) {
if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'THEN') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->keyword === 'THEN'
) {
++$list->idx; // Skip 'THEN'
$newResult = Expression::parse($parser, $list);
$ret->results[] = $newResult;
$new_result = Expression::parse($parser, $list);
$ret->results[] = $new_result;
$state = 1;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error('Unexpected keyword.', $token);
@@ -194,7 +202,10 @@ class CaseExpression extends Component
}
if ($state !== 3) {
$parser->error('Unexpected end of CASE expression', $list->tokens[$list->idx - 1]);
$parser->error(
'Unexpected end of CASE expression',
$list->tokens[$list->idx - 1]
);
} else {
// Parse for alias of CASE expression
$asFound = false;
@@ -207,33 +218,32 @@ class CaseExpression extends Component
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
if (($token->type === Token::TYPE_WHITESPACE)
|| ($token->type === Token::TYPE_COMMENT)
) {
continue;
}
// Handle optional AS keyword before alias
if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'AS') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->keyword === 'AS') {
if ($asFound || ! empty($ret->alias)) {
$parser->error('Potential duplicate alias of CASE expression.', $token);
break;
}
$asFound = true;
continue;
}
if (
$asFound
if ($asFound
&& $token->type === Token::TYPE_KEYWORD
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED || $token->flags & Token::FLAG_KEYWORD_FUNCTION)
) {
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED || $token->flags & Token::FLAG_KEYWORD_FUNCTION)) {
$parser->error('An alias expected after AS but got ' . $token->value, $token);
$asFound = false;
break;
}
if (
$asFound
if ($asFound
|| $token->type === Token::TYPE_STRING
|| ($token->type === Token::TYPE_SYMBOL && ! $token->flags & Token::FLAG_SYMBOL_VARIABLE)
|| $token->type === Token::TYPE_NONE
@@ -243,7 +253,6 @@ class CaseExpression extends Component
$parser->error('An alias was previously found.', $token);
break;
}
$ret->alias = $token->value;
$asFound = false;
@@ -252,7 +261,6 @@ class CaseExpression extends Component
break;
}
if ($asFound) {
$parser->error('An alias was expected after AS.', $list->tokens[$list->idx - 1]);
}
@@ -271,32 +279,30 @@ class CaseExpression extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
$ret = 'CASE ';
if (isset($component->value)) {
// Syntax type 0
$ret .= $component->value . ' ';
$valuesCount = count($component->compare_values);
$resultsCount = count($component->results);
for ($i = 0; $i < $valuesCount && $i < $resultsCount; ++$i) {
$val_cnt = count($component->compare_values);
$res_cnt = count($component->results);
for ($i = 0; $i < $val_cnt && $i < $res_cnt; ++$i) {
$ret .= 'WHEN ' . $component->compare_values[$i] . ' ';
$ret .= 'THEN ' . $component->results[$i] . ' ';
}
} else {
// Syntax type 1
$valuesCount = count($component->conditions);
$resultsCount = count($component->results);
for ($i = 0; $i < $valuesCount && $i < $resultsCount; ++$i) {
$val_cnt = count($component->conditions);
$res_cnt = count($component->results);
for ($i = 0; $i < $val_cnt && $i < $res_cnt; ++$i) {
$ret .= 'WHEN ' . Condition::build($component->conditions[$i]) . ' ';
$ret .= 'THEN ' . $component->results[$i] . ' ';
}
}
if (isset($component->else_result)) {
$ret .= 'ELSE ' . $component->else_result . ' ';
}
$ret .= 'END';
if ($component->alias) {
@@ -1,10 +1,9 @@
<?php
/**
* `WHERE` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,15 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function in_array;
use function is_array;
use function trim;
/**
* `WHERE` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Condition extends Component
{
@@ -29,20 +25,20 @@ class Condition extends Component
*
* @var array
*/
public static $DELIMITERS = [
public static $DELIMITERS = array(
'&&',
'||',
'AND',
'OR',
'XOR',
];
'XOR'
);
/**
* List of allowed reserved keywords in conditions.
*
* @var array
*/
public static $ALLOWED_KEYWORDS = [
public static $ALLOWED_KEYWORDS = array(
'ALL' => 1,
'AND' => 1,
'BETWEEN' => 1,
@@ -60,16 +56,15 @@ class Condition extends Component
'OR' => 1,
'REGEXP' => 1,
'RLIKE' => 1,
'SOUNDS' => 1,
'XOR' => 1,
];
'XOR' => 1
);
/**
* Identifiers recognized.
*
* @var array
*/
public $identifiers = [];
public $identifiers = array();
/**
* Whether this component is an operator.
@@ -86,11 +81,13 @@ class Condition extends Component
public $expr;
/**
* Constructor.
*
* @param string $expr the condition or the operator
*/
public function __construct($expr = null)
{
$this->expr = trim((string) $expr);
$this->expr = trim($expr);
}
/**
@@ -100,11 +97,11 @@ class Condition extends Component
*
* @return Condition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* Counts brackets.
@@ -162,25 +159,23 @@ class Condition extends Component
}
// Adding the operator.
$expr = new static($token->value);
$expr = new self($token->value);
$expr->isOperator = true;
$ret[] = $expr;
// Preparing to parse another condition.
$expr = new static();
$expr = new self();
continue;
}
}
if (
($token->type === Token::TYPE_KEYWORD)
if (($token->type === Token::TYPE_KEYWORD)
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ! ($token->flags & Token::FLAG_KEYWORD_FUNCTION)
) {
if ($token->value === 'BETWEEN') {
$betweenBefore = true;
}
if (($brackets === 0) && empty(static::$ALLOWED_KEYWORDS[$token->value])) {
break;
}
@@ -193,27 +188,21 @@ class Condition extends Component
if ($brackets === 0) {
break;
}
--$brackets;
}
}
$expr->expr .= $token->token;
if (
($token->type !== Token::TYPE_NONE)
&& (($token->type !== Token::TYPE_KEYWORD)
|| ($token->flags & Token::FLAG_KEYWORD_RESERVED))
&& ($token->type !== Token::TYPE_STRING)
&& ($token->type !== Token::TYPE_SYMBOL)
if (($token->type === Token::TYPE_NONE)
|| (($token->type === Token::TYPE_KEYWORD)
&& (! ($token->flags & Token::FLAG_KEYWORD_RESERVED)))
|| ($token->type === Token::TYPE_STRING)
|| ($token->type === Token::TYPE_SYMBOL)
) {
continue;
if (! in_array($token->value, $expr->identifiers)) {
$expr->identifiers[] = $token->value;
}
}
if (in_array($token->value, $expr->identifiers)) {
continue;
}
$expr->identifiers[] = $token->value;
}
// Last iteration was not processed.
@@ -233,7 +222,7 @@ class Condition extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(' ', $component);
@@ -1,12 +1,11 @@
<?php
/**
* Parses the create definition of a column or a key.
*
* Used for parsing `CREATE TABLE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -15,16 +14,14 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
use function trim;
/**
* Parses the create definition of a column or a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CreateDefinition extends Component
{
@@ -33,61 +30,61 @@ class CreateDefinition extends Component
*
* @var array
*/
public static $FIELD_OPTIONS = [
public static $FIELD_OPTIONS = array(
// Tells the `OptionsArray` to not sort the options.
// See the note below.
'_UNSORTED' => true,
'NOT NULL' => 1,
'NULL' => 1,
'DEFAULT' => [
'DEFAULT' => array(
2,
'expr',
['breakOnAlias' => true],
],
array('breakOnAlias' => true)
),
/* Following are not according to grammar, but MySQL happily accepts
* these at any location */
'CHARSET' => [
'CHARSET' => array(
2,
'var',
],
'COLLATE' => [
),
'COLLATE' => array(
3,
'var',
],
),
'AUTO_INCREMENT' => 3,
'PRIMARY' => 4,
'PRIMARY KEY' => 4,
'UNIQUE' => 4,
'UNIQUE KEY' => 4,
'COMMENT' => [
'COMMENT' => array(
5,
'var',
],
'COLUMN_FORMAT' => [
),
'COLUMN_FORMAT' => array(
6,
'var',
],
'ON UPDATE' => [
),
'ON UPDATE' => array(
7,
'expr',
],
),
// Generated columns options.
'GENERATED ALWAYS' => 8,
'AS' => [
'AS' => array(
9,
'expr',
['parenthesesDelimited' => true],
],
array('parenthesesDelimited' => true)
),
'VIRTUAL' => 10,
'PERSISTENT' => 11,
'STORED' => 11,
'CHECK' => [
'CHECK' => array(
12,
'expr',
['parenthesesDelimited' => true],
],
array('parenthesesDelimited' => true),
),
'INVISIBLE' => 13,
'ENFORCED' => 14,
'NOT' => 15,
@@ -100,12 +97,12 @@ class CreateDefinition extends Component
//
// 'UNIQUE' => 4,
// 'UNIQUE KEY' => 4,
// 'COMMENT' => [5, 'var'],
// 'COMMENT' => array(5, 'var'),
// 'NOT NULL' => 1,
// 'NULL' => 1,
// 'PRIMARY' => 4,
// 'PRIMARY KEY' => 4,
];
);
/**
* The name of the new column.
@@ -150,6 +147,8 @@ class CreateDefinition extends Component
public $options;
/**
* Constructor.
*
* @param string $name the name of the field
* @param OptionsArray $options the options of this field
* @param DataType|Key $type the data type of this field or the key
@@ -181,11 +180,11 @@ class CreateDefinition extends Component
*
* @return CreateDefinition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* The state of the parser.
@@ -230,13 +229,16 @@ class CreateDefinition extends Component
}
if ($state === 0) {
if (($token->type !== Token::TYPE_OPERATOR) || ($token->value !== '(')) {
$parser->error('An opening bracket was expected.', $token);
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 1;
} else {
$parser->error(
'An opening bracket was expected.',
$token
);
break;
}
$state = 1;
} elseif ($state === 1) {
if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'CONSTRAINT') {
$expr->isConstraint = true;
@@ -266,7 +268,10 @@ class CreateDefinition extends Component
$expr->name = $token->value;
$state = 2;
} else {
$parser->error('A symbol name was expected!', $token);
$parser->error(
'A symbol name was expected!',
$token
);
return $ret;
}
@@ -283,14 +288,12 @@ class CreateDefinition extends Component
} else {
--$list->idx;
}
$state = 5;
} elseif ($state === 5) {
if (! empty($expr->type) || ! empty($expr->key)) {
$ret[] = $expr;
}
$expr = new static();
$expr = new self();
if ($token->value === ',') {
$state = 1;
} elseif ($token->value === ')') {
@@ -298,7 +301,10 @@ class CreateDefinition extends Component
++$list->idx;
break;
} else {
$parser->error('A comma or a closing bracket was expected.', $token);
$parser->error(
'A comma or a closing bracket was expected.',
$token
);
$state = 0;
break;
}
@@ -311,7 +317,10 @@ class CreateDefinition extends Component
}
if (($state !== 0) && ($state !== 6)) {
$parser->error('A closing bracket was expected.', $list->tokens[$list->idx - 1]);
$parser->error(
'A closing bracket was expected.',
$list->tokens[$list->idx - 1]
);
}
--$list->idx;
@@ -325,7 +334,7 @@ class CreateDefinition extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return "(\n " . implode(",\n ", $component) . "\n)";
@@ -344,7 +353,7 @@ class CreateDefinition extends Component
if (! empty($component->type)) {
$tmp .= DataType::build(
$component->type,
['lowercase' => true]
array('lowercase' => true)
) . ' ';
}
@@ -1,10 +1,9 @@
<?php
/**
* Parses a data type.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,15 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function strtolower;
use function strtoupper;
use function trim;
/**
* Parses a data type.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class DataType extends Component
{
@@ -29,23 +25,23 @@ class DataType extends Component
*
* @var array
*/
public static $DATA_TYPE_OPTIONS = [
public static $DATA_TYPE_OPTIONS = array(
'BINARY' => 1,
'CHARACTER SET' => [
'CHARACTER SET' => array(
2,
'var',
],
'CHARSET' => [
),
'CHARSET' => array(
2,
'var',
],
'COLLATE' => [
),
'COLLATE' => array(
3,
'var',
],
),
'UNSIGNED' => 4,
'ZEROFILL' => 5,
];
'ZEROFILL' => 5
);
/**
* The name of the data type.
@@ -67,7 +63,7 @@ class DataType extends Component
*
* @var array
*/
public $parameters = [];
public $parameters = array();
/**
* The options of this data type.
@@ -77,13 +73,15 @@ class DataType extends Component
public $options;
/**
* Constructor.
*
* @param string $name the name of this data type
* @param array $parameters the parameters (size or possible values)
* @param OptionsArray $options the options of this data type
*/
public function __construct(
$name = null,
array $parameters = [],
array $parameters = array(),
$options = null
) {
$this->name = $name;
@@ -98,9 +96,9 @@ class DataType extends Component
*
* @return DataType|null
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* The state of the parser.
@@ -129,20 +127,18 @@ class DataType extends Component
}
if ($state === 0) {
$ret->name = strtoupper((string) $token->value);
$ret->name = strtoupper($token->value);
if (($token->type !== Token::TYPE_KEYWORD) || (! ($token->flags & Token::FLAG_KEYWORD_DATA_TYPE))) {
$parser->error('Unrecognized data type.', $token);
}
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$parameters = ArrayObj::parse($parser, $list);
++$list->idx;
$ret->parameters = ($ret->name === 'ENUM') || ($ret->name === 'SET') ?
$ret->parameters = (($ret->name === 'ENUM') || ($ret->name === 'SET')) ?
$parameters->raw : $parameters->values;
}
$ret->options = OptionsArray::parse($parser, $list, static::$DATA_TYPE_OPTIONS);
++$list->idx;
break;
@@ -164,7 +160,7 @@ class DataType extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
$name = empty($options['lowercase']) ?
$component->name : strtolower($component->name);
@@ -1,30 +1,25 @@
<?php
/**
* Parses a reference to an expression (column, table or database name, function
* call, mathematical expression, etc.).
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Exceptions\ParserException;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
use function strlen;
use function trim;
/**
* Parses a reference to an expression (column, table or database name, function
* call, mathematical expression, etc.).
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Expression extends Component
{
@@ -33,7 +28,7 @@ class Expression extends Component
*
* @var array
*/
private static $ALLOWED_KEYWORDS = [
private static $ALLOWED_KEYWORDS = array(
'AS' => 1,
'DUAL' => 1,
'NULL' => 1,
@@ -44,10 +39,8 @@ class Expression extends Component
'OR' => 1,
'XOR' => 1,
'NOT' => 1,
'MOD' => 1,
'OVER' => 2,
];
'MOD' => 1
);
/**
* The name of this database.
@@ -99,6 +92,8 @@ class Expression extends Component
public $subquery;
/**
* Constructor.
*
* Syntax:
* new Expression('expr')
* new Expression('expr', 'alias')
@@ -159,12 +154,11 @@ class Expression extends Component
* @param array $options parameters for parsing
*
* @return Expression|null
*
* @throws ParserException
* @throws \PhpMyAdmin\SqlParser\Exceptions\ParserException
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* Whether current tokens make an expression or a table reference.
@@ -199,10 +193,10 @@ class Expression extends Component
*
* @var Token[]
*/
$prev = [
$prev = array(
null,
null,
];
null
);
// When a field is parsed, no parentheses are expected.
if (! empty($options['parseField'])) {
@@ -224,48 +218,50 @@ class Expression extends Component
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
if (($token->type === Token::TYPE_WHITESPACE)
|| ($token->type === Token::TYPE_COMMENT)
) {
if ($isExpr) {
$ret->expr .= $token->token;
}
continue;
}
if ($token->type === Token::TYPE_KEYWORD) {
if (($brackets > 0) && empty($ret->subquery) && ! empty(Parser::$STATEMENT_PARSERS[$token->keyword])) {
if (($brackets > 0) && empty($ret->subquery)
&& ! empty(Parser::$STATEMENT_PARSERS[$token->keyword])
) {
// A `(` was previously found and this keyword is the
// beginning of a statement, so this is a subquery.
$ret->subquery = $token->keyword;
} elseif (
($token->flags & Token::FLAG_KEYWORD_FUNCTION)
} elseif (($token->flags & Token::FLAG_KEYWORD_FUNCTION)
&& (empty($options['parseField'])
&& ! $alias)
) {
$isExpr = true;
} elseif (($token->flags & Token::FLAG_KEYWORD_RESERVED) && ($brackets === 0)) {
} elseif (($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ($brackets === 0)
) {
if (empty(self::$ALLOWED_KEYWORDS[$token->keyword])) {
// A reserved keyword that is not allowed in the
// expression was found so the expression must have
// ended and a new clause is starting.
break;
}
if ($token->keyword === 'AS') {
if (! empty($options['breakOnAlias'])) {
break;
}
if ($alias) {
$parser->error('An alias was expected.', $token);
$parser->error(
'An alias was expected.',
$token
);
break;
}
$alias = true;
continue;
}
if ($token->keyword === 'CASE') {
} elseif ($token->keyword === 'CASE') {
// For a use of CASE like
// 'SELECT a = CASE .... END, b=1, `id`, ... FROM ...'
$tempCaseExpr = CaseExpression::parse($parser, $list);
@@ -273,16 +269,14 @@ class Expression extends Component
$isExpr = true;
continue;
}
$isExpr = true;
} elseif ($brackets === 0 && strlen((string) $ret->expr) > 0 && ! $alias) {
} elseif ($brackets === 0 && strlen($ret->expr) > 0 && ! $alias) {
/* End of expression */
break;
}
}
if (
($token->type === Token::TYPE_NUMBER)
if (($token->type === Token::TYPE_NUMBER)
|| ($token->type === Token::TYPE_BOOL)
|| (($token->type === Token::TYPE_SYMBOL)
&& ($token->flags & Token::FLAG_SYMBOL_VARIABLE))
@@ -301,15 +295,15 @@ class Expression extends Component
}
if ($token->type === Token::TYPE_OPERATOR) {
if (! empty($options['breakOnParentheses']) && (($token->value === '(') || ($token->value === ')'))) {
if (! empty($options['breakOnParentheses'])
&& (($token->value === '(') || ($token->value === ')'))
) {
// No brackets were expected.
break;
}
if ($token->value === '(') {
++$brackets;
if (
empty($ret->function) && ($prev[1] !== null)
if (empty($ret->function) && ($prev[1] !== null)
&& (($prev[1]->type === Token::TYPE_NONE)
|| ($prev[1]->type === Token::TYPE_SYMBOL)
|| (($prev[1]->type === Token::TYPE_KEYWORD)
@@ -321,21 +315,21 @@ class Expression extends Component
if ($brackets === 0) {
// Not our bracket
break;
}
--$brackets;
if ($brackets === 0) {
if (! empty($options['parenthesesDelimited'])) {
// The current token is the last bracket, the next
// one will be outside the expression.
$ret->expr .= $token->token;
++$list->idx;
} else {
--$brackets;
if ($brackets === 0) {
if (! empty($options['parenthesesDelimited'])) {
// The current token is the last bracket, the next
// one will be outside the expression.
$ret->expr .= $token->token;
++$list->idx;
break;
}
} elseif ($brackets < 0) {
// $parser->error('Unexpected closing bracket.', $token);
// $brackets = 0;
break;
}
} elseif ($brackets < 0) {
// $parser->error('Unexpected closing bracket.', $token);
// $brackets = 0;
break;
}
} elseif ($token->value === ',') {
// Expressions are comma-delimited.
@@ -355,27 +349,25 @@ class Expression extends Component
$parser->error('An alias was previously found.', $token);
break;
}
$ret->alias = $token->value;
$alias = false;
} elseif ($isExpr) {
// Handling aliases.
if (
$brackets === 0
&& ($prev[0] === null
|| (($prev[0]->type !== Token::TYPE_OPERATOR || $prev[0]->token === ')')
&& ($prev[0]->type !== Token::TYPE_KEYWORD
|| ! ($prev[0]->flags & Token::FLAG_KEYWORD_RESERVED))))
if (/* (empty($ret->alias)) && */ ($brackets === 0)
&& (($prev[0] === null)
|| ((($prev[0]->type !== Token::TYPE_OPERATOR)
|| ($prev[0]->token === ')'))
&& (($prev[0]->type !== Token::TYPE_KEYWORD)
|| (! ($prev[0]->flags & Token::FLAG_KEYWORD_RESERVED)))))
&& (($prev[1]->type === Token::TYPE_STRING)
|| ($prev[1]->type === Token::TYPE_SYMBOL
&& ! ($prev[1]->flags & Token::FLAG_SYMBOL_VARIABLE))
|| ($prev[1]->type === Token::TYPE_NONE))
|| (($prev[1]->type === Token::TYPE_SYMBOL)
&& (! ($prev[1]->flags & Token::FLAG_SYMBOL_VARIABLE)))
|| ($prev[1]->type === Token::TYPE_NONE))
) {
if (! empty($ret->alias)) {
$parser->error('An alias was previously found.', $token);
break;
}
$ret->alias = $prev[1]->value;
} else {
$ret->expr .= $token->token;
@@ -388,7 +380,6 @@ class Expression extends Component
if (! empty($ret->database) || $dot) {
$parser->error('Unexpected dot.', $token);
}
$ret->database = $ret->table;
$ret->table = $ret->column;
$ret->column = null;
@@ -405,12 +396,10 @@ class Expression extends Component
if (! empty($options['breakOnAlias'])) {
break;
}
if (! empty($ret->alias)) {
$parser->error('An alias was previously found.', $token);
break;
}
$ret->alias = $token->value;
}
}
@@ -418,11 +407,14 @@ class Expression extends Component
}
if ($alias) {
$parser->error('An alias was expected.', $list->tokens[$list->idx - 1]);
$parser->error(
'An alias was expected.',
$list->tokens[$list->idx - 1]
);
}
// White-spaces might be added at the end.
$ret->expr = trim((string) $ret->expr);
$ret->expr = trim($ret->expr);
if ($ret->expr === '') {
return null;
@@ -439,28 +431,25 @@ class Expression extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
}
if ($component->expr !== '' && $component->expr !== null) {
if ($component->expr !== '' && ! is_null($component->expr)) {
$ret = $component->expr;
} else {
$fields = [];
$fields = array();
if (isset($component->database) && ($component->database !== '')) {
$fields[] = $component->database;
}
if (isset($component->table) && ($component->table !== '')) {
$fields[] = $component->table;
}
if (isset($component->column) && ($component->column !== '')) {
$fields[] = $component->column;
}
$ret = implode('.', Context::escape($fields));
}
@@ -1,29 +1,22 @@
<?php
/**
* Parses a list of expressions delimited by a comma.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Exceptions\ParserException;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function count;
use function implode;
use function is_array;
use function preg_match;
use function strlen;
use function substr;
/**
* Parses a list of expressions delimited by a comma.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ExpressionArray extends Component
{
@@ -33,12 +26,11 @@ class ExpressionArray extends Component
* @param array $options parameters for parsing
*
* @return Expression[]
*
* @throws ParserException
* @throws \PhpMyAdmin\SqlParser\Exceptions\ParserException
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
/**
* The state of the parser.
@@ -72,8 +64,7 @@ class ExpressionArray extends Component
continue;
}
if (
($token->type === Token::TYPE_KEYWORD)
if (($token->type === Token::TYPE_KEYWORD)
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ((~$token->flags & Token::FLAG_KEYWORD_FUNCTION))
&& ($token->value !== 'DUAL')
@@ -85,7 +76,9 @@ class ExpressionArray extends Component
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD && $token->value === 'CASE') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'CASE'
) {
$expr = CaseExpression::parse($parser, $list, $options);
} else {
$expr = Expression::parse($parser, $list, $options);
@@ -94,20 +87,22 @@ class ExpressionArray extends Component
if ($expr === null) {
break;
}
$ret[] = $expr;
$state = 1;
} elseif ($state === 1) {
if ($token->value !== ',') {
if ($token->value === ',') {
$state = 0;
} else {
break;
}
$state = 0;
}
}
if ($state === 0) {
$parser->error('An expression was expected.', $list->tokens[$list->idx]);
$parser->error(
'An expression was expected.',
$list->tokens[$list->idx]
);
}
--$list->idx;
@@ -132,9 +127,9 @@ class ExpressionArray extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
$ret = [];
$ret = array();
foreach ($component as $frag) {
$ret[] = $frag::build($frag);
}
@@ -1,10 +1,9 @@
<?php
/**
* Parses a function call.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,12 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function is_array;
/**
* Parses a function call.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class FunctionCall extends Component
{
@@ -36,6 +35,8 @@ class FunctionCall extends Component
public $parameters;
/**
* Constructor.
*
* @param string $name the name of the function to be called
* @param array|ArrayObj $parameters the parameters of this function
*/
@@ -56,9 +57,9 @@ class FunctionCall extends Component
*
* @return FunctionCall
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* The state of the parser.
@@ -98,7 +99,6 @@ class FunctionCall extends Component
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->parameters = ArrayObj::parse($parser, $list);
}
break;
}
}
@@ -112,7 +112,7 @@ class FunctionCall extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
return $component->name . $component->parameters;
}
@@ -1,10 +1,9 @@
<?php
/**
* `GROUP BY` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,20 +11,15 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
use function trim;
/**
* `GROUP BY` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class GroupKeyword extends Component
{
/** @var mixed */
public $type;
/**
* The expression that is used for grouping.
*
@@ -34,6 +28,8 @@ class GroupKeyword extends Component
public $expr;
/**
* Constructor.
*
* @param Expression $expr the expression that we are sorting by
*/
public function __construct($expr = null)
@@ -48,11 +44,11 @@ class GroupKeyword extends Component
*
* @return GroupKeyword[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* The state of the parser.
@@ -90,17 +86,17 @@ class GroupKeyword extends Component
$expr->expr = Expression::parse($parser, $list);
$state = 1;
} elseif ($state === 1) {
if (
($token->type === Token::TYPE_KEYWORD)
if (($token->type === Token::TYPE_KEYWORD)
&& (($token->keyword === 'ASC') || ($token->keyword === 'DESC'))
) {
$expr->type = $token->keyword;
} elseif (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
} elseif (($token->type === Token::TYPE_OPERATOR)
&& ($token->value === ',')
) {
if (! empty($expr->expr)) {
$ret[] = $expr;
}
$expr = new static();
$expr = new self();
$state = 0;
} else {
break;
@@ -124,12 +120,12 @@ class GroupKeyword extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
}
return trim((string) $component->expr);
return trim($component->expr);
}
}
@@ -1,10 +1,9 @@
<?php
/**
* Parses an Index hint.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,13 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
/**
* Parses an Index hint.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class IndexHint extends Component
{
@@ -48,20 +46,18 @@ class IndexHint extends Component
*
* @var array
*/
public $indexes = [];
public $indexes = array();
/**
* Constructor.
*
* @param string $type the type of hint (USE/FORCE/IGNORE)
* @param string $indexOrKey What the hint is for (INDEX/KEY)
* @param string $for the clause for which this hint is (JOIN/ORDER BY/GROUP BY)
* @param array $indexes List of indexes in this hint
* @param string $indexes List of indexes in this hint
*/
public function __construct(
?string $type = null,
?string $indexOrKey = null,
?string $for = null,
array $indexes = []
) {
public function __construct(string $type = null, string $indexOrKey = null, string $for = null, array $indexes = array())
{
$this->type = $type;
$this->indexOrKey = $indexOrKey;
$this->for = $for;
@@ -75,11 +71,11 @@ class IndexHint extends Component
*
* @return IndexHint|Component[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$expr = new static();
$expr->type = $options['type'] ?? null;
$ret = array();
$expr = new self();
$expr->type = isset($options['type']) ? $options['type'] : null;
/**
* The state of the parser.
*
@@ -90,7 +86,6 @@ class IndexHint extends Component
* 2 -------------------- [ expr_list ] --------------------> 0
* 3 -------------- [ JOIN/GROUP BY/ORDER BY ] -------------> 4
* 4 -------------------- [ expr_list ] --------------------> 0
*
* @var int
*/
$state = 0;
@@ -100,7 +95,6 @@ class IndexHint extends Component
if ($list->idx > 0) {
--$list->idx;
}
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
@@ -113,7 +107,6 @@ class IndexHint extends Component
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
@@ -122,14 +115,13 @@ class IndexHint extends Component
switch ($state) {
case 0:
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->keyword !== 'USE' && $token->keyword !== 'IGNORE' && $token->keyword !== 'FORCE') {
if ($token->keyword === 'USE' || $token->keyword === 'IGNORE' || $token->keyword === 'FORCE') {
$expr->type = $token->keyword;
$state = 1;
} else {
break 2;
}
$expr->type = $token->keyword;
$state = 1;
}
break;
case 1:
if ($token->type === Token::TYPE_KEYWORD) {
@@ -138,13 +130,11 @@ class IndexHint extends Component
} else {
$parser->error('Unexpected keyword.', $token);
}
$state = 2;
} else {
// we expect the token to be a keyword
$parser->error('Unexpected token.', $token);
}
break;
case 2:
if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'FOR') {
@@ -153,50 +143,42 @@ class IndexHint extends Component
$expr->indexes = ExpressionArray::parse($parser, $list);
$state = 0;
$ret[] = $expr;
$expr = new static();
$expr = new self();
}
break;
case 3:
if ($token->type === Token::TYPE_KEYWORD) {
if (
$token->keyword === 'JOIN'
|| $token->keyword === 'GROUP BY'
|| $token->keyword === 'ORDER BY'
) {
if ($token->keyword === 'JOIN' || $token->keyword === 'GROUP BY' || $token->keyword === 'ORDER BY') {
$expr->for = $token->keyword;
} else {
$parser->error('Unexpected keyword.', $token);
}
$state = 4;
} else {
// we expect the token to be a keyword
$parser->error('Unexpected token.', $token);
}
break;
case 4:
$expr->indexes = ExpressionArray::parse($parser, $list);
$state = 0;
$ret[] = $expr;
$expr = new static();
$expr = new self();
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param IndexHint|IndexHint[] $component the component to be built
* @param array $options parameters for building
* @param ArrayObj|ArrayObj[] $component the component to be built
* @param array $options parameters for building
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(' ', $component);
@@ -206,7 +188,6 @@ class IndexHint extends Component
if ($component->for !== null) {
$ret .= 'FOR ' . $component->for . ' ';
}
return $ret . ExpressionArray::build($component->indexes);
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `INTO` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,13 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function trim;
/**
* `INTO` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class IntoKeyword extends Component
{
@@ -27,37 +25,37 @@ class IntoKeyword extends Component
*
* @var array
*/
public static $FIELDS_OPTIONS = [
'TERMINATED BY' => [
public static $FIELDS_OPTIONS = array(
'TERMINATED BY' => array(
1,
'expr',
],
),
'OPTIONALLY' => 2,
'ENCLOSED BY' => [
'ENCLOSED BY' => array(
3,
'expr',
],
'ESCAPED BY' => [
),
'ESCAPED BY' => array(
4,
'expr',
],
];
)
);
/**
* LINES Options for `SELECT...INTO` statements.
*
* @var array
*/
public static $LINES_OPTIONS = [
'STARTING BY' => [
public static $LINES_OPTIONS = array(
'STARTING BY' => array(
1,
'expr',
],
'TERMINATED BY' => [
),
'TERMINATED BY' => array(
2,
'expr',
],
];
)
);
/**
* Type of target (OUTFILE or SYMBOL).
@@ -90,9 +88,9 @@ class IntoKeyword extends Component
/**
* Options for FIELDS/COLUMNS keyword.
*
* @see static::$FIELDS_OPTIONS
*
* @var OptionsArray
*
* @see static::$FIELDS_OPTIONS
*/
public $fields_options;
@@ -106,34 +104,36 @@ class IntoKeyword extends Component
/**
* Options for OPTIONS keyword.
*
* @see static::$LINES_OPTIONS
*
* @var OptionsArray
*
* @see static::$LINES_OPTIONS
*/
public $lines_options;
/**
* @param string $type type of destination (may be OUTFILE)
* @param string|Expression $dest actual destination
* @param array $columns column list of destination
* @param array $values selected fields
* @param OptionsArray $fieldsOptions options for FIELDS/COLUMNS keyword
* @param bool $fieldsKeyword options for OPTIONS keyword
* Constructor.
*
* @param string $type type of destination (may be OUTFILE)
* @param string|Expression $dest actual destination
* @param array $columns column list of destination
* @param array $values selected fields
* @param OptionsArray $fields_options options for FIELDS/COLUMNS keyword
* @param bool $fields_keyword options for OPTIONS keyword
*/
public function __construct(
$type = null,
$dest = null,
$columns = null,
$values = null,
$fieldsOptions = null,
$fieldsKeyword = null
$fields_options = null,
$fields_keyword = null
) {
$this->type = $type;
$this->dest = $dest;
$this->columns = $columns;
$this->values = $values;
$this->fields_options = $fieldsOptions;
$this->fields_keyword = $fieldsKeyword;
$this->fields_options = $fields_options;
$this->fields_keyword = $fields_keyword;
}
/**
@@ -143,9 +143,9 @@ class IntoKeyword extends Component
*
* @return IntoKeyword
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* The state of the parser.
@@ -195,8 +195,7 @@ class IntoKeyword extends Component
}
if ($state === 0) {
if (
(isset($options['fromInsert'])
if ((isset($options['fromInsert'])
&& $options['fromInsert'])
|| (isset($options['fromReplace'])
&& $options['fromReplace'])
@@ -204,22 +203,20 @@ class IntoKeyword extends Component
$ret->dest = Expression::parse(
$parser,
$list,
[
array(
'parseField' => 'table',
'breakOnAlias' => true,
]
'breakOnAlias' => true
)
);
} else {
$ret->values = ExpressionArray::parse($parser, $list);
}
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->columns = ArrayObj::parse($parser, $list)->values;
++$list->idx;
}
break;
} elseif ($state === 2) {
$ret->dest = $token->value;
@@ -243,25 +240,26 @@ class IntoKeyword extends Component
return $ret;
}
/**
* @param Parser $parser The parser
* @param TokensList $list A token list
* @param string $keyword They keyword
*
* @return void
*/
public function parseFileOptions(Parser $parser, TokensList $list, $keyword = 'FIELDS')
{
++$list->idx;
if ($keyword === 'FIELDS' || $keyword === 'COLUMNS') {
// parse field options
$this->fields_options = OptionsArray::parse($parser, $list, static::$FIELDS_OPTIONS);
$this->fields_options = OptionsArray::parse(
$parser,
$list,
static::$FIELDS_OPTIONS
);
$this->fields_keyword = ($keyword === 'FIELDS');
} else {
// parse line options
$this->lines_options = OptionsArray::parse($parser, $list, static::$LINES_OPTIONS);
$this->lines_options = OptionsArray::parse(
$parser,
$list,
static::$LINES_OPTIONS
);
}
}
@@ -271,29 +269,27 @@ class IntoKeyword extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if ($component->dest instanceof Expression) {
$columns = ! empty($component->columns) ? '(`' . implode('`, `', $component->columns) . '`)' : '';
return $component->dest . $columns;
}
if (isset($component->values)) {
} elseif (isset($component->values)) {
return ExpressionArray::build($component->values);
}
$ret = 'OUTFILE "' . $component->dest . '"';
$fieldsOptionsString = OptionsArray::build($component->fields_options);
if (trim($fieldsOptionsString) !== '') {
$fields_options_str = OptionsArray::build($component->fields_options);
if (trim($fields_options_str) !== '') {
$ret .= $component->fields_keyword ? ' FIELDS' : ' COLUMNS';
$ret .= ' ' . $fieldsOptionsString;
$ret .= ' ' . $fields_options_str;
}
$linesOptionsString = OptionsArray::build($component->lines_options, ['expr' => true]);
if (trim($linesOptionsString) !== '') {
$ret .= ' LINES ' . $linesOptionsString;
$lines_options_str = OptionsArray::build($component->lines_options, array('expr' => true));
if (trim($lines_options_str) !== '') {
$ret .= ' LINES ' . $lines_options_str;
}
return $ret;
@@ -1,10 +1,9 @@
<?php
/**
* `JOIN` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,13 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function array_search;
use function implode;
/**
* `JOIN` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class JoinKeyword extends Component
{
@@ -27,7 +25,7 @@ class JoinKeyword extends Component
*
* @var array
*/
public static $JOINS = [
public static $JOINS = array(
'CROSS JOIN' => 'CROSS',
'FULL JOIN' => 'FULL',
'FULL OUTER JOIN' => 'FULL',
@@ -42,8 +40,8 @@ class JoinKeyword extends Component
'NATURAL RIGHT JOIN' => 'NATURAL RIGHT',
'NATURAL LEFT OUTER JOIN' => 'NATURAL LEFT OUTER',
'NATURAL RIGHT OUTER JOIN' => 'NATURAL RIGHT OUTER',
'STRAIGHT_JOIN' => 'STRAIGHT',
];
'STRAIGHT_JOIN' => 'STRAIGHT'
);
/**
* Type of this join.
@@ -76,12 +74,14 @@ class JoinKeyword extends Component
public $using;
/**
* @see JoinKeyword::$JOINS
* Constructor.
*
* @param string $type Join type
* @param Expression $expr join expression
* @param Condition[] $on join conditions
* @param ArrayObj $using columns joined
*
* @see JoinKeyword::$JOINS
*/
public function __construct($type = null, $expr = null, $on = null, $using = null)
{
@@ -98,11 +98,11 @@ class JoinKeyword extends Component
*
* @return JoinKeyword[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* The state of the parser.
@@ -150,14 +150,16 @@ class JoinKeyword extends Component
}
if ($state === 0) {
if (($token->type !== Token::TYPE_KEYWORD) || empty(static::$JOINS[$token->keyword])) {
if (($token->type === Token::TYPE_KEYWORD)
&& ! empty(static::$JOINS[$token->keyword])
) {
$expr->type = static::$JOINS[$token->keyword];
$state = 1;
} else {
break;
}
$expr->type = static::$JOINS[$token->keyword];
$state = 1;
} elseif ($state === 1) {
$expr->expr = Expression::parse($parser, $list, ['field' => 'table']);
$expr->expr = Expression::parse($parser, $list, array('field' => 'table'));
$state = 2;
} elseif ($state === 2) {
if ($token->type === Token::TYPE_KEYWORD) {
@@ -169,28 +171,28 @@ class JoinKeyword extends Component
$state = 4;
break;
default:
if (empty(static::$JOINS[$token->keyword])) {
if (! empty(static::$JOINS[$token->keyword])
) {
$ret[] = $expr;
$expr = new self();
$expr->type = static::$JOINS[$token->keyword];
$state = 1;
} else {
/* Next clause is starting */
break 2;
}
$ret[] = $expr;
$expr = new static();
$expr->type = static::$JOINS[$token->keyword];
$state = 1;
break;
}
}
} elseif ($state === 3) {
$expr->on = Condition::parse($parser, $list);
$ret[] = $expr;
$expr = new static();
$expr = new self();
$state = 0;
} elseif ($state === 4) {
$expr->using = ArrayObj::parse($parser, $list);
$ret[] = $expr;
$expr = new static();
$expr = new self();
$state = 0;
}
}
@@ -210,9 +212,9 @@ class JoinKeyword extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
$ret = [];
$ret = array();
foreach ($component as $c) {
$ret[] = array_search($c->type, static::$JOINS) . ' ' . $c->expr
. (! empty($c->on)
@@ -1,10 +1,9 @@
<?php
/**
* Parses the definition of a key.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -13,15 +12,14 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function trim;
/**
* Parses the definition of a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Key extends Component
{
@@ -30,43 +28,43 @@ class Key extends Component
*
* @var array
*/
public static $KEY_OPTIONS = [
'KEY_BLOCK_SIZE' => [
public static $KEY_OPTIONS = array(
'KEY_BLOCK_SIZE' => array(
1,
'var=',
],
'USING' => [
),
'USING' => array(
2,
'var',
],
'WITH PARSER' => [
),
'WITH PARSER' => array(
3,
'var',
],
'COMMENT' => [
),
'COMMENT' => array(
4,
'var',
],
),
// MariaDB options
'CLUSTERING' => [
'CLUSTERING' => array(
4,
'var=',
],
'ENGINE_ATTRIBUTE' => [
),
'ENGINE_ATTRIBUTE' => array(
5,
'var=',
],
'SECONDARY_ENGINE_ATTRIBUTE' => [
),
'SECONDARY_ENGINE_ATTRIBUTE' => array(
5,
'var=',
],
),
// MariaDB & MySQL options
'VISIBLE' => 6,
'INVISIBLE' => 6,
// MariaDB options
'IGNORED' => 10,
'NOT IGNORED' => 10,
];
);
/**
* The name of this key.
@@ -105,6 +103,8 @@ class Key extends Component
public $options;
/**
* Constructor.
*
* @param string $name the name of the key
* @param array $columns the columns covered by this key
* @param string $type the type of this key
@@ -112,7 +112,7 @@ class Key extends Component
*/
public function __construct(
$name = null,
array $columns = [],
array $columns = array(),
$type = null,
$options = null
) {
@@ -129,16 +129,16 @@ class Key extends Component
*
* @return Key
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* Last parsed column.
*
* @var array<string,mixed>
*/
$lastColumn = [];
$lastColumn = array();
/**
* The state of the parser.
@@ -188,7 +188,9 @@ class Key extends Component
$nextToken = $list->getNext();
$list->idx = $positionBeforeSearch;// Restore the position
if ($nextToken !== null && $nextToken->value === '(') {
if (
$nextToken !== null && $nextToken->value === '('
) {
// Switch to expression mode
$state = 5;
} else {
@@ -202,10 +204,10 @@ class Key extends Component
if ($token->value === '(') {
$state = 3;
} elseif (($token->value === ',') || ($token->value === ')')) {
$state = $token->value === ',' ? 2 : 4;
$state = ($token->value === ',') ? 2 : 4;
if (! empty($lastColumn)) {
$ret->columns[] = $lastColumn;
$lastColumn = [];
$lastColumn = array();
}
}
} elseif (
@@ -238,13 +240,11 @@ class Key extends Component
$state = 4;// go back to state 4 to fetch options
continue;
}
// The expression is not finished, adding a separator for the next expression
if ($token->value === ',') {
$ret->expr .= ', ';
continue;
}
// Start of the expression
if ($token->value === '(') {
// This is the first expression, set to empty
@@ -252,12 +252,17 @@ class Key extends Component
$ret->expr = '';
}
$ret->expr .= Expression::parse($parser, $list, ['parenthesesDelimited' => true]);
$ret->expr .= Expression::parse(
$parser,
$list,
array(
'parenthesesDelimited' => true
)
);
continue;
}
// Another unexpected operator was found
}
// Something else than an operator was found
$parser->error('Unexpected token.', $token);
}
@@ -274,7 +279,7 @@ class Key extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
$ret = $component->type . ' ';
if (! empty($component->name)) {
@@ -282,10 +287,10 @@ class Key extends Component
}
if ($component->expr !== null) {
return $ret . '(' . $component->expr . ') ' . $component->options;
return $ret . '(' . $component->expr . ')' . ' ' . $component->options;
}
$columns = [];
$columns = array();
foreach ($component->columns as $column) {
$tmp = '';
if (isset($column['name'])) {
@@ -1,10 +1,9 @@
<?php
/**
* `LIMIT` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -15,7 +14,9 @@ use PhpMyAdmin\SqlParser\TokensList;
/**
* `LIMIT` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Limit extends Component
{
@@ -34,6 +35,8 @@ class Limit extends Component
public $rowCount;
/**
* Constructor.
*
* @param int $rowCount the row count
* @param int $offset the offset
*/
@@ -50,9 +53,9 @@ class Limit extends Component
*
* @return Limit
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
$offset = false;
@@ -82,7 +85,6 @@ class Limit extends Component
if ($offset) {
$parser->error('An offset was expected.', $token);
}
$offset = true;
continue;
}
@@ -107,7 +109,10 @@ class Limit extends Component
}
if ($offset) {
$parser->error('An offset was expected.', $list->tokens[$list->idx - 1]);
$parser->error(
'An offset was expected.',
$list->tokens[$list->idx - 1]
);
}
--$list->idx;
@@ -121,7 +126,7 @@ class Limit extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
return $component->offset . ', ' . $component->rowCount;
}
@@ -1,10 +1,9 @@
<?php
/**
* Parses a reference to a LOCK expression.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,13 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
/**
* Parses a reference to a LOCK expression.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class LockExpression extends Component
{
@@ -41,11 +39,11 @@ class LockExpression extends Component
* @param TokensList $list the list of tokens that are being parsed
* @param array $options parameters for parsing
*
* @return LockExpression
* @return CaseExpression
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* The state of the parser.
@@ -71,8 +69,7 @@ class LockExpression extends Component
$token = $list->tokens[$list->idx];
// End of statement.
if (
$token->type === Token::TYPE_DELIMITER
if ($token->type === Token::TYPE_DELIMITER
|| ($token->type === Token::TYPE_OPERATOR
&& $token->value === ',')
) {
@@ -80,14 +77,13 @@ class LockExpression extends Component
}
if ($state === 0) {
$ret->table = Expression::parse($parser, $list, ['parseField' => 'table']);
$ret->table = Expression::parse($parser, $list, array('parseField' => 'table'));
$state = 1;
} elseif ($state === 1) {
// parse lock type
$ret->type = self::parseLockType($parser, $list);
$state = 2;
}
$prevToken = $token;
}
@@ -107,7 +103,7 @@ class LockExpression extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
@@ -116,9 +112,6 @@ class LockExpression extends Component
return $component->table . ' ' . $component->type;
}
/**
* @return string
*/
private static function parseLockType(Parser $parser, TokensList $list)
{
$lockType = '';
@@ -149,8 +142,7 @@ class LockExpression extends Component
$token = $list->tokens[$list->idx];
// End of statement.
if (
$token->type === Token::TYPE_DELIMITER
if ($token->type === Token::TYPE_DELIMITER
|| ($token->type === Token::TYPE_OPERATOR
&& $token->value === ',')
) {
@@ -180,24 +172,23 @@ class LockExpression extends Component
$parser->error('Unexpected keyword.', $token);
break;
}
$lockType .= $token->keyword;
} elseif ($state === 1) {
if ($token->keyword !== 'LOCAL') {
if ($token->keyword === 'LOCAL') {
$lockType .= ' ' . $token->keyword;
$state = 3;
} else {
$parser->error('Unexpected keyword.', $token);
break;
}
$lockType .= ' ' . $token->keyword;
$state = 3;
} elseif ($state === 2) {
if ($token->keyword !== 'WRITE') {
if ($token->keyword === 'WRITE') {
$lockType .= ' ' . $token->keyword;
$state = 3; // parsing over
} else {
$parser->error('Unexpected keyword.', $token);
break;
}
$lockType .= ' ' . $token->keyword;
$state = 3; // parsing over
}
$prevToken = $token;
@@ -1,10 +1,9 @@
<?php
/**
* Parses a list of options.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -13,19 +12,12 @@ use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use PhpMyAdmin\SqlParser\Translator;
use function array_merge_recursive;
use function count;
use function implode;
use function is_array;
use function ksort;
use function sprintf;
use function strcasecmp;
use function strtoupper;
/**
* Parses a list of options.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class OptionsArray extends Component
{
@@ -34,14 +26,16 @@ class OptionsArray extends Component
*
* @var array
*/
public $options = [];
public $options = array();
/**
* Constructor.
*
* @param array $options The array of options. Options that have a value
* must be an array with at least two keys `name` and
* `expr` or `value`.
*/
public function __construct(array $options = [])
public function __construct(array $options = array())
{
$this->options = $options;
}
@@ -53,9 +47,9 @@ class OptionsArray extends Component
*
* @return OptionsArray
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* The ID that will be assigned to duplicate options.
@@ -125,40 +119,40 @@ class OptionsArray extends Component
if ($lastOption === null) {
$upper = strtoupper($token->token);
if (! isset($options[$upper])) {
if (isset($options[$upper])) {
$lastOption = $options[$upper];
$lastOptionId = is_array($lastOption) ?
$lastOption[0] : $lastOption;
$state = 0;
// Checking for option conflicts.
// For example, in `SELECT` statements the keywords `ALL`
// and `DISTINCT` conflict and if used together, they
// produce an invalid query.
//
// Usually, tokens can be identified in the array by the
// option ID, but if conflicts occur, a generated option ID
// is used.
//
// The first pseudo duplicate ID is the maximum value of the
// real options (e.g. if there are 5 options, the first
// fake ID is 6).
if (isset($ret->options[$lastOptionId])) {
$parser->error(
sprintf(
Translator::gettext('This option conflicts with "%1$s".'),
is_array($ret->options[$lastOptionId])
? $ret->options[$lastOptionId]['name']
: $ret->options[$lastOptionId]
),
$token
);
$lastOptionId = $lastAssignedId++;
}
} else {
// There is no option to be processed.
break;
}
$lastOption = $options[$upper];
$lastOptionId = is_array($lastOption) ?
$lastOption[0] : $lastOption;
$state = 0;
// Checking for option conflicts.
// For example, in `SELECT` statements the keywords `ALL`
// and `DISTINCT` conflict and if used together, they
// produce an invalid query.
//
// Usually, tokens can be identified in the array by the
// option ID, but if conflicts occur, a generated option ID
// is used.
//
// The first pseudo duplicate ID is the maximum value of the
// real options (e.g. if there are 5 options, the first
// fake ID is 6).
if (isset($ret->options[$lastOptionId])) {
$parser->error(
sprintf(
Translator::gettext('This option conflicts with "%1$s".'),
is_array($ret->options[$lastOptionId])
? $ret->options[$lastOptionId]['name']
: $ret->options[$lastOptionId]
),
$token
);
$lastOptionId = $lastAssignedId++;
}
}
if ($state === 0) {
@@ -173,7 +167,7 @@ class OptionsArray extends Component
// This is only the beginning. The value is parsed in state
// 1 and 2. State 1 is used to skip the first equals sign
// and state 2 to parse the actual value.
$ret->options[$lastOptionId] = [
$ret->options[$lastOptionId] = array(
// @var string The name of the option.
'name' => $token->value,
// @var bool Whether it contains an equal sign.
@@ -182,8 +176,8 @@ class OptionsArray extends Component
// @var string Raw value.
'expr' => '',
// @var string Processed value.
'value' => '',
];
'value' => ''
);
$state = 1;
} elseif ($lastOption[1] === 'expr' || $lastOption[1] === 'expr=') {
// This is a keyword that is followed by an expression.
@@ -191,15 +185,15 @@ class OptionsArray extends Component
// Skipping this option in order to parse the expression.
++$list->idx;
$ret->options[$lastOptionId] = [
$ret->options[$lastOptionId] = array(
// @var string The name of the option.
'name' => $token->value,
// @var bool Whether it contains an equal sign.
// This is used by the builder to rebuild it.
'equals' => $lastOption[1] === 'expr=',
// @var Expression The parsed expression.
'expr' => '',
];
'expr' => ''
);
$state = 1;
}
} elseif ($state === 1) {
@@ -212,43 +206,37 @@ class OptionsArray extends Component
// This is outside the `elseif` group above because the change might
// change this iteration.
if ($state !== 2) {
continue;
}
if ($lastOption[1] === 'expr' || $lastOption[1] === 'expr=') {
$ret->options[$lastOptionId]['expr'] = Expression::parse(
$parser,
$list,
empty($lastOption[2]) ? [] : $lastOption[2]
);
if ($ret->options[$lastOptionId]['expr'] !== null) {
if ($state === 2) {
if ($lastOption[1] === 'expr' || $lastOption[1] === 'expr=') {
$ret->options[$lastOptionId]['expr'] = Expression::parse(
$parser,
$list,
empty($lastOption[2]) ? array() : $lastOption[2]
);
$ret->options[$lastOptionId]['value']
= $ret->options[$lastOptionId]['expr']->expr;
}
$lastOption = null;
$state = 0;
} else {
if ($token->token === '(') {
++$brackets;
} elseif ($token->token === ')') {
--$brackets;
}
$ret->options[$lastOptionId]['expr'] .= $token->token;
if (
! (($token->token === '(') && ($brackets === 1)
|| (($token->token === ')') && ($brackets === 0)))
) {
// First pair of brackets is being skipped.
$ret->options[$lastOptionId]['value'] .= $token->value;
}
// Checking if we finished parsing.
if ($brackets === 0) {
$lastOption = null;
$state = 0;
} else {
if ($token->token === '(') {
++$brackets;
} elseif ($token->token === ')') {
--$brackets;
}
$ret->options[$lastOptionId]['expr'] .= $token->token;
if (! ((($token->token === '(') && ($brackets === 1))
|| (($token->token === ')') && ($brackets === 0)))
) {
// First pair of brackets is being skipped.
$ret->options[$lastOptionId]['value'] .= $token->value;
}
// Checking if we finished parsing.
if ($brackets === 0) {
$lastOption = null;
}
}
}
}
@@ -257,8 +245,7 @@ class OptionsArray extends Component
* We reached the end of statement without getting a value
* for an option for which a value was required
*/
if (
$state === 1
if ($state === 1
&& $lastOption
&& ($lastOption[1] === 'expr'
|| $lastOption[1] === 'var'
@@ -289,19 +276,19 @@ class OptionsArray extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (empty($component->options)) {
return '';
}
$options = [];
$options = array();
foreach ($component->options as $option) {
if (! is_array($option)) {
$options[] = $option;
} else {
$options[] = $option['name']
. (! empty($option['equals']) && $option['equals'] ? '=' : ' ')
. ((! empty($option['equals']) && $option['equals']) ? '=' : ' ')
. (! empty($option['expr']) ? $option['expr'] : $option['value']);
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `ORDER BY` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,13 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
/**
* `ORDER BY` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class OrderKeyword extends Component
{
@@ -37,6 +35,8 @@ class OrderKeyword extends Component
public $type;
/**
* Constructor.
*
* @param Expression $expr the expression that we are sorting by
* @param string $type the sorting type
*/
@@ -53,11 +53,11 @@ class OrderKeyword extends Component
*
* @return OrderKeyword[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* The state of the parser.
@@ -95,17 +95,17 @@ class OrderKeyword extends Component
$expr->expr = Expression::parse($parser, $list);
$state = 1;
} elseif ($state === 1) {
if (
($token->type === Token::TYPE_KEYWORD)
if (($token->type === Token::TYPE_KEYWORD)
&& (($token->keyword === 'ASC') || ($token->keyword === 'DESC'))
) {
$expr->type = $token->keyword;
} elseif (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
} elseif (($token->type === Token::TYPE_OPERATOR)
&& ($token->value === ',')
) {
if (! empty($expr->expr)) {
$ret[] = $expr;
}
$expr = new static();
$expr = new self();
$state = 0;
} else {
break;
@@ -129,7 +129,7 @@ class OrderKeyword extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
@@ -1,10 +1,9 @@
<?php
/**
* The definition of a parameter of a function or procedure.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -13,14 +12,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
use function trim;
/**
* The definition of a parameter of a function or procedure.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ParameterDefinition extends Component
{
@@ -46,6 +43,8 @@ class ParameterDefinition extends Component
public $type;
/**
* Constructor.
*
* @param string $name parameter's name
* @param string $inOut parameter's directional type (IN / OUT or None)
* @param DataType $type parameter's type
@@ -64,11 +63,11 @@ class ParameterDefinition extends Component
*
* @return ParameterDefinition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* The state of the parser.
@@ -111,7 +110,6 @@ class ParameterDefinition extends Component
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 1;
}
continue;
} elseif ($state === 1) {
if (($token->value === 'IN') || ($token->value === 'OUT') || ($token->value === 'INOUT')) {
@@ -129,7 +127,7 @@ class ParameterDefinition extends Component
$state = 3;
} elseif ($state === 3) {
$ret[] = $expr;
$expr = new static();
$expr = new self();
if ($token->value === ',') {
$state = 1;
} elseif ($token->value === ')') {
@@ -155,7 +153,7 @@ class ParameterDefinition extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return '(' . implode(', ', $component) . ')';
@@ -1,12 +1,11 @@
<?php
/**
* Parses the create definition of a partition.
*
* Used for parsing `CREATE TABLE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -14,16 +13,14 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
use function trim;
/**
* Parses the create definition of a partition.
*
* Used for parsing `CREATE TABLE` statement.
*
* @final
* @category Components
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class PartitionDefinition extends Component
{
@@ -32,44 +29,44 @@ class PartitionDefinition extends Component
*
* @var array
*/
public static $OPTIONS = [
'STORAGE ENGINE' => [
public static $OPTIONS = array(
'STORAGE ENGINE' => array(
1,
'var',
],
'ENGINE' => [
),
'ENGINE' => array(
1,
'var',
],
'COMMENT' => [
),
'COMMENT' => array(
2,
'var',
],
'DATA DIRECTORY' => [
),
'DATA DIRECTORY' => array(
3,
'var',
],
'INDEX DIRECTORY' => [
),
'INDEX DIRECTORY' => array(
4,
'var',
],
'MAX_ROWS' => [
),
'MAX_ROWS' => array(
5,
'var',
],
'MIN_ROWS' => [
),
'MIN_ROWS' => array(
6,
'var',
],
'TABLESPACE' => [
),
'TABLESPACE' => array(
7,
'var',
],
'NODEGROUP' => [
),
'NODEGROUP' => array(
8,
'var',
],
];
)
);
/**
* Whether this entry is a subpartition or a partition.
@@ -120,9 +117,9 @@ class PartitionDefinition extends Component
*
* @return PartitionDefinition
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* The state of the parser.
@@ -178,10 +175,8 @@ class PartitionDefinition extends Component
if ($nextToken->type !== Token::TYPE_NONE) {
break;
}
$ret->name .= $nextToken->value;
}
$idx = $list->idx--;
// Get the first token after the white space.
$nextToken = $list->tokens[++$idx];
@@ -201,13 +196,12 @@ class PartitionDefinition extends Component
$ret->expr = Expression::parse(
$parser,
$list,
[
array(
'parenthesesDelimited' => true,
'breakOnAlias' => true,
]
'breakOnAlias' => true
)
);
}
$state = 5;
} elseif ($state === 5) {
$ret->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
@@ -217,11 +211,12 @@ class PartitionDefinition extends Component
$ret->subpartitions = ArrayObj::parse(
$parser,
$list,
['type' => 'PhpMyAdmin\\SqlParser\\Components\\PartitionDefinition']
array(
'type' => 'PhpMyAdmin\\SqlParser\\Components\\PartitionDefinition'
)
);
++$list->idx;
}
break;
}
}
@@ -237,7 +232,7 @@ class PartitionDefinition extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return "(\n" . implode(",\n", $component) . "\n)";
@@ -252,8 +247,7 @@ class PartitionDefinition extends Component
return trim(
'PARTITION ' . $component->name
. (empty($component->type) ? '' : ' VALUES ' . $component->type . ' ' . $component->expr . ' ')
. (! empty($component->options) && ! empty($component->type) ? '' : ' ')
. $component->options . $subpartitions
. ((! empty($component->options) && ! empty($component->type)) ? '' : ' ') . $component->options . $subpartitions
);
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `REFERENCES` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -13,13 +12,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function trim;
/**
* `REFERENCES` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Reference extends Component
{
@@ -28,20 +26,20 @@ class Reference extends Component
*
* @var array
*/
public static $REFERENCES_OPTIONS = [
'MATCH' => [
public static $REFERENCES_OPTIONS = array(
'MATCH' => array(
1,
'var',
],
'ON DELETE' => [
),
'ON DELETE' => array(
2,
'var',
],
'ON UPDATE' => [
),
'ON UPDATE' => array(
3,
'var',
],
];
)
);
/**
* The referenced table.
@@ -65,11 +63,13 @@ class Reference extends Component
public $options;
/**
* Constructor.
*
* @param Expression $table the name of the table referenced
* @param array $columns the columns referenced
* @param OptionsArray $options the options
*/
public function __construct($table = null, array $columns = [], $options = null)
public function __construct($table = null, array $columns = array(), $options = null)
{
$this->table = $table;
$this->columns = $columns;
@@ -83,9 +83,9 @@ class Reference extends Component
*
* @return Reference
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new static();
$ret = new self();
/**
* The state of the parser.
@@ -124,10 +124,10 @@ class Reference extends Component
$ret->table = Expression::parse(
$parser,
$list,
[
array(
'parseField' => 'table',
'breakOnAlias' => true,
]
'breakOnAlias' => true
)
);
$state = 1;
} elseif ($state === 1) {
@@ -151,7 +151,7 @@ class Reference extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
return trim(
$component->table
@@ -1,10 +1,9 @@
<?php
/**
* `RENAME TABLE` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,13 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
/**
* `RENAME TABLE` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RenameOperation extends Component
{
@@ -37,6 +35,8 @@ class RenameOperation extends Component
public $new;
/**
* Constructor.
*
* @param Expression $old old expression
* @param Expression $new new expression containing new name
*/
@@ -53,11 +53,11 @@ class RenameOperation extends Component
*
* @return RenameOperation[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* The state of the parser.
@@ -99,50 +99,60 @@ class RenameOperation extends Component
$expr->old = Expression::parse(
$parser,
$list,
[
array(
'breakOnAlias' => true,
'parseField' => 'table',
]
'parseField' => 'table'
)
);
if (empty($expr->old)) {
$parser->error('The old name of the table was expected.', $token);
$parser->error(
'The old name of the table was expected.',
$token
);
}
$state = 1;
} elseif ($state === 1) {
if ($token->type !== Token::TYPE_KEYWORD || $token->keyword !== 'TO') {
$parser->error('Keyword "TO" was expected.', $token);
if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'TO') {
$state = 2;
} else {
$parser->error(
'Keyword "TO" was expected.',
$token
);
break;
}
$state = 2;
} elseif ($state === 2) {
$expr->new = Expression::parse(
$parser,
$list,
[
array(
'breakOnAlias' => true,
'parseField' => 'table',
]
'parseField' => 'table'
)
);
if (empty($expr->new)) {
$parser->error('The new name of the table was expected.', $token);
$parser->error(
'The new name of the table was expected.',
$token
);
}
$state = 3;
} elseif ($state === 3) {
if (($token->type !== Token::TYPE_OPERATOR) || ($token->value !== ',')) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$ret[] = $expr;
$expr = new self();
$state = 0;
} else {
break;
}
$ret[] = $expr;
$expr = new static();
$state = 0;
}
}
if ($state !== 3) {
$parser->error('A rename operation was expected.', $list->tokens[$list->idx - 1]);
$parser->error(
'A rename operation was expected.',
$list->tokens[$list->idx - 1]
);
}
// Last iteration was not saved.
@@ -161,7 +171,7 @@ class RenameOperation extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
@@ -1,10 +1,9 @@
<?php
/**
* `SET` keyword parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
@@ -12,14 +11,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
use function is_array;
use function trim;
/**
* `SET` keyword parser.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class SetOperation extends Component
{
@@ -38,6 +35,8 @@ class SetOperation extends Component
public $value;
/**
* Constructor.
*
* @param string $column Field's name..
* @param string $value new value
*/
@@ -54,11 +53,11 @@ class SetOperation extends Component
*
* @return SetOperation[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = [])
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = [];
$ret = array();
$expr = new static();
$expr = new self();
/**
* The state of the parser.
@@ -100,8 +99,7 @@ class SetOperation extends Component
}
// No keyword is expected.
if (
($token->type === Token::TYPE_KEYWORD)
if (($token->type === Token::TYPE_KEYWORD)
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ($state === 0)
) {
@@ -120,22 +118,22 @@ class SetOperation extends Component
$tmp = Expression::parse(
$parser,
$list,
['breakOnAlias' => true]
array(
'breakOnAlias' => true
)
);
if ($tmp === null) {
if (is_null($tmp)) {
$parser->error('Missing expression.', $token);
break;
}
$expr->column = trim($expr->column);
$expr->value = $tmp->expr;
$ret[] = $expr;
$expr = new static();
$expr = new self();
$state = 0;
$commaLastSeenAt = null;
}
}
--$list->idx;
// We saw a comma, but didn't see a column-value pair after it
@@ -152,7 +150,7 @@ class SetOperation extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
@@ -1,20 +1,19 @@
<?php
/**
* `UNION` keyword builder.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
use function implode;
/**
* `UNION` keyword builder.
*
* @final
* @category Keywords
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class UnionKeyword extends Component
{
@@ -24,9 +23,9 @@ class UnionKeyword extends Component
*
* @return string
*/
public static function build($component, array $options = [])
public static function build($component, array $options = array())
{
$tmp = [];
$tmp = array();
foreach ($component as $componentPart) {
$tmp[] = $componentPart[0] . ' ' . $componentPart[1];
}
@@ -1,67 +0,0 @@
<?php
/**
* `WITH` keyword builder.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Parser;
use RuntimeException;
/**
* `WITH` keyword builder.
*
* @final
*/
final class WithKeyword extends Component
{
/** @var string */
public $name;
/** @var ArrayObj[] */
public $columns = [];
/** @var Parser */
public $statement;
public function __construct(string $name)
{
$this->name = $name;
}
/**
* @param WithKeyword $component
* @param mixed[] $options
*
* @return string
*/
public static function build($component, array $options = [])
{
if (! $component instanceof WithKeyword) {
throw new RuntimeException('Can not build a component that is not a WithKeyword');
}
if (! isset($component->statement)) {
throw new RuntimeException('No statement inside WITH');
}
$str = $component->name;
if ($component->columns) {
$str .= ArrayObj::build($component->columns);
}
$str .= ' AS (';
foreach ($component->statement->statements as $statement) {
$str .= $statement->build();
}
$str .= ')';
return $str;
}
}
+65 -86
View File
@@ -1,4 +1,5 @@
<?php
/**
* Defines a context class that is later extended to define other contexts.
*
@@ -6,26 +7,16 @@
* parsing.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use PhpMyAdmin\SqlParser\Exceptions\LoaderException;
use function class_exists;
use function constant;
use function explode;
use function intval;
use function is_array;
use function is_numeric;
use function str_replace;
use function strlen;
use function strncmp;
use function strtoupper;
use function substr;
/**
* Holds the configuration of the context that is currently used.
*
* @category Contexts
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
abstract class Context
{
@@ -33,23 +24,29 @@ abstract class Context
* The maximum length of a keyword.
*
* @see static::$TOKEN_KEYWORD
*
* @var int
*/
public const KEYWORD_MAX_LENGTH = 30;
const KEYWORD_MAX_LENGTH = 30;
/**
* The maximum length of a label.
*
* @see static::$TOKEN_LABEL
* Ref: https://dev.mysql.com/doc/refman/5.7/en/statement-labels.html
*
* @var int
*/
public const LABEL_MAX_LENGTH = 16;
const LABEL_MAX_LENGTH = 16;
/**
* The maximum length of an operator.
*
* @see static::$TOKEN_OPERATOR
*
* @var int
*/
public const OPERATOR_MAX_LENGTH = 4;
const OPERATOR_MAX_LENGTH = 4;
/**
* The name of the default content.
@@ -89,14 +86,14 @@ abstract class Context
*
* @var array
*/
public static $KEYWORDS = [];
public static $KEYWORDS = array();
/**
* List of operators and their flags.
*
* @var array
*/
public static $OPERATORS = [
public static $OPERATORS = array(
// Some operators (*, =) may have ambiguous flags, because they depend on
// the context they are being used in.
// For example: 1. SELECT * FROM table; # SQL specific (wildcard)
@@ -140,8 +137,8 @@ abstract class Context
')' => 16,
'.' => 16,
',' => 16,
';' => 16,
];
';' => 16
);
/**
* The mode of the MySQL server that will be used in lexing, parsing and
@@ -158,77 +155,77 @@ abstract class Context
// Compatibility mode for Microsoft's SQL server.
// This is the equivalent of ANSI_QUOTES.
public const SQL_MODE_COMPAT_MYSQL = 2;
const SQL_MODE_COMPAT_MYSQL = 2;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_allow_invalid_dates
public const SQL_MODE_ALLOW_INVALID_DATES = 1;
const SQL_MODE_ALLOW_INVALID_DATES = 1;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ansi_quotes
public const SQL_MODE_ANSI_QUOTES = 2;
const SQL_MODE_ANSI_QUOTES = 2;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_error_for_division_by_zero
public const SQL_MODE_ERROR_FOR_DIVISION_BY_ZERO = 4;
const SQL_MODE_ERROR_FOR_DIVISION_BY_ZERO = 4;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_high_not_precedence
public const SQL_MODE_HIGH_NOT_PRECEDENCE = 8;
const SQL_MODE_HIGH_NOT_PRECEDENCE = 8;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ignore_space
public const SQL_MODE_IGNORE_SPACE = 16;
const SQL_MODE_IGNORE_SPACE = 16;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_auto_create_user
public const SQL_MODE_NO_AUTO_CREATE_USER = 32;
const SQL_MODE_NO_AUTO_CREATE_USER = 32;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_auto_value_on_zero
public const SQL_MODE_NO_AUTO_VALUE_ON_ZERO = 64;
const SQL_MODE_NO_AUTO_VALUE_ON_ZERO = 64;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_backslash_escapes
public const SQL_MODE_NO_BACKSLASH_ESCAPES = 128;
const SQL_MODE_NO_BACKSLASH_ESCAPES = 128;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_dir_in_create
public const SQL_MODE_NO_DIR_IN_CREATE = 256;
const SQL_MODE_NO_DIR_IN_CREATE = 256;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_dir_in_create
public const SQL_MODE_NO_ENGINE_SUBSTITUTION = 512;
const SQL_MODE_NO_ENGINE_SUBSTITUTION = 512;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_field_options
public const SQL_MODE_NO_FIELD_OPTIONS = 1024;
const SQL_MODE_NO_FIELD_OPTIONS = 1024;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_key_options
public const SQL_MODE_NO_KEY_OPTIONS = 2048;
const SQL_MODE_NO_KEY_OPTIONS = 2048;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_table_options
public const SQL_MODE_NO_TABLE_OPTIONS = 4096;
const SQL_MODE_NO_TABLE_OPTIONS = 4096;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_unsigned_subtraction
public const SQL_MODE_NO_UNSIGNED_SUBTRACTION = 8192;
const SQL_MODE_NO_UNSIGNED_SUBTRACTION = 8192;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_zero_date
public const SQL_MODE_NO_ZERO_DATE = 16384;
const SQL_MODE_NO_ZERO_DATE = 16384;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_zero_in_date
public const SQL_MODE_NO_ZERO_IN_DATE = 32768;
const SQL_MODE_NO_ZERO_IN_DATE = 32768;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_only_full_group_by
public const SQL_MODE_ONLY_FULL_GROUP_BY = 65536;
const SQL_MODE_ONLY_FULL_GROUP_BY = 65536;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_pipes_as_concat
public const SQL_MODE_PIPES_AS_CONCAT = 131072;
const SQL_MODE_PIPES_AS_CONCAT = 131072;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_real_as_float
public const SQL_MODE_REAL_AS_FLOAT = 262144;
const SQL_MODE_REAL_AS_FLOAT = 262144;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_strict_all_tables
public const SQL_MODE_STRICT_ALL_TABLES = 524288;
const SQL_MODE_STRICT_ALL_TABLES = 524288;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_strict_trans_tables
public const SQL_MODE_STRICT_TRANS_TABLES = 1048576;
const SQL_MODE_STRICT_TRANS_TABLES = 1048576;
// Custom modes.
// The table and column names and any other field that must be escaped will
// not be.
// Reserved keywords are being escaped regardless this mode is used or not.
public const SQL_MODE_NO_ENCLOSING_QUOTES = 1073741824;
const SQL_MODE_NO_ENCLOSING_QUOTES = 1073741824;
/*
* Combination SQL Modes
@@ -236,31 +233,31 @@ abstract class Context
*/
// REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE
public const SQL_MODE_ANSI = 393234;
const SQL_MODE_ANSI = 393234;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS,
public const SQL_MODE_DB2 = 138258;
const SQL_MODE_DB2 = 138258;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS, NO_AUTO_CREATE_USER
public const SQL_MODE_MAXDB = 138290;
const SQL_MODE_MAXDB = 138290;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS
public const SQL_MODE_MSSQL = 138258;
const SQL_MODE_MSSQL = 138258;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS, NO_AUTO_CREATE_USER
public const SQL_MODE_ORACLE = 138290;
const SQL_MODE_ORACLE = 138290;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS
public const SQL_MODE_POSTGRESQL = 138258;
const SQL_MODE_POSTGRESQL = 138258;
// STRICT_TRANS_TABLES, STRICT_ALL_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE,
// ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER
public const SQL_MODE_TRADITIONAL = 1622052;
const SQL_MODE_TRADITIONAL = 1622052;
// -------------------------------------------------------------------------
// Keyword.
@@ -344,24 +341,22 @@ abstract class Context
if ($str[0] === '#') {
return Token::FLAG_COMMENT_BASH;
}
// If comment is opening C style (/*), warning, it could be a MySQL command (/*!)
if (($len > 1) && ($str[0] === '/') && ($str[1] === '*')) {
return ($len > 2) && ($str[2] === '!') ?
Token::FLAG_COMMENT_MYSQL_CMD : Token::FLAG_COMMENT_C;
}
// If comment is closing C style (*/), warning, it could conflicts with wildcard and a real opening C style.
// It would looks like the following valid SQL statement: "SELECT */* comment */ FROM...".
if (($len > 1) && ($str[0] === '*') && ($str[1] === '/')) {
return Token::FLAG_COMMENT_C;
}
// If comment is SQL style (--\s?):
if (($len > 2) && ($str[0] === '-') && ($str[1] === '-') && static::isWhitespace($str[2])) {
if (($len > 2) && ($str[0] === '-')
&& ($str[1] === '-') && static::isWhitespace($str[2])
) {
return Token::FLAG_COMMENT_SQL;
}
if (($len === 2) && $end && ($str[0] === '-') && ($str[1] === '-')) {
return Token::FLAG_COMMENT_SQL;
}
@@ -400,7 +395,7 @@ abstract class Context
*/
public static function isNumber($str)
{
return ($str >= '0') && ($str <= '9') || ($str === '.')
return (($str >= '0') && ($str <= '9')) || ($str === '.')
|| ($str === '-') || ($str === '+') || ($str === 'e') || ($str === 'E');
}
@@ -420,16 +415,11 @@ abstract class Context
if (strlen($str) === 0) {
return null;
}
if ($str[0] === '@') {
return Token::FLAG_SYMBOL_VARIABLE;
}
if ($str[0] === '`') {
} elseif ($str[0] === '`') {
return Token::FLAG_SYMBOL_BACKTICK;
}
if ($str[0] === ':' || $str[0] === '?') {
} elseif ($str[0] === ':' || $str[0] === '?') {
return Token::FLAG_SYMBOL_PARAMETER;
}
@@ -451,12 +441,9 @@ abstract class Context
if (strlen($str) === 0) {
return null;
}
if ($str[0] === '\'') {
return Token::FLAG_STRING_SINGLE_QUOTES;
}
if ($str[0] === '"') {
} elseif ($str[0] === '"') {
return Token::FLAG_STRING_DOUBLE_QUOTES;
}
@@ -493,23 +480,23 @@ abstract class Context
* @param string $context name of the context or full class name that
* defines the context
*
* @throws LoaderException if the specified context doesn't exist.
* @throws LoaderException if the specified context doesn't exist
*/
public static function load($context = '')
{
if (empty($context)) {
$context = self::$defaultContext;
}
if ($context[0] !== '\\') {
// Short context name (must be formatted into class name).
$context = self::$contextPrefix . $context;
}
if (! class_exists($context)) {
throw @new LoaderException('Specified context ("' . $context . '") does not exist.', $context);
throw @new LoaderException(
'Specified context ("' . $context . '") does not exist.',
$context
);
}
self::$loadedContext = $context;
self::$KEYWORDS = $context::$KEYWORDS;
}
@@ -534,7 +521,6 @@ abstract class Context
try {
/* Trying to load the new context */
static::load($context);
return $context;
} catch (LoaderException $e) {
/* Replace last two non zero digits by zeroes */
@@ -546,20 +532,15 @@ abstract class Context
break 2;
}
} while (intval($part) === 0 && $i > 0);
$context = substr($context, 0, $i) . '00' . substr($context, $i + 2);
}
}
/* Fallback to loading at least matching engine */
if (strncmp($context, 'MariaDb', 7) === 0) {
return static::loadClosest('MariaDb100300');
}
if (strncmp($context, 'MySql', 5) === 0) {
} elseif (strncmp($context, 'MySql', 5) === 0) {
return static::loadClosest('MySql50700');
}
return null;
}
@@ -574,7 +555,6 @@ abstract class Context
if (empty($mode)) {
return;
}
$mode = explode(',', $mode);
foreach ($mode as $m) {
static::$MODE |= constant('static::SQL_MODE_' . $m);
@@ -599,7 +579,9 @@ abstract class Context
return $str;
}
if ((static::$MODE & self::SQL_MODE_NO_ENCLOSING_QUOTES) && (! static::isKeyword($str, true))) {
if ((static::$MODE & self::SQL_MODE_NO_ENCLOSING_QUOTES)
&& (! static::isKeyword($str, true))
) {
return $str;
}
@@ -612,7 +594,6 @@ abstract class Context
/**
* Returns char used to quote identifiers based on currently set SQL Mode (ie. standard or ANSI_QUOTES)
*
* @return string either " (double quote, ansi_quotes mode) or ` (backtick, standard mode)
*/
public static function getIdentifierQuote()
@@ -623,16 +604,14 @@ abstract class Context
/**
* Function verifies that given SQL Mode constant is currently set
*
* @return boolean false on empty param, true/false on given constant/int value
* @param int $flag for example Context::SQL_MODE_ANSI_QUOTES
*
* @return bool false on empty param, true/false on given constant/int value
*/
public static function hasMode($flag = null)
{
if (empty($flag)) {
return false;
}
return (self::$MODE & $flag) === $flag;
}
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MariaDB 10.0.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://mariadb.com/kb/en/the-mariadb-library/reserved-words/
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MariaDB 10.0.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://mariadb.com/kb/en/reserved-words/
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMariaDb100000 extends Context
{
@@ -26,10 +32,9 @@ class ContextMariaDb100000 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1,
@@ -296,5 +301,5 @@ class ContextMariaDb100000 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MariaDB 10.1.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://mariadb.com/kb/en/the-mariadb-library/reserved-words/
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MariaDB 10.1.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://mariadb.com/kb/en/reserved-words/
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMariaDb100100 extends Context
{
@@ -26,10 +32,9 @@ class ContextMariaDb100100 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
@@ -343,5 +348,5 @@ class ContextMariaDb100100 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MariaDB 10.2.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://mariadb.com/kb/en/the-mariadb-library/reserved-words/
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MariaDB 10.2.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://mariadb.com/kb/en/reserved-words/
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMariaDb100200 extends Context
{
@@ -26,10 +32,9 @@ class ContextMariaDb100200 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
@@ -122,8 +127,8 @@ class ContextMariaDb100200 extends Context
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'OVER' => 3, 'READ' => 3, 'ROWS' => 3, 'SHOW' => 3, 'THEN' => 3,
'TRUE' => 3, 'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'NULL' => 3, 'READ' => 3, 'ROWS' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3,
'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
@@ -343,5 +348,5 @@ class ContextMariaDb100200 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MariaDB 10.3.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://mariadb.com/kb/en/the-mariadb-library/reserved-words/
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MariaDB 10.3.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://mariadb.com/kb/en/reserved-words/
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMariaDb100300 extends Context
{
@@ -26,10 +32,9 @@ class ContextMariaDb100300 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
@@ -122,8 +127,8 @@ class ContextMariaDb100300 extends Context
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'OVER' => 3, 'READ' => 3, 'ROWS' => 3, 'SHOW' => 3, 'THEN' => 3,
'TRUE' => 3, 'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'NULL' => 3, 'READ' => 3, 'ROWS' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3,
'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
@@ -343,5 +348,5 @@ class ContextMariaDb100300 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,347 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Contexts;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Token;
/**
* Context for MariaDB 10.4.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://mariadb.com/kb/en/reserved-words/
*/
class ContextMariaDb100400 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_RESERVED Token::FLAG_KEYWORD_COMPOSED
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
*/
public static $KEYWORDS = [
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1,
'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1, 'MODE' => 1,
'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'ONLY' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PORT' => 1, 'PREV' => 1, 'SLOW' => 1, 'SOME' => 1, 'STOP' => 1, 'THAN' => 1,
'TYPE' => 1, 'VIEW' => 1, 'WAIT' => 1, 'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'ERROR' => 1, 'EVENT' => 1, 'EVERY' => 1,
'FIRST' => 1, 'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'NEVER' => 1, 'OWNER' => 1, 'PHASE' => 1,
'PROXY' => 1, 'QUERY' => 1, 'QUICK' => 1, 'RELAY' => 1, 'RESET' => 1,
'RTREE' => 1, 'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1,
'SWAPS' => 1, 'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'ALWAYS' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1,
'CLIENT' => 1, 'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1,
'ESCAPE' => 1, 'EVENTS' => 1, 'EXPIRE' => 1, 'EXPORT' => 1, 'FAULTS' => 1,
'FIELDS' => 1, 'FILTER' => 1, 'GLOBAL' => 1, 'GRANTS' => 1, 'IMPORT' => 1,
'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1, 'MEDIUM' => 1, 'MEMORY' => 1,
'MODIFY' => 1, 'NUMBER' => 1, 'OFFSET' => 1, 'PARSER' => 1, 'PLUGIN' => 1,
'RELOAD' => 1, 'REMOVE' => 1, 'REPAIR' => 1, 'RESUME' => 1, 'ROLLUP' => 1,
'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1, 'SOCKET' => 1, 'SONAME' => 1,
'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1, 'STATUS' => 1, 'STRING' => 1,
'TABLES' => 1,
'ACCOUNT' => 1, 'ANALYSE' => 1, 'CHANGED' => 1, 'CHANNEL' => 1, 'COLUMNS' => 1,
'COMMENT' => 1, 'COMPACT' => 1, 'CONTEXT' => 1, 'CURRENT' => 1, 'DEFINER' => 1,
'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1, 'EXECUTE' => 1,
'FOLLOWS' => 1, 'GENERAL' => 1, 'HANDLER' => 1, 'INDEXES' => 1, 'INSTALL' => 1,
'INVOKER' => 1, 'LOGFILE' => 1, 'MIGRATE' => 1, 'NO_WAIT' => 1, 'OPTIONS' => 1,
'PARTIAL' => 1, 'PLUGINS' => 1, 'PREPARE' => 1, 'PROFILE' => 1, 'REBUILD' => 1,
'RECOVER' => 1, 'RESTORE' => 1, 'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1,
'STACKED' => 1, 'STORAGE' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'WITHOUT' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1, 'EXCHANGE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'LANGUAGE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1,
'MIN_ROWS' => 1, 'NATIONAL' => 1, 'NVARCHAR' => 1, 'PRECEDES' => 1, 'PRESERVE' => 1,
'PROFILES' => 1, 'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1, 'SCHEDULE' => 1,
'SECURITY' => 1, 'SEQUENCE' => 1, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1, 'SWITCHES' => 1,
'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'INVISIBLE' => 1, 'IO_THREAD' => 1,
'ISOLATION' => 1, 'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'READ_ONLY' => 1,
'REDUNDANT' => 1, 'SAVEPOINT' => 1, 'SQL_CACHE' => 1, 'TEMPORARY' => 1,
'TEMPTABLE' => 1, 'UNDEFINED' => 1, 'UNINSTALL' => 1, 'VARIABLES' => 1,
'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PLUGIN_DIR' => 1,
'PRIVILEGES' => 1, 'REORGANIZE' => 1, 'REPEATABLE' => 1, 'ROW_FORMAT' => 1,
'SQL_THREAD' => 1, 'TABLESPACE' => 1, 'TABLE_NAME' => 1, 'VALIDATION' => 1,
'COLUMN_NAME' => 1, 'COMPRESSION' => 1, 'CURSOR_NAME' => 1, 'DIAGNOSTICS' => 1,
'EXTENT_SIZE' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1,
'MYSQL_ERRNO' => 1, 'NONBLOCKING' => 1, 'PROCESSLIST' => 1, 'REPLICATION' => 1,
'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1, 'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'DEFAULT_AUTH' => 1, 'DES_KEY_FILE' => 1,
'INITIAL_SIZE' => 1, 'MASTER_DELAY' => 1, 'MESSAGE_TEXT' => 1, 'PARTITIONING' => 1,
'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1, 'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1,
'SQL_TSI_WEEK' => 1, 'SQL_TSI_YEAR' => 1, 'SUBPARTITION' => 1,
'COLUMN_FORMAT' => 1, 'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1, 'RELAY_LOG_POS' => 1,
'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1, 'MASTER_LOG_POS' => 1,
'MASTER_SSL_CRL' => 1, 'MASTER_SSL_KEY' => 1, 'RELAY_LOG_FILE' => 1, 'SQL_TSI_MINUTE' => 1,
'SQL_TSI_SECOND' => 1, 'TABLE_CHECKSUM' => 1, 'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'CONSTRAINT_NAME' => 1, 'DELAY_KEY_WRITE' => 1, 'FILE_BLOCK_SIZE' => 1,
'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1, 'PARSE_GCOL_EXPR' => 1,
'REPLICATE_DO_DB' => 1, 'SQL_AFTER_GTIDS' => 1, 'SQL_TSI_QUARTER' => 1, 'SUBCLASS_ORIGIN' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'SQL_BEFORE_GTIDS' => 1,
'STATS_PERSISTENT' => 1, 'UNDO_BUFFER_SIZE' => 1,
'CONSTRAINT_SCHEMA' => 1, 'GROUP_REPLICATION' => 1, 'IGNORE_SERVER_IDS' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'RETURNED_SQLSTATE' => 1,
'SQL_BUFFER_RESULT' => 1, 'STATS_AUTO_RECALC' => 1,
'CONSTRAINT_CATALOG' => 1, 'MASTER_RETRY_COUNT' => 1, 'MASTER_SSL_CRLPATH' => 1,
'MAX_STATEMENT_TIME' => 1, 'REPLICATE_DO_TABLE' => 1, 'SQL_AFTER_MTS_GAPS' => 1,
'STATS_SAMPLE_PAGES' => 1,
'REPLICATE_IGNORE_DB' => 1,
'MASTER_AUTO_POSITION' => 1, 'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1, 'REPLICATE_REWRITE_DB' => 1,
'REPLICATE_IGNORE_TABLE' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1, 'REPLICATE_WILD_DO_TABLE' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'REPLICATE_WILD_IGNORE_TABLE' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'GET' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3,
'USE' => 3, 'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'OVER' => 3, 'READ' => 3, 'ROWS' => 3, 'SHOW' => 3, 'THEN' => 3,
'TRUE' => 3, 'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'RANGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3,
'UNION' => 3, 'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3,
'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXCEPT' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'LINEAR' => 3, 'OPTION' => 3,
'REGEXP' => 3, 'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3,
'SIGNAL' => 3, 'STORED' => 3, 'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'TRIGGER' => 3, 'VARYING' => 3, 'VIRTUAL' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3, 'ENCLOSED' => 3,
'MAXVALUE' => 3, 'MODIFIES' => 3, 'OPTIMIZE' => 3, 'RESIGNAL' => 3, 'RESTRICT' => 3,
'SPECIFIC' => 3, 'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3, 'UNSIGNED' => 3,
'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'GENERATED' => 3, 'INTERSECT' => 3,
'MIDDLEINT' => 3, 'PARTITION' => 3, 'PRECISION' => 3, 'PROCEDURE' => 3,
'RECURSIVE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ACCESSIBLE' => 3, 'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3,
'DAY_SECOND' => 3, 'OPTIONALLY' => 3, 'READ_WRITE' => 3, 'REFERENCES' => 3,
'SQLWARNING' => 3, 'TERMINATED' => 3, 'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'MASTER_BIND' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3, 'STRAIGHT_JOIN' => 3,
'IO_AFTER_GTIDS' => 3, 'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3, 'IO_BEFORE_GTIDS' => 3, 'OPTIMIZER_COSTS' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'MASTER_SSL_VERIFY_SERVER_CERT' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'LOAD DATA' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7,
'ON UPDATE' => 7, 'UNION ALL' => 7,
'CROSS JOIN' => 7, 'ESCAPED BY' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7,
'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'ENCLOSED BY' => 7, 'LINEAR HASH' => 7, 'STARTING BY' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'NATURAL JOIN' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7, 'TERMINATED BY' => 7,
'DATA DIRECTORY' => 7, 'UNION DISTINCT' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'FULL OUTER JOIN' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'NATURAL LEFT JOIN' => 7, 'START TRANSACTION' => 7,
'LOCK IN SHARE MODE' => 7, 'NATURAL RIGHT JOIN' => 7, 'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'NATURAL LEFT OUTER JOIN' => 7,
'NATURAL RIGHT OUTER JOIN' => 7, 'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'GEOMETRY' => 9, 'MULTISET' => 9,
'MULTILINEPOINT' => 9,
'MULTILINEPOLYGON' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11, 'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'SPATIAL' => 19,
'FULLTEXT' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SHA' => 33, 'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SHA2' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'ST_X' => 33,
'ST_Y' => 33, 'TRIM' => 33, 'USER' => 33, 'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'FIELD' => 33, 'FLOOR' => 33, 'INSTR' => 33, 'LCASE' => 33,
'LEAST' => 33, 'LOG10' => 33, 'LOWER' => 33, 'LTRIM' => 33, 'MONTH' => 33,
'POWER' => 33, 'QUOTE' => 33, 'ROUND' => 33, 'RTRIM' => 33, 'SLEEP' => 33,
'SPACE' => 33, 'UCASE' => 33, 'UNHEX' => 33, 'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'BUFFER' => 33, 'CONCAT' => 33, 'DECODE' => 33,
'ENCODE' => 33, 'EQUALS' => 33, 'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33,
'LENGTH' => 33, 'LOCATE' => 33, 'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33,
'SECOND' => 33, 'STDDEV' => 33, 'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'IS_IPV4' => 33, 'IS_IPV6' => 33, 'QUARTER' => 33, 'RADIANS' => 33,
'REVERSE' => 33, 'SOUNDEX' => 33, 'ST_AREA' => 33, 'ST_SRID' => 33, 'SUBDATE' => 33,
'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33, 'TO_DAYS' => 33, 'VAR_POP' => 33,
'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33, 'CONTAINS' => 33,
'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33, 'DISJOINT' => 33, 'DISTANCE' => 33,
'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33, 'GREATEST' => 33, 'ISCLOSED' => 33,
'ISSIMPLE' => 33, 'JSON_SET' => 33, 'MAKEDATE' => 33, 'MAKETIME' => 33, 'MAKE_SET' => 33,
'MBREQUAL' => 33, 'OVERLAPS' => 33, 'PASSWORD' => 33, 'POSITION' => 33, 'ST_ASWKB' => 33,
'ST_ASWKT' => 33, 'ST_UNION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33, 'VARIANCE' => 33,
'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'ANY_VALUE' => 33, 'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33,
'CONCAT_WS' => 33, 'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33,
'FROM_DAYS' => 33, 'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33,
'JSON_KEYS' => 33, 'JSON_TYPE' => 33, 'LOAD_FILE' => 33, 'MBRCOVERS' => 33,
'MBREQUALS' => 33, 'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33,
'ROW_COUNT' => 33, 'ST_ASTEXT' => 33, 'ST_BUFFER' => 33, 'ST_EQUALS' => 33,
'ST_LENGTH' => 33, 'ST_POINTN' => 33, 'ST_WITHIN' => 33, 'SUBSTRING' => 33,
'TO_BASE64' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'CONVEXHULL' => 33, 'DAYOFMONTH' => 33,
'EXPORT_SET' => 33, 'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INET6_ATON' => 33,
'INET6_NTOA' => 33, 'INTERSECTS' => 33, 'JSON_ARRAY' => 33, 'JSON_DEPTH' => 33,
'JSON_MERGE' => 33, 'JSON_QUOTE' => 33, 'JSON_VALID' => 33, 'MBRTOUCHES' => 33,
'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33,
'STDDEV_POP' => 33, 'ST_CROSSES' => 33, 'ST_GEOHASH' => 33, 'ST_ISEMPTY' => 33,
'ST_ISVALID' => 33, 'ST_TOUCHES' => 33, 'TO_SECONDS' => 33, 'UNCOMPRESS' => 33,
'UUID_SHORT' => 33, 'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'FROM_BASE64' => 33,
'GEOMFROMWKB' => 33, 'GTID_SUBSET' => 33, 'JSON_INSERT' => 33, 'JSON_LENGTH' => 33,
'JSON_OBJECT' => 33, 'JSON_PRETTY' => 33, 'JSON_REMOVE' => 33, 'JSON_SEARCH' => 33,
'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33, 'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33,
'MICROSECOND' => 33, 'PERIOD_DIFF' => 33, 'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33,
'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33, 'ST_ASBINARY' => 33, 'ST_CENTROID' => 33,
'ST_CONTAINS' => 33, 'ST_DISJOINT' => 33, 'ST_DISTANCE' => 33, 'ST_ENDPOINT' => 33,
'ST_ENVELOPE' => 33, 'ST_ISCLOSED' => 33, 'ST_ISSIMPLE' => 33, 'ST_OVERLAPS' => 33,
'ST_SIMPLIFY' => 33, 'ST_VALIDATE' => 33, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'EXTRACTVALUE' => 33, 'GEOMETRYTYPE' => 33,
'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33, 'IS_FREE_LOCK' => 33, 'IS_USED_LOCK' => 33,
'JSON_EXTRACT' => 33, 'JSON_REPLACE' => 33, 'JSON_UNQUOTE' => 33, 'LINEFROMTEXT' => 33,
'MBRCOVEREDBY' => 33, 'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33, 'POLYFROMTEXT' => 33,
'RANDOM_BYTES' => 33, 'RELEASE_LOCK' => 33, 'SESSION_USER' => 33, 'ST_ASGEOJSON' => 33,
'ST_DIMENSION' => 33, 'ST_GEOMETRYN' => 33, 'ST_NUMPOINTS' => 33, 'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'GTID_SUBTRACT' => 33, 'INTERIORRINGN' => 33,
'JSON_CONTAINS' => 33, 'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33, 'ST_CONVEXHULL' => 33,
'ST_DIFFERENCE' => 33, 'ST_INTERSECTS' => 33, 'ST_STARTPOINT' => 33, 'TIMESTAMPDIFF' => 33,
'WEIGHT_STRING' => 33,
'IS_IPV4_COMPAT' => 33, 'IS_IPV4_MAPPED' => 33, 'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33,
'POLYGONFROMWKB' => 33, 'ST_GEOMFROMWKB' => 33, 'ST_LINEFROMWKB' => 33, 'ST_POLYFROMWKB' => 33,
'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'POLYGONFROMTEXT' => 33, 'ST_EXTERIORRING' => 33,
'ST_GEOMETRYTYPE' => 33, 'ST_GEOMFROMTEXT' => 33, 'ST_INTERSECTION' => 33, 'ST_LINEFROMTEXT' => 33,
'ST_MAKEENVELOPE' => 33, 'ST_MLINEFROMWKB' => 33, 'ST_MPOLYFROMWKB' => 33, 'ST_POINTFROMWKB' => 33,
'ST_POLYFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'JSON_MERGE_PATCH' => 33, 'NUMINTERIORRINGS' => 33, 'ST_INTERIORRINGN' => 33,
'ST_MLINEFROMTEXT' => 33, 'ST_MPOINTFROMWKB' => 33, 'ST_MPOLYFROMTEXT' => 33,
'ST_NUMGEOMETRIES' => 33, 'ST_POINTFROMTEXT' => 33, 'ST_SYMDIFFERENCE' => 33,
'JSON_ARRAY_APPEND' => 33, 'JSON_ARRAY_INSERT' => 33, 'JSON_STORAGE_FREE' => 33,
'JSON_STORAGE_SIZE' => 33, 'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'RELEASE_ALL_LOCKS' => 33, 'ST_LATFROMGEOHASH' => 33, 'ST_MPOINTFROMTEXT' => 33,
'ST_POLYGONFROMWKB' => 33,
'JSON_CONTAINS_PATH' => 33, 'MULTIPOINTFROMTEXT' => 33, 'ST_BUFFER_STRATEGY' => 33,
'ST_DISTANCE_SPHERE' => 33, 'ST_GEOMCOLLFROMTXT' => 33, 'ST_GEOMCOLLFROMWKB' => 33,
'ST_GEOMFROMGEOJSON' => 33, 'ST_LONGFROMGEOHASH' => 33, 'ST_POLYGONFROMTEXT' => 33,
'JSON_MERGE_PRESERVE' => 33, 'MULTIPOLYGONFROMWKB' => 33, 'ST_GEOMCOLLFROMTEXT' => 33,
'ST_GEOMETRYFROMTEXT' => 33, 'ST_NUMINTERIORRINGS' => 33, 'ST_POINTFROMGEOHASH' => 33,
'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33, 'ST_LINESTRINGFROMWKB' => 33, 'ST_MULTIPOINTFROMWKB' => 33,
'ST_MULTIPOINTFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33, 'ST_MULTIPOLYGONFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33, 'ST_MULTIPOLYGONFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33, 'ST_MULTILINESTRINGFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33, 'ST_MULTILINESTRINGFROMTEXT' => 33, 'VALIDATE_PASSWORD_STRENGTH' => 33,
'WAIT_FOR_EXECUTED_GTID_SET' => 33,
'ST_GEOMETRYCOLLECTIONFROMWKB' => 33,
'ST_GEOMETRYCOLLECTIONFROMTEXT' => 33,
'WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'EXISTS' => 35, 'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'POINT' => 41,
'POLYGON' => 41,
'TIMESTAMP' => 41,
'LINESTRING' => 41,
'MULTILINESTRING' => 41,
'GEOMETRYCOLLECTION' => 41,
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
}
@@ -1,347 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Contexts;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Token;
/**
* Context for MariaDB 10.5.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://mariadb.com/kb/en/reserved-words/
*/
class ContextMariaDb100500 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_RESERVED Token::FLAG_KEYWORD_COMPOSED
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
*/
public static $KEYWORDS = [
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1,
'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1, 'MODE' => 1,
'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'ONLY' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PORT' => 1, 'PREV' => 1, 'SLOW' => 1, 'SOME' => 1, 'STOP' => 1, 'THAN' => 1,
'TYPE' => 1, 'VIEW' => 1, 'WAIT' => 1, 'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'ERROR' => 1, 'EVENT' => 1, 'EVERY' => 1,
'FIRST' => 1, 'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'NEVER' => 1, 'OWNER' => 1, 'PHASE' => 1,
'PROXY' => 1, 'QUERY' => 1, 'QUICK' => 1, 'RELAY' => 1, 'RESET' => 1,
'RTREE' => 1, 'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1,
'SWAPS' => 1, 'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'ALWAYS' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1,
'CLIENT' => 1, 'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1,
'ESCAPE' => 1, 'EVENTS' => 1, 'EXPIRE' => 1, 'EXPORT' => 1, 'FAULTS' => 1,
'FIELDS' => 1, 'FILTER' => 1, 'GLOBAL' => 1, 'GRANTS' => 1, 'IMPORT' => 1,
'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1, 'MEDIUM' => 1, 'MEMORY' => 1,
'MODIFY' => 1, 'NUMBER' => 1, 'OFFSET' => 1, 'PARSER' => 1, 'PLUGIN' => 1,
'RELOAD' => 1, 'REMOVE' => 1, 'REPAIR' => 1, 'RESUME' => 1, 'ROLLUP' => 1,
'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1, 'SOCKET' => 1, 'SONAME' => 1,
'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1, 'STATUS' => 1, 'STRING' => 1,
'TABLES' => 1,
'ACCOUNT' => 1, 'ANALYSE' => 1, 'CHANGED' => 1, 'CHANNEL' => 1, 'COLUMNS' => 1,
'COMMENT' => 1, 'COMPACT' => 1, 'CONTEXT' => 1, 'CURRENT' => 1, 'DEFINER' => 1,
'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1, 'EXECUTE' => 1,
'FOLLOWS' => 1, 'GENERAL' => 1, 'HANDLER' => 1, 'INDEXES' => 1, 'INSTALL' => 1,
'INVOKER' => 1, 'LOGFILE' => 1, 'MIGRATE' => 1, 'NO_WAIT' => 1, 'OPTIONS' => 1,
'PARTIAL' => 1, 'PLUGINS' => 1, 'PREPARE' => 1, 'PROFILE' => 1, 'REBUILD' => 1,
'RECOVER' => 1, 'RESTORE' => 1, 'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1,
'STACKED' => 1, 'STORAGE' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'WITHOUT' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1, 'EXCHANGE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'LANGUAGE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1,
'MIN_ROWS' => 1, 'NATIONAL' => 1, 'NVARCHAR' => 1, 'PRECEDES' => 1, 'PRESERVE' => 1,
'PROFILES' => 1, 'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1, 'SCHEDULE' => 1,
'SECURITY' => 1, 'SEQUENCE' => 1, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1, 'SWITCHES' => 1,
'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'INVISIBLE' => 1, 'IO_THREAD' => 1,
'ISOLATION' => 1, 'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'READ_ONLY' => 1,
'REDUNDANT' => 1, 'SAVEPOINT' => 1, 'SQL_CACHE' => 1, 'TEMPORARY' => 1,
'TEMPTABLE' => 1, 'UNDEFINED' => 1, 'UNINSTALL' => 1, 'VARIABLES' => 1,
'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PLUGIN_DIR' => 1,
'PRIVILEGES' => 1, 'REORGANIZE' => 1, 'REPEATABLE' => 1, 'ROW_FORMAT' => 1,
'SQL_THREAD' => 1, 'TABLESPACE' => 1, 'TABLE_NAME' => 1, 'VALIDATION' => 1,
'COLUMN_NAME' => 1, 'COMPRESSION' => 1, 'CURSOR_NAME' => 1, 'DIAGNOSTICS' => 1,
'EXTENT_SIZE' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1,
'MYSQL_ERRNO' => 1, 'NONBLOCKING' => 1, 'PROCESSLIST' => 1, 'REPLICATION' => 1,
'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1, 'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'DEFAULT_AUTH' => 1, 'DES_KEY_FILE' => 1,
'INITIAL_SIZE' => 1, 'MASTER_DELAY' => 1, 'MESSAGE_TEXT' => 1, 'PARTITIONING' => 1,
'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1, 'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1,
'SQL_TSI_WEEK' => 1, 'SQL_TSI_YEAR' => 1, 'SUBPARTITION' => 1,
'COLUMN_FORMAT' => 1, 'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1, 'RELAY_LOG_POS' => 1,
'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1, 'MASTER_LOG_POS' => 1,
'MASTER_SSL_CRL' => 1, 'MASTER_SSL_KEY' => 1, 'RELAY_LOG_FILE' => 1, 'SQL_TSI_MINUTE' => 1,
'SQL_TSI_SECOND' => 1, 'TABLE_CHECKSUM' => 1, 'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'CONSTRAINT_NAME' => 1, 'DELAY_KEY_WRITE' => 1, 'FILE_BLOCK_SIZE' => 1,
'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1, 'PARSE_GCOL_EXPR' => 1,
'REPLICATE_DO_DB' => 1, 'SQL_AFTER_GTIDS' => 1, 'SQL_TSI_QUARTER' => 1, 'SUBCLASS_ORIGIN' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'SQL_BEFORE_GTIDS' => 1,
'STATS_PERSISTENT' => 1, 'UNDO_BUFFER_SIZE' => 1,
'CONSTRAINT_SCHEMA' => 1, 'GROUP_REPLICATION' => 1, 'IGNORE_SERVER_IDS' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'RETURNED_SQLSTATE' => 1,
'SQL_BUFFER_RESULT' => 1, 'STATS_AUTO_RECALC' => 1,
'CONSTRAINT_CATALOG' => 1, 'MASTER_RETRY_COUNT' => 1, 'MASTER_SSL_CRLPATH' => 1,
'MAX_STATEMENT_TIME' => 1, 'REPLICATE_DO_TABLE' => 1, 'SQL_AFTER_MTS_GAPS' => 1,
'STATS_SAMPLE_PAGES' => 1,
'REPLICATE_IGNORE_DB' => 1,
'MASTER_AUTO_POSITION' => 1, 'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1, 'REPLICATE_REWRITE_DB' => 1,
'REPLICATE_IGNORE_TABLE' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1, 'REPLICATE_WILD_DO_TABLE' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'REPLICATE_WILD_IGNORE_TABLE' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'GET' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3,
'USE' => 3, 'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'OVER' => 3, 'READ' => 3, 'ROWS' => 3, 'SHOW' => 3, 'THEN' => 3,
'TRUE' => 3, 'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'RANGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3,
'UNION' => 3, 'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3,
'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXCEPT' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'LINEAR' => 3, 'OPTION' => 3,
'REGEXP' => 3, 'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3,
'SIGNAL' => 3, 'STORED' => 3, 'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'TRIGGER' => 3, 'VARYING' => 3, 'VIRTUAL' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3, 'ENCLOSED' => 3,
'MAXVALUE' => 3, 'MODIFIES' => 3, 'OPTIMIZE' => 3, 'RESIGNAL' => 3, 'RESTRICT' => 3,
'SPECIFIC' => 3, 'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3, 'UNSIGNED' => 3,
'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'GENERATED' => 3, 'INTERSECT' => 3,
'MIDDLEINT' => 3, 'PARTITION' => 3, 'PRECISION' => 3, 'PROCEDURE' => 3,
'RECURSIVE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ACCESSIBLE' => 3, 'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3,
'DAY_SECOND' => 3, 'OPTIONALLY' => 3, 'READ_WRITE' => 3, 'REFERENCES' => 3,
'SQLWARNING' => 3, 'TERMINATED' => 3, 'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'MASTER_BIND' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3, 'STRAIGHT_JOIN' => 3,
'IO_AFTER_GTIDS' => 3, 'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3, 'IO_BEFORE_GTIDS' => 3, 'OPTIMIZER_COSTS' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'MASTER_SSL_VERIFY_SERVER_CERT' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'LOAD DATA' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7,
'ON UPDATE' => 7, 'UNION ALL' => 7,
'CROSS JOIN' => 7, 'ESCAPED BY' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7,
'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'ENCLOSED BY' => 7, 'LINEAR HASH' => 7, 'STARTING BY' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'NATURAL JOIN' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7, 'TERMINATED BY' => 7,
'DATA DIRECTORY' => 7, 'UNION DISTINCT' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'FULL OUTER JOIN' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'NATURAL LEFT JOIN' => 7, 'START TRANSACTION' => 7,
'LOCK IN SHARE MODE' => 7, 'NATURAL RIGHT JOIN' => 7, 'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'NATURAL LEFT OUTER JOIN' => 7,
'NATURAL RIGHT OUTER JOIN' => 7, 'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'GEOMETRY' => 9, 'MULTISET' => 9,
'MULTILINEPOINT' => 9,
'MULTILINEPOLYGON' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11, 'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'SPATIAL' => 19,
'FULLTEXT' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SHA' => 33, 'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SHA2' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'ST_X' => 33,
'ST_Y' => 33, 'TRIM' => 33, 'USER' => 33, 'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'FIELD' => 33, 'FLOOR' => 33, 'INSTR' => 33, 'LCASE' => 33,
'LEAST' => 33, 'LOG10' => 33, 'LOWER' => 33, 'LTRIM' => 33, 'MONTH' => 33,
'POWER' => 33, 'QUOTE' => 33, 'ROUND' => 33, 'RTRIM' => 33, 'SLEEP' => 33,
'SPACE' => 33, 'UCASE' => 33, 'UNHEX' => 33, 'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'BUFFER' => 33, 'CONCAT' => 33, 'DECODE' => 33,
'ENCODE' => 33, 'EQUALS' => 33, 'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33,
'LENGTH' => 33, 'LOCATE' => 33, 'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33,
'SECOND' => 33, 'STDDEV' => 33, 'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'IS_IPV4' => 33, 'IS_IPV6' => 33, 'QUARTER' => 33, 'RADIANS' => 33,
'REVERSE' => 33, 'SOUNDEX' => 33, 'ST_AREA' => 33, 'ST_SRID' => 33, 'SUBDATE' => 33,
'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33, 'TO_DAYS' => 33, 'VAR_POP' => 33,
'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33, 'CONTAINS' => 33,
'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33, 'DISJOINT' => 33, 'DISTANCE' => 33,
'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33, 'GREATEST' => 33, 'ISCLOSED' => 33,
'ISSIMPLE' => 33, 'JSON_SET' => 33, 'MAKEDATE' => 33, 'MAKETIME' => 33, 'MAKE_SET' => 33,
'MBREQUAL' => 33, 'OVERLAPS' => 33, 'PASSWORD' => 33, 'POSITION' => 33, 'ST_ASWKB' => 33,
'ST_ASWKT' => 33, 'ST_UNION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33, 'VARIANCE' => 33,
'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'ANY_VALUE' => 33, 'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33,
'CONCAT_WS' => 33, 'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33,
'FROM_DAYS' => 33, 'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33,
'JSON_KEYS' => 33, 'JSON_TYPE' => 33, 'LOAD_FILE' => 33, 'MBRCOVERS' => 33,
'MBREQUALS' => 33, 'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33,
'ROW_COUNT' => 33, 'ST_ASTEXT' => 33, 'ST_BUFFER' => 33, 'ST_EQUALS' => 33,
'ST_LENGTH' => 33, 'ST_POINTN' => 33, 'ST_WITHIN' => 33, 'SUBSTRING' => 33,
'TO_BASE64' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'CONVEXHULL' => 33, 'DAYOFMONTH' => 33,
'EXPORT_SET' => 33, 'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INET6_ATON' => 33,
'INET6_NTOA' => 33, 'INTERSECTS' => 33, 'JSON_ARRAY' => 33, 'JSON_DEPTH' => 33,
'JSON_MERGE' => 33, 'JSON_QUOTE' => 33, 'JSON_VALID' => 33, 'MBRTOUCHES' => 33,
'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33,
'STDDEV_POP' => 33, 'ST_CROSSES' => 33, 'ST_GEOHASH' => 33, 'ST_ISEMPTY' => 33,
'ST_ISVALID' => 33, 'ST_TOUCHES' => 33, 'TO_SECONDS' => 33, 'UNCOMPRESS' => 33,
'UUID_SHORT' => 33, 'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'FROM_BASE64' => 33,
'GEOMFROMWKB' => 33, 'GTID_SUBSET' => 33, 'JSON_INSERT' => 33, 'JSON_LENGTH' => 33,
'JSON_OBJECT' => 33, 'JSON_PRETTY' => 33, 'JSON_REMOVE' => 33, 'JSON_SEARCH' => 33,
'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33, 'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33,
'MICROSECOND' => 33, 'PERIOD_DIFF' => 33, 'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33,
'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33, 'ST_ASBINARY' => 33, 'ST_CENTROID' => 33,
'ST_CONTAINS' => 33, 'ST_DISJOINT' => 33, 'ST_DISTANCE' => 33, 'ST_ENDPOINT' => 33,
'ST_ENVELOPE' => 33, 'ST_ISCLOSED' => 33, 'ST_ISSIMPLE' => 33, 'ST_OVERLAPS' => 33,
'ST_SIMPLIFY' => 33, 'ST_VALIDATE' => 33, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'EXTRACTVALUE' => 33, 'GEOMETRYTYPE' => 33,
'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33, 'IS_FREE_LOCK' => 33, 'IS_USED_LOCK' => 33,
'JSON_EXTRACT' => 33, 'JSON_REPLACE' => 33, 'JSON_UNQUOTE' => 33, 'LINEFROMTEXT' => 33,
'MBRCOVEREDBY' => 33, 'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33, 'POLYFROMTEXT' => 33,
'RANDOM_BYTES' => 33, 'RELEASE_LOCK' => 33, 'SESSION_USER' => 33, 'ST_ASGEOJSON' => 33,
'ST_DIMENSION' => 33, 'ST_GEOMETRYN' => 33, 'ST_NUMPOINTS' => 33, 'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'GTID_SUBTRACT' => 33, 'INTERIORRINGN' => 33,
'JSON_CONTAINS' => 33, 'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33, 'ST_CONVEXHULL' => 33,
'ST_DIFFERENCE' => 33, 'ST_INTERSECTS' => 33, 'ST_STARTPOINT' => 33, 'TIMESTAMPDIFF' => 33,
'WEIGHT_STRING' => 33,
'IS_IPV4_COMPAT' => 33, 'IS_IPV4_MAPPED' => 33, 'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33,
'POLYGONFROMWKB' => 33, 'ST_GEOMFROMWKB' => 33, 'ST_LINEFROMWKB' => 33, 'ST_POLYFROMWKB' => 33,
'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'POLYGONFROMTEXT' => 33, 'ST_EXTERIORRING' => 33,
'ST_GEOMETRYTYPE' => 33, 'ST_GEOMFROMTEXT' => 33, 'ST_INTERSECTION' => 33, 'ST_LINEFROMTEXT' => 33,
'ST_MAKEENVELOPE' => 33, 'ST_MLINEFROMWKB' => 33, 'ST_MPOLYFROMWKB' => 33, 'ST_POINTFROMWKB' => 33,
'ST_POLYFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'JSON_MERGE_PATCH' => 33, 'NUMINTERIORRINGS' => 33, 'ST_INTERIORRINGN' => 33,
'ST_MLINEFROMTEXT' => 33, 'ST_MPOINTFROMWKB' => 33, 'ST_MPOLYFROMTEXT' => 33,
'ST_NUMGEOMETRIES' => 33, 'ST_POINTFROMTEXT' => 33, 'ST_SYMDIFFERENCE' => 33,
'JSON_ARRAY_APPEND' => 33, 'JSON_ARRAY_INSERT' => 33, 'JSON_STORAGE_FREE' => 33,
'JSON_STORAGE_SIZE' => 33, 'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'RELEASE_ALL_LOCKS' => 33, 'ST_LATFROMGEOHASH' => 33, 'ST_MPOINTFROMTEXT' => 33,
'ST_POLYGONFROMWKB' => 33,
'JSON_CONTAINS_PATH' => 33, 'MULTIPOINTFROMTEXT' => 33, 'ST_BUFFER_STRATEGY' => 33,
'ST_DISTANCE_SPHERE' => 33, 'ST_GEOMCOLLFROMTXT' => 33, 'ST_GEOMCOLLFROMWKB' => 33,
'ST_GEOMFROMGEOJSON' => 33, 'ST_LONGFROMGEOHASH' => 33, 'ST_POLYGONFROMTEXT' => 33,
'JSON_MERGE_PRESERVE' => 33, 'MULTIPOLYGONFROMWKB' => 33, 'ST_GEOMCOLLFROMTEXT' => 33,
'ST_GEOMETRYFROMTEXT' => 33, 'ST_NUMINTERIORRINGS' => 33, 'ST_POINTFROMGEOHASH' => 33,
'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33, 'ST_LINESTRINGFROMWKB' => 33, 'ST_MULTIPOINTFROMWKB' => 33,
'ST_MULTIPOINTFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33, 'ST_MULTIPOLYGONFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33, 'ST_MULTIPOLYGONFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33, 'ST_MULTILINESTRINGFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33, 'ST_MULTILINESTRINGFROMTEXT' => 33, 'VALIDATE_PASSWORD_STRENGTH' => 33,
'WAIT_FOR_EXECUTED_GTID_SET' => 33,
'ST_GEOMETRYCOLLECTIONFROMWKB' => 33,
'ST_GEOMETRYCOLLECTIONFROMTEXT' => 33,
'WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'EXISTS' => 35, 'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'POINT' => 41,
'POLYGON' => 41,
'TIMESTAMP' => 41,
'LINESTRING' => 41,
'MULTILINESTRING' => 41,
'GEOMETRYCOLLECTION' => 41,
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
}
@@ -1,347 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Contexts;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Token;
/**
* Context for MariaDB 10.6.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://mariadb.com/kb/en/reserved-words/
*/
class ContextMariaDb100600 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_RESERVED Token::FLAG_KEYWORD_COMPOSED
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
*/
public static $KEYWORDS = [
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1,
'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1, 'MODE' => 1,
'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'ONLY' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PORT' => 1, 'PREV' => 1, 'SLOW' => 1, 'SOME' => 1, 'STOP' => 1, 'THAN' => 1,
'TYPE' => 1, 'VIEW' => 1, 'WAIT' => 1, 'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'ERROR' => 1, 'EVENT' => 1, 'EVERY' => 1,
'FIRST' => 1, 'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'NEVER' => 1, 'OWNER' => 1, 'PHASE' => 1,
'PROXY' => 1, 'QUERY' => 1, 'QUICK' => 1, 'RELAY' => 1, 'RESET' => 1,
'RTREE' => 1, 'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1,
'SWAPS' => 1, 'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'ALWAYS' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1,
'CLIENT' => 1, 'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1,
'ESCAPE' => 1, 'EVENTS' => 1, 'EXPIRE' => 1, 'EXPORT' => 1, 'FAULTS' => 1,
'FIELDS' => 1, 'FILTER' => 1, 'GLOBAL' => 1, 'GRANTS' => 1, 'IMPORT' => 1,
'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1, 'MEDIUM' => 1, 'MEMORY' => 1,
'MODIFY' => 1, 'NUMBER' => 1, 'OFFSET' => 1, 'PARSER' => 1, 'PLUGIN' => 1,
'RELOAD' => 1, 'REMOVE' => 1, 'REPAIR' => 1, 'RESUME' => 1, 'ROLLUP' => 1,
'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1, 'SOCKET' => 1, 'SONAME' => 1,
'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1, 'STATUS' => 1, 'STRING' => 1,
'TABLES' => 1,
'ACCOUNT' => 1, 'ANALYSE' => 1, 'CHANGED' => 1, 'CHANNEL' => 1, 'COLUMNS' => 1,
'COMMENT' => 1, 'COMPACT' => 1, 'CONTEXT' => 1, 'CURRENT' => 1, 'DEFINER' => 1,
'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1, 'EXECUTE' => 1,
'FOLLOWS' => 1, 'GENERAL' => 1, 'HANDLER' => 1, 'INDEXES' => 1, 'INSTALL' => 1,
'INVOKER' => 1, 'LOGFILE' => 1, 'MIGRATE' => 1, 'NO_WAIT' => 1, 'OPTIONS' => 1,
'PARTIAL' => 1, 'PLUGINS' => 1, 'PREPARE' => 1, 'PROFILE' => 1, 'REBUILD' => 1,
'RECOVER' => 1, 'RESTORE' => 1, 'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1,
'STACKED' => 1, 'STORAGE' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'WITHOUT' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1, 'EXCHANGE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'LANGUAGE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1,
'MIN_ROWS' => 1, 'NATIONAL' => 1, 'NVARCHAR' => 1, 'PRECEDES' => 1, 'PRESERVE' => 1,
'PROFILES' => 1, 'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1, 'SCHEDULE' => 1,
'SECURITY' => 1, 'SEQUENCE' => 1, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1, 'SWITCHES' => 1,
'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'INVISIBLE' => 1, 'IO_THREAD' => 1,
'ISOLATION' => 1, 'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'READ_ONLY' => 1,
'REDUNDANT' => 1, 'SAVEPOINT' => 1, 'SQL_CACHE' => 1, 'TEMPORARY' => 1,
'TEMPTABLE' => 1, 'UNDEFINED' => 1, 'UNINSTALL' => 1, 'VARIABLES' => 1,
'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PLUGIN_DIR' => 1,
'PRIVILEGES' => 1, 'REORGANIZE' => 1, 'REPEATABLE' => 1, 'ROW_FORMAT' => 1,
'SQL_THREAD' => 1, 'TABLESPACE' => 1, 'TABLE_NAME' => 1, 'VALIDATION' => 1,
'COLUMN_NAME' => 1, 'COMPRESSION' => 1, 'CURSOR_NAME' => 1, 'DIAGNOSTICS' => 1,
'EXTENT_SIZE' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1,
'MYSQL_ERRNO' => 1, 'NONBLOCKING' => 1, 'PROCESSLIST' => 1, 'REPLICATION' => 1,
'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1, 'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'DEFAULT_AUTH' => 1, 'DES_KEY_FILE' => 1,
'INITIAL_SIZE' => 1, 'MASTER_DELAY' => 1, 'MESSAGE_TEXT' => 1, 'PARTITIONING' => 1,
'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1, 'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1,
'SQL_TSI_WEEK' => 1, 'SQL_TSI_YEAR' => 1, 'SUBPARTITION' => 1,
'COLUMN_FORMAT' => 1, 'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1, 'RELAY_LOG_POS' => 1,
'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1, 'MASTER_LOG_POS' => 1,
'MASTER_SSL_CRL' => 1, 'MASTER_SSL_KEY' => 1, 'RELAY_LOG_FILE' => 1, 'SQL_TSI_MINUTE' => 1,
'SQL_TSI_SECOND' => 1, 'TABLE_CHECKSUM' => 1, 'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'CONSTRAINT_NAME' => 1, 'DELAY_KEY_WRITE' => 1, 'FILE_BLOCK_SIZE' => 1,
'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1, 'PARSE_GCOL_EXPR' => 1,
'REPLICATE_DO_DB' => 1, 'SQL_AFTER_GTIDS' => 1, 'SQL_TSI_QUARTER' => 1, 'SUBCLASS_ORIGIN' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'SQL_BEFORE_GTIDS' => 1,
'STATS_PERSISTENT' => 1, 'UNDO_BUFFER_SIZE' => 1,
'CONSTRAINT_SCHEMA' => 1, 'GROUP_REPLICATION' => 1, 'IGNORE_SERVER_IDS' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'RETURNED_SQLSTATE' => 1,
'SQL_BUFFER_RESULT' => 1, 'STATS_AUTO_RECALC' => 1,
'CONSTRAINT_CATALOG' => 1, 'MASTER_RETRY_COUNT' => 1, 'MASTER_SSL_CRLPATH' => 1,
'MAX_STATEMENT_TIME' => 1, 'REPLICATE_DO_TABLE' => 1, 'SQL_AFTER_MTS_GAPS' => 1,
'STATS_SAMPLE_PAGES' => 1,
'REPLICATE_IGNORE_DB' => 1,
'MASTER_AUTO_POSITION' => 1, 'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1, 'REPLICATE_REWRITE_DB' => 1,
'REPLICATE_IGNORE_TABLE' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1, 'REPLICATE_WILD_DO_TABLE' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'REPLICATE_WILD_IGNORE_TABLE' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'GET' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3,
'USE' => 3, 'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'OVER' => 3, 'READ' => 3, 'ROWS' => 3, 'SHOW' => 3, 'THEN' => 3,
'TRUE' => 3, 'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'RANGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3,
'UNION' => 3, 'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3,
'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXCEPT' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'LINEAR' => 3, 'OPTION' => 3,
'REGEXP' => 3, 'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3,
'SIGNAL' => 3, 'STORED' => 3, 'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'TRIGGER' => 3, 'VARYING' => 3, 'VIRTUAL' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3, 'ENCLOSED' => 3,
'MAXVALUE' => 3, 'MODIFIES' => 3, 'OPTIMIZE' => 3, 'RESIGNAL' => 3, 'RESTRICT' => 3,
'SPECIFIC' => 3, 'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3, 'UNSIGNED' => 3,
'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'GENERATED' => 3, 'INTERSECT' => 3,
'MIDDLEINT' => 3, 'PARTITION' => 3, 'PRECISION' => 3, 'PROCEDURE' => 3,
'RECURSIVE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ACCESSIBLE' => 3, 'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3,
'DAY_SECOND' => 3, 'OPTIONALLY' => 3, 'READ_WRITE' => 3, 'REFERENCES' => 3,
'SQLWARNING' => 3, 'TERMINATED' => 3, 'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'MASTER_BIND' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3, 'STRAIGHT_JOIN' => 3,
'IO_AFTER_GTIDS' => 3, 'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3, 'IO_BEFORE_GTIDS' => 3, 'OPTIMIZER_COSTS' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'MASTER_SSL_VERIFY_SERVER_CERT' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'LOAD DATA' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7,
'ON UPDATE' => 7, 'UNION ALL' => 7,
'CROSS JOIN' => 7, 'ESCAPED BY' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7,
'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'ENCLOSED BY' => 7, 'LINEAR HASH' => 7, 'STARTING BY' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'NATURAL JOIN' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7, 'TERMINATED BY' => 7,
'DATA DIRECTORY' => 7, 'UNION DISTINCT' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'FULL OUTER JOIN' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'NATURAL LEFT JOIN' => 7, 'START TRANSACTION' => 7,
'LOCK IN SHARE MODE' => 7, 'NATURAL RIGHT JOIN' => 7, 'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'NATURAL LEFT OUTER JOIN' => 7,
'NATURAL RIGHT OUTER JOIN' => 7, 'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'GEOMETRY' => 9, 'MULTISET' => 9,
'MULTILINEPOINT' => 9,
'MULTILINEPOLYGON' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11, 'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'SPATIAL' => 19,
'FULLTEXT' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SHA' => 33, 'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SHA2' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'ST_X' => 33,
'ST_Y' => 33, 'TRIM' => 33, 'USER' => 33, 'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'FIELD' => 33, 'FLOOR' => 33, 'INSTR' => 33, 'LCASE' => 33,
'LEAST' => 33, 'LOG10' => 33, 'LOWER' => 33, 'LTRIM' => 33, 'MONTH' => 33,
'POWER' => 33, 'QUOTE' => 33, 'ROUND' => 33, 'RTRIM' => 33, 'SLEEP' => 33,
'SPACE' => 33, 'UCASE' => 33, 'UNHEX' => 33, 'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'BUFFER' => 33, 'CONCAT' => 33, 'DECODE' => 33,
'ENCODE' => 33, 'EQUALS' => 33, 'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33,
'LENGTH' => 33, 'LOCATE' => 33, 'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33,
'SECOND' => 33, 'STDDEV' => 33, 'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'IS_IPV4' => 33, 'IS_IPV6' => 33, 'QUARTER' => 33, 'RADIANS' => 33,
'REVERSE' => 33, 'SOUNDEX' => 33, 'ST_AREA' => 33, 'ST_SRID' => 33, 'SUBDATE' => 33,
'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33, 'TO_DAYS' => 33, 'VAR_POP' => 33,
'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33, 'CONTAINS' => 33,
'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33, 'DISJOINT' => 33, 'DISTANCE' => 33,
'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33, 'GREATEST' => 33, 'ISCLOSED' => 33,
'ISSIMPLE' => 33, 'JSON_SET' => 33, 'MAKEDATE' => 33, 'MAKETIME' => 33, 'MAKE_SET' => 33,
'MBREQUAL' => 33, 'OVERLAPS' => 33, 'PASSWORD' => 33, 'POSITION' => 33, 'ST_ASWKB' => 33,
'ST_ASWKT' => 33, 'ST_UNION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33, 'VARIANCE' => 33,
'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'ANY_VALUE' => 33, 'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33,
'CONCAT_WS' => 33, 'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33,
'FROM_DAYS' => 33, 'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33,
'JSON_KEYS' => 33, 'JSON_TYPE' => 33, 'LOAD_FILE' => 33, 'MBRCOVERS' => 33,
'MBREQUALS' => 33, 'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33,
'ROW_COUNT' => 33, 'ST_ASTEXT' => 33, 'ST_BUFFER' => 33, 'ST_EQUALS' => 33,
'ST_LENGTH' => 33, 'ST_POINTN' => 33, 'ST_WITHIN' => 33, 'SUBSTRING' => 33,
'TO_BASE64' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'CONVEXHULL' => 33, 'DAYOFMONTH' => 33,
'EXPORT_SET' => 33, 'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INET6_ATON' => 33,
'INET6_NTOA' => 33, 'INTERSECTS' => 33, 'JSON_ARRAY' => 33, 'JSON_DEPTH' => 33,
'JSON_MERGE' => 33, 'JSON_QUOTE' => 33, 'JSON_VALID' => 33, 'MBRTOUCHES' => 33,
'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33,
'STDDEV_POP' => 33, 'ST_CROSSES' => 33, 'ST_GEOHASH' => 33, 'ST_ISEMPTY' => 33,
'ST_ISVALID' => 33, 'ST_TOUCHES' => 33, 'TO_SECONDS' => 33, 'UNCOMPRESS' => 33,
'UUID_SHORT' => 33, 'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'FROM_BASE64' => 33,
'GEOMFROMWKB' => 33, 'GTID_SUBSET' => 33, 'JSON_INSERT' => 33, 'JSON_LENGTH' => 33,
'JSON_OBJECT' => 33, 'JSON_PRETTY' => 33, 'JSON_REMOVE' => 33, 'JSON_SEARCH' => 33,
'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33, 'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33,
'MICROSECOND' => 33, 'PERIOD_DIFF' => 33, 'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33,
'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33, 'ST_ASBINARY' => 33, 'ST_CENTROID' => 33,
'ST_CONTAINS' => 33, 'ST_DISJOINT' => 33, 'ST_DISTANCE' => 33, 'ST_ENDPOINT' => 33,
'ST_ENVELOPE' => 33, 'ST_ISCLOSED' => 33, 'ST_ISSIMPLE' => 33, 'ST_OVERLAPS' => 33,
'ST_SIMPLIFY' => 33, 'ST_VALIDATE' => 33, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'EXTRACTVALUE' => 33, 'GEOMETRYTYPE' => 33,
'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33, 'IS_FREE_LOCK' => 33, 'IS_USED_LOCK' => 33,
'JSON_EXTRACT' => 33, 'JSON_REPLACE' => 33, 'JSON_UNQUOTE' => 33, 'LINEFROMTEXT' => 33,
'MBRCOVEREDBY' => 33, 'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33, 'POLYFROMTEXT' => 33,
'RANDOM_BYTES' => 33, 'RELEASE_LOCK' => 33, 'SESSION_USER' => 33, 'ST_ASGEOJSON' => 33,
'ST_DIMENSION' => 33, 'ST_GEOMETRYN' => 33, 'ST_NUMPOINTS' => 33, 'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'GTID_SUBTRACT' => 33, 'INTERIORRINGN' => 33,
'JSON_CONTAINS' => 33, 'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33, 'ST_CONVEXHULL' => 33,
'ST_DIFFERENCE' => 33, 'ST_INTERSECTS' => 33, 'ST_STARTPOINT' => 33, 'TIMESTAMPDIFF' => 33,
'WEIGHT_STRING' => 33,
'IS_IPV4_COMPAT' => 33, 'IS_IPV4_MAPPED' => 33, 'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33,
'POLYGONFROMWKB' => 33, 'ST_GEOMFROMWKB' => 33, 'ST_LINEFROMWKB' => 33, 'ST_POLYFROMWKB' => 33,
'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'POLYGONFROMTEXT' => 33, 'ST_EXTERIORRING' => 33,
'ST_GEOMETRYTYPE' => 33, 'ST_GEOMFROMTEXT' => 33, 'ST_INTERSECTION' => 33, 'ST_LINEFROMTEXT' => 33,
'ST_MAKEENVELOPE' => 33, 'ST_MLINEFROMWKB' => 33, 'ST_MPOLYFROMWKB' => 33, 'ST_POINTFROMWKB' => 33,
'ST_POLYFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'JSON_MERGE_PATCH' => 33, 'NUMINTERIORRINGS' => 33, 'ST_INTERIORRINGN' => 33,
'ST_MLINEFROMTEXT' => 33, 'ST_MPOINTFROMWKB' => 33, 'ST_MPOLYFROMTEXT' => 33,
'ST_NUMGEOMETRIES' => 33, 'ST_POINTFROMTEXT' => 33, 'ST_SYMDIFFERENCE' => 33,
'JSON_ARRAY_APPEND' => 33, 'JSON_ARRAY_INSERT' => 33, 'JSON_STORAGE_FREE' => 33,
'JSON_STORAGE_SIZE' => 33, 'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'RELEASE_ALL_LOCKS' => 33, 'ST_LATFROMGEOHASH' => 33, 'ST_MPOINTFROMTEXT' => 33,
'ST_POLYGONFROMWKB' => 33,
'JSON_CONTAINS_PATH' => 33, 'MULTIPOINTFROMTEXT' => 33, 'ST_BUFFER_STRATEGY' => 33,
'ST_DISTANCE_SPHERE' => 33, 'ST_GEOMCOLLFROMTXT' => 33, 'ST_GEOMCOLLFROMWKB' => 33,
'ST_GEOMFROMGEOJSON' => 33, 'ST_LONGFROMGEOHASH' => 33, 'ST_POLYGONFROMTEXT' => 33,
'JSON_MERGE_PRESERVE' => 33, 'MULTIPOLYGONFROMWKB' => 33, 'ST_GEOMCOLLFROMTEXT' => 33,
'ST_GEOMETRYFROMTEXT' => 33, 'ST_NUMINTERIORRINGS' => 33, 'ST_POINTFROMGEOHASH' => 33,
'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33, 'ST_LINESTRINGFROMWKB' => 33, 'ST_MULTIPOINTFROMWKB' => 33,
'ST_MULTIPOINTFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33, 'ST_MULTIPOLYGONFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33, 'ST_MULTIPOLYGONFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33, 'ST_MULTILINESTRINGFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33, 'ST_MULTILINESTRINGFROMTEXT' => 33, 'VALIDATE_PASSWORD_STRENGTH' => 33,
'WAIT_FOR_EXECUTED_GTID_SET' => 33,
'ST_GEOMETRYCOLLECTIONFROMWKB' => 33,
'ST_GEOMETRYCOLLECTIONFROMTEXT' => 33,
'WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'EXISTS' => 35, 'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'POINT' => 41,
'POLYGON' => 41,
'TIMESTAMP' => 41,
'LINESTRING' => 41,
'MULTILINESTRING' => 41,
'GEOMETRYCOLLECTION' => 41,
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MySQL 5.0.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://dev.mysql.com/doc/refman/5.0/en/keywords.html
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MySQL 5.0.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://dev.mysql.com/doc/refman/5.0/en/keywords.html
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50000 extends Context
{
@@ -26,10 +32,9 @@ class ContextMySql50000 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'BDB' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1,
'NEW' => 1, 'ONE' => 1, 'ROW' => 1,
@@ -270,5 +275,5 @@ class ContextMySql50000 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MySQL 5.1.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://dev.mysql.com/doc/refman/5.1/en/keywords.html
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MySQL 5.1.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://dev.mysql.com/doc/refman/5.1/en/keywords.html
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50100 extends Context
{
@@ -26,10 +32,9 @@ class ContextMySql50100 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'BDB' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1,
'NEW' => 1, 'ONE' => 1, 'ROW' => 1,
@@ -290,5 +295,5 @@ class ContextMySql50100 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MySQL 5.5.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://dev.mysql.com/doc/refman/5.5/en/keywords.html
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MySQL 5.5.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://dev.mysql.com/doc/refman/5.5/en/keywords.html
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50500 extends Context
{
@@ -26,10 +32,9 @@ class ContextMySql50500 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1,
@@ -296,5 +301,5 @@ class ContextMySql50500 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MySQL 5.6.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://dev.mysql.com/doc/refman/5.6/en/keywords.html
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MySQL 5.6.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://dev.mysql.com/doc/refman/5.6/en/keywords.html
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50600 extends Context
{
@@ -26,10 +32,9 @@ class ContextMySql50600 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1,
@@ -321,5 +326,5 @@ class ContextMySql50600 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MySQL 5.7.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://dev.mysql.com/doc/refman/5.7/en/keywords.html
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MySQL 5.7.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://dev.mysql.com/doc/refman/5.7/en/keywords.html
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50700 extends Context
{
@@ -26,10 +32,9 @@ class ContextMySql50700 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
@@ -343,5 +348,5 @@ class ContextMySql50700 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
@@ -1,6 +1,13 @@
<?php
declare(strict_types=1);
/**
* Context for MySQL 8.0.
*
* This file was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see https://dev.mysql.com/doc/refman/8.0/en/keywords.html
*/
namespace PhpMyAdmin\SqlParser\Contexts;
@@ -10,10 +17,9 @@ use PhpMyAdmin\SqlParser\Token;
/**
* Context for MySQL 8.0.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
* @category Contexts
*
* @see https://dev.mysql.com/doc/refman/8.0/en/keywords.html
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql80000 extends Context
{
@@ -26,10 +32,9 @@ class ContextMySql80000 extends Context
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
* @var array
*/
public static $KEYWORDS = [
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
@@ -123,8 +128,8 @@ class ContextMySql80000 extends Context
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'OVER' => 3, 'READ' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3,
'UNDO' => 3, 'WHEN' => 3, 'WITH' => 3,
'NULL' => 3, 'READ' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3, 'UNDO' => 3,
'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
@@ -344,5 +349,5 @@ class ContextMySql80000 extends Context
'CHAR' => 43,
'BINARY' => 43,
'INTERVAL' => 43,
];
);
}
+8 -12
View File
@@ -1,22 +1,19 @@
<?php
/**
* Defines the core helper infrastructure of the library.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use Exception;
class Core
{
/**
* Whether errors should throw exceptions or just be stored.
*
* @see static::$errors
*
* @var bool
*
* @see static::$errors
*/
public $strict = false;
@@ -27,25 +24,24 @@ class Core
* error might be false positive or a partial result (even a bad one)
* might be needed.
*
* @see Core::error()
* @var \Exception[]
*
* @var Exception[]
* @see Core::error()
*/
public $errors = [];
public $errors = array();
/**
* Creates a new error log.
*
* @param Exception $error the error exception
* @param \Exception $error the error exception
*
* @throws Exception throws the exception, if strict mode is enabled.
* @throws \Exception throws the exception, if strict mode is enabled
*/
public function error($error)
{
if ($this->strict) {
throw $error;
}
$this->errors[] = $error;
}
}
@@ -1,18 +1,19 @@
<?php
/**
* Exception thrown by the lexer.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Exceptions;
use Exception;
/**
* Exception thrown by the lexer.
*
* @category Exceptions
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class LexerException extends Exception
class LexerException extends \Exception
{
/**
* The character that produced this error.
@@ -29,6 +30,8 @@ class LexerException extends Exception
public $pos;
/**
* Constructor.
*
* @param string $msg the message of this exception
* @param string $ch the character that produced this exception
* @param int $pos the position of the character
@@ -1,18 +1,19 @@
<?php
/**
* Exception thrown by the lexer.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Exceptions;
use Exception;
/**
* Exception thrown by the lexer.
*
* @category Exceptions
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class LoaderException extends Exception
class LoaderException extends \Exception
{
/**
* The failed load name.
@@ -22,6 +23,8 @@ class LoaderException extends Exception
public $name;
/**
* Constructor.
*
* @param string $msg the message of this exception
* @param string $name the character that produced this exception
* @param int $code the code of this error
@@ -1,19 +1,21 @@
<?php
/**
* Exception thrown by the parser.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Exceptions;
use Exception;
use PhpMyAdmin\SqlParser\Token;
/**
* Exception thrown by the parser.
*
* @category Exceptions
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ParserException extends Exception
class ParserException extends \Exception
{
/**
* The token that produced this error.
@@ -23,11 +25,13 @@ class ParserException extends Exception
public $token;
/**
* Constructor.
*
* @param string $msg the message of this exception
* @param Token $token the token that produced this exception
* @param int $code the code of this error
*/
public function __construct($msg = '', ?Token $token = null, $code = 0)
public function __construct($msg = '', Token $token = null, $code = 0)
{
parent::__construct($msg, $code);
$this->token = $token;
+112 -145
View File
@@ -1,4 +1,5 @@
<?php
/**
* Defines the lexer of the library.
*
@@ -7,20 +8,10 @@
* Depends on context to extract lexemes.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use PhpMyAdmin\SqlParser\Exceptions\LexerException;
use function define;
use function defined;
use function in_array;
use function mb_strlen;
use function sprintf;
use function strlen;
use function substr;
if (! defined('USE_UTF_STRINGS')) {
// NOTE: In previous versions of PHP (5.5 and older) the default
// internal encoding is "ISO-8859-1".
@@ -42,6 +33,10 @@ if (! defined('USE_UTF_STRINGS')) {
*
* The output of the lexer is affected by the context of the SQL statement.
*
* @category Lexer
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*
* @see Context
*/
class Lexer extends Core
@@ -51,7 +46,7 @@ class Lexer extends Core
*
* @var array
*/
public static $PARSER_METHODS = [
public static $PARSER_METHODS = array(
// It is best to put the parsers in order of their complexity
// (ascending) and their occurrence rate (descending).
//
@@ -85,8 +80,8 @@ class Lexer extends Core
'parseSymbol',
'parseKeyword',
'parseLabel',
'parseUnknown',
];
'parseUnknown'
);
/**
* The string to be parsed.
@@ -163,6 +158,8 @@ class Lexer extends Core
}
/**
* Constructor.
*
* @param string|UtfString $str the query to be lexed
* @param bool $strict whether strict mode should be
* enabled or not
@@ -186,7 +183,9 @@ class Lexer extends Core
$this->strict = $strict;
// Setting the delimiter.
$this->setDelimiter(! empty($delimiter) ? $delimiter : static::$DEFAULT_DELIMITER);
$this->setDelimiter(
! empty($delimiter) ? $delimiter : static::$DEFAULT_DELIMITER
);
$this->lex();
}
@@ -234,9 +233,7 @@ class Lexer extends Core
$token = null;
foreach (static::$PARSER_METHODS as $method) {
$token = $this->$method();
if ($token) {
if ($token = $this->$method()) {
break;
}
}
@@ -244,9 +241,12 @@ class Lexer extends Core
if ($token === null) {
// @assert($this->last === $lastIdx);
$token = new Token($this->str[$this->last]);
$this->error('Unexpected character.', $this->str[$this->last], $this->last);
} elseif (
$lastToken !== null
$this->error(
'Unexpected character.',
$this->str[$this->last],
$this->last
);
} elseif ($lastToken !== null
&& $token->type === Token::TYPE_SYMBOL
&& $token->flags & Token::FLAG_SYMBOL_VARIABLE
&& (
@@ -263,8 +263,7 @@ class Lexer extends Core
$lastToken->flags = Token::FLAG_SYMBOL_USER;
$lastToken->value .= '@' . $token->value;
continue;
} elseif (
$lastToken !== null
} elseif ($lastToken !== null
&& $token->type === Token::TYPE_KEYWORD
&& $lastToken->type === Token::TYPE_OPERATOR
&& $lastToken->value === '.'
@@ -283,42 +282,47 @@ class Lexer extends Core
// Handling delimiters.
if ($token->type === Token::TYPE_NONE && $token->value === 'DELIMITER') {
if ($this->last + 1 >= $this->len) {
$this->error('Expected whitespace(s) before delimiter.', '', $this->last + 1);
$this->error(
'Expected whitespace(s) before delimiter.',
'',
$this->last + 1
);
continue;
}
// Skipping last R (from `delimiteR`) and whitespaces between
// the keyword `DELIMITER` and the actual delimiter.
$pos = ++$this->last;
$token = $this->parseWhitespace();
if ($token !== null) {
if (($token = $this->parseWhitespace()) !== null) {
$token->position = $pos;
$list->tokens[$list->count++] = $token;
}
// Preparing the token that holds the new delimiter.
if ($this->last + 1 >= $this->len) {
$this->error('Expected delimiter.', '', $this->last + 1);
$this->error(
'Expected delimiter.',
'',
$this->last + 1
);
continue;
}
$pos = $this->last + 1;
// Parsing the delimiter.
$this->delimiter = null;
$delimiterLen = 0;
while (
++$this->last < $this->len
&& ! Context::isWhitespace($this->str[$this->last])
&& $delimiterLen < 15
) {
while (++$this->last < $this->len && ! Context::isWhitespace($this->str[$this->last]) && $delimiterLen < 15) {
$this->delimiter .= $this->str[$this->last];
++$delimiterLen;
}
if (empty($this->delimiter)) {
$this->error('Expected delimiter.', '', $this->last);
$this->error(
'Expected delimiter.',
'',
$this->last
);
$this->delimiter = ';';
}
@@ -361,24 +365,16 @@ class Lexer extends Core
private function solveAmbiguityOnStarOperator()
{
$iBak = $this->list->idx;
while (($starToken = $this->list->getNextOfTypeAndValue(Token::TYPE_OPERATOR, '*')) !== null) {
// getNext() already gets rid of whitespaces and comments.
$next = $this->list->getNext();
if ($next === null) {
continue;
while (null !== ($starToken = $this->list->getNextOfTypeAndValue(Token::TYPE_OPERATOR, '*'))) {
// ::getNext already gets rid of whitespaces and comments.
if (($next = $this->list->getNext()) !== null) {
if (($next->type === Token::TYPE_KEYWORD && in_array($next->value, array('FROM', 'USING'), true))
|| ($next->type === Token::TYPE_OPERATOR && in_array($next->value, array(',', ')'), true))
) {
$starToken->flags = Token::FLAG_OPERATOR_SQL;
}
}
if (
($next->type !== Token::TYPE_KEYWORD || ! in_array($next->value, ['FROM', 'USING'], true))
&& ($next->type !== Token::TYPE_OPERATOR || ! in_array($next->value, [',', ')'], true))
) {
continue;
}
$starToken->flags = Token::FLAG_OPERATOR_SQL;
}
$this->list->idx = $iBak;
}
@@ -390,7 +386,7 @@ class Lexer extends Core
* @param int $pos the position of the character
* @param int $code the code of the error
*
* @throws LexerException throws the exception, if strict mode is enabled.
* @throws LexerException throws the exception, if strict mode is enabled
*/
public function error($msg, $str = '', $pos = 0, $code = 0)
{
@@ -406,7 +402,7 @@ class Lexer extends Core
/**
* Parses a keyword.
*
* @return Token|null
* @return null|Token
*/
public function parseKeyword()
{
@@ -441,25 +437,22 @@ class Lexer extends Core
--$j; // The size of the keyword didn't increase.
continue;
}
$lastSpace = true;
} else {
$lastSpace = false;
}
$token .= $this->str[$this->last];
$flags = Context::isKeyword($token);
if (($this->last + 1 === $this->len || Context::isSeparator($this->str[$this->last + 1]))
&& $flags = Context::isKeyword($token)
) {
$ret = new Token($token, Token::TYPE_KEYWORD, $flags);
$iEnd = $this->last;
if (($this->last + 1 !== $this->len && ! Context::isSeparator($this->str[$this->last + 1])) || ! $flags) {
continue;
// We don't break so we find longest keyword.
// For example, `OR` and `ORDER` have a common prefix `OR`.
// If we stopped at `OR`, the parsing would be invalid.
}
$ret = new Token($token, Token::TYPE_KEYWORD, $flags);
$iEnd = $this->last;
// We don't break so we find longest keyword.
// For example, `OR` and `ORDER` have a common prefix `OR`.
// If we stopped at `OR`, the parsing would be invalid.
}
$this->last = $iEnd;
@@ -470,7 +463,7 @@ class Lexer extends Core
/**
* Parses a label.
*
* @return Token|null
* @return null|Token
*/
public function parseLabel()
{
@@ -496,9 +489,7 @@ class Lexer extends Core
$ret = new Token($token, Token::TYPE_LABEL);
$iEnd = $this->last;
break;
}
if (Context::isWhitespace($this->str[$this->last]) && $j > 1) {
} elseif (Context::isWhitespace($this->str[$this->last]) && $j > 1) {
// Whitespace between label and :
// The size of the keyword didn't increase.
--$j;
@@ -506,7 +497,6 @@ class Lexer extends Core
// Any other separator
break;
}
$token .= $this->str[$this->last];
}
@@ -518,7 +508,7 @@ class Lexer extends Core
/**
* Parses an operator.
*
* @return Token|null
* @return null|Token
*/
public function parseOperator()
{
@@ -540,14 +530,10 @@ class Lexer extends Core
for ($j = 1; $j < Context::OPERATOR_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
$token .= $this->str[$this->last];
$flags = Context::isOperator($token);
if (! $flags) {
continue;
if ($flags = Context::isOperator($token)) {
$ret = new Token($token, Token::TYPE_OPERATOR, $flags);
$iEnd = $this->last;
}
$ret = new Token($token, Token::TYPE_OPERATOR, $flags);
$iEnd = $this->last;
}
$this->last = $iEnd;
@@ -558,7 +544,7 @@ class Lexer extends Core
/**
* Parses a whitespace.
*
* @return Token|null
* @return null|Token
*/
public function parseWhitespace()
{
@@ -580,7 +566,7 @@ class Lexer extends Core
/**
* Parses a comment.
*
* @return Token|null
* @return null|Token
*/
public function parseComment()
{
@@ -589,10 +575,11 @@ class Lexer extends Core
// Bash style comments. (#comment\n)
if (Context::isComment($token)) {
while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
while (++$this->last < $this->len
&& $this->str[$this->last] !== "\n"
) {
$token .= $this->str[$this->last];
}
// Include trailing \n as whitespace token
if ($this->last < $this->len) {
--$this->last;
@@ -609,7 +596,7 @@ class Lexer extends Core
// This can occurs in the following statements:
// - "SELECT */* comment */ FROM ..."
// - "SELECT 2*/* comment */3 AS `six`;"
$next = $this->last + 1;
$next = $this->last+1;
if (($next < $this->len) && $this->str[$next] === '*') {
// Conflict in "*/*": first "*" was not for ending a comment.
// Stop here and let other parsing method define the true behavior of that first star.
@@ -627,18 +614,18 @@ class Lexer extends Core
}
// Checking if this is a MySQL-specific command.
if ($this->last + 1 < $this->len && $this->str[$this->last + 1] === '!') {
if ($this->last + 1 < $this->len
&& $this->str[$this->last + 1] === '!'
) {
$flags |= Token::FLAG_COMMENT_MYSQL_CMD;
$token .= $this->str[++$this->last];
while (
++$this->last < $this->len
while (++$this->last < $this->len
&& $this->str[$this->last] >= '0'
&& $this->str[$this->last] <= '9'
) {
$token .= $this->str[$this->last];
}
--$this->last;
// We split this comment and parse only its beginning
@@ -647,8 +634,7 @@ class Lexer extends Core
}
// Parsing the comment.
while (
++$this->last < $this->len
while (++$this->last < $this->len
&& (
$this->str[$this->last - 1] !== '*'
|| $this->str[$this->last] !== '/'
@@ -674,15 +660,15 @@ class Lexer extends Core
--$this->last;
$end = true;
}
if (Context::isComment($token, $end)) {
// Checking if this comment did not end already (```--\n```).
if ($this->str[$this->last] !== "\n") {
while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
while (++$this->last < $this->len
&& $this->str[$this->last] !== "\n"
) {
$token .= $this->str[$this->last];
}
}
// Include trailing \n as whitespace token
if ($this->last < $this->len) {
--$this->last;
@@ -699,7 +685,7 @@ class Lexer extends Core
/**
* Parses a boolean.
*
* @return Token|null
* @return null|Token
*/
public function parseBool()
{
@@ -715,9 +701,7 @@ class Lexer extends Core
if (Context::isBool($token)) {
return new Token($token, Token::TYPE_BOOL);
}
if (++$this->last < $this->len) {
} elseif (++$this->last < $this->len) {
$token .= $this->str[$this->last]; // fals_E_
if (Context::isBool($token)) {
return new Token($token, Token::TYPE_BOOL, 1);
@@ -732,7 +716,7 @@ class Lexer extends Core
/**
* Parses a number.
*
* @return Token|null
* @return null|Token
*/
public function parseNumber()
{
@@ -781,8 +765,7 @@ class Lexer extends Core
if ($state === 1) {
if ($this->str[$this->last] === '-') {
$flags |= Token::FLAG_NUMBER_NEGATIVE;
} elseif (
$this->last + 1 < $this->len
} elseif ($this->last + 1 < $this->len
&& $this->str[$this->last] === '0'
&& (
$this->str[$this->last + 1] === 'x'
@@ -803,8 +786,7 @@ class Lexer extends Core
}
} elseif ($state === 2) {
$flags |= Token::FLAG_NUMBER_HEX;
if (
! (
if (! (
($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
|| ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'F')
|| ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'f')
@@ -817,10 +799,8 @@ class Lexer extends Core
$state = 4;
} elseif ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
$state = 5;
} elseif (
($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
|| ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
) {
} elseif (($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
|| ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')) {
// A number can't be directly followed by a letter
$state = -$state;
} elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
@@ -831,10 +811,8 @@ class Lexer extends Core
$flags |= Token::FLAG_NUMBER_FLOAT;
if ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
$state = 5;
} elseif (
($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
|| ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
) {
} elseif (($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
|| ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')) {
// A number can't be directly followed by a letter
$state = -$state;
} elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
@@ -843,15 +821,12 @@ class Lexer extends Core
}
} elseif ($state === 5) {
$flags |= Token::FLAG_NUMBER_APPROXIMATE;
if (
$this->str[$this->last] === '+' || $this->str[$this->last] === '-'
if ($this->str[$this->last] === '+' || $this->str[$this->last] === '-'
|| ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
) {
$state = 6;
} elseif (
($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
|| ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
) {
} elseif (($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
|| ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')) {
// A number can't be directly followed by a letter
$state = -$state;
} else {
@@ -864,30 +839,32 @@ class Lexer extends Core
}
} elseif ($state === 7) {
$flags |= Token::FLAG_NUMBER_BINARY;
if ($this->str[$this->last] !== '\'') {
if ($this->str[$this->last] === '\'') {
$state = 8;
} else {
break;
}
$state = 8;
} elseif ($state === 8) {
if ($this->str[$this->last] === '\'') {
$state = 9;
} elseif ($this->str[$this->last] !== '0' && $this->str[$this->last] !== '1') {
} elseif ($this->str[$this->last] !== '0'
&& $this->str[$this->last] !== '1'
) {
break;
}
} elseif ($state === 9) {
break;
}
$token .= $this->str[$this->last];
}
if ($state === 2 || $state === 3 || ($token !== '.' && $state === 4) || $state === 6 || $state === 9) {
if ($state === 2 || $state === 3
|| ($token !== '.' && $state === 4)
|| $state === 6 || $state === 9
) {
--$this->last;
return new Token($token, Token::TYPE_NUMBER, $flags);
}
$this->last = $iBak;
return null;
@@ -898,24 +875,19 @@ class Lexer extends Core
*
* @param string $quote additional starting symbol
*
* @return Token|null
*
* @return null|Token
* @throws LexerException
*/
public function parseString($quote = '')
{
$token = $this->str[$this->last];
$flags = Context::isString($token);
if (! $flags && $token !== $quote) {
if (! ($flags = Context::isString($token)) && $token !== $quote) {
return null;
}
$quote = $token;
while (++$this->last < $this->len) {
if (
$this->last + 1 < $this->len
if ($this->last + 1 < $this->len
&& (
($this->str[$this->last] === $quote && $this->str[$this->last + 1] === $quote)
|| ($this->str[$this->last] === '\\' && $quote !== '`')
@@ -926,7 +898,6 @@ class Lexer extends Core
if ($this->str[$this->last] === $quote) {
break;
}
$token .= $this->str[$this->last];
}
}
@@ -950,16 +921,13 @@ class Lexer extends Core
/**
* Parses a symbol.
*
* @return Token|null
*
* @return null|Token
* @throws LexerException
*/
public function parseSymbol()
{
$token = $this->str[$this->last];
$flags = Context::isSymbol($token);
if (! $flags) {
if (! ($flags = Context::isSymbol($token))) {
return null;
}
@@ -980,13 +948,13 @@ class Lexer extends Core
$str = null;
if ($this->last < $this->len) {
$str = $this->parseString('`');
if ($str === null) {
$str = $this->parseUnknown();
if ($str === null) {
$this->error('Variable name was expected.', $this->str[$this->last], $this->last);
if (($str = $this->parseString('`')) === null) {
if (($str = $this->parseUnknown()) === null) {
$this->error(
'Variable name was expected.',
$this->str[$this->last],
$this->last
);
}
}
}
@@ -1001,7 +969,7 @@ class Lexer extends Core
/**
* Parses unknown parts of the query.
*
* @return Token|null
* @return null|Token
*/
public function parseUnknown()
{
@@ -1029,7 +997,7 @@ class Lexer extends Core
/**
* Parses the delimiter of the query.
*
* @return Token|null
* @return null|Token
*/
public function parseDelimiter()
{
@@ -1039,7 +1007,6 @@ class Lexer extends Core
if ($this->delimiter[$idx] !== $this->str[$this->last + $idx]) {
return null;
}
++$idx;
}
+158 -156
View File
@@ -1,24 +1,24 @@
<?php
/**
* Defines the parser of the library.
*
* This is one of the most important components, along with the lexer.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use PhpMyAdmin\SqlParser\Exceptions\ParserException;
use PhpMyAdmin\SqlParser\Statements\SelectStatement;
use PhpMyAdmin\SqlParser\Statements\TransactionStatement;
use function is_string;
use function strtoupper;
/**
* Takes multiple tokens (contained in a Lexer instance) as input and builds a
* parse tree.
*
* @category Parser
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Parser extends Core
{
@@ -27,7 +27,7 @@ class Parser extends Core
*
* @var array
*/
public static $STATEMENT_PARSERS = [
public static $STATEMENT_PARSERS = array(
// MySQL Utility Statements
'DESCRIBE' => 'PhpMyAdmin\\SqlParser\\Statements\\ExplainStatement',
'DESC' => 'PhpMyAdmin\\SqlParser\\Statements\\ExplainStatement',
@@ -73,7 +73,6 @@ class Parser extends Core
'REPLACE' => 'PhpMyAdmin\\SqlParser\\Statements\\ReplaceStatement',
'SELECT' => 'PhpMyAdmin\\SqlParser\\Statements\\SelectStatement',
'UPDATE' => 'PhpMyAdmin\\SqlParser\\Statements\\UpdateStatement',
'WITH' => 'PhpMyAdmin\\SqlParser\\Statements\\WithStatement',
// Prepared Statements.
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
@@ -93,247 +92,247 @@ class Parser extends Core
// Lock statements
// https://dev.mysql.com/doc/refman/5.7/en/lock-tables.html
'LOCK' => 'PhpMyAdmin\\SqlParser\\Statements\\LockStatement',
'UNLOCK' => 'PhpMyAdmin\\SqlParser\\Statements\\LockStatement',
];
'UNLOCK' => 'PhpMyAdmin\\SqlParser\\Statements\\LockStatement'
);
/**
* Array of classes that are used in parsing SQL components.
*
* @var array
*/
public static $KEYWORD_PARSERS = [
public static $KEYWORD_PARSERS = array(
// This is not a proper keyword and was added here to help the
// formatter.
'PARTITION BY' => [],
'SUBPARTITION BY' => [],
'PARTITION BY' => array(),
'SUBPARTITION BY' => array(),
// This is not a proper keyword and was added here to help the
// builder.
'_OPTIONS' => [
'_OPTIONS' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\OptionsArray',
'field' => 'options',
],
'_END_OPTIONS' => [
),
'_END_OPTIONS' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\OptionsArray',
'field' => 'end_options',
],
),
'INTERSECT' => [
'INTERSECT' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\UnionKeyword',
'field' => 'union',
],
'EXCEPT' => [
),
'EXCEPT' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\UnionKeyword',
'field' => 'union',
],
'UNION' => [
),
'UNION' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\UnionKeyword',
'field' => 'union',
],
'UNION ALL' => [
),
'UNION ALL' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\UnionKeyword',
'field' => 'union',
],
'UNION DISTINCT' => [
),
'UNION DISTINCT' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\UnionKeyword',
'field' => 'union',
],
),
// Actual clause parsers.
'ALTER' => [
'ALTER' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Expression',
'field' => 'table',
'options' => ['parseField' => 'table'],
],
'ANALYZE' => [
'options' => array('parseField' => 'table'),
),
'ANALYZE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'BACKUP' => [
'options' => array('parseField' => 'table'),
),
'BACKUP' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'CALL' => [
'options' => array('parseField' => 'table'),
),
'CALL' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\FunctionCall',
'field' => 'call',
],
'CHECK' => [
),
'CHECK' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'CHECKSUM' => [
'options' => array('parseField' => 'table'),
),
'CHECKSUM' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'CROSS JOIN' => [
'options' => array('parseField' => 'table'),
),
'CROSS JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'DROP' => [
),
'DROP' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'fields',
'options' => ['parseField' => 'table'],
],
'FORCE' => [
'options' => array('parseField' => 'table'),
),
'FORCE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\IndexHint',
'field' => 'index_hints',
],
'FROM' => [
),
'FROM' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'from',
'options' => ['field' => 'table'],
],
'GROUP BY' => [
'options' => array('field' => 'table'),
),
'GROUP BY' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\GroupKeyword',
'field' => 'group',
],
'HAVING' => [
),
'HAVING' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Condition',
'field' => 'having',
],
'IGNORE' => [
),
'IGNORE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\IndexHint',
'field' => 'index_hints',
],
'INTO' => [
),
'INTO' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\IntoKeyword',
'field' => 'into',
],
'JOIN' => [
),
'JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'LEFT JOIN' => [
),
'LEFT JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'LEFT OUTER JOIN' => [
),
'LEFT OUTER JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'ON' => [
),
'ON' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Expression',
'field' => 'table',
'options' => ['parseField' => 'table'],
],
'RIGHT JOIN' => [
'options' => array('parseField' => 'table'),
),
'RIGHT JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'RIGHT OUTER JOIN' => [
),
'RIGHT OUTER JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'INNER JOIN' => [
),
'INNER JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'FULL JOIN' => [
),
'FULL JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'FULL OUTER JOIN' => [
),
'FULL OUTER JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'NATURAL JOIN' => [
),
'NATURAL JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'NATURAL LEFT JOIN' => [
),
'NATURAL LEFT JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'NATURAL RIGHT JOIN' => [
),
'NATURAL RIGHT JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'NATURAL LEFT OUTER JOIN' => [
),
'NATURAL LEFT OUTER JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'NATURAL RIGHT OUTER JOIN' => [
),
'NATURAL RIGHT OUTER JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'STRAIGHT_JOIN' => [
),
'STRAIGHT_JOIN' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\JoinKeyword',
'field' => 'join',
],
'LIMIT' => [
),
'LIMIT' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Limit',
'field' => 'limit',
],
'OPTIMIZE' => [
),
'OPTIMIZE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'ORDER BY' => [
'options' => array('parseField' => 'table'),
),
'ORDER BY' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\OrderKeyword',
'field' => 'order',
],
'PARTITION' => [
),
'PARTITION' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ArrayObj',
'field' => 'partition',
],
'PROCEDURE' => [
),
'PROCEDURE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\FunctionCall',
'field' => 'procedure',
],
'RENAME' => [
),
'RENAME' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\RenameOperation',
'field' => 'renames',
],
'REPAIR' => [
),
'REPAIR' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'RESTORE' => [
'options' => array('parseField' => 'table'),
),
'RESTORE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'SET' => [
'options' => array('parseField' => 'table'),
),
'SET' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\SetOperation',
'field' => 'set',
],
'SELECT' => [
),
'SELECT' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'expr',
],
'TRUNCATE' => [
),
'TRUNCATE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Expression',
'field' => 'table',
'options' => ['parseField' => 'table'],
],
'UPDATE' => [
'options' => array('parseField' => 'table'),
),
'UPDATE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => ['parseField' => 'table'],
],
'USE' => [
'options' => array('parseField' => 'table'),
),
'USE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\IndexHint',
'field' => 'index_hints',
],
'VALUE' => [
),
'VALUE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Array2d',
'field' => 'values',
],
'VALUES' => [
),
'VALUES' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Array2d',
'field' => 'values',
],
'WHERE' => [
),
'WHERE' => array(
'class' => 'PhpMyAdmin\\SqlParser\\Components\\Condition',
'field' => 'where',
],
];
)
);
/**
* The list of tokens that are parsed.
@@ -347,7 +346,7 @@ class Parser extends Core
*
* @var Statement[]
*/
public $statements = [];
public $statements = array();
/**
* The number of opened brackets.
@@ -357,6 +356,8 @@ class Parser extends Core
public $brackets = 0;
/**
* Constructor.
*
* @param string|UtfString|TokensList $list the list of tokens to be parsed
* @param bool $strict whether strict mode should be enabled or not
*/
@@ -371,16 +372,13 @@ class Parser extends Core
$this->strict = $strict;
if ($list === null) {
return;
if ($list !== null) {
$this->parse();
}
$this->parse();
}
/**
* Builds the parse trees.
*
* @throws ParserException
*/
public function parse()
@@ -430,7 +428,9 @@ class Parser extends Core
// `DELIMITER` is not an actual statement and it requires
// special handling.
if (($token->type === Token::TYPE_NONE) && (strtoupper($token->token) === 'DELIMITER')) {
if (($token->type === Token::TYPE_NONE)
&& (strtoupper($token->token) === 'DELIMITER')
) {
// Skipping to the end of this statement.
$list->getNextOfType(Token::TYPE_DELIMITER);
$prevLastIdx = $list->idx;
@@ -446,20 +446,20 @@ class Parser extends Core
// Statements can start with keywords only.
// Comments, whitespaces, etc. are ignored.
if ($token->type !== Token::TYPE_KEYWORD) {
if (
($token->type !== Token::TYPE_COMMENT)
if (($token->type !== Token::TYPE_COMMENT)
&& ($token->type !== Token::TYPE_WHITESPACE)
&& ($token->type !== Token::TYPE_OPERATOR) // `(` and `)`
&& ($token->type !== Token::TYPE_DELIMITER)
) {
$this->error('Unexpected beginning of statement.', $token);
$this->error(
'Unexpected beginning of statement.',
$token
);
}
continue;
}
if (
($token->keyword === 'UNION') ||
if (($token->keyword === 'UNION') ||
($token->keyword === 'UNION ALL') ||
($token->keyword === 'UNION DISTINCT') ||
($token->keyword === 'EXCEPT') ||
@@ -475,9 +475,11 @@ class Parser extends Core
// A statement is considered recognized if the parser
// is aware that it is a statement, but it does not have
// a parser for it yet.
$this->error('Unrecognized statement type.', $token);
$this->error(
'Unrecognized statement type.',
$token
);
}
// Skipping to the end of this statement.
$list->getNextOfType(Token::TYPE_DELIMITER);
$prevLastIdx = $list->idx;
@@ -510,8 +512,7 @@ class Parser extends Core
$prevLastIdx = $list->idx;
// Handles unions.
if (
! empty($unionType)
if (! empty($unionType)
&& ($lastStatement instanceof SelectStatement)
&& ($statement instanceof SelectStatement)
) {
@@ -526,16 +527,16 @@ class Parser extends Core
*
* @var SelectStatement $lastStatement
*/
$lastStatement->union[] = [
$lastStatement->union[] = array(
$unionType,
$statement,
];
$statement
);
// if there are no no delimiting brackets, the `ORDER` and
// `LIMIT` keywords actually belong to the first statement.
$lastStatement->order = $statement->order;
$lastStatement->limit = $statement->limit;
$statement->order = [];
$statement->order = array();
$statement->limit = null;
// The statement actually ends where the last statement in
@@ -562,11 +563,13 @@ class Parser extends Core
// Even though an error occurred, the query is being
// saved.
$this->statements[] = $statement;
$this->error('No transaction was previously started.', $token);
$this->error(
'No transaction was previously started.',
$token
);
} else {
$lastTransaction->end = $statement;
}
$lastTransaction = null;
}
@@ -584,7 +587,6 @@ class Parser extends Core
} else {
$this->statements[] = $statement;
}
$lastStatement = $statement;
}
}
@@ -596,9 +598,9 @@ class Parser extends Core
* @param Token $token the token that produced the error
* @param int $code the code of the error
*
* @throws ParserException throws the exception, if strict mode is enabled.
* @throws ParserException throws the exception, if strict mode is enabled
*/
public function error($msg, ?Token $token = null, $code = 0)
public function error($msg, Token $token = null, $code = 0)
{
$error = new ParserException(
Translator::gettext($msg),
+73 -70
View File
@@ -1,4 +1,5 @@
<?php
/**
* The result of the parser is an array of statements are extensions of the
* class defined here.
@@ -6,22 +7,17 @@
* A statement represents the result of parsing the lexemes.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use PhpMyAdmin\SqlParser\Components\FunctionCall;
use PhpMyAdmin\SqlParser\Components\OptionsArray;
use function array_flip;
use function array_keys;
use function count;
use function in_array;
use function stripos;
use function trim;
/**
* Abstract statement definition.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
abstract class Statement
{
@@ -44,7 +40,7 @@ abstract class Statement
*
* @var array
*/
public static $OPTIONS = [];
public static $OPTIONS = array();
/**
* The clauses of this statement, in order.
@@ -58,17 +54,16 @@ abstract class Statement
*
* @var array
*/
public static $CLAUSES = [];
public static $CLAUSES = array();
/** @var array */
public static $END_OPTIONS = [];
public static $END_OPTIONS = array();
/**
* The options of this query.
*
* @see static::$OPTIONS
*
* @var OptionsArray
*
* @see static::$OPTIONS
*/
public $options;
@@ -87,16 +82,16 @@ abstract class Statement
public $last;
/**
* Constructor.
*
* @param Parser $parser the instance that requests parsing
* @param TokensList $list the list of tokens to be parsed
*/
public function __construct(?Parser $parser = null, ?TokensList $list = null)
public function __construct(Parser $parser = null, TokensList $list = null)
{
if (($parser === null) || ($list === null)) {
return;
if (($parser !== null) && ($list !== null)) {
$this->parse($parser, $list);
}
$this->parse($parser, $list);
}
/**
@@ -125,7 +120,7 @@ abstract class Statement
*
* @var array
*/
$built = [];
$built = array();
/**
* Statement's clauses.
@@ -176,7 +171,6 @@ abstract class Statement
if (! empty($built[$field])) {
continue;
}
$built[$field] = true;
}
@@ -186,11 +180,9 @@ abstract class Statement
}
// Checking if the result of the builder should be added.
if (! ($type & 1)) {
continue;
if ($type & 1) {
$query = trim($query) . ' ' . $class::build($this->$field);
}
$query = trim($query) . ' ' . $class::build($this->$field);
}
return $query;
@@ -201,7 +193,6 @@ abstract class Statement
*
* @param Parser $parser the instance that requests parsing
* @param TokensList $list the list of tokens to be parsed
*
* @throws Exceptions\ParserException
*/
public function parse(Parser $parser, TokensList $list)
@@ -212,7 +203,7 @@ abstract class Statement
*
* @var array
*/
$parsedClauses = [];
$parsedClauses = array();
// This may be corrected by the parser.
$this->first = $list->idx;
@@ -249,17 +240,17 @@ abstract class Statement
// Only keywords are relevant here. Other parts of the query are
// processed in the functions below.
if ($token->type !== Token::TYPE_KEYWORD) {
if (($token->type !== Token::TYPE_COMMENT) && ($token->type !== Token::TYPE_WHITESPACE)) {
if (($token->type !== Token::TYPE_COMMENT)
&& ($token->type !== Token::TYPE_WHITESPACE)
) {
$parser->error('Unexpected token.', $token);
}
continue;
}
// Unions are parsed by the parser because they represent more than
// one statement.
if (
($token->keyword === 'UNION') ||
if (($token->keyword === 'UNION') ||
($token->keyword === 'UNION ALL') ||
($token->keyword === 'UNION DISTINCT') ||
($token->keyword === 'EXCEPT') ||
@@ -273,7 +264,9 @@ abstract class Statement
// ON DUPLICATE KEY UPDATE ...
// has to be parsed in parent statement (INSERT or REPLACE)
// so look for it and break
if ($this instanceof Statements\SelectStatement && $token->value === 'ON') {
if ($this instanceof Statements\SelectStatement
&& $token->value === 'ON'
) {
++$list->idx; // Skip ON
// look for ON DUPLICATE KEY UPDATE
@@ -281,8 +274,7 @@ abstract class Statement
$second = $list->getNextOfType(Token::TYPE_KEYWORD);
$third = $list->getNextOfType(Token::TYPE_KEYWORD);
if (
$first && $second && $third
if ($first && $second && $third
&& $first->value === 'DUPLICATE'
&& $second->value === 'KEY'
&& $third->value === 'UPDATE'
@@ -291,7 +283,6 @@ abstract class Statement
break;
}
}
$list->idx = $lastIdx;
/**
@@ -313,18 +304,19 @@ abstract class Statement
*
* @var array
*/
$options = [];
$options = array();
// Looking for duplicated clauses.
if (
! empty(Parser::$KEYWORD_PARSERS[$token->value])
if (! empty(Parser::$KEYWORD_PARSERS[$token->value])
|| ! empty(Parser::$STATEMENT_PARSERS[$token->value])
) {
if (! empty($parsedClauses[$token->value])) {
$parser->error('This type of clause was previously parsed.', $token);
$parser->error(
'This type of clause was previously parsed.',
$token
);
break;
}
$parsedClauses[$token->value] = true;
}
@@ -332,19 +324,18 @@ abstract class Statement
// Fix Issue #221: As `truncate` is not a keyword
// but it might be the beginning of a statement of truncate,
// so let the value use the keyword field for truncate type.
$tokenValue = in_array($token->keyword, ['TRUNCATE']) ? $token->keyword : $token->value;
if (! empty(Parser::$KEYWORD_PARSERS[$tokenValue]) && $list->idx < $list->count) {
$class = Parser::$KEYWORD_PARSERS[$tokenValue]['class'];
$field = Parser::$KEYWORD_PARSERS[$tokenValue]['field'];
if (! empty(Parser::$KEYWORD_PARSERS[$tokenValue]['options'])) {
$options = Parser::$KEYWORD_PARSERS[$tokenValue]['options'];
$token_value = in_array($token->keyword, array('TRUNCATE')) ? $token->keyword : $token->value;
if (! empty(Parser::$KEYWORD_PARSERS[$token_value]) && $list->idx < $list->count) {
$class = Parser::$KEYWORD_PARSERS[$token_value]['class'];
$field = Parser::$KEYWORD_PARSERS[$token_value]['field'];
if (! empty(Parser::$KEYWORD_PARSERS[$token_value]['options'])) {
$options = Parser::$KEYWORD_PARSERS[$token_value]['options'];
}
}
// Checking if this is the beginning of the statement.
if (! empty(Parser::$STATEMENT_PARSERS[$token->keyword])) {
if (
! empty(static::$CLAUSES) // Undefined for some statements.
if (! empty(static::$CLAUSES) // Undefined for some statements.
&& empty(static::$CLAUSES[$token->value])
) {
// Some keywords (e.g. `SET`) may be the beginning of a
@@ -358,33 +349,41 @@ abstract class Statement
);
break;
}
if (! $parsedOptions) {
if (empty(static::$OPTIONS[$token->value])) {
// Skipping keyword because if it is not a option.
++$list->idx;
}
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
$parsedOptions = true;
}
} elseif ($class === null) {
if (
$this instanceof Statements\SelectStatement
if ($this instanceof Statements\SelectStatement
&& ($token->value === 'FOR UPDATE'
|| $token->value === 'LOCK IN SHARE MODE')
) {
// Handle special end options in Select statement
// See Statements\SelectStatement::$END_OPTIONS
$this->end_options = OptionsArray::parse($parser, $list, static::$END_OPTIONS);
} elseif (
$this instanceof Statements\SetStatement
$this->end_options = OptionsArray::parse(
$parser,
$list,
static::$END_OPTIONS
);
} elseif ($this instanceof Statements\SetStatement
&& ($token->value === 'COLLATE'
|| $token->value === 'DEFAULT')
) {
// Handle special end options in SET statement
// See Statements\SetStatement::$END_OPTIONS
$this->end_options = OptionsArray::parse($parser, $list, static::$END_OPTIONS);
$this->end_options = OptionsArray::parse(
$parser,
$list,
static::$END_OPTIONS
);
} else {
// There is no parser for this keyword and isn't the beginning
// of a statement (so no options) either.
@@ -402,7 +401,6 @@ abstract class Statement
$parser->error('Keyword at end of statement.', $token);
continue;
}
++$list->idx; // Skipping keyword or last option.
$this->$field = $class::parse($parser, $list, $options);
}
@@ -410,11 +408,12 @@ abstract class Statement
$this->after($parser, $list, $token);
// #223 Here may make a patch, if last is delimiter, back one
if ($class !== FunctionCall::class || $list->offsetGet($list->idx)->type !== Token::TYPE_DELIMITER) {
continue;
// TODO: when not supporting PHP 5.3 anymore, replace this by FunctionCall::class.
if ($class === 'PhpMyAdmin\\SqlParser\\Components\\FunctionCall'
&& $list->offsetGet($list->idx)->type === Token::TYPE_DELIMITER
) {
--$list->idx;
}
--$list->idx;
}
// This may be corrected by the parser.
@@ -474,7 +473,6 @@ abstract class Statement
* @param TokensList $list the list of tokens to be parsed
*
* @return bool
*
* @throws Exceptions\ParserException
*/
public function validateClauseOrder($parser, $list)
@@ -510,10 +508,13 @@ abstract class Statement
$error = 0;
$lastIdx = 0;
foreach ($clauses as $clauseType => $index) {
$clauseStartIdx = Utils\Query::getClauseStartOffset($this, $list, $clauseType);
$clauseStartIdx = Utils\Query::getClauseStartOffset(
$this,
$list,
$clauseType
);
if (
$clauseStartIdx !== -1
if ($clauseStartIdx !== -1
&& $this instanceof Statements\SelectStatement
&& ($clauseType === 'FORCE'
|| $clauseType === 'IGNORE'
@@ -540,17 +541,19 @@ abstract class Statement
if ($clauseStartIdx !== -1 && $clauseStartIdx < $minIdx) {
if ($minJoin === 0 || $error === 1) {
$token = $list->tokens[$clauseStartIdx];
$parser->error('Unexpected ordering of clauses.', $token);
$parser->error(
'Unexpected ordering of clauses.',
$token
);
return false;
}
$minIdx = $clauseStartIdx;
} elseif ($clauseStartIdx !== -1) {
$minIdx = $clauseStartIdx;
}
$lastIdx = $clauseStartIdx !== -1 ? $clauseStartIdx : $lastIdx;
$lastIdx = ($clauseStartIdx !== -1) ? $clauseStartIdx : $lastIdx;
}
return true;
@@ -1,10 +1,9 @@
<?php
/**
* `ALTER` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\AlterOperation;
@@ -15,10 +14,12 @@ use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function implode;
/**
* `ALTER` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class AlterStatement extends Statement
{
@@ -34,14 +35,14 @@ class AlterStatement extends Statement
*
* @var AlterOperation[]
*/
public $altered = [];
public $altered = array();
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'ONLINE' => 1,
'OFFLINE' => 1,
'IGNORE' => 2,
@@ -54,8 +55,8 @@ class AlterStatement extends Statement
'TABLE' => 3,
'TABLESPACE' => 3,
'USER' => 3,
'VIEW' => 3,
];
'VIEW' => 3
);
/**
* @param Parser $parser the instance that requests parsing
@@ -64,17 +65,21 @@ class AlterStatement extends Statement
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `ALTER`.
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
++$list->idx;
// Parsing affected table.
$this->table = Expression::parse(
$parser,
$list,
[
array(
'parseField' => 'table',
'breakOnAlias' => true,
]
'breakOnAlias' => true
)
);
++$list->idx; // Skipping field.
@@ -110,7 +115,7 @@ class AlterStatement extends Statement
}
if ($state === 0) {
$options = [];
$options = array();
if ($this->options->has('DATABASE')) {
$options = AlterOperation::$DB_OPTIONS;
} elseif ($this->options->has('TABLE')) {
@@ -136,7 +141,7 @@ class AlterStatement extends Statement
*/
public function build()
{
$tmp = [];
$tmp = array();
foreach ($this->altered as $altered) {
$tmp[] = $altered::build($altered);
}
@@ -1,10 +1,9 @@
<?php
/**
* `ANALYZE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Expression;
@@ -13,8 +12,12 @@ use PhpMyAdmin\SqlParser\Statement;
/**
* `ANALYZE` statement.
*
* ANALYZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
* ANALYZE array(NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name array(, tbl_name] ...
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class AnalyzeStatement extends Statement
{
@@ -23,12 +26,12 @@ class AnalyzeStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
];
'LOCAL' => 3
);
/**
* Analyzed tables.
@@ -1,16 +1,19 @@
<?php
/**
* `BACKUP` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
/**
* `BACKUP` statement.
*
* BACKUP TABLE tbl_name [, tbl_name] ... TO '/path/to/backup/directory'
* BACKUP TABLE tbl_name array(, tbl_name] ... TO '/path/to/backup/directory'
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class BackupStatement extends MaintenanceStatement
{
@@ -19,15 +22,15 @@ class BackupStatement extends MaintenanceStatement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
'TO' => [
'TO' => array(
4,
'var',
],
];
)
);
}
@@ -1,17 +1,14 @@
<?php
/**
* `CALL` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\FunctionCall;
use PhpMyAdmin\SqlParser\Statement;
use function implode;
/**
* `CALL` statement.
*
@@ -20,6 +17,10 @@ use function implode;
* or
*
* CALL sp_name[()]
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CallStatement extends Statement
{
@@ -37,7 +38,6 @@ class CallStatement extends Statement
*/
public function build()
{
return 'CALL ' . $this->call->name . '('
. ($this->call->parameters ? implode(',', $this->call->parameters->raw) : '') . ')';
return "CALL " . $this->call->name . "(" . ($this->call->parameters ? implode(",", $this->call->parameters->raw) : "") . ")";
}
}
@@ -1,16 +1,19 @@
<?php
/**
* `CHECK` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
/**
* `CHECK` statement.
*
* CHECK TABLE tbl_name [, tbl_name] ... [option] ...
* CHECK TABLE tbl_name array(, tbl_name] ... array(option] ...
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CheckStatement extends MaintenanceStatement
{
@@ -19,7 +22,7 @@ class CheckStatement extends MaintenanceStatement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'TABLE' => 1,
'FOR UPGRADE' => 2,
@@ -27,6 +30,6 @@ class CheckStatement extends MaintenanceStatement
'FAST' => 4,
'MEDIUM' => 5,
'EXTENDED' => 6,
'CHANGED' => 7,
];
'CHANGED' => 7
);
}
@@ -1,16 +1,19 @@
<?php
/**
* `CHECKSUM` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
/**
* `CHECKSUM` statement.
*
* CHECKSUM TABLE tbl_name [, tbl_name] ... [ QUICK | EXTENDED ]
* CHECKSUM TABLE tbl_name array(, tbl_name] ... array( QUICK | EXTENDED ]
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ChecksumStatement extends MaintenanceStatement
{
@@ -19,10 +22,10 @@ class ChecksumStatement extends MaintenanceStatement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'TABLE' => 1,
'QUICK' => 2,
'EXTENDED' => 3,
];
'EXTENDED' => 3
);
}
@@ -1,10 +1,9 @@
<?php
/**
* `CREATE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\ArrayObj;
@@ -19,11 +18,12 @@ use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function is_array;
use function trim;
/**
* `CREATE` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CreateStatement extends Statement
{
@@ -32,26 +32,26 @@ class CreateStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
// CREATE TABLE
'TEMPORARY' => 1,
// CREATE VIEW
'OR REPLACE' => 2,
'ALGORITHM' => [
'ALGORITHM' => array(
3,
'var=',
],
),
// `DEFINER` is also used for `CREATE FUNCTION / PROCEDURE`
'DEFINER' => [
'DEFINER' => array(
4,
'expr=',
],
),
// Used in `CREATE VIEW`
'SQL SECURITY' => [
'SQL SECURITY' => array(
5,
'var',
],
),
'DATABASE' => 6,
'EVENT' => 6,
@@ -70,213 +70,213 @@ class CreateStatement extends Statement
'SCHEMA' => 6,
// CREATE TABLE
'IF NOT EXISTS' => 7,
];
'IF NOT EXISTS' => 7
);
/**
* All database options.
*
* @var array
*/
public static $DB_OPTIONS = [
'CHARACTER SET' => [
public static $DB_OPTIONS = array(
'CHARACTER SET' => array(
1,
'var=',
],
'CHARSET' => [
),
'CHARSET' => array(
1,
'var=',
],
'DEFAULT CHARACTER SET' => [
),
'DEFAULT CHARACTER SET' => array(
1,
'var=',
],
'DEFAULT CHARSET' => [
),
'DEFAULT CHARSET' => array(
1,
'var=',
],
'DEFAULT COLLATE' => [
),
'DEFAULT COLLATE' => array(
2,
'var=',
],
'COLLATE' => [
),
'COLLATE' => array(
2,
'var=',
],
];
)
);
/**
* All table options.
*
* @var array
*/
public static $TABLE_OPTIONS = [
'ENGINE' => [
public static $TABLE_OPTIONS = array(
'ENGINE' => array(
1,
'var=',
],
'AUTO_INCREMENT' => [
),
'AUTO_INCREMENT' => array(
2,
'var=',
],
'AVG_ROW_LENGTH' => [
),
'AVG_ROW_LENGTH' => array(
3,
'var',
],
'CHARACTER SET' => [
),
'CHARACTER SET' => array(
4,
'var=',
],
'CHARSET' => [
),
'CHARSET' => array(
4,
'var=',
],
'DEFAULT CHARACTER SET' => [
),
'DEFAULT CHARACTER SET' => array(
4,
'var=',
],
'DEFAULT CHARSET' => [
),
'DEFAULT CHARSET' => array(
4,
'var=',
],
'CHECKSUM' => [
),
'CHECKSUM' => array(
5,
'var',
],
'DEFAULT COLLATE' => [
),
'DEFAULT COLLATE' => array(
6,
'var=',
],
'COLLATE' => [
),
'COLLATE' => array(
6,
'var=',
],
'COMMENT' => [
),
'COMMENT' => array(
7,
'var=',
],
'CONNECTION' => [
),
'CONNECTION' => array(
8,
'var',
],
'DATA DIRECTORY' => [
),
'DATA DIRECTORY' => array(
9,
'var',
],
'DELAY_KEY_WRITE' => [
),
'DELAY_KEY_WRITE' => array(
10,
'var',
],
'INDEX DIRECTORY' => [
),
'INDEX DIRECTORY' => array(
11,
'var',
],
'INSERT_METHOD' => [
),
'INSERT_METHOD' => array(
12,
'var',
],
'KEY_BLOCK_SIZE' => [
),
'KEY_BLOCK_SIZE' => array(
13,
'var',
],
'MAX_ROWS' => [
),
'MAX_ROWS' => array(
14,
'var',
],
'MIN_ROWS' => [
),
'MIN_ROWS' => array(
15,
'var',
],
'PACK_KEYS' => [
),
'PACK_KEYS' => array(
16,
'var',
],
'PASSWORD' => [
),
'PASSWORD' => array(
17,
'var',
],
'ROW_FORMAT' => [
),
'ROW_FORMAT' => array(
18,
'var',
],
'TABLESPACE' => [
),
'TABLESPACE' => array(
19,
'var',
],
'STORAGE' => [
),
'STORAGE' => array(
20,
'var',
],
'UNION' => [
),
'UNION' => array(
21,
'var',
],
];
)
);
/**
* All function options.
*
* @var array
*/
public static $FUNC_OPTIONS = [
'NOT' => [
public static $FUNC_OPTIONS = array(
'NOT' => array(
2,
'var',
],
'FUNCTION' => [
),
'FUNCTION' => array(
3,
'var=',
],
'PROCEDURE' => [
),
'PROCEDURE' => array(
3,
'var=',
],
'CONTAINS' => [
),
'CONTAINS' => array(
4,
'expr',
],
'NO' => [
),
'NO' => array(
4,
'var',
],
'READS' => [
),
'READS' => array(
4,
'var',
],
'MODIFIES' => [
),
'MODIFIES' => array(
4,
'expr',
],
'SQL SECURITY' => [
),
'SQL SECURITY' => array(
6,
'var',
],
'LANGUAGE' => [
),
'LANGUAGE' => array(
7,
'var',
],
'COMMENT' => [
),
'COMMENT' => array(
8,
'var',
],
),
'CREATE' => 1,
'DETERMINISTIC' => 2,
'DATA' => 5,
];
'DATA' => 5,
);
/**
* All trigger options.
*
* @var array
*/
public static $TRIGGER_OPTIONS = [
public static $TRIGGER_OPTIONS = array(
'BEFORE' => 1,
'AFTER' => 1,
'INSERT' => 2,
'UPDATE' => 2,
'DELETE' => 2,
];
'DELETE' => 2
);
/**
* The name of the entity that is created.
@@ -292,11 +292,11 @@ class CreateStatement extends Statement
*
* Used by `CREATE TABLE`, `CREATE FUNCTION` and `CREATE PROCEDURE`.
*
* @var OptionsArray
*
* @see static::$TABLE_OPTIONS
* @see static::$FUNC_OPTIONS
* @see static::$TRIGGER_OPTIONS
*
* @var OptionsArray
*/
public $entityOptions;
@@ -398,7 +398,7 @@ class CreateStatement extends Statement
*
* @var Token[]|string
*/
public $body = [];
public $body = array();
/**
* @return string
@@ -413,63 +413,53 @@ class CreateStatement extends Statement
$fields = ArrayObj::build($this->fields);
}
}
if ($this->options->has('DATABASE') || $this->options->has('SCHEMA')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. OptionsArray::build($this->entityOptions);
}
if ($this->options->has('TABLE')) {
if ($this->select !== null) {
} elseif ($this->options->has('TABLE')) {
if (! is_null($this->select)) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $this->select->build();
}
if ($this->like !== null) {
} elseif (! is_null($this->like)) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' LIKE '
. Expression::build($this->like);
} else {
$partition = '';
if (! empty($this->partitionBy)) {
$partition .= "\nPARTITION BY " . $this->partitionBy;
}
if (! empty($this->partitionsNum)) {
$partition .= "\nPARTITIONS " . $this->partitionsNum;
}
if (! empty($this->subpartitionBy)) {
$partition .= "\nSUBPARTITION BY " . $this->subpartitionBy;
}
if (! empty($this->subpartitionsNum)) {
$partition .= "\nSUBPARTITIONS " . $this->subpartitionsNum;
}
if (! empty($this->partitions)) {
$partition .= "\n" . PartitionDefinition::build($this->partitions);
}
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $fields
. OptionsArray::build($this->entityOptions)
. $partition;
}
$partition = '';
if (! empty($this->partitionBy)) {
$partition .= "\nPARTITION BY " . $this->partitionBy;
}
if (! empty($this->partitionsNum)) {
$partition .= "\nPARTITIONS " . $this->partitionsNum;
}
if (! empty($this->subpartitionBy)) {
$partition .= "\nSUBPARTITION BY " . $this->subpartitionBy;
}
if (! empty($this->subpartitionsNum)) {
$partition .= "\nSUBPARTITIONS " . $this->subpartitionsNum;
}
if (! empty($this->partitions)) {
$partition .= "\n" . PartitionDefinition::build($this->partitions);
}
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $fields
. OptionsArray::build($this->entityOptions)
. $partition;
} elseif ($this->options->has('VIEW')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $fields . ' AS ' . ($this->select ? $this->select->build() : '')
. (! empty($this->body) ? TokensList::build($this->body) : '') . ' '
. $fields . ' AS ' . ($this->select ? $this->select->build() : '') . (! empty($this->body) ? TokensList::build($this->body) : '') . ' '
. OptionsArray::build($this->entityOptions);
} elseif ($this->options->has('TRIGGER')) {
return 'CREATE '
@@ -478,7 +468,9 @@ class CreateStatement extends Statement
. OptionsArray::build($this->entityOptions) . ' '
. 'ON ' . Expression::build($this->table) . ' '
. 'FOR EACH ROW ' . TokensList::build($this->body);
} elseif ($this->options->has('PROCEDURE') || $this->options->has('FUNCTION')) {
} elseif ($this->options->has('PROCEDURE')
|| $this->options->has('FUNCTION')
) {
$tmp = '';
if ($this->options->has('FUNCTION')) {
$tmp = 'RETURNS ' . DataType::build($this->return);
@@ -488,7 +480,7 @@ class CreateStatement extends Statement
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. ParameterDefinition::build($this->parameters) . ' '
. $tmp . ' ' . OptionsArray::build($this->entityOptions) . ' '
. $tmp . ' ' . OptionsArray::build($this->entityOptions) . ' '
. TokensList::build($this->body);
}
@@ -517,14 +509,17 @@ class CreateStatement extends Statement
$this->name = Expression::parse(
$parser,
$list,
[
array(
'parseField' => $fieldName,
'breakOnAlias' => true,
]
'breakOnAlias' => true
)
);
if (! isset($this->name) || ($this->name === '')) {
$parser->error('The name of the entity was expected.', $list->tokens[$list->idx]);
$parser->error(
'The name of the entity was expected.',
$list->tokens[$list->idx]
);
} else {
++$list->idx; // Skipping field.
}
@@ -541,43 +536,56 @@ class CreateStatement extends Statement
}
if ($isDatabase) {
$this->entityOptions = OptionsArray::parse($parser, $list, static::$DB_OPTIONS);
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$DB_OPTIONS
);
} elseif ($this->options->has('TABLE')) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->keyword === 'SELECT')) {
if (($token->type === Token::TYPE_KEYWORD)
&& ($token->keyword === 'SELECT')) {
/* CREATE TABLE ... SELECT */
$this->select = new SelectStatement($parser, $list);
} elseif (
($token->type === Token::TYPE_KEYWORD) && ($token->keyword === 'AS')
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->keyword === 'AS')
&& ($list->tokens[$nextidx]->type === Token::TYPE_KEYWORD)
&& ($list->tokens[$nextidx]->value === 'SELECT')
) {
&& ($list->tokens[$nextidx]->value === 'SELECT')) {
/* CREATE TABLE ... AS SELECT */
$list->idx = $nextidx;
$this->select = new SelectStatement($parser, $list);
} elseif ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'LIKE') {
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->keyword === 'LIKE') {
/* CREATE TABLE `new_tbl` LIKE 'orig_tbl' */
$list->idx = $nextidx;
$this->like = Expression::parse(
$parser,
$list,
[
array(
'parseField' => 'table',
'breakOnAlias' => true,
]
'breakOnAlias' => true
)
);
// The 'LIKE' keyword was found, but no table_name was found next to it
if ($this->like === null) {
$parser->error('A table name was expected.', $list->tokens[$list->idx]);
if (is_null($this->like)) {
$parser->error(
'A table name was expected.',
$list->tokens[$list->idx]
);
}
} else {
$this->fields = CreateDefinition::parse($parser, $list);
if (empty($this->fields)) {
$parser->error('At least one column definition was expected.', $list->tokens[$list->idx]);
$parser->error(
'At least one column definition was expected.',
$list->tokens[$list->idx]
);
}
++$list->idx;
$this->entityOptions = OptionsArray::parse($parser, $list, static::$TABLE_OPTIONS);
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$TABLE_OPTIONS
);
/**
* The field that is being filled (`partitionBy` or
@@ -642,14 +650,14 @@ class CreateStatement extends Statement
// This is used instead of `++$brackets` because,
// initially, `$brackets` is `false` cannot be
// incremented.
$brackets += 1;
$brackets = $brackets + 1;
} elseif ($token->value === ')') {
--$brackets;
}
}
// Building the expression used for partitioning.
$this->$field .= $token->type === Token::TYPE_WHITESPACE ? ' ' : $token->token;
$this->$field .= ($token->type === Token::TYPE_WHITESPACE) ? ' ' : $token->token;
// Last bracket was read, the expression ended.
// Comparing with `0` and not `false`, because `false` means
@@ -664,30 +672,42 @@ class CreateStatement extends Statement
$this->partitions = ArrayObj::parse(
$parser,
$list,
['type' => 'PhpMyAdmin\\SqlParser\\Components\\PartitionDefinition']
array(
'type' => 'PhpMyAdmin\\SqlParser\\Components\\PartitionDefinition'
)
);
}
break;
}
}
}
} elseif ($this->options->has('PROCEDURE') || $this->options->has('FUNCTION')) {
} elseif ($this->options->has('PROCEDURE')
|| $this->options->has('FUNCTION')
) {
$this->parameters = ParameterDefinition::parse($parser, $list);
if ($this->options->has('FUNCTION')) {
$prevToken = $token;
$prev_token = $token;
$token = $list->getNextOfType(Token::TYPE_KEYWORD);
if ($token === null || $token->keyword !== 'RETURNS') {
$parser->error('A "RETURNS" keyword was expected.', $token ?? $prevToken);
if (is_null($token) || $token->keyword !== 'RETURNS') {
$parser->error(
'A "RETURNS" keyword was expected.',
is_null($token) ? $prev_token : $token
);
} else {
++$list->idx;
$this->return = DataType::parse($parser, $list);
$this->return = DataType::parse(
$parser,
$list
);
}
}
++$list->idx;
$this->entityOptions = OptionsArray::parse($parser, $list, static::$FUNC_OPTIONS);
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$FUNC_OPTIONS
);
++$list->idx;
for (; $list->idx < $list->count; ++$list->idx) {
@@ -716,19 +736,21 @@ class CreateStatement extends Statement
$list->idx = $nextidx;
$this->select = new SelectStatement($parser, $list);
}
// Parsing all other tokens
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
$this->body[] = $token;
}
} elseif ($this->options->has('TRIGGER')) {
// Parsing the time and the event.
$this->entityOptions = OptionsArray::parse($parser, $list, static::$TRIGGER_OPTIONS);
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$TRIGGER_OPTIONS
);
++$list->idx;
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'ON');
@@ -738,10 +760,10 @@ class CreateStatement extends Statement
$this->table = Expression::parse(
$parser,
$list,
[
array(
'parseField' => 'table',
'breakOnAlias' => true,
]
'breakOnAlias' => true
)
);
++$list->idx;
@@ -758,7 +780,6 @@ class CreateStatement extends Statement
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
$this->body[] = $token;
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `DELETE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\ArrayObj;
@@ -20,10 +19,6 @@ use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function count;
use function stripos;
use function strlen;
/**
* `DELETE` statement.
*
@@ -46,6 +41,11 @@ use function strlen;
* FROM tbl_name[.*] [, tbl_name[.*]] ...
* USING table_references
* [WHERE where_condition]
*
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class DeleteStatement extends Statement
{
@@ -54,11 +54,11 @@ class DeleteStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'QUICK' => 2,
'IGNORE' => 3,
];
'IGNORE' => 3
);
/**
* The clauses of this statement, in order.
@@ -67,41 +67,41 @@ class DeleteStatement extends Statement
*
* @var array
*/
public static $CLAUSES = [
'DELETE' => [
public static $CLAUSES = array(
'DELETE' => array(
'DELETE',
2,
],
),
// Used for options.
'_OPTIONS' => [
'_OPTIONS' => array(
'_OPTIONS',
1,
],
'FROM' => [
),
'FROM' => array(
'FROM',
3,
],
'PARTITION' => [
),
'PARTITION' => array(
'PARTITION',
3,
],
'USING' => [
),
'USING' => array(
'USING',
3,
],
'WHERE' => [
),
'WHERE' => array(
'WHERE',
3,
],
'ORDER BY' => [
),
'ORDER BY' => array(
'ORDER BY',
3,
],
'LIMIT' => [
),
'LIMIT' => array(
'LIMIT',
3,
],
];
)
);
/**
* Table(s) used as sources for this statement.
@@ -166,31 +166,25 @@ class DeleteStatement extends Statement
{
$ret = 'DELETE ' . OptionsArray::build($this->options);
if ($this->columns !== null && count($this->columns) > 0) {
if (! is_null($this->columns) && count($this->columns) > 0) {
$ret .= ' ' . ExpressionArray::build($this->columns);
}
if ($this->from !== null && count($this->from) > 0) {
if (! is_null($this->from) && count($this->from) > 0) {
$ret .= ' FROM ' . ExpressionArray::build($this->from);
}
if ($this->join !== null && count($this->join) > 0) {
if (! is_null($this->join) && count($this->join) > 0) {
$ret .= ' ' . JoinKeyword::build($this->join);
}
if ($this->using !== null && count($this->using) > 0) {
if (! is_null($this->using) && count($this->using) > 0) {
$ret .= ' USING ' . ExpressionArray::build($this->using);
}
if ($this->where !== null && count($this->where) > 0) {
if (! is_null($this->where) && count($this->where) > 0) {
$ret .= ' WHERE ' . Condition::build($this->where);
}
if ($this->order !== null && count($this->order) > 0) {
if (! is_null($this->order) && count($this->order) > 0) {
$ret .= ' ORDER BY ' . ExpressionArray::build($this->order);
}
if ($this->limit !== null && strlen((string) $this->limit) > 0) {
if (! is_null($this->limit) && strlen($this->limit) > 0) {
$ret .= ' LIMIT ' . Limit::build($this->limit);
}
@@ -206,7 +200,11 @@ class DeleteStatement extends Statement
++$list->idx; // Skipping `DELETE`.
// parse any options if provided
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
++$list->idx;
/**
@@ -251,31 +249,31 @@ class DeleteStatement extends Statement
if ($token->keyword !== 'FROM') {
$parser->error('Unexpected keyword.', $token);
break;
} else {
++$list->idx; // Skip 'FROM'
$this->from = ExpressionArray::parse($parser, $list);
$state = 2;
}
++$list->idx; // Skip 'FROM'
$this->from = ExpressionArray::parse($parser, $list);
$state = 2;
} else {
$this->columns = ExpressionArray::parse($parser, $list);
$state = 1;
}
} elseif ($state === 1) {
if ($token->type !== Token::TYPE_KEYWORD) {
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->keyword !== 'FROM') {
$parser->error('Unexpected keyword.', $token);
break;
} else {
++$list->idx; // Skip 'FROM'
$this->from = ExpressionArray::parse($parser, $list);
$state = 2;
}
} else {
$parser->error('Unexpected token.', $token);
break;
}
if ($token->keyword !== 'FROM') {
$parser->error('Unexpected keyword.', $token);
break;
}
++$list->idx; // Skip 'FROM'
$this->from = ExpressionArray::parse($parser, $list);
$state = 2;
} elseif ($state === 2) {
if ($token->type === Token::TYPE_KEYWORD) {
if (stripos($token->keyword, 'JOIN') !== false) {
@@ -314,22 +312,27 @@ class DeleteStatement extends Statement
}
}
} elseif ($state === 3) {
if ($token->type !== Token::TYPE_KEYWORD) {
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->keyword === 'WHERE') {
++$list->idx; // Skip 'WHERE'
$this->where = Condition::parse($parser, $list);
$state = 4;
} else {
$parser->error('Unexpected keyword.', $token);
break;
}
} else {
$parser->error('Unexpected token.', $token);
break;
}
if ($token->keyword !== 'WHERE') {
$parser->error('Unexpected keyword.', $token);
break;
}
++$list->idx; // Skip 'WHERE'
$this->where = Condition::parse($parser, $list);
$state = 4;
} elseif ($state === 4) {
if ($multiTable === true && $token->type === Token::TYPE_KEYWORD) {
$parser->error('This type of clause is not valid in Multi-table queries.', $token);
if ($multiTable === true
&& $token->type === Token::TYPE_KEYWORD
) {
$parser->error(
'This type of clause is not valid in Multi-table queries.',
$token
);
break;
}
@@ -352,23 +355,23 @@ class DeleteStatement extends Statement
}
} elseif ($state === 5) {
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->keyword !== 'LIMIT') {
if ($token->keyword === 'LIMIT') {
++$list->idx; // Skip 'LIMIT'
$this->limit = Limit::parse($parser, $list);
$state = 6;
} else {
$parser->error('Unexpected keyword.', $token);
break;
}
++$list->idx; // Skip 'LIMIT'
$this->limit = Limit::parse($parser, $list);
$state = 6;
}
}
}
if ($state >= 2) {
foreach ($this->from as $fromExpr) {
$fromExpr->database = $fromExpr->table;
$fromExpr->table = $fromExpr->column;
$fromExpr->column = null;
foreach ($this->from as $from_expr) {
$from_expr->database = $from_expr->table;
$from_expr->table = $from_expr->column;
$from_expr->column = null;
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `DROP` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Expression;
@@ -12,6 +11,10 @@ use PhpMyAdmin\SqlParser\Statement;
/**
* `DROP` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class DropStatement extends Statement
{
@@ -20,7 +23,7 @@ class DropStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'DATABASE' => 1,
'EVENT' => 1,
'FUNCTION' => 1,
@@ -36,8 +39,8 @@ class DropStatement extends Statement
'USER' => 1,
'TEMPORARY' => 2,
'IF EXISTS' => 3,
];
'IF EXISTS' => 3
);
/**
* The clauses of this statement, in order.
@@ -46,26 +49,26 @@ class DropStatement extends Statement
*
* @var array
*/
public static $CLAUSES = [
'DROP' => [
public static $CLAUSES = array(
'DROP' => array(
'DROP',
2,
],
),
// Used for options.
'_OPTIONS' => [
'_OPTIONS' => array(
'_OPTIONS',
1,
],
),
// Used for select expressions.
'DROP_' => [
'DROP_' => array(
'DROP',
1,
],
'ON' => [
),
'ON' => array(
'ON',
3,
],
];
)
);
/**
* Dropped elements.
@@ -1,14 +1,17 @@
<?php
/**
* `EXPLAIN` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
/**
* `EXPLAIN` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ExplainStatement extends NotImplementedStatement
{
@@ -1,14 +1,13 @@
<?php
/**
* `INSERT` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Array2d;
use PhpMyAdmin\SqlParser\Components\ArrayObj;
use PhpMyAdmin\SqlParser\Components\Array2d;
use PhpMyAdmin\SqlParser\Components\IntoKeyword;
use PhpMyAdmin\SqlParser\Components\OptionsArray;
use PhpMyAdmin\SqlParser\Components\SetOperation;
@@ -17,10 +16,6 @@ use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function count;
use function strlen;
use function trim;
/**
* `INSERT` statement.
*
@@ -53,6 +48,10 @@ use function trim;
* [ ON DUPLICATE KEY UPDATE
* col_name=expr
* [, col_name=expr] ... ]
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class InsertStatement extends Statement
{
@@ -61,12 +60,12 @@ class InsertStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'DELAYED' => 2,
'HIGH_PRIORITY' => 3,
'IGNORE' => 4,
];
'IGNORE' => 4
);
/**
* Tables used as target for this statement.
@@ -114,15 +113,15 @@ class InsertStatement extends Statement
$ret = 'INSERT ' . $this->options;
$ret = trim($ret) . ' INTO ' . $this->into;
if ($this->values !== null && count($this->values) > 0) {
if (! is_null($this->values) && count($this->values) > 0) {
$ret .= ' VALUES ' . Array2d::build($this->values);
} elseif ($this->set !== null && count($this->set) > 0) {
} elseif (! is_null($this->set) && count($this->set) > 0) {
$ret .= ' SET ' . SetOperation::build($this->set);
} elseif ($this->select !== null && strlen((string) $this->select) > 0) {
} elseif (! is_null($this->select) && strlen($this->select) > 0) {
$ret .= ' ' . $this->select->build();
}
if ($this->onDuplicateSet !== null && count($this->onDuplicateSet) > 0) {
if (! is_null($this->onDuplicateSet) && count($this->onDuplicateSet) > 0) {
$ret .= ' ON DUPLICATE KEY UPDATE ' . SetOperation::build($this->onDuplicateSet);
}
@@ -138,7 +137,11 @@ class InsertStatement extends Statement
++$list->idx; // Skipping `INSERT`.
// parse any options if provided
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
++$list->idx;
/**
@@ -181,7 +184,9 @@ class InsertStatement extends Statement
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD && $token->keyword !== 'INTO') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->keyword !== 'INTO'
) {
$parser->error('Unexpected keyword.', $token);
break;
}
@@ -190,33 +195,40 @@ class InsertStatement extends Statement
$this->into = IntoKeyword::parse(
$parser,
$list,
['fromInsert' => true]
array('fromInsert' => true)
);
$state = 1;
} elseif ($state === 1) {
if ($token->type !== Token::TYPE_KEYWORD) {
$parser->error('Unexpected token.', $token);
break;
}
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->keyword === 'VALUE'
|| $token->keyword === 'VALUES'
) {
++$list->idx; // skip VALUES
if ($token->keyword === 'VALUE' || $token->keyword === 'VALUES') {
++$list->idx; // skip VALUES
$this->values = Array2d::parse($parser, $list);
} elseif ($token->keyword === 'SET') {
++$list->idx; // skip SET
$this->values = Array2d::parse($parser, $list);
} elseif ($token->keyword === 'SET') {
++$list->idx; // skip SET
$this->set = SetOperation::parse($parser, $list);
} elseif ($token->keyword === 'SELECT') {
$this->select = new SelectStatement($parser, $list);
$this->set = SetOperation::parse($parser, $list);
} elseif ($token->keyword === 'SELECT') {
$this->select = new SelectStatement($parser, $list);
} else {
$parser->error(
'Unexpected keyword.',
$token
);
break;
}
$state = 2;
$miniState = 1;
} else {
$parser->error('Unexpected keyword.', $token);
$parser->error(
'Unexpected token.',
$token
);
break;
}
$state = 2;
$miniState = 1;
} elseif ($state === 2) {
$lastCount = $miniState;
@@ -231,7 +243,10 @@ class InsertStatement extends Statement
}
if ($lastCount === $miniState) {
$parser->error('Unexpected token.', $token);
$parser->error(
'Unexpected token.',
$token
);
break;
}
@@ -1,10 +1,9 @@
<?php
/**
* `LOAD` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\ArrayObj;
@@ -17,10 +16,6 @@ use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function count;
use function strlen;
use function trim;
/**
* `LOAD` statement.
*
@@ -41,6 +36,11 @@ use function trim;
* [IGNORE number {LINES | ROWS}]
* [(col_name_or_user_var,...)]
* [SET col_name = expr,...]
*
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class LoadStatement extends Statement
{
@@ -49,48 +49,48 @@ class LoadStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'CONCURRENT' => 1,
'LOCAL' => 2,
];
'LOCAL' => 2
);
/**
* FIELDS/COLUMNS Options for `LOAD DATA...INFILE` statements.
*
* @var array
*/
public static $FIELDS_OPTIONS = [
'TERMINATED BY' => [
public static $FIELDS_OPTIONS = array(
'TERMINATED BY' => array(
1,
'expr',
],
),
'OPTIONALLY' => 2,
'ENCLOSED BY' => [
'ENCLOSED BY' => array(
3,
'expr',
],
'ESCAPED BY' => [
),
'ESCAPED BY' => array(
4,
'expr',
],
];
)
);
/**
* LINES Options for `LOAD DATA...INFILE` statements.
*
* @var array
*/
public static $LINES_OPTIONS = [
'STARTING BY' => [
public static $LINES_OPTIONS = array(
'STARTING BY' => array(
1,
'expr',
],
'TERMINATED BY' => [
),
'TERMINATED BY' => array(
2,
'expr',
],
];
)
);
/**
* File name being used to load data.
@@ -123,9 +123,9 @@ class LoadStatement extends Statement
/**
* Options for FIELDS/COLUMNS keyword.
*
* @see static::$FIELDS_OPTIONS
*
* @var OptionsArray
*
* @see static::$FIELDS_OPTIONS
*/
public $fields_options;
@@ -139,9 +139,9 @@ class LoadStatement extends Statement
/**
* Options for OPTIONS keyword.
*
* @see static::$LINES_OPTIONS
*
* @var OptionsArray
*
* @see static::$LINES_OPTIONS
*/
public $lines_options;
@@ -194,7 +194,7 @@ class LoadStatement extends Statement
$ret .= ' INTO TABLE ' . $this->table;
if ($this->partition !== null && strlen((string) $this->partition) > 0) {
if ($this->partition !== null && strlen($this->partition) > 0) {
$ret .= ' PARTITION ' . ArrayObj::build($this->partition);
}
@@ -206,7 +206,7 @@ class LoadStatement extends Statement
$ret .= ' ' . $this->fields_keyword . ' ' . $this->fields_options;
}
if ($this->lines_options !== null && strlen((string) $this->lines_options) > 0) {
if ($this->lines_options !== null && strlen($this->lines_options) > 0) {
$ret .= ' LINES ' . $this->lines_options;
}
@@ -234,7 +234,11 @@ class LoadStatement extends Statement
++$list->idx; // Skipping `LOAD DATA`.
// parse any options if provided
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
++$list->idx;
/**
@@ -263,12 +267,12 @@ class LoadStatement extends Statement
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD && $token->keyword !== 'INFILE') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->keyword !== 'INFILE'
) {
$parser->error('Unexpected keyword.', $token);
break;
}
if ($token->type !== Token::TYPE_KEYWORD) {
} elseif ($token->type !== Token::TYPE_KEYWORD) {
$parser->error('Unexpected token.', $token);
break;
}
@@ -277,34 +281,43 @@ class LoadStatement extends Statement
$this->file_name = Expression::parse(
$parser,
$list,
['parseField' => 'file']
array('parseField' => 'file')
);
$state = 1;
} elseif ($state === 1) {
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->keyword === 'REPLACE' || $token->keyword === 'IGNORE') {
if ($token->keyword === 'REPLACE'
|| $token->keyword === 'IGNORE') {
$this->replace_ignore = trim($token->keyword);
} elseif ($token->keyword === 'INTO') {
$state = 2;
}
}
} elseif ($state === 2) {
if ($token->type !== Token::TYPE_KEYWORD || $token->keyword !== 'TABLE') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->keyword === 'TABLE'
) {
++$list->idx;
$this->table = Expression::parse($parser, $list, array('parseField' => 'table'));
$state = 3;
} else {
$parser->error('Unexpected token.', $token);
break;
}
++$list->idx;
$this->table = Expression::parse($parser, $list, ['parseField' => 'table']);
$state = 3;
} elseif ($state >= 3 && $state <= 7) {
if ($token->type === Token::TYPE_KEYWORD) {
$newState = $this->parseKeywordsAccordingToState($parser, $list, $state);
$newState = $this->parseKeywordsAccordingToState(
$parser,
$list,
$state
);
if ($newState === $state) {
// Avoid infinite loop
break;
}
} elseif ($token->type === Token::TYPE_OPERATOR && $token->token === '(') {
} elseif ($token->type === Token::TYPE_OPERATOR
&& $token->token === '('
) {
$this->col_name_or_user_var
= ExpressionArray::parse($parser, $list);
$state = 7;
@@ -318,33 +331,29 @@ class LoadStatement extends Statement
--$list->idx;
}
/**
* @param Parser $parser The parser
* @param TokensList $list A token list
* @param string $keyword The keyword
*/
public function parseFileOptions(Parser $parser, TokensList $list, $keyword = 'FIELDS'): void
public function parseFileOptions(Parser $parser, TokensList $list, $keyword = 'FIELDS')
{
++$list->idx;
if ($keyword === 'FIELDS' || $keyword === 'COLUMNS') {
// parse field options
$this->fields_options = OptionsArray::parse($parser, $list, static::$FIELDS_OPTIONS);
$this->fields_options = OptionsArray::parse(
$parser,
$list,
static::$FIELDS_OPTIONS
);
$this->fields_keyword = $keyword;
} else {
// parse line options
$this->lines_options = OptionsArray::parse($parser, $list, static::$LINES_OPTIONS);
$this->lines_options = OptionsArray::parse(
$parser,
$list,
static::$LINES_OPTIONS
);
}
}
/**
* @param Parser $parser
* @param TokensList $list
* @param int $state
*
* @return int
*/
public function parseKeywordsAccordingToState($parser, $list, $state)
{
$token = $list->tokens[$list->idx];
@@ -354,27 +363,30 @@ class LoadStatement extends Statement
if ($token->keyword === 'PARTITION') {
++$list->idx;
$this->partition = ArrayObj::parse($parser, $list);
$state = 4;
return 4;
return $state;
}
// no break
case 4:
if ($token->keyword === 'CHARACTER SET') {
++$list->idx;
$this->charset_name = Expression::parse($parser, $list);
$state = 5;
return 5;
return $state;
}
// no break
case 5:
if ($token->keyword === 'FIELDS' || $token->keyword === 'COLUMNS' || $token->keyword === 'LINES') {
if ($token->keyword === 'FIELDS'
|| $token->keyword === 'COLUMNS'
|| $token->keyword === 'LINES'
) {
$this->parseFileOptions($parser, $list, $token->value);
$state = 6;
return 6;
return $state;
}
// no break
case 6:
if ($token->keyword === 'IGNORE') {
@@ -383,26 +395,25 @@ class LoadStatement extends Statement
$this->ignore_number = Expression::parse($parser, $list);
$nextToken = $list->getNextOfType(Token::TYPE_KEYWORD);
if (
$nextToken->type === Token::TYPE_KEYWORD
if ($nextToken->type === Token::TYPE_KEYWORD
&& (($nextToken->keyword === 'LINES')
|| ($nextToken->keyword === 'ROWS'))
) {
$this->lines_rows = $nextToken->token;
}
$state = 7;
return 7;
return $state;
}
// no break
case 7:
if ($token->keyword === 'SET') {
++$list->idx;
$this->set = SetOperation::parse($parser, $list);
$state = 8;
return 8;
return $state;
}
// no break
default:
}
@@ -1,10 +1,9 @@
<?php
/**
* `LOCK` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\LockExpression;
@@ -13,10 +12,12 @@ use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function trim;
/**
* `LOCK` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class LockStatement extends Statement
{
@@ -25,13 +26,11 @@ class LockStatement extends Statement
*
* @var LockExpression[]
*/
public $locked = [];
public $locked = array();
/**
* Whether it's a LOCK statement
* if false, it's an UNLOCK statement
*
* @var bool
*/
public $isLock = true;
@@ -45,7 +44,6 @@ class LockStatement extends Statement
// this is in fact an UNLOCK statement
$this->isLock = false;
}
++$list->idx; // Skipping `LOCK`.
/**
@@ -90,22 +88,18 @@ class LockStatement extends Statement
$parser->error('Unexpected keyword.', $token);
break;
}
$state = 1;
continue;
} else {
$parser->error('Unexpected token.', $token);
break;
}
$parser->error('Unexpected token.', $token);
break;
}
if ($state === 1) {
} elseif ($state === 1) {
if (! $this->isLock) {
// UNLOCK statement should not have any more tokens
$parser->error('Unexpected token.', $token);
break;
}
$this->locked[] = LockExpression::parse($parser, $list);
$state = 2;
} elseif ($state === 2) {
@@ -118,11 +112,9 @@ class LockStatement extends Statement
$prevToken = $token;
}
if ($state === 2 || $prevToken === null) {
return;
if ($state !== 2 && $prevToken != null) {
$parser->error('Unexpected end of LOCK statement.', $prevToken);
}
$parser->error('Unexpected end of LOCK statement.', $prevToken);
}
/**
@@ -1,10 +1,9 @@
<?php
/**
* Maintenance statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Expression;
@@ -19,6 +18,10 @@ use PhpMyAdmin\SqlParser\TokensList;
*
* They follow the syntax:
* STMT [some options] tbl_name [, tbl_name] ... [some more options]
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class MaintenanceStatement extends Statement
{
@@ -1,10 +1,9 @@
<?php
/**
* Not implemented (yet) statements.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Parser;
@@ -16,6 +15,10 @@ use PhpMyAdmin\SqlParser\TokensList;
* Not implemented (yet) statements.
*
* The `after` function makes the parser jump straight to the first delimiter.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class NotImplementedStatement extends Statement
{
@@ -24,7 +27,7 @@ class NotImplementedStatement extends Statement
*
* @var Token[]
*/
public $unknown = [];
public $unknown = array();
/**
* @return string
@@ -52,7 +55,6 @@ class NotImplementedStatement extends Statement
if ($list->tokens[$list->idx]->type === Token::TYPE_DELIMITER) {
break;
}
$this->unknown[] = $list->tokens[$list->idx];
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `OPTIMIZE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Expression;
@@ -15,6 +14,10 @@ use PhpMyAdmin\SqlParser\Statement;
*
* OPTIMIZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class OptimizeStatement extends Statement
{
@@ -23,12 +26,12 @@ class OptimizeStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
];
'LOCAL' => 3
);
/**
* Optimized tables.
@@ -1,26 +1,27 @@
<?php
/**
* `PURGE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Expression;
use PhpMyAdmin\SqlParser\Components\OptionsArray;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function in_array;
use function trim;
/**
* `PURGE` statement.
*
* PURGE { BINARY | MASTER } LOGS
* { TO 'log_name' | BEFORE datetime_expr }
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class PurgeStatement extends Statement
{
@@ -50,9 +51,8 @@ class PurgeStatement extends Statement
*/
public function build()
{
$ret = 'PURGE ' . $this->log_type . ' LOGS '
$ret = 'PURGE ' . $this->log_type . ' ' . 'LOGS '
. ($this->end_option !== null ? ($this->end_option . ' ' . $this->end_expr) : '');
return trim($ret);
}
@@ -71,7 +71,6 @@ class PurgeStatement extends Statement
*/
$state = 0;
$prevToken = null;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
@@ -93,58 +92,52 @@ class PurgeStatement extends Statement
switch ($state) {
case 0:
// parse `{ BINARY | MASTER }`
$this->log_type = self::parseExpectedKeyword($parser, $token, ['BINARY', 'MASTER']);
$this->log_type = self::parseExpectedKeyword($parser, $token, array('BINARY', 'MASTER'));
break;
case 1:
// parse `LOGS`
self::parseExpectedKeyword($parser, $token, ['LOGS']);
self::parseExpectedKeyword($parser, $token, array('LOGS'));
break;
case 2:
// parse `{ TO | BEFORE }`
$this->end_option = self::parseExpectedKeyword($parser, $token, ['TO', 'BEFORE']);
$this->end_option = self::parseExpectedKeyword($parser, $token, array('TO', 'BEFORE'));
break;
case 3:
// parse `expr`
$this->end_expr = Expression::parse($parser, $list, []);
$this->end_expr = Expression::parse($parser, $list, array());
break;
default:
$parser->error('Unexpected token.', $token);
break;
}
$state++;
$prevToken = $token;
}
// Only one possible end state
if ($state === 4) {
return;
if ($state != 4) {
$parser->error('Unexpected token.', $prevToken);
}
$parser->error('Unexpected token.', $prevToken);
}
/**
* Parse expected keyword (or throw relevant error)
*
* @param Parser $parser the instance that requests parsing
* @param Token $token token to be parsed
* @param array $expectedKeywords array of possibly expected keywords at this point
*
* @return mixed|null
* @param Parser $parser the instance that requests parsing
* @param Token $token token to be parsed
* @param Array $expected_keywords array of possibly expected keywords at this point
*/
private static function parseExpectedKeyword($parser, $token, $expectedKeywords)
private static function parseExpectedKeyword($parser, $token, $expected_keywords)
{
if ($token->type === Token::TYPE_KEYWORD) {
if (in_array($token->keyword, $expectedKeywords)) {
if (in_array($token->keyword, $expected_keywords)) {
return $token->keyword;
} else {
$parser->error('Unexpected keyword', $token);
}
$parser->error('Unexpected keyword', $token);
} else {
$parser->error('Unexpected token.', $token);
}
return null;
}
}
@@ -1,10 +1,9 @@
<?php
/**
* `RENAME` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\RenameOperation;
@@ -18,6 +17,10 @@ use PhpMyAdmin\SqlParser\TokensList;
*
* RENAME TABLE tbl_name TO new_tbl_name
* [, tbl_name2 TO new_tbl_name2] ...
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RenameStatement extends Statement
{
@@ -39,12 +42,10 @@ class RenameStatement extends Statement
*/
public function before(Parser $parser, TokensList $list, Token $token)
{
if (($token->type !== Token::TYPE_KEYWORD) || ($token->keyword !== 'RENAME')) {
return;
if (($token->type === Token::TYPE_KEYWORD) && ($token->keyword === 'RENAME')) {
// Checking if it is the beginning of the query.
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'TABLE');
}
// Checking if it is the beginning of the query.
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'TABLE');
}
/**
@@ -1,10 +1,9 @@
<?php
/**
* `REPAIR` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
/**
@@ -13,6 +12,10 @@ namespace PhpMyAdmin\SqlParser\Statements;
* REPAIR [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
* [QUICK] [EXTENDED] [USE_FRM]
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RepairStatement extends MaintenanceStatement
{
@@ -21,7 +24,7 @@ class RepairStatement extends MaintenanceStatement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
@@ -29,6 +32,6 @@ class RepairStatement extends MaintenanceStatement
'QUICK' => 4,
'EXTENDED' => 5,
'USE_FRM' => 6,
];
'USE_FRM' => 6
);
}
@@ -1,10 +1,9 @@
<?php
/**
* `REPLACE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Array2d;
@@ -16,10 +15,6 @@ use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function count;
use function strlen;
use function trim;
/**
* `REPLACE` statement.
*
@@ -40,6 +35,10 @@ use function trim;
* [PARTITION (partition_name,...)]
* [(col_name,...)]
* SELECT ...
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ReplaceStatement extends Statement
{
@@ -48,10 +47,10 @@ class ReplaceStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'DELAYED' => 1,
];
'DELAYED' => 1
);
/**
* Tables used as target for this statement.
@@ -91,11 +90,11 @@ class ReplaceStatement extends Statement
$ret = 'REPLACE ' . $this->options;
$ret = trim($ret) . ' INTO ' . $this->into;
if ($this->values !== null && count($this->values) > 0) {
if (! is_null($this->values) && count($this->values) > 0) {
$ret .= ' VALUES ' . Array2d::build($this->values);
} elseif ($this->set !== null && count($this->set) > 0) {
} elseif (! is_null($this->set) && count($this->set) > 0) {
$ret .= ' SET ' . SetOperation::build($this->set);
} elseif ($this->select !== null && strlen((string) $this->select) > 0) {
} elseif (! is_null($this->select) && strlen($this->select) > 0) {
$ret .= ' ' . $this->select->build();
}
@@ -111,7 +110,11 @@ class ReplaceStatement extends Statement
++$list->idx; // Skipping `REPLACE`.
// parse any options if provided
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
++$list->idx;
@@ -147,41 +150,49 @@ class ReplaceStatement extends Statement
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD && $token->keyword !== 'INTO') {
if ($token->type === Token::TYPE_KEYWORD
&& $token->keyword !== 'INTO'
) {
$parser->error('Unexpected keyword.', $token);
break;
}
++$list->idx;
$this->into = IntoKeyword::parse(
$parser,
$list,
['fromReplace' => true]
array('fromReplace' => true)
);
$state = 1;
} elseif ($state === 1) {
if ($token->type !== Token::TYPE_KEYWORD) {
$parser->error('Unexpected token.', $token);
break;
}
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->keyword === 'VALUE'
|| $token->keyword === 'VALUES'
) {
++$list->idx; // skip VALUES
if ($token->keyword === 'VALUE' || $token->keyword === 'VALUES') {
++$list->idx; // skip VALUES
$this->values = Array2d::parse($parser, $list);
} elseif ($token->keyword === 'SET') {
++$list->idx; // skip SET
$this->values = Array2d::parse($parser, $list);
} elseif ($token->keyword === 'SET') {
++$list->idx; // skip SET
$this->set = SetOperation::parse($parser, $list);
} elseif ($token->keyword === 'SELECT') {
$this->select = new SelectStatement($parser, $list);
$this->set = SetOperation::parse($parser, $list);
} elseif ($token->keyword === 'SELECT') {
$this->select = new SelectStatement($parser, $list);
} else {
$parser->error(
'Unexpected keyword.',
$token
);
break;
}
$state = 2;
} else {
$parser->error('Unexpected keyword.', $token);
$parser->error(
'Unexpected token.',
$token
);
break;
}
$state = 2;
}
}
@@ -1,16 +1,19 @@
<?php
/**
* `RESTORE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
/**
* `RESTORE` statement.
*
* RESTORE TABLE tbl_name [, tbl_name] ... FROM '/path/to/backup/directory'
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RestoreStatement extends MaintenanceStatement
{
@@ -19,12 +22,12 @@ class RestoreStatement extends MaintenanceStatement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'TABLE' => 1,
'FROM' => [
'FROM' => array(
2,
'var',
],
];
)
);
}
@@ -1,23 +1,22 @@
<?php
/**
* `SELECT` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\ArrayObj;
use PhpMyAdmin\SqlParser\Components\Condition;
use PhpMyAdmin\SqlParser\Components\Expression;
use PhpMyAdmin\SqlParser\Components\FunctionCall;
use PhpMyAdmin\SqlParser\Components\GroupKeyword;
use PhpMyAdmin\SqlParser\Components\IndexHint;
use PhpMyAdmin\SqlParser\Components\IntoKeyword;
use PhpMyAdmin\SqlParser\Components\JoinKeyword;
use PhpMyAdmin\SqlParser\Components\Limit;
use PhpMyAdmin\SqlParser\Components\OptionsArray;
use PhpMyAdmin\SqlParser\Components\OrderKeyword;
use PhpMyAdmin\SqlParser\Components\GroupKeyword;
use PhpMyAdmin\SqlParser\Statement;
/**
@@ -35,10 +34,10 @@ use PhpMyAdmin\SqlParser\Statement;
* [PARTITION partition_list]
* [WHERE where_condition]
* [GROUP BY {col_name | expr | position}
* [ASC | DESC], ... [WITH ROLLUP]]
* [ASC | DESC), ... [WITH ROLLUP]]
* [HAVING where_condition]
* [ORDER BY {col_name | expr | position}
* [ASC | DESC], ...]
* [ASC | DESC), ...]
* [LIMIT {[offset,] row_count | row_count OFFSET offset}]
* [PROCEDURE procedure_name(argument_list)]
* [INTO OUTFILE 'file_name'
@@ -47,6 +46,10 @@ use PhpMyAdmin\SqlParser\Statement;
* | INTO DUMPFILE 'file_name'
* | INTO var_name [, var_name]]
* [FOR UPDATE | LOCK IN SHARE MODE]]
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class SelectStatement extends Statement
{
@@ -55,29 +58,28 @@ class SelectStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'ALL' => 1,
'DISTINCT' => 1,
'DISTINCTROW' => 1,
'HIGH_PRIORITY' => 2,
'MAX_STATEMENT_TIME' => [
'MAX_STATEMENT_TIME' => array(
3,
'var=',
],
),
'STRAIGHT_JOIN' => 4,
'SQL_SMALL_RESULT' => 5,
'SQL_BIG_RESULT' => 6,
'SQL_BUFFER_RESULT' => 7,
'SQL_CACHE' => 8,
'SQL_NO_CACHE' => 8,
'SQL_CALC_FOUND_ROWS' => 9,
];
'SQL_CALC_FOUND_ROWS' => 9
);
/** @var array<string,int> */
public static $END_OPTIONS = [
public static $END_OPTIONS = array(
'FOR UPDATE' => 1,
'LOCK IN SHARE MODE' => 1,
];
'LOCK IN SHARE MODE' => 1
);
/**
* The clauses of this statement, in order.
@@ -86,153 +88,153 @@ class SelectStatement extends Statement
*
* @var array
*/
public static $CLAUSES = [
'SELECT' => [
public static $CLAUSES = array(
'SELECT' => array(
'SELECT',
2,
],
),
// Used for options.
'_OPTIONS' => [
'_OPTIONS' => array(
'_OPTIONS',
1,
],
),
// Used for selected expressions.
'_SELECT' => [
'_SELECT' => array(
'SELECT',
1,
],
'INTO' => [
),
'INTO' => array(
'INTO',
3,
],
'FROM' => [
),
'FROM' => array(
'FROM',
3,
],
'FORCE' => [
),
'FORCE' => array(
'FORCE',
1,
],
'USE' => [
),
'USE' => array(
'USE',
1,
],
'IGNORE' => [
),
'IGNORE' => array(
'IGNORE',
3,
],
'PARTITION' => [
),
'PARTITION' => array(
'PARTITION',
3,
],
),
'JOIN' => [
'JOIN' => array(
'JOIN',
1,
],
'FULL JOIN' => [
),
'FULL JOIN' => array(
'FULL JOIN',
1,
],
'INNER JOIN' => [
),
'INNER JOIN' => array(
'INNER JOIN',
1,
],
'LEFT JOIN' => [
),
'LEFT JOIN' => array(
'LEFT JOIN',
1,
],
'LEFT OUTER JOIN' => [
),
'LEFT OUTER JOIN' => array(
'LEFT OUTER JOIN',
1,
],
'RIGHT JOIN' => [
),
'RIGHT JOIN' => array(
'RIGHT JOIN',
1,
],
'RIGHT OUTER JOIN' => [
),
'RIGHT OUTER JOIN' => array(
'RIGHT OUTER JOIN',
1,
],
'NATURAL JOIN' => [
),
'NATURAL JOIN' => array(
'NATURAL JOIN',
1,
],
'NATURAL LEFT JOIN' => [
),
'NATURAL LEFT JOIN' => array(
'NATURAL LEFT JOIN',
1,
],
'NATURAL RIGHT JOIN' => [
),
'NATURAL RIGHT JOIN' => array(
'NATURAL RIGHT JOIN',
1,
],
'NATURAL LEFT OUTER JOIN' => [
),
'NATURAL LEFT OUTER JOIN' => array(
'NATURAL LEFT OUTER JOIN',
1,
],
'NATURAL RIGHT OUTER JOIN' => [
),
'NATURAL RIGHT OUTER JOIN' => array(
'NATURAL RIGHT JOIN',
1,
],
),
'WHERE' => [
'WHERE' => array(
'WHERE',
3,
],
'GROUP BY' => [
),
'GROUP BY' => array(
'GROUP BY',
3,
],
'HAVING' => [
),
'HAVING' => array(
'HAVING',
3,
],
'ORDER BY' => [
),
'ORDER BY' => array(
'ORDER BY',
3,
],
'LIMIT' => [
),
'LIMIT' => array(
'LIMIT',
3,
],
'PROCEDURE' => [
),
'PROCEDURE' => array(
'PROCEDURE',
3,
],
'UNION' => [
),
'UNION' => array(
'UNION',
1,
],
'EXCEPT' => [
),
'EXCEPT' => array(
'EXCEPT',
1,
],
'INTERSECT' => [
),
'INTERSECT' => array(
'INTERSECT',
1,
],
'_END_OPTIONS' => [
),
'_END_OPTIONS' => array(
'_END_OPTIONS',
1,
],
),
// These are available only when `UNION` is present.
// 'ORDER BY' => ['ORDER BY', 3],
// 'LIMIT' => ['LIMIT', 3],
];
// 'ORDER BY' => array('ORDER BY', 3),
// 'LIMIT' => array('LIMIT', 3)
);
/**
* Expressions that are being selected by this statement.
*
* @var Expression[]
*/
public $expr = [];
public $expr = array();
/**
* Tables used as sources for this statement.
*
* @var Expression[]
*/
public $from = [];
public $from = array();
/**
* Index hints
@@ -309,14 +311,14 @@ class SelectStatement extends Statement
*
* @var SelectStatement[]
*/
public $union = [];
public $union = array();
/**
* The end options of this query.
*
* @see static::$END_OPTIONS
*
* @var OptionsArray
*
* @see static::$END_OPTIONS
*/
public $end_options;
@@ -333,14 +335,14 @@ class SelectStatement extends Statement
if (! empty($this->union)) {
$clauses = static::$CLAUSES;
unset($clauses['ORDER BY'], $clauses['LIMIT']);
$clauses['ORDER BY'] = [
$clauses['ORDER BY'] = array(
'ORDER BY',
3,
];
$clauses['LIMIT'] = [
3
);
$clauses['LIMIT'] = array(
'LIMIT',
3,
];
3
);
return $clauses;
}
@@ -1,20 +1,21 @@
<?php
/**
* `SET` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\OptionsArray;
use PhpMyAdmin\SqlParser\Components\SetOperation;
use PhpMyAdmin\SqlParser\Statement;
use function trim;
/**
* `SET` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class SetStatement extends Statement
{
@@ -25,39 +26,39 @@ class SetStatement extends Statement
*
* @var array
*/
public static $CLAUSES = [
'SET' => [
public static $CLAUSES = array(
'SET' => array(
'SET',
3,
],
'_END_OPTIONS' => [
3
),
'_END_OPTIONS' => array(
'_END_OPTIONS',
1,
],
];
1
)
);
/**
* Possible exceptions in SET statement.
* Possible exceptions in SET statment.
*
* @var array
*/
public static $OPTIONS = [
'CHARSET' => [
public static $OPTIONS = array(
'CHARSET' => array(
3,
'var',
],
'CHARACTER SET' => [
),
'CHARACTER SET' => array(
3,
'var',
],
'NAMES' => [
),
'NAMES' => array(
3,
'var',
],
'PASSWORD' => [
),
'PASSWORD' => array(
3,
'expr',
],
),
'SESSION' => 3,
'GLOBAL' => 3,
'PERSIST' => 3,
@@ -66,16 +67,15 @@ class SetStatement extends Statement
'@@GLOBAL' => 3,
'@@PERSIST' => 3,
'@@PERSIST_ONLY' => 3,
];
);
/** @var array */
public static $END_OPTIONS = [
'COLLATE' => [
public static $END_OPTIONS = array(
'COLLATE' => array(
1,
'var',
],
'DEFAULT' => 1,
];
),
'DEFAULT' => 1
);
/**
* Options used in current statement.
@@ -87,9 +87,9 @@ class SetStatement extends Statement
/**
* The end options of this query.
*
* @see static::$END_OPTIONS
*
* @var OptionsArray
*
* @see static::$END_OPTIONS
*/
public $end_options;
@@ -1,14 +1,17 @@
<?php
/**
* `SHOW` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
/**
* `SHOW` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ShowStatement extends NotImplementedStatement
{
@@ -17,7 +20,7 @@ class ShowStatement extends NotImplementedStatement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'CREATE' => 1,
'AUTHORS' => 2,
'BINARY' => 2,
@@ -58,6 +61,6 @@ class ShowStatement extends NotImplementedStatement
'TRIGGERS' => 2,
'VARIABLES' => 2,
'VIEW' => 2,
'WARNINGS' => 2,
];
'WARNINGS' => 2
);
}
@@ -1,10 +1,9 @@
<?php
/**
* Transaction statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\OptionsArray;
@@ -14,18 +13,26 @@ use PhpMyAdmin\SqlParser\TokensList;
/**
* Transaction statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class TransactionStatement extends Statement
{
/**
* START TRANSACTION and BEGIN.
*
* @var int
*/
public const TYPE_BEGIN = 1;
const TYPE_BEGIN = 1;
/**
* COMMIT and ROLLBACK.
*
* @var int
*/
public const TYPE_END = 2;
const TYPE_END = 2;
/**
* The type of this query.
@@ -53,7 +60,7 @@ class TransactionStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'START TRANSACTION' => 1,
'BEGIN' => 1,
'COMMIT' => 1,
@@ -63,8 +70,8 @@ class TransactionStatement extends Statement
'AND NO CHAIN' => 3,
'AND CHAIN' => 3,
'RELEASE' => 4,
'NO RELEASE' => 4,
];
'NO RELEASE' => 4
);
/**
* @param Parser $parser the instance that requests parsing
@@ -75,9 +82,13 @@ class TransactionStatement extends Statement
parent::parse($parser, $list);
// Checks the type of this query.
if ($this->options->has('START TRANSACTION') || $this->options->has('BEGIN')) {
if ($this->options->has('START TRANSACTION')
|| $this->options->has('BEGIN')
) {
$this->type = self::TYPE_BEGIN;
} elseif ($this->options->has('COMMIT') || $this->options->has('ROLLBACK')) {
} elseif ($this->options->has('COMMIT')
|| $this->options->has('ROLLBACK')
) {
$this->type = self::TYPE_END;
}
}
@@ -95,7 +106,6 @@ class TransactionStatement extends Statement
*/
$ret .= ';' . $statement->build();
}
$ret .= ';' . $this->end->build();
}
@@ -1,10 +1,9 @@
<?php
/**
* `TRUNCATE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Expression;
@@ -12,6 +11,10 @@ use PhpMyAdmin\SqlParser\Statement;
/**
* `TRUNCATE` statement.
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class TruncateStatement extends Statement
{
@@ -20,7 +23,9 @@ class TruncateStatement extends Statement
*
* @var array
*/
public static $OPTIONS = ['TABLE' => 1];
public static $OPTIONS = array(
'TABLE' => 1
);
/**
* The name of the truncated table.
@@ -1,10 +1,9 @@
<?php
/**
* `UPDATE` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Condition;
@@ -28,6 +27,10 @@ use PhpMyAdmin\SqlParser\Statement;
* UPDATE [LOW_PRIORITY] [IGNORE] table_references
* SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
* [WHERE where_condition]
*
* @category Statements
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class UpdateStatement extends Statement
{
@@ -36,10 +39,10 @@ class UpdateStatement extends Statement
*
* @var array
*/
public static $OPTIONS = [
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'IGNORE' => 2,
];
'IGNORE' => 2
);
/**
* The clauses of this statement, in order.
@@ -48,38 +51,38 @@ class UpdateStatement extends Statement
*
* @var array
*/
public static $CLAUSES = [
'UPDATE' => [
public static $CLAUSES = array(
'UPDATE' => array(
'UPDATE',
2,
],
),
// Used for options.
'_OPTIONS' => [
'_OPTIONS' => array(
'_OPTIONS',
1,
],
),
// Used for updated tables.
'_UPDATE' => [
'_UPDATE' => array(
'UPDATE',
1,
],
'SET' => [
),
'SET' => array(
'SET',
3,
],
'WHERE' => [
),
'WHERE' => array(
'WHERE',
3,
],
'ORDER BY' => [
),
'ORDER BY' => array(
'ORDER BY',
3,
],
'LIMIT' => [
),
'LIMIT' => array(
'LIMIT',
3,
],
];
)
);
/**
* Tables used as sources for this statement.
@@ -1,214 +0,0 @@
<?php
/**
* `WITH` statement.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Statements;
use PhpMyAdmin\SqlParser\Components\Array2d;
use PhpMyAdmin\SqlParser\Components\OptionsArray;
use PhpMyAdmin\SqlParser\Components\WithKeyword;
use PhpMyAdmin\SqlParser\Exceptions\ParserException;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use PhpMyAdmin\SqlParser\Translator;
use function array_slice;
use function count;
/**
* `WITH` statement.
* WITH [RECURSIVE] query_name [ (column_name [,...]) ] AS (SELECT ...) [, ...]
*/
final class WithStatement extends Statement
{
/**
* Options for `WITH` statements and their slot ID.
*
* @var mixed[]
*/
public static $OPTIONS = ['RECURSIVE' => 1];
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var mixed[]
*/
public static $CLAUSES = [
'WITH' => [
'WITH',
2,
],
// Used for options.
'_OPTIONS' => [
'_OPTIONS',
1,
],
'AS' => [
'AS',
2,
],
];
/** @var WithKeyword[] */
public $withers = [];
/**
* @param Parser $parser the instance that requests parsing
* @param TokensList $list the list of tokens to be parsed
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `WITH`.
// parse any options if provided
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
++$list->idx;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------- [ name ] -----------------> 1
* 1 -------------- [( columns )] AS ----------------> 2
* 2 ------------------ [ , ] --------------------> 0
*
* @var int
*/
$state = 0;
$wither = null;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token
*/
$token = $list->tokens[$list->idx];
// Skipping whitespaces and comments.
if ($token->type === Token::TYPE_WHITESPACE || $token->type === Token::TYPE_COMMENT) {
continue;
}
if ($token->type === Token::TYPE_NONE) {
$wither = $token->value;
$this->withers[$wither] = new WithKeyword($wither);
$state = 1;
continue;
}
if ($state === 1) {
if ($token->value === '(') {
$this->withers[$wither]->columns = Array2d::parse($parser, $list);
continue;
}
if ($token->keyword === 'AS') {
++$list->idx;
$state = 2;
continue;
}
} elseif ($state === 2) {
if ($token->value === '(') {
++$list->idx;
$subList = $this->getSubTokenList($list);
if ($subList instanceof ParserException) {
$parser->errors[] = $subList;
continue;
}
$subParser = new Parser($subList);
if (count($subParser->errors)) {
foreach ($subParser->errors as $error) {
$parser->errors[] = $error;
}
}
$this->withers[$wither]->statement = $subParser;
continue;
}
// There's another WITH expression to parse, go back to state=0
if ($token->value === ',') {
$list->idx++;
$state = 0;
continue;
}
// No more WITH expressions, we're done with this statement
break;
}
}
--$list->idx;
}
/**
* {@inheritdoc}
*/
public function build()
{
$str = 'WITH ';
foreach ($this->withers as $wither) {
$str .= $str === 'WITH ' ? '' : ', ';
$str .= WithKeyword::build($wither);
}
return $str;
}
/**
* Get tokens within the WITH expression to use them in another parser
*
* @return ParserException|TokensList
*/
private function getSubTokenList(TokensList $list)
{
$idx = $list->idx;
/** @var Token $token */
$token = $list->tokens[$list->idx];
$openParenthesis = 0;
while ($list->idx < $list->count) {
if ($token->value === '(') {
++$openParenthesis;
} elseif ($token->value === ')') {
if (--$openParenthesis === -1) {
break;
}
}
++$list->idx;
if (! isset($list->tokens[$list->idx])) {
break;
}
$token = $list->tokens[$list->idx];
}
// performance improvement: return the error to avoid a try/catch in the loop
if ($list->idx === $list->count) {
--$list->idx;
return new ParserException(
Translator::gettext('A closing bracket was expected.'),
$token
);
}
$length = $list->idx - $idx;
return new TokensList(array_slice($list->tokens, $idx, $length), $length);
}
}
+77 -60
View File
@@ -1,24 +1,20 @@
<?php
/**
* Defines a token along with a set of types and flags and utility functions.
*
* An array of tokens will result after parsing the query.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use function hexdec;
use function mb_strlen;
use function mb_substr;
use function str_replace;
use function stripcslashes;
use function strtoupper;
/**
* A structure representing a lexeme that explicitly indicates its
* categorization for the purpose of parsing.
*
* @category Tokens
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Token
{
@@ -28,13 +24,17 @@ class Token
* This type is used when the token is invalid or its type cannot be
* determined because of the ambiguous context. Further analysis might be
* required to detect its type.
*
* @var int
*/
public const TYPE_NONE = 0;
const TYPE_NONE = 0;
/**
* SQL specific keywords: SELECT, UPDATE, INSERT, etc.
*
* @var int
*/
public const TYPE_KEYWORD = 1;
const TYPE_KEYWORD = 1;
/**
* Any type of legal operator.
@@ -45,13 +45,17 @@ class Token
* Assignment operators: =, +=, -=, etc.
* SQL specific operators: . (e.g. .. WHERE database.table ..),
* * (e.g. SELECT * FROM ..)
*
* @var int
*/
public const TYPE_OPERATOR = 2;
const TYPE_OPERATOR = 2;
/**
* Spaces, tabs, new lines, etc.
*
* @var int
*/
public const TYPE_WHITESPACE = 3;
const TYPE_WHITESPACE = 3;
/**
* Any type of legal comment.
@@ -70,36 +74,48 @@ class Token
* comment*\/
*
* Backslashes were added to respect PHP's comments syntax.
*
* @var int
*/
public const TYPE_COMMENT = 4;
const TYPE_COMMENT = 4;
/**
* Boolean values: true or false.
*
* @var int
*/
public const TYPE_BOOL = 5;
const TYPE_BOOL = 5;
/**
* Numbers: 4, 0x8, 15.16, 23e42, etc.
*
* @var int
*/
public const TYPE_NUMBER = 6;
const TYPE_NUMBER = 6;
/**
* Literal strings: 'string', "test".
* Some of these strings are actually symbols.
*
* @var int
*/
public const TYPE_STRING = 7;
const TYPE_STRING = 7;
/**
* Database, table names, variables, etc.
* For example: ```SELECT `foo`, `bar` FROM `database`.`table`;```.
*
* @var int
*/
public const TYPE_SYMBOL = 8;
const TYPE_SYMBOL = 8;
/**
* Delimits an unknown string.
* For example: ```SELECT * FROM test;```, `test` is a delimiter.
*
* @var int
*/
public const TYPE_DELIMITER = 9;
const TYPE_DELIMITER = 9;
/**
* Labels in LOOP statement, ITERATE statement etc.
@@ -108,48 +124,50 @@ class Token
* begin_label: LOOP [statement_list] END LOOP [end_label]
* begin_label: REPEAT [statement_list] ... END REPEAT [end_label]
* begin_label: WHILE ... DO [statement_list] END WHILE [end_label].
*
* @var int
*/
public const TYPE_LABEL = 10;
const TYPE_LABEL = 10;
// Flags that describe the tokens in more detail.
// All keywords must have flag 1 so `Context::isKeyword` method doesn't
// require strict comparison.
public const FLAG_KEYWORD_RESERVED = 2;
public const FLAG_KEYWORD_COMPOSED = 4;
public const FLAG_KEYWORD_DATA_TYPE = 8;
public const FLAG_KEYWORD_KEY = 16;
public const FLAG_KEYWORD_FUNCTION = 32;
const FLAG_KEYWORD_RESERVED = 2;
const FLAG_KEYWORD_COMPOSED = 4;
const FLAG_KEYWORD_DATA_TYPE = 8;
const FLAG_KEYWORD_KEY = 16;
const FLAG_KEYWORD_FUNCTION = 32;
// Numbers related flags.
public const FLAG_NUMBER_HEX = 1;
public const FLAG_NUMBER_FLOAT = 2;
public const FLAG_NUMBER_APPROXIMATE = 4;
public const FLAG_NUMBER_NEGATIVE = 8;
public const FLAG_NUMBER_BINARY = 16;
const FLAG_NUMBER_HEX = 1;
const FLAG_NUMBER_FLOAT = 2;
const FLAG_NUMBER_APPROXIMATE = 4;
const FLAG_NUMBER_NEGATIVE = 8;
const FLAG_NUMBER_BINARY = 16;
// Strings related flags.
public const FLAG_STRING_SINGLE_QUOTES = 1;
public const FLAG_STRING_DOUBLE_QUOTES = 2;
const FLAG_STRING_SINGLE_QUOTES = 1;
const FLAG_STRING_DOUBLE_QUOTES = 2;
// Comments related flags.
public const FLAG_COMMENT_BASH = 1;
public const FLAG_COMMENT_C = 2;
public const FLAG_COMMENT_SQL = 4;
public const FLAG_COMMENT_MYSQL_CMD = 8;
const FLAG_COMMENT_BASH = 1;
const FLAG_COMMENT_C = 2;
const FLAG_COMMENT_SQL = 4;
const FLAG_COMMENT_MYSQL_CMD = 8;
// Operators related flags.
public const FLAG_OPERATOR_ARITHMETIC = 1;
public const FLAG_OPERATOR_LOGICAL = 2;
public const FLAG_OPERATOR_BITWISE = 4;
public const FLAG_OPERATOR_ASSIGNMENT = 8;
public const FLAG_OPERATOR_SQL = 16;
const FLAG_OPERATOR_ARITHMETIC = 1;
const FLAG_OPERATOR_LOGICAL = 2;
const FLAG_OPERATOR_BITWISE = 4;
const FLAG_OPERATOR_ASSIGNMENT = 8;
const FLAG_OPERATOR_SQL = 16;
// Symbols related flags.
public const FLAG_SYMBOL_VARIABLE = 1;
public const FLAG_SYMBOL_BACKTICK = 2;
public const FLAG_SYMBOL_USER = 4;
public const FLAG_SYMBOL_SYSTEM = 8;
public const FLAG_SYMBOL_PARAMETER = 16;
const FLAG_SYMBOL_VARIABLE = 1;
const FLAG_SYMBOL_BACKTICK = 2;
const FLAG_SYMBOL_USER = 4;
const FLAG_SYMBOL_SYSTEM = 8;
const FLAG_SYMBOL_PARAMETER = 16;
/**
* The token it its raw string representation.
@@ -197,6 +215,8 @@ class Token
public $position;
/**
* Constructor.
*
* @param string $token the value of the token
* @param int $type the type of the token
* @param int $flags the flags of the token
@@ -229,13 +249,10 @@ class Token
}
return $this->keyword;
case self::TYPE_WHITESPACE:
return ' ';
case self::TYPE_BOOL:
return strtoupper($this->token) === 'TRUE';
case self::TYPE_NUMBER:
$ret = str_replace('--', '', $this->token); // e.g. ---42 === -42
if ($this->flags & self::FLAG_NUMBER_HEX) {
@@ -245,14 +262,15 @@ class Token
} else {
$ret = hexdec($ret);
}
} elseif (($this->flags & self::FLAG_NUMBER_APPROXIMATE) || ($this->flags & self::FLAG_NUMBER_FLOAT)) {
} elseif (($this->flags & self::FLAG_NUMBER_APPROXIMATE)
|| ($this->flags & self::FLAG_NUMBER_FLOAT)
) {
$ret = (float) $ret;
} elseif (! ($this->flags & self::FLAG_NUMBER_BINARY)) {
$ret = (int) $ret;
}
return $ret;
case self::TYPE_STRING:
// Trims quotes.
$str = $this->token;
@@ -274,7 +292,6 @@ class Token
$str = stripcslashes($str);
return $str;
case self::TYPE_SYMBOL:
$str = $this->token;
if (isset($str[0]) && ($str[0] === '@')) {
@@ -282,17 +299,17 @@ class Token
// in PHP 5.3- the `null` parameter isn't handled correctly.
$str = mb_substr(
$str,
! empty($str[1]) && ($str[1] === '@') ? 2 : 1,
(! empty($str[1]) && ($str[1] === '@')) ? 2 : 1,
mb_strlen($str),
'UTF-8'
);
}
if (isset($str[0]) && ($str[0] === ':')) {
$str = mb_substr($str, 1, mb_strlen($str), 'UTF-8');
}
if (isset($str[0]) && (($str[0] === '`') || ($str[0] === '"') || ($str[0] === '\''))) {
if (isset($str[0]) && (($str[0] === '`')
|| ($str[0] === '"') || ($str[0] === '\''))
) {
$quote = $str[0];
$str = str_replace($quote . $quote, $quote, $str);
$str = mb_substr($str, 1, -1, 'UTF-8');
@@ -312,16 +329,16 @@ class Token
public function getInlineToken()
{
return str_replace(
[
array(
"\r",
"\n",
"\t",
],
[
),
array(
'\r',
'\n',
'\t',
],
),
$this->token
);
}
+19 -24
View File
@@ -1,29 +1,26 @@
<?php
/**
* Defines an array of tokens and utility functions to iterate through it.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use ArrayAccess;
use function count;
use function is_array;
use function is_string;
/**
* A structure representing a list of tokens.
*
* @category Tokens
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class TokensList implements ArrayAccess
class TokensList implements \ArrayAccess
{
/**
* The array of tokens.
*
* @var array
*/
public $tokens = [];
public $tokens = array();
/**
* The count of tokens.
@@ -40,17 +37,19 @@ class TokensList implements ArrayAccess
public $idx = 0;
/**
* Constructor.
*
* @param array $tokens the initial array of tokens
* @param int $count the count of tokens in the initial array
*/
public function __construct(array $tokens = [], $count = -1)
public function __construct(array $tokens = array(), $count = -1)
{
if (empty($tokens)) {
return;
if (! empty($tokens)) {
$this->tokens = $tokens;
if ($count === -1) {
$this->count = count($tokens);
}
}
$this->tokens = $tokens;
$this->count = $count === -1 ? count($tokens) : $count;
}
/**
@@ -99,8 +98,7 @@ class TokensList implements ArrayAccess
public function getNext()
{
for (; $this->idx < $this->count; ++$this->idx) {
if (
($this->tokens[$this->idx]->type !== Token::TYPE_WHITESPACE)
if (($this->tokens[$this->idx]->type !== Token::TYPE_WHITESPACE)
&& ($this->tokens[$this->idx]->type !== Token::TYPE_COMMENT)
) {
return $this->tokens[$this->idx++];
@@ -139,7 +137,9 @@ class TokensList implements ArrayAccess
public function getNextOfTypeAndValue($type, $value)
{
for (; $this->idx < $this->count; ++$this->idx) {
if (($this->tokens[$this->idx]->type === $type) && ($this->tokens[$this->idx]->value === $value)) {
if (($this->tokens[$this->idx]->type === $type)
&& ($this->tokens[$this->idx]->value === $value)
) {
return $this->tokens[$this->idx++];
}
}
@@ -153,7 +153,6 @@ class TokensList implements ArrayAccess
* @param int $offset the offset to be set
* @param Token $value the token to be saved
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
if ($offset === null) {
@@ -170,7 +169,6 @@ class TokensList implements ArrayAccess
*
* @return Token
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $offset < $this->count ? $this->tokens[$offset] : null;
@@ -183,7 +181,6 @@ class TokensList implements ArrayAccess
*
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return $offset < $this->count;
@@ -194,7 +191,6 @@ class TokensList implements ArrayAccess
*
* @param int $offset the offset to be unset
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
unset($this->tokens[$offset]);
@@ -202,7 +198,6 @@ class TokensList implements ArrayAccess
for ($i = $offset; $i < $this->count; ++$i) {
$this->tokens[$i] = $this->tokens[$i + 1];
}
unset($this->tokens[$this->count]);
}
}
@@ -1,403 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Tools;
use function array_map;
use function array_merge;
use function array_slice;
use function basename;
use function count;
use function dirname;
use function file;
use function file_put_contents;
use function implode;
use function ksort;
use function preg_match;
use function round;
use function scandir;
use function sort;
use function sprintf;
use function str_repeat;
use function str_replace;
use function str_split;
use function strlen;
use function strstr;
use function strtoupper;
use function substr;
use function trim;
use const FILE_IGNORE_NEW_LINES;
use const FILE_SKIP_EMPTY_LINES;
use const SORT_STRING;
/**
* Used for context generation.
*/
class ContextGenerator
{
/**
* Labels and flags that may be used when defining keywords.
*
* @var array
*/
public static $LABELS_FLAGS = [
'(R)' => 2, // reserved
'(D)' => 8, // data type
'(K)' => 16, // keyword
'(F)' => 32, // function name
];
/**
* Documentation links for each context.
*
* @var array
*/
public static $LINKS = [
'MySql50000' => 'https://dev.mysql.com/doc/refman/5.0/en/keywords.html',
'MySql50100' => 'https://dev.mysql.com/doc/refman/5.1/en/keywords.html',
'MySql50500' => 'https://dev.mysql.com/doc/refman/5.5/en/keywords.html',
'MySql50600' => 'https://dev.mysql.com/doc/refman/5.6/en/keywords.html',
'MySql50700' => 'https://dev.mysql.com/doc/refman/5.7/en/keywords.html',
'MySql80000' => 'https://dev.mysql.com/doc/refman/8.0/en/keywords.html',
'MariaDb100000' => 'https://mariadb.com/kb/en/reserved-words/',
'MariaDb100100' => 'https://mariadb.com/kb/en/reserved-words/',
'MariaDb100200' => 'https://mariadb.com/kb/en/reserved-words/',
'MariaDb100300' => 'https://mariadb.com/kb/en/reserved-words/',
'MariaDb100400' => 'https://mariadb.com/kb/en/reserved-words/',
'MariaDb100500' => 'https://mariadb.com/kb/en/reserved-words/',
'MariaDb100600' => 'https://mariadb.com/kb/en/reserved-words/',
];
/**
* The template of a context.
*
* Parameters:
* 1 - name
* 2 - class
* 3 - link
* 4 - keywords array
*/
public const TEMPLATE = <<<'PHP'
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Contexts;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Token;
/**
* Context for %1$s.
*
* This class was auto-generated from tools/contexts/*.txt.
* Use tools/run_generators.sh for update.
*
* @see %3$s
*/
class %2$s extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_RESERVED Token::FLAG_KEYWORD_COMPOSED
* Token::FLAG_KEYWORD_DATA_TYPE Token::FLAG_KEYWORD_KEY
* Token::FLAG_KEYWORD_FUNCTION
*
* @var array<string,int>
* @phpstan-var non-empty-array<non-empty-string,Token::FLAG_KEYWORD_*|int>
*/
public static $KEYWORDS = [
%4$s ];
}
PHP;
/**
* Sorts an array of words.
*
* @param array $arr
*
* @return array
*/
public static function sortWords(array &$arr)
{
ksort($arr);
foreach ($arr as &$wordsByLen) {
ksort($wordsByLen);
foreach ($wordsByLen as &$words) {
sort($words, SORT_STRING);
}
}
return $arr;
}
/**
* Reads a list of words and sorts it by type, length and keyword.
*
* @param string[] $files
*
* @return array
*/
public static function readWords(array $files)
{
$words = [];
foreach ($files as $file) {
$words = array_merge($words, file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
}
$types = [];
for ($i = 0, $count = count($words); $i !== $count; ++$i) {
$type = 1;
$value = trim($words[$i]);
// Reserved, data types, keys, functions, etc. keywords.
foreach (static::$LABELS_FLAGS as $label => $flags) {
if (strstr($value, $label) === false) {
continue;
}
$type |= $flags;
$value = trim(str_replace($label, '', $value));
}
// Composed keyword.
if (strstr($value, ' ') !== false) {
$type |= 2; // Reserved keyword.
$type |= 4; // Composed keyword.
}
$len = strlen($words[$i]);
if ($len === 0) {
continue;
}
$value = strtoupper($value);
if (! isset($types[$value])) {
$types[$value] = $type;
} else {
$types[$value] |= $type;
}
}
$ret = [];
foreach ($types as $word => $type) {
$len = strlen($word);
if (! isset($ret[$type])) {
$ret[$type] = [];
}
if (! isset($ret[$type][$len])) {
$ret[$type][$len] = [];
}
$ret[$type][$len][] = $word;
}
return static::sortWords($ret);
}
/**
* Prints an array of a words in PHP format.
*
* @param array $words the list of words to be formatted
* @param int $spaces the number of spaces that starts every line
* @param int $line the length of a line
*
* @return string
*/
public static function printWords($words, $spaces = 8, $line = 140)
{
$typesCount = count($words);
$ret = '';
$j = 0;
foreach ($words as $type => $wordsByType) {
foreach ($wordsByType as $len => $wordsByLen) {
$count = round(($line - $spaces) / ($len + 9)); // strlen("'' => 1, ") = 9
$i = 0;
foreach ($wordsByLen as $word) {
if ($i === 0) {
$ret .= str_repeat(' ', $spaces);
}
$ret .= sprintf('\'%s\' => %s, ', $word, $type);
if (++$i !== $count && ++$i <= $count) {
continue;
}
$ret .= "\n";
$i = 0;
}
if ($i === 0) {
continue;
}
$ret .= "\n";
}
if (++$j >= $typesCount) {
continue;
}
$ret .= "\n";
}
// Trim trailing spaces and return.
return str_replace(" \n", "\n", $ret);
}
/**
* Generates a context's class.
*
* @param array $options the options that are used in generating this context
*
* @return string
*/
public static function generate($options)
{
if (isset($options['keywords'])) {
$options['keywords'] = static::printWords($options['keywords']);
}
return sprintf(self::TEMPLATE, $options['name'], $options['class'], $options['link'], $options['keywords']);
}
/**
* Formats context name.
*
* @param string $name name to format
*
* @return string
*/
public static function formatName($name)
{
/* Split name and version */
$parts = [];
if (preg_match('/([^[0-9]*)([0-9]*)/', $name, $parts) === false) {
return $name;
}
/* Format name */
$base = $parts[1];
switch ($base) {
case 'MySql':
$base = 'MySQL';
break;
case 'MariaDb':
$base = 'MariaDB';
break;
}
/* Parse version to array */
$versionString = $parts[2];
if (strlen($versionString) % 2 === 1) {
$versionString = '0' . $versionString;
}
$version = array_map('intval', str_split($versionString, 2));
/* Remove trailing zero */
if ($version[count($version) - 1] === 0) {
$version = array_slice($version, 0, count($version) - 1);
}
/* Create name */
return $base . ' ' . implode('.', $version);
}
/**
* Builds a test.
*
* Reads the input file, generates the data and writes it back.
*
* @param string $input the input file
* @param string $output the output directory
*/
public static function build($input, $output)
{
/**
* The directory that contains the input file.
*
* Used to include common files.
*
* @var string
*/
$directory = dirname($input) . '/';
/**
* The name of the file that contains the context.
*
* @var string
*/
$file = basename($input);
/**
* The name of the context.
*
* @var string
*/
$name = substr($file, 0, -4);
/**
* The name of the class that defines this context.
*
* @var string
*/
$class = 'Context' . $name;
/**
* The formatted name of this context.
*
* @var string
*/
$formattedName = static::formatName($name);
file_put_contents(
$output . '/' . $class . '.php',
static::generate(
[
'name' => $formattedName,
'class' => $class,
'link' => static::$LINKS[$name],
'keywords' => static::readWords(
[
$directory . '_common.txt',
$directory . '_functions' . $file,
$directory . $file,
]
),
]
)
);
}
/**
* Generates recursively all tests preserving the directory structure.
*
* @param string $input the input directory
* @param string $output the output directory
*/
public static function buildAll($input, $output)
{
$files = scandir($input);
foreach ($files as $file) {
// Skipping current and parent directories.
if (($file[0] === '.') || ($file[0] === '_')) {
continue;
}
// Building the context.
sprintf("Building context for %s...\n", $file);
static::build($input . '/' . $file, $output);
}
}
}
@@ -1,244 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Tools;
use Exception;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Exceptions\LexerException;
use PhpMyAdmin\SqlParser\Exceptions\ParserException;
use PhpMyAdmin\SqlParser\Lexer;
use PhpMyAdmin\SqlParser\Parser;
use Zumba\JsonSerializer\JsonSerializer;
use function file_exists;
use function file_get_contents;
use function file_put_contents;
use function in_array;
use function is_dir;
use function json_decode;
use function json_encode;
use function mkdir;
use function print_r;
use function scandir;
use function sprintf;
use function strpos;
use function substr;
use const JSON_PRESERVE_ZERO_FRACTION;
use const JSON_PRETTY_PRINT;
use const JSON_UNESCAPED_UNICODE;
/**
* Used for test generation.
*/
class TestGenerator
{
/**
* Generates a test's data.
*
* @param string $query the query to be analyzed
* @param string $type test's type (may be `lexer` or `parser`)
*
* @return array
*/
public static function generate($query, $type = 'parser')
{
/**
* Lexer used for tokenizing the query.
*
* @var Lexer
*/
$lexer = new Lexer($query);
/**
* Parsed used for analyzing the query.
* A new instance of parser is generated only if the test requires.
*
* @var Parser
*/
$parser = $type === 'parser' ? new Parser($lexer->list) : null;
/**
* Lexer's errors.
*
* @var array
*/
$lexerErrors = [];
/**
* Parser's errors.
*
* @var array
*/
$parserErrors = [];
// Both the lexer and the parser construct exception for errors.
// Usually, exceptions contain a full stack trace and other details that
// are not required.
// The code below extracts only the relevant information.
// Extracting lexer's errors.
if (! empty($lexer->errors)) {
/** @var LexerException $err */
foreach ($lexer->errors as $err) {
$lexerErrors[] = [
$err->getMessage(),
$err->ch,
$err->pos,
$err->getCode(),
];
}
$lexer->errors = [];
}
// Extracting parser's errors.
if (! empty($parser->errors)) {
/** @var ParserException $err */
foreach ($parser->errors as $err) {
$parserErrors[] = [
$err->getMessage(),
$err->token,
$err->getCode(),
];
}
$parser->errors = [];
}
return [
'query' => $query,
'lexer' => $lexer,
'parser' => $parser,
'errors' => [
'lexer' => $lexerErrors,
'parser' => $parserErrors,
],
];
}
/**
* Builds a test.
*
* Reads the input file, generates the data and writes it back.
*
* @param string $type the type of this test
* @param string $input the input file
* @param string $output the output file
* @param string $debug the debug file
* @param bool $ansi activate quotes ANSI mode
*/
public static function build($type, $input, $output, $debug = null, $ansi = false)
{
// Support query types: `lexer` / `parser`.
if (! in_array($type, ['lexer', 'parser'])) {
throw new Exception('Unknown test type (expected `lexer` or `parser`).');
}
/**
* The query that is used to generate the test.
*
* @var string
*/
$query = file_get_contents($input);
// There is no point in generating a test without a query.
if (empty($query)) {
throw new Exception('No input query specified.');
}
if ($ansi === true) {
// set ANSI_QUOTES for ansi tests
Context::setMode('ANSI_QUOTES');
}
$mariaDbPos = strpos($input, '_mariadb_');
if ($mariaDbPos !== false) {// Keep in sync with TestCase.php
// set context
$mariaDbVersion = (int) substr($input, $mariaDbPos + 9, 6);
Context::load('MariaDb' . $mariaDbVersion);
}
$test = static::generate($query, $type);
// unset mode, reset to default every time, to be sure
Context::setMode();
$serializer = new JsonSerializer();
// Writing test's data.
$encoded = $serializer->serialize($test);
$encoded = json_encode(
json_decode($encoded),
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION
);
file_put_contents($output, $encoded);
// Dumping test's data in human readable format too (if required).
if (empty($debug)) {
return;
}
file_put_contents($debug, print_r($test, true));
}
/**
* Generates recursively all tests preserving the directory structure.
*
* @param string $input the input directory
* @param string $output the output directory
* @param mixed|null $debug
*/
public static function buildAll($input, $output, $debug = null)
{
$files = scandir($input);
foreach ($files as $file) {
// Skipping current and parent directories.
if (($file === '.') || ($file === '..')) {
continue;
}
// Appending the filename to directories.
$inputFile = $input . '/' . $file;
$outputFile = $output . '/' . $file;
$debugFile = $debug !== null ? $debug . '/' . $file : null;
if (is_dir($inputFile)) {
// Creating required directories to maintain the structure.
// Ignoring errors if the folder structure exists already.
if (! is_dir($outputFile)) {
mkdir($outputFile);
}
if (($debug !== null) && (! is_dir($debugFile))) {
mkdir($debugFile);
}
// Generating tests recursively.
static::buildAll($inputFile, $outputFile, $debugFile);
} elseif (substr($inputFile, -3) === '.in') {
// Generating file names by replacing `.in` with `.out` and
// `.debug`.
$outputFile = substr($outputFile, 0, -3) . '.out';
if ($debug !== null) {
$debugFile = substr($debugFile, 0, -3) . '.debug';
}
// Building the test.
if (! file_exists($outputFile)) {
sprintf("Building test for %s...\n", $inputFile);
static::build(
strpos($inputFile, 'lex') !== false ? 'lexer' : 'parser',
$inputFile,
$outputFile,
$debugFile,
strpos($inputFile, 'ansi') !== false
);
} else {
sprintf("Test for %s already built!\n", $inputFile);
}
}
}
}
}
@@ -1,22 +1,17 @@
<?php
/**
* Defines the localization helper infrastructure of the library.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use PhpMyAdmin\MoTranslator\Loader;
use function class_exists;
class Translator
{
/**
* The MoTranslator loader object.
*
* @var Loader
* @var \PhpMyAdmin\MoTranslator\Loader
*/
private static $loader;
@@ -32,9 +27,9 @@ class Translator
*/
public static function load()
{
if (self::$loader === null) {
if (is_null(self::$loader)) {
// Create loader object
self::$loader = new Loader();
self::$loader = new \PhpMyAdmin\MoTranslator\Loader();
// Set locale
self::$loader->setlocale(
@@ -48,12 +43,10 @@ class Translator
self::$loader->bindtextdomain('sqlparser', __DIR__ . '/../locale/');
}
if (self::$translator !== null) {
return;
if (is_null(self::$translator)) {
// Get translator
self::$translator = self::$loader->getTranslator();
}
// Get translator
self::$translator = self::$loader->getTranslator();
}
/**
+18 -155
View File
@@ -1,4 +1,5 @@
<?php
/**
* Implementation for UTF-8 strings.
*
@@ -10,23 +11,18 @@
* implemented.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser;
use ArrayAccess;
use Exception;
use function mb_check_encoding;
use function mb_strlen;
use function ord;
/**
* Implements array-like access for UTF-8 strings.
*
* In this library, this class should be used to parse UTF-8 queries.
*
* @category Misc
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class UtfString implements ArrayAccess
class UtfString implements \ArrayAccess
{
/**
* The raw, multi-byte string.
@@ -69,119 +65,8 @@ class UtfString implements ArrayAccess
public $charLen = 0;
/**
* A map of ASCII binary values to their ASCII code
* This is to improve performance and avoid calling ord($byte)
* Constructor.
*
* Source: https://www.freecodecamp.org/news/ascii-table-hex-to-ascii-value-character-code-chart-2/
*
* @var array<int|string,int>
*/
protected static $asciiMap = [
"\0" => 0, // (00000000) NUL Null
"\t" => 9, // (00001001) HT Horizontal Tab
"\n" => 10, // (00001010) LF Newline / Line Feed
"\v" => 11, // (00001011) VT Vertical Tab
"\f" => 12, // (00001100) FF Form Feed
"\r" => 13, // (00001101) CR Carriage Return
' ' => 32, // (00100000) SP Space
'!' => 33, // (00100001) ! Exclamation mark
'"' => 34, // (00100010) " Double quote
'#' => 35, // (00100011) # Number
'$' => 36, // (00100100) $ Dollar
'%' => 37, // (00100101) % Percent
'&' => 38, // (00100110) & Ampersand
'\'' => 39, // (00100111) ' Single quote
'(' => 40, // (00101000) ( Left parenthesis
')' => 41, // (00101001) ) Right parenthesis
'*' => 42, // (00101010) * Asterisk
'+' => 43, // (00101011) + Plus
',' => 44, // (00101100) , Comma
'-' => 45, // (00101101) - Minus
'.' => 46, // (00101110) . Period
'/' => 47, // (00101111) / Slash
'0' => 48, // (00110000) 0 Zero
'1' => 49, // (00110001) 1 One
'2' => 50, // (00110010) 2 Two
'3' => 51, // (00110011) 3 Three
'4' => 52, // (00110100) 4 Four
'5' => 53, // (00110101) 5 Five
'6' => 54, // (00110110) 6 Six
'7' => 55, // (00110111) 7 Seven
'8' => 56, // (00111000) 8 Eight
'9' => 57, // (00111001) 9 Nine
':' => 58, // (00111010) : Colon
';' => 59, // (00111011) ; Semicolon
'<' => 60, // (00111100) < Less than
'=' => 61, // (00111101) = Equal sign
'>' => 62, // (00111110) > Greater than
'?' => 63, // (00111111) ? Question mark
'@' => 64, // (01000000) @ At sign
'A' => 65, // (01000001) A Uppercase A
'B' => 66, // (01000010) B Uppercase B
'C' => 67, // (01000011) C Uppercase C
'D' => 68, // (01000100) D Uppercase D
'E' => 69, // (01000101) E Uppercase E
'F' => 70, // (01000110) F Uppercase F
'G' => 71, // (01000111) G Uppercase G
'H' => 72, // (01001000) H Uppercase H
'I' => 73, // (01001001) I Uppercase I
'J' => 74, // (01001010) J Uppercase J
'K' => 75, // (01001011) K Uppercase K
'L' => 76, // (01001100) L Uppercase L
'M' => 77, // (01001101) M Uppercase M
'N' => 78, // (01001110) N Uppercase N
'O' => 79, // (01001111) O Uppercase O
'P' => 80, // (01010000) P Uppercase P
'Q' => 81, // (01010001) Q Uppercase Q
'R' => 82, // (01010010) R Uppercase R
'S' => 83, // (01010011) S Uppercase S
'T' => 84, // (01010100) T Uppercase T
'U' => 85, // (01010101) U Uppercase U
'V' => 86, // (01010110) V Uppercase V
'W' => 87, // (01010111) W Uppercase W
'X' => 88, // (01011000) X Uppercase X
'Y' => 89, // (01011001) Y Uppercase Y
'Z' => 90, // (01011010) Z Uppercase Z
'[' => 91, // (01011011) [ Left square bracket
'\\' => 92, // (01011100) \ backslash
']' => 93, // (01011101) ] Right square bracket
'^' => 94, // (01011110) ^ Caret / circumflex
'_' => 95, // (01011111) _ Underscore
'`' => 96, // (01100000) ` Grave / accent
'a' => 97, // (01100001) a Lowercase a
'b' => 98, // (01100010) b Lowercase b
'c' => 99, // (01100011) c Lowercase c
'd' => 100, // (01100100) d Lowercase d
'e' => 101, // (01100101) e Lowercase e
'f' => 102, // (01100110) f Lowercase
'g' => 103, // (01100111) g Lowercase g
'h' => 104, // (01101000) h Lowercase h
'i' => 105, // (01101001) i Lowercase i
'j' => 106, // (01101010) j Lowercase j
'k' => 107, // (01101011) k Lowercase k
'l' => 108, // (01101100) l Lowercase l
'm' => 109, // (01101101) m Lowercase m
'n' => 110, // (01101110) n Lowercase n
'o' => 111, // (01101111) o Lowercase o
'p' => 112, // (01110000) p Lowercase p
'q' => 113, // (01110001) q Lowercase q
'r' => 114, // (01110010) r Lowercase r
's' => 115, // (01110011) s Lowercase s
't' => 116, // (01110100) t Lowercase t
'u' => 117, // (01110101) u Lowercase u
'v' => 118, // (01110110) v Lowercase v
'w' => 119, // (01110111) w Lowercase w
'x' => 120, // (01111000) x Lowercase x
'y' => 121, // (01111001) y Lowercase y
'z' => 122, // (01111010) z Lowercase z
'{' => 123, // (01111011) { Left curly bracket
'|' => 124, // (01111100) | Vertical bar
'}' => 125, // (01111101) } Right curly bracket
'~' => 126, // (01111110) ~ Tilde
"\x7f" => 127, // (01111111) DEL Delete
];
/**
* @param string $str the string
*/
public function __construct($str)
@@ -204,7 +89,6 @@ class UtfString implements ArrayAccess
*
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return ($offset >= 0) && ($offset < $this->charLen);
@@ -217,7 +101,6 @@ class UtfString implements ArrayAccess
*
* @return string|null
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
if (($offset < 0) || ($offset >= $this->charLen)) {
@@ -238,7 +121,6 @@ class UtfString implements ArrayAccess
do {
$byte = ord($this->str[--$this->byteIdx]);
} while (($byte >= 128) && ($byte < 192));
--$this->charIdx;
}
}
@@ -259,12 +141,11 @@ class UtfString implements ArrayAccess
* @param int $offset the offset to be set
* @param string $value the value to be set
*
* @throws Exception not implemented.
* @throws \Exception not implemented
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
throw new Exception('Not implemented.');
throw new \Exception('Not implemented.');
}
/**
@@ -272,12 +153,11 @@ class UtfString implements ArrayAccess
*
* @param int $offset the value to be unset
*
* @throws Exception not implemented.
* @throws \Exception not implemented
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
throw new Exception('Not implemented.');
throw new \Exception('Not implemented.');
}
/**
@@ -287,41 +167,24 @@ class UtfString implements ArrayAccess
* However, this implementation supports UTF-8 characters containing up to 6
* bytes.
*
* @see https://tools.ietf.org/html/rfc3629
*
* @param string $byte the byte to be analyzed
*
* @see https://tools.ietf.org/html/rfc3629
*
* @return int
*/
public static function getCharLength($byte)
{
// Use the default ASCII map as queries are mostly ASCII chars
// ord($byte) has a performance cost
if (! isset(static::$asciiMap[$byte])) {
// Complete the cache with missing items
static::$asciiMap[$byte] = ord($byte);
}
$byte = static::$asciiMap[$byte];
$byte = ord($byte);
if ($byte < 128) {
return 1;
}
if ($byte < 224) {
} elseif ($byte < 224) {
return 2;
}
if ($byte < 240) {
} elseif ($byte < 240) {
return 3;
}
if ($byte < 248) {
} elseif ($byte < 248) {
return 4;
}
if ($byte < 252) {
} elseif ($byte < 252) {
return 5; // unofficial
}
@@ -1,41 +1,39 @@
<?php
/**
* Buffered query utilities.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Context;
use function array_merge;
use function strlen;
use function substr;
use function trim;
/**
* Buffer query utilities.
*
* Implements a specialized lexer used to extract statements from large inputs
* that are being buffered. After each statement has been extracted, a lexer or
* a parser may be used.
*
* @category Lexer
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class BufferedQuery
{
// Constants that describe the current status of the parser.
// A string is being parsed.
public const STATUS_STRING = 16; // 0001 0000
public const STATUS_STRING_SINGLE_QUOTES = 17; // 0001 0001
public const STATUS_STRING_DOUBLE_QUOTES = 18; // 0001 0010
public const STATUS_STRING_BACKTICK = 20; // 0001 0100
const STATUS_STRING = 16; // 0001 0000
const STATUS_STRING_SINGLE_QUOTES = 17; // 0001 0001
const STATUS_STRING_DOUBLE_QUOTES = 18; // 0001 0010
const STATUS_STRING_BACKTICK = 20; // 0001 0100
// A comment is being parsed.
public const STATUS_COMMENT = 32; // 0010 0000
public const STATUS_COMMENT_BASH = 33; // 0010 0001
public const STATUS_COMMENT_C = 34; // 0010 0010
public const STATUS_COMMENT_SQL = 36; // 0010 0100
const STATUS_COMMENT = 32; // 0010 0000
const STATUS_COMMENT_BASH = 33; // 0010 0001
const STATUS_COMMENT_C = 34; // 0010 0010
const STATUS_COMMENT_SQL = 36; // 0010 0100
/**
* The query that is being processed.
@@ -51,7 +49,7 @@ class BufferedQuery
*
* @var array
*/
public $options = [];
public $options = array();
/**
* The last delimiter used.
@@ -82,14 +80,16 @@ class BufferedQuery
public $current = '';
/**
* Constructor.
*
* @param string $query the query to be parsed
* @param array $options the options of this parser
*/
public function __construct($query = '', array $options = [])
public function __construct($query = '', array $options = array())
{
// Merges specified options with defaults.
$this->options = array_merge(
[
array(
/*
* The starting delimiter.
*
@@ -111,7 +111,7 @@ class BufferedQuery
* @var bool
*/
'add_delimiter' => false,
],
),
$options
);
@@ -191,7 +191,7 @@ class BufferedQuery
* treated differently, because of the preceding backslash, it will
* be ignored.
*/
if ((($this->status & self::STATUS_COMMENT) === 0) && ($this->query[$i] === '\\')) {
if ((($this->status & static::STATUS_COMMENT) === 0) && ($this->query[$i] === '\\')) {
$this->current .= $this->query[$i] . ($i + 1 < $len ? $this->query[++$i] : '');
continue;
}
@@ -199,43 +199,40 @@ class BufferedQuery
/*
* Handling special parses statuses.
*/
if ($this->status === self::STATUS_STRING_SINGLE_QUOTES) {
if ($this->status === static::STATUS_STRING_SINGLE_QUOTES) {
// Single-quoted strings like 'foo'.
if ($this->query[$i] === '\'') {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} elseif ($this->status === self::STATUS_STRING_DOUBLE_QUOTES) {
} elseif ($this->status === static::STATUS_STRING_DOUBLE_QUOTES) {
// Double-quoted strings like "bar".
if ($this->query[$i] === '"') {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} elseif ($this->status === self::STATUS_STRING_BACKTICK) {
} elseif ($this->status === static::STATUS_STRING_BACKTICK) {
if ($this->query[$i] === '`') {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} elseif (($this->status === self::STATUS_COMMENT_BASH) || ($this->status === self::STATUS_COMMENT_SQL)) {
} elseif (($this->status === static::STATUS_COMMENT_BASH)
|| ($this->status === static::STATUS_COMMENT_SQL)
) {
// Bash-like (#) or SQL-like (-- ) comments end in new line.
if ($this->query[$i] === "\n") {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} elseif ($this->status === self::STATUS_COMMENT_C) {
} elseif ($this->status === static::STATUS_COMMENT_C) {
// C-like comments end in */.
if (($this->query[$i - 1] === '*') && ($this->query[$i] === '/')) {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
}
@@ -244,19 +241,15 @@ class BufferedQuery
* Checking if a string started.
*/
if ($this->query[$i] === '\'') {
$this->status = self::STATUS_STRING_SINGLE_QUOTES;
$this->status = static::STATUS_STRING_SINGLE_QUOTES;
$this->current .= $this->query[$i];
continue;
}
if ($this->query[$i] === '"') {
$this->status = self::STATUS_STRING_DOUBLE_QUOTES;
} elseif ($this->query[$i] === '"') {
$this->status = static::STATUS_STRING_DOUBLE_QUOTES;
$this->current .= $this->query[$i];
continue;
}
if ($this->query[$i] === '`') {
$this->status = self::STATUS_STRING_BACKTICK;
} elseif ($this->query[$i] === '`') {
$this->status = static::STATUS_STRING_BACKTICK;
$this->current .= $this->query[$i];
continue;
}
@@ -265,24 +258,20 @@ class BufferedQuery
* Checking if a comment started.
*/
if ($this->query[$i] === '#') {
$this->status = self::STATUS_COMMENT_BASH;
$this->status = static::STATUS_COMMENT_BASH;
$this->current .= $this->query[$i];
continue;
}
if ($i + 2 < $len) {
if (
($this->query[$i] === '-')
&& ($this->query[$i + 1] === '-')
&& Context::isWhitespace($this->query[$i + 2])
) {
$this->status = self::STATUS_COMMENT_SQL;
} elseif ($i + 2 < $len) {
if (($this->query[$i] === '-')
&& ($this->query[$i + 1] === '-')
&& Context::isWhitespace($this->query[$i + 2])) {
$this->status = static::STATUS_COMMENT_SQL;
$this->current .= $this->query[$i];
continue;
}
if (($this->query[$i] === '/') && ($this->query[$i + 1] === '*') && ($this->query[$i + 2] !== '!')) {
$this->status = self::STATUS_COMMENT_C;
} elseif (($this->query[$i] === '/')
&& ($this->query[$i + 1] === '*')
&& ($this->query[$i + 2] !== '!')) {
$this->status = static::STATUS_COMMENT_C;
$this->current .= $this->query[$i];
continue;
}
@@ -300,8 +289,7 @@ class BufferedQuery
* it has a special meaning is when it is the beginning of a
* statement. This is the reason for the last condition.
*/
if (
($i + 9 < $len)
if (($i + 9 < $len)
&& (($this->query[$i] === 'D') || ($this->query[$i] === 'd'))
&& (($this->query[$i + 1] === 'E') || ($this->query[$i + 1] === 'e'))
&& (($this->query[$i + 2] === 'L') || ($this->query[$i + 2] === 'l'))
@@ -330,9 +318,8 @@ class BufferedQuery
}
// Checking if the delimiter definition ended.
if (
($delimiter !== '')
&& (($i < $len) && Context::isWhitespace($this->query[$i])
if (($delimiter !== '')
&& ((($i < $len) && Context::isWhitespace($this->query[$i]))
|| (($i === $len) && $end))
) {
// Saving the delimiter.
@@ -374,8 +361,7 @@ class BufferedQuery
* There is no point in checking if two strings match if not even
* the first letter matches.
*/
if (
($this->query[$i] === $this->delimiter[0])
if (($this->query[$i] === $this->delimiter[0])
&& (($this->delimiterLen === 1)
|| (substr($this->query, $i, $this->delimiterLen) === $this->delimiter))
) {
+40 -105
View File
@@ -1,92 +1,65 @@
<?php
/**
* CLI interface.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Lexer;
use PhpMyAdmin\SqlParser\Parser;
use function count;
use function getopt;
use function implode;
use function in_array;
use function rtrim;
use function stream_get_contents;
use function stream_select;
use function var_export;
use const STDIN;
/**
* CLI interface.
*
* @category Exceptions
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CLI
{
/**
* @param string[]|false[] $params
* @param string[] $longopts
*
* @return void
*/
public function mergeLongOpts(&$params, &$longopts)
{
foreach ($longopts as $value) {
$value = rtrim($value, ':');
if (! isset($params[$value])) {
continue;
if (isset($params[$value])) {
$params[$value[0]] = $params[$value];
}
$params[$value[0]] = $params[$value];
}
}
/**
* @return void
*/
public function usageHighlight()
{
echo "Usage: highlight-query --query SQL [--format html|cli|text] [--ansi]\n";
echo " cat file.sql | highlight-query\n";
}
/**
* @param string $opt
* @param array $long
*
* @return string[]|false[]|false
*/
public function getopt($opt, $long)
{
return getopt($opt, $long);
}
/**
* @return mixed|false
*/
public function parseHighlight()
{
$longopts = [
$longopts = array(
'help',
'query:',
'format:',
'ansi',
];
$params = $this->getopt('hq:f:a', $longopts);
'ansi'
);
$params = $this->getopt(
'hq:f:a',
$longopts
);
if ($params === false) {
return false;
}
$this->mergeLongOpts($params, $longopts);
if (! isset($params['f'])) {
$params['f'] = 'cli';
}
if (! in_array($params['f'], ['html', 'cli', 'text'])) {
if (! in_array($params['f'], array('html', 'cli', 'text'))) {
echo "ERROR: Invalid value for format!\n";
return false;
@@ -95,26 +68,19 @@ class CLI
return $params;
}
/**
* @return int
*/
public function runHighlight()
{
$params = $this->parseHighlight();
if ($params === false) {
return 1;
}
if (isset($params['h'])) {
$this->usageHighlight();
return 0;
}
if (! isset($params['q'])) {
$stdIn = $this->readStdin();
if ($stdIn) {
if (!isset($params['q'])) {
if ($stdIn = $this->readStdin()) {
$params['q'] = $stdIn;
}
}
@@ -122,77 +88,63 @@ class CLI
if (isset($params['a'])) {
Context::setMode('ANSI_QUOTES');
}
if (isset($params['q'])) {
echo Formatter::format(
$params['q'],
['type' => $params['f']]
array('type' => $params['f'])
);
echo "\n";
return 0;
}
echo "ERROR: Missing parameters!\n";
$this->usageHighlight();
return 1;
}
/**
* @return void
*/
public function usageLint()
{
echo "Usage: lint-query --query SQL [--ansi]\n";
echo " cat file.sql | lint-query\n";
}
/**
* @return mixed
*/
public function parseLint()
{
$longopts = [
$longopts = array(
'help',
'query:',
'context:',
'ansi',
];
$params = $this->getopt('hq:c:a', $longopts);
'ansi'
);
$params = $this->getopt(
'hq:c:a',
$longopts
);
$this->mergeLongOpts($params, $longopts);
return $params;
}
/**
* @return int
*/
public function runLint()
{
$params = $this->parseLint();
if ($params === false) {
return 1;
}
if (isset($params['h'])) {
$this->usageLint();
return 0;
}
if (isset($params['c'])) {
Context::load($params['c']);
}
if (! isset($params['q'])) {
$stdIn = $this->readStdin();
if ($stdIn) {
if (!isset($params['q'])) {
if ($stdIn = $this->readStdin()) {
$params['q'] = $stdIn;
}
}
if (isset($params['a'])) {
Context::setMode('ANSI_QUOTES');
}
@@ -200,69 +152,57 @@ class CLI
if (isset($params['q'])) {
$lexer = new Lexer($params['q'], false);
$parser = new Parser($lexer->list);
$errors = Error::get([$lexer, $parser]);
$errors = Error::get(array($lexer, $parser));
if (count($errors) === 0) {
return 0;
}
$output = Error::format($errors);
echo implode("\n", $output);
echo "\n";
return 10;
}
echo "ERROR: Missing parameters!\n";
$this->usageLint();
return 1;
}
/**
* @return void
*/
public function usageTokenize()
{
echo "Usage: tokenize-query --query SQL [--ansi]\n";
echo " cat file.sql | tokenize-query\n";
}
/**
* @return mixed
*/
public function parseTokenize()
{
$longopts = [
$longopts = array(
'help',
'query:',
'ansi',
];
$params = $this->getopt('hq:a', $longopts);
'ansi'
);
$params = $this->getopt(
'hq:a',
$longopts
);
$this->mergeLongOpts($params, $longopts);
return $params;
}
/**
* @return int
*/
public function runTokenize()
{
$params = $this->parseTokenize();
if ($params === false) {
return 1;
}
if (isset($params['h'])) {
$this->usageTokenize();
return 0;
}
if (! isset($params['q'])) {
$stdIn = $this->readStdin();
if ($stdIn) {
if (!isset($params['q'])) {
if ($stdIn = $this->readStdin()) {
$params['q'] = $stdIn;
}
}
@@ -270,7 +210,6 @@ class CLI
if (isset($params['a'])) {
Context::setMode('ANSI_QUOTES');
}
if (isset($params['q'])) {
$lexer = new Lexer($params['q'], false);
foreach ($lexer->list->tokens as $idx => $token) {
@@ -288,21 +227,17 @@ class CLI
return 0;
}
echo "ERROR: Missing parameters!\n";
$this->usageTokenize();
return 1;
}
/**
* @return string|false
*/
public function readStdin()
{
$read = [STDIN];
$write = [];
$except = [];
$read = array(STDIN);
$write = array();
$except = array();
// Assume there's nothing to be read from STDIN.
$stdin = null;
@@ -1,22 +1,20 @@
<?php
/**
* Error related utilities.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Exceptions\LexerException;
use PhpMyAdmin\SqlParser\Exceptions\ParserException;
use PhpMyAdmin\SqlParser\Lexer;
use PhpMyAdmin\SqlParser\Parser;
use function htmlspecialchars;
use function sprintf;
/**
* Error related utilities.
*
* @category Exceptions
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Error
{
@@ -30,32 +28,30 @@ class Error
* `$err[1]` holds the error code.
* `$err[2]` holds the string that caused the issue.
* `$err[3]` holds the position of the string.
* (i.e. `[$msg, $code, $str, $pos]`)
* (i.e. `array($msg, $code, $str, $pos)`)
*/
public static function get($objs)
{
$ret = [];
$ret = array();
foreach ($objs as $obj) {
if ($obj instanceof Lexer) {
/** @var LexerException $err */
foreach ($obj->errors as $err) {
$ret[] = [
$ret[] = array(
$err->getMessage(),
$err->getCode(),
$err->ch,
$err->pos,
];
$err->pos
);
}
} elseif ($obj instanceof Parser) {
/** @var ParserException $err */
foreach ($obj->errors as $err) {
$ret[] = [
$ret[] = array(
$err->getMessage(),
$err->getCode(),
$err->token->token,
$err->token->position,
];
$err->token->position
);
}
}
}
@@ -81,7 +77,7 @@ class Error
$errors,
$format = '#%1$d: %2$s (near "%4$s" at position %5$d)'
) {
$ret = [];
$ret = array();
$i = 0;
foreach ($errors as $key => $err) {
@@ -90,7 +86,7 @@ class Error
++$i,
$err[0],
$err[1],
htmlspecialchars((string) $err[2]),
htmlspecialchars($err[2]),
$err[3]
);
}
@@ -1,10 +1,9 @@
<?php
/**
* Utilities that are used for formatting queries.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Components\JoinKeyword;
@@ -13,22 +12,12 @@ use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function array_merge;
use function array_pop;
use function end;
use function htmlspecialchars;
use function in_array;
use function mb_strlen;
use function str_repeat;
use function str_replace;
use function strpos;
use function strtoupper;
use const ENT_NOQUOTES;
use const PHP_SAPI;
/**
* Utilities that are used for formatting queries.
*
* @category Misc
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Formatter
{
@@ -57,10 +46,10 @@ class Formatter
*
* @var array
*/
public static $SHORT_CLAUSES = [
public static $SHORT_CLAUSES = array(
'CREATE' => true,
'INSERT' => true,
];
'INSERT' => true
);
/**
* Clauses that must be inlined.
@@ -69,7 +58,7 @@ class Formatter
*
* @var array
*/
public static $INLINE_CLAUSES = [
public static $INLINE_CLAUSES = array(
'CREATE' => true,
'INTO' => true,
'LIMIT' => true,
@@ -77,13 +66,15 @@ class Formatter
'PARTITION' => true,
'PROCEDURE' => true,
'SUBPARTITION BY' => true,
'VALUES' => true,
];
'VALUES' => true
);
/**
* Constructor.
*
* @param array $options the formatting options
*/
public function __construct(array $options = [])
public function __construct(array $options = array())
{
$this->options = $this->getMergedOptions($options);
}
@@ -108,11 +99,11 @@ class Formatter
$options['formats'] = $this->getDefaultFormats();
}
if ($options['line_ending'] === null) {
if (is_null($options['line_ending'])) {
$options['line_ending'] = $options['type'] === 'html' ? '<br/>' : "\n";
}
if ($options['indentation'] === null) {
if (is_null($options['indentation'])) {
$options['indentation'] = $options['type'] === 'html' ? '&nbsp;&nbsp;&nbsp;&nbsp;' : ' ';
}
@@ -129,13 +120,13 @@ class Formatter
*/
protected function getDefaultOptions()
{
return [
return array(
/*
* The format of the result.
*
* @var string The type ('text', 'cli' or 'html')
*/
'type' => PHP_SAPI === 'cli' ? 'cli' : 'text',
'type' => php_sapi_name() === 'cli' ? 'cli' : 'text',
/*
* The line ending used.
@@ -179,129 +170,122 @@ class Formatter
*
* @var bool
*/
'indent_parts' => true,
];
'indent_parts' => true
);
}
/**
* The styles used for HTML formatting.
* [$type, $flags, $span, $callback].
* array($type, $flags, $span, $callback).
*
* @return array
*/
protected function getDefaultFormats()
{
return [
[
return array(
array(
'type' => Token::TYPE_KEYWORD,
'flags' => Token::FLAG_KEYWORD_RESERVED,
'html' => 'class="sql-reserved"',
'cli' => "\x1b[35m",
'function' => 'strtoupper',
],
[
),
array(
'type' => Token::TYPE_KEYWORD,
'flags' => 0,
'html' => 'class="sql-keyword"',
'cli' => "\x1b[95m",
'function' => 'strtoupper',
],
[
),
array(
'type' => Token::TYPE_COMMENT,
'flags' => 0,
'html' => 'class="sql-comment"',
'cli' => "\x1b[37m",
'function' => '',
],
[
),
array(
'type' => Token::TYPE_BOOL,
'flags' => 0,
'html' => 'class="sql-atom"',
'cli' => "\x1b[36m",
'function' => 'strtoupper',
],
[
),
array(
'type' => Token::TYPE_NUMBER,
'flags' => 0,
'html' => 'class="sql-number"',
'cli' => "\x1b[92m",
'function' => 'strtolower',
],
[
),
array(
'type' => Token::TYPE_STRING,
'flags' => 0,
'html' => 'class="sql-string"',
'cli' => "\x1b[91m",
'function' => '',
],
[
),
array(
'type' => Token::TYPE_SYMBOL,
'flags' => Token::FLAG_SYMBOL_PARAMETER,
'html' => 'class="sql-parameter"',
'cli' => "\x1b[31m",
'function' => '',
],
[
),
array(
'type' => Token::TYPE_SYMBOL,
'flags' => 0,
'html' => 'class="sql-variable"',
'cli' => "\x1b[36m",
'function' => '',
],
];
)
);
}
private static function mergeFormats(array $formats, array $newFormats): array
private static function mergeFormats(array $formats, array $newFormats)
{
$added = [];
$integers = [
$added = array();
$integers = array(
'flags',
'type',
];
$strings = [
'type'
);
$strings = array(
'html',
'cli',
'function',
];
'function'
);
/* Sanitize the array so that we do not have to care later */
foreach ($newFormats as $j => $new) {
foreach ($integers as $name) {
if (isset($new[$name])) {
continue;
if (! isset($new[$name])) {
$newFormats[$j][$name] = 0;
}
$newFormats[$j][$name] = 0;
}
foreach ($strings as $name) {
if (isset($new[$name])) {
continue;
if (! isset($new[$name])) {
$newFormats[$j][$name] = '';
}
$newFormats[$j][$name] = '';
}
}
/* Process changes to existing formats */
foreach ($formats as $i => $original) {
foreach ($newFormats as $j => $new) {
if ($new['type'] !== $original['type'] || $original['flags'] !== $new['flags']) {
continue;
if ($new['type'] === $original['type']
&& $original['flags'] === $new['flags']
) {
$formats[$i] = $new;
$added[] = $j;
}
$formats[$i] = $new;
$added[] = $j;
}
}
/* Add not already handled formats */
foreach ($newFormats as $j => $new) {
if (in_array($j, $added)) {
continue;
if (! in_array($j, $added)) {
$formats[] = $new;
}
$formats[] = $new;
}
return $formats;
@@ -357,7 +341,7 @@ class Formatter
*
* @var array
*/
$blocksIndentation = [];
$blocksIndentation = array();
/**
* A stack that keeps track of the line endings every time a new block
@@ -365,7 +349,7 @@ class Formatter
*
* @var array
*/
$blocksLineEndings = [];
$blocksLineEndings = array();
/**
* Whether clause's options were formatted.
@@ -400,15 +384,13 @@ class Formatter
if ($curr->type === Token::TYPE_WHITESPACE) {
// Keep linebreaks before and after comments
if (
strpos($curr->token, "\n") !== false && (
if (strpos($curr->token, "\n") !== false && (
($prev !== null && $prev->type === Token::TYPE_COMMENT) ||
($next !== null && $next->type === Token::TYPE_COMMENT)
)
) {
$lineEnded = true;
}
// Whitespaces are skipped because the formatter adds its own.
continue;
}
@@ -427,8 +409,7 @@ class Formatter
}
// The options of a clause should stay on the same line and everything that follows.
if (
$this->options['parts_newline']
if ($this->options['parts_newline']
&& ! $formattedOptions
&& empty(self::$INLINE_CLAUSES[$lastClause])
&& (
@@ -445,13 +426,8 @@ class Formatter
}
// Checking if this clause ended.
$isClause = static::isClause($curr);
if ($isClause) {
if (
($isClause === 2 || $this->options['clause_newline'])
&& empty(self::$SHORT_CLAUSES[$lastClause])
) {
if ($isClause = static::isClause($curr)) {
if (($isClause === 2 || $this->options['clause_newline']) && empty(self::$SHORT_CLAUSES[$lastClause])) {
$lineEnded = true;
if ($this->options['parts_newline'] && $indent > 0) {
--$indent;
@@ -460,10 +436,8 @@ class Formatter
}
// Inline JOINs
if (
($prev->type === Token::TYPE_KEYWORD && isset(JoinKeyword::$JOINS[$prev->value]))
|| (in_array($curr->value, ['ON', 'USING'], true)
&& isset(JoinKeyword::$JOINS[$list->tokens[$list->idx - 2]->value]))
if (($prev->type === Token::TYPE_KEYWORD && isset(JoinKeyword::$JOINS[$prev->value]))
|| (in_array($curr->value, array('ON', 'USING'), true) && isset(JoinKeyword::$JOINS[$list->tokens[$list->idx - 2]->value]))
|| isset($list->tokens[$list->idx - 4], JoinKeyword::$JOINS[$list->tokens[$list->idx - 4]->value])
|| isset($list->tokens[$list->idx - 6], JoinKeyword::$JOINS[$list->tokens[$list->idx - 6]->value])
) {
@@ -485,8 +459,7 @@ class Formatter
// Fragments delimited by a comma are broken into multiple
// pieces only if the clause is not inlined or this fragment
// is between brackets that are on new line.
if (
end($blocksLineEndings) === true
if (end($blocksLineEndings) === true
|| (
empty(self::$INLINE_CLAUSES[$lastClause])
&& ! $shortGroup
@@ -508,7 +481,6 @@ class Formatter
$lineEnded = true;
$shortGroup = false;
}
$blocksLineEndings[] = $lineEnded;
} elseif ($curr->type === Token::TYPE_OPERATOR && $curr->value === ')') {
$indent = array_pop($blocksIndentation);
@@ -522,23 +494,20 @@ class Formatter
// Finishing the line.
if ($lineEnded) {
$ret .= $this->options['line_ending']
. str_repeat($this->options['indentation'], (int) $indent);
. str_repeat($this->options['indentation'], $indent);
$lineEnded = false;
} else {
// If the line ended there is no point in adding whitespaces.
// Also, some tokens do not have spaces before or after them.
if (
// A space after delimiters that are longer than 2 characters.
if (// A space after delimiters that are longer than 2 characters.
$prev->keyword === 'DELIMITER'
|| ! (
($prev->type === Token::TYPE_OPERATOR && ($prev->value === '.' || $prev->value === '('))
// No space after . (
|| ($curr->type === Token::TYPE_OPERATOR
&& ($curr->value === '.' || $curr->value === ','
|| $curr->value === '(' || $curr->value === ')'))
|| ($curr->type === Token::TYPE_OPERATOR && ($curr->value === '.' || $curr->value === ',' || $curr->value === '(' || $curr->value === ')'))
// No space before . , ( )
|| $curr->type === Token::TYPE_DELIMITER && mb_strlen((string) $curr->value, 'UTF-8') < 2
|| $curr->type === Token::TYPE_DELIMITER && mb_strlen($curr->value, 'UTF-8') < 2
)
) {
$ret .= ' ';
@@ -557,10 +526,10 @@ class Formatter
return $ret;
}
public function escapeConsole(string $string): string
public function escapeConsole($string)
{
return str_replace(
[
array(
"\x00",
"\x01",
"\x02",
@@ -593,8 +562,8 @@ class Formatter
"\x1D",
"\x1E",
"\x1F",
],
[
),
array(
'\x00',
'\x01',
'\x02',
@@ -627,7 +596,7 @@ class Formatter
'\x1D',
'\x1E',
'\x1F',
],
),
$string
);
}
@@ -645,32 +614,30 @@ class Formatter
static $prev;
foreach ($this->options['formats'] as $format) {
if ($token->type !== $format['type'] || ! (($token->flags & $format['flags']) === $format['flags'])) {
continue;
}
// Running transformation function.
if (! empty($format['function'])) {
$func = $format['function'];
$text = $func($text);
}
// Formatting HTML.
if ($this->options['type'] === 'html') {
return '<span ' . $format['html'] . '>' . htmlspecialchars($text, ENT_NOQUOTES) . '</span>';
}
if ($this->options['type'] === 'cli') {
if ($prev !== $format['cli']) {
$prev = $format['cli'];
return $format['cli'] . $this->escapeConsole($text);
if ($token->type === $format['type']
&& ($token->flags & $format['flags']) === $format['flags']
) {
// Running transformation function.
if (! empty($format['function'])) {
$func = $format['function'];
$text = $func($text);
}
return $this->escapeConsole($text);
}
// Formatting HTML.
if ($this->options['type'] === 'html') {
return '<span ' . $format['html'] . '>' . htmlspecialchars($text, ENT_NOQUOTES) . '</span>';
} elseif ($this->options['type'] === 'cli') {
if ($prev !== $format['cli']) {
$prev = $format['cli'];
break;
return $format['cli'] . $this->escapeConsole($text);
}
return $this->escapeConsole($text);
}
break;
}
}
if ($this->options['type'] === 'cli') {
@@ -681,9 +648,7 @@ class Formatter
}
return $this->escapeConsole($text);
}
if ($this->options['type'] === 'html') {
} elseif ($this->options['type'] === 'html') {
return htmlspecialchars($text, ENT_NOQUOTES);
}
@@ -698,7 +663,7 @@ class Formatter
*
* @return string the formatted string
*/
public static function format($query, array $options = [])
public static function format($query, array $options = array())
{
$lexer = new Lexer($query);
$formatter = new self($options);
@@ -748,7 +713,7 @@ class Formatter
}
// Keeping track of this group's length.
$length += mb_strlen((string) $list->tokens[$idx]->value, 'UTF-8');
$length += mb_strlen($list->tokens[$idx]->value, 'UTF-8');
}
return $length;
@@ -763,14 +728,12 @@ class Formatter
*/
public static function isClause($token)
{
if (
($token->type === Token::TYPE_KEYWORD && isset(Parser::$STATEMENT_PARSERS[$token->keyword]))
if (($token->type === Token::TYPE_KEYWORD && isset(Parser::$STATEMENT_PARSERS[$token->keyword]))
|| ($token->type === Token::TYPE_NONE && strtoupper($token->token) === 'DELIMITER')
) {
return 2;
}
if ($token->type === Token::TYPE_KEYWORD && isset(Parser::$KEYWORD_PARSERS[$token->keyword])) {
} elseif ($token->type === Token::TYPE_KEYWORD && isset(Parser::$KEYWORD_PARSERS[$token->keyword])
) {
return 1;
}
+26 -19
View File
@@ -1,10 +1,9 @@
<?php
/**
* Miscellaneous utilities.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Components\Expression;
@@ -12,6 +11,10 @@ use PhpMyAdmin\SqlParser\Statements\SelectStatement;
/**
* Miscellaneous utilities.
*
* @category Misc
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Misc
{
@@ -25,13 +28,16 @@ class Misc
*/
public static function getAliases($statement, $database)
{
if (! ($statement instanceof SelectStatement) || empty($statement->expr) || empty($statement->from)) {
return [];
if (! ($statement instanceof SelectStatement)
|| empty($statement->expr)
|| empty($statement->from)
) {
return array();
}
$retval = [];
$retval = array();
$tables = [];
$tables = array();
/**
* Expressions that may contain aliases.
@@ -53,41 +59,42 @@ class Misc
continue;
}
$thisDb = isset($expr->database) && ($expr->database !== '') ?
$thisDb = (isset($expr->database) && ($expr->database !== '')) ?
$expr->database : $database;
if (! isset($retval[$thisDb])) {
$retval[$thisDb] = [
$retval[$thisDb] = array(
'alias' => null,
'tables' => [],
];
'tables' => array()
);
}
if (! isset($retval[$thisDb]['tables'][$expr->table])) {
$retval[$thisDb]['tables'][$expr->table] = [
'alias' => isset($expr->alias) && ($expr->alias !== '') ?
$retval[$thisDb]['tables'][$expr->table] = array(
'alias' => (isset($expr->alias) && ($expr->alias !== '')) ?
$expr->alias : null,
'columns' => [],
];
'columns' => array()
);
}
if (! isset($tables[$thisDb])) {
$tables[$thisDb] = [];
$tables[$thisDb] = array();
}
$tables[$thisDb][$expr->alias] = $expr->table;
}
foreach ($statement->expr as $expr) {
if (! isset($expr->column, $expr->alias) || ($expr->column === '') || ($expr->alias === '')) {
if (! isset($expr->column, $expr->alias) || ($expr->column === '') || ($expr->alias === '')
) {
continue;
}
$thisDb = isset($expr->database) && ($expr->database !== '') ?
$thisDb = (isset($expr->database) && ($expr->database !== '')) ?
$expr->database : $database;
if (isset($expr->table) && ($expr->table !== '')) {
$thisTable = $tables[$thisDb][$expr->table] ?? $expr->table;
$thisTable = isset($tables[$thisDb][$expr->table]) ?
$tables[$thisDb][$expr->table] : $expr->table;
$retval[$thisDb]['tables'][$thisTable]['columns'][$expr->column] = $expr->alias;
} else {
foreach ($retval[$thisDb]['tables'] as &$table) {
+96 -106
View File
@@ -1,10 +1,9 @@
<?php
/**
* Statement utilities.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Components\Expression;
@@ -34,24 +33,21 @@ use PhpMyAdmin\SqlParser\Statements\UpdateStatement;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use function array_flip;
use function array_keys;
use function count;
use function in_array;
use function is_string;
use function trim;
/**
* Statement utilities.
*
* @category Statement
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Query
{
/**
* Functions that set the flag `is_func`.
*
* @var string[]
* @var array
*/
public static $FUNCTIONS = [
public static $FUNCTIONS = array(
'SUM',
'AVG',
'STD',
@@ -59,11 +55,10 @@ class Query
'MIN',
'MAX',
'BIT_OR',
'BIT_AND',
];
'BIT_AND'
);
/** @var array<string,false> */
public static $ALLFLAGS = [
public static $ALLFLAGS = array(
/*
* select ... DISTINCT ...
*/
@@ -216,8 +211,8 @@ class Query
/*
* ... UNION ...
*/
'union' => false,
];
'union' => false
);
/**
* Gets an array with flags select statement has.
@@ -244,7 +239,9 @@ class Query
$flags['is_group'] = true;
}
if (! empty($statement->into) && ($statement->into->type === 'OUTFILE')) {
if (! empty($statement->into)
&& ($statement->into->type === 'OUTFILE')
) {
$flags['is_export'] = true;
}
@@ -263,15 +260,14 @@ class Query
$flags['is_func'] = true;
}
}
if (empty($expr->subquery)) {
continue;
if (! empty($expr->subquery)) {
$flags['is_subquery'] = true;
}
$flags['is_subquery'] = true;
}
if (! empty($statement->procedure) && ($statement->procedure->name === 'ANALYSE')) {
if (! empty($statement->procedure)
&& ($statement->procedure->name === 'ANALYSE')
) {
$flags['is_analyse'] = true;
}
@@ -304,7 +300,7 @@ class Query
*/
public static function getFlags($statement, $all = false)
{
$flags = ['querytype' => false];
$flags = array('querytype' => false);
if ($all) {
$flags = self::$ALLFLAGS;
}
@@ -341,7 +337,9 @@ class Query
$flags['querytype'] = 'DROP';
$flags['reload'] = true;
if ($statement->options->has('DATABASE') || $statement->options->has('SCHEMA')) {
if ($statement->options->has('DATABASE')
|| $statement->options->has('SCHEMA')
) {
$flags['drop_database'] = true;
}
} elseif ($statement instanceof ExplainStatement) {
@@ -372,15 +370,13 @@ class Query
$flags['querytype'] = 'SET';
}
if (
($statement instanceof SelectStatement)
if (($statement instanceof SelectStatement)
|| ($statement instanceof UpdateStatement)
|| ($statement instanceof DeleteStatement)
) {
if (! empty($statement->limit)) {
$flags['limit'] = true;
}
if (! empty($statement->order)) {
$flags['order'] = true;
}
@@ -420,20 +416,19 @@ class Query
$ret['statement'] = $statement;
if ($statement instanceof SelectStatement) {
$ret['select_tables'] = [];
$ret['select_expr'] = [];
$ret['select_tables'] = array();
$ret['select_expr'] = array();
// Finding tables' aliases and their associated real names.
$tableAliases = [];
$tableAliases = array();
foreach ($statement->from as $expr) {
if (! isset($expr->table, $expr->alias) || ($expr->table === '') || ($expr->alias === '')) {
continue;
if (isset($expr->table, $expr->alias) && ($expr->table !== '') && ($expr->alias !== '')
) {
$tableAliases[$expr->alias] = array(
$expr->table,
isset($expr->database) ? $expr->database : null
);
}
$tableAliases[$expr->alias] = [
$expr->table,
$expr->database ?? null,
];
}
// Trying to find selected tables only from the select expression.
@@ -444,13 +439,12 @@ class Query
if (isset($tableAliases[$expr->table])) {
$arr = $tableAliases[$expr->table];
} else {
$arr = [
$arr = array(
$expr->table,
isset($expr->database) && ($expr->database !== '') ?
$expr->database : null,
];
(isset($expr->database) && ($expr->database !== '')) ?
$expr->database : null
);
}
if (! in_array($arr, $ret['select_tables'])) {
$ret['select_tables'][] = $arr;
}
@@ -464,20 +458,16 @@ class Query
// extracted from the FROM clause.
if (empty($ret['select_tables'])) {
foreach ($statement->from as $expr) {
if (! isset($expr->table) || ($expr->table === '')) {
continue;
if (isset($expr->table) && ($expr->table !== '')) {
$arr = array(
$expr->table,
(isset($expr->database) && ($expr->database !== '')) ?
$expr->database : null
);
if (! in_array($arr, $ret['select_tables'])) {
$ret['select_tables'][] = $arr;
}
}
$arr = [
$expr->table,
isset($expr->database) && ($expr->database !== '') ?
$expr->database : null,
];
if (in_array($arr, $ret['select_tables'])) {
continue;
}
$ret['select_tables'][] = $arr;
}
}
}
@@ -494,22 +484,27 @@ class Query
*/
public static function getTables($statement)
{
$expressions = [];
$expressions = array();
if (($statement instanceof InsertStatement) || ($statement instanceof ReplaceStatement)) {
$expressions = [$statement->into->dest];
if (($statement instanceof InsertStatement)
|| ($statement instanceof ReplaceStatement)
) {
$expressions = array($statement->into->dest);
} elseif ($statement instanceof UpdateStatement) {
$expressions = $statement->tables;
} elseif (($statement instanceof SelectStatement) || ($statement instanceof DeleteStatement)) {
} elseif (($statement instanceof SelectStatement)
|| ($statement instanceof DeleteStatement)
) {
$expressions = $statement->from;
} elseif (($statement instanceof AlterStatement) || ($statement instanceof TruncateStatement)) {
$expressions = [$statement->table];
} elseif (($statement instanceof AlterStatement)
|| ($statement instanceof TruncateStatement)
) {
$expressions = array($statement->table);
} elseif ($statement instanceof DropStatement) {
if (! $statement->options->has('TABLE')) {
// No tables are dropped.
return [];
return array();
}
$expressions = $statement->fields;
} elseif ($statement instanceof RenameStatement) {
foreach ($statement->renames as $rename) {
@@ -517,15 +512,13 @@ class Query
}
}
$ret = [];
$ret = array();
foreach ($expressions as $expr) {
if (empty($expr->table)) {
continue;
if (! empty($expr->table)) {
$expr->expr = null; // Force rebuild.
$expr->alias = null; // Aliases are not required.
$ret[] = Expression::build($expr);
}
$expr->expr = null; // Force rebuild.
$expr->alias = null; // Aliases are not required.
$ret[] = Expression::build($expr);
}
return $ret;
@@ -598,7 +591,7 @@ class Query
*
* @var int
*/
$clauseIdx = $clauses[$clauseType] ?? -1;
$clauseIdx = isset($clauses[$clauseType]) ? $clauses[$clauseType] : -1;
$firstClauseIdx = $clauseIdx;
$lastClauseIdx = $clauseIdx;
@@ -642,8 +635,7 @@ class Query
if ($brackets === 0) {
// Checking if the section was changed.
if (
($token->type === Token::TYPE_KEYWORD)
if (($token->type === Token::TYPE_KEYWORD)
&& isset($clauses[$token->keyword])
&& ($clauses[$token->keyword] >= $currIdx)
) {
@@ -656,11 +648,9 @@ class Query
}
}
if (($firstClauseIdx > $currIdx) || ($currIdx > $lastClauseIdx)) {
continue;
if (($firstClauseIdx <= $currIdx) && ($currIdx <= $lastClauseIdx)) {
$ret .= $token->token;
}
$ret .= $token->token;
}
return trim($ret);
@@ -708,7 +698,7 @@ class Query
* @param Statement $statement the parsed query that has to be modified
* @param TokensList $list the list of tokens
* @param array $ops Clauses to be replaced. Contains multiple
* arrays having two values: [$old, $new].
* arrays having two values: array($old, $new).
* Clauses must be sorted.
*
* @return string
@@ -731,7 +721,12 @@ class Query
// If there is only one clause, `replaceClause()` should be used.
if ($count === 1) {
return static::replaceClause($statement, $list, $ops[0][0], $ops[0][1]);
return static::replaceClause(
$statement,
$list,
$ops[0][0],
$ops[0][1]
);
}
// Adding everything before first replacement.
@@ -742,15 +737,15 @@ class Query
$ret .= $clause[1] . ' ';
// Adding everything between this and next replacement.
if ($i + 1 === $count) {
continue;
if ($i + 1 !== $count) {
$ret .= static::getClause($statement, $list, $clause[0], $ops[$i + 1][0]) . ' ';
}
$ret .= static::getClause($statement, $list, $clause[0], $ops[$i + 1][0]) . ' ';
}
// Adding everything after the last replacement.
return $ret . static::getClause($statement, $list, $ops[$count - 1][0], 1);
$ret .= static::getClause($statement, $list, $ops[$count - 1][0], 1);
return $ret;
}
/**
@@ -801,11 +796,11 @@ class Query
// No statement was found so we return the entire query as being the
// remaining part.
if (! $fullStatement) {
return [
return array(
null,
$query,
$delimiter,
];
$delimiter
);
}
// At least one query was found so we have to build the rest of the
@@ -815,11 +810,11 @@ class Query
$query .= $list->tokens[$list->idx]->token;
}
return [
return array(
trim($statement),
$query,
$delimiter,
];
$delimiter
);
}
/**
@@ -863,20 +858,15 @@ class Query
}
}
if ($brackets !== 0) {
continue;
}
if (
($token->type === Token::TYPE_KEYWORD)
&& isset($clauses[$token->keyword])
&& ($clause === $token->keyword)
) {
return $i;
}
if ($token->keyword === 'UNION') {
return -1;
if ($brackets === 0) {
if (($token->type === Token::TYPE_KEYWORD)
&& isset($clauses[$token->keyword])
&& ($clause === $token->keyword)
) {
return $i;
} elseif ($token->keyword === 'UNION') {
return -1;
}
}
}
@@ -1,10 +1,9 @@
<?php
/**
* Routine utilities.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Components\DataType;
@@ -13,11 +12,12 @@ use PhpMyAdmin\SqlParser\Lexer;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statements\CreateStatement;
use function implode;
use function is_string;
/**
* Routine utilities.
*
* @category Routines
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Routine
{
@@ -36,27 +36,27 @@ class Routine
$type = DataType::parse(new Parser(), $lexer->list);
if ($type === null) {
return [
return array(
'',
'',
'',
'',
'',
];
''
);
}
$options = [];
$options = array();
foreach ($type->options->options as $opt) {
$options[] = is_string($opt) ? $opt : $opt['value'];
}
return [
return array(
'',
'',
$type->name,
implode(',', $type->parameters),
implode(' ', $options),
];
implode(' ', $options)
);
}
/**
@@ -74,29 +74,29 @@ class Routine
$param = ParameterDefinition::parse(new Parser(), $lexer->list);
if (empty($param[0])) {
return [
return array(
'',
'',
'',
'',
'',
];
''
);
}
$param = $param[0];
$options = [];
$options = array();
foreach ($param->type->options->options as $opt) {
$options[] = is_string($opt) ? $opt : $opt['value'];
}
return [
return array(
empty($param->inOut) ? '' : $param->inOut,
$param->name,
$param->type->name,
implode(',', $param->type->parameters),
implode(' ', $options),
];
implode(' ', $options)
);
}
/**
@@ -108,15 +108,15 @@ class Routine
*/
public static function getParameters($statement)
{
$retval = [
$retval = array(
'num' => 0,
'dir' => [],
'name' => [],
'type' => [],
'length' => [],
'length_arr' => [],
'opts' => [],
];
'dir' => array(),
'name' => array(),
'type' => array(),
'length' => array(),
'length_arr' => array(),
'opts' => array()
);
if (! empty($statement->parameters)) {
$idx = 0;
@@ -126,12 +126,11 @@ class Routine
$retval['type'][$idx] = $param->type->name;
$retval['length'][$idx] = implode(',', $param->type->parameters);
$retval['length_arr'][$idx] = $param->type->parameters;
$retval['opts'][$idx] = [];
$retval['opts'][$idx] = array();
foreach ($param->type->options->options as $opt) {
$retval['opts'][$idx][] = is_string($opt) ?
$opt : $opt['value'];
}
$retval['opts'][$idx] = implode(' ', $retval['opts'][$idx]);
++$idx;
}
@@ -1,19 +1,19 @@
<?php
/**
* Table utilities.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Statements\CreateStatement;
use function is_array;
use function str_replace;
/**
* Table utilities.
*
* @category Statement
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Table
{
@@ -26,47 +26,49 @@ class Table
*/
public static function getForeignKeys($statement)
{
if (empty($statement->fields) || (! is_array($statement->fields)) || (! $statement->options->has('TABLE'))) {
return [];
if (empty($statement->fields)
|| (! is_array($statement->fields))
|| (! $statement->options->has('TABLE'))
) {
return array();
}
$ret = [];
$ret = array();
foreach ($statement->fields as $field) {
if (empty($field->key) || ($field->key->type !== 'FOREIGN KEY')) {
continue;
}
$columns = [];
$columns = array();
foreach ($field->key->columns as $column) {
if (! isset($column['name'])) {
continue;
}
$columns[] = $column['name'];
}
$tmp = [
$tmp = array(
'constraint' => $field->name,
'index_list' => $columns,
];
'index_list' => $columns
);
if (! empty($field->references)) {
$tmp['ref_db_name'] = $field->references->table->database;
$tmp['ref_table_name'] = $field->references->table->table;
$tmp['ref_index_list'] = $field->references->columns;
$opt = $field->references->options->has('ON UPDATE');
if ($opt) {
if ($opt = $field->references->options->has('ON UPDATE')) {
$tmp['on_update'] = str_replace(' ', '_', $opt);
}
$opt = $field->references->options->has('ON DELETE');
if ($opt) {
if ($opt = $field->references->options->has('ON DELETE')) {
$tmp['on_delete'] = str_replace(' ', '_', $opt);
}
// if (($opt = $field->references->options->has('MATCH'))) {
// $tmp['match'] = str_replace(' ', '_', $opt);
// }
}
$ret[] = $tmp;
@@ -84,11 +86,14 @@ class Table
*/
public static function getFields($statement)
{
if (empty($statement->fields) || (! is_array($statement->fields)) || (! $statement->options->has('TABLE'))) {
return [];
if (empty($statement->fields)
|| (! is_array($statement->fields))
|| (! $statement->options->has('TABLE'))
) {
return array();
}
$ret = [];
$ret = array();
foreach ($statement->fields as $field) {
// Skipping keys.
@@ -96,44 +101,36 @@ class Table
continue;
}
$ret[$field->name] = [
$ret[$field->name] = array(
'type' => $field->type->name,
'timestamp_not_null' => false,
];
'timestamp_not_null' => false
);
if (! $field->options) {
continue;
}
if ($field->options) {
if ($field->type->name === 'TIMESTAMP') {
if ($field->options->has('NOT NULL')) {
$ret[$field->name]['timestamp_not_null'] = true;
}
}
if ($field->type->name === 'TIMESTAMP') {
if ($field->options->has('NOT NULL')) {
$ret[$field->name]['timestamp_not_null'] = true;
if ($option = $field->options->has('DEFAULT')) {
$ret[$field->name]['default_value'] = $option;
if ($option === 'CURRENT_TIMESTAMP') {
$ret[$field->name]['default_current_timestamp'] = true;
}
}
if ($option = $field->options->has('ON UPDATE')) {
if ($option === 'CURRENT_TIMESTAMP') {
$ret[$field->name]['on_update_current_timestamp'] = true;
}
}
if ($option = $field->options->has('AS')) {
$ret[$field->name]['generated'] = true;
$ret[$field->name]['expr'] = $option;
}
}
$option = $field->options->has('DEFAULT');
if ($option) {
$ret[$field->name]['default_value'] = $option;
if ($option === 'CURRENT_TIMESTAMP') {
$ret[$field->name]['default_current_timestamp'] = true;
}
}
$option = $field->options->has('ON UPDATE');
if ($option === 'CURRENT_TIMESTAMP') {
$ret[$field->name]['on_update_current_timestamp'] = true;
}
$option = $field->options->has('AS');
if (! $option) {
continue;
}
$ret[$field->name]['generated'] = true;
$ret[$field->name]['expr'] = $option;
}
return $ret;
@@ -1,22 +1,21 @@
<?php
/**
* Token utilities.
*/
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Utils;
use PhpMyAdmin\SqlParser\Lexer;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use PhpMyAdmin\SqlParser\UtfString;
use function count;
use function strcasecmp;
/**
* Token utilities.
*
* @category Token
*
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Tokens
{
@@ -31,36 +30,42 @@ class Tokens
public static function match(Token $token, array $pattern)
{
// Token.
if (isset($pattern['token']) && ($pattern['token'] !== $token->token)) {
if (isset($pattern['token'])
&& ($pattern['token'] !== $token->token)
) {
return false;
}
// Value.
if (isset($pattern['value']) && ($pattern['value'] !== $token->value)) {
if (isset($pattern['value'])
&& ($pattern['value'] !== $token->value)
) {
return false;
}
if (isset($pattern['value_str']) && strcasecmp($pattern['value_str'], (string) $token->value)) {
if (isset($pattern['value_str'])
&& strcasecmp($pattern['value_str'], $token->value)
) {
return false;
}
// Type.
if (isset($pattern['type']) && ($pattern['type'] !== $token->type)) {
if (isset($pattern['type'])
&& ($pattern['type'] !== $token->type)
) {
return false;
}
// Flags.
return ! isset($pattern['flags'])
|| (! (($pattern['flags'] & $token->flags) === 0));
if (isset($pattern['flags'])
&& (($pattern['flags'] & $token->flags) === 0)
) {
return false;
}
return true;
}
/**
* @param TokensList|string|UtfString $list
* @param array $find
* @param array $replace
*
* @return TokensList
*/
public static function replaceTokens($list, array $find, array $replace)
{
/**
@@ -80,7 +85,7 @@ class Tokens
*
* @var array
*/
$newList = [];
$newList = array();
/**
* The length of the find pattern is calculated only once.