Initial commit

This commit is contained in:
2022-11-21 09:47:28 +01:00
commit 76cec83d26
11652 changed files with 1980467 additions and 0 deletions

View File

@ -0,0 +1,250 @@
<?php
/**
* This file is based on Composer's autoloader.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* @package SqlParser
* @subpackage Autoload
*/
namespace SqlParser\Autoload;
/**
* ClassLoader implements a PSR-4 class loader,
*
* This class is loosely based on the Symfony UniversalClassLoader.
* This class is a stripped version of Composer's ClassLoader.
*
* @package SqlParser
* @subpackage Autoload
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ClassLoader
{
public $prefixLengths = array();
public $prefixDirs = array();
public $fallbackDirs = array();
public $classMap = array();
public $classMapAuthoritative = false;
/**
* @param array $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if (!empty($this->classMap)) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-0 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirs = array_merge(
(array) $paths,
$this->fallbackDirs
);
} else {
$this->fallbackDirs = array_merge(
$this->fallbackDirs,
(array) $paths
);
}
} elseif (!isset($this->prefixDirs[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengths[$prefix[0]][$prefix] = $length;
$this->prefixDirs[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirs[$prefix] = array_merge(
(array) $paths,
$this->prefixDirs[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirs[$prefix] = array_merge(
$this->prefixDirs[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirs = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengths[$prefix[0]][$prefix] = $length;
$this->prefixDirs[$prefix] = (array) $paths;
}
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
*
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731
if ('\\' == $class[0]) {
$class = substr($class, 1);
}
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative) {
return false;
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if ($file === null && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if ($file === null) {
// Remember that this class does not exist.
return $this->classMap[$class] = false;
}
return $file;
}
/**
* Finds a file that defines the specified class and has the specified
* extension.
*
* @param string $class The name of the class
* @param string $ext The extension of the file
*
* @return string|false The path if found, false otherwise
*/
public function findFileWithExtension($class, $ext)
{
$logicalPath = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengths[$first])) {
foreach ($this->prefixLengths[$first] as $prefix => $length) {
if (0 === strpos($class, $prefix)) {
foreach ($this->prefixDirs[$prefix] as $dir) {
if (is_file($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPath, $length))) {
return $file;
}
}
}
}
}
foreach ($this->fallbackDirs as $dir) {
if (is_file($file = $dir . DIRECTORY_SEPARATOR . $logicalPath)) {
return $file;
}
}
return false;
}
}
if (!function_exists('SqlParser\\Autoload\\includeFile')) {
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file The name of the file
*
* @return void
*/
function includeFile($file)
{
include $file;
}
}

View File

@ -0,0 +1,78 @@
<?php
/**
* The autoloader used for loading sql-parser's components.
*
* This file is based on Composer's autoloader.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* @package SqlParser
* @subpackage Autoload
*/
namespace SqlParser\Autoload;
if (!class_exists('SqlParser\\Autoload\\ClassLoader')) {
if (! file_exists('./libraries/sql-parser/ClassLoader.php')) {
die('Invalid invocation');
}
include_once './libraries/sql-parser/ClassLoader.php';
}
use SqlParser\Autoload\ClassLoader;
/**
* Initializes the autoloader.
*
* @package SqlParser
* @subpackage Autoload
*/
class AutoloaderInit
{
/**
* The loader instance.
*
* @var ClassLoader
*/
public static $loader;
/**
* Constructs and returns the class loader.
*
* @param array $map Array containing path to each namespace.
*
* @return ClassLoader
*/
public static function getLoader(array $map)
{
if (null !== self::$loader) {
return self::$loader;
}
self::$loader = $loader = new ClassLoader();
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$loader->register(true);
return $loader;
}
}
// php-gettext is used to translate error messages.
// This must be included before any class of the parser is loaded because
// if there is no `__` function defined, the library defines a dummy one
// in `common.php`.
require_once './libraries/vendor_config.php';
require_once GETTEXT_INC;
// Initializing the autoloader.
return AutoloaderInit::getLoader(
array(
'SqlParser\\' => array(dirname(__FILE__) . '/src'),
)
);

View File

@ -0,0 +1,81 @@
<?php
/**
* Defines a component that is later extended to parse specialized components or
* keywords.
*
* There is a small difference between *Component and *Keyword classes: usually,
* *Component parsers can be reused in multiple situations and *Keyword parsers
* count on the *Component classes to do their job.
*
* @package SqlParser
*/
namespace SqlParser;
require_once 'common.php';
/**
* A component (of a statement) is a part of a statement that is common to
* multiple query types.
*
* @category Components
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
abstract class Component
{
/**
* Parses the tokens contained in the given list in the context of the given
* parser.
*
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @throws \Exception Not implemented yet.
*
* @return mixed
*/
public static function parse(
Parser $parser,
TokensList $list,
array $options = array()
) {
// This method should be abstract, but it can't be both static and
// abstract.
throw new \Exception(\__('Not implemented yet.'));
}
/**
* Builds the string representation of a component of this type.
*
* In other words, this function represents the inverse function of
* `static::parse`.
*
* @param mixed $component The component to be built.
* @param array $options Parameters for building.
*
* @throws \Exception Not implemented yet.
*
* @return string
*/
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(\__('Not implemented yet.'));
}
/**
* Builds the string representation of a component of this type.
*
* @see static::build
*
* @return string
*/
public function __toString()
{
return static::build($this);
}
}

View File

@ -0,0 +1,265 @@
<?php
/**
* Parses an alter operation.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses an alter operation.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class AlterOperation extends Component
{
/**
* All database options
*
* @var array
*/
public static $DB_OPTIONS = array(
'CHARACTER SET' => array(1, 'var'),
'CHARSET' => array(1, 'var'),
'DEFAULT CHARACTER SET' => array(1, 'var'),
'DEFAULT CHARSET' => array(1, 'var'),
'UPGRADE' => array(1, 'var'),
'COLLATE' => array(2, 'var'),
'DEFAULT COLLATE' => array(2, 'var'),
);
/**
* All table options
*
* @var array
*/
public static $TABLE_OPTIONS = array(
'ENGINE' => array(1, 'var='),
'AUTO_INCREMENT' => array(1, 'var='),
'AVG_ROW_LENGTH' => array(1, 'var'),
'MAX_ROWS' => array(1, 'var'),
'ROW_FORMAT' => array(1, 'var'),
'COMMENT' => array(1, 'var'),
'ADD' => 1,
'ALTER' => 1,
'ANALYZE' => 1,
'CHANGE' => 1,
'CHECK' => 1,
'COALESCE' => 1,
'CONVERT' => 1,
'DISABLE' => 1,
'DISCARD' => 1,
'DROP' => 1,
'ENABLE' => 1,
'IMPORT' => 1,
'MODIFY' => 1,
'OPTIMIZE' => 1,
'ORDER' => 1,
'PARTITION' => 1,
'REBUILD' => 1,
'REMOVE' => 1,
'RENAME' => 1,
'REORGANIZE' => 1,
'REPAIR' => 1,
'UPGRADE' => 1,
'COLUMN' => 2,
'CONSTRAINT' => 2,
'DEFAULT' => 2,
'TO' => 2,
'BY' => 2,
'FOREIGN' => 2,
'FULLTEXT' => 2,
'KEY' => 2,
'KEYS' => 2,
'PARTITIONING' => 2,
'PRIMARY KEY' => 2,
'SPATIAL' => 2,
'TABLESPACE' => 2,
'INDEX' => 2,
);
/**
* All view options
*
* @var array
*/
public static $VIEW_OPTIONS = array(
'AS' => 1,
);
/**
* Options of this operation.
*
* @var OptionsArray
*/
public $options;
/**
* The altered field.
*
* @var Expression
*/
public $field;
/**
* Unparsed tokens.
*
* @var Token[]|string
*/
public $unknown = array();
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return AlterOperation
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new AlterOperation();
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------[ options ]---------------------> 1
*
* 1 ----------------------[ field ]----------------------> 2
*
* 2 -------------------------[ , ]-----------------------> 0
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
// Skipping whitespaces.
if ($token->type === Token::TYPE_WHITESPACE) {
if ($state === 2) {
// When parsing the unknown part, the whitespaces are
// included to not break anything.
$ret->unknown[] = $token;
}
continue;
}
if ($state === 0) {
$ret->options = OptionsArray::parse($parser, $list, $options);
if ($ret->options->has('AS')) {
for (; $list->idx < $list->count; ++$list->idx) {
if ($list->tokens[$list->idx]->type === Token::TYPE_DELIMITER) {
break;
}
$ret->unknown[] = $list->tokens[$list->idx];
}
break;
}
$state = 1;
} elseif ($state === 1) {
$ret->field = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
'parseField' => 'column',
)
);
if ($ret->field === null) {
// No field was read. We go back one token so the next
// iteration will parse the same token, but in state 2.
--$list->idx;
}
$state = 2;
} elseif ($state === 2) {
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
} elseif (($token->value === ',') && ($brackets === 0)) {
break;
}
} elseif (!empty(Parser::$STATEMENT_PARSERS[$token->value])) {
// We have reached the end of ALTER operation and suddenly found
// a start to new statement, but have not find a delimiter between them
if (! ($token->value == 'SET' && $list->tokens[$list->idx - 1]->value == 'CHARACTER')) {
$parser->error(
__('A new statement was found, but no delimiter between it and the previous one.'),
$token
);
break;
}
}
$ret->unknown[] = $token;
}
}
if ($ret->options->isEmpty()) {
$parser->error(
__('Unrecognized alter operation.'),
$list->tokens[$list->idx]
);
}
--$list->idx;
return $ret;
}
/**
* @param AlterOperation $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = $component->options . ' ';
if ((isset($component->field)) && ($component->field !== '')) {
$ret .= $component->field . ' ';
}
$ret .= TokensList::build($component->unknown);
return $ret;
}
}

View File

@ -0,0 +1,133 @@
<?php
/**
* `VALUES` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `VALUES` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Array2d extends Component
{
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return ArrayObj[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
/**
* The number of values in each set.
*
* @var int $count
*/
$count = -1;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ array ]----------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 -----------------------[ else ]----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
// No keyword is expected.
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
break;
}
if ($state === 0) {
if ($token->value === '(') {
$arr = ArrayObj::parse($parser, $list, $options);
$arrCount = count($arr->values);
if ($count === -1) {
$count = $arrCount;
} elseif ($arrCount != $count) {
$parser->error(
sprintf(
__('%1$d values were expected, but found %2$d.'),
$count,
$arrCount
),
$token
);
}
$ret[] = $arr;
$state = 1;
} else {
break;
}
} elseif ($state === 1) {
if ($token->value === ',') {
$state = 0;
} else {
break;
}
}
}
if ($state === 0) {
$parser->error(
__('An opening bracket followed by a set of values was expected.'),
$list->tokens[$list->idx]
);
}
--$list->idx;
return $ret;
}
/**
* @param ArrayObj[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
return ArrayObj::build($component);
}
}

View File

@ -0,0 +1,193 @@
<?php
/**
* Parses an array.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses an array.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ArrayObj extends Component
{
/**
* The array that contains the unprocessed value of each token.
*
* @var array
*/
public $raw = array();
/**
* The array that contains the processed value of each token.
*
* @var array
*/
public $values = array();
/**
* Constructor.
*
* @param array $raw The unprocessed values.
* @param array $values The processed values.
*/
public function __construct(array $raw = array(), array $values = array())
{
$this->raw = $raw;
$this->values = $values;
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return ArrayObj|Component[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = empty($options['type']) ? new ArrayObj() : array();
/**
* The last raw expression.
*
* @var string $lastRaw
*/
$lastRaw = '';
/**
* The last value.
*
* @var string $lastValue
*/
$lastValue = '';
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* Last separator (bracket or comma).
*
* @var boolean $isCommaLast
*/
$isCommaLast = false;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
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 !== '('))
) {
$parser->error(__('An opening bracket was expected.'), $token);
break;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
if (++$brackets === 1) { // 1 is the base level.
continue;
}
} elseif ($token->value === ')') {
if (--$brackets === 0) { // Array ended.
break;
}
} elseif ($token->value === ',') {
if ($brackets === 1) {
$isCommaLast = true;
if (empty($options['type'])) {
$ret->raw[] = trim($lastRaw);
$ret->values[] = trim($lastValue);
$lastRaw = $lastValue = '';
}
}
continue;
}
}
if (empty($options['type'])) {
$lastRaw .= $token->token;
$lastValue .= $token->value;
} else {
$ret[] = $options['type']::parse(
$parser,
$list,
empty($options['typeOptions']) ? array() : $options['typeOptions']
);
}
}
// Handling last element.
//
// This is treated differently to treat the following cases:
//
// => array()
// (,) => array('', '')
// () => array()
// (a,) => array('a', '')
// (a) => array('a')
//
$lastRaw = trim($lastRaw);
if ((empty($options['type']))
&& ((strlen($lastRaw) > 0) || ($isCommaLast))
) {
$ret->raw[] = $lastRaw;
$ret->values[] = trim($lastValue);
}
return $ret;
}
/**
* @param ArrayObj|ArrayObj[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
} elseif (!empty($component->raw)) {
return '(' . implode(', ', $component->raw) . ')';
} else {
return '(' . implode(', ', $component->values) . ')';
}
}
}

View File

@ -0,0 +1,249 @@
<?php
/**
* Parses a reference to a CASE expression
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a reference to a CASE expression
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CaseExpression extends Component
{
/**
* The value to be compared
*
* @var Expression
*/
public $value;
/**
* The conditions in WHEN clauses
*
* @var array
*/
public $conditions;
/**
* The results matching with the WHEN clauses
*
* @var array
*/
public $results;
/**
* The values to be compared against
*
* @var array
*/
public $compare_values;
/**
* The result in ELSE section of expr
*
* @var array
*/
public $else_result;
/**
* Constructor.
*
*/
public function __construct()
{
}
/**
*
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
*
* @return Expression
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new CaseExpression();
/**
* State of parser
*
* @var int $parser
*/
$state = 0;
/**
* Syntax type (type 0 or type 1)
*
* @var int $type
*/
$type = 0;
++$list->idx; // Skip 'CASE'
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE)
|| ($token->type === Token::TYPE_COMMENT)
) {
continue;
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'WHEN'
) {
++$list->idx; // Skip 'WHEN'
$new_condition = Condition::parse($parser, $list);
$type = 1;
$state = 1;
$ret->conditions[] = $new_condition;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'ELSE'
) {
++$list->idx; // Skip 'ELSE'
$ret->else_result = Expression::parse($parser, $list);
$state = 0; // last clause of CASE expression
} elseif ($token->type === Token::TYPE_KEYWORD
&& ($token->value === 'END'
|| $token->value === 'end')
) {
$state = 3; // end of CASE expression
++$list->idx;
break;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
} else {
$ret->value = Expression::parse($parser, $list);
$type = 0;
$state = 1;
}
} elseif ($state === 1) {
if ($type === 0) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'WHEN'
) {
++$list->idx; // Skip 'WHEN'
$new_value = Expression::parse($parser, $list);
$state = 2;
$ret->compare_values[] = $new_value;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'ELSE'
) {
++$list->idx; // Skip 'ELSE'
$ret->else_result = Expression::parse($parser, $list);
$state = 0; // last clause of CASE expression
} elseif ($token->type === Token::TYPE_KEYWORD
&& ($token->value === 'END'
|| $token->value === 'end')
) {
$state = 3; // end of CASE expression
++$list->idx;
break;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
}
} else {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'THEN'
) {
++$list->idx; // Skip 'THEN'
$new_result = Expression::parse($parser, $list);
$state = 0;
$ret->results[] = $new_result;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
}
}
} elseif ($state === 2) {
if ($type === 0) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'THEN'
) {
++$list->idx; // Skip 'THEN'
$new_result = Expression::parse($parser, $list);
$ret->results[] = $new_result;
$state = 1;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
}
}
}
}
if ($state !== 3) {
$parser->error(
__('Unexpected end of CASE expression'),
$list->tokens[$list->idx - 1]
);
}
--$list->idx;
return $ret;
}
/**
* @param Expression $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = 'CASE ';
if (isset($component->value)) {
// Syntax type 0
$ret .= $component->value . ' ';
for (
$i = 0;
$i < count($component->compare_values) && $i < count($component->results);
++$i
) {
$ret .= 'WHEN ' . $component->compare_values[$i] . ' ';
$ret .= 'THEN ' . $component->results[$i] . ' ';
}
} else {
// Syntax type 1
for (
$i = 0;
$i < count($component->conditions) && $i < count($component->results);
++$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';
return $ret;
}
}

View File

@ -0,0 +1,231 @@
<?php
/**
* `WHERE` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `WHERE` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Condition extends Component
{
/**
* Logical operators that can be used to delimit expressions.
*
* @var array
*/
public static $DELIMITERS = array('&&', '||', 'AND', 'OR', 'XOR');
/**
* List of allowed reserved keywords in conditions.
*
* @var array
*/
public static $ALLOWED_KEYWORDS = array(
'ALL' => 1,
'AND' => 1,
'BETWEEN' => 1,
'EXISTS' => 1,
'IF' => 1,
'IN' => 1,
'INTERVAL' => 1,
'IS' => 1,
'LIKE' => 1,
'MATCH' => 1,
'NOT IN' => 1,
'NOT NULL' => 1,
'NOT' => 1,
'NULL' => 1,
'OR' => 1,
'REGEXP' => 1,
'RLIKE' => 1,
'XOR' => 1,
);
/**
* Identifiers recognized.
*
* @var array
*/
public $identifiers = array();
/**
* Whether this component is an operator.
*
* @var bool
*/
public $isOperator = false;
/**
* The condition.
*
* @var string
*/
public $expr;
/**
* Constructor.
*
* @param string $expr The condition or the operator.
*/
public function __construct($expr = null)
{
$this->expr = trim($expr);
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return Condition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new Condition();
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* Whether there was a `BETWEEN` keyword before or not.
*
* It is required to keep track of them because their structure contains
* the keyword `AND`, which is also an operator that delimits
* expressions.
*
* @var bool $betweenBefore
*/
$betweenBefore = false;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
// Replacing all whitespaces (new lines, tabs, etc.) with a single
// space character.
if ($token->type === Token::TYPE_WHITESPACE) {
$expr->expr .= ' ';
continue;
}
// Conditions are delimited by logical operators.
if (in_array($token->value, static::$DELIMITERS, true)) {
if (($betweenBefore) && ($token->value === 'AND')) {
// The syntax of keyword `BETWEEN` is hard-coded.
$betweenBefore = false;
} else {
// The expression ended.
$expr->expr = trim($expr->expr);
if (!empty($expr->expr)) {
$ret[] = $expr;
}
// Adding the operator.
$expr = new Condition($token->value);
$expr->isOperator = true;
$ret[] = $expr;
// Preparing to parse another condition.
$expr = new Condition();
continue;
}
}
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;
}
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
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 (!in_array($token->value, $expr->identifiers)) {
$expr->identifiers[] = $token->value;
}
}
}
// Last iteration was not processed.
$expr->expr = trim($expr->expr);
if (!empty($expr->expr)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param Condition[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(' ', $component);
} else {
return $component->expr;
}
}
}

View File

@ -0,0 +1,339 @@
<?php
/**
* Parses the create definition of a column or a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses the create definition of a column or a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CreateDefinition extends Component
{
/**
* All field options.
*
* @var array
*/
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' => array(2, 'expr', array('breakOnAlias' => true)),
'AUTO_INCREMENT' => 3,
'PRIMARY' => 4,
'PRIMARY KEY' => 4,
'UNIQUE' => 4,
'UNIQUE KEY' => 4,
'COMMENT' => array(5, 'var'),
'COLUMN_FORMAT' => array(6, 'var'),
'ON UPDATE' => array(7, 'expr'),
// Generated columns options.
'GENERATED ALWAYS' => 8,
'AS' => array(9, 'expr', array('parenthesesDelimited' => true)),
'VIRTUAL' => 10,
'PERSISTENT' => 11,
'STORED' => 11,
// Common entries.
//
// NOTE: Some of the common options are not in the same order which
// causes troubles when checking if the options are in the right order.
// I should find a way to define multiple sets of options and make the
// parser select the right set.
//
// 'UNIQUE' => 4,
// 'UNIQUE KEY' => 4,
// 'COMMENT' => array(5, 'var'),
// 'NOT NULL' => 1,
// 'NULL' => 1,
// 'PRIMARY' => 4,
// 'PRIMARY KEY' => 4,
);
/**
* The name of the new column.
*
* @var string
*/
public $name;
/**
* Whether this field is a constraint or not.
*
* @var bool
*/
public $isConstraint;
/**
* The data type of thew new column.
*
* @var DataType
*/
public $type;
/**
* The key.
*
* @var Key
*/
public $key;
/**
* The table that is referenced.
*
* @var Reference
*/
public $references;
/**
* The options of this field.
*
* @var OptionsArray
*/
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.
* @param bool $isConstraint Whether this field is a constraint or not.
* @param Reference $references References.
*/
public function __construct(
$name = null,
$options = null,
$type = null,
$isConstraint = false,
$references = null
) {
$this->name = $name;
$this->options = $options;
if ($type instanceof DataType) {
$this->type = $type;
} elseif ($type instanceof Key) {
$this->key = $type;
$this->isConstraint = $isConstraint;
$this->references = $references;
}
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return CreateDefinition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new CreateDefinition();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ ( ]------------------------> 1
*
* 1 --------------------[ CONSTRAINT ]------------------> 1
* 1 -----------------------[ key ]----------------------> 2
* 1 -------------[ constraint / column name ]-----------> 2
*
* 2 --------------------[ data type ]-------------------> 3
*
* 3 ---------------------[ options ]--------------------> 4
*
* 4 --------------------[ REFERENCES ]------------------> 4
*
* 5 ------------------------[ , ]-----------------------> 1
* 5 ------------------------[ ) ]-----------------------> 6 (-1)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 1;
} else {
$parser->error(
__('An opening bracket was expected.'),
$token
);
break;
}
} elseif ($state === 1) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'CONSTRAINT')) {
$expr->isConstraint = true;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_KEY)) {
$expr->key = Key::parse($parser, $list);
$state = 4;
} elseif ($token->type === Token::TYPE_SYMBOL || $token->type === Token::TYPE_NONE) {
$expr->name = $token->value;
if (!$expr->isConstraint) {
$state = 2;
}
} else if ($token->type === Token::TYPE_KEYWORD) {
if ($token->flags & Token::FLAG_KEYWORD_RESERVED) {
// Reserved keywords can't be used
// as field names without backquotes
$parser->error(
__('A symbol name was expected! '
. 'A reserved keyword can not be used '
. 'as a column name without backquotes.'
),
$token
);
return $ret;
} else {
// Non-reserved keywords are allowed without backquotes
$expr->name = $token->value;
$state = 2;
}
} else {
$parser->error(
__('A symbol name was expected!'),
$token
);
return $ret;
}
} elseif ($state === 2) {
$expr->type = DataType::parse($parser, $list);
$state = 3;
} elseif ($state === 3) {
$expr->options = OptionsArray::parse($parser, $list, static::$FIELD_OPTIONS);
$state = 4;
} elseif ($state === 4) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'REFERENCES')) {
++$list->idx; // Skipping keyword 'REFERENCES'.
$expr->references = Reference::parse($parser, $list);
} else {
--$list->idx;
}
$state = 5;
} elseif ($state === 5) {
if ((!empty($expr->type)) || (!empty($expr->key))) {
$ret[] = $expr;
}
$expr = new CreateDefinition();
if ($token->value === ',') {
$state = 1;
} elseif ($token->value === ')') {
$state = 6;
++$list->idx;
break;
} else {
$parser->error(
__('A comma or a closing bracket was expected.'),
$token
);
$state = 0;
break;
}
}
}
// Last iteration was not saved.
if ((!empty($expr->type)) || (!empty($expr->key))) {
$ret[] = $expr;
}
if (($state !== 0) && ($state !== 6)) {
$parser->error(
__('A closing bracket was expected.'),
$list->tokens[$list->idx - 1]
);
}
--$list->idx;
return $ret;
}
/**
* @param CreateDefinition|CreateDefinition[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return "(\n " . implode(",\n ", $component) . "\n)";
} else {
$tmp = '';
if ($component->isConstraint) {
$tmp .= 'CONSTRAINT ';
}
if ((isset($component->name)) && ($component->name !== '')) {
$tmp .= Context::escape($component->name) . ' ';
}
if (!empty($component->type)) {
$tmp .= DataType::build(
$component->type,
array('lowercase' => true)
) . ' ';
}
if (!empty($component->key)) {
$tmp .= $component->key . ' ';
}
if (!empty($component->references)) {
$tmp .= 'REFERENCES ' . $component->references . ' ';
}
$tmp .= $component->options;
return trim($tmp);
}
}
}

View File

@ -0,0 +1,170 @@
<?php
/**
* Parses a data type.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a data type.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class DataType extends Component
{
/**
* All data type options.
*
* @var array
*/
public static $DATA_TYPE_OPTIONS = array(
'BINARY' => 1,
'CHARACTER SET' => array(2, 'var'),
'CHARSET' => array(2, 'var'),
'COLLATE' => array(3, 'var'),
'UNSIGNED' => 4,
'ZEROFILL' => 5,
);
/**
* The name of the data type.
*
* @var string
*/
public $name;
/**
* The parameters of this data type.
*
* Some data types have no parameters.
* Numeric types might have parameters for the maximum number of digits,
* precision, etc.
* String types might have parameters for the maximum length stored.
* `ENUM` and `SET` have parameters for possible values.
*
* For more information, check the MySQL manual.
*
* @var array
*/
public $parameters = array();
/**
* The options of this data type.
*
* @var OptionsArray
*/
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(),
$options = null
) {
$this->name = $name;
$this->parameters = $parameters;
$this->options = $options;
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return DataType
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new DataType();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -------------------[ data type ]--------------------> 1
*
* 1 ----------------[ size and options ]----------------> 2
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$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')) ?
$parameters->raw : $parameters->values;
}
$ret->options = OptionsArray::parse($parser, $list, static::$DATA_TYPE_OPTIONS);
++$list->idx;
break;
}
}
if (empty($ret->name)) {
return null;
}
--$list->idx;
return $ret;
}
/**
* @param DataType $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$name = (empty($options['lowercase'])) ?
$component->name : strtolower($component->name);
$parameters = '';
if (!empty($component->parameters)) {
$parameters = '(' . implode(',', $component->parameters) . ')';
}
return trim($name . $parameters . ' ' . $component->options);
}
}

View File

@ -0,0 +1,448 @@
<?php
/**
* Parses a reference to an expression (column, table or database name, function
* call, mathematical expression, etc.).
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a reference to an expression (column, table or database name, function
* call, mathematical expression, etc.).
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Expression extends Component
{
/**
* List of allowed reserved keywords in expressions.
*
* @var array
*/
private static $ALLOWED_KEYWORDS = array(
'AS' => 1, 'DUAL' => 1, 'NULL' => 1, 'REGEXP' => 1, 'CASE' => 1
);
/**
* The name of this database.
*
* @var string
*/
public $database;
/**
* The name of this table.
*
* @var string
*/
public $table;
/**
* The name of the column.
*
* @var string
*/
public $column;
/**
* The sub-expression.
*
* @var string
*/
public $expr = '';
/**
* The alias of this expression.
*
* @var string
*/
public $alias;
/**
* The name of the function.
*
* @var mixed
*/
public $function;
/**
* The type of subquery.
*
* @var string
*/
public $subquery;
/**
* Constructor.
*
* Syntax:
* new Expression('expr')
* new Expression('expr', 'alias')
* new Expression('database', 'table', 'column')
* new Expression('database', 'table', 'column', 'alias')
*
* If the database, table or column name is not required, pass an empty
* string.
*
* @param string $database The name of the database or the the expression.
* the the expression.
* @param string $table The name of the table or the alias of the expression.
* the alias of the expression.
* @param string $column The name of the column.
* @param string $alias The name of the alias.
*/
public function __construct($database = null, $table = null, $column = null, $alias = null)
{
if (($column === null) && ($alias === null)) {
$this->expr = $database; // case 1
$this->alias = $table; // case 2
} else {
$this->database = $database; // case 3
$this->table = $table; // case 3
$this->column = $column; // case 3
$this->alias = $alias; // case 4
}
}
/**
* Possible options:
*
* `field`
*
* First field to be filled.
* If this is not specified, it takes the value of `parseField`.
*
* `parseField`
*
* Specifies the type of the field parsed. It may be `database`,
* `table` or `column`. These expressions may not include
* parentheses.
*
* `breakOnAlias`
*
* If not empty, breaks when the alias occurs (it is not included).
*
* `breakOnParentheses`
*
* If not empty, breaks when the first parentheses occurs.
*
* `parenthesesDelimited`
*
* If not empty, breaks after last parentheses occurred.
*
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return Expression
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Expression();
/**
* Whether current tokens make an expression or a table reference.
*
* @var bool $isExpr
*/
$isExpr = false;
/**
* Whether a period was previously found.
*
* @var bool $dot
*/
$dot = false;
/**
* Whether an alias is expected. Is 2 if `AS` keyword was found.
*
* @var bool $alias
*/
$alias = false;
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* Keeps track of the last two previous tokens.
*
* @var Token[] $prev
*/
$prev = array(null, null);
// When a field is parsed, no parentheses are expected.
if (!empty($options['parseField'])) {
$options['breakOnParentheses'] = true;
$options['field'] = $options['parseField'];
}
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
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->value]))
) {
// A `(` was previously found and this keyword is the
// beginning of a statement, so this is a subquery.
$ret->subquery = $token->value;
} elseif (($token->flags & Token::FLAG_KEYWORD_FUNCTION)
&& (empty($options['parseField'])
&& ! $alias)
) {
$isExpr = true;
} elseif (($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ($brackets === 0)
) {
if (empty(self::$ALLOWED_KEYWORDS[$token->value])) {
// 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->value === 'AS') {
if (!empty($options['breakOnAlias'])) {
break;
}
if ($alias) {
$parser->error(
__('An alias was expected.'),
$token
);
break;
}
$alias = true;
continue;
} elseif ($token->value === 'CASE') {
// For a use of CASE like
// 'SELECT a = CASE .... END, b=1, `id`, ... FROM ...'
$tempCaseExpr = CaseExpression::parse($parser, $list);
$ret->expr .= CaseExpression::build($tempCaseExpr);
$isExpr = true;
continue;
}
$isExpr = true;
} elseif ($brackets === 0 && count($ret->expr) > 0 && ! $alias) {
/* End of expression */
break;
}
}
if (($token->type === Token::TYPE_NUMBER)
|| ($token->type === Token::TYPE_BOOL)
|| (($token->type === Token::TYPE_SYMBOL)
&& ($token->flags & Token::FLAG_SYMBOL_VARIABLE))
|| (($token->type === Token::TYPE_OPERATOR)
&& ($token->value !== '.'))
) {
if (!empty($options['parseField'])) {
break;
}
// Numbers, booleans and operators (except dot) are usually part
// of expressions.
$isExpr = true;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ((!empty($options['breakOnParentheses']))
&& (($token->value === '(') || ($token->value === ')'))
) {
// No brackets were expected.
break;
}
if ($token->value === '(') {
++$brackets;
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)
&& ($prev[1]->flags & Token::FLAG_KEYWORD_FUNCTION)))
) {
$ret->function = $prev[1]->value;
}
} elseif ($token->value === ')' && $brackets == 0) {
// Not our bracket
break;
} elseif ($token->value === ')') {
--$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 ($token->value === ',') {
// Expressions are comma-delimited.
if ($brackets === 0) {
break;
}
}
}
// Saving the previous tokens.
$prev[0] = $prev[1];
$prev[1] = $token;
if ($alias) {
// An alias is expected (the keyword `AS` was previously found).
if (!empty($ret->alias)) {
$parser->error(__('An alias was previously found.'), $token);
break;
}
$ret->alias = $token->value;
$alias = false;
} elseif ($isExpr) {
// Handling aliases.
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))
) {
if (!empty($ret->alias)) {
$parser->error(__('An alias was previously found.'), $token);
break;
}
$ret->alias = $prev[1]->value;
} else {
$ret->expr .= $token->token;
}
} elseif (!$isExpr) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '.')) {
// Found a `.` which means we expect a column name and
// the column name we parsed is actually the table name
// and the table name is actually a database name.
if ((!empty($ret->database)) || ($dot)) {
$parser->error(__('Unexpected dot.'), $token);
}
$ret->database = $ret->table;
$ret->table = $ret->column;
$ret->column = null;
$dot = true;
$ret->expr .= $token->token;
} else {
$field = empty($options['field']) ? 'column' : $options['field'];
if (empty($ret->$field)) {
$ret->$field = $token->value;
$ret->expr .= $token->token;
$dot = false;
} else {
// No alias is expected.
if (!empty($options['breakOnAlias'])) {
break;
}
if (!empty($ret->alias)) {
$parser->error(__('An alias was previously found.'), $token);
break;
}
$ret->alias = $token->value;
}
}
}
}
if ($alias) {
$parser->error(
__('An alias was expected.'),
$list->tokens[$list->idx - 1]
);
}
// White-spaces might be added at the end.
$ret->expr = trim($ret->expr);
if ($ret->expr === '') {
return null;
}
--$list->idx;
return $ret;
}
/**
* @param Expression|Expression[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode($component, ', ');
} else {
if ($component->expr !== '' && !is_null($component->expr)) {
$ret = $component->expr;
} else {
$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));
}
if (!empty($component->alias)) {
$ret .= ' AS ' . Context::escape($component->alias);
}
return $ret;
}
}
}

View File

@ -0,0 +1,129 @@
<?php
/**
* Parses a list of expressions delimited by a comma.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a list of expressions delimited by a comma.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ExpressionArray extends Component
{
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return Expression[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ array ]---------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 -----------------------[ else ]----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD)
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ((~$token->flags & Token::FLAG_KEYWORD_FUNCTION))
&& ($token->value !== 'DUAL')
&& ($token->value !== 'NULL')
&& ($token->value !== 'CASE')
) {
// No keyword is expected.
break;
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'CASE'
) {
$expr = CaseExpression::parse($parser, $list, $options);
} else {
$expr = Expression::parse($parser, $list, $options);
}
if ($expr === null) {
break;
}
$ret[] = $expr;
$state = 1;
} elseif ($state === 1) {
if ($token->value === ',') {
$state = 0;
} else {
break;
}
}
}
if ($state === 0) {
$parser->error(
__('An expression was expected.'),
$list->tokens[$list->idx]
);
}
--$list->idx;
return $ret;
}
/**
* @param Expression[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = array();
foreach ($component as $frag) {
$ret[] = $frag::build($frag);
}
return implode($ret, ', ');
}
}

View File

@ -0,0 +1,124 @@
<?php
/**
* Parses a function call.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a function call.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class FunctionCall extends Component
{
/**
* The name of this function.
*
* @var string
*/
public $name;
/**
* The list of parameters
*
* @var ArrayObj
*/
public $parameters;
/**
* Constructor.
*
* @param string $name The name of the function to be called.
* @param array|ArrayObj $parameters The parameters of this function.
*/
public function __construct($name = null, $parameters = null)
{
$this->name = $name;
if (is_array($parameters)) {
$this->parameters = new ArrayObj($parameters);
} elseif ($parameters instanceof ArrayObj) {
$this->parameters = $parameters;
}
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return FunctionCall
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new FunctionCall();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ name ]-----------------------> 1
*
* 1 --------------------[ parameters ]-------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$ret->name = $token->value;
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->parameters = ArrayObj::parse($parser, $list);
}
break;
}
}
return $ret;
}
/**
* @param FunctionCall $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
return $component->name . $component->parameters;
}
}

View File

@ -0,0 +1,164 @@
<?php
/**
* `INTO` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `INTO` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class IntoKeyword extends Component
{
/**
* Type of target (OUTFILE or SYMBOL).
*
* @var string
*/
public $type;
/**
* The destination, which can be a table or a file.
*
* @var string|Expression
*/
public $dest;
/**
* The name of the columns.
*
* @var array
*/
public $columns;
/**
* The values to be selected into (SELECT .. INTO @var1)
*
* @var ExpressionArray
*/
public $values;
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return IntoKeyword
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new IntoKeyword();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ name ]----------------------> 1
* 0 ---------------------[ OUTFILE ]---------------------> 2
*
* 1 ------------------------[ ( ]------------------------> (END)
*
* 2 ---------------------[ filename ]--------------------> 1
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
if (($state === 0) && ($token->value === 'OUTFILE')) {
$ret->type = 'OUTFILE';
$state = 2;
continue;
}
// No other keyword is expected.
break;
}
if ($state === 0) {
if ((isset($options['fromInsert'])
&& $options['fromInsert'])
|| (isset($options['fromReplace'])
&& $options['fromReplace'])
) {
$ret->dest = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'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;
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param IntoKeyword $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if ($component->dest instanceof Expression) {
$columns = !empty($component->columns) ?
'(`' . implode('`, `', $component->columns) . '`)' : '';
return $component->dest . $columns;
} elseif (isset($component->values)) {
return ExpressionArray::build($component->values);
} else {
return 'OUTFILE "' . $component->dest . '"';
}
}
}

View File

@ -0,0 +1,210 @@
<?php
/**
* `JOIN` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `JOIN` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class JoinKeyword extends Component
{
/**
* Types of join.
*
* @var array
*/
public static $JOINS = array(
'CROSS JOIN' => 'CROSS',
'FULL JOIN' => 'FULL',
'FULL OUTER JOIN' => 'FULL',
'INNER JOIN' => 'INNER',
'JOIN' => 'JOIN',
'LEFT JOIN' => 'LEFT',
'LEFT OUTER JOIN' => 'LEFT',
'RIGHT JOIN' => 'RIGHT',
'RIGHT OUTER JOIN' => 'RIGHT',
'NATURAL JOIN' => 'NATURAL',
'NATURAL LEFT JOIN' => 'NATURAL LEFT',
'NATURAL LEFT JOIN' => 'NATURAL LEFT',
'NATURAL RIGHT JOIN' => 'NATURAL RIGHT',
'NATURAL LEFT OUTER JOIN' => 'NATURAL LEFT OUTER',
'NATURAL RIGHT OUTER JOIN' => 'NATURAL RIGHT OUTER',
'STRAIGHT_JOIN' => 'STRAIGHT',
);
/**
* Type of this join.
*
* @see static::$JOINS
* @var string
*/
public $type;
/**
* Join expression.
*
* @var Expression
*/
public $expr;
/**
* Join conditions.
*
* @var Condition[]
*/
public $on;
/**
* Columns in Using clause
*
* @var ArrayObj
*/
public $using;
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return JoinKeyword[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new JoinKeyword();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ JOIN ]----------------------> 1
*
* 1 -----------------------[ expr ]----------------------> 2
*
* 2 ------------------------[ ON ]-----------------------> 3
* 2 -----------------------[ USING ]---------------------> 4
*
* 3 --------------------[ conditions ]-------------------> 0
*
* 4 ----------------------[ columns ]--------------------> 0
*
* @var int $state
*/
$state = 0;
// By design, the parser will parse first token after the keyword.
// In this case, the keyword must be analyzed too, in order to determine
// the type of this join.
if ($list->idx > 0) {
--$list->idx;
}
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
if (($token->type === Token::TYPE_KEYWORD)
&& (!empty(static::$JOINS[$token->value]))
) {
$expr->type = static::$JOINS[$token->value];
$state = 1;
} else {
break;
}
} elseif ($state === 1) {
$expr->expr = Expression::parse($parser, $list, array('field' => 'table'));
$state = 2;
} elseif ($state === 2) {
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->value === 'ON') {
$state = 3;
} elseif ($token->value === 'USING') {
$state = 4;
} else {
if (($token->type === Token::TYPE_KEYWORD)
&& (!empty(static::$JOINS[$token->value]))
) {
$ret[] = $expr;
$expr = new JoinKeyword();
$expr->type = static::$JOINS[$token->value];
$state = 1;
} else {
/* Next clause is starting */
break;
}
}
}
} elseif ($state === 3) {
$expr->on = Condition::parse($parser, $list);
$ret[] = $expr;
$expr = new JoinKeyword();
$state = 0;
} elseif ($state === 4) {
$expr->using = ArrayObj::parse($parser, $list);
$ret[] = $expr;
$expr = new JoinKeyword();
$state = 0;
}
}
if (!empty($expr->type)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param JoinKeyword[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = array();
foreach ($component as $c) {
$ret[] = array_search($c->type, static::$JOINS) . ' ' . $c->expr
. (!empty($c->on)
? ' ON ' . Condition::build($c->on) : '')
. (!empty($c->using)
? ' USING ' . ArrayObj::build($c->using) : '');
}
return implode(' ', $ret);
}
}

View File

@ -0,0 +1,207 @@
<?php
/**
* Parses the definition of a key.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses the definition of a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Key extends Component
{
/**
* All key options.
*
* @var array
*/
public static $KEY_OPTIONS = array(
'KEY_BLOCK_SIZE' => array(1, 'var'),
'USING' => array(2, 'var'),
'WITH PARSER' => array(3, 'var'),
'COMMENT' => array(4, 'var='),
);
/**
* The name of this key.
*
* @var string
*/
public $name;
/**
* Columns.
*
* @var array
*/
public $columns;
/**
* The type of this key.
*
* @var string
*/
public $type;
/**
* The options of this key.
*
* @var OptionsArray
*/
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.
* @param OptionsArray $options The options of this key.
*/
public function __construct(
$name = null,
array $columns = array(),
$type = null,
$options = null
) {
$this->name = $name;
$this->columns = $columns;
$this->type = $type;
$this->options = $options;
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return Key
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Key();
/**
* Last parsed column.
*
* @var array
*/
$lastColumn = array();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ type ]-----------------------> 1
*
* 1 ----------------------[ name ]-----------------------> 1
* 1 ---------------------[ columns ]---------------------> 2
*
* 2 ---------------------[ options ]---------------------> 3
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$ret->type = $token->value;
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 2;
} else {
$ret->name = $token->value;
}
} elseif ($state === 2) {
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
$state = 3;
} elseif (($token->value === ',') || ($token->value === ')')) {
$state = ($token->value === ',') ? 2 : 4;
if (!empty($lastColumn)) {
$ret->columns[] = $lastColumn;
$lastColumn = array();
}
}
} else {
$lastColumn['name'] = $token->value;
}
} elseif ($state === 3) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ')')) {
$state = 2;
} else {
$lastColumn['length'] = $token->value;
}
} elseif ($state === 4) {
$ret->options = OptionsArray::parse($parser, $list, static::$KEY_OPTIONS);
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param Key $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = $component->type . ' ';
if (!empty($component->name)) {
$ret .= Context::escape($component->name) . ' ';
}
$columns = array();
foreach ($component->columns as $column) {
$tmp = Context::escape($column['name']);
if (isset($column['length'])) {
$tmp .= '(' . $column['length'] . ')';
}
$columns[] = $tmp;
}
$ret .= '(' . implode(',', $columns) . ') ' . $component->options;
return trim($ret);
}
}

View File

@ -0,0 +1,131 @@
<?php
/**
* `LIMIT` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `LIMIT` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Limit extends Component
{
/**
* The number of rows skipped.
*
* @var int
*/
public $offset;
/**
* The number of rows to be returned.
*
* @var int
*/
public $rowCount;
/**
* Constructor.
*
* @param int $rowCount The row count.
* @param int $offset The offset.
*/
public function __construct($rowCount = 0, $offset = 0)
{
$this->rowCount = $rowCount;
$this->offset = $offset;
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return Limit
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Limit();
$offset = false;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
break;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'OFFSET')) {
if ($offset) {
$parser->error(__('An offset was expected.'), $token);
}
$offset = true;
continue;
}
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$ret->offset = $ret->rowCount;
$ret->rowCount = 0;
continue;
}
if ($offset) {
$ret->offset = $token->value;
$offset = false;
} else {
$ret->rowCount = $token->value;
}
}
if ($offset) {
$parser->error(
__('An offset was expected.'),
$list->tokens[$list->idx - 1]
);
}
--$list->idx;
return $ret;
}
/**
* @param Limit $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
return $component->offset . ', ' . $component->rowCount;
}
}

View File

@ -0,0 +1,372 @@
<?php
/**
* Parses a list of options.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a list of options.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class OptionsArray extends Component
{
/**
* ArrayObj of selected options.
*
* @var array
*/
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 = array())
{
$this->options = $options;
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return OptionsArray
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new OptionsArray();
/**
* The ID that will be assigned to duplicate options.
*
* @var int $lastAssignedId
*/
$lastAssignedId = count($options) + 1;
/**
* The option that was processed last time.
*
* @var array $lastOption
*/
$lastOption = null;
/**
* The index of the option that was processed last time.
*
* @var int $lastOptionId
*/
$lastOptionId = 0;
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------[ option ]----------------------> 1
*
* 1 -------------------[ = (optional) ]------------------> 2
*
* 2 ----------------------[ value ]----------------------> 0
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
// Skipping whitespace if not parsing value.
if (($token->type === Token::TYPE_WHITESPACE) && ($brackets === 0)) {
continue;
}
if ($lastOption === null) {
$upper = strtoupper($token->token);
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(
__('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;
}
}
if ($state === 0) {
if (!is_array($lastOption)) {
// This is a just keyword option without any value.
// This is the beginning and the end of it.
$ret->options[$lastOptionId] = $token->value;
$lastOption = null;
$state = 0;
} elseif (($lastOption[1] === 'var') || ($lastOption[1] === 'var=')) {
// This is a keyword that is followed by a value.
// 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] = 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] === 'var=',
// @var string Raw value.
'expr' => '',
// @var string Processed value.
'value' => '',
);
$state = 1;
} elseif ($lastOption[1] === 'expr' || $lastOption[1] === 'expr=') {
// This is a keyword that is followed by an expression.
// The expression is used by the specialized parser.
// Skipping this option in order to parse the expression.
++$list->idx;
$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' => '',
);
$state = 1;
}
} elseif ($state === 1) {
$state = 2;
if ($token->token === '=') {
$ret->options[$lastOptionId]['equals'] = true;
continue;
}
}
// This is outside the `elseif` group above because the change might
// change this iteration.
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;
}
}
}
}
/*
* We reached the end of statement without getting a value
* for an option for which a value was required
*/
if ($state === 1
&& $lastOption
&& ($lastOption[1] == 'expr'
|| $lastOption[1] == 'var'
|| $lastOption[1] == 'var='
|| $lastOption[1] == 'expr=')
) {
$parser->error(
sprintf(
__('Value/Expression for the option %1$s was expected'),
$ret->options[$lastOptionId]['name']
),
$list->tokens[$list->idx - 1]
);
}
if (empty($options['_UNSORTED'])) {
ksort($ret->options);
}
--$list->idx;
return $ret;
}
/**
* @param OptionsArray $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (empty($component->options)) {
return '';
}
$options = array();
foreach ($component->options as $option) {
if (!is_array($option)) {
$options[] = $option;
} else {
$options[] = $option['name']
. ((!empty($option['equals']) && $option['equals']) ? '=' : ' ')
. (!empty($option['expr']) ? $option['expr'] : $option['value']);
}
}
return implode(' ', $options);
}
/**
* Checks if it has the specified option and returns it value or true.
*
* @param string $key The key to be checked.
* @param bool $getExpr Gets the expression instead of the value.
* The value is the processed form of the expression.
*
* @return mixed
*/
public function has($key, $getExpr = false)
{
foreach ($this->options as $option) {
if (is_array($option)) {
if (!strcasecmp($key, $option['name'])) {
return $getExpr ? $option['expr'] : $option['value'];
}
} elseif (!strcasecmp($key, $option)) {
return true;
}
}
return false;
}
/**
* Removes the option from the array.
*
* @param string $key The key to be removed.
*
* @return bool Whether the key was found and deleted or not.
*/
public function remove($key)
{
foreach ($this->options as $idx => $option) {
if (is_array($option)) {
if (!strcasecmp($key, $option['name'])) {
unset($this->options[$idx]);
return true;
}
} elseif (!strcasecmp($key, $option)) {
unset($this->options[$idx]);
return true;
}
}
return false;
}
/**
* Merges the specified options with these ones. Values with same ID will be
* replaced.
*
* @param array|OptionsArray $options The options to be merged.
*
* @return void
*/
public function merge($options)
{
if (is_array($options)) {
$this->options = array_merge_recursive($this->options, $options);
} elseif ($options instanceof OptionsArray) {
$this->options = array_merge_recursive($this->options, $options->options);
}
}
/**
* Checks tf there are no options set.
*
* @return bool
*/
public function isEmpty()
{
return empty($this->options);
}
}

View File

@ -0,0 +1,144 @@
<?php
/**
* `ORDER BY` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `ORDER BY` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class OrderKeyword extends Component
{
/**
* The expression that is used for ordering.
*
* @var Expression
*/
public $expr;
/**
* The order type.
*
* @var string
*/
public $type;
/**
* Constructor.
*
* @param Expression $expr The expression that we are sorting by.
* @param string $type The sorting type.
*/
public function __construct($expr = null, $type = 'ASC')
{
$this->expr = $expr;
$this->type = $type;
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return OrderKeyword[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new OrderKeyword();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 --------------------[ expression ]-------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 -------------------[ ASC / DESC ]--------------------> 1
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$expr->expr = Expression::parse($parser, $list);
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_KEYWORD)
&& (($token->value === 'ASC') || ($token->value === 'DESC'))
) {
$expr->type = $token->value;
} elseif (($token->type === Token::TYPE_OPERATOR)
&& ($token->value === ',')
) {
if (!empty($expr->expr)) {
$ret[] = $expr;
}
$expr = new OrderKeyword();
$state = 0;
} else {
break;
}
}
}
// Last iteration was not processed.
if (!empty($expr->expr)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param OrderKeyword|OrderKeyword[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
} else {
return $component->expr . ' ' . $component->type;
}
}
}

View File

@ -0,0 +1,160 @@
<?php
/**
* The definition of a parameter of a function or procedure.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* The definition of a parameter of a function or procedure.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ParameterDefinition extends Component
{
/**
* The name of the new column.
*
* @var string
*/
public $name;
/**
* Parameter's direction (IN, OUT or INOUT).
*
* @var string
*/
public $inOut;
/**
* The data type of thew new column.
*
* @var DataType
*/
public $type;
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return ParameterDefinition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new ParameterDefinition();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ ( ]------------------------> 1
*
* 1 ----------------[ IN / OUT / INOUT ]----------------> 1
* 1 ----------------------[ name ]----------------------> 2
*
* 2 -------------------[ data type ]--------------------> 3
*
* 3 ------------------------[ , ]-----------------------> 1
* 3 ------------------------[ ) ]-----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 1;
}
continue;
} elseif ($state === 1) {
if (($token->value === 'IN') || ($token->value === 'OUT') || ($token->value === 'INOUT')) {
$expr->inOut = $token->value;
++$list->idx;
} elseif ($token->value === ')') {
++$list->idx;
break;
} else {
$expr->name = $token->value;
$state = 2;
}
} elseif ($state === 2) {
$expr->type = DataType::parse($parser, $list);
$state = 3;
} elseif ($state === 3) {
$ret[] = $expr;
$expr = new ParameterDefinition();
if ($token->value === ',') {
$state = 1;
} elseif ($token->value === ')') {
++$list->idx;
break;
}
}
}
// Last iteration was not saved.
if ((isset($expr->name)) && ($expr->name !== '')) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param ParameterDefinition[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return '(' . implode(', ', $component) . ')';
} else {
$tmp = '';
if (!empty($component->inOut)) {
$tmp .= $component->inOut . ' ';
}
return trim(
$tmp . Context::escape($component->name) . ' ' . $component->type
);
}
}
}

View File

@ -0,0 +1,223 @@
<?php
/**
* Parses the create definition of a partition.
*
* Used for parsing `CREATE TABLE` statement.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses the create definition of a partition.
*
* Used for parsing `CREATE TABLE` statement.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class PartitionDefinition extends Component
{
/**
* All field options.
*
* @var array
*/
public static $OPTIONS = array(
'STORAGE ENGINE' => array(1, 'var'),
'ENGINE' => array(1, 'var'),
'COMMENT' => array(2, 'var'),
'DATA DIRECTORY' => array(3, 'var'),
'INDEX DIRECTORY' => array(4, 'var'),
'MAX_ROWS' => array(5, 'var'),
'MIN_ROWS' => array(6, 'var'),
'TABLESPACE' => array(7, 'var'),
'NODEGROUP' => array(8, 'var'),
);
/**
* Whether this entry is a subpartition or a partition.
*
* @var bool
*/
public $isSubpartition;
/**
* The name of this partition.
*
* @var string
*/
public $name;
/**
* The type of this partition (what follows the `VALUES` keyword).
*
* @var string
*/
public $type;
/**
* The expression used to defined this partition.
*
* @var Expression|string
*/
public $expr;
/**
* The subpartitions of this partition.
*
* @var PartitionDefinition[]
*/
public $subpartitions;
/**
* The options of this field.
*
* @var OptionsArray
*/
public $options;
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return PartitionDefinition
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new PartitionDefinition();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -------------[ PARTITION | SUBPARTITION ]------------> 1
*
* 1 -----------------------[ name ]----------------------> 2
*
* 2 ----------------------[ VALUES ]---------------------> 3
*
* 3 ---------------------[ LESS THAN ]-------------------> 4
* 3 ------------------------[ IN ]-----------------------> 4
*
* 4 -----------------------[ expr ]----------------------> 5
*
* 5 ----------------------[ options ]--------------------> 6
*
* 6 ------------------[ subpartitions ]------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$ret->isSubpartition = ($token->type === Token::TYPE_KEYWORD) && ($token->value === 'SUBPARTITION');
$state = 1;
} elseif ($state === 1) {
$ret->name = $token->value;
// Looking ahead for a 'VALUES' keyword.
$idx = $list->idx;
$list->getNext();
$nextToken = $list->getNext();
$list->idx = $idx;
$state = ($nextToken->type === Token::TYPE_KEYWORD)
&& ($nextToken->value === 'VALUES')
? 2 : 5;
} elseif ($state === 2) {
$state = 3;
} elseif ($state === 3) {
$ret->type = $token->value;
$state = 4;
} elseif ($state === 4) {
if ($token->value === 'MAXVALUE') {
$ret->expr = $token->value;
} else {
$ret->expr = Expression::parse(
$parser,
$list,
array(
'parenthesesDelimited' => true,
'breakOnAlias' => true,
)
);
}
$state = 5;
} elseif ($state === 5) {
$ret->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$state = 6;
} elseif ($state === 6) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->subpartitions = ArrayObj::parse(
$parser,
$list,
array(
'type' => 'SqlParser\\Components\\PartitionDefinition'
)
);
++$list->idx;
}
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param PartitionDefinition|PartitionDefinition[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return "(\n" . implode(",\n", $component) . "\n)";
} else {
if ($component->isSubpartition) {
return trim('SUBPARTITION ' . $component->name . ' ' . $component->options);
} else {
$subpartitions = empty($component->subpartitions)
? '' : ' ' . PartitionDefinition::build($component->subpartitions);
return trim(
'PARTITION ' . $component->name
. (empty($component->type) ? '' : ' VALUES ' . $component->type . ' ' . $component->expr . ' ')
. $component->options . $subpartitions
);
}
}
}
}

View File

@ -0,0 +1,157 @@
<?php
/**
* `REFERENCES` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `REFERENCES` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Reference extends Component
{
/**
* All references options.
*
* @var array
*/
public static $REFERENCES_OPTIONS = array(
'MATCH' => array(1, 'var'),
'ON DELETE' => array(2, 'var'),
'ON UPDATE' => array(3, 'var'),
);
/**
* The referenced table.
*
* @var Expression
*/
public $table;
/**
* The referenced columns.
*
* @var array
*/
public $columns;
/**
* The options of the referencing.
*
* @var OptionsArray
*/
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 = array(), $options = null)
{
$this->table = $table;
$this->columns = $columns;
$this->options = $options;
}
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return Reference
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Reference();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ table ]---------------------> 1
*
* 1 ---------------------[ columns ]--------------------> 2
*
* 2 ---------------------[ options ]--------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$ret->table = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
$state = 1;
} elseif ($state === 1) {
$ret->columns = ArrayObj::parse($parser, $list)->values;
$state = 2;
} elseif ($state === 2) {
$ret->options = OptionsArray::parse($parser, $list, static::$REFERENCES_OPTIONS);
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param Reference $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
return trim(
$component->table
. ' (' . implode(', ', Context::escape($component->columns)) . ') '
. $component->options
);
}
}

View File

@ -0,0 +1,173 @@
<?php
/**
* `RENAME TABLE` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `RENAME TABLE` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RenameOperation extends Component
{
/**
* The old table name.
*
* @var Expression
*/
public $old;
/**
* The new table name.
*
* @var Expression
*/
public $new;
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return RenameOperation[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new RenameOperation();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------[ old name ]--------------------> 1
*
* 1 ------------------------[ TO ]-----------------------> 2
*
* 2 ---------------------[ old name ]--------------------> 3
*
* 3 ------------------------[ , ]------------------------> 0
* 3 -----------------------[ else ]----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$expr->old = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
'parseField' => 'table',
)
);
if (empty($expr->old)) {
$parser->error(
__('The old name of the table was expected.'),
$token
);
}
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'TO')) {
$state = 2;
} else {
$parser->error(
__('Keyword "TO" was expected.'),
$token
);
break;
}
} elseif ($state === 2) {
$expr->new = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
'parseField' => 'table',
)
);
if (empty($expr->new)) {
$parser->error(
__('The new name of the table was expected.'),
$token
);
}
$state = 3;
} elseif ($state === 3) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$ret[] = $expr;
$expr = new RenameOperation();
$state = 0;
} else {
break;
}
}
}
if ($state !== 3) {
$parser->error(
__('A rename operation was expected.'),
$list->tokens[$list->idx - 1]
);
}
// Last iteration was not saved.
if (!empty($expr->old)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param RenameOperation $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
} else {
return $component->old . ' TO ' . $component->new;
}
}
}

View File

@ -0,0 +1,137 @@
<?php
/**
* `SET` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `SET` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class SetOperation extends Component
{
/**
* The name of the column that is being updated.
*
* @var string
*/
public $column;
/**
* The new value.
*
* @var string
*/
public $value;
/**
* @param Parser $parser The parser that serves as context.
* @param TokensList $list The list of tokens that are being parsed.
* @param array $options Parameters for parsing.
*
* @return SetOperation[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new SetOperation();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -------------------[ column name ]-------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 ----------------------[ value ]----------------------> 1
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
// No keyword is expected.
if (($token->type === Token::TYPE_KEYWORD)
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ($state == 0)
) {
break;
}
if ($state === 0) {
if ($token->token === '=') {
$state = 1;
} elseif ($token->value !== ',') {
$expr->column .= $token->token;
}
} elseif ($state === 1) {
$tmp = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
)
);
if ($tmp == null) {
break;
}
$expr->column = trim($expr->column);
$expr->value = $tmp->expr;
$ret[] = $expr;
$expr = new SetOperation();
$state = 0;
}
}
--$list->idx;
return $ret;
}
/**
* @param SetOperation|SetOperation[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (is_array($component)) {
return implode(', ', $component);
} else {
return $component->column . ' = ' . $component->value;
}
}
}

View File

@ -0,0 +1,39 @@
<?php
/**
* `UNION` keyword builder.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Statements\SelectStatement;
/**
* `UNION` keyword builder.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class UnionKeyword extends Component
{
/**
* @param SelectStatement[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$tmp = array();
foreach ($component as $component) {
$tmp[] = $component[0] . ' ' . $component[1];
}
return implode(' ', $tmp);
}
}

View File

@ -0,0 +1,554 @@
<?php
/**
* Defines a context class that is later extended to define other contexts.
*
* A context is a collection of keywords, operators and functions used for
* parsing.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* Holds the configuration of the context that is currently used.
*
* @category Contexts
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
abstract class Context
{
/**
* The maximum length of a keyword.
*
* @see static::$TOKEN_KEYWORD
*
* @var int
*/
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
*/
const LABEL_MAX_LENGTH = 16;
/**
* The maximum length of an operator.
*
* @see static::$TOKEN_OPERATOR
*
* @var int
*/
const OPERATOR_MAX_LENGTH = 4;
/**
* The name of the default content.
*
* @var string
*/
public static $defaultContext = '\\SqlParser\\Contexts\\ContextMySql50700';
/**
* The name of the loaded context.
*
* @var string
*/
public static $loadedContext = '\\SqlParser\\Contexts\\ContextMySql50700';
/**
* The prefix concatenated to the context name when an incomplete class name
* is specified.
*
* @var string
*/
public static $contextPrefix = '\\SqlParser\\Contexts\\Context';
/**
* List of keywords.
*
* Because, PHP's associative arrays are basically hash tables, it is more
* efficient to store keywords as keys instead of values.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* Elements are sorted by flags, length and keyword.
*
* @var array
*/
public static $KEYWORDS = array();
/**
* List of operators and their flags.
*
* @var array
*/
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)
// SELECT 2 * 3; # arithmetic
// 2. SELECT * FROM table WHERE foo = 'bar';
// SET @i = 0;
// @see Token::FLAG_OPERATOR_ARITHMETIC
'%' => 1, '*' => 1, '+' => 1, '-' => 1, '/' => 1,
// @see Token::FLAG_OPERATOR_LOGICAL
'!' => 2, '!=' => 2, '&&' => 2, '<' => 2, '<=' => 2,
'<=>' => 2, '<>' => 2, '=' => 2, '>' => 2, '>=' => 2,
'||' => 2,
// @see Token::FLAG_OPERATOR_BITWISE
'&' => 4, '<<' => 4, '>>' => 4, '^' => 4, '|' => 4,
'~' => 4,
// @see Token::FLAG_OPERATOR_ASSIGNMENT
':=' => 8,
// @see Token::FLAG_OPERATOR_SQL
'(' => 16, ')' => 16, '.' => 16, ',' => 16, ';' => 16,
);
/**
* The mode of the MySQL server that will be used in lexing, parsing and
* building the statements.
*
* @var int
*/
public static $MODE = 0;
/*
* Server SQL Modes
* https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html
*/
// Compatibility mode for Microsoft's SQL server.
// This is the equivalent of ANSI_QUOTES.
const COMPAT_MYSQL = 2;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_allow_invalid_dates
const ALLOW_INVALID_DATES = 1;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ansi_quotes
const ANSI_QUOTES = 2;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_error_for_division_by_zero
const ERROR_FOR_DIVISION_BY_ZERO = 4;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_high_not_precedence
const HIGH_NOT_PRECEDENCE = 8;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ignore_space
const IGNORE_SPACE = 16;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_auto_create_user
const NO_AUTO_CREATE_USER = 32;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_auto_value_on_zero
const NO_AUTO_VALUE_ON_ZERO = 64;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_backslash_escapes
const NO_BACKSLASH_ESCAPES = 128;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_dir_in_create
const NO_DIR_IN_CREATE = 256;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_dir_in_create
const NO_ENGINE_SUBSTITUTION = 512;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_field_options
const NO_FIELD_OPTIONS = 1024;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_key_options
const NO_KEY_OPTIONS = 2048;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_table_options
const NO_TABLE_OPTIONS = 4096;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_unsigned_subtraction
const NO_UNSIGNED_SUBTRACTION = 8192;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_zero_date
const NO_ZERO_DATE = 16384;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_zero_in_date
const NO_ZERO_IN_DATE = 32768;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_only_full_group_by
const ONLY_FULL_GROUP_BY = 65536;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_pipes_as_concat
const PIPES_AS_CONCAT = 131072;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_real_as_float
const REAL_AS_FLOAT = 262144;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_strict_all_tables
const STRICT_ALL_TABLES = 524288;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_strict_trans_tables
const 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.
const NO_ENCLOSING_QUOTES = 1073741824;
/*
* Combination SQL Modes
* https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sql-mode-combo
*/
// REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE
const SQL_MODE_ANSI = 393234;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS,
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
const SQL_MODE_MAXDB = 138290;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS
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
const SQL_MODE_ORACLE = 138290;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS
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
const SQL_MODE_TRADITIONAL = 1622052;
// -------------------------------------------------------------------------
// Keyword.
/**
* Checks if the given string is a keyword.
*
* @param string $str String to be checked.
* @param bool $isReserved Checks if the keyword is reserved.
*
* @return int
*/
public static function isKeyword($str, $isReserved = false)
{
$str = strtoupper($str);
if (isset(static::$KEYWORDS[$str])) {
if ($isReserved) {
if (!(static::$KEYWORDS[$str] & Token::FLAG_KEYWORD_RESERVED)) {
return null;
}
}
return static::$KEYWORDS[$str];
}
return null;
}
// -------------------------------------------------------------------------
// Operator.
/**
* Checks if the given string is an operator.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the operator.
*/
public static function isOperator($str)
{
if (!isset(static::$OPERATORS[$str])) {
return null;
}
return static::$OPERATORS[$str];
}
// -------------------------------------------------------------------------
// Whitespace.
/**
* Checks if the given character is a whitespace.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isWhitespace($str)
{
return ($str === ' ') || ($str === "\r") || ($str === "\n") || ($str === "\t");
}
// -------------------------------------------------------------------------
// Comment.
/**
* Checks if the given string is the beginning of a whitespace.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the comment type.
*/
public static function isComment($str)
{
$len = strlen($str);
if ($str[0] === '#') {
return Token::FLAG_COMMENT_BASH;
} elseif (($len > 1) && ($str[0] === '/') && ($str[1] === '*')) {
return (($len > 2) && ($str[2] == '!')) ?
Token::FLAG_COMMENT_MYSQL_CMD : Token::FLAG_COMMENT_C;
} elseif (($len > 1) && ($str[0] === '*') && ($str[1] === '/')) {
return Token::FLAG_COMMENT_C;
} elseif (($len > 2) && ($str[0] === '-')
&& ($str[1] === '-') && (static::isWhitespace($str[2]))
) {
return Token::FLAG_COMMENT_SQL;
}
return null;
}
// -------------------------------------------------------------------------
// Bool.
/**
* Checks if the given string is a boolean value.
* This actually check only for `TRUE` and `FALSE` because `1` or `0` are
* actually numbers and are parsed by specific methods.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isBool($str)
{
$str = strtoupper($str);
return ($str === 'TRUE') || ($str === 'FALSE');
}
// -------------------------------------------------------------------------
// Number.
/**
* Checks if the given character can be a part of a number.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isNumber($str)
{
return (($str >= '0') && ($str <= '9')) || ($str === '.')
|| ($str === '-') || ($str === '+') || ($str === 'e') || ($str === 'E');
}
// -------------------------------------------------------------------------
// Symbol.
/**
* Checks if the given character is the beginning of a symbol. A symbol
* can be either a variable or a field name.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the symbol type.
*/
public static function isSymbol($str)
{
if ($str[0] === '@') {
return Token::FLAG_SYMBOL_VARIABLE;
} elseif ($str[0] === '`') {
return Token::FLAG_SYMBOL_BACKTICK;
}
return null;
}
// -------------------------------------------------------------------------
// String.
/**
* Checks if the given character is the beginning of a string.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the string type.
*/
public static function isString($str)
{
if ($str[0] === '\'') {
return Token::FLAG_STRING_SINGLE_QUOTES;
} elseif ($str[0] === '"') {
return Token::FLAG_STRING_DOUBLE_QUOTES;
}
return null;
}
// -------------------------------------------------------------------------
// Delimiter.
/**
* Checks if the given character can be a separator for two lexeme.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isSeparator($str)
{
// NOTES: Only non alphanumeric ASCII characters may be separators.
// `~` is the last printable ASCII character.
return ($str <= '~') && ($str !== '_')
&& (($str < '0') || ($str > '9'))
&& (($str < 'a') || ($str > 'z'))
&& (($str < 'A') || ($str > 'Z'));
}
/**
* Loads the specified context.
*
* Contexts may be used by accessing the context directly.
*
* @param string $context Name of the context or full class name that
* defines the context.
*
* @throws \Exception If the specified context doesn't exist.
*
* @return void
*/
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 \Exception(
'Specified context ("' . $context . '") does not exist.'
);
}
self::$loadedContext = $context;
self::$KEYWORDS = $context::$KEYWORDS;
}
/**
* Loads the context with the closest version to the one specified.
*
* The closest context is found by replacing last digits with zero until one
* is loaded successfully.
*
* @see Context::load()
*
* @param string $context Name of the context or full class name that
* defines the context.
*
* @return string The loaded context. `null` if no context was loaded.
*/
public static function loadClosest($context = '')
{
/**
* The number of replaces done by `preg_replace`.
* This actually represents whether a new context was generated or not.
*
* @var int $count
*/
$count = 0;
// As long as a new context can be generated, we try to load it.
do {
try {
// Trying to load the new context.
static::load($context);
} catch (\Exception $e) {
// If it didn't work, we are looking for a new one and skipping
// over to the next generation that will try the new context.
$context = preg_replace(
'/[1-9](0*)$/',
'0$1',
$context,
-1,
$count
);
continue;
}
// Last generated context was valid (did not throw any exceptions).
// So we return it, to let the user know what context was loaded.
return $context;
} while ($count !== 0);
return null;
}
/**
* Sets the SQL mode.
*
* @param string $mode The list of modes. If empty, the mode is reset.
*
* @return void
*/
public static function setMode($mode = '')
{
static::$MODE = 0;
if (empty($mode)) {
return;
}
$mode = explode(',', $mode);
foreach ($mode as $m) {
static::$MODE |= constant('static::' . $m);
}
}
/**
* Escapes the symbol by adding surrounding backticks.
*
* @param array|string $str The string to be escaped.
* @param string $quote Quote to be used when escaping.
*
* @return string
*/
public static function escape($str, $quote = '`')
{
if (is_array($str)) {
foreach ($str as $key => $value) {
$str[$key] = static::escape($value);
}
return $str;
}
if ((static::$MODE & Context::NO_ENCLOSING_QUOTES)
&& (!static::isKeyword($str, true))
) {
return $str;
}
if (static::$MODE & Context::ANSI_QUOTES) {
$quote = '"';
}
return $quote . str_replace($quote, $quote . $quote, $str) . $quote;
}
}
// Initializing the default context.
Context::load();

View File

@ -0,0 +1,287 @@
<?php
/**
* Context for MySQL 5.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.0/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50000 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
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,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'FAST' => 1,
'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1, 'LAST' => 1, 'LOGS' => 1,
'MODE' => 1, 'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PREV' => 1, 'ROWS' => 1, 'SOME' => 1, 'STOP' => 1, 'TYPE' => 1, 'VIEW' => 1,
'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 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, 'PHASE' => 1,
'QUERY' => 1, 'QUICK' => 1, 'RAID0' => 1, 'RESET' => 1, 'RTREE' => 1,
'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1, 'SWAPS' => 1,
'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1, 'CLIENT' => 1,
'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1, 'ESCAPE' => 1,
'EVENTS' => 1, 'FAULTS' => 1, 'FIELDS' => 1, 'GLOBAL' => 1, 'GRANTS' => 1,
'IMPORT' => 1, 'INNODB' => 1, 'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1,
'MEDIUM' => 1, 'MEMORY' => 1, 'MODIFY' => 1, 'OFFSET' => 1, 'RELOAD' => 1,
'REPAIR' => 1, 'RESUME' => 1, 'ROLLUP' => 1, 'SIGNED' => 1, 'SIMPLE' => 1,
'SOUNDS' => 1, 'SOURCE' => 1, 'STATUS' => 1, 'STRING' => 1, 'TABLES' => 1,
'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1, 'COMPACT' => 1, 'CONTEXT' => 1,
'DEFINER' => 1, 'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1,
'EXECUTE' => 1, 'HANDLER' => 1, 'INDEXES' => 1, 'INVOKER' => 1, 'MIGRATE' => 1,
'PARTIAL' => 1, 'PREPARE' => 1, 'PROFILE' => 1, 'RECOVER' => 1, 'RESTORE' => 1,
'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1, 'STORAGE' => 1, 'STRIPED' => 1,
'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1, 'UNKNOWN' => 1, 'UPGRADE' => 1,
'USE_FRM' => 1, 'VIRTUAL' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DUMPFILE' => 1, 'EXTENDED' => 1,
'FUNCTION' => 1, 'INNOBASE' => 1, 'LANGUAGE' => 1, 'MAX_ROWS' => 1,
'MIN_ROWS' => 1, 'NATIONAL' => 1, 'NVARCHAR' => 1, 'ONE_SHOT' => 1,
'PROFILES' => 1, 'ROLLBACK' => 1, 'SECURITY' => 1, 'SHUTDOWN' => 1,
'SNAPSHOT' => 1, 'SWITCHES' => 1, 'TRIGGERS' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'PACK_KEYS' => 1, 'RAID_TYPE' => 1, 'REDUNDANT' => 1, 'SAVEPOINT' => 1,
'SQL_CACHE' => 1, 'TEMPORARY' => 1, 'TEMPTABLE' => 1, 'UNDEFINED' => 1,
'VARIABLES' => 1,
'BERKELEYDB' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PRIVILEGES' => 1,
'REPEATABLE' => 1, 'ROW_FORMAT' => 1, 'SQL_THREAD' => 1, 'TABLESPACE' => 1,
'FRAC_SECOND' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1,
'PROCESSLIST' => 1, 'RAID_CHUNKS' => 1, 'REPLICATION' => 1, 'SQL_TSI_DAY' => 1,
'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'DES_KEY_FILE' => 1, 'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1,
'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1, 'SQL_TSI_WEEK' => 1,
'SQL_TSI_YEAR' => 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, 'MASTER_LOG_POS' => 1,
'MASTER_SSL_KEY' => 1, 'RAID_CHUNKSIZE' => 1, 'RELAY_LOG_FILE' => 1,
'SQL_TSI_MINUTE' => 1, 'SQL_TSI_SECOND' => 1, 'USER_RESOURCES' => 1,
'DELAY_KEY_WRITE' => 1, 'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1,
'MASTER_SSL_CERT' => 1, 'SQL_TSI_QUARTER' => 1,
'MASTER_SERVER_ID' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'SQL_BUFFER_RESULT' => 1,
'SQL_TSI_FRAC_SECOND' => 1,
'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 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, '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, '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,
'PURGE' => 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, 'EXISTS' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'OPTION' => 3, 'REGEXP' => 3,
'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3, 'SONAME' => 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,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'MODIFIES' => 3, 'OPTIMIZE' => 3, 'RESTRICT' => 3,
'SPECIFIC' => 3, 'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3,
'UNSIGNED' => 3, 'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'MIDDLEINT' => 3, 'PRECISION' => 3,
'PROCEDURE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3, 'DAY_SECOND' => 3,
'OPTIONALLY' => 3, 'REFERENCES' => 3, 'SQLWARNING' => 3, 'TERMINATED' => 3,
'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 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, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'CROSS JOIN' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7, 'LINEAR KEY' => 7,
'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'LINEAR HASH' => 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,
'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, 'BINARY' => 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,
'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, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'TRIM' => 33, 'USER' => 33,
'UUID' => 33, 'WEEK' => 33,
'ASCII' => 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, '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, 'QUARTER' => 33, 'RADIANS' => 33, 'REVERSE' => 33, 'SOUNDEX' => 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, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33, 'MAKEDATE' => 33,
'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33, 'OVERLAPS' => 33,
'PASSWORD' => 33, 'POSITION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33,
'VARIANCE' => 33, 'VAR_SAMP' => 33, 'YEARWEEK' => 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, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'SUBSTRING' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INTERSECTS' => 33, 'MBRTOUCHES' => 33,
'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33,
'STDDEV_POP' => 33, 'UNCOMPRESS' => 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, 'GEOMFROMWKB' => 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, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'GEOMETRYTYPE' => 33,
'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33, 'IS_FREE_LOCK' => 33,
'IS_USED_LOCK' => 33, 'LINEFROMTEXT' => 33, 'MLINEFROMWKB' => 33,
'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33, 'OCTET_LENGTH' => 33,
'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33, 'POLYFROMTEXT' => 33,
'RELEASE_LOCK' => 33, 'SESSION_USER' => 33, 'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'INTERIORRINGN' => 33,
'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33,
'TIMESTAMPDIFF' => 33,
'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33, 'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'NUMINTERIORRINGS' => 33,
'UNCOMPRESSED_LENGTH' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 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,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,312 @@
<?php
/**
* Context for MySQL 5.1.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.1/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.1.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50100 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
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,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'GOTO' => 1, 'HASH' => 1,
'HELP' => 1, 'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1,
'MODE' => 1, 'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PORT' => 1, 'PREV' => 1, 'ROWS' => 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, 'EVENT' => 1, 'EVERY' => 1, 'FIRST' => 1,
'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1, 'LABEL' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'OWNER' => 1, 'PHASE' => 1, 'QUERY' => 1,
'QUICK' => 1, 'RAID0' => 1, 'RESET' => 1, 'RTREE' => 1, 'SHARE' => 1,
'SLAVE' => 1, 'START' => 1, 'SUPER' => 1, 'SWAPS' => 1, 'TYPES' => 1,
'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1, 'CLIENT' => 1,
'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1, 'ESCAPE' => 1,
'EVENTS' => 1, 'FAULTS' => 1, 'FIELDS' => 1, 'GLOBAL' => 1, 'GRANTS' => 1,
'IMPORT' => 1, 'INNODB' => 1, 'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1,
'MEDIUM' => 1, 'MEMORY' => 1, 'MODIFY' => 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,
'AUTHORS' => 1, 'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1, 'COMPACT' => 1,
'CONTEXT' => 1, 'DEFINER' => 1, 'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1,
'ENGINES' => 1, 'EXECUTE' => 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,
'STORAGE' => 1, 'STRIPED' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'VIRTUAL' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'INNOBASE' => 1, 'LANGUAGE' => 1,
'MAXVALUE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1, 'MIN_ROWS' => 1,
'NATIONAL' => 1, 'NVARCHAR' => 1, 'ONE_SHOT' => 1, 'PRESERVE' => 1,
'PROFILES' => 1, 'REDOFILE' => 1, 'ROLLBACK' => 1, 'SCHEDULE' => 1,
'SECURITY' => 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, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'PARTITION' => 1, 'RAID_TYPE' => 1,
'READ_ONLY' => 1, 'REDUNDANT' => 1, 'SAVEPOINT' => 1, 'SCHEDULER' => 1,
'SQL_CACHE' => 1, 'TEMPORARY' => 1, 'TEMPTABLE' => 1, 'UNDEFINED' => 1,
'UNINSTALL' => 1, 'VARIABLES' => 1,
'BERKELEYDB' => 1, 'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1,
'CONNECTION' => 1, 'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1,
'MASTER_SSL' => 1, 'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1,
'PRIVILEGES' => 1, 'REORGANISE' => 1, 'REORGANIZE' => 1, 'REPEATABLE' => 1,
'ROW_FORMAT' => 1, 'SQL_THREAD' => 1, 'TABLESPACE' => 1,
'EXTENT_SIZE' => 1, 'FRAC_SECOND' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1,
'MASTER_USER' => 1, 'PROCESSLIST' => 1, 'RAID_CHUNKS' => 1, 'REPLICATION' => 1,
'SQL_TSI_DAY' => 1, 'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CONTRIBUTORS' => 1, 'DES_KEY_FILE' => 1, 'INITIAL_SIZE' => 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,
'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1, 'PAGE_CHECKSUM' => 1,
'RELAY_LOG_POS' => 1, 'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'TRANSACTIONAL' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1,
'MASTER_LOG_POS' => 1, 'MASTER_SSL_KEY' => 1, 'RAID_CHUNKSIZE' => 1,
'RELAY_LOG_FILE' => 1, 'SQL_TSI_MINUTE' => 1, 'SQL_TSI_SECOND' => 1,
'TABLE_CHECKSUM' => 1, 'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'DELAY_KEY_WRITE' => 1, 'MASTER_LOG_FILE' => 1,
'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1, 'SQL_TSI_QUARTER' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'UNDO_BUFFER_SIZE' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'SQL_BUFFER_RESULT' => 1,
'SQL_TSI_FRAC_SECOND' => 1,
'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 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, '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, '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,
'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, 'EXISTS' => 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,
'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,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'MODIFIES' => 3, 'OPTIMIZE' => 3, 'RESTRICT' => 3,
'SPECIFIC' => 3, 'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3,
'UNSIGNED' => 3, 'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'MIDDLEINT' => 3, 'PRECISION' => 3,
'PROCEDURE' => 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,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 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, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'CROSS JOIN' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7, 'LINEAR KEY' => 7,
'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'LINEAR HASH' => 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,
'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, 'BINARY' => 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, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'TRIM' => 33, 'USER' => 33,
'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'DECOD' => 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, 'CONCAT' => 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, 'QUARTER' => 33, 'RADIANS' => 33, 'REVERSE' => 33, 'SOUNDEX' => 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, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33, 'MAKEDATE' => 33,
'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33, 'OVERLAPS' => 33,
'PASSWORD' => 33, 'POSITION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33,
'VARIANCE' => 33, 'VAR_SAMP' => 33, 'YEARWEEK' => 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, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'SUBSTRING' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INTERSECTS' => 33, 'MBRTOUCHES' => 33,
'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33,
'STDDEV_POP' => 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, 'GEOMFROMWKB' => 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, '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, 'LINEFROMTEXT' => 33,
'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33,
'POLYFROMTEXT' => 33, 'RELEASE_LOCK' => 33, 'SESSION_USER' => 33,
'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'INTERIORRINGN' => 33,
'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33,
'TIMESTAMPDIFF' => 33,
'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33, 'POLYGONFROMWKB' => 33,
'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'POLYGONFROMTEXT' => 33,
'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'MULTIPOINTFROMTEXT' => 33,
'MULTIPOLYGONFROMWKB' => 33, 'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 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,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,317 @@
<?php
/**
* Context for MySQL 5.5.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.5/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.5.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50500 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
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,
'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, 'OPEN' => 1, 'PAGE' => 1, 'PORT' => 1,
'PREV' => 1, 'ROWS' => 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, '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, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1, 'CLIENT' => 1,
'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1, 'ESCAPE' => 1,
'EVENTS' => 1, 'FAULTS' => 1, 'FIELDS' => 1, 'GLOBAL' => 1, 'GRANTS' => 1,
'IMPORT' => 1, 'INNODB' => 1, 'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1,
'MEDIUM' => 1, 'MEMORY' => 1, 'MODIFY' => 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,
'AUTHORS' => 1, 'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1, 'COMPACT' => 1,
'CONTEXT' => 1, 'DEFINER' => 1, 'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1,
'ENGINES' => 1, 'EXECUTE' => 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, 'STORAGE' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'VIRTUAL' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'INNOBASE' => 1, 'LANGUAGE' => 1,
'MAX_ROWS' => 1, 'MAX_SIZE' => 1, 'MIN_ROWS' => 1, 'NATIONAL' => 1,
'NVARCHAR' => 1, 'ONE_SHOT' => 1, 'PRESERVE' => 1, 'PROFILES' => 1,
'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1, 'SCHEDULE' => 1,
'SECURITY' => 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, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'PARTITION' => 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, 'PRIVILEGES' => 1,
'REORGANIZE' => 1, 'REPEATABLE' => 1, 'ROW_FORMAT' => 1, 'SQL_THREAD' => 1,
'TABLESPACE' => 1, 'TABLE_NAME' => 1,
'COLUMN_NAME' => 1, 'CURSOR_NAME' => 1, 'EXTENT_SIZE' => 1, 'FRAC_SECOND' => 1,
'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1, 'MYSQL_ERRNO' => 1,
'PROCESSLIST' => 1, 'REPLICATION' => 1, 'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1,
'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'CONTRIBUTORS' => 1,
'DES_KEY_FILE' => 1, 'INITIAL_SIZE' => 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,
'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_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,
'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1,
'SQL_TSI_QUARTER' => 1, 'SUBCLASS_ORIGIN' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'UNDO_BUFFER_SIZE' => 1,
'CONSTRAINT_SCHEMA' => 1, 'IGNORE_SERVER_IDS' => 1, 'MASTER_SSL_CAPATH' => 1,
'MASTER_SSL_CIPHER' => 1, 'SQL_BUFFER_RESULT' => 1,
'CONSTRAINT_CATALOG' => 1,
'SQL_TSI_FRAC_SECOND' => 1,
'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 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, '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, '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,
'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, 'EXISTS' => 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, '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,
'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, 'MIDDLEINT' => 3, 'PRECISION' => 3,
'PROCEDURE' => 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,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 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, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'CROSS JOIN' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7, 'LINEAR KEY' => 7,
'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'LINEAR HASH' => 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,
'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, 'BINARY' => 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, '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, '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, 'QUARTER' => 33, 'RADIANS' => 33, 'REVERSE' => 33, 'SOUNDEX' => 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, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33, 'MAKEDATE' => 33,
'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33, 'OVERLAPS' => 33,
'PASSWORD' => 33, 'POSITION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33,
'VARIANCE' => 33, 'VAR_SAMP' => 33, 'YEARWEEK' => 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, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'SUBSTRING' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INTERSECTS' => 33, 'MBRTOUCHES' => 33,
'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33,
'STDDEV_POP' => 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, 'GEOMFROMWKB' => 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, '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, 'LINEFROMTEXT' => 33,
'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33,
'POLYFROMTEXT' => 33, 'RELEASE_LOCK' => 33, 'SESSION_USER' => 33,
'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'INTERIORRINGN' => 33,
'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33,
'TIMESTAMPDIFF' => 33,
'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33, 'POLYGONFROMWKB' => 33,
'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'POLYGONFROMTEXT' => 33,
'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'MULTIPOINTFROMTEXT' => 33,
'MULTIPOLYGONFROMWKB' => 33, 'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 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,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,346 @@
<?php
/**
* Context for MySQL 5.6.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.6/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.6.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50600 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
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,
'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, 'ROWS' => 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, '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, '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,
'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,
'ANALYSE' => 1, 'AUTHORS' => 1, 'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1,
'COMPACT' => 1, 'CONTEXT' => 1, 'CURRENT' => 1, 'DEFINER' => 1, 'DISABLE' => 1,
'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1, 'EXECUTE' => 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, 'STORAGE' => 1, 'SUBJECT' => 1,
'SUSPEND' => 1, 'UNICODE' => 1, 'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1,
'VIRTUAL' => 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, 'ONE_SHOT' => 1, 'PRESERVE' => 1, 'PROFILES' => 1,
'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1, 'SCHEDULE' => 1,
'SECURITY' => 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, '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,
'COLUMN_NAME' => 1, 'CURSOR_NAME' => 1, 'DIAGNOSTICS' => 1, 'EXTENT_SIZE' => 1,
'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1, 'MYSQL_ERRNO' => 1,
'PROCESSLIST' => 1, 'REPLICATION' => 1, 'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1,
'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'CONTRIBUTORS' => 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,
'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 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, '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,
'SQL_AFTER_MTS_GAPS' => 1, 'STATS_SAMPLE_PAGES' => 1,
'MASTER_AUTO_POSITION' => 1, 'MASTER_CONNECT_RETRY' => 1,
'MAX_QUERIES_PER_HOUR' => 1, 'MAX_UPDATES_PER_HOUR' => 1,
'MAX_USER_CONNECTIONS' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 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, '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,
'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, 'EXISTS' => 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, '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,
'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, 'MIDDLEINT' => 3, 'PARTITION' => 3,
'PRECISION' => 3, 'PROCEDURE' => 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,
'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, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'CROSS JOIN' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7, 'LINEAR KEY' => 7,
'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'LINEAR HASH' => 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,
'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, 'BINARY' => 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, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 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,
'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, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'ST_ASTEXT' => 33, 'ST_BUFFER' => 33, 'ST_EQUALS' => 33, 'ST_POINTN' => 33,
'ST_WITHIN' => 33, 'SUBSTRING' => 33, 'TO_BASE64' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INET6_ATON' => 33, 'INET6_NTOA' => 33,
'INTERSECTS' => 33, 'MBRTOUCHES' => 33, 'MULTIPOINT' => 33, 'NAME_CONST' => 33,
'PERIOD_ADD' => 33, 'STARTPOINT' => 33, 'STDDEV_POP' => 33, 'ST_CROSSES' => 33,
'ST_ISEMPTY' => 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, '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, '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, 'LINEFROMTEXT' => 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_DIMENSION' => 33, 'ST_GEOMETRYN' => 33,
'ST_NUMPOINTS' => 33, 'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'CREATE_DIGEST' => 33, 'FROM_UNIXTIME' => 33,
'GTID_SUBTRACT' => 33, 'INTERIORRINGN' => 33, 'MBRINTERSECTS' => 33,
'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33, 'MPOLYFROMTEXT' => 33,
'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 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,
'ASYMMETRIC_SIGN' => 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_POINTFROMWKB' => 33, 'ST_POLYFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33, 'ST_INTERIORRINGN' => 33, 'ST_NUMGEOMETRIES' => 33,
'ST_POINTFROMTEXT' => 33, 'ST_SYMDIFFERENCE' => 33,
'ASYMMETRIC_DERIVE' => 33, 'ASYMMETRIC_VERIFY' => 33, 'LINESTRINGFROMWKB' => 33,
'MULTIPOINTFROMWKB' => 33, 'ST_POLYGONFROMWKB' => 33,
'ASYMMETRIC_DECRYPT' => 33, 'ASYMMETRIC_ENCRYPT' => 33, 'MULTIPOINTFROMTEXT' => 33,
'ST_GEOMCOLLFROMTXT' => 33, 'ST_GEOMCOLLFROMWKB' => 33, 'ST_POLYGONFROMTEXT' => 33,
'MULTIPOLYGONFROMWKB' => 33, 'ST_GEOMCOLLFROMTEXT' => 33, 'ST_GEOMETRYFROMTEXT' => 33,
'ST_NUMINTERIORRINGS' => 33, 'UNCOMPRESSED_LENGTH' => 33,
'CREATE_DH_PARAMETERS' => 33, 'MULTIPOLYGONFROMTEXT' => 33,
'ST_LINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33,
'CREATE_ASYMMETRIC_PUB_KEY' => 33, 'GEOMETRYCOLLECTIONFROMWKB' => 33,
'CREATE_ASYMMETRIC_PRIV_KEY' => 33, 'GEOMETRYCOLLECTIONFROMTEXT' => 33,
'VALIDATE_PASSWORD_STRENGTH' => 33,
'SQL_THREAD_WAIT_AFTER_GTIDS' => 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,
'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,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,358 @@
<?php
/**
* Context for MySQL 5.7.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.7/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.7.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ContextMySql50700 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
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,
'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, 'ROWS' => 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, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1, 'SWITCHES' => 1,
'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 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, '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,
'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, 'EXISTS' => 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, 'MIDDLEINT' => 3,
'PARTITION' => 3, 'PRECISION' => 3, 'PROCEDURE' => 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, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'CROSS JOIN' => 7, 'FOR UPDATE' => 7, 'INNER JOIN' => 7, 'LINEAR KEY' => 7,
'NO RELEASE' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'LINEAR HASH' => 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,
'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, 'BINARY' => 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,
'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,
'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, '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, '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, '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, '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,
'NUMINTERIORRINGS' => 33, 'ST_INTERIORRINGN' => 33, 'ST_MLINEFROMTEXT' => 33,
'ST_MPOINTFROMWKB' => 33, 'ST_MPOLYFROMTEXT' => 33, 'ST_NUMGEOMETRIES' => 33,
'ST_POINTFROMTEXT' => 33, 'ST_SYMDIFFERENCE' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33, 'RELEASE_ALL_LOCKS' => 33,
'ST_LATFROMGEOHASH' => 33, 'ST_MPOINTFROMTEXT' => 33, 'ST_POLYGONFROMWKB' => 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,
'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,
'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,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,50 @@
<?php
/**
* Exception thrown by the lexer.
*
* @package SqlParser
* @subpackage Exceptions
*/
namespace SqlParser\Exceptions;
/**
* Exception thrown by the lexer.
*
* @category Exceptions
* @package SqlParser
* @subpackage Exceptions
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class LexerException extends \Exception
{
/**
* The character that produced this error.
*
* @var string
*/
public $ch;
/**
* The index of the character that produced this error.
*
* @var int
*/
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.
* @param int $code The code of this error.
*/
public function __construct($msg = '', $ch = '', $pos = 0, $code = 0)
{
parent::__construct($msg, $code);
$this->ch = $ch;
$this->pos = $pos;
}
}

View File

@ -0,0 +1,43 @@
<?php
/**
* Exception thrown by the parser.
*
* @package SqlParser
* @subpackage Exceptions
*/
namespace SqlParser\Exceptions;
use SqlParser\Token;
/**
* Exception thrown by the parser.
*
* @category Exceptions
* @package SqlParser
* @subpackage Exceptions
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ParserException extends \Exception
{
/**
* The token that produced this error.
*
* @var Token
*/
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)
{
parent::__construct($msg, $code);
$this->token = $token;
}
}

View File

@ -0,0 +1,930 @@
<?php
/**
* Defines the lexer of the library.
*
* This is one of the most important components, along with the parser.
*
* Depends on context to extract lexemes.
*
* @package SqlParser
*/
namespace SqlParser;
require_once 'common.php';
use SqlParser\Exceptions\LexerException;
if (!defined('USE_UTF_STRINGS')) {
// NOTE: In previous versions of PHP (5.5 and older) the default
// internal encoding is "ISO-8859-1".
// All `mb_` functions must specify the correct encoding, which is
// 'UTF-8' in order to work properly.
/**
* Forces usage of `UtfString` if the string is multibyte.
* `UtfString` may be slower, but it gives better results.
*
* @var bool
*/
define('USE_UTF_STRINGS', true);
}
/**
* Performs lexical analysis over a SQL statement and splits it in multiple
* tokens.
*
* The output of the lexer is affected by the context of the SQL statement.
*
* @category Lexer
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
* @see Context
*/
class Lexer
{
/**
* A list of methods that are used in lexing the SQL query.
*
* @var array
*/
public static $PARSER_METHODS = array(
// It is best to put the parsers in order of their complexity
// (ascending) and their occurrence rate (descending).
//
// Conflicts:
//
// 1. `parseDelimiter`, `parseUnknown`, `parseKeyword`, `parseNumber`
// They fight over delimiter. The delimiter may be a keyword, a
// number or almost any character which makes the delimiter one of
// the first tokens that must be parsed.
//
// 1. `parseNumber` and `parseOperator`
// They fight over `+` and `-`.
//
// 2. `parseComment` and `parseOperator`
// They fight over `/` (as in ```/*comment*/``` or ```a / b```)
//
// 3. `parseBool` and `parseKeyword`
// They fight over `TRUE` and `FALSE`.
//
// 4. `parseKeyword` and `parseUnknown`
// They fight over words. `parseUnknown` does not know about
// keywords.
'parseDelimiter', 'parseWhitespace', 'parseNumber',
'parseComment', 'parseOperator', 'parseBool', 'parseString',
'parseSymbol', 'parseKeyword', 'parseLabel', 'parseUnknown'
);
/**
* Whether errors should throw exceptions or just be stored.
*
* @var bool
*
* @see static::$errors
*/
public $strict = false;
/**
* The string to be parsed.
*
* @var string|UtfString
*/
public $str = '';
/**
* The length of `$str`.
*
* By storing its length, a lot of time is saved, because parsing methods
* would call `strlen` everytime.
*
* @var int
*/
public $len = 0;
/**
* The index of the last parsed character.
*
* @var int
*/
public $last = 0;
/**
* Tokens extracted from given strings.
*
* @var TokensList
*/
public $list;
/**
* The default delimiter. This is used, by default, in all new instances.
*
* @var string
*/
public static $DEFAULT_DELIMITER = ';';
/**
* Statements delimiter.
* This may change during lexing.
*
* @var string
*/
public $delimiter;
/**
* The length of the delimiter.
*
* Because `parseDelimiter` can be called a lot, it would perform a lot of
* calls to `strlen`, which might affect performance when the delimiter is
* big.
*
* @var int
*/
public $delimiterLen;
/**
* List of errors that occurred during lexing.
*
* Usually, the lexing does not stop once an error occurred because that
* error might be false positive or a partial result (even a bad one)
* might be needed.
*
* @var LexerException[]
*
* @see Lexer::error()
*/
public $errors = array();
/**
* Gets the tokens list parsed by a new instance of a lexer.
*
* @param string|UtfString $str The query to be lexed.
* @param bool $strict Whether strict mode should be
* enabled or not.
* @param string $delimiter The delimiter to be used.
*
* @return TokensList
*/
public static function getTokens($str, $strict = false, $delimiter = null)
{
$lexer = new Lexer($str, $strict, $delimiter);
return $lexer->list;
}
/**
* Constructor.
*
* @param string|UtfString $str The query to be lexed.
* @param bool $strict Whether strict mode should be
* enabled or not.
* @param string $delimiter The delimiter to be used.
*/
public function __construct($str, $strict = false, $delimiter = null)
{
// `strlen` is used instead of `mb_strlen` because the lexer needs to
// parse each byte of the input.
$len = ($str instanceof UtfString) ? $str->length() : strlen($str);
// For multi-byte strings, a new instance of `UtfString` is
// initialized (only if `UtfString` usage is forced.
if (!($str instanceof UtfString)) {
if ((USE_UTF_STRINGS) && ($len !== mb_strlen($str, 'UTF-8'))) {
$str = new UtfString($str);
}
}
$this->str = $str;
$this->len = ($str instanceof UtfString) ? $str->length() : $len;
$this->strict = $strict;
// Setting the delimiter.
$this->setDelimiter(
!empty($delimiter) ? $delimiter : static::$DEFAULT_DELIMITER
);
$this->lex();
}
/**
* Sets the delimiter.
*
* @param string $delimiter The new delimiter.
*/
public function setDelimiter($delimiter)
{
$this->delimiter = $delimiter;
$this->delimiterLen = strlen($delimiter);
}
/**
* Parses the string and extracts lexemes.
*
* @return void
*/
public function lex()
{
// TODO: Sometimes, static::parse* functions make unnecessary calls to
// is* functions. For a better performance, some rules can be deduced
// from context.
// For example, in `parseBool` there is no need to compare the token
// every time with `true` and `false`. The first step would be to
// compare with 'true' only and just after that add another letter from
// context and compare again with `false`.
// Another example is `parseComment`.
$list = new TokensList();
/**
* Last processed token.
*
* @var Token $lastToken
*/
$lastToken = null;
for ($this->last = 0, $lastIdx = 0; $this->last < $this->len; $lastIdx = ++$this->last) {
/**
* The new token.
*
* @var Token $token
*/
$token = null;
foreach (static::$PARSER_METHODS as $method) {
if (($token = $this->$method())) {
break;
}
}
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)
&& ($token->type === Token::TYPE_SYMBOL)
&& ($token->flags & Token::FLAG_SYMBOL_VARIABLE)
&& (($lastToken->type === Token::TYPE_STRING)
|| (($lastToken->type === Token::TYPE_SYMBOL)
&& ($lastToken->flags & Token::FLAG_SYMBOL_BACKTICK)))
) {
// Handles ```... FROM 'user'@'%' ...```.
$lastToken->token .= $token->token;
$lastToken->type = Token::TYPE_SYMBOL;
$lastToken->flags = Token::FLAG_SYMBOL_USER;
$lastToken->value .= '@' . $token->value;
continue;
} elseif (($lastToken !== null)
&& ($token->type === Token::TYPE_KEYWORD)
&& ($lastToken->type === Token::TYPE_OPERATOR)
&& ($lastToken->value === '.')
) {
// Handles ```... tbl.FROM ...```. In this case, FROM is not
// a reserved word.
$token->type = Token::TYPE_NONE;
$token->flags = 0;
$token->value = $token->token;
}
$token->position = $lastIdx;
$list->tokens[$list->count++] = $token;
// 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
);
continue;
}
// Skipping last R (from `delimiteR`) and whitespaces between
// the keyword `DELIMITER` and the actual delimiter.
$pos = ++$this->last;
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
);
continue;
}
$pos = $this->last + 1;
// Parsing the delimiter.
$this->delimiter = null;
while ((++$this->last < $this->len) && (!Context::isWhitespace($this->str[$this->last]))) {
$this->delimiter .= $this->str[$this->last];
}
if (empty($this->delimiter)) {
$this->error(
__('Expected delimiter.'),
'',
$this->last
);
$this->delimiter = ';';
}
--$this->last;
// Saving the delimiter and its token.
$this->delimiterLen = strlen($this->delimiter);
$token = new Token($this->delimiter, Token::TYPE_DELIMITER);
$token->position = $pos;
$list->tokens[$list->count++] = $token;
}
$lastToken = $token;
}
// Adding a final delimiter to mark the ending.
$list->tokens[$list->count++] = new Token(null, Token::TYPE_DELIMITER);
// Saving the tokens list.
$this->list = $list;
}
/**
* Creates a new error log.
*
* @param string $msg The error message.
* @param string $str The character that produced the error.
* @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.
*
* @return void
*/
public function error($msg = '', $str = '', $pos = 0, $code = 0)
{
$error = new LexerException($msg, $str, $pos, $code);
if ($this->strict) {
throw $error;
}
$this->errors[] = $error;
}
/**
* Parses a keyword.
*
* @return Token
*/
public function parseKeyword()
{
$token = '';
/**
* Value to be returned.
*
* @var Token $ret
*/
$ret = null;
/**
* The value of `$this->last` where `$token` ends in `$this->str`.
*
* @var int $iEnd
*/
$iEnd = $this->last;
/**
* Whether last parsed character is a whitespace.
*
* @var bool $lastSpace
*/
$lastSpace = false;
for ($j = 1; $j < Context::KEYWORD_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
// Composed keywords shouldn't have more than one whitespace between
// keywords.
if (Context::isWhitespace($this->str[$this->last])) {
if ($lastSpace) {
--$j; // The size of the keyword didn't increase.
continue;
} else {
$lastSpace = true;
}
} else {
$lastSpace = false;
}
$token .= $this->str[$this->last];
if (($this->last + 1 === $this->len) || (Context::isSeparator($this->str[$this->last + 1]))) {
if (($flags = Context::isKeyword($token))) {
$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;
return $ret;
}
/**
* Parses a label.
*
* @return Token
*/
public function parseLabel()
{
$token = '';
/**
* Value to be returned.
*
* @var Token $ret
*/
$ret = null;
/**
* The value of `$this->last` where `$token` ends in `$this->str`.
*
* @var int $iEnd
*/
$iEnd = $this->last;
/**
* Whether last parsed character is a whitespace.
*
* @var bool $lastSpace
*/
$lastSpace = false;
for ($j = 1; $j < Context::LABEL_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
// Composed keywords shouldn't have more than one whitespace between
// keywords.
if (Context::isWhitespace($this->str[$this->last])) {
if ($lastSpace) {
--$j; // The size of the keyword didn't increase.
continue;
} else {
$lastSpace = true;
}
} elseif ($this->str[$this->last] === ':') {
$token .= $this->str[$this->last];
$ret = new Token($token, Token::TYPE_LABEL);
$iEnd = $this->last;
break;
} else {
$lastSpace = false;
}
$token .= $this->str[$this->last];
}
$this->last = $iEnd;
return $ret;
}
/**
* Parses an operator.
*
* @return Token
*/
public function parseOperator()
{
$token = '';
/**
* Value to be returned.
*
* @var Token $ret
*/
$ret = null;
/**
* The value of `$this->last` where `$token` ends in `$this->str`.
*
* @var int $iEnd
*/
$iEnd = $this->last;
for ($j = 1; $j < Context::OPERATOR_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
$token .= $this->str[$this->last];
if ($flags = Context::isOperator($token)) {
$ret = new Token($token, Token::TYPE_OPERATOR, $flags);
$iEnd = $this->last;
}
}
$this->last = $iEnd;
return $ret;
}
/**
* Parses a whitespace.
*
* @return Token
*/
public function parseWhitespace()
{
$token = $this->str[$this->last];
if (!Context::isWhitespace($token)) {
return null;
}
while ((++$this->last < $this->len) && (Context::isWhitespace($this->str[$this->last]))) {
$token .= $this->str[$this->last];
}
--$this->last;
return new Token($token, Token::TYPE_WHITESPACE);
}
/**
* Parses a comment.
*
* @return Token
*/
public function parseComment()
{
$iBak = $this->last;
$token = $this->str[$this->last];
// Bash style comments. (#comment\n)
if (Context::isComment($token)) {
while ((++$this->last < $this->len) && ($this->str[$this->last] !== "\n")) {
$token .= $this->str[$this->last];
}
$token .= "\n"; // Adding the line ending.
return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_BASH);
}
// C style comments. (/*comment*\/)
if (++$this->last < $this->len) {
$token .= $this->str[$this->last];
if (Context::isComment($token)) {
$flags = Token::FLAG_COMMENT_C;
// This comment already ended. It may be a part of a
// previous MySQL specific command.
if ($token === '*/') {
return new Token($token, Token::TYPE_COMMENT, $flags);
}
// Checking if this is a MySQL-specific command.
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)
&& ('0' <= $this->str[$this->last])
&& ($this->str[$this->last] <= '9')
) {
$token .= $this->str[$this->last];
}
--$this->last;
// We split this comment and parse only its beginning
// here.
return new Token($token, Token::TYPE_COMMENT, $flags);
}
// Parsing the comment.
while ((++$this->last < $this->len)
&& (($this->str[$this->last - 1] !== '*') || ($this->str[$this->last] !== '/'))
) {
$token .= $this->str[$this->last];
}
// Adding the ending.
if ($this->last < $this->len) {
$token .= $this->str[$this->last];
}
return new Token($token, Token::TYPE_COMMENT, $flags);
}
}
// SQL style comments. (-- comment\n)
if (++$this->last < $this->len) {
$token .= $this->str[$this->last];
if (Context::isComment($token)) {
// 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")) {
$token .= $this->str[$this->last];
}
$token .= "\n"; // Adding the line ending.
}
return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_SQL);
}
}
$this->last = $iBak;
return null;
}
/**
* Parses a boolean.
*
* @return Token
*/
public function parseBool()
{
if ($this->last + 3 >= $this->len) {
// At least `min(strlen('TRUE'), strlen('FALSE'))` characters are
// required.
return null;
}
$iBak = $this->last;
$token = $this->str[$this->last] . $this->str[++$this->last]
. $this->str[++$this->last] . $this->str[++$this->last]; // _TRUE_ or _FALS_e
if (Context::isBool($token)) {
return new Token($token, Token::TYPE_BOOL);
} elseif (++$this->last < $this->len) {
$token .= $this->str[$this->last]; // fals_E_
if (Context::isBool($token)) {
return new Token($token, Token::TYPE_BOOL, 1);
}
}
$this->last = $iBak;
return null;
}
/**
* Parses a number.
*
* @return Token
*/
public function parseNumber()
{
// A rudimentary state machine is being used to parse numbers due to
// the various forms of their notation.
//
// Below are the states of the machines and the conditions to change
// the state.
//
// 1 --------------------[ + or - ]-------------------> 1
// 1 -------------------[ 0x or 0X ]------------------> 2
// 1 --------------------[ 0 to 9 ]-------------------> 3
// 1 -----------------------[ . ]---------------------> 4
// 1 -----------------------[ b ]---------------------> 7
//
// 2 --------------------[ 0 to F ]-------------------> 2
//
// 3 --------------------[ 0 to 9 ]-------------------> 3
// 3 -----------------------[ . ]---------------------> 4
// 3 --------------------[ e or E ]-------------------> 5
//
// 4 --------------------[ 0 to 9 ]-------------------> 4
// 4 --------------------[ e or E ]-------------------> 5
//
// 5 ---------------[ + or - or 0 to 9 ]--------------> 6
//
// 7 -----------------------[ ' ]---------------------> 8
//
// 8 --------------------[ 0 or 1 ]-------------------> 8
// 8 -----------------------[ ' ]---------------------> 9
//
// State 1 may be reached by negative numbers.
// State 2 is reached only by hex numbers.
// State 4 is reached only by float numbers.
// State 5 is reached only by numbers in approximate form.
// State 7 is reached only by numbers in bit representation.
//
// Valid final states are: 2, 3, 4 and 6. Any parsing that finished in a
// state other than these is invalid.
$iBak = $this->last;
$token = '';
$flags = 0;
$state = 1;
for (; $this->last < $this->len; ++$this->last) {
if ($state === 1) {
if ($this->str[$this->last] === '-') {
$flags |= Token::FLAG_NUMBER_NEGATIVE;
} elseif (($this->last + 1 < $this->len)
&& ($this->str[$this->last] === '0')
&& (($this->str[$this->last + 1] === 'x')
|| ($this->str[$this->last + 1] === 'X'))
) {
$token .= $this->str[$this->last++];
$state = 2;
} elseif (($this->str[$this->last] >= '0') && ($this->str[$this->last] <= '9')) {
$state = 3;
} elseif ($this->str[$this->last] === '.') {
$state = 4;
} elseif ($this->str[$this->last] === 'b') {
$state = 7;
} elseif ($this->str[$this->last] !== '+') {
// `+` is a valid character in a number.
break;
}
} elseif ($state === 2) {
$flags |= Token::FLAG_NUMBER_HEX;
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')))
) {
break;
}
} elseif ($state === 3) {
if ($this->str[$this->last] === '.') {
$state = 4;
} elseif (($this->str[$this->last] === 'e') || ($this->str[$this->last] === 'E')) {
$state = 5;
} elseif (($this->str[$this->last] < '0') || ($this->str[$this->last] > '9')) {
// Just digits and `.`, `e` and `E` are valid characters.
break;
}
} elseif ($state === 4) {
$flags |= Token::FLAG_NUMBER_FLOAT;
if (($this->str[$this->last] === 'e') || ($this->str[$this->last] === 'E')) {
$state = 5;
} elseif (($this->str[$this->last] < '0') || ($this->str[$this->last] > '9')) {
// Just digits, `e` and `E` are valid characters.
break;
}
} elseif ($state === 5) {
$flags |= Token::FLAG_NUMBER_APPROXIMATE;
if (($this->str[$this->last] === '+') || ($this->str[$this->last] === '-')
|| ((($this->str[$this->last] >= '0') && ($this->str[$this->last] <= '9')))
) {
$state = 6;
} else {
break;
}
} elseif ($state === 6) {
if (($this->str[$this->last] < '0') || ($this->str[$this->last] > '9')) {
// Just digits are valid characters.
break;
}
} elseif ($state === 7) {
$flags |= Token::FLAG_NUMBER_BINARY;
if ($this->str[$this->last] === '\'') {
$state = 8;
} else {
break;
}
} elseif ($state === 8) {
if ($this->str[$this->last] === '\'') {
$state = 9;
} 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)
) {
--$this->last;
return new Token($token, Token::TYPE_NUMBER, $flags);
}
$this->last = $iBak;
return null;
}
/**
* Parses a string.
*
* @param string $quote Additional starting symbol.
*
* @return Token
*/
public function parseString($quote = '')
{
$token = $this->str[$this->last];
if ((!($flags = Context::isString($token))) && ($token !== $quote)) {
return null;
}
$quote = $token;
while (++$this->last < $this->len) {
if (($this->last + 1 < $this->len)
&& ((($this->str[$this->last] === $quote) && ($this->str[$this->last + 1] === $quote))
|| (($this->str[$this->last] === '\\') && ($quote !== '`')))
) {
$token .= $this->str[$this->last] . $this->str[++$this->last];
} else {
if ($this->str[$this->last] === $quote) {
break;
}
$token .= $this->str[$this->last];
}
}
if (($this->last >= $this->len) || ($this->str[$this->last] !== $quote)) {
$this->error(
sprintf(
__('Ending quote %1$s was expected.'),
$quote
),
'',
$this->last
);
} else {
$token .= $this->str[$this->last];
}
return new Token($token, Token::TYPE_STRING, $flags);
}
/**
* Parses a symbol.
*
* @return Token
*/
public function parseSymbol()
{
$token = $this->str[$this->last];
if (!($flags = Context::isSymbol($token))) {
return null;
}
if ($flags & Token::FLAG_SYMBOL_VARIABLE) {
if ($this->str[++$this->last] === '@') {
// This is a system variable (e.g. `@@hostname`).
$token .= $this->str[$this->last++];
$flags |= Token::FLAG_SYMBOL_SYSTEM;
}
} else {
$token = '';
}
$str = null;
if ($this->last < $this->len) {
if (($str = $this->parseString('`')) === null) {
if (($str = static::parseUnknown()) === null) {
$this->error(
__('Variable name was expected.'),
$this->str[$this->last],
$this->last
);
}
}
}
if ($str !== null) {
$token .= $str->token;
}
return new Token($token, Token::TYPE_SYMBOL, $flags);
}
/**
* Parses unknown parts of the query.
*
* @return Token
*/
public function parseUnknown()
{
$token = $this->str[$this->last];
if (Context::isSeparator($token)) {
return null;
}
while ((++$this->last < $this->len) && (!Context::isSeparator($this->str[$this->last]))) {
$token .= $this->str[$this->last];
}
--$this->last;
return new Token($token);
}
/**
* Parses the delimiter of the query.
*
* @return Token
*/
public function parseDelimiter()
{
$idx = 0;
while (($idx < $this->delimiterLen) && ($this->last + $idx < $this->len)) {
if ($this->delimiter[$idx] !== $this->str[$this->last + $idx]) {
return null;
}
++$idx;
}
$this->last += $this->delimiterLen - 1;
return new Token($this->delimiter, Token::TYPE_DELIMITER);
}
}

View File

@ -0,0 +1,607 @@
<?php
/**
* Defines the parser of the library.
*
* This is one of the most important components, along with the lexer.
*
* @package SqlParser
*/
namespace SqlParser;
require_once 'common.php';
use SqlParser\Exceptions\ParserException;
use SqlParser\Statements\SelectStatement;
use SqlParser\Statements\TransactionStatement;
/**
* Takes multiple tokens (contained in a Lexer instance) as input and builds a
* parse tree.
*
* @category Parser
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Parser
{
/**
* Array of classes that are used in parsing the SQL statements.
*
* @var array
*/
public static $STATEMENT_PARSERS = array(
// MySQL Utility Statements
'DESCRIBE' => 'SqlParser\\Statements\\ExplainStatement',
'DESC' => 'SqlParser\\Statements\\ExplainStatement',
'EXPLAIN' => 'SqlParser\\Statements\\ExplainStatement',
'FLUSH' => '',
'GRANT' => '',
'HELP' => '',
'SET PASSWORD' => '',
'STATUS' => '',
'USE' => '',
// Table Maintenance Statements
// https://dev.mysql.com/doc/refman/5.7/en/table-maintenance-sql.html
'ANALYZE' => 'SqlParser\\Statements\\AnalyzeStatement',
'BACKUP' => 'SqlParser\\Statements\\BackupStatement',
'CHECK' => 'SqlParser\\Statements\\CheckStatement',
'CHECKSUM' => 'SqlParser\\Statements\\ChecksumStatement',
'OPTIMIZE' => 'SqlParser\\Statements\\OptimizeStatement',
'REPAIR' => 'SqlParser\\Statements\\RepairStatement',
'RESTORE' => 'SqlParser\\Statements\\RestoreStatement',
// Database Administration Statements
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-server-administration.html
'SET' => 'SqlParser\\Statements\\SetStatement',
'SHOW' => 'SqlParser\\Statements\\ShowStatement',
// Data Definition Statements.
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-data-definition.html
'ALTER' => 'SqlParser\\Statements\\AlterStatement',
'CREATE' => 'SqlParser\\Statements\\CreateStatement',
'DROP' => 'SqlParser\\Statements\\DropStatement',
'RENAME' => 'SqlParser\\Statements\\RenameStatement',
'TRUNCATE' => 'SqlParser\\Statements\\TruncateStatement',
// Data Manipulation Statements.
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-data-manipulation.html
'CALL' => 'SqlParser\\Statements\\CallStatement',
'DELETE' => 'SqlParser\\Statements\\DeleteStatement',
'DO' => '',
'HANDLER' => '',
'INSERT' => 'SqlParser\\Statements\\InsertStatement',
'LOAD' => '',
'REPLACE' => 'SqlParser\\Statements\\ReplaceStatement',
'SELECT' => 'SqlParser\\Statements\\SelectStatement',
'UPDATE' => 'SqlParser\\Statements\\UpdateStatement',
// Prepared Statements.
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
'DEALLOCATE' => '',
'EXECUTE' => '',
'PREPARE' => '',
// Transactional and Locking Statements
// https://dev.mysql.com/doc/refman/5.7/en/commit.html
'BEGIN' => 'SqlParser\\Statements\\TransactionStatement',
'COMMIT' => 'SqlParser\\Statements\\TransactionStatement',
'ROLLBACK' => 'SqlParser\\Statements\\TransactionStatement',
'START TRANSACTION' => 'SqlParser\\Statements\\TransactionStatement',
);
/**
* Array of classes that are used in parsing SQL components.
*
* @var array
*/
public static $KEYWORD_PARSERS = array(
// This is not a proper keyword and was added here to help the
// formatter.
'PARTITION BY' => array(),
'SUBPARTITION BY' => array(),
// This is not a proper keyword and was added here to help the
// builder.
'_OPTIONS' => array(
'class' => 'SqlParser\\Components\\OptionsArray',
'field' => 'options',
),
'_END_OPTIONS' => array(
'class' => 'SqlParser\\Components\\OptionsArray',
'field' => 'end_options',
),
'UNION' => array(
'class' => 'SqlParser\\Components\\UnionKeyword',
'field' => 'union',
),
'UNION ALL' => array(
'class' => 'SqlParser\\Components\\UnionKeyword',
'field' => 'union',
),
'UNION DISTINCT' => array(
'class' => 'SqlParser\\Components\\UnionKeyword',
'field' => 'union',
),
// Actual clause parsers.
'ALTER' => array(
'class' => 'SqlParser\\Components\\Expression',
'field' => 'table',
'options' => array('parseField' => 'table'),
),
'ANALYZE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'BACKUP' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'CALL' => array(
'class' => 'SqlParser\\Components\\FunctionCall',
'field' => 'call',
),
'CHECK' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'CHECKSUM' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'CROSS JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'DROP' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'fields',
'options' => array('parseField' => 'table'),
),
'FROM' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'from',
'options' => array('field' => 'table'),
),
'GROUP BY' => array(
'class' => 'SqlParser\\Components\\OrderKeyword',
'field' => 'group',
),
'HAVING' => array(
'class' => 'SqlParser\\Components\\Condition',
'field' => 'having',
),
'INTO' => array(
'class' => 'SqlParser\\Components\\IntoKeyword',
'field' => 'into',
),
'JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'LEFT JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'LEFT OUTER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'ON' => array(
'class' => 'SqlParser\\Components\\Expression',
'field' => 'table',
'options' => array('parseField' => 'table'),
),
'RIGHT JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'RIGHT OUTER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'INNER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'FULL JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'FULL OUTER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'NATURAL JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'NATURAL LEFT JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'NATURAL RIGHT JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'NATURAL LEFT OUTER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'NATURAL RIGHT OUTER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'LIMIT' => array(
'class' => 'SqlParser\\Components\\Limit',
'field' => 'limit',
),
'OPTIMIZE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'ORDER BY' => array(
'class' => 'SqlParser\\Components\\OrderKeyword',
'field' => 'order',
),
'PARTITION' => array(
'class' => 'SqlParser\\Components\\ArrayObj',
'field' => 'partition',
),
'PROCEDURE' => array(
'class' => 'SqlParser\\Components\\FunctionCall',
'field' => 'procedure',
),
'RENAME' => array(
'class' => 'SqlParser\\Components\\RenameOperation',
'field' => 'renames',
),
'REPAIR' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'RESTORE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'SET' => array(
'class' => 'SqlParser\\Components\\SetOperation',
'field' => 'set',
),
'SELECT' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'expr',
),
'TRUNCATE' => array(
'class' => 'SqlParser\\Components\\Expression',
'field' => 'table',
'options' => array('parseField' => 'table'),
),
'UPDATE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'VALUE' => array(
'class' => 'SqlParser\\Components\\Array2d',
'field' => 'values',
),
'VALUES' => array(
'class' => 'SqlParser\\Components\\Array2d',
'field' => 'values',
),
'WHERE' => array(
'class' => 'SqlParser\\Components\\Condition',
'field' => 'where',
),
);
/**
* The list of tokens that are parsed.
*
* @var TokensList
*/
public $list;
/**
* Whether errors should throw exceptions or just be stored.
*
* @var bool
*
* @see static::$errors
*/
public $strict = false;
/**
* List of errors that occurred during parsing.
*
* Usually, the parsing does not stop once an error occurred because that
* error might be a false positive or a partial result (even a bad one)
* might be needed.
*
* @var ParserException[]
*
* @see Parser::error()
*/
public $errors = array();
/**
* List of statements parsed.
*
* @var Statement[]
*/
public $statements = array();
/**
* The number of opened brackets.
*
* @var int
*/
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.
*/
public function __construct($list = null, $strict = false)
{
if ((is_string($list)) || ($list instanceof UtfString)) {
$lexer = new Lexer($list, $strict);
$this->list = $lexer->list;
} elseif ($list instanceof TokensList) {
$this->list = $list;
}
$this->strict = $strict;
if ($list !== null) {
$this->parse();
}
}
/**
* Builds the parse trees.
*
* @return void
*/
public function parse()
{
/**
* Last transaction.
*
* @var TransactionStatement $lastTransaction
*/
$lastTransaction = null;
/**
* Last parsed statement.
*
* @var Statement $lastStatement
*/
$lastStatement = null;
/**
* Union's type or false for no union.
*
* @var bool|string $unionType
*/
$unionType = false;
/**
* The index of the last token from the last statement.
*
* @var int $prevLastIdx
*/
$prevLastIdx = -1;
/**
* The list of tokens.
*
* @var TokensList $list
*/
$list = &$this->list;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// `DELIMITER` is not an actual statement and it requires
// special handling.
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;
continue;
}
// Counting the brackets around statements.
if ($token->value === '(') {
++$this->brackets;
continue;
}
// Statements can start with keywords only.
// Comments, whitespaces, etc. are ignored.
if ($token->type !== Token::TYPE_KEYWORD) {
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
);
}
continue;
}
if (($token->value === 'UNION') || ($token->value === 'UNION ALL') || ($token->value === 'UNION DISTINCT')) {
$unionType = $token->value;
continue;
}
// Checking if it is a known statement that can be parsed.
if (empty(static::$STATEMENT_PARSERS[$token->value])) {
if (!isset(static::$STATEMENT_PARSERS[$token->value])) {
// 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
);
}
// Skipping to the end of this statement.
$list->getNextOfType(Token::TYPE_DELIMITER);
$prevLastIdx = $list->idx;
continue;
}
/**
* The name of the class that is used for parsing.
*
* @var string $class
*/
$class = static::$STATEMENT_PARSERS[$token->value];
/**
* Processed statement.
*
* @var Statement $statement
*/
$statement = new $class($this, $this->list);
// The first token that is a part of this token is the next token
// unprocessed by the previous statement.
// There might be brackets around statements and this shouldn't
// affect the parser
$statement->first = $prevLastIdx + 1;
// Storing the index of the last token parsed and updating the old
// index.
$statement->last = $list->idx;
$prevLastIdx = $list->idx;
// Handles unions.
if ((!empty($unionType))
&& ($lastStatement instanceof SelectStatement)
&& ($statement instanceof SelectStatement)
) {
/**
* This SELECT statement.
*
* @var SelectStatement $statement
*/
/**
* Last SELECT statement.
*
* @var SelectStatement $lastStatement
*/
$lastStatement->union[] = array($unionType, $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 = array();
$statement->limit = null;
// The statement actually ends where the last statement in
// union ends.
$lastStatement->last = $statement->last;
$unionType = false;
// Validate clause order
$statement->validateClauseOrder($this, $list);
continue;
}
// Handles transactions.
if ($statement instanceof TransactionStatement) {
/**
* @var TransactionStatement $statement
*/
if ($statement->type === TransactionStatement::TYPE_BEGIN) {
$lastTransaction = $statement;
$this->statements[] = $statement;
} elseif ($statement->type === TransactionStatement::TYPE_END) {
if ($lastTransaction === null) {
// Even though an error occurred, the query is being
// saved.
$this->statements[] = $statement;
$this->error(
__('No transaction was previously started.'),
$token
);
} else {
$lastTransaction->end = $statement;
}
$lastTransaction = null;
}
// Validate clause order
$statement->validateClauseOrder($this, $list);
continue;
}
// Validate clause order
$statement->validateClauseOrder($this, $list);
// Finally, storing the statement.
if ($lastTransaction !== null) {
$lastTransaction->statements[] = $statement;
} else {
$this->statements[] = $statement;
}
$lastStatement = $statement;
}
}
/**
* Creates a new error log.
*
* @param string $msg The error message.
* @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.
*
* @return void
*/
public function error($msg = '', Token $token = null, $code = 0)
{
$error = new ParserException($msg, $token, $code);
if ($this->strict) {
throw $error;
}
$this->errors[] = $error;
}
}

View File

@ -0,0 +1,509 @@
<?php
/**
* The result of the parser is an array of statements are extensions of the
* class defined here.
*
* A statement represents the result of parsing the lexemes.
*
* @package SqlParser
*/
namespace SqlParser;
use SqlParser\Components\OptionsArray;
/**
* Abstract statement definition.
*
* @category Statements
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
abstract class Statement
{
/**
* Options for this statement.
*
* The option would be the key and the value can be an integer or an array.
*
* The integer represents only the index used.
*
* The array may have two keys: `0` is used to represent the index used and
* `1` is the type of the option (which may be 'var' or 'var='). Both
* options mean they expect a value after the option (e.g. `A = B` or `A B`,
* in which case `A` is the key and `B` is the value). The only difference
* is in the building process. `var` options are built as `A B` and `var=`
* options are built as `A = B`
*
* Two options that can be used together must have different values for
* indexes, else, when they will be used together, an error will occur.
*
* @var array
*/
public static $OPTIONS = array();
/**
* The clauses of this statement, in order.
*
* The value attributed to each clause is used by the builder and it may
* have one of the following values:
*
* - 1 = 01 - add the clause only
* - 2 = 10 - add the keyword
* - 3 = 11 - add both the keyword and the clause
*
* @var array
*/
public static $CLAUSES = array();
/**
* The options of this query.
*
* @var OptionsArray
*
* @see static::$OPTIONS
*/
public $options;
/**
* The index of the first token used in this statement.
*
* @var int
*/
public $first;
/**
* The index of the last token used in this statement.
*
* @var int
*/
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)
{
if (($parser !== null) && ($list !== null)) {
$this->parse($parser, $list);
}
}
/**
* Builds the string representation of this statement.
*
* @return string
*/
public function build()
{
/**
* Query to be returned.
*
* @var string $query
*/
$query = '';
/**
* Clauses which were built already.
*
* It is required to keep track of built clauses because some fields,
* for example `join` is used by multiple clauses (`JOIN`, `LEFT JOIN`,
* `LEFT OUTER JOIN`, etc.). The same happens for `VALUE` and `VALUES`.
*
* A clause is considered built just after fields' value
* (`$this->field`) was used in building.
*
* @var array
*/
$built = array();
/**
* Statement's clauses.
*
* @var array
*/
$clauses = $this->getClauses();
foreach ($clauses as $clause) {
/**
* The name of the clause.
*
* @var string $name
*/
$name = $clause[0];
/**
* The type of the clause.
*
* @see self::$CLAUSES
* @var int $type
*/
$type = $clause[1];
/**
* The builder (parser) of this clause.
*
* @var Component $class
*/
$class = Parser::$KEYWORD_PARSERS[$name]['class'];
/**
* The name of the field that is used as source for the builder.
* Same field is used to store the result of parsing.
*
* @var string $field
*/
$field = Parser::$KEYWORD_PARSERS[$name]['field'];
// The field is empty, there is nothing to be built.
if (empty($this->$field)) {
continue;
}
// Checking if this field was already built.
if ($type & 1) {
if (!empty($built[$field])) {
continue;
}
$built[$field] = true;
}
// Checking if the name of the clause should be added.
if ($type & 2) {
$query .= $name . ' ';
}
// Checking if the result of the builder should be added.
if ($type & 1) {
$query .= $class::build($this->$field) . ' ';
}
}
return $query;
}
/**
* Parses the statements defined by the tokens list.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
/**
* Array containing all list of clauses parsed.
* This is used to check for duplicates.
*
* @var array $parsedClauses
*/
$parsedClauses = array();
// This may be corrected by the parser.
$this->first = $list->idx;
/**
* Whether options were parsed or not.
* For statements that do not have any options this is set to `true` by
* default.
*
* @var bool $parsedOptions
*/
$parsedOptions = empty(static::$OPTIONS);
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Checking if this closing bracket is the pair for a bracket
// outside the statement.
if (($token->value === ')') && ($parser->brackets > 0)) {
--$parser->brackets;
continue;
}
// 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)
) {
$parser->error(__('Unexpected token.'), $token);
}
continue;
}
// Unions are parsed by the parser because they represent more than
// one statement.
if (($token->value === 'UNION') || ($token->value === 'UNION ALL') || ($token->value === 'UNION DISTINCT')) {
break;
}
$lastIdx = $list->idx;
// ON DUPLICATE KEY UPDATE ...
// has to be parsed in parent statement (INSERT or REPLACE)
// so look for it and break
if (get_class($this) === 'SqlParser\Statements\SelectStatement'
&& $token->value === 'ON'
) {
++$list->idx; // Skip ON
// look for ON DUPLICATE KEY UPDATE
$first = $list->getNextOfType(Token::TYPE_KEYWORD);
$second = $list->getNextOfType(Token::TYPE_KEYWORD);
$third = $list->getNextOfType(Token::TYPE_KEYWORD);
if ($first && $second && $third
&& $first->value === 'DUPLICATE'
&& $second->value === 'KEY'
&& $third->value === 'UPDATE'
) {
$list->idx = $lastIdx;
break;
}
}
$list->idx = $lastIdx;
/**
* The name of the class that is used for parsing.
*
* @var Component $class
*/
$class = null;
/**
* The name of the field where the result of the parsing is stored.
*
* @var string $field
*/
$field = null;
/**
* Parser's options.
*
* @var array $options
*/
$options = array();
// Looking for duplicated clauses.
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
);
break;
}
$parsedClauses[$token->value] = true;
}
// Checking if this is the beginning of a clause.
if (!empty(Parser::$KEYWORD_PARSERS[$token->value])) {
$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->value])) {
if ((!empty(static::$CLAUSES)) // Undefined for some statements.
&& (empty(static::$CLAUSES[$token->value]))
) {
// Some keywords (e.g. `SET`) may be the beginning of a
// statement and a clause.
// If such keyword was found and it cannot be a clause of
// this statement it means it is a new statement, but no
// delimiter was found between them.
$parser->error(
__('A new statement was found, but no delimiter between it and the previous one.'),
$token
);
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
);
$parsedOptions = true;
}
} elseif ($class === null) {
// Handle special end options in Select statement
// See Statements\SelectStatement::$END_OPTIONS
if (get_class($this) === 'SqlParser\Statements\SelectStatement'
&& ($token->value === 'FOR UPDATE'
|| $token->value === 'LOCK IN SHARE MODE')
) {
$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.
$parser->error(__('Unrecognized keyword.'), $token);
continue;
}
}
$this->before($parser, $list, $token);
// Parsing this keyword.
if ($class !== null) {
++$list->idx; // Skipping keyword or last option.
$this->$field = $class::parse($parser, $list, $options);
}
$this->after($parser, $list, $token);
}
// This may be corrected by the parser.
$this->last = --$list->idx; // Go back to last used token.
}
/**
* Function called before the token is processed.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function before(Parser $parser, TokensList $list, Token $token)
{
}
/**
* Function called after the token was processed.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function after(Parser $parser, TokensList $list, Token $token)
{
}
/**
* Gets the clauses of this statement.
*
* @return array
*/
public function getClauses()
{
return static::$CLAUSES;
}
/**
* Builds the string representation of this statement.
*
* @see static::build
*
* @return string
*/
public function __toString()
{
return $this->build();
}
/**
* Validates the order of the clauses in parsed statement
* Ideally this should be called after successfully
* completing the parsing of each statement
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return boolean
*/
public function validateClauseOrder($parser, $list)
{
$clauses = array_flip(array_keys($this->getClauses()));
if (empty($clauses)
|| count($clauses) == 0
) {
return true;
}
$minIdx = -1;
/**
* For tracking JOIN clauses in a query
* 0 - JOIN not found till now
* 1 - JOIN has been found
* 2 - A Non-JOIN clause has been found
* after a previously found JOIN clause
*
* @var int $joinStart
*/
$joinStart = 0;
$error = 0;
foreach ($clauses as $clauseType => $index) {
$clauseStartIdx = Utils\Query::getClauseStartOffset(
$this,
$list,
$clauseType
);
// Handle ordering of Multiple Joins in a query
if ($clauseStartIdx != -1) {
if ($joinStart == 0 && stripos($clauseType, 'JOIN')) {
$joinStart = 1;
} elseif ($joinStart == 1 && ! stripos($clauseType, 'JOIN')) {
$joinStart = 2;
} elseif ($joinStart == 2 && stripos($clauseType, 'JOIN')) {
$error = 1;
}
}
if ($clauseStartIdx != -1 && $clauseStartIdx < $minIdx) {
if ($joinStart == 0 || ($joinStart == 2 && $error = 1)) {
$token = $list->tokens[$clauseStartIdx];
$parser->error(
__('Unexpected ordering of clauses.'),
$token
);
return false;
} else {
$minIdx = $clauseStartIdx;
}
} elseif ($clauseStartIdx != -1) {
$minIdx = $clauseStartIdx;
}
}
return true;
}
}

View File

@ -0,0 +1,156 @@
<?php
/**
* `ALTER` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\AlterOperation;
use SqlParser\Components\Expression;
use SqlParser\Components\OptionsArray;
/**
* `ALTER` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class AlterStatement extends Statement
{
/**
* Table affected.
*
* @var Expression
*/
public $table;
/**
* Column affected by this statement.
*
* @var AlterOperation[]
*/
public $altered = array();
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'ONLINE' => 1,
'OFFLINE' => 1,
'IGNORE' => 2,
'DATABASE' => 3,
'EVENT' => 3,
'FUNCTION' => 3,
'PROCEDURE' => 3,
'SERVER' => 3,
'TABLE' => 3,
'TABLESPACE' => 3,
'VIEW' => 3,
);
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `ALTER`.
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
++$list->idx;
// Parsing affected table.
$this->table = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
++$list->idx; // Skipping field.
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------[ alter operation ]-----------------> 1
*
* 1 -------------------------[ , ]-----------------------> 0
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$options = array();
if ($this->options->has('DATABASE')) {
$options = AlterOperation::$DB_OPTIONS;
} elseif ($this->options->has('TABLE')) {
$options = AlterOperation::$TABLE_OPTIONS;
} elseif ($this->options->has('VIEW')) {
$options = AlterOperation::$VIEW_OPTIONS;
}
$this->altered[] = AlterOperation::parse($parser, $list, $options);
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$state = 0;
}
}
}
}
/**
* @return string
*/
public function build()
{
$tmp = array();
foreach ($this->altered as $altered) {
$tmp[] = $altered::build($altered);
}
return 'ALTER ' . OptionsArray::build($this->options)
. ' ' . Expression::build($this->table)
. ' ' . implode(', ', $tmp);
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* `ANALYZE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `ANALYZE` statement.
*
* ANALYZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class AnalyzeStatement extends Statement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
);
/**
* Analyzed tables.
*
* @var Expression[]
*/
public $tables;
}

View File

@ -0,0 +1,38 @@
<?php
/**
* `BACKUP` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `BACKUP` statement.
*
* BACKUP TABLE tbl_name [, tbl_name] ... TO '/path/to/backup/directory'
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class BackupStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
'TO' => array(4, 'var'),
);
}

View File

@ -0,0 +1,37 @@
<?php
/**
* `CALL` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\FunctionCall;
/**
* `CALL` statement.
*
* CALL sp_name([parameter[,...]])
*
* or
*
* CALL sp_name[()]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CallStatement extends Statement
{
/**
* The name of the function and its parameters.
*
* @var FunctionCall
*/
public $call;
}

View File

@ -0,0 +1,40 @@
<?php
/**
* `CHECK` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `CHECK` statement.
*
* CHECK TABLE tbl_name [, tbl_name] ... [option] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CheckStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'FOR UPGRADE' => 2,
'QUICK' => 3,
'FAST' => 4,
'MEDIUM' => 5,
'EXTENDED' => 6,
'CHANGED' => 7,
);
}

View File

@ -0,0 +1,36 @@
<?php
/**
* `CHECKSUM` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `CHECKSUM` statement.
*
* CHECKSUM TABLE tbl_name [, tbl_name] ... [ QUICK | EXTENDED ]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ChecksumStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'QUICK' => 2,
'EXTENDED' => 3,
);
}

View File

@ -0,0 +1,638 @@
<?php
/**
* `CREATE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\ArrayObj;
use SqlParser\Components\DataType;
use SqlParser\Components\CreateDefinition;
use SqlParser\Components\PartitionDefinition;
use SqlParser\Components\Expression;
use SqlParser\Components\OptionsArray;
use SqlParser\Components\ParameterDefinition;
use SqlParser\Statements\SelectStatement;
/**
* `CREATE` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CreateStatement extends Statement
{
/**
* Options for `CREATE` statements.
*
* @var array
*/
public static $OPTIONS = array(
// CREATE TABLE
'TEMPORARY' => 1,
// CREATE VIEW
'OR REPLACE' => array(2, 'var='),
'ALGORITHM' => array(3, 'var='),
// `DEFINER` is also used for `CREATE FUNCTION / PROCEDURE`
'DEFINER' => array(4, 'expr='),
'SQL SECURITY' => array(5, 'var'),
'DATABASE' => 6,
'EVENT' => 6,
'FUNCTION' => 6,
'INDEX' => 6,
'UNIQUE INDEX' => 6,
'FULLTEXT INDEX' => 6,
'SPATIAL INDEX' => 6,
'PROCEDURE' => 6,
'SERVER' => 6,
'TABLE' => 6,
'TABLESPACE' => 6,
'TRIGGER' => 6,
'USER' => 6,
'VIEW' => 6,
// CREATE TABLE
'IF NOT EXISTS' => 7,
);
/**
* All database options.
*
* @var array
*/
public static $DB_OPTIONS = array(
'CHARACTER SET' => array(1, 'var='),
'CHARSET' => array(1, 'var='),
'DEFAULT CHARACTER SET' => array(1, 'var='),
'DEFAULT CHARSET' => array(1, 'var='),
'DEFAULT COLLATE' => array(2, 'var='),
'COLLATE' => array(2, 'var='),
);
/**
* All table options.
*
* @var array
*/
public static $TABLE_OPTIONS = array(
'ENGINE' => array(1, 'var='),
'AUTO_INCREMENT' => array(2, 'var='),
'AVG_ROW_LENGTH' => array(3, 'var'),
'CHARACTER SET' => array(4, 'var='),
'CHARSET' => array(4, 'var='),
'DEFAULT CHARACTER SET' => array(4, 'var='),
'DEFAULT CHARSET' => array(4, 'var='),
'CHECKSUM' => array(5, 'var'),
'DEFAULT COLLATE' => array(6, 'var='),
'COLLATE' => array(6, 'var='),
'COMMENT' => array(7, 'var='),
'CONNECTION' => array(8, 'var'),
'DATA DIRECTORY' => array(9, 'var'),
'DELAY_KEY_WRITE' => array(10, 'var'),
'INDEX DIRECTORY' => array(11, 'var'),
'INSERT_METHOD' => array(12, 'var'),
'KEY_BLOCK_SIZE' => array(13, 'var'),
'MAX_ROWS' => array(14, 'var'),
'MIN_ROWS' => array(15, 'var'),
'PACK_KEYS' => array(16, 'var'),
'PASSWORD' => array(17, 'var'),
'ROW_FORMAT' => array(18, 'var'),
'TABLESPACE' => array(19, 'var'),
'STORAGE' => array(20, 'var'),
'UNION' => array(21, 'var'),
);
/**
* All function options.
*
* @var array
*/
public static $FUNC_OPTIONS = array(
'COMMENT' => array(1, 'var='),
'LANGUAGE SQL' => 2,
'DETERMINISTIC' => 3,
'NOT DETERMINISTIC' => 3,
'CONTAINS SQL' => 4,
'NO SQL' => 4,
'READS SQL DATA' => 4,
'MODIFIES SQL DATA' => 4,
'SQL SECURITY DEFINER' => array(5, 'var'),
);
/**
* All trigger options.
*
* @var array
*/
public static $TRIGGER_OPTIONS = array(
'BEFORE' => 1,
'AFTER' => 1,
'INSERT' => 2,
'UPDATE' => 2,
'DELETE' => 2,
);
/**
* The name of the entity that is created.
*
* Used by all `CREATE` statements.
*
* @var Expression
*/
public $name;
/**
* The options of the entity (table, procedure, function, etc.).
*
* Used by `CREATE TABLE`, `CREATE FUNCTION` and `CREATE PROCEDURE`.
*
* @var OptionsArray
*
* @see static::$TABLE_OPTIONS
* @see static::$FUNC_OPTIONS
* @see static::$TRIGGER_OPTIONS
*/
public $entityOptions;
/**
* If `CREATE TABLE`, a list of columns and keys.
* If `CREATE VIEW`, a list of columns.
*
* Used by `CREATE TABLE` and `CREATE VIEW`.
*
* @var CreateDefinition[]|ArrayObj
*/
public $fields;
/**
* If `CREATE TABLE ... SELECT`
*
* Used by `CREATE TABLE`
*
* @var SelectStatement
*/
public $select;
/**
* If `CREATE TABLE ... LIKE`
*
* Used by `CREATE TABLE`
*
* @var Expression
*/
public $like;
/**
* Expression used for partitioning.
*
* @var string
*/
public $partitionBy;
/**
* The number of partitions.
*
* @var int
*/
public $partitionsNum;
/**
* Expression used for subpartitioning.
*
* @var string
*/
public $subpartitionBy;
/**
* The number of subpartitions.
*
* @var int
*/
public $subpartitionsNum;
/**
* The partition of the new table.
*
* @var PartitionDefinition[]
*/
public $partitions;
/**
* If `CREATE TRIGGER` the name of the table.
*
* Used by `CREATE TRIGGER`.
*
* @var Expression
*/
public $table;
/**
* The return data type of this routine.
*
* Used by `CREATE FUNCTION`.
*
* @var DataType
*/
public $return;
/**
* The parameters of this routine.
*
* Used by `CREATE FUNCTION` and `CREATE PROCEDURE`.
*
* @var ParameterDefinition[]
*/
public $parameters;
/**
* The body of this function or procedure. For views, it is the select
* statement that gets the
*
* Used by `CREATE FUNCTION`, `CREATE PROCEDURE` and `CREATE VIEW`.
*
* @var Token[]|string
*/
public $body = array();
/**
* @return string
*/
public function build()
{
$fields = '';
if (!empty($this->fields)) {
if (is_array($this->fields)) {
$fields = CreateDefinition::build($this->fields) . ' ';
} elseif ($this->fields instanceof ArrayObj) {
$fields = ArrayObj::build($this->fields);
}
}
if ($this->options->has('DATABASE')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. OptionsArray::build($this->entityOptions);
} elseif ($this->options->has('TABLE') && !is_null($this->select)) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $this->select->build();
} elseif ($this->options->has('TABLE') && !is_null($this->like)) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' LIKE '
. Expression::build($this->like);
} elseif ($this->options->has('TABLE')) {
$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 ' . TokensList::build($this->body) . ' '
. OptionsArray::build($this->entityOptions);
} elseif ($this->options->has('TRIGGER')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. 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'))
) {
$tmp = '';
if ($this->options->has('FUNCTION')) {
$tmp = 'RETURNS ' . DataType::build($this->return);
}
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. ParameterDefinition::build($this->parameters) . ' '
. $tmp . ' ' . TokensList::build($this->body);
}
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. TokensList::build($this->body);
}
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `CREATE`.
// Parsing options.
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
++$list->idx; // Skipping last option.
// Parsing the field name.
$this->name = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
if ((!isset($this->name)) || ($this->name === '')) {
$parser->error(
__('The name of the entity was expected.'),
$list->tokens[$list->idx]
);
} else {
++$list->idx; // Skipping field.
}
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
$nextidx = $list->idx + 1;
while ($nextidx < $list->count && $list->tokens[$nextidx]->type == Token::TYPE_WHITESPACE) {
$nextidx++;
}
if ($this->options->has('DATABASE')) {
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$DB_OPTIONS
);
} elseif ($this->options->has('TABLE')
&& ($token->type == Token::TYPE_KEYWORD)
&& ($token->value == 'SELECT')
) {
/* CREATE TABLE ... SELECT */
$this->select = new SelectStatement($parser, $list);
} elseif ($this->options->has('TABLE')
&& ($token->type == Token::TYPE_KEYWORD) && ($token->value == 'AS')
&& ($list->tokens[$nextidx]->type == Token::TYPE_KEYWORD)
&& ($list->tokens[$nextidx]->value == 'SELECT')
) {
/* CREATE TABLE ... AS SELECT */
$list->idx = $nextidx;
$this->select = new SelectStatement($parser, $list);
} elseif ($this->options->has('TABLE')
&& $token->type == Token::TYPE_KEYWORD
&& $token->value == 'LIKE'
) {
/* CREATE TABLE `new_tbl` LIKE 'orig_tbl' */
$list->idx = $nextidx;
$this->like = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'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]
);
}
} elseif ($this->options->has('TABLE')) {
$this->fields = CreateDefinition::parse($parser, $list);
if (empty($this->fields)) {
$parser->error(
__('At least one column definition was expected.'),
$list->tokens[$list->idx]
);
}
++$list->idx;
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$TABLE_OPTIONS
);
/**
* The field that is being filled (`partitionBy` or
* `subpartitionBy`).
*
* @var string $field
*/
$field = null;
/**
* The number of brackets. `false` means no bracket was found
* previously. At least one bracket is required to validate the
* expression.
*
* @var int|bool $brackets
*/
$brackets = false;
/*
* Handles partitions.
*/
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'PARTITION BY')) {
$field = 'partitionBy';
$brackets = false;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'SUBPARTITION BY')) {
$field = 'subpartitionBy';
$brackets = false;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'PARTITIONS')) {
$token = $list->getNextOfType(Token::TYPE_NUMBER);
--$list->idx; // `getNextOfType` also advances one position.
$this->partitionsNum = $token->value;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'SUBPARTITIONS')) {
$token = $list->getNextOfType(Token::TYPE_NUMBER);
--$list->idx; // `getNextOfType` also advances one position.
$this->subpartitionsNum = $token->value;
} elseif (!empty($field)) {
/*
* Handling the content of `PARTITION BY` and `SUBPARTITION BY`.
*/
// Counting brackets.
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
// This is used instead of `++$brackets` because,
// initially, `$brackets` is `false` cannot be
// incremented.
$brackets = $brackets + 1;
} elseif (($token->type === Token::TYPE_OPERATOR) && ($token->value === ')')) {
--$brackets;
}
// Building the expression used for partitioning.
$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
// that no bracket was found and at least one must is
// required.
if ($brackets === 0) {
$this->$field = trim($this->$field);
$field = null;
}
} elseif (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
if (!empty($this->partitionBy)) {
$this->partitions = ArrayObj::parse(
$parser,
$list,
array(
'type' => 'SqlParser\\Components\\PartitionDefinition'
)
);
}
break;
}
}
} elseif (($this->options->has('PROCEDURE'))
|| ($this->options->has('FUNCTION'))
) {
$this->parameters = ParameterDefinition::parse($parser, $list);
if ($this->options->has('FUNCTION')) {
$token = $list->getNextOfType(Token::TYPE_KEYWORD);
if ($token->value !== 'RETURNS') {
$parser->error(
__('A "RETURNS" keyword was expected.'),
$token
);
} else {
++$list->idx;
$this->return = DataType::parse(
$parser,
$list
);
}
}
++$list->idx;
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$FUNC_OPTIONS
);
++$list->idx;
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
$this->body[] = $token;
}
} elseif ($this->options->has('VIEW')) {
$token = $list->getNext(); // Skipping whitespaces and comments.
// Parsing columns list.
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
--$list->idx; // getNext() also goes forward one field.
$this->fields = ArrayObj::parse($parser, $list);
++$list->idx; // Skipping last token from the array.
$list->getNext();
}
// Parsing the `AS` keyword.
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
);
++$list->idx;
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'ON');
++$list->idx; // Skipping `ON`.
// Parsing the name of the table.
$this->table = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
++$list->idx;
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'FOR EACH ROW');
++$list->idx; // Skipping `FOR EACH ROW`.
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
$this->body[] = $token;
}
} else {
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
$this->body[] = $token;
}
}
}
}

View File

@ -0,0 +1,349 @@
<?php
/**
* `DELETE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\ArrayObj;
use SqlParser\Components\Expression;
use SqlParser\Components\ExpressionArray;
use SqlParser\Components\Limit;
use SqlParser\Components\OrderKeyword;
use SqlParser\Components\Condition;
use SqlParser\Components\OptionsArray;
/**
* `DELETE` statement.
*
* DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
* [PARTITION (partition_name,...)]
* [WHERE where_condition]
* [ORDER BY ...]
* [LIMIT row_count]
*
* Multi-table syntax
*
* DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
* tbl_name[.*] [, tbl_name[.*]] ...
* FROM table_references
* [WHERE where_condition]
*
* OR
*
* DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
* FROM tbl_name[.*] [, tbl_name[.*]] ...
* USING table_references
* [WHERE where_condition]
*
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class DeleteStatement extends Statement
{
/**
* Options for `DELETE` statements.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'QUICK' => 2,
'IGNORE' => 3,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'DELETE' => array('DELETE', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
'FROM' => array('FROM', 3),
'PARTITION' => array('PARTITION', 3),
'USING' => array('USING', 3),
'WHERE' => array('WHERE', 3),
'ORDER BY' => array('ORDER BY', 3),
'LIMIT' => array('LIMIT', 3),
);
/**
* Table(s) used as sources for this statement.
*
* @var Expression[]
*/
public $from;
/**
* Tables used as sources for this statement
*
* @var Expression[]
*/
public $using;
/**
* Columns used in this statement
*
* @var Expression[]
*/
public $columns;
/**
* Partitions used as source for this statement.
*
* @var ArrayObj
*/
public $partition;
/**
* Conditions used for filtering each row of the result set.
*
* @var Condition[]
*/
public $where;
/**
* Specifies the order of the rows in the result set.
*
* @var OrderKeyword[]
*/
public $order;
/**
* Conditions used for limiting the size of the result set.
*
* @var Limit
*/
public $limit;
/**
* @return string
*/
public function build()
{
$ret = 'DELETE ' . OptionsArray::build($this->options);
if ($this->columns != NULL && count($this->columns) > 0) {
$ret .= ' ' . ExpressionArray::build($this->columns);
}
if ($this->from != NULL && count($this->from) > 0) {
$ret .= ' FROM ' . ExpressionArray::build($this->from);
}
if ($this->using != NULL && count($this->using) > 0) {
$ret .= ' USING ' . ExpressionArray::build($this->using);
}
if ($this->where != NULL && count($this->where) > 0) {
$ret .= ' WHERE ' . Condition::build($this->where);
}
if ($this->order != NULL && count($this->order) > 0) {
$ret .= ' ORDER BY ' . ExpressionArray::build($this->order);
}
if ($this->limit != NULL && count($this->limit) > 0) {
$ret .= ' LIMIT ' . Limit::build($this->limit);
}
return $ret;
}
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `DELETE`.
// 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 ---------------------------------[ FROM ]----------------------------------> 2
* 0 ------------------------------[ table[.*] ]--------------------------------> 1
* 1 ---------------------------------[ FROM ]----------------------------------> 2
* 2 --------------------------------[ USING ]----------------------------------> 3
* 2 --------------------------------[ WHERE ]----------------------------------> 4
* 2 --------------------------------[ ORDER ]----------------------------------> 5
* 2 --------------------------------[ LIMIT ]----------------------------------> 6
*
* @var int $state
*/
$state = 0;
/**
* If the query is multi-table or not
*
* @var bool $multiTable
*/
$multiTable = false;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value !== 'FROM'
) {
$parser->error(__('Unexpected keyword.'), $token);
break;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'FROM'
) {
++$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
&& $token->value !== 'FROM'
) {
$parser->error(__('Unexpected keyword.'), $token);
break;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'FROM'
) {
++$list->idx; // Skip 'FROM'
$this->from = ExpressionArray::parse($parser, $list);
$state = 2;
} else {
$parser->error(__('Unexpected token.'), $token);
break;
}
} elseif ($state === 2) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'USING'
) {
++$list->idx; // Skip 'USING'
$this->using = ExpressionArray::parse($parser, $list);
$state = 3;
$multiTable = true;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'WHERE'
) {
++$list->idx; // Skip 'WHERE'
$this->where = Condition::parse($parser, $list);
$state = 4;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'ORDER BY'
) {
++$list->idx; // Skip 'ORDER BY'
$this->order = OrderKeyword::parse($parser, $list);
$state = 5;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'LIMIT'
) {
++$list->idx; // Skip 'LIMIT'
$this->limit = Limit::parse($parser, $list);
$state = 6;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
}
} elseif ($state === 3) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'WHERE'
) {
++$list->idx; // Skip 'WHERE'
$this->where = Condition::parse($parser, $list);
$state = 4;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
} else {
$parser->error(__('Unexpected token.'), $token);
break;
}
} 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
);
break;
}
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'ORDER BY'
) {
++$list->idx; // Skip 'ORDER BY'
$this->order = OrderKeyword::parse($parser, $list);
$state = 5;
} elseif ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'LIMIT'
) {
++$list->idx; // Skip 'LIMIT'
$this->limit = Limit::parse($parser, $list);
$state = 6;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
}
} elseif ($state === 5) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value === 'LIMIT'
) {
++$list->idx; // Skip 'LIMIT'
$this->limit = Limit::parse($parser, $list);
$state = 6;
} elseif ($token->type === Token::TYPE_KEYWORD) {
$parser->error(__('Unexpected keyword.'), $token);
break;
}
}
}
if ($state >= 2) {
foreach ($this->from as $from_expr) {
$from_expr->database = $from_expr->table;
$from_expr->table = $from_expr->column;
$from_expr->column = null;
}
}
--$list->idx;
}
}

View File

@ -0,0 +1,78 @@
<?php
/**
* `DROP` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `DROP` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class DropStatement extends Statement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'DATABASE' => 1,
'EVENT' => 1,
'FUNCTION' => 1,
'INDEX' => 1,
'LOGFILE' => 1,
'PROCEDURE' => 1,
'SCHEMA' => 1,
'SERVER' => 1,
'TABLE' => 1,
'VIEW' => 1,
'TABLESPACE' => 1,
'TRIGGER' => 1,
'TEMPORARY' => 2,
'IF EXISTS' => 3,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'DROP' => array('DROP', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
// Used for select expressions.
'DROP_' => array('DROP', 1),
'ON' => array('ON', 3),
);
/**
* Dropped elements.
*
* @var Expression[]
*/
public $fields;
/**
* Table of the dropped index.
*
* @var Expression
*/
public $table;
}

View File

@ -0,0 +1,22 @@
<?php
/**
* `EXPLAIN` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `EXPLAIN` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ExplainStatement extends NotImplementedStatement
{
}

View File

@ -0,0 +1,272 @@
<?php
/**
* `INSERT` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Statement;
use SqlParser\Statements\SelectStatement;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\Array2d;
use SqlParser\Components\OptionsArray;
use SqlParser\Components\SetOperation;
/**
* `INSERT` statement.
*
* INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
* [INTO] tbl_name
* [PARTITION (partition_name,...)]
* [(col_name,...)]
* {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
* [ ON DUPLICATE KEY UPDATE
* col_name=expr
* [, col_name=expr] ... ]
*
* or
*
* INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
* [INTO] tbl_name
* [PARTITION (partition_name,...)]
* SET col_name={expr | DEFAULT}, ...
* [ ON DUPLICATE KEY UPDATE
* col_name=expr
* [, col_name=expr] ... ]
*
* or
*
* INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
* [INTO] tbl_name
* [PARTITION (partition_name,...)]
* [(col_name,...)]
* SELECT ...
* [ ON DUPLICATE KEY UPDATE
* col_name=expr
* [, col_name=expr] ... ]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class InsertStatement extends Statement
{
/**
* Options for `INSERT` statements.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'DELAYED' => 2,
'HIGH_PRIORITY' => 3,
'IGNORE' => 4,
);
/**
* Tables used as target for this statement.
*
* @var IntoKeyword
*/
public $into;
/**
* Values to be inserted.
*
* @var Array2d
*/
public $values;
/**
* If SET clause is present
* holds the SetOperation
*
* @var SetOperation[]
*/
public $set;
/**
* If SELECT clause is present
* holds the SelectStatement
*
* @var SelectStatement
*/
public $select;
/**
* If ON DUPLICATE KEY UPDATE clause is present
* holds the SetOperation
*
* @var SetOperation[]
*/
public $onDuplicateSet;
/**
* @return string
*/
public function build()
{
$ret = 'INSERT ' . $this->options
. ' INTO ' . $this->into;
if ($this->values != NULL && count($this->values) > 0) {
$ret .= ' VALUES ' . Array2d::build($this->values);
} elseif ($this->set != NULL && count($this->set) > 0) {
$ret .= ' SET ' . SetOperation::build($this->set);
} elseif ($this->select != NULL && count($this->select) > 0) {
$ret .= ' ' . $this->select->build();
}
if ($this->onDuplicateSet != NULL && count($this->onDuplicateSet) > 0) {
$ret .= ' ON DUPLICATE KEY UPDATE ' . SetOperation::build($this->onDuplicateSet);
}
return $ret;
}
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `INSERT`.
// 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 ---------------------------------[ INTO ]----------------------------------> 1
*
* 1 -------------------------[ VALUES/VALUE/SET/SELECT ]-----------------------> 2
*
* 2 -------------------------[ ON DUPLICATE KEY UPDATE ]-----------------------> 3
*
* @var int $state
*/
$state = 0;
/**
* For keeping track of semi-states on encountering
* ON DUPLICATE KEY UPDATE ...
*
*/
$miniState = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value !== 'INTO'
) {
$parser->error(__('Unexpected keyword.'), $token);
break;
} else {
++$list->idx;
$this->into = IntoKeyword::parse(
$parser,
$list,
array('fromInsert' => true)
);
}
$state = 1;
} elseif ($state === 1) {
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->value === 'VALUE'
|| $token->value === 'VALUES'
) {
++$list->idx; // skip VALUES
$this->values = Array2d::parse($parser, $list);
} elseif ($token->value === 'SET') {
++$list->idx; // skip SET
$this->set = SetOperation::parse($parser, $list);
} elseif ($token->value === 'SELECT') {
$this->select = new SelectStatement($parser, $list);
} else {
$parser->error(
__('Unexpected keyword.'),
$token
);
break;
}
$state = 2;
$miniState = 1;
} else {
$parser->error(
__('Unexpected token.'),
$token
);
break;
}
} elseif ($state == 2) {
$lastCount = $miniState;
if ($miniState === 1 && $token->value === 'ON') {
$miniState++;
} elseif ($miniState === 2 && $token->value === 'DUPLICATE') {
$miniState++;
} elseif ($miniState === 3 && $token->value === 'KEY') {
$miniState++;
} elseif ($miniState === 4 && $token->value === 'UPDATE') {
$miniState++;
}
if ($lastCount === $miniState) {
$parser->error(
__('Unexpected token.'),
$token
);
break;
}
if ($miniState === 5) {
++$list->idx;
$this->onDuplicateSet = SetOperation::parse($parser, $list);
$state = 3;
}
}
}
--$list->idx;
}
}

View File

@ -0,0 +1,67 @@
<?php
/**
* Maintenance statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\Expression;
use SqlParser\Components\OptionsArray;
/**
* Maintenance statement.
*
* They follow the syntax:
* STMT [some options] tbl_name [, tbl_name] ... [some more options]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class MaintenanceStatement extends Statement
{
/**
* Tables maintained.
*
* @var Expression[]
*/
public $tables;
/**
* Function called after the token was processed.
*
* Parses the additional options from the end.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function after(Parser $parser, TokensList $list, Token $token)
{
// [some options] is going to be parsed first.
//
// There is a parser specified in `Parser::$KEYWORD_PARSERS`
// which parses the name of the tables.
//
// Finally, we parse here [some more options] and that's all.
++$list->idx;
$this->options->merge(
OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
)
);
}
}

View File

@ -0,0 +1,67 @@
<?php
/**
* Not implemented (yet) statements.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Not implemented (yet) statements.
*
* The `after` function makes the parser jump straight to the first delimiter.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class NotImplementedStatement extends Statement
{
/**
* The part of the statement that can't be parsed.
*
* @var Token[]
*/
public $unknown = array();
/**
* @return string
*/
public function build()
{
// Building the parsed part of the query (if any).
$query = parent::build() . ' ';
// Rebuilding the unknown part from tokens.
foreach ($this->unknown as $token) {
$query .= $token->token;
}
return $query;
}
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
for (; $list->idx < $list->count; ++$list->idx) {
if ($list->tokens[$list->idx]->type === Token::TYPE_DELIMITER) {
break;
}
$this->unknown[] = $list->tokens[$list->idx];
}
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* `OPTIMIZE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `OPTIMIZE` statement.
*
* OPTIMIZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class OptimizeStatement extends Statement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
);
/**
* Optimized tables.
*
* @var Expression[]
*/
public $tables;
}

View File

@ -0,0 +1,56 @@
<?php
/**
* `RENAME` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\RenameOperation;
/**
* `RENAME` statement.
*
* RENAME TABLE tbl_name TO new_tbl_name
* [, tbl_name2 TO new_tbl_name2] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RenameStatement extends Statement
{
/**
* The old and new names of the tables.
*
* @var RenameOperation[]
*/
public $renames;
/**
* Function called before the token is processed.
*
* Skips the `TABLE` keyword after `RENAME`.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function before(Parser $parser, TokensList $list, Token $token)
{
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'RENAME')) {
// Checking if it is the beginning of the query.
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'TABLE');
}
}
}

View File

@ -0,0 +1,42 @@
<?php
/**
* `REPAIR` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `REPAIR` statement.
*
* REPAIR [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
* [QUICK] [EXTENDED] [USE_FRM]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RepairStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
'QUICK' => 4,
'EXTENDED' => 5,
'USE_FRM' => 6,
);
}

View File

@ -0,0 +1,211 @@
<?php
/**
* `REPLACE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Statement;
use SqlParser\Statements\SelectStatement;
use SqlParser\Components\Array2d;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\OptionsArray;
use SqlParser\Components\SetOperation;
/**
* `REPLACE` statement.
*
* REPLACE [LOW_PRIORITY | DELAYED]
* [INTO] tbl_name [(col_name,...)]
* {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
*
* or
*
* REPLACE [LOW_PRIORITY | DELAYED]
* [INTO] tbl_name
* SET col_name={expr | DEFAULT}, ...
*
* or
*
* REPLACE [LOW_PRIORITY | DELAYED]
* [INTO] tbl_name
* [PARTITION (partition_name,...)]
* [(col_name,...)]
* SELECT ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ReplaceStatement extends Statement
{
/**
* Options for `REPLACE` statements and their slot ID.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'DELAYED' => 1,
);
/**
* Tables used as target for this statement.
*
* @var IntoKeyword
*/
public $into;
/**
* Values to be replaced.
*
* @var Array2d
*/
public $values;
/**
* If SET clause is present
* holds the SetOperation
*
* @var SetOperation[]
*/
public $set;
/**
* If SELECT clause is present
* holds the SelectStatement
*
* @var SelectStatement
*/
public $select;
/**
* @return string
*/
public function build()
{
$ret = 'REPLACE ' . $this->options
. ' INTO ' . $this->into;
if ($this->values != NULL && count($this->values) > 0) {
$ret .= ' VALUES ' . Array2d::build($this->values);
} elseif ($this->set != NULL && count($this->set) > 0) {
$ret .= ' SET ' . SetOperation::build($this->set);
} elseif ($this->select != NULL && count($this->select) > 0) {
$ret .= ' ' . $this->select->build();
}
return $ret;
}
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `REPLACE`.
// parse any options if provided
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
++$list->idx;
$token = $list->tokens[$list->idx];
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------------------[ INTO ]----------------------------------> 1
*
* 1 -------------------------[ VALUES/VALUE/SET/SELECT ]-----------------------> 2
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
if ($token->type === Token::TYPE_KEYWORD
&& $token->value !== 'INTO'
) {
$parser->error(__('Unexpected keyword.'), $token);
break;
} else {
++$list->idx;
$this->into = IntoKeyword::parse(
$parser,
$list,
array('fromReplace' => true)
);
}
$state = 1;
} elseif ($state === 1) {
if ($token->type === Token::TYPE_KEYWORD) {
if ($token->value === 'VALUE'
|| $token->value === 'VALUES'
) {
++$list->idx; // skip VALUES
$this->values = Array2d::parse($parser, $list);
} elseif ($token->value === 'SET') {
++$list->idx; // skip SET
$this->set = SetOperation::parse($parser, $list);
} elseif ($token->value === 'SELECT') {
$this->select = new SelectStatement($parser, $list);
} else {
$parser->error(
__('Unexpected keyword.'),
$token
);
break;
}
$state = 2;
} else {
$parser->error(
__('Unexpected token.'),
$token
);
break;
}
}
}
--$list->idx;
}
}

View File

@ -0,0 +1,35 @@
<?php
/**
* `RESTORE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `RESTORE` statement.
*
* RESTORE TABLE tbl_name [, tbl_name] ... FROM '/path/to/backup/directory'
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class RestoreStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'FROM' => array(2, 'var'),
);
}

View File

@ -0,0 +1,238 @@
<?php
/**
* `SELECT` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\ArrayObj;
use SqlParser\Components\FunctionCall;
use SqlParser\Components\Expression;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\JoinKeyword;
use SqlParser\Components\Limit;
use SqlParser\Components\OrderKeyword;
use SqlParser\Components\Condition;
/**
* `SELECT` statement.
*
* SELECT
* [ALL | DISTINCT | DISTINCTROW ]
* [HIGH_PRIORITY]
* [MAX_STATEMENT_TIME = N]
* [STRAIGHT_JOIN]
* [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
* [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
* select_expr [, select_expr ...]
* [FROM table_references
* [PARTITION partition_list]
* [WHERE where_condition]
* [GROUP BY {col_name | expr | position}
* [ASC | DESC], ... [WITH ROLLUP]]
* [HAVING where_condition]
* [ORDER BY {col_name | expr | position}
* [ASC | DESC], ...]
* [LIMIT {[offset,] row_count | row_count OFFSET offset}]
* [PROCEDURE procedure_name(argument_list)]
* [INTO OUTFILE 'file_name'
* [CHARACTER SET charset_name]
* export_options
* | INTO DUMPFILE 'file_name'
* | INTO var_name [, var_name]]
* [FOR UPDATE | LOCK IN SHARE MODE]]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class SelectStatement extends Statement
{
/**
* Options for `SELECT` statements and their slot ID.
*
* @var array
*/
public static $OPTIONS = array(
'ALL' => 1,
'DISTINCT' => 1,
'DISTINCTROW' => 1,
'HIGH_PRIORITY' => 2,
'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,
);
public static $END_OPTIONS = array(
'FOR UPDATE' => 1,
'LOCK IN SHARE MODE' => 1
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'SELECT' => array('SELECT', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
// Used for selected expressions.
'_SELECT' => array('SELECT', 1),
'INTO' => array('INTO', 3),
'FROM' => array('FROM', 3),
'PARTITION' => array('PARTITION', 3),
'JOIN' => array('JOIN', 1),
'FULL JOIN' => array('FULL JOIN', 1),
'INNER JOIN' => array('INNER JOIN', 1),
'LEFT JOIN' => array('LEFT JOIN', 1),
'LEFT OUTER JOIN' => array('LEFT OUTER JOIN', 1),
'RIGHT JOIN' => array('RIGHT JOIN', 1),
'RIGHT OUTER JOIN' => array('RIGHT OUTER JOIN', 1),
'NATURAL JOIN' => array('NATURAL JOIN', 1),
'NATURAL LEFT JOIN' => array('NATURAL LEFT JOIN', 1),
'NATURAL RIGHT JOIN' => array('NATURAL RIGHT JOIN', 1),
'NATURAL LEFT OUTER JOIN' => array('NATURAL LEFT OUTER JOIN', 1),
'NATURAL RIGHT OUTER JOIN' => array('NATURAL RIGHT JOIN', 1),
'WHERE' => array('WHERE', 3),
'GROUP BY' => array('GROUP BY', 3),
'HAVING' => array('HAVING', 3),
'ORDER BY' => array('ORDER BY', 3),
'LIMIT' => array('LIMIT', 3),
'PROCEDURE' => array('PROCEDURE', 3),
'UNION' => array('UNION', 1),
'_END_OPTIONS' => array('_END_OPTIONS', 1)
// These are available only when `UNION` is present.
// 'ORDER BY' => array('ORDER BY', 3),
// 'LIMIT' => array('LIMIT', 3),
);
/**
* Expressions that are being selected by this statement.
*
* @var Expression[]
*/
public $expr = array();
/**
* Tables used as sources for this statement.
*
* @var Expression[]
*/
public $from = array();
/**
* Partitions used as source for this statement.
*
* @var ArrayObj
*/
public $partition;
/**
* Conditions used for filtering each row of the result set.
*
* @var Condition[]
*/
public $where;
/**
* Conditions used for grouping the result set.
*
* @var OrderKeyword[]
*/
public $group;
/**
* Conditions used for filtering the result set.
*
* @var Condition[]
*/
public $having;
/**
* Specifies the order of the rows in the result set.
*
* @var OrderKeyword[]
*/
public $order;
/**
* Conditions used for limiting the size of the result set.
*
* @var Limit
*/
public $limit;
/**
* Procedure that should process the data in the result set.
*
* @var FunctionCall
*/
public $procedure;
/**
* Destination of this result set.
*
* @var IntoKeyword
*/
public $into;
/**
* Joins.
*
* @var JoinKeyword[]
*/
public $join;
/**
* Unions.
*
* @var SelectStatement[]
*/
public $union = array();
/**
* The end options of this query.
*
* @var OptionsArray
*
* @see static::$END_OPTIONS
*/
public $end_options;
/**
* Gets the clauses of this statement.
*
* @return array
*/
public function getClauses()
{
// This is a cheap fix for `SELECT` statements that contain `UNION`.
// The `ORDER BY` and `LIMIT` clauses should be at the end of the
// statement.
if (!empty($this->union)) {
$clauses = static::$CLAUSES;
unset($clauses['ORDER BY']);
unset($clauses['LIMIT']);
$clauses['ORDER BY'] = array('ORDER BY', 3);
$clauses['LIMIT'] = array('LIMIT', 3);
return $clauses;
}
return static::$CLAUSES;
}
}

View File

@ -0,0 +1,71 @@
<?php
/**
* `SET` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\SetOperation;
use SqlParser\Components\OptionsArray;
/**
* `SET` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class SetStatement extends Statement
{
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'SET' => array('SET', 3),
);
/**
* Possible exceptions in SET statment
*
* @var array
*/
public static $OPTIONS = array(
'CHARSET' => array(3, 'var'),
'CHARACTER SET' => array(3, 'var'),
'NAMES' => array(3, 'var'),
'PASSWORD' => array(3, 'expr'),
);
/**
* Options used in current statement
*
* @var OptionsArray[]
*/
public $options;
/**
* The updated values.
*
* @var SetOperation[]
*/
public $set;
/**
* @return string
*/
public function build()
{
return 'SET ' . OptionsArray::build($this->options)
. ' ' . SetOperation::build($this->set);
}
}

View File

@ -0,0 +1,70 @@
<?php
/**
* `SHOW` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `SHOW` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class ShowStatement extends NotImplementedStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'CREATE' => 1,
'AUTHORS' => 2,
'BINARY' => 2,
'BINLOG' => 2,
'CHARACTER' => 2,
'CODE' => 2,
'COLLATION' => 2,
'COLUMNS' => 2,
'CONTRIBUTORS' => 2,
'DATABASE' => 2,
'DATABASES' => 2,
'ENGINE' => 2,
'ENGINES' => 2,
'ERRORS' => 2,
'EVENT' => 2,
'EVENTS' => 2,
'FUNCTION' => 2,
'GRANTS' => 2,
'HOSTS' => 2,
'INDEX' => 2,
'INNODB' => 2,
'LOGS' => 2,
'MASTER' => 2,
'OPEN' => 2,
'PLUGINS' => 2,
'PRIVILEGES' => 2,
'PROCEDURE' => 2,
'PROCESSLIST' => 2,
'PROFILE' => 2,
'PROFILES' => 2,
'SCHEDULER' => 2,
'SET' => 2,
'SLAVE' => 2,
'STATUS' => 2,
'TABLE' => 2,
'TABLES' => 2,
'TRIGGER' => 2,
'TRIGGERS' => 2,
'VARIABLES' => 2,
'VIEW' => 2,
'WARNINGS' => 2,
);
}

View File

@ -0,0 +1,119 @@
<?php
/**
* Transaction statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\TokensList;
use SqlParser\Components\OptionsArray;
/**
* Transaction statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class TransactionStatement extends Statement
{
/**
* START TRANSACTION and BEGIN
*
* @var int
*/
const TYPE_BEGIN = 1;
/**
* COMMIT and ROLLBACK
*
* @var int
*/
const TYPE_END = 2;
/**
* The type of this query.
*
* @var int
*/
public $type;
/**
* The list of statements in this transaction.
*
* @var Statement[]
*/
public $statements;
/**
* The ending transaction statement which may be a `COMMIT` or a `ROLLBACK`.
*
* @var TransactionStatement
*/
public $end;
/**
* Options for this query.
*
* @var array
*/
public static $OPTIONS = array(
'START TRANSACTION' => 1,
'BEGIN' => 1,
'COMMIT' => 1,
'ROLLBACK' => 1,
'WITH CONSISTENT SNAPSHOT' => 2,
'WORK' => 2,
'AND NO CHAIN' => 3,
'AND CHAIN' => 3,
'RELEASE' => 4,
'NO RELEASE' => 4,
);
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
parent::parse($parser, $list);
// Checks the type of this query.
if (($this->options->has('START TRANSACTION'))
|| ($this->options->has('BEGIN'))
) {
$this->type = TransactionStatement::TYPE_BEGIN;
} elseif (($this->options->has('COMMIT'))
|| ($this->options->has('ROLLBACK'))
) {
$this->type = TransactionStatement::TYPE_END;
}
}
/**
* @return string
*/
public function build()
{
$ret = OptionsArray::build($this->options);
if ($this->type === TransactionStatement::TYPE_BEGIN) {
foreach ($this->statements as $statement) {
/**
* @var SelectStatement $statement
*/
$ret .= ';' . $statement->build();
}
$ret .= ';' . $this->end->build();
}
return $ret;
}
}

View File

@ -0,0 +1,40 @@
<?php
/**
* `TRUNCATE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `TRUNCATE` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class TruncateStatement extends Statement
{
/**
* Options for `TRUNCATE` statements.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
);
/**
* The name of the truncated table.
*
* @var Expression
*/
public $table;
}

View File

@ -0,0 +1,104 @@
<?php
/**
* `UPDATE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
use SqlParser\Components\Limit;
use SqlParser\Components\OrderKeyword;
use SqlParser\Components\SetOperation;
use SqlParser\Components\Condition;
/**
* `UPDATE` statement.
*
* UPDATE [LOW_PRIORITY] [IGNORE] table_reference
* SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
* [WHERE where_condition]
* [ORDER BY ...]
* [LIMIT row_count]
*
* or
*
* UPDATE [LOW_PRIORITY] [IGNORE] table_references
* SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
* [WHERE where_condition]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class UpdateStatement extends Statement
{
/**
* Options for `UPDATE` statements and their slot ID.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'IGNORE' => 2,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'UPDATE' => array('UPDATE', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
// Used for updated tables.
'_UPDATE' => array('UPDATE', 1),
'SET' => array('SET', 3),
'WHERE' => array('WHERE', 3),
'ORDER BY' => array('ORDER BY', 3),
'LIMIT' => array('LIMIT', 3),
);
/**
* Tables used as sources for this statement.
*
* @var Expression[]
*/
public $tables;
/**
* The updated values.
*
* @var SetOperation[]
*/
public $set;
/**
* Conditions used for filtering each row of the result set.
*
* @var Condition[]
*/
public $where;
/**
* Specifies the order of the rows in the result set.
*
* @var OrderKeyword[]
*/
public $order;
/**
* Conditions used for limiting the size of the result set.
*
* @var Limit
*/
public $limit;
}

View File

@ -0,0 +1,303 @@
<?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.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* A structure representing a lexeme that explicitly indicates its
* categorization for the purpose of parsing.
*
* @category Tokens
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Token
{
// Types of tokens (a vague description of a token's purpose).
/**
* 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
*/
const TYPE_NONE = 0;
/**
* SQL specific keywords: SELECT, UPDATE, INSERT, etc.
*
* @var int
*/
const TYPE_KEYWORD = 1;
/**
* Any type of legal operator.
*
* Arithmetic operators: +, -, *, /, etc.
* Logical operators: ===, <>, !==, etc.
* Bitwise operators: &, |, ^, etc.
* Assignment operators: =, +=, -=, etc.
* SQL specific operators: . (e.g. .. WHERE database.table ..),
* * (e.g. SELECT * FROM ..)
*
* @var int
*/
const TYPE_OPERATOR = 2;
/**
* Spaces, tabs, new lines, etc.
*
* @var int
*/
const TYPE_WHITESPACE = 3;
/**
* Any type of legal comment.
*
* Bash (#), C (/* *\/) or SQL (--) comments:
*
* -- SQL-comment
*
* #Bash-like comment
*
* /*C-like comment*\/
*
* or:
*
* /*C-like
* comment*\/
*
* Backslashes were added to respect PHP's comments syntax.
*
* @var int
*/
const TYPE_COMMENT = 4;
/**
* Boolean values: true or false.
*
* @var int
*/
const TYPE_BOOL = 5;
/**
* Numbers: 4, 0x8, 15.16, 23e42, etc.
*
* @var int
*/
const TYPE_NUMBER = 6;
/**
* Literal strings: 'string', "test".
* Some of these strings are actually symbols.
*
* @var int
*/
const TYPE_STRING = 7;
/**
* Database, table names, variables, etc.
* For example: ```SELECT `foo`, `bar` FROM `database`.`table`;```
*
* @var int
*/
const TYPE_SYMBOL = 8;
/**
* Delimits an unknown string.
* For example: ```SELECT * FROM test;```, `test` is a delimiter.
*
* @var int
*/
const TYPE_DELIMITER = 9;
/**
* Labels in LOOP statement, ITERATE statement etc.
* For example (only for begin label):
* begin_label: BEGIN [statement_list] END [end_label]
* 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
*/
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.
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.
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.
const FLAG_STRING_SINGLE_QUOTES = 1;
const FLAG_STRING_DOUBLE_QUOTES = 2;
// Comments related flags.
const FLAG_COMMENT_BASH = 1;
const FLAG_COMMENT_C = 2;
const FLAG_COMMENT_SQL = 4;
const FLAG_COMMENT_MYSQL_CMD = 8;
// Operators related flags.
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.
const FLAG_SYMBOL_VARIABLE = 1;
const FLAG_SYMBOL_BACKTICK = 2;
const FLAG_SYMBOL_USER = 4;
const FLAG_SYMBOL_SYSTEM = 8;
/**
* The token it its raw string representation.
*
* @var string
*/
public $token;
/**
* The value this token contains (i.e. token after some evaluation)
*
* @var mixed
*/
public $value;
/**
* The type of this token.
*
* @var int
*/
public $type;
/**
* The flags of this token.
*
* @var int
*/
public $flags;
/**
* The position in the initial string where this token started.
*
* @var int
*/
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.
*/
public function __construct($token, $type = 0, $flags = 0)
{
$this->token = $token;
$this->type = $type;
$this->flags = $flags;
$this->value = $this->extract();
}
/**
* Does little processing to the token to extract a value.
*
* If no processing can be done it will return the initial string.
*
* @return mixed
*/
public function extract()
{
switch ($this->type) {
case Token::TYPE_KEYWORD:
if (!($this->flags & Token::FLAG_KEYWORD_RESERVED)) {
// Unreserved keywords should stay the way they are because they
// might represent field names.
return $this->token;
}
return strtoupper($this->token);
case Token::TYPE_WHITESPACE:
return ' ';
case Token::TYPE_BOOL:
return strtoupper($this->token) === 'TRUE';
case Token::TYPE_NUMBER:
$ret = str_replace('--', '', $this->token); // e.g. ---42 === -42
if ($this->flags & Token::FLAG_NUMBER_HEX) {
if ($this->flags & Token::FLAG_NUMBER_NEGATIVE) {
$ret = str_replace('-', '', $this->token);
sscanf($ret, '%x', $ret);
$ret = -$ret;
} else {
sscanf($ret, '%x', $ret);
}
} elseif (($this->flags & Token::FLAG_NUMBER_APPROXIMATE)
|| ($this->flags & Token::FLAG_NUMBER_FLOAT)
) {
sscanf($ret, '%f', $ret);
} else {
sscanf($ret, '%d', $ret);
}
return $ret;
case Token::TYPE_STRING:
$quote = $this->token[0];
$str = str_replace($quote . $quote, $quote, $this->token);
return mb_substr($str, 1, -1, 'UTF-8'); // trims quotes
case Token::TYPE_SYMBOL:
$str = $this->token;
if ((isset($str[0])) && ($str[0] === '@')) {
// `mb_strlen($str)` must be used instead of `null` because
// in PHP 5.3- the `null` parameter isn't handled correctly.
$str = mb_substr(
$str,
((!empty($str[1])) && ($str[1] === '@')) ? 2 : 1,
mb_strlen($str),
'UTF-8'
);
}
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');
}
return $str;
}
return $this->token;
}
/**
* Converts the token into an inline token by replacing tabs and new lines.
*
* @return string
*/
public function getInlineToken()
{
return str_replace(
array("\r", "\n", "\t"),
array('\r', '\n', '\t'),
$this->token
);
}
}

View File

@ -0,0 +1,207 @@
<?php
/**
* Defines an array of tokens and utility functions to iterate through it.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* A structure representing a list of tokens.
*
* @category Tokens
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class TokensList implements \ArrayAccess
{
/**
* The array of tokens.
*
* @var array
*/
public $tokens = array();
/**
* The count of tokens.
*
* @var int
*/
public $count = 0;
/**
* The index of the next token to be returned.
*
* @var int
*/
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 = array(), $count = -1)
{
if (!empty($tokens)) {
$this->tokens = $tokens;
if ($count === -1) {
$this->count = count($tokens);
}
}
}
/**
* Builds an array of tokens by merging their raw value.
*
* @param string|Token[]|TokensList $list The tokens to be built.
*
* @return string
*/
public static function build($list)
{
if (is_string($list)) {
return $list;
}
if ($list instanceof TokensList) {
$list = $list->tokens;
}
$ret = '';
if (is_array($list)) {
foreach ($list as $tok) {
$ret .= $tok->token;
}
}
return $ret;
}
/**
* Adds a new token.
*
* @param Token $token Token to be added in list.
*
* @return void
*/
public function add(Token $token)
{
$this->tokens[$this->count++] = $token;
}
/**
* Gets the next token. Skips any irrelevant token (whitespaces and
* comments).
*
* @return Token
*/
public function getNext()
{
for (; $this->idx < $this->count; ++$this->idx) {
if (($this->tokens[$this->idx]->type !== Token::TYPE_WHITESPACE)
&& ($this->tokens[$this->idx]->type !== Token::TYPE_COMMENT)
) {
return $this->tokens[$this->idx++];
}
}
return null;
}
/**
* Gets the next token.
*
* @param int $type The type.
*
* @return Token
*/
public function getNextOfType($type)
{
for (; $this->idx < $this->count; ++$this->idx) {
if ($this->tokens[$this->idx]->type === $type) {
return $this->tokens[$this->idx++];
}
}
return null;
}
/**
* Gets the next token.
*
* @param int $type The type of the token.
* @param string $value The value of the token.
*
* @return Token
*/
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)
) {
return $this->tokens[$this->idx++];
}
}
return null;
}
/**
* Sets an value inside the container.
*
* @param int $offset The offset to be set.
* @param Token $value The token to be saved.
*
* @return void
*/
public function offsetSet($offset, $value)
{
if ($offset === null) {
$this->tokens[$this->count++] = $value;
} else {
$this->tokens[$offset] = $value;
}
}
/**
* Gets a value from the container.
*
* @param int $offset The offset to be returned.
*
* @return Token
*/
public function offsetGet($offset)
{
return $offset < $this->count ? $this->tokens[$offset] : null;
}
/**
* Checks if an offset was previously set.
*
* @param int $offset The offset to be checked.
*
* @return bool
*/
public function offsetExists($offset)
{
return $offset < $this->count;
}
/**
* Unsets the value of an offset.
*
* @param int $offset The offset to be unset.
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->tokens[$offset]);
--$this->count;
for ($i = $offset; $i < $this->count; ++$i) {
$this->tokens[$i] = $this->tokens[$i + 1];
}
unset($this->tokens[$this->count]);
}
}

View File

@ -0,0 +1,217 @@
<?php
/**
* Implementation for UTF-8 strings.
*
* The subscript operator in PHP, when used with string will return a byte
* and not a character. Because in UTF-8 strings a character may occupy more
* than one byte, the subscript operator may return an invalid character.
*
* Because the lexer relies on the subscript operator this class had to be
* implemented.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* Implements array-like access for UTF-8 strings.
*
* In this library, this class should be used to parse UTF-8 queries.
*
* @category Misc
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class UtfString implements \ArrayAccess
{
/**
* The raw, multi-byte string.
*
* @var string
*/
public $str = '';
/**
* The index of current byte.
*
* For ASCII strings, the byte index is equal to the character index.
*
* @var int
*/
public $byteIdx = 0;
/**
* The index of current character.
*
* For non-ASCII strings, some characters occupy more than one byte and
* the character index will have a lower value than the byte index.
*
* @var int
*/
public $charIdx = 0;
/**
* The length of the string (in bytes).
*
* @var int
*/
public $byteLen = 0;
/**
* The length of the string (in characters).
*
* @var int
*/
public $charLen = 0;
/**
* Constructor.
*
* @param string $str The string.
*/
public function __construct($str)
{
$this->str = $str;
$this->byteIdx = 0;
$this->charIdx = 0;
// TODO: `strlen($str)` might return a wrong length when function
// overloading is enabled.
// https://php.net/manual/ro/mbstring.overload.php
$this->byteLen = strlen($str);
$this->charLen = mb_strlen($str, 'UTF-8');
}
/**
* Checks if the given offset exists.
*
* @param int $offset The offset to be checked.
*
* @return bool
*/
public function offsetExists($offset)
{
return ($offset >= 0) && ($offset < $this->charLen);
}
/**
* Gets the character at given offset.
*
* @param int $offset The offset to be returned.
*
* @return string
*/
public function offsetGet($offset)
{
if (($offset < 0) || ($offset >= $this->charLen)) {
return null;
}
$delta = $offset - $this->charIdx;
if ($delta > 0) {
// Fast forwarding.
while ($delta-- > 0) {
$this->byteIdx += static::getCharLength($this->str[$this->byteIdx]);
++$this->charIdx;
}
} elseif ($delta < 0) {
// Rewinding.
while ($delta++ < 0) {
do {
$byte = ord($this->str[--$this->byteIdx]);
} while ((128 <= $byte) && ($byte < 192));
--$this->charIdx;
}
}
$bytesCount = static::getCharLength($this->str[$this->byteIdx]);
$ret = '';
for ($i = 0; $bytesCount-- > 0; ++$i) {
$ret .= $this->str[$this->byteIdx + $i];
}
return $ret;
}
/**
* Sets the value of a character.
*
* @param int $offset The offset to be set.
* @param string $value The value to be set.
*
* @throws \Exception Not implemented.
*
* @return void
*/
public function offsetSet($offset, $value)
{
throw new \Exception('Not implemented.');
}
/**
* Unsets an index.
*
* @param int $offset The value to be unset.
*
* @throws \Exception Not implemented.
*
* @return void
*/
public function offsetUnset($offset)
{
throw new \Exception('Not implemented.');
}
/**
* Gets the length of an UTF-8 character.
*
* According to RFC 3629, a UTF-8 character can have at most 4 bytes.
* However, this implementation supports UTF-8 characters containing up to 6
* bytes.
*
* @param string $byte The byte to be analyzed.
*
* @see http://tools.ietf.org/html/rfc3629
*
* @return int
*/
public static function getCharLength($byte)
{
$byte = ord($byte);
if ($byte < 128) {
return 1;
} elseif ($byte < 224) {
return 2;
} elseif ($byte < 240) {
return 3;
} elseif ($byte < 248) {
return 4;
} elseif ($byte < 252) {
return 5; // unofficial
}
return 6; // unofficial
}
/**
* Returns the length in characters of the string.
*
* @return int
*/
public function length()
{
return $this->charLen;
}
/**
* Returns the contained string.
*
* @return string
*/
public function __toString()
{
return $this->str;
}
}

View File

@ -0,0 +1,416 @@
<?php
/**
* Buffered query utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Context;
/**
* 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.
*
* All comments are skipped, with one exception: MySQL commands inside `/*!`.
*
* @category Lexer
* @package SqlParser
* @subpackage Utils
* @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.
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.
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.
*
* This field can be modified just by appending to it!
*
* @var string
*/
public $query = '';
/**
* The options of this parser.
*
* @var array
*/
public $options = array();
/**
* The last delimiter used.
*
* @var string
*/
public $delimiter;
/**
* The length of the delimiter.
*
* @var int
*/
public $delimiterLen;
/**
* The current status of the parser.
*
* @var int
*/
public $status;
/**
* The last incomplete query that was extracted.
*
* @var string
*/
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 = array())
{
// Merges specified options with defaults.
$this->options = array_merge(
array(
/**
* The starting delimiter.
*
* @var string
*/
'delimiter' => ';',
/**
* Whether `DELIMITER` statements should be parsed.
*
* @var bool
*/
'parse_delimiter' => false,
/**
* Whether a delimiter should be added at the end of the
* statement.
*
* @var bool
*/
'add_delimiter' => false,
),
$options
);
$this->query = $query;
$this->setDelimiter($this->options['delimiter']);
}
/**
* Sets the delimiter.
*
* Used to update the length of it too.
*
* @param string $delimiter
*/
public function setDelimiter($delimiter)
{
$this->delimiter = $delimiter;
$this->delimiterLen = strlen($delimiter);
}
/**
* Extracts a statement from the buffer.
*
* @param bool $end Whether the end of the buffer was reached.
*
* @return string
*/
public function extract($end = false)
{
/**
* The last parsed position.
*
* This is statically defined because it is not used outside anywhere
* outside this method and there is probably a (minor) performance
* improvement to it.
*
* @var int
*/
static $i = 0;
if (empty($this->query)) {
return false;
}
/**
* The length of the buffer.
*
* @var int $len
*/
$len = strlen($this->query);
/**
* The last index of the string that is going to be parsed.
*
* There must be a few characters left in the buffer so the parser can
* avoid confusing some symbols that may have multiple meanings.
*
* For example, if the buffer ends in `-` that may be an operator or the
* beginning of a comment.
*
* Another example if the buffer ends in `DELIMITE`. The parser is going
* to require a few more characters because that may be a part of the
* `DELIMITER` keyword or just a column named `DELIMITE`.
*
* Those extra characters are required only if there is more data
* expected (the end of the buffer was not reached).
*
* @var int $loopLen
*/
$loopLen = $end ? $len : $len - 16;
for (; $i < $loopLen; ++$i) {
/**
* Handling backslash.
*
* Even if the next character is a special character that should be
* treated differently, because of the preceding backslash, it will
* be ignored.
*/
if ((($this->status & static::STATUS_COMMENT) == 0) && ($this->query[$i] === '\\')) {
$this->current .= $this->query[$i] . $this->query[++$i];
continue;
}
/*
* Handling special parses statuses.
*/
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 === 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 === static::STATUS_STRING_BACKTICK) {
if ($this->query[$i] === '`') {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} 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;
}
continue;
} elseif ($this->status === static::STATUS_COMMENT_C) {
// C-like comments end in */.
if (($this->query[$i - 1] === '*') && ($this->query[$i] === '/')) {
$this->status = 0;
}
continue;
}
/*
* Checking if a string started.
*/
if ($this->query[$i] === '\'') {
$this->status = static::STATUS_STRING_SINGLE_QUOTES;
$this->current .= $this->query[$i];
continue;
} elseif ($this->query[$i] === '"') {
$this->status = static::STATUS_STRING_DOUBLE_QUOTES;
$this->current .= $this->query[$i];
continue;
} elseif ($this->query[$i] === '`') {
$this->status = static::STATUS_STRING_BACKTICK;
$this->current .= $this->query[$i];
continue;
}
/*
* Checking if a comment started.
*/
if ($this->query[$i] === '#') {
$this->status = static::STATUS_COMMENT_BASH;
continue;
} elseif (($i + 2 < $len)
&& ($this->query[$i] === '-')
&& ($this->query[$i + 1] === '-')
&& (Context::isWhitespace($this->query[$i + 2]))
) {
$this->status = static::STATUS_COMMENT_SQL;
continue;
} elseif (($i + 2 < $len)
&& ($this->query[$i] === '/')
&& ($this->query[$i + 1] === '*')
&& ($this->query[$i + 2] !== '!')
) {
$this->status = static::STATUS_COMMENT_C;
continue;
}
/*
* Handling `DELIMITER` statement.
*
* The code below basically checks for
* `strtoupper(substr($this->query, $i, 9)) === 'DELIMITER'`
*
* This optimization makes the code about 3 times faster.
*
* `DELIMITER` is not being considered a keyword. The only context
* 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)
&& (($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'))
&& (($this->query[$i + 3] === 'I') || ($this->query[$i + 3] === 'i'))
&& (($this->query[$i + 4] === 'M') || ($this->query[$i + 4] === 'm'))
&& (($this->query[$i + 5] === 'I') || ($this->query[$i + 5] === 'i'))
&& (($this->query[$i + 6] === 'T') || ($this->query[$i + 6] === 't'))
&& (($this->query[$i + 7] === 'E') || ($this->query[$i + 7] === 'e'))
&& (($this->query[$i + 8] === 'R') || ($this->query[$i + 8] === 'r'))
&& (Context::isWhitespace($this->query[$i + 9]))
&& (trim($this->current) === '')
) {
// Saving the current index to be able to revert any parsing
// done in this block.
$iBak = $i;
$i += 9; // Skipping `DELIMITER`.
// Skipping whitespaces.
while (($i < $len) && (Context::isWhitespace($this->query[$i]))) {
++$i;
}
// Parsing the delimiter.
$delimiter = '';
while (($i < $len) && (!Context::isWhitespace($this->query[$i]))) {
$delimiter .= $this->query[$i++];
}
// Checking if the delimiter definition ended.
if (($delimiter != '')
&& ((($i < $len) && (Context::isWhitespace($this->query[$i])))
|| (($i === $len) && ($end)))
) {
// Saving the delimiter.
$this->setDelimiter($delimiter);
// Whether this statement should be returned or not.
$ret = '';
if (!empty($this->options['parse_delimiter'])) {
// Appending the `DELIMITER` statement that was just
// found to the current statement.
$ret = trim(
$this->current . ' ' . substr($this->query, $iBak, $i - $iBak)
);
}
// Removing the statement that was just extracted from the
// query.
$this->query = substr($this->query, $i);
$i = 0;
// Resetting the current statement.
$this->current = '';
return $ret;
}
// Incomplete statement. Reverting
$i = $iBak;
return false;
}
/*
* Checking if the current statement finished.
*
* The first letter of the delimiter is being checked as an
* optimization. This code is almost as fast as the one above.
*
* There is no point in checking if two strings match if not even
* the first letter matches.
*/
if (($this->query[$i] === $this->delimiter[0])
&& (($this->delimiterLen === 1)
|| (substr($this->query, $i, $this->delimiterLen) === $this->delimiter))
) {
// Saving the statement that just ended.
$ret = $this->current;
// If needed, adds a delimiter at the end of the statement.
if (!empty($this->options['add_delimiter'])) {
$ret .= $this->delimiter;
}
// Removing the statement that was just extracted from the
// query.
$this->query = substr($this->query, $i + $this->delimiterLen);
$i = 0;
// Resetting the current statement.
$this->current = '';
// Returning the statement.
return trim($ret);
}
/*
* Appending current character to current statement.
*/
$this->current .= $this->query[$i];
}
if (($end) && ($i === $len)) {
// If the end of the buffer was reached, the buffer is emptied and
// the current statement that was extracted is returned.
$ret = $this->current;
// Emptying the buffer.
$this->query = '';
$i = 0;
// Resetting the current statement.
$this->current = '';
// Returning the statement.
return trim($ret);
}
return '';
}
}

View File

@ -0,0 +1,127 @@
<?php
/**
* CLI interface
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Parser;
use SqlParser\Lexer;
/**
* CLI interface
*
* @category Exceptions
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class CLI
{
public function mergeLongOpts(&$params, &$longopts)
{
foreach ($longopts as $value) {
$value = rtrim($value, ':');
if (isset($params[$value])) {
$params[$value[0]] = $params[$value];
}
}
}
public function usageHighlight()
{
echo "Usage: highlight-query --query SQL [--format html|cli|text]\n";
}
public function getopt($opt, $long)
{
return getopt($opt, $long);
}
public function parseHighlight()
{
$longopts = array('help', 'query:', 'format:');
$params = $this->getopt(
'hq:f:', $longopts
);
if ($params === false) {
return false;
}
$this->mergeLongOpts($params, $longopts);
if (! isset($params['f'])) {
$params['f'] = 'cli';
}
if (! in_array($params['f'], array('html', 'cli', 'text'))) {
echo "ERROR: Invalid value for format!\n";
return false;
}
return $params;
}
public function runHighlight()
{
$params = $this->parseHighlight();
if ($params === false) {
return 1;
}
if (isset($params['h'])) {
$this->usageHighlight();
return 0;
}
if (isset($params['q'])) {
echo Formatter::format(
$params['q'], array('type' => $params['f'])
);
echo "\n";
return 0;
}
echo "ERROR: Missing parameters!\n";
$this->usageHighlight();
return 1;
}
public function usageLint()
{
echo "Usage: lint-query --query SQL\n";
}
public function parseLint()
{
$longopts = array('help', 'query:');
$params = $this->getopt(
'hq:', $longopts
);
$this->mergeLongOpts($params, $longopts);
return $params;
}
public function runLint()
{
$params = $this->parseLint();
if ($params === false) {
return 1;
}
if (isset($params['h'])) {
$this->usageLint();
return 0;
}
if (isset($params['q'])) {
$lexer = new Lexer($params['q'], false);
$parser = new Parser($lexer->list);
$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;
}
}

View File

@ -0,0 +1,99 @@
<?php
/**
* Error related utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
/**
* Error related utilities.
*
* @category Exceptions
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Error
{
/**
* Gets the errors of a lexer and a parser.
*
* @param array $objs Objects from where the errors will be extracted.
*
* @return array Each element of the array represents an error.
* `$err[0]` holds the error message.
* `$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. `array($msg, $code, $str, $pos)`)
*/
public static function get($objs)
{
$ret = array();
foreach ($objs as $obj) {
if ($obj instanceof Lexer) {
foreach ($obj->errors as $err) {
$ret[] = array(
$err->getMessage(),
$err->getCode(),
$err->ch,
$err->pos
);
}
} elseif ($obj instanceof Parser) {
foreach ($obj->errors as $err) {
$ret[] = array(
$err->getMessage(),
$err->getCode(),
$err->token->token,
$err->token->position
);
}
}
}
return $ret;
}
/**
* Formats the specified errors
*
* @param array $errors The errors to be formatted.
* @param string $format The format of an error.
* '$1$d' is replaced by the position of this error.
* '$2$s' is replaced by the error message.
* '$3$d' is replaced by the error code.
* '$4$s' is replaced by the string that caused the
* issue.
* '$5$d' is replaced by the position of the string.
* @return array
*/
public static function format(
$errors,
$format = '#%1$d: %2$s (near "%4$s" at position %5$d)'
) {
$ret = array();
$i = 0;
foreach ($errors as $key => $err) {
$ret[$key] = sprintf(
$format,
++$i,
$err[0],
$err[1],
htmlspecialchars($err[2]),
$err[3]
);
}
return $ret;
}
}

View File

@ -0,0 +1,573 @@
<?php
/**
* Utilities that are used for formatting queries.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Utilities that are used for formatting queries.
*
* @category Misc
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Formatter
{
/**
* The formatting options.
*
* @var array
*/
public $options;
/**
* Clauses that must be inlined.
*
* These clauses usually are short and it's nicer to have them inline.
*
* @var array
*/
public static $INLINE_CLAUSES = array(
'CREATE' => true,
'LIMIT' => true,
'PARTITION BY' => true,
'PARTITION' => true,
'PROCEDURE' => true,
'SUBPARTITION BY' => true,
'VALUES' => true,
);
/**
* Constructor.
*
* @param array $options The formatting options.
*/
public function __construct(array $options = array())
{
// The specified formatting options are merged with the default values.
$this->options = array_merge(
array(
/**
* The format of the result.
*
* @var string The type ('text', 'cli' or 'html')
*/
'type' => php_sapi_name() == 'cli' ? 'cli' : 'text',
/**
* The line ending used.
* By default, for text this is "\n" and for HTML this is "<br/>".
*
* @var string
*/
'line_ending' => NULL,
/**
* The string used for indentation.
*
* @var string
*/
'indentation' => ' ',
/**
* Whether comments should be removed or not.
*
* @var bool
*/
'remove_comments' => false,
/**
* Whether each clause should be on a new line.
*
* @var bool
*/
'clause_newline' => true,
/**
* Whether each part should be on a new line.
* Parts are delimited by brackets and commas.
*
* @var bool
*/
'parts_newline' => true,
/**
* Whether each part of each clause should be indented.
*
* @var bool
*/
'indent_parts' => true,
/**
* The styles used for HTML formatting.
* array($type, $flags, $span, $callback)
*
* @var array[]
*/
'formats' => 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' => 0,
'html' => 'class="sql-variable"',
'cli' => "\x1b[36m",
'function' => '',
),
)
),
$options
);
if (is_null($this->options['line_ending'])) {
$this->options['line_ending'] = $this->options['type'] == 'html' ? '<br/>' : "\n";
}
// `parts_newline` requires `clause_newline`
$this->options['parts_newline'] &= $this->options['clause_newline'];
}
/**
* Formats the given list of tokens.
*
* @param TokensList $list The list of tokens.
*
* @return string
*/
public function formatList($list)
{
/**
* The query to be returned.
*
* @var string $ret
*/
$ret = '';
/**
* The indentation level.
*
* @var int $indent
*/
$indent = 0;
/**
* Whether the line ended.
*
* @var bool $lineEnded
*/
$lineEnded = false;
/**
* Whether current group is short (no linebreaks)
*
* @var bool $shortGroup
*/
$shortGroup = false;
/**
* The name of the last clause.
*
* @var string $lastClause
*/
$lastClause = '';
/**
* A stack that keeps track of the indentation level every time a new
* block is found.
*
* @var array $blocksIndentation
*/
$blocksIndentation = array();
/**
* A stack that keeps track of the line endings every time a new block
* is found.
*
* @var array $blocksLineEndings
*/
$blocksLineEndings = array();
/**
* Whether clause's options were formatted.
*
* @var bool $formattedOptions
*/
$formattedOptions = false;
/**
* Previously parsed token.
*
* @var Token $prev
*/
$prev = null;
/**
* Comments are being formatted separately to maintain the whitespaces
* before and after them.
*
* @var string $comment
*/
$comment = '';
// In order to be able to format the queries correctly, the next token
// must be taken into consideration. The loop below uses two pointers,
// `$prev` and `$curr` which store two consecutive tokens.
// Actually, at every iteration the previous token is being used.
for ($list->idx = 0; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $curr
*/
$curr = $list->tokens[$list->idx];
if ($curr->type === Token::TYPE_WHITESPACE) {
// Whitespaces are skipped because the formatter adds its own.
continue;
} elseif ($curr->type === Token::TYPE_COMMENT) {
// Whether the comments should be parsed.
if (!empty($this->options['remove_comments'])) {
continue;
}
if ($list->tokens[$list->idx - 1]->type === Token::TYPE_WHITESPACE) {
// The whitespaces before and after are preserved for
// formatting reasons.
$comment .= $list->tokens[$list->idx - 1]->token;
}
$comment .= $this->toString($curr);
if (($list->tokens[$list->idx + 1]->type === Token::TYPE_WHITESPACE)
&& ($list->tokens[$list->idx + 2]->type !== Token::TYPE_COMMENT)
) {
// Adding the next whitespace only there is no comment that
// follows it immediately which may cause adding a
// whitespace twice.
$comment .= $list->tokens[$list->idx + 1]->token;
}
// Everything was handled here, no need to continue.
continue;
}
// Checking if pointers were initialized.
if ($prev !== null) {
// Checking if a new clause started.
if (static::isClause($prev) !== false) {
$lastClause = $prev->value;
$formattedOptions = false;
}
// The options of a clause should stay on the same line and everything that follows.
if (($this->options['parts_newline'])
&& (!$formattedOptions)
&& (empty(self::$INLINE_CLAUSES[$lastClause]))
&& (($curr->type !== Token::TYPE_KEYWORD)
|| (($curr->type === Token::TYPE_KEYWORD)
&& ($curr->flags & Token::FLAG_KEYWORD_FUNCTION)))
) {
$formattedOptions = true;
$lineEnded = true;
++$indent;
}
// Checking if this clause ended.
if ($tmp = static::isClause($curr)) {
if (($tmp == 2) || ($this->options['clause_newline'])) {
$lineEnded = true;
if ($this->options['parts_newline']) {
--$indent;
}
}
}
// Indenting BEGIN ... END blocks.
if (($prev->type === Token::TYPE_KEYWORD) && ($prev->value === 'BEGIN')) {
$lineEnded = true;
array_push($blocksIndentation, $indent);
++$indent;
} elseif (($curr->type === Token::TYPE_KEYWORD) && ($curr->value === 'END')) {
$lineEnded = true;
$indent = array_pop($blocksIndentation);
}
// Formatting fragments delimited by comma.
if (($prev->type === Token::TYPE_OPERATOR) && ($prev->value === ',')) {
// 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 (((empty(self::$INLINE_CLAUSES[$lastClause]))
&& ! $shortGroup
&& ($this->options['parts_newline']))
|| (end($blocksLineEndings) === true)
) {
$lineEnded = true;
}
}
// Handling brackets.
// Brackets are indented only if the length of the fragment between
// them is longer than 30 characters.
if (($prev->type === Token::TYPE_OPERATOR) && ($prev->value === '(')) {
array_push($blocksIndentation, $indent);
$shortGroup = true;
if (static::getGroupLength($list) > 30) {
++$indent;
$lineEnded = true;
$shortGroup = false;
}
array_push($blocksLineEndings, $lineEnded);
} elseif (($curr->type === Token::TYPE_OPERATOR) && ($curr->value === ')')) {
$indent = array_pop($blocksIndentation);
$lineEnded |= array_pop($blocksLineEndings);
$shortGroup = false;
}
// Delimiter must be placed on the same line with the last
// clause.
if ($curr->type === Token::TYPE_DELIMITER) {
$lineEnded = false;
}
// Adding the token.
$ret .= $this->toString($prev);
// Finishing the line.
if ($lineEnded) {
if ($indent < 0) {
// TODO: Make sure this never occurs and delete it.
$indent = 0;
}
if ($curr->type !== Token::TYPE_COMMENT) {
$ret .= $this->options['line_ending']
. 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 (!((($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 === ')')))
// No space before . , ( )
|| (($curr->type === Token::TYPE_DELIMITER)) && (mb_strlen($curr->value, 'UTF-8') < 2))
// A space after delimiters that are longer than 2 characters.
|| ($prev->value === 'DELIMITER')
) {
$ret .= ' ';
}
}
}
if (!empty($comment)) {
$ret .= $comment;
$comment = '';
}
// Iteration finished, consider current token as previous.
$prev = $curr;
}
if ($this->options['type'] === 'cli') {
return $ret . "\x1b[0m";
}
return $ret;
}
public function escapeConsole($string)
{
return str_replace(
array(
"\x00", "\x01", "\x02", "\x03", "\x04",
"\x05", "\x06", "\x07", "\x08", "\x09", "\x0A",
"\x0B","\x0C","\x0D", "\x0E", "\x0F", "\x10", "\x11",
"\x12","\x13","\x14","\x15", "\x16", "\x17", "\x18",
"\x19","\x1A","\x1B","\x1C","\x1D", "\x1E", "\x1F"
),
array(
'\x00', '\x01', '\x02', '\x03', '\x04',
'\x05', '\x06', '\x07', '\x08', '\x09', '\x0A',
'\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11',
'\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18',
'\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F'
),
$string
);
}
/**
* Tries to print the query and returns the result.
*
* @param Token $token The token to be printed.
*
* @return string
*/
public function toString($token)
{
$text = $token->token;
foreach ($this->options['formats'] as $format) {
if (($token->type === $format['type'])
&& (($token->flags & $format['flags']) === $format['flags'])
) {
// 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>';
} elseif ($this->options['type'] === 'cli') {
return $format['cli'] . $this->escapeConsole($text);
}
break;
}
}
if ($this->options['type'] === 'cli') {
return "\x1b[39m" . $this->escapeConsole($text);
} elseif ($this->options['type'] === 'html') {
return htmlspecialchars($text, ENT_NOQUOTES);
}
}
/**
* Formats a query.
*
* @param string $query The query to be formatted
* @param array $options The formatting options.
*
* @return string The formatted string.
*/
public static function format($query, array $options = array())
{
$lexer = new Lexer($query);
$formatter = new Formatter($options);
return $formatter->formatList($lexer->list);
}
/**
* Computes the length of a group.
*
* A group is delimited by a pair of brackets.
*
* @param TokensList $list The list of tokens.
*
* @return int
*/
public static function getGroupLength($list)
{
/**
* The number of opening brackets found.
* This counter starts at one because by the time this function called,
* the list already advanced one position and the opening bracket was
* already parsed.
*
* @var int $count
*/
$count = 1;
/**
* The length of this group.
*
* @var int $length
*/
$length = 0;
for ($idx = $list->idx; $idx < $list->count; ++$idx) {
// Counting the brackets.
if ($list->tokens[$idx]->type === Token::TYPE_OPERATOR) {
if ($list->tokens[$idx]->value === '(') {
++$count;
} elseif ($list->tokens[$idx]->value === ')') {
--$count;
if ($count == 0) {
break;
}
}
}
// Keeping track of this group's length.
$length += mb_strlen($list->tokens[$idx]->value, 'UTF-8');
}
return $length;
}
/**
* Checks if a token is a statement or a clause inside a statement.
*
* @param Token $token The token to be checked.
*
* @return int|bool
*/
public static function isClause($token)
{
if ((($token->type === Token::TYPE_NONE) && (strtoupper($token->token) === 'DELIMITER'))
|| (($token->type === Token::TYPE_KEYWORD) && (isset(Parser::$STATEMENT_PARSERS[$token->value])))
) {
return 2;
} elseif (($token->type === Token::TYPE_KEYWORD) && (isset(Parser::$KEYWORD_PARSERS[$token->value]))) {
return 1;
}
return false;
}
}

View File

@ -0,0 +1,113 @@
<?php
/**
* Miscellaneous utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Components\Expression;
use SqlParser\Statements\SelectStatement;
/**
* Miscellaneous utilities.
*
* @category Misc
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Misc
{
/**
* Gets a list of all aliases and their original names.
*
* @param SelectStatement $statement The statement to be processed.
* @param string $database The name of the database.
*
* @return array
*/
public static function getAliases($statement, $database)
{
if (!($statement instanceof SelectStatement)
|| (empty($statement->expr))
|| (empty($statement->from))
) {
return array();
}
$retval = array();
$tables = array();
/**
* Expressions that may contain aliases.
* These are extracted from `FROM` and `JOIN` keywords.
*
* @var Expression[] $expressions
*/
$expressions = $statement->from;
// Adding expressions from JOIN.
if (!empty($statement->join)) {
foreach ($statement->join as $join) {
$expressions[] = $join->expr;
}
}
foreach ($expressions as $expr) {
if ((!isset($expr->table)) || ($expr->table === '')) {
continue;
}
$thisDb = ((isset($expr->database)) && ($expr->database !== '')) ?
$expr->database : $database;
if (!isset($retval[$thisDb])) {
$retval[$thisDb] = array(
'alias' => null,
'tables' => array(),
);
}
if (!isset($retval[$thisDb]['tables'][$expr->table])) {
$retval[$thisDb]['tables'][$expr->table] = array(
'alias' => ((isset($expr->alias)) && ($expr->alias !== '')) ?
$expr->alias : null,
'columns' => array(),
);
}
if (!isset($tables[$thisDb])) {
$tables[$thisDb] = array();
}
$tables[$thisDb][$expr->alias] = $expr->table;
}
foreach ($statement->expr as $expr) {
if ((!isset($expr->column)) || ($expr->column === '')
|| (!isset($expr->alias)) || ($expr->alias === '')
) {
continue;
}
$thisDb = ((isset($expr->database)) && ($expr->database !== '')) ?
$expr->database : $database;
if ((isset($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) {
$table['columns'][$expr->column] = $expr->alias;
}
}
}
return $retval;
}
}

View File

@ -0,0 +1,840 @@
<?php
/**
* Statement utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\Expression;
use SqlParser\Statements\AlterStatement;
use SqlParser\Statements\AnalyzeStatement;
use SqlParser\Statements\CallStatement;
use SqlParser\Statements\CheckStatement;
use SqlParser\Statements\ChecksumStatement;
use SqlParser\Statements\CreateStatement;
use SqlParser\Statements\DeleteStatement;
use SqlParser\Statements\DropStatement;
use SqlParser\Statements\ExplainStatement;
use SqlParser\Statements\InsertStatement;
use SqlParser\Statements\OptimizeStatement;
use SqlParser\Statements\RenameStatement;
use SqlParser\Statements\RepairStatement;
use SqlParser\Statements\ReplaceStatement;
use SqlParser\Statements\SelectStatement;
use SqlParser\Statements\ShowStatement;
use SqlParser\Statements\TruncateStatement;
use SqlParser\Statements\UpdateStatement;
/**
* Statement utilities.
*
* @category Statement
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Query
{
/**
* Functions that set the flag `is_func`.
*
* @var array
*/
public static $FUNCTIONS = array(
'SUM', 'AVG', 'STD', 'STDDEV', 'MIN', 'MAX', 'BIT_OR', 'BIT_AND'
);
/**
* Gets an array with flags this statement has.
*
* @param Statement|null $statement The statement to be processed.
* @param bool $all If `false`, false values will not be included.
*
* @return array
*/
public static function getFlags($statement, $all = false)
{
$flags = array();
if ($all) {
$flags = array(
/**
* select ... DISTINCT ...
*/
'distinct' => false,
/**
* drop ... DATABASE ...
*/
'drop_database' => false,
/**
* ... GROUP BY ...
*/
'group' => false,
/**
* ... HAVING ...
*/
'having' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* DELETE ...
*/
'is_affected' => false,
/**
* select ... PROCEDURE ANALYSE( ... ) ...
*/
'is_analyse' => false,
/**
* select COUNT( ... ) ...
*/
'is_count' => false,
/**
* DELETE ...
*/
'is_delete' => false, // @deprecated; use `querytype`
/**
* EXPLAIN ...
*/
'is_explain' => false, // @deprecated; use `querytype`
/**
* select ... INTO OUTFILE ...
*/
'is_export' => false,
/**
* select FUNC( ... ) ...
*/
'is_func' => false,
/**
* select ... GROUP BY ...
* or
* select ... HAVING ...
*/
'is_group' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* TODO: LOAD DATA ...
*/
'is_insert' => false,
/**
* ANALYZE ...
* or
* CHECK ...
* or
* CHECKSUM ...
* or
* OPTIMIZE ...
* or
* REPAIR ...
*/
'is_maint' => false,
/**
* CALL ...
*/
'is_procedure' => false,
/**
* REPLACE ...
*/
'is_replace' => false, // @deprecated; use `querytype`
/**
* SELECT ...
*/
'is_select' => false, // @deprecated; use `querytype`
/**
* SHOW ...
*/
'is_show' => false, // @deprecated; use `querytype`
/**
* Contains a subquery.
*/
'is_subquery' => false,
/**
* ... JOIN ...
*/
'join' => false,
/**
* ... LIMIT ...
*/
'limit' => false,
/**
* TODO
*/
'offset' => false,
/**
* ... ORDER ...
*/
'order' => false,
/**
* The type of the query (which is usually the first keyword of
* the statement).
*/
'querytype' => false,
/**
* Whether a page reload is required.
*/
'reload' => false,
/**
* SELECT ... FROM ...
*/
'select_from' => false,
/**
* ... UNION ...
*/
'union' => false
);
}
if ($statement instanceof AlterStatement) {
$flags['querytype'] = 'ALTER';
$flags['reload'] = true;
} elseif ($statement instanceof CreateStatement) {
$flags['querytype'] = 'CREATE';
$flags['reload'] = true;
} elseif ($statement instanceof AnalyzeStatement) {
$flags['querytype'] = 'ANALYZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof CheckStatement) {
$flags['querytype'] = 'CHECK';
$flags['is_maint'] = true;
} elseif ($statement instanceof ChecksumStatement) {
$flags['querytype'] = 'CHECKSUM';
$flags['is_maint'] = true;
} elseif ($statement instanceof OptimizeStatement) {
$flags['querytype'] = 'OPTIMIZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof RepairStatement) {
$flags['querytype'] = 'REPAIR';
$flags['is_maint'] = true;
} elseif ($statement instanceof CallStatement) {
$flags['querytype'] = 'CALL';
$flags['is_procedure'] = true;
} elseif ($statement instanceof DeleteStatement) {
$flags['querytype'] = 'DELETE';
$flags['is_delete'] = true;
$flags['is_affected'] = true;
} elseif ($statement instanceof DropStatement) {
$flags['querytype'] = 'DROP';
$flags['reload'] = true;
if (($statement->options->has('DATABASE')
|| ($statement->options->has('SCHEMA')))
) {
$flags['drop_database'] = true;
}
} elseif ($statement instanceof ExplainStatement) {
$flags['querytype'] = 'EXPLAIN';
$flags['is_explain'] = true;
} elseif ($statement instanceof InsertStatement) {
$flags['querytype'] = 'INSERT';
$flags['is_affected'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof ReplaceStatement) {
$flags['querytype'] = 'REPLACE';
$flags['is_affected'] = true;
$flags['is_replace'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof SelectStatement) {
$flags['querytype'] = 'SELECT';
$flags['is_select'] = true;
if (!empty($statement->from)) {
$flags['select_from'] = true;
}
if ($statement->options->has('DISTINCT')) {
$flags['distinct'] = true;
}
if ((!empty($statement->group)) || (!empty($statement->having))) {
$flags['is_group'] = true;
}
if ((!empty($statement->into))
&& ($statement->into->type === 'OUTFILE')
) {
$flags['is_export'] = true;
}
$expressions = $statement->expr;
if (!empty($statement->join)) {
foreach ($statement->join as $join) {
$expressions[] = $join->expr;
}
}
foreach ($expressions as $expr) {
if (!empty($expr->function)) {
if ($expr->function === 'COUNT') {
$flags['is_count'] = true;
} elseif (in_array($expr->function, static::$FUNCTIONS)) {
$flags['is_func'] = true;
}
}
if (!empty($expr->subquery)) {
$flags['is_subquery'] = true;
}
}
if ((!empty($statement->procedure))
&& ($statement->procedure->name === 'ANALYSE')
) {
$flags['is_analyse'] = true;
}
if (!empty($statement->group)) {
$flags['group'] = true;
}
if (!empty($statement->having)) {
$flags['having'] = true;
}
if (!empty($statement->union)) {
$flags['union'] = true;
}
if (!empty($statement->join)) {
$flags['join'] = true;
}
} elseif ($statement instanceof ShowStatement) {
$flags['querytype'] = 'SHOW';
$flags['is_show'] = true;
} elseif ($statement instanceof UpdateStatement) {
$flags['querytype'] = 'UPDATE';
$flags['is_affected'] = true;
}
if (($statement instanceof SelectStatement)
|| ($statement instanceof UpdateStatement)
|| ($statement instanceof DeleteStatement)
) {
if (!empty($statement->limit)) {
$flags['limit'] = true;
}
if (!empty($statement->order)) {
$flags['order'] = true;
}
}
return $flags;
}
/**
* Parses a query and gets all information about it.
*
* @param string $query The query to be parsed.
*
* @return array The array returned is the one returned by
* `static::getFlags()`, with the following keys added:
* - parser - the parser used to analyze the query;
* - statement - the first statement resulted from parsing;
* - select_tables - the real name of the tables selected;
* if there are no table names in the `SELECT`
* expressions, the table names are fetched from the
* `FROM` expressions
* - select_expr - selected expressions
*/
public static function getAll($query)
{
$parser = new Parser($query);
if (empty($parser->statements[0])) {
return static::getFlags(null, true);
}
$statement = $parser->statements[0];
$ret = static::getFlags($statement, true);
$ret['parser'] = $parser;
$ret['statement'] = $statement;
if ($statement instanceof SelectStatement) {
$ret['select_tables'] = array();
$ret['select_expr'] = array();
// Finding tables' aliases and their associated real names.
$tableAliases = array();
foreach ($statement->from as $expr) {
if ((isset($expr->table)) && ($expr->table !== '')
&& (isset($expr->alias)) && ($expr->alias !== '')
) {
$tableAliases[$expr->alias] = array(
$expr->table,
isset($expr->database) ? $expr->database : null
);
}
}
// Trying to find selected tables only from the select expression.
// Sometimes, this is not possible because the tables aren't defined
// explicitly (e.g. SELECT * FROM film, SELECT film_id FROM film).
foreach ($statement->expr as $expr) {
if ((isset($expr->table)) && ($expr->table !== '')) {
if (isset($tableAliases[$expr->table])) {
$arr = $tableAliases[$expr->table];
} else {
$arr = array(
$expr->table,
((isset($expr->database)) && ($expr->database !== '')) ?
$expr->database : null
);
}
if (!in_array($arr, $ret['select_tables'])) {
$ret['select_tables'][] = $arr;
}
} else {
$ret['select_expr'][] = $expr->expr;
}
}
// If no tables names were found in the SELECT clause or if there
// are expressions like * or COUNT(*), etc. tables names should be
// extracted from the FROM clause.
if (empty($ret['select_tables'])) {
foreach ($statement->from as $expr) {
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;
}
}
}
}
}
return $ret;
}
/**
* Gets a list of all tables used in this statement.
*
* @param Statement $statement Statement to be scanned.
*
* @return array
*/
public static function getTables($statement)
{
$expressions = array();
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)
) {
$expressions = $statement->from;
} 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 array();
}
$expressions = $statement->fields;
} elseif ($statement instanceof RenameStatement) {
foreach ($statement->renames as $rename) {
$expressions[] = $rename->old;
}
}
$ret = array();
foreach ($expressions as $expr) {
if (!empty($expr->table)) {
$expr->expr = null; // Force rebuild.
$expr->alias = null; // Aliases are not required.
$ret[] = Expression::build($expr);
}
}
return $ret;
}
/**
* Gets a specific clause.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param string $clause The clause to be returned.
* @param int|string $type The type of the search.
* If int,
* -1 for everything that was before
* 0 only for the clause
* 1 for everything after
* If string, the name of the first clause that
* should not be included.
* @param bool $skipFirst Whether to skip the first keyword in clause.
*
* @return string
*/
public static function getClause($statement, $list, $clause, $type = 0, $skipFirst = true)
{
/**
* The index of the current clause.
*
* @var int $currIdx
*/
$currIdx = 0;
/**
* The count of brackets.
* We keep track of them so we won't insert the clause in a subquery.
*
* @var int $brackets
*/
$brackets = 0;
/**
* The string to be returned.
*
* @var string $ret
*/
$ret = '';
/**
* The clauses of this type of statement and their index.
*
* @var array $clauses
*/
$clauses = array_flip(array_keys($statement->getClauses()));
/**
* Lexer used for lexing the clause.
*
* @var Lexer $lexer
*/
$lexer = new Lexer($clause);
/**
* The type of this clause.
*
* @var string $clauseType
*/
$clauseType = $lexer->list->getNextOfType(Token::TYPE_KEYWORD)->value;
/**
* The index of this clause.
*
* @var int $clauseIdx
*/
$clauseIdx = $clauses[$clauseType];
$firstClauseIdx = $clauseIdx;
$lastClauseIdx = $clauseIdx + 1;
// Determining the behavior of this function.
if ($type === -1) {
$firstClauseIdx = -1; // Something small enough.
$lastClauseIdx = $clauseIdx - 1;
} elseif ($type === 1) {
$firstClauseIdx = $clauseIdx + 1;
$lastClauseIdx = 10000; // Something big enough.
} elseif (is_string($type)) {
if ($clauses[$type] > $clauseIdx) {
$firstClauseIdx = $clauseIdx + 1;
$lastClauseIdx = $clauses[$type] - 1;
} else {
$firstClauseIdx = $clauses[$type] + 1;
$lastClauseIdx = $clauseIdx - 1;
}
}
// This option is unavailable for multiple clauses.
if ($type !== 0) {
$skipFirst = false;
}
for ($i = $statement->first; $i <= $statement->last; ++$i) {
$token = $list->tokens[$i];
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
}
}
if ($brackets == 0) {
// Checking if the section was changed.
if (($token->type === Token::TYPE_KEYWORD)
&& (isset($clauses[$token->value]))
&& ($clauses[$token->value] >= $currIdx)
) {
$currIdx = $clauses[$token->value];
if (($skipFirst) && ($currIdx == $clauseIdx)) {
// This token is skipped (not added to the old
// clause) because it will be replaced.
continue;
}
}
}
if (($firstClauseIdx <= $currIdx) && ($currIdx <= $lastClauseIdx)) {
$ret .= $token->token;
}
}
return trim($ret);
}
/**
* Builds a query by rebuilding the statement from the tokens list supplied
* and replaces a clause.
*
* It is a very basic version of a query builder.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param string $old The type of the clause that should be
* replaced. This can be an entire clause.
* @param string $new The new clause. If this parameter is omitted
* it is considered to be equal with `$old`.
* @param bool $onlyType Whether only the type of the clause should
* be replaced or the entire clause.
*
* @return string
*/
public static function replaceClause($statement, $list, $old, $new = null, $onlyType = false)
{
// TODO: Update the tokens list and the statement.
if ($new === null) {
$new = $old;
}
if ($onlyType) {
return static::getClause($statement, $list, $old, -1, false) . ' ' .
$new . ' ' . static::getClause($statement, $list, $old, 0) . ' ' .
static::getClause($statement, $list, $old, 1, false);
}
return static::getClause($statement, $list, $old, -1, false) . ' ' .
$new . ' ' . static::getClause($statement, $list, $old, 1, false);
}
/**
* Builds a query by rebuilding the statement from the tokens list supplied
* and replaces multiple clauses.
*
* @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: array($old, $new).
* Clauses must be sorted.
*
* @return string
*/
public static function replaceClauses($statement, $list, array $ops)
{
$count = count($ops);
// Nothing to do.
if ($count === 0) {
return '';
}
/**
* Value to be returned.
*
* @var string $ret
*/
$ret = '';
// If there is only one clause, `replaceClause()` should be used.
if ($count === 1) {
return static::replaceClause(
$statement,
$list,
$ops[0][0],
$ops[0][1]
);
}
// Adding everything before first replacement.
$ret .= static::getClause($statement, $list, $ops[0][0], -1) . ' ';
// Doing replacements.
for ($i = 0; $i < $count; ++$i) {
$ret .= $ops[$i][1] . ' ';
// Adding everything between this and next replacement.
if ($i + 1 !== $count) {
$ret .= static::getClause($statement, $list, $ops[$i][0], $ops[$i + 1][0]) . ' ';
}
}
// Adding everything after the last replacement.
$ret .= static::getClause($statement, $list, $ops[$count - 1][0], 1);
return $ret;
}
/**
* Gets the first full statement in the query.
*
* @param string $query The query to be analyzed.
* @param string $delimiter The delimiter to be used.
*
* @return array Array containing the first full query, the
* remaining part of the query and the last
* delimiter.
*/
public static function getFirstStatement($query, $delimiter = null)
{
$lexer = new Lexer($query, false, $delimiter);
$list = $lexer->list;
/**
* Whether a full statement was found.
*
* @var bool $fullStatement
*/
$fullStatement = false;
/**
* The first full statement.
*
* @var string $statement
*/
$statement = '';
for ($list->idx = 0; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
$statement .= $token->token;
if (($token->type === Token::TYPE_DELIMITER) && (!empty($token->token))) {
$delimiter = $token->token;
$fullStatement = true;
break;
}
}
// No statement was found so we return the entire query as being the
// remaining part.
if (!$fullStatement) {
return array(null, $query, $delimiter);
}
// At least one query was found so we have to build the rest of the
// remaining query.
$query = '';
for (++$list->idx; $list->idx < $list->count; ++$list->idx) {
$query .= $list->tokens[$list->idx]->token;
}
return array(trim($statement), $query, $delimiter);
}
/**
* Gets a starting offset of a specific clause.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param string $clause The clause to be returned.
*
* @return int
*/
public static function getClauseStartOffset($statement, $list, $clause)
{
/**
* The count of brackets.
* We keep track of them so we won't insert the clause in a subquery.
*
* @var int $brackets
*/
$brackets = 0;
/**
* The clauses of this type of statement and their index.
*
* @var array $clauses
*/
$clauses = array_flip(array_keys($statement->getClauses()));
for ($i = $statement->first; $i <= $statement->last; ++$i) {
$token = $list->tokens[$i];
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
}
}
if ($brackets == 0) {
if (($token->type === Token::TYPE_KEYWORD)
&& (isset($clauses[$token->value]))
&& ($clause === $token->value)
) {
return $i;
}
}
}
return -1;
}
}

View File

@ -0,0 +1,135 @@
<?php
/**
* Routine utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Components\DataType;
use SqlParser\Components\ParameterDefinition;
use SqlParser\Statements\CreateStatement;
/**
* Routine utilities.
*
* @category Routines
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Routine
{
/**
* Parses a parameter of a routine.
*
* @param string $param Parameter's definition.
*
* @return array
*/
public static function getReturnType($param)
{
$lexer = new Lexer($param);
// A dummy parser is used for error reporting.
$type = DataType::parse(new Parser(), $lexer->list);
if ($type === null) {
return array('', '', '', '', '');
}
$options = array();
foreach ($type->options->options as $opt) {
$options[] = is_string($opt) ? $opt : $opt['value'];
}
return array(
'',
'',
$type->name,
implode(',', $type->parameters),
implode(' ', $options)
);
}
/**
* Parses a parameter of a routine.
*
* @param string $param Parameter's definition.
*
* @return array
*/
public static function getParameter($param)
{
$lexer = new Lexer('(' . $param . ')');
// A dummy parser is used for error reporting.
$param = ParameterDefinition::parse(new Parser(), $lexer->list);
if (empty($param[0])) {
return array('', '', '', '', '');
}
$param = $param[0];
$options = array();
foreach ($param->type->options->options as $opt) {
$options[] = is_string($opt) ? $opt : $opt['value'];
}
return array(
empty($param->inOut) ? '' : $param->inOut,
$param->name,
$param->type->name,
implode(',', $param->type->parameters),
implode(' ', $options)
);
}
/**
* Gets the parameters of a routine from the parse tree.
*
* @param CreateStatement $statement The statement to be processed.
*
* @return array
*/
public static function getParameters($statement)
{
$retval = array(
'num' => 0,
'dir' => array(),
'name' => array(),
'type' => array(),
'length' => array(),
'length_arr' => array(),
'opts' => array(),
);
if (!empty($statement->parameters)) {
$idx = 0;
foreach ($statement->parameters as $param) {
$retval['dir'][$idx] = $param->inOut;
$retval['name'][$idx] = $param->name;
$retval['type'][$idx] = $param->type->name;
$retval['length'][$idx] = implode(',', $param->type->parameters);
$retval['length_arr'][$idx] = $param->type->parameters;
$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;
}
$retval['num'] = $idx;
}
return $retval;
}
}

View File

@ -0,0 +1,141 @@
<?php
/**
* Table utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Statements\CreateStatement;
/**
* Table utilities.
*
* @category Statement
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Table
{
/**
* Gets the foreign keys of the table.
*
* @param CreateStatement $statement The statement to be processed.
*
* @return array
*/
public static function getForeignKeys($statement)
{
if ((empty($statement->fields))
|| (!is_array($statement->fields))
|| (!$statement->options->has('TABLE'))
) {
return array();
}
$ret = array();
foreach ($statement->fields as $field) {
if ((empty($field->key)) || ($field->key->type !== 'FOREIGN KEY')) {
continue;
}
$columns = array();
foreach ($field->key->columns as $column) {
$columns[] = $column['name'];
}
$tmp = array(
'constraint' => $field->name,
'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;
if (($opt = $field->references->options->has('ON UPDATE'))) {
$tmp['on_update'] = str_replace(' ', '_', $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;
}
return $ret;
}
/**
* Gets fields of the table.
*
* @param CreateStatement $statement The statement to be processed.
*
* @return array
*/
public static function getFields($statement)
{
if ((empty($statement->fields))
|| (!is_array($statement->fields))
|| (!$statement->options->has('TABLE'))
) {
return array();
}
$ret = array();
foreach ($statement->fields as $field) {
// Skipping keys.
if (empty($field->type)) {
continue;
}
$ret[$field->name] = array(
'type' => $field->type->name,
'timestamp_not_null' => false,
);
if ($field->options) {
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;
}
}
}
return $ret;
}
}

View File

@ -0,0 +1,174 @@
<?php
/**
* Token utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Token utilities.
*
* @category Token
* @package SqlParser
* @subpackage Utils
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
class Tokens
{
/**
* Checks if a pattern is a match for the specified token.
*
* @param Token $token The token to be matched.
* @param array $pattern The pattern to be matches.
*
* @return bool
*/
public static function match(Token $token, array $pattern)
{
// Token.
if ((isset($pattern['token']))
&& ($pattern['token'] !== $token->token)
) {
return false;
}
// Value.
if ((isset($pattern['value']))
&& ($pattern['value'] !== $token->value)
) {
return false;
}
if ((isset($pattern['value_str']))
&& (strcasecmp($pattern['value_str'], $token->value))
) {
return false;
}
// Type.
if ((isset($pattern['type']))
&& ($pattern['type'] !== $token->type)
) {
return false;
}
// Flags.
if ((isset($pattern['flags']))
&& (($pattern['flags'] & $token->flags) === 0)
) {
return false;
}
return true;
}
public static function replaceTokens($list, array $find, array $replace)
{
/**
* Whether the first parameter is a list.
*
* @var bool
*/
$isList = $list instanceof TokensList;
// Parsing the tokens.
if (!$isList) {
$list = Lexer::getTokens($list);
}
/**
* The list to be returned.
*
* @var array
*/
$newList = array();
/**
* The length of the find pattern is calculated only once.
*
* @var int
*/
$findCount = count($find);
/**
* The starting index of the pattern.
*
* @var int
*/
$i = 0;
while ($i < $list->count) {
// A sequence may not start with a comment.
if ($list->tokens[$i]->type === Token::TYPE_COMMENT) {
$newList[] = $list->tokens[$i];
++$i;
continue;
}
/**
* The index used to parse `$list->tokens`.
*
* This index might be running faster than `$k` because some tokens
* are skipped.
*
* @var int
*/
$j = $i;
/**
* The index used to parse `$find`.
*
* This index might be running slower than `$j` because some tokens
* are skipped.
*
* @var int
*/
$k = 0;
// Checking if the next tokens match the pattern described.
while (($j < $list->count) && ($k < $findCount)) {
// Comments are being skipped.
if ($list->tokens[$j]->type === Token::TYPE_COMMENT) {
++$j;
}
if (!static::match($list->tokens[$j], $find[$k])) {
// This token does not match the pattern.
break;
}
// Going to next token and segment of find pattern.
++$j;
++$k;
}
// Checking if the sequence was found.
if ($k === $findCount) {
// Inserting new tokens.
foreach ($replace as $token) {
$newList[] = $token;
}
// Skipping next `$findCount` tokens.
$i = $j;
} else {
// Adding the same token.
$newList[] = $list->tokens[$i];
++$i;
}
}
return $isList ?
new TokensList($newList) : TokensList::build($newList);
}
}

View File

@ -0,0 +1,21 @@
<?php
/**
* Defines common elements used by the library.
*
* @package SqlParser
*/
if (!function_exists('__')) {
/**
* Translates the given string.
*
* @param string $str String to be translated.
*
* @return string
*/
function __($str)
{
return $str;
}
}