3 * @copyright Copyright (C) 2010-2021, 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\Cache;
25 use Friendica\Core\System;
26 use Friendica\Network\HTTPException\InternalServerErrorException;
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;
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->connected = true;
142 } catch (PDOException $e) {
143 $this->connected = false;
147 if (!$this->connected && class_exists('\mysqli')) {
148 $this->driver = self::MYSQLI;
151 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
153 $this->connection = @new mysqli($server, $user, $pass, $db);
156 if (!mysqli_connect_errno()) {
157 $this->connected = true;
160 $this->connection->set_charset($charset);
165 // No suitable SQL driver was found.
166 if (!$this->connected) {
167 $this->driver = null;
168 $this->connection = null;
171 return $this->connected;
174 public function setTestmode(bool $test)
176 $this->testmode = $test;
179 * Sets the logger for DBA
181 * @note this is necessary because if we want to load the logger configuration
182 * from the DB, but there's an error, we would print out an exception.
183 * So the logger gets updated after the logger configuration can be retrieved
186 * @param LoggerInterface $logger
188 public function setLogger(LoggerInterface $logger)
190 $this->logger = $logger;
194 * Sets the profiler for DBA
196 * @param Profiler $profiler
198 public function setProfiler(Profiler $profiler)
200 $this->profiler = $profiler;
203 * Disconnects the current database connection
205 public function disconnect()
207 if (!is_null($this->connection)) {
208 switch ($this->driver) {
210 $this->connection = null;
213 $this->connection->close();
214 $this->connection = null;
219 $this->driver = null;
220 $this->connected = false;
224 * Perform a reconnect of an existing database connection
226 public function reconnect()
229 return $this->connect();
233 * Return the database object.
237 public function getConnection()
239 return $this->connection;
243 * Return the database driver string
245 * @return string with either "pdo" or "mysqli"
247 public function getDriver()
249 return $this->driver;
253 * Returns the MySQL server version string
255 * This function discriminate between the deprecated mysql API and the current
256 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
260 public function serverInfo()
262 if ($this->server_info == '') {
263 switch ($this->driver) {
265 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
268 $this->server_info = $this->connection->server_info;
272 return $this->server_info;
276 * Returns the selected database name
281 public function databaseName()
283 $ret = $this->p("SELECT DATABASE() AS `db`");
284 $data = $this->toArray($ret);
285 return $data[0]['db'];
289 * Analyze a database query and log this if some conditions are met.
291 * @param string $query The database query that will be analyzed
295 private function logIndex($query)
298 if (!$this->configCache->get('system', 'db_log_index')) {
302 // Don't explain an explain statement
303 if (strtolower(substr($query, 0, 7)) == "explain") {
307 // Only do the explain on "select", "update" and "delete"
308 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
312 $r = $this->p("EXPLAIN " . $query);
313 if (!$this->isResult($r)) {
317 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
318 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
320 while ($row = $this->fetch($r)) {
321 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
322 $log = (in_array($row['key'], $watchlist) &&
323 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
328 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
332 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
337 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
338 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
339 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
340 basename($backtrace[1]["file"]) . "\t" .
341 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
342 substr($query, 0, 4000) . "\n", FILE_APPEND);
348 * Removes every not allowlisted character from the identifier string
350 * @param string $identifier
352 * @return string sanitized identifier
355 private function sanitizeIdentifier($identifier)
357 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
360 public function escape($str)
362 if ($this->connected) {
363 switch ($this->driver) {
365 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
368 return @$this->connection->real_escape_string($str);
371 return str_replace("'", "\\'", $str);
375 public function isConnected()
377 return $this->connected;
380 public function connected()
384 if (is_null($this->connection)) {
388 switch ($this->driver) {
390 $r = $this->p("SELECT 1");
391 if ($this->isResult($r)) {
392 $row = $this->toArray($r);
393 $connected = ($row[0]['1'] == '1');
397 $connected = $this->connection->ping();
405 * Replaces ANY_VALUE() function by MIN() function,
406 * if the database server does not support ANY_VALUE().
408 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
409 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
410 * A standard fall-back is to use MIN().
412 * @param string $sql An SQL string without the values
414 * @return string The input SQL string modified if necessary.
416 public function anyValueFallback($sql)
418 $server_info = $this->serverInfo();
419 if (version_compare($server_info, '5.7.5', '<') ||
420 (stripos($server_info, 'MariaDB') !== false)) {
421 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
427 * Replaces the ? placeholders with the parameters in the $args array
429 * @param string $sql SQL query
430 * @param array $args The parameters that are to replace the ? placeholders
432 * @return string The replaced SQL query
434 private function replaceParameters($sql, $args)
437 foreach ($args AS $param => $value) {
438 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
439 $replace = intval($args[$param]);
440 } elseif (is_null($args[$param])) {
443 $replace = "'" . $this->escape($args[$param]) . "'";
446 $pos = strpos($sql, '?', $offset);
447 if ($pos !== false) {
448 $sql = substr_replace($sql, $replace, $pos, 1);
450 $offset = $pos + strlen($replace);
456 * Executes a prepared statement that returns data
458 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
460 * Please only use it with complicated queries.
461 * For all regular queries please use DBA::select or DBA::exists
463 * @param string $sql SQL statement
465 * @return bool|object statement object or result object
468 public function p($sql)
471 $stamp1 = microtime(true);
473 $params = DBA::getParam(func_get_args());
475 // Renumber the array keys to be sure that they fit
478 foreach ($params AS $param) {
479 // Avoid problems with some MySQL servers and boolean values. See issue #3645
480 if (is_bool($param)) {
481 $param = (int)$param;
483 $args[++$i] = $param;
486 if (!$this->connected) {
490 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
491 // Question: Should we continue or stop the query here?
492 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
495 $sql = DBA::cleanQuery($sql);
496 $sql = $this->anyValueFallback($sql);
500 if ($this->configCache->get('system', 'db_callstack') !== null) {
501 $sql = "/*" . System::callstack() . " */ " . $sql;
507 $this->affected_rows = 0;
509 // We have to make some things different if this function is called from "e"
510 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
512 if (isset($trace[1])) {
513 $called_from = $trace[1];
515 // We use just something that is defined to avoid warnings
516 $called_from = $trace[0];
518 // We are having an own error logging in the function "e"
519 $called_from_e = ($called_from['function'] == 'e');
521 if (!isset($this->connection)) {
522 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
525 switch ($this->driver) {
527 // If there are no arguments we use "query"
528 if (count($args) == 0) {
529 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
530 $errorInfo = $this->connection->errorInfo();
531 $this->error = $errorInfo[2];
532 $this->errorno = $errorInfo[1];
537 $this->affected_rows = $retval->rowCount();
541 /** @var $stmt mysqli_stmt|PDOStatement */
542 if (!$stmt = $this->connection->prepare($sql)) {
543 $errorInfo = $this->connection->errorInfo();
544 $this->error = $errorInfo[2];
545 $this->errorno = $errorInfo[1];
551 foreach ($args AS $param => $value) {
552 if (is_int($args[$param])) {
553 $data_type = PDO::PARAM_INT;
555 $data_type = PDO::PARAM_STR;
557 $stmt->bindParam($param, $args[$param], $data_type);
560 if (!$stmt->execute()) {
561 $errorInfo = $stmt->errorInfo();
562 $this->error = $errorInfo[2];
563 $this->errorno = $errorInfo[1];
568 $this->affected_rows = $retval->rowCount();
572 // There are SQL statements that cannot be executed with a prepared statement
573 $parts = explode(' ', $orig_sql);
574 $command = strtolower($parts[0]);
575 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
577 // The fallback routine is called as well when there are no arguments
578 if (!$can_be_prepared || (count($args) == 0)) {
579 $retval = $this->connection->query($this->replaceParameters($sql, $args));
580 if ($this->connection->errno) {
581 $this->error = $this->connection->error;
582 $this->errorno = $this->connection->errno;
586 if (isset($retval->num_rows)) {
587 $this->affected_rows = $retval->num_rows;
589 $this->affected_rows = $this->connection->affected_rows;
595 $stmt = $this->connection->stmt_init();
597 if (!$stmt->prepare($sql)) {
598 $this->error = $stmt->error;
599 $this->errorno = $stmt->errno;
607 foreach ($args AS $param => $value) {
608 if (is_int($args[$param])) {
610 } elseif (is_float($args[$param])) {
612 } elseif (is_string($args[$param])) {
617 $values[] = &$args[$param];
620 if (count($values) > 0) {
621 array_unshift($values, $param_types);
622 call_user_func_array([$stmt, 'bind_param'], $values);
625 if (!$stmt->execute()) {
626 $this->error = $this->connection->error;
627 $this->errorno = $this->connection->errno;
631 $stmt->store_result();
633 $this->affected_rows = $retval->affected_rows;
638 // See issue https://github.com/friendica/friendica/issues/8572
639 // Ensure that we always get an error message on an error.
640 if ($is_error && empty($this->errorno)) {
644 if ($is_error && empty($this->error)) {
645 $this->error = 'Unknown database error';
648 // We are having an own error logging in the function "e"
649 if (($this->errorno != 0) && !$called_from_e) {
650 // We have to preserve the error code, somewhere in the logging it get lost
651 $error = $this->error;
652 $errorno = $this->errorno;
654 if ($this->testmode) {
655 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
658 $this->logger->error('DB Error', [
661 'callstack' => System::callstack(8),
662 'params' => $this->replaceParameters($sql, $args),
665 // On a lost connection we try to reconnect - but only once.
666 if ($errorno == 2006) {
667 if ($this->in_retrial || !$this->reconnect()) {
668 // It doesn't make sense to continue when the database connection was lost
669 if ($this->in_retrial) {
670 $this->logger->notice('Giving up retrial because of database error', [
675 $this->logger->notice('Couldn\'t reconnect after database error', [
683 $this->logger->notice('Reconnected after database error', [
687 $this->in_retrial = true;
688 $ret = $this->p($sql, $args);
689 $this->in_retrial = false;
694 $this->error = $error;
695 $this->errorno = $errorno;
698 $this->profiler->saveTimestamp($stamp1, 'database');
700 if ($this->configCache->get('system', 'db_log')) {
701 $stamp2 = microtime(true);
702 $duration = (float)($stamp2 - $stamp1);
704 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
705 $duration = round($duration, 3);
706 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
708 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
709 basename($backtrace[1]["file"]) . "\t" .
710 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
711 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
718 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
720 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
722 * @param string $sql SQL statement
724 * @return boolean Was the query successfull? False is returned only if an error occurred
727 public function e($sql)
730 $stamp = microtime(true);
732 $params = DBA::getParam(func_get_args());
734 // In a case of a deadlock we are repeating the query 20 times
738 $stmt = $this->p($sql, $params);
740 if (is_bool($stmt)) {
742 } elseif (is_object($stmt)) {
750 } while (($this->errorno == 1213) && (--$timeout > 0));
752 if ($this->errorno != 0) {
753 // We have to preserve the error code, somewhere in the logging it get lost
754 $error = $this->error;
755 $errorno = $this->errorno;
757 if ($this->testmode) {
758 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
761 $this->logger->error('DB Error', [
764 'callstack' => System::callstack(8),
765 'params' => $this->replaceParameters($sql, $params),
768 // On a lost connection we simply quit.
769 // A reconnect like in $this->p could be dangerous with modifications
770 if ($errorno == 2006) {
771 $this->logger->notice('Giving up because of database error', [
778 $this->error = $error;
779 $this->errorno = $errorno;
782 $this->profiler->saveTimestamp($stamp, "database_write");
788 * Check if data exists
790 * @param string|array $table Table name or array [schema => table]
791 * @param array $condition array of fields for condition
793 * @return boolean Are there rows for that condition?
796 public function exists($table, $condition)
804 if (empty($condition)) {
805 return DBStructure::existsTable($table);
809 $first_key = key($condition);
810 if (!is_int($first_key)) {
811 $fields = [$first_key];
814 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
816 if (is_bool($stmt)) {
819 $retval = ($this->numRows($stmt) > 0);
828 * Fetches the first row
830 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
832 * Fetches the first row
834 * @param string $sql SQL statement
836 * @return array first row of query
839 public function fetchFirst($sql)
841 $params = DBA::getParam(func_get_args());
843 $stmt = $this->p($sql, $params);
845 if (is_bool($stmt)) {
848 $retval = $this->fetch($stmt);
857 * Returns the number of affected rows of the last statement
859 * @return int Number of rows
861 public function affectedRows()
863 return $this->affected_rows;
867 * Returns the number of columns of a statement
869 * @param object Statement object
871 * @return int Number of columns
873 public function columnCount($stmt)
875 if (!is_object($stmt)) {
878 switch ($this->driver) {
880 return $stmt->columnCount();
882 return $stmt->field_count;
888 * Returns the number of rows of a statement
890 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
892 * @return int Number of rows
894 public function numRows($stmt)
896 if (!is_object($stmt)) {
899 switch ($this->driver) {
901 return $stmt->rowCount();
903 return $stmt->num_rows;
911 * @param PDOStatement|mysqli_stmt $stmt statement object
913 * @return array|false current row
915 public function fetch($stmt)
917 $stamp1 = microtime(true);
921 if (!is_object($stmt)) {
925 switch ($this->driver) {
927 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
928 if (!empty($stmt->table) && is_array($columns)) {
929 $columns = $this->castFields($stmt->table, $columns);
933 if (get_class($stmt) == 'mysqli_result') {
934 $columns = $stmt->fetch_assoc() ?? false;
938 // This code works, but is slow
940 // Bind the result to a result array
944 for ($x = 0; $x < $stmt->field_count; $x++) {
945 $cols[] = &$cols_num[$x];
948 call_user_func_array([$stmt, 'bind_result'], $cols);
950 if (!$stmt->fetch()) {
955 // We need to get the field names for the array keys
956 // It seems that there is no better way to do this.
957 $result = $stmt->result_metadata();
958 $fields = $result->fetch_fields();
960 foreach ($cols_num AS $param => $col) {
961 $columns[$fields[$param]->name] = $col;
965 $this->profiler->saveTimestamp($stamp1, 'database');
971 * Insert a row into a table
973 * @param string|array $table Table name or array [schema => table]
974 * @param array $param parameter array
975 * @param int $duplicate_mode What to do on a duplicated entry
977 * @return boolean was the insert successful?
980 public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT)
982 if (empty($table) || empty($param)) {
983 $this->logger->info('Table and fields have to be set');
987 $param = $this->castFields($table, $param);
989 $table_string = DBA::buildTableString($table);
991 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
993 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
997 if ($duplicate_mode == self::INSERT_IGNORE) {
1001 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1003 if ($duplicate_mode == self::INSERT_UPDATE) {
1004 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1006 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1008 $values = array_values($param);
1009 $param = array_merge_recursive($values, $values);
1012 $result = $this->e($sql, $param);
1013 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1017 return $this->affectedRows() != 0;
1021 * Inserts a row with the provided data in the provided table.
1022 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1024 * @param string|array $table Table name or array [schema => table]
1025 * @param array $param parameter array
1027 * @return boolean was the insert successful?
1028 * @throws \Exception
1030 public function replace($table, array $param)
1032 if (empty($table) || empty($param)) {
1033 $this->logger->info('Table and fields have to be set');
1037 $param = $this->castFields($table, $param);
1039 $table_string = DBA::buildTableString($table);
1041 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1043 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1045 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1047 return $this->e($sql, $param);
1051 * Fetch the id of the last insert command
1053 * @return integer Last inserted id
1055 public function lastInsertId()
1057 switch ($this->driver) {
1059 $id = $this->connection->lastInsertId();
1062 $id = $this->connection->insert_id;
1069 * Locks a table for exclusive write access
1071 * This function can be extended in the future to accept a table array as well.
1073 * @param string|array $table Table name or array [schema => table]
1075 * @return boolean was the lock successful?
1076 * @throws \Exception
1078 public function lock($table)
1080 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1081 if ($this->driver == self::PDO) {
1082 $this->e("SET autocommit=0");
1083 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1085 $this->connection->autocommit(false);
1088 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1090 if ($this->driver == self::PDO) {
1091 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1095 if ($this->driver == self::PDO) {
1096 $this->e("SET autocommit=1");
1098 $this->connection->autocommit(true);
1101 $this->in_transaction = true;
1107 * Unlocks all locked tables
1109 * @return boolean was the unlock successful?
1110 * @throws \Exception
1112 public function unlock()
1114 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1115 $this->performCommit();
1117 if ($this->driver == self::PDO) {
1118 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1121 $success = $this->e("UNLOCK TABLES");
1123 if ($this->driver == self::PDO) {
1124 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1125 $this->e("SET autocommit=1");
1127 $this->connection->autocommit(true);
1130 $this->in_transaction = false;
1135 * Starts a transaction
1137 * @return boolean Was the command executed successfully?
1139 public function transaction()
1141 if (!$this->performCommit()) {
1145 switch ($this->driver) {
1147 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1153 if (!$this->connection->begin_transaction()) {
1159 $this->in_transaction = true;
1163 protected function performCommit()
1165 switch ($this->driver) {
1167 if (!$this->connection->inTransaction()) {
1171 return $this->connection->commit();
1174 return $this->connection->commit();
1183 * @return boolean Was the command executed successfully?
1185 public function commit()
1187 if (!$this->performCommit()) {
1190 $this->in_transaction = false;
1197 * @return boolean Was the command executed successfully?
1199 public function rollback()
1203 switch ($this->driver) {
1205 if (!$this->connection->inTransaction()) {
1209 $ret = $this->connection->rollBack();
1213 $ret = $this->connection->rollback();
1216 $this->in_transaction = false;
1221 * Delete a row from a table
1223 * @param string $table Table name
1224 * @param array $conditions Field condition(s)
1226 * @return boolean was the delete successful?
1227 * @throws \Exception
1229 public function delete($table, array $conditions)
1231 if (empty($table) || empty($conditions)) {
1232 $this->logger->info('Table and conditions have to be set');
1236 $table_string = DBA::buildTableString($table);
1238 $condition_string = DBA::buildCondition($conditions);
1240 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1241 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1242 return $this->e($sql, $conditions);
1248 * Updates rows in the database. When $old_fields is set to an array,
1249 * the system will only do an update if the fields in that array changed.
1252 * Only the values in $old_fields are compared.
1253 * This is an intentional behaviour.
1256 * We include the timestamp field in $fields but not in $old_fields.
1257 * Then the row will only get the new timestamp when the other fields had changed.
1259 * When $old_fields is set to a boolean value the system will do this compare itself.
1260 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1263 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1264 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1266 * @param string|array $table Table name or array [schema => table]
1267 * @param array $fields contains the fields that are updated
1268 * @param array $condition condition array with the key values
1269 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1271 * @return boolean was the update successfull?
1272 * @throws \Exception
1274 public function update($table, $fields, $condition, $old_fields = [])
1276 if (empty($table) || empty($fields) || empty($condition)) {
1277 $this->logger->info('Table, fields and condition have to be set');
1281 if (is_bool($old_fields)) {
1282 $do_insert = $old_fields;
1284 $old_fields = $this->selectFirst($table, [], $condition);
1286 if (is_bool($old_fields)) {
1288 $values = array_merge($condition, $fields);
1289 return $this->replace($table, $values);
1295 foreach ($old_fields AS $fieldname => $content) {
1296 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1297 unset($fields[$fieldname]);
1301 if (count($fields) == 0) {
1305 $fields = $this->castFields($table, $fields);
1307 $table_string = DBA::buildTableString($table);
1309 $condition_string = DBA::buildCondition($condition);
1311 $sql = "UPDATE " . $table_string . " SET "
1312 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1313 . $condition_string;
1315 // Combines the updated fields parameter values with the condition parameter values
1316 $params = array_merge(array_values($fields), $condition);
1318 return $this->e($sql, $params);
1322 * Retrieve a single record from a table and returns it in an associative array
1324 * @param string|array $table
1325 * @param array $fields
1326 * @param array $condition
1327 * @param array $params
1329 * @return bool|array
1330 * @throws \Exception
1331 * @see $this->select
1333 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1335 $params['limit'] = 1;
1336 $result = $this->select($table, $fields, $condition, $params);
1338 if (is_bool($result)) {
1341 $row = $this->fetch($result);
1342 $this->close($result);
1348 * Select rows from a table and fills an array with the data
1350 * @param string|array $table Table name or array [schema => table]
1351 * @param array $fields Array of selected fields, empty for all
1352 * @param array $condition Array of fields for condition
1353 * @param array $params Array of several parameters
1355 * @return array Data array
1356 * @throws \Exception
1359 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1361 return $this->toArray($this->select($table, $fields, $condition, $params));
1365 * Select rows from a table
1371 * $table = ['schema' => 'table'];
1372 * @see DBA::buildTableString()
1374 * $fields = ['id', 'uri', 'uid', 'network'];
1376 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1378 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1379 * @see DBA::buildCondition()
1381 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1382 * @see DBA::buildParameter()
1384 * $data = DBA::select($table, $fields, $condition, $params);
1386 * @param string|array $table Table name or array [schema => table]
1387 * @param array $fields Array of selected fields, empty for all
1388 * @param array $condition Array of fields for condition
1389 * @param array $params Array of several parameters
1390 * @return boolean|object
1391 * @throws \Exception
1393 public function select($table, array $fields = [], array $condition = [], array $params = [])
1395 if (empty($table)) {
1399 if (count($fields) > 0) {
1400 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1402 $select_string = '*';
1405 $table_string = DBA::buildTableString($table);
1407 $condition_string = DBA::buildCondition($condition);
1409 $param_string = DBA::buildParameter($params);
1411 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1413 $result = $this->p($sql, $condition);
1415 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1416 $result->table = $table;
1423 * Counts the rows from a table satisfying the provided condition
1425 * @param string|array $table Table name or array [schema => table]
1426 * @param array $condition Array of fields for condition
1427 * @param array $params Array of several parameters
1434 * $condition = ["uid" => 1, "network" => 'dspr'];
1436 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1438 * $count = DBA::count($table, $condition);
1439 * @throws \Exception
1441 public function count($table, array $condition = [], array $params = [])
1443 if (empty($table)) {
1447 $table_string = DBA::buildTableString($table);
1449 $condition_string = DBA::buildCondition($condition);
1451 if (empty($params['expression'])) {
1453 } elseif (!empty($params['distinct'])) {
1454 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1456 $expression = DBA::quoteIdentifier($params['expression']);
1459 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1461 $row = $this->fetchFirst($sql, $condition);
1463 // Ensure to always return either a "null" or a numeric value
1464 return is_numeric($row['count']) ? (int)$row['count'] : $row['count'];
1468 * Fills an array with data from a query
1470 * @param object $stmt statement object
1471 * @param bool $do_close Close database connection after last row
1472 * @param int $count maximum number of rows to be fetched
1474 * @return array Data array
1476 public function toArray($stmt, $do_close = true, int $count = 0)
1478 if (is_bool($stmt)) {
1483 while ($row = $this->fetch($stmt)) {
1485 if (($count != 0) && (count($data) == $count)) {
1491 $this->close($stmt);
1498 * Cast field types according to the table definition
1500 * @param string $table
1501 * @param array $fields
1502 * @return array casted fields
1504 public function castFields(string $table, array $fields) {
1505 // When there is no data, we don't need to do something
1506 if (empty($fields)) {
1510 // We only need to cast fields with PDO
1511 if ($this->driver != self::PDO) {
1515 // We only need to cast when emulating the prepares
1516 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1522 $tables = DBStructure::definition('', false);
1523 if (empty($tables[$table])) {
1524 // When a matching table wasn't found we check if it is a view
1525 $views = View::definition('', false);
1526 if (empty($views[$table])) {
1530 foreach(array_keys($fields) as $field) {
1531 if (!empty($views[$table]['fields'][$field])) {
1532 $viewdef = $views[$table]['fields'][$field];
1533 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1534 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1539 foreach ($tables[$table]['fields'] as $field => $definition) {
1540 $types[$field] = $definition['type'];
1544 foreach ($fields as $field => $content) {
1545 if (is_null($content) || empty($types[$field])) {
1549 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1550 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1551 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1552 $fields[$field] = (int)$content;
1554 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1555 $fields[$field] = (float)$content;
1563 * Returns the error number of the last query
1565 * @return string Error number (0 if no error)
1567 public function errorNo()
1569 return $this->errorno;
1573 * Returns the error message of the last query
1575 * @return string Error message ('' if no error)
1577 public function errorMessage()
1579 return $this->error;
1583 * Closes the current statement
1585 * @param object $stmt statement object
1587 * @return boolean was the close successful?
1589 public function close($stmt)
1592 $stamp1 = microtime(true);
1594 if (!is_object($stmt)) {
1598 switch ($this->driver) {
1600 $ret = $stmt->closeCursor();
1603 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1604 // We should be careful not to assume the object type of $stmt
1605 // because DBA::p() has been able to return both types.
1606 if ($stmt instanceof mysqli_stmt) {
1607 $stmt->free_result();
1608 $ret = $stmt->close();
1609 } elseif ($stmt instanceof mysqli_result) {
1618 $this->profiler->saveTimestamp($stamp1, 'database');
1624 * Return a list of database processes
1627 * 'list' => List of processes, separated in their different states
1628 * 'amount' => Number of concurrent database processes
1629 * @throws \Exception
1631 public function processlist()
1633 $ret = $this->p("SHOW PROCESSLIST");
1634 $data = $this->toArray($ret);
1638 foreach ($data as $process) {
1639 $state = trim($process["State"]);
1641 // Filter out all non blocking processes
1642 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1649 foreach ($states as $state => $usage) {
1650 if ($statelist != "") {
1653 $statelist .= $state . ": " . $usage;
1655 return (["list" => $statelist, "amount" => $processes]);
1659 * Fetch a database variable
1661 * @param string $name
1662 * @return string content
1664 public function getVariable(string $name)
1666 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1667 return $result['Value'] ?? null;
1671 * Checks if $array is a filled array with at least one entry.
1673 * @param mixed $array A filled array with at least one entry
1675 * @return boolean Whether $array is a filled array or an object with rows
1677 public function isResult($array)
1679 // It could be a return value from an update statement
1680 if (is_bool($array)) {
1684 if (is_object($array)) {
1685 return $this->numRows($array) > 0;
1688 return (is_array($array) && (count($array) > 0));
1692 * Callback function for "esc_array"
1694 * @param mixed $value Array value
1695 * @param string $key Array key
1696 * @param boolean $add_quotation add quotation marks for string values
1700 private function escapeArrayCallback(&$value, $key, $add_quotation)
1702 if (!$add_quotation) {
1703 if (is_bool($value)) {
1704 $value = ($value ? '1' : '0');
1706 $value = $this->escape($value);
1711 if (is_bool($value)) {
1712 $value = ($value ? 'true' : 'false');
1713 } elseif (is_float($value) || is_integer($value)) {
1714 $value = (string)$value;
1716 $value = "'" . $this->escape($value) . "'";
1721 * Escapes a whole array
1723 * @param mixed $arr Array with values to be escaped
1724 * @param boolean $add_quotation add quotation marks for string values
1728 public function escapeArray(&$arr, $add_quotation = false)
1730 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);