3 * @copyright Copyright (C) 2010-2023, 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\Capability\IManageConfigValues;
25 use Friendica\Core\System;
26 use Friendica\Database\Definition\DbaDefinition;
27 use Friendica\Database\Definition\ViewDefinition;
28 use Friendica\Network\HTTPException\ServiceUnavailableException;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Profiler;
31 use InvalidArgumentException;
38 use Psr\Log\LoggerInterface;
41 * This class is for the low level database stuff that does driver specific things.
46 const MYSQLI = 'mysqli';
48 const INSERT_DEFAULT = 0;
49 const INSERT_UPDATE = 1;
50 const INSERT_IGNORE = 2;
52 protected $connected = false;
55 * @var IManageConfigValues
63 * @var LoggerInterface
66 protected $server_info = '';
67 /** @var PDO|mysqli */
68 protected $connection;
69 protected $driver = '';
70 protected $pdo_emulate_prepares = false;
73 private $affected_rows = 0;
74 protected $in_transaction = false;
75 protected $in_retrial = false;
76 protected $testmode = false;
77 private $relation = [];
78 /** @var DbaDefinition */
79 protected $dbaDefinition;
80 /** @var ViewDefinition */
81 protected $viewDefinition;
83 public function __construct(IManageConfigValues $config, Profiler $profiler, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition, LoggerInterface $logger)
85 // We are storing these values for being able to perform a reconnect
86 $this->config = $config;
87 $this->profiler = $profiler;
88 $this->dbaDefinition = $dbaDefinition;
89 $this->viewDefinition = $viewDefinition;
90 $this->logger = $logger;
96 * Tries to connect to database
98 * @return bool Success
100 public function connect(): bool
102 if (!is_null($this->connection) && $this->connected()) {
103 return $this->connected;
106 // Reset connected state
107 $this->connected = false;
110 $serveraddr = trim($this->config->get('database', 'hostname') ?? '');
111 $serverdata = explode(':', $serveraddr);
112 $host = trim($serverdata[0]);
113 if (count($serverdata) > 1) {
114 $port = trim($serverdata[1]);
117 if (trim($this->config->get('database', 'port') ?? 0)) {
118 $port = trim($this->config->get('database', 'port') ?? 0);
121 $user = trim($this->config->get('database', 'username'));
122 $pass = trim($this->config->get('database', 'password'));
123 $database = trim($this->config->get('database', 'database'));
124 $charset = trim($this->config->get('database', 'charset'));
125 $socket = trim($this->config->get('database', 'socket'));
127 if (!$host && !$socket || !$user) {
131 $persistent = (bool)$this->config->get('database', 'persistent');
133 $this->pdo_emulate_prepares = (bool)$this->config->get('database', 'pdo_emulate_prepares');
135 if (!$this->config->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
136 $this->driver = self::PDO;
138 $connect = 'mysql:unix_socket=' . $socket;
140 $connect = 'mysql:host=' . $host;
142 $connect .= ';port=' . $port;
147 $connect .= ';charset=' . $charset;
150 $connect .= ';dbname=' . $database;
153 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
154 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
155 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
156 $this->connected = true;
157 } catch (PDOException $e) {
158 $this->connected = false;
162 if (!$this->connected && class_exists('\mysqli')) {
163 $this->driver = self::MYSQLI;
166 $this->connection = @new mysqli(null, $user, $pass, $database, null, $socket);
167 } elseif ($port > 0) {
168 $this->connection = @new mysqli($host, $user, $pass, $database, $port);
170 $this->connection = @new mysqli($host, $user, $pass, $database);
173 if (!mysqli_connect_errno()) {
174 $this->connected = true;
177 $this->connection->set_charset($charset);
182 // No suitable SQL driver was found.
183 if (!$this->connected) {
185 $this->connection = null;
188 return $this->connected;
191 public function setTestmode(bool $test)
193 $this->testmode = $test;
197 * Sets the profiler for DBA
199 * @param Profiler $profiler
201 public function setProfiler(Profiler $profiler)
203 $this->profiler = $profiler;
207 * Disconnects the current database connection
209 public function disconnect()
211 if (!is_null($this->connection)) {
212 switch ($this->driver) {
214 $this->connection = null;
217 $this->connection->close();
218 $this->connection = null;
224 $this->connected = false;
228 * Perform a reconnect of an existing database connection
230 public function reconnect()
233 return $this->connect();
237 * Return the database object.
241 public function getConnection()
243 return $this->connection;
247 * Return the database driver string
249 * @return string with either "pdo" or "mysqli"
251 public function getDriver(): string
253 return $this->driver;
257 * Returns the MySQL server version string
259 * This function discriminate between the deprecated mysql API and the current
260 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
262 * @return string Database server information
264 public function serverInfo(): string
266 if ($this->server_info == '') {
267 switch ($this->driver) {
269 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
272 $this->server_info = $this->connection->server_info;
276 return $this->server_info;
280 * Returns the selected database name
282 * @return string Database name
285 public function databaseName(): string
287 $ret = $this->p("SELECT DATABASE() AS `db`");
288 $data = $this->toArray($ret);
289 return $data[0]['db'];
293 * Analyze a database query and log this if some conditions are met.
295 * @param string $query The database query that will be analyzed
299 private function logIndex(string $query)
302 if (!$this->config->get('system', 'db_log_index')) {
306 // Don't explain an explain statement
307 if (strtolower(substr($query, 0, 7)) == "explain") {
311 // Only do the explain on "select", "update" and "delete"
312 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
316 $r = $this->p("EXPLAIN " . $query);
317 if (!$this->isResult($r)) {
321 $watchlist = explode(',', $this->config->get('system', 'db_log_index_watch'));
322 $denylist = explode(',', $this->config->get('system', 'db_log_index_denylist'));
324 while ($row = $this->fetch($r)) {
325 if ((intval($this->config->get('system', 'db_loglimit_index')) > 0)) {
326 $log = (in_array($row['key'], $watchlist) &&
327 ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index'))));
332 if ((intval($this->config->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index_high')))) {
336 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
341 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
343 $this->config->get('system', 'db_log_index'),
344 DateTimeFormat::utcNow() . "\t" .
345 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
346 basename($backtrace[1]["file"]) . "\t" .
347 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
348 substr($query, 0, 4000) . "\n",
356 * Removes every not allowlisted character from the identifier string
358 * @param string $identifier
359 * @return string sanitized identifier
362 private function sanitizeIdentifier(string $identifier): string
364 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
367 public function escape($str)
369 if ($this->connected) {
370 switch ($this->driver) {
372 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
375 return @$this->connection->real_escape_string($str);
378 return str_replace("'", "\\'", $str);
383 * Returns connected flag
385 * @return bool Whether connection to database was success
387 public function isConnected(): bool
389 return $this->connected;
393 * Checks connection status
395 * @return bool Whether connection to database was success
397 public function connected()
401 if (is_null($this->connection)) {
405 switch ($this->driver) {
407 $r = $this->p("SELECT 1");
408 if ($this->isResult($r)) {
409 $row = $this->toArray($r);
410 $connected = ($row[0]['1'] == '1');
414 $connected = $this->connection->ping();
422 * Replaces ANY_VALUE() function by MIN() function,
423 * if the database server does not support ANY_VALUE().
425 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
426 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
427 * A standard fall-back is to use MIN().
429 * @param string $sql An SQL string without the values
431 * @return string The input SQL string modified if necessary.
433 public function anyValueFallback(string $sql): string
435 $server_info = $this->serverInfo();
436 if (version_compare($server_info, '5.7.5', '<') ||
437 (stripos($server_info, 'MariaDB') !== false)) {
438 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
444 * Replaces the ? placeholders with the parameters in the $args array
446 * @param string $sql SQL query
447 * @param array $args The parameters that are to replace the ? placeholders
449 * @return string The replaced SQL query
451 private function replaceParameters(string $sql, array $args): string
454 foreach ($args as $param => $value) {
455 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
456 $replace = intval($args[$param]);
457 } elseif (is_null($args[$param])) {
460 $replace = "'" . $this->escape($args[$param]) . "'";
463 $pos = strpos($sql, '?', $offset);
464 if ($pos !== false) {
465 $sql = substr_replace($sql, $replace, $pos, 1);
467 $offset = $pos + strlen($replace);
473 * Executes a prepared statement that returns data
475 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
477 * Please only use it with complicated queries.
478 * For all regular queries please use DBA::select or DBA::exists
480 * @param string $sql SQL statement
482 * @return bool|object statement object or result object
485 public function p(string $sql)
488 $this->profiler->startRecording('database');
489 $stamp1 = microtime(true);
491 $params = DBA::getParam(func_get_args());
493 // Renumber the array keys to be sure that they fit
496 foreach ($params as $param) {
497 // Avoid problems with some MySQL servers and boolean values. See issue #3645
498 if (is_bool($param)) {
499 $param = (int)$param;
501 $args[++$i] = $param;
504 if (!$this->connected) {
508 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
509 // Question: Should we continue or stop the query here?
510 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
513 $sql = DBA::cleanQuery($sql);
514 $sql = $this->anyValueFallback($sql);
518 if ($this->config->get('system', 'db_callstack') !== null) {
519 $sql = "/*" . System::callstack() . " */ " . $sql;
525 $this->affected_rows = 0;
527 // We have to make some things different if this function is called from "e"
528 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
530 if (isset($trace[1])) {
531 $called_from = $trace[1];
533 // We use just something that is defined to avoid warnings
534 $called_from = $trace[0];
536 // We are having an own error logging in the function "e"
537 $called_from_e = ($called_from['function'] == 'e');
539 if (!isset($this->connection)) {
540 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
543 switch ($this->driver) {
545 // If there are no arguments we use "query"
546 if (count($args) == 0) {
547 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
548 $errorInfo = $this->connection->errorInfo();
549 $this->error = (string)$errorInfo[2];
550 $this->errorno = (int)$errorInfo[1];
555 $this->affected_rows = $retval->rowCount();
559 /** @var $stmt mysqli_stmt|PDOStatement */
560 if (!$stmt = $this->connection->prepare($sql)) {
561 $errorInfo = $this->connection->errorInfo();
562 $this->error = (string)$errorInfo[2];
563 $this->errorno = (int)$errorInfo[1];
569 foreach (array_keys($args) as $param) {
570 $data_type = PDO::PARAM_STR;
571 if (is_int($args[$param])) {
572 $data_type = PDO::PARAM_INT;
573 } elseif ($args[$param] !== null) {
574 $args[$param] = (string)$args[$param];
577 $stmt->bindParam($param, $args[$param], $data_type);
580 if (!$stmt->execute()) {
581 $errorInfo = $stmt->errorInfo();
582 $this->error = (string)$errorInfo[2];
583 $this->errorno = (int)$errorInfo[1];
588 $this->affected_rows = $retval->rowCount();
592 // There are SQL statements that cannot be executed with a prepared statement
593 $parts = explode(' ', $orig_sql);
594 $command = strtolower($parts[0]);
595 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
597 // The fallback routine is called as well when there are no arguments
598 if (!$can_be_prepared || (count($args) == 0)) {
599 $retval = $this->connection->query($this->replaceParameters($sql, $args));
600 if ($this->connection->errno) {
601 $this->error = (string)$this->connection->error;
602 $this->errorno = (int)$this->connection->errno;
606 if (isset($retval->num_rows)) {
607 $this->affected_rows = $retval->num_rows;
609 $this->affected_rows = $this->connection->affected_rows;
615 $stmt = $this->connection->stmt_init();
617 if (!$stmt->prepare($sql)) {
618 $this->error = (string)$stmt->error;
619 $this->errorno = (int)$stmt->errno;
627 foreach (array_keys($args) as $param) {
628 if (is_int($args[$param])) {
630 } elseif (is_float($args[$param])) {
632 } elseif (is_string($args[$param])) {
634 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
636 $args[$param] = (string)$args[$param];
640 $values[] = &$args[$param];
643 if (count($values) > 0) {
644 array_unshift($values, $param_types);
645 call_user_func_array([$stmt, 'bind_param'], $values);
648 if (!$stmt->execute()) {
649 $this->error = (string)$this->connection->error;
650 $this->errorno = (int)$this->connection->errno;
654 $stmt->store_result();
656 $this->affected_rows = $retval->affected_rows;
661 // See issue https://github.com/friendica/friendica/issues/8572
662 // Ensure that we always get an error message on an error.
663 if ($is_error && empty($this->errorno)) {
667 if ($is_error && empty($this->error)) {
668 $this->error = 'Unknown database error';
671 // We are having an own error logging in the function "e"
672 if (($this->errorno != 0) && !$called_from_e) {
673 // We have to preserve the error code, somewhere in the logging it get lost
674 $error = $this->error;
675 $errorno = $this->errorno;
677 if ($this->testmode) {
678 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
681 $this->logger->error('DB Error', [
684 'callstack' => System::callstack(8),
685 'params' => $this->replaceParameters($sql, $args),
688 // On a lost connection we try to reconnect - but only once.
689 if ($errorno == 2006) {
690 if ($this->in_retrial || !$this->reconnect()) {
691 // It doesn't make sense to continue when the database connection was lost
692 if ($this->in_retrial) {
693 $this->logger->notice('Giving up retrial because of database error', [
698 $this->logger->notice('Couldn\'t reconnect after database error', [
706 $this->logger->notice('Reconnected after database error', [
710 $this->in_retrial = true;
711 $ret = $this->p($sql, $args);
712 $this->in_retrial = false;
717 $this->error = (string)$error;
718 $this->errorno = (int)$errorno;
721 $this->profiler->stopRecording();
723 if ($this->config->get('system', 'db_log')) {
724 $stamp2 = microtime(true);
725 $duration = (float)($stamp2 - $stamp1);
727 if (($duration > $this->config->get('system', 'db_loglimit'))) {
728 $duration = round($duration, 3);
729 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
732 $this->config->get('system', 'db_log'),
733 DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
734 basename($backtrace[1]["file"]) . "\t" .
735 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
736 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n",
745 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
747 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
749 * @param string $sql SQL statement
751 * @return boolean Was the query successfull? False is returned only if an error occurred
754 public function e(string $sql): bool
758 $this->profiler->startRecording('database_write');
760 $params = DBA::getParam(func_get_args());
762 // In a case of a deadlock we are repeating the query 20 times
766 $stmt = $this->p($sql, $params);
768 if (is_bool($stmt)) {
770 } elseif (is_object($stmt)) {
778 } while (($this->errorno == 1213) && (--$timeout > 0));
780 if ($this->errorno != 0) {
781 // We have to preserve the error code, somewhere in the logging it get lost
782 $error = $this->error;
783 $errorno = $this->errorno;
785 if ($this->testmode) {
786 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
789 $this->logger->error('DB Error', [
792 'callstack' => System::callstack(8),
793 'params' => $this->replaceParameters($sql, $params),
796 // On a lost connection we simply quit.
797 // A reconnect like in $this->p could be dangerous with modifications
798 if ($errorno == 2006) {
799 $this->logger->notice('Giving up because of database error', [
806 $this->error = $error;
807 $this->errorno = $errorno;
810 $this->profiler->stopRecording();
816 * Check if data exists
818 * @param string $table Table name in format [schema.]table
819 * @param array $condition Array of fields for condition
821 * @return boolean Are there rows for that condition?
823 * @todo Please unwrap the DBStructure::existsTable() call so this method has one behavior only: checking existence on records
825 public function exists(string $table, array $condition): bool
833 if (empty($condition)) {
834 return DBStructure::existsTable($table);
838 $first_key = key($condition);
839 if (!is_int($first_key)) {
840 $fields = [$first_key];
843 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
845 if (is_bool($stmt)) {
848 $retval = ($this->numRows($stmt) > 0);
857 * Fetches the first row
859 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
861 * Fetches the first row
863 * @param string $sql SQL statement
865 * @return array|bool first row of query or false on failure
868 public function fetchFirst(string $sql)
870 $params = DBA::getParam(func_get_args());
872 $stmt = $this->p($sql, $params);
874 if (is_bool($stmt)) {
877 $retval = $this->fetch($stmt);
886 * Returns the number of affected rows of the last statement
888 * @return int Number of rows
890 public function affectedRows(): int
892 return $this->affected_rows;
896 * Returns the number of columns of a statement
898 * @param object Statement object
900 * @return int Number of columns
902 public function columnCount($stmt): int
904 if (!is_object($stmt)) {
907 switch ($this->driver) {
909 return $stmt->columnCount();
911 return $stmt->field_count;
917 * Returns the number of rows of a statement
919 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
921 * @return int Number of rows
923 public function numRows($stmt): int
925 if (!is_object($stmt)) {
928 switch ($this->driver) {
930 return $stmt->rowCount();
932 return $stmt->num_rows;
940 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
942 * @return array|bool Current row or false on failure
944 public function fetch($stmt)
946 $this->profiler->startRecording('database');
950 if (!is_object($stmt)) {
954 switch ($this->driver) {
956 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
957 if (!empty($stmt->table) && is_array($columns)) {
958 $columns = $this->castFields($stmt->table, $columns);
962 if (get_class($stmt) == 'mysqli_result') {
963 $columns = $stmt->fetch_assoc() ?? false;
967 // This code works, but is slow
969 // Bind the result to a result array
973 for ($x = 0; $x < $stmt->field_count; $x++) {
974 $cols[] = &$cols_num[$x];
977 call_user_func_array([$stmt, 'bind_result'], $cols);
979 if (!$stmt->fetch()) {
984 // We need to get the field names for the array keys
985 // It seems that there is no better way to do this.
986 $result = $stmt->result_metadata();
987 $fields = $result->fetch_fields();
989 foreach ($cols_num as $param => $col) {
990 $columns[$fields[$param]->name] = $col;
994 $this->profiler->stopRecording();
1000 * Insert a row into a table. Field value objects will be cast as string.
1002 * @param string $table Table name in format [schema.]table
1003 * @param array $param parameter array
1004 * @param int $duplicate_mode What to do on a duplicated entry
1006 * @return boolean was the insert successful?
1007 * @throws \Exception
1009 public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1011 if (empty($table) || empty($param)) {
1012 $this->logger->info('Table and fields have to be set');
1016 $param = $this->castFields($table, $param);
1018 $table_string = DBA::buildTableString([$table]);
1020 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1022 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1026 if ($duplicate_mode == self::INSERT_IGNORE) {
1030 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1032 if ($duplicate_mode == self::INSERT_UPDATE) {
1033 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1035 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1037 $values = array_values($param);
1038 $param = array_merge_recursive($values, $values);
1041 $result = $this->e($sql, $param);
1042 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1046 return $this->affectedRows() != 0;
1050 * Inserts a row with the provided data in the provided table.
1051 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1053 * @param string $table Table name in format [schema.]table
1054 * @param array $param parameter array
1055 * @return boolean was the insert successful?
1056 * @throws \Exception
1058 public function replace(string $table, array $param): bool
1060 if (empty($table) || empty($param)) {
1061 $this->logger->info('Table and fields have to be set');
1065 $param = $this->castFields($table, $param);
1067 $table_string = DBA::buildTableString([$table]);
1069 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1071 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1073 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1075 return $this->e($sql, $param);
1079 * Fetch the id of the last insert command
1081 * @return integer Last inserted id
1083 public function lastInsertId(): int
1085 switch ($this->driver) {
1087 $id = $this->connection->lastInsertId();
1090 $id = $this->connection->insert_id;
1097 * Locks a table for exclusive write access
1099 * This function can be extended in the future to accept a table array as well.
1101 * @param string $table Table name in format [schema.]table
1102 * @return boolean was the lock successful?
1103 * @throws \Exception
1105 public function lock(string $table): bool
1107 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1108 if ($this->driver == self::PDO) {
1109 $this->e("SET autocommit=0");
1110 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1112 $this->connection->autocommit(false);
1115 $success = $this->e("LOCK TABLES " . DBA::buildTableString([$table]) . " WRITE");
1117 if ($this->driver == self::PDO) {
1118 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1122 if ($this->driver == self::PDO) {
1123 $this->e("SET autocommit=1");
1125 $this->connection->autocommit(true);
1128 $this->in_transaction = true;
1134 * Unlocks all locked tables
1136 * @return boolean was the unlock successful?
1137 * @throws \Exception
1139 public function unlock(): bool
1141 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1142 $this->performCommit();
1144 if ($this->driver == self::PDO) {
1145 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1148 $success = $this->e("UNLOCK TABLES");
1150 if ($this->driver == self::PDO) {
1151 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1152 $this->e("SET autocommit=1");
1154 $this->connection->autocommit(true);
1157 $this->in_transaction = false;
1162 * Starts a transaction
1164 * @return boolean Was the command executed successfully?
1166 public function transaction(): bool
1168 if (!$this->performCommit()) {
1172 switch ($this->driver) {
1174 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1180 if (!$this->connection->begin_transaction()) {
1186 $this->in_transaction = true;
1191 * Performs the commit
1193 * @return boolean Was the command executed successfully?
1195 protected function performCommit(): bool
1197 switch ($this->driver) {
1199 if (!$this->connection->inTransaction()) {
1203 return $this->connection->commit();
1206 return $this->connection->commit();
1215 * @return boolean Was the command executed successfully?
1217 public function commit(): bool
1219 if (!$this->performCommit()) {
1222 $this->in_transaction = false;
1229 * @return boolean Was the command executed successfully?
1231 public function rollback(): bool
1235 switch ($this->driver) {
1237 if (!$this->connection->inTransaction()) {
1241 $ret = $this->connection->rollBack();
1245 $ret = $this->connection->rollback();
1249 $this->in_transaction = false;
1254 * Delete a row from a table
1256 * @param string $table Table name
1257 * @param array $conditions Field condition(s)
1259 * @return boolean was the delete successful?
1260 * @throws \Exception
1262 public function delete(string $table, array $conditions): bool
1264 if (empty($table) || empty($conditions)) {
1265 $this->logger->info('Table and conditions have to be set');
1269 $table_string = DBA::buildTableString([$table]);
1271 $condition_string = DBA::buildCondition($conditions);
1273 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1274 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1275 return $this->e($sql, $conditions);
1279 * Updates rows in the database. Field value objects will be cast as string.
1281 * When $old_fields is set to an array,
1282 * the system will only do an update if the fields in that array changed.
1285 * Only the values in $old_fields are compared.
1286 * This is an intentional behaviour.
1289 * We include the timestamp field in $fields but not in $old_fields.
1290 * Then the row will only get the new timestamp when the other fields had changed.
1292 * When $old_fields is set to a boolean value the system will do this compare itself.
1293 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1296 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1297 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1299 * @param string $table Table name in format [schema.]table
1300 * @param array $fields contains the fields that are updated
1301 * @param array $condition condition array with the key values
1302 * @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)
1303 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1305 * @return boolean was the update successfull?
1306 * @throws \Exception
1307 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1309 public function update(string $table, array $fields, array $condition, $old_fields = [], array $params = [])
1311 if (empty($table) || empty($fields) || empty($condition)) {
1312 $this->logger->info('Table, fields and condition have to be set');
1316 if (is_bool($old_fields)) {
1317 $do_insert = $old_fields;
1319 $old_fields = $this->selectFirst($table, [], $condition);
1321 if (is_bool($old_fields)) {
1323 $values = array_merge($condition, $fields);
1324 return $this->replace($table, $values);
1330 foreach ($old_fields as $fieldname => $content) {
1331 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1332 unset($fields[$fieldname]);
1336 if (count($fields) == 0) {
1340 $fields = $this->castFields($table, $fields);
1342 $table_string = DBA::buildTableString([$table]);
1344 $condition_string = DBA::buildCondition($condition);
1346 if (!empty($params['ignore'])) {
1347 $ignore = 'IGNORE ';
1352 $sql = "UPDATE " . $ignore . $table_string . " SET "
1353 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1354 . $condition_string;
1356 // Combines the updated fields parameter values with the condition parameter values
1357 $params = array_merge(array_values($fields), $condition);
1359 return $this->e($sql, $params);
1363 * Retrieve a single record from a table and returns it in an associative array
1365 * @param string $table Table name in format [schema.]table
1366 * @param array $fields Array of selected fields, empty for all
1367 * @param array $condition Array of fields for condition
1368 * @param array $params Array of several parameters
1370 * @return bool|array
1371 * @throws \Exception
1372 * @see $this->select
1374 public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1376 $params['limit'] = 1;
1377 $result = $this->select($table, $fields, $condition, $params);
1379 if (is_bool($result)) {
1382 $row = $this->fetch($result);
1383 $this->close($result);
1389 * Select rows from a table and fills an array with the data
1391 * @param string $table Table name in format [schema.]table
1392 * @param array $fields Array of selected fields, empty for all
1393 * @param array $condition Array of fields for condition
1394 * @param array $params Array of several parameters
1395 * @return array Data array
1396 * @throws \Exception
1399 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1401 return $this->toArray($this->select($table, $fields, $condition, $params));
1405 * Escape fields, adding special treatment for "group by" handling
1407 * @param array $fields
1408 * @param array $options
1409 * @return array Escaped fields
1411 private function escapeFields(array $fields, array $options): array
1413 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1414 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1415 // Otherwise MySQL would report errors.
1416 if (!empty($options['group_by']) && !empty($options['order'])) {
1417 foreach ($options['order'] as $key => $field) {
1418 if (!is_int($key)) {
1419 if (!in_array($key, $fields)) {
1423 if (!in_array($field, $fields)) {
1430 array_walk($fields, function (&$value, $key) use ($options) {
1432 $value = DBA::quoteIdentifier($field);
1434 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1435 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1443 * Select rows from a table
1449 * $table = ['schema' => 'table'];
1450 * @see DBA::buildTableString()
1452 * $fields = ['id', 'uri', 'uid', 'network'];
1454 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1456 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1457 * @see DBA::buildCondition()
1459 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1460 * @see DBA::buildParameter()
1462 * $data = DBA::select($table, $fields, $condition, $params);
1464 * @param string $table Table name in format [schema.]table
1465 * @param array $fields Array of selected fields, empty for all
1466 * @param array $condition Array of fields for condition
1467 * @param array $params Array of several parameters
1468 * @return boolean|object
1469 * @throws \Exception
1471 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1473 if (empty($table)) {
1477 if (count($fields) > 0) {
1478 $fields = $this->escapeFields($fields, $params);
1479 $select_string = implode(', ', $fields);
1481 $select_string = '*';
1484 $table_string = DBA::buildTableString([$table]);
1486 $condition_string = DBA::buildCondition($condition);
1488 $param_string = DBA::buildParameter($params);
1490 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1492 $result = $this->p($sql, $condition);
1494 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1495 $result->table = $table;
1502 * Counts the rows from a table satisfying the provided condition
1504 * @param string $table Table name in format [schema.]table
1505 * @param array $condition Array of fields for condition
1506 * @param array $params Array of several parameters
1508 * @return int Count of rows
1513 * $condition = ["uid" => 1, "network" => 'dspr'];
1515 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1517 * $count = DBA::count($table, $condition);
1518 * @throws \Exception
1520 public function count(string $table, array $condition = [], array $params = []): int
1522 if (empty($table)) {
1523 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1526 $table_string = DBA::buildTableString([$table]);
1528 $condition_string = DBA::buildCondition($condition);
1530 if (empty($params['expression'])) {
1532 } elseif (!empty($params['distinct'])) {
1533 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1535 $expression = DBA::quoteIdentifier($params['expression']);
1538 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1540 $row = $this->fetchFirst($sql, $condition);
1542 if (!isset($row['count'])) {
1543 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1546 return (int)$row['count'];
1551 * Fills an array with data from a query
1553 * @param object $stmt statement object
1554 * @param bool $do_close Close database connection after last row
1555 * @param int $count maximum number of rows to be fetched
1557 * @return array Data array
1559 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1561 if (is_bool($stmt)) {
1566 while ($row = $this->fetch($stmt)) {
1568 if (($count != 0) && (count($data) == $count)) {
1574 $this->close($stmt);
1581 * Cast field types according to the table definition
1583 * @param string $table
1584 * @param array $fields
1585 * @return array casted fields
1587 public function castFields(string $table, array $fields): array
1589 // When there is no data, we don't need to do something
1590 if (empty($fields)) {
1594 // We only need to cast fields with PDO
1595 if ($this->driver != self::PDO) {
1599 // We only need to cast when emulating the prepares
1600 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1606 $tables = $this->dbaDefinition->getAll();
1607 if (empty($tables[$table])) {
1608 // When a matching table wasn't found we check if it is a view
1609 $views = $this->viewDefinition->getAll();
1610 if (empty($views[$table])) {
1614 foreach (array_keys($fields) as $field) {
1615 if (!empty($views[$table]['fields'][$field])) {
1616 $viewdef = $views[$table]['fields'][$field];
1617 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1618 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1623 foreach ($tables[$table]['fields'] as $field => $definition) {
1624 $types[$field] = $definition['type'];
1628 foreach ($fields as $field => $content) {
1629 if (is_null($content) || empty($types[$field])) {
1633 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1634 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1635 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1636 $fields[$field] = (int)$content;
1638 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1639 $fields[$field] = (float)$content;
1647 * Returns the error number of the last query
1649 * @return string Error number (0 if no error)
1651 public function errorNo(): int
1653 return $this->errorno;
1657 * Returns the error message of the last query
1659 * @return string Error message ('' if no error)
1661 public function errorMessage(): string
1663 return $this->error;
1667 * Closes the current statement
1669 * @param object $stmt statement object
1671 * @return boolean was the close successful?
1673 public function close($stmt): bool
1676 $this->profiler->startRecording('database');
1678 if (!is_object($stmt)) {
1682 switch ($this->driver) {
1684 $ret = $stmt->closeCursor();
1687 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1688 // We should be careful not to assume the object type of $stmt
1689 // because DBA::p() has been able to return both types.
1690 if ($stmt instanceof mysqli_stmt) {
1691 $stmt->free_result();
1692 $ret = $stmt->close();
1693 } elseif ($stmt instanceof mysqli_result) {
1702 $this->profiler->stopRecording();
1708 * Return a list of database processes
1711 * 'list' => List of processes, separated in their different states
1712 * 'amount' => Number of concurrent database processes
1713 * @throws \Exception
1715 public function processlist(): array
1717 $ret = $this->p('SHOW PROCESSLIST');
1718 $data = $this->toArray($ret);
1722 foreach ($data as $process) {
1723 $state = trim($process['State']);
1725 // Filter out all non blocking processes
1726 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1733 foreach ($states as $state => $usage) {
1734 if ($statelist != '') {
1737 $statelist .= $state . ': ' . $usage;
1739 return (['list' => $statelist, 'amount' => $processes]);
1743 * Fetch a database variable
1745 * @param string $name
1746 * @return string|null content or null if inexistent
1747 * @throws \Exception
1749 public function getVariable(string $name)
1751 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1752 return $result['Value'] ?? null;
1756 * Checks if $array is a filled array with at least one entry.
1758 * @param mixed $array A filled array with at least one entry
1759 * @return boolean Whether $array is a filled array or an object with rows
1761 public function isResult($array): bool
1763 // It could be a return value from an update statement
1764 if (is_bool($array)) {
1768 if (is_object($array)) {
1769 return $this->numRows($array) > 0;
1772 return (is_array($array) && (count($array) > 0));
1776 * Callback function for "esc_array"
1778 * @param mixed $value Array value
1779 * @param string $key Array key
1780 * @param boolean $add_quotation add quotation marks for string values
1783 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1785 if (!$add_quotation) {
1786 if (is_bool($value)) {
1787 $value = ($value ? '1' : '0');
1789 $value = $this->escape($value);
1794 if (is_bool($value)) {
1795 $value = ($value ? 'true' : 'false');
1796 } elseif (is_float($value) || is_integer($value)) {
1797 $value = (string)$value;
1799 $value = "'" . $this->escape($value) . "'";
1804 * Escapes a whole array
1806 * @param mixed $arr Array with values to be escaped
1807 * @param boolean $add_quotation add quotation marks for string values
1810 public function escapeArray(&$arr, bool $add_quotation = false)
1812 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1816 * Replaces a string in the provided fields of the provided table
1818 * @param string $table Table name
1819 * @param array $fields List of field names in the provided table
1820 * @param string $search String to search for
1821 * @param string $replace String to replace with
1823 * @throws \Exception
1825 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1827 $search = $this->escape($search);
1828 $replace = $this->escape($replace);
1831 foreach ($fields as $field) {
1832 $field = DBA::quoteIdentifier($field);
1833 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1836 $upds = implode(', ', $upd);
1838 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1840 if (!$this->isResult($r)) {
1841 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());