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;
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;
52 * @var \Friendica\Core\Config\ValueObject\Cache
54 protected $configCache;
60 * @var LoggerInterface
63 protected $server_info = '';
64 /** @var PDO|mysqli */
65 protected $connection;
67 protected $pdo_emulate_prepares = false;
68 private $error = false;
70 private $affected_rows = 0;
71 protected $in_transaction = false;
72 protected $in_retrial = false;
73 protected $testmode = false;
74 private $relation = [];
76 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger)
78 // We are storing these values for being able to perform a reconnect
79 $this->configCache = $configCache;
80 $this->profiler = $profiler;
81 $this->logger = $logger;
85 if ($this->isConnected()) {
86 // Loads DB_UPDATE_VERSION constant
87 DBStructure::definition($configCache->get('system', 'basepath'), false);
92 * Tries to connect to database
94 * @return bool Success
96 public function connect(): bool
98 if (!is_null($this->connection) && $this->connected()) {
99 return $this->connected;
102 // Reset connected state
103 $this->connected = false;
106 $serveraddr = trim($this->configCache->get('database', 'hostname'));
107 $serverdata = explode(':', $serveraddr);
108 $server = $serverdata[0];
109 if (count($serverdata) > 1) {
110 $port = trim($serverdata[1]);
113 if (!empty(trim($this->configCache->get('database', 'port')))) {
114 $port = trim($this->configCache->get('database', 'port'));
117 $server = trim($server);
118 $user = trim($this->configCache->get('database', 'username'));
119 $pass = trim($this->configCache->get('database', 'password'));
120 $db = trim($this->configCache->get('database', 'database'));
121 $charset = trim($this->configCache->get('database', 'charset'));
122 $socket = trim($this->configCache->get('database', 'socket'));
124 if (!(strlen($server) && strlen($user))) {
128 $persistent = (bool)$this->configCache->get('database', 'persistent');
130 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
132 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
133 $this->driver = self::PDO;
134 $connect = "mysql:host=" . $server . ";dbname=" . $db;
137 $connect .= ";port=" . $port;
141 $connect .= ";charset=" . $charset;
145 $connect .= ";$unix_socket=" . $socket;
149 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
150 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
151 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
152 $this->connected = true;
153 } catch (PDOException $e) {
154 $this->connected = false;
158 if (!$this->connected && class_exists('\mysqli')) {
159 $this->driver = self::MYSQLI;
162 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
164 $this->connection = @new mysqli($server, $user, $pass, $db);
167 if (!mysqli_connect_errno()) {
168 $this->connected = true;
171 $this->connection->set_charset($charset);
175 $this->connection->set_socket($socket);
181 // No suitable SQL driver was found.
182 if (!$this->connected) {
183 $this->driver = null;
184 $this->connection = null;
187 return $this->connected;
190 public function setTestmode(bool $test)
192 $this->testmode = $test;
195 * Sets the logger for DBA
197 * @note this is necessary because if we want to load the logger configuration
198 * from the DB, but there's an error, we would print out an exception.
199 * So the logger gets updated after the logger configuration can be retrieved
202 * @param LoggerInterface $logger
204 public function setLogger(LoggerInterface $logger)
206 $this->logger = $logger;
210 * Sets the profiler for DBA
212 * @param Profiler $profiler
214 public function setProfiler(Profiler $profiler)
216 $this->profiler = $profiler;
219 * Disconnects the current database connection
221 public function disconnect()
223 if (!is_null($this->connection)) {
224 switch ($this->driver) {
226 $this->connection = null;
229 $this->connection->close();
230 $this->connection = null;
235 $this->driver = null;
236 $this->connected = false;
240 * Perform a reconnect of an existing database connection
242 public function reconnect()
245 return $this->connect();
249 * Return the database object.
253 public function getConnection()
255 return $this->connection;
259 * Return the database driver string
261 * @return string with either "pdo" or "mysqli"
263 public function getDriver(): string
265 return $this->driver;
269 * Returns the MySQL server version string
271 * This function discriminate between the deprecated mysql API and the current
272 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
274 * @return string Database server information
276 public function serverInfo(): string
278 if ($this->server_info == '') {
279 switch ($this->driver) {
281 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
284 $this->server_info = $this->connection->server_info;
288 return $this->server_info;
292 * Returns the selected database name
294 * @return string Database name
297 public function databaseName(): string
299 $ret = $this->p("SELECT DATABASE() AS `db`");
300 $data = $this->toArray($ret);
301 return $data[0]['db'];
305 * Analyze a database query and log this if some conditions are met.
307 * @param string $query The database query that will be analyzed
311 private function logIndex(string $query)
314 if (!$this->configCache->get('system', 'db_log_index')) {
318 // Don't explain an explain statement
319 if (strtolower(substr($query, 0, 7)) == "explain") {
323 // Only do the explain on "select", "update" and "delete"
324 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
328 $r = $this->p("EXPLAIN " . $query);
329 if (!$this->isResult($r)) {
333 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
334 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
336 while ($row = $this->fetch($r)) {
337 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
338 $log = (in_array($row['key'], $watchlist) &&
339 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
344 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
348 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
353 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
354 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
355 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
356 basename($backtrace[1]["file"]) . "\t" .
357 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
358 substr($query, 0, 4000) . "\n", FILE_APPEND);
364 * Removes every not allowlisted character from the identifier string
366 * @param string $identifier
367 * @return string sanitized identifier
370 private function sanitizeIdentifier(string $identifier): string
372 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
375 public function escape($str)
377 if ($this->connected) {
378 switch ($this->driver) {
380 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
383 return @$this->connection->real_escape_string($str);
386 return str_replace("'", "\\'", $str);
391 * Returns connected flag
393 * @return bool Whether connection to database was success
395 public function isConnected(): bool
397 return $this->connected;
401 * Checks connection status
403 * @return bool Whether connection to database was success
405 public function connected()
409 if (is_null($this->connection)) {
413 switch ($this->driver) {
415 $r = $this->p("SELECT 1");
416 if ($this->isResult($r)) {
417 $row = $this->toArray($r);
418 $connected = ($row[0]['1'] == '1');
422 $connected = $this->connection->ping();
430 * Replaces ANY_VALUE() function by MIN() function,
431 * if the database server does not support ANY_VALUE().
433 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
434 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
435 * A standard fall-back is to use MIN().
437 * @param string $sql An SQL string without the values
439 * @return string The input SQL string modified if necessary.
441 public function anyValueFallback(string $sql): string
443 $server_info = $this->serverInfo();
444 if (version_compare($server_info, '5.7.5', '<') ||
445 (stripos($server_info, 'MariaDB') !== false)) {
446 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
452 * Replaces the ? placeholders with the parameters in the $args array
454 * @param string $sql SQL query
455 * @param array $args The parameters that are to replace the ? placeholders
457 * @return string The replaced SQL query
459 private function replaceParameters(string $sql, array $args): string
462 foreach ($args as $param => $value) {
463 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
464 $replace = intval($args[$param]);
465 } elseif (is_null($args[$param])) {
468 $replace = "'" . $this->escape($args[$param]) . "'";
471 $pos = strpos($sql, '?', $offset);
472 if ($pos !== false) {
473 $sql = substr_replace($sql, $replace, $pos, 1);
475 $offset = $pos + strlen($replace);
481 * Executes a prepared statement that returns data
483 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
485 * Please only use it with complicated queries.
486 * For all regular queries please use DBA::select or DBA::exists
488 * @param string $sql SQL statement
490 * @return bool|object statement object or result object
493 public function p(string $sql)
496 $this->profiler->startRecording('database');
497 $stamp1 = microtime(true);
499 $params = DBA::getParam(func_get_args());
501 // Renumber the array keys to be sure that they fit
504 foreach ($params as $param) {
505 // Avoid problems with some MySQL servers and boolean values. See issue #3645
506 if (is_bool($param)) {
507 $param = (int)$param;
509 $args[++$i] = $param;
512 if (!$this->connected) {
516 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
517 // Question: Should we continue or stop the query here?
518 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
521 $sql = DBA::cleanQuery($sql);
522 $sql = $this->anyValueFallback($sql);
526 if ($this->configCache->get('system', 'db_callstack') !== null) {
527 $sql = "/*" . System::callstack() . " */ " . $sql;
533 $this->affected_rows = 0;
535 // We have to make some things different if this function is called from "e"
536 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
538 if (isset($trace[1])) {
539 $called_from = $trace[1];
541 // We use just something that is defined to avoid warnings
542 $called_from = $trace[0];
544 // We are having an own error logging in the function "e"
545 $called_from_e = ($called_from['function'] == 'e');
547 if (!isset($this->connection)) {
548 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
551 switch ($this->driver) {
553 // If there are no arguments we use "query"
554 if (count($args) == 0) {
555 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
556 $errorInfo = $this->connection->errorInfo();
557 $this->error = $errorInfo[2];
558 $this->errorno = (int) $errorInfo[1];
563 $this->affected_rows = $retval->rowCount();
567 /** @var $stmt mysqli_stmt|PDOStatement */
568 if (!$stmt = $this->connection->prepare($sql)) {
569 $errorInfo = $this->connection->errorInfo();
570 $this->error = $errorInfo[2];
571 $this->errorno = (int) $errorInfo[1];
577 foreach (array_keys($args) as $param) {
578 $data_type = PDO::PARAM_STR;
579 if (is_int($args[$param])) {
580 $data_type = PDO::PARAM_INT;
581 } elseif ($args[$param] !== null) {
582 $args[$param] = (string)$args[$param];
585 $stmt->bindParam($param, $args[$param], $data_type);
588 if (!$stmt->execute()) {
589 $errorInfo = $stmt->errorInfo();
590 $this->error = $errorInfo[2];
591 $this->errorno = (int) $errorInfo[1];
596 $this->affected_rows = $retval->rowCount();
600 // There are SQL statements that cannot be executed with a prepared statement
601 $parts = explode(' ', $orig_sql);
602 $command = strtolower($parts[0]);
603 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
605 // The fallback routine is called as well when there are no arguments
606 if (!$can_be_prepared || (count($args) == 0)) {
607 $retval = $this->connection->query($this->replaceParameters($sql, $args));
608 if ($this->connection->errno) {
609 $this->error = $this->connection->error;
610 $this->errorno = $this->connection->errno;
614 if (isset($retval->num_rows)) {
615 $this->affected_rows = $retval->num_rows;
617 $this->affected_rows = $this->connection->affected_rows;
623 $stmt = $this->connection->stmt_init();
625 if (!$stmt->prepare($sql)) {
626 $this->error = $stmt->error;
627 $this->errorno = $stmt->errno;
635 foreach (array_keys($args) as $param) {
636 if (is_int($args[$param])) {
638 } elseif (is_float($args[$param])) {
640 } elseif (is_string($args[$param])) {
642 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
644 $args[$param] = (string)$args[$param];
648 $values[] = &$args[$param];
651 if (count($values) > 0) {
652 array_unshift($values, $param_types);
653 call_user_func_array([$stmt, 'bind_param'], $values);
656 if (!$stmt->execute()) {
657 $this->error = $this->connection->error;
658 $this->errorno = $this->connection->errno;
662 $stmt->store_result();
664 $this->affected_rows = $retval->affected_rows;
669 // See issue https://github.com/friendica/friendica/issues/8572
670 // Ensure that we always get an error message on an error.
671 if ($is_error && empty($this->errorno)) {
675 if ($is_error && empty($this->error)) {
676 $this->error = 'Unknown database error';
679 // We are having an own error logging in the function "e"
680 if (($this->errorno != 0) && !$called_from_e) {
681 // We have to preserve the error code, somewhere in the logging it get lost
682 $error = $this->error;
683 $errorno = $this->errorno;
685 if ($this->testmode) {
686 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
689 $this->logger->error('DB Error', [
692 'callstack' => System::callstack(8),
693 'params' => $this->replaceParameters($sql, $args),
696 // On a lost connection we try to reconnect - but only once.
697 if ($errorno == 2006) {
698 if ($this->in_retrial || !$this->reconnect()) {
699 // It doesn't make sense to continue when the database connection was lost
700 if ($this->in_retrial) {
701 $this->logger->notice('Giving up retrial because of database error', [
706 $this->logger->notice('Couldn\'t reconnect after database error', [
714 $this->logger->notice('Reconnected after database error', [
718 $this->in_retrial = true;
719 $ret = $this->p($sql, $args);
720 $this->in_retrial = false;
725 $this->error = $error;
726 $this->errorno = (int) $errorno;
729 $this->profiler->stopRecording();
731 if ($this->configCache->get('system', 'db_log')) {
732 $stamp2 = microtime(true);
733 $duration = (float)($stamp2 - $stamp1);
735 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
736 $duration = round($duration, 3);
737 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
739 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
740 basename($backtrace[1]["file"]) . "\t" .
741 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
742 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
749 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
751 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
753 * @param string $sql SQL statement
755 * @return boolean Was the query successfull? False is returned only if an error occurred
758 public function e(string $sql): bool
762 $this->profiler->startRecording('database_write');
764 $params = DBA::getParam(func_get_args());
766 // In a case of a deadlock we are repeating the query 20 times
770 $stmt = $this->p($sql, $params);
772 if (is_bool($stmt)) {
774 } elseif (is_object($stmt)) {
782 } while (($this->errorno == 1213) && (--$timeout > 0));
784 if ($this->errorno != 0) {
785 // We have to preserve the error code, somewhere in the logging it get lost
786 $error = $this->error;
787 $errorno = $this->errorno;
789 if ($this->testmode) {
790 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
793 $this->logger->error('DB Error', [
796 'callstack' => System::callstack(8),
797 'params' => $this->replaceParameters($sql, $params),
800 // On a lost connection we simply quit.
801 // A reconnect like in $this->p could be dangerous with modifications
802 if ($errorno == 2006) {
803 $this->logger->notice('Giving up because of database error', [
810 $this->error = $error;
811 $this->errorno = $errorno;
814 $this->profiler->stopRecording();
820 * Check if data exists
822 * @param string|array $table Table name or array [schema => table]
823 * @param array $condition array of fields for condition
825 * @return boolean Are there rows for that condition?
828 public function exists($table, array $condition): bool
836 if (empty($condition)) {
837 return DBStructure::existsTable($table);
841 $first_key = key($condition);
842 if (!is_int($first_key)) {
843 $fields = [$first_key];
846 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
848 if (is_bool($stmt)) {
851 $retval = ($this->numRows($stmt) > 0);
860 * Fetches the first row
862 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
864 * Fetches the first row
866 * @param string $sql SQL statement
868 * @return array|bool first row of query or false on failure
871 public function fetchFirst(string $sql)
873 $params = DBA::getParam(func_get_args());
875 $stmt = $this->p($sql, $params);
877 if (is_bool($stmt)) {
880 $retval = $this->fetch($stmt);
889 * Returns the number of affected rows of the last statement
891 * @return int Number of rows
893 public function affectedRows(): int
895 return $this->affected_rows;
899 * Returns the number of columns of a statement
901 * @param object Statement object
903 * @return int Number of columns
905 public function columnCount($stmt): int
907 if (!is_object($stmt)) {
910 switch ($this->driver) {
912 return $stmt->columnCount();
914 return $stmt->field_count;
920 * Returns the number of rows of a statement
922 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
924 * @return int Number of rows
926 public function numRows($stmt): int
928 if (!is_object($stmt)) {
931 switch ($this->driver) {
933 return $stmt->rowCount();
935 return $stmt->num_rows;
943 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
945 * @return array|bool Current row or false on failure
947 public function fetch($stmt)
949 $this->profiler->startRecording('database');
953 if (!is_object($stmt)) {
957 switch ($this->driver) {
959 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
960 if (!empty($stmt->table) && is_array($columns)) {
961 $columns = $this->castFields($stmt->table, $columns);
965 if (get_class($stmt) == 'mysqli_result') {
966 $columns = $stmt->fetch_assoc() ?? false;
970 // This code works, but is slow
972 // Bind the result to a result array
976 for ($x = 0; $x < $stmt->field_count; $x++) {
977 $cols[] = &$cols_num[$x];
980 call_user_func_array([$stmt, 'bind_result'], $cols);
982 if (!$stmt->fetch()) {
987 // We need to get the field names for the array keys
988 // It seems that there is no better way to do this.
989 $result = $stmt->result_metadata();
990 $fields = $result->fetch_fields();
992 foreach ($cols_num as $param => $col) {
993 $columns[$fields[$param]->name] = $col;
997 $this->profiler->stopRecording();
1003 * Insert a row into a table. Field value objects will be cast as string.
1005 * @param string|array $table Table name or array [schema => table]
1006 * @param array $param parameter array
1007 * @param int $duplicate_mode What to do on a duplicated entry
1009 * @return boolean was the insert successful?
1010 * @throws \Exception
1012 public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1014 if (empty($table) || empty($param)) {
1015 $this->logger->info('Table and fields have to be set');
1019 $param = $this->castFields($table, $param);
1021 $table_string = DBA::buildTableString($table);
1023 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1025 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1029 if ($duplicate_mode == self::INSERT_IGNORE) {
1033 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1035 if ($duplicate_mode == self::INSERT_UPDATE) {
1036 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1038 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1040 $values = array_values($param);
1041 $param = array_merge_recursive($values, $values);
1044 $result = $this->e($sql, $param);
1045 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1049 return $this->affectedRows() != 0;
1053 * Inserts a row with the provided data in the provided table.
1054 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1056 * @param string|array $table Table name or array [schema => table]
1057 * @param array $param parameter array
1059 * @return boolean was the insert successful?
1060 * @throws \Exception
1062 public function replace($table, array $param): bool
1064 if (empty($table) || empty($param)) {
1065 $this->logger->info('Table and fields have to be set');
1069 $param = $this->castFields($table, $param);
1071 $table_string = DBA::buildTableString($table);
1073 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1075 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1077 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1079 return $this->e($sql, $param);
1083 * Fetch the id of the last insert command
1085 * @return integer Last inserted id
1087 public function lastInsertId(): int
1089 switch ($this->driver) {
1091 $id = $this->connection->lastInsertId();
1094 $id = $this->connection->insert_id;
1101 * Locks a table for exclusive write access
1103 * This function can be extended in the future to accept a table array as well.
1105 * @param string|array $table Table name or array [schema => table]
1107 * @return boolean was the lock successful?
1108 * @throws \Exception
1110 public function lock($table): bool
1112 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1113 if ($this->driver == self::PDO) {
1114 $this->e("SET autocommit=0");
1115 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1117 $this->connection->autocommit(false);
1120 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1122 if ($this->driver == self::PDO) {
1123 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1127 if ($this->driver == self::PDO) {
1128 $this->e("SET autocommit=1");
1130 $this->connection->autocommit(true);
1133 $this->in_transaction = true;
1139 * Unlocks all locked tables
1141 * @return boolean was the unlock successful?
1142 * @throws \Exception
1144 public function unlock(): bool
1146 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1147 $this->performCommit();
1149 if ($this->driver == self::PDO) {
1150 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1153 $success = $this->e("UNLOCK TABLES");
1155 if ($this->driver == self::PDO) {
1156 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1157 $this->e("SET autocommit=1");
1159 $this->connection->autocommit(true);
1162 $this->in_transaction = false;
1167 * Starts a transaction
1169 * @return boolean Was the command executed successfully?
1171 public function transaction(): bool
1173 if (!$this->performCommit()) {
1177 switch ($this->driver) {
1179 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1185 if (!$this->connection->begin_transaction()) {
1191 $this->in_transaction = true;
1196 * Performs the commit
1198 * @return boolean Was the command executed successfully?
1200 protected function performCommit(): bool
1202 switch ($this->driver) {
1204 if (!$this->connection->inTransaction()) {
1208 return $this->connection->commit();
1211 return $this->connection->commit();
1220 * @return boolean Was the command executed successfully?
1222 public function commit(): bool
1224 if (!$this->performCommit()) {
1227 $this->in_transaction = false;
1234 * @return boolean Was the command executed successfully?
1236 public function rollback(): bool
1240 switch ($this->driver) {
1242 if (!$this->connection->inTransaction()) {
1246 $ret = $this->connection->rollBack();
1250 $ret = $this->connection->rollback();
1254 $this->in_transaction = false;
1259 * Delete a row from a table
1261 * @param string $table Table name
1262 * @param array $conditions Field condition(s)
1264 * @return boolean was the delete successful?
1265 * @throws \Exception
1267 public function delete($table, array $conditions): bool
1269 if (empty($table) || empty($conditions)) {
1270 $this->logger->info('Table and conditions have to be set');
1274 $table_string = DBA::buildTableString($table);
1276 $condition_string = DBA::buildCondition($conditions);
1278 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1279 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1280 return $this->e($sql, $conditions);
1284 * Updates rows in the database. Field value objects will be cast as string.
1286 * When $old_fields is set to an array,
1287 * the system will only do an update if the fields in that array changed.
1290 * Only the values in $old_fields are compared.
1291 * This is an intentional behaviour.
1294 * We include the timestamp field in $fields but not in $old_fields.
1295 * Then the row will only get the new timestamp when the other fields had changed.
1297 * When $old_fields is set to a boolean value the system will do this compare itself.
1298 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1301 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1302 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1304 * @param string|array $table Table name or array [schema => table]
1305 * @param array $fields contains the fields that are updated
1306 * @param array $condition condition array with the key values
1307 * @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)
1308 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1310 * @return boolean was the update successfull?
1311 * @throws \Exception
1312 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1314 public function update($table, array $fields, array $condition, $old_fields = [], array $params = [])
1316 if (empty($table) || empty($fields) || empty($condition)) {
1317 $this->logger->info('Table, fields and condition have to be set');
1321 if (is_bool($old_fields)) {
1322 $do_insert = $old_fields;
1324 $old_fields = $this->selectFirst($table, [], $condition);
1326 if (is_bool($old_fields)) {
1328 $values = array_merge($condition, $fields);
1329 return $this->replace($table, $values);
1335 foreach ($old_fields as $fieldname => $content) {
1336 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1337 unset($fields[$fieldname]);
1341 if (count($fields) == 0) {
1345 $fields = $this->castFields($table, $fields);
1347 $table_string = DBA::buildTableString($table);
1349 $condition_string = DBA::buildCondition($condition);
1351 if (!empty($params['ignore'])) {
1352 $ignore = 'IGNORE ';
1357 $sql = "UPDATE " . $ignore . $table_string . " SET "
1358 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1359 . $condition_string;
1361 // Combines the updated fields parameter values with the condition parameter values
1362 $params = array_merge(array_values($fields), $condition);
1364 return $this->e($sql, $params);
1368 * Retrieve a single record from a table and returns it in an associative array
1370 * @param string|array $table
1371 * @param array $fields
1372 * @param array $condition
1373 * @param array $params
1375 * @return bool|array
1376 * @throws \Exception
1377 * @see $this->select
1379 public function selectFirst($table, array $fields = [], array $condition = [], array $params = [])
1381 $params['limit'] = 1;
1382 $result = $this->select($table, $fields, $condition, $params);
1384 if (is_bool($result)) {
1387 $row = $this->fetch($result);
1388 $this->close($result);
1394 * Select rows from a table and fills an array with the data
1396 * @param string|array $table Table name or array [schema => table]
1397 * @param array $fields Array of selected fields, empty for all
1398 * @param array $condition Array of fields for condition
1399 * @param array $params Array of several parameters
1401 * @return array Data array
1402 * @throws \Exception
1405 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1407 return $this->toArray($this->select($table, $fields, $condition, $params));
1411 * Escape fields, adding special treatment for "group by" handling
1413 * @param array $fields
1414 * @param array $options
1415 * @return array Escaped fields
1417 private function escapeFields(array $fields, array $options): array
1419 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1420 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1421 // Otherwise MySQL would report errors.
1422 if (!empty($options['group_by']) && !empty($options['order'])) {
1423 foreach ($options['order'] as $key => $field) {
1424 if (!is_int($key)) {
1425 if (!in_array($key, $fields)) {
1429 if (!in_array($field, $fields)) {
1436 array_walk($fields, function(&$value, $key) use ($options)
1439 $value = '`' . str_replace('`', '``', $value) . '`';
1441 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1442 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1450 * Select rows from a table
1456 * $table = ['schema' => 'table'];
1457 * @see DBA::buildTableString()
1459 * $fields = ['id', 'uri', 'uid', 'network'];
1461 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1463 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1464 * @see DBA::buildCondition()
1466 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1467 * @see DBA::buildParameter()
1469 * $data = DBA::select($table, $fields, $condition, $params);
1471 * @param string|array $table Table name or array [schema => table]
1472 * @param array $fields Array of selected fields, empty for all
1473 * @param array $condition Array of fields for condition
1474 * @param array $params Array of several parameters
1475 * @return boolean|object
1476 * @throws \Exception
1478 public function select($table, array $fields = [], array $condition = [], array $params = [])
1480 if (empty($table)) {
1484 if (count($fields) > 0) {
1485 $fields = $this->escapeFields($fields, $params);
1486 $select_string = implode(', ', $fields);
1488 $select_string = '*';
1491 $table_string = DBA::buildTableString($table);
1493 $condition_string = DBA::buildCondition($condition);
1495 $param_string = DBA::buildParameter($params);
1497 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1499 $result = $this->p($sql, $condition);
1501 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1502 $result->table = $table;
1509 * Counts the rows from a table satisfying the provided condition
1511 * @param string|array $table Table name or array [schema => table]
1512 * @param array $condition Array of fields for condition
1513 * @param array $params Array of several parameters
1520 * $condition = ["uid" => 1, "network" => 'dspr'];
1522 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1524 * $count = DBA::count($table, $condition);
1525 * @throws \Exception
1527 public function count($table, array $condition = [], array $params = [])
1529 // @TODO Can we dump this to have ": int" as returned type-hint?
1530 if (empty($table)) {
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;", $table_name, $upds));
1847 if (!$this->isResult($r)) {
1848 throw new \RuntimeException("Failed updating `$table_name`: " . $this->errorMessage());