3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
24 use Friendica\Core\Config\Capability\IManageConfigValues;
25 use Friendica\Core\System;
26 use Friendica\Database\Definition\DbaDefinition;
27 use Friendica\Database\Definition\ViewDefinition;
28 use Friendica\Network\HTTPException\ServiceUnavailableException;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Profiler;
31 use InvalidArgumentException;
38 use Psr\Log\LoggerInterface;
39 use Psr\Log\NullLogger;
42 * This class is for the low level database stuff that does driver specific things.
47 const MYSQLI = 'mysqli';
49 const INSERT_DEFAULT = 0;
50 const INSERT_UPDATE = 1;
51 const INSERT_IGNORE = 2;
53 protected $connected = false;
56 * @var IManageConfigValues
58 protected $config = null;
62 protected $profiler = null;
64 * @var LoggerInterface
66 protected $logger = null;
67 protected $server_info = '';
68 /** @var PDO|mysqli */
69 protected $connection;
70 protected $driver = '';
71 protected $pdo_emulate_prepares = false;
74 private $affected_rows = 0;
75 protected $in_transaction = false;
76 protected $in_retrial = false;
77 protected $testmode = false;
78 private $relation = [];
79 /** @var DbaDefinition */
80 protected $dbaDefinition;
81 /** @var ViewDefinition */
82 protected $viewDefinition;
83 /** @var string|null */
84 private $currentTable;
86 public function __construct(IManageConfigValues $config, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition)
88 // We are storing these values for being able to perform a reconnect
89 $this->config = $config;
90 $this->dbaDefinition = $dbaDefinition;
91 $this->viewDefinition = $viewDefinition;
93 // Use dummy values - necessary for the first factory call of the logger itself
94 $this->logger = new NullLogger();
95 $this->profiler = new Profiler($config);
101 * @param IManageConfigValues $config
102 * @param Profiler $profiler
103 * @param LoggerInterface $logger
107 * @todo Make this method obsolete - use a clean pattern instead ...
109 public function setDependency(IManageConfigValues $config, Profiler $profiler, LoggerInterface $logger)
111 $this->logger = $logger;
112 $this->profiler = $profiler;
113 $this->config = $config;
117 * Tries to connect to database
119 * @return bool Success
121 public function connect(): bool
123 if (!is_null($this->connection) && $this->connected()) {
124 return $this->connected;
127 // Reset connected state
128 $this->connected = false;
131 $serveraddr = trim($this->config->get('database', 'hostname') ?? '');
132 $serverdata = explode(':', $serveraddr);
133 $host = trim($serverdata[0]);
134 if (count($serverdata) > 1) {
135 $port = trim($serverdata[1]);
138 if (trim($this->config->get('database', 'port') ?? 0)) {
139 $port = trim($this->config->get('database', 'port') ?? 0);
142 $user = trim($this->config->get('database', 'username'));
143 $pass = trim($this->config->get('database', 'password'));
144 $database = trim($this->config->get('database', 'database'));
145 $charset = trim($this->config->get('database', 'charset'));
146 $socket = trim($this->config->get('database', 'socket'));
148 if (!$host && !$socket || !$user) {
152 $persistent = (bool)$this->config->get('database', 'persistent');
154 $this->pdo_emulate_prepares = (bool)$this->config->get('database', 'pdo_emulate_prepares');
156 if (!$this->config->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
157 $this->driver = self::PDO;
159 $connect = 'mysql:unix_socket=' . $socket;
161 $connect = 'mysql:host=' . $host;
163 $connect .= ';port=' . $port;
168 $connect .= ';charset=' . $charset;
171 $connect .= ';dbname=' . $database;
174 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
175 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
176 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
177 $this->connected = true;
178 } catch (PDOException $e) {
179 $this->connected = false;
183 if (!$this->connected && class_exists('\mysqli')) {
184 $this->driver = self::MYSQLI;
187 $this->connection = @new mysqli(null, $user, $pass, $database, null, $socket);
188 } elseif ($port > 0) {
189 $this->connection = @new mysqli($host, $user, $pass, $database, $port);
191 $this->connection = @new mysqli($host, $user, $pass, $database);
194 if (!mysqli_connect_errno()) {
195 $this->connected = true;
198 $this->connection->set_charset($charset);
203 // No suitable SQL driver was found.
204 if (!$this->connected) {
206 $this->connection = null;
209 return $this->connected;
212 public function setTestmode(bool $test)
214 $this->testmode = $test;
218 * Sets the profiler for DBA
220 * @param Profiler $profiler
222 public function setProfiler(Profiler $profiler)
224 $this->profiler = $profiler;
228 * Disconnects the current database connection
230 public function disconnect()
232 if (!is_null($this->connection)) {
233 switch ($this->driver) {
235 $this->connection = null;
238 $this->connection->close();
239 $this->connection = null;
245 $this->connected = false;
249 * Perform a reconnect of an existing database connection
251 public function reconnect()
254 return $this->connect();
258 * Return the database object.
262 public function getConnection()
264 return $this->connection;
268 * Return the database driver string
270 * @return string with either "pdo" or "mysqli"
272 public function getDriver(): string
274 return $this->driver;
278 * Returns the MySQL server version string
280 * This function discriminate between the deprecated mysql API and the current
281 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
283 * @return string Database server information
285 public function serverInfo(): string
287 if ($this->server_info == '') {
288 switch ($this->driver) {
290 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
293 $this->server_info = $this->connection->server_info;
297 return $this->server_info;
301 * Returns the selected database name
303 * @return string Database name
306 public function databaseName(): string
308 $ret = $this->p("SELECT DATABASE() AS `db`");
309 $data = $this->toArray($ret);
310 return $data[0]['db'];
314 * Analyze a database query and log this if some conditions are met.
316 * @param string $query The database query that will be analyzed
320 private function logIndex(string $query)
323 if (!$this->config->get('system', 'db_log_index')) {
327 // Don't explain an explain statement
328 if (strtolower(substr($query, 0, 7)) == "explain") {
332 // Only do the explain on "select", "update" and "delete"
333 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
337 $r = $this->p("EXPLAIN " . $query);
338 if (!$this->isResult($r)) {
342 $watchlist = explode(',', $this->config->get('system', 'db_log_index_watch'));
343 $denylist = explode(',', $this->config->get('system', 'db_log_index_denylist'));
345 while ($row = $this->fetch($r)) {
346 if ((intval($this->config->get('system', 'db_loglimit_index')) > 0)) {
347 $log = (in_array($row['key'], $watchlist) &&
348 ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index'))));
353 if ((intval($this->config->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index_high')))) {
357 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
362 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
364 $this->config->get('system', 'db_log_index'),
365 DateTimeFormat::utcNow() . "\t" .
366 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
367 basename($backtrace[1]["file"]) . "\t" .
368 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
369 substr($query, 0, 4000) . "\n",
377 * Removes every not allowlisted character from the identifier string
379 * @param string $identifier
380 * @return string sanitized identifier
383 private function sanitizeIdentifier(string $identifier): string
385 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
388 public function escape($str)
390 if ($this->connected) {
391 switch ($this->driver) {
393 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
396 return @$this->connection->real_escape_string($str);
399 return str_replace("'", "\\'", $str);
404 * Returns connected flag
406 * @return bool Whether connection to database was success
408 public function isConnected(): bool
410 return $this->connected;
414 * Checks connection status
416 * @return bool Whether connection to database was success
418 public function connected()
422 if (is_null($this->connection)) {
426 switch ($this->driver) {
428 $r = $this->p("SELECT 1");
429 if ($this->isResult($r)) {
430 $row = $this->toArray($r);
431 $connected = ($row[0]['1'] == '1');
435 $connected = $this->connection->ping();
443 * Replaces ANY_VALUE() function by MIN() function,
444 * if the database server does not support ANY_VALUE().
446 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
447 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
448 * A standard fall-back is to use MIN().
450 * @param string $sql An SQL string without the values
452 * @return string The input SQL string modified if necessary.
454 public function anyValueFallback(string $sql): string
456 $server_info = $this->serverInfo();
457 if (version_compare($server_info, '5.7.5', '<') ||
458 (stripos($server_info, 'MariaDB') !== false)) {
459 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
465 * Replaces the ? placeholders with the parameters in the $args array
467 * @param string $sql SQL query
468 * @param array $args The parameters that are to replace the ? placeholders
470 * @return string The replaced SQL query
472 private function replaceParameters(string $sql, array $args): string
475 foreach ($args as $param => $value) {
476 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
477 $replace = intval($args[$param]);
478 } elseif (is_null($args[$param])) {
481 $replace = "'" . $this->escape($args[$param]) . "'";
484 $pos = strpos($sql, '?', $offset);
485 if ($pos !== false) {
486 $sql = substr_replace($sql, $replace, $pos, 1);
488 $offset = $pos + strlen($replace);
494 * Executes a prepared statement that returns data
496 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
498 * Please only use it with complicated queries.
499 * For all regular queries please use DBA::select or DBA::exists
501 * @param string $sql SQL statement
503 * @return bool|object statement object or result object
506 public function p(string $sql)
508 $this->currentTable = null;
509 $this->profiler->startRecording('database');
510 $stamp1 = microtime(true);
512 $params = DBA::getParam(func_get_args());
514 // Renumber the array keys to be sure that they fit
517 foreach ($params as $param) {
518 // Avoid problems with some MySQL servers and boolean values. See issue #3645
519 if (is_bool($param)) {
520 $param = (int)$param;
522 $args[++$i] = $param;
525 if (!$this->connected) {
529 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
530 // Question: Should we continue or stop the query here?
531 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
534 $sql = DBA::cleanQuery($sql);
535 $sql = $this->anyValueFallback($sql);
539 if ($this->config->get('system', 'db_callstack') !== null) {
540 $sql = "/*" . System::callstack() . " */ " . $sql;
546 $this->affected_rows = 0;
548 // We have to make some things different if this function is called from "e"
549 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
551 if (isset($trace[1])) {
552 $called_from = $trace[1];
554 // We use just something that is defined to avoid warnings
555 $called_from = $trace[0];
557 // We are having an own error logging in the function "e"
558 $called_from_e = ($called_from['function'] == 'e');
560 if (!isset($this->connection)) {
561 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
564 switch ($this->driver) {
566 // If there are no arguments we use "query"
567 if (count($args) == 0) {
568 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
569 $errorInfo = $this->connection->errorInfo();
570 $this->error = (string)$errorInfo[2];
571 $this->errorno = (int)$errorInfo[1];
576 $this->affected_rows = $retval->rowCount();
580 /** @var $stmt mysqli_stmt|PDOStatement */
581 if (!$stmt = $this->connection->prepare($sql)) {
582 $errorInfo = $this->connection->errorInfo();
583 $this->error = (string)$errorInfo[2];
584 $this->errorno = (int)$errorInfo[1];
590 foreach (array_keys($args) as $param) {
591 $data_type = PDO::PARAM_STR;
592 if (is_int($args[$param])) {
593 $data_type = PDO::PARAM_INT;
594 } elseif ($args[$param] !== null) {
595 $args[$param] = (string)$args[$param];
598 $stmt->bindParam($param, $args[$param], $data_type);
601 if (!$stmt->execute()) {
602 $errorInfo = $stmt->errorInfo();
603 $this->error = (string)$errorInfo[2];
604 $this->errorno = (int)$errorInfo[1];
609 $this->affected_rows = $retval->rowCount();
613 // There are SQL statements that cannot be executed with a prepared statement
614 $parts = explode(' ', $orig_sql);
615 $command = strtolower($parts[0]);
616 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
618 // The fallback routine is called as well when there are no arguments
619 if (!$can_be_prepared || (count($args) == 0)) {
620 $retval = $this->connection->query($this->replaceParameters($sql, $args));
621 if ($this->connection->errno) {
622 $this->error = (string)$this->connection->error;
623 $this->errorno = (int)$this->connection->errno;
627 if (isset($retval->num_rows)) {
628 $this->affected_rows = $retval->num_rows;
630 $this->affected_rows = $this->connection->affected_rows;
636 $stmt = $this->connection->stmt_init();
638 if (!$stmt->prepare($sql)) {
639 $this->error = (string)$stmt->error;
640 $this->errorno = (int)$stmt->errno;
648 foreach (array_keys($args) as $param) {
649 if (is_int($args[$param])) {
651 } elseif (is_float($args[$param])) {
653 } elseif (is_string($args[$param])) {
655 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
657 $args[$param] = (string)$args[$param];
661 $values[] = &$args[$param];
664 if (count($values) > 0) {
665 array_unshift($values, $param_types);
666 call_user_func_array([$stmt, 'bind_param'], $values);
669 if (!$stmt->execute()) {
670 $this->error = (string)$this->connection->error;
671 $this->errorno = (int)$this->connection->errno;
675 $stmt->store_result();
677 $this->affected_rows = $retval->affected_rows;
682 // See issue https://github.com/friendica/friendica/issues/8572
683 // Ensure that we always get an error message on an error.
684 if ($is_error && empty($this->errorno)) {
688 if ($is_error && empty($this->error)) {
689 $this->error = 'Unknown database error';
692 // We are having an own error logging in the function "e"
693 if (($this->errorno != 0) && !$called_from_e) {
694 // We have to preserve the error code, somewhere in the logging it get lost
695 $error = $this->error;
696 $errorno = $this->errorno;
698 if ($this->testmode) {
699 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
702 $this->logger->error('DB Error', [
705 'callstack' => System::callstack(8),
706 'params' => $this->replaceParameters($sql, $args),
709 // On a lost connection we try to reconnect - but only once.
710 if ($errorno == 2006) {
711 if ($this->in_retrial || !$this->reconnect()) {
712 // It doesn't make sense to continue when the database connection was lost
713 if ($this->in_retrial) {
714 $this->logger->notice('Giving up retrial because of database error', [
719 $this->logger->notice('Couldn\'t reconnect after database error', [
727 $this->logger->notice('Reconnected after database error', [
731 $this->in_retrial = true;
732 $ret = $this->p($sql, $args);
733 $this->in_retrial = false;
738 $this->error = (string)$error;
739 $this->errorno = (int)$errorno;
742 $this->profiler->stopRecording();
744 if ($this->config->get('system', 'db_log')) {
745 $stamp2 = microtime(true);
746 $duration = (float)($stamp2 - $stamp1);
748 if (($duration > $this->config->get('system', 'db_loglimit'))) {
749 $duration = round($duration, 3);
750 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
753 $this->config->get('system', 'db_log'),
754 DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
755 basename($backtrace[1]['file']) . "\t" .
756 $backtrace[1]['line'] . "\t" . $backtrace[2]['function'] . "\t" .
757 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n",
766 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
768 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
770 * @param string $sql SQL statement
772 * @return boolean Was the query successful? False is returned only if an error occurred
775 public function e(string $sql): bool
779 $this->profiler->startRecording('database_write');
781 $params = DBA::getParam(func_get_args());
783 // In a case of a deadlock we are repeating the query 20 times
787 $stmt = $this->p($sql, $params);
789 if (is_bool($stmt)) {
791 } elseif (is_object($stmt)) {
799 } while (($this->errorno == 1213) && (--$timeout > 0));
801 if ($this->errorno != 0) {
802 // We have to preserve the error code, somewhere in the logging it get lost
803 $error = $this->error;
804 $errorno = $this->errorno;
806 if ($this->testmode) {
807 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
810 $this->logger->error('DB Error', [
813 'callstack' => System::callstack(8),
814 'params' => $this->replaceParameters($sql, $params),
817 // On a lost connection we simply quit.
818 // A reconnect like in $this->p could be dangerous with modifications
819 if ($errorno == 2006) {
820 $this->logger->notice('Giving up because of database error', [
827 $this->error = $error;
828 $this->errorno = $errorno;
831 $this->profiler->stopRecording();
837 * Check if data exists
839 * @param string $table Table name in format [schema.]table
840 * @param array $condition Array of fields for condition
842 * @return boolean Are there rows for that condition?
844 * @todo Please unwrap the DBStructure::existsTable() call so this method has one behavior only: checking existence on records
846 public function exists(string $table, array $condition): bool
854 if (empty($condition)) {
855 return DBStructure::existsTable($table);
859 $first_key = key($condition);
860 if (!is_int($first_key)) {
861 $fields = [$first_key];
864 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
866 if (is_bool($stmt)) {
869 $retval = ($this->numRows($stmt) > 0);
878 * Fetches the first row
880 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
882 * Fetches the first row
884 * @param string $sql SQL statement
886 * @return array|bool first row of query or false on failure
889 public function fetchFirst(string $sql)
891 $params = DBA::getParam(func_get_args());
893 $stmt = $this->p($sql, $params);
895 if (is_bool($stmt)) {
898 $retval = $this->fetch($stmt);
907 * Returns the number of affected rows of the last statement
909 * @return int Number of rows
911 public function affectedRows(): int
913 return $this->affected_rows;
917 * Returns the number of columns of a statement
919 * @param object Statement object
921 * @return int Number of columns
923 public function columnCount($stmt): int
925 if (!is_object($stmt)) {
928 switch ($this->driver) {
930 return $stmt->columnCount();
932 return $stmt->field_count;
938 * Returns the number of rows of a statement
940 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
942 * @return int Number of rows
944 public function numRows($stmt): int
946 if (!is_object($stmt)) {
949 switch ($this->driver) {
951 return $stmt->rowCount();
953 return $stmt->num_rows;
961 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
963 * @return array|bool Current row or false on failure
965 public function fetch($stmt)
967 $this->profiler->startRecording('database');
971 if (!is_object($stmt)) {
975 switch ($this->driver) {
977 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
978 if (!empty($this->currentTable) && is_array($columns)) {
979 $columns = $this->castFields($this->currentTable, $columns);
983 if (get_class($stmt) == 'mysqli_result') {
984 $columns = $stmt->fetch_assoc() ?? false;
988 // This code works, but is slow
990 // Bind the result to a result array
994 for ($x = 0; $x < $stmt->field_count; $x++) {
995 $cols[] = &$cols_num[$x];
998 call_user_func_array([$stmt, 'bind_result'], $cols);
1000 if (!$stmt->fetch()) {
1005 // We need to get the field names for the array keys
1006 // It seems that there is no better way to do this.
1007 $result = $stmt->result_metadata();
1008 $fields = $result->fetch_fields();
1010 foreach ($cols_num as $param => $col) {
1011 $columns[$fields[$param]->name] = $col;
1015 $this->profiler->stopRecording();
1021 * Insert a row into a table. Field value objects will be cast as string.
1023 * @param string $table Table name in format [schema.]table
1024 * @param array $param parameter array
1025 * @param int $duplicate_mode What to do on a duplicated entry
1027 * @return boolean was the insert successful?
1028 * @throws \Exception
1030 public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1032 if (empty($table) || empty($param)) {
1033 $this->logger->info('Table and fields have to be set');
1037 $param = $this->castFields($table, $param);
1039 $table_string = DBA::buildTableString([$table]);
1041 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1043 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1047 if ($duplicate_mode == self::INSERT_IGNORE) {
1051 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1053 if ($duplicate_mode == self::INSERT_UPDATE) {
1054 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1056 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1058 $values = array_values($param);
1059 $param = array_merge_recursive($values, $values);
1062 $result = $this->e($sql, $param);
1063 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1067 return $this->affectedRows() != 0;
1071 * Inserts a row with the provided data in the provided table.
1072 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1074 * @param string $table Table name in format [schema.]table
1075 * @param array $param parameter array
1076 * @return boolean was the insert successful?
1077 * @throws \Exception
1079 public function replace(string $table, array $param): bool
1081 if (empty($table) || empty($param)) {
1082 $this->logger->info('Table and fields have to be set');
1086 $param = $this->castFields($table, $param);
1088 $table_string = DBA::buildTableString([$table]);
1090 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1092 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1094 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1096 return $this->e($sql, $param);
1100 * Fetch the id of the last insert command
1102 * @return integer Last inserted id
1104 public function lastInsertId(): int
1106 switch ($this->driver) {
1108 $id = $this->connection->lastInsertId();
1111 $id = $this->connection->insert_id;
1118 * Locks a table for exclusive write access
1120 * This function can be extended in the future to accept a table array as well.
1122 * @param string $table Table name in format [schema.]table
1123 * @return boolean was the lock successful?
1124 * @throws \Exception
1126 public function lock(string $table): bool
1128 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1129 if ($this->driver == self::PDO) {
1130 $this->e("SET autocommit=0");
1131 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1133 $this->connection->autocommit(false);
1136 $success = $this->e("LOCK TABLES " . DBA::buildTableString([$table]) . " WRITE");
1138 if ($this->driver == self::PDO) {
1139 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1143 if ($this->driver == self::PDO) {
1144 $this->e("SET autocommit=1");
1146 $this->connection->autocommit(true);
1149 $this->in_transaction = true;
1155 * Unlocks all locked tables
1157 * @return boolean was the unlock successful?
1158 * @throws \Exception
1160 public function unlock(): bool
1162 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1163 $this->performCommit();
1165 if ($this->driver == self::PDO) {
1166 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1169 $success = $this->e("UNLOCK TABLES");
1171 if ($this->driver == self::PDO) {
1172 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1173 $this->e("SET autocommit=1");
1175 $this->connection->autocommit(true);
1178 $this->in_transaction = false;
1183 * Starts a transaction
1185 * @return boolean Was the command executed successfully?
1187 public function transaction(): bool
1189 if (!$this->performCommit()) {
1193 switch ($this->driver) {
1195 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1201 if (!$this->connection->begin_transaction()) {
1207 $this->in_transaction = true;
1212 * Performs the commit
1214 * @return boolean Was the command executed successfully?
1216 protected function performCommit(): bool
1218 switch ($this->driver) {
1220 if (!$this->connection->inTransaction()) {
1224 return $this->connection->commit();
1227 return $this->connection->commit();
1236 * @return boolean Was the command executed successfully?
1238 public function commit(): bool
1240 if (!$this->performCommit()) {
1243 $this->in_transaction = false;
1250 * @return boolean Was the command executed successfully?
1252 public function rollback(): bool
1256 switch ($this->driver) {
1258 if (!$this->connection->inTransaction()) {
1262 $ret = $this->connection->rollBack();
1266 $ret = $this->connection->rollback();
1270 $this->in_transaction = false;
1275 * Delete a row from a table
1277 * @param string $table Table name
1278 * @param array $conditions Field condition(s)
1280 * @return boolean was the delete successful?
1281 * @throws \Exception
1283 public function delete(string $table, array $conditions): bool
1285 if (empty($table) || empty($conditions)) {
1286 $this->logger->info('Table and conditions have to be set');
1290 $table_string = DBA::buildTableString([$table]);
1292 $condition_string = DBA::buildCondition($conditions);
1294 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1295 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1296 return $this->e($sql, $conditions);
1300 * Updates rows in the database. Field value objects will be cast as string.
1302 * When $old_fields is set to an array,
1303 * the system will only do an update if the fields in that array changed.
1306 * Only the values in $old_fields are compared.
1307 * This is an intentional behaviour.
1310 * We include the timestamp field in $fields but not in $old_fields.
1311 * Then the row will only get the new timestamp when the other fields had changed.
1313 * When $old_fields is set to a boolean value the system will do this compare itself.
1314 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1317 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1318 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1320 * @param string $table Table name in format [schema.]table
1321 * @param array $fields contains the fields that are updated
1322 * @param array $condition condition array with the key values
1323 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
1324 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1326 * @return boolean was the update successful?
1327 * @throws \Exception
1328 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1330 public function update(string $table, array $fields, array $condition, $old_fields = [], array $params = [])
1332 if (empty($table) || empty($fields) || empty($condition)) {
1333 $this->logger->info('Table, fields and condition have to be set');
1337 if (is_bool($old_fields)) {
1338 $do_insert = $old_fields;
1340 $old_fields = $this->selectFirst($table, [], $condition);
1342 if (is_bool($old_fields)) {
1344 $values = array_merge($condition, $fields);
1345 return $this->replace($table, $values);
1351 foreach ($old_fields as $fieldname => $content) {
1352 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1353 unset($fields[$fieldname]);
1357 if (count($fields) == 0) {
1361 $fields = $this->castFields($table, $fields);
1362 $direct_fields = [];
1364 foreach ($fields as $key => $value) {
1365 if (is_numeric($key)) {
1366 $direct_fields[] = $value;
1367 unset($fields[$key]);
1372 $table_string = DBA::buildTableString([$table]);
1374 $condition_string = DBA::buildCondition($condition);
1376 if (!empty($params['ignore'])) {
1377 $ignore = 'IGNORE ';
1382 $sql = "UPDATE " . $ignore . $table_string . " SET "
1383 . ((count($fields) > 0) ? implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?" : "")
1384 . ((count($direct_fields) > 0) ? ((count($fields) > 0) ? " , " : "") . implode(" , ", $direct_fields) : "")
1385 . $condition_string;
1387 // Combines the updated fields parameter values with the condition parameter values
1388 $params = array_merge(array_values($fields), $condition);
1390 return $this->e($sql, $params);
1394 * Retrieve a single record from a table and returns it in an associative array
1396 * @param string $table Table name in format [schema.]table
1397 * @param array $fields Array of selected fields, empty for all
1398 * @param array $condition Array of fields for condition
1399 * @param array $params Array of several parameters
1401 * @return bool|array
1402 * @throws \Exception
1403 * @see $this->select
1405 public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1407 $params['limit'] = 1;
1408 $result = $this->select($table, $fields, $condition, $params);
1410 if (is_bool($result)) {
1413 $row = $this->fetch($result);
1414 $this->close($result);
1420 * Select rows from a table and fills an array with the data
1422 * @param string $table Table name in format [schema.]table
1423 * @param array $fields Array of selected fields, empty for all
1424 * @param array $condition Array of fields for condition
1425 * @param array $params Array of several parameters
1426 * @return array Data array
1427 * @throws \Exception
1430 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1432 return $this->toArray($this->select($table, $fields, $condition, $params));
1436 * Escape fields, adding special treatment for "group by" handling
1438 * @param array $fields
1439 * @param array $options
1440 * @return array Escaped fields
1442 private function escapeFields(array $fields, array $options): array
1444 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1445 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1446 // Otherwise MySQL would report errors.
1447 if (!empty($options['group_by']) && !empty($options['order'])) {
1448 foreach ($options['order'] as $key => $field) {
1449 if (!is_int($key)) {
1450 if (!in_array($key, $fields)) {
1454 if (!in_array($field, $fields)) {
1461 array_walk($fields, function (&$value, $key) use ($options) {
1463 $value = DBA::quoteIdentifier($field);
1465 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1466 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1474 * Select rows from a table
1480 * $table = ['schema' => 'table'];
1481 * @see DBA::buildTableString()
1483 * $fields = ['id', 'uri', 'uid', 'network'];
1485 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1487 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1488 * @see DBA::buildCondition()
1490 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1491 * @see DBA::buildParameter()
1493 * $data = DBA::select($table, $fields, $condition, $params);
1495 * @param string $table Table name in format [schema.]table
1496 * @param array $fields Array of selected fields, empty for all
1497 * @param array $condition Array of fields for condition
1498 * @param array $params Array of several parameters
1499 * @return boolean|object
1500 * @throws \Exception
1502 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1504 if (empty($table)) {
1508 if (count($fields) > 0) {
1509 $fields = $this->escapeFields($fields, $params);
1510 $select_string = implode(', ', $fields);
1512 $select_string = '*';
1515 $table_string = DBA::buildTableString([$table]);
1517 $condition_string = DBA::buildCondition($condition);
1519 $param_string = DBA::buildParameter($params);
1521 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1523 $result = $this->p($sql, $condition);
1525 if ($this->driver == self::PDO && !empty($result)) {
1526 $this->currentTable = $table;
1533 * Counts the rows from a table satisfying the provided condition
1535 * @param string $table Table name in format [schema.]table
1536 * @param array $condition Array of fields for condition
1537 * @param array $params Array of several parameters
1539 * @return int Count of rows
1544 * $condition = ["uid" => 1, "network" => 'dspr'];
1546 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1548 * $count = DBA::count($table, $condition);
1549 * @throws \Exception
1551 public function count(string $table, array $condition = [], array $params = []): int
1553 if (empty($table)) {
1554 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1557 $table_string = DBA::buildTableString([$table]);
1559 $condition_string = DBA::buildCondition($condition);
1561 if (empty($params['expression'])) {
1563 } elseif (!empty($params['distinct'])) {
1564 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1566 $expression = DBA::quoteIdentifier($params['expression']);
1569 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1571 $row = $this->fetchFirst($sql, $condition);
1573 if (!isset($row['count'])) {
1574 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1577 return (int)$row['count'];
1582 * Fills an array with data from a query
1584 * @param object $stmt statement object
1585 * @param bool $do_close Close database connection after last row
1586 * @param int $count maximum number of rows to be fetched
1588 * @return array Data array
1590 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1592 if (is_bool($stmt)) {
1597 while ($row = $this->fetch($stmt)) {
1599 if (($count != 0) && (count($data) == $count)) {
1605 $this->close($stmt);
1612 * Cast field types according to the table definition
1614 * @param string $table
1615 * @param array $fields
1616 * @return array casted fields
1618 public function castFields(string $table, array $fields): array
1620 // When there is no data, we don't need to do something
1621 if (empty($fields)) {
1625 // We only need to cast fields with PDO
1626 if ($this->driver != self::PDO) {
1630 // We only need to cast when emulating the prepares
1631 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1637 $tables = $this->dbaDefinition->getAll();
1638 if (empty($tables[$table])) {
1639 // When a matching table wasn't found we check if it is a view
1640 $views = $this->viewDefinition->getAll();
1641 if (empty($views[$table])) {
1645 foreach (array_keys($fields) as $field) {
1646 if (!empty($views[$table]['fields'][$field])) {
1647 $viewdef = $views[$table]['fields'][$field];
1648 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1649 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1654 foreach ($tables[$table]['fields'] as $field => $definition) {
1655 $types[$field] = $definition['type'];
1659 foreach ($fields as $field => $content) {
1660 if (is_null($content) || empty($types[$field])) {
1664 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1665 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1666 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1667 $fields[$field] = (int)$content;
1669 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1670 $fields[$field] = (float)$content;
1678 * Returns the error number of the last query
1680 * @return string Error number (0 if no error)
1682 public function errorNo(): int
1684 return $this->errorno;
1688 * Returns the error message of the last query
1690 * @return string Error message ('' if no error)
1692 public function errorMessage(): string
1694 return $this->error;
1698 * Closes the current statement
1700 * @param object $stmt statement object
1702 * @return boolean was the close successful?
1704 public function close($stmt): bool
1707 $this->profiler->startRecording('database');
1709 if (!is_object($stmt)) {
1713 switch ($this->driver) {
1715 $ret = $stmt->closeCursor();
1718 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1719 // We should be careful not to assume the object type of $stmt
1720 // because DBA::p() has been able to return both types.
1721 if ($stmt instanceof mysqli_stmt) {
1722 $stmt->free_result();
1723 $ret = $stmt->close();
1724 } elseif ($stmt instanceof mysqli_result) {
1733 $this->profiler->stopRecording();
1739 * Return a list of database processes
1742 * 'list' => List of processes, separated in their different states
1743 * 'amount' => Number of concurrent database processes
1744 * @throws \Exception
1746 public function processlist(): array
1748 $ret = $this->p('SHOW PROCESSLIST');
1749 $data = $this->toArray($ret);
1753 foreach ($data as $process) {
1754 $state = trim($process['State']);
1756 // Filter out all non blocking processes
1757 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1764 foreach ($states as $state => $usage) {
1765 if ($statelist != '') {
1768 $statelist .= $state . ': ' . $usage;
1770 return (['list' => $statelist, 'amount' => $processes]);
1776 * @param string $table a given table
1778 * @return bool True, if successfully optimized, otherwise false
1779 * @throws \Exception
1781 public function optimizeTable(string $table): bool
1783 return $this->e("OPTIMIZE TABLE " . DBA::buildTableString([$table])) !== false;
1787 * Kill sleeping database processes
1791 public function deleteSleepingProcesses()
1793 $processes = $this->p("SHOW FULL PROCESSLIST");
1794 while ($process = $this->fetch($processes)) {
1795 if (($process['Command'] != 'Sleep') || ($process['Time'] < 300) || ($process['db'] != $this->databaseName())) {
1799 $this->e("KILL ?", $process['Id']);
1801 $this->close($processes);
1805 * Fetch a database variable
1807 * @param string $name
1808 * @return string|null content or null if inexistent
1809 * @throws \Exception
1811 public function getVariable(string $name)
1813 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1814 return $result['Value'] ?? null;
1818 * Checks if $array is a filled array with at least one entry.
1820 * @param mixed $array A filled array with at least one entry
1821 * @return boolean Whether $array is a filled array or an object with rows
1823 public function isResult($array): bool
1825 // It could be a return value from an update statement
1826 if (is_bool($array)) {
1830 if (is_object($array)) {
1831 return $this->numRows($array) > 0;
1834 return (is_array($array) && (count($array) > 0));
1838 * Callback function for "esc_array"
1840 * @param mixed $value Array value
1841 * @param string $key Array key
1842 * @param boolean $add_quotation add quotation marks for string values
1845 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1847 if (!$add_quotation) {
1848 if (is_bool($value)) {
1849 $value = ($value ? '1' : '0');
1851 $value = $this->escape($value);
1856 if (is_bool($value)) {
1857 $value = ($value ? 'true' : 'false');
1858 } elseif (is_float($value) || is_integer($value)) {
1859 $value = (string)$value;
1861 $value = "'" . $this->escape($value) . "'";
1866 * Escapes a whole array
1868 * @param mixed $arr Array with values to be escaped
1869 * @param boolean $add_quotation add quotation marks for string values
1872 public function escapeArray(&$arr, bool $add_quotation = false)
1874 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1878 * Replaces a string in the provided fields of the provided table
1880 * @param string $table Table name
1881 * @param array $fields List of field names in the provided table
1882 * @param string $search String to search for
1883 * @param string $replace String to replace with
1885 * @throws \Exception
1887 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1889 $search = $this->escape($search);
1890 $replace = $this->escape($replace);
1893 foreach ($fields as $field) {
1894 $field = DBA::quoteIdentifier($field);
1895 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1898 $upds = implode(', ', $upd);
1900 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1902 if (!$this->isResult($r)) {
1903 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());