namespace Friendica\Database;
-use Friendica\Core\Config\Cache\ConfigCache;
+use Friendica\Core\Config\Cache;
use Friendica\Core\System;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\DateTimeFormat;
protected $connected = false;
/**
- * @var ConfigCache
+ * @var Cache
*/
protected $configCache;
/**
protected $in_retrial = false;
private $relation = [];
- public function __construct(ConfigCache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
+ public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
{
// We are storing these values for being able to perform a reconnect
$this->configCache = $configCache;
{
// Use environment variables for mysql if they are set beforehand
if (!empty($server['MYSQL_HOST'])
- && !empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER']))
+ && (!empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER'])))
&& $server['MYSQL_PASSWORD'] !== false
&& !empty($server['MYSQL_DATABASE']))
{
public function connect()
{
if (!is_null($this->connection) && $this->connected()) {
- return true;
+ return $this->connected;
}
+ // Reset connected state
+ $this->connected = false;
+
$port = 0;
$serveraddr = trim($this->configCache->get('database', 'hostname'));
$serverdata = explode(':', $serveraddr);
*/
public function disconnect()
{
- if (is_null($this->connection)) {
- return;
+ if (!is_null($this->connection)) {
+ switch ($this->driver) {
+ case 'pdo':
+ $this->connection = null;
+ break;
+ case 'mysqli':
+ $this->connection->close();
+ $this->connection = null;
+ break;
+ }
}
- switch ($this->driver) {
- case 'pdo':
- $this->connection = null;
- break;
- case 'mysqli':
- $this->connection->close();
- $this->connection = null;
- break;
- }
+ $this->driver = null;
+ $this->connected = false;
}
/**
}
/**
- * @brief Returns the MySQL server version string
+ * Returns the MySQL server version string
*
* This function discriminate between the deprecated mysql API and the current
* object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
}
/**
- * @brief Returns the selected database name
+ * Returns the selected database name
*
* @return string
* @throws \Exception
}
/**
- * @brief Analyze a database query and log this if some conditions are met.
+ * Analyze a database query and log this if some conditions are met.
*
* @param string $query The database query that will be analyzed
*
$connected = $this->connection->ping();
break;
}
+
return $connected;
}
/**
- * @brief Replaces ANY_VALUE() function by MIN() function,
- * if the database server does not support ANY_VALUE().
+ * Replaces ANY_VALUE() function by MIN() function,
+ * if the database server does not support ANY_VALUE().
*
* Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
* ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
}
/**
- * @brief Replaces the ? placeholders with the parameters in the $args array
+ * Replaces the ? placeholders with the parameters in the $args array
*
* @param string $sql SQL query
* @param array $args The parameters that are to replace the ? placeholders
}
/**
- * @brief Executes a prepared statement that returns data
+ * Executes a prepared statement that returns data
+ *
* @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
*
* Please only use it with complicated queries.
}
/**
- * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
+ * Executes a prepared statement like UPDATE or INSERT that doesn't return data
*
* Please use DBA::delete, DBA::insert, DBA::update, ... instead
*
}
/**
- * @brief Check if data exists
+ * Check if data exists
*
* @param string|array $table Table name or array [schema => table]
* @param array $condition array of fields for condition
*
* Please use DBA::selectFirst or DBA::exists whenever this is possible.
*
- * @brief Fetches the first row
+ * Fetches the first row
*
* @param string $sql SQL statement
*
}
/**
- * @brief Returns the number of affected rows of the last statement
+ * Returns the number of affected rows of the last statement
*
* @return int Number of rows
*/
}
/**
- * @brief Returns the number of columns of a statement
+ * Returns the number of columns of a statement
*
* @param object Statement object
*
}
/**
- * @brief Returns the number of rows of a statement
+ * Returns the number of rows of a statement
*
* @param PDOStatement|mysqli_result|mysqli_stmt Statement object
*
}
/**
- * @brief Fetch a single row
+ * Fetch a single row
*
* @param mixed $stmt statement object
*
}
/**
- * @brief Insert a row into a table
+ * Insert a row into a table
*
* @param string|array $table Table name or array [schema => table]
* @param array $param parameter array
}
/**
- * @brief Fetch the id of the last insert command
+ * Fetch the id of the last insert command
*
* @return integer Last inserted id
*/
}
/**
- * @brief Locks a table for exclusive write access
+ * Locks a table for exclusive write access
*
* This function can be extended in the future to accept a table array as well.
*
}
/**
- * @brief Unlocks all locked tables
+ * Unlocks all locked tables
*
* @return boolean was the unlock successful?
* @throws \Exception
}
/**
- * @brief Starts a transaction
+ * Starts a transaction
*
* @return boolean Was the command executed successfully?
*/
}
/**
- * @brief Does a commit
+ * Does a commit
*
* @return boolean Was the command executed successfully?
*/
}
/**
- * @brief Does a rollback
+ * Does a rollback
*
* @return boolean Was the command executed successfully?
*/
}
/**
- * @brief Build the array with the table relations
+ * Build the array with the table relations
*
* The array is build from the database definitions in DBStructure.php
*
}
/**
- * @brief Delete a row from a table
+ * Delete a row from a table
*
* Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
*
}
/**
- * @brief Updates rows
+ * Updates rows
*
* Updates rows in the database. When $old_fields is set to an array,
* the system will only do an update if the fields in that array changed.
return false;
}
- $table_string = DBA::buildTableString($table);
-
- $condition_string = DBA::buildCondition($condition);
-
if (is_bool($old_fields)) {
$do_insert = $old_fields;
}
}
- $do_update = (count($old_fields) == 0);
-
foreach ($old_fields AS $fieldname => $content) {
- if (isset($fields[$fieldname])) {
- if (($fields[$fieldname] == $content) && !is_null($content)) {
- unset($fields[$fieldname]);
- } else {
- $do_update = true;
- }
+ if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
+ unset($fields[$fieldname]);
}
}
- if (!$do_update || (count($fields) == 0)) {
+ if (count($fields) == 0) {
return true;
}
+ $table_string = DBA::buildTableString($table);
+
+ $condition_string = DBA::buildCondition($condition);
+
$sql = "UPDATE " . $table_string . " SET "
. implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
. $condition_string;
- $params1 = array_values($fields);
- $params2 = array_values($condition);
- $params = array_merge_recursive($params1, $params2);
+ // Combines the updated fields parameter values with the condition parameter values
+ $params = array_merge(array_values($fields), $condition);
return $this->e($sql, $params);
}
/**
* Retrieve a single record from a table and returns it in an associative array
*
- * @brief Retrieve a single record from a table
- *
- * @param string $table
- * @param array $fields
- * @param array $condition
- * @param array $params
+ * @param string|array $table
+ * @param array $fields
+ * @param array $condition
+ * @param array $params
*
* @return bool|array
* @throws \Exception
}
/**
- * @brief Select rows from a table and fills an array with the data
+ * Select rows from a table and fills an array with the data
*
* @param string|array $table Table name or array [schema => table]
* @param array $fields Array of selected fields, empty for all
* @throws \Exception
* @see self::select
*/
- public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
+ public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
{
return $this->toArray($this->select($table, $fields, $condition, $params));
}
/**
- * @brief Select rows from a table
+ * Select rows from a table
*
* @param string|array $table Table name or array [schema => table]
* @param array $fields Array of selected fields, empty for all
}
/**
- * @brief Counts the rows from a table satisfying the provided condition
+ * Counts the rows from a table satisfying the provided condition
*
* @param string|array $table Table name or array [schema => table]
* @param array $condition Array of fields for condition
+ * @param array $params Array of several parameters
*
* @return int
*
* $count = DBA::count($table, $condition);
* @throws \Exception
*/
- public function count($table, array $condition = [])
+ public function count($table, array $condition = [], array $params = [])
{
if (empty($table)) {
return false;
$condition_string = DBA::buildCondition($condition);
- $sql = "SELECT COUNT(*) AS `count` FROM " . $table_string . $condition_string;
+ if (empty($params['expression'])) {
+ $expression = '*';
+ } elseif (!empty($params['distinct'])) {
+ $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
+ } else {
+ $expression = DBA::quoteIdentifier($params['expression']);
+ }
+
+ $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
$row = $this->fetchFirst($sql, $condition);
}
/**
- * @brief Fills an array with data from a query
+ * Fills an array with data from a query
*
* @param object $stmt statement object
* @param bool $do_close
}
/**
- * @brief Returns the error number of the last query
+ * Returns the error number of the last query
*
* @return string Error number (0 if no error)
*/
}
/**
- * @brief Returns the error message of the last query
+ * Returns the error message of the last query
*
* @return string Error message ('' if no error)
*/
}
/**
- * @brief Closes the current statement
+ * Closes the current statement
*
* @param object $stmt statement object
*
}
/**
- * @brief Return a list of database processes
+ * Return a list of database processes
*
* @return array
* 'list' => List of processes, separated in their different states
}
/**
- * @brief Callback function for "esc_array"
+ * Callback function for "esc_array"
*
* @param mixed $value Array value
* @param string $key Array key
}
/**
- * @brief Escapes a whole array
+ * Escapes a whole array
*
* @param mixed $arr Array with values to be escaped
* @param boolean $add_quotation add quotation marks for string values