Update website

This commit is contained in:
Guilhem Lavaux 2024-11-19 08:02:04 +01:00
parent 4413528994
commit 1d90fbf296
6865 changed files with 1091082 additions and 0 deletions

View file

@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Query;
use PhpMyAdmin\Util;
use function array_shift;
use function count;
use function is_array;
/**
* Handles caching results
*/
class Cache
{
/** @var array Table data cache */
private $tableCache = [];
/**
* Caches table data so Table does not require to issue
* SHOW TABLE STATUS again
*
* @param array $tables information for tables of some databases
* @param string|bool $table table name
*/
public function cacheTableData(array $tables, $table): void
{
// Note: I don't see why we would need array_merge_recursive() here,
// as it creates double entries for the same table (for example a double
// entry for Comment when changing the storage engine in Operations)
// Note 2: Instead of array_merge(), simply use the + operator because
// array_merge() renumbers numeric keys starting with 0, therefore
// we would lose a db name that consists only of numbers
foreach ($tables as $one_database => $_) {
if (isset($this->tableCache[$one_database])) {
// the + operator does not do the intended effect
// when the cache for one table already exists
if ($table && isset($this->tableCache[$one_database][$table])) {
unset($this->tableCache[$one_database][$table]);
}
$this->tableCache[$one_database] += $tables[$one_database];
} else {
$this->tableCache[$one_database] = $tables[$one_database];
}
}
}
/**
* Set an item in table cache using dot notation.
*
* @param array|null $contentPath Array with the target path
* @param mixed $value Target value
*/
public function cacheTableContent(?array $contentPath, $value): void
{
$loc = &$this->tableCache;
if (! isset($contentPath)) {
$loc = $value;
return;
}
while (count($contentPath) > 1) {
$key = array_shift($contentPath);
// If the key doesn't exist at this depth, we will just create an empty
// array to hold the next value, allowing us to create the arrays to hold
// final values at the correct depth. Then we'll keep digging into the
// array.
if (! isset($loc[$key]) || ! is_array($loc[$key])) {
$loc[$key] = [];
}
$loc = &$loc[$key];
}
$loc[array_shift($contentPath)] = $value;
}
/**
* Get a cached value from table cache.
*
* @param array $contentPath Array of the name of the target value
* @param mixed $default Return value on cache miss
*
* @return mixed cached value or default
*/
public function getCachedTableContent(array $contentPath, $default = null)
{
return Util::getValueByKey($this->tableCache, $contentPath, $default);
}
public function getCache(): array
{
return $this->tableCache;
}
public function clearTableCache(): void
{
$this->tableCache = [];
}
}

View file

@ -0,0 +1,256 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Query;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Util;
use function in_array;
use function is_string;
use function strlen;
use function strpos;
use function strtoupper;
use function substr;
/**
* Handles data compatibility from SQL query results
*/
class Compatibility
{
public static function getISCompatForGetTablesFull(array $eachTables, string $eachDatabase): array
{
foreach ($eachTables as $table_name => $_) {
if (! isset($eachTables[$table_name]['Type']) && isset($eachTables[$table_name]['Engine'])) {
// pma BC, same parts of PMA still uses 'Type'
$eachTables[$table_name]['Type'] =& $eachTables[$table_name]['Engine'];
} elseif (! isset($eachTables[$table_name]['Engine']) && isset($eachTables[$table_name]['Type'])) {
// old MySQL reports Type, newer MySQL reports Engine
$eachTables[$table_name]['Engine'] =& $eachTables[$table_name]['Type'];
}
// Compatibility with INFORMATION_SCHEMA output
$eachTables[$table_name]['TABLE_SCHEMA'] = $eachDatabase;
$eachTables[$table_name]['TABLE_NAME'] =& $eachTables[$table_name]['Name'];
$eachTables[$table_name]['ENGINE'] =& $eachTables[$table_name]['Engine'];
$eachTables[$table_name]['VERSION'] =& $eachTables[$table_name]['Version'];
$eachTables[$table_name]['ROW_FORMAT'] =& $eachTables[$table_name]['Row_format'];
$eachTables[$table_name]['TABLE_ROWS'] =& $eachTables[$table_name]['Rows'];
$eachTables[$table_name]['AVG_ROW_LENGTH'] =& $eachTables[$table_name]['Avg_row_length'];
$eachTables[$table_name]['DATA_LENGTH'] =& $eachTables[$table_name]['Data_length'];
$eachTables[$table_name]['MAX_DATA_LENGTH'] =& $eachTables[$table_name]['Max_data_length'];
$eachTables[$table_name]['INDEX_LENGTH'] =& $eachTables[$table_name]['Index_length'];
$eachTables[$table_name]['DATA_FREE'] =& $eachTables[$table_name]['Data_free'];
$eachTables[$table_name]['AUTO_INCREMENT'] =& $eachTables[$table_name]['Auto_increment'];
$eachTables[$table_name]['CREATE_TIME'] =& $eachTables[$table_name]['Create_time'];
$eachTables[$table_name]['UPDATE_TIME'] =& $eachTables[$table_name]['Update_time'];
$eachTables[$table_name]['CHECK_TIME'] =& $eachTables[$table_name]['Check_time'];
$eachTables[$table_name]['TABLE_COLLATION'] =& $eachTables[$table_name]['Collation'];
$eachTables[$table_name]['CHECKSUM'] =& $eachTables[$table_name]['Checksum'];
$eachTables[$table_name]['CREATE_OPTIONS'] =& $eachTables[$table_name]['Create_options'];
$eachTables[$table_name]['TABLE_COMMENT'] =& $eachTables[$table_name]['Comment'];
if (
strtoupper($eachTables[$table_name]['Comment'] ?? '') === 'VIEW'
&& $eachTables[$table_name]['Engine'] == null
) {
$eachTables[$table_name]['TABLE_TYPE'] = 'VIEW';
} elseif ($eachDatabase === 'information_schema') {
$eachTables[$table_name]['TABLE_TYPE'] = 'SYSTEM VIEW';
} else {
/**
* @todo difference between 'TEMPORARY' and 'BASE TABLE'
* but how to detect?
*/
$eachTables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
}
}
return $eachTables;
}
public static function getISCompatForGetColumnsFull(array $columns, string $database, string $table): array
{
$ordinal_position = 1;
foreach ($columns as $column_name => $_) {
// Compatibility with INFORMATION_SCHEMA output
$columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
$columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
$columns[$column_name]['COLLATION_NAME'] =& $columns[$column_name]['Collation'];
$columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
$columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
$columns[$column_name]['COLUMN_DEFAULT'] =& $columns[$column_name]['Default'];
$columns[$column_name]['EXTRA'] =& $columns[$column_name]['Extra'];
$columns[$column_name]['PRIVILEGES'] =& $columns[$column_name]['Privileges'];
$columns[$column_name]['COLUMN_COMMENT'] =& $columns[$column_name]['Comment'];
$columns[$column_name]['TABLE_CATALOG'] = null;
$columns[$column_name]['TABLE_SCHEMA'] = $database;
$columns[$column_name]['TABLE_NAME'] = $table;
$columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
$colType = $columns[$column_name]['COLUMN_TYPE'];
$colType = is_string($colType) ? $colType : '';
$colTypePosComa = strpos($colType, '(');
$colTypePosComa = $colTypePosComa !== false ? $colTypePosComa : strlen($colType);
$columns[$column_name]['DATA_TYPE'] = substr($colType, 0, $colTypePosComa);
/**
* @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
*/
$columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
/**
* @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
*/
$columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
$columns[$column_name]['NUMERIC_PRECISION'] = null;
$columns[$column_name]['NUMERIC_SCALE'] = null;
$colCollation = $columns[$column_name]['COLLATION_NAME'];
$colCollation = is_string($colCollation) ? $colCollation : '';
$colCollationPosUnderscore = strpos($colCollation, '_');
$colCollationPosUnderscore = $colCollationPosUnderscore !== false
? $colCollationPosUnderscore
: strlen($colCollation);
$columns[$column_name]['CHARACTER_SET_NAME'] = substr($colCollation, 0, $colCollationPosUnderscore);
$ordinal_position++;
}
return $columns;
}
public static function isMySqlOrPerconaDb(): bool
{
$serverType = Util::getServerType();
return $serverType === 'MySQL' || $serverType === 'Percona Server';
}
public static function isMariaDb(): bool
{
$serverType = Util::getServerType();
return $serverType === 'MariaDB';
}
public static function isCompatibleRenameIndex(int $serverVersion): bool
{
if (self::isMySqlOrPerconaDb()) {
return $serverVersion >= 50700;
}
// @see https://mariadb.com/kb/en/alter-table/#rename-indexkey
if (self::isMariaDb()) {
return $serverVersion >= 100502;
}
return false;
}
public static function isIntegersLengthRestricted(DatabaseInterface $dbi): bool
{
// MySQL made restrictions on the integer types' length from versions >= 8.0.18
// See: https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-19.html
$serverType = Util::getServerType();
$serverVersion = $dbi->getVersion();
return $serverType === 'MySQL' && $serverVersion >= 80018;
}
public static function supportsReferencesPrivilege(DatabaseInterface $dbi): bool
{
// See: https://mariadb.com/kb/en/grant/#table-privileges
// Unused
if ($dbi->isMariaDB()) {
return false;
}
// https://dev.mysql.com/doc/refman/5.6/en/privileges-provided.html#priv_references
// This privilege is unused before MySQL 5.6.22.
// As of 5.6.22, creation of a foreign key constraint
// requires at least one of the SELECT, INSERT, UPDATE, DELETE,
// or REFERENCES privileges for the parent table.
return $dbi->getVersion() >= 50622;
}
public static function isIntegersSupportLength(string $type, string $length, DatabaseInterface $dbi): bool
{
// MySQL Removed the Integer types' length from versions >= 8.0.18
// except TINYINT(1).
// See: https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-19.html
$integerTypes = ['SMALLINT', 'MEDIUMINT', 'INT', 'BIGINT'];
$typeLengthNotAllowed = in_array($type, $integerTypes) || $type === 'TINYINT' && $length !== '1';
return ! (self::isIntegersLengthRestricted($dbi) && $typeLengthNotAllowed);
}
/**
* Returns whether the database server supports virtual columns
*/
public static function isVirtualColumnsSupported(int $serverVersion): bool
{
// @see: https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html
if (self::isMySqlOrPerconaDb()) {
return $serverVersion >= 50706;
}
// @see https://mariadb.com/kb/en/changes-improvements-in-mariadb-52/#new-features
if (self::isMariaDb()) {
return $serverVersion >= 50200;
}
return false;
}
/**
* Check whether the database supports UUID data type
* true if uuid is supported
*/
public static function isUUIDSupported(DatabaseInterface $dbi): bool
{
// @see: https://mariadb.com/kb/en/mariadb-1070-release-notes/#uuid
return $dbi->isMariaDB() && $dbi->getVersion() >= 100700; // 10.7.0
}
/**
* Returns whether the database server supports virtual columns
*/
public static function supportsStoredKeywordForVirtualColumns(int $serverVersion): bool
{
// @see: https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html
if (self::isMySqlOrPerconaDb()) {
return $serverVersion >= 50706;
}
// @see https://mariadb.com/kb/en/generated-columns/#mysql-compatibility-support
if (self::isMariaDb()) {
return $serverVersion >= 100201;
}
return false;
}
/**
* Returns whether the database server supports compressed columns
*/
public static function supportsCompressedColumns(int $serverVersion): bool
{
// @see https://mariadb.com/kb/en/innodb-page-compression/#comment_1992
// Comment: Page compression is only available in MariaDB >= 10.1. [...]
if (self::isMariaDb()) {
return $serverVersion >= 100100;
}
return false;
}
/**
* @see https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html#mysqld-5-7-6-account-management
* @see https://mariadb.com/kb/en/mariadb-1042-release-notes/#notable-changes
*
* @psalm-pure
*/
public static function hasAccountLocking(bool $isMariaDb, int $version): bool
{
return $isMariaDb && $version >= 100402 || ! $isMariaDb && $version >= 50706;
}
}

View file

@ -0,0 +1,407 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Query;
use PhpMyAdmin\Util;
use function count;
use function implode;
use function is_array;
use function sprintf;
/**
* Handles generating SQL queries
*/
class Generator
{
/**
* returns a segment of the SQL WHERE clause regarding table name and type
*
* @param array|string $escapedTableOrTables table(s)
* @param bool $tblIsGroup $table is a table group
* @param string $tableType whether table or view
*
* @return string a segment of the WHERE clause
*/
public static function getTableCondition(
$escapedTableOrTables,
bool $tblIsGroup,
?string $tableType
): string {
// get table information from information_schema
if ($escapedTableOrTables) {
if (is_array($escapedTableOrTables)) {
$sqlWhereTable = 'AND t.`TABLE_NAME` '
. Util::getCollateForIS() . ' IN (\''
. implode('\', \'', $escapedTableOrTables)
. '\')';
} elseif ($tblIsGroup === true) {
$sqlWhereTable = 'AND t.`TABLE_NAME` LIKE \''
. Util::escapeMysqlWildcards($escapedTableOrTables)
. '%\'';
} else {
$sqlWhereTable = 'AND t.`TABLE_NAME` '
. Util::getCollateForIS() . ' = \''
. $escapedTableOrTables . '\'';
}
} else {
$sqlWhereTable = '';
}
if ($tableType) {
if ($tableType === 'view') {
$sqlWhereTable .= " AND t.`TABLE_TYPE` NOT IN ('BASE TABLE', 'SYSTEM VERSIONED')";
} elseif ($tableType === 'table') {
$sqlWhereTable .= " AND t.`TABLE_TYPE` IN ('BASE TABLE', 'SYSTEM VERSIONED')";
}
}
return $sqlWhereTable;
}
/**
* returns the beginning of the SQL statement to fetch the list of tables
*
* @param string[] $thisDatabases databases to list
* @param string $sqlWhereTable additional condition
*
* @return string the SQL statement
*/
public static function getSqlForTablesFull(array $thisDatabases, string $sqlWhereTable): string
{
return 'SELECT *,'
. ' `TABLE_SCHEMA` AS `Db`,'
. ' `TABLE_NAME` AS `Name`,'
. ' `TABLE_TYPE` AS `TABLE_TYPE`,'
. ' `ENGINE` AS `Engine`,'
. ' `ENGINE` AS `Type`,'
. ' `VERSION` AS `Version`,'
. ' `ROW_FORMAT` AS `Row_format`,'
. ' `TABLE_ROWS` AS `Rows`,'
. ' `AVG_ROW_LENGTH` AS `Avg_row_length`,'
. ' `DATA_LENGTH` AS `Data_length`,'
. ' `MAX_DATA_LENGTH` AS `Max_data_length`,'
. ' `INDEX_LENGTH` AS `Index_length`,'
. ' `DATA_FREE` AS `Data_free`,'
. ' `AUTO_INCREMENT` AS `Auto_increment`,'
. ' `CREATE_TIME` AS `Create_time`,'
. ' `UPDATE_TIME` AS `Update_time`,'
. ' `CHECK_TIME` AS `Check_time`,'
. ' `TABLE_COLLATION` AS `Collation`,'
. ' `CHECKSUM` AS `Checksum`,'
. ' `CREATE_OPTIONS` AS `Create_options`,'
. ' `TABLE_COMMENT` AS `Comment`'
. ' FROM `information_schema`.`TABLES` t'
. ' WHERE `TABLE_SCHEMA` ' . Util::getCollateForIS()
. ' IN (\'' . implode("', '", $thisDatabases) . '\')'
. ' ' . $sqlWhereTable;
}
/**
* Returns SQL for fetching information on table indexes (SHOW INDEXES)
*
* @param string $database name of database
* @param string $table name of the table whose indexes are to be retrieved
* @param string $where additional conditions for WHERE
*
* @return string SQL for getting indexes
*/
public static function getTableIndexesSql(
string $database,
string $table,
?string $where = null
): string {
$sql = 'SHOW INDEXES FROM ' . Util::backquote($database) . '.'
. Util::backquote($table);
if ($where) {
$sql .= ' WHERE (' . $where . ')';
}
return $sql;
}
/**
* Returns SQL query for fetching columns for a table
*
* @param string $database name of database
* @param string $table name of table to retrieve columns from
* @param string|null $escapedColumn name of column, null to show all columns
* @param bool $full whether to return full info or only column names
*/
public static function getColumnsSql(
string $database,
string $table,
?string $escapedColumn = null,
bool $full = false
): string {
return 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS FROM '
. Util::backquote($database) . '.' . Util::backquote($table)
. ($escapedColumn !== null ? " LIKE '"
. $escapedColumn . "'" : '');
}
public static function getInformationSchemaRoutinesRequest(
string $escapedDb,
?string $routineType,
?string $escapedRoutineName
): string {
$query = 'SELECT'
. ' `ROUTINE_SCHEMA` AS `Db`,'
. ' `SPECIFIC_NAME` AS `Name`,'
. ' `ROUTINE_TYPE` AS `Type`,'
. ' `DEFINER` AS `Definer`,'
. ' `LAST_ALTERED` AS `Modified`,'
. ' `CREATED` AS `Created`,'
. ' `SECURITY_TYPE` AS `Security_type`,'
. ' `ROUTINE_COMMENT` AS `Comment`,'
. ' `CHARACTER_SET_CLIENT` AS `character_set_client`,'
. ' `COLLATION_CONNECTION` AS `collation_connection`,'
. ' `DATABASE_COLLATION` AS `Database Collation`,'
. ' `DTD_IDENTIFIER`'
. ' FROM `information_schema`.`ROUTINES`'
. ' WHERE `ROUTINE_SCHEMA` ' . Util::getCollateForIS()
. " = '" . $escapedDb . "'";
if ($routineType !== null) {
$query .= " AND `ROUTINE_TYPE` = '" . $routineType . "'";
}
if ($escapedRoutineName !== null) {
$query .= ' AND `SPECIFIC_NAME`'
. " = '" . $escapedRoutineName . "'";
}
return $query;
}
public static function getInformationSchemaEventsRequest(string $escapedDb, ?string $escapedEventName): string
{
$query = 'SELECT'
. ' `EVENT_SCHEMA` AS `Db`,'
. ' `EVENT_NAME` AS `Name`,'
. ' `DEFINER` AS `Definer`,'
. ' `TIME_ZONE` AS `Time zone`,'
. ' `EVENT_TYPE` AS `Type`,'
. ' `EXECUTE_AT` AS `Execute at`,'
. ' `INTERVAL_VALUE` AS `Interval value`,'
. ' `INTERVAL_FIELD` AS `Interval field`,'
. ' `STARTS` AS `Starts`,'
. ' `ENDS` AS `Ends`,'
. ' `STATUS` AS `Status`,'
. ' `ORIGINATOR` AS `Originator`,'
. ' `CHARACTER_SET_CLIENT` AS `character_set_client`,'
. ' `COLLATION_CONNECTION` AS `collation_connection`, '
. '`DATABASE_COLLATION` AS `Database Collation`'
. ' FROM `information_schema`.`EVENTS`'
. ' WHERE `EVENT_SCHEMA` ' . Util::getCollateForIS()
. " = '" . $escapedDb . "'";
if ($escapedEventName !== null) {
$query .= ' AND `EVENT_NAME`'
. " = '" . $escapedEventName . "'";
}
return $query;
}
public static function getInformationSchemaTriggersRequest(string $escapedDb, ?string $escapedTable): string
{
$query = 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION'
. ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
. ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
. ' FROM information_schema.TRIGGERS'
. ' WHERE EVENT_OBJECT_SCHEMA ' . Util::getCollateForIS() . '='
. ' \'' . $escapedDb . '\'';
if ($escapedTable !== null) {
$query .= ' AND EVENT_OBJECT_TABLE ' . Util::getCollateForIS()
. " = '" . $escapedTable . "';";
}
return $query;
}
public static function getInformationSchemaDataForCreateRequest(string $user, string $host): string
{
return 'SELECT 1 FROM `INFORMATION_SCHEMA`.`USER_PRIVILEGES` '
. "WHERE `PRIVILEGE_TYPE` = 'CREATE USER' AND "
. "'''" . $user . "''@''" . $host . "''' LIKE `GRANTEE` LIMIT 1";
}
public static function getInformationSchemaDataForGranteeRequest(string $user, string $host): string
{
return 'SELECT 1 FROM ('
. 'SELECT `GRANTEE`, `IS_GRANTABLE` FROM '
. '`INFORMATION_SCHEMA`.`COLUMN_PRIVILEGES` UNION '
. 'SELECT `GRANTEE`, `IS_GRANTABLE` FROM '
. '`INFORMATION_SCHEMA`.`TABLE_PRIVILEGES` UNION '
. 'SELECT `GRANTEE`, `IS_GRANTABLE` FROM '
. '`INFORMATION_SCHEMA`.`SCHEMA_PRIVILEGES` UNION '
. 'SELECT `GRANTEE`, `IS_GRANTABLE` FROM '
. '`INFORMATION_SCHEMA`.`USER_PRIVILEGES`) t '
. "WHERE `IS_GRANTABLE` = 'YES' AND "
. "'''" . $user . "''@''" . $host . "''' LIKE `GRANTEE` LIMIT 1";
}
public static function getInformationSchemaForeignKeyConstraintsRequest(
string $escapedDatabase,
string $tablesListForQueryCsv
): string {
return 'SELECT'
. ' TABLE_NAME,'
. ' COLUMN_NAME,'
. ' REFERENCED_TABLE_NAME,'
. ' REFERENCED_COLUMN_NAME'
. ' FROM information_schema.key_column_usage'
. ' WHERE referenced_table_name IS NOT NULL'
. " AND TABLE_SCHEMA = '" . $escapedDatabase . "'"
. ' AND TABLE_NAME IN (' . $tablesListForQueryCsv . ')'
. ' AND REFERENCED_TABLE_NAME IN (' . $tablesListForQueryCsv . ');';
}
public static function getInformationSchemaDatabasesFullRequest(
bool $forceStats,
string $sqlWhereSchema,
string $sortBy,
string $sortOrder,
string $limit
): string {
$sql = 'SELECT *, CAST(BIN_NAME AS CHAR CHARACTER SET utf8) AS SCHEMA_NAME FROM (';
$sql .= 'SELECT BINARY s.SCHEMA_NAME AS BIN_NAME, s.DEFAULT_COLLATION_NAME';
if ($forceStats) {
$sql .= ','
. ' COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,'
. ' SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,'
. ' SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,'
. ' SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,'
. ' SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,'
. ' SUM(t.DATA_LENGTH + t.INDEX_LENGTH) AS SCHEMA_LENGTH,'
. ' SUM(IF(t.ENGINE <> \'InnoDB\', t.DATA_FREE, 0)) AS SCHEMA_DATA_FREE';
}
$sql .= ' FROM `information_schema`.SCHEMATA s ';
if ($forceStats) {
$sql .= ' LEFT JOIN `information_schema`.TABLES t ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
}
$sql .= $sqlWhereSchema
. ' GROUP BY BINARY s.SCHEMA_NAME, s.DEFAULT_COLLATION_NAME'
. ' ORDER BY ';
if ($sortBy === 'SCHEMA_NAME' || $sortBy === 'DEFAULT_COLLATION_NAME') {
$sql .= 'BINARY ';
}
$sql .= Util::backquote($sortBy)
. ' ' . $sortOrder
. $limit;
$sql .= ') a';
return $sql;
}
public static function getInformationSchemaColumnsFullRequest(
?string $escapedDatabase,
?string $escapedTable,
?string $escapedColumn
): array {
$sqlWheres = [];
$arrayKeys = [];
// get columns information from information_schema
if ($escapedDatabase !== null) {
$sqlWheres[] = '`TABLE_SCHEMA` = \''
. $escapedDatabase . '\' ';
} else {
$arrayKeys[] = 'TABLE_SCHEMA';
}
if ($escapedTable !== null) {
$sqlWheres[] = '`TABLE_NAME` = \''
. $escapedTable . '\' ';
} else {
$arrayKeys[] = 'TABLE_NAME';
}
if ($escapedColumn !== null) {
$sqlWheres[] = '`COLUMN_NAME` = \''
. $escapedColumn . '\' ';
} else {
$arrayKeys[] = 'COLUMN_NAME';
}
// for PMA bc:
// `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
$sql = 'SELECT *,'
. ' `COLUMN_NAME` AS `Field`,'
. ' `COLUMN_TYPE` AS `Type`,'
. ' `COLLATION_NAME` AS `Collation`,'
. ' `IS_NULLABLE` AS `Null`,'
. ' `COLUMN_KEY` AS `Key`,'
. ' `COLUMN_DEFAULT` AS `Default`,'
. ' `EXTRA` AS `Extra`,'
. ' `PRIVILEGES` AS `Privileges`,'
. ' `COLUMN_COMMENT` AS `Comment`'
. ' FROM `information_schema`.`COLUMNS`';
if (count($sqlWheres)) {
$sql .= "\n" . ' WHERE ' . implode(' AND ', $sqlWheres);
}
return [$sql, $arrayKeys];
}
/**
* Function to get sql query for renaming the index using SQL RENAME INDEX Syntax
*/
public static function getSqlQueryForIndexRename(
string $dbName,
string $tableName,
string $oldIndexName,
string $newIndexName
): string {
return sprintf(
'ALTER TABLE %s.%s RENAME INDEX %s TO %s;',
Util::backquote($dbName),
Util::backquote($tableName),
Util::backquote($oldIndexName),
Util::backquote($newIndexName)
);
}
/**
* Function to get sql query to re-order the table
*/
public static function getQueryForReorderingTable(
string $table,
string $orderField,
?string $order
): string {
return 'ALTER TABLE '
. Util::backquote($table)
. ' ORDER BY '
. Util::backquote($orderField)
. ($order === 'desc' ? ' DESC;' : ' ASC;');
}
/**
* Function to get sql query to partition the table
*
* @param string[] $partitionNames
*/
public static function getQueryForPartitioningTable(
string $table,
string $partitionOperation,
array $partitionNames
): string {
$sql_query = 'ALTER TABLE '
. Util::backquote($table) . ' '
. $partitionOperation
. ' PARTITION ';
if ($partitionOperation === 'COALESCE') {
return $sql_query . count($partitionNames);
}
return $sql_query . implode(', ', $partitionNames) . ';';
}
}

View file

@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Query;
use PhpMyAdmin\Dbal\ResultInterface;
use PhpMyAdmin\Error;
use PhpMyAdmin\Url;
use function __;
use function array_slice;
use function debug_backtrace;
use function explode;
use function htmlspecialchars;
use function htmlspecialchars_decode;
use function intval;
use function md5;
use function sprintf;
use function str_contains;
use function strcasecmp;
use function strnatcasecmp;
use function strtolower;
/**
* Some helfull functions for common tasks related to SQL results
*/
class Utilities
{
/**
* Get the list of system schemas
*
* @return string[] list of system schemas
*/
public static function getSystemSchemas(): array
{
$schemas = [
'information_schema',
'performance_schema',
'mysql',
'sys',
];
$systemSchemas = [];
foreach ($schemas as $schema) {
if (! self::isSystemSchema($schema, true)) {
continue;
}
$systemSchemas[] = $schema;
}
return $systemSchemas;
}
/**
* Checks whether given schema is a system schema
*
* @param string $schema_name Name of schema (database) to test
* @param bool $testForMysqlSchema Whether 'mysql' schema should
* be treated the same as IS and DD
*/
public static function isSystemSchema(
string $schema_name,
bool $testForMysqlSchema = false
): bool {
$schema_name = strtolower($schema_name);
$isMySqlSystemSchema = $schema_name === 'mysql' && $testForMysqlSchema;
return $schema_name === 'information_schema'
|| $schema_name === 'performance_schema'
|| $isMySqlSystemSchema
|| $schema_name === 'sys';
}
/**
* Formats database error message in a friendly way.
* This is needed because some errors messages cannot
* be obtained by mysql_error().
*
* @param int $error_number Error code
* @param string $error_message Error message as returned by server
*
* @return string HML text with error details
* @psalm-return non-empty-string
*/
public static function formatError(int $error_number, string $error_message): string
{
$error_message = htmlspecialchars($error_message);
$error = '#' . ((string) $error_number);
$separator = ' &mdash; ';
if ($error_number == 2002) {
$error .= ' - ' . $error_message;
$error .= $separator;
$error .= __('The server is not responding (or the local server\'s socket is not correctly configured).');
} elseif ($error_number == 2003) {
$error .= ' - ' . $error_message;
$error .= $separator . __('The server is not responding.');
} elseif ($error_number == 1698) {
$error .= ' - ' . $error_message;
$error .= $separator . '<a href="' . Url::getFromRoute('/logout') . '" class="disableAjax">';
$error .= __('Logout and try as another user.') . '</a>';
} elseif ($error_number == 1005) {
if (str_contains($error_message, 'errno: 13')) {
$error .= ' - ' . $error_message;
$error .= $separator
. __('Please check privileges of directory containing database.');
} else {
/**
* InnoDB constraints, see
* https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
*/
$error .= ' - ' . $error_message .
' (<a href="' .
Url::getFromRoute('/server/engines/InnoDB/Status') .
'">' . __('Details…') . '</a>)';
}
} else {
$error .= ' - ' . $error_message;
}
return $error;
}
/**
* usort comparison callback
*
* @param array $a first argument to sort
* @param array $b second argument to sort
* @param string $sortBy Key to sort by
* @param string $sortOrder The order (ASC/DESC)
*
* @return int a value representing whether $a should be before $b in the
* sorted array or not
*/
public static function usortComparisonCallback(array $a, array $b, string $sortBy, string $sortOrder): int
{
global $cfg;
/* No sorting when key is not present */
if (! isset($a[$sortBy], $b[$sortBy])) {
return 0;
}
// produces f.e.:
// return -1 * strnatcasecmp($a['SCHEMA_TABLES'], $b['SCHEMA_TABLES'])
$compare = $cfg['NaturalOrder'] ? strnatcasecmp(
(string) $a[$sortBy],
(string) $b[$sortBy]
) : strcasecmp(
(string) $a[$sortBy],
(string) $b[$sortBy]
);
return ($sortOrder === 'ASC' ? 1 : -1) * $compare;
}
/**
* Convert version string to integer.
*
* @param string $version MySQL server version
*/
public static function versionToInt(string $version): int
{
$match = explode('.', $version);
return (int) sprintf('%d%02d%02d', $match[0], $match[1], intval($match[2]));
}
/**
* Stores query data into session data for debugging purposes
*
* @param string $query Query text
* @param string|null $errorMessage Error message from getError()
* @param ResultInterface|false $result Query result
* @param int|float $time Time to execute query
*/
public static function debugLogQueryIntoSession(string $query, ?string $errorMessage, $result, $time): void
{
$dbgInfo = [];
if ($result === false && $errorMessage !== null) {
// because Utilities::formatError is applied in DbiMysqli
$dbgInfo['error'] = htmlspecialchars_decode($errorMessage);
}
$dbgInfo['query'] = $query;
$dbgInfo['time'] = $time;
// Get and slightly format backtrace, this is used
// in the javascript console.
// Strip call to debugLogQueryIntoSession
$dbgInfo['trace'] = Error::processBacktrace(
array_slice(debug_backtrace(), 1)
);
$dbgInfo['hash'] = md5($query);
$_SESSION['debug']['queries'][] = $dbgInfo;
}
}