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;
67 protected $driver = '';
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) {
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;
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 $table Table name in format schema.table (while scheme is optiona)
824 * @param array $condition Array of fields for condition
826 * @return boolean Are there rows for that condition?
828 * @todo Get rid of the DBStructure::existsTable() invocation
830 public function exists(string $table, array $condition): bool
838 if (empty($condition)) {
839 return DBStructure::existsTable($table);
843 $first_key = key($condition);
844 if (!is_int($first_key)) {
845 $fields = [$first_key];
848 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
850 if (is_bool($stmt)) {
853 $retval = ($this->numRows($stmt) > 0);
862 * Fetches the first row
864 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
866 * Fetches the first row
868 * @param string $sql SQL statement
870 * @return array|bool first row of query or false on failure
873 public function fetchFirst(string $sql)
875 $params = DBA::getParam(func_get_args());
877 $stmt = $this->p($sql, $params);
879 if (is_bool($stmt)) {
882 $retval = $this->fetch($stmt);
891 * Returns the number of affected rows of the last statement
893 * @return int Number of rows
895 public function affectedRows(): int
897 return $this->affected_rows;
901 * Returns the number of columns of a statement
903 * @param object Statement object
905 * @return int Number of columns
907 public function columnCount($stmt): int
909 if (!is_object($stmt)) {
912 switch ($this->driver) {
914 return $stmt->columnCount();
916 return $stmt->field_count;
922 * Returns the number of rows of a statement
924 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
926 * @return int Number of rows
928 public function numRows($stmt): int
930 if (!is_object($stmt)) {
933 switch ($this->driver) {
935 return $stmt->rowCount();
937 return $stmt->num_rows;
945 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
947 * @return array|bool Current row or false on failure
949 public function fetch($stmt)
951 $this->profiler->startRecording('database');
955 if (!is_object($stmt)) {
959 switch ($this->driver) {
961 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
962 if (!empty($stmt->table) && is_array($columns)) {
963 $columns = $this->castFields($stmt->table, $columns);
967 if (get_class($stmt) == 'mysqli_result') {
968 $columns = $stmt->fetch_assoc() ?? false;
972 // This code works, but is slow
974 // Bind the result to a result array
978 for ($x = 0; $x < $stmt->field_count; $x++) {
979 $cols[] = &$cols_num[$x];
982 call_user_func_array([$stmt, 'bind_result'], $cols);
984 if (!$stmt->fetch()) {
989 // We need to get the field names for the array keys
990 // It seems that there is no better way to do this.
991 $result = $stmt->result_metadata();
992 $fields = $result->fetch_fields();
994 foreach ($cols_num as $param => $col) {
995 $columns[$fields[$param]->name] = $col;
999 $this->profiler->stopRecording();
1005 * Insert a row into a table. Field value objects will be cast as string.
1007 * @param string $table Table name in format schema.table (while scheme is optiona)
1008 * @param array $param parameter array
1009 * @param int $duplicate_mode What to do on a duplicated entry
1011 * @return boolean was the insert successful?
1012 * @throws \Exception
1014 public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1016 if (empty($table) || empty($param)) {
1017 $this->logger->info('Table and fields have to be set');
1021 $param = $this->castFields($table, $param);
1023 $table_string = DBA::buildTableString([$table]);
1025 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1027 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1031 if ($duplicate_mode == self::INSERT_IGNORE) {
1035 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1037 if ($duplicate_mode == self::INSERT_UPDATE) {
1038 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1040 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1042 $values = array_values($param);
1043 $param = array_merge_recursive($values, $values);
1046 $result = $this->e($sql, $param);
1047 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1051 return $this->affectedRows() != 0;
1055 * Inserts a row with the provided data in the provided table.
1056 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1058 * @param string $table Table name in format schema.table (while scheme is optiona)
1059 * @param array $param parameter array
1060 * @return boolean was the insert successful?
1061 * @throws \Exception
1063 public function replace(string $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 $table Table name in format schema.table (while scheme is optiona)
1107 * @return boolean was the lock successful?
1108 * @throws \Exception
1110 public function lock(string $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(string $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 $table Table name in format schema.table (while scheme is optiona)
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(string $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 $table Table name in format schema.table (while scheme is optiona)
1371 * @param array $fields Array of selected fields, empty for all
1372 * @param array $condition Array of fields for condition
1373 * @param array $params Array of several parameters
1375 * @return bool|array
1376 * @throws \Exception
1377 * @see $this->select
1379 public function selectFirst(string $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 $table Table name in format schema.table (while scheme is optiona)
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
1400 * @return array Data array
1401 * @throws \Exception
1404 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1406 return $this->toArray($this->select($table, $fields, $condition, $params));
1410 * Escape fields, adding special treatment for "group by" handling
1412 * @param array $fields
1413 * @param array $options
1414 * @return array Escaped fields
1416 private function escapeFields(array $fields, array $options): array
1418 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1419 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1420 // Otherwise MySQL would report errors.
1421 if (!empty($options['group_by']) && !empty($options['order'])) {
1422 foreach ($options['order'] as $key => $field) {
1423 if (!is_int($key)) {
1424 if (!in_array($key, $fields)) {
1428 if (!in_array($field, $fields)) {
1435 array_walk($fields, function(&$value, $key) use ($options)
1438 $value = '`' . str_replace('`', '``', $value) . '`';
1440 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1441 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1449 * Select rows from a table
1455 * $table = ['schema' => 'table'];
1456 * @see DBA::buildTableString()
1458 * $fields = ['id', 'uri', 'uid', 'network'];
1460 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1462 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1463 * @see DBA::buildCondition()
1465 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1466 * @see DBA::buildParameter()
1468 * $data = DBA::select($table, $fields, $condition, $params);
1470 * @param string $table Table name in format schema.table (while scheme is optiona)
1471 * @param array $fields Array of selected fields, empty for all
1472 * @param array $condition Array of fields for condition
1473 * @param array $params Array of several parameters
1474 * @return boolean|object
1475 * @throws \Exception
1477 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1479 if (empty($table)) {
1483 if (count($fields) > 0) {
1484 $fields = $this->escapeFields($fields, $params);
1485 $select_string = implode(', ', $fields);
1487 $select_string = '*';
1490 $table_string = DBA::buildTableString([$table]);
1492 $condition_string = DBA::buildCondition($condition);
1494 $param_string = DBA::buildParameter($params);
1496 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1498 $result = $this->p($sql, $condition);
1500 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1501 $result->table = $table;
1508 * Counts the rows from a table satisfying the provided condition
1510 * @param string $table Table name in format schema.table (while scheme is optiona)
1511 * @param array $condition Array of fields for condition
1512 * @param array $params Array of several parameters
1514 * @return int Count of rows
1519 * $condition = ["uid" => 1, "network" => 'dspr'];
1521 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1523 * $count = DBA::count($table, $condition);
1524 * @throws \Exception
1526 public function count(string $table, array $condition = [], array $params = []): int
1528 if (empty($table)) {
1529 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1532 $table_string = DBA::buildTableString([$table]);
1534 $condition_string = DBA::buildCondition($condition);
1536 if (empty($params['expression'])) {
1538 } elseif (!empty($params['distinct'])) {
1539 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1541 $expression = DBA::quoteIdentifier($params['expression']);
1544 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1546 $row = $this->fetchFirst($sql, $condition);
1548 if (!isset($row['count'])) {
1549 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1552 return (int)$row['count'];
1557 * Fills an array with data from a query
1559 * @param object $stmt statement object
1560 * @param bool $do_close Close database connection after last row
1561 * @param int $count maximum number of rows to be fetched
1563 * @return array Data array
1565 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1567 if (is_bool($stmt)) {
1572 while ($row = $this->fetch($stmt)) {
1574 if (($count != 0) && (count($data) == $count)) {
1580 $this->close($stmt);
1587 * Cast field types according to the table definition
1589 * @param string $table
1590 * @param array $fields
1591 * @return array casted fields
1593 public function castFields(string $table, array $fields): array
1595 // When there is no data, we don't need to do something
1596 if (empty($fields)) {
1600 // We only need to cast fields with PDO
1601 if ($this->driver != self::PDO) {
1605 // We only need to cast when emulating the prepares
1606 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1612 $tables = DBStructure::definition('', false);
1613 if (empty($tables[$table])) {
1614 // When a matching table wasn't found we check if it is a view
1615 $views = View::definition('', false);
1616 if (empty($views[$table])) {
1620 foreach (array_keys($fields) as $field) {
1621 if (!empty($views[$table]['fields'][$field])) {
1622 $viewdef = $views[$table]['fields'][$field];
1623 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1624 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1629 foreach ($tables[$table]['fields'] as $field => $definition) {
1630 $types[$field] = $definition['type'];
1634 foreach ($fields as $field => $content) {
1635 if (is_null($content) || empty($types[$field])) {
1639 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1640 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1641 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1642 $fields[$field] = (int)$content;
1644 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1645 $fields[$field] = (float)$content;
1653 * Returns the error number of the last query
1655 * @return string Error number (0 if no error)
1657 public function errorNo(): int
1659 return $this->errorno;
1663 * Returns the error message of the last query
1665 * @return string Error message ('' if no error)
1667 public function errorMessage(): string
1669 return $this->error;
1673 * Closes the current statement
1675 * @param object $stmt statement object
1677 * @return boolean was the close successful?
1679 public function close($stmt): bool
1682 $this->profiler->startRecording('database');
1684 if (!is_object($stmt)) {
1688 switch ($this->driver) {
1690 $ret = $stmt->closeCursor();
1693 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1694 // We should be careful not to assume the object type of $stmt
1695 // because DBA::p() has been able to return both types.
1696 if ($stmt instanceof mysqli_stmt) {
1697 $stmt->free_result();
1698 $ret = $stmt->close();
1699 } elseif ($stmt instanceof mysqli_result) {
1708 $this->profiler->stopRecording();
1714 * Return a list of database processes
1717 * 'list' => List of processes, separated in their different states
1718 * 'amount' => Number of concurrent database processes
1719 * @throws \Exception
1721 public function processlist(): array
1723 $ret = $this->p('SHOW PROCESSLIST');
1724 $data = $this->toArray($ret);
1728 foreach ($data as $process) {
1729 $state = trim($process['State']);
1731 // Filter out all non blocking processes
1732 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1739 foreach ($states as $state => $usage) {
1740 if ($statelist != '') {
1743 $statelist .= $state . ': ' . $usage;
1745 return (['list' => $statelist, 'amount' => $processes]);
1749 * Fetch a database variable
1751 * @param string $name
1752 * @return string|null content or null if inexistent
1753 * @throws \Exception
1755 public function getVariable(string $name)
1757 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1758 return $result['Value'] ?? null;
1762 * Checks if $array is a filled array with at least one entry.
1764 * @param mixed $array A filled array with at least one entry
1765 * @return boolean Whether $array is a filled array or an object with rows
1767 public function isResult($array): bool
1769 // It could be a return value from an update statement
1770 if (is_bool($array)) {
1774 if (is_object($array)) {
1775 return $this->numRows($array) > 0;
1778 return (is_array($array) && (count($array) > 0));
1782 * Callback function for "esc_array"
1784 * @param mixed $value Array value
1785 * @param string $key Array key
1786 * @param boolean $add_quotation add quotation marks for string values
1789 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1791 if (!$add_quotation) {
1792 if (is_bool($value)) {
1793 $value = ($value ? '1' : '0');
1795 $value = $this->escape($value);
1800 if (is_bool($value)) {
1801 $value = ($value ? 'true' : 'false');
1802 } elseif (is_float($value) || is_integer($value)) {
1803 $value = (string)$value;
1805 $value = "'" . $this->escape($value) . "'";
1810 * Escapes a whole array
1812 * @param mixed $arr Array with values to be escaped
1813 * @param boolean $add_quotation add quotation marks for string values
1816 public function escapeArray(&$arr, bool $add_quotation = false)
1818 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1822 * Replaces a string in the provided fields of the provided table
1824 * @param string $table Table name
1825 * @param array $fields List of field names in the provided table
1826 * @param string $search String to search for
1827 * @param string $replace String to replace with
1829 * @throws \Exception
1831 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1833 $search = $this->escape($search);
1834 $replace = $this->escape($replace);
1837 foreach ($fields as $field) {
1838 $field = DBA::quoteIdentifier($field);
1839 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1842 $upds = implode(', ', $upd);
1844 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1846 if (!$this->isResult($r)) {
1847 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());