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 = (int) $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 = (int) $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 = (int) $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 = (int) $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(): bool
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)
1287 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1289 * @return boolean was the update successfull?
1290 * @throws \Exception
1292 public function update($table, $fields, $condition, $old_fields = [], $params = [])
1294 if (empty($table) || empty($fields) || empty($condition)) {
1295 $this->logger->info('Table, fields and condition have to be set');
1299 if (is_bool($old_fields)) {
1300 $do_insert = $old_fields;
1302 $old_fields = $this->selectFirst($table, [], $condition);
1304 if (is_bool($old_fields)) {
1306 $values = array_merge($condition, $fields);
1307 return $this->replace($table, $values);
1313 foreach ($old_fields as $fieldname => $content) {
1314 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1315 unset($fields[$fieldname]);
1319 if (count($fields) == 0) {
1323 $fields = $this->castFields($table, $fields);
1325 $table_string = DBA::buildTableString($table);
1327 $condition_string = DBA::buildCondition($condition);
1329 if (!empty($params['ignore'])) {
1330 $ignore = 'IGNORE ';
1335 $sql = "UPDATE " . $ignore . $table_string . " SET "
1336 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1337 . $condition_string;
1339 // Combines the updated fields parameter values with the condition parameter values
1340 $params = array_merge(array_values($fields), $condition);
1342 return $this->e($sql, $params);
1346 * Retrieve a single record from a table and returns it in an associative array
1348 * @param string|array $table
1349 * @param array $fields
1350 * @param array $condition
1351 * @param array $params
1353 * @return bool|array
1354 * @throws \Exception
1355 * @see $this->select
1357 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1359 $params['limit'] = 1;
1360 $result = $this->select($table, $fields, $condition, $params);
1362 if (is_bool($result)) {
1365 $row = $this->fetch($result);
1366 $this->close($result);
1372 * Select rows from a table and fills an array with the data
1374 * @param string|array $table Table name or array [schema => table]
1375 * @param array $fields Array of selected fields, empty for all
1376 * @param array $condition Array of fields for condition
1377 * @param array $params Array of several parameters
1379 * @return array Data array
1380 * @throws \Exception
1383 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1385 return $this->toArray($this->select($table, $fields, $condition, $params));
1389 * Escape fields, adding special treatment for "group by" handling
1391 * @param array $fields
1392 * @param array $options
1395 private function escapeFields(array $fields, array $options)
1397 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1398 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1399 // Otherwise MySQL would report errors.
1400 if (!empty($options['group_by']) && !empty($options['order'])) {
1401 foreach ($options['order'] as $key => $field) {
1402 if (!is_int($key)) {
1403 if (!in_array($key, $fields)) {
1407 if (!in_array($field, $fields)) {
1414 array_walk($fields, function(&$value, $key) use ($options)
1417 $value = '`' . str_replace('`', '``', $value) . '`';
1419 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1420 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1428 * Select rows from a table
1434 * $table = ['schema' => 'table'];
1435 * @see DBA::buildTableString()
1437 * $fields = ['id', 'uri', 'uid', 'network'];
1439 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1441 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1442 * @see DBA::buildCondition()
1444 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1445 * @see DBA::buildParameter()
1447 * $data = DBA::select($table, $fields, $condition, $params);
1449 * @param string|array $table Table name or array [schema => table]
1450 * @param array $fields Array of selected fields, empty for all
1451 * @param array $condition Array of fields for condition
1452 * @param array $params Array of several parameters
1453 * @return boolean|object
1454 * @throws \Exception
1456 public function select($table, array $fields = [], array $condition = [], array $params = [])
1458 if (empty($table)) {
1462 if (count($fields) > 0) {
1463 $fields = $this->escapeFields($fields, $params);
1464 $select_string = implode(', ', $fields);
1466 $select_string = '*';
1469 $table_string = DBA::buildTableString($table);
1471 $condition_string = DBA::buildCondition($condition);
1473 $param_string = DBA::buildParameter($params);
1475 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1477 $result = $this->p($sql, $condition);
1479 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1480 $result->table = $table;
1487 * Counts the rows from a table satisfying the provided condition
1489 * @param string|array $table Table name or array [schema => table]
1490 * @param array $condition Array of fields for condition
1491 * @param array $params Array of several parameters
1498 * $condition = ["uid" => 1, "network" => 'dspr'];
1500 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1502 * $count = DBA::count($table, $condition);
1503 * @throws \Exception
1505 public function count($table, array $condition = [], array $params = [])
1507 if (empty($table)) {
1511 $table_string = DBA::buildTableString($table);
1513 $condition_string = DBA::buildCondition($condition);
1515 if (empty($params['expression'])) {
1517 } elseif (!empty($params['distinct'])) {
1518 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1520 $expression = DBA::quoteIdentifier($params['expression']);
1523 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1525 $row = $this->fetchFirst($sql, $condition);
1527 if (!isset($row['count'])) {
1528 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1531 return (int)$row['count'];
1536 * Fills an array with data from a query
1538 * @param object $stmt statement object
1539 * @param bool $do_close Close database connection after last row
1540 * @param int $count maximum number of rows to be fetched
1542 * @return array Data array
1544 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1546 if (is_bool($stmt)) {
1551 while ($row = $this->fetch($stmt)) {
1553 if (($count != 0) && (count($data) == $count)) {
1559 $this->close($stmt);
1566 * Cast field types according to the table definition
1568 * @param string $table
1569 * @param array $fields
1570 * @return array casted fields
1572 public function castFields(string $table, array $fields) {
1573 // When there is no data, we don't need to do something
1574 if (empty($fields)) {
1578 // We only need to cast fields with PDO
1579 if ($this->driver != self::PDO) {
1583 // We only need to cast when emulating the prepares
1584 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1590 $tables = DBStructure::definition('', false);
1591 if (empty($tables[$table])) {
1592 // When a matching table wasn't found we check if it is a view
1593 $views = View::definition('', false);
1594 if (empty($views[$table])) {
1598 foreach(array_keys($fields) as $field) {
1599 if (!empty($views[$table]['fields'][$field])) {
1600 $viewdef = $views[$table]['fields'][$field];
1601 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1602 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1607 foreach ($tables[$table]['fields'] as $field => $definition) {
1608 $types[$field] = $definition['type'];
1612 foreach ($fields as $field => $content) {
1613 if (is_null($content) || empty($types[$field])) {
1617 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1618 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1619 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1620 $fields[$field] = (int)$content;
1622 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1623 $fields[$field] = (float)$content;
1631 * Returns the error number of the last query
1633 * @return string Error number (0 if no error)
1635 public function errorNo(): int
1637 return $this->errorno;
1641 * Returns the error message of the last query
1643 * @return string Error message ('' if no error)
1645 public function errorMessage()
1647 return $this->error;
1651 * Closes the current statement
1653 * @param object $stmt statement object
1655 * @return boolean was the close successful?
1657 public function close($stmt): bool
1660 $this->profiler->startRecording('database');
1662 if (!is_object($stmt)) {
1666 switch ($this->driver) {
1668 $ret = $stmt->closeCursor();
1671 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1672 // We should be careful not to assume the object type of $stmt
1673 // because DBA::p() has been able to return both types.
1674 if ($stmt instanceof mysqli_stmt) {
1675 $stmt->free_result();
1676 $ret = $stmt->close();
1677 } elseif ($stmt instanceof mysqli_result) {
1686 $this->profiler->stopRecording();
1692 * Return a list of database processes
1695 * 'list' => List of processes, separated in their different states
1696 * 'amount' => Number of concurrent database processes
1697 * @throws \Exception
1699 public function processlist(): array
1701 $ret = $this->p("SHOW PROCESSLIST");
1702 $data = $this->toArray($ret);
1706 foreach ($data as $process) {
1707 $state = trim($process["State"]);
1709 // Filter out all non blocking processes
1710 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1717 foreach ($states as $state => $usage) {
1718 if ($statelist != "") {
1721 $statelist .= $state . ": " . $usage;
1723 return (["list" => $statelist, "amount" => $processes]);
1727 * Fetch a database variable
1729 * @param string $name
1730 * @return string content
1732 public function getVariable(string $name)
1734 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1735 return $result['Value'] ?? null;
1739 * Checks if $array is a filled array with at least one entry.
1741 * @param mixed $array A filled array with at least one entry
1743 * @return boolean Whether $array is a filled array or an object with rows
1745 public function isResult($array)
1747 // It could be a return value from an update statement
1748 if (is_bool($array)) {
1752 if (is_object($array)) {
1753 return $this->numRows($array) > 0;
1756 return (is_array($array) && (count($array) > 0));
1760 * Callback function for "esc_array"
1762 * @param mixed $value Array value
1763 * @param string $key Array key
1764 * @param boolean $add_quotation add quotation marks for string values
1768 private function escapeArrayCallback(&$value, $key, $add_quotation)
1770 if (!$add_quotation) {
1771 if (is_bool($value)) {
1772 $value = ($value ? '1' : '0');
1774 $value = $this->escape($value);
1779 if (is_bool($value)) {
1780 $value = ($value ? 'true' : 'false');
1781 } elseif (is_float($value) || is_integer($value)) {
1782 $value = (string)$value;
1784 $value = "'" . $this->escape($value) . "'";
1789 * Escapes a whole array
1791 * @param mixed $arr Array with values to be escaped
1792 * @param boolean $add_quotation add quotation marks for string values
1796 public function escapeArray(&$arr, $add_quotation = false)
1798 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1802 * Replaces a string in the provided fields of the provided table
1804 * @param string $table_name
1805 * @param array $fields List of field names in the provided table
1806 * @param string $search
1807 * @param string $replace
1808 * @throws \Exception
1810 public function replaceInTableFields(string $table_name, array $fields, string $search, string $replace)
1812 $search = $this->escape($search);
1813 $replace = $this->escape($replace);
1816 foreach ($fields as $field) {
1817 $field = DBA::quoteIdentifier($field);
1818 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1821 $upds = implode(', ', $upd);
1823 $r = $this->e(sprintf("UPDATE %s SET %s;", $table_name, $upds));
1824 if (!$this->isResult($r)) {
1825 throw new \RuntimeException("Failed updating `$table_name`: " . $this->errorMessage());