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 . ";unix_socket=" . $socket;
132 $connect .= ";port=" . $port;
136 $connect .= ";charset=" . $charset;
140 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
141 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
142 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
143 $this->connected = true;
144 } catch (PDOException $e) {
145 $this->connected = false;
149 if (!$this->connected && class_exists('\mysqli')) {
150 $this->driver = self::MYSQLI;
153 $this->connection = @new mysqli($server, $user, $pass, $db, $port, $socket);
155 $this->connection = @new mysqli($server, $user, $pass, $db, $socket);
158 if (!mysqli_connect_errno()) {
159 $this->connected = true;
162 $this->connection->set_charset($charset);
167 // No suitable SQL driver was found.
168 if (!$this->connected) {
169 $this->driver = null;
170 $this->connection = null;
173 return $this->connected;
176 public function setTestmode(bool $test)
178 $this->testmode = $test;
181 * Sets the logger for DBA
183 * @note this is necessary because if we want to load the logger configuration
184 * from the DB, but there's an error, we would print out an exception.
185 * So the logger gets updated after the logger configuration can be retrieved
188 * @param LoggerInterface $logger
190 public function setLogger(LoggerInterface $logger)
192 $this->logger = $logger;
196 * Sets the profiler for DBA
198 * @param Profiler $profiler
200 public function setProfiler(Profiler $profiler)
202 $this->profiler = $profiler;
205 * Disconnects the current database connection
207 public function disconnect()
209 if (!is_null($this->connection)) {
210 switch ($this->driver) {
212 $this->connection = null;
215 $this->connection->close();
216 $this->connection = null;
221 $this->driver = null;
222 $this->connected = false;
226 * Perform a reconnect of an existing database connection
228 public function reconnect()
231 return $this->connect();
235 * Return the database object.
239 public function getConnection()
241 return $this->connection;
245 * Return the database driver string
247 * @return string with either "pdo" or "mysqli"
249 public function getDriver()
251 return $this->driver;
255 * Returns the MySQL server version string
257 * This function discriminate between the deprecated mysql API and the current
258 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
262 public function serverInfo()
264 if ($this->server_info == '') {
265 switch ($this->driver) {
267 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
270 $this->server_info = $this->connection->server_info;
274 return $this->server_info;
278 * Returns the selected database name
283 public function databaseName()
285 $ret = $this->p("SELECT DATABASE() AS `db`");
286 $data = $this->toArray($ret);
287 return $data[0]['db'];
291 * Analyze a database query and log this if some conditions are met.
293 * @param string $query The database query that will be analyzed
297 private function logIndex($query)
300 if (!$this->configCache->get('system', 'db_log_index')) {
304 // Don't explain an explain statement
305 if (strtolower(substr($query, 0, 7)) == "explain") {
309 // Only do the explain on "select", "update" and "delete"
310 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
314 $r = $this->p("EXPLAIN " . $query);
315 if (!$this->isResult($r)) {
319 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
320 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
322 while ($row = $this->fetch($r)) {
323 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
324 $log = (in_array($row['key'], $watchlist) &&
325 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
330 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
334 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
339 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
340 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
341 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
342 basename($backtrace[1]["file"]) . "\t" .
343 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
344 substr($query, 0, 4000) . "\n", FILE_APPEND);
350 * Removes every not allowlisted character from the identifier string
352 * @param string $identifier
354 * @return string sanitized identifier
357 private function sanitizeIdentifier($identifier)
359 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
362 public function escape($str)
364 if ($this->connected) {
365 switch ($this->driver) {
367 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
370 return @$this->connection->real_escape_string($str);
373 return str_replace("'", "\\'", $str);
377 public function isConnected()
379 return $this->connected;
382 public function connected()
386 if (is_null($this->connection)) {
390 switch ($this->driver) {
392 $r = $this->p("SELECT 1");
393 if ($this->isResult($r)) {
394 $row = $this->toArray($r);
395 $connected = ($row[0]['1'] == '1');
399 $connected = $this->connection->ping();
407 * Replaces ANY_VALUE() function by MIN() function,
408 * if the database server does not support ANY_VALUE().
410 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
411 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
412 * A standard fall-back is to use MIN().
414 * @param string $sql An SQL string without the values
416 * @return string The input SQL string modified if necessary.
418 public function anyValueFallback($sql)
420 $server_info = $this->serverInfo();
421 if (version_compare($server_info, '5.7.5', '<') ||
422 (stripos($server_info, 'MariaDB') !== false)) {
423 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
429 * Replaces the ? placeholders with the parameters in the $args array
431 * @param string $sql SQL query
432 * @param array $args The parameters that are to replace the ? placeholders
434 * @return string The replaced SQL query
436 private function replaceParameters($sql, $args)
439 foreach ($args as $param => $value) {
440 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
441 $replace = intval($args[$param]);
442 } elseif (is_null($args[$param])) {
445 $replace = "'" . $this->escape($args[$param]) . "'";
448 $pos = strpos($sql, '?', $offset);
449 if ($pos !== false) {
450 $sql = substr_replace($sql, $replace, $pos, 1);
452 $offset = $pos + strlen($replace);
458 * Executes a prepared statement that returns data
460 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
462 * Please only use it with complicated queries.
463 * For all regular queries please use DBA::select or DBA::exists
465 * @param string $sql SQL statement
467 * @return bool|object statement object or result object
470 public function p($sql)
473 $this->profiler->startRecording('database');
474 $stamp1 = microtime(true);
476 $params = DBA::getParam(func_get_args());
478 // Renumber the array keys to be sure that they fit
481 foreach ($params as $param) {
482 // Avoid problems with some MySQL servers and boolean values. See issue #3645
483 if (is_bool($param)) {
484 $param = (int)$param;
486 $args[++$i] = $param;
489 if (!$this->connected) {
493 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
494 // Question: Should we continue or stop the query here?
495 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
498 $sql = DBA::cleanQuery($sql);
499 $sql = $this->anyValueFallback($sql);
503 if ($this->configCache->get('system', 'db_callstack') !== null) {
504 $sql = "/*" . System::callstack() . " */ " . $sql;
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 ServiceUnavailableException('The Connection is empty, although connected is set true.');
528 switch ($this->driver) {
530 // If there are no arguments we use "query"
531 if (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];
540 $this->affected_rows = $retval->rowCount();
544 /** @var $stmt mysqli_stmt|PDOStatement */
545 if (!$stmt = $this->connection->prepare($sql)) {
546 $errorInfo = $this->connection->errorInfo();
547 $this->error = $errorInfo[2];
548 $this->errorno = $errorInfo[1];
554 foreach (array_keys($args) as $param) {
555 $data_type = PDO::PARAM_STR;
556 if (is_int($args[$param])) {
557 $data_type = PDO::PARAM_INT;
558 } elseif ($args[$param] !== null) {
559 $args[$param] = (string)$args[$param];
562 $stmt->bindParam($param, $args[$param], $data_type);
565 if (!$stmt->execute()) {
566 $errorInfo = $stmt->errorInfo();
567 $this->error = $errorInfo[2];
568 $this->errorno = $errorInfo[1];
573 $this->affected_rows = $retval->rowCount();
577 // There are SQL statements that cannot be executed with a prepared statement
578 $parts = explode(' ', $orig_sql);
579 $command = strtolower($parts[0]);
580 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
582 // The fallback routine is called as well when there are no arguments
583 if (!$can_be_prepared || (count($args) == 0)) {
584 $retval = $this->connection->query($this->replaceParameters($sql, $args));
585 if ($this->connection->errno) {
586 $this->error = $this->connection->error;
587 $this->errorno = $this->connection->errno;
591 if (isset($retval->num_rows)) {
592 $this->affected_rows = $retval->num_rows;
594 $this->affected_rows = $this->connection->affected_rows;
600 $stmt = $this->connection->stmt_init();
602 if (!$stmt->prepare($sql)) {
603 $this->error = $stmt->error;
604 $this->errorno = $stmt->errno;
612 foreach (array_keys($args) as $param) {
613 if (is_int($args[$param])) {
615 } elseif (is_float($args[$param])) {
617 } elseif (is_string($args[$param])) {
619 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
621 $args[$param] = (string)$args[$param];
625 $values[] = &$args[$param];
628 if (count($values) > 0) {
629 array_unshift($values, $param_types);
630 call_user_func_array([$stmt, 'bind_param'], $values);
633 if (!$stmt->execute()) {
634 $this->error = $this->connection->error;
635 $this->errorno = $this->connection->errno;
639 $stmt->store_result();
641 $this->affected_rows = $retval->affected_rows;
646 // See issue https://github.com/friendica/friendica/issues/8572
647 // Ensure that we always get an error message on an error.
648 if ($is_error && empty($this->errorno)) {
652 if ($is_error && empty($this->error)) {
653 $this->error = 'Unknown database error';
656 // We are having an own error logging in the function "e"
657 if (($this->errorno != 0) && !$called_from_e) {
658 // We have to preserve the error code, somewhere in the logging it get lost
659 $error = $this->error;
660 $errorno = $this->errorno;
662 if ($this->testmode) {
663 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
666 $this->logger->error('DB Error', [
669 'callstack' => System::callstack(8),
670 'params' => $this->replaceParameters($sql, $args),
673 // On a lost connection we try to reconnect - but only once.
674 if ($errorno == 2006) {
675 if ($this->in_retrial || !$this->reconnect()) {
676 // It doesn't make sense to continue when the database connection was lost
677 if ($this->in_retrial) {
678 $this->logger->notice('Giving up retrial because of database error', [
683 $this->logger->notice('Couldn\'t reconnect after database error', [
691 $this->logger->notice('Reconnected after database error', [
695 $this->in_retrial = true;
696 $ret = $this->p($sql, $args);
697 $this->in_retrial = false;
702 $this->error = $error;
703 $this->errorno = $errorno;
706 $this->profiler->stopRecording();
708 if ($this->configCache->get('system', 'db_log')) {
709 $stamp2 = microtime(true);
710 $duration = (float)($stamp2 - $stamp1);
712 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
713 $duration = round($duration, 3);
714 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
716 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
717 basename($backtrace[1]["file"]) . "\t" .
718 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
719 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
726 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
728 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
730 * @param string $sql SQL statement
732 * @return boolean Was the query successfull? False is returned only if an error occurred
735 public function e($sql)
738 $this->profiler->startRecording('database_write');
740 $params = DBA::getParam(func_get_args());
742 // In a case of a deadlock we are repeating the query 20 times
746 $stmt = $this->p($sql, $params);
748 if (is_bool($stmt)) {
750 } elseif (is_object($stmt)) {
758 } while (($this->errorno == 1213) && (--$timeout > 0));
760 if ($this->errorno != 0) {
761 // We have to preserve the error code, somewhere in the logging it get lost
762 $error = $this->error;
763 $errorno = $this->errorno;
765 if ($this->testmode) {
766 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
769 $this->logger->error('DB Error', [
772 'callstack' => System::callstack(8),
773 'params' => $this->replaceParameters($sql, $params),
776 // On a lost connection we simply quit.
777 // A reconnect like in $this->p could be dangerous with modifications
778 if ($errorno == 2006) {
779 $this->logger->notice('Giving up because of database error', [
786 $this->error = $error;
787 $this->errorno = $errorno;
790 $this->profiler->stopRecording();
796 * Check if data exists
798 * @param string|array $table Table name or array [schema => table]
799 * @param array $condition array of fields for condition
801 * @return boolean Are there rows for that condition?
804 public function exists($table, $condition)
812 if (empty($condition)) {
813 return DBStructure::existsTable($table);
817 $first_key = key($condition);
818 if (!is_int($first_key)) {
819 $fields = [$first_key];
822 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
824 if (is_bool($stmt)) {
827 $retval = ($this->numRows($stmt) > 0);
836 * Fetches the first row
838 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
840 * Fetches the first row
842 * @param string $sql SQL statement
844 * @return array first row of query
847 public function fetchFirst($sql)
849 $params = DBA::getParam(func_get_args());
851 $stmt = $this->p($sql, $params);
853 if (is_bool($stmt)) {
856 $retval = $this->fetch($stmt);
865 * Returns the number of affected rows of the last statement
867 * @return int Number of rows
869 public function affectedRows()
871 return $this->affected_rows;
875 * Returns the number of columns of a statement
877 * @param object Statement object
879 * @return int Number of columns
881 public function columnCount($stmt)
883 if (!is_object($stmt)) {
886 switch ($this->driver) {
888 return $stmt->columnCount();
890 return $stmt->field_count;
896 * Returns the number of rows of a statement
898 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
900 * @return int Number of rows
902 public function numRows($stmt)
904 if (!is_object($stmt)) {
907 switch ($this->driver) {
909 return $stmt->rowCount();
911 return $stmt->num_rows;
919 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
921 * @return array|false current row
923 public function fetch($stmt)
925 $this->profiler->startRecording('database');
929 if (!is_object($stmt)) {
933 switch ($this->driver) {
935 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
936 if (!empty($stmt->table) && is_array($columns)) {
937 $columns = $this->castFields($stmt->table, $columns);
941 if (get_class($stmt) == 'mysqli_result') {
942 $columns = $stmt->fetch_assoc() ?? false;
946 // This code works, but is slow
948 // Bind the result to a result array
952 for ($x = 0; $x < $stmt->field_count; $x++) {
953 $cols[] = &$cols_num[$x];
956 call_user_func_array([$stmt, 'bind_result'], $cols);
958 if (!$stmt->fetch()) {
963 // We need to get the field names for the array keys
964 // It seems that there is no better way to do this.
965 $result = $stmt->result_metadata();
966 $fields = $result->fetch_fields();
968 foreach ($cols_num as $param => $col) {
969 $columns[$fields[$param]->name] = $col;
973 $this->profiler->stopRecording();
979 * Insert a row into a table. Field value objects will be cast as string.
981 * @param string|array $table Table name or array [schema => table]
982 * @param array $param parameter array
983 * @param int $duplicate_mode What to do on a duplicated entry
985 * @return boolean was the insert successful?
988 public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT)
990 if (empty($table) || empty($param)) {
991 $this->logger->info('Table and fields have to be set');
995 $param = $this->castFields($table, $param);
997 $table_string = DBA::buildTableString($table);
999 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1001 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1005 if ($duplicate_mode == self::INSERT_IGNORE) {
1009 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1011 if ($duplicate_mode == self::INSERT_UPDATE) {
1012 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1014 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1016 $values = array_values($param);
1017 $param = array_merge_recursive($values, $values);
1020 $result = $this->e($sql, $param);
1021 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1025 return $this->affectedRows() != 0;
1029 * Inserts a row with the provided data in the provided table.
1030 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1032 * @param string|array $table Table name or array [schema => table]
1033 * @param array $param parameter array
1035 * @return boolean was the insert successful?
1036 * @throws \Exception
1038 public function replace($table, array $param)
1040 if (empty($table) || empty($param)) {
1041 $this->logger->info('Table and fields have to be set');
1045 $param = $this->castFields($table, $param);
1047 $table_string = DBA::buildTableString($table);
1049 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1051 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1053 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1055 return $this->e($sql, $param);
1059 * Fetch the id of the last insert command
1061 * @return integer Last inserted id
1063 public function lastInsertId()
1065 switch ($this->driver) {
1067 $id = $this->connection->lastInsertId();
1070 $id = $this->connection->insert_id;
1077 * Locks a table for exclusive write access
1079 * This function can be extended in the future to accept a table array as well.
1081 * @param string|array $table Table name or array [schema => table]
1083 * @return boolean was the lock successful?
1084 * @throws \Exception
1086 public function lock($table)
1088 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1089 if ($this->driver == self::PDO) {
1090 $this->e("SET autocommit=0");
1091 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1093 $this->connection->autocommit(false);
1096 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1098 if ($this->driver == self::PDO) {
1099 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1103 if ($this->driver == self::PDO) {
1104 $this->e("SET autocommit=1");
1106 $this->connection->autocommit(true);
1109 $this->in_transaction = true;
1115 * Unlocks all locked tables
1117 * @return boolean was the unlock successful?
1118 * @throws \Exception
1120 public function unlock()
1122 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1123 $this->performCommit();
1125 if ($this->driver == self::PDO) {
1126 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1129 $success = $this->e("UNLOCK TABLES");
1131 if ($this->driver == self::PDO) {
1132 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1133 $this->e("SET autocommit=1");
1135 $this->connection->autocommit(true);
1138 $this->in_transaction = false;
1143 * Starts a transaction
1145 * @return boolean Was the command executed successfully?
1147 public function transaction()
1149 if (!$this->performCommit()) {
1153 switch ($this->driver) {
1155 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1161 if (!$this->connection->begin_transaction()) {
1167 $this->in_transaction = true;
1171 protected function performCommit()
1173 switch ($this->driver) {
1175 if (!$this->connection->inTransaction()) {
1179 return $this->connection->commit();
1182 return $this->connection->commit();
1191 * @return boolean Was the command executed successfully?
1193 public function commit()
1195 if (!$this->performCommit()) {
1198 $this->in_transaction = false;
1205 * @return boolean Was the command executed successfully?
1207 public function rollback()
1211 switch ($this->driver) {
1213 if (!$this->connection->inTransaction()) {
1217 $ret = $this->connection->rollBack();
1221 $ret = $this->connection->rollback();
1224 $this->in_transaction = false;
1229 * Delete a row from a table
1231 * @param string $table Table name
1232 * @param array $conditions Field condition(s)
1234 * @return boolean was the delete successful?
1235 * @throws \Exception
1237 public function delete($table, array $conditions)
1239 if (empty($table) || empty($conditions)) {
1240 $this->logger->info('Table and conditions have to be set');
1244 $table_string = DBA::buildTableString($table);
1246 $condition_string = DBA::buildCondition($conditions);
1248 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1249 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1250 return $this->e($sql, $conditions);
1254 * Updates rows in the database. Field value objects will be cast as string.
1256 * When $old_fields is set to an array,
1257 * the system will only do an update if the fields in that array changed.
1260 * Only the values in $old_fields are compared.
1261 * This is an intentional behaviour.
1264 * We include the timestamp field in $fields but not in $old_fields.
1265 * Then the row will only get the new timestamp when the other fields had changed.
1267 * When $old_fields is set to a boolean value the system will do this compare itself.
1268 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1271 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1272 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1274 * @param string|array $table Table name or array [schema => table]
1275 * @param array $fields contains the fields that are updated
1276 * @param array $condition condition array with the key values
1277 * @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)
1279 * @return boolean was the update successfull?
1280 * @throws \Exception
1282 public function update($table, $fields, $condition, $old_fields = [])
1284 if (empty($table) || empty($fields) || empty($condition)) {
1285 $this->logger->info('Table, fields and condition have to be set');
1289 if (is_bool($old_fields)) {
1290 $do_insert = $old_fields;
1292 $old_fields = $this->selectFirst($table, [], $condition);
1294 if (is_bool($old_fields)) {
1296 $values = array_merge($condition, $fields);
1297 return $this->replace($table, $values);
1303 foreach ($old_fields as $fieldname => $content) {
1304 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1305 unset($fields[$fieldname]);
1309 if (count($fields) == 0) {
1313 $fields = $this->castFields($table, $fields);
1315 $table_string = DBA::buildTableString($table);
1317 $condition_string = DBA::buildCondition($condition);
1319 $sql = "UPDATE " . $table_string . " SET "
1320 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1321 . $condition_string;
1323 // Combines the updated fields parameter values with the condition parameter values
1324 $params = array_merge(array_values($fields), $condition);
1326 return $this->e($sql, $params);
1330 * Retrieve a single record from a table and returns it in an associative array
1332 * @param string|array $table
1333 * @param array $fields
1334 * @param array $condition
1335 * @param array $params
1337 * @return bool|array
1338 * @throws \Exception
1339 * @see $this->select
1341 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1343 $params['limit'] = 1;
1344 $result = $this->select($table, $fields, $condition, $params);
1346 if (is_bool($result)) {
1349 $row = $this->fetch($result);
1350 $this->close($result);
1356 * Select rows from a table and fills an array with the data
1358 * @param string|array $table Table name or array [schema => table]
1359 * @param array $fields Array of selected fields, empty for all
1360 * @param array $condition Array of fields for condition
1361 * @param array $params Array of several parameters
1363 * @return array Data array
1364 * @throws \Exception
1367 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1369 return $this->toArray($this->select($table, $fields, $condition, $params));
1373 * Escape fields, adding special treatment for "group by" handling
1375 * @param array $fields
1376 * @param array $options
1379 private function escapeFields(array $fields, array $options)
1381 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1382 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1383 // Otherwise MySQL would report errors.
1384 if (!empty($options['group_by']) && !empty($options['order'])) {
1385 foreach ($options['order'] as $key => $field) {
1386 if (!is_int($key)) {
1387 if (!in_array($key, $fields)) {
1391 if (!in_array($field, $fields)) {
1398 array_walk($fields, function(&$value, $key) use ($options)
1401 $value = '`' . str_replace('`', '``', $value) . '`';
1403 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1404 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1412 * Select rows from a table
1418 * $table = ['schema' => 'table'];
1419 * @see DBA::buildTableString()
1421 * $fields = ['id', 'uri', 'uid', 'network'];
1423 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1425 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1426 * @see DBA::buildCondition()
1428 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1429 * @see DBA::buildParameter()
1431 * $data = DBA::select($table, $fields, $condition, $params);
1433 * @param string|array $table Table name or array [schema => table]
1434 * @param array $fields Array of selected fields, empty for all
1435 * @param array $condition Array of fields for condition
1436 * @param array $params Array of several parameters
1437 * @return boolean|object
1438 * @throws \Exception
1440 public function select($table, array $fields = [], array $condition = [], array $params = [])
1442 if (empty($table)) {
1446 if (count($fields) > 0) {
1447 $fields = $this->escapeFields($fields, $params);
1448 $select_string = implode(', ', $fields);
1450 $select_string = '*';
1453 $table_string = DBA::buildTableString($table);
1455 $condition_string = DBA::buildCondition($condition);
1457 $param_string = DBA::buildParameter($params);
1459 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1461 $result = $this->p($sql, $condition);
1463 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1464 $result->table = $table;
1471 * Counts the rows from a table satisfying the provided condition
1473 * @param string|array $table Table name or array [schema => table]
1474 * @param array $condition Array of fields for condition
1475 * @param array $params Array of several parameters
1482 * $condition = ["uid" => 1, "network" => 'dspr'];
1484 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1486 * $count = DBA::count($table, $condition);
1487 * @throws \Exception
1489 public function count($table, array $condition = [], array $params = [])
1491 if (empty($table)) {
1495 $table_string = DBA::buildTableString($table);
1497 $condition_string = DBA::buildCondition($condition);
1499 if (empty($params['expression'])) {
1501 } elseif (!empty($params['distinct'])) {
1502 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1504 $expression = DBA::quoteIdentifier($params['expression']);
1507 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1509 $row = $this->fetchFirst($sql, $condition);
1511 if (!isset($row['count'])) {
1512 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1515 return (int)$row['count'];
1520 * Fills an array with data from a query
1522 * @param object $stmt statement object
1523 * @param bool $do_close Close database connection after last row
1524 * @param int $count maximum number of rows to be fetched
1526 * @return array Data array
1528 public function toArray($stmt, $do_close = true, int $count = 0)
1530 if (is_bool($stmt)) {
1535 while ($row = $this->fetch($stmt)) {
1537 if (($count != 0) && (count($data) == $count)) {
1543 $this->close($stmt);
1550 * Cast field types according to the table definition
1552 * @param string $table
1553 * @param array $fields
1554 * @return array casted fields
1556 public function castFields(string $table, array $fields) {
1557 // When there is no data, we don't need to do something
1558 if (empty($fields)) {
1562 // We only need to cast fields with PDO
1563 if ($this->driver != self::PDO) {
1567 // We only need to cast when emulating the prepares
1568 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1574 $tables = DBStructure::definition('', false);
1575 if (empty($tables[$table])) {
1576 // When a matching table wasn't found we check if it is a view
1577 $views = View::definition('', false);
1578 if (empty($views[$table])) {
1582 foreach(array_keys($fields) as $field) {
1583 if (!empty($views[$table]['fields'][$field])) {
1584 $viewdef = $views[$table]['fields'][$field];
1585 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1586 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1591 foreach ($tables[$table]['fields'] as $field => $definition) {
1592 $types[$field] = $definition['type'];
1596 foreach ($fields as $field => $content) {
1597 if (is_null($content) || empty($types[$field])) {
1601 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1602 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1603 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1604 $fields[$field] = (int)$content;
1606 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1607 $fields[$field] = (float)$content;
1615 * Returns the error number of the last query
1617 * @return string Error number (0 if no error)
1619 public function errorNo()
1621 return $this->errorno;
1625 * Returns the error message of the last query
1627 * @return string Error message ('' if no error)
1629 public function errorMessage()
1631 return $this->error;
1635 * Closes the current statement
1637 * @param object $stmt statement object
1639 * @return boolean was the close successful?
1641 public function close($stmt)
1644 $this->profiler->startRecording('database');
1646 if (!is_object($stmt)) {
1650 switch ($this->driver) {
1652 $ret = $stmt->closeCursor();
1655 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1656 // We should be careful not to assume the object type of $stmt
1657 // because DBA::p() has been able to return both types.
1658 if ($stmt instanceof mysqli_stmt) {
1659 $stmt->free_result();
1660 $ret = $stmt->close();
1661 } elseif ($stmt instanceof mysqli_result) {
1670 $this->profiler->stopRecording();
1676 * Return a list of database processes
1679 * 'list' => List of processes, separated in their different states
1680 * 'amount' => Number of concurrent database processes
1681 * @throws \Exception
1683 public function processlist()
1685 $ret = $this->p("SHOW PROCESSLIST");
1686 $data = $this->toArray($ret);
1690 foreach ($data as $process) {
1691 $state = trim($process["State"]);
1693 // Filter out all non blocking processes
1694 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1701 foreach ($states as $state => $usage) {
1702 if ($statelist != "") {
1705 $statelist .= $state . ": " . $usage;
1707 return (["list" => $statelist, "amount" => $processes]);
1711 * Fetch a database variable
1713 * @param string $name
1714 * @return string content
1716 public function getVariable(string $name)
1718 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1719 return $result['Value'] ?? null;
1723 * Checks if $array is a filled array with at least one entry.
1725 * @param mixed $array A filled array with at least one entry
1727 * @return boolean Whether $array is a filled array or an object with rows
1729 public function isResult($array)
1731 // It could be a return value from an update statement
1732 if (is_bool($array)) {
1736 if (is_object($array)) {
1737 return $this->numRows($array) > 0;
1740 return (is_array($array) && (count($array) > 0));
1744 * Callback function for "esc_array"
1746 * @param mixed $value Array value
1747 * @param string $key Array key
1748 * @param boolean $add_quotation add quotation marks for string values
1752 private function escapeArrayCallback(&$value, $key, $add_quotation)
1754 if (!$add_quotation) {
1755 if (is_bool($value)) {
1756 $value = ($value ? '1' : '0');
1758 $value = $this->escape($value);
1763 if (is_bool($value)) {
1764 $value = ($value ? 'true' : 'false');
1765 } elseif (is_float($value) || is_integer($value)) {
1766 $value = (string)$value;
1768 $value = "'" . $this->escape($value) . "'";
1773 * Escapes a whole array
1775 * @param mixed $arr Array with values to be escaped
1776 * @param boolean $add_quotation add quotation marks for string values
1780 public function escapeArray(&$arr, $add_quotation = false)
1782 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);