3 * @copyright Copyright (C) 2020, Friendica
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\Cache;
25 use Friendica\Core\System;
26 use Friendica\Network\HTTPException\InternalServerErrorException;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Profiler;
35 use Psr\Log\LoggerInterface;
38 * This class is for the low level database stuff that does driver specific things.
42 protected $connected = false;
47 protected $configCache;
53 * @var LoggerInterface
56 protected $server_info = '';
57 /** @var PDO|mysqli */
58 protected $connection;
60 protected $emulate_prepares = false;
61 private $error = false;
63 private $affected_rows = 0;
64 protected $in_transaction = false;
65 protected $in_retrial = false;
66 protected $testmode = false;
67 private $relation = [];
69 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
71 // We are storing these values for being able to perform a reconnect
72 $this->configCache = $configCache;
73 $this->profiler = $profiler;
74 $this->logger = $logger;
78 if ($this->isConnected()) {
79 // Loads DB_UPDATE_VERSION constant
80 DBStructure::definition($configCache->get('system', 'basepath'), false);
84 public function connect()
86 if (!is_null($this->connection) && $this->connected()) {
87 return $this->connected;
90 // Reset connected state
91 $this->connected = false;
94 $serveraddr = trim($this->configCache->get('database', 'hostname'));
95 $serverdata = explode(':', $serveraddr);
96 $server = $serverdata[0];
97 if (count($serverdata) > 1) {
98 $port = trim($serverdata[1]);
101 if (!empty(trim($this->configCache->get('database', 'port')))) {
102 $port = trim(trim($this->configCache->get('database', 'port')));
105 $server = trim($server);
106 $user = trim($this->configCache->get('database', 'username'));
107 $pass = trim($this->configCache->get('database', 'password'));
108 $db = trim($this->configCache->get('database', 'database'));
109 $charset = trim($this->configCache->get('database', 'charset'));
111 if (!(strlen($server) && strlen($user))) {
115 $persistent = (bool)$this->configCache->get('database', 'persistent');
117 $this->emulate_prepares = (bool)$this->configCache->get('database', 'emulate_prepares');
118 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
120 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
121 $this->driver = 'pdo';
122 $connect = "mysql:host=" . $server . ";dbname=" . $db;
125 $connect .= ";port=" . $port;
129 $connect .= ";charset=" . $charset;
133 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
134 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
135 $this->connected = true;
136 } catch (PDOException $e) {
137 $this->connected = false;
141 if (!$this->connected && class_exists('\mysqli')) {
142 $this->driver = 'mysqli';
145 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
147 $this->connection = @new mysqli($server, $user, $pass, $db);
150 if (!mysqli_connect_errno()) {
151 $this->connected = true;
154 $this->connection->set_charset($charset);
159 // No suitable SQL driver was found.
160 if (!$this->connected) {
161 $this->driver = null;
162 $this->connection = null;
165 return $this->connected;
168 public function setTestmode(bool $test)
170 $this->testmode = $test;
173 * Sets the logger for DBA
175 * @note this is necessary because if we want to load the logger configuration
176 * from the DB, but there's an error, we would print out an exception.
177 * So the logger gets updated after the logger configuration can be retrieved
180 * @param LoggerInterface $logger
182 public function setLogger(LoggerInterface $logger)
184 $this->logger = $logger;
188 * Sets the profiler for DBA
190 * @param Profiler $profiler
192 public function setProfiler(Profiler $profiler)
194 $this->profiler = $profiler;
197 * Disconnects the current database connection
199 public function disconnect()
201 if (!is_null($this->connection)) {
202 switch ($this->driver) {
204 $this->connection = null;
207 $this->connection->close();
208 $this->connection = null;
213 $this->driver = null;
214 $this->connected = false;
218 * Perform a reconnect of an existing database connection
220 public function reconnect()
223 return $this->connect();
227 * Return the database object.
231 public function getConnection()
233 return $this->connection;
237 * Returns the MySQL server version string
239 * This function discriminate between the deprecated mysql API and the current
240 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
244 public function serverInfo()
246 if ($this->server_info == '') {
247 switch ($this->driver) {
249 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
252 $this->server_info = $this->connection->server_info;
256 return $this->server_info;
260 * Returns the selected database name
265 public function databaseName()
267 $ret = $this->p("SELECT DATABASE() AS `db`");
268 $data = $this->toArray($ret);
269 return $data[0]['db'];
273 * Analyze a database query and log this if some conditions are met.
275 * @param string $query The database query that will be analyzed
279 private function logIndex($query)
282 if (!$this->configCache->get('system', 'db_log_index')) {
286 // Don't explain an explain statement
287 if (strtolower(substr($query, 0, 7)) == "explain") {
291 // Only do the explain on "select", "update" and "delete"
292 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
296 $r = $this->p("EXPLAIN " . $query);
297 if (!$this->isResult($r)) {
301 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
302 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
304 while ($row = $this->fetch($r)) {
305 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
306 $log = (in_array($row['key'], $watchlist) &&
307 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
312 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
316 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
321 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
322 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
323 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
324 basename($backtrace[1]["file"]) . "\t" .
325 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
326 substr($query, 0, 4000) . "\n", FILE_APPEND);
332 * Removes every not allowlisted character from the identifier string
334 * @param string $identifier
336 * @return string sanitized identifier
339 private function sanitizeIdentifier($identifier)
341 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
344 public function escape($str)
346 if ($this->connected) {
347 switch ($this->driver) {
349 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
352 return @$this->connection->real_escape_string($str);
355 return str_replace("'", "\\'", $str);
359 public function isConnected()
361 return $this->connected;
364 public function connected()
368 if (is_null($this->connection)) {
372 switch ($this->driver) {
374 $r = $this->p("SELECT 1");
375 if ($this->isResult($r)) {
376 $row = $this->toArray($r);
377 $connected = ($row[0]['1'] == '1');
381 $connected = $this->connection->ping();
389 * Replaces ANY_VALUE() function by MIN() function,
390 * if the database server does not support ANY_VALUE().
392 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
393 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
394 * A standard fall-back is to use MIN().
396 * @param string $sql An SQL string without the values
398 * @return string The input SQL string modified if necessary.
400 public function anyValueFallback($sql)
402 $server_info = $this->serverInfo();
403 if (version_compare($server_info, '5.7.5', '<') ||
404 (stripos($server_info, 'MariaDB') !== false)) {
405 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
411 * Replaces the ? placeholders with the parameters in the $args array
413 * @param string $sql SQL query
414 * @param array $args The parameters that are to replace the ? placeholders
416 * @return string The replaced SQL query
418 private function replaceParameters($sql, $args)
421 foreach ($args AS $param => $value) {
422 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
423 $replace = intval($args[$param]);
424 } elseif (is_null($args[$param])) {
427 $replace = "'" . $this->escape($args[$param]) . "'";
430 $pos = strpos($sql, '?', $offset);
431 if ($pos !== false) {
432 $sql = substr_replace($sql, $replace, $pos, 1);
434 $offset = $pos + strlen($replace);
440 * Executes a prepared statement that returns data
442 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
444 * Please only use it with complicated queries.
445 * For all regular queries please use DBA::select or DBA::exists
447 * @param string $sql SQL statement
449 * @return bool|object statement object or result object
452 public function p($sql)
455 $stamp1 = microtime(true);
457 $params = DBA::getParam(func_get_args());
459 // Renumber the array keys to be sure that they fit
462 foreach ($params AS $param) {
463 // Avoid problems with some MySQL servers and boolean values. See issue #3645
464 if (is_bool($param)) {
465 $param = (int)$param;
467 $args[++$i] = $param;
470 if (!$this->connected) {
474 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
475 // Question: Should we continue or stop the query here?
476 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
479 $sql = DBA::cleanQuery($sql);
480 $sql = $this->anyValueFallback($sql);
484 if ($this->configCache->get('system', 'db_callstack') !== null) {
485 $sql = "/*" . System::callstack() . " */ " . $sql;
491 $this->affected_rows = 0;
493 // We have to make some things different if this function is called from "e"
494 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
496 if (isset($trace[1])) {
497 $called_from = $trace[1];
499 // We use just something that is defined to avoid warnings
500 $called_from = $trace[0];
502 // We are having an own error logging in the function "e"
503 $called_from_e = ($called_from['function'] == 'e');
505 if (!isset($this->connection)) {
506 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
509 switch ($this->driver) {
511 // If there are no arguments we use "query"
512 if ($this->emulate_prepares || count($args) == 0) {
513 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
514 $errorInfo = $this->connection->errorInfo();
515 $this->error = $errorInfo[2];
516 $this->errorno = $errorInfo[1];
521 $this->affected_rows = $retval->rowCount();
525 /** @var $stmt mysqli_stmt|PDOStatement */
526 if (!$stmt = $this->connection->prepare($sql)) {
527 $errorInfo = $this->connection->errorInfo();
528 $this->error = $errorInfo[2];
529 $this->errorno = $errorInfo[1];
535 foreach ($args AS $param => $value) {
536 if (is_int($args[$param])) {
537 $data_type = PDO::PARAM_INT;
539 $data_type = PDO::PARAM_STR;
541 $stmt->bindParam($param, $args[$param], $data_type);
544 if (!$stmt->execute()) {
545 $errorInfo = $stmt->errorInfo();
546 $this->error = $errorInfo[2];
547 $this->errorno = $errorInfo[1];
552 $this->affected_rows = $retval->rowCount();
556 // There are SQL statements that cannot be executed with a prepared statement
557 $parts = explode(' ', $orig_sql);
558 $command = strtolower($parts[0]);
559 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
561 // The fallback routine is called as well when there are no arguments
562 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
563 $retval = $this->connection->query($this->replaceParameters($sql, $args));
564 if ($this->connection->errno) {
565 $this->error = $this->connection->error;
566 $this->errorno = $this->connection->errno;
570 if (isset($retval->num_rows)) {
571 $this->affected_rows = $retval->num_rows;
573 $this->affected_rows = $this->connection->affected_rows;
579 $stmt = $this->connection->stmt_init();
581 if (!$stmt->prepare($sql)) {
582 $this->error = $stmt->error;
583 $this->errorno = $stmt->errno;
591 foreach ($args AS $param => $value) {
592 if (is_int($args[$param])) {
594 } elseif (is_float($args[$param])) {
596 } elseif (is_string($args[$param])) {
601 $values[] = &$args[$param];
604 if (count($values) > 0) {
605 array_unshift($values, $param_types);
606 call_user_func_array([$stmt, 'bind_param'], $values);
609 if (!$stmt->execute()) {
610 $this->error = $this->connection->error;
611 $this->errorno = $this->connection->errno;
615 $stmt->store_result();
617 $this->affected_rows = $retval->affected_rows;
622 // See issue https://github.com/friendica/friendica/issues/8572
623 // Ensure that we always get an error message on an error.
624 if ($is_error && empty($this->errorno)) {
628 if ($is_error && empty($this->error)) {
629 $this->error = 'Unknown database error';
632 // We are having an own error logging in the function "e"
633 if (($this->errorno != 0) && !$called_from_e) {
634 // We have to preserve the error code, somewhere in the logging it get lost
635 $error = $this->error;
636 $errorno = $this->errorno;
638 if ($this->testmode) {
639 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
642 $this->logger->error('DB Error', [
645 'callstack' => System::callstack(8),
646 'params' => $this->replaceParameters($sql, $args),
649 // On a lost connection we try to reconnect - but only once.
650 if ($errorno == 2006) {
651 if ($this->in_retrial || !$this->reconnect()) {
652 // It doesn't make sense to continue when the database connection was lost
653 if ($this->in_retrial) {
654 $this->logger->notice('Giving up retrial because of database error', [
659 $this->logger->notice('Couldn\'t reconnect after database error', [
667 $this->logger->notice('Reconnected after database error', [
671 $this->in_retrial = true;
672 $ret = $this->p($sql, $args);
673 $this->in_retrial = false;
678 $this->error = $error;
679 $this->errorno = $errorno;
682 $this->profiler->saveTimestamp($stamp1, 'database');
684 if ($this->configCache->get('system', 'db_log')) {
685 $stamp2 = microtime(true);
686 $duration = (float)($stamp2 - $stamp1);
688 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
689 $duration = round($duration, 3);
690 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
692 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
693 basename($backtrace[1]["file"]) . "\t" .
694 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
695 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
702 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
704 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
706 * @param string $sql SQL statement
708 * @return boolean Was the query successfull? False is returned only if an error occurred
711 public function e($sql)
714 $stamp = microtime(true);
716 $params = DBA::getParam(func_get_args());
718 // In a case of a deadlock we are repeating the query 20 times
722 $stmt = $this->p($sql, $params);
724 if (is_bool($stmt)) {
726 } elseif (is_object($stmt)) {
734 } while (($this->errorno == 1213) && (--$timeout > 0));
736 if ($this->errorno != 0) {
737 // We have to preserve the error code, somewhere in the logging it get lost
738 $error = $this->error;
739 $errorno = $this->errorno;
741 if ($this->testmode) {
742 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
745 $this->logger->error('DB Error', [
748 'callstack' => System::callstack(8),
749 'params' => $this->replaceParameters($sql, $params),
752 // On a lost connection we simply quit.
753 // A reconnect like in $this->p could be dangerous with modifications
754 if ($errorno == 2006) {
755 $this->logger->notice('Giving up because of database error', [
762 $this->error = $error;
763 $this->errorno = $errorno;
766 $this->profiler->saveTimestamp($stamp, "database_write");
772 * Check if data exists
774 * @param string|array $table Table name or array [schema => table]
775 * @param array $condition array of fields for condition
777 * @return boolean Are there rows for that condition?
780 public function exists($table, $condition)
788 if (empty($condition)) {
789 return DBStructure::existsTable($table);
793 $first_key = key($condition);
794 if (!is_int($first_key)) {
795 $fields = [$first_key];
798 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
800 if (is_bool($stmt)) {
803 $retval = ($this->numRows($stmt) > 0);
812 * Fetches the first row
814 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
816 * Fetches the first row
818 * @param string $sql SQL statement
820 * @return array first row of query
823 public function fetchFirst($sql)
825 $params = DBA::getParam(func_get_args());
827 $stmt = $this->p($sql, $params);
829 if (is_bool($stmt)) {
832 $retval = $this->fetch($stmt);
841 * Returns the number of affected rows of the last statement
843 * @return int Number of rows
845 public function affectedRows()
847 return $this->affected_rows;
851 * Returns the number of columns of a statement
853 * @param object Statement object
855 * @return int Number of columns
857 public function columnCount($stmt)
859 if (!is_object($stmt)) {
862 switch ($this->driver) {
864 return $stmt->columnCount();
866 return $stmt->field_count;
872 * Returns the number of rows of a statement
874 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
876 * @return int Number of rows
878 public function numRows($stmt)
880 if (!is_object($stmt)) {
883 switch ($this->driver) {
885 return $stmt->rowCount();
887 return $stmt->num_rows;
895 * @param mixed $stmt statement object
897 * @return array current row
899 public function fetch($stmt)
902 $stamp1 = microtime(true);
906 if (!is_object($stmt)) {
910 switch ($this->driver) {
912 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
915 if (get_class($stmt) == 'mysqli_result') {
916 $columns = $stmt->fetch_assoc();
920 // This code works, but is slow
922 // Bind the result to a result array
926 for ($x = 0; $x < $stmt->field_count; $x++) {
927 $cols[] = &$cols_num[$x];
930 call_user_func_array([$stmt, 'bind_result'], $cols);
932 if (!$stmt->fetch()) {
937 // We need to get the field names for the array keys
938 // It seems that there is no better way to do this.
939 $result = $stmt->result_metadata();
940 $fields = $result->fetch_fields();
942 foreach ($cols_num AS $param => $col) {
943 $columns[$fields[$param]->name] = $col;
947 $this->profiler->saveTimestamp($stamp1, 'database');
953 * Insert a row into a table
955 * @param string|array $table Table name or array [schema => table]
956 * @param array $param parameter array
957 * @param bool $on_duplicate_update Do an update on a duplicate entry
959 * @return boolean was the insert successful?
962 public function insert($table, array $param, bool $on_duplicate_update = false)
964 if (empty($table) || empty($param)) {
965 $this->logger->info('Table and fields have to be set');
969 $table_string = DBA::buildTableString($table);
971 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
973 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
975 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
977 if ($on_duplicate_update) {
978 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
980 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
982 $values = array_values($param);
983 $param = array_merge_recursive($values, $values);
986 return $this->e($sql, $param);
990 * Inserts a row with the provided data in the provided table.
991 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
993 * @param string|array $table Table name or array [schema => table]
994 * @param array $param parameter array
996 * @return boolean was the insert successful?
999 public function replace($table, array $param)
1001 if (empty($table) || empty($param)) {
1002 $this->logger->info('Table and fields have to be set');
1006 $table_string = DBA::buildTableString($table);
1008 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1010 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1012 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1014 return $this->e($sql, $param);
1018 * Fetch the id of the last insert command
1020 * @return integer Last inserted id
1022 public function lastInsertId()
1024 switch ($this->driver) {
1026 $id = $this->connection->lastInsertId();
1029 $id = $this->connection->insert_id;
1036 * Locks a table for exclusive write access
1038 * This function can be extended in the future to accept a table array as well.
1040 * @param string|array $table Table name or array [schema => table]
1042 * @return boolean was the lock successful?
1043 * @throws \Exception
1045 public function lock($table)
1047 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1048 if ($this->driver == 'pdo') {
1049 $this->e("SET autocommit=0");
1050 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1052 $this->connection->autocommit(false);
1055 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1057 if ($this->driver == 'pdo') {
1058 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1062 if ($this->driver == 'pdo') {
1063 $this->e("SET autocommit=1");
1065 $this->connection->autocommit(true);
1068 $this->in_transaction = true;
1074 * Unlocks all locked tables
1076 * @return boolean was the unlock successful?
1077 * @throws \Exception
1079 public function unlock()
1081 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1082 $this->performCommit();
1084 if ($this->driver == 'pdo') {
1085 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1088 $success = $this->e("UNLOCK TABLES");
1090 if ($this->driver == 'pdo') {
1091 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1092 $this->e("SET autocommit=1");
1094 $this->connection->autocommit(true);
1097 $this->in_transaction = false;
1102 * Starts a transaction
1104 * @return boolean Was the command executed successfully?
1106 public function transaction()
1108 if (!$this->performCommit()) {
1112 switch ($this->driver) {
1114 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1120 if (!$this->connection->begin_transaction()) {
1126 $this->in_transaction = true;
1130 protected function performCommit()
1132 switch ($this->driver) {
1134 if (!$this->connection->inTransaction()) {
1138 return $this->connection->commit();
1141 return $this->connection->commit();
1150 * @return boolean Was the command executed successfully?
1152 public function commit()
1154 if (!$this->performCommit()) {
1157 $this->in_transaction = false;
1164 * @return boolean Was the command executed successfully?
1166 public function rollback()
1170 switch ($this->driver) {
1172 if (!$this->connection->inTransaction()) {
1176 $ret = $this->connection->rollBack();
1180 $ret = $this->connection->rollback();
1183 $this->in_transaction = false;
1188 * Build the array with the table relations
1190 * The array is build from the database definitions in DBStructure.php
1192 * This process must only be started once, since the value is cached.
1194 private function buildRelationData()
1196 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1198 foreach ($definition AS $table => $structure) {
1199 foreach ($structure['fields'] AS $field => $field_struct) {
1200 if (isset($field_struct['relation'])) {
1201 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1202 $this->relation[$rel_table][$rel_field][$table][] = $field;
1210 * Delete a row from a table
1212 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1214 * @param string $table Table name
1215 * @param array $conditions Field condition(s)
1216 * @param array $options
1217 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1218 * relations (default: true)
1219 * @param array $callstack Internal use: prevent endless loops
1221 * @return boolean was the delete successful?
1222 * @throws \Exception
1224 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1226 if (empty($table) || empty($conditions)) {
1227 $this->logger->info('Table and conditions have to be set');
1233 // Create a key for the loop prevention
1234 $key = $table . ':' . json_encode($conditions);
1236 // We quit when this key already exists in the callstack.
1237 if (isset($callstack[$key])) {
1241 $callstack[$key] = true;
1243 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1245 // Don't use "defaults" here, since it would set "false" to "true"
1246 if (isset($options['cascade'])) {
1247 $cascade = $options['cascade'];
1252 // To speed up the whole process we cache the table relations
1253 if ($cascade && count($this->relation) == 0) {
1254 $this->buildRelationData();
1257 // Is there a relation entry for the table?
1258 if ($cascade && isset($this->relation[$table])) {
1259 // We only allow a simple "one field" relation.
1260 $field = array_keys($this->relation[$table])[0];
1261 $rel_def = array_values($this->relation[$table])[0];
1263 // Create a key for preventing double queries
1264 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1266 // When the search field is the relation field, we don't need to fetch the rows
1267 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1268 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1269 foreach ($rel_def AS $rel_table => $rel_fields) {
1270 foreach ($rel_fields AS $rel_field) {
1271 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1274 // We quit when this key already exists in the callstack.
1275 } elseif (!isset($callstack[$qkey])) {
1276 $callstack[$qkey] = true;
1278 // Fetch all rows that are to be deleted
1279 $data = $this->select($table, [$field], $conditions);
1281 while ($row = $this->fetch($data)) {
1282 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1285 $this->close($data);
1287 // Since we had split the delete command we don't need the original command anymore
1288 unset($commands[$key]);
1292 // Now we finalize the process
1293 $do_transaction = !$this->in_transaction;
1295 if ($do_transaction) {
1296 $this->transaction();
1302 foreach ($commands AS $command) {
1303 $conditions = $command['conditions'];
1305 $first_key = key($conditions);
1307 $condition_string = DBA::buildCondition($conditions);
1309 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1310 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1311 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1313 if (!$this->e($sql, $conditions)) {
1314 if ($do_transaction) {
1320 $key_table = $command['table'];
1321 $key_condition = array_keys($command['conditions'])[0];
1322 $value = array_values($command['conditions'])[0];
1324 // Split the SQL queries in chunks of 100 values
1325 // We do the $i stuff here to make the code better readable
1326 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1327 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1331 $compacted[$key_table][$key_condition][$i][$value] = $value;
1332 $counter[$key_table][$key_condition] = $i;
1335 foreach ($compacted AS $table => $values) {
1336 foreach ($values AS $field => $field_value_list) {
1337 foreach ($field_value_list AS $field_values) {
1338 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1339 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1341 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1343 if (!$this->e($sql, $field_values)) {
1344 if ($do_transaction) {
1352 if ($do_transaction) {
1361 * Updates rows in the database. When $old_fields is set to an array,
1362 * the system will only do an update if the fields in that array changed.
1365 * Only the values in $old_fields are compared.
1366 * This is an intentional behaviour.
1369 * We include the timestamp field in $fields but not in $old_fields.
1370 * Then the row will only get the new timestamp when the other fields had changed.
1372 * When $old_fields is set to a boolean value the system will do this compare itself.
1373 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1376 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1377 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1379 * @param string|array $table Table name or array [schema => table]
1380 * @param array $fields contains the fields that are updated
1381 * @param array $condition condition array with the key values
1382 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1384 * @return boolean was the update successfull?
1385 * @throws \Exception
1387 public function update($table, $fields, $condition, $old_fields = [])
1389 if (empty($table) || empty($fields) || empty($condition)) {
1390 $this->logger->info('Table, fields and condition have to be set');
1394 if (is_bool($old_fields)) {
1395 $do_insert = $old_fields;
1397 $old_fields = $this->selectFirst($table, [], $condition);
1399 if (is_bool($old_fields)) {
1401 $values = array_merge($condition, $fields);
1402 return $this->replace($table, $values);
1408 foreach ($old_fields AS $fieldname => $content) {
1409 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1410 unset($fields[$fieldname]);
1414 if (count($fields) == 0) {
1418 $table_string = DBA::buildTableString($table);
1420 $condition_string = DBA::buildCondition($condition);
1422 $sql = "UPDATE " . $table_string . " SET "
1423 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1424 . $condition_string;
1426 // Combines the updated fields parameter values with the condition parameter values
1427 $params = array_merge(array_values($fields), $condition);
1429 return $this->e($sql, $params);
1433 * Retrieve a single record from a table and returns it in an associative array
1435 * @param string|array $table
1436 * @param array $fields
1437 * @param array $condition
1438 * @param array $params
1440 * @return bool|array
1441 * @throws \Exception
1442 * @see $this->select
1444 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1446 $params['limit'] = 1;
1447 $result = $this->select($table, $fields, $condition, $params);
1449 if (is_bool($result)) {
1452 $row = $this->fetch($result);
1453 $this->close($result);
1459 * Select rows from a table and fills an array with the data
1461 * @param string|array $table Table name or array [schema => table]
1462 * @param array $fields Array of selected fields, empty for all
1463 * @param array $condition Array of fields for condition
1464 * @param array $params Array of several parameters
1466 * @return array Data array
1467 * @throws \Exception
1470 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1472 return $this->toArray($this->select($table, $fields, $condition, $params));
1476 * Select rows from a table
1482 * $table = ['schema' => 'table'];
1483 * @see DBA::buildTableString()
1485 * $fields = ['id', 'uri', 'uid', 'network'];
1487 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1489 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1490 * @see DBA::buildCondition()
1492 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1493 * @see DBA::buildParameter()
1495 * $data = DBA::select($table, $fields, $condition, $params);
1497 * @param string|array $table Table name or array [schema => table]
1498 * @param array $fields Array of selected fields, empty for all
1499 * @param array $condition Array of fields for condition
1500 * @param array $params Array of several parameters
1501 * @return boolean|object
1502 * @throws \Exception
1504 public function select($table, array $fields = [], array $condition = [], array $params = [])
1506 if (empty($table)) {
1510 if (count($fields) > 0) {
1511 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1513 $select_string = '*';
1516 $table_string = DBA::buildTableString($table);
1518 $condition_string = DBA::buildCondition($condition);
1520 $param_string = DBA::buildParameter($params);
1522 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1524 $result = $this->p($sql, $condition);
1530 * Counts the rows from a table satisfying the provided condition
1532 * @param string|array $table Table name or array [schema => table]
1533 * @param array $condition Array of fields for condition
1534 * @param array $params Array of several parameters
1541 * $condition = ["uid" => 1, "network" => 'dspr'];
1543 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1545 * $count = DBA::count($table, $condition);
1546 * @throws \Exception
1548 public function count($table, array $condition = [], array $params = [])
1550 if (empty($table)) {
1554 $table_string = DBA::buildTableString($table);
1556 $condition_string = DBA::buildCondition($condition);
1558 if (empty($params['expression'])) {
1560 } elseif (!empty($params['distinct'])) {
1561 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1563 $expression = DBA::quoteIdentifier($params['expression']);
1566 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1568 $row = $this->fetchFirst($sql, $condition);
1570 return $row['count'];
1574 * Fills an array with data from a query
1576 * @param object $stmt statement object
1577 * @param bool $do_close
1579 * @return array Data array
1581 public function toArray($stmt, $do_close = true)
1583 if (is_bool($stmt)) {
1588 while ($row = $this->fetch($stmt)) {
1593 $this->close($stmt);
1600 * Returns the error number of the last query
1602 * @return string Error number (0 if no error)
1604 public function errorNo()
1606 return $this->errorno;
1610 * Returns the error message of the last query
1612 * @return string Error message ('' if no error)
1614 public function errorMessage()
1616 return $this->error;
1620 * Closes the current statement
1622 * @param object $stmt statement object
1624 * @return boolean was the close successful?
1626 public function close($stmt)
1629 $stamp1 = microtime(true);
1631 if (!is_object($stmt)) {
1635 switch ($this->driver) {
1637 $ret = $stmt->closeCursor();
1640 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1641 // We should be careful not to assume the object type of $stmt
1642 // because DBA::p() has been able to return both types.
1643 if ($stmt instanceof mysqli_stmt) {
1644 $stmt->free_result();
1645 $ret = $stmt->close();
1646 } elseif ($stmt instanceof mysqli_result) {
1655 $this->profiler->saveTimestamp($stamp1, 'database');
1661 * Return a list of database processes
1664 * 'list' => List of processes, separated in their different states
1665 * 'amount' => Number of concurrent database processes
1666 * @throws \Exception
1668 public function processlist()
1670 $ret = $this->p("SHOW PROCESSLIST");
1671 $data = $this->toArray($ret);
1675 foreach ($data as $process) {
1676 $state = trim($process["State"]);
1678 // Filter out all non blocking processes
1679 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1686 foreach ($states as $state => $usage) {
1687 if ($statelist != "") {
1690 $statelist .= $state . ": " . $usage;
1692 return (["list" => $statelist, "amount" => $processes]);
1696 * Fetch a database variable
1698 * @param string $name
1699 * @return string content
1701 public function getVariable(string $name)
1703 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1704 return $result['Value'] ?? null;
1708 * Checks if $array is a filled array with at least one entry.
1710 * @param mixed $array A filled array with at least one entry
1712 * @return boolean Whether $array is a filled array or an object with rows
1714 public function isResult($array)
1716 // It could be a return value from an update statement
1717 if (is_bool($array)) {
1721 if (is_object($array)) {
1722 return $this->numRows($array) > 0;
1725 return (is_array($array) && (count($array) > 0));
1729 * Callback function for "esc_array"
1731 * @param mixed $value Array value
1732 * @param string $key Array key
1733 * @param boolean $add_quotation add quotation marks for string values
1737 private function escapeArrayCallback(&$value, $key, $add_quotation)
1739 if (!$add_quotation) {
1740 if (is_bool($value)) {
1741 $value = ($value ? '1' : '0');
1743 $value = $this->escape($value);
1748 if (is_bool($value)) {
1749 $value = ($value ? 'true' : 'false');
1750 } elseif (is_float($value) || is_integer($value)) {
1751 $value = (string)$value;
1753 $value = "'" . $this->escape($value) . "'";
1758 * Escapes a whole array
1760 * @param mixed $arr Array with values to be escaped
1761 * @param boolean $add_quotation add quotation marks for string values
1765 public function escapeArray(&$arr, $add_quotation = false)
1767 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);