Correctly escape identifier names

- Add support for schema, multiple tables in $table parameters
- Remove Database->formatTableName method
This commit is contained in:
Hypolite Petovan 2019-07-28 23:00:29 -04:00
parent c290bcb975
commit 0e0fff3324
3 changed files with 129 additions and 106 deletions

View file

@ -180,7 +180,7 @@ class DBA extends BaseObject
/** /**
* @brief Check if data exists * @brief Check if data exists
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $condition array of fields for condition * @param array $condition array of fields for condition
* *
* @return boolean Are there rows for that condition? * @return boolean Are there rows for that condition?
@ -253,7 +253,7 @@ class DBA extends BaseObject
/** /**
* @brief Insert a row into a table * @brief Insert a row into a table
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $param parameter array * @param array $param parameter array
* @param bool $on_duplicate_update Do an update on a duplicate entry * @param bool $on_duplicate_update Do an update on a duplicate entry
* *
@ -280,7 +280,7 @@ class DBA extends BaseObject
* *
* This function can be extended in the future to accept a table array as well. * This function can be extended in the future to accept a table array as well.
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* *
* @return boolean was the lock successful? * @return boolean was the lock successful?
* @throws \Exception * @throws \Exception
@ -369,7 +369,7 @@ class DBA extends BaseObject
* Only set $old_fields to a boolean value when you are sure that you will update a single row. * Only set $old_fields to a boolean value when you are sure that you will update a single row.
* When you set $old_fields to "true" then $fields must contain all relevant fields! * When you set $old_fields to "true" then $fields must contain all relevant fields!
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $fields contains the fields that are updated * @param array $fields contains the fields that are updated
* @param array $condition condition array with the key values * @param array $condition condition array with the key values
* @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate) * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
@ -386,7 +386,7 @@ class DBA extends BaseObject
* Retrieve a single record from a table and returns it in an associative array * Retrieve a single record from a table and returns it in an associative array
* *
* @brief Retrieve a single record from a table * @brief Retrieve a single record from a table
* @param string $table * @param string|array $table Table name or array [schema => table]
* @param array $fields * @param array $fields
* @param array $condition * @param array $condition
* @param array $params * @param array $params
@ -402,7 +402,7 @@ class DBA extends BaseObject
/** /**
* @brief Select rows from a table and fills an array with the data * @brief Select rows from a table and fills an array with the data
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $fields Array of selected fields, empty for all * @param array $fields Array of selected fields, empty for all
* @param array $condition Array of fields for condition * @param array $condition Array of fields for condition
* @param array $params Array of several parameters * @param array $params Array of several parameters
@ -419,7 +419,7 @@ class DBA extends BaseObject
/** /**
* @brief Select rows from a table * @brief Select rows from a table
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $fields Array of selected fields, empty for all * @param array $fields Array of selected fields, empty for all
* @param array $condition Array of fields for condition * @param array $condition Array of fields for condition
* @param array $params Array of several parameters * @param array $params Array of several parameters
@ -447,7 +447,7 @@ class DBA extends BaseObject
/** /**
* @brief Counts the rows from a table satisfying the provided condition * @brief Counts the rows from a table satisfying the provided condition
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $condition array of fields for condition * @param array $condition array of fields for condition
* *
* @return int * @return int
@ -467,6 +467,47 @@ class DBA extends BaseObject
return self::getClass(Database::class)->count($table, $condition); return self::getClass(Database::class)->count($table, $condition);
} }
/**
* Build the table query substring from one or more tables, with or without a schema.
*
* Expected formats:
* - table
* - [table1, table2, ...]
* - [schema1 => table1, schema2 => table2, table3, ...]
*
* @param string|array $tables
* @return string
*/
public static function buildTableString($tables)
{
if (is_string($tables)) {
$tables = [$tables];
}
$quotedTables = [];
foreach ($tables as $schema => $table) {
if (is_numeric($schema)) {
$quotedTables[] = self::quoteIdentifier($table);
} else {
$quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
}
}
return implode(', ', $quotedTables);
}
/**
* Escape an identifier (table or field name)
*
* @param $identifier
* @return string
*/
public static function quoteIdentifier($identifier)
{
return '`' . str_replace('`', '``', $identifier) . '`';
}
/** /**
* @brief Returns the SQL condition string built from the provided condition array * @brief Returns the SQL condition string built from the provided condition array
* *
@ -527,12 +568,12 @@ class DBA extends BaseObject
$new_values = array_merge($new_values, array_values($value)); $new_values = array_merge($new_values, array_values($value));
$placeholders = substr(str_repeat("?, ", count($value)), 0, -2); $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
$condition_string .= "`" . $field . "` IN (" . $placeholders . ")"; $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
} elseif (is_null($value)) { } elseif (is_null($value)) {
$condition_string .= "`" . $field . "` IS NULL"; $condition_string .= self::quoteIdentifier($field) . " IS NULL";
} else { } else {
$new_values[$field] = $value; $new_values[$field] = $value;
$condition_string .= "`" . $field . "` = ?"; $condition_string .= self::quoteIdentifier($field) . " = ?";
} }
} }
$condition_string = " WHERE (" . $condition_string . ")"; $condition_string = " WHERE (" . $condition_string . ")";
@ -552,12 +593,8 @@ class DBA extends BaseObject
public static function buildParameter(array $params = []) public static function buildParameter(array $params = [])
{ {
$groupby_string = ''; $groupby_string = '';
if (isset($params['group_by'])) { if (!empty($params['group_by'])) {
$groupby_string = " GROUP BY "; $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
foreach ($params['group_by'] as $fields) {
$groupby_string .= "`" . $fields . "`, ";
}
$groupby_string = substr($groupby_string, 0, -2);
} }
$order_string = ''; $order_string = '';
@ -567,9 +604,9 @@ class DBA extends BaseObject
if ($order === 'RAND()') { if ($order === 'RAND()') {
$order_string .= "RAND(), "; $order_string .= "RAND(), ";
} elseif (!is_int($fields)) { } elseif (!is_int($fields)) {
$order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", "; $order_string .= self::quoteIdentifier($fields) . " " . ($order ? "DESC" : "ASC") . ", ";
} else { } else {
$order_string .= "`" . $order . "`, "; $order_string .= self::quoteIdentifier($order) . ", ";
} }
} }
$order_string = substr($order_string, 0, -2); $order_string = substr($order_string, 0, -2);

View file

@ -40,16 +40,19 @@ class DBStructure
*/ */
public static function convertToInnoDB() public static function convertToInnoDB()
{ {
$r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'", $tables = DBA::selectToArray(
DBA::escape(DBA::databaseName())); ['information_schema' => 'tables'],
['table_name'],
['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
);
if (!DBA::isResult($r)) { if (!DBA::isResult($tables)) {
echo L10n::t('There are no tables on MyISAM.') . "\n"; echo L10n::t('There are no tables on MyISAM.') . "\n";
return; return;
} }
foreach ($r AS $table) { foreach ($tables AS $table) {
$sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME'])); $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['TABLE_NAME']) . " engine=InnoDB;";
echo $sql . "\n"; echo $sql . "\n";
$result = DBA::e($sql); $result = DBA::e($sql);
@ -817,7 +820,7 @@ class DBStructure
/** /**
* Check if a table exists * Check if a table exists
* *
* @param string $table Table name * @param string|array $table Table name
* *
* @return boolean Does the table exist? * @return boolean Does the table exist?
* @throws Exception * @throws Exception
@ -828,21 +831,15 @@ class DBStructure
return false; return false;
} }
$table = DBA::escape($table); if (is_array($table)) {
$condition = ['table_schema' => key($table), 'table_name' => current($table)];
$sql = "SHOW TABLES LIKE '" . $table . "';";
$stmt = DBA::p($sql);
if (is_bool($stmt)) {
$retval = $stmt;
} else { } else {
$retval = (DBA::numRows($stmt) > 0); $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
} }
DBA::close($stmt); $result = DBA::exists(['information_schema' => 'tables'], $condition);
return $retval; return $result;
} }
/** /**

View file

@ -725,7 +725,7 @@ class Database
/** /**
* @brief Check if data exists * @brief Check if data exists
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $condition array of fields for condition * @param array $condition array of fields for condition
* *
* @return boolean Are there rows for that condition? * @return boolean Are there rows for that condition?
@ -906,30 +906,7 @@ class Database
/** /**
* @brief Insert a row into a table * @brief Insert a row into a table
* *
* @param string/array $table Table name * @param string|array $table Table name or array [schema => table]
*
* @return string formatted and sanitzed table name
* @throws \Exception
*/
public function formatTableName($table)
{
if (is_string($table)) {
return "`" . $this->sanitizeIdentifier($table) . "`";
}
if (!is_array($table)) {
return '';
}
$scheme = key($table);
return "`" . $this->sanitizeIdentifier($scheme) . "`.`" . $this->sanitizeIdentifier($table[$scheme]) . "`";
}
/**
* @brief Insert a row into a table
*
* @param string $table Table name
* @param array $param parameter array * @param array $param parameter array
* @param bool $on_duplicate_update Do an update on a duplicate entry * @param bool $on_duplicate_update Do an update on a duplicate entry
* *
@ -938,17 +915,23 @@ class Database
*/ */
public function insert($table, $param, $on_duplicate_update = false) public function insert($table, $param, $on_duplicate_update = false)
{ {
if (empty($table) || empty($param)) { if (empty($table) || empty($param)) {
$this->logger->info('Table and fields have to be set'); $this->logger->info('Table and fields have to be set');
return false; return false;
} }
$sql = "INSERT INTO " . $this->formatTableName($table) . " (`" . implode("`, `", array_keys($param)) . "`) VALUES (" . $table_string = DBA::buildTableString($table);
substr(str_repeat("?, ", count($param)), 0, -2) . ")";
$fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
$values_string = substr(str_repeat("?, ", count($param)), 0, -2);
$sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
if ($on_duplicate_update) { if ($on_duplicate_update) {
$sql .= " ON DUPLICATE KEY UPDATE `" . implode("` = ?, `", array_keys($param)) . "` = ?"; $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
$sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
$values = array_values($param); $values = array_values($param);
$param = array_merge_recursive($values, $values); $param = array_merge_recursive($values, $values);
@ -980,7 +963,7 @@ class Database
* *
* This function can be extended in the future to accept a table array as well. * This function can be extended in the future to accept a table array as well.
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* *
* @return boolean was the lock successful? * @return boolean was the lock successful?
* @throws \Exception * @throws \Exception
@ -995,7 +978,7 @@ class Database
$this->connection->autocommit(false); $this->connection->autocommit(false);
} }
$success = $this->e("LOCK TABLES " . $this->formatTableName($table) . " WRITE"); $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
if ($this->driver == 'pdo') { if ($this->driver == 'pdo') {
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
@ -1152,6 +1135,8 @@ class Database
/** /**
* @brief Delete a row from a table * @brief Delete a row from a table
* *
* Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
*
* @param string $table Table name * @param string $table Table name
* @param array $conditions Field condition(s) * @param array $conditions Field condition(s)
* @param array $options * @param array $options
@ -1176,13 +1161,11 @@ class Database
// We quit when this key already exists in the callstack. // We quit when this key already exists in the callstack.
if (isset($callstack[$key])) { if (isset($callstack[$key])) {
return $commands; return true;
} }
$callstack[$key] = true; $callstack[$key] = true;
$table = $this->sanitizeIdentifier($table);
$commands[$key] = ['table' => $table, 'conditions' => $conditions]; $commands[$key] = ['table' => $table, 'conditions' => $conditions];
// Don't use "defaults" here, since it would set "false" to "true" // Don't use "defaults" here, since it would set "false" to "true"
@ -1250,7 +1233,7 @@ class Database
$condition_string = DBA::buildCondition($conditions); $condition_string = DBA::buildCondition($conditions);
if ((count($command['conditions']) > 1) || is_int($first_key)) { if ((count($command['conditions']) > 1) || is_int($first_key)) {
$sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string; $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
$this->logger->debug($this->replaceParameters($sql, $conditions)); $this->logger->debug($this->replaceParameters($sql, $conditions));
if (!$this->e($sql, $conditions)) { if (!$this->e($sql, $conditions)) {
@ -1278,7 +1261,7 @@ class Database
foreach ($compacted AS $table => $values) { foreach ($compacted AS $table => $values) {
foreach ($values AS $field => $field_value_list) { foreach ($values AS $field => $field_value_list) {
foreach ($field_value_list AS $field_values) { foreach ($field_value_list AS $field_values) {
$sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" . $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
substr(str_repeat("?, ", count($field_values)), 0, -2) . ");"; substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
$this->logger->debug($this->replaceParameters($sql, $field_values)); $this->logger->debug($this->replaceParameters($sql, $field_values));
@ -1319,7 +1302,7 @@ class Database
* Only set $old_fields to a boolean value when you are sure that you will update a single row. * Only set $old_fields to a boolean value when you are sure that you will update a single row.
* When you set $old_fields to "true" then $fields must contain all relevant fields! * When you set $old_fields to "true" then $fields must contain all relevant fields!
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $fields contains the fields that are updated * @param array $fields contains the fields that are updated
* @param array $condition condition array with the key values * @param array $condition condition array with the key values
* @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate) * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
@ -1329,12 +1312,13 @@ class Database
*/ */
public function update($table, $fields, $condition, $old_fields = []) public function update($table, $fields, $condition, $old_fields = [])
{ {
if (empty($table) || empty($fields) || empty($condition)) { if (empty($table) || empty($fields) || empty($condition)) {
$this->logger->info('Table, fields and condition have to be set'); $this->logger->info('Table, fields and condition have to be set');
return false; return false;
} }
$table_string = DBA::buildTableString($table);
$condition_string = DBA::buildCondition($condition); $condition_string = DBA::buildCondition($condition);
if (is_bool($old_fields)) { if (is_bool($old_fields)) {
@ -1367,8 +1351,9 @@ class Database
return true; return true;
} }
$sql = "UPDATE " . $this->formatTableName($table) . " SET `" . $sql = "UPDATE " . $table_string . " SET "
implode("` = ?, `", array_keys($fields)) . "` = ?" . $condition_string; . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
. $condition_string;
$params1 = array_values($fields); $params1 = array_values($fields);
$params2 = array_values($condition); $params2 = array_values($condition);
@ -1408,7 +1393,7 @@ class Database
/** /**
* @brief Select rows from a table and fills an array with the data * @brief Select rows from a table and fills an array with the data
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $fields Array of selected fields, empty for all * @param array $fields Array of selected fields, empty for all
* @param array $condition Array of fields for condition * @param array $condition Array of fields for condition
* @param array $params Array of several parameters * @param array $params Array of several parameters
@ -1425,7 +1410,7 @@ class Database
/** /**
* @brief Select rows from a table * @brief Select rows from a table
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $fields Array of selected fields, empty for all * @param array $fields Array of selected fields, empty for all
* @param array $condition Array of fields for condition * @param array $condition Array of fields for condition
* @param array $params Array of several parameters * @param array $params Array of several parameters
@ -1452,16 +1437,18 @@ class Database
} }
if (count($fields) > 0) { if (count($fields) > 0) {
$select_fields = "`" . implode("`, `", array_values($fields)) . "`"; $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
} else { } else {
$select_fields = "*"; $select_string = '*';
} }
$table_string = DBA::buildTableString($table);
$condition_string = DBA::buildCondition($condition); $condition_string = DBA::buildCondition($condition);
$param_string = DBA::buildParameter($params); $param_string = DBA::buildParameter($params);
$sql = "SELECT " . $select_fields . " FROM " . $this->formatTableName($table) . $condition_string . $param_string; $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
$result = $this->p($sql, $condition); $result = $this->p($sql, $condition);
@ -1471,8 +1458,8 @@ class Database
/** /**
* @brief Counts the rows from a table satisfying the provided condition * @brief Counts the rows from a table satisfying the provided condition
* *
* @param string $table Table name * @param string|array $table Table name or array [schema => table]
* @param array $condition array of fields for condition * @param array $condition Array of fields for condition
* *
* @return int * @return int
* *
@ -1492,9 +1479,11 @@ class Database
return false; return false;
} }
$table_string = DBA::buildTableString($table);
$condition_string = DBA::buildCondition($condition); $condition_string = DBA::buildCondition($condition);
$sql = "SELECT COUNT(*) AS `count` FROM " . $this->formatTableName($table) . $condition_string; $sql = "SELECT COUNT(*) AS `count` FROM " . $table_string . $condition_string;
$row = $this->fetchFirst($sql, $condition); $row = $this->fetchFirst($sql, $condition);