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 private $emulate_prepares = false;
61 private $error = false;
63 private $affected_rows = 0;
64 protected $in_transaction = false;
65 protected $in_retrial = false;
66 private $relation = [];
68 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
70 // We are storing these values for being able to perform a reconnect
71 $this->configCache = $configCache;
72 $this->profiler = $profiler;
73 $this->logger = $logger;
75 $this->readServerVariables($server);
78 if ($this->isConnected()) {
79 // Loads DB_UPDATE_VERSION constant
80 DBStructure::definition($configCache->get('system', 'basepath'), false);
84 private function readServerVariables(array $server)
86 // Use environment variables for mysql if they are set beforehand
87 if (!empty($server['MYSQL_HOST'])
88 && (!empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER'])))
89 && $server['MYSQL_PASSWORD'] !== false
90 && !empty($server['MYSQL_DATABASE']))
92 $db_host = $server['MYSQL_HOST'];
93 if (!empty($server['MYSQL_PORT'])) {
94 $db_host .= ':' . $server['MYSQL_PORT'];
96 $this->configCache->set('database', 'hostname', $db_host);
98 if (!empty($server['MYSQL_USERNAME'])) {
99 $this->configCache->set('database', 'username', $server['MYSQL_USERNAME']);
101 $this->configCache->set('database', 'username', $server['MYSQL_USER']);
103 $this->configCache->set('database', 'password', (string) $server['MYSQL_PASSWORD']);
104 $this->configCache->set('database', 'database', $server['MYSQL_DATABASE']);
108 public function connect()
110 if (!is_null($this->connection) && $this->connected()) {
111 return $this->connected;
114 // Reset connected state
115 $this->connected = false;
118 $serveraddr = trim($this->configCache->get('database', 'hostname'));
119 $serverdata = explode(':', $serveraddr);
120 $server = $serverdata[0];
121 if (count($serverdata) > 1) {
122 $port = trim($serverdata[1]);
124 $server = trim($server);
125 $user = trim($this->configCache->get('database', 'username'));
126 $pass = trim($this->configCache->get('database', 'password'));
127 $db = trim($this->configCache->get('database', 'database'));
128 $charset = trim($this->configCache->get('database', 'charset'));
130 if (!(strlen($server) && strlen($user))) {
134 $this->emulate_prepares = (bool)$this->configCache->get('database', 'emulate_prepares');
136 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
137 $this->driver = 'pdo';
138 $connect = "mysql:host=" . $server . ";dbname=" . $db;
141 $connect .= ";port=" . $port;
145 $connect .= ";charset=" . $charset;
149 $this->connection = @new PDO($connect, $user, $pass);
150 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
151 $this->connected = true;
152 } catch (PDOException $e) {
153 $this->connected = false;
157 if (!$this->connected && class_exists('\mysqli')) {
158 $this->driver = 'mysqli';
161 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
163 $this->connection = @new mysqli($server, $user, $pass, $db);
166 if (!mysqli_connect_errno()) {
167 $this->connected = true;
170 $this->connection->set_charset($charset);
175 // No suitable SQL driver was found.
176 if (!$this->connected) {
177 $this->driver = null;
178 $this->connection = null;
181 return $this->connected;
185 * Sets the logger for DBA
187 * @note this is necessary because if we want to load the logger configuration
188 * from the DB, but there's an error, we would print out an exception.
189 * So the logger gets updated after the logger configuration can be retrieved
192 * @param LoggerInterface $logger
194 public function setLogger(LoggerInterface $logger)
196 $this->logger = $logger;
200 * Sets the profiler for DBA
202 * @param Profiler $profiler
204 public function setProfiler(Profiler $profiler)
206 $this->profiler = $profiler;
209 * Disconnects the current database connection
211 public function disconnect()
213 if (!is_null($this->connection)) {
214 switch ($this->driver) {
216 $this->connection = null;
219 $this->connection->close();
220 $this->connection = null;
225 $this->driver = null;
226 $this->connected = false;
230 * Perform a reconnect of an existing database connection
232 public function reconnect()
235 return $this->connect();
239 * Return the database object.
243 public function getConnection()
245 return $this->connection;
249 * Returns the MySQL server version string
251 * This function discriminate between the deprecated mysql API and the current
252 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
256 public function serverInfo()
258 if ($this->server_info == '') {
259 switch ($this->driver) {
261 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
264 $this->server_info = $this->connection->server_info;
268 return $this->server_info;
272 * Returns the selected database name
277 public function databaseName()
279 $ret = $this->p("SELECT DATABASE() AS `db`");
280 $data = $this->toArray($ret);
281 return $data[0]['db'];
285 * Analyze a database query and log this if some conditions are met.
287 * @param string $query The database query that will be analyzed
291 private function logIndex($query)
294 if (!$this->configCache->get('system', 'db_log_index')) {
298 // Don't explain an explain statement
299 if (strtolower(substr($query, 0, 7)) == "explain") {
303 // Only do the explain on "select", "update" and "delete"
304 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
308 $r = $this->p("EXPLAIN " . $query);
309 if (!$this->isResult($r)) {
313 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
314 $blacklist = explode(',', $this->configCache->get('system', 'db_log_index_blacklist'));
316 while ($row = $this->fetch($r)) {
317 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
318 $log = (in_array($row['key'], $watchlist) &&
319 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
324 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
328 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
333 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
334 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
335 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
336 basename($backtrace[1]["file"]) . "\t" .
337 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
338 substr($query, 0, 2000) . "\n", FILE_APPEND);
344 * Removes every not whitelisted character from the identifier string
346 * @param string $identifier
348 * @return string sanitized identifier
351 private function sanitizeIdentifier($identifier)
353 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
356 public function escape($str)
358 if ($this->connected) {
359 switch ($this->driver) {
361 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
364 return @$this->connection->real_escape_string($str);
367 return str_replace("'", "\\'", $str);
371 public function isConnected()
373 return $this->connected;
376 public function connected()
380 if (is_null($this->connection)) {
384 switch ($this->driver) {
386 $r = $this->p("SELECT 1");
387 if ($this->isResult($r)) {
388 $row = $this->toArray($r);
389 $connected = ($row[0]['1'] == '1');
393 $connected = $this->connection->ping();
401 * Replaces ANY_VALUE() function by MIN() function,
402 * if the database server does not support ANY_VALUE().
404 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
405 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
406 * A standard fall-back is to use MIN().
408 * @param string $sql An SQL string without the values
410 * @return string The input SQL string modified if necessary.
412 public function anyValueFallback($sql)
414 $server_info = $this->serverInfo();
415 if (version_compare($server_info, '5.7.5', '<') ||
416 (stripos($server_info, 'MariaDB') !== false)) {
417 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
423 * Replaces the ? placeholders with the parameters in the $args array
425 * @param string $sql SQL query
426 * @param array $args The parameters that are to replace the ? placeholders
428 * @return string The replaced SQL query
430 private function replaceParameters($sql, $args)
433 foreach ($args AS $param => $value) {
434 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
435 $replace = intval($args[$param]);
436 } elseif (is_null($args[$param])) {
439 $replace = "'" . $this->escape($args[$param]) . "'";
442 $pos = strpos($sql, '?', $offset);
443 if ($pos !== false) {
444 $sql = substr_replace($sql, $replace, $pos, 1);
446 $offset = $pos + strlen($replace);
452 * Executes a prepared statement that returns data
454 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
456 * Please only use it with complicated queries.
457 * For all regular queries please use DBA::select or DBA::exists
459 * @param string $sql SQL statement
461 * @return bool|object statement object or result object
464 public function p($sql)
467 $stamp1 = microtime(true);
469 $params = DBA::getParam(func_get_args());
471 // Renumber the array keys to be sure that they fit
474 foreach ($params AS $param) {
475 // Avoid problems with some MySQL servers and boolean values. See issue #3645
476 if (is_bool($param)) {
477 $param = (int)$param;
479 $args[++$i] = $param;
482 if (!$this->connected) {
486 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
487 // Question: Should we continue or stop the query here?
488 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
491 $sql = DBA::cleanQuery($sql);
492 $sql = $this->anyValueFallback($sql);
496 if ($this->configCache->get('system', 'db_callstack') !== null) {
497 $sql = "/*" . System::callstack() . " */ " . $sql;
502 $this->affected_rows = 0;
504 // We have to make some things different if this function is called from "e"
505 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
507 if (isset($trace[1])) {
508 $called_from = $trace[1];
510 // We use just something that is defined to avoid warnings
511 $called_from = $trace[0];
513 // We are having an own error logging in the function "e"
514 $called_from_e = ($called_from['function'] == 'e');
516 if (!isset($this->connection)) {
517 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
520 switch ($this->driver) {
522 // If there are no arguments we use "query"
523 if ($this->emulate_prepares || count($args) == 0) {
524 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
525 $errorInfo = $this->connection->errorInfo();
526 $this->error = $errorInfo[2];
527 $this->errorno = $errorInfo[1];
531 $this->affected_rows = $retval->rowCount();
535 /** @var $stmt mysqli_stmt|PDOStatement */
536 if (!$stmt = $this->connection->prepare($sql)) {
537 $errorInfo = $this->connection->errorInfo();
538 $this->error = $errorInfo[2];
539 $this->errorno = $errorInfo[1];
544 foreach ($args AS $param => $value) {
545 if (is_int($args[$param])) {
546 $data_type = PDO::PARAM_INT;
548 $data_type = PDO::PARAM_STR;
550 $stmt->bindParam($param, $args[$param], $data_type);
553 if (!$stmt->execute()) {
554 $errorInfo = $stmt->errorInfo();
555 $this->error = $errorInfo[2];
556 $this->errorno = $errorInfo[1];
560 $this->affected_rows = $retval->rowCount();
564 // There are SQL statements that cannot be executed with a prepared statement
565 $parts = explode(' ', $orig_sql);
566 $command = strtolower($parts[0]);
567 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
569 // The fallback routine is called as well when there are no arguments
570 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
571 $retval = $this->connection->query($this->replaceParameters($sql, $args));
572 if ($this->connection->errno) {
573 $this->error = $this->connection->error;
574 $this->errorno = $this->connection->errno;
577 if (isset($retval->num_rows)) {
578 $this->affected_rows = $retval->num_rows;
580 $this->affected_rows = $this->connection->affected_rows;
586 $stmt = $this->connection->stmt_init();
588 if (!$stmt->prepare($sql)) {
589 $this->error = $stmt->error;
590 $this->errorno = $stmt->errno;
597 foreach ($args AS $param => $value) {
598 if (is_int($args[$param])) {
600 } elseif (is_float($args[$param])) {
602 } elseif (is_string($args[$param])) {
607 $values[] = &$args[$param];
610 if (count($values) > 0) {
611 array_unshift($values, $param_types);
612 call_user_func_array([$stmt, 'bind_param'], $values);
615 if (!$stmt->execute()) {
616 $this->error = $this->connection->error;
617 $this->errorno = $this->connection->errno;
620 $stmt->store_result();
622 $this->affected_rows = $retval->affected_rows;
627 // We are having an own error logging in the function "e"
628 if (($this->errorno != 0) && !$called_from_e) {
629 // We have to preserve the error code, somewhere in the logging it get lost
630 $error = $this->error;
631 $errorno = $this->errorno;
633 $this->logger->error('DB Error', [
634 'code' => $this->errorno,
635 'error' => $this->error,
636 'callstack' => System::callstack(8),
637 'params' => $this->replaceParameters($sql, $args),
640 // On a lost connection we try to reconnect - but only once.
641 if ($errorno == 2006) {
642 if ($this->in_retrial || !$this->reconnect()) {
643 // It doesn't make sense to continue when the database connection was lost
644 if ($this->in_retrial) {
645 $this->logger->notice('Giving up retrial because of database error', [
646 'code' => $this->errorno,
647 'error' => $this->error,
650 $this->logger->notice('Couldn\'t reconnect after database error', [
651 'code' => $this->errorno,
652 'error' => $this->error,
658 $this->logger->notice('Reconnected after database error', [
659 'code' => $this->errorno,
660 'error' => $this->error,
662 $this->in_retrial = true;
663 $ret = $this->p($sql, $args);
664 $this->in_retrial = false;
669 $this->error = $error;
670 $this->errorno = $errorno;
673 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
675 if ($this->configCache->get('system', 'db_log')) {
676 $stamp2 = microtime(true);
677 $duration = (float)($stamp2 - $stamp1);
679 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
680 $duration = round($duration, 3);
681 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
683 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
684 basename($backtrace[1]["file"]) . "\t" .
685 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
686 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
693 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
695 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
697 * @param string $sql SQL statement
699 * @return boolean Was the query successfull? False is returned only if an error occurred
702 public function e($sql)
705 $stamp = microtime(true);
707 $params = DBA::getParam(func_get_args());
709 // In a case of a deadlock we are repeating the query 20 times
713 $stmt = $this->p($sql, $params);
715 if (is_bool($stmt)) {
717 } elseif (is_object($stmt)) {
725 } while (($this->errorno == 1213) && (--$timeout > 0));
727 if ($this->errorno != 0) {
728 // We have to preserve the error code, somewhere in the logging it get lost
729 $error = $this->error;
730 $errorno = $this->errorno;
732 $this->logger->error('DB Error', [
733 'code' => $this->errorno,
734 'error' => $this->error,
735 'callstack' => System::callstack(8),
736 'params' => $this->replaceParameters($sql, $params),
739 // On a lost connection we simply quit.
740 // A reconnect like in $this->p could be dangerous with modifications
741 if ($errorno == 2006) {
742 $this->logger->notice('Giving up because of database error', [
743 'code' => $this->errorno,
744 'error' => $this->error,
749 $this->error = $error;
750 $this->errorno = $errorno;
753 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
759 * Check if data exists
761 * @param string|array $table Table name or array [schema => table]
762 * @param array $condition array of fields for condition
764 * @return boolean Are there rows for that condition?
767 public function exists($table, $condition)
775 if (empty($condition)) {
776 return DBStructure::existsTable($table);
780 $first_key = key($condition);
781 if (!is_int($first_key)) {
782 $fields = [$first_key];
785 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
787 if (is_bool($stmt)) {
790 $retval = ($this->numRows($stmt) > 0);
799 * Fetches the first row
801 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
803 * Fetches the first row
805 * @param string $sql SQL statement
807 * @return array first row of query
810 public function fetchFirst($sql)
812 $params = DBA::getParam(func_get_args());
814 $stmt = $this->p($sql, $params);
816 if (is_bool($stmt)) {
819 $retval = $this->fetch($stmt);
828 * Returns the number of affected rows of the last statement
830 * @return int Number of rows
832 public function affectedRows()
834 return $this->affected_rows;
838 * Returns the number of columns of a statement
840 * @param object Statement object
842 * @return int Number of columns
844 public function columnCount($stmt)
846 if (!is_object($stmt)) {
849 switch ($this->driver) {
851 return $stmt->columnCount();
853 return $stmt->field_count;
859 * Returns the number of rows of a statement
861 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
863 * @return int Number of rows
865 public function numRows($stmt)
867 if (!is_object($stmt)) {
870 switch ($this->driver) {
872 return $stmt->rowCount();
874 return $stmt->num_rows;
882 * @param mixed $stmt statement object
884 * @return array current row
886 public function fetch($stmt)
889 $stamp1 = microtime(true);
893 if (!is_object($stmt)) {
897 switch ($this->driver) {
899 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
902 if (get_class($stmt) == 'mysqli_result') {
903 $columns = $stmt->fetch_assoc();
907 // This code works, but is slow
909 // Bind the result to a result array
913 for ($x = 0; $x < $stmt->field_count; $x++) {
914 $cols[] = &$cols_num[$x];
917 call_user_func_array([$stmt, 'bind_result'], $cols);
919 if (!$stmt->fetch()) {
924 // We need to get the field names for the array keys
925 // It seems that there is no better way to do this.
926 $result = $stmt->result_metadata();
927 $fields = $result->fetch_fields();
929 foreach ($cols_num AS $param => $col) {
930 $columns[$fields[$param]->name] = $col;
934 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
940 * Insert a row into a table
942 * @param string|array $table Table name or array [schema => table]
943 * @param array $param parameter array
944 * @param bool $on_duplicate_update Do an update on a duplicate entry
946 * @return boolean was the insert successful?
949 public function insert($table, $param, $on_duplicate_update = false)
951 if (empty($table) || empty($param)) {
952 $this->logger->info('Table and fields have to be set');
956 $table_string = DBA::buildTableString($table);
958 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
960 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
962 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
964 if ($on_duplicate_update) {
965 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
967 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
969 $values = array_values($param);
970 $param = array_merge_recursive($values, $values);
973 return $this->e($sql, $param);
977 * Fetch the id of the last insert command
979 * @return integer Last inserted id
981 public function lastInsertId()
983 switch ($this->driver) {
985 $id = $this->connection->lastInsertId();
988 $id = $this->connection->insert_id;
995 * Locks a table for exclusive write access
997 * This function can be extended in the future to accept a table array as well.
999 * @param string|array $table Table name or array [schema => table]
1001 * @return boolean was the lock successful?
1002 * @throws \Exception
1004 public function lock($table)
1006 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1007 if ($this->driver == 'pdo') {
1008 $this->e("SET autocommit=0");
1009 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1011 $this->connection->autocommit(false);
1014 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1016 if ($this->driver == 'pdo') {
1017 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1021 if ($this->driver == 'pdo') {
1022 $this->e("SET autocommit=1");
1024 $this->connection->autocommit(true);
1027 $this->in_transaction = true;
1033 * Unlocks all locked tables
1035 * @return boolean was the unlock successful?
1036 * @throws \Exception
1038 public function unlock()
1040 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1041 $this->performCommit();
1043 if ($this->driver == 'pdo') {
1044 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1047 $success = $this->e("UNLOCK TABLES");
1049 if ($this->driver == 'pdo') {
1050 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1051 $this->e("SET autocommit=1");
1053 $this->connection->autocommit(true);
1056 $this->in_transaction = false;
1061 * Starts a transaction
1063 * @return boolean Was the command executed successfully?
1065 public function transaction()
1067 if (!$this->performCommit()) {
1071 switch ($this->driver) {
1073 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1079 if (!$this->connection->begin_transaction()) {
1085 $this->in_transaction = true;
1089 protected function performCommit()
1091 switch ($this->driver) {
1093 if (!$this->connection->inTransaction()) {
1097 return $this->connection->commit();
1100 return $this->connection->commit();
1109 * @return boolean Was the command executed successfully?
1111 public function commit()
1113 if (!$this->performCommit()) {
1116 $this->in_transaction = false;
1123 * @return boolean Was the command executed successfully?
1125 public function rollback()
1129 switch ($this->driver) {
1131 if (!$this->connection->inTransaction()) {
1135 $ret = $this->connection->rollBack();
1139 $ret = $this->connection->rollback();
1142 $this->in_transaction = false;
1147 * Build the array with the table relations
1149 * The array is build from the database definitions in DBStructure.php
1151 * This process must only be started once, since the value is cached.
1153 private function buildRelationData()
1155 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1157 foreach ($definition AS $table => $structure) {
1158 foreach ($structure['fields'] AS $field => $field_struct) {
1159 if (isset($field_struct['relation'])) {
1160 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1161 $this->relation[$rel_table][$rel_field][$table][] = $field;
1169 * Delete a row from a table
1171 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1173 * @param string $table Table name
1174 * @param array $conditions Field condition(s)
1175 * @param array $options
1176 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1177 * relations (default: true)
1178 * @param array $callstack Internal use: prevent endless loops
1180 * @return boolean was the delete successful?
1181 * @throws \Exception
1183 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1185 if (empty($table) || empty($conditions)) {
1186 $this->logger->info('Table and conditions have to be set');
1192 // Create a key for the loop prevention
1193 $key = $table . ':' . json_encode($conditions);
1195 // We quit when this key already exists in the callstack.
1196 if (isset($callstack[$key])) {
1200 $callstack[$key] = true;
1202 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1204 // Don't use "defaults" here, since it would set "false" to "true"
1205 if (isset($options['cascade'])) {
1206 $cascade = $options['cascade'];
1211 // To speed up the whole process we cache the table relations
1212 if ($cascade && count($this->relation) == 0) {
1213 $this->buildRelationData();
1216 // Is there a relation entry for the table?
1217 if ($cascade && isset($this->relation[$table])) {
1218 // We only allow a simple "one field" relation.
1219 $field = array_keys($this->relation[$table])[0];
1220 $rel_def = array_values($this->relation[$table])[0];
1222 // Create a key for preventing double queries
1223 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1225 // When the search field is the relation field, we don't need to fetch the rows
1226 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1227 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1228 foreach ($rel_def AS $rel_table => $rel_fields) {
1229 foreach ($rel_fields AS $rel_field) {
1230 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1233 // We quit when this key already exists in the callstack.
1234 } elseif (!isset($callstack[$qkey])) {
1235 $callstack[$qkey] = true;
1237 // Fetch all rows that are to be deleted
1238 $data = $this->select($table, [$field], $conditions);
1240 while ($row = $this->fetch($data)) {
1241 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1244 $this->close($data);
1246 // Since we had split the delete command we don't need the original command anymore
1247 unset($commands[$key]);
1251 // Now we finalize the process
1252 $do_transaction = !$this->in_transaction;
1254 if ($do_transaction) {
1255 $this->transaction();
1261 foreach ($commands AS $command) {
1262 $conditions = $command['conditions'];
1264 $first_key = key($conditions);
1266 $condition_string = DBA::buildCondition($conditions);
1268 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1269 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1270 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1272 if (!$this->e($sql, $conditions)) {
1273 if ($do_transaction) {
1279 $key_table = $command['table'];
1280 $key_condition = array_keys($command['conditions'])[0];
1281 $value = array_values($command['conditions'])[0];
1283 // Split the SQL queries in chunks of 100 values
1284 // We do the $i stuff here to make the code better readable
1285 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1286 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1290 $compacted[$key_table][$key_condition][$i][$value] = $value;
1291 $counter[$key_table][$key_condition] = $i;
1294 foreach ($compacted AS $table => $values) {
1295 foreach ($values AS $field => $field_value_list) {
1296 foreach ($field_value_list AS $field_values) {
1297 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1298 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1300 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1302 if (!$this->e($sql, $field_values)) {
1303 if ($do_transaction) {
1311 if ($do_transaction) {
1320 * Updates rows in the database. When $old_fields is set to an array,
1321 * the system will only do an update if the fields in that array changed.
1324 * Only the values in $old_fields are compared.
1325 * This is an intentional behaviour.
1328 * We include the timestamp field in $fields but not in $old_fields.
1329 * Then the row will only get the new timestamp when the other fields had changed.
1331 * When $old_fields is set to a boolean value the system will do this compare itself.
1332 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1335 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1336 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1338 * @param string|array $table Table name or array [schema => table]
1339 * @param array $fields contains the fields that are updated
1340 * @param array $condition condition array with the key values
1341 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1343 * @return boolean was the update successfull?
1344 * @throws \Exception
1346 public function update($table, $fields, $condition, $old_fields = [])
1348 if (empty($table) || empty($fields) || empty($condition)) {
1349 $this->logger->info('Table, fields and condition have to be set');
1353 if (is_bool($old_fields)) {
1354 $do_insert = $old_fields;
1356 $old_fields = $this->selectFirst($table, [], $condition);
1358 if (is_bool($old_fields)) {
1360 $values = array_merge($condition, $fields);
1361 return $this->insert($table, $values, $do_insert);
1367 foreach ($old_fields AS $fieldname => $content) {
1368 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1369 unset($fields[$fieldname]);
1373 if (count($fields) == 0) {
1377 $table_string = DBA::buildTableString($table);
1379 $condition_string = DBA::buildCondition($condition);
1381 $sql = "UPDATE " . $table_string . " SET "
1382 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1383 . $condition_string;
1385 // Combines the updated fields parameter values with the condition parameter values
1386 $params = array_merge(array_values($fields), $condition);
1388 return $this->e($sql, $params);
1392 * Retrieve a single record from a table and returns it in an associative array
1394 * @param string|array $table
1395 * @param array $fields
1396 * @param array $condition
1397 * @param array $params
1399 * @return bool|array
1400 * @throws \Exception
1401 * @see $this->select
1403 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1405 $params['limit'] = 1;
1406 $result = $this->select($table, $fields, $condition, $params);
1408 if (is_bool($result)) {
1411 $row = $this->fetch($result);
1412 $this->close($result);
1418 * Select rows from a table and fills an array with the data
1420 * @param string|array $table Table name or array [schema => table]
1421 * @param array $fields Array of selected fields, empty for all
1422 * @param array $condition Array of fields for condition
1423 * @param array $params Array of several parameters
1425 * @return array Data array
1426 * @throws \Exception
1429 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1431 return $this->toArray($this->select($table, $fields, $condition, $params));
1435 * Select rows from a table
1437 * @param string|array $table Table name or array [schema => table]
1438 * @param array $fields Array of selected fields, empty for all
1439 * @param array $condition Array of fields for condition
1440 * @param array $params Array of several parameters
1442 * @return boolean|object
1446 * $fields = array("id", "uri", "uid", "network");
1448 * $condition = array("uid" => 1, "network" => 'dspr');
1450 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1452 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1454 * $data = DBA::select($table, $fields, $condition, $params);
1455 * @throws \Exception
1457 public function select($table, array $fields = [], array $condition = [], array $params = [])
1459 if (empty($table)) {
1463 if (count($fields) > 0) {
1464 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1466 $select_string = '*';
1469 $table_string = DBA::buildTableString($table);
1471 $condition_string = DBA::buildCondition($condition);
1473 $param_string = DBA::buildParameter($params);
1475 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1477 $result = $this->p($sql, $condition);
1483 * Counts the rows from a table satisfying the provided condition
1485 * @param string|array $table Table name or array [schema => table]
1486 * @param array $condition Array of fields for condition
1487 * @param array $params Array of several parameters
1494 * $condition = ["uid" => 1, "network" => 'dspr'];
1496 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1498 * $count = DBA::count($table, $condition);
1499 * @throws \Exception
1501 public function count($table, array $condition = [], array $params = [])
1503 if (empty($table)) {
1507 $table_string = DBA::buildTableString($table);
1509 $condition_string = DBA::buildCondition($condition);
1511 if (empty($params['expression'])) {
1513 } elseif (!empty($params['distinct'])) {
1514 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1516 $expression = DBA::quoteIdentifier($params['expression']);
1519 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1521 $row = $this->fetchFirst($sql, $condition);
1523 return $row['count'];
1527 * Fills an array with data from a query
1529 * @param object $stmt statement object
1530 * @param bool $do_close
1532 * @return array Data array
1534 public function toArray($stmt, $do_close = true)
1536 if (is_bool($stmt)) {
1541 while ($row = $this->fetch($stmt)) {
1546 $this->close($stmt);
1553 * Returns the error number of the last query
1555 * @return string Error number (0 if no error)
1557 public function errorNo()
1559 return $this->errorno;
1563 * Returns the error message of the last query
1565 * @return string Error message ('' if no error)
1567 public function errorMessage()
1569 return $this->error;
1573 * Closes the current statement
1575 * @param object $stmt statement object
1577 * @return boolean was the close successful?
1579 public function close($stmt)
1582 $stamp1 = microtime(true);
1584 if (!is_object($stmt)) {
1588 switch ($this->driver) {
1590 $ret = $stmt->closeCursor();
1593 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1594 // We should be careful not to assume the object type of $stmt
1595 // because DBA::p() has been able to return both types.
1596 if ($stmt instanceof mysqli_stmt) {
1597 $stmt->free_result();
1598 $ret = $stmt->close();
1599 } elseif ($stmt instanceof mysqli_result) {
1608 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1614 * Return a list of database processes
1617 * 'list' => List of processes, separated in their different states
1618 * 'amount' => Number of concurrent database processes
1619 * @throws \Exception
1621 public function processlist()
1623 $ret = $this->p("SHOW PROCESSLIST");
1624 $data = $this->toArray($ret);
1628 foreach ($data as $process) {
1629 $state = trim($process["State"]);
1631 // Filter out all non blocking processes
1632 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1639 foreach ($states as $state => $usage) {
1640 if ($statelist != "") {
1643 $statelist .= $state . ": " . $usage;
1645 return (["list" => $statelist, "amount" => $processes]);
1649 * Fetch a database variable
1651 * @param string $name
1652 * @return string content
1654 public function getVariable(string $name)
1656 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1657 return $result['Value'] ?? null;
1661 * Checks if $array is a filled array with at least one entry.
1663 * @param mixed $array A filled array with at least one entry
1665 * @return boolean Whether $array is a filled array or an object with rows
1667 public function isResult($array)
1669 // It could be a return value from an update statement
1670 if (is_bool($array)) {
1674 if (is_object($array)) {
1675 return $this->numRows($array) > 0;
1678 return (is_array($array) && (count($array) > 0));
1682 * Callback function for "esc_array"
1684 * @param mixed $value Array value
1685 * @param string $key Array key
1686 * @param boolean $add_quotation add quotation marks for string values
1690 private function escapeArrayCallback(&$value, $key, $add_quotation)
1692 if (!$add_quotation) {
1693 if (is_bool($value)) {
1694 $value = ($value ? '1' : '0');
1696 $value = $this->escape($value);
1701 if (is_bool($value)) {
1702 $value = ($value ? 'true' : 'false');
1703 } elseif (is_float($value) || is_integer($value)) {
1704 $value = (string)$value;
1706 $value = "'" . $this->escape($value) . "'";
1711 * Escapes a whole array
1713 * @param mixed $arr Array with values to be escaped
1714 * @param boolean $add_quotation add quotation marks for string values
1718 public function escapeArray(&$arr, $add_quotation = false)
1720 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);