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.
43 const MYSQLI = 'mysqli';
45 protected $connected = false;
50 protected $configCache;
56 * @var LoggerInterface
59 protected $server_info = '';
60 /** @var PDO|mysqli */
61 protected $connection;
63 protected $emulate_prepares = false;
64 protected $pdo_emulate_prepares = false;
65 private $error = false;
67 private $affected_rows = 0;
68 protected $in_transaction = false;
69 protected $in_retrial = false;
70 protected $testmode = false;
71 private $relation = [];
73 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger)
75 // We are storing these values for being able to perform a reconnect
76 $this->configCache = $configCache;
77 $this->profiler = $profiler;
78 $this->logger = $logger;
82 if ($this->isConnected()) {
83 // Loads DB_UPDATE_VERSION constant
84 DBStructure::definition($configCache->get('system', 'basepath'), false);
88 public function connect()
90 if (!is_null($this->connection) && $this->connected()) {
91 return $this->connected;
94 // Reset connected state
95 $this->connected = false;
98 $serveraddr = trim($this->configCache->get('database', 'hostname'));
99 $serverdata = explode(':', $serveraddr);
100 $server = $serverdata[0];
101 if (count($serverdata) > 1) {
102 $port = trim($serverdata[1]);
105 if (!empty(trim($this->configCache->get('database', 'port')))) {
106 $port = trim($this->configCache->get('database', 'port'));
109 $server = trim($server);
110 $user = trim($this->configCache->get('database', 'username'));
111 $pass = trim($this->configCache->get('database', 'password'));
112 $db = trim($this->configCache->get('database', 'database'));
113 $charset = trim($this->configCache->get('database', 'charset'));
115 if (!(strlen($server) && strlen($user))) {
119 $persistent = (bool)$this->configCache->get('database', 'persistent');
121 $this->emulate_prepares = (bool)$this->configCache->get('database', 'emulate_prepares');
122 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
124 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
125 $this->driver = self::PDO;
126 $connect = "mysql:host=" . $server . ";dbname=" . $db;
129 $connect .= ";port=" . $port;
133 $connect .= ";charset=" . $charset;
137 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
138 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
139 $this->connected = true;
140 } catch (PDOException $e) {
141 $this->connected = false;
145 if (!$this->connected && class_exists('\mysqli')) {
146 $this->driver = self::MYSQLI;
149 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
151 $this->connection = @new mysqli($server, $user, $pass, $db);
154 if (!mysqli_connect_errno()) {
155 $this->connected = true;
158 $this->connection->set_charset($charset);
163 // No suitable SQL driver was found.
164 if (!$this->connected) {
165 $this->driver = null;
166 $this->connection = null;
169 return $this->connected;
172 public function setTestmode(bool $test)
174 $this->testmode = $test;
177 * Sets the logger for DBA
179 * @note this is necessary because if we want to load the logger configuration
180 * from the DB, but there's an error, we would print out an exception.
181 * So the logger gets updated after the logger configuration can be retrieved
184 * @param LoggerInterface $logger
186 public function setLogger(LoggerInterface $logger)
188 $this->logger = $logger;
192 * Sets the profiler for DBA
194 * @param Profiler $profiler
196 public function setProfiler(Profiler $profiler)
198 $this->profiler = $profiler;
201 * Disconnects the current database connection
203 public function disconnect()
205 if (!is_null($this->connection)) {
206 switch ($this->driver) {
208 $this->connection = null;
211 $this->connection->close();
212 $this->connection = null;
217 $this->driver = null;
218 $this->connected = false;
222 * Perform a reconnect of an existing database connection
224 public function reconnect()
227 return $this->connect();
231 * Return the database object.
235 public function getConnection()
237 return $this->connection;
241 * Return the database driver string
243 * @return string with either "pdo" or "mysqli"
245 public function getDriver()
247 return $this->driver;
251 * Returns the MySQL server version string
253 * This function discriminate between the deprecated mysql API and the current
254 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
258 public function serverInfo()
260 if ($this->server_info == '') {
261 switch ($this->driver) {
263 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
266 $this->server_info = $this->connection->server_info;
270 return $this->server_info;
274 * Returns the selected database name
279 public function databaseName()
281 $ret = $this->p("SELECT DATABASE() AS `db`");
282 $data = $this->toArray($ret);
283 return $data[0]['db'];
287 * Analyze a database query and log this if some conditions are met.
289 * @param string $query The database query that will be analyzed
293 private function logIndex($query)
296 if (!$this->configCache->get('system', 'db_log_index')) {
300 // Don't explain an explain statement
301 if (strtolower(substr($query, 0, 7)) == "explain") {
305 // Only do the explain on "select", "update" and "delete"
306 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
310 $r = $this->p("EXPLAIN " . $query);
311 if (!$this->isResult($r)) {
315 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
316 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
318 while ($row = $this->fetch($r)) {
319 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
320 $log = (in_array($row['key'], $watchlist) &&
321 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
326 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
330 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
335 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
336 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
337 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
338 basename($backtrace[1]["file"]) . "\t" .
339 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
340 substr($query, 0, 4000) . "\n", FILE_APPEND);
346 * Removes every not allowlisted character from the identifier string
348 * @param string $identifier
350 * @return string sanitized identifier
353 private function sanitizeIdentifier($identifier)
355 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
358 public function escape($str)
360 if ($this->connected) {
361 switch ($this->driver) {
363 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
366 return @$this->connection->real_escape_string($str);
369 return str_replace("'", "\\'", $str);
373 public function isConnected()
375 return $this->connected;
378 public function connected()
382 if (is_null($this->connection)) {
386 switch ($this->driver) {
388 $r = $this->p("SELECT 1");
389 if ($this->isResult($r)) {
390 $row = $this->toArray($r);
391 $connected = ($row[0]['1'] == '1');
395 $connected = $this->connection->ping();
403 * Replaces ANY_VALUE() function by MIN() function,
404 * if the database server does not support ANY_VALUE().
406 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
407 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
408 * A standard fall-back is to use MIN().
410 * @param string $sql An SQL string without the values
412 * @return string The input SQL string modified if necessary.
414 public function anyValueFallback($sql)
416 $server_info = $this->serverInfo();
417 if (version_compare($server_info, '5.7.5', '<') ||
418 (stripos($server_info, 'MariaDB') !== false)) {
419 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
425 * Replaces the ? placeholders with the parameters in the $args array
427 * @param string $sql SQL query
428 * @param array $args The parameters that are to replace the ? placeholders
430 * @return string The replaced SQL query
432 private function replaceParameters($sql, $args)
435 foreach ($args AS $param => $value) {
436 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
437 $replace = intval($args[$param]);
438 } elseif (is_null($args[$param])) {
441 $replace = "'" . $this->escape($args[$param]) . "'";
444 $pos = strpos($sql, '?', $offset);
445 if ($pos !== false) {
446 $sql = substr_replace($sql, $replace, $pos, 1);
448 $offset = $pos + strlen($replace);
454 * Executes a prepared statement that returns data
456 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
458 * Please only use it with complicated queries.
459 * For all regular queries please use DBA::select or DBA::exists
461 * @param string $sql SQL statement
463 * @return bool|object statement object or result object
466 public function p($sql)
469 $stamp1 = microtime(true);
471 $params = DBA::getParam(func_get_args());
473 // Renumber the array keys to be sure that they fit
476 foreach ($params AS $param) {
477 // Avoid problems with some MySQL servers and boolean values. See issue #3645
478 if (is_bool($param)) {
479 $param = (int)$param;
481 $args[++$i] = $param;
484 if (!$this->connected) {
488 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
489 // Question: Should we continue or stop the query here?
490 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
493 $sql = DBA::cleanQuery($sql);
494 $sql = $this->anyValueFallback($sql);
498 if ($this->configCache->get('system', 'db_callstack') !== null) {
499 $sql = "/*" . System::callstack() . " */ " . $sql;
505 $this->affected_rows = 0;
507 // We have to make some things different if this function is called from "e"
508 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
510 if (isset($trace[1])) {
511 $called_from = $trace[1];
513 // We use just something that is defined to avoid warnings
514 $called_from = $trace[0];
516 // We are having an own error logging in the function "e"
517 $called_from_e = ($called_from['function'] == 'e');
519 if (!isset($this->connection)) {
520 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
523 switch ($this->driver) {
525 // If there are no arguments we use "query"
526 if ($this->emulate_prepares || count($args) == 0) {
527 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
528 $errorInfo = $this->connection->errorInfo();
529 $this->error = $errorInfo[2];
530 $this->errorno = $errorInfo[1];
535 $this->affected_rows = $retval->rowCount();
539 /** @var $stmt mysqli_stmt|PDOStatement */
540 if (!$stmt = $this->connection->prepare($sql)) {
541 $errorInfo = $this->connection->errorInfo();
542 $this->error = $errorInfo[2];
543 $this->errorno = $errorInfo[1];
549 foreach ($args AS $param => $value) {
550 if (is_int($args[$param])) {
551 $data_type = PDO::PARAM_INT;
553 $data_type = PDO::PARAM_STR;
555 $stmt->bindParam($param, $args[$param], $data_type);
558 if (!$stmt->execute()) {
559 $errorInfo = $stmt->errorInfo();
560 $this->error = $errorInfo[2];
561 $this->errorno = $errorInfo[1];
566 $this->affected_rows = $retval->rowCount();
570 // There are SQL statements that cannot be executed with a prepared statement
571 $parts = explode(' ', $orig_sql);
572 $command = strtolower($parts[0]);
573 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
575 // The fallback routine is called as well when there are no arguments
576 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
577 $retval = $this->connection->query($this->replaceParameters($sql, $args));
578 if ($this->connection->errno) {
579 $this->error = $this->connection->error;
580 $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;
605 foreach ($args AS $param => $value) {
606 if (is_int($args[$param])) {
608 } elseif (is_float($args[$param])) {
610 } elseif (is_string($args[$param])) {
615 $values[] = &$args[$param];
618 if (count($values) > 0) {
619 array_unshift($values, $param_types);
620 call_user_func_array([$stmt, 'bind_param'], $values);
623 if (!$stmt->execute()) {
624 $this->error = $this->connection->error;
625 $this->errorno = $this->connection->errno;
629 $stmt->store_result();
631 $this->affected_rows = $retval->affected_rows;
636 // See issue https://github.com/friendica/friendica/issues/8572
637 // Ensure that we always get an error message on an error.
638 if ($is_error && empty($this->errorno)) {
642 if ($is_error && empty($this->error)) {
643 $this->error = 'Unknown database error';
646 // We are having an own error logging in the function "e"
647 if (($this->errorno != 0) && !$called_from_e) {
648 // We have to preserve the error code, somewhere in the logging it get lost
649 $error = $this->error;
650 $errorno = $this->errorno;
652 if ($this->testmode) {
653 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
656 $this->logger->error('DB Error', [
659 'callstack' => System::callstack(8),
660 'params' => $this->replaceParameters($sql, $args),
663 // On a lost connection we try to reconnect - but only once.
664 if ($errorno == 2006) {
665 if ($this->in_retrial || !$this->reconnect()) {
666 // It doesn't make sense to continue when the database connection was lost
667 if ($this->in_retrial) {
668 $this->logger->notice('Giving up retrial because of database error', [
673 $this->logger->notice('Couldn\'t reconnect after database error', [
681 $this->logger->notice('Reconnected after database error', [
685 $this->in_retrial = true;
686 $ret = $this->p($sql, $args);
687 $this->in_retrial = false;
692 $this->error = $error;
693 $this->errorno = $errorno;
696 $this->profiler->saveTimestamp($stamp1, 'database');
698 if ($this->configCache->get('system', 'db_log')) {
699 $stamp2 = microtime(true);
700 $duration = (float)($stamp2 - $stamp1);
702 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
703 $duration = round($duration, 3);
704 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
706 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
707 basename($backtrace[1]["file"]) . "\t" .
708 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
709 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
716 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
718 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
720 * @param string $sql SQL statement
722 * @return boolean Was the query successfull? False is returned only if an error occurred
725 public function e($sql)
728 $stamp = microtime(true);
730 $params = DBA::getParam(func_get_args());
732 // In a case of a deadlock we are repeating the query 20 times
736 $stmt = $this->p($sql, $params);
738 if (is_bool($stmt)) {
740 } elseif (is_object($stmt)) {
748 } while (($this->errorno == 1213) && (--$timeout > 0));
750 if ($this->errorno != 0) {
751 // We have to preserve the error code, somewhere in the logging it get lost
752 $error = $this->error;
753 $errorno = $this->errorno;
755 if ($this->testmode) {
756 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
759 $this->logger->error('DB Error', [
762 'callstack' => System::callstack(8),
763 'params' => $this->replaceParameters($sql, $params),
766 // On a lost connection we simply quit.
767 // A reconnect like in $this->p could be dangerous with modifications
768 if ($errorno == 2006) {
769 $this->logger->notice('Giving up because of database error', [
776 $this->error = $error;
777 $this->errorno = $errorno;
780 $this->profiler->saveTimestamp($stamp, "database_write");
786 * Check if data exists
788 * @param string|array $table Table name or array [schema => table]
789 * @param array $condition array of fields for condition
791 * @return boolean Are there rows for that condition?
794 public function exists($table, $condition)
802 if (empty($condition)) {
803 return DBStructure::existsTable($table);
807 $first_key = key($condition);
808 if (!is_int($first_key)) {
809 $fields = [$first_key];
812 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
814 if (is_bool($stmt)) {
817 $retval = ($this->numRows($stmt) > 0);
826 * Fetches the first row
828 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
830 * Fetches the first row
832 * @param string $sql SQL statement
834 * @return array first row of query
837 public function fetchFirst($sql)
839 $params = DBA::getParam(func_get_args());
841 $stmt = $this->p($sql, $params);
843 if (is_bool($stmt)) {
846 $retval = $this->fetch($stmt);
855 * Returns the number of affected rows of the last statement
857 * @return int Number of rows
859 public function affectedRows()
861 return $this->affected_rows;
865 * Returns the number of columns of a statement
867 * @param object Statement object
869 * @return int Number of columns
871 public function columnCount($stmt)
873 if (!is_object($stmt)) {
876 switch ($this->driver) {
878 return $stmt->columnCount();
880 return $stmt->field_count;
886 * Returns the number of rows of a statement
888 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
890 * @return int Number of rows
892 public function numRows($stmt)
894 if (!is_object($stmt)) {
897 switch ($this->driver) {
899 return $stmt->rowCount();
901 return $stmt->num_rows;
909 * @param mixed $stmt statement object
911 * @return array current row
913 public function fetch($stmt)
916 $stamp1 = microtime(true);
920 if (!is_object($stmt)) {
924 switch ($this->driver) {
926 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
929 if (get_class($stmt) == 'mysqli_result') {
930 $columns = $stmt->fetch_assoc();
934 // This code works, but is slow
936 // Bind the result to a result array
940 for ($x = 0; $x < $stmt->field_count; $x++) {
941 $cols[] = &$cols_num[$x];
944 call_user_func_array([$stmt, 'bind_result'], $cols);
946 if (!$stmt->fetch()) {
951 // We need to get the field names for the array keys
952 // It seems that there is no better way to do this.
953 $result = $stmt->result_metadata();
954 $fields = $result->fetch_fields();
956 foreach ($cols_num AS $param => $col) {
957 $columns[$fields[$param]->name] = $col;
961 $this->profiler->saveTimestamp($stamp1, 'database');
967 * Insert a row into a table
969 * @param string|array $table Table name or array [schema => table]
970 * @param array $param parameter array
971 * @param bool $on_duplicate_update Do an update on a duplicate entry
973 * @return boolean was the insert successful?
976 public function insert($table, array $param, bool $on_duplicate_update = false)
978 if (empty($table) || empty($param)) {
979 $this->logger->info('Table and fields have to be set');
983 $table_string = DBA::buildTableString($table);
985 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
987 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
989 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
991 if ($on_duplicate_update) {
992 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
994 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
996 $values = array_values($param);
997 $param = array_merge_recursive($values, $values);
1000 return $this->e($sql, $param);
1004 * Inserts a row with the provided data in the provided table.
1005 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1007 * @param string|array $table Table name or array [schema => table]
1008 * @param array $param parameter array
1010 * @return boolean was the insert successful?
1011 * @throws \Exception
1013 public function replace($table, array $param)
1015 if (empty($table) || empty($param)) {
1016 $this->logger->info('Table and fields have to be set');
1020 $table_string = DBA::buildTableString($table);
1022 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1024 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1026 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1028 return $this->e($sql, $param);
1032 * Fetch the id of the last insert command
1034 * @return integer Last inserted id
1036 public function lastInsertId()
1038 switch ($this->driver) {
1040 $id = $this->connection->lastInsertId();
1043 $id = $this->connection->insert_id;
1050 * Locks a table for exclusive write access
1052 * This function can be extended in the future to accept a table array as well.
1054 * @param string|array $table Table name or array [schema => table]
1056 * @return boolean was the lock successful?
1057 * @throws \Exception
1059 public function lock($table)
1061 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1062 if ($this->driver == self::PDO) {
1063 $this->e("SET autocommit=0");
1064 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1066 $this->connection->autocommit(false);
1069 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1071 if ($this->driver == self::PDO) {
1072 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1076 if ($this->driver == self::PDO) {
1077 $this->e("SET autocommit=1");
1079 $this->connection->autocommit(true);
1082 $this->in_transaction = true;
1088 * Unlocks all locked tables
1090 * @return boolean was the unlock successful?
1091 * @throws \Exception
1093 public function unlock()
1095 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1096 $this->performCommit();
1098 if ($this->driver == self::PDO) {
1099 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1102 $success = $this->e("UNLOCK TABLES");
1104 if ($this->driver == self::PDO) {
1105 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1106 $this->e("SET autocommit=1");
1108 $this->connection->autocommit(true);
1111 $this->in_transaction = false;
1116 * Starts a transaction
1118 * @return boolean Was the command executed successfully?
1120 public function transaction()
1122 if (!$this->performCommit()) {
1126 switch ($this->driver) {
1128 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1134 if (!$this->connection->begin_transaction()) {
1140 $this->in_transaction = true;
1144 protected function performCommit()
1146 switch ($this->driver) {
1148 if (!$this->connection->inTransaction()) {
1152 return $this->connection->commit();
1155 return $this->connection->commit();
1164 * @return boolean Was the command executed successfully?
1166 public function commit()
1168 if (!$this->performCommit()) {
1171 $this->in_transaction = false;
1178 * @return boolean Was the command executed successfully?
1180 public function rollback()
1184 switch ($this->driver) {
1186 if (!$this->connection->inTransaction()) {
1190 $ret = $this->connection->rollBack();
1194 $ret = $this->connection->rollback();
1197 $this->in_transaction = false;
1202 * Build the array with the table relations
1204 * The array is build from the database definitions in DBStructure.php
1206 * This process must only be started once, since the value is cached.
1208 private function buildRelationData()
1210 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1212 foreach ($definition AS $table => $structure) {
1213 foreach ($structure['fields'] AS $field => $field_struct) {
1214 if (isset($field_struct['relation'])) {
1215 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1216 $this->relation[$rel_table][$rel_field][$table][] = $field;
1224 * Delete a row from a table
1226 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1228 * @param string $table Table name
1229 * @param array $conditions Field condition(s)
1230 * @param array $options
1231 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1232 * relations (default: true)
1233 * @param array $callstack Internal use: prevent endless loops
1235 * @return boolean was the delete successful?
1236 * @throws \Exception
1238 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1240 if (empty($table) || empty($conditions)) {
1241 $this->logger->info('Table and conditions have to be set');
1247 // Create a key for the loop prevention
1248 $key = $table . ':' . json_encode($conditions);
1250 // We quit when this key already exists in the callstack.
1251 if (isset($callstack[$key])) {
1255 $callstack[$key] = true;
1257 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1259 // Don't use "defaults" here, since it would set "false" to "true"
1260 if (isset($options['cascade'])) {
1261 $cascade = $options['cascade'];
1266 // To speed up the whole process we cache the table relations
1267 if ($cascade && count($this->relation) == 0) {
1268 $this->buildRelationData();
1271 // Is there a relation entry for the table?
1272 if ($cascade && isset($this->relation[$table])) {
1273 // We only allow a simple "one field" relation.
1274 $field = array_keys($this->relation[$table])[0];
1275 $rel_def = array_values($this->relation[$table])[0];
1277 // Create a key for preventing double queries
1278 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1280 // When the search field is the relation field, we don't need to fetch the rows
1281 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1282 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1283 foreach ($rel_def AS $rel_table => $rel_fields) {
1284 foreach ($rel_fields AS $rel_field) {
1285 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1288 // We quit when this key already exists in the callstack.
1289 } elseif (!isset($callstack[$qkey])) {
1290 $callstack[$qkey] = true;
1292 // Fetch all rows that are to be deleted
1293 $data = $this->select($table, [$field], $conditions);
1295 while ($row = $this->fetch($data)) {
1296 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1299 $this->close($data);
1301 // Since we had split the delete command we don't need the original command anymore
1302 unset($commands[$key]);
1306 // Now we finalize the process
1307 $do_transaction = !$this->in_transaction;
1309 if ($do_transaction) {
1310 $this->transaction();
1316 foreach ($commands AS $command) {
1317 $conditions = $command['conditions'];
1319 $first_key = key($conditions);
1321 $condition_string = DBA::buildCondition($conditions);
1323 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1324 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1325 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1327 if (!$this->e($sql, $conditions)) {
1328 if ($do_transaction) {
1334 $key_table = $command['table'];
1335 $key_condition = array_keys($command['conditions'])[0];
1336 $value = array_values($command['conditions'])[0];
1338 // Split the SQL queries in chunks of 100 values
1339 // We do the $i stuff here to make the code better readable
1340 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1341 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1345 $compacted[$key_table][$key_condition][$i][$value] = $value;
1346 $counter[$key_table][$key_condition] = $i;
1349 foreach ($compacted AS $table => $values) {
1350 foreach ($values AS $field => $field_value_list) {
1351 foreach ($field_value_list AS $field_values) {
1352 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1353 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1355 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1357 if (!$this->e($sql, $field_values)) {
1358 if ($do_transaction) {
1366 if ($do_transaction) {
1375 * Updates rows in the database. When $old_fields is set to an array,
1376 * the system will only do an update if the fields in that array changed.
1379 * Only the values in $old_fields are compared.
1380 * This is an intentional behaviour.
1383 * We include the timestamp field in $fields but not in $old_fields.
1384 * Then the row will only get the new timestamp when the other fields had changed.
1386 * When $old_fields is set to a boolean value the system will do this compare itself.
1387 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1390 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1391 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1393 * @param string|array $table Table name or array [schema => table]
1394 * @param array $fields contains the fields that are updated
1395 * @param array $condition condition array with the key values
1396 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1398 * @return boolean was the update successfull?
1399 * @throws \Exception
1401 public function update($table, $fields, $condition, $old_fields = [])
1403 if (empty($table) || empty($fields) || empty($condition)) {
1404 $this->logger->info('Table, fields and condition have to be set');
1408 if (is_bool($old_fields)) {
1409 $do_insert = $old_fields;
1411 $old_fields = $this->selectFirst($table, [], $condition);
1413 if (is_bool($old_fields)) {
1415 $values = array_merge($condition, $fields);
1416 return $this->replace($table, $values);
1422 foreach ($old_fields AS $fieldname => $content) {
1423 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1424 unset($fields[$fieldname]);
1428 if (count($fields) == 0) {
1432 $table_string = DBA::buildTableString($table);
1434 $condition_string = DBA::buildCondition($condition);
1436 $sql = "UPDATE " . $table_string . " SET "
1437 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1438 . $condition_string;
1440 // Combines the updated fields parameter values with the condition parameter values
1441 $params = array_merge(array_values($fields), $condition);
1443 return $this->e($sql, $params);
1447 * Retrieve a single record from a table and returns it in an associative array
1449 * @param string|array $table
1450 * @param array $fields
1451 * @param array $condition
1452 * @param array $params
1454 * @return bool|array
1455 * @throws \Exception
1456 * @see $this->select
1458 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1460 $params['limit'] = 1;
1461 $result = $this->select($table, $fields, $condition, $params);
1463 if (is_bool($result)) {
1466 $row = $this->fetch($result);
1467 $this->close($result);
1473 * Select rows from a table and fills an array with the data
1475 * @param string|array $table Table name or array [schema => table]
1476 * @param array $fields Array of selected fields, empty for all
1477 * @param array $condition Array of fields for condition
1478 * @param array $params Array of several parameters
1480 * @return array Data array
1481 * @throws \Exception
1484 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1486 return $this->toArray($this->select($table, $fields, $condition, $params));
1490 * Select rows from a table
1496 * $table = ['schema' => 'table'];
1497 * @see DBA::buildTableString()
1499 * $fields = ['id', 'uri', 'uid', 'network'];
1501 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1503 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1504 * @see DBA::buildCondition()
1506 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1507 * @see DBA::buildParameter()
1509 * $data = DBA::select($table, $fields, $condition, $params);
1511 * @param string|array $table Table name or array [schema => table]
1512 * @param array $fields Array of selected fields, empty for all
1513 * @param array $condition Array of fields for condition
1514 * @param array $params Array of several parameters
1515 * @return boolean|object
1516 * @throws \Exception
1518 public function select($table, array $fields = [], array $condition = [], array $params = [])
1520 if (empty($table)) {
1524 if (count($fields) > 0) {
1525 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1527 $select_string = '*';
1530 $table_string = DBA::buildTableString($table);
1532 $condition_string = DBA::buildCondition($condition);
1534 $param_string = DBA::buildParameter($params);
1536 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1538 $result = $this->p($sql, $condition);
1544 * Counts the rows from a table satisfying the provided condition
1546 * @param string|array $table Table name or array [schema => table]
1547 * @param array $condition Array of fields for condition
1548 * @param array $params Array of several parameters
1555 * $condition = ["uid" => 1, "network" => 'dspr'];
1557 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1559 * $count = DBA::count($table, $condition);
1560 * @throws \Exception
1562 public function count($table, array $condition = [], array $params = [])
1564 if (empty($table)) {
1568 $table_string = DBA::buildTableString($table);
1570 $condition_string = DBA::buildCondition($condition);
1572 if (empty($params['expression'])) {
1574 } elseif (!empty($params['distinct'])) {
1575 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1577 $expression = DBA::quoteIdentifier($params['expression']);
1580 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1582 $row = $this->fetchFirst($sql, $condition);
1584 return $row['count'];
1588 * Fills an array with data from a query
1590 * @param object $stmt statement object
1591 * @param bool $do_close
1593 * @return array Data array
1595 public function toArray($stmt, $do_close = true)
1597 if (is_bool($stmt)) {
1602 while ($row = $this->fetch($stmt)) {
1607 $this->close($stmt);
1614 * Returns the error number of the last query
1616 * @return string Error number (0 if no error)
1618 public function errorNo()
1620 return $this->errorno;
1624 * Returns the error message of the last query
1626 * @return string Error message ('' if no error)
1628 public function errorMessage()
1630 return $this->error;
1634 * Closes the current statement
1636 * @param object $stmt statement object
1638 * @return boolean was the close successful?
1640 public function close($stmt)
1643 $stamp1 = microtime(true);
1645 if (!is_object($stmt)) {
1649 switch ($this->driver) {
1651 $ret = $stmt->closeCursor();
1654 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1655 // We should be careful not to assume the object type of $stmt
1656 // because DBA::p() has been able to return both types.
1657 if ($stmt instanceof mysqli_stmt) {
1658 $stmt->free_result();
1659 $ret = $stmt->close();
1660 } elseif ($stmt instanceof mysqli_result) {
1669 $this->profiler->saveTimestamp($stamp1, 'database');
1675 * Return a list of database processes
1678 * 'list' => List of processes, separated in their different states
1679 * 'amount' => Number of concurrent database processes
1680 * @throws \Exception
1682 public function processlist()
1684 $ret = $this->p("SHOW PROCESSLIST");
1685 $data = $this->toArray($ret);
1689 foreach ($data as $process) {
1690 $state = trim($process["State"]);
1692 // Filter out all non blocking processes
1693 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1700 foreach ($states as $state => $usage) {
1701 if ($statelist != "") {
1704 $statelist .= $state . ": " . $usage;
1706 return (["list" => $statelist, "amount" => $processes]);
1710 * Fetch a database variable
1712 * @param string $name
1713 * @return string content
1715 public function getVariable(string $name)
1717 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1718 return $result['Value'] ?? null;
1722 * Checks if $array is a filled array with at least one entry.
1724 * @param mixed $array A filled array with at least one entry
1726 * @return boolean Whether $array is a filled array or an object with rows
1728 public function isResult($array)
1730 // It could be a return value from an update statement
1731 if (is_bool($array)) {
1735 if (is_object($array)) {
1736 return $this->numRows($array) > 0;
1739 return (is_array($array) && (count($array) > 0));
1743 * Callback function for "esc_array"
1745 * @param mixed $value Array value
1746 * @param string $key Array key
1747 * @param boolean $add_quotation add quotation marks for string values
1751 private function escapeArrayCallback(&$value, $key, $add_quotation)
1753 if (!$add_quotation) {
1754 if (is_bool($value)) {
1755 $value = ($value ? '1' : '0');
1757 $value = $this->escape($value);
1762 if (is_bool($value)) {
1763 $value = ($value ? 'true' : 'false');
1764 } elseif (is_float($value) || is_integer($value)) {
1765 $value = (string)$value;
1767 $value = "'" . $this->escape($value) . "'";
1772 * Escapes a whole array
1774 * @param mixed $arr Array with values to be escaped
1775 * @param boolean $add_quotation add quotation marks for string values
1779 public function escapeArray(&$arr, $add_quotation = false)
1781 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);