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;
39 use Psr\Log\NullLogger;
42 * This class is for the low level database stuff that does driver specific things.
47 const MYSQLI = 'mysqli';
49 const INSERT_DEFAULT = 0;
50 const INSERT_UPDATE = 1;
51 const INSERT_IGNORE = 2;
53 protected $connected = false;
56 * @var IManageConfigValues
58 protected $config = null;
62 protected $profiler = null;
64 * @var LoggerInterface
66 protected $logger = null;
67 protected $server_info = '';
68 /** @var PDO|mysqli */
69 protected $connection;
70 protected $driver = '';
71 protected $pdo_emulate_prepares = false;
74 private $affected_rows = 0;
75 protected $in_transaction = false;
76 protected $in_retrial = false;
77 protected $testmode = false;
78 private $relation = [];
79 /** @var DbaDefinition */
80 protected $dbaDefinition;
81 /** @var ViewDefinition */
82 protected $viewDefinition;
83 /** @var string|null */
84 private $currentTable;
86 public function __construct(IManageConfigValues $config, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition)
88 // We are storing these values for being able to perform a reconnect
89 $this->config = $config;
90 $this->dbaDefinition = $dbaDefinition;
91 $this->viewDefinition = $viewDefinition;
93 // Use dummy values - necessary for the first factory call of the logger itself
94 $this->logger = new NullLogger();
95 $this->profiler = new Profiler($config);
101 * @param IManageConfigValues $config
102 * @param Profiler $profiler
103 * @param LoggerInterface $logger
107 * @todo Make this method obsolete - use a clean pattern instead ...
109 public function setDependency(IManageConfigValues $config, Profiler $profiler, LoggerInterface $logger)
111 $this->logger = $logger;
112 $this->profiler = $profiler;
113 $this->config = $config;
117 * Tries to connect to database
119 * @return bool Success
121 public function connect(): bool
123 if (!is_null($this->connection) && $this->connected()) {
124 return $this->connected;
127 // Reset connected state
128 $this->connected = false;
131 $serveraddr = trim($this->config->get('database', 'hostname') ?? '');
132 $serverdata = explode(':', $serveraddr);
133 $host = trim($serverdata[0]);
134 if (count($serverdata) > 1) {
135 $port = trim($serverdata[1]);
138 if (trim($this->config->get('database', 'port') ?? 0)) {
139 $port = trim($this->config->get('database', 'port') ?? 0);
142 $user = trim($this->config->get('database', 'username'));
143 $pass = trim($this->config->get('database', 'password'));
144 $database = trim($this->config->get('database', 'database'));
145 $charset = trim($this->config->get('database', 'charset'));
146 $socket = trim($this->config->get('database', 'socket'));
148 if (!$host && !$socket || !$user) {
152 $persistent = (bool)$this->config->get('database', 'persistent');
154 $this->pdo_emulate_prepares = (bool)$this->config->get('database', 'pdo_emulate_prepares');
156 if (!$this->config->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
157 $this->driver = self::PDO;
159 $connect = 'mysql:unix_socket=' . $socket;
161 $connect = 'mysql:host=' . $host;
163 $connect .= ';port=' . $port;
168 $connect .= ';charset=' . $charset;
171 $connect .= ';dbname=' . $database;
174 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
175 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
176 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
177 $this->connected = true;
178 } catch (PDOException $e) {
179 $this->connected = false;
183 if (!$this->connected && class_exists('\mysqli')) {
184 $this->driver = self::MYSQLI;
187 $this->connection = @new mysqli(null, $user, $pass, $database, null, $socket);
188 } elseif ($port > 0) {
189 $this->connection = @new mysqli($host, $user, $pass, $database, $port);
191 $this->connection = @new mysqli($host, $user, $pass, $database);
194 if (!mysqli_connect_errno()) {
195 $this->connected = true;
198 $this->connection->set_charset($charset);
203 // No suitable SQL driver was found.
204 if (!$this->connected) {
206 $this->connection = null;
209 return $this->connected;
212 public function setTestmode(bool $test)
214 $this->testmode = $test;
218 * Sets the profiler for DBA
220 * @param Profiler $profiler
222 public function setProfiler(Profiler $profiler)
224 $this->profiler = $profiler;
228 * Disconnects the current database connection
230 public function disconnect()
232 if (!is_null($this->connection)) {
233 switch ($this->driver) {
235 $this->connection = null;
238 $this->connection->close();
239 $this->connection = null;
245 $this->connected = false;
249 * Perform a reconnect of an existing database connection
251 public function reconnect()
254 return $this->connect();
258 * Return the database object.
262 public function getConnection()
264 return $this->connection;
268 * Return the database driver string
270 * @return string with either "pdo" or "mysqli"
272 public function getDriver(): string
274 return $this->driver;
278 * Returns the MySQL server version string
280 * This function discriminate between the deprecated mysql API and the current
281 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
283 * @return string Database server information
285 public function serverInfo(): string
287 if ($this->server_info == '') {
288 switch ($this->driver) {
290 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
293 $this->server_info = $this->connection->server_info;
297 return $this->server_info;
301 * Returns the selected database name
303 * @return string Database name
306 public function databaseName(): string
308 $ret = $this->p("SELECT DATABASE() AS `db`");
309 $data = $this->toArray($ret);
310 return $data[0]['db'];
314 * Analyze a database query and log this if some conditions are met.
316 * @param string $query The database query that will be analyzed
320 private function logIndex(string $query)
323 if (!$this->config->get('system', 'db_log_index')) {
327 // Don't explain an explain statement
328 if (strtolower(substr($query, 0, 7)) == "explain") {
332 // Only do the explain on "select", "update" and "delete"
333 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
337 $r = $this->p("EXPLAIN " . $query);
338 if (!$this->isResult($r)) {
342 $watchlist = explode(',', $this->config->get('system', 'db_log_index_watch'));
343 $denylist = explode(',', $this->config->get('system', 'db_log_index_denylist'));
345 while ($row = $this->fetch($r)) {
346 if ((intval($this->config->get('system', 'db_loglimit_index')) > 0)) {
347 $log = (in_array($row['key'], $watchlist) &&
348 ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index'))));
353 if ((intval($this->config->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index_high')))) {
357 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
362 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
364 $this->config->get('system', 'db_log_index'),
365 DateTimeFormat::utcNow() . "\t" .
366 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
367 basename($backtrace[1]["file"]) . "\t" .
368 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
369 substr($query, 0, 4000) . "\n",
377 * Removes every not allowlisted character from the identifier string
379 * @param string $identifier
380 * @return string sanitized identifier
383 private function sanitizeIdentifier(string $identifier): string
385 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
388 public function escape($str)
390 if ($this->connected) {
391 switch ($this->driver) {
393 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
396 return @$this->connection->real_escape_string($str);
399 return str_replace("'", "\\'", $str);
404 * Returns connected flag
406 * @return bool Whether connection to database was success
408 public function isConnected(): bool
410 return $this->connected;
414 * Checks connection status
416 * @return bool Whether connection to database was success
418 public function connected()
422 if (is_null($this->connection)) {
426 switch ($this->driver) {
428 $r = $this->p("SELECT 1");
429 if ($this->isResult($r)) {
430 $row = $this->toArray($r);
431 $connected = ($row[0]['1'] == '1');
435 $connected = $this->connection->ping();
443 * Replaces ANY_VALUE() function by MIN() function,
444 * if the database server does not support ANY_VALUE().
446 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
447 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
448 * A standard fall-back is to use MIN().
450 * @param string $sql An SQL string without the values
452 * @return string The input SQL string modified if necessary.
454 public function anyValueFallback(string $sql): string
456 $server_info = $this->serverInfo();
457 if (version_compare($server_info, '5.7.5', '<') ||
458 (stripos($server_info, 'MariaDB') !== false)) {
459 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
465 * Replaces the ? placeholders with the parameters in the $args array
467 * @param string $sql SQL query
468 * @param array $args The parameters that are to replace the ? placeholders
470 * @return string The replaced SQL query
472 private function replaceParameters(string $sql, array $args): string
475 foreach ($args as $param => $value) {
476 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
477 $replace = intval($args[$param]);
478 } elseif (is_null($args[$param])) {
481 $replace = "'" . $this->escape($args[$param]) . "'";
484 $pos = strpos($sql, '?', $offset);
485 if ($pos !== false) {
486 $sql = substr_replace($sql, $replace, $pos, 1);
488 $offset = $pos + strlen($replace);
494 * Executes a prepared statement that returns data
496 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
498 * Please only use it with complicated queries.
499 * For all regular queries please use DBA::select or DBA::exists
501 * @param string $sql SQL statement
503 * @return bool|object statement object or result object
506 public function p(string $sql)
508 $this->currentTable = null;
509 $this->profiler->startRecording('database');
510 $stamp1 = microtime(true);
512 $params = DBA::getParam(func_get_args());
514 // Renumber the array keys to be sure that they fit
517 foreach ($params as $param) {
518 // Avoid problems with some MySQL servers and boolean values. See issue #3645
519 if (is_bool($param)) {
520 $param = (int)$param;
522 $args[++$i] = $param;
525 if (!$this->connected) {
529 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
530 // Question: Should we continue or stop the query here?
531 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args]);
534 $sql = DBA::cleanQuery($sql);
535 $sql = $this->anyValueFallback($sql);
539 if ($this->config->get('system', 'db_callstack') !== null) {
540 $sql = "/*" . System::callstack() . " */ " . $sql;
546 $this->affected_rows = 0;
548 // We have to make some things different if this function is called from "e"
549 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
551 if (isset($trace[1])) {
552 $called_from = $trace[1];
554 // We use just something that is defined to avoid warnings
555 $called_from = $trace[0];
557 // We are having an own error logging in the function "e"
558 $called_from_e = ($called_from['function'] == 'e');
560 if (!isset($this->connection)) {
561 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
564 switch ($this->driver) {
566 // If there are no arguments we use "query"
567 if (count($args) == 0) {
568 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
569 $errorInfo = $this->connection->errorInfo();
570 $this->error = (string)$errorInfo[2];
571 $this->errorno = (int)$errorInfo[1];
576 $this->affected_rows = $retval->rowCount();
580 /** @var $stmt mysqli_stmt|PDOStatement */
581 if (!$stmt = $this->connection->prepare($sql)) {
582 $errorInfo = $this->connection->errorInfo();
583 $this->error = (string)$errorInfo[2];
584 $this->errorno = (int)$errorInfo[1];
590 foreach (array_keys($args) as $param) {
591 $data_type = PDO::PARAM_STR;
592 if (is_int($args[$param])) {
593 $data_type = PDO::PARAM_INT;
594 } elseif ($args[$param] !== null) {
595 $args[$param] = (string)$args[$param];
598 $stmt->bindParam($param, $args[$param], $data_type);
601 if (!$stmt->execute()) {
602 $errorInfo = $stmt->errorInfo();
603 $this->error = (string)$errorInfo[2];
604 $this->errorno = (int)$errorInfo[1];
609 $this->affected_rows = $retval->rowCount();
613 // There are SQL statements that cannot be executed with a prepared statement
614 $parts = explode(' ', $orig_sql);
615 $command = strtolower($parts[0]);
616 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
618 // The fallback routine is called as well when there are no arguments
619 if (!$can_be_prepared || (count($args) == 0)) {
620 $retval = $this->connection->query($this->replaceParameters($sql, $args));
621 if ($this->connection->errno) {
622 $this->error = (string)$this->connection->error;
623 $this->errorno = (int)$this->connection->errno;
627 if (isset($retval->num_rows)) {
628 $this->affected_rows = $retval->num_rows;
630 $this->affected_rows = $this->connection->affected_rows;
636 $stmt = $this->connection->stmt_init();
638 if (!$stmt->prepare($sql)) {
639 $this->error = (string)$stmt->error;
640 $this->errorno = (int)$stmt->errno;
648 foreach (array_keys($args) as $param) {
649 if (is_int($args[$param])) {
651 } elseif (is_float($args[$param])) {
653 } elseif (is_string($args[$param])) {
655 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
657 $args[$param] = (string)$args[$param];
661 $values[] = &$args[$param];
664 if (count($values) > 0) {
665 array_unshift($values, $param_types);
666 call_user_func_array([$stmt, 'bind_param'], $values);
669 if (!$stmt->execute()) {
670 $this->error = (string)$this->connection->error;
671 $this->errorno = (int)$this->connection->errno;
675 $stmt->store_result();
677 $this->affected_rows = $retval->affected_rows;
682 // See issue https://github.com/friendica/friendica/issues/8572
683 // Ensure that we always get an error message on an error.
684 if ($is_error && empty($this->errorno)) {
688 if ($is_error && empty($this->error)) {
689 $this->error = 'Unknown database error';
692 // We are having an own error logging in the function "e"
693 if (($this->errorno != 0) && !$called_from_e) {
694 // We have to preserve the error code, somewhere in the logging it get lost
695 $error = $this->error;
696 $errorno = $this->errorno;
698 if ($this->testmode) {
699 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
702 $this->logger->error('DB Error', [
705 'params' => $this->replaceParameters($sql, $args),
708 // On a lost connection we try to reconnect - but only once.
709 if ($errorno == 2006) {
710 if ($this->in_retrial || !$this->reconnect()) {
711 // It doesn't make sense to continue when the database connection was lost
712 if ($this->in_retrial) {
713 $this->logger->notice('Giving up retrial because of database error', [
718 $this->logger->notice('Couldn\'t reconnect after database error', [
726 $this->logger->notice('Reconnected after database error', [
730 $this->in_retrial = true;
731 $ret = $this->p($sql, $args);
732 $this->in_retrial = false;
737 $this->error = (string)$error;
738 $this->errorno = (int)$errorno;
741 $this->profiler->stopRecording();
743 if ($this->config->get('system', 'db_log')) {
744 $stamp2 = microtime(true);
745 $duration = (float)($stamp2 - $stamp1);
747 if (($duration > $this->config->get('system', 'db_loglimit'))) {
748 $duration = round($duration, 3);
749 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
752 $this->config->get('system', 'db_log'),
753 DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
754 basename($backtrace[1]['file']) . "\t" .
755 $backtrace[1]['line'] . "\t" . $backtrace[2]['function'] . "\t" .
756 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n",
765 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
767 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
769 * @param string $sql SQL statement
771 * @return boolean Was the query successful? False is returned only if an error occurred
774 public function e(string $sql): bool
778 $this->profiler->startRecording('database_write');
780 $params = DBA::getParam(func_get_args());
782 // In a case of a deadlock we are repeating the query 20 times
786 $stmt = $this->p($sql, $params);
788 if (is_bool($stmt)) {
790 } elseif (is_object($stmt)) {
798 } while (($this->errorno == 1213) && (--$timeout > 0));
800 if ($this->errorno != 0) {
801 // We have to preserve the error code, somewhere in the logging it get lost
802 $error = $this->error;
803 $errorno = $this->errorno;
805 if ($this->testmode) {
806 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
809 $this->logger->error('DB Error', [
812 'params' => $this->replaceParameters($sql, $params),
815 // On a lost connection we simply quit.
816 // A reconnect like in $this->p could be dangerous with modifications
817 if ($errorno == 2006) {
818 $this->logger->notice('Giving up because of database error', [
825 $this->error = $error;
826 $this->errorno = $errorno;
829 $this->profiler->stopRecording();
835 * Check if data exists
837 * @param string $table Table name in format [schema.]table
838 * @param array $condition Array of fields for condition
840 * @return boolean Are there rows for that condition?
842 * @todo Please unwrap the DBStructure::existsTable() call so this method has one behavior only: checking existence on records
844 public function exists(string $table, array $condition): bool
852 if (empty($condition)) {
853 return DBStructure::existsTable($table);
857 $first_key = key($condition);
858 if (!is_int($first_key)) {
859 $fields = [$first_key];
862 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
864 if (is_bool($stmt)) {
867 $retval = ($this->numRows($stmt) > 0);
876 * Fetches the first row
878 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
880 * Fetches the first row
882 * @param string $sql SQL statement
884 * @return array|bool first row of query or false on failure
887 public function fetchFirst(string $sql)
889 $params = DBA::getParam(func_get_args());
891 $stmt = $this->p($sql, $params);
893 if (is_bool($stmt)) {
896 $retval = $this->fetch($stmt);
905 * Returns the number of affected rows of the last statement
907 * @return int Number of rows
909 public function affectedRows(): int
911 return $this->affected_rows;
915 * Returns the number of columns of a statement
917 * @param object Statement object
919 * @return int Number of columns
921 public function columnCount($stmt): int
923 if (!is_object($stmt)) {
926 switch ($this->driver) {
928 return $stmt->columnCount();
930 return $stmt->field_count;
936 * Returns the number of rows of a statement
938 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
940 * @return int Number of rows
942 public function numRows($stmt): int
944 if (!is_object($stmt)) {
947 switch ($this->driver) {
949 return $stmt->rowCount();
951 return $stmt->num_rows;
959 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
961 * @return array|bool Current row or false on failure
963 public function fetch($stmt)
965 $this->profiler->startRecording('database');
969 if (!is_object($stmt)) {
973 switch ($this->driver) {
975 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
976 if (!empty($this->currentTable) && is_array($columns)) {
977 $columns = $this->castFields($this->currentTable, $columns);
981 if (get_class($stmt) == 'mysqli_result') {
982 $columns = $stmt->fetch_assoc() ?? false;
986 // This code works, but is slow
988 // Bind the result to a result array
992 for ($x = 0; $x < $stmt->field_count; $x++) {
993 $cols[] = &$cols_num[$x];
996 call_user_func_array([$stmt, 'bind_result'], $cols);
998 if (!$stmt->fetch()) {
1003 // We need to get the field names for the array keys
1004 // It seems that there is no better way to do this.
1005 $result = $stmt->result_metadata();
1006 $fields = $result->fetch_fields();
1008 foreach ($cols_num as $param => $col) {
1009 $columns[$fields[$param]->name] = $col;
1013 $this->profiler->stopRecording();
1019 * Insert a row into a table. Field value objects will be cast as string.
1021 * @param string $table Table name in format [schema.]table
1022 * @param array $param parameter array
1023 * @param int $duplicate_mode What to do on a duplicated entry
1025 * @return boolean was the insert successful?
1026 * @throws \Exception
1028 public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1030 if (empty($table) || empty($param)) {
1031 $this->logger->info('Table and fields have to be set');
1035 $param = $this->castFields($table, $param);
1037 $table_string = DBA::buildTableString([$table]);
1039 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1041 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1045 if ($duplicate_mode == self::INSERT_IGNORE) {
1049 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1051 if ($duplicate_mode == self::INSERT_UPDATE) {
1052 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1054 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1056 $values = array_values($param);
1057 $param = array_merge_recursive($values, $values);
1060 $result = $this->e($sql, $param);
1061 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1065 return $this->affectedRows() != 0;
1069 * Inserts a row with the provided data in the provided table.
1070 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1072 * @param string $table Table name in format [schema.]table
1073 * @param array $param parameter array
1074 * @return boolean was the insert successful?
1075 * @throws \Exception
1077 public function replace(string $table, array $param): bool
1079 if (empty($table) || empty($param)) {
1080 $this->logger->info('Table and fields have to be set');
1084 $param = $this->castFields($table, $param);
1086 $table_string = DBA::buildTableString([$table]);
1088 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1090 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1092 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1094 return $this->e($sql, $param);
1098 * Fetch the id of the last insert command
1100 * @return integer Last inserted id
1102 public function lastInsertId(): int
1104 switch ($this->driver) {
1106 $id = $this->connection->lastInsertId();
1109 $id = $this->connection->insert_id;
1116 * Locks a table for exclusive write access
1118 * This function can be extended in the future to accept a table array as well.
1120 * @param string $table Table name in format [schema.]table
1121 * @return boolean was the lock successful?
1122 * @throws \Exception
1124 public function lock(string $table): bool
1126 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1127 if ($this->driver == self::PDO) {
1128 $this->e("SET autocommit=0");
1129 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1131 $this->connection->autocommit(false);
1134 $success = $this->e("LOCK TABLES " . DBA::buildTableString([$table]) . " WRITE");
1136 if ($this->driver == self::PDO) {
1137 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1141 if ($this->driver == self::PDO) {
1142 $this->e("SET autocommit=1");
1144 $this->connection->autocommit(true);
1147 $this->in_transaction = true;
1153 * Unlocks all locked tables
1155 * @return boolean was the unlock successful?
1156 * @throws \Exception
1158 public function unlock(): bool
1160 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1161 $this->performCommit();
1163 if ($this->driver == self::PDO) {
1164 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1167 $success = $this->e("UNLOCK TABLES");
1169 if ($this->driver == self::PDO) {
1170 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1171 $this->e("SET autocommit=1");
1173 $this->connection->autocommit(true);
1176 $this->in_transaction = false;
1181 * Starts a transaction
1183 * @return boolean Was the command executed successfully?
1185 public function transaction(): bool
1187 if (!$this->performCommit()) {
1191 switch ($this->driver) {
1193 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1199 if (!$this->connection->begin_transaction()) {
1205 $this->in_transaction = true;
1210 * Performs the commit
1212 * @return boolean Was the command executed successfully?
1214 protected function performCommit(): bool
1216 switch ($this->driver) {
1218 if (!$this->connection->inTransaction()) {
1222 return $this->connection->commit();
1225 return $this->connection->commit();
1234 * @return boolean Was the command executed successfully?
1236 public function commit(): bool
1238 if (!$this->performCommit()) {
1241 $this->in_transaction = false;
1248 * @return boolean Was the command executed successfully?
1250 public function rollback(): bool
1254 switch ($this->driver) {
1256 if (!$this->connection->inTransaction()) {
1260 $ret = $this->connection->rollBack();
1264 $ret = $this->connection->rollback();
1268 $this->in_transaction = false;
1273 * Delete a row from a table
1275 * @param string $table Table name
1276 * @param array $conditions Field condition(s)
1278 * @return boolean was the delete successful?
1279 * @throws \Exception
1281 public function delete(string $table, array $conditions): bool
1283 if (empty($table) || empty($conditions)) {
1284 $this->logger->info('Table and conditions have to be set');
1288 $table_string = DBA::buildTableString([$table]);
1290 $condition_string = DBA::buildCondition($conditions);
1292 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1293 $this->logger->debug($this->replaceParameters($sql, $conditions));
1294 return $this->e($sql, $conditions);
1298 * Updates rows in the database. Field value objects will be cast as string.
1300 * When $old_fields is set to an array,
1301 * the system will only do an update if the fields in that array changed.
1304 * Only the values in $old_fields are compared.
1305 * This is an intentional behaviour.
1308 * We include the timestamp field in $fields but not in $old_fields.
1309 * Then the row will only get the new timestamp when the other fields had changed.
1311 * When $old_fields is set to a boolean value the system will do this compare itself.
1312 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1315 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1316 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1318 * @param string $table Table name in format [schema.]table
1319 * @param array $fields contains the fields that are updated
1320 * @param array $condition condition array with the key values
1321 * @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)
1322 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1324 * @return boolean was the update successful?
1325 * @throws \Exception
1326 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1328 public function update(string $table, array $fields, array $condition, $old_fields = [], array $params = [])
1330 if (empty($table) || empty($fields) || empty($condition)) {
1331 $this->logger->info('Table, fields and condition have to be set');
1335 if (is_bool($old_fields)) {
1336 $do_insert = $old_fields;
1338 $old_fields = $this->selectFirst($table, [], $condition);
1340 if (is_bool($old_fields)) {
1342 $values = array_merge($condition, $fields);
1343 return $this->replace($table, $values);
1349 foreach ($old_fields as $fieldname => $content) {
1350 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1351 unset($fields[$fieldname]);
1355 if (count($fields) == 0) {
1359 $fields = $this->castFields($table, $fields);
1360 $direct_fields = [];
1362 foreach ($fields as $key => $value) {
1363 if (is_numeric($key)) {
1364 $direct_fields[] = $value;
1365 unset($fields[$key]);
1370 $table_string = DBA::buildTableString([$table]);
1372 $condition_string = DBA::buildCondition($condition);
1374 if (!empty($params['ignore'])) {
1375 $ignore = 'IGNORE ';
1380 $sql = "UPDATE " . $ignore . $table_string . " SET "
1381 . ((count($fields) > 0) ? implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?" : "")
1382 . ((count($direct_fields) > 0) ? ((count($fields) > 0) ? " , " : "") . implode(" , ", $direct_fields) : "")
1383 . $condition_string;
1385 // Combines the updated fields parameter values with the condition parameter values
1386 $params = array_merge(array_values($fields), $condition);
1388 return $this->e($sql, $params);
1392 * Retrieve a single record from a table and returns it in an associative array
1394 * @param string $table Table name in format [schema.]table
1395 * @param array $fields Array of selected fields, empty for all
1396 * @param array $condition Array of fields for condition
1397 * @param array $params Array of several parameters
1399 * @return bool|array
1400 * @throws \Exception
1401 * @see $this->select
1403 public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1405 $params['limit'] = 1;
1406 $result = $this->select($table, $fields, $condition, $params);
1408 if (is_bool($result)) {
1411 $row = $this->fetch($result);
1412 $this->close($result);
1418 * Select rows from a table and fills an array with the data
1420 * @param string $table Table name in format [schema.]table
1421 * @param array $fields Array of selected fields, empty for all
1422 * @param array $condition Array of fields for condition
1423 * @param array $params Array of several parameters
1424 * @return array Data array
1425 * @throws \Exception
1428 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1430 return $this->toArray($this->select($table, $fields, $condition, $params));
1434 * Escape fields, adding special treatment for "group by" handling
1436 * @param array $fields
1437 * @param array $options
1438 * @return array Escaped fields
1440 private function escapeFields(array $fields, array $options): array
1442 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1443 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1444 // Otherwise MySQL would report errors.
1445 if (!empty($options['group_by']) && !empty($options['order'])) {
1446 foreach ($options['order'] as $key => $field) {
1447 if (!is_int($key)) {
1448 if (!in_array($key, $fields)) {
1452 if (!in_array($field, $fields)) {
1459 array_walk($fields, function (&$value, $key) use ($options) {
1461 $value = DBA::quoteIdentifier($field);
1463 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1464 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1472 * Select rows from a table
1478 * $table = ['schema' => 'table'];
1479 * @see DBA::buildTableString()
1481 * $fields = ['id', 'uri', 'uid', 'network'];
1483 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1485 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1486 * @see DBA::buildCondition()
1488 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1489 * @see DBA::buildParameter()
1491 * $data = DBA::select($table, $fields, $condition, $params);
1493 * @param string $table Table name in format [schema.]table
1494 * @param array $fields Array of selected fields, empty for all
1495 * @param array $condition Array of fields for condition
1496 * @param array $params Array of several parameters
1497 * @return boolean|object
1498 * @throws \Exception
1500 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1502 if (empty($table)) {
1506 if (count($fields) > 0) {
1507 $fields = $this->escapeFields($fields, $params);
1508 $select_string = implode(', ', $fields);
1510 $select_string = '*';
1513 $table_string = DBA::buildTableString([$table]);
1515 $condition_string = DBA::buildCondition($condition);
1517 $param_string = DBA::buildParameter($params);
1519 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1521 $result = $this->p($sql, $condition);
1523 if ($this->driver == self::PDO && !empty($result)) {
1524 $this->currentTable = $table;
1531 * Counts the rows from a table satisfying the provided condition
1533 * @param string $table Table name in format [schema.]table
1534 * @param array $condition Array of fields for condition
1535 * @param array $params Array of several parameters
1537 * @return int Count of rows
1542 * $condition = ["uid" => 1, "network" => 'dspr'];
1544 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1546 * $count = DBA::count($table, $condition);
1547 * @throws \Exception
1549 public function count(string $table, array $condition = [], array $params = []): int
1551 if (empty($table)) {
1552 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1555 $table_string = DBA::buildTableString([$table]);
1557 $condition_string = DBA::buildCondition($condition);
1559 if (empty($params['expression'])) {
1561 } elseif (!empty($params['distinct'])) {
1562 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1564 $expression = DBA::quoteIdentifier($params['expression']);
1567 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1569 $row = $this->fetchFirst($sql, $condition);
1571 if (!isset($row['count'])) {
1572 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1575 return (int)$row['count'];
1580 * Fills an array with data from a query
1582 * @param object $stmt statement object
1583 * @param bool $do_close Close database connection after last row
1584 * @param int $count maximum number of rows to be fetched
1586 * @return array Data array
1588 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1590 if (is_bool($stmt)) {
1595 while ($row = $this->fetch($stmt)) {
1597 if (($count != 0) && (count($data) == $count)) {
1603 $this->close($stmt);
1610 * Cast field types according to the table definition
1612 * @param string $table
1613 * @param array $fields
1614 * @return array casted fields
1616 public function castFields(string $table, array $fields): array
1618 // When there is no data, we don't need to do something
1619 if (empty($fields)) {
1623 // We only need to cast fields with PDO
1624 if ($this->driver != self::PDO) {
1628 // We only need to cast when emulating the prepares
1629 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1635 $tables = $this->dbaDefinition->getAll();
1636 if (empty($tables[$table])) {
1637 // When a matching table wasn't found we check if it is a view
1638 $views = $this->viewDefinition->getAll();
1639 if (empty($views[$table])) {
1643 foreach (array_keys($fields) as $field) {
1644 if (!empty($views[$table]['fields'][$field])) {
1645 $viewdef = $views[$table]['fields'][$field];
1646 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1647 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1652 foreach ($tables[$table]['fields'] as $field => $definition) {
1653 $types[$field] = $definition['type'];
1657 foreach ($fields as $field => $content) {
1658 if (is_null($content) || empty($types[$field])) {
1662 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1663 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1664 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1665 $fields[$field] = (int)$content;
1667 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1668 $fields[$field] = (float)$content;
1676 * Returns the error number of the last query
1678 * @return string Error number (0 if no error)
1680 public function errorNo(): int
1682 return $this->errorno;
1686 * Returns the error message of the last query
1688 * @return string Error message ('' if no error)
1690 public function errorMessage(): string
1692 return $this->error;
1696 * Closes the current statement
1698 * @param object $stmt statement object
1700 * @return boolean was the close successful?
1702 public function close($stmt): bool
1705 $this->profiler->startRecording('database');
1707 if (!is_object($stmt)) {
1711 switch ($this->driver) {
1713 $ret = $stmt->closeCursor();
1716 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1717 // We should be careful not to assume the object type of $stmt
1718 // because DBA::p() has been able to return both types.
1719 if ($stmt instanceof mysqli_stmt) {
1720 $stmt->free_result();
1721 $ret = $stmt->close();
1722 } elseif ($stmt instanceof mysqli_result) {
1731 $this->profiler->stopRecording();
1737 * Return a list of database processes
1740 * 'list' => List of processes, separated in their different states
1741 * 'amount' => Number of concurrent database processes
1742 * @throws \Exception
1744 public function processlist(): array
1746 $ret = $this->p('SHOW PROCESSLIST');
1747 $data = $this->toArray($ret);
1751 foreach ($data as $process) {
1752 $state = trim($process['State']);
1754 // Filter out all non blocking processes
1755 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1762 foreach ($states as $state => $usage) {
1763 if ($statelist != '') {
1766 $statelist .= $state . ': ' . $usage;
1768 return (['list' => $statelist, 'amount' => $processes]);
1774 * @param string $table a given table
1776 * @return bool True, if successfully optimized, otherwise false
1777 * @throws \Exception
1779 public function optimizeTable(string $table): bool
1781 return $this->e("OPTIMIZE TABLE " . DBA::buildTableString([$table])) !== false;
1785 * Kill sleeping database processes
1789 public function deleteSleepingProcesses()
1791 $processes = $this->p("SHOW FULL PROCESSLIST");
1792 while ($process = $this->fetch($processes)) {
1793 if (($process['Command'] != 'Sleep') || ($process['Time'] < 300) || ($process['db'] != $this->databaseName())) {
1797 $this->e("KILL ?", $process['Id']);
1799 $this->close($processes);
1803 * Fetch a database variable
1805 * @param string $name
1806 * @return string|null content or null if inexistent
1807 * @throws \Exception
1809 public function getVariable(string $name)
1811 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1812 return $result['Value'] ?? null;
1816 * Checks if $array is a filled array with at least one entry.
1818 * @param mixed $array A filled array with at least one entry
1819 * @return boolean Whether $array is a filled array or an object with rows
1821 public function isResult($array): bool
1823 // It could be a return value from an update statement
1824 if (is_bool($array)) {
1828 if (is_object($array)) {
1829 return $this->numRows($array) > 0;
1832 return (is_array($array) && (count($array) > 0));
1836 * Callback function for "esc_array"
1838 * @param mixed $value Array value
1839 * @param string $key Array key
1840 * @param boolean $add_quotation add quotation marks for string values
1843 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1845 if (!$add_quotation) {
1846 if (is_bool($value)) {
1847 $value = ($value ? '1' : '0');
1849 $value = $this->escape($value);
1854 if (is_bool($value)) {
1855 $value = ($value ? 'true' : 'false');
1856 } elseif (is_float($value) || is_integer($value)) {
1857 $value = (string)$value;
1859 $value = "'" . $this->escape($value) . "'";
1864 * Escapes a whole array
1866 * @param mixed $arr Array with values to be escaped
1867 * @param boolean $add_quotation add quotation marks for string values
1870 public function escapeArray(&$arr, bool $add_quotation = false)
1872 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1876 * Replaces a string in the provided fields of the provided table
1878 * @param string $table Table name
1879 * @param array $fields List of field names in the provided table
1880 * @param string $search String to search for
1881 * @param string $replace String to replace with
1883 * @throws \Exception
1885 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1887 $search = $this->escape($search);
1888 $replace = $this->escape($replace);
1891 foreach ($fields as $field) {
1892 $field = DBA::quoteIdentifier($field);
1893 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1896 $upds = implode(', ', $upd);
1898 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1900 if (!$this->isResult($r)) {
1901 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());