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;
25 use Friendica\Core\Config\Cache;
26 use Friendica\Core\System;
28 use Friendica\Network\HTTPException\InternalServerErrorException;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Profiler;
37 use Psr\Log\LoggerInterface;
40 * This class is for the low level database stuff that does driver specific things.
44 protected $connected = false;
49 protected $configCache;
55 * @var LoggerInterface
58 protected $server_info = '';
59 /** @var PDO|mysqli */
60 protected $connection;
62 private $emulate_prepares = false;
63 private $error = false;
65 private $affected_rows = 0;
66 protected $in_transaction = false;
67 protected $in_retrial = false;
68 protected $testmode = false;
69 private $relation = [];
71 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
73 // We are storing these values for being able to perform a reconnect
74 $this->configCache = $configCache;
75 $this->profiler = $profiler;
76 $this->logger = $logger;
78 $this->readServerVariables($server);
81 if ($this->isConnected()) {
82 // Loads DB_UPDATE_VERSION constant
83 DBStructure::definition($configCache->get('system', 'basepath'), false);
87 private function readServerVariables(array $server)
89 // Use environment variables for mysql if they are set beforehand
90 if (!empty($server['MYSQL_HOST'])
91 && (!empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER'])))
92 && $server['MYSQL_PASSWORD'] !== false
93 && !empty($server['MYSQL_DATABASE']))
95 $db_host = $server['MYSQL_HOST'];
96 if (!empty($server['MYSQL_PORT'])) {
97 $db_host .= ':' . $server['MYSQL_PORT'];
99 $this->configCache->set('database', 'hostname', $db_host);
101 if (!empty($server['MYSQL_USERNAME'])) {
102 $this->configCache->set('database', 'username', $server['MYSQL_USERNAME']);
104 $this->configCache->set('database', 'username', $server['MYSQL_USER']);
106 $this->configCache->set('database', 'password', (string) $server['MYSQL_PASSWORD']);
107 $this->configCache->set('database', 'database', $server['MYSQL_DATABASE']);
111 public function connect()
113 if (!is_null($this->connection) && $this->connected()) {
114 return $this->connected;
117 // Reset connected state
118 $this->connected = false;
121 $serveraddr = trim($this->configCache->get('database', 'hostname'));
122 $serverdata = explode(':', $serveraddr);
123 $server = $serverdata[0];
124 if (count($serverdata) > 1) {
125 $port = trim($serverdata[1]);
127 $server = trim($server);
128 $user = trim($this->configCache->get('database', 'username'));
129 $pass = trim($this->configCache->get('database', 'password'));
130 $db = trim($this->configCache->get('database', 'database'));
131 $charset = trim($this->configCache->get('database', 'charset'));
133 if (!(strlen($server) && strlen($user))) {
137 $this->emulate_prepares = (bool)$this->configCache->get('database', 'emulate_prepares');
138 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
140 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
141 $this->driver = 'pdo';
142 $connect = "mysql:host=" . $server . ";dbname=" . $db;
145 $connect .= ";port=" . $port;
149 $connect .= ";charset=" . $charset;
153 $this->connection = @new PDO($connect, $user, $pass);
154 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
155 $this->connected = true;
156 } catch (PDOException $e) {
157 $this->connected = false;
161 if (!$this->connected && class_exists('\mysqli')) {
162 $this->driver = 'mysqli';
165 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
167 $this->connection = @new mysqli($server, $user, $pass, $db);
170 if (!mysqli_connect_errno()) {
171 $this->connected = true;
174 $this->connection->set_charset($charset);
179 // No suitable SQL driver was found.
180 if (!$this->connected) {
181 $this->driver = null;
182 $this->connection = null;
185 return $this->connected;
188 public function setTestmode(bool $test)
190 $this->testmode = $test;
193 * Sets the logger for DBA
195 * @note this is necessary because if we want to load the logger configuration
196 * from the DB, but there's an error, we would print out an exception.
197 * So the logger gets updated after the logger configuration can be retrieved
200 * @param LoggerInterface $logger
202 public function setLogger(LoggerInterface $logger)
204 $this->logger = $logger;
208 * Sets the profiler for DBA
210 * @param Profiler $profiler
212 public function setProfiler(Profiler $profiler)
214 $this->profiler = $profiler;
217 * Disconnects the current database connection
219 public function disconnect()
221 if (!is_null($this->connection)) {
222 switch ($this->driver) {
224 $this->connection = null;
227 $this->connection->close();
228 $this->connection = null;
233 $this->driver = null;
234 $this->connected = false;
238 * Perform a reconnect of an existing database connection
240 public function reconnect()
243 return $this->connect();
247 * Return the database object.
251 public function getConnection()
253 return $this->connection;
257 * Returns the MySQL server version string
259 * This function discriminate between the deprecated mysql API and the current
260 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
264 public function serverInfo()
266 if ($this->server_info == '') {
267 switch ($this->driver) {
269 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
272 $this->server_info = $this->connection->server_info;
276 return $this->server_info;
280 * Returns the selected database name
285 public function databaseName()
287 $ret = $this->p("SELECT DATABASE() AS `db`");
288 $data = $this->toArray($ret);
289 return $data[0]['db'];
293 * Analyze a database query and log this if some conditions are met.
295 * @param string $query The database query that will be analyzed
299 private function logIndex($query)
302 if (!$this->configCache->get('system', 'db_log_index')) {
306 // Don't explain an explain statement
307 if (strtolower(substr($query, 0, 7)) == "explain") {
311 // Only do the explain on "select", "update" and "delete"
312 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
316 $r = $this->p("EXPLAIN " . $query);
317 if (!$this->isResult($r)) {
321 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
322 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
324 while ($row = $this->fetch($r)) {
325 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
326 $log = (in_array($row['key'], $watchlist) &&
327 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
332 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
336 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
341 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
342 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
343 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
344 basename($backtrace[1]["file"]) . "\t" .
345 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
346 substr($query, 0, 2000) . "\n", FILE_APPEND);
352 * Removes every not whitelisted character from the identifier string
354 * @param string $identifier
356 * @return string sanitized identifier
359 private function sanitizeIdentifier($identifier)
361 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
364 public function escape($str)
366 if ($this->connected) {
367 switch ($this->driver) {
369 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
372 return @$this->connection->real_escape_string($str);
375 return str_replace("'", "\\'", $str);
379 public function isConnected()
381 return $this->connected;
384 public function connected()
388 if (is_null($this->connection)) {
392 switch ($this->driver) {
394 $r = $this->p("SELECT 1");
395 if ($this->isResult($r)) {
396 $row = $this->toArray($r);
397 $connected = ($row[0]['1'] == '1');
401 $connected = $this->connection->ping();
409 * Replaces ANY_VALUE() function by MIN() function,
410 * if the database server does not support ANY_VALUE().
412 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
413 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
414 * A standard fall-back is to use MIN().
416 * @param string $sql An SQL string without the values
418 * @return string The input SQL string modified if necessary.
420 public function anyValueFallback($sql)
422 $server_info = $this->serverInfo();
423 if (version_compare($server_info, '5.7.5', '<') ||
424 (stripos($server_info, 'MariaDB') !== false)) {
425 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
431 * Replaces the ? placeholders with the parameters in the $args array
433 * @param string $sql SQL query
434 * @param array $args The parameters that are to replace the ? placeholders
436 * @return string The replaced SQL query
438 private function replaceParameters($sql, $args)
441 foreach ($args AS $param => $value) {
442 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
443 $replace = intval($args[$param]);
444 } elseif (is_null($args[$param])) {
447 $replace = "'" . $this->escape($args[$param]) . "'";
450 $pos = strpos($sql, '?', $offset);
451 if ($pos !== false) {
452 $sql = substr_replace($sql, $replace, $pos, 1);
454 $offset = $pos + strlen($replace);
460 * Executes a prepared statement that returns data
462 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
464 * Please only use it with complicated queries.
465 * For all regular queries please use DBA::select or DBA::exists
467 * @param string $sql SQL statement
469 * @return bool|object statement object or result object
472 public function p($sql)
475 $stamp1 = microtime(true);
477 $params = DBA::getParam(func_get_args());
479 // Renumber the array keys to be sure that they fit
482 foreach ($params AS $param) {
483 // Avoid problems with some MySQL servers and boolean values. See issue #3645
484 if (is_bool($param)) {
485 $param = (int)$param;
487 $args[++$i] = $param;
490 if (!$this->connected) {
494 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
495 // Question: Should we continue or stop the query here?
496 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
499 $sql = DBA::cleanQuery($sql);
500 $sql = $this->anyValueFallback($sql);
504 if ($this->configCache->get('system', 'db_callstack') !== null) {
505 $sql = "/*" . System::callstack() . " */ " . $sql;
511 $this->affected_rows = 0;
513 // We have to make some things different if this function is called from "e"
514 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
516 if (isset($trace[1])) {
517 $called_from = $trace[1];
519 // We use just something that is defined to avoid warnings
520 $called_from = $trace[0];
522 // We are having an own error logging in the function "e"
523 $called_from_e = ($called_from['function'] == 'e');
525 if (!isset($this->connection)) {
526 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
529 switch ($this->driver) {
531 // If there are no arguments we use "query"
532 if ($this->emulate_prepares || count($args) == 0) {
533 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
534 $errorInfo = $this->connection->errorInfo();
535 $this->error = $errorInfo[2];
536 $this->errorno = $errorInfo[1];
541 $this->affected_rows = $retval->rowCount();
545 /** @var $stmt mysqli_stmt|PDOStatement */
546 if (!$stmt = $this->connection->prepare($sql)) {
547 $errorInfo = $this->connection->errorInfo();
548 $this->error = $errorInfo[2];
549 $this->errorno = $errorInfo[1];
555 foreach ($args AS $param => $value) {
556 if (is_int($args[$param])) {
557 $data_type = PDO::PARAM_INT;
559 $data_type = PDO::PARAM_STR;
561 $stmt->bindParam($param, $args[$param], $data_type);
564 if (!$stmt->execute()) {
565 $errorInfo = $stmt->errorInfo();
566 $this->error = $errorInfo[2];
567 $this->errorno = $errorInfo[1];
572 $this->affected_rows = $retval->rowCount();
576 // There are SQL statements that cannot be executed with a prepared statement
577 $parts = explode(' ', $orig_sql);
578 $command = strtolower($parts[0]);
579 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
581 // The fallback routine is called as well when there are no arguments
582 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
583 $retval = $this->connection->query($this->replaceParameters($sql, $args));
584 if ($this->connection->errno) {
585 $this->error = $this->connection->error;
586 $this->errorno = $this->connection->errno;
590 if (isset($retval->num_rows)) {
591 $this->affected_rows = $retval->num_rows;
593 $this->affected_rows = $this->connection->affected_rows;
599 $stmt = $this->connection->stmt_init();
601 if (!$stmt->prepare($sql)) {
602 $this->error = $stmt->error;
603 $this->errorno = $stmt->errno;
611 foreach ($args AS $param => $value) {
612 if (is_int($args[$param])) {
614 } elseif (is_float($args[$param])) {
616 } elseif (is_string($args[$param])) {
621 $values[] = &$args[$param];
624 if (count($values) > 0) {
625 array_unshift($values, $param_types);
626 call_user_func_array([$stmt, 'bind_param'], $values);
629 if (!$stmt->execute()) {
630 $this->error = $this->connection->error;
631 $this->errorno = $this->connection->errno;
635 $stmt->store_result();
637 $this->affected_rows = $retval->affected_rows;
642 // See issue https://github.com/friendica/friendica/issues/8572
643 // Ensure that we always get an error message on an error.
644 if ($is_error && empty($this->errorno)) {
648 if ($is_error && empty($this->error)) {
649 $this->error = 'Unknown database error';
652 // We are having an own error logging in the function "e"
653 if (($this->errorno != 0) && !$called_from_e) {
654 // We have to preserve the error code, somewhere in the logging it get lost
655 $error = $this->error;
656 $errorno = $this->errorno;
658 if ($this->testmode) {
659 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $args)));
662 $this->logger->error('DB Error', [
665 'callstack' => System::callstack(8),
666 'params' => $this->replaceParameters($sql, $args),
669 // On a lost connection we try to reconnect - but only once.
670 if ($errorno == 2006) {
671 if ($this->in_retrial || !$this->reconnect()) {
672 // It doesn't make sense to continue when the database connection was lost
673 if ($this->in_retrial) {
674 $this->logger->notice('Giving up retrial because of database error', [
679 $this->logger->notice('Couldn\'t reconnect after database error', [
687 $this->logger->notice('Reconnected after database error', [
691 $this->in_retrial = true;
692 $ret = $this->p($sql, $args);
693 $this->in_retrial = false;
698 $this->error = $error;
699 $this->errorno = $errorno;
702 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
704 if ($this->configCache->get('system', 'db_log')) {
705 $stamp2 = microtime(true);
706 $duration = (float)($stamp2 - $stamp1);
708 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
709 $duration = round($duration, 3);
710 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
712 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
713 basename($backtrace[1]["file"]) . "\t" .
714 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
715 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
722 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
724 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
726 * @param string $sql SQL statement
728 * @return boolean Was the query successfull? False is returned only if an error occurred
731 public function e($sql)
734 $stamp = microtime(true);
736 $params = DBA::getParam(func_get_args());
738 // In a case of a deadlock we are repeating the query 20 times
742 $stmt = $this->p($sql, $params);
744 if (is_bool($stmt)) {
746 } elseif (is_object($stmt)) {
754 } while (($this->errorno == 1213) && (--$timeout > 0));
756 if ($this->errorno != 0) {
757 // We have to preserve the error code, somewhere in the logging it get lost
758 $error = $this->error;
759 $errorno = $this->errorno;
761 if ($this->testmode) {
762 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $params)));
765 $this->logger->error('DB Error', [
768 'callstack' => System::callstack(8),
769 'params' => $this->replaceParameters($sql, $params),
772 // On a lost connection we simply quit.
773 // A reconnect like in $this->p could be dangerous with modifications
774 if ($errorno == 2006) {
775 $this->logger->notice('Giving up because of database error', [
782 $this->error = $error;
783 $this->errorno = $errorno;
786 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
792 * Check if data exists
794 * @param string|array $table Table name or array [schema => table]
795 * @param array $condition array of fields for condition
797 * @return boolean Are there rows for that condition?
800 public function exists($table, $condition)
808 if (empty($condition)) {
809 return DBStructure::existsTable($table);
813 $first_key = key($condition);
814 if (!is_int($first_key)) {
815 $fields = [$first_key];
818 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
820 if (is_bool($stmt)) {
823 $retval = ($this->numRows($stmt) > 0);
832 * Fetches the first row
834 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
836 * Fetches the first row
838 * @param string $sql SQL statement
840 * @return array first row of query
843 public function fetchFirst($sql)
845 $params = DBA::getParam(func_get_args());
847 $stmt = $this->p($sql, $params);
849 if (is_bool($stmt)) {
852 $retval = $this->fetch($stmt);
861 * Returns the number of affected rows of the last statement
863 * @return int Number of rows
865 public function affectedRows()
867 return $this->affected_rows;
871 * Returns the number of columns of a statement
873 * @param object Statement object
875 * @return int Number of columns
877 public function columnCount($stmt)
879 if (!is_object($stmt)) {
882 switch ($this->driver) {
884 return $stmt->columnCount();
886 return $stmt->field_count;
892 * Returns the number of rows of a statement
894 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
896 * @return int Number of rows
898 public function numRows($stmt)
900 if (!is_object($stmt)) {
903 switch ($this->driver) {
905 return $stmt->rowCount();
907 return $stmt->num_rows;
915 * @param mixed $stmt statement object
917 * @return array current row
919 public function fetch($stmt)
922 $stamp1 = microtime(true);
926 if (!is_object($stmt)) {
930 switch ($this->driver) {
932 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
935 if (get_class($stmt) == 'mysqli_result') {
936 $columns = $stmt->fetch_assoc();
940 // This code works, but is slow
942 // Bind the result to a result array
946 for ($x = 0; $x < $stmt->field_count; $x++) {
947 $cols[] = &$cols_num[$x];
950 call_user_func_array([$stmt, 'bind_result'], $cols);
952 if (!$stmt->fetch()) {
957 // We need to get the field names for the array keys
958 // It seems that there is no better way to do this.
959 $result = $stmt->result_metadata();
960 $fields = $result->fetch_fields();
962 foreach ($cols_num AS $param => $col) {
963 $columns[$fields[$param]->name] = $col;
967 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
973 * Insert a row into a table
975 * @param string|array $table Table name or array [schema => table]
976 * @param array $param parameter array
977 * @param bool $on_duplicate_update Do an update on a duplicate entry
979 * @return boolean was the insert successful?
982 public function insert($table, $param, $on_duplicate_update = false)
984 if (empty($table) || empty($param)) {
985 $this->logger->info('Table and fields have to be set');
989 $table_string = DBA::buildTableString($table);
991 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
993 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
995 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
997 if ($on_duplicate_update) {
998 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1000 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1002 $values = array_values($param);
1003 $param = array_merge_recursive($values, $values);
1006 return $this->e($sql, $param);
1010 * Fetch the id of the last insert command
1012 * @return integer Last inserted id
1014 public function lastInsertId()
1016 switch ($this->driver) {
1018 $id = $this->connection->lastInsertId();
1021 $id = $this->connection->insert_id;
1028 * Locks a table for exclusive write access
1030 * This function can be extended in the future to accept a table array as well.
1032 * @param string|array $table Table name or array [schema => table]
1034 * @return boolean was the lock successful?
1035 * @throws \Exception
1037 public function lock($table)
1039 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1040 if ($this->driver == 'pdo') {
1041 $this->e("SET autocommit=0");
1042 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1044 $this->connection->autocommit(false);
1047 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1049 if ($this->driver == 'pdo') {
1050 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1054 if ($this->driver == 'pdo') {
1055 $this->e("SET autocommit=1");
1057 $this->connection->autocommit(true);
1060 $this->in_transaction = true;
1066 * Unlocks all locked tables
1068 * @return boolean was the unlock successful?
1069 * @throws \Exception
1071 public function unlock()
1073 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1074 $this->performCommit();
1076 if ($this->driver == 'pdo') {
1077 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1080 $success = $this->e("UNLOCK TABLES");
1082 if ($this->driver == 'pdo') {
1083 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1084 $this->e("SET autocommit=1");
1086 $this->connection->autocommit(true);
1089 $this->in_transaction = false;
1094 * Starts a transaction
1096 * @return boolean Was the command executed successfully?
1098 public function transaction()
1100 if (!$this->performCommit()) {
1104 switch ($this->driver) {
1106 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1112 if (!$this->connection->begin_transaction()) {
1118 $this->in_transaction = true;
1122 protected function performCommit()
1124 switch ($this->driver) {
1126 if (!$this->connection->inTransaction()) {
1130 return $this->connection->commit();
1133 return $this->connection->commit();
1142 * @return boolean Was the command executed successfully?
1144 public function commit()
1146 if (!$this->performCommit()) {
1149 $this->in_transaction = false;
1156 * @return boolean Was the command executed successfully?
1158 public function rollback()
1162 switch ($this->driver) {
1164 if (!$this->connection->inTransaction()) {
1168 $ret = $this->connection->rollBack();
1172 $ret = $this->connection->rollback();
1175 $this->in_transaction = false;
1180 * Build the array with the table relations
1182 * The array is build from the database definitions in DBStructure.php
1184 * This process must only be started once, since the value is cached.
1186 private function buildRelationData()
1188 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1190 foreach ($definition AS $table => $structure) {
1191 foreach ($structure['fields'] AS $field => $field_struct) {
1192 if (isset($field_struct['relation'])) {
1193 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1194 $this->relation[$rel_table][$rel_field][$table][] = $field;
1202 * Delete a row from a table
1204 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1206 * @param string $table Table name
1207 * @param array $conditions Field condition(s)
1208 * @param array $options
1209 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1210 * relations (default: true)
1211 * @param array $callstack Internal use: prevent endless loops
1213 * @return boolean was the delete successful?
1214 * @throws \Exception
1216 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1218 if (empty($table) || empty($conditions)) {
1219 $this->logger->info('Table and conditions have to be set');
1225 // Create a key for the loop prevention
1226 $key = $table . ':' . json_encode($conditions);
1228 // We quit when this key already exists in the callstack.
1229 if (isset($callstack[$key])) {
1233 $callstack[$key] = true;
1235 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1237 // Don't use "defaults" here, since it would set "false" to "true"
1238 if (isset($options['cascade'])) {
1239 $cascade = $options['cascade'];
1244 // To speed up the whole process we cache the table relations
1245 if ($cascade && count($this->relation) == 0) {
1246 $this->buildRelationData();
1249 // Is there a relation entry for the table?
1250 if ($cascade && isset($this->relation[$table])) {
1251 // We only allow a simple "one field" relation.
1252 $field = array_keys($this->relation[$table])[0];
1253 $rel_def = array_values($this->relation[$table])[0];
1255 // Create a key for preventing double queries
1256 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1258 // When the search field is the relation field, we don't need to fetch the rows
1259 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1260 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1261 foreach ($rel_def AS $rel_table => $rel_fields) {
1262 foreach ($rel_fields AS $rel_field) {
1263 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1266 // We quit when this key already exists in the callstack.
1267 } elseif (!isset($callstack[$qkey])) {
1268 $callstack[$qkey] = true;
1270 // Fetch all rows that are to be deleted
1271 $data = $this->select($table, [$field], $conditions);
1273 while ($row = $this->fetch($data)) {
1274 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1277 $this->close($data);
1279 // Since we had split the delete command we don't need the original command anymore
1280 unset($commands[$key]);
1284 // Now we finalize the process
1285 $do_transaction = !$this->in_transaction;
1287 if ($do_transaction) {
1288 $this->transaction();
1294 foreach ($commands AS $command) {
1295 $conditions = $command['conditions'];
1297 $first_key = key($conditions);
1299 $condition_string = DBA::buildCondition($conditions);
1301 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1302 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1303 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1305 if (!$this->e($sql, $conditions)) {
1306 if ($do_transaction) {
1312 $key_table = $command['table'];
1313 $key_condition = array_keys($command['conditions'])[0];
1314 $value = array_values($command['conditions'])[0];
1316 // Split the SQL queries in chunks of 100 values
1317 // We do the $i stuff here to make the code better readable
1318 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1319 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1323 $compacted[$key_table][$key_condition][$i][$value] = $value;
1324 $counter[$key_table][$key_condition] = $i;
1327 foreach ($compacted AS $table => $values) {
1328 foreach ($values AS $field => $field_value_list) {
1329 foreach ($field_value_list AS $field_values) {
1330 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1331 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1333 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1335 if (!$this->e($sql, $field_values)) {
1336 if ($do_transaction) {
1344 if ($do_transaction) {
1353 * Updates rows in the database. When $old_fields is set to an array,
1354 * the system will only do an update if the fields in that array changed.
1357 * Only the values in $old_fields are compared.
1358 * This is an intentional behaviour.
1361 * We include the timestamp field in $fields but not in $old_fields.
1362 * Then the row will only get the new timestamp when the other fields had changed.
1364 * When $old_fields is set to a boolean value the system will do this compare itself.
1365 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1368 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1369 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1371 * @param string|array $table Table name or array [schema => table]
1372 * @param array $fields contains the fields that are updated
1373 * @param array $condition condition array with the key values
1374 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1376 * @return boolean was the update successfull?
1377 * @throws \Exception
1379 public function update($table, $fields, $condition, $old_fields = [])
1381 if (empty($table) || empty($fields) || empty($condition)) {
1382 $this->logger->info('Table, fields and condition have to be set');
1386 if (is_bool($old_fields)) {
1387 $do_insert = $old_fields;
1389 $old_fields = $this->selectFirst($table, [], $condition);
1391 if (is_bool($old_fields)) {
1393 $values = array_merge($condition, $fields);
1394 return $this->insert($table, $values, $do_insert);
1400 foreach ($old_fields AS $fieldname => $content) {
1401 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1402 unset($fields[$fieldname]);
1406 if (count($fields) == 0) {
1410 $table_string = DBA::buildTableString($table);
1412 $condition_string = DBA::buildCondition($condition);
1414 $sql = "UPDATE " . $table_string . " SET "
1415 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1416 . $condition_string;
1418 // Combines the updated fields parameter values with the condition parameter values
1419 $params = array_merge(array_values($fields), $condition);
1421 return $this->e($sql, $params);
1425 * Retrieve a single record from a table and returns it in an associative array
1427 * @param string|array $table
1428 * @param array $fields
1429 * @param array $condition
1430 * @param array $params
1432 * @return bool|array
1433 * @throws \Exception
1434 * @see $this->select
1436 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1438 $params['limit'] = 1;
1439 $result = $this->select($table, $fields, $condition, $params);
1441 if (is_bool($result)) {
1444 $row = $this->fetch($result);
1445 $this->close($result);
1451 * Select rows from a table and fills an array with the data
1453 * @param string|array $table Table name or array [schema => table]
1454 * @param array $fields Array of selected fields, empty for all
1455 * @param array $condition Array of fields for condition
1456 * @param array $params Array of several parameters
1458 * @return array Data array
1459 * @throws \Exception
1462 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1464 return $this->toArray($this->select($table, $fields, $condition, $params));
1468 * Select rows from a table
1470 * @param string|array $table Table name or array [schema => table]
1471 * @param array $fields Array of selected fields, empty for all
1472 * @param array $condition Array of fields for condition
1473 * @param array $params Array of several parameters
1475 * @return boolean|object
1479 * $fields = array("id", "uri", "uid", "network");
1481 * $condition = array("uid" => 1, "network" => 'dspr');
1483 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1485 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1487 * $data = DBA::select($table, $fields, $condition, $params);
1488 * @throws \Exception
1490 public function select($table, array $fields = [], array $condition = [], array $params = [])
1492 if (empty($table)) {
1496 if (count($fields) > 0) {
1497 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1499 $select_string = '*';
1502 $table_string = DBA::buildTableString($table);
1504 $condition_string = DBA::buildCondition($condition);
1506 $param_string = DBA::buildParameter($params);
1508 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1510 $result = $this->p($sql, $condition);
1516 * Counts the rows from a table satisfying the provided condition
1518 * @param string|array $table Table name or array [schema => table]
1519 * @param array $condition Array of fields for condition
1520 * @param array $params Array of several parameters
1527 * $condition = ["uid" => 1, "network" => 'dspr'];
1529 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1531 * $count = DBA::count($table, $condition);
1532 * @throws \Exception
1534 public function count($table, array $condition = [], array $params = [])
1536 if (empty($table)) {
1540 $table_string = DBA::buildTableString($table);
1542 $condition_string = DBA::buildCondition($condition);
1544 if (empty($params['expression'])) {
1546 } elseif (!empty($params['distinct'])) {
1547 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1549 $expression = DBA::quoteIdentifier($params['expression']);
1552 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1554 $row = $this->fetchFirst($sql, $condition);
1556 return $row['count'];
1560 * Fills an array with data from a query
1562 * @param object $stmt statement object
1563 * @param bool $do_close
1565 * @return array Data array
1567 public function toArray($stmt, $do_close = true)
1569 if (is_bool($stmt)) {
1574 while ($row = $this->fetch($stmt)) {
1579 $this->close($stmt);
1586 * Returns the error number of the last query
1588 * @return string Error number (0 if no error)
1590 public function errorNo()
1592 return $this->errorno;
1596 * Returns the error message of the last query
1598 * @return string Error message ('' if no error)
1600 public function errorMessage()
1602 return $this->error;
1606 * Closes the current statement
1608 * @param object $stmt statement object
1610 * @return boolean was the close successful?
1612 public function close($stmt)
1615 $stamp1 = microtime(true);
1617 if (!is_object($stmt)) {
1621 switch ($this->driver) {
1623 $ret = $stmt->closeCursor();
1626 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1627 // We should be careful not to assume the object type of $stmt
1628 // because DBA::p() has been able to return both types.
1629 if ($stmt instanceof mysqli_stmt) {
1630 $stmt->free_result();
1631 $ret = $stmt->close();
1632 } elseif ($stmt instanceof mysqli_result) {
1641 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1647 * Return a list of database processes
1650 * 'list' => List of processes, separated in their different states
1651 * 'amount' => Number of concurrent database processes
1652 * @throws \Exception
1654 public function processlist()
1656 $ret = $this->p("SHOW PROCESSLIST");
1657 $data = $this->toArray($ret);
1661 foreach ($data as $process) {
1662 $state = trim($process["State"]);
1664 // Filter out all non blocking processes
1665 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1672 foreach ($states as $state => $usage) {
1673 if ($statelist != "") {
1676 $statelist .= $state . ": " . $usage;
1678 return (["list" => $statelist, "amount" => $processes]);
1682 * Fetch a database variable
1684 * @param string $name
1685 * @return string content
1687 public function getVariable(string $name)
1689 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1690 return $result['Value'] ?? null;
1694 * Checks if $array is a filled array with at least one entry.
1696 * @param mixed $array A filled array with at least one entry
1698 * @return boolean Whether $array is a filled array or an object with rows
1700 public function isResult($array)
1702 // It could be a return value from an update statement
1703 if (is_bool($array)) {
1707 if (is_object($array)) {
1708 return $this->numRows($array) > 0;
1711 return (is_array($array) && (count($array) > 0));
1715 * Callback function for "esc_array"
1717 * @param mixed $value Array value
1718 * @param string $key Array key
1719 * @param boolean $add_quotation add quotation marks for string values
1723 private function escapeArrayCallback(&$value, $key, $add_quotation)
1725 if (!$add_quotation) {
1726 if (is_bool($value)) {
1727 $value = ($value ? '1' : '0');
1729 $value = $this->escape($value);
1734 if (is_bool($value)) {
1735 $value = ($value ? 'true' : 'false');
1736 } elseif (is_float($value) || is_integer($value)) {
1737 $value = (string)$value;
1739 $value = "'" . $this->escape($value) . "'";
1744 * Escapes a whole array
1746 * @param mixed $arr Array with values to be escaped
1747 * @param boolean $add_quotation add quotation marks for string values
1751 public function escapeArray(&$arr, $add_quotation = false)
1753 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);