3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
25 use Friendica\Core\Config\Cache;
26 use Friendica\Core\System;
28 use Friendica\Network\HTTPException\InternalServerErrorException;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Profiler;
37 use Psr\Log\LoggerInterface;
40 * This class is for the low level database stuff that does driver specific things.
44 protected $connected = false;
49 protected $configCache;
55 * @var LoggerInterface
58 protected $server_info = '';
59 /** @var PDO|mysqli */
60 protected $connection;
62 protected $emulate_prepares = false;
63 private $error = false;
65 private $affected_rows = 0;
66 protected $in_transaction = false;
67 protected $in_retrial = false;
68 protected $testmode = false;
69 private $relation = [];
71 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
73 // We are storing these values for being able to perform a reconnect
74 $this->configCache = $configCache;
75 $this->profiler = $profiler;
76 $this->logger = $logger;
78 $this->readServerVariables($server);
81 if ($this->isConnected()) {
82 // Loads DB_UPDATE_VERSION constant
83 DBStructure::definition($configCache->get('system', 'basepath'), false);
87 private function readServerVariables(array $server)
89 // Use environment variables for mysql if they are set beforehand
90 if (!empty($server['MYSQL_HOST'])
91 && (!empty($server['MYSQL_USERNAME']) || !empty($server['MYSQL_USER']))
92 && $server['MYSQL_PASSWORD'] !== false
93 && !empty($server['MYSQL_DATABASE']))
95 $db_host = $server['MYSQL_HOST'];
96 if (!empty($server['MYSQL_PORT'])) {
97 $db_host .= ':' . $server['MYSQL_PORT'];
99 $this->configCache->set('database', 'hostname', $db_host);
101 if (!empty($server['MYSQL_USERNAME'])) {
102 $this->configCache->set('database', 'username', $server['MYSQL_USERNAME']);
104 $this->configCache->set('database', 'username', $server['MYSQL_USER']);
106 $this->configCache->set('database', 'password', (string) $server['MYSQL_PASSWORD']);
107 $this->configCache->set('database', 'database', $server['MYSQL_DATABASE']);
111 public function connect()
113 if (!is_null($this->connection) && $this->connected()) {
114 return $this->connected;
117 // Reset connected state
118 $this->connected = false;
121 $serveraddr = trim($this->configCache->get('database', 'hostname'));
122 $serverdata = explode(':', $serveraddr);
123 $server = $serverdata[0];
124 if (count($serverdata) > 1) {
125 $port = trim($serverdata[1]);
127 $server = trim($server);
128 $user = trim($this->configCache->get('database', 'username'));
129 $pass = trim($this->configCache->get('database', 'password'));
130 $db = trim($this->configCache->get('database', 'database'));
131 $charset = trim($this->configCache->get('database', 'charset'));
133 if (!(strlen($server) && strlen($user))) {
137 $persistent = (bool)$this->configCache->get('database', 'persistent');
139 $this->emulate_prepares = (bool)$this->configCache->get('database', 'emulate_prepares');
140 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
142 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
143 $this->driver = 'pdo';
144 $connect = "mysql:host=" . $server . ";dbname=" . $db;
147 $connect .= ";port=" . $port;
151 $connect .= ";charset=" . $charset;
155 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
156 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
157 $this->connected = true;
158 } catch (PDOException $e) {
159 $this->connected = false;
163 if (!$this->connected && class_exists('\mysqli')) {
164 $this->driver = 'mysqli';
167 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
169 $this->connection = @new mysqli($server, $user, $pass, $db);
172 if (!mysqli_connect_errno()) {
173 $this->connected = true;
176 $this->connection->set_charset($charset);
181 // No suitable SQL driver was found.
182 if (!$this->connected) {
183 $this->driver = null;
184 $this->connection = null;
187 return $this->connected;
190 public function setTestmode(bool $test)
192 $this->testmode = $test;
195 * Sets the logger for DBA
197 * @note this is necessary because if we want to load the logger configuration
198 * from the DB, but there's an error, we would print out an exception.
199 * So the logger gets updated after the logger configuration can be retrieved
202 * @param LoggerInterface $logger
204 public function setLogger(LoggerInterface $logger)
206 $this->logger = $logger;
210 * Sets the profiler for DBA
212 * @param Profiler $profiler
214 public function setProfiler(Profiler $profiler)
216 $this->profiler = $profiler;
219 * Disconnects the current database connection
221 public function disconnect()
223 if (!is_null($this->connection)) {
224 switch ($this->driver) {
226 $this->connection = null;
229 $this->connection->close();
230 $this->connection = null;
235 $this->driver = null;
236 $this->connected = false;
240 * Perform a reconnect of an existing database connection
242 public function reconnect()
245 return $this->connect();
249 * Return the database object.
253 public function getConnection()
255 return $this->connection;
259 * Returns the MySQL server version string
261 * This function discriminate between the deprecated mysql API and the current
262 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
266 public function serverInfo()
268 if ($this->server_info == '') {
269 switch ($this->driver) {
271 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
274 $this->server_info = $this->connection->server_info;
278 return $this->server_info;
282 * Returns the selected database name
287 public function databaseName()
289 $ret = $this->p("SELECT DATABASE() AS `db`");
290 $data = $this->toArray($ret);
291 return $data[0]['db'];
295 * Analyze a database query and log this if some conditions are met.
297 * @param string $query The database query that will be analyzed
301 private function logIndex($query)
304 if (!$this->configCache->get('system', 'db_log_index')) {
308 // Don't explain an explain statement
309 if (strtolower(substr($query, 0, 7)) == "explain") {
313 // Only do the explain on "select", "update" and "delete"
314 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
318 $r = $this->p("EXPLAIN " . $query);
319 if (!$this->isResult($r)) {
323 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
324 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
326 while ($row = $this->fetch($r)) {
327 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
328 $log = (in_array($row['key'], $watchlist) &&
329 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
334 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
338 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
343 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
344 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
345 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
346 basename($backtrace[1]["file"]) . "\t" .
347 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
348 substr($query, 0, 4000) . "\n", FILE_APPEND);
354 * Removes every not allowlisted character from the identifier string
356 * @param string $identifier
358 * @return string sanitized identifier
361 private function sanitizeIdentifier($identifier)
363 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
366 public function escape($str)
368 if ($this->connected) {
369 switch ($this->driver) {
371 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
374 return @$this->connection->real_escape_string($str);
377 return str_replace("'", "\\'", $str);
381 public function isConnected()
383 return $this->connected;
386 public function connected()
390 if (is_null($this->connection)) {
394 switch ($this->driver) {
396 $r = $this->p("SELECT 1");
397 if ($this->isResult($r)) {
398 $row = $this->toArray($r);
399 $connected = ($row[0]['1'] == '1');
403 $connected = $this->connection->ping();
411 * Replaces ANY_VALUE() function by MIN() function,
412 * if the database server does not support ANY_VALUE().
414 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
415 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
416 * A standard fall-back is to use MIN().
418 * @param string $sql An SQL string without the values
420 * @return string The input SQL string modified if necessary.
422 public function anyValueFallback($sql)
424 $server_info = $this->serverInfo();
425 if (version_compare($server_info, '5.7.5', '<') ||
426 (stripos($server_info, 'MariaDB') !== false)) {
427 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
433 * Replaces the ? placeholders with the parameters in the $args array
435 * @param string $sql SQL query
436 * @param array $args The parameters that are to replace the ? placeholders
438 * @return string The replaced SQL query
440 private function replaceParameters($sql, $args)
443 foreach ($args AS $param => $value) {
444 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
445 $replace = intval($args[$param]);
446 } elseif (is_null($args[$param])) {
449 $replace = "'" . $this->escape($args[$param]) . "'";
452 $pos = strpos($sql, '?', $offset);
453 if ($pos !== false) {
454 $sql = substr_replace($sql, $replace, $pos, 1);
456 $offset = $pos + strlen($replace);
462 * Executes a prepared statement that returns data
464 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
466 * Please only use it with complicated queries.
467 * For all regular queries please use DBA::select or DBA::exists
469 * @param string $sql SQL statement
471 * @return bool|object statement object or result object
474 public function p($sql)
477 $stamp1 = microtime(true);
479 $params = DBA::getParam(func_get_args());
481 // Renumber the array keys to be sure that they fit
484 foreach ($params AS $param) {
485 // Avoid problems with some MySQL servers and boolean values. See issue #3645
486 if (is_bool($param)) {
487 $param = (int)$param;
489 $args[++$i] = $param;
492 if (!$this->connected) {
496 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
497 // Question: Should we continue or stop the query here?
498 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
501 $sql = DBA::cleanQuery($sql);
502 $sql = $this->anyValueFallback($sql);
506 if ($this->configCache->get('system', 'db_callstack') !== null) {
507 $sql = "/*" . System::callstack() . " */ " . $sql;
513 $this->affected_rows = 0;
515 // We have to make some things different if this function is called from "e"
516 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
518 if (isset($trace[1])) {
519 $called_from = $trace[1];
521 // We use just something that is defined to avoid warnings
522 $called_from = $trace[0];
524 // We are having an own error logging in the function "e"
525 $called_from_e = ($called_from['function'] == 'e');
527 if (!isset($this->connection)) {
528 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
531 switch ($this->driver) {
533 // If there are no arguments we use "query"
534 if ($this->emulate_prepares || count($args) == 0) {
535 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
536 $errorInfo = $this->connection->errorInfo();
537 $this->error = $errorInfo[2];
538 $this->errorno = $errorInfo[1];
543 $this->affected_rows = $retval->rowCount();
547 /** @var $stmt mysqli_stmt|PDOStatement */
548 if (!$stmt = $this->connection->prepare($sql)) {
549 $errorInfo = $this->connection->errorInfo();
550 $this->error = $errorInfo[2];
551 $this->errorno = $errorInfo[1];
557 foreach ($args AS $param => $value) {
558 if (is_int($args[$param])) {
559 $data_type = PDO::PARAM_INT;
561 $data_type = PDO::PARAM_STR;
563 $stmt->bindParam($param, $args[$param], $data_type);
566 if (!$stmt->execute()) {
567 $errorInfo = $stmt->errorInfo();
568 $this->error = $errorInfo[2];
569 $this->errorno = $errorInfo[1];
574 $this->affected_rows = $retval->rowCount();
578 // There are SQL statements that cannot be executed with a prepared statement
579 $parts = explode(' ', $orig_sql);
580 $command = strtolower($parts[0]);
581 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
583 // The fallback routine is called as well when there are no arguments
584 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
585 $retval = $this->connection->query($this->replaceParameters($sql, $args));
586 if ($this->connection->errno) {
587 $this->error = $this->connection->error;
588 $this->errorno = $this->connection->errno;
592 if (isset($retval->num_rows)) {
593 $this->affected_rows = $retval->num_rows;
595 $this->affected_rows = $this->connection->affected_rows;
601 $stmt = $this->connection->stmt_init();
603 if (!$stmt->prepare($sql)) {
604 $this->error = $stmt->error;
605 $this->errorno = $stmt->errno;
613 foreach ($args AS $param => $value) {
614 if (is_int($args[$param])) {
616 } elseif (is_float($args[$param])) {
618 } elseif (is_string($args[$param])) {
623 $values[] = &$args[$param];
626 if (count($values) > 0) {
627 array_unshift($values, $param_types);
628 call_user_func_array([$stmt, 'bind_param'], $values);
631 if (!$stmt->execute()) {
632 $this->error = $this->connection->error;
633 $this->errorno = $this->connection->errno;
637 $stmt->store_result();
639 $this->affected_rows = $retval->affected_rows;
644 // See issue https://github.com/friendica/friendica/issues/8572
645 // Ensure that we always get an error message on an error.
646 if ($is_error && empty($this->errorno)) {
650 if ($is_error && empty($this->error)) {
651 $this->error = 'Unknown database error';
654 // We are having an own error logging in the function "e"
655 if (($this->errorno != 0) && !$called_from_e) {
656 // We have to preserve the error code, somewhere in the logging it get lost
657 $error = $this->error;
658 $errorno = $this->errorno;
660 if ($this->testmode) {
661 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $args)));
664 $this->logger->error('DB Error', [
667 'callstack' => System::callstack(8),
668 'params' => $this->replaceParameters($sql, $args),
671 // On a lost connection we try to reconnect - but only once.
672 if ($errorno == 2006) {
673 if ($this->in_retrial || !$this->reconnect()) {
674 // It doesn't make sense to continue when the database connection was lost
675 if ($this->in_retrial) {
676 $this->logger->notice('Giving up retrial because of database error', [
681 $this->logger->notice('Couldn\'t reconnect after database error', [
689 $this->logger->notice('Reconnected after database error', [
693 $this->in_retrial = true;
694 $ret = $this->p($sql, $args);
695 $this->in_retrial = false;
700 $this->error = $error;
701 $this->errorno = $errorno;
704 $this->profiler->saveTimestamp($stamp1, 'database');
706 if ($this->configCache->get('system', 'db_log')) {
707 $stamp2 = microtime(true);
708 $duration = (float)($stamp2 - $stamp1);
710 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
711 $duration = round($duration, 3);
712 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
714 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
715 basename($backtrace[1]["file"]) . "\t" .
716 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
717 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
724 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
726 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
728 * @param string $sql SQL statement
730 * @return boolean Was the query successfull? False is returned only if an error occurred
733 public function e($sql)
736 $stamp = microtime(true);
738 $params = DBA::getParam(func_get_args());
740 // In a case of a deadlock we are repeating the query 20 times
744 $stmt = $this->p($sql, $params);
746 if (is_bool($stmt)) {
748 } elseif (is_object($stmt)) {
756 } while (($this->errorno == 1213) && (--$timeout > 0));
758 if ($this->errorno != 0) {
759 // We have to preserve the error code, somewhere in the logging it get lost
760 $error = $this->error;
761 $errorno = $this->errorno;
763 if ($this->testmode) {
764 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $params)));
767 $this->logger->error('DB Error', [
770 'callstack' => System::callstack(8),
771 'params' => $this->replaceParameters($sql, $params),
774 // On a lost connection we simply quit.
775 // A reconnect like in $this->p could be dangerous with modifications
776 if ($errorno == 2006) {
777 $this->logger->notice('Giving up because of database error', [
784 $this->error = $error;
785 $this->errorno = $errorno;
788 $this->profiler->saveTimestamp($stamp, "database_write");
794 * Check if data exists
796 * @param string|array $table Table name or array [schema => table]
797 * @param array $condition array of fields for condition
799 * @return boolean Are there rows for that condition?
802 public function exists($table, $condition)
810 if (empty($condition)) {
811 return DBStructure::existsTable($table);
815 $first_key = key($condition);
816 if (!is_int($first_key)) {
817 $fields = [$first_key];
820 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
822 if (is_bool($stmt)) {
825 $retval = ($this->numRows($stmt) > 0);
834 * Fetches the first row
836 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
838 * Fetches the first row
840 * @param string $sql SQL statement
842 * @return array first row of query
845 public function fetchFirst($sql)
847 $params = DBA::getParam(func_get_args());
849 $stmt = $this->p($sql, $params);
851 if (is_bool($stmt)) {
854 $retval = $this->fetch($stmt);
863 * Returns the number of affected rows of the last statement
865 * @return int Number of rows
867 public function affectedRows()
869 return $this->affected_rows;
873 * Returns the number of columns of a statement
875 * @param object Statement object
877 * @return int Number of columns
879 public function columnCount($stmt)
881 if (!is_object($stmt)) {
884 switch ($this->driver) {
886 return $stmt->columnCount();
888 return $stmt->field_count;
894 * Returns the number of rows of a statement
896 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
898 * @return int Number of rows
900 public function numRows($stmt)
902 if (!is_object($stmt)) {
905 switch ($this->driver) {
907 return $stmt->rowCount();
909 return $stmt->num_rows;
917 * @param mixed $stmt statement object
919 * @return array current row
921 public function fetch($stmt)
924 $stamp1 = microtime(true);
928 if (!is_object($stmt)) {
932 switch ($this->driver) {
934 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
937 if (get_class($stmt) == 'mysqli_result') {
938 $columns = $stmt->fetch_assoc();
942 // This code works, but is slow
944 // Bind the result to a result array
948 for ($x = 0; $x < $stmt->field_count; $x++) {
949 $cols[] = &$cols_num[$x];
952 call_user_func_array([$stmt, 'bind_result'], $cols);
954 if (!$stmt->fetch()) {
959 // We need to get the field names for the array keys
960 // It seems that there is no better way to do this.
961 $result = $stmt->result_metadata();
962 $fields = $result->fetch_fields();
964 foreach ($cols_num AS $param => $col) {
965 $columns[$fields[$param]->name] = $col;
969 $this->profiler->saveTimestamp($stamp1, 'database');
975 * Insert a row into a table
977 * @param string|array $table Table name or array [schema => table]
978 * @param array $param parameter array
979 * @param bool $on_duplicate_update Do an update on a duplicate entry
981 * @return boolean was the insert successful?
984 public function insert($table, array $param, bool $on_duplicate_update = false)
986 if (empty($table) || empty($param)) {
987 $this->logger->info('Table and fields have to be set');
991 $table_string = DBA::buildTableString($table);
993 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
995 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
997 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
999 if ($on_duplicate_update) {
1000 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1002 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1004 $values = array_values($param);
1005 $param = array_merge_recursive($values, $values);
1008 return $this->e($sql, $param);
1012 * Inserts a row with the provided data in the provided table.
1013 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1015 * @param string|array $table Table name or array [schema => table]
1016 * @param array $param parameter array
1018 * @return boolean was the insert successful?
1019 * @throws \Exception
1021 public function replace($table, array $param)
1023 if (empty($table) || empty($param)) {
1024 $this->logger->info('Table and fields have to be set');
1028 $table_string = DBA::buildTableString($table);
1030 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1032 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1034 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1036 return $this->e($sql, $param);
1040 * Fetch the id of the last insert command
1042 * @return integer Last inserted id
1044 public function lastInsertId()
1046 switch ($this->driver) {
1048 $id = $this->connection->lastInsertId();
1051 $id = $this->connection->insert_id;
1058 * Locks a table for exclusive write access
1060 * This function can be extended in the future to accept a table array as well.
1062 * @param string|array $table Table name or array [schema => table]
1064 * @return boolean was the lock successful?
1065 * @throws \Exception
1067 public function lock($table)
1069 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1070 if ($this->driver == 'pdo') {
1071 $this->e("SET autocommit=0");
1072 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1074 $this->connection->autocommit(false);
1077 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1079 if ($this->driver == 'pdo') {
1080 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1084 if ($this->driver == 'pdo') {
1085 $this->e("SET autocommit=1");
1087 $this->connection->autocommit(true);
1090 $this->in_transaction = true;
1096 * Unlocks all locked tables
1098 * @return boolean was the unlock successful?
1099 * @throws \Exception
1101 public function unlock()
1103 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1104 $this->performCommit();
1106 if ($this->driver == 'pdo') {
1107 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1110 $success = $this->e("UNLOCK TABLES");
1112 if ($this->driver == 'pdo') {
1113 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1114 $this->e("SET autocommit=1");
1116 $this->connection->autocommit(true);
1119 $this->in_transaction = false;
1124 * Starts a transaction
1126 * @return boolean Was the command executed successfully?
1128 public function transaction()
1130 if (!$this->performCommit()) {
1134 switch ($this->driver) {
1136 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1142 if (!$this->connection->begin_transaction()) {
1148 $this->in_transaction = true;
1152 protected function performCommit()
1154 switch ($this->driver) {
1156 if (!$this->connection->inTransaction()) {
1160 return $this->connection->commit();
1163 return $this->connection->commit();
1172 * @return boolean Was the command executed successfully?
1174 public function commit()
1176 if (!$this->performCommit()) {
1179 $this->in_transaction = false;
1186 * @return boolean Was the command executed successfully?
1188 public function rollback()
1192 switch ($this->driver) {
1194 if (!$this->connection->inTransaction()) {
1198 $ret = $this->connection->rollBack();
1202 $ret = $this->connection->rollback();
1205 $this->in_transaction = false;
1210 * Build the array with the table relations
1212 * The array is build from the database definitions in DBStructure.php
1214 * This process must only be started once, since the value is cached.
1216 private function buildRelationData()
1218 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1220 foreach ($definition AS $table => $structure) {
1221 foreach ($structure['fields'] AS $field => $field_struct) {
1222 if (isset($field_struct['relation'])) {
1223 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1224 $this->relation[$rel_table][$rel_field][$table][] = $field;
1232 * Delete a row from a table
1234 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1236 * @param string $table Table name
1237 * @param array $conditions Field condition(s)
1238 * @param array $options
1239 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1240 * relations (default: true)
1241 * @param array $callstack Internal use: prevent endless loops
1243 * @return boolean was the delete successful?
1244 * @throws \Exception
1246 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1248 if (empty($table) || empty($conditions)) {
1249 $this->logger->info('Table and conditions have to be set');
1255 // Create a key for the loop prevention
1256 $key = $table . ':' . json_encode($conditions);
1258 // We quit when this key already exists in the callstack.
1259 if (isset($callstack[$key])) {
1263 $callstack[$key] = true;
1265 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1267 // Don't use "defaults" here, since it would set "false" to "true"
1268 if (isset($options['cascade'])) {
1269 $cascade = $options['cascade'];
1274 // To speed up the whole process we cache the table relations
1275 if ($cascade && count($this->relation) == 0) {
1276 $this->buildRelationData();
1279 // Is there a relation entry for the table?
1280 if ($cascade && isset($this->relation[$table])) {
1281 // We only allow a simple "one field" relation.
1282 $field = array_keys($this->relation[$table])[0];
1283 $rel_def = array_values($this->relation[$table])[0];
1285 // Create a key for preventing double queries
1286 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1288 // When the search field is the relation field, we don't need to fetch the rows
1289 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1290 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1291 foreach ($rel_def AS $rel_table => $rel_fields) {
1292 foreach ($rel_fields AS $rel_field) {
1293 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1296 // We quit when this key already exists in the callstack.
1297 } elseif (!isset($callstack[$qkey])) {
1298 $callstack[$qkey] = true;
1300 // Fetch all rows that are to be deleted
1301 $data = $this->select($table, [$field], $conditions);
1303 while ($row = $this->fetch($data)) {
1304 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1307 $this->close($data);
1309 // Since we had split the delete command we don't need the original command anymore
1310 unset($commands[$key]);
1314 // Now we finalize the process
1315 $do_transaction = !$this->in_transaction;
1317 if ($do_transaction) {
1318 $this->transaction();
1324 foreach ($commands AS $command) {
1325 $conditions = $command['conditions'];
1327 $first_key = key($conditions);
1329 $condition_string = DBA::buildCondition($conditions);
1331 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1332 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1333 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1335 if (!$this->e($sql, $conditions)) {
1336 if ($do_transaction) {
1342 $key_table = $command['table'];
1343 $key_condition = array_keys($command['conditions'])[0];
1344 $value = array_values($command['conditions'])[0];
1346 // Split the SQL queries in chunks of 100 values
1347 // We do the $i stuff here to make the code better readable
1348 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1349 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1353 $compacted[$key_table][$key_condition][$i][$value] = $value;
1354 $counter[$key_table][$key_condition] = $i;
1357 foreach ($compacted AS $table => $values) {
1358 foreach ($values AS $field => $field_value_list) {
1359 foreach ($field_value_list AS $field_values) {
1360 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1361 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1363 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1365 if (!$this->e($sql, $field_values)) {
1366 if ($do_transaction) {
1374 if ($do_transaction) {
1383 * Updates rows in the database. When $old_fields is set to an array,
1384 * the system will only do an update if the fields in that array changed.
1387 * Only the values in $old_fields are compared.
1388 * This is an intentional behaviour.
1391 * We include the timestamp field in $fields but not in $old_fields.
1392 * Then the row will only get the new timestamp when the other fields had changed.
1394 * When $old_fields is set to a boolean value the system will do this compare itself.
1395 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1398 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1399 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1401 * @param string|array $table Table name or array [schema => table]
1402 * @param array $fields contains the fields that are updated
1403 * @param array $condition condition array with the key values
1404 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1406 * @return boolean was the update successfull?
1407 * @throws \Exception
1409 public function update($table, $fields, $condition, $old_fields = [])
1411 if (empty($table) || empty($fields) || empty($condition)) {
1412 $this->logger->info('Table, fields and condition have to be set');
1416 if (is_bool($old_fields)) {
1417 $do_insert = $old_fields;
1419 $old_fields = $this->selectFirst($table, [], $condition);
1421 if (is_bool($old_fields)) {
1423 $values = array_merge($condition, $fields);
1424 return $this->replace($table, $values);
1430 foreach ($old_fields AS $fieldname => $content) {
1431 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1432 unset($fields[$fieldname]);
1436 if (count($fields) == 0) {
1440 $table_string = DBA::buildTableString($table);
1442 $condition_string = DBA::buildCondition($condition);
1444 $sql = "UPDATE " . $table_string . " SET "
1445 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1446 . $condition_string;
1448 // Combines the updated fields parameter values with the condition parameter values
1449 $params = array_merge(array_values($fields), $condition);
1451 return $this->e($sql, $params);
1455 * Retrieve a single record from a table and returns it in an associative array
1457 * @param string|array $table
1458 * @param array $fields
1459 * @param array $condition
1460 * @param array $params
1462 * @return bool|array
1463 * @throws \Exception
1464 * @see $this->select
1466 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1468 $params['limit'] = 1;
1469 $result = $this->select($table, $fields, $condition, $params);
1471 if (is_bool($result)) {
1474 $row = $this->fetch($result);
1475 $this->close($result);
1481 * Select rows from a table and fills an array with the data
1483 * @param string|array $table Table name or array [schema => table]
1484 * @param array $fields Array of selected fields, empty for all
1485 * @param array $condition Array of fields for condition
1486 * @param array $params Array of several parameters
1488 * @return array Data array
1489 * @throws \Exception
1492 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1494 return $this->toArray($this->select($table, $fields, $condition, $params));
1498 * Select rows from a table
1504 * $table = ['schema' => 'table'];
1505 * @see DBA::buildTableString()
1507 * $fields = ['id', 'uri', 'uid', 'network'];
1509 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1511 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1512 * @see DBA::buildCondition()
1514 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1515 * @see DBA::buildParameter()
1517 * $data = DBA::select($table, $fields, $condition, $params);
1519 * @param string|array $table Table name or array [schema => table]
1520 * @param array $fields Array of selected fields, empty for all
1521 * @param array $condition Array of fields for condition
1522 * @param array $params Array of several parameters
1523 * @return boolean|object
1524 * @throws \Exception
1526 public function select($table, array $fields = [], array $condition = [], array $params = [])
1528 if (empty($table)) {
1532 if (count($fields) > 0) {
1533 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1535 $select_string = '*';
1538 $table_string = DBA::buildTableString($table);
1540 $condition_string = DBA::buildCondition($condition);
1542 $param_string = DBA::buildParameter($params);
1544 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1546 $result = $this->p($sql, $condition);
1552 * Counts the rows from a table satisfying the provided condition
1554 * @param string|array $table Table name or array [schema => table]
1555 * @param array $condition Array of fields for condition
1556 * @param array $params Array of several parameters
1563 * $condition = ["uid" => 1, "network" => 'dspr'];
1565 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1567 * $count = DBA::count($table, $condition);
1568 * @throws \Exception
1570 public function count($table, array $condition = [], array $params = [])
1572 if (empty($table)) {
1576 $table_string = DBA::buildTableString($table);
1578 $condition_string = DBA::buildCondition($condition);
1580 if (empty($params['expression'])) {
1582 } elseif (!empty($params['distinct'])) {
1583 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1585 $expression = DBA::quoteIdentifier($params['expression']);
1588 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1590 $row = $this->fetchFirst($sql, $condition);
1592 return $row['count'];
1596 * Fills an array with data from a query
1598 * @param object $stmt statement object
1599 * @param bool $do_close
1601 * @return array Data array
1603 public function toArray($stmt, $do_close = true)
1605 if (is_bool($stmt)) {
1610 while ($row = $this->fetch($stmt)) {
1615 $this->close($stmt);
1622 * Returns the error number of the last query
1624 * @return string Error number (0 if no error)
1626 public function errorNo()
1628 return $this->errorno;
1632 * Returns the error message of the last query
1634 * @return string Error message ('' if no error)
1636 public function errorMessage()
1638 return $this->error;
1642 * Closes the current statement
1644 * @param object $stmt statement object
1646 * @return boolean was the close successful?
1648 public function close($stmt)
1651 $stamp1 = microtime(true);
1653 if (!is_object($stmt)) {
1657 switch ($this->driver) {
1659 $ret = $stmt->closeCursor();
1662 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1663 // We should be careful not to assume the object type of $stmt
1664 // because DBA::p() has been able to return both types.
1665 if ($stmt instanceof mysqli_stmt) {
1666 $stmt->free_result();
1667 $ret = $stmt->close();
1668 } elseif ($stmt instanceof mysqli_result) {
1677 $this->profiler->saveTimestamp($stamp1, 'database');
1683 * Return a list of database processes
1686 * 'list' => List of processes, separated in their different states
1687 * 'amount' => Number of concurrent database processes
1688 * @throws \Exception
1690 public function processlist()
1692 $ret = $this->p("SHOW PROCESSLIST");
1693 $data = $this->toArray($ret);
1697 foreach ($data as $process) {
1698 $state = trim($process["State"]);
1700 // Filter out all non blocking processes
1701 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1708 foreach ($states as $state => $usage) {
1709 if ($statelist != "") {
1712 $statelist .= $state . ": " . $usage;
1714 return (["list" => $statelist, "amount" => $processes]);
1718 * Fetch a database variable
1720 * @param string $name
1721 * @return string content
1723 public function getVariable(string $name)
1725 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1726 return $result['Value'] ?? null;
1730 * Checks if $array is a filled array with at least one entry.
1732 * @param mixed $array A filled array with at least one entry
1734 * @return boolean Whether $array is a filled array or an object with rows
1736 public function isResult($array)
1738 // It could be a return value from an update statement
1739 if (is_bool($array)) {
1743 if (is_object($array)) {
1744 return $this->numRows($array) > 0;
1747 return (is_array($array) && (count($array) > 0));
1751 * Callback function for "esc_array"
1753 * @param mixed $value Array value
1754 * @param string $key Array key
1755 * @param boolean $add_quotation add quotation marks for string values
1759 private function escapeArrayCallback(&$value, $key, $add_quotation)
1761 if (!$add_quotation) {
1762 if (is_bool($value)) {
1763 $value = ($value ? '1' : '0');
1765 $value = $this->escape($value);
1770 if (is_bool($value)) {
1771 $value = ($value ? 'true' : 'false');
1772 } elseif (is_float($value) || is_integer($value)) {
1773 $value = (string)$value;
1775 $value = "'" . $this->escape($value) . "'";
1780 * Escapes a whole array
1782 * @param mixed $arr Array with values to be escaped
1783 * @param boolean $add_quotation add quotation marks for string values
1787 public function escapeArray(&$arr, $add_quotation = false)
1789 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);