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'));
118 if (!(strlen($server) && strlen($user))) {
122 $persistent = (bool)$this->configCache->get('database', 'persistent');
124 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
126 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
127 $this->driver = self::PDO;
128 $connect = "mysql:host=" . $server . ";dbname=" . $db;
131 $connect .= ";port=" . $port;
135 $connect .= ";charset=" . $charset;
139 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
140 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
141 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
142 $this->connected = true;
143 } catch (PDOException $e) {
144 $this->connected = false;
148 if (!$this->connected && class_exists('\mysqli')) {
149 $this->driver = self::MYSQLI;
152 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
154 $this->connection = @new mysqli($server, $user, $pass, $db);
157 if (!mysqli_connect_errno()) {
158 $this->connected = true;
161 $this->connection->set_charset($charset);
166 // No suitable SQL driver was found.
167 if (!$this->connected) {
168 $this->driver = null;
169 $this->connection = null;
172 return $this->connected;
175 public function setTestmode(bool $test)
177 $this->testmode = $test;
180 * Sets the logger for DBA
182 * @note this is necessary because if we want to load the logger configuration
183 * from the DB, but there's an error, we would print out an exception.
184 * So the logger gets updated after the logger configuration can be retrieved
187 * @param LoggerInterface $logger
189 public function setLogger(LoggerInterface $logger)
191 $this->logger = $logger;
195 * Sets the profiler for DBA
197 * @param Profiler $profiler
199 public function setProfiler(Profiler $profiler)
201 $this->profiler = $profiler;
204 * Disconnects the current database connection
206 public function disconnect()
208 if (!is_null($this->connection)) {
209 switch ($this->driver) {
211 $this->connection = null;
214 $this->connection->close();
215 $this->connection = null;
220 $this->driver = null;
221 $this->connected = false;
225 * Perform a reconnect of an existing database connection
227 public function reconnect()
230 return $this->connect();
234 * Return the database object.
238 public function getConnection()
240 return $this->connection;
244 * Return the database driver string
246 * @return string with either "pdo" or "mysqli"
248 public function getDriver()
250 return $this->driver;
254 * Returns the MySQL server version string
256 * This function discriminate between the deprecated mysql API and the current
257 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
261 public function serverInfo()
263 if ($this->server_info == '') {
264 switch ($this->driver) {
266 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
269 $this->server_info = $this->connection->server_info;
273 return $this->server_info;
277 * Returns the selected database name
282 public function databaseName()
284 $ret = $this->p("SELECT DATABASE() AS `db`");
285 $data = $this->toArray($ret);
286 return $data[0]['db'];
290 * Analyze a database query and log this if some conditions are met.
292 * @param string $query The database query that will be analyzed
296 private function logIndex($query)
299 if (!$this->configCache->get('system', 'db_log_index')) {
303 // Don't explain an explain statement
304 if (strtolower(substr($query, 0, 7)) == "explain") {
308 // Only do the explain on "select", "update" and "delete"
309 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
313 $r = $this->p("EXPLAIN " . $query);
314 if (!$this->isResult($r)) {
318 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
319 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
321 while ($row = $this->fetch($r)) {
322 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
323 $log = (in_array($row['key'], $watchlist) &&
324 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
329 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
333 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
338 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
339 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
340 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
341 basename($backtrace[1]["file"]) . "\t" .
342 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
343 substr($query, 0, 4000) . "\n", FILE_APPEND);
349 * Removes every not allowlisted character from the identifier string
351 * @param string $identifier
353 * @return string sanitized identifier
356 private function sanitizeIdentifier($identifier)
358 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
361 public function escape($str)
363 if ($this->connected) {
364 switch ($this->driver) {
366 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
369 return @$this->connection->real_escape_string($str);
372 return str_replace("'", "\\'", $str);
376 public function isConnected()
378 return $this->connected;
381 public function connected()
385 if (is_null($this->connection)) {
389 switch ($this->driver) {
391 $r = $this->p("SELECT 1");
392 if ($this->isResult($r)) {
393 $row = $this->toArray($r);
394 $connected = ($row[0]['1'] == '1');
398 $connected = $this->connection->ping();
406 * Replaces ANY_VALUE() function by MIN() function,
407 * if the database server does not support ANY_VALUE().
409 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
410 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
411 * A standard fall-back is to use MIN().
413 * @param string $sql An SQL string without the values
415 * @return string The input SQL string modified if necessary.
417 public function anyValueFallback($sql)
419 $server_info = $this->serverInfo();
420 if (version_compare($server_info, '5.7.5', '<') ||
421 (stripos($server_info, 'MariaDB') !== false)) {
422 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
428 * Replaces the ? placeholders with the parameters in the $args array
430 * @param string $sql SQL query
431 * @param array $args The parameters that are to replace the ? placeholders
433 * @return string The replaced SQL query
435 private function replaceParameters($sql, $args)
438 foreach ($args as $param => $value) {
439 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
440 $replace = intval($args[$param]);
441 } elseif (is_null($args[$param])) {
444 $replace = "'" . $this->escape($args[$param]) . "'";
447 $pos = strpos($sql, '?', $offset);
448 if ($pos !== false) {
449 $sql = substr_replace($sql, $replace, $pos, 1);
451 $offset = $pos + strlen($replace);
457 * Executes a prepared statement that returns data
459 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
461 * Please only use it with complicated queries.
462 * For all regular queries please use DBA::select or DBA::exists
464 * @param string $sql SQL statement
466 * @return bool|object statement object or result object
469 public function p($sql)
472 $this->profiler->startRecording('database');
473 $stamp1 = microtime(true);
475 $params = DBA::getParam(func_get_args());
477 // Renumber the array keys to be sure that they fit
480 foreach ($params as $param) {
481 // Avoid problems with some MySQL servers and boolean values. See issue #3645
482 if (is_bool($param)) {
483 $param = (int)$param;
485 $args[++$i] = $param;
488 if (!$this->connected) {
492 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
493 // Question: Should we continue or stop the query here?
494 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
497 $sql = DBA::cleanQuery($sql);
498 $sql = $this->anyValueFallback($sql);
502 if ($this->configCache->get('system', 'db_callstack') !== null) {
503 $sql = "/*" . System::callstack() . " */ " . $sql;
509 $this->affected_rows = 0;
511 // We have to make some things different if this function is called from "e"
512 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
514 if (isset($trace[1])) {
515 $called_from = $trace[1];
517 // We use just something that is defined to avoid warnings
518 $called_from = $trace[0];
520 // We are having an own error logging in the function "e"
521 $called_from_e = ($called_from['function'] == 'e');
523 if (!isset($this->connection)) {
524 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
527 switch ($this->driver) {
529 // If there are no arguments we use "query"
530 if (count($args) == 0) {
531 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
532 $errorInfo = $this->connection->errorInfo();
533 $this->error = $errorInfo[2];
534 $this->errorno = $errorInfo[1];
539 $this->affected_rows = $retval->rowCount();
543 /** @var $stmt mysqli_stmt|PDOStatement */
544 if (!$stmt = $this->connection->prepare($sql)) {
545 $errorInfo = $this->connection->errorInfo();
546 $this->error = $errorInfo[2];
547 $this->errorno = $errorInfo[1];
553 foreach (array_keys($args) as $param) {
554 $data_type = PDO::PARAM_STR;
555 if (is_int($args[$param])) {
556 $data_type = PDO::PARAM_INT;
557 } elseif ($args[$param] !== null) {
558 $args[$param] = (string)$args[$param];
561 $stmt->bindParam($param, $args[$param], $data_type);
564 if (!$stmt->execute()) {
565 $errorInfo = $stmt->errorInfo();
566 $this->error = $errorInfo[2];
567 $this->errorno = $errorInfo[1];
572 $this->affected_rows = $retval->rowCount();
576 // There are SQL statements that cannot be executed with a prepared statement
577 $parts = explode(' ', $orig_sql);
578 $command = strtolower($parts[0]);
579 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
581 // The fallback routine is called as well when there are no arguments
582 if (!$can_be_prepared || (count($args) == 0)) {
583 $retval = $this->connection->query($this->replaceParameters($sql, $args));
584 if ($this->connection->errno) {
585 $this->error = $this->connection->error;
586 $this->errorno = $this->connection->errno;
590 if (isset($retval->num_rows)) {
591 $this->affected_rows = $retval->num_rows;
593 $this->affected_rows = $this->connection->affected_rows;
599 $stmt = $this->connection->stmt_init();
601 if (!$stmt->prepare($sql)) {
602 $this->error = $stmt->error;
603 $this->errorno = $stmt->errno;
611 foreach (array_keys($args) as $param) {
612 if (is_int($args[$param])) {
614 } elseif (is_float($args[$param])) {
616 } elseif (is_string($args[$param])) {
618 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
620 $args[$param] = (string)$args[$param];
624 $values[] = &$args[$param];
627 if (count($values) > 0) {
628 array_unshift($values, $param_types);
629 call_user_func_array([$stmt, 'bind_param'], $values);
632 if (!$stmt->execute()) {
633 $this->error = $this->connection->error;
634 $this->errorno = $this->connection->errno;
638 $stmt->store_result();
640 $this->affected_rows = $retval->affected_rows;
645 // See issue https://github.com/friendica/friendica/issues/8572
646 // Ensure that we always get an error message on an error.
647 if ($is_error && empty($this->errorno)) {
651 if ($is_error && empty($this->error)) {
652 $this->error = 'Unknown database error';
655 // We are having an own error logging in the function "e"
656 if (($this->errorno != 0) && !$called_from_e) {
657 // We have to preserve the error code, somewhere in the logging it get lost
658 $error = $this->error;
659 $errorno = $this->errorno;
661 if ($this->testmode) {
662 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
665 $this->logger->error('DB Error', [
668 'callstack' => System::callstack(8),
669 'params' => $this->replaceParameters($sql, $args),
672 // On a lost connection we try to reconnect - but only once.
673 if ($errorno == 2006) {
674 if ($this->in_retrial || !$this->reconnect()) {
675 // It doesn't make sense to continue when the database connection was lost
676 if ($this->in_retrial) {
677 $this->logger->notice('Giving up retrial because of database error', [
682 $this->logger->notice('Couldn\'t reconnect after database error', [
690 $this->logger->notice('Reconnected after database error', [
694 $this->in_retrial = true;
695 $ret = $this->p($sql, $args);
696 $this->in_retrial = false;
701 $this->error = $error;
702 $this->errorno = $errorno;
705 $this->profiler->stopRecording();
707 if ($this->configCache->get('system', 'db_log')) {
708 $stamp2 = microtime(true);
709 $duration = (float)($stamp2 - $stamp1);
711 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
712 $duration = round($duration, 3);
713 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
715 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
716 basename($backtrace[1]["file"]) . "\t" .
717 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
718 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
725 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
727 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
729 * @param string $sql SQL statement
731 * @return boolean Was the query successfull? False is returned only if an error occurred
734 public function e($sql)
737 $this->profiler->startRecording('database_write');
739 $params = DBA::getParam(func_get_args());
741 // In a case of a deadlock we are repeating the query 20 times
745 $stmt = $this->p($sql, $params);
747 if (is_bool($stmt)) {
749 } elseif (is_object($stmt)) {
757 } while (($this->errorno == 1213) && (--$timeout > 0));
759 if ($this->errorno != 0) {
760 // We have to preserve the error code, somewhere in the logging it get lost
761 $error = $this->error;
762 $errorno = $this->errorno;
764 if ($this->testmode) {
765 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
768 $this->logger->error('DB Error', [
771 'callstack' => System::callstack(8),
772 'params' => $this->replaceParameters($sql, $params),
775 // On a lost connection we simply quit.
776 // A reconnect like in $this->p could be dangerous with modifications
777 if ($errorno == 2006) {
778 $this->logger->notice('Giving up because of database error', [
785 $this->error = $error;
786 $this->errorno = $errorno;
789 $this->profiler->stopRecording();
795 * Check if data exists
797 * @param string|array $table Table name or array [schema => table]
798 * @param array $condition array of fields for condition
800 * @return boolean Are there rows for that condition?
803 public function exists($table, $condition)
811 if (empty($condition)) {
812 return DBStructure::existsTable($table);
816 $first_key = key($condition);
817 if (!is_int($first_key)) {
818 $fields = [$first_key];
821 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
823 if (is_bool($stmt)) {
826 $retval = ($this->numRows($stmt) > 0);
835 * Fetches the first row
837 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
839 * Fetches the first row
841 * @param string $sql SQL statement
843 * @return array first row of query
846 public function fetchFirst($sql)
848 $params = DBA::getParam(func_get_args());
850 $stmt = $this->p($sql, $params);
852 if (is_bool($stmt)) {
855 $retval = $this->fetch($stmt);
864 * Returns the number of affected rows of the last statement
866 * @return int Number of rows
868 public function affectedRows()
870 return $this->affected_rows;
874 * Returns the number of columns of a statement
876 * @param object Statement object
878 * @return int Number of columns
880 public function columnCount($stmt)
882 if (!is_object($stmt)) {
885 switch ($this->driver) {
887 return $stmt->columnCount();
889 return $stmt->field_count;
895 * Returns the number of rows of a statement
897 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
899 * @return int Number of rows
901 public function numRows($stmt)
903 if (!is_object($stmt)) {
906 switch ($this->driver) {
908 return $stmt->rowCount();
910 return $stmt->num_rows;
918 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
920 * @return array|false current row
922 public function fetch($stmt)
924 $this->profiler->startRecording('database');
928 if (!is_object($stmt)) {
932 switch ($this->driver) {
934 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
935 if (!empty($stmt->table) && is_array($columns)) {
936 $columns = $this->castFields($stmt->table, $columns);
940 if (get_class($stmt) == 'mysqli_result') {
941 $columns = $stmt->fetch_assoc() ?? false;
945 // This code works, but is slow
947 // Bind the result to a result array
951 for ($x = 0; $x < $stmt->field_count; $x++) {
952 $cols[] = &$cols_num[$x];
955 call_user_func_array([$stmt, 'bind_result'], $cols);
957 if (!$stmt->fetch()) {
962 // We need to get the field names for the array keys
963 // It seems that there is no better way to do this.
964 $result = $stmt->result_metadata();
965 $fields = $result->fetch_fields();
967 foreach ($cols_num as $param => $col) {
968 $columns[$fields[$param]->name] = $col;
972 $this->profiler->stopRecording();
978 * Insert a row into a table. Field value objects will be cast as string.
980 * @param string|array $table Table name or array [schema => table]
981 * @param array $param parameter array
982 * @param int $duplicate_mode What to do on a duplicated entry
984 * @return boolean was the insert successful?
987 public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT)
989 if (empty($table) || empty($param)) {
990 $this->logger->info('Table and fields have to be set');
994 $param = $this->castFields($table, $param);
996 $table_string = DBA::buildTableString($table);
998 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1000 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1004 if ($duplicate_mode == self::INSERT_IGNORE) {
1008 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1010 if ($duplicate_mode == self::INSERT_UPDATE) {
1011 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1013 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1015 $values = array_values($param);
1016 $param = array_merge_recursive($values, $values);
1019 $result = $this->e($sql, $param);
1020 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1024 return $this->affectedRows() != 0;
1028 * Inserts a row with the provided data in the provided table.
1029 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1031 * @param string|array $table Table name or array [schema => table]
1032 * @param array $param parameter array
1034 * @return boolean was the insert successful?
1035 * @throws \Exception
1037 public function replace($table, array $param)
1039 if (empty($table) || empty($param)) {
1040 $this->logger->info('Table and fields have to be set');
1044 $param = $this->castFields($table, $param);
1046 $table_string = DBA::buildTableString($table);
1048 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1050 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1052 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1054 return $this->e($sql, $param);
1058 * Fetch the id of the last insert command
1060 * @return integer Last inserted id
1062 public function lastInsertId()
1064 switch ($this->driver) {
1066 $id = $this->connection->lastInsertId();
1069 $id = $this->connection->insert_id;
1076 * Locks a table for exclusive write access
1078 * This function can be extended in the future to accept a table array as well.
1080 * @param string|array $table Table name or array [schema => table]
1082 * @return boolean was the lock successful?
1083 * @throws \Exception
1085 public function lock($table)
1087 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1088 if ($this->driver == self::PDO) {
1089 $this->e("SET autocommit=0");
1090 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1092 $this->connection->autocommit(false);
1095 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1097 if ($this->driver == self::PDO) {
1098 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1102 if ($this->driver == self::PDO) {
1103 $this->e("SET autocommit=1");
1105 $this->connection->autocommit(true);
1108 $this->in_transaction = true;
1114 * Unlocks all locked tables
1116 * @return boolean was the unlock successful?
1117 * @throws \Exception
1119 public function unlock()
1121 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1122 $this->performCommit();
1124 if ($this->driver == self::PDO) {
1125 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1128 $success = $this->e("UNLOCK TABLES");
1130 if ($this->driver == self::PDO) {
1131 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1132 $this->e("SET autocommit=1");
1134 $this->connection->autocommit(true);
1137 $this->in_transaction = false;
1142 * Starts a transaction
1144 * @return boolean Was the command executed successfully?
1146 public function transaction()
1148 if (!$this->performCommit()) {
1152 switch ($this->driver) {
1154 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1160 if (!$this->connection->begin_transaction()) {
1166 $this->in_transaction = true;
1170 protected function performCommit()
1172 switch ($this->driver) {
1174 if (!$this->connection->inTransaction()) {
1178 return $this->connection->commit();
1181 return $this->connection->commit();
1190 * @return boolean Was the command executed successfully?
1192 public function commit()
1194 if (!$this->performCommit()) {
1197 $this->in_transaction = false;
1204 * @return boolean Was the command executed successfully?
1206 public function rollback()
1210 switch ($this->driver) {
1212 if (!$this->connection->inTransaction()) {
1216 $ret = $this->connection->rollBack();
1220 $ret = $this->connection->rollback();
1223 $this->in_transaction = false;
1228 * Delete a row from a table
1230 * @param string $table Table name
1231 * @param array $conditions Field condition(s)
1233 * @return boolean was the delete successful?
1234 * @throws \Exception
1236 public function delete($table, array $conditions)
1238 if (empty($table) || empty($conditions)) {
1239 $this->logger->info('Table and conditions have to be set');
1243 $table_string = DBA::buildTableString($table);
1245 $condition_string = DBA::buildCondition($conditions);
1247 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1248 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1249 return $this->e($sql, $conditions);
1253 * Updates rows in the database. Field value objects will be cast as string.
1255 * When $old_fields is set to an array,
1256 * the system will only do an update if the fields in that array changed.
1259 * Only the values in $old_fields are compared.
1260 * This is an intentional behaviour.
1263 * We include the timestamp field in $fields but not in $old_fields.
1264 * Then the row will only get the new timestamp when the other fields had changed.
1266 * When $old_fields is set to a boolean value the system will do this compare itself.
1267 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1270 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1271 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1273 * @param string|array $table Table name or array [schema => table]
1274 * @param array $fields contains the fields that are updated
1275 * @param array $condition condition array with the key values
1276 * @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)
1278 * @return boolean was the update successfull?
1279 * @throws \Exception
1281 public function update($table, $fields, $condition, $old_fields = [])
1283 if (empty($table) || empty($fields) || empty($condition)) {
1284 $this->logger->info('Table, fields and condition have to be set');
1288 if (is_bool($old_fields)) {
1289 $do_insert = $old_fields;
1291 $old_fields = $this->selectFirst($table, [], $condition);
1293 if (is_bool($old_fields)) {
1295 $values = array_merge($condition, $fields);
1296 return $this->replace($table, $values);
1302 foreach ($old_fields as $fieldname => $content) {
1303 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1304 unset($fields[$fieldname]);
1308 if (count($fields) == 0) {
1312 $fields = $this->castFields($table, $fields);
1314 $table_string = DBA::buildTableString($table);
1316 $condition_string = DBA::buildCondition($condition);
1318 $sql = "UPDATE " . $table_string . " SET "
1319 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1320 . $condition_string;
1322 // Combines the updated fields parameter values with the condition parameter values
1323 $params = array_merge(array_values($fields), $condition);
1325 return $this->e($sql, $params);
1329 * Retrieve a single record from a table and returns it in an associative array
1331 * @param string|array $table
1332 * @param array $fields
1333 * @param array $condition
1334 * @param array $params
1336 * @return bool|array
1337 * @throws \Exception
1338 * @see $this->select
1340 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1342 $params['limit'] = 1;
1343 $result = $this->select($table, $fields, $condition, $params);
1345 if (is_bool($result)) {
1348 $row = $this->fetch($result);
1349 $this->close($result);
1355 * Select rows from a table and fills an array with the data
1357 * @param string|array $table Table name or array [schema => table]
1358 * @param array $fields Array of selected fields, empty for all
1359 * @param array $condition Array of fields for condition
1360 * @param array $params Array of several parameters
1362 * @return array Data array
1363 * @throws \Exception
1366 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1368 return $this->toArray($this->select($table, $fields, $condition, $params));
1372 * Escape fields, adding special treatment for "group by" handling
1374 * @param array $fields
1375 * @param array $options
1378 private function escapeFields(array $fields, array $options)
1380 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1381 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1382 // Otherwise MySQL would report errors.
1383 if (!empty($options['group_by']) && !empty($options['order'])) {
1384 foreach ($options['order'] as $key => $field) {
1385 if (!is_int($key)) {
1386 if (!in_array($key, $fields)) {
1390 if (!in_array($field, $fields)) {
1397 array_walk($fields, function(&$value, $key) use ($options)
1400 $value = '`' . str_replace('`', '``', $value) . '`';
1402 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1403 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1411 * Select rows from a table
1417 * $table = ['schema' => 'table'];
1418 * @see DBA::buildTableString()
1420 * $fields = ['id', 'uri', 'uid', 'network'];
1422 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1424 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1425 * @see DBA::buildCondition()
1427 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1428 * @see DBA::buildParameter()
1430 * $data = DBA::select($table, $fields, $condition, $params);
1432 * @param string|array $table Table name or array [schema => table]
1433 * @param array $fields Array of selected fields, empty for all
1434 * @param array $condition Array of fields for condition
1435 * @param array $params Array of several parameters
1436 * @return boolean|object
1437 * @throws \Exception
1439 public function select($table, array $fields = [], array $condition = [], array $params = [])
1441 if (empty($table)) {
1445 if (count($fields) > 0) {
1446 $fields = $this->escapeFields($fields, $params);
1447 $select_string = implode(', ', $fields);
1449 $select_string = '*';
1452 $table_string = DBA::buildTableString($table);
1454 $condition_string = DBA::buildCondition($condition);
1456 $param_string = DBA::buildParameter($params);
1458 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1460 $result = $this->p($sql, $condition);
1462 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1463 $result->table = $table;
1470 * Counts the rows from a table satisfying the provided condition
1472 * @param string|array $table Table name or array [schema => table]
1473 * @param array $condition Array of fields for condition
1474 * @param array $params Array of several parameters
1481 * $condition = ["uid" => 1, "network" => 'dspr'];
1483 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1485 * $count = DBA::count($table, $condition);
1486 * @throws \Exception
1488 public function count($table, array $condition = [], array $params = [])
1490 if (empty($table)) {
1494 $table_string = DBA::buildTableString($table);
1496 $condition_string = DBA::buildCondition($condition);
1498 if (empty($params['expression'])) {
1500 } elseif (!empty($params['distinct'])) {
1501 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1503 $expression = DBA::quoteIdentifier($params['expression']);
1506 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1508 $row = $this->fetchFirst($sql, $condition);
1510 if (!isset($row['count'])) {
1511 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1514 return (int)$row['count'];
1519 * Fills an array with data from a query
1521 * @param object $stmt statement object
1522 * @param bool $do_close Close database connection after last row
1523 * @param int $count maximum number of rows to be fetched
1525 * @return array Data array
1527 public function toArray($stmt, $do_close = true, int $count = 0)
1529 if (is_bool($stmt)) {
1534 while ($row = $this->fetch($stmt)) {
1536 if (($count != 0) && (count($data) == $count)) {
1542 $this->close($stmt);
1549 * Cast field types according to the table definition
1551 * @param string $table
1552 * @param array $fields
1553 * @return array casted fields
1555 public function castFields(string $table, array $fields) {
1556 // When there is no data, we don't need to do something
1557 if (empty($fields)) {
1561 // We only need to cast fields with PDO
1562 if ($this->driver != self::PDO) {
1566 // We only need to cast when emulating the prepares
1567 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1573 $tables = DBStructure::definition('', false);
1574 if (empty($tables[$table])) {
1575 // When a matching table wasn't found we check if it is a view
1576 $views = View::definition('', false);
1577 if (empty($views[$table])) {
1581 foreach(array_keys($fields) as $field) {
1582 if (!empty($views[$table]['fields'][$field])) {
1583 $viewdef = $views[$table]['fields'][$field];
1584 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1585 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1590 foreach ($tables[$table]['fields'] as $field => $definition) {
1591 $types[$field] = $definition['type'];
1595 foreach ($fields as $field => $content) {
1596 if (is_null($content) || empty($types[$field])) {
1600 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1601 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1602 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1603 $fields[$field] = (int)$content;
1605 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1606 $fields[$field] = (float)$content;
1614 * Returns the error number of the last query
1616 * @return string Error number (0 if no error)
1618 public function errorNo()
1620 return $this->errorno;
1624 * Returns the error message of the last query
1626 * @return string Error message ('' if no error)
1628 public function errorMessage()
1630 return $this->error;
1634 * Closes the current statement
1636 * @param object $stmt statement object
1638 * @return boolean was the close successful?
1640 public function close($stmt)
1643 $this->profiler->startRecording('database');
1645 if (!is_object($stmt)) {
1649 switch ($this->driver) {
1651 $ret = $stmt->closeCursor();
1654 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1655 // We should be careful not to assume the object type of $stmt
1656 // because DBA::p() has been able to return both types.
1657 if ($stmt instanceof mysqli_stmt) {
1658 $stmt->free_result();
1659 $ret = $stmt->close();
1660 } elseif ($stmt instanceof mysqli_result) {
1669 $this->profiler->stopRecording();
1675 * Return a list of database processes
1678 * 'list' => List of processes, separated in their different states
1679 * 'amount' => Number of concurrent database processes
1680 * @throws \Exception
1682 public function processlist()
1684 $ret = $this->p("SHOW PROCESSLIST");
1685 $data = $this->toArray($ret);
1689 foreach ($data as $process) {
1690 $state = trim($process["State"]);
1692 // Filter out all non blocking processes
1693 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1700 foreach ($states as $state => $usage) {
1701 if ($statelist != "") {
1704 $statelist .= $state . ": " . $usage;
1706 return (["list" => $statelist, "amount" => $processes]);
1710 * Fetch a database variable
1712 * @param string $name
1713 * @return string content
1715 public function getVariable(string $name)
1717 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1718 return $result['Value'] ?? null;
1722 * Checks if $array is a filled array with at least one entry.
1724 * @param mixed $array A filled array with at least one entry
1726 * @return boolean Whether $array is a filled array or an object with rows
1728 public function isResult($array)
1730 // It could be a return value from an update statement
1731 if (is_bool($array)) {
1735 if (is_object($array)) {
1736 return $this->numRows($array) > 0;
1739 return (is_array($array) && (count($array) > 0));
1743 * Callback function for "esc_array"
1745 * @param mixed $value Array value
1746 * @param string $key Array key
1747 * @param boolean $add_quotation add quotation marks for string values
1751 private function escapeArrayCallback(&$value, $key, $add_quotation)
1753 if (!$add_quotation) {
1754 if (is_bool($value)) {
1755 $value = ($value ? '1' : '0');
1757 $value = $this->escape($value);
1762 if (is_bool($value)) {
1763 $value = ($value ? 'true' : 'false');
1764 } elseif (is_float($value) || is_integer($value)) {
1765 $value = (string)$value;
1767 $value = "'" . $this->escape($value) . "'";
1772 * Escapes a whole array
1774 * @param mixed $arr Array with values to be escaped
1775 * @param boolean $add_quotation add quotation marks for string values
1779 public function escapeArray(&$arr, $add_quotation = false)
1781 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);