Merge pull request #1728 from udan11/new-parser

[WIP] Implementing sql-parser
This commit is contained in:
Marc Delisle 2015-07-12 06:54:13 -04:00
commit 0e1fcdd5bb
141 changed files with 12605 additions and 7565 deletions

View File

@ -80,15 +80,30 @@ if (isset($_REQUEST['submit_sql']) && ! empty($sql_query)) {
if (! preg_match('@^SELECT@i', $sql_query)) {
$message_to_display = true;
} else {
$goto = 'db_sql.php';
$goto = 'db_sql.php';
// Parse and analyze the query
include_once 'libraries/parse_analyze.inc.php';
PMA_executeQueryAndSendQueryResponse(
$analyzed_sql_results, false, $_REQUEST['db'], null, false, null, null,
false, null, null, null, $goto, $pmaThemeImage, null, null, null,
$sql_query, null, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$_REQUEST['db'], // db
null, // table
false, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}
}

View File

@ -284,14 +284,20 @@ if (!defined('TESTSUITE')) {
// Merge SQL Query aliases with Export aliases from
// export page, Export page aliases are given more
// preference over SQL Query aliases.
if (!empty($_REQUEST['aliases'])) {
$aliases = PMA_mergeAliases(
PMA_SQP_getAliasesFromQuery($sql_query, $db),
$_REQUEST['aliases']
);
$_SESSION['tmpval']['aliases'] = $_REQUEST['aliases'];
} else {
$aliases = PMA_SQP_getAliasesFromQuery($sql_query, $db);
$parser = new SqlParser\Parser($sql_query);
$aliases = array();
if ((!empty($parser->statements[0]))
&& ($parser->statements[0] instanceof SqlParser\Statements\SelectStatement)
) {
if (!empty($_REQUEST['aliases'])) {
$aliases = PMA_mergeAliases(
SqlParser\Utils\Misc::getAliases($parser->statements[0], $db),
$_REQUEST['aliases']
);
$_SESSION['tmpval']['aliases'] = $_REQUEST['aliases'];
} else {
$aliases = SqlParser\Utils\Misc::getAliases($parser->statements[0], $db);
}
}
/**

View File

@ -745,10 +745,24 @@ if ($go_sql) {
include 'libraries/parse_analyze.inc.php';
$html_output .= PMA_executeQueryAndGetQueryResponse(
$analyzed_sql_results, false, $db, $table, null,
$sql_query, null, $analyzed_sql_results['is_affected'],
null, null, null, $goto, $pmaThemeImage,
null, null, null, $sql_query, null, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$db, // db
$table, // table
null, // find_real_end
$sql_query, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}

File diff suppressed because it is too large Load Diff

View File

@ -247,55 +247,6 @@ class PMA_Table
return $result ? true : false;
}
/**
* Returns the analysis of 'SHOW CREATE TABLE' query for the table.
* In case of a view, the values are taken from the information_schema.
*
* @param string $db database
* @param string $table table
*
* @return array analysis of 'SHOW CREATE TABLE' query for the table
*/
static public function analyzeStructure($db = null, $table = null)
{
if (empty($db) || empty($table)) {
return false;
}
$analyzed_sql = array();
if (self::isView($db, $table)) {
// For a view, 'SHOW CREATE TABLE' returns the definition,
// but the structure of the view. So, we try to mock
// the result of analyzing 'SHOW CREATE TABLE' query.
$analyzed_sql[0] = array();
$analyzed_sql[0]['create_table_fields'] = array();
$results = $GLOBALS['dbi']->fetchResult(
"SELECT COLUMN_NAME, DATA_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = '" . PMA_Util::sqlAddSlashes($db) . "'
AND TABLE_NAME = '" . PMA_Util::sqlAddSlashes($table) . "'"
);
foreach ($results as $result) {
$analyzed_sql[0]['create_table_fields'][$result['COLUMN_NAME']]
= array(
'type' => /*overload*/mb_strtoupper($result['DATA_TYPE'])
);
}
} else {
$show_create_table = $GLOBALS['dbi']->fetchValue(
'SHOW CREATE TABLE '
. PMA_Util::backquote($db)
. '.' . PMA_Util::backquote($table),
0,
1
);
$analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
}
return $analyzed_sql;
}
/**
* sets given $value for given $param
*
@ -763,9 +714,10 @@ class PMA_Table
static public function moveCopy($source_db, $source_table, $target_db,
$target_table, $what, $move, $mode
) {
global $err_url;
/* Try moving table directly */
// Try moving the tables directly, using native `RENAME` statement.
if ($move && $what == 'data') {
$tbl = new PMA_Table($source_table, $source_db);
$result = $tbl->rename($target_table, $target_db);
@ -775,11 +727,11 @@ class PMA_Table
}
}
// set export settings we need
// Setting required export settings.
$GLOBALS['sql_backquotes'] = 1;
$GLOBALS['asfile'] = 1;
// Ensure the target is valid
// Ensuring the target database is valid.
if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
if (! $GLOBALS['pma']->databases->exists($source_db)) {
$GLOBALS['message'] = PMA_Message::rawError(
@ -800,24 +752,40 @@ class PMA_Table
return false;
}
/**
* The full name of source table, quoted.
* @var string $source
*/
$source = PMA_Util::backquote($source_db)
. '.' . PMA_Util::backquote($source_table);
// If the target database is not specified, the operation is taking
// place in the same database.
if (! isset($target_db) || ! /*overload*/mb_strlen($target_db)) {
$target_db = $source_db;
}
// Doing a select_db could avoid some problems with replicated databases,
// when moving table from replicated one to not replicated one
// Selecting the database could avoid some problems with replicated
// databases, when moving table from replicated one to not replicated one.
$GLOBALS['dbi']->selectDb($target_db);
/**
* The full name of target table, quoted.
* @var string $target
*/
$target = PMA_Util::backquote($target_db)
. '.' . PMA_Util::backquote($target_table);
// do not create the table if dataonly
// No table is created when this is a data-only operation.
if ($what != 'dataonly') {
include_once "libraries/plugin_interface.lib.php";
// get Export SQL instance
/* @var $export_sql_plugin ExportSql */
/**
* Instance used for exporting the current structure of the table.
*
* @var ExportSql
*/
$export_sql_plugin = PMA_getPlugin(
"export",
"sql",
@ -835,141 +803,134 @@ class PMA_Table
$GLOBALS['sql_auto_increment'] = $_POST['sql_auto_increment'];
}
/**
* The old structure of the table..
* @var string $sql_structure
*/
$sql_structure = $export_sql_plugin->getTableDef(
$source_db, $source_table, "\n", $err_url, false, false
);
unset($no_constraints_comments);
$parsed_sql = PMA_SQP_parse($sql_structure);
$analyzed_sql = PMA_SQP_analyze($parsed_sql);
$i = 0;
if (empty($analyzed_sql[0]['create_table_fields'])) {
// this is not a CREATE TABLE, so find the first VIEW
$target_for_view = PMA_Util::backquote($target_db);
while (true) {
if ($parsed_sql[$i]['type'] == 'alpha_reservedWord'
&& $parsed_sql[$i]['data'] == 'VIEW'
) {
break;
}
$i++;
}
}
unset($analyzed_sql);
if (PMA_DRIZZLE) {
$table_delimiter = 'quote_backtick';
} else {
$server_sql_mode = $GLOBALS['dbi']->fetchValue(
"SHOW VARIABLES LIKE 'sql_mode'",
0,
1
// -----------------------------------------------------------------
// Phase 0: Preparing structures used.
/**
* The destination where the table is moved or copied to.
* @var SqlParser\Components\Expression
*/
$destination = new SqlParser\Components\Expression(
$target_db, $target_table, ''
);
// Find server's SQL mode so the builder can generate correct
// queries.
// One of the options that alters the behaviour is `ANSI_QUOTES`.
// This is not availabile for Drizzle.
if (!PMA_DRIZZLE) {
SqlParser\Context::setMode(
$GLOBALS['dbi']->fetchValue(
"SHOW VARIABLES LIKE 'sql_mode'", 0, 1
)
);
// ANSI_QUOTES might be a subset of sql_mode, for example
// REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
if (false !== /*overload*/mb_strpos($server_sql_mode, 'ANSI_QUOTES')
) {
$table_delimiter = 'quote_double';
} else {
$table_delimiter = 'quote_backtick';
}
unset($server_sql_mode);
}
/* Find table name in query and replace it */
while ($parsed_sql[$i]['type'] != $table_delimiter) {
$i++;
}
// -----------------------------------------------------------------
// Phase 1: Dropping existent element of the same name (if exists
// and required).
/* no need to backquote() */
if (isset($target_for_view)) {
// this a view definition; we just found the first db name
// that follows DEFINER VIEW
// so change it for the new db name
$parsed_sql[$i]['data'] = $target_for_view;
// then we have to find all references to the source db
// and change them to the target db, ensuring we stay into
// the $parsed_sql limits
$last = $parsed_sql['len'] - 1;
$backquoted_source_db = PMA_Util::backquote($source_db);
for (++$i; $i <= $last; $i++) {
if ($parsed_sql[$i]['type'] == $table_delimiter
&& $parsed_sql[$i]['data'] == $backquoted_source_db
&& $parsed_sql[$i - 1]['type'] != 'punct_qualifier'
) {
$parsed_sql[$i]['data'] = $target_for_view;
}
}
unset($last,$backquoted_source_db);
} else {
$parsed_sql[$i]['data'] = $target;
}
/* Generate query back */
$sql_structure = PMA_SQP_format($parsed_sql, 'query_only');
// If table exists, and 'add drop table' is selected: Drop it!
if (isset($_REQUEST['drop_if_exists'])
&& $_REQUEST['drop_if_exists'] == 'true'
) {
if (PMA_Table::isView($target_db, $target_table)) {
$drop_query = 'DROP VIEW';
} else {
$drop_query = 'DROP TABLE';
}
$drop_query .= ' IF EXISTS '
. PMA_Util::backquote($target_db) . '.'
. PMA_Util::backquote($target_table);
/**
* Drop statement used for building the query.
* @var SqlParser\Statements\DropStatement $statement
*/
$statement = new SqlParser\Statements\DropStatement();
$statement->options = new SqlParser\Components\OptionsArray(
array(
PMA_Table::isView($target_db, $target_table) ?
'VIEW' : 'TABLE',
'IF EXISTS',
)
);
$statement->fields = array($destination);
// Building the query.
$drop_query = $statement->build() . ';';
// Executing it.
$GLOBALS['dbi']->query($drop_query);
$GLOBALS['sql_query'] .= "\n" . $drop_query;
$GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
// If an existing table gets deleted, maintain any
// entries for the PMA_* tables
// If an existing table gets deleted, maintain any entries for
// the PMA_* tables.
$maintain_relations = true;
}
@$GLOBALS['dbi']->query($sql_structure);
$GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
// -----------------------------------------------------------------
// Phase 2: Generating the new query of this structure.
/**
* The parser responsible for parsing the old queries.
* @var SqlParser\Parser $parser
*/
$parser = new SqlParser\Parser($sql_structure);
if (!empty($parser->statements[0])) {
/**
* The CREATE statement of this structure.
* @var SqlParser\Statements\CreateStatement $statement
*/
$statement = $parser->statements[0];
// Changing the destination.
$statement->name = $destination;
// Building back the query.
$sql_structure = $statement->build() . ';';
// Executing it.
$GLOBALS['dbi']->query($sql_structure);
$GLOBALS['sql_query'] .= "\n" . $sql_structure;
}
// -----------------------------------------------------------------
// Phase 3: Adding constraints.
// All constraint names are removed because they must be unique.
if (($move || isset($GLOBALS['add_constraints']))
&& !empty($GLOBALS['sql_constraints_query'])
) {
$parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
$i = 0;
// find the first $table_delimiter, it must be the source
// table name
while ($parsed_sql[$i]['type'] != $table_delimiter) {
$i++;
// maybe someday we should guard against going over limit
//if ($i == $parsed_sql['len']) {
// break;
//}
}
$parser = new SqlParser\Parser($GLOBALS['sql_constraints_query']);
// replace it by the target table name, no need
// to backquote()
$parsed_sql[$i]['data'] = $target;
/**
* The ALTER statement that generates the constraints.
* @var SqlParser\Statements\AlterStatement $statement
*/
$statement = $parser->statements[0];
// now we must remove all $table_delimiter that follow a
// CONSTRAINT keyword, because a constraint name must be
// unique in a db
// Changing the altered table to the destination.
$statement->table = $destination;
$cnt = $parsed_sql['len'] - 1;
for ($j = $i; $j < $cnt; $j++) {
$dataUpper = /*overload*/mb_strtoupper($parsed_sql[$j]['data']);
if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
&& $dataUpper == 'CONSTRAINT'
) {
if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
$parsed_sql[$j+1]['data'] = '';
}
// Removing the name of the constraints.
foreach ($statement->altered as $idx => $altered) {
// All constraint names are removed because they must be unique.
if ($altered->options->has('CONSTRAINT')) {
$altered->field = null;
}
}
// Generate query back
$GLOBALS['sql_constraints_query'] = PMA_SQP_format(
$parsed_sql, 'query_only'
);
// Building back the query.
$GLOBALS['sql_constraints_query'] = $statement->build() . ';';
// Executing it.
if ($mode == 'one_table') {
$GLOBALS['dbi']->query($GLOBALS['sql_constraints_query']);
}
@ -979,95 +940,70 @@ class PMA_Table
}
}
// add indexes to the table
// -----------------------------------------------------------------
// Phase 4: Adding indexes.
// View phase 3.
if (!empty($GLOBALS['sql_indexes'])) {
$index_queries = array();
$sql_indexes = $GLOBALS['sql_indexes'];
$GLOBALS['sql_indexes'] = '';
$parser = new SqlParser\Parser($GLOBALS['sql_indexes']);
$parsed_sql = PMA_SQP_parse($sql_indexes);
$cnt = $parsed_sql['len'] - 1;
$k = 0;
/**
* The ALTER statement that generates the indexes.
* @var SqlParser\Statements\AlterStatement $statement
*/
$statement = $parser->statements[0];
for ($j = 0; $j < $cnt; $j++) {
if ($parsed_sql[$j]['type'] == 'punct_queryend') {
$index_queries[] = substr(
$sql_indexes, $k, $parsed_sql[$j]['pos'] - $k
);
$k = $parsed_sql[$j]['pos'];
// Changing the altered table to the destination.
$statement->table = $destination;
// Removing the name of the constraints.
foreach ($statement->altered as $idx => $altered) {
// All constraint names are removed because they must be unique.
if ($altered->options->has('CONSTRAINT')) {
$altered->field = null;
}
}
foreach ($index_queries as $index_query) {
// Building back the query.
$GLOBALS['sql_indexes'] = $statement->build() . ';';
$parsed_sql = PMA_SQP_parse($index_query);
$i = 0;
while ($parsed_sql[$i]['type'] != $table_delimiter) {
$i++;
}
$parsed_sql[$i]['data'] = $target;
$cnt = $parsed_sql['len'] - 1;
for ($j = $i; $j < $cnt; $j++) {
$dataUpper = /*overload*/mb_strtoupper($parsed_sql[$j]['data']);
if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
&& $dataUpper == 'CONSTRAINT'
) {
if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
$parsed_sql[$j+1]['data'] = '';
}
}
}
$sql_index = PMA_SQP_format($parsed_sql, 'query_only');
if ($mode == 'one_table' || $mode == 'db_copy') {
$GLOBALS['dbi']->query($sql_index);
}
$GLOBALS['sql_indexes'] .= $sql_index;
// Executing it.
if ($mode == 'one_table' || $mode == 'db_copy') {
$GLOBALS['dbi']->query($GLOBALS['sql_indexes']);
}
$GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_indexes'];
if ($mode == 'one_table' || $mode == 'db_copy') {
unset($GLOBALS['sql_indexes']);
}
}
/*
* add AUTO_INCREMENT to the table
*
* @todo refactor with similar code above
*/
// -----------------------------------------------------------------
// Phase 5: Adding AUTO_INCREMENT.
if (! empty($GLOBALS['sql_auto_increments'])) {
if ($mode == 'one_table' || $mode == 'db_copy') {
$parsed_sql = PMA_SQP_parse($GLOBALS['sql_auto_increments']);
$i = 0;
// find the first $table_delimiter, it must be the source
// table name
while ($parsed_sql[$i]['type'] != $table_delimiter) {
$i++;
}
$parser = new SqlParser\Parser($GLOBALS['sql_auto_increments']);
// replace it by the target table name, no need
// to backquote()
$parsed_sql[$i]['data'] = $target;
/**
* The ALTER statement that alters the AUTO_INCREMENT value.
* @var SqlParser\Statements\AlterStatement $statement
*/
$statement = $parser->statements[0];
// Generate query back
$GLOBALS['sql_auto_increments'] = PMA_SQP_format(
$parsed_sql, 'query_only'
);
// Changing the altered table to the destination.
$statement->table = $destination;
// Building back the query.
$GLOBALS['sql_auto_increments'] = $statement->build() . ';';
// Executing it.
$GLOBALS['dbi']->query($GLOBALS['sql_auto_increments']);
$GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_auto_increments'];
unset($GLOBALS['sql_auto_increments']);
}
}
} else {
$GLOBALS['sql_query'] = '';
}
@ -1085,7 +1021,7 @@ class PMA_Table
$sql_insert_data = 'INSERT INTO ' . $target
. ' SELECT * FROM ' . $source;
$GLOBALS['dbi']->query($sql_insert_data);
$GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
$GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
}
$GLOBALS['cfgRelation'] = PMA_getRelationsParam();
@ -1111,7 +1047,7 @@ class PMA_Table
$source_table, $target_table
);
$GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
$GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
// end if ($move)
} else {
// we are copying
@ -1289,6 +1225,7 @@ class PMA_Table
*/
}
}
return true;
}
@ -1823,7 +1760,7 @@ class PMA_Table
foreach ($columns as $column) {
$temp = explode('.', $column);
$column_name = $temp[2];
if (PMA_SQP_isKeyWord($column_name)) {
if (SqlParser\Context::isKeyword($column_name, true)) {
$return[] = $column_name;
}
}
@ -1985,7 +1922,8 @@ class PMA_Table
*
* @return boolean True on update succeed or False on failure
*/
public function updateDisplayField($disp, $display_field, $cfgRelation) {
public function updateDisplayField($disp, $display_field, $cfgRelation)
{
$upd_query = false;
if ($disp) {
if ($display_field == '') {
@ -2038,8 +1976,9 @@ class PMA_Table
* @return boolean
*/
public function updateInternalRelations($multi_edit_columns_name,
$destination_db, $destination_table, $destination_column,
$cfgRelation, $existrel) {
$destination_db, $destination_table, $destination_column,
$cfgRelation, $existrel
) {
$updated = false;
foreach ($destination_db as $master_field_md5 => $foreign_db) {
$upd_query = null;
@ -2122,8 +2061,9 @@ class PMA_Table
* @return array
*/
public function updateForeignKeys($destination_foreign_db,
$multi_edit_columns_name, $destination_foreign_table,
$destination_foreign_column, $options_array, $table, $existrel_foreign) {
$multi_edit_columns_name, $destination_foreign_table,
$destination_foreign_column, $options_array, $table, $existrel_foreign
) {
$html_output = '';
$preview_sql_data = '';
$display_query = '';
@ -2247,8 +2187,8 @@ class PMA_Table
);
}
$html_output .= PMA_Util::showMySQLDocu(
'InnoDB_foreign_key_constraints'
) . "\n";
'InnoDB_foreign_key_constraints'
) . "\n";
}
} else {
$preview_sql_data .= $create_query . "\n";
@ -2303,7 +2243,7 @@ class PMA_Table
* @return string SQL query for foreign key constraint creation
*/
private function getSQLToCreateForeignKey($table, $field, $foreignDb, $foreignTable,
$foreignField, $name = null, $onDelete = null, $onUpdate = null
$foreignField, $name = null, $onDelete = null, $onUpdate = null
) {
$sql_query = 'ALTER TABLE ' . PMA_Util::backquote($table) . ' ADD ';
// if user entered a constraint name

View File

@ -585,68 +585,105 @@ class PMA_Util
* Displays a MySQL error message in the main panel when $exit is true.
* Returns the error message otherwise.
*
* @param string|bool $error_message the error message
* @param string $the_query the sql query that failed
* @param bool $is_modify_link whether to show a "modify" link or not
* @param string $back_url the "back" link url (full path is not
* required)
* @param bool $exit EXIT the page?
* @param string|bool $server_msg Server's error message.
* @param string $sql_query The SQL query that failed.
* @param bool $is_modify_link Whether to show a "modify" link or not.
* @param string $back_url URL for the "back" link (full path is
* not required).
* @param bool $exit Whether execution should be stopped or
* the error message should be returned.
*
* @return string
*
* @global string $table the current table
* @global string $db the current db
* @global string $table The current table.
* @global string $db The current database.
*
* @access public
*/
public static function mysqlDie(
$error_message = '', $the_query = '',
$server_msg = '', $sql_query = '',
$is_modify_link = true, $back_url = '', $exit = true
) {
global $table, $db;
/**
* Error message to be built.
* @var string $error_msg
*/
$error_msg = '';
if (! $error_message) {
$error_message = $GLOBALS['dbi']->getError();
}
if (! $the_query && ! empty($GLOBALS['sql_query'])) {
$the_query = $GLOBALS['sql_query'];
// Checking for any server errors.
if (empty($server_msg)) {
$server_msg = $GLOBALS['dbi']->getError();
}
// --- Added to solve bug #641765
if (! function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
$formatted_sql = htmlspecialchars($the_query);
} elseif (empty($the_query) || (trim($the_query) == '')) {
// Finding the query that failed, if not specified.
if ((empty($sql_query) && (!empty($GLOBALS['sql_query'])))) {
$sql_query = $GLOBALS['sql_query'];
}
$sql_query = trim($sql_query);
/**
* The lexer used for analysis.
* @var SqlParser\Lexer $lexer
*/
$lexer = new SqlParser\Lexer($sql_query);
/**
* The parser used for analysis.
* @var SqlParser\Parser $parser
*/
$parser = new SqlParser\Parser($lexer->list);
/**
* The errors found by the lexer and the parser.
* @var array $errors
*/
$errors = SqlParser\Utils\Error::get(array($lexer, $parser));
if (empty($sql_query)) {
$formatted_sql = '';
} elseif (count($errors)) {
$formatted_sql = htmlspecialchars($sql_query);
} else {
$formatted_sql = self::formatSql($the_query, true);
$formatted_sql = self::formatSql($sql_query, true);
}
// ---
$error_msg .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
$error_msg .= ' <div class="error"><h1>' . __('Error')
. '</h1>' . "\n";
// if the config password is wrong, or the MySQL server does not
// respond, do not show the query that would reveal the
// username/password
if (! empty($the_query) && ! /*overload*/mb_strstr($the_query, 'connect')) {
// --- Added to solve bug #641765
if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
$error_msg .= PMA_SQP_getErrorString() . "\n";
$error_msg .= '<br />' . "\n";
$error_msg .= '<div class="error"><h1>' . __('Error') . '</h1>';
// For security reasons, if the MySQL refuses the connection, the query
// is hidden so no details are revealed.
if ((!empty($sql_query)) && (!(mb_strstr($sql_query, 'connect')))) {
// Static analysis errors.
if (!empty($errors)) {
$error_msg .= '<p><strong>' . __('Static analysis:') . '</strong></p>';
$error_msg .= '<p>' . sprintf(
__('%d errors were found during analysis.'), count($errors)
) . '</p>';
$error_msg .= '<p><ol>';
$error_msg .= implode(
SqlParser\Utils\Error::format(
$errors,
'<li>%2$s (near "%4$s" at position %5$d)</li>'
)
);
$error_msg .= '</ol></p>';
}
// ---
// modified to show the help on sql errors
// Display the SQL query and link to MySQL documentation.
$error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
$formattedSqlToLower = /*overload*/mb_strtolower($formatted_sql);
// TODO: Show documentation for all statement types.
if (/*overload*/mb_strstr($formattedSqlToLower, 'select')) {
// please show me help to the error on select
$error_msg .= self::showMySQLDocu('SELECT');
}
if ($is_modify_link) {
$_url_params = array(
'sql_query' => $the_query,
'sql_query' => $sql_query,
'show_query' => 1,
);
if (/*overload*/mb_strlen($table)) {
@ -666,46 +703,47 @@ class PMA_Util
$error_msg .= $doedit_goto
. self::getIcon('b_edit.png', __('Edit'))
. '</a>';
} // end if
}
$error_msg .= ' </p>' . "\n"
. '<p>' . "\n"
. $formatted_sql . "\n"
. '</p>' . "\n";
} // end if
}
if (! empty($error_message)) {
$error_message = preg_replace(
// Display server's error.
if (!empty($server_msg)) {
$server_msg = preg_replace(
"@((\015\012)|(\015)|(\012)){3,}@",
"\n\n",
$error_message
$server_msg
);
// Adds a link to MySQL documentation.
$error_msg .= '<p>' . "\n"
. ' <strong>' . __('MySQL said: ') . '</strong>'
. self::showMySQLDocu('Error-messages-server')
. "\n"
. '</p>' . "\n";
// The error message will be displayed within a CODE segment.
// To preserve original formatting, but allow word-wrapping,
// a couple of replacements are done.
// All non-single blanks and TAB-characters are replaced with their
// HTML-counterpart
$server_msg = str_replace(
array(' ', "\t"),
array('&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'),
$server_msg
);
// Replace line breaks
$server_msg = nl2br($server_msg);
$error_msg .= '<code>' . $server_msg . '</code><br/>';
}
// modified to show the help on error-returns
// (now error-messages-server)
$error_msg .= '<p>' . "\n"
. ' <strong>' . __('MySQL said: ') . '</strong>'
. self::showMySQLDocu('Error-messages-server')
. "\n"
. '</p>' . "\n";
// The error message will be displayed within a CODE segment.
// To preserve original formatting, but allow wordwrapping,
// we do a couple of replacements
// Replace all non-single blanks with their HTML-counterpart
$error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
// Replace TAB-characters with their HTML-counterpart
$error_message = str_replace(
"\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message
);
// Replace line breaks
$error_message = nl2br($error_message);
$error_msg .= '<code>' . "\n"
. $error_message . "\n"
. '</code><br />' . "\n";
$error_msg .= '</div>';
$_SESSION['Import_message']['message'] = $error_msg;
if (!$exit) {
@ -713,19 +751,17 @@ class PMA_Util
}
/**
* If in an Ajax request
* - avoid displaying a Back link
* - use PMA_Response() to transmit the message and exit
* If this is an AJAX request, there is no "Back" link and
* `PMA_Response()` is used to send the response.
*/
if (isset($GLOBALS['is_ajax_request'])
&& $GLOBALS['is_ajax_request'] == true
) {
if (!empty($GLOBALS['is_ajax_request'])) {
$response = PMA_Response::getInstance();
$response->isSuccess(false);
$response->addJSON('message', $error_msg);
exit;
}
if (! empty($back_url)) {
if (!empty($back_url)) {
if (/*overload*/mb_strstr($back_url, '?')) {
$back_url .= '&amp;no_history=true';
} else {
@ -738,9 +774,9 @@ class PMA_Util
. '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
. '</fieldset>' . "\n\n";
}
echo $error_msg;
exit;
} // end of the 'mysqlDie()' function
exit($error_msg);
}
/**
* Check the correct row count
@ -907,9 +943,7 @@ class PMA_Util
}
if (! $do_it) {
global $PMA_SQPdata_forbidden_word;
$eltNameUpper = /*overload*/mb_strtoupper($a_name);
if (!in_array($eltNameUpper, $PMA_SQPdata_forbidden_word)) {
if (!(SqlParser\Context::isKeyword($a_name) & SqlParser\Token::FLAG_KEYWORD_RESERVED)) {
return $a_name;
}
}
@ -954,9 +988,7 @@ class PMA_Util
}
if (! $do_it) {
global $PMA_SQPdata_forbidden_word;
$eltNameUpper = /*overload*/mb_strtoupper($a_name);
if (!in_array($eltNameUpper, $PMA_SQPdata_forbidden_word)) {
if (!SqlParser\Context::isKeyword($a_name)) {
return $a_name;
}
}
@ -1091,56 +1123,6 @@ class PMA_Util
) . '[...]'
)
);
} elseif (! empty($GLOBALS['parsed_sql'])
&& $query_base == $GLOBALS['parsed_sql']['raw']
) {
// (here, use "! empty" because when deleting a bookmark,
// $GLOBALS['parsed_sql'] is set but empty
$parsed_sql = $GLOBALS['parsed_sql'];
} else {
// Parse SQL if needed
$parsed_sql = PMA_SQP_parse($query_base);
}
// Analyze it
if (isset($parsed_sql) && ! PMA_SQP_isError()) {
$analyzed_display_query = PMA_SQP_analyze($parsed_sql);
// Same as below (append LIMIT), append the remembered ORDER BY
if ($GLOBALS['cfg']['RememberSorting']
&& isset($analyzed_display_query[0]['queryflags']['select_from'])
&& isset($GLOBALS['sql_order_to_append'])
) {
$query_base = $analyzed_display_query[0]['section_before_limit']
. "\n" . $GLOBALS['sql_order_to_append']
. $analyzed_display_query[0]['limit_clause'] . ' '
. $analyzed_display_query[0]['section_after_limit'];
// update the $analyzed_display_query
$analyzed_display_query[0]['section_before_limit']
.= $GLOBALS['sql_order_to_append'];
$analyzed_display_query[0]['order_by_clause']
= $GLOBALS['sorted_col'];
}
// Here we append the LIMIT added for navigation, to
// enable its display. Adding it higher in the code
// to $sql_query would create a problem when
// using the Refresh or Edit links.
// Only append it on SELECTs.
/**
* @todo what would be the best to do when someone hits Refresh:
* use the current LIMITs ?
*/
if (isset($analyzed_display_query[0]['queryflags']['select_from'])
&& ! empty($GLOBALS['sql_limit_to_append'])
) {
$query_base = $analyzed_display_query[0]['section_before_limit']
. "\n" . $GLOBALS['sql_limit_to_append']
. $analyzed_display_query[0]['section_after_limit'];
}
}
if (! empty($GLOBALS['show_as_php'])) {
@ -2143,22 +2125,24 @@ class PMA_Util
/**
* Function to generate unique condition for specified row.
*
* @param resource $handle current query result
* @param integer $fields_cnt number of fields
* @param array $fields_meta meta information about fields
* @param array $row current row
* @param boolean $force_unique generate condition only on pk or
* unique
* @param string|boolean $restrict_to_table restrict the unique condition to
* this table or false if none
* @param resource $handle current query result
* @param integer $fields_cnt number of fields
* @param array $fields_meta meta information about fields
* @param array $row current row
* @param boolean $force_unique generate condition only on pk
* or unique
* @param string|boolean $restrict_to_table restrict the unique condition
* to this table or false if
* none
* @param array $analyzed_sql_results the analyzed query
*
* @access public
*
* @return array the calculated condition and whether condition is unique
* @return array the calculated condition and whether condition is unique
*/
public static function getUniqueCondition(
$handle, $fields_cnt, $fields_meta, $row, $force_unique = false,
$restrict_to_table = false
$restrict_to_table = false, $analyzed_sql_results = null
) {
$primary_key = '';
$unique_key = '';
@ -2179,19 +2163,16 @@ class PMA_Util
if (! isset($meta->orgname) || ! /*overload*/mb_strlen($meta->orgname)) {
$meta->orgname = $meta->name;
if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
&& is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
) {
foreach (
$GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr
) {
// need (string) === (string)
// '' !== 0 but '' == 0
if ((string)$select_expr['alias'] === (string)$meta->name) {
$meta->orgname = $select_expr['column'];
if (!empty($analyzed_sql_results['statement']->expr)) {
foreach ($analyzed_sql_results['statement']->expr as $expr) {
if ((empty($expr->alias)) || (empty($expr->column))) {
continue;
}
if (strcasecmp($meta->name, $expr->alias) == 0) {
$meta->orgname = $expr->column;
break;
} // end if
} // end foreach
}
}
}
}
@ -3947,7 +3928,6 @@ class PMA_Util
* @param bool $insert_mode Whether the operation is 'insert'
*
* @global array $cfg PMA configuration
* @global array $analyzed_sql Analyzed SQL query
* @global mixed $data data of currently edited row
* (used to detect whether to choose defaults)
*
@ -4185,38 +4165,6 @@ class PMA_Util
return $server_type;
}
/**
* Analyzes the limit clause and return the start and length attributes of it.
*
* @param string $limit_clause limit clause
*
* @return array|bool Start and length attributes of the limit clause or false
* on failure
*/
public static function analyzeLimitClause($limit_clause)
{
$limitParams = trim(str_ireplace('LIMIT', '', $limit_clause));
if ('' == $limitParams) {
return false;
}
$start_and_length = explode(',', $limitParams);
$size = count($start_and_length);
if ($size == 1) {
return array(
'start' => '0',
'length' => trim($start_and_length[0])
);
} elseif ($size == 2) {
return array(
'start' => trim($start_and_length[0]),
'length' => trim($start_and_length[1])
);
}
return false;
}
/**
* Prepare HTML code for display button.
*

View File

@ -435,12 +435,12 @@ function PMA_makeConsistentWithList($db, $selected_tables)
if ($column['col_default']) {
if ($column['col_default'] != 'CURRENT_TIMESTAMP') {
$query .= ' DEFAULT \'' . PMA_Util::sqlAddSlashes(
$column['col_default']
) . '\'';
$column['col_default']
) . '\'';
} else {
$query .= ' DEFAULT ' . PMA_Util::sqlAddSlashes(
$column['col_default']
);
$column['col_default']
);
}
}
$query .= ',';
@ -514,7 +514,7 @@ function PMA_getCentralColumnsFromTable($db, $table, $allFields=false)
* @return true|PMA_Message
*/
function PMA_updateOneColumn($db, $orig_col_name, $col_name, $col_type,
$col_attribute,$col_length, $col_isNull, $collation, $col_extra, $col_default
$col_attribute,$col_length, $col_isNull, $collation, $col_extra, $col_default
) {
$cfgCentralColumns = PMA_centralColumnsGetParams();
if (empty($cfgCentralColumns)) {
@ -865,7 +865,8 @@ function PMA_getHTMLforCentralColumnsTableRow($row, $odd_row, $row_num, $db)
. '<input name="orig_col_name" type="hidden" '
. 'value="' . htmlspecialchars($row['col_name']) . '">'
. PMA\Template::get('columns_definitions/column_name')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 0,
'ci_offset' => 0,
@ -875,19 +876,22 @@ function PMA_getHTMLforCentralColumnsTableRow($row, $odd_row, $row_num, $db)
'cfgRelation' => array(
'centralcolumnswork' => false
)
))
)
)
. '</td>';
$tableHtml .=
'<td name = "col_type" class="nowrap"><span>'
. htmlspecialchars($row['col_type']) . '</span>'
. PMA\Template::get('columns_definitions/column_type')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 1,
'ci_offset' => 0,
'type_upper' => /*overload*/mb_strtoupper($row['col_type']),
'columnMeta' => array()
))
)
)
. '</td>';
$tableHtml .=
'<td class="nowrap" name="col_length">'
@ -922,13 +926,15 @@ function PMA_getHTMLforCentralColumnsTableRow($row, $odd_row, $row_num, $db)
? htmlspecialchars($row['col_default']) : 'None')
. '</span>'
. PMA\Template::get('columns_definitions/column_default')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 3,
'ci_offset' => 0,
'type_upper' => /*overload*/mb_strtoupper($row['col_type']),
'columnMeta' => $meta
))
)
)
. '</td>';
$tableHtml .=
@ -946,29 +952,32 @@ function PMA_getHTMLforCentralColumnsTableRow($row, $odd_row, $row_num, $db)
? htmlspecialchars($row['col_attribute']) : "" )
. '</span>'
. PMA\Template::get('columns_definitions/column_attribute')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 5,
'ci_offset' => 0,
'extracted_columnspec' => array(),
'columnMeta' => $row['col_attribute'],
'submit_attribute' => false,
'analyzed_sql' => null
))
)
)
. '</td>';
$tableHtml .=
'<td class="nowrap" name="col_isNull">'
. '<span>' . ($row['col_isNull'] ? __('Yes') : __('No'))
. '</span>'
. PMA\Template::get('columns_definitions/column_null')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 6,
'ci_offset' => 0,
'columnMeta' => array(
'Null' => $row['col_isNull']
)
))
)
)
. '</td>';
$tableHtml .=
@ -1006,7 +1015,8 @@ function PMA_getHTMLforCentralColumnsEditTableRow($row, $odd_row, $row_num)
. 'value="' . htmlspecialchars($row['col_name']) . '">'
. '<td name="col_name" class="nowrap">'
. PMA\Template::get('columns_definitions/column_name')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 0,
'ci_offset' => 0,
@ -1016,18 +1026,21 @@ function PMA_getHTMLforCentralColumnsEditTableRow($row, $odd_row, $row_num)
'cfgRelation' => array(
'centralcolumnswork' => false
)
))
)
)
. '</td>';
$tableHtml .=
'<td name = "col_type" class="nowrap">'
. PMA\Template::get('columns_definitions/column_type')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 1,
'ci_offset' => 0,
'type_upper' => /*overload*/mb_strtoupper($row['col_type']),
'columnMeta' => array()
))
)
)
. '</td>';
$tableHtml .=
'<td class="nowrap" name="col_length">'
@ -1057,13 +1070,15 @@ function PMA_getHTMLforCentralColumnsEditTableRow($row, $odd_row, $row_num)
$tableHtml .=
'<td class="nowrap" name="col_default">'
. PMA\Template::get('columns_definitions/column_default')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 3,
'ci_offset' => 0,
'type_upper' => /*overload*/mb_strtoupper($row['col_default']),
'columnMeta' => $meta
))
)
)
. '</td>';
$tableHtml .=
'<td name="collation" class="nowrap">'
@ -1075,7 +1090,8 @@ function PMA_getHTMLforCentralColumnsEditTableRow($row, $odd_row, $row_num)
$tableHtml .=
'<td class="nowrap" name="col_attribute">'
. PMA\Template::get('columns_definitions/column_attribute')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 5,
'ci_offset' => 0,
@ -1084,20 +1100,22 @@ function PMA_getHTMLforCentralColumnsEditTableRow($row, $odd_row, $row_num)
),
'columnMeta' => array(),
'submit_attribute' => false,
'analyzed_sql' => null
))
)
)
. '</td>';
$tableHtml .=
'<td class="nowrap" name="col_isNull">'
. PMA\Template::get('columns_definitions/column_null')
->render(array(
->render(
array(
'columnNumber' => $row_num,
'ci' => 6,
'ci_offset' => 0,
'columnMeta' => array(
'Null' => $row['col_isNull']
)
))
)
)
. '</td>';
$tableHtml .=
@ -1255,7 +1273,8 @@ function PMA_getHTMLforAddNewColumn($db)
. '<td></td>'
. '<td name="col_name" class="nowrap">'
. PMA\Template::get('columns_definitions/column_name')
->render(array(
->render(
array(
'columnNumber' => 0,
'ci' => 0,
'ci_offset' => 0,
@ -1263,17 +1282,20 @@ function PMA_getHTMLforAddNewColumn($db)
'cfgRelation' => array(
'centralcolumnswork' => false
)
))
)
)
. '</td>'
. '<td name = "col_type" class="nowrap">'
. PMA\Template::get('columns_definitions/column_type')
->render(array(
->render(
array(
'columnNumber' => 0,
'ci' => 1,
'ci_offset' => 0,
'type_upper' => '',
'columnMeta' => array()
))
)
)
. '</td>'
. '<td class="nowrap" name="col_length">'
. PMA\Template::get('columns_definitions/column_length')->render(
@ -1288,13 +1310,15 @@ function PMA_getHTMLforAddNewColumn($db)
. '</td>'
. '<td class="nowrap" name="col_default">'
. PMA\Template::get('columns_definitions/column_default')
->render(array(
->render(
array(
'columnNumber' => 0,
'ci' => 3,
'ci_offset' => 0,
'type_upper' => '',
'columnMeta' => array()
))
)
)
. '</td>'
. '<td name="collation" class="nowrap">'
. PMA_generateCharsetDropdownBox(
@ -1304,24 +1328,27 @@ function PMA_getHTMLforAddNewColumn($db)
. '</td>'
. '<td class="nowrap" name="col_attribute">'
. PMA\Template::get('columns_definitions/column_attribute')
->render(array(
->render(
array(
'columnNumber' => 0,
'ci' => 5,
'ci_offset' => 0,
'extracted_columnspec' => array(),
'columnMeta' => array(),
'submit_attribute' => false,
'analyzed_sql' => null
))
)
)
. '</td>'
. '<td class="nowrap" name="col_isNull">'
. PMA\Template::get('columns_definitions/column_null')
->render(array(
->render(
array(
'columnNumber' => 0,
'ci' => 6,
'ci_offset' => 0,
'columnMeta' => array()
))
)
)
. '</td>'
. '<td class="nowrap" name="col_extra">'
. PMA\Template::get('columns_definitions/column_extra')->render(

View File

@ -1054,9 +1054,32 @@ if (! defined('PMA_MINIMUM_COMMON')) {
}
/**
* SQL Parser code
* Charset information
*/
include_once './libraries/sqlparser.lib.php';
if (!PMA_DRIZZLE) {
include_once './libraries/mysql_charsets.inc.php';
}
if (!isset($mysql_charsets)) {
$mysql_charsets = array();
$mysql_collations_flat = array();
}
/**
* Initializes the SQL parsing library.
*/
include_once './libraries/sql-parser/autoload.php';
// Loads closest context to this version.
SqlParser\Context::loadClosest(
(PMA_DRIZZLE ? 'Drizzle' : 'MySql') . PMA_MYSQL_INT_VERSION
);
// Sets the default delimiter (if specified).
if (!empty($_REQUEST['sql_delimiter'])) {
SqlParser\Lexer::$DEFAULT_DELIMITER = $_REQUEST['sql_delimiter'];
}
// TODO: Set SQL modes too.
/**
* the PMA_List_Database class

View File

@ -115,9 +115,9 @@ foreach ($fields as $row) {
$attribute = $extracted_columnspec['attribute'];
// prepare a common variable to reuse below; however,
// in case of a VIEW, $analyzed_sql[0]['create_table_fields'] is empty
if (isset($analyzed_sql[0]['create_table_fields'][$row['Field']])) {
$tempField = $analyzed_sql[0]['create_table_fields'][$row['Field']];
// in case of a VIEW, $create_table_fields is empty
if (isset($create_table_fields[$row['Field']])) {
$tempField = $create_table_fields[$row['Field']];
} else {
$tempField = array();
}

View File

@ -1006,10 +1006,10 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
if ($create_db) {
if (PMA_DRIZZLE) {
$sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
. " COLLATE " . $collation;
. " COLLATE " . $collation . ";";
} else {
$sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
. " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
. " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation . ";";
}
}
@ -1388,33 +1388,33 @@ function PMA_handleSimulateDMLRequest()
continue;
}
// Parse and Analyze the query.
$parsed_sql = PMA_SQP_parse($sql_query);
$analyzed_sql = PMA_SQP_analyze($parsed_sql);
// Parsing the query.
$parser = new SqlParser\Parser($sql_query);
if (empty($parser->statements[0])) {
continue;
}
$statement = $parser->statements[0];
$analyzed_sql_results = array(
'parsed_sql' => $parsed_sql,
'analyzed_sql' => $analyzed_sql
'query' => $sql_query,
'parser' => $parser,
'statement' => $statement,
);
// Only UPDATE/DELETE queries accepted.
$query_type = $analyzed_sql_results['analyzed_sql'][0]['querytype'];
if ($query_type != 'UPDATE' && $query_type != 'DELETE') {
if ((!(($statement instanceof SqlParser\Statements\UpdateStatement)
|| ($statement instanceof SqlParser\Statements\DeleteStatement)))
|| (!empty($statement->join))
) {
$error = $error_msg;
break;
}
// Only single-table queries accepted.
$table_references = PMA_getTableReferences($analyzed_sql_results);
$table_references = $table_references ? $table_references : '';
if (preg_match('/JOIN/i', $table_references)) {
$tables = SqlParser\Utils\Query::getTables($statement);
if (count($tables) > 1) {
$error = $error_msg;
break;
} else {
$tables = explode(',', $table_references);
if (count($tables) > 1) {
$error = $error_msg;
break;
}
}
// Get the matched rows for the query.
@ -1444,20 +1444,18 @@ function PMA_handleSimulateDMLRequest()
*/
function PMA_getMatchedRows($analyzed_sql_results = array())
{
// Get the query type.
$query_type = (isset($analyzed_sql_results['analyzed_sql'][0]['querytype']))
? $analyzed_sql_results['analyzed_sql'][0]['querytype']
: '';
$statement = $analyzed_sql_results['statement'];
$matched_row_query = '';
if ($query_type == 'DELETE') {
if ($statement instanceof SqlParser\Statements\DeleteStatement) {
$matched_row_query = PMA_getSimulatedDeleteQuery($analyzed_sql_results);
} else if ($query_type == 'UPDATE') {
} elseif ($statement instanceof SqlParser\Statements\UpdateStatement) {
$matched_row_query = PMA_getSimulatedUpdateQuery($analyzed_sql_results);
}
// Execute the query and get the number of matched rows.
$matched_rows = PMA_executeMatchedRowQuery($matched_row_query);
// URL to matched rows.
$_url_params = array(
'db' => $GLOBALS['db'],
@ -1466,9 +1464,7 @@ function PMA_getMatchedRows($analyzed_sql_results = array())
$matched_rows_url = 'sql.php' . PMA_URL_getCommon($_url_params);
return array(
'sql_query' => PMA_Util::formatSql(
$analyzed_sql_results['parsed_sql']['raw']
),
'sql_query' => PMA_Util::formatSql($analyzed_sql_results['query']),
'matched_rows' => $matched_rows,
'matched_rows_url' => $matched_rows_url
);
@ -1483,95 +1479,51 @@ function PMA_getMatchedRows($analyzed_sql_results = array())
*/
function PMA_getSimulatedUpdateQuery($analyzed_sql_results)
{
$where_clause = '';
$extra_where_clause = array();
$target_cols = array();
$table_references = SqlParser\Utils\Query::getTables(
$analyzed_sql_results['statement']
);
$prev_term = '';
$i = 0;
$in_function = 0;
foreach ($analyzed_sql_results['parsed_sql'] as $key => $term) {
if (! isset($get_set_expr)
&& preg_match(
'/\bSET\b/i',
isset($term['data']) ? $term['data'] : ''
)
) {
$get_set_expr = true;
continue;
}
$where = SqlParser\Utils\Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'WHERE'
);
if (isset($get_set_expr)) {
if (preg_match(
'/\bWHERE\b|\bORDER BY\b|\bLIMIT\b/i',
isset($term['data']) ? $term['data'] : ''
)
) {
break;
}
if (!$in_function) {
if ($term['type'] == 'punct_listsep') {
$extra_where_clause[] = ' OR ';
} else if ($term['type'] == 'punct') {
$extra_where_clause[] = ' <> ';
} else if ($term['type'] == 'alpha_functionName') {
array_pop($extra_where_clause);
array_pop($extra_where_clause);
} else {
$extra_where_clause[] = $term['data'];
}
} else if ($term['type'] == 'punct_bracket_close_round') {
$in_function--;
}
if ($term['type'] == 'alpha_functionName') {
$in_function++;
}
// Get columns in SET expression.
if ($prev_term != 'punct') {
if ($term['type'] != 'punct_listsep'
&& $term['type'] != 'punct'
&& $term['type'] != 'punct_bracket_open_round'
&& $term['type'] != 'punct_bracket_close_round'
&& !$in_function
&& isset($term['data'])
) {
if (isset($target_cols[$i])) {
$target_cols[$i] .= $term['data'];
} else {
$target_cols[$i] = $term['data'];
}
}
} else {
$i++;
}
$prev_term = $term['type'];
continue;
}
if (empty($where)) {
$where = '1';
}
// Get table_references.
$table_references = PMA_getTableReferences($analyzed_sql_results);
$target_cols = implode(', ', $target_cols);
// Get WHERE clause.
$where_clause .= $analyzed_sql_results['analyzed_sql'][0]['where_clause'];
if (empty($where_clause)) {
$where_clause = (!empty($extra_where_clause) && $extra_where_clause[0])
? implode(' ', $extra_where_clause)
: '1';
$columns = array();
$diff = array();
foreach ($analyzed_sql_results['statement']->set as $set) {
$columns[] = $set->column;
$diff[] = $set->column . ' <> ' . $set->value;
}
if (!empty($diff)) {
$where .= ' AND (' . implode(' OR ', $diff) . ')';
}
$matched_row_query = 'SELECT '
. $target_cols
. ' FROM '
. $table_references
. ' WHERE '
. $where_clause;
$order_and_limit = '';
return $matched_row_query;
if (!empty($analyzed_sql_results['statement']->order)) {
$order_and_limit .= ' ORDER BY ' . SqlParser\Utils\Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'ORDER BY'
);
}
if (!empty($analyzed_sql_results['statement']->limit)) {
$order_and_limit .= ' LIMIT ' . SqlParser\Utils\Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'LIMIT'
);
}
return 'SELECT ' . implode(', ', $columns) .
' FROM ' . implode(', ', $table_references) .
' WHERE ' . $where . $order_and_limit;
}
/**
@ -1583,115 +1535,40 @@ function PMA_getSimulatedUpdateQuery($analyzed_sql_results)
*/
function PMA_getSimulatedDeleteQuery($analyzed_sql_results)
{
$where_clause = '';
$table_references = SqlParser\Utils\Query::getTables(
$analyzed_sql_results['statement']
);
$where_clause .= $analyzed_sql_results['analyzed_sql'][0]['where_clause'];
if (empty($where_clause)) {
$where_clause = '1';
$where = SqlParser\Utils\Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'WHERE'
);
if (empty($where)) {
$where = '1';
}
// Get the table_references.
$table_references = PMA_getTableReferences($analyzed_sql_results);
$order_and_limit = '';
$matched_row_query = 'SELECT * '
. ' FROM '
. $table_references
. ' WHERE '
. $where_clause;
return $matched_row_query;
}
/**
* Finds table_references from a given query.
* Queries Supported: INSERT, UPDATE, DELETE, REPLACE, ALTER, DROP, TRUNCATE
* and RENAME.
*
* @param array $analyzed_sql_results Analyzed SQL results from parser
*
* @return string table_references
*/
function PMA_getTableReferences($analyzed_sql_results)
{
$table_references = '';
foreach ($analyzed_sql_results['parsed_sql'] as $key => $term) {
// Skip first KeyWord and other invalid keys.
if ($key == 0 || ! isset($term['data'])) {
continue;
}
// Get the query type.
$query_type = (isset($analyzed_sql_results['analyzed_sql'][0]['querytype']))
? $analyzed_sql_results['analyzed_sql'][0]['querytype']
: '';
// Terms to 'ignore' from query for table_references.
$ignore_re = '/';
// Terminating condition for table_references.
$terminate_re = '/';
// Create relevant Regular Expressions.
switch ($query_type) {
case 'REPLACE':
case 'INSERT':
$ignore_re .= '\bINSERT\b|\bREPLACE\b|\bLOW_PRIORITY\b|\bDELAYED\b'
. '|\bHIGH_PRIORITY\b|\bIGNORE\b|\bINTO\b';
$terminate_re .= '\bPARTITION\b|\(|\bVALUE\b|\bVALUES\b|\bSELECT\b';
break;
case 'UPDATE':
$ignore_re .= '\bUPDATE\b|\bLOW_PRIORITY\b|\bIGNORE\b';
$terminate_re .= '\bSET\b|\bUSING\b';
break;
case 'DELETE':
$ignore_re .= '\bDELETE\b|\bLOW_PRIORITY\b|\bQUICK\b|\bIGNORE\b'
. '|\bFROM\b';
$terminate_re .= '\bPARTITION\b|\bWHERE\b|\bORDER\b|\bLIMIT\b|\bUSING\b';
break;
case 'ALTER':
$ignore_re .= '\bALTER\b|\bONLINE\b|\bOFFLINE\b|\bIGNORE\b|\bTABLE\b';
$terminate_re .= '\bADD\b|\bALTER\b|\bCHANGE\b|\bMODIFY\b|\bDROP\b'
. '|\bDISABLE\b|\bENABLE\b|\bRENAME\b|\bORDER\b|\bCONVERT\b'
. '|\bDEFAULT\b|\bDISCARD\b|\bIMPORT\b|\bCOALESCE\b|\bREORGANIZE\b'
. '|\bANALYZE\b|\bCHECK\b|\bOPTIMIZE\b|\bREBUILD\b|\bREPAIR\b'
. '|\bPARTITION\b|\bREMOVE\b|\bCHARACTER\b';
break;
case 'DROP':
$ignore_re .= '\bDROP\b|\bTEMPORARY\b|\bTABLE\b|\bIF\b|\bEXISTS\b';
$terminate_re .= '\bRESTRICT\b|\bCASCADE\b';
break;
case 'TRUNCATE':
$ignore_re .= '\bTRUNCATE\b|\bTABLE\b';
$terminate_re .= '';
break;
case 'RENAME':
$ignore_re .= '\bRENAME\b|\bTABLE\b';
$terminate_re .= '\bTO\b';
break;
default:
return false;
}
// Ignore 'case' in RegEx.
$ignore_re .= '/i';
$terminate_re .= '/i';
if ($query_type != 'TRUNCATE'
&& preg_match($terminate_re, $term['data'])
) {
break;
}
if (preg_match($ignore_re, $term['data'])
|| ! is_numeric($key)
|| $key == 0
) {
continue;
}
$table_references .= ' ' . $term['data'];
if (!empty($analyzed_sql_results['statement']->order)) {
$order_and_limit .= ' ORDER BY ' . SqlParser\Utils\Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'ORDER BY'
);
}
return $table_references;
if (!empty($analyzed_sql_results['statement']->limit)) {
$order_and_limit .= ' LIMIT ' . SqlParser\Utils\Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'LIMIT'
);
}
return 'SELECT * FROM ' . implode(', ', $table_references) .
' WHERE ' . $where . $order_and_limit;
}
/**
@ -1712,93 +1589,6 @@ function PMA_executeMatchedRowQuery($matched_row_query)
return $result;
}
/**
* Extracts unique table names from table_references.
*
* @param string $table_references table_references
*
* @return array $table_names
*/
function PMA_getTableNamesFromTableReferences($table_references)
{
$table_names = array();
$parsed_data = PMA_SQP_parse($table_references);
$prev_term = array(
'data' => '',
'type' => ''
);
$on_encountered = false;
$qualifier_encountered = false;
$i = 0;
foreach ($parsed_data as $key => $term) {
// To skip first 'raw' key and other invalid keys.
if (! is_numeric($key)
|| ! isset($term['data'])
|| ! isset($term['type'])
) {
continue;
}
$add_to_table_names = true;
// Un-quote the data, if any.
if ($term['type'] == 'quote_backtick') {
$term['data'] = PMA_Util::unQuote($term['data']);
$term['type'] = 'alpha_identifier';
}
// New table name expected after 'JOIN' keyword.
if (preg_match('/\bJOIN\b/i', $term['data'])) {
$on_encountered = false;
}
// If term is a qualifier, set flag.
if ($term['type'] == 'punct_qualifier') {
$qualifier_encountered = true;
}
// Skip the JOIN conditions after 'ON' keyword.
if (preg_match('/\bON\b/i', $term['data'])) {
$on_encountered = true;
}
// If the word is not an 'identifier', skip it.
if ($term['type'] != 'alpha_identifier') {
$add_to_table_names = false;
}
// Skip table 'alias'.
if (preg_match('/\bAS\b/i', $prev_term['data'])
|| $prev_term['type'] == 'alpha_identifier'
) {
$add_to_table_names = false;
}
// Everything fine up to now, add name to list if 'unique'.
if ($add_to_table_names
&& ! $on_encountered
&& ! in_array($term['data'], $table_names)
) {
if (! $qualifier_encountered) {
$table_names[] = PMA_Util::backquote($term['data']);
$i++;
} else {
// If qualifier encountered, concatenate DB name and table name.
$table_names[$i-1] = $table_names[$i-1]
. '.'
. PMA_Util::backquote($term['data']);
$qualifier_encountered = false;
}
}
// Update previous term.
$prev_term = $term;
}
return $table_names;
}
/**
* Handles request for ROLLBACK.
*
@ -1853,37 +1643,25 @@ function PMA_handleRollbackRequest($sql_query)
*/
function PMA_checkIfRollbackPossible($sql_query)
{
// Supported queries.
$supported_queries = array(
'INSERT',
'UPDATE',
'DELETE',
'REPLACE'
);
$parser = new SqlParser\Parser($sql_query);
// Parse and Analyze the query.
$parsed_sql = PMA_SQP_parse($sql_query);
$analyzed_sql = PMA_SQP_analyze($parsed_sql);
$analyzed_sql_results = array(
'parsed_sql' => $parsed_sql,
'analyzed_sql' => $analyzed_sql
);
if (empty($parser->statements[0])) {
return false;
}
// Get the query type.
$query_type = (isset($analyzed_sql_results['analyzed_sql'][0]['querytype']))
? $analyzed_sql_results['analyzed_sql'][0]['querytype']
: '';
$statement = $parser->statements[0];
// Check if query is supported.
if (! in_array($query_type, $supported_queries)) {
if (!(($statement instanceof SqlParser\Statements\InsertStatement)
|| ($statement instanceof SqlParser\Statements\UpdateStatement)
|| ($statement instanceof SqlParser\Statements\DeleteStatement)
|| ($statement instanceof SqlParser\Statements\ReplaceStatement))
) {
return false;
}
// Get table_references from the query.
$table_references = PMA_getTableReferences($analyzed_sql_results);
$table_references = $table_references ? $table_references : '';
// Get table names from table_references.
$tables = PMA_getTableNamesFromTableReferences($table_references);
$tables = SqlParser\Utils\Query::getTables($statement);
// Check if each table is 'InnoDB'.
foreach ($tables as $table) {

View File

@ -134,7 +134,13 @@ function PMA_showEmptyResultMessageOrSetUniqueCondition($rows, $key_id,
list($unique_condition, $tmp_clause_is_unique)
= PMA_Util::getUniqueCondition(
$result[$key_id], count($meta), $meta, $rows[$key_id], true
$result[$key_id], // handle
count($meta), // fields_cnt
$meta, // fields_meta
$rows[$key_id], // row
true, // force_unique
false, // restrict_to_table
null // analyzed_sql_results
);
if (! empty($unique_condition)) {
@ -1803,7 +1809,13 @@ function PMA_setSessionForEditNext($one_where_clause)
// not a combination of all fields
list($unique_condition, $clause_is_unique)
= PMA_Util::getUniqueCondition(
$res, count($meta), $meta, $row, true
$res, // handle
count($meta), // fields_cnt
$meta, // fields_meta
$row, // row
true, // force_unique
false, // restrict_to_table
null // analyzed_sql_results
);
if (! empty($unique_condition)) {
$_SESSION['edit_next'] = $unique_condition;

View File

@ -244,15 +244,31 @@ if (!empty($submit_mult) && !empty($what)) {
}
if ($use_sql) {
/**
* Parse and analyze the query
*/
include_once 'libraries/parse_analyze.inc.php';
PMA_executeQueryAndSendQueryResponse(
$analyzed_sql_results, false, $db, $table, null, null, null,
false, null, null, null, $goto, $pmaThemeImage, null, null,
$query_type, $sql_query, $selected, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$db, // db
$table, // table
null, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
$query_type, // query_type
$sql_query, // sql_query
$selected, // selectedTables
null // complete_query
);
} elseif (!$run_parts) {
$GLOBALS['dbi']->selectDb($db);

View File

@ -95,7 +95,6 @@ function PMA_getHtmlForCreateNewColumn(
'length' => '',
'extracted_columnspec' => array(),
'submit_attribute' => null,
'analyzed_sql' => null,
'comments_map' => $comments_map,
'fields_meta' => null,
'is_backup' => true,
@ -107,12 +106,14 @@ function PMA_getHtmlForCreateNewColumn(
}
return PMA\Template::get('columns_definitions/table_fields_definitions')
->render(array(
->render(
array(
'is_backup' => true,
'fields_meta' => null,
'mimework' => $cfgRelation['mimework'],
'content_cells' => $content_cells
));
)
);
}
/**
* build the html for step 1.1 of normalization

View File

@ -9,136 +9,47 @@ if (! defined('PHPMYADMIN')) {
exit;
}
/**
*
*/
$GLOBALS['unparsed_sql'] = $sql_query;
$parsed_sql = PMA_SQP_parse($sql_query);
$analyzed_sql = PMA_SQP_analyze($parsed_sql);
// for bug 780516: now that we use case insensitive preg_match
// or flags from the analyser, do not put back the reformatted query
// into $sql_query, to make this kind of query work without
// capitalizing keywords:
//
// CREATE TABLE SG_Persons (
// id int(10) unsigned NOT NULL auto_increment,
// first varchar(64) NOT NULL default '',
// PRIMARY KEY (`id`)
// )
// Get details about the SQL query.
$analyzed_sql_results = SqlParser\Utils\Query::getAll($sql_query);
// Fills some variables from the analysed SQL
// A table has to be created, renamed, dropped:
// the navigation panel should be reloaded
$reload = isset($analyzed_sql[0]['queryflags']['reload']);
// TODO: Refactor this.
extract($analyzed_sql_results);
// check for drop database
$drop_database = isset($analyzed_sql[0]['queryflags']['drop_database']);
// If the targeted table (and database) are different than the ones that is
// currently browsed, edit `$db` and `$table` to match them so other elements
// (page headers, links, navigation panel) can be updated properly.
if (!empty($analyzed_sql_results['select_tables'])) {
// for the presence of EXPLAIN
$is_explain = isset($analyzed_sql[0]['queryflags']['is_explain']);
// for the presence of DELETE
$is_delete = isset($analyzed_sql[0]['queryflags']['is_delete']);
// for the presence of UPDATE, DELETE or INSERT|LOAD DATA|REPLACE
$is_affected = isset($analyzed_sql[0]['queryflags']['is_affected']);
// for the presence of REPLACE
$is_replace = isset($analyzed_sql[0]['queryflags']['is_replace']);
// for the presence of INSERT
$is_insert = isset($analyzed_sql[0]['queryflags']['is_insert']);
// for the presence of CHECK|ANALYZE|REPAIR|OPTIMIZE|CHECKSUM TABLE
$is_maint = isset($analyzed_sql[0]['queryflags']['is_maint']);
// for the presence of SHOW
$is_show = isset($analyzed_sql[0]['queryflags']['is_show']);
// for the presence of PROCEDURE ANALYSE
$is_analyse = isset($analyzed_sql[0]['queryflags']['is_analyse']);
// for the presence of INTO OUTFILE
$is_export = isset($analyzed_sql[0]['queryflags']['is_export']);
// for the presence of GROUP BY|HAVING|SELECT DISTINCT
$is_group = isset($analyzed_sql[0]['queryflags']['is_group']);
// for the presence of SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND
$is_func = isset($analyzed_sql[0]['queryflags']['is_func']);
// for the presence of SELECT COUNT
$is_count = isset($analyzed_sql[0]['queryflags']['is_count']);
// check for a real SELECT ... FROM
$is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
// the query contains a subquery
$is_subquery = isset($analyzed_sql[0]['queryflags']['is_subquery']);
// check for CALL
// Since multiple query execution is anyway handled,
// ignore the WHERE clause of the first sql statement
// which might contain a phrase like 'call '
if (isset($analyzed_sql[0]['queryflags']['is_procedure'])
&& empty($analyzed_sql[0]['where_clause'])
) {
$is_procedure = true;
} else {
$is_procedure = false;
}
// aggregates all the results into one array
$analyzed_sql_results = array(
"parsed_sql" => $parsed_sql,
"analyzed_sql" => $analyzed_sql,
"reload" => $reload,
"drop_database" => $drop_database,
"is_explain" => $is_explain,
"is_delete" => $is_delete,
"is_affected" => $is_affected,
"is_replace" => $is_replace,
"is_insert" => $is_insert,
"is_maint" => $is_maint,
"is_show" => $is_show,
"is_analyse" => $is_analyse,
"is_export" => $is_export,
"is_group" => $is_group,
"is_func" => $is_func,
"is_count" => $is_count,
"is_select" => $is_select,
"is_procedure" => $is_procedure,
"is_subquery" => $is_subquery
);
// If the query is a Select, extract the db and table names and modify
// $db and $table, to have correct page headers, links and left frame.
// db and table name may be enclosed with backquotes, db is optional,
// query may contain aliases.
/**
* @todo if there are more than one table name in the Select:
* - do not extract the first table name
* - do not show a table name in the page header
* - do not display the sub-pages links)
*/
if ($is_select) {
// Previous table and database name is stored to check if it changed.
$prev_db = $db;
if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name'])) {
$table = $analyzed_sql[0]['table_ref'][0]['table_true_name'];
}
if (isset($analyzed_sql[0]['table_ref'][0]['db'])
&& /*overload*/mb_strlen($analyzed_sql[0]['table_ref'][0]['db'])
) {
$db = $analyzed_sql[0]['table_ref'][0]['db'];
if (count($analyzed_sql_results['select_tables']) > 1) {
/**
* @todo if there are more than one table name in the Select:
* - do not extract the first table name
* - do not show a table name in the page header
* - do not display the sub-pages links)
*/
$table = '';
} else {
$db = $prev_db;
$table = $analyzed_sql_results['select_tables'][0][0];
if (!empty($analyzed_sql_results['select_tables'][0][1])) {
$db = $analyzed_sql_results['select_tables'][0][1];
}
}
// Don't change reload, if we already decided to reload in import
if (empty($reload) && empty($GLOBALS['is_ajax_request'])) {
$reload = ($db == $prev_db) ? 0 : 1;
// There is no point checking if a reload is required if we already decided
// to reload. Also, no reload is required for AJAX requests.
if ((empty($reload)) && (empty($GLOBALS['is_ajax_request']))) {
// NOTE: Database names are case-insensitive.
$reload = strcasecmp($db, $prev_db) != 0;
}
// Updating the array.
$analyzed_sql_results['reload'] = $reload;
}
?>
return $analyzed_sql_results;

View File

@ -1392,10 +1392,14 @@ class ExportSql extends ExportPlugin
return $this->_exportComment(__('in use') . '(' . $tmp_error . ')');
}
// Old mode is stored so it can be restored once exporting is done.
$old_mode = SqlParser\Context::$MODE;
$warning = '';
if ($result != false && ($row = $GLOBALS['dbi']->fetchRow($result))) {
$create_query = $row[1];
unset($row);
// Convert end of line chars to one that we want (note that MySQL
// doesn't return query it will accept in all cases)
if (/*overload*/mb_strpos($create_query, "(\r\n ")) {
@ -1420,11 +1424,13 @@ class ExportSql extends ExportPlugin
$create_query
);
}
// substitute aliases in create query
// Substitute aliases in `CREATE` query.
$create_query = $this->replaceWithAliases(
$create_query, $aliases, $db, $table, $flag
);
// One warning per view
// One warning per view.
if ($flag && $view) {
$warning = $this->_exportComment()
. $this->_exportComment(
@ -1435,7 +1441,8 @@ class ExportSql extends ExportPlugin
)
. $this->_exportComment();
}
// Should we use IF NOT EXISTS?
// Adding IF NOT EXISTS, if required.
if (isset($GLOBALS['sql_if_not_exists'])) {
$create_query = preg_replace(
'/^CREATE TABLE/',
@ -1444,14 +1451,15 @@ class ExportSql extends ExportPlugin
);
}
// Making the query MSSQL compatible.
if ($compat == 'MSSQL') {
$create_query = $this->_makeCreateTableMSSQLCompatible(
$create_query
);
}
// Drizzle (checked on 2011.03.13) returns ROW_FORMAT surrounded
// with quotes, which is not accepted by parser
// Drizzle (checked on 2011.03.13) returns `ROW_FORMAT`'s value
// surrounded with quotes, which is not accepted by parser
if (PMA_DRIZZLE) {
$create_query = preg_replace(
'/ROW_FORMAT=\'(\S+)\'/',
@ -1460,295 +1468,193 @@ class ExportSql extends ExportPlugin
);
}
//are there any constraints to cut out?
if (preg_match('@CONSTRAINT|KEY@', $create_query)) {
$has_constraints = 0;
$has_indexes = 0;
// Views have no constraints, indexes, etc. They do not require any
// analysis.
if (!$view) {
// Using appropriate quotes.
if (($compat === 'MSSQL') || ($sql_backquotes === '"')) {
SqlParser\Context::$MODE |= SqlParser\Context::ANSI_QUOTES;
}
/**
* Parser used for analysis.
* @var SqlParser
*/
$parser = new SqlParser\Parser($create_query);
}
if (!empty($parser->statements[0]->fields)) {
/**
* `CREATE TABLE` statement.
* @var SqlParser\Statements\SelectStatement
*/
$statement = $parser->statements[0];
/**
* Fragments containining definition of each constraint.
* @var array
*/
$constraints = array();
/**
* Fragments containining definition of each index.
* @var array
*/
$indexes = array();
/**
* Fragments containining definition of each FULLTEXT index.
* @var array
*/
$indexes_fulltext = array();
/**
* Fragments containining definition of each foreign key that will
* be dropped.
* @var array
*/
$dropped = array();
/**
* Fragment containining definition of the `AUTO_INCREMENT`.
* @var array
*/
$auto_increment = array();
// Scanning each field of the `CREATE` statement to fill the arrays
// above.
// If the field is used in any of the arrays above, it is removed
// from the original definition.
// Also, AUTO_INCREMENT attribute is removed.
foreach ($statement->fields as $key => $field) {
if ($field->isConstraint) {
// Creating the parts that add constraints.
$constraints[] = $field::build($field);
unset($statement->fields[$key]);
} elseif (!empty($field->key)) {
// Creating the parts that add indexes (must not be
// constraints).
if ($field->key->type === 'FULLTEXT KEY') {
$indexes_fulltext[] = $field->build($field);
} else {
$indexes[] = $field->build($field);
}
unset($statement->fields[$key]);
}
// Creating the parts that drop foreign keys.
if (!empty($field->key)) {
if ($field->key->type === 'FOREIGN KEY') {
$dropped[] = 'FOREIGN KEY ' . SqlParser\Context::escape($field->name);
}
unset($statement->fields[$key]);
}
// Dropping AUTO_INCREMENT.
if (!empty($field->options)) {
if ($field->options->has('AUTO_INCREMENT')) {
$auto_increment[] = $field::build($field);
$field->options->remove('AUTO_INCREMENT');
}
}
}
/**
* The header of the `ALTER` statement (`ALTER TABLE tbl`).
* @var string
*/
$alter_header = 'ALTER TABLE ' .
PMA_Util::backquoteCompat(
$table_alias, $compat, $sql_backquotes
);
/**
* The footer of the `ALTER` statement (usually ';')
* @var string
*/
$alter_footer = ';' . $crlf;
// Generating constraints-related query.
if (!empty($constraints)) {
$sql_constraints_query = $alter_header .
$crlf . ' ADD ' . implode(',' . $crlf . ' ADD ', $constraints) .
$alter_footer;
//if there are constraints
if (preg_match(
'@CONSTRAINT@',
$create_query
)) {
$has_constraints = 1;
// comments -> constraints for dumped tables
$sql_constraints = $this->generateComment(
$crlf, $sql_constraints, __('Constraints for dumped tables'),
__('Constraints for table'), $table_alias, $compat
);
$sql_constraints_query .= 'ALTER TABLE '
. PMA_Util::backquoteCompat(
$table_alias, $compat, $sql_backquotes
)
. $crlf;
$sql_constraints .= 'ALTER TABLE '
. PMA_Util::backquoteCompat(
$table_alias, $compat, $sql_backquotes
)
. $crlf;
$sql_drop_foreign_keys .= 'ALTER TABLE '
. PMA_Util::backquoteCompat(
$db_alias, $compat, $sql_backquotes
)
. '.'
. PMA_Util::backquoteCompat(
$table_alias, $compat, $sql_backquotes
)
. $crlf;
) . $sql_constraints_query;
}
//if there are indexes
// (look for KEY followed by whitespace to avoid matching
// keywords like PACK_KEYS)
if ($update_indexes_increments && preg_match(
'@KEY[\s]+@',
$create_query
)) {
$has_indexes = 1;
// comments -> indexes for dumped tables
// Generating indexes-related query.
$sql_indexes_query = '';
if (!empty($indexes)) {
$sql_indexes_query .= $alter_header .
$crlf . ' ADD ' . implode(',' . $crlf . ' ADD ', $indexes) .
$alter_footer;
}
if (!empty($indexes_fulltext)) {
// InnoDB supports one FULLTEXT index creation at a time.
// So FULLTEXT indexes are created one-by-one after other
// indexes where created.
$sql_indexes_query .= $alter_header .
' ADD ' . implode(
$alter_footer . $alter_header . ' ADD ', $indexes_fulltext
) . $alter_footer;
}
if ((!empty($indexes)) || (!empty($indexes_fulltext))) {
$sql_indexes = $this->generateComment(
$crlf, $sql_indexes, __('Indexes for dumped tables'),
__('Indexes for table'), $table_alias, $compat
);
$sql_indexes_query_start = 'ALTER TABLE '
. PMA_Util::backquoteCompat(
$table_alias, $compat, $sql_backquotes
);
$sql_indexes_query .= $sql_indexes_query_start;
$sql_indexes_start = 'ALTER TABLE '
. PMA_Util::backquoteCompat(
$table_alias, $compat, $sql_backquotes
);
$sql_indexes .= $sql_indexes_start;
) . $sql_indexes_query;
}
if ($update_indexes_increments && preg_match(
'@AUTO_INCREMENT@',
$create_query
)) {
// comments -> auto increments for dumped tables
// Generating drop foreign keys-related query.
if (!empty($dropped)) {
$sql_drop_foreign_keys = $alter_header .
$crlf . ' DROP ' . implode(',' . $crlf . ' DROP ', $dropped) .
$alter_footer;
}
// Generating auto-increment-related query.
if ((!empty($auto_increment)) && ($update_indexes_increments)) {
$sql_auto_increments_query = $alter_header .
$crlf . ' MODIFY ' . implode(',' . $crlf . ' MODIFY ', $auto_increment) .
', AUTO_INCREMENT=' . $statement->entityOptions->has('AUTO_INCREMENT')
. $alter_footer;
$sql_auto_increments = $this->generateComment(
$crlf, $sql_auto_increments,
__('AUTO_INCREMENT for dumped tables'),
__('AUTO_INCREMENT for table'), $table_alias, $compat
);
$sql_auto_increments .= 'ALTER TABLE '
. PMA_Util::backquoteCompat(
$table_alias, $compat, $sql_backquotes
)
. $crlf;
) . $sql_auto_increments_query;
}
// Split the query into lines, so we can easily handle it.
// We know lines are separated by $crlf (done few lines above).
$sql_lines = explode($crlf, $create_query);
$sql_count = count($sql_lines);
// lets find first line with constraints
$first_occur = -1;
for ($i = 0; $i < $sql_count; $i++) {
$sql_line = current(explode(' COMMENT ', $sql_lines[$i], 2));
if (preg_match(
'@[\s]+(CONSTRAINT|KEY)@',
$sql_line
) && $first_occur == -1) {
$first_occur = $i;
}
// Removing the `AUTO_INCREMENT` attribute from the `CREATE TABLE`
// too.
if (!empty($statement->entityOptions)) {
$statement->entityOptions->remove('AUTO_INCREMENT');
}
for ($k = 0; $k < $sql_count; $k++) {
if ($update_indexes_increments && preg_match(
'( AUTO_INCREMENT | AUTO_INCREMENT,| AUTO_INCREMENT$)',
$sql_lines[$k]
)) {
//creates auto increment code
$sql_auto_increments .= " MODIFY " . ltrim($sql_lines[$k]);
//removes auto increment code from table definition
$sql_lines[$k] = str_replace(
" AUTO_INCREMENT", "", $sql_lines[$k]
);
}
if (isset($GLOBALS['sql_auto_increment'])
&& $update_indexes_increments && preg_match(
'@[\s]+(AUTO_INCREMENT=)@',
$sql_lines[$k]
)) {
//adds auto increment value
$increment_value = /*overload*/mb_substr(
$sql_lines[$k],
/*overload*/mb_strpos($sql_lines[$k], "AUTO_INCREMENT")
);
$increment_value_array = explode(' ', $increment_value);
$sql_auto_increments .= $increment_value_array[0] . ";";
}
}
if ($sql_auto_increments != '') {
$sql_auto_increments = /*overload*/mb_substr(
$sql_auto_increments, 0, -1
) . ';';
}
// If we really found a constraint
if ($first_occur != $sql_count) {
// lets find first line
$sql_lines[$first_occur - 1] = preg_replace(
'@,$@',
'',
$sql_lines[$first_occur - 1]
);
$first = true;
$sql_index_ended = false;
for ($j = $first_occur; $j < $sql_count; $j++) {
//removes extra space at the beginning, if there is
$sql_lines[$j]=ltrim($sql_lines[$j], ' ');
//if it's a constraint
if (preg_match(
'@CONSTRAINT|FOREIGN[\s]+KEY@',
$sql_lines[$j]
)) {
if (! $first) {
$sql_constraints .= $crlf;
}
$posConstraint = /*overload*/mb_strpos(
$sql_lines[$j],
'CONSTRAINT'
);
$tmp_str = $sql_lines[$j];
if (! $sql_backquotes) {
$tmp_str = preg_replace_callback(
'/REFERENCES[\s]([\S]*)[\s]\(([\S]*)\)/',
function ($matches) {
global $compat, $sql_backquotes;
$refTable = PMA_Util::backquoteCompat(
$matches[1], $compat, $sql_backquotes
);
$refColumn = PMA_Util::backquoteCompat(
$matches[2], $compat, $sql_backquotes
);
return 'REFERENCES ' . $refTable . ' (' . $refColumn . ')';
},
$tmp_str
);
}
if ($posConstraint === false) {
$tmp_str = preg_replace(
'/(FOREIGN[\s]+KEY)/',
' ADD \1',
$tmp_str
);
$sql_constraints_query .= $tmp_str;
$sql_constraints .= $tmp_str;
} else {
$tmp_str = preg_replace(
'/(CONSTRAINT)/',
' ADD \1',
$tmp_str
);
$sql_constraints_query .= $tmp_str;
$sql_constraints .= $tmp_str;
preg_match(
'/(CONSTRAINT)([\s])([\S]*)([\s])/',
$sql_lines[$j],
$matches
);
if (! $first) {
$sql_drop_foreign_keys .= ', ';
}
$sql_drop_foreign_keys .= 'DROP FOREIGN KEY '
. $matches[3];
}
$first = false;
} else if ($update_indexes_increments && preg_match(
'@KEY[\s]+@',
$sql_lines[$j]
)) {
//if it's a index
// if index query was terminated earlier
if ($sql_index_ended) {
// start a new query with ALTER TABLE
$sql_indexes .= $sql_indexes_start;
$sql_indexes_query .= $sql_indexes_query_start;
$sql_index_ended = false;
}
$tmp_str = $crlf . " ADD " . $sql_lines[$j];
$sql_indexes_query .= $tmp_str;
$sql_indexes .= $tmp_str;
// InnoDB supports one FULLTEXT index creation at a time
// So end the query and start over
if ($update_indexes_increments && preg_match(
'@FULLTEXT KEY[\s]+@',
$sql_lines[$j]
)) {
//removes superfluous comma at the end
$sql_indexes = rtrim($sql_indexes, ',');
$sql_indexes_query = rtrim($sql_indexes_query, ',');
// add ending semicolon
$sql_indexes .= ';' . $crlf;
$sql_indexes_query .= ';' . $crlf;
$sql_index_ended = true;
}
} else {
break;
}
}
//removes superfluous comma at the end
$sql_indexes = rtrim($sql_indexes, ',');
$sql_indexes_query = rtrim($sql_indexes_query, ',');
//removes superfluous semicolon at the end
if ($has_constraints == 1) {
$sql_constraints .= ';' . $crlf;
$sql_constraints_query .= ';';
}
if ($has_indexes == 1 && ! $sql_index_ended) {
$sql_indexes .= ';' . $crlf;
$sql_indexes_query .= ';';
}
//remove indexes and constraints from the $create_query
$create_query = implode(
$crlf,
array_slice($sql_lines, 0, $first_occur)
)
. $crlf
. implode(
$crlf,
array_slice($sql_lines, $j, $sql_count - 1)
);
unset($sql_lines);
}
// Rebuilding the query.
$create_query = $statement->build();
}
$schema_create .= $create_query;
}
// remove a possible "AUTO_INCREMENT = value" clause
// that could be there starting with MySQL 5.0.24
// in Drizzle it's useless as it contains the value given at table
// creation time
if (preg_match('/AUTO_INCREMENT\s*=\s*([0-9])+/', $schema_create)) {
if ($compat == 'MSSQL' || $auto_increment == '') {
$auto_increment = ' ';
}
$schema_create = preg_replace(
'/\sAUTO_INCREMENT\s*=\s*([0-9])+\s/',
$auto_increment,
$schema_create
);
}
$GLOBALS['dbi']->freeResult($result);
// Restoring old mode.
SqlParser\Context::$MODE = $old_mode;
return $warning . $schema_create . ($add_semicolon ? ';' . $crlf : '');
} // end of the 'getTableDef()' function
@ -2339,10 +2245,13 @@ class ExportSql extends ExportPlugin
list($tmp_unique_condition, $tmp_clause_is_unique)
= PMA_Util::getUniqueCondition(
$result,
$fields_cnt,
$fields_meta,
$row
$result, // handle
$fields_cnt, // fields_cnt
$fields_meta, // fields_meta
$row, // row
false, // force_unique
false, // restrict_to_table
null // analyzed_sql_results
);
$insert_line .= ' WHERE ' . $tmp_unique_condition;
unset($tmp_unique_condition, $tmp_clause_is_unique);
@ -2538,216 +2447,164 @@ class ExportSql extends ExportPlugin
$sql_query, $aliases, $db, $table = '', &$flag = null
) {
$flag = false;
// Return original sql query if no aliases are provided.
if (!is_array($aliases) || empty($aliases) || empty($sql_query)) {
/**
* The parser of this query.
* @var SqlParser\Parser $parser
*/
$parser = new SqlParser\Parser($sql_query);
if (empty($parser->statements[0])) {
return $sql_query;
}
$supported_query_types = array(
'CREATE' => true,
);
$supported_query_ons = array(
'TABLE' => true,
'VIEW' => true,
'TRIGGER' => true,
'FUNCTION' => true,
'PROCEDURE' => true
);
$identifier_types = array(
'alpha_identifier',
'quote_backtick'
);
$query_type = '';
$query_on = '';
// Adjustment value for each pos value
// of token after replacement
$offset = 0;
$open_braces = 0;
$in_create_table_fields = false;
// flag to force end query parsing
$query_end = false;
// Convert all line feeds to Unix style
$sql_query = str_replace("\r\n", "\n", $sql_query);
$sql_query = str_replace("\r", "\n", $sql_query);
$tokens = PMA_SQP_parse($sql_query);
$ref_seen = false;
$ref_table_seen = false;
$old_table = $table;
$on_seen = false;
$size = $tokens['len'];
for ($i = 0; $i < $size && !$query_end; $i++) {
$type = $tokens[$i]['type'];
$data = $tokens[$i]['data'];
$data_next = isset($tokens[$i+1]['data'])
? $tokens[$i+1]['data'] : '';
$data_prev = ($i > 0) ? $tokens[$i-1]['data'] : '';
$d_unq = PMA_Util::unQuote($data);
$d_unq_next = PMA_Util::unQuote($data_next);
$d_unq_prev = PMA_Util::unQuote($data_prev);
$d_upper = /*overload*/mb_strtoupper($d_unq);
$d_upper_next = /*overload*/mb_strtoupper($d_unq_next);
$d_upper_prev = /*overload*/mb_strtoupper($d_unq_prev);
$pos = $tokens[$i]['pos'] + $offset;
if ($type === 'alpha_reservedWord') {
if ($query_type === ''
&& !empty($supported_query_types[$d_upper])
) {
$query_type = $d_upper;
} elseif ($query_on === ''
&& !empty($supported_query_ons[$d_upper])
) {
$query_on = $d_upper;
/**
* The statement that represents the query.
* @var SqlParser\Statements\CreateStatement $statement
*/
$statement = $parser->statements[0];
/**
* Old database name.
* @var string $old_database
*/
$old_database = $db;
// Replacing aliases in `CREATE TABLE` statement.
if ($statement->options->has('TABLE')) {
// Extracting the name of the old database and table from the
// statement to make sure the parameters are corect.
if (!empty($statement->name->database)) {
$old_database = $statement->name->database;
}
/**
* Old table name.
* @var string $old_table
*/
$old_table = $statement->name->table;
// Finding the aliased database name.
// The database might be empty so we have to add a few checks.
$new_database = null;
if (!empty($statement->name->database)) {
$new_database = $statement->name->database;
if (!empty($aliases[$old_database]['alias'])) {
$new_database = $aliases[$old_database]['alias'];
}
}
// CREATE TABLE - Alias replacement
if ($query_type === 'CREATE' && $query_on === 'TABLE') {
// replace create table name
if (!$in_create_table_fields
&& in_array($type, $identifier_types)
&& !empty($aliases[$db]['tables'][$table]['alias'])
) {
$sql_query = $this->substituteAlias(
$sql_query, $data,
$aliases[$db]['tables'][$table]['alias'],
$pos, $offset
);
$flag = true;
} elseif ($type === 'punct_bracket_open_round') {
// CREATE TABLE fields started
if (!$in_create_table_fields) {
$in_create_table_fields = true;
}
$open_braces++;
} elseif ($type === 'punct_bracket_close_round') {
// end our parsing after last )
// no columns appear after that
if ($in_create_table_fields && $open_braces === 0) {
$query_end = true;
}
// End of Foreign key reference
if ($ref_seen) {
$ref_seen = $ref_table_seen = false;
$table = $old_table;
}
$open_braces--;
// handles Foreign key references
} elseif ($type === 'alpha_reservedWord'
&& $d_upper === 'REFERENCES'
) {
$ref_seen = true;
} elseif (in_array($type, $identifier_types)
&& $ref_seen === true && !$ref_table_seen
) {
$table = $d_unq;
$ref_table_seen = true;
if (!empty($aliases[$db]['tables'][$table]['alias'])) {
$sql_query = $this->substituteAlias(
$sql_query, $data,
$aliases[$db]['tables'][$table]['alias'],
$pos, $offset
);
// Finding the aliases table name.
$new_table = $old_table;
if (!empty($aliases[$old_database]['tables'][$old_table]['alias'])) {
$new_table = $aliases[$old_database]['tables'][$old_table]['alias'];
}
// Replacing new values.
if (($statement->name->database !== $new_database)
|| ($statement->name->table !== $new_table)
) {
$statement->name->database = $new_database;
$statement->name->table = $new_table;
$statement->name->expr = null; // Force rebuild.
$flag = true;
}
foreach ($statement->fields as $field) {
// Column name.
if (!empty($field->type)) {
if (!empty($aliases[$old_database]['tables'][$old_table]['columns'][$field->name])) {
$field->name = $aliases[$old_database]['tables']
[$old_table]['columns'][$field->name];
$flag = true;
}
// Replace column names
} elseif (in_array($type, $identifier_types)
&& !empty($aliases[$db]['tables'][$table]['columns'][$d_unq])
) {
$sql_query = $this->substituteAlias(
$sql_query, $data,
$aliases[$db]['tables'][$table]['columns'][$d_unq],
$pos, $offset
);
$flag = true;
}
// CREATE TRIGGER - Alias replacement
} elseif ($query_type === 'CREATE' && $query_on === 'TRIGGER') {
// Skip till 'ON' in encountered
if (!$on_seen && $type === 'alpha_reservedWord'
&& $d_upper === 'ON'
) {
$on_seen = true;
} elseif ($on_seen && in_array($type, $identifier_types)) {
if (!$ref_table_seen
&& !empty($aliases[$db]['tables'][$d_unq]['alias'])
) {
$ref_table_seen = true;
$sql_query = $this->substituteAlias(
$sql_query, $data,
$aliases[$db]['tables'][$d_unq]['alias'],
$pos, $offset
);
$flag = true;
} else {
// search for identifier alias
$alias = $this->getAlias($aliases, $d_unq);
if (!empty($alias)) {
$sql_query = $this->substituteAlias(
$sql_query, $data, $alias, $pos, $offset
);
// Key's columns.
if (!empty($field->key)) {
foreach ($field->key->columns as $key => $column) {
if (!empty($aliases[$old_database]['tables'][$old_table]['columns'][$column])) {
$field->key->columns[$key] = $aliases[$old_database]
['tables'][$old_table]['columns'][$column];
$flag = true;
}
}
}
// CREATE PROCEDURE|FUNCTION|VIEW - Alias replacement
} elseif ($query_type === 'CREATE'
&& ($query_on === 'FUNCTION'
|| $query_on === 'PROCEDURE'
|| $query_on === 'VIEW')
) {
// LANGUAGE SQL | (READS|MODIFIES) SQL DATA
// characteristics are skipped
if ($type === 'alpha_identifier'
&& (($d_upper === 'LANGUAGE' && $d_upper_next === 'SQL')
|| ($d_upper === 'DATA' && $d_upper_prev === 'SQL'))
) {
continue;
// No need to process further in case of VIEW
// when 'WITH' keyword has been detected
} elseif ($query_on === 'VIEW'
&& $type === 'alpha_reservedWord' && $d_upper === 'WITH'
) {
$query_end = true;
} elseif (in_array($type, $identifier_types)) {
// search for identifier alias
$alias = $this->getAlias($aliases, $d_unq);
if (!empty($alias)) {
$sql_query = $this->substituteAlias(
$sql_query, $data, $alias, $pos, $offset
);
// References.
if (!empty($field->references)) {
$ref_table = $field->references->table;
// Replacing table.
if (!empty($aliases[$old_database]['tables'][$ref_table]['alias'])) {
$field->references->table = $aliases[$old_database]['tables'][$ref_table]['alias'];
$flag = true;
};
}
// Replacing column names.
foreach ($field->references->columns as $key => $column) {
if (!empty($aliases[$old_database]['tables'][$ref_table]['columns'][$column])) {
$field->references->columns[$key] = $aliases[$old_database]['tables'][$ref_table]['columns'][$column];
$flag = true;
}
}
}
}
} elseif ($statement->options->has('TRIGGER')) {
// Extracting the name of the old database and table from the
// statement to make sure the parameters are corect.
if (!empty($statement->table->database)) {
$old_database = $statement->table->database;
}
/**
* Old table name.
* @var string $old_table
*/
$old_table = $statement->table->table;
if (!empty($aliases[$old_database]['tables'][$old_table]['alias'])) {
$statement->table->table = $aliases[$old_database]['tables'][$old_table]['alias'];
$statement->table->expr = null; // Force rebuild.
$flag = true;
}
}
if (($statement->options->has('TRIGGER'))
|| ($statement->options->has('PROCEDURE'))
|| ($statement->options->has('FUNCTION'))
|| ($statement->options->has('VIEW'))
) {
// Repalcing the body.
for ($i = 0, $count = count($statement->body); $i < $count; ++$i) {
/**
* Token parsed at this moment.
* @var Token $token
*/
$token = $statement->body[$i];
// Replacing only symbols (that are not variables) and unknown
// identifiers.
if ((($token->type === SqlParser\Token::TYPE_SYMBOL)
&& (!($token->flags & SqlParser\Token::FLAG_SYMBOL_VARIABLE)))
|| ((($token->type === SqlParser\Token::TYPE_KEYWORD)
&& (!($token->flags & SqlParser\Token::FLAG_KEYWORD_RESERVED)))
|| ($token->type === SqlParser\Token::TYPE_NONE))
) {
$alias = $this->getAlias($aliases, $token->value);
if (!empty($alias)) {
// Replacing the token.
$token->token = SqlParser\Context::escape($alias);
$flag = true;
}
}
}
}
return $sql_query;
}
/**
* substitutes alias in query at given position
* Note: pos is the value from PMA_SQP_parse() + offset
*
* @param string $sql_query the SQL query
* @param string $data the data to be replaced
* @param string $alias the replacement
* @param string $pos the position of alias
* @param string &$offset the change in pos occurred after substitution
*
* @return string replaced query with alias
*/
public function substituteAlias($sql_query, $data, $alias, $pos, &$offset = null)
{
if (!empty($GLOBALS['sql_backquotes'])) {
$alias = PMA_Util::backquote($alias);
}
$alias_len = /*overload*/mb_strlen($alias);
$data_len = /*overload*/mb_strlen($data);
if (isset($offset)) {
$offset += ($alias_len - $data_len);
}
$sql_query = substr_replace(
$sql_query, $alias, $pos - $data_len, $data_len
);
return $sql_query;
return $statement->build();
}
/**

View File

@ -45,8 +45,6 @@ abstract class SQLTransformationsPlugin extends TransformationsPlugin
{
// see PMA_highlightSQL()
$result = PMA_Util::formatSql($buffer);
// Need to clear error state not to break subsequent queries display.
PMA_SQP_resetError();
return $result;
}

View File

@ -734,15 +734,18 @@ function PMA_getForeigners($db, $table, $column = '', $source = 'both')
if (($source == 'both' || $source == 'foreign') && /*overload*/mb_strlen($table)
) {
$showCreateTableQuery = 'SHOW CREATE TABLE '
. PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table);
$show_create_table = $GLOBALS['dbi']->fetchValue(
$showCreateTableQuery, 0, 1
'SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.'
. PMA_Util::backquote($table),
0, 1
);
if ($show_create_table) {
$analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
$foreign['foreign_keys_data'] = $analyzed_sql[0]['foreign_keys'];
$parser = new SqlParser\Parser($show_create_table);
/**
* @var CreateStatement $stmt
*/
$stmt = $parser->statements[0];
$foreign['foreign_keys_data'] = SqlParser\Utils\Table::getForeignKeys($stmt);
}
}

View File

@ -220,16 +220,21 @@ function PMA_RTN_getRowForList($routine, $rowclass = '')
// Check if the routine has any input parameters. If it does,
// we will show a dialog to get values for these parameters,
// otherwise we can execute it directly.
$params = PMA_RTN_parseAllParameters(
PMA_SQP_parse(
$GLOBALS['dbi']->getDefinition(
$db,
$routine['type'],
$routine['name']
)
),
$routine['type']
$parser = new SqlParser\Parser(
$GLOBALS['dbi']->getDefinition(
$db,
$routine['type'],
$routine['name']
)
);
/**
* @var CreateStatement $stmt
*/
$stmt = $parser->statements[0];
$params = SqlParser\Utils\Routine::getParameters($stmt);
if ($routine !== false) {
if (PMA_Util::currentUserHasPrivilege('EXECUTE', $db)) {
$execute_action = 'execute_routine';

View File

@ -9,6 +9,8 @@ if (! defined('PHPMYADMIN')) {
exit;
}
require_once 'libraries/Template.class.php';
/**
* Sets required globals
*
@ -79,193 +81,6 @@ function PMA_RTN_main($type)
}
} // end PMA_RTN_main()
/**
* This function parses a string containing one parameter of a routine,
* as returned by PMA_RTN_parseAllParameters() and returns an array containing
* the information about this parameter.
*
* @param string $value A string containing one parameter of a routine
*
* @return array Parsed information about the input parameter
*/
function PMA_RTN_parseOneParameter($value)
{
global $param_directions;
$retval = array(0 => '',
1 => '',
2 => '',
3 => '',
4 => '');
$parsed_param = PMA_SQP_parse($value);
$pos = 0;
if (in_array(
/*overload*/mb_strtoupper($parsed_param[$pos]['data']),
$param_directions
)) {
$retval[0] = /*overload*/mb_strtoupper($parsed_param[0]['data']);
$pos++;
}
if ($parsed_param[$pos]['type'] == 'alpha_identifier'
|| $parsed_param[$pos]['type'] == 'quote_backtick'
) {
$retval[1] = PMA_Util::unQuote(
$parsed_param[$pos]['data']
);
$pos++;
}
$depth = 0;
$param_length = '';
$param_opts = array();
for ($i = $pos; $i < $parsed_param['len']; $i++) {
if (($parsed_param[$i]['type'] == 'alpha_columnType'
|| $parsed_param[$i]['type'] == 'alpha_functionName') && $depth == 0
) {
$retval[2] = /*overload*/mb_strtoupper($parsed_param[$i]['data']);
} else if ($parsed_param[$i]['type'] == 'punct_bracket_open_round'
&& $depth == 0
) {
$depth = 1;
} else if ($parsed_param[$i]['type'] == 'punct_bracket_close_round'
&& $depth == 1
) {
$depth = 0;
} else if ($depth == 1) {
$param_length .= $parsed_param[$i]['data'];
} else if ($parsed_param[$i]['type'] == 'alpha_reservedWord'
&& /*overload*/mb_strtoupper($parsed_param[$i]['data']) == 'CHARSET'
&& $depth == 0
) {
if ($parsed_param[$i+1]['type'] == 'alpha_charset'
|| $parsed_param[$i+1]['type'] == 'alpha_identifier'
) {
$param_opts[] = /*overload*/mb_strtolower(
$parsed_param[$i+1]['data']
);
}
} else if ($parsed_param[$i]['type'] == 'alpha_columnAttrib'
&& $depth == 0
) {
$param_opts[] = /*overload*/mb_strtoupper($parsed_param[$i]['data']);
}
}
$retval[3] = $param_length;
sort($param_opts);
$retval[4] = implode(' ', $param_opts);
return $retval;
} // end PMA_RTN_parseOneParameter()
/**
* This function looks through the contents of a parsed
* SHOW CREATE [PROCEDURE | FUNCTION] query and extracts
* information about the routine's parameters.
*
* @param array $parsed_query Parsed query, returned by by PMA_SQP_parse()
* @param string $routine_type Routine type: 'PROCEDURE' or 'FUNCTION'
*
* @return array Information about the parameters of a routine.
*/
function PMA_RTN_parseAllParameters($parsed_query, $routine_type)
{
$retval = array();
$retval['num'] = 0;
if ($parsed_query) {
// First get the list of parameters from the query
$buffer = '';
$params = array();
$fetching = false;
$depth = 0;
for ($i = 0; $i < $parsed_query['len']; $i++) {
if ($parsed_query[$i]['type'] == 'alpha_reservedWord'
&& $parsed_query[$i]['data'] == $routine_type
) {
$fetching = true;
} else if ($fetching == true
&& $parsed_query[$i]['type'] == 'punct_bracket_open_round'
) {
$depth++;
if ($depth > 1) {
$buffer .= $parsed_query[$i]['data'] . ' ';
}
} else if ($fetching == true
&& $parsed_query[$i]['type'] == 'punct_bracket_close_round'
) {
$depth--;
if ($depth > 0) {
$buffer .= $parsed_query[$i]['data'] . ' ';
} else {
break;
}
} else if ($parsed_query[$i]['type'] == 'punct_listsep' && $depth == 1) {
$params[] = $buffer;
$retval['num']++;
$buffer = '';
} else if ($fetching == true && $depth > 0) {
$buffer .= $parsed_query[$i]['data'] . ' ';
}
}
if (! empty($buffer)) {
$params[] = $buffer;
$retval['num']++;
}
// Now parse each parameter individually
foreach ($params as $key => $value) {
list($retval['dir'][],
$retval['name'][],
$retval['type'][],
$retval['length'][],
$retval['opts'][]) = PMA_RTN_parseOneParameter($value);
}
}
// Since some indices of $retval may be still undefined, we fill
// them each with an empty array to avoid E_ALL errors in PHP.
foreach (array('dir', 'name', 'type', 'length', 'opts') as $key => $index) {
if (! isset($retval[$index])) {
$retval[$index] = array();
}
}
return $retval;
} // end PMA_RTN_parseAllParameters()
/**
* This function looks through the contents of a parsed
* SHOW CREATE [PROCEDURE | FUNCTION] query and extracts
* information about the routine's definer.
*
* @param array $parsed_query Parsed query, returned by PMA_SQP_parse()
*
* @return string The definer of a routine.
*/
function PMA_RTN_parseRoutineDefiner($parsed_query)
{
$retval = '';
$fetching = false;
for ($i = 0; $i < $parsed_query['len']; $i++) {
if ($parsed_query[$i]['type'] == 'alpha_reservedWord'
&& $parsed_query[$i]['data'] == 'DEFINER'
) {
$fetching = true;
} else if ($fetching == true
&& $parsed_query[$i]['type'] != 'quote_backtick'
&& /*overload*/mb_substr($parsed_query[$i]['type'], 0, 5) != 'punct'
) {
break;
} else if ($fetching == true
&& $parsed_query[$i]['type'] == 'quote_backtick'
) {
$retval .= PMA_Util::unQuote(
$parsed_query[$i]['data']
);
} else if ($fetching == true && $parsed_query[$i]['type'] == 'punct_user') {
$retval .= $parsed_query[$i]['data'];
}
}
return $retval;
} // end PMA_RTN_parseRoutineDefiner()
/**
* Handles editor requests for adding or editing an item
*
@ -694,21 +509,29 @@ function PMA_RTN_getDataFromName($name, $type, $all = true)
// Get required data
$retval['item_name'] = $routine['SPECIFIC_NAME'];
$retval['item_type'] = $routine['ROUTINE_TYPE'];
$parsed_query = PMA_SQP_parse(
$parser = new SqlParser\Parser(
$GLOBALS['dbi']->getDefinition(
$db,
$routine['ROUTINE_TYPE'],
$routine['SPECIFIC_NAME']
)
);
$params = PMA_RTN_parseAllParameters($parsed_query, $routine['ROUTINE_TYPE']);
$retval['item_num_params'] = $params['num'];
$retval['item_param_dir'] = $params['dir'];
$retval['item_param_name'] = $params['name'];
$retval['item_param_type'] = $params['type'];
$retval['item_param_length'] = $params['length'];
$retval['item_param_opts_num'] = $params['opts'];
$retval['item_param_opts_text'] = $params['opts'];
/**
* @var CreateStatement $stmt
*/
$stmt = $parser->statements[0];
$params = SqlParser\Utils\Routine::getParameters($stmt);
$retval['item_num_params'] = $params['num'];
$retval['item_param_dir'] = $params['dir'];
$retval['item_param_name'] = $params['name'];
$retval['item_param_type'] = $params['type'];
$retval['item_param_length'] = $params['length'];
$retval['item_param_length_arr'] = $params['length_arr'];
$retval['item_param_opts_num'] = $params['opts'];
$retval['item_param_opts_text'] = $params['opts'];
// Get extra data
if (!$all) {
@ -720,55 +543,24 @@ function PMA_RTN_getDataFromName($name, $type, $all = true)
} else {
$retval['item_type_toggle'] = 'FUNCTION';
}
$retval['item_returntype'] = '';
$retval['item_returnlength'] = '';
$retval['item_returntype'] = '';
$retval['item_returnlength'] = '';
$retval['item_returnopts_num'] = '';
$retval['item_returnopts_text'] = '';
if (! empty($routine['DTD_IDENTIFIER'])) {
if (/*overload*/mb_strlen($routine['DTD_IDENTIFIER']) > 63) {
// If the DTD_IDENTIFIER string from INFORMATION_SCHEMA is
// at least 64 characters, then it may actually have been
// chopped because that column is a varchar(64), so we will
// parse the output of SHOW CREATE query to get accurate
// information about the return variable.
$dtd = '';
$fetching = false;
for ($i = 0; $i < $parsed_query['len']; $i++) {
if ($parsed_query[$i]['type'] == 'alpha_reservedWord'
&& /*overload*/mb_strtoupper($parsed_query[$i]['data']) == 'RETURNS'
) {
$fetching = true;
} else if ($fetching == true
&& $parsed_query[$i]['type'] == 'alpha_reservedWord'
) {
// We will not be looking for options such as UNSIGNED
// or ZEROFILL because there is no way that a numeric
// field's DTD_IDENTIFIER can be longer than 64
// characters. We can safely assume that the return
// datatype is either ENUM or SET, so we only look
// for CHARSET.
$word = /*overload*/mb_strtoupper($parsed_query[$i]['data']);
if ($word == 'CHARSET'
&& ($parsed_query[$i+1]['type'] == 'alpha_charset'
|| $parsed_query[$i+1]['type'] == 'alpha_identifier')
) {
$dtd .= $word . ' ' . $parsed_query[$i + 1]['data'];
}
break;
} else if ($fetching == true) {
$dtd .= $parsed_query[$i]['data'] . ' ';
}
}
$routine['DTD_IDENTIFIER'] = $dtd;
$options = array();
foreach ($stmt->return->options->options as $opt) {
$options[] = is_string($opt) ? $opt : $opt['value'];
}
$returnparam = PMA_RTN_parseOneParameter($routine['DTD_IDENTIFIER']);
$retval['item_returntype'] = $returnparam[2];
$retval['item_returnlength'] = $returnparam[3];
$retval['item_returnopts_num'] = $returnparam[4];
$retval['item_returnopts_text'] = $returnparam[4];
$retval['item_returntype'] = $stmt->return->name;
$retval['item_returnlength'] = implode(',', $stmt->return->size);
$retval['item_returnopts_num'] = implode(' ', $options);
$retval['item_returnopts_text'] = implode(' ', $options);
}
$retval['item_definer'] = PMA_RTN_parseRoutineDefiner($parsed_query);
$retval['item_definer'] = $stmt->options->has('DEFINER');
$retval['item_definition'] = $routine['ROUTINE_DEFINITION'];
$retval['item_isdeterministic'] = '';
if ($routine['IS_DETERMINISTIC'] == 'YES') {
@ -1756,24 +1548,18 @@ function PMA_RTN_getExecuteForm($routine)
}
$retval .= "<td class='nowrap'>\n";
if (in_array($routine['item_param_type'][$i], array('ENUM', 'SET'))) {
$tokens = PMA_SQP_parse($routine['item_param_length'][$i]);
if ($routine['item_param_type'][$i] == 'ENUM') {
$input_type = 'radio';
} else {
$input_type = 'checkbox';
}
for ($j = 0; $j < $tokens['len']; $j++) {
if ($tokens[$j]['type'] != 'punct_listsep') {
$tokens[$j]['data'] = htmlentities(
PMA_Util::unquote($tokens[$j]['data']),
ENT_QUOTES
);
$retval .= "<input name='params["
. $routine['item_param_name'][$i] . "][]' "
. "value='" . $tokens[$j]['data'] . "' type='"
. $input_type . "' />"
. $tokens[$j]['data'] . "<br />\n";
}
foreach ($routine['item_param_length_arr'][$i] as $value) {
$value = htmlentities(PMA_Util::unquote($value), ENT_QUOTES);
$retval .= "<input name='params["
. $routine['item_param_name'][$i] . "][]' "
. "value='" . $value . "' type='"
. $input_type . "' />"
. $value . "<br />\n";
}
} else if (in_array(
/*overload*/mb_strtolower($routine['item_param_type'][$i]),

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,68 @@
<?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')) {
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;
}
}
// Initializing the autoloader.
return AutoloaderInit::getLoader(
array(
'SqlParser\\' => array(dirname(__FILE__) . '/src'),
)
);

View File

@ -0,0 +1,60 @@
<?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;
/**
* A component (of a statement) is a part of a statement that is common to
* multiple query types.
*
* @category Components
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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.
*
* @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.
return null;
}
/**
* 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.
*
* @return string
*/
public static function build($component)
{
// This method should be abstract, but it can't be both static and
// abstract.
return null;
}
}

View File

@ -0,0 +1,200 @@
<?php
/**
* Parses a reference to a field.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a reference to a field.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class AlterOperation extends Component
{
/**
* All alter operations.
*
* @var array
*/
public static $OPTIONS = array(
'ADD' => 3,
'ALTER' => 3,
'ANALYZE' => 3,
'CHANGE' => 3,
'CHECK' => 3,
'COALESCE' => 3,
'CONVERT' => 3,
'DISABLE' => 3,
'DISCARD' => 3,
'DROP' => 3,
'ENABLE' => 3,
'IMPORT' => 3,
'MODIFY' => 3,
'OPTIMIZE' => 3,
'ORDER' => 3,
'PARTITION' => 3,
'REBUILD' => 3,
'REMOVE' => 3,
'RENAME' => 3,
'REORGANIZE' => 3,
'REPAIR' => 3,
'COLUMN' => 4,
'CONSTRAINT' => 4,
'DEFAULT' => 4,
'TO' => 4,
'BY' => 4,
'FOREIGN' => 4,
'FULLTEXT' => 4,
'KEY' => 4,
'KEYS' => 4,
'PARTITIONING' => 4,
'PRIMARY KEY' => 4,
'SPATIAL' => 4,
'TABLESPACE' => 4,
'INDEX' => 4,
'DEFAULT CHARACTER SET' => array(5, 'var'),
'DEFAULT CHARSET' => array(5, 'var'),
'COLLATE' => array(6, 'var'),
);
/**
* 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 = 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)) {
if ($state !== 2) {
// State 2 parses the unknown part which must include whitespaces as well.
continue;
}
}
if ($state === 0) {
$ret->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$state = 1;
} elseif ($state === 1) {
$ret->field = Expression::parse(
$parser,
$list,
array(
'noAlias' => true,
'noBrackets' => true,
)
);
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 === ',') {
break;
}
}
$ret->unknown[] = $token;
}
}
--$list->idx;
return $ret;
}
/**
* @param AlterOperation $component The component to be built.
*
* @return string
*/
public static function build($component)
{
$ret = OptionsArray::build($component->options) . ' ';
if (!empty($component->field)) {
$ret .= Expression::build($component->field) . ' ';
}
$ret .= TokensList::build($component->unknown);
return $ret;
}
}

View File

@ -0,0 +1,128 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Array2d extends Component
{
/**
* An array with the values of the row to be inserted.
*
* @var array
*/
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 Array2d
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new Array2d();
$value = '';
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ------------------------[ ( ]-----------------------> 1
*
* 1 ----------------------[ value ]---------------------> 2
*
* 2 ------------------------[ , ]-----------------------> 1
* 2 ------------------------[ ) ]-----------------------> 3
*
* 3 ---------------------[ options ]--------------------> 4
*
* @var int
*/
$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 ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
$state = 1;
continue;
} elseif ($token->value === ',') {
if ($state !== 3) {
$expr->values[] = $value;
$value = '';
$state = 1;
}
continue;
} elseif ($token->value === ')') {
$state = 3;
$expr->values[] = $value;
$ret[] = $expr;
$value = '';
$expr = new Array2d();
continue;
}
// No other operator is expected.
break;
}
if ($state === 1) {
$value .= $token->value;
$state = 2;
}
}
// Last iteration was not saved.
if (!empty($expr->values)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
}

View File

@ -0,0 +1,146 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new ArrayObj();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ ( ]------------------------> 1
*
* 1 ------------------[ array element ]-----------------> 2
*
* 2 ------------------------[ , ]-----------------------> 1
* 2 ------------------------[ ) ]-----------------------> -1
*
* @var int
*/
$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 !== '(')) {
$parser->error('An open bracket was expected.', $token);
break;
}
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ')')) {
// Empty array.
break;
}
$ret->values[] = $token->value;
$ret->raw[] = $token->token;
$state = 2;
} elseif ($state === 2) {
if (($token->type !== Token::TYPE_OPERATOR) || (($token->value !== ',') && ($token->value !== ')'))) {
$parser->error('Symbols \')\' or \',\' were expected', $token);
break;
}
if ($token->value === ',') {
$state = 1;
} else { // )
break;
}
}
}
return $ret;
}
/**
* @param ArrayObj $component The component to be built.
*
* @return string
*/
public static function build($component)
{
$values = array();
if (!empty($component->raw)) {
$values = $component->raw;
} else {
foreach ($component->values as $value) {
$values[] = $value;
}
}
return '(' . implode(', ', $values) . ')';
}
}

View File

@ -0,0 +1,208 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Condition extends Component
{
/**
* Logical operators that can be used to delimit expressions.
*
* @var array
*/
public static $DELIMITERS = array('&&', 'AND', 'OR', 'XOR', '||');
/**
* Hash map containing reserved keywords that are also operators.
*
* @var array
*/
public static $OPERATORS = array(
'AND' => 1,
'BETWEEN' => 1,
'IN' => 1,
'IS' => 1,
'LIKE' => 1,
'NOT NULL' => 1,
'NULL' => 1,
'OR' => 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 = 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')) {
$betweenBefore = false;
} else {
$expr->expr = trim($expr->expr);
if (!empty($expr->expr)) {
// Adding the condition that is delimited by this operator.
$ret[] = $expr;
}
// Adding the operator.
$expr = new Condition($token->value);
$expr->isOperator = true;
$ret[] = $expr;
$expr = new Condition();
continue;
}
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
}
}
// No keyword is expected.
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
if ($token->value === 'BETWEEN') {
$betweenBefore = true;
}
if (($brackets === 0) && (empty(static::$OPERATORS[$token->value]))) {
break;
}
}
$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)
) {
$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.
*
* @return string
*/
public static function build($component)
{
$ret = array();
foreach ($component as $c) {
$ret[] = $c->expr;
}
return implode(' ', $ret);
}
}

View File

@ -0,0 +1,166 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 = 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.
*
* @return string
*/
public static function build($component)
{
$tmp = '';
if (!empty($component->parameters)) {
$tmp = '(' . implode(', ', $component->parameters) . ')';
}
return trim(
$component->name . ' ' . $tmp . ' '
. OptionsArray::build($component->options)
);
}
}

View File

@ -0,0 +1,337 @@
<?php
/**
* Parses a reference to a field.
*
* @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 a field.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Expression extends Component
{
/**
* 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
}
}
/**
* @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 $period
*/
$period = false;
/**
* Whether an alias is expected. Is 2 if `AS` keyword was found.
* @var int $alias
*/
$alias = 0;
/**
* Counts brackets.
* @var int $brackets
*/
$brackets = 0;
/**
* Keeps track of the previous token.
* Possible values:
* string, if function was previously found;
* true, if open bracket was previously found;
* null, in any other case.
* @var string|bool $prev
*/
$prev = null;
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) && (!$alias)) {
$ret->expr .= $token->token;
}
if (($alias === 0) && (empty($options['noAlias'])) && (!$isExpr) && (!$period) && (!empty($ret->expr))) {
$alias = 1;
}
continue;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
// Keywords may be found only between brackets.
if ($brackets === 0) {
if ((empty($options['noAlias'])) && ($token->value === 'AS')) {
$alias = 2;
continue;
}
if (!($token->flags & Token::FLAG_KEYWORD_FUNCTION)) {
break;
}
} elseif ($prev === true) {
if ((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;
}
}
}
if ($token->type === Token::TYPE_OPERATOR) {
if ((!empty($options['noBrackets']))
&& (($token->value === '(') || ($token->value === ')'))
) {
break;
}
if ($token->value === '(') {
++$brackets;
// We don't check to see if `$prev` is `true` (open bracket
// was found before) because the brackets count is one (the
// only bracket we found is this one).
if (($brackets === 1) && (empty($ret->function)) && ($prev !== null) && ($prev !== true)) {
// A function name was previously found and now an open
// bracket, so this is a function call.
$ret->function = $prev;
}
$isExpr = true;
} elseif ($token->value === ')') {
--$brackets;
if ($brackets < 0) {
$parser->error('Unexpected bracket.', $token);
$brackets = 0;
}
} elseif ($token->value === ',') {
if ($brackets === 0) {
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 !== '.')
) {
// Numbers, booleans and operators are usually part of expressions.
$isExpr = true;
}
if ($alias) {
// An alias is expected (the keyword `AS` was previously found).
$ret->alias = $token->value;
$alias = 0;
} else {
if (!$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)) || ($period)) {
$parser->error('Unexpected dot.', $token);
}
$ret->database = $ret->table;
$ret->table = $ret->column;
$ret->column = null;
$period = true;
} else {
// We found the name of a column (or table if column
// field should be skipped; used to parse table names).
if (!empty($options['skipColumn'])) {
if (!empty($ret->table)) {
break;
}
$ret->table = $token->value;
} else {
if (!empty($ret->column)) {
break;
}
$ret->column = $token->value;
}
$period = false;
}
} else {
// Parsing aliases without `AS` keyword.
// Example: SELECT 'foo' `bar`
if ($brackets === 0) {
if (($token->type === Token::TYPE_NONE) || ($token->type === Token::TYPE_STRING)
|| (($token->type === Token::TYPE_SYMBOL) && ($token->flags & Token::FLAG_SYMBOL_BACKTICK))
) {
$ret->alias = $token->value;
}
}
}
$ret->expr .= $token->token;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_FUNCTION)) {
$prev = strtoupper($token->value);
} elseif (($token->type === Token::TYPE_OPERATOR) || ($token->value === '(')) {
$prev = true;
} else {
$prev = null;
}
}
if ($alias === 2) {
$parser->error('Alias was expected.');
}
// Whitespaces might be added at the end.
$ret->expr = trim($ret->expr);
if (empty($ret->expr)) {
return null;
}
--$list->idx;
return $ret;
}
/**
* @param Expression $component The component to be built.
*
* @return string
*/
public static function build($component)
{
if (!empty($component->expr)) {
$ret = $component->expr;
} else {
$fields = array();
if (!empty($component->database)) {
$fields[] = $component->database;
}
if (!empty($component->table)) {
$fields[] = $component->table;
}
if (!empty($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,96 @@
<?php
/**
* Parses a a list of fields delimited by a single comma.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a a list of fields delimited by a single comma.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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();
$expr = null;
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)) {
// No keyword is expected.
break;
}
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$ret[] = $expr;
} else {
$expr = Expression::parse($parser, $list, $options);
if ($expr === null) {
break;
}
}
}
// Last iteration was not processed.
if ($expr !== null) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param Expression[] $component The component to be built.
*
* @return string
*/
public static function build($component)
{
$ret = array();
foreach ($component as $frag) {
$ret[] = $frag::build($frag);
}
return implode($ret, ', ');
}
}

View File

@ -0,0 +1,267 @@
<?php
/**
* Parses the definition of a field.
*
* 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 definition of a field.
*
* Used for parsing `CREATE TABLE` statement.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class FieldDefinition extends Component
{
/**
* All field options.
*
* @var array
*/
public static $FIELD_OPTIONS = array(
'NOT NULL' => 1,
'NULL' => 1,
'DEFAULT' => array(2, 'var'),
'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, 'var'),
);
/**
* 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 FieldDefinition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new FieldDefinition();
/**
* 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 ------------------------[ ) ]-----------------------> -1
*
* @var int
*/
$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;
}
} 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;
} else {
$expr->name = $token->value;
if (!$expr->isConstraint) {
$state = 2;
}
}
} 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 FieldDefinition();
if ($token->value === ',') {
$state = 1;
continue;
} elseif ($token->value === ')') {
++$list->idx;
break;
}
}
}
// Last iteration was not saved.
if ((!empty($expr->type)) || (!empty($expr->key))) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param FieldDefinition[] $component The component to be built.
*
* @return string
*/
public static function build($component)
{
if (is_array($component)) {
$ret = array();
foreach ($component as $c) {
$ret[] = static::build($c);
}
return "(\n" . implode(",\n", $ret) . "\n)";
} else {
$tmp = '';
if ($component->isConstraint) {
$tmp .= 'CONSTRAINT ';
}
if (!empty($component->name)) {
$tmp .= Context::escape($component->name) . ' ';
}
if (!empty($component->type)) {
$tmp .= DataType::build($component->type) . ' ';
}
if (!empty($component->key)) {
$tmp .= Key::build($component->key) . ' ';
}
if (!empty($component->references)) {
$tmp .= 'REFERENCES ' . Reference::build($component->references) . ' ';
}
$tmp .= OptionsArray::build($component->options);
return trim($tmp);
}
}
}

View File

@ -0,0 +1,123 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 ]-------------------> -1
*
* @var int
*/
$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.
*
* @return string
*/
public static function build($component)
{
return $component->name . ArrayObj::build($component->parameters);
}
}

View File

@ -0,0 +1,131 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 $fields;
/**
* @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 ------------------------[ ( ]------------------------> -1
*
* 2 ---------------------[ filename ]--------------------> 1
*
* @var int
*/
$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) {
$ret->dest = Expression::parse(
$parser,
$list,
array(
'noAlias' => true,
'noBrackets' => true,
'skipColumn' => true,
)
);
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->fields = ArrayObj::parse($parser, $list)->values;
++$list->idx;
}
break;
} elseif ($state === 2) {
$ret->dest = $token->value;
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
}

View File

@ -0,0 +1,164 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class JoinKeyword extends Component
{
/**
* Types of join.
*
* @var array
*/
public static $JOINS = array(
'FULL JOIN' => 'FULL',
'INNER JOIN' => 'INNER',
'JOIN' => 'JOIN',
'LEFT JOIN' => 'LEFT',
'RIGHT JOIN' => 'RIGHT',
);
/**
* Type of this join.
*
* @see static::$JOINS
* @var string
*/
public $type;
/**
* Join expression.
*
* @var Expression
*/
public $expr;
/**
* Join conditions.
*
* @var Condition[]
*/
public $on;
/**
* @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
*
* 3 --------------------[ conditions ]-------------------> 0
*
* @var int
*/
$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('skipColumn' => true));
$state = 2;
} elseif ($state === 2) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'ON')) {
$state = 3;
}
} else if ($state === 3) {
$expr->on = Condition::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.
*
* @return string
*/
public static function build($component)
{
$ret = array();
foreach ($component as $c) {
$ret[] = (($c->type === 'JOIN') ? 'JOIN ' : ($c->type . ' JOIN ')) .
Expression::build($c->expr) . ' ON ' . Condition::build($c->on);
}
return implode(' ', $ret);
}
}

View File

@ -0,0 +1,168 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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'),
);
/**
* 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();
/**
* 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 = 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 === '(')) {
$ret->columns = ArrayObj::parse($parser, $list)->values;
$state = 2;
} else {
$ret->name = $token->value;
}
} elseif ($state === 2) {
$ret->options = OptionsArray::parse($parser, $list, static::$KEY_OPTIONS);
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param Key $component The component to be built.
*
* @return string
*/
public static function build($component)
{
$ret = $component->type . ' ';
if (!empty($component->name)) {
$ret .= Context::escape($component->name) . ' ';
}
$ret .= '(' . implode(', ', Context::escape($component->columns)) . ')';
$ret .= OptionsArray::build($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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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.');
}
$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->idx;
return $ret;
}
/**
* @param Limit $component The component to be built.
*
* @return string
*/
public static function build($component)
{
if (empty($component->offset)) {
return $component->rowCount;
} else {
return $component->offset . ', ' . $component->rowCount;
}
}
}

View File

@ -0,0 +1,230 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 two keys 'name' and '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;
$brackets = 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 ($lastOption === null) {
if (isset($options[strtoupper($token->token)])) {
$lastOption = $options[strtoupper($token->token)];
$lastOptionId = is_array($lastOption) ? $lastOption[0] : $lastOption;
// 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('This option conflicts with \'' . $ret->options[$lastOptionId] . '\'.', $token);
$lastOptionId = $lastAssignedId++;
}
} else {
// There is no option to be processed.
break;
}
}
if (is_array($lastOption)) {
if (empty($ret->options[$lastOptionId])) {
$ret->options[$lastOptionId] = array(
'name' => $token->value,
'equal' => $lastOption[1] === 'var=',
'value' => '',
'value_' => '',
);
} else {
if ($token->value !== '=') {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
} else {
// Raw and processed value.
$ret->options[$lastOptionId]['value'] .= $token->token;
$ret->options[$lastOptionId]['value_'] .= $token->value;
}
if ($brackets === 0) {
$lastOption = null;
}
}
}
} else {
$ret->options[$lastOptionId] = $token->value;
$lastOption = null;
}
}
ksort($ret->options);
--$list->idx;
return $ret;
}
/**
* @param OptionsArray $component The component to be built.
*
* @return string
*/
public static function build($component)
{
if ((empty($component)) || (!is_array($component->options))) {
return '';
}
$options = array();
foreach ($component->options as $option) {
if (is_array($option)) {
$options[] = $option['name']
. (!empty($option['equal']) ? '=' : ' ')
. $option['value'];
} else {
$options[] = $option;
}
}
return implode(' ', $options);
}
/**
* Checks if it has the specified option and returns it value or true.
*
* @param string $key The key to be checked.
*
* @return mixed
*/
public function has($key)
{
foreach ($this->options as $option) {
if ($key === $option) {
return true;
} elseif ((is_array($option)) && ($key === $option['name'])) {
return $option['value'];
}
}
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 (($key === $option)
|| ((is_array($option)) && ($key === $option['name']))
) {
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);
}
}
}

View File

@ -0,0 +1,113 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class OrderKeyword extends Component
{
/**
* The field that is used for ordering.
*
* @var Expression
*/
public $field;
/**
* The order type.
*
* @var string
*/
public $type = 'ASC';
/**
* @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 ----------------------[ field ]----------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 -------------------[ ASC / DESC ]--------------------> 1
*
* @var int
*/
$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->field = 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->field)) {
$ret[] = $expr;
}
$expr = new OrderKeyword();
$state = 0;
} else {
break;
}
}
}
// Last iteration was not processed.
if (!empty($expr->field)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
}

View File

@ -0,0 +1,161 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 ------------------------[ ) ]-----------------------> -1
*
* @var int
*/
$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;
continue;
} elseif ($token->value === ')') {
++$list->idx;
break;
}
}
}
// Last iteration was not saved.
if (!empty($expr->name)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param ParameterDefinition[] $component The component to be built.
*
* @return string
*/
public static function build($component)
{
$ret = array();
foreach ($component as $c) {
$tmp = '';
if (!empty($c->inOut)) {
$tmp .= $c->inOut . ' ';
}
$ret[] = trim(
$tmp . Context::escape($c->name) . ' ' .
DataType::build($c->type)
);
}
return '(' . implode(', ', $ret) . ')';
}
}

View File

@ -0,0 +1,149 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 string
*/
public $table;
/**
* The referenced columns.
*
* @var array
*/
public $columns;
/**
* The options of the referencing.
*
* @var OptionsArray
*/
public $options;
/**
* Constructor.
*
* @param string $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 ]--------------------> -1
*
* @var int
*/
$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 = $token->value;
$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.
*
* @return string
*/
public static function build($component)
{
return trim(
Context::escape($component->table)
. ' (' . implode(', ', Context::escape($component->columns)) . ') '
. OptionsArray::build($component->options)
);
}
}

View File

@ -0,0 +1,146 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 ]----------------------> -1
*
* @var int
*/
$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 === 1) && ($token->value === 'TO')) {
$state = 2;
continue;
}
// No other keyword is expected.
break;
}
if ($token->type === Token::TYPE_OPERATOR) {
if (($state === 3) && ($token->value === ',')) {
$ret[] = $expr;
$expr = new RenameOperation();
$state = 0;
continue;
}
// No other operator is expected.
break;
}
if ($state == 0) {
$expr->old = Expression::parse(
$parser,
$list,
array(
'noAlias' => true,
'noBrackets' => true,
'skipColumn' => true,
)
);
$state = 1;
} elseif ($state == 2) {
$expr->new = Expression::parse(
$parser,
$list,
array(
'noBrackets' => true,
'skipColumn' => true,
'noAlias' => true,
)
);
$state = 3;
}
}
// Last iteration was not saved.
if (!empty($expr->old)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
}

View File

@ -0,0 +1,122 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 -------------------[ field name ]--------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 ----------------------[ value ]----------------------> 1
*
* @var int
*/
$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 ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === ',') {
$expr->column = trim($expr->column);
$expr->value = trim($expr->value);
$ret[] = $expr;
$expr = new SetOperation();
$state = 0;
continue;
} elseif ($token->value === '=') {
$state = 1;
continue;
}
}
if ($state === 0) {
$expr->column .= $token->token;
} else { // } else if ($state === 1) {
$expr->value .= $token->token;
}
}
// Last iteration was not saved.
if (!empty($expr->column)) {
$expr->column = trim($expr->column);
$expr->value = trim($expr->value);
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
}

View File

@ -0,0 +1,521 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
abstract class Context
{
/**
* The maximum length of a keyword.
*
* @see static::$TOKEN_KEYWORD
*
* @var int
*/
const KEYWORD_MAX_LENGTH = 30;
/**
* 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,
);
/**
* 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;
/*
* 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] === '*'))
|| (($str[0] === '*') && ($str[1] === '/')))
) {
return Token::FLAG_COMMENT_C;
} elseif (($len > 2) && ($str[0] === '-')
&& ($str[1] === '-') && ($str[2] !== "\n")
&& (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)
{
return !ctype_alnum($str) && $str !== '_';
}
/**
* 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 succesfully.
*
* @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 = 0;
// As long as a new context can be generated, we try to laod it.
do {
$loaded = true;
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::ANSI_QUOTES) {
$quote = '"';
}
return $quote . str_replace($quote, $quote . $quote, $str) . $quote;
}
}
// Initialing the default context.
Context::load();

View File

@ -0,0 +1,271 @@
<?php
/**
* Context for MySQL 5.
*
* @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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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, 'BIT' => 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, 'SERIAL' => 1, 'SIGNED' => 1,
'SIMPLE' => 1, 'SOUNDS' => 1, 'SOURCE' => 1, 'STATUS' => 1, 'STRING' => 1,
'TABLES' => 1,
'AGAINST' => 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,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DUMPFILE' => 1, 'EXTENDED' => 1,
'FUNCTION' => 1, 'GEOMETRY' => 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, '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,
'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, 'MATCH' => 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, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 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,
'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7, 'NO ACTION' => 7,
'ON DELETE' => 7, 'ON UPDATE' => 7,
'INNER JOIN' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'FOR EACH ROW' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'DEFAULT CHARACTER SET' => 7,
'XML' => 9,
'ENUM' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 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,
'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, 'POINT' => 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, '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,
'POLYGON' => 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, 'LINESTRING' => 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, 'MULTILINESTRING' => 33,
'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'NUMINTERIORRINGS' => 33,
'GEOMETRYCOLLECTION' => 33,
'UNCOMPRESSED_LENGTH' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 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,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,293 @@
<?php
/**
* Context for MySQL 5.1.
*
* @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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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, 'BIT' => 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, 'SERIAL' => 1, 'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1,
'SOCKET' => 1, 'SONAME' => 1, 'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1,
'STATUS' => 1, 'STRING' => 1, 'TABLES' => 1,
'AGAINST' => 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, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'GEOMETRY' => 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, '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, 'MATCH' => 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, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 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,
'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7, 'NO ACTION' => 7,
'ON DELETE' => 7, 'ON UPDATE' => 7,
'INNER JOIN' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'FOR EACH ROW' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'DEFAULT CHARACTER SET' => 7,
'XML' => 9,
'ENUM' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 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,
'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, 'POINT' => 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, '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,
'POLYGON' => 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, 'LINESTRING' => 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, 'MULTILINESTRING' => 33,
'POLYGONFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'GEOMETRYCOLLECTION' => 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,
'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,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,297 @@
<?php
/**
* Context for MySQL 5.5.
*
* @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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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, 'BIT' => 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, 'SERIAL' => 1, 'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1,
'SOCKET' => 1, 'SONAME' => 1, 'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1,
'STATUS' => 1, 'STRING' => 1, 'TABLES' => 1,
'AGAINST' => 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, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'GEOMETRY' => 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, '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, 'MATCH' => 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, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 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,
'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7, 'NO ACTION' => 7,
'ON DELETE' => 7, 'ON UPDATE' => 7,
'INNER JOIN' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'FOR EACH ROW' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'DEFAULT CHARACTER SET' => 7,
'XML' => 9,
'ENUM' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 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,
'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,
'POINT' => 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, '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,
'POLYGON' => 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, 'LINESTRING' => 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, 'MULTILINESTRING' => 33,
'POLYGONFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'GEOMETRYCOLLECTION' => 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,
'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,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,328 @@
<?php
/**
* Context for MySQL 5.6.
*
* @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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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, 'BIT' => 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, 'SERIAL' => 1, 'SERVER' => 1,
'SIGNED' => 1, 'SIMPLE' => 1, 'SOCKET' => 1, 'SONAME' => 1, 'SOUNDS' => 1,
'SOURCE' => 1, 'STARTS' => 1, 'STATUS' => 1, 'STRING' => 1, 'TABLES' => 1,
'AGAINST' => 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, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXCHANGE' => 1, 'EXTENDED' => 1, 'FUNCTION' => 1, 'GEOMETRY' => 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, '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, 'MATCH' => 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, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 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,
'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7, 'NO ACTION' => 7,
'ON DELETE' => 7, 'ON UPDATE' => 7,
'INNER JOIN' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'FOR EACH ROW' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'DEFAULT CHARACTER SET' => 7,
'XML' => 9,
'ENUM' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 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,
'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,
'POINT' => 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, '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, 'POLYGON' => 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, 'LINESTRING' => 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,
'MULTILINESTRING' => 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, 'GEOMETRYCOLLECTION' => 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,
'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,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,340 @@
<?php
/**
* Context for MySQL 5.7.
*
* @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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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, 'BIT' => 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,
'SERIAL' => 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, 'AGAINST' => 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, 'GEOMETRY' => 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, '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, 'MATCH' => 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, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'VIRTUAL' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 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,
'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7, 'NO ACTION' => 7,
'ON DELETE' => 7, 'ON UPDATE' => 7,
'INNER JOIN' => 7, 'OR REPLACE' => 7, 'RIGHT JOIN' => 7,
'FOR EACH ROW' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'DEFAULT CHARACTER SET' => 7,
'XML' => 9,
'ENUM' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 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,
'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,
'POINT' => 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, '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, 'POLYGON' => 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, 'LINESTRING' => 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, 'MULTILINESTRING' => 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,
'GEOMETRYCOLLECTION' => 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,
'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,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -0,0 +1,51 @@
<?php
/**
* Exception thrown by the lexer.
*
* @package SqlParser
* @subpackage Exceptions
*/
namespace SqlParser\Exceptions;
/**
* Exception thrown by the lexer.
*
* @category Exceptions
* @package SqlParser
* @subpackage Exceptions
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,44 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,700 @@
<?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;
use SqlParser\Exceptions\LexerException;
/**
* 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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
* @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` and `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', '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 = 1;
/**
* 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();
/**
* Constructor.
*
* @param string|UtfString $str The query to be lexed.
* @param bool $strict Whether strict mode should be enabled or not.
*/
public function __construct($str, $strict = false)
{
$this->str = $str;
$this->len = ($str instanceof UtfString) ?
$str->length() : strlen($str);
$this->strict = $strict;
$this->delimiter = static::$DEFAULT_DELIMITER;
$this->lex();
}
/**
* 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 (($token->type === Token::TYPE_SYMBOL)
&& ($token->flags & Token::FLAG_SYMBOL_VARIABLE)
&& ($lastToken !== null)
) {
// Handles ```... FROM 'user'@'%' ...```.
if ((($lastToken->type === Token::TYPE_SYMBOL)
&& ($lastToken->flags & Token::FLAG_SYMBOL_BACKTICK))
|| ($lastToken->type === Token::TYPE_STRING)
) {
$lastToken->token .= $token->token;
$lastToken->type = Token::TYPE_SYMBOL;
$lastToken->flags = Token::FLAG_SYMBOL_USER;
$lastToken->value .= '@' . $token->value;
continue;
}
}
$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 = '';
while ((++$this->last < $this->len) && (!Context::isWhitespace($this->str[$this->last]))) {
$this->delimiter .= $this->str[$this->last];
}
--$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 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 .= $this->str[$this->last];
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;
if (($this->last + 1 < $this->len) && ($this->str[$this->last + 1] === '!')) {
// It is a MySQL-specific command.
$flags |= Token::FLAG_COMMENT_MYSQL_CMD;
}
while ((++$this->last < $this->len) &&
(($this->str[$this->last - 1] !== '*') || ($this->str[$this->last] !== '/'))) {
$token .= $this->str[$this->last];
}
$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)) {
if ($this->str[$this->last] !== "\n") {
// Checking if this comment did not end already (```--\n```).
while ((++$this->last < $this->len) && ($this->str[$this->last] !== "\n")) {
$token .= $this->str[$this->last];
}
if ($this->last < $this->len) {
$token .= $this->str[$this->last];
}
}
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
//
// 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
//
// 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.
//
// 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->str[$this->last] === '0') && ($this->last + 1 < $this->len)
&& (($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] !== '+') {
// `+` 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;
}
}
$token .= $this->str[$this->last];
}
if (($state === 2) || ($state === 3) || (($token !== '.') && ($state === 4)) || ($state === 6)) {
--$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('Ending quote ' . $quote . ' was expected.', '', $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) {
++$this->last;
} else {
$token = '';
}
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) {
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,408 @@
<?php
/**
* Defines the parser of the library.
*
* This is one of the most important components, along with the lexer.
*
* @package SqlParser
*/
namespace SqlParser;
use SqlParser\Statements\SelectStatement;
use SqlParser\Exceptions\ParserException;
/**
* Takes multiple tokens (contained in a Lexer instance) as input and builds a
* parse tree.
*
* @category Parser
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Parser
{
/**
* Array of classes that are used in parsing the SQL statements.
*
* @var array
*/
public static $STATEMENT_PARSERS = array(
'EXPLAIN' => 'SqlParser\\Statements\\ExplainStatement',
// 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' => '',
'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
'PREPARE' => '',
'EXECUTE' => '',
);
/**
* 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 builder.
'_OPTIONS' => array(
'class' => 'SqlParser\\Components\\OptionsArray',
'field' => 'options',
),
'ALTER' => array(
'class' => 'SqlParser\\Components\\Expression',
'field' => 'table',
'options' => array('skipColumn' => true),
),
'ANALYZE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('skipColumn' => true),
),
'BACKUP' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('skipColumn' => true),
),
'CALL' => array(
'class' => 'SqlParser\\Components\\FunctionCall',
'field' => 'call',
),
'CHECK' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('skipColumn' => true),
),
'CHECKSUM' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('skipColumn' => true),
),
'DROP' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'fields',
'options' => array('skipColumn' => true),
),
'FROM' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'from',
'options' => array('skipColumn' => true),
),
'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',
),
'RIGHT 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',
),
'LIMIT' => array(
'class' => 'SqlParser\\Components\\Limit',
'field' => 'limit',
),
'OPTIMIZE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('skipColumn' => true),
),
'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('skipColumn' => true),
),
'RESTORE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('skipColumn' => true),
),
'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('skipColumn' => true),
),
'UPDATE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('skipColumn' => true),
),
'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();
/**
* Constructor.
*
* @param mixed $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 parsed statement.
* @var Statement $lastStatement
*/
$lastStatement = null;
/**
* Whether a union is parsed or not.
* @var bool $inUnion
*/
$inUnion = true;
/**
* 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];
// Statements can start with keywords only.
// Comments, whitespaces, etc. are ignored.
if ($token->type !== Token::TYPE_KEYWORD) {
continue;
}
if ($token->value === 'UNION') {
$inUnion = true;
continue;
}
// Checking if it is a known statement that can be parsed.
if (empty(static::$STATEMENT_PARSERS[$token->value])) {
$this->error(
'Unrecognized statement type "' . $token->value . '".',
$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 $stmt
*/
$stmt = 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
$stmt->first = $prevLastIdx + 1;
// Storing the index of the last token parsed and updating the old
// index.
$stmt->last = $list->idx;
$prevLastIdx = $list->idx;
// Finally, storing the statement.
if (($inUnion)
&& ($lastStatement instanceof SelectStatement)
&& ($stmt instanceof SelectStatement)
) {
$lastStatement->union[] = $stmt;
$inUnion = false;
} else {
$this->statements[] = $stmt;
$lastStatement = $stmt;
}
}
}
/**
* 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,295 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 statement.
*
* @return string
*/
public function build()
{
/**
* Query to be returned.
* @var string $query
*/
$query = '';
foreach (static::$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];
// Checking if there is any parser (builder) for this clause.
if (empty(Parser::$KEYWORD_PARSERS[$name])) {
continue;
}
/**
* The builder (parser) of this clause.
* @var string $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 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)
{
// 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) ? false : true;
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;
}
// Only keywords are relevant here. Other parts of the query are
// processed in the functions below.
if ($token->type !== Token::TYPE_KEYWORD) {
continue;
}
// Unions are parsed by the parser because they represent more than
// one statement.
if ($token->value === 'UNION') {
break;
}
/**
* The name of the class that is used for parsing.
* @var string $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();
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'];
}
}
if (!empty(Parser::$STATEMENT_PARSERS[$token->value])) {
if (!$parsedOptions) {
++$list->idx; // Skipping keyword.
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
$parsedOptions = true;
}
} elseif ($class === null) {
// There is no parser for this keyword and isn't the beginning
// of a statement (so no options) either.
$parser->error(
'Unrecognized keyword "' . $token->value . '".',
$token
);
continue;
}
$this->before($parser, $list, $token);
// Parsing this keyword.
if ($class !== null) {
++$list->idx; // Skipping keyword.
$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)
{
}
}

View File

@ -0,0 +1,138 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,
);
/**
* @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
);
// Skipping `TABLE`.
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'TABLE');
// Parsing affected table.
$this->table = Expression::parse(
$parser, $list, array(
'noAlias' => true,
'noBrackets' => 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 = 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) {
$this->altered[] = AlterOperation::parse($parser, $list);
$state = 1;
} else if ($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)
. ' TABLE ' . Expression::build($this->table)
. ' ' . implode(', ', $tmp);
}
}

View File

@ -0,0 +1,48 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,39 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,38 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class CallStatement extends Statement
{
/**
* The name of the function and its parameters.
*
* @var FunctionCall
*/
public $call;
}

View File

@ -0,0 +1,41 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,37 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,391 @@
<?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\FieldDefinition;
use SqlParser\Components\Expression;
use SqlParser\Components\OptionsArray;
use SqlParser\Components\ParameterDefinition;
/**
* `CREATE` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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, 'var='),
'SQL SECURITY' => array(5, 'var'),
'DATABASE' => 6,
'EVENT' => 6,
'FUNCTION' => 6,
'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 fields in the new table.
* If `CREATE VIEW`, a list of columns.
*
* Used by `CREATE TABLE` and `CREATE VIEW`.
*
* @var FieldDefinition[]|ArrayObj
*/
public $fields;
/**
* 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 = FieldDefinition::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')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $fields
. OptionsArray::build($this->entityOptions);
} 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 '';
}
/**
* @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(
'noAlias' => true,
'noBrackets' => true,
'skipColumn' => true,
)
);
++$list->idx; // Skipping field.
if ($this->options->has('DATABASE')) {
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$DB_OPTIONS
);
} elseif ($this->options->has('TABLE')) {
$this->fields = FieldDefinition::parse($parser, $list);
++$list->idx;
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$TABLE_OPTIONS
);
} 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(
'\'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;
}
} else if ($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;
}
} else if ($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(
'noAlias' => true,
'noBrackets' => true,
'skipColumn' => 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;
}
}
}
}

View File

@ -0,0 +1,99 @@
<?php
/**
* `DELETE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\ArrayObj;
use SqlParser\Components\Expression;
use SqlParser\Components\Limit;
use SqlParser\Components\OrderKeyword;
use SqlParser\Components\Condition;
/**
* `DELETE` statement.
*
* DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
* [PARTITION (partition_name,...)]
* [WHERE where_condition]
* [ORDER BY ...]
* [LIMIT row_count]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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),
'WHERE' => array('WHERE', 3),
'ORDER BY' => array('ORDER BY', 3),
'LIMIT' => array('LIMIT', 3),
);
/**
* Tables used as sources for this statement.
*
* @var Expression[]
*/
public $from;
/**
* 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;
}

View File

@ -0,0 +1,70 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,
'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),
);
/**
* Dropped elements.
*
* @var Expression[]
*/
public $fields;
}

View File

@ -0,0 +1,23 @@
<?php
/**
* `EXPLAIN` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `EXPLAIN` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ExplainStatement extends NotImplementedStatement
{
}

View File

@ -0,0 +1,82 @@
<?php
/**
* `INSERT` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\Array2d;
/**
* `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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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;
}

View File

@ -0,0 +1,68 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,68 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,48 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,57 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,43 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,68 @@
<?php
/**
* `REPLACE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\SetOperation;
use SqlParser\Components\Array2d;
/**
* `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}, ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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;
/**
* The replaced values.
*
* @var SetOperation[]
*/
public $set;
}

View File

@ -0,0 +1,36 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,187 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,
);
/**
* 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),
'FROM' => array('FROM', 3),
'PARTITION' => array('PARTITION', 3),
'JOIN' => array('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),
'INTO' => array('INTO', 3),
'UNION' => array('UNION', 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();
}

View File

@ -0,0 +1,71 @@
<?php
/**
* `SHOW` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `SHOW` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,41 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,105 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,283 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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;
// 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;
// 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;
/**
* 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); // trims quotes
case Token::TYPE_SYMBOL:
$str = $this->token;
if ((isset($str[0])) && ($str[0] === '@')) {
$str = mb_substr($str, 1);
}
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);
}
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,208 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,249 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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);
}
/**
* Checks if the given offset exists.
*
* @param int $offset The offset to be checked.
*
* @return bool
*/
public function offsetExists($offset)
{
return $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 number of remaining characters.
*
* @return int
*/
public function remaining()
{
if ($this->charIdx < $this->charLen) {
return $this->charLen - $this->charIdx;
}
return 0;
}
/**
* Returns the length in characters of the string.
*
* @return int
*/
public function length()
{
return $this->charLen;
}
/**
* Gets the values of the indexes.
*
* @param int &$byte Reference to the byte index.
* @param int &$char Reference to the character index.
*
* @return void
*/
public function getIndexes(&$byte, &$char)
{
$byte = $this->byteIdx;
$char = $this->charIdx;
}
/**
* Sets the values of the indexes.
*
* @param int $byte The byte index.
* @param int $char The character index.
*
* @return void
*/
public function setIndexes($byte = 0, $char = 0)
{
$this->byteIdx = $byte;
$this->charIdx = $char;
}
}

View File

@ -0,0 +1,94 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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], $err[2], $err[3]
);
}
return $ret;
}
}

View File

@ -0,0 +1,107 @@
<?php
/**
* Miscellaneous utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Statements\SelectStatement;
/**
* Miscellaneous utilities.
*
* @category Misc
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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 = $statement->from;
// Adding expressions from JOIN.
if (!empty($statement->join)) {
foreach ($statement->join as $join) {
$expressions[] = $join->expr;
}
}
foreach ($expressions as $expr) {
if (empty($expr->table)) {
continue;
}
$thisDb = empty($expr->database) ? $database : $expr->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' => empty($expr->alias) ? null : $expr->alias,
'columns' => array(),
);
}
if (!isset($tables[$thisDb])) {
$tables[$thisDb] = array();
}
$tables[$thisDb][$expr->alias] = $expr->table;
}
foreach ($statement->expr as $expr) {
if ((empty($expr->column)) || (empty($expr->alias))) {
continue;
}
$thisDb = empty($expr->database) ? $database : $expr->database;
if (empty($expr->table)) {
foreach ($retval[$thisDb]['tables'] as &$table) {
$table['columns'][$expr->column] = $expr->alias;
}
} else {
$thisTable = isset($tables[$thisDb][$expr->table]) ?
$tables[$thisDb][$expr->table] : $expr->table;
$retval[$thisDb]['tables'][$thisTable]['columns'][$expr->column] = $expr->alias;
}
}
return $retval;
}
}

View File

@ -0,0 +1,704 @@
<?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 Routines
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Query
{
/**
* Functions that set the flag `is_func`.
*
* @var array
*/
public static $FUNCTIONS = array(
'SUM','AVG','STD','STDDEV','MIN','MAX','BIT_OR','BIT_AND'
);
/**
* Gets an array with flags this statement has.
*
* @param Statement $statement The statement to be processed.
* @param bool $all If `false`, false values will not be included.
*
* @return array
*/
public static function getFlags($statement, $all = false)
{
$flags = array();
if ($all) {
$flags = array(
/**
* select ... DISTINCT ...
*/
'distinct' => false,
/**
* drop ... DATABASE ...
*/
'drop_database' => false,
/**
* ... GROUP BY ...
*/
'group' => false,
/**
* ... HAVING ...
*/
'having' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* DELETE ...
*/
'is_affected' => false,
/**
* select ... PROCEDURE ANALYSE( ... ) ...
*/
'is_analyse' => false,
/**
* select COUNT( ... ) ...
*/
'is_count' => false,
/**
* DELETE ...
*/
'is_delete' => false, // @deprecated; use `querytype`
/**
* EXPLAIN ...
*/
'is_explain' => false, // @deprecated; use `querytype`
/**
* select ... INTO OUTFILE ...
*/
'is_export' => false,
/**
* select FUNC( ... ) ...
*/
'is_func' => false,
/**
* select ... GROUP BY ...
* or
* select ... HAVING ...
*/
'is_group' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* TODO: LOAD DATA ...
*/
'is_insert' => false,
/**
* ANALYZE ...
* or
* CHECK ...
* or
* CHECKSUM ...
* or
* OPTIMIZE ...
* or
* REPAIR ...
*/
'is_maint' => false,
/**
* CALL ...
*/
'is_procedure' => false,
/**
* REPLACE ...
*/
'is_replace' => false, // @deprecated; use `querytype`
/**
* SELECT ...
*/
'is_select' => false, // @deprecated; use `querytype`
/**
* SHOW ...
*/
'is_show' => false, // @deprecated; use `querytype`
/**
* Contains a subquery.
*/
'is_subquery' => false,
/**
* ... JOIN ...
*/
'join' => false,
/**
* ... LIMIT ...
*/
'limit' => false,
/**
* TODO
*/
'offset' => false,
/**
* ... ORDER ...
*/
'order' => false,
/**
* The type of the query (which is usually the first keyword of
* the statement).
*/
'querytype' => false,
/**
* Whether a page reload is required.
*/
'reload' => false,
/**
* SELECT ... FROM ...
*/
'select_from' => false,
/**
* ... UNION ...
*/
'union' => false
);
}
if ($statement instanceof AlterStatement) {
$flags['querytype'] = 'ALTER';
$flags['reload'] = true;
} elseif ($statement instanceof CreateStatement) {
$flags['querytype'] = 'CREATE';
$flags['reload'] = true;
} elseif ($statement instanceof AnalyzeStatement) {
$flags['querytype'] = 'ANALYZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof CheckStatement) {
$flags['querytype'] = 'CHECK';
$flags['is_maint'] = true;
} elseif ($statement instanceof ChecksumStatement) {
$flags['querytype'] = 'CHECKSUM';
$flags['is_maint'] = true;
} elseif ($statement instanceof OptimizeStatement) {
$flags['querytype'] = 'OPTIMIZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof RepairStatement) {
$flags['querytype'] = 'REPAIR';
$flags['is_maint'] = true;
} elseif ($statement instanceof CallStatement) {
$flags['querytype'] = 'CALL';
$flags['is_procedure'] = true;
} elseif ($statement instanceof DeleteStatement) {
$flags['querytype'] = 'DELETE';
$flags['is_delete'] = true;
$flags['is_affected'] = true;
} elseif ($statement instanceof DropStatement) {
$flags['querytype'] = 'DROP';
$flags['reload'] = true;
if (($statement->options->has('DATABASE')
|| ($statement->options->has('SCHEMA')))
) {
$flags['drop_database'] = true;
}
} elseif ($statement instanceof ExplainStatement) {
$flags['querytype'] = 'EXPLAIN';
$flags['is_explain'] = true;
} elseif ($statement instanceof InsertStatement) {
$flags['querytype'] = 'INSERT';
$flags['is_affected'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof ReplaceStatement) {
$flags['querytype'] = 'REPLACE';
$flags['is_affected'] = true;
$flags['is_replace'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof SelectStatement) {
$flags['querytype'] = 'SELECT';
$flags['is_select'] = true;
if (!empty($statement->from)) {
$flags['select_from'] = true;
}
if ($statement->options->has('DISTINCT')) {
$flags['distinct'] = true;
}
if ((!empty($statement->group)) || (!empty($statement->having))) {
$flags['is_group'] = true;
}
if ((!empty($statement->into))
&& ($statement->into->type === 'OUTFILE')
) {
$flags['is_export'] = true;
}
foreach ($statement->expr as $expr) {
if (!empty($expr->function)) {
if ($expr->function === 'COUNT') {
$flags['is_count'] = true;
} elseif (in_array($expr->function, static::$FUNCTIONS)) {
$flags['is_func'] = true;
}
}
if (!empty($expr->subquery)) {
$flags['is_subquery'] = true;
}
}
if ((!empty($statement->procedure))
&& ($statement->procedure->name === 'ANALYSE')
) {
$flags['is_analyse'] = true;
}
if (!empty($statement->group)) {
$flags['group'] = true;
}
if (!empty($statement->having)) {
$flags['having'] = true;
}
if (!empty($statement->union)) {
$flags['union'] = true;
}
if (!empty($statement->join)) {
$flags['join'] = true;
}
} elseif ($statement instanceof ShowStatement) {
$flags['querytype'] = 'SHOW';
$flags['is_show'] = true;
} elseif ($statement instanceof UpdateStatement) {
$flags['querytype'] = 'UPDATE';
$flags['is_affected'] = true;
}
if (($statement instanceof SelectStatement)
|| ($statement instanceof UpdateStatement)
|| ($statement instanceof DeleteStatement)
) {
if (!empty($statement->limit)) {
$flags['limit'] = true;
}
if (!empty($statement->order)) {
$flags['order'] = true;
}
}
return $flags;
}
/**
* Parses a query and gets all information about it.
*
* @param string $query The query to be parsed.
*
* @return array 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 (!isset($parser->statements[0])) {
return array();
}
$statement = $parser->statements[0];
$ret = static::getFlags($statement, true);
$ret['parser'] = $parser;
$ret['statement'] = $statement;
if ($statement instanceof SelectStatement) {
$ret['select_tables'] = array();
$ret['select_expr'] = array();
// Finding tables' aliases and their associated real names.
$tableAliases = array();
foreach ($statement->from as $expr) {
if ((!empty($expr->table)) && (!empty($expr->alias))) {
$tableAliases[$expr->alias] = array(
$expr->table,
!empty($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 (!empty($expr->table)) {
if (empty($tableAliases[$expr->table])) {
$arr = array(
$expr->table,
!empty($expr->database) ? $expr->database : null
);
} else {
$arr = $tableAliases[$expr->table];
}
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 (!empty($expr->table)) {
$arr = array(
$expr->table,
!empty($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)
{
$fields = array();
if (($statement instanceof InsertStatement)
|| ($statement instanceof ReplaceStatement)
) {
$fields = array($statement->into->dest);
} elseif ($statement instanceof UpdateStatement) {
$fields = $statement->tables;
} elseif (($statement instanceof SelectStatement)
|| ($statement instanceof DeleteStatement)
) {
$fields = $statement->from;
} elseif (($statement instanceof AlterStatement)
|| ($statement instanceof TruncateStatement)
) {
$fields = array($statement->table);
} elseif ($statement instanceof DropStatement) {
if (!$statement->options->has('TABLE')) {
// No tables are dropped.
return array();
}
$fields = $statement->fields;
} elseif ($statement instanceof RenameStatement) {
foreach ($statement->renames as $rename) {
$fields[] = $rename->old;
}
}
$ret = array();
foreach ($fields as $field) {
if (!empty($field->table)) {
$field->expr = null; // Force rebuild.
$field->alias = null; // Aliases are not required.
$ret[] = Expression::build($field);
}
}
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::$CLAUSES));
/**
* 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 behaviour 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_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
}
}
if ($brackets == 0) {
// Checking if we changed sections.
if (($token->type === Token::TYPE_KEYWORD)
&& (isset($clauses[$token->value]))
&& ($clauses[$token->value] >= $currIdx)
) {
$currIdx = $clauses[$token->value];
if (($skipFirst) && ($currIdx == $clauseIdx)) {
// This token is skipped (not added to the old
// clause) because it will be replaced.
continue;
}
}
}
if (($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;
}
}

View File

@ -0,0 +1,136 @@
<?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
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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,131 @@
<?php
/**
* Table utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Statements\CreateStatement;
/**
* Table utilities.
*
* @category Tables
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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;
}
$tmp = array(
'constraint' => $field->name,
'index_list' => $field->key->columns,
);
if (!empty($field->references)) {
$tmp['ref_table_name'] = $field->references->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;
}
}
}
}
return $ret;
}
}

View File

@ -60,7 +60,6 @@ function PMA_getTableNameBySQL($sql, $tables)
return trim($table);
}
/**
* Handle remembered sorting order, only for single table query
*
@ -75,34 +74,36 @@ function PMA_handleSortOrder(
$db, $table, &$analyzed_sql_results, &$full_sql_query
) {
$pmatable = new PMA_Table($table, $db);
if (empty($analyzed_sql_results['analyzed_sql'][0]['order_by_clause'])) {
$sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
if ($sorted_col) {
//remove the tablename from retrieved preference
//to get just the column name and the sort order
$sorted_col = str_replace(
PMA_Util::backquote($table) . '.', '', $sorted_col
);
// retrieve the remembered sorting order for current table
$sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
$full_sql_query
= $analyzed_sql_results['analyzed_sql'][0]['section_before_limit']
. $sql_order_to_append
. $analyzed_sql_results['analyzed_sql'][0]['limit_clause']
. ' '
. $analyzed_sql_results['analyzed_sql'][0]['section_after_limit'];
// update the $analyzed_sql
$analyzed_sql_results['analyzed_sql'][0]['section_before_limit']
.= $sql_order_to_append;
$analyzed_sql_results['analyzed_sql'][0]['order_by_clause']
= $sorted_col;
if (empty($analyzed_sql_results['order'])) {
// Retrieving the name of the column we should sort after.
$sortCol = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
if (empty($sortCol)) {
return;
}
// Remove the name of the the table from the retrieved field name.
$sortCol = str_replace(PMA_Util::backquote($table) . '.', '', $sortCol);
// Create the new query.
$full_sql_query = SqlParser\Utils\Query::replaceClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'ORDER BY ' . $sortCol
);
// TODO: Avoid reparsing the query.
$analyzed_sql_results = SqlParser\Utils\Query::getAll($full_sql_query);
} else {
// store the remembered table into session
// Store the remembered table into session.
$pmatable->setUiProp(
PMA_Table::PROP_SORTED_COLUMN,
$analyzed_sql_results['analyzed_sql'][0]['order_by_clause']
SqlParser\Utils\Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'ORDER BY'
)
);
}
}
@ -110,16 +111,18 @@ function PMA_handleSortOrder(
/**
* Append limit clause to SQL query
*
* @param array $analyzed_sql the analyzed query
* @param string $sql_limit_to_append clause to append
* @param array &$analyzed_sql_results the analyzed query results
*
* @return string limit clause appended SQL query
*/
function PMA_getSqlWithLimitClause($analyzed_sql,
$sql_limit_to_append
) {
return $analyzed_sql[0]['section_before_limit'] . "\n"
. $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
function PMA_getSqlWithLimitClause(&$analyzed_sql_results)
{
return SqlParser\Utils\Query::replaceClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'LIMIT ' . $_SESSION['tmpval']['pos'] . ', '
. $_SESSION['tmpval']['max_rows']
);
}
@ -617,23 +620,16 @@ function PMA_getHtmlForBookmark($displayParts, $cfgBookmark, $sql_query, $db,
*/
function PMA_isRememberSortingOrder($analyzed_sql_results)
{
$select_from = isset(
$analyzed_sql_results['analyzed_sql'][0]['queryflags']['select_from']
);
if ($GLOBALS['cfg']['RememberSorting']
return $GLOBALS['cfg']['RememberSorting']
&& ! ($analyzed_sql_results['is_count']
|| $analyzed_sql_results['is_export']
|| $analyzed_sql_results['is_func']
|| $analyzed_sql_results['is_analyse'])
&& isset($analyzed_sql_results['analyzed_sql'][0]['select_expr'])
&& (count($analyzed_sql_results['analyzed_sql'][0]['select_expr']) == 0)
&& $select_from
&& count($analyzed_sql_results['analyzed_sql'][0]['table_ref']) == 1
) {
return true;
} else {
return false;
}
|| $analyzed_sql_results['is_export']
|| $analyzed_sql_results['is_func']
|| $analyzed_sql_results['is_analyse'])
&& $analyzed_sql_results['select_from']
&& ((empty($analyzed_sql_results['select_expr']))
|| (count($analyzed_sql_results['select_expr'] == 1)
&& ($analyzed_sql_results['select_expr'][0] == '*')))
&& count($analyzed_sql_results['select_tables']) == 1;
}
/**
@ -646,20 +642,12 @@ function PMA_isRememberSortingOrder($analyzed_sql_results)
*/
function PMA_isAppendLimitClause($analyzed_sql_results)
{
$select_from = isset(
$analyzed_sql_results['analyzed_sql'][0]['queryflags']['select_from']
);
if (($_SESSION['tmpval']['max_rows'] != 'all')
return ($_SESSION['tmpval']['max_rows'] != 'all')
&& ! ($analyzed_sql_results['is_export']
|| $analyzed_sql_results['is_analyse'])
&& ($select_from || $analyzed_sql_results['is_subquery'])
&& ! isset($analyzed_sql_results['analyzed_sql'][0]['queryflags']['offset'])
&& empty($analyzed_sql_results['analyzed_sql'][0]['limit_clause'])
) {
return true;
} else {
return false;
}
&& ($analyzed_sql_results['select_from']
|| $analyzed_sql_results['is_subquery'])
&& empty($analyzed_sql_results['limit']);
}
/**
@ -673,29 +661,18 @@ function PMA_isAppendLimitClause($analyzed_sql_results)
*/
function PMA_isJustBrowsing($analyzed_sql_results, $find_real_end)
{
$distinct = isset(
$analyzed_sql_results['analyzed_sql'][0]['queryflags']['distinct']
);
$table_name = isset(
$analyzed_sql_results['analyzed_sql'][0]['table_ref'][1]['table_name']
);
if (! $analyzed_sql_results['is_group']
return ! $analyzed_sql_results['is_group']
&& ! $analyzed_sql_results['is_func']
&& ! isset($analyzed_sql_results['analyzed_sql'][0]['queryflags']['union'])
&& ! $distinct
&& ! $table_name
&& (empty($analyzed_sql_results['analyzed_sql'][0]['where_clause'])
|| $analyzed_sql_results['analyzed_sql'][0]['where_clause'] == '1 ')
&& empty($analyzed_sql_results['analyzed_sql'][0]['group_by_clause'])
&& empty($analyzed_sql_results['union'])
&& empty($analyzed_sql_results['distinct'])
&& count($analyzed_sql_results['select_tables'] <= 1)
&& (empty($analyzed_sql_results['statement']->where)
|| (count($analyzed_sql_results['statement']->where) == 1
&& $analyzed_sql_results['statement']->where[0]->expr ==='1'))
&& empty($analyzed_sql_results['group'])
&& ! isset($find_real_end)
&& !$analyzed_sql_results['is_subquery']
&& empty($analyzed_sql_results['analyzed_sql'][0]['having_clause'])
) {
return true;
} else {
return false;
}
&& ! $analyzed_sql_results['is_subquery']
&& empty($analyzed_sql_results['having']);
}
/**
@ -708,14 +685,9 @@ function PMA_isJustBrowsing($analyzed_sql_results, $find_real_end)
*/
function PMA_isDeleteTransformationInfo($analyzed_sql_results)
{
if (!empty($analyzed_sql_results['analyzed_sql'][0]['querytype'])
&& (($analyzed_sql_results['analyzed_sql'][0]['querytype'] == 'ALTER')
|| ($analyzed_sql_results['analyzed_sql'][0]['querytype'] == 'DROP'))
) {
return true;
} else {
return false;
}
return !empty($analyzed_sql_results['querytype'])
&& (($analyzed_sql_results['querytype'] == 'ALTER')
|| ($analyzed_sql_results['querytype'] == 'DROP'));
}
/**
@ -1099,18 +1071,13 @@ function PMA_getNumberOfRowsAffectedOrChanged($is_affected, $result)
*/
function PMA_hasCurrentDbChanged($db)
{
// Checks if the current database has changed
// This could happen if the user sends a query like "USE `database`;"
$reload = 0;
if (/*overload*/mb_strlen($db)) {
$current_db = $GLOBALS['dbi']->fetchValue('SELECT DATABASE()');
// $current_db is false, except when a USE statement was sent
if ($current_db != false && $db !== $current_db) {
$reload = 1;
}
return ($current_db != false) && ($db !== $current_db);
}
return $reload;
return false;
}
/**
@ -1154,26 +1121,26 @@ function PMA_cleanupRelations($db, $table, $dropped_column, $purge, $extra_data)
* the 'LIMIT' clause that may have been programatically added
*
* @param int $num_rows number of rows affected/changed by the query
* @param bool $is_select whether the query is SELECT or not
* @param bool $justBrowsing whether just browsing or not
* @param string $db the current database
* @param string $table the current table
* @param array $parsed_sql parsed sql
* @param array $analyzed_sql_results the analyzed query and other variables set
* after analyzing the query
*
* @return int $unlim_num_rows unlimited number of rows
*/
function PMA_countQueryResults(
$num_rows, $is_select, $justBrowsing,
$db, $table, $parsed_sql, $analyzed_sql_results
$num_rows, $justBrowsing, $db, $table, $analyzed_sql_results
) {
if (!PMA_isAppendLimitClause($analyzed_sql_results)) {
// if we did not append a limit, set this to get a correct
// "Showing rows..." message
// $_SESSION['tmpval']['max_rows'] = 'all';
$unlim_num_rows = $num_rows;
} elseif ($is_select || $analyzed_sql_results['is_subquery']) {
$unlim_num_rows = $num_rows;
} elseif ($analyzed_sql_results['querytype'] == 'SELECT'
|| $analyzed_sql_results['is_subquery']
) {
// c o u n t q u e r y
// If we are "just browsing", there is only one table,
@ -1210,62 +1177,32 @@ function PMA_countQueryResults(
}
} else {
// add select expression after the SQL_CALC_FOUND_ROWS
// for UNION, just adding SQL_CALC_FOUND_ROWS
// after the first SELECT works.
// The SQL_CALC_FOUND_ROWS option of the SELECT statement is used.
// take the left part, could be:
// SELECT
// (SELECT
// For UNION statements, only a SQL_CALC_FOUND_ROWS is required
// after the first SELECT.
$analyzed_sql = $analyzed_sql_results['analyzed_sql'];
$count_query = PMA_SQP_format(
$parsed_sql,
'query_only',
0,
$analyzed_sql[0]['position_of_first_select'] + 1
$count_query = SqlParser\Utils\Query::replaceClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'SELECT SQL_CALC_FOUND_ROWS',
null,
true
);
$count_query .= ' SQL_CALC_FOUND_ROWS ';
// add everything that was after the first SELECT
$count_query .= PMA_SQP_format(
$parsed_sql,
'query_only',
$analyzed_sql[0]['position_of_first_select'] + 1
);
// ensure there is no semicolon at the end of the
// count query because we'll probably add
// a LIMIT 1 clause after it
$count_query = rtrim($count_query);
$count_query = rtrim($count_query, ';');
// if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
// long delays. Returned count will be complete anyway.
// (but a LIMIT would disrupt results in an UNION)
// Another LIMIT clause is added to avoid long delays.
// A complete result will be returned anyway, but the LIMIT would
// stop the query as soon as the result that is required has been
// computed.
if (! isset($analyzed_sql[0]['queryflags']['union'])) {
if (empty($analyzed_sql_results['union'])) {
$count_query .= ' LIMIT 1';
}
// run the count query
// Running the count query.
$GLOBALS['dbi']->tryQuery($count_query);
// if (mysql_error()) {
// void.
// I tried the case
// (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
// UNION (SELECT `User`, `Host`, "%" AS "Db",
// `Select_priv`
// FROM `user`) ORDER BY `User`, `Host`, `Db`;
// and although the generated count_query is wrong
// the SELECT FOUND_ROWS() work! (maybe it gets the
// count from the latest query that worked)
//
// another case where the count_query is wrong:
// SELECT COUNT(*), f1 from t1 group by f1
// and you click to sort on count(*)
// }
$unlim_num_rows = $GLOBALS['dbi']->fetchValue('SELECT FOUND_ROWS()');
} // end else "just browsing"
} else {// not $is_select
@ -1341,8 +1278,7 @@ function PMA_executeTheQuery($analyzed_sql_results, $full_sql_query, $is_gotofil
);
$unlim_num_rows = PMA_countQueryResults(
$num_rows, $analyzed_sql_results['is_select'], $justBrowsing, $db,
$table, $analyzed_sql_results['parsed_sql'], $analyzed_sql_results
$num_rows, $justBrowsing, $db, $table, $analyzed_sql_results
);
$extra_data = PMA_cleanupRelations(
@ -1365,31 +1301,27 @@ function PMA_executeTheQuery($analyzed_sql_results, $full_sql_query, $is_gotofil
/**
* Delete related tranformatioinformationn information
*
* @param String $db current database
* @param String $table current table
* @param array $analyzed_sql analyzed sql query
* @param String $db current database
* @param String $table current table
* @param array $analyzed_sql_results analyzed sql results
*
* @return void
*/
function PMA_deleteTransformationInfo($db, $table, $analyzed_sql)
function PMA_deleteTransformationInfo($db, $table, $analyzed_sql_results)
{
include_once 'libraries/transformations.lib.php';
if ($analyzed_sql[0]['querytype'] == 'ALTER') {
$posDrop = /*overload*/mb_stripos(
$analyzed_sql[0]['unsorted_query'],
'DROP'
);
if ($posDrop !== false) {
$drop_column = PMA_getColumnNameInColumnDropSql(
$analyzed_sql[0]['unsorted_query']
);
if ($drop_column != '') {
PMA_clearTransformations($db, $table, $drop_column);
$statement = $analyzed_sql_results['statement'];
if ($statement instanceof SqlParser\Statements\AlterStatement) {
if ($statement->altered[0]->options->has('DROP')) {
if (!empty($statement->altered[0]->field->column)) {
PMA_clearTransformations(
$db,
$table,
$statement->altered[0]->field->column
);
}
}
} else if (($analyzed_sql[0]['querytype'] == 'DROP') && ($table != '')) {
} elseif ($statement instanceof SqlParser\Statements\DropStatement) {
PMA_clearTransformations($db, $table);
}
}
@ -1403,14 +1335,14 @@ function PMA_deleteTransformationInfo($db, $table, $analyzed_sql)
*
* @return string $message
*/
function PMA_getMessageForNoRowsReturned($message_to_show, $analyzed_sql_results,
$num_rows
function PMA_getMessageForNoRowsReturned($message_to_show,
$analyzed_sql_results, $num_rows
) {
if ($analyzed_sql_results['is_delete']) {
if ($analyzed_sql_results['querytype'] == 'DELETE"') {
$message = PMA_Message::getMessageForDeletedRows($num_rows);
} elseif ($analyzed_sql_results['is_insert']) {
if ($analyzed_sql_results['is_replace']) {
// For replace we get DELETED + INSERTED row count,
if ($analyzed_sql_results['querytype'] == 'REPLACE') {
// For REPLACE we get DELETED + INSERTED row count,
// so we have to call it affected
$message = PMA_Message::getMessageForAffectedRows($num_rows);
} else {
@ -1438,7 +1370,9 @@ function PMA_getMessageForNoRowsReturned($message_to_show, $analyzed_sql_results
// fact that $message_to_show is sent for every case.
// The $message_to_show containing a success message and sent with
// the form should not have priority over errors
} elseif (! empty($message_to_show) && ! $analyzed_sql_results['is_select']) {
} elseif (! empty($message_to_show)
&& $analyzed_sql_results['querytype'] != 'SELECT'
) {
$message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
} elseif (! empty($GLOBALS['show_as_php'])) {
$message = PMA_Message::success(__('Showing as PHP code'));
@ -1492,14 +1426,12 @@ function PMA_getQueryResponseForNoResultsReturned($analyzed_sql_results, $db,
$table, $message_to_show, $num_rows, $displayResultsObject, $extra_data
) {
if (PMA_isDeleteTransformationInfo($analyzed_sql_results)) {
PMA_deleteTransformationInfo(
$db, $table, $analyzed_sql_results['analyzed_sql']
);
PMA_deleteTransformationInfo($db, $table, $analyzed_sql_results);
}
$message = PMA_getMessageForNoRowsReturned(
isset($message_to_show) ? $message_to_show : null, $analyzed_sql_results,
$num_rows
isset($message_to_show) ? $message_to_show : null,
$analyzed_sql_results, $num_rows
);
$html_output = '';
@ -1526,10 +1458,9 @@ function PMA_getQueryResponseForNoResultsReturned($analyzed_sql_results, $db,
$response = PMA_Response::getInstance();
$response->addJSON(isset($extra_data) ? $extra_data : array());
$query_type = PMA_DisplayResults::QUERY_TYPE_SELECT;
if ($analyzed_sql_results['analyzed_sql'][0]['querytype'] == $query_type) {
if (!empty($analyzed_sql_results['is_select'])) {
$html_output .= $displayResultsObject->getCreateViewQueryResultOp(
$analyzed_sql_results['analyzed_sql']
$analyzed_sql_results
);
}
}
@ -1688,7 +1619,7 @@ function PMA_getHtmlForSqlQueryResultsTable($displayResultsObject,
$table_html .= $displayResultsObject->getTable(
$result,
$displayParts,
$analyzed_sql_results['analyzed_sql']
$analyzed_sql_results
);
}
@ -1704,17 +1635,29 @@ function PMA_getHtmlForSqlQueryResultsTable($displayResultsObject,
}
$_SESSION['is_multi_query'] = false;
$displayResultsObject->setProperties(
$unlim_num_rows, $fields_meta, $analyzed_sql_results['is_count'],
$analyzed_sql_results['is_export'], $analyzed_sql_results['is_func'],
$analyzed_sql_results['is_analyse'], $num_rows,
$fields_cnt, $GLOBALS['querytime'], $pmaThemeImage, $GLOBALS['text_dir'],
$analyzed_sql_results['is_maint'], $analyzed_sql_results['is_explain'],
$analyzed_sql_results['is_show'], $showtable, $printview, $url_query,
$editable, $browse_dist
$unlim_num_rows,
$fields_meta,
$analyzed_sql_results['is_count'],
$analyzed_sql_results['is_export'],
$analyzed_sql_results['is_func'],
$analyzed_sql_results['is_analyse'],
$num_rows,
$fields_cnt, $GLOBALS['querytime'],
$pmaThemeImage, $GLOBALS['text_dir'],
$analyzed_sql_results['is_maint'],
$analyzed_sql_results['is_explain'],
$analyzed_sql_results['is_show'],
$showtable,
$printview,
$url_query,
$editable,
$browse_dist
);
$table_html .= $displayResultsObject->getTable(
$result, $displayParts, $analyzed_sql_results['analyzed_sql']
$result,
$displayParts,
$analyzed_sql_results
);
$GLOBALS['dbi']->freeResult($result);
}
@ -1854,12 +1797,10 @@ function PMA_getHtmlForIndexesProblems($query_type, $selectedTables, $db)
*
* @return string html
*/
function PMA_getQueryResponseForResultsReturned($result,
$analyzed_sql_results, $db, $table, $message, $sql_data,
$displayResultsObject, $pmaThemeImage,
$unlim_num_rows, $num_rows, $disp_query,
$disp_message, $profiling_results, $query_type, $selectedTables, $sql_query,
$complete_query
function PMA_getQueryResponseForResultsReturned($result, $analyzed_sql_results,
$db, $table, $message, $sql_data, $displayResultsObject, $pmaThemeImage,
$unlim_num_rows, $num_rows, $disp_query, $disp_message, $profiling_results,
$query_type, $selectedTables, $sql_query, $complete_query
) {
// If we are retrieving the full value of a truncated field or the original
// value of a transformed field, show it here
@ -1886,10 +1827,16 @@ function PMA_getQueryResponseForResultsReturned($result,
// - if the result set does not contain all the columns of a unique key
// (unless this is an updatable view)
$sele_exp_cls = $analyzed_sql_results['analyzed_sql'][0]['select_expr_clause'];
$updatableView
= trim($sele_exp_cls) == '*'
&& PMA_Table::isUpdatableView($db, $table);
$updatableView = false;
$statement = $analyzed_sql_results['statement'];
if ($statement instanceof SqlParser\Statements\SelectStatement) {
if (!empty($statement->expr)) {
if ($statement->expr[0]->expr === '*') {
$updatableView = PMA_Table::isUpdatableView($db, $table);
}
}
}
$has_unique = PMA_resultSetContainsUniqueKey(
$db, $table, $fields_meta
@ -2029,7 +1976,6 @@ function PMA_getQueryResponseForResultsReturned($result,
* @param bool|null $find_real_end whether to find real end or not
* @param string $sql_query_for_bookmark the sql query to be stored as bookmark
* @param array|null $extra_data extra data
* @param bool $is_affected whether affected or not
* @param string $message_to_show message to show
* @param string $message message
* @param array|null $sql_data sql data
@ -2049,16 +1995,29 @@ function PMA_getQueryResponseForResultsReturned($result,
*/
function PMA_executeQueryAndSendQueryResponse($analyzed_sql_results,
$is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark,
$extra_data, $is_affected, $message_to_show, $message,
$sql_data, $goto, $pmaThemeImage, $disp_query, $disp_message,
$query_type, $sql_query, $selectedTables, $complete_query
$extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage,
$disp_query, $disp_message, $query_type, $sql_query, $selectedTables,
$complete_query
) {
$html_output = PMA_executeQueryAndGetQueryResponse(
$analyzed_sql_results, $is_gotofile, $db, $table,
$find_real_end, $sql_query_for_bookmark,
$extra_data, $is_affected, $message_to_show, $message,
$sql_data, $goto, $pmaThemeImage, $disp_query, $disp_message,
$query_type, $sql_query, $selectedTables, $complete_query
$analyzed_sql_results, // analyzed_sql_results
$is_gotofile, // is_gotofile
$db, // db
$table, // table
$find_real_end, // find_real_end
$sql_query_for_bookmark, // sql_query_for_bookmark
$extra_data, // extra_data
$message_to_show, // message_to_show
$message, // message
$sql_data, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
$disp_query, // disp_query
$disp_message, // disp_message
$query_type, // query_type
$sql_query, // sql_query
$selectedTables, // selectedTables
$complete_query // complete_query
);
$response = PMA_Response::getInstance();
@ -2075,7 +2034,6 @@ function PMA_executeQueryAndSendQueryResponse($analyzed_sql_results,
* @param bool|null $find_real_end whether to find real end or not
* @param string $sql_query_for_bookmark the sql query to be stored as bookmark
* @param array|null $extra_data extra data
* @param bool $is_affected whether affected or not
* @param string $message_to_show message to show
* @param string $message message
* @param array|null $sql_data sql data
@ -2095,9 +2053,9 @@ function PMA_executeQueryAndSendQueryResponse($analyzed_sql_results,
*/
function PMA_executeQueryAndGetQueryResponse($analyzed_sql_results,
$is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark,
$extra_data, $is_affected, $message_to_show, $message,
$sql_data, $goto, $pmaThemeImage, $disp_query, $disp_message,
$query_type, $sql_query, $selectedTables, $complete_query
$extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage,
$disp_query, $disp_message, $query_type, $sql_query, $selectedTables,
$complete_query
) {
// Include PMA_Index class for use in PMA_DisplayResults class
include_once './libraries/Index.class.php';
@ -2111,7 +2069,7 @@ function PMA_executeQueryAndGetQueryResponse($analyzed_sql_results,
// Handling is not required when it's a union query
// (the parser never sets the 'union' key to 0)
if (PMA_isRememberSortingOrder($analyzed_sql_results)
&& ! isset($analyzed_sql_results['analyzed_sql'][0]['queryflags']['union'])
&& empty($analyzed_sql_results['union'])
) {
if (! isset($_SESSION['sql_from_query_box'])) {
PMA_handleSortOrder($db, $table, $analyzed_sql_results, $sql_query);
@ -2131,11 +2089,7 @@ function PMA_executeQueryAndGetQueryResponse($analyzed_sql_results,
// Do append a "LIMIT" clause?
if (PMA_isAppendLimitClause($analyzed_sql_results)) {
$full_sql_query = PMA_getSqlWithLimitClause(
$analyzed_sql_results['analyzed_sql'],
' LIMIT ' . $_SESSION['tmpval']['pos']
. ', ' . $_SESSION['tmpval']['max_rows'] . " "
);
$full_sql_query = PMA_getSqlWithLimitClause($analyzed_sql_results);
}
$GLOBALS['reload'] = PMA_hasCurrentDbChanged($db);
@ -2155,7 +2109,7 @@ function PMA_executeQueryAndGetQueryResponse($analyzed_sql_results,
);
// No rows returned -> move back to the calling page
if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
if ((0 == $num_rows && 0 == $unlim_num_rows) || $analyzed_sql_results['is_affected']) {
$html_output = PMA_getQueryResponseForNoResultsReturned(
$analyzed_sql_results, $db, $table,
isset($message_to_show) ? $message_to_show : null,

View File

@ -1,997 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* SQL Parser Matching Data
*
* Copyright 2002 Robin Johnson <robbat2@users.sourceforge.net>
* http://www.orbis-terrarum.net/?l=people.robbat2
*
* This data is used by the SQL Parser to recognize keywords
*
* It has been extracted from the lex.h file in the MySQL BK tree
* (around 4.0.2) as well as the MySQL documentation.
*
* It's easier to use only uppercase for proper sorting. In case of
* doubt, use the test case to verify.
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
if (! isset($GLOBALS['sql_delimiter'])) {
$GLOBALS['sql_delimiter'] = ';';
}
/**
* @global array MySQL function names
*/
$PMA_SQPdata_function_name = array (
'ABS',
'ACOS',
'ADDDATE',
'ADDTIME',
'AES_DECRYPT',
'AES_ENCRYPT',
'AREA', // polygon-property-functions.html
'ASBINARY',
'ASCII',
'ASIN',
'ASTEXT',
'ATAN',
'ATAN2',
'AVG',
'BDMPOLYFROMTEXT',
'BDMPOLYFROMWKB',
'BDPOLYFROMTEXT',
'BDPOLYFROMWKB',
'BENCHMARK',
'BIN',
'BIT_AND',
'BIT_COUNT',
'BIT_LENGTH',
'BIT_OR',
'BIT_XOR', // group-by-functions.html
'BOUNDARY', // general-geometry-property-functions.html
'BUFFER',
'CAST',
'CEIL',
'CEILING',
'CENTROID', // multipolygon-property-functions.html
'CHAR', // string-functions.html
'CHARACTER_LENGTH',
'CHARSET', // information-functions.html
'CHAR_LENGTH',
'COALESCE',
'COERCIBILITY', // information-functions.html
'COLLATION', // information-functions.html
'COMPRESS', // string-functions.html
'CONCAT',
'CONCAT_WS',
'CONNECTION_ID',
'CONTAINS',
'CONV',
'CONVERT',
'CONVERT_TZ',
'CONVEXHULL',
'COS',
'COT',
'COUNT',
'CRC32', // mathematical-functions.html
'CROSSES',
'CURDATE',
'CURRENT_DATE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'CURTIME',
'DATABASE',
'DATE', // date-and-time-functions.html
'DATEDIFF', // date-and-time-functions.html
'DATE_ADD',
'DATE_DIFF',
'DATE_FORMAT',
'DATE_SUB',
'DAY',
'DAYNAME',
'DAYOFMONTH',
'DAYOFWEEK',
'DAYOFYEAR',
'DECODE',
'DEFAULT', // miscellaneous-functions.html
'DEGREES',
'DES_DECRYPT',
'DES_ENCRYPT',
'DIFFERENCE',
'DIMENSION', // general-geometry-property-functions.html
'DISJOINT',
'DISTANCE',
'ELT',
'ENCODE',
'ENCRYPT',
'ENDPOINT', // linestring-property-functions.html
'ENVELOPE', // general-geometry-property-functions.html
'EQUALS',
'EXP',
'EXPORT_SET',
'EXTERIORRING', // polygon-property-functions.html
'EXTRACT',
'EXTRACTVALUE', // xml-functions.html
'FIELD',
'FIND_IN_SET',
'FLOOR',
'FORMAT',
'FOUND_ROWS',
'FROM_DAYS',
'FROM_UNIXTIME',
'GEOMCOLLFROMTEXT',
'GEOMCOLLFROMWKB',
'GEOMETRYCOLLECTION',
'GEOMETRYCOLLECTIONFROMTEXT',
'GEOMETRYCOLLECTIONFROMWKB',
'GEOMETRYFROMTEXT',
'GEOMETRYFROMWKB',
'GEOMETRYN', // geometrycollection-property-functions.html
'GEOMETRYTYPE', // general-geometry-property-functions.html
'GEOMFROMTEXT',
'GEOMFROMWKB',
'GET_FORMAT',
'GET_LOCK',
'GLENGTH', // linestring-property-functions.html
'GREATEST',
'GROUP_CONCAT',
'GROUP_UNIQUE_USERS',
'HEX',
'HOUR',
'IF', //control-flow-functions.html
'IFNULL',
'INET_ATON',
'INET_NTOA',
'INSERT', // string-functions.html
'INSTR',
'INTERIORRINGN', // polygon-property-functions.html
'INTERSECTION',
'INTERSECTS',
'INTERVAL',
'ISCLOSED', // multilinestring-property-functions.html
'ISEMPTY', // general-geometry-property-functions.html
'ISNULL',
'ISRING', // linestring-property-functions.html
'ISSIMPLE', // general-geometry-property-functions.html
'IS_FREE_LOCK',
'IS_USED_LOCK', // miscellaneous-functions.html
'LAST_DAY',
'LAST_INSERT_ID',
'LCASE',
'LEAST',
'LEFT',
'LENGTH',
'LINEFROMTEXT',
'LINEFROMWKB',
'LINESTRING',
'LINESTRINGFROMTEXT',
'LINESTRINGFROMWKB',
'LN',
'LOAD_FILE',
'LOCALTIME',
'LOCALTIMESTAMP',
'LOCATE',
'LOG',
'LOG10',
'LOG2',
'LOWER',
'LPAD',
'LTRIM',
'MAKEDATE',
'MAKETIME',
'MAKE_SET',
'MASTER_POS_WAIT',
'MAX',
'MBRCONTAINS',
'MBRDISJOINT',
'MBREQUAL',
'MBRINTERSECTS',
'MBROVERLAPS',
'MBRTOUCHES',
'MBRWITHIN',
'MD5',
'MICROSECOND',
'MID',
'MIN',
'MINUTE',
'MLINEFROMTEXT',
'MLINEFROMWKB',
'MOD',
'MONTH',
'MONTHNAME',
'MPOINTFROMTEXT',
'MPOINTFROMWKB',
'MPOLYFROMTEXT',
'MPOLYFROMWKB',
'MULTILINESTRING',
'MULTILINESTRINGFROMTEXT',
'MULTILINESTRINGFROMWKB',
'MULTIPOINT',
'MULTIPOINTFROMTEXT',
'MULTIPOINTFROMWKB',
'MULTIPOLYGON',
'MULTIPOLYGONFROMTEXT',
'MULTIPOLYGONFROMWKB',
'NAME_CONST', // NAME_CONST()
'NOW',
'NULLIF',
'NUMGEOMETRIES', // geometrycollection-property-functions.html
'NUMINTERIORRINGS', // polygon-property-functions.html
'NUMPOINTS', // linestring-property-functions.html
'OCT',
'OCTET_LENGTH',
'OLD_PASSWORD',
'ORD',
'OVERLAPS',
'PASSWORD',
'PERIOD_ADD',
'PERIOD_DIFF',
'PI',
'POINT',
'POINTFROMTEXT',
'POINTFROMWKB',
'POINTN', // inestring-property-functions.html
'POINTONSURFACE', // multipolygon-property-functions.html
'POLYFROMTEXT',
'POLYFROMWKB',
'POLYGON',
'POLYGONFROMTEXT',
'POLYGONFROMWKB',
'POSITION',
'POW',
'POWER',
'QUARTER',
'QUOTE',
'RADIANS',
'RAND',
'RELATED',
'RELEASE_LOCK',
'REPEAT',
'REPLACE', // string-functions.html
'REVERSE',
'RIGHT',
'ROUND',
'ROW_COUNT', // information-functions.html
'RPAD',
'RTRIM',
'SCHEMA', // information-functions.html
'SECOND',
'SEC_TO_TIME',
'SESSION_USER',
'SHA',
'SHA1',
'SIGN',
'SIN',
'SLEEP', // miscellaneous-functions.html
'SOUNDEX',
'SPACE',
'SQRT',
'SRID', // general-geometry-property-functions.html
'STARTPOINT', // linestring-property-functions.html
'STD',
'STDDEV',
'STDDEV_POP', // group-by-functions.html
'STDDEV_SAMP', // group-by-functions.html
'STRCMP',
'STR_TO_DATE',
'SUBDATE',
'SUBSTR',
'SUBSTRING',
'SUBSTRING_INDEX',
'SUBTIME',
'SUM',
'SYMDIFFERENCE',
'SYSDATE',
'SYSTEM_USER',
'TAN',
'TIME',
'TIMEDIFF',
'TIMESTAMP',
'TIMESTAMPADD',
'TIMESTAMPDIFF',
'TIME_FORMAT',
'TIME_TO_SEC',
'TOUCHES',
'TO_DAYS',
'TRIM',
'TRUNCATE', // mathematical-functions.html
'UCASE',
'UNCOMPRESS', // string-functions.html
'UNCOMPRESSED_LENGTH', // string-functions.html
'UNHEX', // string-functions.html
'UNIQUE_USERS',
'UNIX_TIMESTAMP',
'UPDATEXML', // xml-functions.html
'UPPER',
'USER',
'UTC_DATE',
'UTC_TIME',
'UTC_TIMESTAMP',
'UUID', // miscellaneous-functions.html
'VARIANCE', // group-by-functions.html
'VAR_POP', // group-by-functions.html
'VAR_SAMP', // group-by-functions.html
'VERSION',
'WEEK',
'WEEKDAY',
'WEEKOFYEAR',
'WITHIN',
'X', // point-property-functions.html
'Y', // point-property-functions.html
'YEAR',
'YEARWEEK'
);
/**
* @global array MySQL attributes
*/
$PMA_SQPdata_column_attrib = array (
'ARCHIVE', // Engine
'ASCII',
'AUTO_INCREMENT',
'BDB', // Engine
'BERKELEYDB', // Engine alias BDB
'BINARY',
'BLACKHOLE', // Engine
'CSV', // Engine
'DEFAULT',
'EXAMPLE', // Engine
'FEDERATED', // Engine
'HEAP', // Engine
'INNOBASE', // Engine alias InnoDB
'INNODB', // Engine InnoDB
'ISAM', // Engine
'MARIA', // Engine
'MEMORY', // Engine alias HEAP, but preferred
'MERGE', // Engine
'MRG_ISAM', // Engine
'MRG_MYISAM', // Engine alias MERGE
'MYISAM', // Engine MyISAM
'NATIONAL',
'NDB', // Engine alias NDBCLUSTER
'NDBCLUSTER', // Engine
'PRECISION',
'UNDEFINED',
'UNICODE',
'UNSIGNED',
'VARYING',
'ZEROFILL'
);
/**
* words that are reserved by MySQL and may not be used as identifiers without
* quotes
*
* @see http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
*
* @global array MySQL reserved words
*/
$PMA_SQPdata_reserved_word = array (
'ACCESSIBLE', // 5.1
'ACTION',
'ADD',
'AFTER',
'AGAINST',
'AGGREGATE',
'ALGORITHM',
'ALL',
'ALTER',
'ANALYSE',
'ANALYZE',
'AND',
'AS',
'ASC',
'AUTOCOMMIT',
'AUTO_INCREMENT',
'AVG_ROW_LENGTH',
'BACKUP',
'BEFORE',
'BEGIN',
'BETWEEN',
'BINLOG',
'BOTH',
'BY',
'CALL',
'CASCADE',
'CASE',
'CHANGE',
'CHANGED',
'CHARSET',
'CHECK',
'CHECKSUM',
'COLLATE',
'COLLATION',
'COLUMN',
'COLUMNS',
'COMMENT',
'COMMIT',
'COMMITTED',
'COMPRESSED',
'CONCURRENT',
'CONSTRAINT',
'CONTAINS',
'CONVERT',
'CREATE',
'CROSS',
'CURRENT_TIMESTAMP',
'DATABASE',
'DATABASES',
'DAY',
'DAY_HOUR',
'DAY_MINUTE',
'DAY_SECOND',
'DECLARE',
'DEFINER',
'DELAYED',
'DELAY_KEY_WRITE',
'DELETE',
'DESC',
'DESCRIBE',
'DETERMINISTIC',
'DISTINCT',
'DISTINCTROW',
'DIV',
'DO',
'DROP',
'DUMPFILE',
'DUPLICATE',
'DYNAMIC',
'EACH',
'ELSE',
'ELSEIF',
'ENCLOSED',
'END',
'ENGINE',
'ENGINES',
'ESCAPE',
'ESCAPED',
'EVENTS',
'EXECUTE',
'EXISTS',
'EXIT',
'EXPLAIN',
'EXTENDED',
'FALSE',
'FAST',
'FIELDS',
'FILE',
'FIRST',
'FIXED',
'FLUSH',
'FOR',
'FORCE',
'FOREIGN',
'FROM',
'FULL',
'FULLTEXT',
'FUNCTION',
'GEMINI',
'GEMINI_SPIN_RETRIES',
'GLOBAL',
'GRANT',
'GRANTS',
'GROUP',
'HAVING',
'HEAP',
'HIGH_PRIORITY',
'HOSTS',
'HOUR',
'HOUR_MINUTE',
'HOUR_SECOND',
'IDENTIFIED',
'IF',
'IGNORE',
'IGNORE_SERVER_IDS',
'IN',
'INDEX',
'INDEXES',
'INFILE',
'INNER',
'INOUT',
'INSERT',
'INSERT_ID',
'INSERT_METHOD',
'INTERVAL',
'INTO',
'INVOKER',
'IS',
'ISOLATION',
'JOIN',
'KEY',
'KEYS',
'KILL',
'LAST_INSERT_ID',
'LEADING',
'LEFT',
'LIKE',
'LIMIT',
'LINEAR', // 5.1
'LINES',
'LOAD',
'LOCAL',
'LOCK',
'LOCKS',
'LOGS',
'LOW_PRIORITY',
'MARIA', // 5.1 ?
'MASTER_CONNECT_RETRY',
'MASTER_HEARTBEAT_PERIOD',
'MASTER_HOST',
'MASTER_LOG_FILE',
'MASTER_LOG_POS',
'MASTER_PASSWORD',
'MASTER_PORT',
'MASTER_USER',
'MATCH',
'MAXVALUE',
'MAX_CONNECTIONS_PER_HOUR',
'MAX_QUERIES_PER_HOUR',
'MAX_ROWS',
'MAX_UPDATES_PER_HOUR',
'MAX_USER_CONNECTIONS',
'MEDIUM',
'MERGE',
'MINUTE',
'MINUTE_SECOND',
'MIN_ROWS',
'MODE',
'MODIFIES',
'MODIFY',
'MONTH',
'MRG_MYISAM',
'MYISAM',
'NAMES',
'NATURAL',
// 'NO' is not allowed in SQL-99 but is allowed in MySQL
//'NO',
'NOT',
'NULL',
'OFFSET',
'ON',
'OPEN',
'OPTIMIZE',
'OPTION',
'OPTIONALLY',
'OR',
'ORDER',
'OUT',
'OUTER',
'OUTFILE',
'PACK_KEYS',
'PAGE', // 5.1-maria ?
'PAGE_CHECKSUM', // 5.1
'PARTIAL',
'PARTITION', // 5.1
'PARTITIONS', // 5.1
'PASSWORD',
'PRIMARY',
'PRIVILEGES',
'PROCEDURE',
'PROCESS',
'PROCESSLIST',
'PURGE',
'QUICK',
'RAID0',
'RAID_CHUNKS',
'RAID_CHUNKSIZE',
'RAID_TYPE',
'RANGE', // 5.1
'READ',
'READS',
'READ_ONLY', // 5.1
'READ_WRITE', // 5.1
'REFERENCES',
'REGEXP',
'RELOAD',
'RENAME',
'REPAIR',
'REPEATABLE',
'REPLACE',
'REPLICATION',
'RESET',
'RESIGNAL',
'RESTORE',
'RESTRICT',
'RETURN',
'RETURNS',
'REVOKE',
'RIGHT',
'RLIKE',
'ROLLBACK',
'ROW',
'ROWS',
'ROW_FORMAT',
'SECOND',
'SECURITY',
'SELECT',
'SEPARATOR',
'SERIALIZABLE',
'SESSION',
'SHARE',
'SHOW',
'SHUTDOWN',
'SIGNAL',
'SLAVE',
'SLOW',
'SONAME',
'SOUNDS', // string-functions.html
'SQL',
'SQL_AUTO_IS_NULL',
'SQL_BIG_RESULT',
'SQL_BIG_SELECTS',
'SQL_BIG_TABLES',
'SQL_BUFFER_RESULT',
'SQL_CACHE',
'SQL_CALC_FOUND_ROWS',
'SQL_LOG_BIN',
'SQL_LOG_OFF',
'SQL_LOG_UPDATE',
'SQL_LOW_PRIORITY_UPDATES',
'SQL_MAX_JOIN_SIZE',
'SQL_NO_CACHE',
'SQL_QUOTE_SHOW_CREATE',
'SQL_SAFE_UPDATES',
'SQL_SELECT_LIMIT',
'SQL_SLAVE_SKIP_COUNTER',
'SQL_SMALL_RESULT',
'SQL_WARNINGS',
'START',
'STARTING',
'STATUS',
'STOP',
'STORAGE',
'STRAIGHT_JOIN',
'STRING',
'STRIPED',
'SUPER',
'TABLE',
'TABLES',
'TEMPORARY',
'TERMINATED',
'THEN',
'TO',
'TRAILING',
'TRANSACTIONAL', // 5.1 ?
'TRIGGER',
'TRUE',
'TRUNCATE',
'TYPE',
'TYPES',
'UNCOMMITTED',
'UNION',
'UNIQUE',
'UNLOCK',
'UPDATE',
'USAGE',
'USE',
'USING',
'VALUES',
'VARIABLES',
'VIEW',
'WHEN',
'WHERE',
'WITH',
'WORK',
'WRITE',
'XOR',
'YEAR_MONTH'
);
/**
* words forbidden to be used as column or table name without quotes
* as seen in http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
*
* @global array MySQL forbidden words
*/
$PMA_SQPdata_forbidden_word = array (
'ACCESSIBLE',
'ADD',
'ALL',
'ALTER',
'ANALYZE',
'AND',
'AS',
'ASC',
'ASENSITIVE',
'BEFORE',
'BETWEEN',
'BIGINT',
'BINARY',
'BLOB',
'BOTH',
'BY',
'CALL',
'CASCADE',
'CASE',
'CHANGE',
'CHAR',
'CHARACTER',
'CHECK',
'COLLATE',
'COLUMN',
'CONDITION',
'CONSTRAINT',
'CONTINUE',
'CONVERT',
'CREATE',
'CROSS',
'CURRENT_DATE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'CURSOR',
'DATABASE',
'DATABASES',
'DAY_HOUR',
'DAY_MICROSECOND',
'DAY_MINUTE',
'DAY_SECOND',
'DEC',
'DECIMAL',
'DECLARE',
'DEFAULT',
'DELAYED',
'DELETE',
'DESC',
'DESCRIBE',
'DETERMINISTIC',
'DISTINCT',
'DISTINCTROW',
'DIV',
'DOUBLE',
'DROP',
'DUAL',
'EACH',
'ELSE',
'ELSEIF',
'ENCLOSED',
'ESCAPED',
'EXISTS',
'EXIT',
'EXPLAIN',
'FALSE',
'FETCH',
'FLOAT',
'FLOAT4',
'FLOAT8',
'FOR',
'FORCE',
'FOREIGN',
'FROM',
'FULLTEXT',
'GET',
'GRANT',
'GROUP',
'HAVING',
'HIGH_PRIORITY',
'HOUR_MICROSECOND',
'HOUR_MINUTE',
'HOUR_SECOND',
'IF',
'IGNORE',
'IGNORE_SERVER_IDS',
'IN',
'INDEX',
'INFILE',
'INNER',
'INOUT',
'INSENSITIVE',
'INSERT',
'INT',
'INT1',
'INT2',
'INT3',
'INT4',
'INT8',
'INTEGER',
'INTERVAL',
'INTO',
'IO_AFTER_GTIDS',
'IO_BEFORE_GTIDS',
'IS',
'ITERATE',
'JOIN',
'KEY',
'KEYS',
'KILL',
'LEADING',
'LEAVE',
'LEFT',
'LIKE',
'LIMIT',
'LINEAR',
'LINES',
'LOAD',
'LOCALTIME',
'LOCALTIMESTAMP',
'LOCK',
'LONG',
'LONGBLOB',
'LONGTEXT',
'LOOP',
'LOW_PRIORITY',
'MASTER_BIND',
'MASTER_HEARTBEAT_PERIOD',
'MASTER_SSL_VERIFY_SERVER_CERT',
'MATCH',
'MAXVALUE',
'MEDIUMBLOB',
'MEDIUMINT',
'MEDIUMTEXT',
'MIDDLEINT',
'MINUTE_MICROSECOND',
'MINUTE_SECOND',
'MOD',
'MODIFIES',
'NATURAL',
'NOT',
'NO_WRITE_TO_BINLOG',
'NULL',
'NUMERIC',
'ON',
'ONE_SHOT',
'OPTIMIZE',
'OPTION',
'OPTIONALLY',
'OR',
'ORDER',
'OUT',
'OUTER',
'OUTFILE',
'PARTITION',
'PRECISION',
'PRIMARY',
'PROCEDURE',
'PURGE',
'RANGE',
'READ',
'READS',
'READ_WRITE',
'REAL',
'REFERENCES',
'REGEXP',
'RELEASE',
'RENAME',
'REPEAT',
'REPLACE',
'REQUIRE',
'RESIGNAL',
'RESTRICT',
'RETURN',
'REVOKE',
'RIGHT',
'RLIKE',
'SCHEMA',
'SCHEMAS',
'SECOND_MICROSECOND',
'SELECT',
'SENSITIVE',
'SEPARATOR',
'SET',
'SHOW',
'SIGNAL',
'SLOW',
'SMALLINT',
'SPATIAL',
'SPECIFIC',
'SQL',
'SQLEXCEPTION',
'SQLSTATE',
'SQLWARNING',
'SQL_AFTER_GTIDS',
'SQL_BEFORE_GTIDS',
'SQL_BIG_RESULT',
'SQL_CALC_FOUND_ROWS',
'SQL_SMALL_RESULT',
'SSL',
'STARTING',
'STRAIGHT_JOIN',
'TABLE',
'TERMINATED',
'THEN',
'TINYBLOB',
'TINYINT',
'TINYTEXT',
'TO',
'TRAILING',
'TRIGGER',
'TRUE',
'UNDO',
'UNION',
'UNIQUE',
'UNLOCK',
'UNSIGNED',
'UPDATE',
'USAGE',
'USE',
'USING',
'UTC_DATE',
'UTC_TIME',
'UTC_TIMESTAMP',
'VALUES',
'VARBINARY',
'VARCHAR',
'VARCHARACTER',
'VARYING',
'WHEN',
'WHERE',
'WHILE',
'WITH',
'WRITE',
'XOR',
'YEAR_MONTH',
'ZEROFILL'
);
/**
* the MySQL column/data types
*
* @see http://dev.mysql.com/doc/refman/5.1/en/data-types.html
* @see http://dev.mysql.com/doc/refman/5.1/en/mysql-spatial-datatypes.html
*
* @global array MySQL column types
*/
$PMA_SQPdata_column_type = array (
'BIGINT',
'BINARY',
'BIT',
'BLOB',
'BOOL',
'BOOLEAN', // numeric-type-overview.html
'CHAR',
'CHARACTER',
'DATE',
'DATETIME',
'DEC',
'DECIMAL',
'DOUBLE',
'ENUM',
'FLOAT',
'FLOAT4',
'FLOAT8',
'GEOMETRY', // spatial
'GEOMETRYCOLLECTION', // spatial
'INT',
'INT1',
'INT2',
'INT3',
'INT4',
'INT8',
'INTEGER',
'LINESTRING', // spatial
'LONG',
'LONGBLOB',
'LONGTEXT',
'MEDIUMBLOB',
'MEDIUMINT',
'MEDIUMTEXT',
'MIDDLEINT',
'MULTILINESTRING', // spatial
'MULTIPOINT', // spatial
'MULTIPOLYGON', // spatial
'NCHAR',
'NUMERIC',
'POINT', // spatial
'POLYGON', // spatial
'REAL',
'SERIAL', // alias
'SET',
'SMALLINT',
'TEXT',
'TIME',
'TIMESTAMP',
'TINYBLOB',
'TINYINT',
'TINYTEXT',
'VARBINARY',
'VARCHAR',
'YEAR'
);
?>

File diff suppressed because it is too large Load Diff

View File

@ -3004,9 +3004,24 @@ function PMA_displayTableBrowseForSelectedColumns($db, $table, $goto,
include_once 'libraries/sql.lib.php';
PMA_executeQueryAndSendQueryResponse(
$analyzed_sql_results, false, $db, $table, null, null, null, false,
null, null, null, $goto, $pmaThemeImage, null, null,
null, $sql_query, null, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$db, // db
$table, // table
null, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}

View File

@ -2,8 +2,6 @@
<phpunit bootstrap="test/bootstrap-dist.php"
backupGlobals="true"
backupStaticAttributes="false"
strict="true"
timeoutForSmallTests="3"
colors="true"
verbose="true">
@ -43,12 +41,13 @@
<directory suffix=".php">.</directory>
<exclude>
<!-- we don't care about coverage of embedded libraries -->
<directory suffix=".php">libraries/tcpdf</directory>
<directory suffix=".php">libraries/phpseclib</directory>
<directory suffix=".inc">libraries/php-gettext</directory>
<directory suffix=".php">libraries/bfShapeFiles</directory>
<directory suffix=".php">libraries/php-gettext</directory>
<directory suffix=".inc">libraries/php-gettext</directory>
<directory suffix=".php">libraries/phpseclib</directory>
<directory suffix=".php">libraries/plugins/auth/swekey/</directory>
<directory suffix=".php">libraries/sql-parser</directory>
<directory suffix=".php">libraries/tcpdf</directory>
<!-- code sniffer checker -->
<directory suffix=".php">PMAStandard</directory>
<!-- examples for users -->

38
sql.php
View File

@ -17,7 +17,6 @@ require_once 'libraries/Header.class.php';
require_once 'libraries/check_user_privileges.lib.php';
require_once 'libraries/bookmark.lib.php';
require_once 'libraries/sql.lib.php';
require_once 'libraries/sqlparser.lib.php';
require_once 'libraries/config/page_settings.class.php';
PMA_PageSettings::showGroup('Browse');
@ -197,23 +196,22 @@ if ($goto == 'sql.php') {
} // end if
PMA_executeQueryAndSendQueryResponse(
$analyzed_sql_results,
$is_gotofile,
$db,
$table,
isset($find_real_end) ? $find_real_end : null,
isset($import_text) ? $import_text : null,
isset($extra_data) ? $extra_data : null,
$is_affected,
isset($message_to_show) ? $message_to_show : null,
isset($message) ? $message : null,
isset($sql_data) ? $sql_data : null,
$goto,
$pmaThemeImage,
isset($disp_query) ? $display_query : null,
isset($disp_message) ? $disp_message : null,
isset($query_type) ? $query_type : null,
$sql_query,
isset($selected) ? $selected : null,
isset($complete_query) ? $complete_query : null
$analyzed_sql_results, // analyzed_sql_results
$is_gotofile, // is_gotofile
$db, // db
$table, // table
isset($find_real_end) ? $find_real_end : null, // find_real_end
isset($import_text) ? $import_text : null, // sql_query_for_bookmark
isset($extra_data) ? $extra_data : null, // extra_data
isset($message_to_show) ? $message_to_show : null, // message_to_show
isset($message) ? $message : null, // message
isset($sql_data) ? $sql_data : null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
isset($disp_query) ? $display_query : null, // disp_query
isset($disp_message) ? $disp_message : null, // disp_message
isset($query_type) ? $query_type : null, // query_type
$sql_query, // sql_query
isset($selected) ? $selected : null, // selectedTables
isset($complete_query) ? $complete_query : null // complete_query
);

View File

@ -105,74 +105,61 @@ $export_page_title = __('View dump (schema) of table');
// generate WHERE clause (if we are asked to export specific rows)
if (! empty($sql_query)) {
// Parse query so we can work with tokens
$parsed_sql = PMA_SQP_parse($sql_query);
$analyzed_sql = PMA_SQP_analyze($parsed_sql);
$parser = new SqlParser\Parser($sql_query);
// Need to generate WHERE clause?
if (isset($where_clause)) {
if ((!empty($parser->statements[0]))
&& ($parser->statements[0] instanceof SqlParser\Statements\SelectStatement)
) {
// If a table alias is used, get rid of it since
// where clauses are on real table name
if ($analyzed_sql[0]['table_ref'][0]['table_alias']) {
// Exporting selected rows is only allowed for queries involving
// a single table. So we can safely assume that there is only one
// table in 'table_ref' array.
$temp_sql_array = preg_split('/\bfrom\b/i', $sql_query);
$sql_query = $temp_sql_array[0] . 'FROM ';
if (! empty($analyzed_sql[0]['table_ref'][0]['db'])) {
$sql_query .= PMA_Util::backquote(
$analyzed_sql[0]['table_ref'][0]['db']
);
$sql_query .= '.';
// Finding aliases and removing them, but we keep track of them to be
// able to replace them in select expression too.
$aliases = array();
foreach ($parser->statements[0]->from as $from) {
if ((!empty($from->table)) && (!empty($from->alias))) {
$aliases[$from->alias] = $from->table;
// We remove the alias of the table because they are going to
// be replaced anyway.
$from->alias = null;
$from->expr = null; // Force rebuild.
}
$sql_query .= PMA_Util::backquote(
$analyzed_sql[0]['table_ref'][0]['table_name']
}
// Replacing the aliases in select expressions.
foreach ($parser->statements[0]->expr as $expr) {
if ((!empty($expr->table)) && (!empty($aliases[$expr->table]))) {
// Changing the table to null (leave the MySQL to find the
// right table).
// This is possible because exporting selected rows is only
// allowed for queries involing a single table.
$expr->table = null;
$expr->expr = null; // Force rebuild.
}
}
// Rebuilding the SELECT and FROM clauses.
$replaces = array(
array('SELECT', 'SELECT ' . SqlParser\Components\ExpressionArray::build($parser->statements[0]->expr)),
array('FROM', 'FROM ' . SqlParser\Components\ExpressionArray::build($parser->statements[0]->from)),
);
// Checking if the WHERE clause has to be replaced.
if ((!empty($where_clause)) && (is_array($where_clause))) {
$replaces[] = array(
'WHERE', 'WHERE (' . implode(') OR (', $where_clause) . ')'
);
}
unset($temp_sql_array);
// Regular expressions which can appear in sql query,
// before the sql segment which remains as it is.
$regex_array = array(
'/\bwhere\b/i', '/\bgroup by\b/i', '/\bhaving\b/i', '/\border by\b/i'
// Preparing to remove the LIMIT clause.
$replaces[] = array('LIMIT', '');
// Replacing the clauses.
$sql_query = SqlParser\Utils\Query::replaceClauses(
$parser->statements[0],
$parser->list,
$replaces
);
$first_occurring_regex = PMA_Util::getFirstOccurringRegularExpression(
$regex_array, $sql_query
);
unset($regex_array);
// The part "SELECT `id`, `name` FROM `customers`"
// is not modified by the next code segment, when exporting
// the result set from a query such as
// "SELECT `id`, `name` FROM `customers` WHERE id NOT IN
// ( SELECT id FROM companies WHERE name LIKE '%u%')"
if (! is_null($first_occurring_regex)) {
$temp_sql_array = preg_split($first_occurring_regex, $sql_query);
$sql_query = $temp_sql_array[0];
}
unset($first_occurring_regex, $temp_sql_array);
// Append the where clause using the primary key of each row
if (is_array($where_clause) && (count($where_clause) > 0)) {
$sql_query .= ' WHERE (' . implode(') OR (', $where_clause) . ')';
}
if (!empty($analyzed_sql[0]['group_by_clause'])) {
$sql_query .= ' GROUP BY ' . $analyzed_sql[0]['group_by_clause'];
}
if (!empty($analyzed_sql[0]['having_clause'])) {
$sql_query .= ' HAVING ' . $analyzed_sql[0]['having_clause'];
}
if (!empty($analyzed_sql[0]['order_by_clause'])) {
$sql_query .= ' ORDER BY ' . $analyzed_sql[0]['order_by_clause'];
}
} else {
// Just crop LIMIT clause
$sql_query = $analyzed_sql[0]['section_before_limit']
. $analyzed_sql[0]['section_after_limit'];
}
echo PMA_Util::getMessage(PMA_Message::success());
}

View File

@ -145,9 +145,24 @@ if (!empty($submit_mult)) {
include_once 'libraries/parse_analyze.inc.php';
PMA_executeQueryAndSendQueryResponse(
$analyzed_sql_results, false, $db, $table, null, null, null, false, null,
null, null, $goto, $pmaThemeImage, null, null, null, $sql_query,
null, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$db, // db
$table, // table
null, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}
}

View File

@ -64,6 +64,7 @@ if (! isset($_POST['columnsToDisplay']) && ! isset($_POST['displayAllColumns']))
$response->addHTML($table_search->getSelectionForm($goto));
} else {
/**
* Selection criteria have been submitted -> do the work
*/
@ -75,8 +76,23 @@ if (! isset($_POST['columnsToDisplay']) && ! isset($_POST['displayAllColumns']))
include_once 'libraries/parse_analyze.inc.php';
PMA_executeQueryAndSendQueryResponse(
$analyzed_sql_results, false, $db, $table, null, null, null, false,
null, null, null, $GLOBALS['goto'], $pmaThemeImage, null,
null, null, $sql_query, null, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$db, // db
$table, // table
null, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$GLOBALS['goto'], // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}

View File

@ -51,11 +51,11 @@ if (isset($_REQUEST['reserved_word_check'])) {
$columns_names = $_REQUEST['field_name'];
$reserved_keywords_names = array();
foreach ($columns_names as $column) {
if (PMA_SQP_isKeyWord(trim($column))) {
if (SqlParser\Context::isKeyword(trim($column), true)) {
$reserved_keywords_names[] = trim($column);
}
}
if (PMA_SQP_isKeyWord(trim($table))) {
if (SqlParser\Context::isKeyword(trim($table), true)) {
$reserved_keywords_names[] = trim($table);
}
if (count($reserved_keywords_names) == 0) {
@ -199,7 +199,14 @@ $show_create_table = $GLOBALS['dbi']->fetchValue(
. PMA_Util::backquote($table),
0, 1
);
$analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
$parser = new SqlParser\Parser($show_create_table);
/**
* @var CreateStatement $stmt
*/
$stmt = $parser->statements[0];
$create_table_fields = SqlParser\Utils\Table::getFields($stmt);
/**
* prepare table infos

View File

@ -143,8 +143,13 @@ if (isset($_POST['zoom_submit'])
}
//Get unique condition on each row (will be needed for row update)
$uniqueCondition = PMA_Util::getUniqueCondition(
$result, count($table_search->getColumnNames()), $fields_meta, $tmpRow,
true
$result, // handle
count($table_search->getColumnNames()), // fields_cnt
$fields_meta, // fields_meta
$tmpRow, // row
true, // force_unique
false, // restrict_to_table
null // analyzed_sql_results
);
//Append it to row array as where_clause
$row['where_clause'] = $uniqueCondition[0];

View File

@ -55,6 +55,7 @@ $CFG = new PMA_Config();
// Initialize PMA_VERSION variable
define('PMA_VERSION', $CFG->get('PMA_VERSION'));
unset($CFG);
require_once 'libraries/sql-parser/autoload.php';
// Set proxy information from env, if available
$http_proxy = getenv('http_proxy');

View File

@ -16,7 +16,6 @@ require_once 'libraries/core.lib.php';
require_once 'libraries/database_interface.inc.php';
require_once 'libraries/Tracker.class.php';
require_once 'libraries/relation.lib.php';
require_once 'libraries/sqlparser.lib.php';
/**
* Tests for PMA_DBQbe class

View File

@ -94,15 +94,16 @@ class PMA_DisplayResults_Test extends PHPUnit_Framework_TestCase
*/
public function testisSelect()
{
$analyzed_sql = array(array());
$analyzed_sql[0]['select_expr'] = array();
$analyzed_sql[0]['queryflags']['select_from'] = 'pma';
$analyzed_sql[0]['table_ref'] = array('table_ref');
$parser = new \SqlParser\Parser('SELECT * FROM pma');
$this->assertTrue(
$this->_callPrivateFunction(
'_isSelect',
array($analyzed_sql)
array(
array(
'statement' => $parser->statements[0],
'select_from' => true,
),
)
)
);
}
@ -349,57 +350,6 @@ class PMA_DisplayResults_Test extends PHPUnit_Framework_TestCase
);
}
/**
* Data provider for testGetSortParams
*
* @return array parameters and output
*/
public function dataProviderForGetSortParams()
{
return array(
array('', array(array(''), array(''), array(''))),
array(
'`a_sales`.`customer_id` ASC',
array(
array('`a_sales`.`customer_id` ASC'),
array('`a_sales`.`customer_id`'),
array('ASC')
)
),
array(
'`a_sales`.`customer_id` ASC, `b_sales`.`customer_id` DESC',
array(
array(
'`a_sales`.`customer_id` ASC',
'`b_sales`.`customer_id` DESC'
),
array('`a_sales`.`customer_id`', '`b_sales`.`customer_id`'),
array('ASC', 'DESC')
)
),
);
}
/**
* Test for _getSortParams
*
* @param string $order_by_clause the order by clause of the sql query
* @param string $output output of _getSortParams
*
* @return void
*
* @dataProvider dataProviderForGetSortParams
*/
public function testGetSortParams($order_by_clause, $output)
{
$this->assertEquals(
$output,
$this->_callPrivateFunction(
'_getSortParams', array($order_by_clause)
)
);
}
/**
* Data provider for testGetCheckboxForMultiRowSubmissions
*
@ -1288,26 +1238,18 @@ class PMA_DisplayResults_Test extends PHPUnit_Framework_TestCase
*/
public function dataProviderForTestSetHighlightedColumnGlobalField()
{
$parser = new SqlParser\Parser(
'SELECT * FROM db_name WHERE `db_name`.`tbl`.id > 0 AND `id` < 10'
);
return array(
array(
array(),
array()
),
array(
array('statement' => $parser->statements[0]),
array(
0 => array(
'where_clause_identifiers' => array(
0 => '`id`',
1 => '`id`',
2 => '`db_name`'
)
)
'db_name' => 'true',
'tbl' => 'true',
'id' => 'true',
),
array(
'`id`' => 'true',
'`db_name`' => 'true'
)
)
),
);
}
@ -1620,7 +1562,7 @@ class PMA_DisplayResults_Test extends PHPUnit_Framework_TestCase
* @param string $default_function the default transformation function
* @param string $transform_options the transformation parameters
* @param boolean $is_field_truncated is data truncated due to LimitChars
* @param array $analyzed_sql the analyzed query
* @param array $analyzed_sql_results the analyzed query
* @param integer $dt_result the link id associated to the query
* which results have to be displayed
* @param integer $col_index the column index
@ -1634,7 +1576,7 @@ class PMA_DisplayResults_Test extends PHPUnit_Framework_TestCase
$protectBinary, $column, $class, $meta, $map,
$_url_params, $condition_field, $transformation_plugin,
$default_function, $transform_options, $is_field_truncated,
$analyzed_sql, $dt_result, $col_index, $output
$analyzed_sql_results, $dt_result, $col_index, $output
) {
$_SESSION['tmpval']['display_binary'] = true;
$_SESSION['tmpval']['display_blob'] = false;
@ -1648,7 +1590,7 @@ class PMA_DisplayResults_Test extends PHPUnit_Framework_TestCase
array(
$column, $class, $meta, $map, $_url_params, $condition_field,
$transformation_plugin, $default_function, $transform_options,
$is_field_truncated, $analyzed_sql, &$dt_result, $col_index
$is_field_truncated, $analyzed_sql_results, &$dt_result, $col_index
)
)
);

View File

@ -16,7 +16,6 @@ require_once 'libraries/Util.class.php';
require_once 'libraries/php-gettext/gettext.inc';
require_once 'libraries/database_interface.inc.php';
require_once 'libraries/relation.lib.php';
require_once 'libraries/sqlparser.lib.php';
require_once 'libraries/Theme.class.php';
require_once 'libraries/Tracker.class.php';
require_once 'libraries/Types.class.php';

View File

@ -10,7 +10,6 @@
* Include to test.
*/
require_once 'libraries/Table.class.php';
require_once 'libraries/sqlparser.lib.php';
require_once 'libraries/mysql_charsets.lib.php';
require_once 'libraries/Util.class.php';
require_once 'libraries/database_interface.inc.php';
@ -607,37 +606,6 @@ class PMA_Table_Test extends PHPUnit_Framework_TestCase
);
}
/**
* Test for analyzeStructure
*
* @return void
*/
public function testAnalyzeStructure()
{
$this->assertEquals(
false,
PMA_Table::analyzeStructure()
);
//validate that it is the same as DBI fetchResult
$show_create_table = PMA_Table::analyzeStructure('PMA', 'PMA_BookMark');
$this->assertEquals(
array('type'=>'DATA_TYPE'),
$show_create_table[0]['create_table_fields']['COLUMN_NAME']
);
//not a view
$show_create_table = PMA_Table::analyzeStructure('PMA', 'PMA_BookMark_2');
$this->assertEquals(
array('type'=>'INT', 'timestamp_not_null'=>false),
$show_create_table[0]['create_table_fields']['id']
);
$this->assertEquals(
array('type'=>'TEXT', 'timestamp_not_null'=>false),
$show_create_table[0]['create_table_fields']['username']
);
}
/**
* Test for isMerge
*

View File

@ -11,7 +11,6 @@ require_once 'libraries/Util.class.php';
require_once 'libraries/Config.class.php';
require_once 'libraries/Theme_Manager.class.php';
require_once 'libraries/php-gettext/gettext.inc';
require_once 'libraries/sqlparser.lib.php';
require_once 'libraries/url_generating.lib.php';
/**

View File

@ -18,42 +18,6 @@ require_once 'libraries/Util.class.php';
*/
class PMA_Util_Test extends PHPUnit_Framework_TestCase
{
/**
* Test for analyze Limit Clause
*
* @return void
*/
public function testAnalyzeLimitClause()
{
$limit_data = PMA_Util::analyzeLimitClause("limit 2,4");
$this->assertEquals(
'2',
$limit_data['start']
);
$this->assertEquals(
'4',
$limit_data['length']
);
$limit_data = PMA_Util::analyzeLimitClause("limit 3");
$this->assertEquals(
'0',
$limit_data['start']
);
$this->assertEquals(
'3',
$limit_data['length']
);
$limit_data = PMA_Util::analyzeLimitClause("limit 3,2,5");
$this->assertFalse($limit_data);
$limit_data = PMA_Util::analyzeLimitClause("limit");
$this->assertFalse($limit_data);
$limit_data = PMA_Util::analyzeLimitClause("limit ");
$this->assertFalse($limit_data);
}
/**
* Test for createGISData

Some files were not shown because too many files have changed in this diff Show More