3 * @copyright Copyright (C) 2010-2022, the Friendica project
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\ValueObject\Cache;
25 use Friendica\Core\System;
26 use Friendica\Network\HTTPException\ServiceUnavailableException;
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 const INSERT_DEFAULT = 0;
46 const INSERT_UPDATE = 1;
47 const INSERT_IGNORE = 2;
49 protected $connected = false;
52 * @var \Friendica\Core\Config\ValueObject\Cache
54 protected $configCache;
60 * @var LoggerInterface
63 protected $server_info = '';
64 /** @var PDO|mysqli */
65 protected $connection;
67 protected $pdo_emulate_prepares = false;
68 private $error = false;
70 private $affected_rows = 0;
71 protected $in_transaction = false;
72 protected $in_retrial = false;
73 protected $testmode = false;
74 private $relation = [];
76 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger)
78 // We are storing these values for being able to perform a reconnect
79 $this->configCache = $configCache;
80 $this->profiler = $profiler;
81 $this->logger = $logger;
85 if ($this->isConnected()) {
86 // Loads DB_UPDATE_VERSION constant
87 DBStructure::definition($configCache->get('system', 'basepath'), false);
91 public function connect()
93 if (!is_null($this->connection) && $this->connected()) {
94 return $this->connected;
97 // Reset connected state
98 $this->connected = false;
101 $serveraddr = trim($this->configCache->get('database', 'hostname'));
102 $serverdata = explode(':', $serveraddr);
103 $server = $serverdata[0];
104 if (count($serverdata) > 1) {
105 $port = trim($serverdata[1]);
108 if (!empty(trim($this->configCache->get('database', 'port')))) {
109 $port = trim($this->configCache->get('database', 'port'));
112 $server = trim($server);
113 $user = trim($this->configCache->get('database', 'username'));
114 $pass = trim($this->configCache->get('database', 'password'));
115 $db = trim($this->configCache->get('database', 'database'));
116 $charset = trim($this->configCache->get('database', 'charset'));
117 $socket = trim($this->configCache->get('database', 'socket'));
119 if (!(strlen($server) && strlen($user))) {
123 $persistent = (bool)$this->configCache->get('database', 'persistent');
125 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
127 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
128 $this->driver = self::PDO;
129 $connect = "mysql:host=" . $server . ";dbname=" . $db;
132 $connect .= ";port=" . $port;
136 $connect .= ";charset=" . $charset;
140 $connect .= ";$unix_socket=" . $socket;
144 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
145 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
146 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
147 $this->connected = true;
148 } catch (PDOException $e) {
149 $this->connected = false;
153 if (!$this->connected && class_exists('\mysqli')) {
154 $this->driver = self::MYSQLI;
157 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
159 $this->connection = @new mysqli($server, $user, $pass, $db);
162 if (!mysqli_connect_errno()) {
163 $this->connected = true;
166 $this->connection->set_charset($charset);
170 $this->connection->set_socket($socket);
176 // No suitable SQL driver was found.
177 if (!$this->connected) {
178 $this->driver = null;
179 $this->connection = null;
182 return $this->connected;
185 public function setTestmode(bool $test)
187 $this->testmode = $test;
190 * Sets the logger for DBA
192 * @note this is necessary because if we want to load the logger configuration
193 * from the DB, but there's an error, we would print out an exception.
194 * So the logger gets updated after the logger configuration can be retrieved
197 * @param LoggerInterface $logger
199 public function setLogger(LoggerInterface $logger)
201 $this->logger = $logger;
205 * Sets the profiler for DBA
207 * @param Profiler $profiler
209 public function setProfiler(Profiler $profiler)
211 $this->profiler = $profiler;
214 * Disconnects the current database connection
216 public function disconnect()
218 if (!is_null($this->connection)) {
219 switch ($this->driver) {
221 $this->connection = null;
224 $this->connection->close();
225 $this->connection = null;
230 $this->driver = null;
231 $this->connected = false;
235 * Perform a reconnect of an existing database connection
237 public function reconnect()
240 return $this->connect();
244 * Return the database object.
248 public function getConnection()
250 return $this->connection;
254 * Return the database driver string
256 * @return string with either "pdo" or "mysqli"
258 public function getDriver()
260 return $this->driver;
264 * Returns the MySQL server version string
266 * This function discriminate between the deprecated mysql API and the current
267 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
271 public function serverInfo()
273 if ($this->server_info == '') {
274 switch ($this->driver) {
276 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
279 $this->server_info = $this->connection->server_info;
283 return $this->server_info;
287 * Returns the selected database name
292 public function databaseName()
294 $ret = $this->p("SELECT DATABASE() AS `db`");
295 $data = $this->toArray($ret);
296 return $data[0]['db'];
300 * Analyze a database query and log this if some conditions are met.
302 * @param string $query The database query that will be analyzed
306 private function logIndex($query)
309 if (!$this->configCache->get('system', 'db_log_index')) {
313 // Don't explain an explain statement
314 if (strtolower(substr($query, 0, 7)) == "explain") {
318 // Only do the explain on "select", "update" and "delete"
319 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
323 $r = $this->p("EXPLAIN " . $query);
324 if (!$this->isResult($r)) {
328 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
329 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
331 while ($row = $this->fetch($r)) {
332 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
333 $log = (in_array($row['key'], $watchlist) &&
334 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
339 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
343 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
348 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
349 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
350 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
351 basename($backtrace[1]["file"]) . "\t" .
352 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
353 substr($query, 0, 4000) . "\n", FILE_APPEND);
359 * Removes every not allowlisted character from the identifier string
361 * @param string $identifier
363 * @return string sanitized identifier
366 private function sanitizeIdentifier($identifier)
368 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
371 public function escape($str)
373 if ($this->connected) {
374 switch ($this->driver) {
376 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
379 return @$this->connection->real_escape_string($str);
382 return str_replace("'", "\\'", $str);
386 public function isConnected()
388 return $this->connected;
391 public function connected()
395 if (is_null($this->connection)) {
399 switch ($this->driver) {
401 $r = $this->p("SELECT 1");
402 if ($this->isResult($r)) {
403 $row = $this->toArray($r);
404 $connected = ($row[0]['1'] == '1');
408 $connected = $this->connection->ping();
416 * Replaces ANY_VALUE() function by MIN() function,
417 * if the database server does not support ANY_VALUE().
419 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
420 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
421 * A standard fall-back is to use MIN().
423 * @param string $sql An SQL string without the values
425 * @return string The input SQL string modified if necessary.
427 public function anyValueFallback($sql)
429 $server_info = $this->serverInfo();
430 if (version_compare($server_info, '5.7.5', '<') ||
431 (stripos($server_info, 'MariaDB') !== false)) {
432 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
438 * Replaces the ? placeholders with the parameters in the $args array
440 * @param string $sql SQL query
441 * @param array $args The parameters that are to replace the ? placeholders
443 * @return string The replaced SQL query
445 private function replaceParameters($sql, $args)
448 foreach ($args as $param => $value) {
449 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
450 $replace = intval($args[$param]);
451 } elseif (is_null($args[$param])) {
454 $replace = "'" . $this->escape($args[$param]) . "'";
457 $pos = strpos($sql, '?', $offset);
458 if ($pos !== false) {
459 $sql = substr_replace($sql, $replace, $pos, 1);
461 $offset = $pos + strlen($replace);
467 * Executes a prepared statement that returns data
469 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
471 * Please only use it with complicated queries.
472 * For all regular queries please use DBA::select or DBA::exists
474 * @param string $sql SQL statement
476 * @return bool|object statement object or result object
479 public function p($sql)
482 $this->profiler->startRecording('database');
483 $stamp1 = microtime(true);
485 $params = DBA::getParam(func_get_args());
487 // Renumber the array keys to be sure that they fit
490 foreach ($params as $param) {
491 // Avoid problems with some MySQL servers and boolean values. See issue #3645
492 if (is_bool($param)) {
493 $param = (int)$param;
495 $args[++$i] = $param;
498 if (!$this->connected) {
502 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
503 // Question: Should we continue or stop the query here?
504 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
507 $sql = DBA::cleanQuery($sql);
508 $sql = $this->anyValueFallback($sql);
512 if ($this->configCache->get('system', 'db_callstack') !== null) {
513 $sql = "/*" . System::callstack() . " */ " . $sql;
519 $this->affected_rows = 0;
521 // We have to make some things different if this function is called from "e"
522 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
524 if (isset($trace[1])) {
525 $called_from = $trace[1];
527 // We use just something that is defined to avoid warnings
528 $called_from = $trace[0];
530 // We are having an own error logging in the function "e"
531 $called_from_e = ($called_from['function'] == 'e');
533 if (!isset($this->connection)) {
534 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
537 switch ($this->driver) {
539 // If there are no arguments we use "query"
540 if (count($args) == 0) {
541 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
542 $errorInfo = $this->connection->errorInfo();
543 $this->error = $errorInfo[2];
544 $this->errorno = $errorInfo[1];
549 $this->affected_rows = $retval->rowCount();
553 /** @var $stmt mysqli_stmt|PDOStatement */
554 if (!$stmt = $this->connection->prepare($sql)) {
555 $errorInfo = $this->connection->errorInfo();
556 $this->error = $errorInfo[2];
557 $this->errorno = $errorInfo[1];
563 foreach (array_keys($args) as $param) {
564 $data_type = PDO::PARAM_STR;
565 if (is_int($args[$param])) {
566 $data_type = PDO::PARAM_INT;
567 } elseif ($args[$param] !== null) {
568 $args[$param] = (string)$args[$param];
571 $stmt->bindParam($param, $args[$param], $data_type);
574 if (!$stmt->execute()) {
575 $errorInfo = $stmt->errorInfo();
576 $this->error = $errorInfo[2];
577 $this->errorno = $errorInfo[1];
582 $this->affected_rows = $retval->rowCount();
586 // There are SQL statements that cannot be executed with a prepared statement
587 $parts = explode(' ', $orig_sql);
588 $command = strtolower($parts[0]);
589 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
591 // The fallback routine is called as well when there are no arguments
592 if (!$can_be_prepared || (count($args) == 0)) {
593 $retval = $this->connection->query($this->replaceParameters($sql, $args));
594 if ($this->connection->errno) {
595 $this->error = $this->connection->error;
596 $this->errorno = $this->connection->errno;
600 if (isset($retval->num_rows)) {
601 $this->affected_rows = $retval->num_rows;
603 $this->affected_rows = $this->connection->affected_rows;
609 $stmt = $this->connection->stmt_init();
611 if (!$stmt->prepare($sql)) {
612 $this->error = $stmt->error;
613 $this->errorno = $stmt->errno;
621 foreach (array_keys($args) as $param) {
622 if (is_int($args[$param])) {
624 } elseif (is_float($args[$param])) {
626 } elseif (is_string($args[$param])) {
628 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
630 $args[$param] = (string)$args[$param];
634 $values[] = &$args[$param];
637 if (count($values) > 0) {
638 array_unshift($values, $param_types);
639 call_user_func_array([$stmt, 'bind_param'], $values);
642 if (!$stmt->execute()) {
643 $this->error = $this->connection->error;
644 $this->errorno = $this->connection->errno;
648 $stmt->store_result();
650 $this->affected_rows = $retval->affected_rows;
655 // See issue https://github.com/friendica/friendica/issues/8572
656 // Ensure that we always get an error message on an error.
657 if ($is_error && empty($this->errorno)) {
661 if ($is_error && empty($this->error)) {
662 $this->error = 'Unknown database error';
665 // We are having an own error logging in the function "e"
666 if (($this->errorno != 0) && !$called_from_e) {
667 // We have to preserve the error code, somewhere in the logging it get lost
668 $error = $this->error;
669 $errorno = $this->errorno;
671 if ($this->testmode) {
672 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
675 $this->logger->error('DB Error', [
678 'callstack' => System::callstack(8),
679 'params' => $this->replaceParameters($sql, $args),
682 // On a lost connection we try to reconnect - but only once.
683 if ($errorno == 2006) {
684 if ($this->in_retrial || !$this->reconnect()) {
685 // It doesn't make sense to continue when the database connection was lost
686 if ($this->in_retrial) {
687 $this->logger->notice('Giving up retrial because of database error', [
692 $this->logger->notice('Couldn\'t reconnect after database error', [
700 $this->logger->notice('Reconnected after database error', [
704 $this->in_retrial = true;
705 $ret = $this->p($sql, $args);
706 $this->in_retrial = false;
711 $this->error = $error;
712 $this->errorno = $errorno;
715 $this->profiler->stopRecording();
717 if ($this->configCache->get('system', 'db_log')) {
718 $stamp2 = microtime(true);
719 $duration = (float)($stamp2 - $stamp1);
721 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
722 $duration = round($duration, 3);
723 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
725 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
726 basename($backtrace[1]["file"]) . "\t" .
727 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
728 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
735 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
737 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
739 * @param string $sql SQL statement
741 * @return boolean Was the query successfull? False is returned only if an error occurred
744 public function e($sql)
747 $this->profiler->startRecording('database_write');
749 $params = DBA::getParam(func_get_args());
751 // In a case of a deadlock we are repeating the query 20 times
755 $stmt = $this->p($sql, $params);
757 if (is_bool($stmt)) {
759 } elseif (is_object($stmt)) {
767 } while (($this->errorno == 1213) && (--$timeout > 0));
769 if ($this->errorno != 0) {
770 // We have to preserve the error code, somewhere in the logging it get lost
771 $error = $this->error;
772 $errorno = $this->errorno;
774 if ($this->testmode) {
775 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
778 $this->logger->error('DB Error', [
781 'callstack' => System::callstack(8),
782 'params' => $this->replaceParameters($sql, $params),
785 // On a lost connection we simply quit.
786 // A reconnect like in $this->p could be dangerous with modifications
787 if ($errorno == 2006) {
788 $this->logger->notice('Giving up because of database error', [
795 $this->error = $error;
796 $this->errorno = $errorno;
799 $this->profiler->stopRecording();
805 * Check if data exists
807 * @param string|array $table Table name or array [schema => table]
808 * @param array $condition array of fields for condition
810 * @return boolean Are there rows for that condition?
813 public function exists($table, $condition)
821 if (empty($condition)) {
822 return DBStructure::existsTable($table);
826 $first_key = key($condition);
827 if (!is_int($first_key)) {
828 $fields = [$first_key];
831 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
833 if (is_bool($stmt)) {
836 $retval = ($this->numRows($stmt) > 0);
845 * Fetches the first row
847 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
849 * Fetches the first row
851 * @param string $sql SQL statement
853 * @return array first row of query
856 public function fetchFirst($sql)
858 $params = DBA::getParam(func_get_args());
860 $stmt = $this->p($sql, $params);
862 if (is_bool($stmt)) {
865 $retval = $this->fetch($stmt);
874 * Returns the number of affected rows of the last statement
876 * @return int Number of rows
878 public function affectedRows()
880 return $this->affected_rows;
884 * Returns the number of columns of a statement
886 * @param object Statement object
888 * @return int Number of columns
890 public function columnCount($stmt)
892 if (!is_object($stmt)) {
895 switch ($this->driver) {
897 return $stmt->columnCount();
899 return $stmt->field_count;
905 * Returns the number of rows of a statement
907 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
909 * @return int Number of rows
911 public function numRows($stmt)
913 if (!is_object($stmt)) {
916 switch ($this->driver) {
918 return $stmt->rowCount();
920 return $stmt->num_rows;
928 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
930 * @return array|false current row
932 public function fetch($stmt)
934 $this->profiler->startRecording('database');
938 if (!is_object($stmt)) {
942 switch ($this->driver) {
944 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
945 if (!empty($stmt->table) && is_array($columns)) {
946 $columns = $this->castFields($stmt->table, $columns);
950 if (get_class($stmt) == 'mysqli_result') {
951 $columns = $stmt->fetch_assoc() ?? false;
955 // This code works, but is slow
957 // Bind the result to a result array
961 for ($x = 0; $x < $stmt->field_count; $x++) {
962 $cols[] = &$cols_num[$x];
965 call_user_func_array([$stmt, 'bind_result'], $cols);
967 if (!$stmt->fetch()) {
972 // We need to get the field names for the array keys
973 // It seems that there is no better way to do this.
974 $result = $stmt->result_metadata();
975 $fields = $result->fetch_fields();
977 foreach ($cols_num as $param => $col) {
978 $columns[$fields[$param]->name] = $col;
982 $this->profiler->stopRecording();
988 * Insert a row into a table. Field value objects will be cast as string.
990 * @param string|array $table Table name or array [schema => table]
991 * @param array $param parameter array
992 * @param int $duplicate_mode What to do on a duplicated entry
994 * @return boolean was the insert successful?
997 public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT)
999 if (empty($table) || empty($param)) {
1000 $this->logger->info('Table and fields have to be set');
1004 $param = $this->castFields($table, $param);
1006 $table_string = DBA::buildTableString($table);
1008 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1010 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1014 if ($duplicate_mode == self::INSERT_IGNORE) {
1018 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1020 if ($duplicate_mode == self::INSERT_UPDATE) {
1021 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1023 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1025 $values = array_values($param);
1026 $param = array_merge_recursive($values, $values);
1029 $result = $this->e($sql, $param);
1030 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1034 return $this->affectedRows() != 0;
1038 * Inserts a row with the provided data in the provided table.
1039 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1041 * @param string|array $table Table name or array [schema => table]
1042 * @param array $param parameter array
1044 * @return boolean was the insert successful?
1045 * @throws \Exception
1047 public function replace($table, array $param)
1049 if (empty($table) || empty($param)) {
1050 $this->logger->info('Table and fields have to be set');
1054 $param = $this->castFields($table, $param);
1056 $table_string = DBA::buildTableString($table);
1058 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1060 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1062 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1064 return $this->e($sql, $param);
1068 * Fetch the id of the last insert command
1070 * @return integer Last inserted id
1072 public function lastInsertId()
1074 switch ($this->driver) {
1076 $id = $this->connection->lastInsertId();
1079 $id = $this->connection->insert_id;
1086 * Locks a table for exclusive write access
1088 * This function can be extended in the future to accept a table array as well.
1090 * @param string|array $table Table name or array [schema => table]
1092 * @return boolean was the lock successful?
1093 * @throws \Exception
1095 public function lock($table)
1097 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1098 if ($this->driver == self::PDO) {
1099 $this->e("SET autocommit=0");
1100 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1102 $this->connection->autocommit(false);
1105 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1107 if ($this->driver == self::PDO) {
1108 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1112 if ($this->driver == self::PDO) {
1113 $this->e("SET autocommit=1");
1115 $this->connection->autocommit(true);
1118 $this->in_transaction = true;
1124 * Unlocks all locked tables
1126 * @return boolean was the unlock successful?
1127 * @throws \Exception
1129 public function unlock()
1131 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1132 $this->performCommit();
1134 if ($this->driver == self::PDO) {
1135 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1138 $success = $this->e("UNLOCK TABLES");
1140 if ($this->driver == self::PDO) {
1141 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1142 $this->e("SET autocommit=1");
1144 $this->connection->autocommit(true);
1147 $this->in_transaction = false;
1152 * Starts a transaction
1154 * @return boolean Was the command executed successfully?
1156 public function transaction()
1158 if (!$this->performCommit()) {
1162 switch ($this->driver) {
1164 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1170 if (!$this->connection->begin_transaction()) {
1176 $this->in_transaction = true;
1180 protected function performCommit()
1182 switch ($this->driver) {
1184 if (!$this->connection->inTransaction()) {
1188 return $this->connection->commit();
1191 return $this->connection->commit();
1200 * @return boolean Was the command executed successfully?
1202 public function commit()
1204 if (!$this->performCommit()) {
1207 $this->in_transaction = false;
1214 * @return boolean Was the command executed successfully?
1216 public function rollback()
1220 switch ($this->driver) {
1222 if (!$this->connection->inTransaction()) {
1226 $ret = $this->connection->rollBack();
1230 $ret = $this->connection->rollback();
1233 $this->in_transaction = false;
1238 * Delete a row from a table
1240 * @param string $table Table name
1241 * @param array $conditions Field condition(s)
1243 * @return boolean was the delete successful?
1244 * @throws \Exception
1246 public function delete($table, array $conditions)
1248 if (empty($table) || empty($conditions)) {
1249 $this->logger->info('Table and conditions have to be set');
1253 $table_string = DBA::buildTableString($table);
1255 $condition_string = DBA::buildCondition($conditions);
1257 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1258 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1259 return $this->e($sql, $conditions);
1263 * Updates rows in the database. Field value objects will be cast as string.
1265 * When $old_fields is set to an array,
1266 * the system will only do an update if the fields in that array changed.
1269 * Only the values in $old_fields are compared.
1270 * This is an intentional behaviour.
1273 * We include the timestamp field in $fields but not in $old_fields.
1274 * Then the row will only get the new timestamp when the other fields had changed.
1276 * When $old_fields is set to a boolean value the system will do this compare itself.
1277 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1280 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1281 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1283 * @param string|array $table Table name or array [schema => table]
1284 * @param array $fields contains the fields that are updated
1285 * @param array $condition condition array with the key values
1286 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
1288 * @return boolean was the update successfull?
1289 * @throws \Exception
1291 public function update($table, $fields, $condition, $old_fields = [])
1293 if (empty($table) || empty($fields) || empty($condition)) {
1294 $this->logger->info('Table, fields and condition have to be set');
1298 if (is_bool($old_fields)) {
1299 $do_insert = $old_fields;
1301 $old_fields = $this->selectFirst($table, [], $condition);
1303 if (is_bool($old_fields)) {
1305 $values = array_merge($condition, $fields);
1306 return $this->replace($table, $values);
1312 foreach ($old_fields as $fieldname => $content) {
1313 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1314 unset($fields[$fieldname]);
1318 if (count($fields) == 0) {
1322 $fields = $this->castFields($table, $fields);
1324 $table_string = DBA::buildTableString($table);
1326 $condition_string = DBA::buildCondition($condition);
1328 $sql = "UPDATE " . $table_string . " SET "
1329 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1330 . $condition_string;
1332 // Combines the updated fields parameter values with the condition parameter values
1333 $params = array_merge(array_values($fields), $condition);
1335 return $this->e($sql, $params);
1339 * Retrieve a single record from a table and returns it in an associative array
1341 * @param string|array $table
1342 * @param array $fields
1343 * @param array $condition
1344 * @param array $params
1346 * @return bool|array
1347 * @throws \Exception
1348 * @see $this->select
1350 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1352 $params['limit'] = 1;
1353 $result = $this->select($table, $fields, $condition, $params);
1355 if (is_bool($result)) {
1358 $row = $this->fetch($result);
1359 $this->close($result);
1365 * Select rows from a table and fills an array with the data
1367 * @param string|array $table Table name or array [schema => table]
1368 * @param array $fields Array of selected fields, empty for all
1369 * @param array $condition Array of fields for condition
1370 * @param array $params Array of several parameters
1372 * @return array Data array
1373 * @throws \Exception
1376 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1378 return $this->toArray($this->select($table, $fields, $condition, $params));
1382 * Escape fields, adding special treatment for "group by" handling
1384 * @param array $fields
1385 * @param array $options
1388 private function escapeFields(array $fields, array $options)
1390 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1391 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1392 // Otherwise MySQL would report errors.
1393 if (!empty($options['group_by']) && !empty($options['order'])) {
1394 foreach ($options['order'] as $key => $field) {
1395 if (!is_int($key)) {
1396 if (!in_array($key, $fields)) {
1400 if (!in_array($field, $fields)) {
1407 array_walk($fields, function(&$value, $key) use ($options)
1410 $value = '`' . str_replace('`', '``', $value) . '`';
1412 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1413 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1421 * Select rows from a table
1427 * $table = ['schema' => 'table'];
1428 * @see DBA::buildTableString()
1430 * $fields = ['id', 'uri', 'uid', 'network'];
1432 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1434 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1435 * @see DBA::buildCondition()
1437 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1438 * @see DBA::buildParameter()
1440 * $data = DBA::select($table, $fields, $condition, $params);
1442 * @param string|array $table Table name or array [schema => table]
1443 * @param array $fields Array of selected fields, empty for all
1444 * @param array $condition Array of fields for condition
1445 * @param array $params Array of several parameters
1446 * @return boolean|object
1447 * @throws \Exception
1449 public function select($table, array $fields = [], array $condition = [], array $params = [])
1451 if (empty($table)) {
1455 if (count($fields) > 0) {
1456 $fields = $this->escapeFields($fields, $params);
1457 $select_string = implode(', ', $fields);
1459 $select_string = '*';
1462 $table_string = DBA::buildTableString($table);
1464 $condition_string = DBA::buildCondition($condition);
1466 $param_string = DBA::buildParameter($params);
1468 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1470 $result = $this->p($sql, $condition);
1472 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1473 $result->table = $table;
1480 * Counts the rows from a table satisfying the provided condition
1482 * @param string|array $table Table name or array [schema => table]
1483 * @param array $condition Array of fields for condition
1484 * @param array $params Array of several parameters
1491 * $condition = ["uid" => 1, "network" => 'dspr'];
1493 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1495 * $count = DBA::count($table, $condition);
1496 * @throws \Exception
1498 public function count($table, array $condition = [], array $params = [])
1500 if (empty($table)) {
1504 $table_string = DBA::buildTableString($table);
1506 $condition_string = DBA::buildCondition($condition);
1508 if (empty($params['expression'])) {
1510 } elseif (!empty($params['distinct'])) {
1511 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1513 $expression = DBA::quoteIdentifier($params['expression']);
1516 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1518 $row = $this->fetchFirst($sql, $condition);
1520 if (!isset($row['count'])) {
1521 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1524 return (int)$row['count'];
1529 * Fills an array with data from a query
1531 * @param object $stmt statement object
1532 * @param bool $do_close Close database connection after last row
1533 * @param int $count maximum number of rows to be fetched
1535 * @return array Data array
1537 public function toArray($stmt, $do_close = true, int $count = 0)
1539 if (is_bool($stmt)) {
1544 while ($row = $this->fetch($stmt)) {
1546 if (($count != 0) && (count($data) == $count)) {
1552 $this->close($stmt);
1559 * Cast field types according to the table definition
1561 * @param string $table
1562 * @param array $fields
1563 * @return array casted fields
1565 public function castFields(string $table, array $fields) {
1566 // When there is no data, we don't need to do something
1567 if (empty($fields)) {
1571 // We only need to cast fields with PDO
1572 if ($this->driver != self::PDO) {
1576 // We only need to cast when emulating the prepares
1577 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1583 $tables = DBStructure::definition('', false);
1584 if (empty($tables[$table])) {
1585 // When a matching table wasn't found we check if it is a view
1586 $views = View::definition('', false);
1587 if (empty($views[$table])) {
1591 foreach(array_keys($fields) as $field) {
1592 if (!empty($views[$table]['fields'][$field])) {
1593 $viewdef = $views[$table]['fields'][$field];
1594 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1595 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1600 foreach ($tables[$table]['fields'] as $field => $definition) {
1601 $types[$field] = $definition['type'];
1605 foreach ($fields as $field => $content) {
1606 if (is_null($content) || empty($types[$field])) {
1610 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1611 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1612 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1613 $fields[$field] = (int)$content;
1615 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1616 $fields[$field] = (float)$content;
1624 * Returns the error number of the last query
1626 * @return string Error number (0 if no error)
1628 public function errorNo()
1630 return $this->errorno;
1634 * Returns the error message of the last query
1636 * @return string Error message ('' if no error)
1638 public function errorMessage()
1640 return $this->error;
1644 * Closes the current statement
1646 * @param object $stmt statement object
1648 * @return boolean was the close successful?
1650 public function close($stmt)
1653 $this->profiler->startRecording('database');
1655 if (!is_object($stmt)) {
1659 switch ($this->driver) {
1661 $ret = $stmt->closeCursor();
1664 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1665 // We should be careful not to assume the object type of $stmt
1666 // because DBA::p() has been able to return both types.
1667 if ($stmt instanceof mysqli_stmt) {
1668 $stmt->free_result();
1669 $ret = $stmt->close();
1670 } elseif ($stmt instanceof mysqli_result) {
1679 $this->profiler->stopRecording();
1685 * Return a list of database processes
1688 * 'list' => List of processes, separated in their different states
1689 * 'amount' => Number of concurrent database processes
1690 * @throws \Exception
1692 public function processlist()
1694 $ret = $this->p("SHOW PROCESSLIST");
1695 $data = $this->toArray($ret);
1699 foreach ($data as $process) {
1700 $state = trim($process["State"]);
1702 // Filter out all non blocking processes
1703 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1710 foreach ($states as $state => $usage) {
1711 if ($statelist != "") {
1714 $statelist .= $state . ": " . $usage;
1716 return (["list" => $statelist, "amount" => $processes]);
1720 * Fetch a database variable
1722 * @param string $name
1723 * @return string content
1725 public function getVariable(string $name)
1727 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1728 return $result['Value'] ?? null;
1732 * Checks if $array is a filled array with at least one entry.
1734 * @param mixed $array A filled array with at least one entry
1736 * @return boolean Whether $array is a filled array or an object with rows
1738 public function isResult($array)
1740 // It could be a return value from an update statement
1741 if (is_bool($array)) {
1745 if (is_object($array)) {
1746 return $this->numRows($array) > 0;
1749 return (is_array($array) && (count($array) > 0));
1753 * Callback function for "esc_array"
1755 * @param mixed $value Array value
1756 * @param string $key Array key
1757 * @param boolean $add_quotation add quotation marks for string values
1761 private function escapeArrayCallback(&$value, $key, $add_quotation)
1763 if (!$add_quotation) {
1764 if (is_bool($value)) {
1765 $value = ($value ? '1' : '0');
1767 $value = $this->escape($value);
1772 if (is_bool($value)) {
1773 $value = ($value ? 'true' : 'false');
1774 } elseif (is_float($value) || is_integer($value)) {
1775 $value = (string)$value;
1777 $value = "'" . $this->escape($value) . "'";
1782 * Escapes a whole array
1784 * @param mixed $arr Array with values to be escaped
1785 * @param boolean $add_quotation add quotation marks for string values
1789 public function escapeArray(&$arr, $add_quotation = false)
1791 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1795 * Replaces a string in the provided fields of the provided table
1797 * @param string $table_name
1798 * @param array $fields List of field names in the provided table
1799 * @param string $search
1800 * @param string $replace
1801 * @throws \Exception
1803 public function replaceInTableFields(string $table_name, array $fields, string $search, string $replace)
1805 $search = $this->escape($search);
1806 $replace = $this->escape($replace);
1809 foreach ($fields as $field) {
1810 $field = DBA::quoteIdentifier($field);
1811 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1814 $upds = implode(', ', $upd);
1816 $r = $this->e(sprintf("UPDATE %s SET %s;", $table_name, $upds));
1817 if (!$this->isResult($r)) {
1818 throw new \RuntimeException("Failed updating `$table_name`: " . $this->errorMessage());