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;
509 $this->affected_rows = 0;
511 // We have to make some things different if this function is called from "e"
512 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
514 if (isset($trace[1])) {
515 $called_from = $trace[1];
517 // We use just something that is defined to avoid warnings
518 $called_from = $trace[0];
520 // We are having an own error logging in the function "e"
521 $called_from_e = ($called_from['function'] == 'e');
523 if (!isset($this->connection)) {
524 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
527 switch ($this->driver) {
529 // If there are no arguments we use "query"
530 if ($this->emulate_prepares || count($args) == 0) {
531 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
532 $errorInfo = $this->connection->errorInfo();
533 $this->error = $errorInfo[2];
534 $this->errorno = $errorInfo[1];
538 $this->affected_rows = $retval->rowCount();
542 /** @var $stmt mysqli_stmt|PDOStatement */
543 if (!$stmt = $this->connection->prepare($sql)) {
544 $errorInfo = $this->connection->errorInfo();
545 $this->error = $errorInfo[2];
546 $this->errorno = $errorInfo[1];
551 foreach ($args AS $param => $value) {
552 if (is_int($args[$param])) {
553 $data_type = PDO::PARAM_INT;
555 $data_type = PDO::PARAM_STR;
557 $stmt->bindParam($param, $args[$param], $data_type);
560 if (!$stmt->execute()) {
561 $errorInfo = $stmt->errorInfo();
562 $this->error = $errorInfo[2];
563 $this->errorno = $errorInfo[1];
567 $this->affected_rows = $retval->rowCount();
571 // There are SQL statements that cannot be executed with a prepared statement
572 $parts = explode(' ', $orig_sql);
573 $command = strtolower($parts[0]);
574 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
576 // The fallback routine is called as well when there are no arguments
577 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
578 $retval = $this->connection->query($this->replaceParameters($sql, $args));
579 if ($this->connection->errno) {
580 $this->error = $this->connection->error;
581 $this->errorno = $this->connection->errno;
584 if (isset($retval->num_rows)) {
585 $this->affected_rows = $retval->num_rows;
587 $this->affected_rows = $this->connection->affected_rows;
593 $stmt = $this->connection->stmt_init();
595 if (!$stmt->prepare($sql)) {
596 $this->error = $stmt->error;
597 $this->errorno = $stmt->errno;
604 foreach ($args AS $param => $value) {
605 if (is_int($args[$param])) {
607 } elseif (is_float($args[$param])) {
609 } elseif (is_string($args[$param])) {
614 $values[] = &$args[$param];
617 if (count($values) > 0) {
618 array_unshift($values, $param_types);
619 call_user_func_array([$stmt, 'bind_param'], $values);
622 if (!$stmt->execute()) {
623 $this->error = $this->connection->error;
624 $this->errorno = $this->connection->errno;
627 $stmt->store_result();
629 $this->affected_rows = $retval->affected_rows;
634 // We are having an own error logging in the function "e"
635 if (($this->errorno != 0) && !$called_from_e) {
636 // We have to preserve the error code, somewhere in the logging it get lost
637 $error = $this->error;
638 $errorno = $this->errorno;
640 if ($this->testmode) {
641 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $args)));
644 $this->logger->error('DB Error', [
645 'code' => $this->errorno,
646 'error' => $this->error,
647 'callstack' => System::callstack(8),
648 'params' => $this->replaceParameters($sql, $args),
651 // On a lost connection we try to reconnect - but only once.
652 if ($errorno == 2006) {
653 if ($this->in_retrial || !$this->reconnect()) {
654 // It doesn't make sense to continue when the database connection was lost
655 if ($this->in_retrial) {
656 $this->logger->notice('Giving up retrial because of database error', [
657 'code' => $this->errorno,
658 'error' => $this->error,
661 $this->logger->notice('Couldn\'t reconnect after database error', [
662 'code' => $this->errorno,
663 'error' => $this->error,
669 $this->logger->notice('Reconnected after database error', [
670 'code' => $this->errorno,
671 'error' => $this->error,
673 $this->in_retrial = true;
674 $ret = $this->p($sql, $args);
675 $this->in_retrial = false;
680 $this->error = $error;
681 $this->errorno = $errorno;
684 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
686 if ($this->configCache->get('system', 'db_log')) {
687 $stamp2 = microtime(true);
688 $duration = (float)($stamp2 - $stamp1);
690 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
691 $duration = round($duration, 3);
692 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
694 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
695 basename($backtrace[1]["file"]) . "\t" .
696 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
697 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
704 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
706 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
708 * @param string $sql SQL statement
710 * @return boolean Was the query successfull? False is returned only if an error occurred
713 public function e($sql)
716 $stamp = microtime(true);
718 $params = DBA::getParam(func_get_args());
720 // In a case of a deadlock we are repeating the query 20 times
724 $stmt = $this->p($sql, $params);
726 if (is_bool($stmt)) {
728 } elseif (is_object($stmt)) {
736 } while (($this->errorno == 1213) && (--$timeout > 0));
738 if ($this->errorno != 0) {
739 // We have to preserve the error code, somewhere in the logging it get lost
740 $error = $this->error;
741 $errorno = $this->errorno;
743 if ($this->testmode) {
744 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $params)));
747 $this->logger->error('DB Error', [
748 'code' => $this->errorno,
749 'error' => $this->error,
750 'callstack' => System::callstack(8),
751 'params' => $this->replaceParameters($sql, $params),
754 // On a lost connection we simply quit.
755 // A reconnect like in $this->p could be dangerous with modifications
756 if ($errorno == 2006) {
757 $this->logger->notice('Giving up because of database error', [
758 'code' => $this->errorno,
759 'error' => $this->error,
764 $this->error = $error;
765 $this->errorno = $errorno;
768 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
774 * Check if data exists
776 * @param string|array $table Table name or array [schema => table]
777 * @param array $condition array of fields for condition
779 * @return boolean Are there rows for that condition?
782 public function exists($table, $condition)
790 if (empty($condition)) {
791 return DBStructure::existsTable($table);
795 $first_key = key($condition);
796 if (!is_int($first_key)) {
797 $fields = [$first_key];
800 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
802 if (is_bool($stmt)) {
805 $retval = ($this->numRows($stmt) > 0);
814 * Fetches the first row
816 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
818 * Fetches the first row
820 * @param string $sql SQL statement
822 * @return array first row of query
825 public function fetchFirst($sql)
827 $params = DBA::getParam(func_get_args());
829 $stmt = $this->p($sql, $params);
831 if (is_bool($stmt)) {
834 $retval = $this->fetch($stmt);
843 * Returns the number of affected rows of the last statement
845 * @return int Number of rows
847 public function affectedRows()
849 return $this->affected_rows;
853 * Returns the number of columns of a statement
855 * @param object Statement object
857 * @return int Number of columns
859 public function columnCount($stmt)
861 if (!is_object($stmt)) {
864 switch ($this->driver) {
866 return $stmt->columnCount();
868 return $stmt->field_count;
874 * Returns the number of rows of a statement
876 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
878 * @return int Number of rows
880 public function numRows($stmt)
882 if (!is_object($stmt)) {
885 switch ($this->driver) {
887 return $stmt->rowCount();
889 return $stmt->num_rows;
897 * @param mixed $stmt statement object
899 * @return array current row
901 public function fetch($stmt)
904 $stamp1 = microtime(true);
908 if (!is_object($stmt)) {
912 switch ($this->driver) {
914 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
917 if (get_class($stmt) == 'mysqli_result') {
918 $columns = $stmt->fetch_assoc();
922 // This code works, but is slow
924 // Bind the result to a result array
928 for ($x = 0; $x < $stmt->field_count; $x++) {
929 $cols[] = &$cols_num[$x];
932 call_user_func_array([$stmt, 'bind_result'], $cols);
934 if (!$stmt->fetch()) {
939 // We need to get the field names for the array keys
940 // It seems that there is no better way to do this.
941 $result = $stmt->result_metadata();
942 $fields = $result->fetch_fields();
944 foreach ($cols_num AS $param => $col) {
945 $columns[$fields[$param]->name] = $col;
949 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
955 * Insert a row into a table
957 * @param string|array $table Table name or array [schema => table]
958 * @param array $param parameter array
959 * @param bool $on_duplicate_update Do an update on a duplicate entry
961 * @return boolean was the insert successful?
964 public function insert($table, $param, $on_duplicate_update = false)
966 if (empty($table) || empty($param)) {
967 $this->logger->info('Table and fields have to be set');
971 $table_string = DBA::buildTableString($table);
973 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
975 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
977 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
979 if ($on_duplicate_update) {
980 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
982 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
984 $values = array_values($param);
985 $param = array_merge_recursive($values, $values);
988 return $this->e($sql, $param);
992 * Fetch the id of the last insert command
994 * @return integer Last inserted id
996 public function lastInsertId()
998 switch ($this->driver) {
1000 $id = $this->connection->lastInsertId();
1003 $id = $this->connection->insert_id;
1010 * Locks a table for exclusive write access
1012 * This function can be extended in the future to accept a table array as well.
1014 * @param string|array $table Table name or array [schema => table]
1016 * @return boolean was the lock successful?
1017 * @throws \Exception
1019 public function lock($table)
1021 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1022 if ($this->driver == 'pdo') {
1023 $this->e("SET autocommit=0");
1024 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1026 $this->connection->autocommit(false);
1029 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1031 if ($this->driver == 'pdo') {
1032 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1036 if ($this->driver == 'pdo') {
1037 $this->e("SET autocommit=1");
1039 $this->connection->autocommit(true);
1042 $this->in_transaction = true;
1048 * Unlocks all locked tables
1050 * @return boolean was the unlock successful?
1051 * @throws \Exception
1053 public function unlock()
1055 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1056 $this->performCommit();
1058 if ($this->driver == 'pdo') {
1059 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1062 $success = $this->e("UNLOCK TABLES");
1064 if ($this->driver == 'pdo') {
1065 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1066 $this->e("SET autocommit=1");
1068 $this->connection->autocommit(true);
1071 $this->in_transaction = false;
1076 * Starts a transaction
1078 * @return boolean Was the command executed successfully?
1080 public function transaction()
1082 if (!$this->performCommit()) {
1086 switch ($this->driver) {
1088 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1094 if (!$this->connection->begin_transaction()) {
1100 $this->in_transaction = true;
1104 protected function performCommit()
1106 switch ($this->driver) {
1108 if (!$this->connection->inTransaction()) {
1112 return $this->connection->commit();
1115 return $this->connection->commit();
1124 * @return boolean Was the command executed successfully?
1126 public function commit()
1128 if (!$this->performCommit()) {
1131 $this->in_transaction = false;
1138 * @return boolean Was the command executed successfully?
1140 public function rollback()
1144 switch ($this->driver) {
1146 if (!$this->connection->inTransaction()) {
1150 $ret = $this->connection->rollBack();
1154 $ret = $this->connection->rollback();
1157 $this->in_transaction = false;
1162 * Build the array with the table relations
1164 * The array is build from the database definitions in DBStructure.php
1166 * This process must only be started once, since the value is cached.
1168 private function buildRelationData()
1170 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1172 foreach ($definition AS $table => $structure) {
1173 foreach ($structure['fields'] AS $field => $field_struct) {
1174 if (isset($field_struct['relation'])) {
1175 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1176 $this->relation[$rel_table][$rel_field][$table][] = $field;
1184 * Delete a row from a table
1186 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1188 * @param string $table Table name
1189 * @param array $conditions Field condition(s)
1190 * @param array $options
1191 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1192 * relations (default: true)
1193 * @param array $callstack Internal use: prevent endless loops
1195 * @return boolean was the delete successful?
1196 * @throws \Exception
1198 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1200 if (empty($table) || empty($conditions)) {
1201 $this->logger->info('Table and conditions have to be set');
1207 // Create a key for the loop prevention
1208 $key = $table . ':' . json_encode($conditions);
1210 // We quit when this key already exists in the callstack.
1211 if (isset($callstack[$key])) {
1215 $callstack[$key] = true;
1217 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1219 // Don't use "defaults" here, since it would set "false" to "true"
1220 if (isset($options['cascade'])) {
1221 $cascade = $options['cascade'];
1226 // To speed up the whole process we cache the table relations
1227 if ($cascade && count($this->relation) == 0) {
1228 $this->buildRelationData();
1231 // Is there a relation entry for the table?
1232 if ($cascade && isset($this->relation[$table])) {
1233 // We only allow a simple "one field" relation.
1234 $field = array_keys($this->relation[$table])[0];
1235 $rel_def = array_values($this->relation[$table])[0];
1237 // Create a key for preventing double queries
1238 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1240 // When the search field is the relation field, we don't need to fetch the rows
1241 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1242 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1243 foreach ($rel_def AS $rel_table => $rel_fields) {
1244 foreach ($rel_fields AS $rel_field) {
1245 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1248 // We quit when this key already exists in the callstack.
1249 } elseif (!isset($callstack[$qkey])) {
1250 $callstack[$qkey] = true;
1252 // Fetch all rows that are to be deleted
1253 $data = $this->select($table, [$field], $conditions);
1255 while ($row = $this->fetch($data)) {
1256 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1259 $this->close($data);
1261 // Since we had split the delete command we don't need the original command anymore
1262 unset($commands[$key]);
1266 // Now we finalize the process
1267 $do_transaction = !$this->in_transaction;
1269 if ($do_transaction) {
1270 $this->transaction();
1276 foreach ($commands AS $command) {
1277 $conditions = $command['conditions'];
1279 $first_key = key($conditions);
1281 $condition_string = DBA::buildCondition($conditions);
1283 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1284 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1285 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1287 if (!$this->e($sql, $conditions)) {
1288 if ($do_transaction) {
1294 $key_table = $command['table'];
1295 $key_condition = array_keys($command['conditions'])[0];
1296 $value = array_values($command['conditions'])[0];
1298 // Split the SQL queries in chunks of 100 values
1299 // We do the $i stuff here to make the code better readable
1300 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1301 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1305 $compacted[$key_table][$key_condition][$i][$value] = $value;
1306 $counter[$key_table][$key_condition] = $i;
1309 foreach ($compacted AS $table => $values) {
1310 foreach ($values AS $field => $field_value_list) {
1311 foreach ($field_value_list AS $field_values) {
1312 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1313 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1315 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1317 if (!$this->e($sql, $field_values)) {
1318 if ($do_transaction) {
1326 if ($do_transaction) {
1335 * Updates rows in the database. When $old_fields is set to an array,
1336 * the system will only do an update if the fields in that array changed.
1339 * Only the values in $old_fields are compared.
1340 * This is an intentional behaviour.
1343 * We include the timestamp field in $fields but not in $old_fields.
1344 * Then the row will only get the new timestamp when the other fields had changed.
1346 * When $old_fields is set to a boolean value the system will do this compare itself.
1347 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1350 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1351 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1353 * @param string|array $table Table name or array [schema => table]
1354 * @param array $fields contains the fields that are updated
1355 * @param array $condition condition array with the key values
1356 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1358 * @return boolean was the update successfull?
1359 * @throws \Exception
1361 public function update($table, $fields, $condition, $old_fields = [])
1363 if (empty($table) || empty($fields) || empty($condition)) {
1364 $this->logger->info('Table, fields and condition have to be set');
1368 if (is_bool($old_fields)) {
1369 $do_insert = $old_fields;
1371 $old_fields = $this->selectFirst($table, [], $condition);
1373 if (is_bool($old_fields)) {
1375 $values = array_merge($condition, $fields);
1376 return $this->insert($table, $values, $do_insert);
1382 foreach ($old_fields AS $fieldname => $content) {
1383 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1384 unset($fields[$fieldname]);
1388 if (count($fields) == 0) {
1392 $table_string = DBA::buildTableString($table);
1394 $condition_string = DBA::buildCondition($condition);
1396 $sql = "UPDATE " . $table_string . " SET "
1397 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1398 . $condition_string;
1400 // Combines the updated fields parameter values with the condition parameter values
1401 $params = array_merge(array_values($fields), $condition);
1403 return $this->e($sql, $params);
1407 * Retrieve a single record from a table and returns it in an associative array
1409 * @param string|array $table
1410 * @param array $fields
1411 * @param array $condition
1412 * @param array $params
1414 * @return bool|array
1415 * @throws \Exception
1416 * @see $this->select
1418 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1420 $params['limit'] = 1;
1421 $result = $this->select($table, $fields, $condition, $params);
1423 if (is_bool($result)) {
1426 $row = $this->fetch($result);
1427 $this->close($result);
1433 * Select rows from a table and fills an array with the data
1435 * @param string|array $table Table name or array [schema => table]
1436 * @param array $fields Array of selected fields, empty for all
1437 * @param array $condition Array of fields for condition
1438 * @param array $params Array of several parameters
1440 * @return array Data array
1441 * @throws \Exception
1444 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1446 return $this->toArray($this->select($table, $fields, $condition, $params));
1450 * Select rows from a table
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 boolean|object
1461 * $fields = array("id", "uri", "uid", "network");
1463 * $condition = array("uid" => 1, "network" => 'dspr');
1465 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1467 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1469 * $data = DBA::select($table, $fields, $condition, $params);
1470 * @throws \Exception
1472 public function select($table, array $fields = [], array $condition = [], array $params = [])
1474 if (empty($table)) {
1478 if (count($fields) > 0) {
1479 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1481 $select_string = '*';
1484 $table_string = DBA::buildTableString($table);
1486 $condition_string = DBA::buildCondition($condition);
1488 $param_string = DBA::buildParameter($params);
1490 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1492 $result = $this->p($sql, $condition);
1498 * Counts the rows from a table satisfying the provided condition
1500 * @param string|array $table Table name or array [schema => table]
1501 * @param array $condition Array of fields for condition
1502 * @param array $params Array of several parameters
1509 * $condition = ["uid" => 1, "network" => 'dspr'];
1511 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1513 * $count = DBA::count($table, $condition);
1514 * @throws \Exception
1516 public function count($table, array $condition = [], array $params = [])
1518 if (empty($table)) {
1522 $table_string = DBA::buildTableString($table);
1524 $condition_string = DBA::buildCondition($condition);
1526 if (empty($params['expression'])) {
1528 } elseif (!empty($params['distinct'])) {
1529 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1531 $expression = DBA::quoteIdentifier($params['expression']);
1534 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1536 $row = $this->fetchFirst($sql, $condition);
1538 return $row['count'];
1542 * Fills an array with data from a query
1544 * @param object $stmt statement object
1545 * @param bool $do_close
1547 * @return array Data array
1549 public function toArray($stmt, $do_close = true)
1551 if (is_bool($stmt)) {
1556 while ($row = $this->fetch($stmt)) {
1561 $this->close($stmt);
1568 * Returns the error number of the last query
1570 * @return string Error number (0 if no error)
1572 public function errorNo()
1574 return $this->errorno;
1578 * Returns the error message of the last query
1580 * @return string Error message ('' if no error)
1582 public function errorMessage()
1584 return $this->error;
1588 * Closes the current statement
1590 * @param object $stmt statement object
1592 * @return boolean was the close successful?
1594 public function close($stmt)
1597 $stamp1 = microtime(true);
1599 if (!is_object($stmt)) {
1603 switch ($this->driver) {
1605 $ret = $stmt->closeCursor();
1608 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1609 // We should be careful not to assume the object type of $stmt
1610 // because DBA::p() has been able to return both types.
1611 if ($stmt instanceof mysqli_stmt) {
1612 $stmt->free_result();
1613 $ret = $stmt->close();
1614 } elseif ($stmt instanceof mysqli_result) {
1623 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1629 * Return a list of database processes
1632 * 'list' => List of processes, separated in their different states
1633 * 'amount' => Number of concurrent database processes
1634 * @throws \Exception
1636 public function processlist()
1638 $ret = $this->p("SHOW PROCESSLIST");
1639 $data = $this->toArray($ret);
1643 foreach ($data as $process) {
1644 $state = trim($process["State"]);
1646 // Filter out all non blocking processes
1647 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1654 foreach ($states as $state => $usage) {
1655 if ($statelist != "") {
1658 $statelist .= $state . ": " . $usage;
1660 return (["list" => $statelist, "amount" => $processes]);
1664 * Fetch a database variable
1666 * @param string $name
1667 * @return string content
1669 public function getVariable(string $name)
1671 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1672 return $result['Value'] ?? null;
1676 * Checks if $array is a filled array with at least one entry.
1678 * @param mixed $array A filled array with at least one entry
1680 * @return boolean Whether $array is a filled array or an object with rows
1682 public function isResult($array)
1684 // It could be a return value from an update statement
1685 if (is_bool($array)) {
1689 if (is_object($array)) {
1690 return $this->numRows($array) > 0;
1693 return (is_array($array) && (count($array) > 0));
1697 * Callback function for "esc_array"
1699 * @param mixed $value Array value
1700 * @param string $key Array key
1701 * @param boolean $add_quotation add quotation marks for string values
1705 private function escapeArrayCallback(&$value, $key, $add_quotation)
1707 if (!$add_quotation) {
1708 if (is_bool($value)) {
1709 $value = ($value ? '1' : '0');
1711 $value = $this->escape($value);
1716 if (is_bool($value)) {
1717 $value = ($value ? 'true' : 'false');
1718 } elseif (is_float($value) || is_integer($value)) {
1719 $value = (string)$value;
1721 $value = "'" . $this->escape($value) . "'";
1726 * Escapes a whole array
1728 * @param mixed $arr Array with values to be escaped
1729 * @param boolean $add_quotation add quotation marks for string values
1733 public function escapeArray(&$arr, $add_quotation = false)
1735 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);