gcdb::get_table_from_query()
最后更新于:2021-11-26 09:00:54
gcdb::get_table_from_query( string$query)Finds the first table name referenced in a query.
参数
- $query
-
(string) (Required) The query to search.
响应
(string|false) The table name found, or false if a table couldn’t be found.
源文件
文件: gc-includes/gc-db.php
protected function get_table_from_query( $query ) {
// Remove characters that can legally trail the table name.
$query = rtrim( $query, ';/-#' );
// Allow (select...) union [...] style queries. Use the first query's table name.
$query = ltrim( $query, "rnt (" );
// Strip everything between parentheses except nested selects.
$query = preg_replace( '/((?!s*select)[^(]*?)/is', '()', $query );
// Quickly match most common queries.
if ( preg_match(
'/^s*(?:'
. 'SELECT.*?s+FROM'
. '|INSERT(?:s+LOW_PRIORITY|s+DELAYED|s+HIGH_PRIORITY)?(?:s+IGNORE)?(?:s+INTO)?'
. '|REPLACE(?:s+LOW_PRIORITY|s+DELAYED)?(?:s+INTO)?'
. '|UPDATE(?:s+LOW_PRIORITY)?(?:s+IGNORE)?'
. '|DELETE(?:s+LOW_PRIORITY|s+QUICK|s+IGNORE)*(?:.+?FROM)?'
. ')s+((?:[0-9a-zA-Z$_.`-]|[xC2-xDF][x80-xBF])+)/is',
$query,
$maybe
) ) {
return str_replace( '`', '', $maybe[1] );
}
// SHOW TABLE STATUS and SHOW TABLES WHERE Name = 'gc_posts'
if ( preg_match( '/^s*SHOWs+(?:TABLEs+STATUS|(?:FULLs+)?TABLES).+WHEREs+Names*=s*("|')((?:[0-9a-zA-Z$_.-]|[xC2-xDF][x80-xBF])+)\1/is', $query, $maybe ) ) {
return $maybe[2];
}
/*
* SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'gc_123_%'
* This quoted LIKE operand seldom holds a full table name.
* It is usually a pattern for matching a prefix so we just
* strip the trailing % and unescape the _ to get 'gc_123_'
* which drop-ins can use for routing these SQL statements.
*/
if ( preg_match( '/^s*SHOWs+(?:TABLEs+STATUS|(?:FULLs+)?TABLES)s+(?:WHEREs+Names+)?LIKEs*("|')((?:[\\0-9a-zA-Z$_.-]|[xC2-xDF][x80-xBF])+)%?\1/is', $query, $maybe ) ) {
return str_replace( '\_', '_', $maybe[2] );
}
// Big pattern for the rest of the table-related queries.
if ( preg_match(
'/^s*(?:'
. '(?:EXPLAINs+(?:EXTENDEDs+)?)?SELECT.*?s+FROM'
. '|DESCRIBE|DESC|EXPLAIN|HANDLER'
. '|(?:LOCK|UNLOCK)s+TABLE(?:S)?'
. '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*s+TABLE'
. '|TRUNCATE(?:s+TABLE)?'
. '|CREATE(?:s+TEMPORARY)?s+TABLE(?:s+IFs+NOTs+EXISTS)?'
. '|ALTER(?:s+IGNORE)?s+TABLE'
. '|DROPs+TABLE(?:s+IFs+EXISTS)?'
. '|CREATE(?:s+w+)?s+INDEX.*s+ON'
. '|DROPs+INDEX.*s+ON'
. '|LOADs+DATA.*INFILE.*INTOs+TABLE'
. '|(?:GRANT|REVOKE).*ONs+TABLE'
. '|SHOWs+(?:.*FROM|.*TABLE)'
. ')s+(*s*((?:[0-9a-zA-Z$_.`-]|[xC2-xDF][x80-xBF])+)s*)*/is',
$query,
$maybe
) ) {
return str_replace( '`', '', $maybe[1] );
}
return false;
}