3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
25 use Friendica\Core\Config\Cache;
26 use Friendica\Core\System;
28 use Friendica\Network\HTTPException\InternalServerErrorException;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Profiler;
37 use Psr\Log\LoggerInterface;
40 * This class is for the low level database stuff that does driver specific things.
44 protected $connected = false;
49 protected $configCache;
55 * @var LoggerInterface
58 protected $server_info = '';
59 /** @var PDO|mysqli */
60 protected $connection;
62 private $emulate_prepares = false;
63 private $error = false;
65 private $affected_rows = 0;
66 protected $in_transaction = false;
67 protected $in_retrial = false;
68 protected $testmode = false;
69 private $relation = [];
71 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
73 // We are storing these values for being able to perform a reconnect
74 $this->configCache = $configCache;
75 $this->profiler = $profiler;
76 $this->logger = $logger;
78 $this->readServerVariables($server);
81 if ($this->isConnected()) {
82 // Loads DB_UPDATE_VERSION constant
83 DBStructure::definition($configCache->get('system', 'basepath'), false);
87 private function readServerVariables(array $server)
89 // Use environment variables for mysql if they are set beforehand
90 if (!empty($server['MYSQL_HOST'])
91 && (!empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER'])))
92 && $server['MYSQL_PASSWORD'] !== false
93 && !empty($server['MYSQL_DATABASE']))
95 $db_host = $server['MYSQL_HOST'];
96 if (!empty($server['MYSQL_PORT'])) {
97 $db_host .= ':' . $server['MYSQL_PORT'];
99 $this->configCache->set('database', 'hostname', $db_host);
101 if (!empty($server['MYSQL_USERNAME'])) {
102 $this->configCache->set('database', 'username', $server['MYSQL_USERNAME']);
104 $this->configCache->set('database', 'username', $server['MYSQL_USER']);
106 $this->configCache->set('database', 'password', (string) $server['MYSQL_PASSWORD']);
107 $this->configCache->set('database', 'database', $server['MYSQL_DATABASE']);
111 public function connect()
113 if (!is_null($this->connection) && $this->connected()) {
114 return $this->connected;
117 // Reset connected state
118 $this->connected = false;
121 $serveraddr = trim($this->configCache->get('database', 'hostname'));
122 $serverdata = explode(':', $serveraddr);
123 $server = $serverdata[0];
124 if (count($serverdata) > 1) {
125 $port = trim($serverdata[1]);
127 $server = trim($server);
128 $user = trim($this->configCache->get('database', 'username'));
129 $pass = trim($this->configCache->get('database', 'password'));
130 $db = trim($this->configCache->get('database', 'database'));
131 $charset = trim($this->configCache->get('database', 'charset'));
133 if (!(strlen($server) && strlen($user))) {
137 $this->emulate_prepares = (bool)$this->configCache->get('database', 'emulate_prepares');
138 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
140 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
141 $this->driver = 'pdo';
142 $connect = "mysql:host=" . $server . ";dbname=" . $db;
145 $connect .= ";port=" . $port;
149 $connect .= ";charset=" . $charset;
153 $this->connection = @new PDO($connect, $user, $pass);
154 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
155 $this->connected = true;
156 } catch (PDOException $e) {
157 $this->connected = false;
161 if (!$this->connected && class_exists('\mysqli')) {
162 $this->driver = 'mysqli';
165 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
167 $this->connection = @new mysqli($server, $user, $pass, $db);
170 if (!mysqli_connect_errno()) {
171 $this->connected = true;
174 $this->connection->set_charset($charset);
179 // No suitable SQL driver was found.
180 if (!$this->connected) {
181 $this->driver = null;
182 $this->connection = null;
185 return $this->connected;
188 public function setTestmode(bool $test)
190 $this->testmode = $test;
193 * Sets the logger for DBA
195 * @note this is necessary because if we want to load the logger configuration
196 * from the DB, but there's an error, we would print out an exception.
197 * So the logger gets updated after the logger configuration can be retrieved
200 * @param LoggerInterface $logger
202 public function setLogger(LoggerInterface $logger)
204 $this->logger = $logger;
208 * Sets the profiler for DBA
210 * @param Profiler $profiler
212 public function setProfiler(Profiler $profiler)
214 $this->profiler = $profiler;
217 * Disconnects the current database connection
219 public function disconnect()
221 if (!is_null($this->connection)) {
222 switch ($this->driver) {
224 $this->connection = null;
227 $this->connection->close();
228 $this->connection = null;
233 $this->driver = null;
234 $this->connected = false;
238 * Perform a reconnect of an existing database connection
240 public function reconnect()
243 return $this->connect();
247 * Return the database object.
251 public function getConnection()
253 return $this->connection;
257 * Returns the MySQL server version string
259 * This function discriminate between the deprecated mysql API and the current
260 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
264 public function serverInfo()
266 if ($this->server_info == '') {
267 switch ($this->driver) {
269 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
272 $this->server_info = $this->connection->server_info;
276 return $this->server_info;
280 * Returns the selected database name
285 public function databaseName()
287 $ret = $this->p("SELECT DATABASE() AS `db`");
288 $data = $this->toArray($ret);
289 return $data[0]['db'];
293 * Analyze a database query and log this if some conditions are met.
295 * @param string $query The database query that will be analyzed
299 private function logIndex($query)
302 if (!$this->configCache->get('system', 'db_log_index')) {
306 // Don't explain an explain statement
307 if (strtolower(substr($query, 0, 7)) == "explain") {
311 // Only do the explain on "select", "update" and "delete"
312 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
316 $r = $this->p("EXPLAIN " . $query);
317 if (!$this->isResult($r)) {
321 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
322 $blacklist = explode(',', $this->configCache->get('system', 'db_log_index_blacklist'));
324 while ($row = $this->fetch($r)) {
325 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
326 $log = (in_array($row['key'], $watchlist) &&
327 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
332 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
336 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
341 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
342 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
343 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
344 basename($backtrace[1]["file"]) . "\t" .
345 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
346 substr($query, 0, 2000) . "\n", FILE_APPEND);
352 * Removes every not whitelisted character from the identifier string
354 * @param string $identifier
356 * @return string sanitized identifier
359 private function sanitizeIdentifier($identifier)
361 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
364 public function escape($str)
366 if ($this->connected) {
367 switch ($this->driver) {
369 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
372 return @$this->connection->real_escape_string($str);
375 return str_replace("'", "\\'", $str);
379 public function isConnected()
381 return $this->connected;
384 public function connected()
388 if (is_null($this->connection)) {
392 switch ($this->driver) {
394 $r = $this->p("SELECT 1");
395 if ($this->isResult($r)) {
396 $row = $this->toArray($r);
397 $connected = ($row[0]['1'] == '1');
401 $connected = $this->connection->ping();
409 * Replaces ANY_VALUE() function by MIN() function,
410 * if the database server does not support ANY_VALUE().
412 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
413 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
414 * A standard fall-back is to use MIN().
416 * @param string $sql An SQL string without the values
418 * @return string The input SQL string modified if necessary.
420 public function anyValueFallback($sql)
422 $server_info = $this->serverInfo();
423 if (version_compare($server_info, '5.7.5', '<') ||
424 (stripos($server_info, 'MariaDB') !== false)) {
425 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
431 * Replaces the ? placeholders with the parameters in the $args array
433 * @param string $sql SQL query
434 * @param array $args The parameters that are to replace the ? placeholders
436 * @return string The replaced SQL query
438 private function replaceParameters($sql, $args)
441 foreach ($args AS $param => $value) {
442 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
443 $replace = intval($args[$param]);
444 } elseif (is_null($args[$param])) {
447 $replace = "'" . $this->escape($args[$param]) . "'";
450 $pos = strpos($sql, '?', $offset);
451 if ($pos !== false) {
452 $sql = substr_replace($sql, $replace, $pos, 1);
454 $offset = $pos + strlen($replace);
460 * Executes a prepared statement that returns data
462 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
464 * Please only use it with complicated queries.
465 * For all regular queries please use DBA::select or DBA::exists
467 * @param string $sql SQL statement
469 * @return bool|object statement object or result object
472 public function p($sql)
475 $stamp1 = microtime(true);
477 $params = DBA::getParam(func_get_args());
479 // Renumber the array keys to be sure that they fit
482 foreach ($params AS $param) {
483 // Avoid problems with some MySQL servers and boolean values. See issue #3645
484 if (is_bool($param)) {
485 $param = (int)$param;
487 $args[++$i] = $param;
490 if (!$this->connected) {
494 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
495 // Question: Should we continue or stop the query here?
496 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
499 $sql = DBA::cleanQuery($sql);
500 $sql = $this->anyValueFallback($sql);
504 if ($this->configCache->get('system', 'db_callstack') !== null) {
505 $sql = "/*" . System::callstack() . " */ " . $sql;
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];
539 $this->affected_rows = $retval->rowCount();
543 /** @var $stmt mysqli_stmt|PDOStatement */
544 if (!$stmt = $this->connection->prepare($sql)) {
545 $errorInfo = $this->connection->errorInfo();
546 $this->error = $errorInfo[2];
547 $this->errorno = $errorInfo[1];
552 foreach ($args AS $param => $value) {
553 if (is_int($args[$param])) {
554 $data_type = PDO::PARAM_INT;
556 $data_type = PDO::PARAM_STR;
558 $stmt->bindParam($param, $args[$param], $data_type);
561 if (!$stmt->execute()) {
562 $errorInfo = $stmt->errorInfo();
563 $this->error = $errorInfo[2];
564 $this->errorno = $errorInfo[1];
568 $this->affected_rows = $retval->rowCount();
572 // There are SQL statements that cannot be executed with a prepared statement
573 $parts = explode(' ', $orig_sql);
574 $command = strtolower($parts[0]);
575 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
577 // The fallback routine is called as well when there are no arguments
578 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
579 $retval = $this->connection->query($this->replaceParameters($sql, $args));
580 if ($this->connection->errno) {
581 $this->error = $this->connection->error;
582 $this->errorno = $this->connection->errno;
585 if (isset($retval->num_rows)) {
586 $this->affected_rows = $retval->num_rows;
588 $this->affected_rows = $this->connection->affected_rows;
594 $stmt = $this->connection->stmt_init();
596 if (!$stmt->prepare($sql)) {
597 $this->error = $stmt->error;
598 $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;
628 $stmt->store_result();
630 $this->affected_rows = $retval->affected_rows;
635 // We are having an own error logging in the function "e"
636 if (($this->errorno != 0) && !$called_from_e) {
637 // We have to preserve the error code, somewhere in the logging it get lost
638 $error = $this->error;
639 $errorno = $this->errorno;
641 if ($this->testmode) {
642 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $args)));
645 $this->logger->error('DB Error', [
646 'code' => $this->errorno,
647 'error' => $this->error,
648 'callstack' => System::callstack(8),
649 'params' => $this->replaceParameters($sql, $args),
652 // On a lost connection we try to reconnect - but only once.
653 if ($errorno == 2006) {
654 if ($this->in_retrial || !$this->reconnect()) {
655 // It doesn't make sense to continue when the database connection was lost
656 if ($this->in_retrial) {
657 $this->logger->notice('Giving up retrial because of database error', [
658 'code' => $this->errorno,
659 'error' => $this->error,
662 $this->logger->notice('Couldn\'t reconnect after database error', [
663 'code' => $this->errorno,
664 'error' => $this->error,
670 $this->logger->notice('Reconnected after database error', [
671 'code' => $this->errorno,
672 'error' => $this->error,
674 $this->in_retrial = true;
675 $ret = $this->p($sql, $args);
676 $this->in_retrial = false;
681 $this->error = $error;
682 $this->errorno = $errorno;
685 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
687 if ($this->configCache->get('system', 'db_log')) {
688 $stamp2 = microtime(true);
689 $duration = (float)($stamp2 - $stamp1);
691 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
692 $duration = round($duration, 3);
693 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
695 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
696 basename($backtrace[1]["file"]) . "\t" .
697 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
698 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
705 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
707 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
709 * @param string $sql SQL statement
711 * @return boolean Was the query successfull? False is returned only if an error occurred
714 public function e($sql)
717 $stamp = microtime(true);
719 $params = DBA::getParam(func_get_args());
721 // In a case of a deadlock we are repeating the query 20 times
725 $stmt = $this->p($sql, $params);
727 if (is_bool($stmt)) {
729 } elseif (is_object($stmt)) {
737 } while (($this->errorno == 1213) && (--$timeout > 0));
739 if ($this->errorno != 0) {
740 // We have to preserve the error code, somewhere in the logging it get lost
741 $error = $this->error;
742 $errorno = $this->errorno;
744 if ($this->testmode) {
745 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $params)));
748 $this->logger->error('DB Error', [
749 'code' => $this->errorno,
750 'error' => $this->error,
751 'callstack' => System::callstack(8),
752 'params' => $this->replaceParameters($sql, $params),
755 // On a lost connection we simply quit.
756 // A reconnect like in $this->p could be dangerous with modifications
757 if ($errorno == 2006) {
758 $this->logger->notice('Giving up because of database error', [
759 'code' => $this->errorno,
760 'error' => $this->error,
765 $this->error = $error;
766 $this->errorno = $errorno;
769 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
775 * Check if data exists
777 * @param string|array $table Table name or array [schema => table]
778 * @param array $condition array of fields for condition
780 * @return boolean Are there rows for that condition?
783 public function exists($table, $condition)
791 if (empty($condition)) {
792 return DBStructure::existsTable($table);
796 $first_key = key($condition);
797 if (!is_int($first_key)) {
798 $fields = [$first_key];
801 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
803 if (is_bool($stmt)) {
806 $retval = ($this->numRows($stmt) > 0);
815 * Fetches the first row
817 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
819 * Fetches the first row
821 * @param string $sql SQL statement
823 * @return array first row of query
826 public function fetchFirst($sql)
828 $params = DBA::getParam(func_get_args());
830 $stmt = $this->p($sql, $params);
832 if (is_bool($stmt)) {
835 $retval = $this->fetch($stmt);
844 * Returns the number of affected rows of the last statement
846 * @return int Number of rows
848 public function affectedRows()
850 return $this->affected_rows;
854 * Returns the number of columns of a statement
856 * @param object Statement object
858 * @return int Number of columns
860 public function columnCount($stmt)
862 if (!is_object($stmt)) {
865 switch ($this->driver) {
867 return $stmt->columnCount();
869 return $stmt->field_count;
875 * Returns the number of rows of a statement
877 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
879 * @return int Number of rows
881 public function numRows($stmt)
883 if (!is_object($stmt)) {
886 switch ($this->driver) {
888 return $stmt->rowCount();
890 return $stmt->num_rows;
898 * @param mixed $stmt statement object
900 * @return array current row
902 public function fetch($stmt)
905 $stamp1 = microtime(true);
909 if (!is_object($stmt)) {
913 switch ($this->driver) {
915 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
918 if (get_class($stmt) == 'mysqli_result') {
919 $columns = $stmt->fetch_assoc();
923 // This code works, but is slow
925 // Bind the result to a result array
929 for ($x = 0; $x < $stmt->field_count; $x++) {
930 $cols[] = &$cols_num[$x];
933 call_user_func_array([$stmt, 'bind_result'], $cols);
935 if (!$stmt->fetch()) {
940 // We need to get the field names for the array keys
941 // It seems that there is no better way to do this.
942 $result = $stmt->result_metadata();
943 $fields = $result->fetch_fields();
945 foreach ($cols_num AS $param => $col) {
946 $columns[$fields[$param]->name] = $col;
950 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
956 * Insert a row into a table
958 * @param string|array $table Table name or array [schema => table]
959 * @param array $param parameter array
960 * @param bool $on_duplicate_update Do an update on a duplicate entry
962 * @return boolean was the insert successful?
965 public function insert($table, $param, $on_duplicate_update = false)
967 if (empty($table) || empty($param)) {
968 $this->logger->info('Table and fields have to be set');
972 $table_string = DBA::buildTableString($table);
974 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
976 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
978 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
980 if ($on_duplicate_update) {
981 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
983 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
985 $values = array_values($param);
986 $param = array_merge_recursive($values, $values);
989 return $this->e($sql, $param);
993 * Fetch the id of the last insert command
995 * @return integer Last inserted id
997 public function lastInsertId()
999 switch ($this->driver) {
1001 $id = $this->connection->lastInsertId();
1004 $id = $this->connection->insert_id;
1011 * Locks a table for exclusive write access
1013 * This function can be extended in the future to accept a table array as well.
1015 * @param string|array $table Table name or array [schema => table]
1017 * @return boolean was the lock successful?
1018 * @throws \Exception
1020 public function lock($table)
1022 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1023 if ($this->driver == 'pdo') {
1024 $this->e("SET autocommit=0");
1025 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1027 $this->connection->autocommit(false);
1030 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1032 if ($this->driver == 'pdo') {
1033 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1037 if ($this->driver == 'pdo') {
1038 $this->e("SET autocommit=1");
1040 $this->connection->autocommit(true);
1043 $this->in_transaction = true;
1049 * Unlocks all locked tables
1051 * @return boolean was the unlock successful?
1052 * @throws \Exception
1054 public function unlock()
1056 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1057 $this->performCommit();
1059 if ($this->driver == 'pdo') {
1060 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1063 $success = $this->e("UNLOCK TABLES");
1065 if ($this->driver == 'pdo') {
1066 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1067 $this->e("SET autocommit=1");
1069 $this->connection->autocommit(true);
1072 $this->in_transaction = false;
1077 * Starts a transaction
1079 * @return boolean Was the command executed successfully?
1081 public function transaction()
1083 if (!$this->performCommit()) {
1087 switch ($this->driver) {
1089 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1095 if (!$this->connection->begin_transaction()) {
1101 $this->in_transaction = true;
1105 protected function performCommit()
1107 switch ($this->driver) {
1109 if (!$this->connection->inTransaction()) {
1113 return $this->connection->commit();
1116 return $this->connection->commit();
1125 * @return boolean Was the command executed successfully?
1127 public function commit()
1129 if (!$this->performCommit()) {
1132 $this->in_transaction = false;
1139 * @return boolean Was the command executed successfully?
1141 public function rollback()
1145 switch ($this->driver) {
1147 if (!$this->connection->inTransaction()) {
1151 $ret = $this->connection->rollBack();
1155 $ret = $this->connection->rollback();
1158 $this->in_transaction = false;
1163 * Build the array with the table relations
1165 * The array is build from the database definitions in DBStructure.php
1167 * This process must only be started once, since the value is cached.
1169 private function buildRelationData()
1171 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1173 foreach ($definition AS $table => $structure) {
1174 foreach ($structure['fields'] AS $field => $field_struct) {
1175 if (isset($field_struct['relation'])) {
1176 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1177 $this->relation[$rel_table][$rel_field][$table][] = $field;
1185 * Delete a row from a table
1187 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1189 * @param string $table Table name
1190 * @param array $conditions Field condition(s)
1191 * @param array $options
1192 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1193 * relations (default: true)
1194 * @param array $callstack Internal use: prevent endless loops
1196 * @return boolean was the delete successful?
1197 * @throws \Exception
1199 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1201 if (empty($table) || empty($conditions)) {
1202 $this->logger->info('Table and conditions have to be set');
1208 // Create a key for the loop prevention
1209 $key = $table . ':' . json_encode($conditions);
1211 // We quit when this key already exists in the callstack.
1212 if (isset($callstack[$key])) {
1216 $callstack[$key] = true;
1218 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1220 // Don't use "defaults" here, since it would set "false" to "true"
1221 if (isset($options['cascade'])) {
1222 $cascade = $options['cascade'];
1227 // To speed up the whole process we cache the table relations
1228 if ($cascade && count($this->relation) == 0) {
1229 $this->buildRelationData();
1232 // Is there a relation entry for the table?
1233 if ($cascade && isset($this->relation[$table])) {
1234 // We only allow a simple "one field" relation.
1235 $field = array_keys($this->relation[$table])[0];
1236 $rel_def = array_values($this->relation[$table])[0];
1238 // Create a key for preventing double queries
1239 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1241 // When the search field is the relation field, we don't need to fetch the rows
1242 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1243 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1244 foreach ($rel_def AS $rel_table => $rel_fields) {
1245 foreach ($rel_fields AS $rel_field) {
1246 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1249 // We quit when this key already exists in the callstack.
1250 } elseif (!isset($callstack[$qkey])) {
1251 $callstack[$qkey] = true;
1253 // Fetch all rows that are to be deleted
1254 $data = $this->select($table, [$field], $conditions);
1256 while ($row = $this->fetch($data)) {
1257 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1260 $this->close($data);
1262 // Since we had split the delete command we don't need the original command anymore
1263 unset($commands[$key]);
1267 // Now we finalize the process
1268 $do_transaction = !$this->in_transaction;
1270 if ($do_transaction) {
1271 $this->transaction();
1277 foreach ($commands AS $command) {
1278 $conditions = $command['conditions'];
1280 $first_key = key($conditions);
1282 $condition_string = DBA::buildCondition($conditions);
1284 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1285 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1286 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1288 if (!$this->e($sql, $conditions)) {
1289 if ($do_transaction) {
1295 $key_table = $command['table'];
1296 $key_condition = array_keys($command['conditions'])[0];
1297 $value = array_values($command['conditions'])[0];
1299 // Split the SQL queries in chunks of 100 values
1300 // We do the $i stuff here to make the code better readable
1301 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1302 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1306 $compacted[$key_table][$key_condition][$i][$value] = $value;
1307 $counter[$key_table][$key_condition] = $i;
1310 foreach ($compacted AS $table => $values) {
1311 foreach ($values AS $field => $field_value_list) {
1312 foreach ($field_value_list AS $field_values) {
1313 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1314 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1316 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1318 if (!$this->e($sql, $field_values)) {
1319 if ($do_transaction) {
1327 if ($do_transaction) {
1336 * Updates rows in the database. When $old_fields is set to an array,
1337 * the system will only do an update if the fields in that array changed.
1340 * Only the values in $old_fields are compared.
1341 * This is an intentional behaviour.
1344 * We include the timestamp field in $fields but not in $old_fields.
1345 * Then the row will only get the new timestamp when the other fields had changed.
1347 * When $old_fields is set to a boolean value the system will do this compare itself.
1348 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1351 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1352 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1354 * @param string|array $table Table name or array [schema => table]
1355 * @param array $fields contains the fields that are updated
1356 * @param array $condition condition array with the key values
1357 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1359 * @return boolean was the update successfull?
1360 * @throws \Exception
1362 public function update($table, $fields, $condition, $old_fields = [])
1364 if (empty($table) || empty($fields) || empty($condition)) {
1365 $this->logger->info('Table, fields and condition have to be set');
1369 if (is_bool($old_fields)) {
1370 $do_insert = $old_fields;
1372 $old_fields = $this->selectFirst($table, [], $condition);
1374 if (is_bool($old_fields)) {
1376 $values = array_merge($condition, $fields);
1377 return $this->insert($table, $values, $do_insert);
1383 foreach ($old_fields AS $fieldname => $content) {
1384 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1385 unset($fields[$fieldname]);
1389 if (count($fields) == 0) {
1393 $table_string = DBA::buildTableString($table);
1395 $condition_string = DBA::buildCondition($condition);
1397 $sql = "UPDATE " . $table_string . " SET "
1398 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1399 . $condition_string;
1401 // Combines the updated fields parameter values with the condition parameter values
1402 $params = array_merge(array_values($fields), $condition);
1404 return $this->e($sql, $params);
1408 * Retrieve a single record from a table and returns it in an associative array
1410 * @param string|array $table
1411 * @param array $fields
1412 * @param array $condition
1413 * @param array $params
1415 * @return bool|array
1416 * @throws \Exception
1417 * @see $this->select
1419 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1421 $params['limit'] = 1;
1422 $result = $this->select($table, $fields, $condition, $params);
1424 if (is_bool($result)) {
1427 $row = $this->fetch($result);
1428 $this->close($result);
1434 * Select rows from a table and fills an array with the data
1436 * @param string|array $table Table name or array [schema => table]
1437 * @param array $fields Array of selected fields, empty for all
1438 * @param array $condition Array of fields for condition
1439 * @param array $params Array of several parameters
1441 * @return array Data array
1442 * @throws \Exception
1445 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1447 return $this->toArray($this->select($table, $fields, $condition, $params));
1451 * Select rows from a table
1453 * @param string|array $table Table name or array [schema => table]
1454 * @param array $fields Array of selected fields, empty for all
1455 * @param array $condition Array of fields for condition
1456 * @param array $params Array of several parameters
1458 * @return boolean|object
1462 * $fields = array("id", "uri", "uid", "network");
1464 * $condition = array("uid" => 1, "network" => 'dspr');
1466 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1468 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1470 * $data = DBA::select($table, $fields, $condition, $params);
1471 * @throws \Exception
1473 public function select($table, array $fields = [], array $condition = [], array $params = [])
1475 if (empty($table)) {
1479 if (count($fields) > 0) {
1480 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1482 $select_string = '*';
1485 $table_string = DBA::buildTableString($table);
1487 $condition_string = DBA::buildCondition($condition);
1489 $param_string = DBA::buildParameter($params);
1491 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1493 $result = $this->p($sql, $condition);
1499 * Counts the rows from a table satisfying the provided condition
1501 * @param string|array $table Table name or array [schema => table]
1502 * @param array $condition Array of fields for condition
1503 * @param array $params Array of several parameters
1510 * $condition = ["uid" => 1, "network" => 'dspr'];
1512 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1514 * $count = DBA::count($table, $condition);
1515 * @throws \Exception
1517 public function count($table, array $condition = [], array $params = [])
1519 if (empty($table)) {
1523 $table_string = DBA::buildTableString($table);
1525 $condition_string = DBA::buildCondition($condition);
1527 if (empty($params['expression'])) {
1529 } elseif (!empty($params['distinct'])) {
1530 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1532 $expression = DBA::quoteIdentifier($params['expression']);
1535 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1537 $row = $this->fetchFirst($sql, $condition);
1539 return $row['count'];
1543 * Fills an array with data from a query
1545 * @param object $stmt statement object
1546 * @param bool $do_close
1548 * @return array Data array
1550 public function toArray($stmt, $do_close = true)
1552 if (is_bool($stmt)) {
1557 while ($row = $this->fetch($stmt)) {
1562 $this->close($stmt);
1569 * Returns the error number of the last query
1571 * @return string Error number (0 if no error)
1573 public function errorNo()
1575 return $this->errorno;
1579 * Returns the error message of the last query
1581 * @return string Error message ('' if no error)
1583 public function errorMessage()
1585 return $this->error;
1589 * Closes the current statement
1591 * @param object $stmt statement object
1593 * @return boolean was the close successful?
1595 public function close($stmt)
1598 $stamp1 = microtime(true);
1600 if (!is_object($stmt)) {
1604 switch ($this->driver) {
1606 $ret = $stmt->closeCursor();
1609 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1610 // We should be careful not to assume the object type of $stmt
1611 // because DBA::p() has been able to return both types.
1612 if ($stmt instanceof mysqli_stmt) {
1613 $stmt->free_result();
1614 $ret = $stmt->close();
1615 } elseif ($stmt instanceof mysqli_result) {
1624 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1630 * Return a list of database processes
1633 * 'list' => List of processes, separated in their different states
1634 * 'amount' => Number of concurrent database processes
1635 * @throws \Exception
1637 public function processlist()
1639 $ret = $this->p("SHOW PROCESSLIST");
1640 $data = $this->toArray($ret);
1644 foreach ($data as $process) {
1645 $state = trim($process["State"]);
1647 // Filter out all non blocking processes
1648 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1655 foreach ($states as $state => $usage) {
1656 if ($statelist != "") {
1659 $statelist .= $state . ": " . $usage;
1661 return (["list" => $statelist, "amount" => $processes]);
1665 * Fetch a database variable
1667 * @param string $name
1668 * @return string content
1670 public function getVariable(string $name)
1672 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1673 return $result['Value'] ?? null;
1677 * Checks if $array is a filled array with at least one entry.
1679 * @param mixed $array A filled array with at least one entry
1681 * @return boolean Whether $array is a filled array or an object with rows
1683 public function isResult($array)
1685 // It could be a return value from an update statement
1686 if (is_bool($array)) {
1690 if (is_object($array)) {
1691 return $this->numRows($array) > 0;
1694 return (is_array($array) && (count($array) > 0));
1698 * Callback function for "esc_array"
1700 * @param mixed $value Array value
1701 * @param string $key Array key
1702 * @param boolean $add_quotation add quotation marks for string values
1706 private function escapeArrayCallback(&$value, $key, $add_quotation)
1708 if (!$add_quotation) {
1709 if (is_bool($value)) {
1710 $value = ($value ? '1' : '0');
1712 $value = $this->escape($value);
1717 if (is_bool($value)) {
1718 $value = ($value ? 'true' : 'false');
1719 } elseif (is_float($value) || is_integer($value)) {
1720 $value = (string)$value;
1722 $value = "'" . $this->escape($value) . "'";
1727 * Escapes a whole array
1729 * @param mixed $arr Array with values to be escaped
1730 * @param boolean $add_quotation add quotation marks for string values
1734 public function escapeArray(&$arr, $add_quotation = false)
1736 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);