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;
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 $emulate_prepares = false;
68 protected $pdo_emulate_prepares = false;
69 private $error = false;
71 private $affected_rows = 0;
72 protected $in_transaction = false;
73 protected $in_retrial = false;
74 protected $testmode = false;
75 private $relation = [];
77 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger)
79 // We are storing these values for being able to perform a reconnect
80 $this->configCache = $configCache;
81 $this->profiler = $profiler;
82 $this->logger = $logger;
86 if ($this->isConnected()) {
87 // Loads DB_UPDATE_VERSION constant
88 DBStructure::definition($configCache->get('system', 'basepath'), false);
92 public function connect()
94 if (!is_null($this->connection) && $this->connected()) {
95 return $this->connected;
98 // Reset connected state
99 $this->connected = false;
102 $serveraddr = trim($this->configCache->get('database', 'hostname'));
103 $serverdata = explode(':', $serveraddr);
104 $server = $serverdata[0];
105 if (count($serverdata) > 1) {
106 $port = trim($serverdata[1]);
109 if (!empty(trim($this->configCache->get('database', 'port')))) {
110 $port = trim($this->configCache->get('database', 'port'));
113 $server = trim($server);
114 $user = trim($this->configCache->get('database', 'username'));
115 $pass = trim($this->configCache->get('database', 'password'));
116 $db = trim($this->configCache->get('database', 'database'));
117 $charset = trim($this->configCache->get('database', 'charset'));
119 if (!(strlen($server) && strlen($user))) {
123 $persistent = (bool)$this->configCache->get('database', 'persistent');
125 $this->emulate_prepares = (bool)$this->configCache->get('database', 'emulate_prepares');
126 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
128 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
129 $this->driver = self::PDO;
130 $connect = "mysql:host=" . $server . ";dbname=" . $db;
133 $connect .= ";port=" . $port;
137 $connect .= ";charset=" . $charset;
141 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
142 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
143 $this->connected = true;
144 } catch (PDOException $e) {
145 $this->connected = false;
149 if (!$this->connected && class_exists('\mysqli')) {
150 $this->driver = self::MYSQLI;
153 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
155 $this->connection = @new mysqli($server, $user, $pass, $db);
158 if (!mysqli_connect_errno()) {
159 $this->connected = true;
162 $this->connection->set_charset($charset);
167 // No suitable SQL driver was found.
168 if (!$this->connected) {
169 $this->driver = null;
170 $this->connection = null;
173 return $this->connected;
176 public function setTestmode(bool $test)
178 $this->testmode = $test;
181 * Sets the logger for DBA
183 * @note this is necessary because if we want to load the logger configuration
184 * from the DB, but there's an error, we would print out an exception.
185 * So the logger gets updated after the logger configuration can be retrieved
188 * @param LoggerInterface $logger
190 public function setLogger(LoggerInterface $logger)
192 $this->logger = $logger;
196 * Sets the profiler for DBA
198 * @param Profiler $profiler
200 public function setProfiler(Profiler $profiler)
202 $this->profiler = $profiler;
205 * Disconnects the current database connection
207 public function disconnect()
209 if (!is_null($this->connection)) {
210 switch ($this->driver) {
212 $this->connection = null;
215 $this->connection->close();
216 $this->connection = null;
221 $this->driver = null;
222 $this->connected = false;
226 * Perform a reconnect of an existing database connection
228 public function reconnect()
231 return $this->connect();
235 * Return the database object.
239 public function getConnection()
241 return $this->connection;
245 * Return the database driver string
247 * @return string with either "pdo" or "mysqli"
249 public function getDriver()
251 return $this->driver;
255 * Returns the MySQL server version string
257 * This function discriminate between the deprecated mysql API and the current
258 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
262 public function serverInfo()
264 if ($this->server_info == '') {
265 switch ($this->driver) {
267 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
270 $this->server_info = $this->connection->server_info;
274 return $this->server_info;
278 * Returns the selected database name
283 public function databaseName()
285 $ret = $this->p("SELECT DATABASE() AS `db`");
286 $data = $this->toArray($ret);
287 return $data[0]['db'];
291 * Analyze a database query and log this if some conditions are met.
293 * @param string $query The database query that will be analyzed
297 private function logIndex($query)
300 if (!$this->configCache->get('system', 'db_log_index')) {
304 // Don't explain an explain statement
305 if (strtolower(substr($query, 0, 7)) == "explain") {
309 // Only do the explain on "select", "update" and "delete"
310 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
314 $r = $this->p("EXPLAIN " . $query);
315 if (!$this->isResult($r)) {
319 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
320 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
322 while ($row = $this->fetch($r)) {
323 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
324 $log = (in_array($row['key'], $watchlist) &&
325 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
330 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
334 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
339 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
340 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
341 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
342 basename($backtrace[1]["file"]) . "\t" .
343 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
344 substr($query, 0, 4000) . "\n", FILE_APPEND);
350 * Removes every not allowlisted character from the identifier string
352 * @param string $identifier
354 * @return string sanitized identifier
357 private function sanitizeIdentifier($identifier)
359 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
362 public function escape($str)
364 if ($this->connected) {
365 switch ($this->driver) {
367 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
370 return @$this->connection->real_escape_string($str);
373 return str_replace("'", "\\'", $str);
377 public function isConnected()
379 return $this->connected;
382 public function connected()
386 if (is_null($this->connection)) {
390 switch ($this->driver) {
392 $r = $this->p("SELECT 1");
393 if ($this->isResult($r)) {
394 $row = $this->toArray($r);
395 $connected = ($row[0]['1'] == '1');
399 $connected = $this->connection->ping();
407 * Replaces ANY_VALUE() function by MIN() function,
408 * if the database server does not support ANY_VALUE().
410 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
411 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
412 * A standard fall-back is to use MIN().
414 * @param string $sql An SQL string without the values
416 * @return string The input SQL string modified if necessary.
418 public function anyValueFallback($sql)
420 $server_info = $this->serverInfo();
421 if (version_compare($server_info, '5.7.5', '<') ||
422 (stripos($server_info, 'MariaDB') !== false)) {
423 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
429 * Replaces the ? placeholders with the parameters in the $args array
431 * @param string $sql SQL query
432 * @param array $args The parameters that are to replace the ? placeholders
434 * @return string The replaced SQL query
436 private function replaceParameters($sql, $args)
439 foreach ($args AS $param => $value) {
440 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
441 $replace = intval($args[$param]);
442 } elseif (is_null($args[$param])) {
445 $replace = "'" . $this->escape($args[$param]) . "'";
448 $pos = strpos($sql, '?', $offset);
449 if ($pos !== false) {
450 $sql = substr_replace($sql, $replace, $pos, 1);
452 $offset = $pos + strlen($replace);
458 * Executes a prepared statement that returns data
460 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
462 * Please only use it with complicated queries.
463 * For all regular queries please use DBA::select or DBA::exists
465 * @param string $sql SQL statement
467 * @return bool|object statement object or result object
470 public function p($sql)
473 $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 InternalServerErrorException('The Connection is empty, although connected is set true.');
527 switch ($this->driver) {
529 // If there are no arguments we use "query"
530 if ($this->emulate_prepares || 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 ($args AS $param => $value) {
554 if (is_int($args[$param])) {
555 $data_type = PDO::PARAM_INT;
557 $data_type = PDO::PARAM_STR;
559 $stmt->bindParam($param, $args[$param], $data_type);
562 if (!$stmt->execute()) {
563 $errorInfo = $stmt->errorInfo();
564 $this->error = $errorInfo[2];
565 $this->errorno = $errorInfo[1];
570 $this->affected_rows = $retval->rowCount();
574 // There are SQL statements that cannot be executed with a prepared statement
575 $parts = explode(' ', $orig_sql);
576 $command = strtolower($parts[0]);
577 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
579 // The fallback routine is called as well when there are no arguments
580 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
581 $retval = $this->connection->query($this->replaceParameters($sql, $args));
582 if ($this->connection->errno) {
583 $this->error = $this->connection->error;
584 $this->errorno = $this->connection->errno;
588 if (isset($retval->num_rows)) {
589 $this->affected_rows = $retval->num_rows;
591 $this->affected_rows = $this->connection->affected_rows;
597 $stmt = $this->connection->stmt_init();
599 if (!$stmt->prepare($sql)) {
600 $this->error = $stmt->error;
601 $this->errorno = $stmt->errno;
609 foreach ($args AS $param => $value) {
610 if (is_int($args[$param])) {
612 } elseif (is_float($args[$param])) {
614 } elseif (is_string($args[$param])) {
619 $values[] = &$args[$param];
622 if (count($values) > 0) {
623 array_unshift($values, $param_types);
624 call_user_func_array([$stmt, 'bind_param'], $values);
627 if (!$stmt->execute()) {
628 $this->error = $this->connection->error;
629 $this->errorno = $this->connection->errno;
633 $stmt->store_result();
635 $this->affected_rows = $retval->affected_rows;
640 // See issue https://github.com/friendica/friendica/issues/8572
641 // Ensure that we always get an error message on an error.
642 if ($is_error && empty($this->errorno)) {
646 if ($is_error && empty($this->error)) {
647 $this->error = 'Unknown database error';
650 // We are having an own error logging in the function "e"
651 if (($this->errorno != 0) && !$called_from_e) {
652 // We have to preserve the error code, somewhere in the logging it get lost
653 $error = $this->error;
654 $errorno = $this->errorno;
656 if ($this->testmode) {
657 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
660 $this->logger->error('DB Error', [
663 'callstack' => System::callstack(8),
664 'params' => $this->replaceParameters($sql, $args),
667 // On a lost connection we try to reconnect - but only once.
668 if ($errorno == 2006) {
669 if ($this->in_retrial || !$this->reconnect()) {
670 // It doesn't make sense to continue when the database connection was lost
671 if ($this->in_retrial) {
672 $this->logger->notice('Giving up retrial because of database error', [
677 $this->logger->notice('Couldn\'t reconnect after database error', [
685 $this->logger->notice('Reconnected after database error', [
689 $this->in_retrial = true;
690 $ret = $this->p($sql, $args);
691 $this->in_retrial = false;
696 $this->error = $error;
697 $this->errorno = $errorno;
700 $this->profiler->saveTimestamp($stamp1, 'database');
702 if ($this->configCache->get('system', 'db_log')) {
703 $stamp2 = microtime(true);
704 $duration = (float)($stamp2 - $stamp1);
706 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
707 $duration = round($duration, 3);
708 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
710 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
711 basename($backtrace[1]["file"]) . "\t" .
712 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
713 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
720 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
722 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
724 * @param string $sql SQL statement
726 * @return boolean Was the query successfull? False is returned only if an error occurred
729 public function e($sql)
732 $stamp = microtime(true);
734 $params = DBA::getParam(func_get_args());
736 // In a case of a deadlock we are repeating the query 20 times
740 $stmt = $this->p($sql, $params);
742 if (is_bool($stmt)) {
744 } elseif (is_object($stmt)) {
752 } while (($this->errorno == 1213) && (--$timeout > 0));
754 if ($this->errorno != 0) {
755 // We have to preserve the error code, somewhere in the logging it get lost
756 $error = $this->error;
757 $errorno = $this->errorno;
759 if ($this->testmode) {
760 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
763 $this->logger->error('DB Error', [
766 'callstack' => System::callstack(8),
767 'params' => $this->replaceParameters($sql, $params),
770 // On a lost connection we simply quit.
771 // A reconnect like in $this->p could be dangerous with modifications
772 if ($errorno == 2006) {
773 $this->logger->notice('Giving up because of database error', [
780 $this->error = $error;
781 $this->errorno = $errorno;
784 $this->profiler->saveTimestamp($stamp, "database_write");
790 * Check if data exists
792 * @param string|array $table Table name or array [schema => table]
793 * @param array $condition array of fields for condition
795 * @return boolean Are there rows for that condition?
798 public function exists($table, $condition)
806 if (empty($condition)) {
807 return DBStructure::existsTable($table);
811 $first_key = key($condition);
812 if (!is_int($first_key)) {
813 $fields = [$first_key];
816 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
818 if (is_bool($stmt)) {
821 $retval = ($this->numRows($stmt) > 0);
830 * Fetches the first row
832 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
834 * Fetches the first row
836 * @param string $sql SQL statement
838 * @return array first row of query
841 public function fetchFirst($sql)
843 $params = DBA::getParam(func_get_args());
845 $stmt = $this->p($sql, $params);
847 if (is_bool($stmt)) {
850 $retval = $this->fetch($stmt);
859 * Returns the number of affected rows of the last statement
861 * @return int Number of rows
863 public function affectedRows()
865 return $this->affected_rows;
869 * Returns the number of columns of a statement
871 * @param object Statement object
873 * @return int Number of columns
875 public function columnCount($stmt)
877 if (!is_object($stmt)) {
880 switch ($this->driver) {
882 return $stmt->columnCount();
884 return $stmt->field_count;
890 * Returns the number of rows of a statement
892 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
894 * @return int Number of rows
896 public function numRows($stmt)
898 if (!is_object($stmt)) {
901 switch ($this->driver) {
903 return $stmt->rowCount();
905 return $stmt->num_rows;
913 * @param mixed $stmt statement object
915 * @return array current row
917 public function fetch($stmt)
920 $stamp1 = microtime(true);
924 if (!is_object($stmt)) {
928 switch ($this->driver) {
930 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
931 if (!empty($stmt->table) && is_array($columns)) {
932 $columns = $this->castFields($stmt->table, $columns);
936 if (get_class($stmt) == 'mysqli_result') {
937 $columns = $stmt->fetch_assoc();
941 // This code works, but is slow
943 // Bind the result to a result array
947 for ($x = 0; $x < $stmt->field_count; $x++) {
948 $cols[] = &$cols_num[$x];
951 call_user_func_array([$stmt, 'bind_result'], $cols);
953 if (!$stmt->fetch()) {
958 // We need to get the field names for the array keys
959 // It seems that there is no better way to do this.
960 $result = $stmt->result_metadata();
961 $fields = $result->fetch_fields();
963 foreach ($cols_num AS $param => $col) {
964 $columns[$fields[$param]->name] = $col;
968 $this->profiler->saveTimestamp($stamp1, 'database');
974 * Insert a row into a table
976 * @param string|array $table Table name or array [schema => table]
977 * @param array $param parameter array
978 * @param int $duplicate_mode What to do on a duplicated entry
980 * @return boolean was the insert successful?
983 public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT)
985 if (empty($table) || empty($param)) {
986 $this->logger->info('Table and fields have to be set');
990 $param = $this->castFields($table, $param);
992 $table_string = DBA::buildTableString($table);
994 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
996 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1000 if ($duplicate_mode == self::INSERT_IGNORE) {
1004 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1006 if ($duplicate_mode == self::INSERT_UPDATE) {
1007 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1009 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1011 $values = array_values($param);
1012 $param = array_merge_recursive($values, $values);
1015 $result = $this->e($sql, $param);
1016 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1020 return $this->affectedRows() != 0;
1024 * Inserts a row with the provided data in the provided table.
1025 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1027 * @param string|array $table Table name or array [schema => table]
1028 * @param array $param parameter array
1030 * @return boolean was the insert successful?
1031 * @throws \Exception
1033 public function replace($table, array $param)
1035 if (empty($table) || empty($param)) {
1036 $this->logger->info('Table and fields have to be set');
1040 $param = $this->castFields($table, $param);
1042 $table_string = DBA::buildTableString($table);
1044 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1046 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1048 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1050 return $this->e($sql, $param);
1054 * Fetch the id of the last insert command
1056 * @return integer Last inserted id
1058 public function lastInsertId()
1060 switch ($this->driver) {
1062 $id = $this->connection->lastInsertId();
1065 $id = $this->connection->insert_id;
1072 * Locks a table for exclusive write access
1074 * This function can be extended in the future to accept a table array as well.
1076 * @param string|array $table Table name or array [schema => table]
1078 * @return boolean was the lock successful?
1079 * @throws \Exception
1081 public function lock($table)
1083 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1084 if ($this->driver == self::PDO) {
1085 $this->e("SET autocommit=0");
1086 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1088 $this->connection->autocommit(false);
1091 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1093 if ($this->driver == self::PDO) {
1094 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1098 if ($this->driver == self::PDO) {
1099 $this->e("SET autocommit=1");
1101 $this->connection->autocommit(true);
1104 $this->in_transaction = true;
1110 * Unlocks all locked tables
1112 * @return boolean was the unlock successful?
1113 * @throws \Exception
1115 public function unlock()
1117 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1118 $this->performCommit();
1120 if ($this->driver == self::PDO) {
1121 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1124 $success = $this->e("UNLOCK TABLES");
1126 if ($this->driver == self::PDO) {
1127 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1128 $this->e("SET autocommit=1");
1130 $this->connection->autocommit(true);
1133 $this->in_transaction = false;
1138 * Starts a transaction
1140 * @return boolean Was the command executed successfully?
1142 public function transaction()
1144 if (!$this->performCommit()) {
1148 switch ($this->driver) {
1150 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1156 if (!$this->connection->begin_transaction()) {
1162 $this->in_transaction = true;
1166 protected function performCommit()
1168 switch ($this->driver) {
1170 if (!$this->connection->inTransaction()) {
1174 return $this->connection->commit();
1177 return $this->connection->commit();
1186 * @return boolean Was the command executed successfully?
1188 public function commit()
1190 if (!$this->performCommit()) {
1193 $this->in_transaction = false;
1200 * @return boolean Was the command executed successfully?
1202 public function rollback()
1206 switch ($this->driver) {
1208 if (!$this->connection->inTransaction()) {
1212 $ret = $this->connection->rollBack();
1216 $ret = $this->connection->rollback();
1219 $this->in_transaction = false;
1224 * Build the array with the table relations
1226 * The array is build from the database definitions in DBStructure.php
1228 * This process must only be started once, since the value is cached.
1230 private function buildRelationData()
1232 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1234 foreach ($definition AS $table => $structure) {
1235 foreach ($structure['fields'] AS $field => $field_struct) {
1236 if (isset($field_struct['relation'])) {
1237 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1238 $this->relation[$rel_table][$rel_field][$table][] = $field;
1246 * Delete a row from a table
1248 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1250 * @param string $table Table name
1251 * @param array $conditions Field condition(s)
1252 * @param array $options
1253 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1254 * relations (default: true)
1255 * @param array $callstack Internal use: prevent endless loops
1257 * @return boolean was the delete successful?
1258 * @throws \Exception
1260 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1262 if (empty($table) || empty($conditions)) {
1263 $this->logger->info('Table and conditions have to be set');
1269 // Create a key for the loop prevention
1270 $key = $table . ':' . json_encode($conditions);
1272 // We quit when this key already exists in the callstack.
1273 if (isset($callstack[$key])) {
1277 $callstack[$key] = true;
1279 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1281 // Don't use "defaults" here, since it would set "false" to "true"
1282 if (isset($options['cascade'])) {
1283 $cascade = $options['cascade'];
1288 // To speed up the whole process we cache the table relations
1289 if ($cascade && count($this->relation) == 0) {
1290 $this->buildRelationData();
1293 // Is there a relation entry for the table?
1294 if ($cascade && isset($this->relation[$table])) {
1295 // We only allow a simple "one field" relation.
1296 $field = array_keys($this->relation[$table])[0];
1297 $rel_def = array_values($this->relation[$table])[0];
1299 // Create a key for preventing double queries
1300 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1302 // When the search field is the relation field, we don't need to fetch the rows
1303 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1304 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1305 foreach ($rel_def AS $rel_table => $rel_fields) {
1306 foreach ($rel_fields AS $rel_field) {
1307 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1310 // We quit when this key already exists in the callstack.
1311 } elseif (!isset($callstack[$qkey])) {
1312 $callstack[$qkey] = true;
1314 // Fetch all rows that are to be deleted
1315 $data = $this->select($table, [$field], $conditions);
1317 while ($row = $this->fetch($data)) {
1318 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1321 $this->close($data);
1323 // Since we had split the delete command we don't need the original command anymore
1324 unset($commands[$key]);
1328 // Now we finalize the process
1329 $do_transaction = !$this->in_transaction;
1331 if ($do_transaction) {
1332 $this->transaction();
1338 foreach ($commands AS $command) {
1339 $conditions = $command['conditions'];
1341 $first_key = key($conditions);
1343 $condition_string = DBA::buildCondition($conditions);
1345 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1346 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1347 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1349 if (!$this->e($sql, $conditions)) {
1350 if ($do_transaction) {
1356 $key_table = $command['table'];
1357 $key_condition = array_keys($command['conditions'])[0];
1358 $value = array_values($command['conditions'])[0];
1360 // Split the SQL queries in chunks of 100 values
1361 // We do the $i stuff here to make the code better readable
1362 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1363 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1367 $compacted[$key_table][$key_condition][$i][$value] = $value;
1368 $counter[$key_table][$key_condition] = $i;
1371 foreach ($compacted AS $table => $values) {
1372 foreach ($values AS $field => $field_value_list) {
1373 foreach ($field_value_list AS $field_values) {
1374 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1375 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1377 $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1379 if (!$this->e($sql, $field_values)) {
1380 if ($do_transaction) {
1388 if ($do_transaction) {
1397 * Updates rows in the database. When $old_fields is set to an array,
1398 * the system will only do an update if the fields in that array changed.
1401 * Only the values in $old_fields are compared.
1402 * This is an intentional behaviour.
1405 * We include the timestamp field in $fields but not in $old_fields.
1406 * Then the row will only get the new timestamp when the other fields had changed.
1408 * When $old_fields is set to a boolean value the system will do this compare itself.
1409 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1412 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1413 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1415 * @param string|array $table Table name or array [schema => table]
1416 * @param array $fields contains the fields that are updated
1417 * @param array $condition condition array with the key values
1418 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1420 * @return boolean was the update successfull?
1421 * @throws \Exception
1423 public function update($table, $fields, $condition, $old_fields = [])
1425 if (empty($table) || empty($fields) || empty($condition)) {
1426 $this->logger->info('Table, fields and condition have to be set');
1430 if (is_bool($old_fields)) {
1431 $do_insert = $old_fields;
1433 $old_fields = $this->selectFirst($table, [], $condition);
1435 if (is_bool($old_fields)) {
1437 $values = array_merge($condition, $fields);
1438 return $this->replace($table, $values);
1444 foreach ($old_fields AS $fieldname => $content) {
1445 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1446 unset($fields[$fieldname]);
1450 if (count($fields) == 0) {
1454 $fields = $this->castFields($table, $fields);
1456 $table_string = DBA::buildTableString($table);
1458 $condition_string = DBA::buildCondition($condition);
1460 $sql = "UPDATE " . $table_string . " SET "
1461 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1462 . $condition_string;
1464 // Combines the updated fields parameter values with the condition parameter values
1465 $params = array_merge(array_values($fields), $condition);
1467 return $this->e($sql, $params);
1471 * Retrieve a single record from a table and returns it in an associative array
1473 * @param string|array $table
1474 * @param array $fields
1475 * @param array $condition
1476 * @param array $params
1478 * @return bool|array
1479 * @throws \Exception
1480 * @see $this->select
1482 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1484 $params['limit'] = 1;
1485 $result = $this->select($table, $fields, $condition, $params);
1487 if (is_bool($result)) {
1490 $row = $this->fetch($result);
1491 $this->close($result);
1497 * Select rows from a table and fills an array with the data
1499 * @param string|array $table Table name or array [schema => table]
1500 * @param array $fields Array of selected fields, empty for all
1501 * @param array $condition Array of fields for condition
1502 * @param array $params Array of several parameters
1504 * @return array Data array
1505 * @throws \Exception
1508 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1510 return $this->toArray($this->select($table, $fields, $condition, $params));
1514 * Select rows from a table
1520 * $table = ['schema' => 'table'];
1521 * @see DBA::buildTableString()
1523 * $fields = ['id', 'uri', 'uid', 'network'];
1525 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1527 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1528 * @see DBA::buildCondition()
1530 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1531 * @see DBA::buildParameter()
1533 * $data = DBA::select($table, $fields, $condition, $params);
1535 * @param string|array $table Table name or array [schema => table]
1536 * @param array $fields Array of selected fields, empty for all
1537 * @param array $condition Array of fields for condition
1538 * @param array $params Array of several parameters
1539 * @return boolean|object
1540 * @throws \Exception
1542 public function select($table, array $fields = [], array $condition = [], array $params = [])
1544 if (empty($table)) {
1548 if (count($fields) > 0) {
1549 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1551 $select_string = '*';
1554 $table_string = DBA::buildTableString($table);
1556 $condition_string = DBA::buildCondition($condition);
1558 $param_string = DBA::buildParameter($params);
1560 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1562 $result = $this->p($sql, $condition);
1564 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1565 $result->table = $table;
1572 * Counts the rows from a table satisfying the provided condition
1574 * @param string|array $table Table name or array [schema => table]
1575 * @param array $condition Array of fields for condition
1576 * @param array $params Array of several parameters
1583 * $condition = ["uid" => 1, "network" => 'dspr'];
1585 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1587 * $count = DBA::count($table, $condition);
1588 * @throws \Exception
1590 public function count($table, array $condition = [], array $params = [])
1592 if (empty($table)) {
1596 $table_string = DBA::buildTableString($table);
1598 $condition_string = DBA::buildCondition($condition);
1600 if (empty($params['expression'])) {
1602 } elseif (!empty($params['distinct'])) {
1603 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1605 $expression = DBA::quoteIdentifier($params['expression']);
1608 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1610 $row = $this->fetchFirst($sql, $condition);
1612 // Ensure to always return either a "null" or a numeric value
1613 return is_numeric($row['count']) ? (int)$row['count'] : $row['count'];
1617 * Fills an array with data from a query
1619 * @param object $stmt statement object
1620 * @param bool $do_close
1622 * @return array Data array
1624 public function toArray($stmt, $do_close = true)
1626 if (is_bool($stmt)) {
1631 while ($row = $this->fetch($stmt)) {
1636 $this->close($stmt);
1643 * Cast field types according to the table definition
1645 * @param string $table
1646 * @param array $fields
1647 * @return array casted fields
1649 public function castFields(string $table, array $fields) {
1650 // When there is no data, we don't need to do something
1651 if (empty($fields)) {
1655 // We only need to cast fields with PDO
1656 if ($this->driver != self::PDO) {
1660 // We only need to cast when emulating the prepares
1661 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1667 $tables = DBStructure::definition('', false);
1668 if (empty($tables[$table])) {
1669 // When a matching table wasn't found we check if it is a view
1670 $views = View::definition('', false);
1671 if (empty($views[$table])) {
1675 foreach(array_keys($fields) as $field) {
1676 if (!empty($views[$table]['fields'][$field])) {
1677 $viewdef = $views[$table]['fields'][$field];
1678 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1679 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1684 foreach ($tables[$table]['fields'] as $field => $definition) {
1685 $types[$field] = $definition['type'];
1689 foreach ($fields as $field => $content) {
1690 if (is_null($content) || empty($types[$field])) {
1694 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1695 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1696 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1697 $fields[$field] = (int)$content;
1699 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1700 $fields[$field] = (float)$content;
1708 * Returns the error number of the last query
1710 * @return string Error number (0 if no error)
1712 public function errorNo()
1714 return $this->errorno;
1718 * Returns the error message of the last query
1720 * @return string Error message ('' if no error)
1722 public function errorMessage()
1724 return $this->error;
1728 * Closes the current statement
1730 * @param object $stmt statement object
1732 * @return boolean was the close successful?
1734 public function close($stmt)
1737 $stamp1 = microtime(true);
1739 if (!is_object($stmt)) {
1743 switch ($this->driver) {
1745 $ret = $stmt->closeCursor();
1748 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1749 // We should be careful not to assume the object type of $stmt
1750 // because DBA::p() has been able to return both types.
1751 if ($stmt instanceof mysqli_stmt) {
1752 $stmt->free_result();
1753 $ret = $stmt->close();
1754 } elseif ($stmt instanceof mysqli_result) {
1763 $this->profiler->saveTimestamp($stamp1, 'database');
1769 * Return a list of database processes
1772 * 'list' => List of processes, separated in their different states
1773 * 'amount' => Number of concurrent database processes
1774 * @throws \Exception
1776 public function processlist()
1778 $ret = $this->p("SHOW PROCESSLIST");
1779 $data = $this->toArray($ret);
1783 foreach ($data as $process) {
1784 $state = trim($process["State"]);
1786 // Filter out all non blocking processes
1787 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1794 foreach ($states as $state => $usage) {
1795 if ($statelist != "") {
1798 $statelist .= $state . ": " . $usage;
1800 return (["list" => $statelist, "amount" => $processes]);
1804 * Fetch a database variable
1806 * @param string $name
1807 * @return string content
1809 public function getVariable(string $name)
1811 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1812 return $result['Value'] ?? null;
1816 * Checks if $array is a filled array with at least one entry.
1818 * @param mixed $array A filled array with at least one entry
1820 * @return boolean Whether $array is a filled array or an object with rows
1822 public function isResult($array)
1824 // It could be a return value from an update statement
1825 if (is_bool($array)) {
1829 if (is_object($array)) {
1830 return $this->numRows($array) > 0;
1833 return (is_array($array) && (count($array) > 0));
1837 * Callback function for "esc_array"
1839 * @param mixed $value Array value
1840 * @param string $key Array key
1841 * @param boolean $add_quotation add quotation marks for string values
1845 private function escapeArrayCallback(&$value, $key, $add_quotation)
1847 if (!$add_quotation) {
1848 if (is_bool($value)) {
1849 $value = ($value ? '1' : '0');
1851 $value = $this->escape($value);
1856 if (is_bool($value)) {
1857 $value = ($value ? 'true' : 'false');
1858 } elseif (is_float($value) || is_integer($value)) {
1859 $value = (string)$value;
1861 $value = "'" . $this->escape($value) . "'";
1866 * Escapes a whole array
1868 * @param mixed $arr Array with values to be escaped
1869 * @param boolean $add_quotation add quotation marks for string values
1873 public function escapeArray(&$arr, $add_quotation = false)
1875 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);