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');
139 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
140 $this->driver = 'pdo';
141 $connect = "mysql:host=" . $server . ";dbname=" . $db;
144 $connect .= ";port=" . $port;
148 $connect .= ";charset=" . $charset;
152 $this->connection = @new PDO($connect, $user, $pass);
153 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
154 $this->connected = true;
155 } catch (PDOException $e) {
156 $this->connected = false;
160 if (!$this->connected && class_exists('\mysqli')) {
161 $this->driver = 'mysqli';
164 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
166 $this->connection = @new mysqli($server, $user, $pass, $db);
169 if (!mysqli_connect_errno()) {
170 $this->connected = true;
173 $this->connection->set_charset($charset);
178 // No suitable SQL driver was found.
179 if (!$this->connected) {
180 $this->driver = null;
181 $this->connection = null;
184 return $this->connected;
187 public function setTestmode(bool $test)
189 $this->testmode = $test;
192 * Sets the logger for DBA
194 * @note this is necessary because if we want to load the logger configuration
195 * from the DB, but there's an error, we would print out an exception.
196 * So the logger gets updated after the logger configuration can be retrieved
199 * @param LoggerInterface $logger
201 public function setLogger(LoggerInterface $logger)
203 $this->logger = $logger;
207 * Sets the profiler for DBA
209 * @param Profiler $profiler
211 public function setProfiler(Profiler $profiler)
213 $this->profiler = $profiler;
216 * Disconnects the current database connection
218 public function disconnect()
220 if (!is_null($this->connection)) {
221 switch ($this->driver) {
223 $this->connection = null;
226 $this->connection->close();
227 $this->connection = null;
232 $this->driver = null;
233 $this->connected = false;
237 * Perform a reconnect of an existing database connection
239 public function reconnect()
242 return $this->connect();
246 * Return the database object.
250 public function getConnection()
252 return $this->connection;
256 * Returns the MySQL server version string
258 * This function discriminate between the deprecated mysql API and the current
259 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
263 public function serverInfo()
265 if ($this->server_info == '') {
266 switch ($this->driver) {
268 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
271 $this->server_info = $this->connection->server_info;
275 return $this->server_info;
279 * Returns the selected database name
284 public function databaseName()
286 $ret = $this->p("SELECT DATABASE() AS `db`");
287 $data = $this->toArray($ret);
288 return $data[0]['db'];
292 * Analyze a database query and log this if some conditions are met.
294 * @param string $query The database query that will be analyzed
298 private function logIndex($query)
301 if (!$this->configCache->get('system', 'db_log_index')) {
305 // Don't explain an explain statement
306 if (strtolower(substr($query, 0, 7)) == "explain") {
310 // Only do the explain on "select", "update" and "delete"
311 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
315 $r = $this->p("EXPLAIN " . $query);
316 if (!$this->isResult($r)) {
320 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
321 $blacklist = explode(',', $this->configCache->get('system', 'db_log_index_blacklist'));
323 while ($row = $this->fetch($r)) {
324 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
325 $log = (in_array($row['key'], $watchlist) &&
326 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
331 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
335 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
340 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
341 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
342 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
343 basename($backtrace[1]["file"]) . "\t" .
344 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
345 substr($query, 0, 2000) . "\n", FILE_APPEND);
351 * Removes every not whitelisted character from the identifier string
353 * @param string $identifier
355 * @return string sanitized identifier
358 private function sanitizeIdentifier($identifier)
360 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
363 public function escape($str)
365 if ($this->connected) {
366 switch ($this->driver) {
368 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
371 return @$this->connection->real_escape_string($str);
374 return str_replace("'", "\\'", $str);
378 public function isConnected()
380 return $this->connected;
383 public function connected()
387 if (is_null($this->connection)) {
391 switch ($this->driver) {
393 $r = $this->p("SELECT 1");
394 if ($this->isResult($r)) {
395 $row = $this->toArray($r);
396 $connected = ($row[0]['1'] == '1');
400 $connected = $this->connection->ping();
408 * Replaces ANY_VALUE() function by MIN() function,
409 * if the database server does not support ANY_VALUE().
411 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
412 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
413 * A standard fall-back is to use MIN().
415 * @param string $sql An SQL string without the values
417 * @return string The input SQL string modified if necessary.
419 public function anyValueFallback($sql)
421 $server_info = $this->serverInfo();
422 if (version_compare($server_info, '5.7.5', '<') ||
423 (stripos($server_info, 'MariaDB') !== false)) {
424 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
430 * Replaces the ? placeholders with the parameters in the $args array
432 * @param string $sql SQL query
433 * @param array $args The parameters that are to replace the ? placeholders
435 * @return string The replaced SQL query
437 private function replaceParameters($sql, $args)
440 foreach ($args AS $param => $value) {
441 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
442 $replace = intval($args[$param]);
443 } elseif (is_null($args[$param])) {
446 $replace = "'" . $this->escape($args[$param]) . "'";
449 $pos = strpos($sql, '?', $offset);
450 if ($pos !== false) {
451 $sql = substr_replace($sql, $replace, $pos, 1);
453 $offset = $pos + strlen($replace);
459 * Executes a prepared statement that returns data
461 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
463 * Please only use it with complicated queries.
464 * For all regular queries please use DBA::select or DBA::exists
466 * @param string $sql SQL statement
468 * @return bool|object statement object or result object
471 public function p($sql)
474 $stamp1 = microtime(true);
476 $params = DBA::getParam(func_get_args());
478 // Renumber the array keys to be sure that they fit
481 foreach ($params AS $param) {
482 // Avoid problems with some MySQL servers and boolean values. See issue #3645
483 if (is_bool($param)) {
484 $param = (int)$param;
486 $args[++$i] = $param;
489 if (!$this->connected) {
493 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
494 // Question: Should we continue or stop the query here?
495 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
498 $sql = DBA::cleanQuery($sql);
499 $sql = $this->anyValueFallback($sql);
503 if ($this->configCache->get('system', 'db_callstack') !== null) {
504 $sql = "/*" . System::callstack() . " */ " . $sql;
510 $this->affected_rows = 0;
512 // We have to make some things different if this function is called from "e"
513 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
515 if (isset($trace[1])) {
516 $called_from = $trace[1];
518 // We use just something that is defined to avoid warnings
519 $called_from = $trace[0];
521 // We are having an own error logging in the function "e"
522 $called_from_e = ($called_from['function'] == 'e');
524 if (!isset($this->connection)) {
525 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
528 switch ($this->driver) {
530 // If there are no arguments we use "query"
531 if ($this->emulate_prepares || count($args) == 0) {
532 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
533 $errorInfo = $this->connection->errorInfo();
534 $this->error = $errorInfo[2];
535 $this->errorno = $errorInfo[1];
540 $this->affected_rows = $retval->rowCount();
544 /** @var $stmt mysqli_stmt|PDOStatement */
545 if (!$stmt = $this->connection->prepare($sql)) {
546 $errorInfo = $this->connection->errorInfo();
547 $this->error = $errorInfo[2];
548 $this->errorno = $errorInfo[1];
554 foreach ($args AS $param => $value) {
555 if (is_int($args[$param])) {
556 $data_type = PDO::PARAM_INT;
558 $data_type = PDO::PARAM_STR;
560 $stmt->bindParam($param, $args[$param], $data_type);
563 if (!$stmt->execute()) {
564 $errorInfo = $stmt->errorInfo();
565 $this->error = $errorInfo[2];
566 $this->errorno = $errorInfo[1];
571 $this->affected_rows = $retval->rowCount();
575 // There are SQL statements that cannot be executed with a prepared statement
576 $parts = explode(' ', $orig_sql);
577 $command = strtolower($parts[0]);
578 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
580 // The fallback routine is called as well when there are no arguments
581 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
582 $retval = $this->connection->query($this->replaceParameters($sql, $args));
583 if ($this->connection->errno) {
584 $this->error = $this->connection->error;
585 $this->errorno = $this->connection->errno;
589 if (isset($retval->num_rows)) {
590 $this->affected_rows = $retval->num_rows;
592 $this->affected_rows = $this->connection->affected_rows;
598 $stmt = $this->connection->stmt_init();
600 if (!$stmt->prepare($sql)) {
601 $this->error = $stmt->error;
602 $this->errorno = $stmt->errno;
610 foreach ($args AS $param => $value) {
611 if (is_int($args[$param])) {
613 } elseif (is_float($args[$param])) {
615 } elseif (is_string($args[$param])) {
620 $values[] = &$args[$param];
623 if (count($values) > 0) {
624 array_unshift($values, $param_types);
625 call_user_func_array([$stmt, 'bind_param'], $values);
628 if (!$stmt->execute()) {
629 $this->error = $this->connection->error;
630 $this->errorno = $this->connection->errno;
634 $stmt->store_result();
636 $this->affected_rows = $retval->affected_rows;
641 // See issue https://github.com/friendica/friendica/issues/8572
642 // Ensure that we always get an error message on an error.
643 if ($is_error && empty($this->errorno)) {
647 if ($is_error && empty($this->error)) {
648 $this->error = 'Unknown database error';
651 // We are having an own error logging in the function "e"
652 if (($this->errorno != 0) && !$called_from_e) {
653 // We have to preserve the error code, somewhere in the logging it get lost
654 $error = $this->error;
655 $errorno = $this->errorno;
657 if ($this->testmode) {
658 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $args)));
661 $this->logger->error('DB Error', [
664 'callstack' => System::callstack(8),
665 'params' => $this->replaceParameters($sql, $args),
668 // On a lost connection we try to reconnect - but only once.
669 if ($errorno == 2006) {
670 if ($this->in_retrial || !$this->reconnect()) {
671 // It doesn't make sense to continue when the database connection was lost
672 if ($this->in_retrial) {
673 $this->logger->notice('Giving up retrial because of database error', [
678 $this->logger->notice('Couldn\'t reconnect after database error', [
686 $this->logger->notice('Reconnected after database error', [
690 $this->in_retrial = true;
691 $ret = $this->p($sql, $args);
692 $this->in_retrial = false;
697 $this->error = $error;
698 $this->errorno = $errorno;
701 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
703 if ($this->configCache->get('system', 'db_log')) {
704 $stamp2 = microtime(true);
705 $duration = (float)($stamp2 - $stamp1);
707 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
708 $duration = round($duration, 3);
709 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
711 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
712 basename($backtrace[1]["file"]) . "\t" .
713 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
714 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
721 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
723 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
725 * @param string $sql SQL statement
727 * @return boolean Was the query successfull? False is returned only if an error occurred
730 public function e($sql)
733 $stamp = microtime(true);
735 $params = DBA::getParam(func_get_args());
737 // In a case of a deadlock we are repeating the query 20 times
741 $stmt = $this->p($sql, $params);
743 if (is_bool($stmt)) {
745 } elseif (is_object($stmt)) {
753 } while (($this->errorno == 1213) && (--$timeout > 0));
755 if ($this->errorno != 0) {
756 // We have to preserve the error code, somewhere in the logging it get lost
757 $error = $this->error;
758 $errorno = $this->errorno;
760 if ($this->testmode) {
761 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $params)));
764 $this->logger->error('DB Error', [
767 'callstack' => System::callstack(8),
768 'params' => $this->replaceParameters($sql, $params),
771 // On a lost connection we simply quit.
772 // A reconnect like in $this->p could be dangerous with modifications
773 if ($errorno == 2006) {
774 $this->logger->notice('Giving up because of database error', [
781 $this->error = $error;
782 $this->errorno = $errorno;
785 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
791 * Check if data exists
793 * @param string|array $table Table name or array [schema => table]
794 * @param array $condition array of fields for condition
796 * @return boolean Are there rows for that condition?
799 public function exists($table, $condition)
807 if (empty($condition)) {
808 return DBStructure::existsTable($table);
812 $first_key = key($condition);
813 if (!is_int($first_key)) {
814 $fields = [$first_key];
817 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
819 if (is_bool($stmt)) {
822 $retval = ($this->numRows($stmt) > 0);
831 * Fetches the first row
833 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
835 * Fetches the first row
837 * @param string $sql SQL statement
839 * @return array first row of query
842 public function fetchFirst($sql)
844 $params = DBA::getParam(func_get_args());
846 $stmt = $this->p($sql, $params);
848 if (is_bool($stmt)) {
851 $retval = $this->fetch($stmt);
860 * Returns the number of affected rows of the last statement
862 * @return int Number of rows
864 public function affectedRows()
866 return $this->affected_rows;
870 * Returns the number of columns of a statement
872 * @param object Statement object
874 * @return int Number of columns
876 public function columnCount($stmt)
878 if (!is_object($stmt)) {
881 switch ($this->driver) {
883 return $stmt->columnCount();
885 return $stmt->field_count;
891 * Returns the number of rows of a statement
893 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
895 * @return int Number of rows
897 public function numRows($stmt)
899 if (!is_object($stmt)) {
902 switch ($this->driver) {
904 return $stmt->rowCount();
906 return $stmt->num_rows;
914 * @param mixed $stmt statement object
916 * @return array current row
918 public function fetch($stmt)
921 $stamp1 = microtime(true);
925 if (!is_object($stmt)) {
929 switch ($this->driver) {
931 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
934 if (get_class($stmt) == 'mysqli_result') {
935 $columns = $stmt->fetch_assoc();
939 // This code works, but is slow
941 // Bind the result to a result array
945 for ($x = 0; $x < $stmt->field_count; $x++) {
946 $cols[] = &$cols_num[$x];
949 call_user_func_array([$stmt, 'bind_result'], $cols);
951 if (!$stmt->fetch()) {
956 // We need to get the field names for the array keys
957 // It seems that there is no better way to do this.
958 $result = $stmt->result_metadata();
959 $fields = $result->fetch_fields();
961 foreach ($cols_num AS $param => $col) {
962 $columns[$fields[$param]->name] = $col;
966 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
972 * Insert a row into a table
974 * @param string|array $table Table name or array [schema => table]
975 * @param array $param parameter array
976 * @param bool $on_duplicate_update Do an update on a duplicate entry
978 * @return boolean was the insert successful?
981 public function insert($table, $param, $on_duplicate_update = false)
983 if (empty($table) || empty($param)) {
984 $this->logger->info('Table and fields have to be set');
988 $table_string = DBA::buildTableString($table);
990 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
992 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
994 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
996 if ($on_duplicate_update) {
997 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
999 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1001 $values = array_values($param);
1002 $param = array_merge_recursive($values, $values);
1005 return $this->e($sql, $param);
1009 * Fetch the id of the last insert command
1011 * @return integer Last inserted id
1013 public function lastInsertId()
1015 switch ($this->driver) {
1017 $id = $this->connection->lastInsertId();
1020 $id = $this->connection->insert_id;
1027 * Locks a table for exclusive write access
1029 * This function can be extended in the future to accept a table array as well.
1031 * @param string|array $table Table name or array [schema => table]
1033 * @return boolean was the lock successful?
1034 * @throws \Exception
1036 public function lock($table)
1038 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1039 if ($this->driver == 'pdo') {
1040 $this->e("SET autocommit=0");
1041 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1043 $this->connection->autocommit(false);
1046 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1048 if ($this->driver == 'pdo') {
1049 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1053 if ($this->driver == 'pdo') {
1054 $this->e("SET autocommit=1");
1056 $this->connection->autocommit(true);
1059 $this->in_transaction = true;
1065 * Unlocks all locked tables
1067 * @return boolean was the unlock successful?
1068 * @throws \Exception
1070 public function unlock()
1072 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1073 $this->performCommit();
1075 if ($this->driver == 'pdo') {
1076 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1079 $success = $this->e("UNLOCK TABLES");
1081 if ($this->driver == 'pdo') {
1082 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1083 $this->e("SET autocommit=1");
1085 $this->connection->autocommit(true);
1088 $this->in_transaction = false;
1093 * Starts a transaction
1095 * @return boolean Was the command executed successfully?
1097 public function transaction()
1099 if (!$this->performCommit()) {
1103 switch ($this->driver) {
1105 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1111 if (!$this->connection->begin_transaction()) {
1117 $this->in_transaction = true;
1121 protected function performCommit()
1123 switch ($this->driver) {
1125 if (!$this->connection->inTransaction()) {
1129 return $this->connection->commit();
1132 return $this->connection->commit();
1141 * @return boolean Was the command executed successfully?
1143 public function commit()
1145 if (!$this->performCommit()) {
1148 $this->in_transaction = false;
1155 * @return boolean Was the command executed successfully?
1157 public function rollback()
1161 switch ($this->driver) {
1163 if (!$this->connection->inTransaction()) {
1167 $ret = $this->connection->rollBack();
1171 $ret = $this->connection->rollback();
1174 $this->in_transaction = false;
1179 * Build the array with the table relations
1181 * The array is build from the database definitions in DBStructure.php
1183 * This process must only be started once, since the value is cached.
1185 private function buildRelationData()
1187 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1189 foreach ($definition AS $table => $structure) {
1190 foreach ($structure['fields'] AS $field => $field_struct) {
1191 if (isset($field_struct['relation'])) {
1192 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1193 $this->relation[$rel_table][$rel_field][$table][] = $field;
1201 * Delete a row from a table
1203 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1205 * @param string $table Table name
1206 * @param array $conditions Field condition(s)
1207 * @param array $options
1208 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1209 * relations (default: true)
1210 * @param array $callstack Internal use: prevent endless loops
1212 * @return boolean was the delete successful?
1213 * @throws \Exception
1215 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1217 if (empty($table) || empty($conditions)) {
1218 $this->logger->info('Table and conditions have to be set');
1224 // Create a key for the loop prevention
1225 $key = $table . ':' . json_encode($conditions);
1227 // We quit when this key already exists in the callstack.
1228 if (isset($callstack[$key])) {
1232 $callstack[$key] = true;
1234 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1236 // Don't use "defaults" here, since it would set "false" to "true"
1237 if (isset($options['cascade'])) {
1238 $cascade = $options['cascade'];
1243 // To speed up the whole process we cache the table relations
1244 if ($cascade && count($this->relation) == 0) {
1245 $this->buildRelationData();
1248 // Is there a relation entry for the table?
1249 if ($cascade && isset($this->relation[$table])) {
1250 // We only allow a simple "one field" relation.
1251 $field = array_keys($this->relation[$table])[0];
1252 $rel_def = array_values($this->relation[$table])[0];
1254 // Create a key for preventing double queries
1255 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1257 // When the search field is the relation field, we don't need to fetch the rows
1258 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1259 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1260 foreach ($rel_def AS $rel_table => $rel_fields) {
1261 foreach ($rel_fields AS $rel_field) {
1262 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1265 // We quit when this key already exists in the callstack.
1266 } elseif (!isset($callstack[$qkey])) {
1267 $callstack[$qkey] = true;
1269 // Fetch all rows that are to be deleted
1270 $data = $this->select($table, [$field], $conditions);
1272 while ($row = $this->fetch($data)) {
1273 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1276 $this->close($data);
1278 // Since we had split the delete command we don't need the original command anymore
1279 unset($commands[$key]);
1283 // Now we finalize the process
1284 $do_transaction = !$this->in_transaction;
1286 if ($do_transaction) {
1287 $this->transaction();
1293 foreach ($commands AS $command) {
1294 $conditions = $command['conditions'];
1296 $first_key = key($conditions);
1298 $condition_string = DBA::buildCondition($conditions);
1300 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1301 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1302 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1304 if (!$this->e($sql, $conditions)) {
1305 if ($do_transaction) {
1311 $key_table = $command['table'];
1312 $key_condition = array_keys($command['conditions'])[0];
1313 $value = array_values($command['conditions'])[0];
1315 // Split the SQL queries in chunks of 100 values
1316 // We do the $i stuff here to make the code better readable
1317 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1318 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1322 $compacted[$key_table][$key_condition][$i][$value] = $value;
1323 $counter[$key_table][$key_condition] = $i;
1326 foreach ($compacted AS $table => $values) {
1327 foreach ($values AS $field => $field_value_list) {
1328 foreach ($field_value_list AS $field_values) {
1329 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1330 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1332 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1334 if (!$this->e($sql, $field_values)) {
1335 if ($do_transaction) {
1343 if ($do_transaction) {
1352 * Updates rows in the database. When $old_fields is set to an array,
1353 * the system will only do an update if the fields in that array changed.
1356 * Only the values in $old_fields are compared.
1357 * This is an intentional behaviour.
1360 * We include the timestamp field in $fields but not in $old_fields.
1361 * Then the row will only get the new timestamp when the other fields had changed.
1363 * When $old_fields is set to a boolean value the system will do this compare itself.
1364 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1367 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1368 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1370 * @param string|array $table Table name or array [schema => table]
1371 * @param array $fields contains the fields that are updated
1372 * @param array $condition condition array with the key values
1373 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1375 * @return boolean was the update successfull?
1376 * @throws \Exception
1378 public function update($table, $fields, $condition, $old_fields = [])
1380 if (empty($table) || empty($fields) || empty($condition)) {
1381 $this->logger->info('Table, fields and condition have to be set');
1385 if (is_bool($old_fields)) {
1386 $do_insert = $old_fields;
1388 $old_fields = $this->selectFirst($table, [], $condition);
1390 if (is_bool($old_fields)) {
1392 $values = array_merge($condition, $fields);
1393 return $this->insert($table, $values, $do_insert);
1399 foreach ($old_fields AS $fieldname => $content) {
1400 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1401 unset($fields[$fieldname]);
1405 if (count($fields) == 0) {
1409 $table_string = DBA::buildTableString($table);
1411 $condition_string = DBA::buildCondition($condition);
1413 $sql = "UPDATE " . $table_string . " SET "
1414 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1415 . $condition_string;
1417 // Combines the updated fields parameter values with the condition parameter values
1418 $params = array_merge(array_values($fields), $condition);
1420 return $this->e($sql, $params);
1424 * Retrieve a single record from a table and returns it in an associative array
1426 * @param string|array $table
1427 * @param array $fields
1428 * @param array $condition
1429 * @param array $params
1431 * @return bool|array
1432 * @throws \Exception
1433 * @see $this->select
1435 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1437 $params['limit'] = 1;
1438 $result = $this->select($table, $fields, $condition, $params);
1440 if (is_bool($result)) {
1443 $row = $this->fetch($result);
1444 $this->close($result);
1450 * Select rows from a table and fills an array with the data
1452 * @param string|array $table Table name or array [schema => table]
1453 * @param array $fields Array of selected fields, empty for all
1454 * @param array $condition Array of fields for condition
1455 * @param array $params Array of several parameters
1457 * @return array Data array
1458 * @throws \Exception
1461 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1463 return $this->toArray($this->select($table, $fields, $condition, $params));
1467 * Select rows from a table
1469 * @param string|array $table Table name or array [schema => table]
1470 * @param array $fields Array of selected fields, empty for all
1471 * @param array $condition Array of fields for condition
1472 * @param array $params Array of several parameters
1474 * @return boolean|object
1478 * $fields = array("id", "uri", "uid", "network");
1480 * $condition = array("uid" => 1, "network" => 'dspr');
1482 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1484 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1486 * $data = DBA::select($table, $fields, $condition, $params);
1487 * @throws \Exception
1489 public function select($table, array $fields = [], array $condition = [], array $params = [])
1491 if (empty($table)) {
1495 if (count($fields) > 0) {
1496 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1498 $select_string = '*';
1501 $table_string = DBA::buildTableString($table);
1503 $condition_string = DBA::buildCondition($condition);
1505 $param_string = DBA::buildParameter($params);
1507 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1509 $result = $this->p($sql, $condition);
1515 * Counts the rows from a table satisfying the provided condition
1517 * @param string|array $table Table name or array [schema => table]
1518 * @param array $condition Array of fields for condition
1519 * @param array $params Array of several parameters
1526 * $condition = ["uid" => 1, "network" => 'dspr'];
1528 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1530 * $count = DBA::count($table, $condition);
1531 * @throws \Exception
1533 public function count($table, array $condition = [], array $params = [])
1535 if (empty($table)) {
1539 $table_string = DBA::buildTableString($table);
1541 $condition_string = DBA::buildCondition($condition);
1543 if (empty($params['expression'])) {
1545 } elseif (!empty($params['distinct'])) {
1546 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1548 $expression = DBA::quoteIdentifier($params['expression']);
1551 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1553 $row = $this->fetchFirst($sql, $condition);
1555 return $row['count'];
1559 * Fills an array with data from a query
1561 * @param object $stmt statement object
1562 * @param bool $do_close
1564 * @return array Data array
1566 public function toArray($stmt, $do_close = true)
1568 if (is_bool($stmt)) {
1573 while ($row = $this->fetch($stmt)) {
1578 $this->close($stmt);
1585 * Returns the error number of the last query
1587 * @return string Error number (0 if no error)
1589 public function errorNo()
1591 return $this->errorno;
1595 * Returns the error message of the last query
1597 * @return string Error message ('' if no error)
1599 public function errorMessage()
1601 return $this->error;
1605 * Closes the current statement
1607 * @param object $stmt statement object
1609 * @return boolean was the close successful?
1611 public function close($stmt)
1614 $stamp1 = microtime(true);
1616 if (!is_object($stmt)) {
1620 switch ($this->driver) {
1622 $ret = $stmt->closeCursor();
1625 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1626 // We should be careful not to assume the object type of $stmt
1627 // because DBA::p() has been able to return both types.
1628 if ($stmt instanceof mysqli_stmt) {
1629 $stmt->free_result();
1630 $ret = $stmt->close();
1631 } elseif ($stmt instanceof mysqli_result) {
1640 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1646 * Return a list of database processes
1649 * 'list' => List of processes, separated in their different states
1650 * 'amount' => Number of concurrent database processes
1651 * @throws \Exception
1653 public function processlist()
1655 $ret = $this->p("SHOW PROCESSLIST");
1656 $data = $this->toArray($ret);
1660 foreach ($data as $process) {
1661 $state = trim($process["State"]);
1663 // Filter out all non blocking processes
1664 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1671 foreach ($states as $state => $usage) {
1672 if ($statelist != "") {
1675 $statelist .= $state . ": " . $usage;
1677 return (["list" => $statelist, "amount" => $processes]);
1681 * Fetch a database variable
1683 * @param string $name
1684 * @return string content
1686 public function getVariable(string $name)
1688 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1689 return $result['Value'] ?? null;
1693 * Checks if $array is a filled array with at least one entry.
1695 * @param mixed $array A filled array with at least one entry
1697 * @return boolean Whether $array is a filled array or an object with rows
1699 public function isResult($array)
1701 // It could be a return value from an update statement
1702 if (is_bool($array)) {
1706 if (is_object($array)) {
1707 return $this->numRows($array) > 0;
1710 return (is_array($array) && (count($array) > 0));
1714 * Callback function for "esc_array"
1716 * @param mixed $value Array value
1717 * @param string $key Array key
1718 * @param boolean $add_quotation add quotation marks for string values
1722 private function escapeArrayCallback(&$value, $key, $add_quotation)
1724 if (!$add_quotation) {
1725 if (is_bool($value)) {
1726 $value = ($value ? '1' : '0');
1728 $value = $this->escape($value);
1733 if (is_bool($value)) {
1734 $value = ($value ? 'true' : 'false');
1735 } elseif (is_float($value) || is_integer($value)) {
1736 $value = (string)$value;
1738 $value = "'" . $this->escape($value) . "'";
1743 * Escapes a whole array
1745 * @param mixed $arr Array with values to be escaped
1746 * @param boolean $add_quotation add quotation marks for string values
1750 public function escapeArray(&$arr, $add_quotation = false)
1752 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);