3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
24 use Friendica\Core\Config\ValueObject\Cache;
25 use Friendica\Core\System;
26 use Friendica\Network\HTTPException\ServiceUnavailableException;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Profiler;
29 use InvalidArgumentException;
36 use Psr\Log\LoggerInterface;
39 * This class is for the low level database stuff that does driver specific things.
44 const MYSQLI = 'mysqli';
46 const INSERT_DEFAULT = 0;
47 const INSERT_UPDATE = 1;
48 const INSERT_IGNORE = 2;
50 protected $connected = false;
53 * @var \Friendica\Core\Config\ValueObject\Cache
55 protected $configCache;
61 * @var LoggerInterface
64 protected $server_info = '';
65 /** @var PDO|mysqli */
66 protected $connection;
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);
93 * Tries to connect to database
95 * @return bool Success
97 public function connect(): bool
99 if (!is_null($this->connection) && $this->connected()) {
100 return $this->connected;
103 // Reset connected state
104 $this->connected = false;
107 $serveraddr = trim($this->configCache->get('database', 'hostname'));
108 $serverdata = explode(':', $serveraddr);
109 $server = $serverdata[0];
110 if (count($serverdata) > 1) {
111 $port = trim($serverdata[1]);
114 if (!empty(trim($this->configCache->get('database', 'port')))) {
115 $port = trim($this->configCache->get('database', 'port'));
118 $server = trim($server);
119 $user = trim($this->configCache->get('database', 'username'));
120 $pass = trim($this->configCache->get('database', 'password'));
121 $db = trim($this->configCache->get('database', 'database'));
122 $charset = trim($this->configCache->get('database', 'charset'));
123 $socket = trim($this->configCache->get('database', 'socket'));
125 if (!(strlen($server) && strlen($user))) {
129 $persistent = (bool)$this->configCache->get('database', 'persistent');
131 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
133 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
134 $this->driver = self::PDO;
135 $connect = "mysql:host=" . $server . ";dbname=" . $db;
138 $connect .= ";port=" . $port;
142 $connect .= ";charset=" . $charset;
146 $connect .= ";$unix_socket=" . $socket;
150 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
151 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
152 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
153 $this->connected = true;
154 } catch (PDOException $e) {
155 $this->connected = false;
159 if (!$this->connected && class_exists('\mysqli')) {
160 $this->driver = self::MYSQLI;
163 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
165 $this->connection = @new mysqli($server, $user, $pass, $db);
168 if (!mysqli_connect_errno()) {
169 $this->connected = true;
172 $this->connection->set_charset($charset);
176 $this->connection->set_socket($socket);
182 // No suitable SQL driver was found.
183 if (!$this->connected) {
184 $this->driver = null;
185 $this->connection = null;
188 return $this->connected;
191 public function setTestmode(bool $test)
193 $this->testmode = $test;
196 * Sets the logger for DBA
198 * @note this is necessary because if we want to load the logger configuration
199 * from the DB, but there's an error, we would print out an exception.
200 * So the logger gets updated after the logger configuration can be retrieved
203 * @param LoggerInterface $logger
205 public function setLogger(LoggerInterface $logger)
207 $this->logger = $logger;
211 * Sets the profiler for DBA
213 * @param Profiler $profiler
215 public function setProfiler(Profiler $profiler)
217 $this->profiler = $profiler;
220 * Disconnects the current database connection
222 public function disconnect()
224 if (!is_null($this->connection)) {
225 switch ($this->driver) {
227 $this->connection = null;
230 $this->connection->close();
231 $this->connection = null;
236 $this->driver = null;
237 $this->connected = false;
241 * Perform a reconnect of an existing database connection
243 public function reconnect()
246 return $this->connect();
250 * Return the database object.
254 public function getConnection()
256 return $this->connection;
260 * Return the database driver string
262 * @return string with either "pdo" or "mysqli"
264 public function getDriver(): string
266 return $this->driver;
270 * Returns the MySQL server version string
272 * This function discriminate between the deprecated mysql API and the current
273 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
275 * @return string Database server information
277 public function serverInfo(): string
279 if ($this->server_info == '') {
280 switch ($this->driver) {
282 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
285 $this->server_info = $this->connection->server_info;
289 return $this->server_info;
293 * Returns the selected database name
295 * @return string Database name
298 public function databaseName(): string
300 $ret = $this->p("SELECT DATABASE() AS `db`");
301 $data = $this->toArray($ret);
302 return $data[0]['db'];
306 * Analyze a database query and log this if some conditions are met.
308 * @param string $query The database query that will be analyzed
312 private function logIndex(string $query)
315 if (!$this->configCache->get('system', 'db_log_index')) {
319 // Don't explain an explain statement
320 if (strtolower(substr($query, 0, 7)) == "explain") {
324 // Only do the explain on "select", "update" and "delete"
325 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
329 $r = $this->p("EXPLAIN " . $query);
330 if (!$this->isResult($r)) {
334 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
335 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
337 while ($row = $this->fetch($r)) {
338 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
339 $log = (in_array($row['key'], $watchlist) &&
340 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
345 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
349 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
354 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
355 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
356 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
357 basename($backtrace[1]["file"]) . "\t" .
358 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
359 substr($query, 0, 4000) . "\n", FILE_APPEND);
365 * Removes every not allowlisted character from the identifier string
367 * @param string $identifier
368 * @return string sanitized identifier
371 private function sanitizeIdentifier(string $identifier): string
373 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
376 public function escape($str)
378 if ($this->connected) {
379 switch ($this->driver) {
381 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
384 return @$this->connection->real_escape_string($str);
387 return str_replace("'", "\\'", $str);
392 * Returns connected flag
394 * @return bool Whether connection to database was success
396 public function isConnected(): bool
398 return $this->connected;
402 * Checks connection status
404 * @return bool Whether connection to database was success
406 public function connected()
410 if (is_null($this->connection)) {
414 switch ($this->driver) {
416 $r = $this->p("SELECT 1");
417 if ($this->isResult($r)) {
418 $row = $this->toArray($r);
419 $connected = ($row[0]['1'] == '1');
423 $connected = $this->connection->ping();
431 * Replaces ANY_VALUE() function by MIN() function,
432 * if the database server does not support ANY_VALUE().
434 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
435 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
436 * A standard fall-back is to use MIN().
438 * @param string $sql An SQL string without the values
440 * @return string The input SQL string modified if necessary.
442 public function anyValueFallback(string $sql): string
444 $server_info = $this->serverInfo();
445 if (version_compare($server_info, '5.7.5', '<') ||
446 (stripos($server_info, 'MariaDB') !== false)) {
447 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
453 * Replaces the ? placeholders with the parameters in the $args array
455 * @param string $sql SQL query
456 * @param array $args The parameters that are to replace the ? placeholders
458 * @return string The replaced SQL query
460 private function replaceParameters(string $sql, array $args): string
463 foreach ($args as $param => $value) {
464 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
465 $replace = intval($args[$param]);
466 } elseif (is_null($args[$param])) {
469 $replace = "'" . $this->escape($args[$param]) . "'";
472 $pos = strpos($sql, '?', $offset);
473 if ($pos !== false) {
474 $sql = substr_replace($sql, $replace, $pos, 1);
476 $offset = $pos + strlen($replace);
482 * Executes a prepared statement that returns data
484 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
486 * Please only use it with complicated queries.
487 * For all regular queries please use DBA::select or DBA::exists
489 * @param string $sql SQL statement
491 * @return bool|object statement object or result object
494 public function p(string $sql)
497 $this->profiler->startRecording('database');
498 $stamp1 = microtime(true);
500 $params = DBA::getParam(func_get_args());
502 // Renumber the array keys to be sure that they fit
505 foreach ($params as $param) {
506 // Avoid problems with some MySQL servers and boolean values. See issue #3645
507 if (is_bool($param)) {
508 $param = (int)$param;
510 $args[++$i] = $param;
513 if (!$this->connected) {
517 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
518 // Question: Should we continue or stop the query here?
519 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
522 $sql = DBA::cleanQuery($sql);
523 $sql = $this->anyValueFallback($sql);
527 if ($this->configCache->get('system', 'db_callstack') !== null) {
528 $sql = "/*" . System::callstack() . " */ " . $sql;
534 $this->affected_rows = 0;
536 // We have to make some things different if this function is called from "e"
537 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
539 if (isset($trace[1])) {
540 $called_from = $trace[1];
542 // We use just something that is defined to avoid warnings
543 $called_from = $trace[0];
545 // We are having an own error logging in the function "e"
546 $called_from_e = ($called_from['function'] == 'e');
548 if (!isset($this->connection)) {
549 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
552 switch ($this->driver) {
554 // If there are no arguments we use "query"
555 if (count($args) == 0) {
556 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
557 $errorInfo = $this->connection->errorInfo();
558 $this->error = $errorInfo[2];
559 $this->errorno = (int) $errorInfo[1];
564 $this->affected_rows = $retval->rowCount();
568 /** @var $stmt mysqli_stmt|PDOStatement */
569 if (!$stmt = $this->connection->prepare($sql)) {
570 $errorInfo = $this->connection->errorInfo();
571 $this->error = $errorInfo[2];
572 $this->errorno = (int) $errorInfo[1];
578 foreach (array_keys($args) as $param) {
579 $data_type = PDO::PARAM_STR;
580 if (is_int($args[$param])) {
581 $data_type = PDO::PARAM_INT;
582 } elseif ($args[$param] !== null) {
583 $args[$param] = (string)$args[$param];
586 $stmt->bindParam($param, $args[$param], $data_type);
589 if (!$stmt->execute()) {
590 $errorInfo = $stmt->errorInfo();
591 $this->error = $errorInfo[2];
592 $this->errorno = (int) $errorInfo[1];
597 $this->affected_rows = $retval->rowCount();
601 // There are SQL statements that cannot be executed with a prepared statement
602 $parts = explode(' ', $orig_sql);
603 $command = strtolower($parts[0]);
604 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
606 // The fallback routine is called as well when there are no arguments
607 if (!$can_be_prepared || (count($args) == 0)) {
608 $retval = $this->connection->query($this->replaceParameters($sql, $args));
609 if ($this->connection->errno) {
610 $this->error = $this->connection->error;
611 $this->errorno = $this->connection->errno;
615 if (isset($retval->num_rows)) {
616 $this->affected_rows = $retval->num_rows;
618 $this->affected_rows = $this->connection->affected_rows;
624 $stmt = $this->connection->stmt_init();
626 if (!$stmt->prepare($sql)) {
627 $this->error = $stmt->error;
628 $this->errorno = $stmt->errno;
636 foreach (array_keys($args) as $param) {
637 if (is_int($args[$param])) {
639 } elseif (is_float($args[$param])) {
641 } elseif (is_string($args[$param])) {
643 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
645 $args[$param] = (string)$args[$param];
649 $values[] = &$args[$param];
652 if (count($values) > 0) {
653 array_unshift($values, $param_types);
654 call_user_func_array([$stmt, 'bind_param'], $values);
657 if (!$stmt->execute()) {
658 $this->error = $this->connection->error;
659 $this->errorno = $this->connection->errno;
663 $stmt->store_result();
665 $this->affected_rows = $retval->affected_rows;
670 // See issue https://github.com/friendica/friendica/issues/8572
671 // Ensure that we always get an error message on an error.
672 if ($is_error && empty($this->errorno)) {
676 if ($is_error && empty($this->error)) {
677 $this->error = 'Unknown database error';
680 // We are having an own error logging in the function "e"
681 if (($this->errorno != 0) && !$called_from_e) {
682 // We have to preserve the error code, somewhere in the logging it get lost
683 $error = $this->error;
684 $errorno = $this->errorno;
686 if ($this->testmode) {
687 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
690 $this->logger->error('DB Error', [
693 'callstack' => System::callstack(8),
694 'params' => $this->replaceParameters($sql, $args),
697 // On a lost connection we try to reconnect - but only once.
698 if ($errorno == 2006) {
699 if ($this->in_retrial || !$this->reconnect()) {
700 // It doesn't make sense to continue when the database connection was lost
701 if ($this->in_retrial) {
702 $this->logger->notice('Giving up retrial because of database error', [
707 $this->logger->notice('Couldn\'t reconnect after database error', [
715 $this->logger->notice('Reconnected after database error', [
719 $this->in_retrial = true;
720 $ret = $this->p($sql, $args);
721 $this->in_retrial = false;
726 $this->error = $error;
727 $this->errorno = (int) $errorno;
730 $this->profiler->stopRecording();
732 if ($this->configCache->get('system', 'db_log')) {
733 $stamp2 = microtime(true);
734 $duration = (float)($stamp2 - $stamp1);
736 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
737 $duration = round($duration, 3);
738 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
740 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
741 basename($backtrace[1]["file"]) . "\t" .
742 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
743 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
750 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
752 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
754 * @param string $sql SQL statement
756 * @return boolean Was the query successfull? False is returned only if an error occurred
759 public function e(string $sql): bool
763 $this->profiler->startRecording('database_write');
765 $params = DBA::getParam(func_get_args());
767 // In a case of a deadlock we are repeating the query 20 times
771 $stmt = $this->p($sql, $params);
773 if (is_bool($stmt)) {
775 } elseif (is_object($stmt)) {
783 } while (($this->errorno == 1213) && (--$timeout > 0));
785 if ($this->errorno != 0) {
786 // We have to preserve the error code, somewhere in the logging it get lost
787 $error = $this->error;
788 $errorno = $this->errorno;
790 if ($this->testmode) {
791 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
794 $this->logger->error('DB Error', [
797 'callstack' => System::callstack(8),
798 'params' => $this->replaceParameters($sql, $params),
801 // On a lost connection we simply quit.
802 // A reconnect like in $this->p could be dangerous with modifications
803 if ($errorno == 2006) {
804 $this->logger->notice('Giving up because of database error', [
811 $this->error = $error;
812 $this->errorno = $errorno;
815 $this->profiler->stopRecording();
821 * Check if data exists
823 * @param string|array $table Table name or array [schema => table]
824 * @param array $condition array of fields for condition
826 * @return boolean Are there rows for that condition?
829 public function exists($table, array $condition): bool
837 if (empty($condition)) {
838 return DBStructure::existsTable($table);
842 $first_key = key($condition);
843 if (!is_int($first_key)) {
844 $fields = [$first_key];
847 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
849 if (is_bool($stmt)) {
852 $retval = ($this->numRows($stmt) > 0);
861 * Fetches the first row
863 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
865 * Fetches the first row
867 * @param string $sql SQL statement
869 * @return array|bool first row of query or false on failure
872 public function fetchFirst(string $sql)
874 $params = DBA::getParam(func_get_args());
876 $stmt = $this->p($sql, $params);
878 if (is_bool($stmt)) {
881 $retval = $this->fetch($stmt);
890 * Returns the number of affected rows of the last statement
892 * @return int Number of rows
894 public function affectedRows(): int
896 return $this->affected_rows;
900 * Returns the number of columns of a statement
902 * @param object Statement object
904 * @return int Number of columns
906 public function columnCount($stmt): int
908 if (!is_object($stmt)) {
911 switch ($this->driver) {
913 return $stmt->columnCount();
915 return $stmt->field_count;
921 * Returns the number of rows of a statement
923 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
925 * @return int Number of rows
927 public function numRows($stmt): int
929 if (!is_object($stmt)) {
932 switch ($this->driver) {
934 return $stmt->rowCount();
936 return $stmt->num_rows;
944 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
946 * @return array|bool Current row or false on failure
948 public function fetch($stmt)
950 $this->profiler->startRecording('database');
954 if (!is_object($stmt)) {
958 switch ($this->driver) {
960 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
961 if (!empty($stmt->table) && is_array($columns)) {
962 $columns = $this->castFields($stmt->table, $columns);
966 if (get_class($stmt) == 'mysqli_result') {
967 $columns = $stmt->fetch_assoc() ?? false;
971 // This code works, but is slow
973 // Bind the result to a result array
977 for ($x = 0; $x < $stmt->field_count; $x++) {
978 $cols[] = &$cols_num[$x];
981 call_user_func_array([$stmt, 'bind_result'], $cols);
983 if (!$stmt->fetch()) {
988 // We need to get the field names for the array keys
989 // It seems that there is no better way to do this.
990 $result = $stmt->result_metadata();
991 $fields = $result->fetch_fields();
993 foreach ($cols_num as $param => $col) {
994 $columns[$fields[$param]->name] = $col;
998 $this->profiler->stopRecording();
1004 * Insert a row into a table. Field value objects will be cast as string.
1006 * @param string|array $table Table name or array [schema => table]
1007 * @param array $param parameter array
1008 * @param int $duplicate_mode What to do on a duplicated entry
1010 * @return boolean was the insert successful?
1011 * @throws \Exception
1013 public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1015 if (empty($table) || empty($param)) {
1016 $this->logger->info('Table and fields have to be set');
1020 $param = $this->castFields($table, $param);
1022 $table_string = DBA::buildTableString($table);
1024 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1026 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1030 if ($duplicate_mode == self::INSERT_IGNORE) {
1034 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1036 if ($duplicate_mode == self::INSERT_UPDATE) {
1037 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1039 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1041 $values = array_values($param);
1042 $param = array_merge_recursive($values, $values);
1045 $result = $this->e($sql, $param);
1046 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1050 return $this->affectedRows() != 0;
1054 * Inserts a row with the provided data in the provided table.
1055 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1057 * @param string|array $table Table name or array [schema => table]
1058 * @param array $param parameter array
1060 * @return boolean was the insert successful?
1061 * @throws \Exception
1063 public function replace($table, array $param): bool
1065 if (empty($table) || empty($param)) {
1066 $this->logger->info('Table and fields have to be set');
1070 $param = $this->castFields($table, $param);
1072 $table_string = DBA::buildTableString($table);
1074 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1076 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1078 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1080 return $this->e($sql, $param);
1084 * Fetch the id of the last insert command
1086 * @return integer Last inserted id
1088 public function lastInsertId(): int
1090 switch ($this->driver) {
1092 $id = $this->connection->lastInsertId();
1095 $id = $this->connection->insert_id;
1102 * Locks a table for exclusive write access
1104 * This function can be extended in the future to accept a table array as well.
1106 * @param string|array $table Table name or array [schema => table]
1108 * @return boolean was the lock successful?
1109 * @throws \Exception
1111 public function lock($table): bool
1113 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1114 if ($this->driver == self::PDO) {
1115 $this->e("SET autocommit=0");
1116 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1118 $this->connection->autocommit(false);
1121 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1123 if ($this->driver == self::PDO) {
1124 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1128 if ($this->driver == self::PDO) {
1129 $this->e("SET autocommit=1");
1131 $this->connection->autocommit(true);
1134 $this->in_transaction = true;
1140 * Unlocks all locked tables
1142 * @return boolean was the unlock successful?
1143 * @throws \Exception
1145 public function unlock(): bool
1147 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1148 $this->performCommit();
1150 if ($this->driver == self::PDO) {
1151 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1154 $success = $this->e("UNLOCK TABLES");
1156 if ($this->driver == self::PDO) {
1157 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1158 $this->e("SET autocommit=1");
1160 $this->connection->autocommit(true);
1163 $this->in_transaction = false;
1168 * Starts a transaction
1170 * @return boolean Was the command executed successfully?
1172 public function transaction(): bool
1174 if (!$this->performCommit()) {
1178 switch ($this->driver) {
1180 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1186 if (!$this->connection->begin_transaction()) {
1192 $this->in_transaction = true;
1197 * Performs the commit
1199 * @return boolean Was the command executed successfully?
1201 protected function performCommit(): bool
1203 switch ($this->driver) {
1205 if (!$this->connection->inTransaction()) {
1209 return $this->connection->commit();
1212 return $this->connection->commit();
1221 * @return boolean Was the command executed successfully?
1223 public function commit(): bool
1225 if (!$this->performCommit()) {
1228 $this->in_transaction = false;
1235 * @return boolean Was the command executed successfully?
1237 public function rollback(): bool
1241 switch ($this->driver) {
1243 if (!$this->connection->inTransaction()) {
1247 $ret = $this->connection->rollBack();
1251 $ret = $this->connection->rollback();
1255 $this->in_transaction = false;
1260 * Delete a row from a table
1262 * @param string $table Table name
1263 * @param array $conditions Field condition(s)
1265 * @return boolean was the delete successful?
1266 * @throws \Exception
1268 public function delete($table, array $conditions): bool
1270 if (empty($table) || empty($conditions)) {
1271 $this->logger->info('Table and conditions have to be set');
1275 $table_string = DBA::buildTableString($table);
1277 $condition_string = DBA::buildCondition($conditions);
1279 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1280 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1281 return $this->e($sql, $conditions);
1285 * Updates rows in the database. Field value objects will be cast as string.
1287 * When $old_fields is set to an array,
1288 * the system will only do an update if the fields in that array changed.
1291 * Only the values in $old_fields are compared.
1292 * This is an intentional behaviour.
1295 * We include the timestamp field in $fields but not in $old_fields.
1296 * Then the row will only get the new timestamp when the other fields had changed.
1298 * When $old_fields is set to a boolean value the system will do this compare itself.
1299 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1302 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1303 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1305 * @param string|array $table Table name or array [schema => table]
1306 * @param array $fields contains the fields that are updated
1307 * @param array $condition condition array with the key values
1308 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
1309 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1311 * @return boolean was the update successfull?
1312 * @throws \Exception
1313 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1315 public function update($table, array $fields, array $condition, $old_fields = [], array $params = [])
1317 if (empty($table) || empty($fields) || empty($condition)) {
1318 $this->logger->info('Table, fields and condition have to be set');
1322 if (is_bool($old_fields)) {
1323 $do_insert = $old_fields;
1325 $old_fields = $this->selectFirst($table, [], $condition);
1327 if (is_bool($old_fields)) {
1329 $values = array_merge($condition, $fields);
1330 return $this->replace($table, $values);
1336 foreach ($old_fields as $fieldname => $content) {
1337 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1338 unset($fields[$fieldname]);
1342 if (count($fields) == 0) {
1346 $fields = $this->castFields($table, $fields);
1348 $table_string = DBA::buildTableString($table);
1350 $condition_string = DBA::buildCondition($condition);
1352 if (!empty($params['ignore'])) {
1353 $ignore = 'IGNORE ';
1358 $sql = "UPDATE " . $ignore . $table_string . " SET "
1359 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1360 . $condition_string;
1362 // Combines the updated fields parameter values with the condition parameter values
1363 $params = array_merge(array_values($fields), $condition);
1365 return $this->e($sql, $params);
1369 * Retrieve a single record from a table and returns it in an associative array
1371 * @param string|array $table
1372 * @param array $fields
1373 * @param array $condition
1374 * @param array $params
1376 * @return bool|array
1377 * @throws \Exception
1378 * @see $this->select
1380 public function selectFirst($table, array $fields = [], array $condition = [], array $params = [])
1382 $params['limit'] = 1;
1383 $result = $this->select($table, $fields, $condition, $params);
1385 if (is_bool($result)) {
1388 $row = $this->fetch($result);
1389 $this->close($result);
1395 * Select rows from a table and fills an array with the data
1397 * @param string|array $table Table name or array [schema => table]
1398 * @param array $fields Array of selected fields, empty for all
1399 * @param array $condition Array of fields for condition
1400 * @param array $params Array of several parameters
1402 * @return array Data array
1403 * @throws \Exception
1406 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1408 return $this->toArray($this->select($table, $fields, $condition, $params));
1412 * Escape fields, adding special treatment for "group by" handling
1414 * @param array $fields
1415 * @param array $options
1416 * @return array Escaped fields
1418 private function escapeFields(array $fields, array $options): array
1420 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1421 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1422 // Otherwise MySQL would report errors.
1423 if (!empty($options['group_by']) && !empty($options['order'])) {
1424 foreach ($options['order'] as $key => $field) {
1425 if (!is_int($key)) {
1426 if (!in_array($key, $fields)) {
1430 if (!in_array($field, $fields)) {
1437 array_walk($fields, function(&$value, $key) use ($options)
1440 $value = '`' . str_replace('`', '``', $value) . '`';
1442 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1443 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1451 * Select rows from a table
1457 * $table = ['schema' => 'table'];
1458 * @see DBA::buildTableString()
1460 * $fields = ['id', 'uri', 'uid', 'network'];
1462 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1464 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1465 * @see DBA::buildCondition()
1467 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1468 * @see DBA::buildParameter()
1470 * $data = DBA::select($table, $fields, $condition, $params);
1472 * @param string|array $table Table name or array [schema => table]
1473 * @param array $fields Array of selected fields, empty for all
1474 * @param array $condition Array of fields for condition
1475 * @param array $params Array of several parameters
1476 * @return boolean|object
1477 * @throws \Exception
1479 public function select($table, array $fields = [], array $condition = [], array $params = [])
1481 if (empty($table)) {
1485 if (count($fields) > 0) {
1486 $fields = $this->escapeFields($fields, $params);
1487 $select_string = implode(', ', $fields);
1489 $select_string = '*';
1492 $table_string = DBA::buildTableString($table);
1494 $condition_string = DBA::buildCondition($condition);
1496 $param_string = DBA::buildParameter($params);
1498 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1500 $result = $this->p($sql, $condition);
1502 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1503 $result->table = $table;
1510 * Counts the rows from a table satisfying the provided condition
1512 * @param string|array $table Table name or array [schema => table]
1513 * @param array $condition Array of fields for condition
1514 * @param array $params Array of several parameters
1516 * @return int Count of rows
1521 * $condition = ["uid" => 1, "network" => 'dspr'];
1523 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1525 * $count = DBA::count($table, $condition);
1526 * @throws \Exception
1528 public function count($table, array $condition = [], array $params = []): int
1530 if (empty($table)) {
1531 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1534 $table_string = DBA::buildTableString($table);
1536 $condition_string = DBA::buildCondition($condition);
1538 if (empty($params['expression'])) {
1540 } elseif (!empty($params['distinct'])) {
1541 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1543 $expression = DBA::quoteIdentifier($params['expression']);
1546 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1548 $row = $this->fetchFirst($sql, $condition);
1550 if (!isset($row['count'])) {
1551 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1554 return (int)$row['count'];
1559 * Fills an array with data from a query
1561 * @param object $stmt statement object
1562 * @param bool $do_close Close database connection after last row
1563 * @param int $count maximum number of rows to be fetched
1565 * @return array Data array
1567 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1569 if (is_bool($stmt)) {
1574 while ($row = $this->fetch($stmt)) {
1576 if (($count != 0) && (count($data) == $count)) {
1582 $this->close($stmt);
1589 * Cast field types according to the table definition
1591 * @param string $table
1592 * @param array $fields
1593 * @return array casted fields
1595 public function castFields(string $table, array $fields): array
1597 // When there is no data, we don't need to do something
1598 if (empty($fields)) {
1602 // We only need to cast fields with PDO
1603 if ($this->driver != self::PDO) {
1607 // We only need to cast when emulating the prepares
1608 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1614 $tables = DBStructure::definition('', false);
1615 if (empty($tables[$table])) {
1616 // When a matching table wasn't found we check if it is a view
1617 $views = View::definition('', false);
1618 if (empty($views[$table])) {
1622 foreach(array_keys($fields) as $field) {
1623 if (!empty($views[$table]['fields'][$field])) {
1624 $viewdef = $views[$table]['fields'][$field];
1625 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1626 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1631 foreach ($tables[$table]['fields'] as $field => $definition) {
1632 $types[$field] = $definition['type'];
1636 foreach ($fields as $field => $content) {
1637 if (is_null($content) || empty($types[$field])) {
1641 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1642 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1643 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1644 $fields[$field] = (int)$content;
1646 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1647 $fields[$field] = (float)$content;
1655 * Returns the error number of the last query
1657 * @return string Error number (0 if no error)
1659 public function errorNo(): int
1661 return $this->errorno;
1665 * Returns the error message of the last query
1667 * @return string Error message ('' if no error)
1669 public function errorMessage(): string
1671 return $this->error;
1675 * Closes the current statement
1677 * @param object $stmt statement object
1679 * @return boolean was the close successful?
1681 public function close($stmt): bool
1684 $this->profiler->startRecording('database');
1686 if (!is_object($stmt)) {
1690 switch ($this->driver) {
1692 $ret = $stmt->closeCursor();
1695 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1696 // We should be careful not to assume the object type of $stmt
1697 // because DBA::p() has been able to return both types.
1698 if ($stmt instanceof mysqli_stmt) {
1699 $stmt->free_result();
1700 $ret = $stmt->close();
1701 } elseif ($stmt instanceof mysqli_result) {
1710 $this->profiler->stopRecording();
1716 * Return a list of database processes
1719 * 'list' => List of processes, separated in their different states
1720 * 'amount' => Number of concurrent database processes
1721 * @throws \Exception
1723 public function processlist(): array
1725 $ret = $this->p("SHOW PROCESSLIST");
1726 $data = $this->toArray($ret);
1730 foreach ($data as $process) {
1731 $state = trim($process["State"]);
1733 // Filter out all non blocking processes
1734 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1741 foreach ($states as $state => $usage) {
1742 if ($statelist != "") {
1745 $statelist .= $state . ": " . $usage;
1747 return (["list" => $statelist, "amount" => $processes]);
1751 * Fetch a database variable
1753 * @param string $name
1754 * @return string content
1756 public function getVariable(string $name): string
1758 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1759 return $result['Value'] ?? null;
1763 * Checks if $array is a filled array with at least one entry.
1765 * @param mixed $array A filled array with at least one entry
1767 * @return boolean Whether $array is a filled array or an object with rows
1769 public function isResult($array): bool
1771 // It could be a return value from an update statement
1772 if (is_bool($array)) {
1776 if (is_object($array)) {
1777 return $this->numRows($array) > 0;
1780 return (is_array($array) && (count($array) > 0));
1784 * Callback function for "esc_array"
1786 * @param mixed $value Array value
1787 * @param string $key Array key
1788 * @param boolean $add_quotation add quotation marks for string values
1791 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1793 if (!$add_quotation) {
1794 if (is_bool($value)) {
1795 $value = ($value ? '1' : '0');
1797 $value = $this->escape($value);
1802 if (is_bool($value)) {
1803 $value = ($value ? 'true' : 'false');
1804 } elseif (is_float($value) || is_integer($value)) {
1805 $value = (string)$value;
1807 $value = "'" . $this->escape($value) . "'";
1812 * Escapes a whole array
1814 * @param mixed $arr Array with values to be escaped
1815 * @param boolean $add_quotation add quotation marks for string values
1818 public function escapeArray(&$arr, bool $add_quotation = false)
1820 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1824 * Replaces a string in the provided fields of the provided table
1826 * @param string $table_name Table name
1827 * @param array $fields List of field names in the provided table
1828 * @param string $search
1829 * @param string $replace
1831 * @throws \Exception
1833 public function replaceInTableFields(string $table_name, array $fields, string $search, string $replace)
1835 $search = $this->escape($search);
1836 $replace = $this->escape($replace);
1839 foreach ($fields as $field) {
1840 $field = DBA::quoteIdentifier($field);
1841 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1844 $upds = implode(', ', $upd);
1846 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table_name), $upds));
1847 if (!$this->isResult($r)) {
1848 throw new \RuntimeException("Failed updating `$table_name`: " . $this->errorMessage());