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;
84 public function __construct(IManageConfigValues $config, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition)
86 // We are storing these values for being able to perform a reconnect
87 $this->config = $config;
88 $this->dbaDefinition = $dbaDefinition;
89 $this->viewDefinition = $viewDefinition;
91 // Use dummy values - necessary for the first factory call of the logger itself
92 $this->logger = new NullLogger();
93 $this->profiler = new Profiler($config);
99 * @param IManageConfigValues $config
100 * @param Profiler $profiler
101 * @param LoggerInterface $logger
105 * @todo Make this method obsolet - use a clean pattern instead ...
107 public function setDependency(IManageConfigValues $config, Profiler $profiler, LoggerInterface $logger)
109 $this->logger = $logger;
110 $this->profiler = $profiler;
111 $this->config = $config;
115 * Tries to connect to database
117 * @return bool Success
119 public function connect(): bool
121 if (!is_null($this->connection) && $this->connected()) {
122 return $this->connected;
125 // Reset connected state
126 $this->connected = false;
129 $serveraddr = trim($this->config->get('database', 'hostname') ?? '');
130 $serverdata = explode(':', $serveraddr);
131 $host = trim($serverdata[0]);
132 if (count($serverdata) > 1) {
133 $port = trim($serverdata[1]);
136 if (trim($this->config->get('database', 'port') ?? 0)) {
137 $port = trim($this->config->get('database', 'port') ?? 0);
140 $user = trim($this->config->get('database', 'username'));
141 $pass = trim($this->config->get('database', 'password'));
142 $database = trim($this->config->get('database', 'database'));
143 $charset = trim($this->config->get('database', 'charset'));
144 $socket = trim($this->config->get('database', 'socket'));
146 if (!$host && !$socket || !$user) {
150 $persistent = (bool)$this->config->get('database', 'persistent');
152 $this->pdo_emulate_prepares = (bool)$this->config->get('database', 'pdo_emulate_prepares');
154 if (!$this->config->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
155 $this->driver = self::PDO;
157 $connect = 'mysql:unix_socket=' . $socket;
159 $connect = 'mysql:host=' . $host;
161 $connect .= ';port=' . $port;
166 $connect .= ';charset=' . $charset;
169 $connect .= ';dbname=' . $database;
172 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
173 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
174 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
175 $this->connected = true;
176 } catch (PDOException $e) {
177 $this->connected = false;
181 if (!$this->connected && class_exists('\mysqli')) {
182 $this->driver = self::MYSQLI;
185 $this->connection = @new mysqli(null, $user, $pass, $database, null, $socket);
186 } elseif ($port > 0) {
187 $this->connection = @new mysqli($host, $user, $pass, $database, $port);
189 $this->connection = @new mysqli($host, $user, $pass, $database);
192 if (!mysqli_connect_errno()) {
193 $this->connected = true;
196 $this->connection->set_charset($charset);
201 // No suitable SQL driver was found.
202 if (!$this->connected) {
204 $this->connection = null;
207 return $this->connected;
210 public function setTestmode(bool $test)
212 $this->testmode = $test;
216 * Sets the profiler for DBA
218 * @param Profiler $profiler
220 public function setProfiler(Profiler $profiler)
222 $this->profiler = $profiler;
226 * Disconnects the current database connection
228 public function disconnect()
230 if (!is_null($this->connection)) {
231 switch ($this->driver) {
233 $this->connection = null;
236 $this->connection->close();
237 $this->connection = null;
243 $this->connected = false;
247 * Perform a reconnect of an existing database connection
249 public function reconnect()
252 return $this->connect();
256 * Return the database object.
260 public function getConnection()
262 return $this->connection;
266 * Return the database driver string
268 * @return string with either "pdo" or "mysqli"
270 public function getDriver(): string
272 return $this->driver;
276 * Returns the MySQL server version string
278 * This function discriminate between the deprecated mysql API and the current
279 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
281 * @return string Database server information
283 public function serverInfo(): string
285 if ($this->server_info == '') {
286 switch ($this->driver) {
288 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
291 $this->server_info = $this->connection->server_info;
295 return $this->server_info;
299 * Returns the selected database name
301 * @return string Database name
304 public function databaseName(): string
306 $ret = $this->p("SELECT DATABASE() AS `db`");
307 $data = $this->toArray($ret);
308 return $data[0]['db'];
312 * Analyze a database query and log this if some conditions are met.
314 * @param string $query The database query that will be analyzed
318 private function logIndex(string $query)
321 if (!$this->config->get('system', 'db_log_index')) {
325 // Don't explain an explain statement
326 if (strtolower(substr($query, 0, 7)) == "explain") {
330 // Only do the explain on "select", "update" and "delete"
331 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
335 $r = $this->p("EXPLAIN " . $query);
336 if (!$this->isResult($r)) {
340 $watchlist = explode(',', $this->config->get('system', 'db_log_index_watch'));
341 $denylist = explode(',', $this->config->get('system', 'db_log_index_denylist'));
343 while ($row = $this->fetch($r)) {
344 if ((intval($this->config->get('system', 'db_loglimit_index')) > 0)) {
345 $log = (in_array($row['key'], $watchlist) &&
346 ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index'))));
351 if ((intval($this->config->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->config->get('system', 'db_loglimit_index_high')))) {
355 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
360 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
362 $this->config->get('system', 'db_log_index'),
363 DateTimeFormat::utcNow() . "\t" .
364 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
365 basename($backtrace[1]["file"]) . "\t" .
366 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
367 substr($query, 0, 4000) . "\n",
375 * Removes every not allowlisted character from the identifier string
377 * @param string $identifier
378 * @return string sanitized identifier
381 private function sanitizeIdentifier(string $identifier): string
383 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
386 public function escape($str)
388 if ($this->connected) {
389 switch ($this->driver) {
391 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
394 return @$this->connection->real_escape_string($str);
397 return str_replace("'", "\\'", $str);
402 * Returns connected flag
404 * @return bool Whether connection to database was success
406 public function isConnected(): bool
408 return $this->connected;
412 * Checks connection status
414 * @return bool Whether connection to database was success
416 public function connected()
420 if (is_null($this->connection)) {
424 switch ($this->driver) {
426 $r = $this->p("SELECT 1");
427 if ($this->isResult($r)) {
428 $row = $this->toArray($r);
429 $connected = ($row[0]['1'] == '1');
433 $connected = $this->connection->ping();
441 * Replaces ANY_VALUE() function by MIN() function,
442 * if the database server does not support ANY_VALUE().
444 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
445 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
446 * A standard fall-back is to use MIN().
448 * @param string $sql An SQL string without the values
450 * @return string The input SQL string modified if necessary.
452 public function anyValueFallback(string $sql): string
454 $server_info = $this->serverInfo();
455 if (version_compare($server_info, '5.7.5', '<') ||
456 (stripos($server_info, 'MariaDB') !== false)) {
457 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
463 * Replaces the ? placeholders with the parameters in the $args array
465 * @param string $sql SQL query
466 * @param array $args The parameters that are to replace the ? placeholders
468 * @return string The replaced SQL query
470 private function replaceParameters(string $sql, array $args): string
473 foreach ($args as $param => $value) {
474 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
475 $replace = intval($args[$param]);
476 } elseif (is_null($args[$param])) {
479 $replace = "'" . $this->escape($args[$param]) . "'";
482 $pos = strpos($sql, '?', $offset);
483 if ($pos !== false) {
484 $sql = substr_replace($sql, $replace, $pos, 1);
486 $offset = $pos + strlen($replace);
492 * Executes a prepared statement that returns data
494 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
496 * Please only use it with complicated queries.
497 * For all regular queries please use DBA::select or DBA::exists
499 * @param string $sql SQL statement
501 * @return bool|object statement object or result object
504 public function p(string $sql)
507 $this->profiler->startRecording('database');
508 $stamp1 = microtime(true);
510 $params = DBA::getParam(func_get_args());
512 // Renumber the array keys to be sure that they fit
515 foreach ($params as $param) {
516 // Avoid problems with some MySQL servers and boolean values. See issue #3645
517 if (is_bool($param)) {
518 $param = (int)$param;
520 $args[++$i] = $param;
523 if (!$this->connected) {
527 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
528 // Question: Should we continue or stop the query here?
529 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
532 $sql = DBA::cleanQuery($sql);
533 $sql = $this->anyValueFallback($sql);
537 if ($this->config->get('system', 'db_callstack') !== null) {
538 $sql = "/*" . System::callstack() . " */ " . $sql;
544 $this->affected_rows = 0;
546 // We have to make some things different if this function is called from "e"
547 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
549 if (isset($trace[1])) {
550 $called_from = $trace[1];
552 // We use just something that is defined to avoid warnings
553 $called_from = $trace[0];
555 // We are having an own error logging in the function "e"
556 $called_from_e = ($called_from['function'] == 'e');
558 if (!isset($this->connection)) {
559 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
562 switch ($this->driver) {
564 // If there are no arguments we use "query"
565 if (count($args) == 0) {
566 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
567 $errorInfo = $this->connection->errorInfo();
568 $this->error = (string)$errorInfo[2];
569 $this->errorno = (int)$errorInfo[1];
574 $this->affected_rows = $retval->rowCount();
578 /** @var $stmt mysqli_stmt|PDOStatement */
579 if (!$stmt = $this->connection->prepare($sql)) {
580 $errorInfo = $this->connection->errorInfo();
581 $this->error = (string)$errorInfo[2];
582 $this->errorno = (int)$errorInfo[1];
588 foreach (array_keys($args) as $param) {
589 $data_type = PDO::PARAM_STR;
590 if (is_int($args[$param])) {
591 $data_type = PDO::PARAM_INT;
592 } elseif ($args[$param] !== null) {
593 $args[$param] = (string)$args[$param];
596 $stmt->bindParam($param, $args[$param], $data_type);
599 if (!$stmt->execute()) {
600 $errorInfo = $stmt->errorInfo();
601 $this->error = (string)$errorInfo[2];
602 $this->errorno = (int)$errorInfo[1];
607 $this->affected_rows = $retval->rowCount();
611 // There are SQL statements that cannot be executed with a prepared statement
612 $parts = explode(' ', $orig_sql);
613 $command = strtolower($parts[0]);
614 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
616 // The fallback routine is called as well when there are no arguments
617 if (!$can_be_prepared || (count($args) == 0)) {
618 $retval = $this->connection->query($this->replaceParameters($sql, $args));
619 if ($this->connection->errno) {
620 $this->error = (string)$this->connection->error;
621 $this->errorno = (int)$this->connection->errno;
625 if (isset($retval->num_rows)) {
626 $this->affected_rows = $retval->num_rows;
628 $this->affected_rows = $this->connection->affected_rows;
634 $stmt = $this->connection->stmt_init();
636 if (!$stmt->prepare($sql)) {
637 $this->error = (string)$stmt->error;
638 $this->errorno = (int)$stmt->errno;
646 foreach (array_keys($args) as $param) {
647 if (is_int($args[$param])) {
649 } elseif (is_float($args[$param])) {
651 } elseif (is_string($args[$param])) {
653 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
655 $args[$param] = (string)$args[$param];
659 $values[] = &$args[$param];
662 if (count($values) > 0) {
663 array_unshift($values, $param_types);
664 call_user_func_array([$stmt, 'bind_param'], $values);
667 if (!$stmt->execute()) {
668 $this->error = (string)$this->connection->error;
669 $this->errorno = (int)$this->connection->errno;
673 $stmt->store_result();
675 $this->affected_rows = $retval->affected_rows;
680 // See issue https://github.com/friendica/friendica/issues/8572
681 // Ensure that we always get an error message on an error.
682 if ($is_error && empty($this->errorno)) {
686 if ($is_error && empty($this->error)) {
687 $this->error = 'Unknown database error';
690 // We are having an own error logging in the function "e"
691 if (($this->errorno != 0) && !$called_from_e) {
692 // We have to preserve the error code, somewhere in the logging it get lost
693 $error = $this->error;
694 $errorno = $this->errorno;
696 if ($this->testmode) {
697 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
700 $this->logger->error('DB Error', [
703 'callstack' => System::callstack(8),
704 'params' => $this->replaceParameters($sql, $args),
707 // On a lost connection we try to reconnect - but only once.
708 if ($errorno == 2006) {
709 if ($this->in_retrial || !$this->reconnect()) {
710 // It doesn't make sense to continue when the database connection was lost
711 if ($this->in_retrial) {
712 $this->logger->notice('Giving up retrial because of database error', [
717 $this->logger->notice('Couldn\'t reconnect after database error', [
725 $this->logger->notice('Reconnected after database error', [
729 $this->in_retrial = true;
730 $ret = $this->p($sql, $args);
731 $this->in_retrial = false;
736 $this->error = (string)$error;
737 $this->errorno = (int)$errorno;
740 $this->profiler->stopRecording();
742 if ($this->config->get('system', 'db_log')) {
743 $stamp2 = microtime(true);
744 $duration = (float)($stamp2 - $stamp1);
746 if (($duration > $this->config->get('system', 'db_loglimit'))) {
747 $duration = round($duration, 3);
748 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
751 $this->config->get('system', 'db_log'),
752 DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
753 basename($backtrace[1]["file"]) . "\t" .
754 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
755 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n",
764 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
766 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
768 * @param string $sql SQL statement
770 * @return boolean Was the query successfull? False is returned only if an error occurred
773 public function e(string $sql): bool
777 $this->profiler->startRecording('database_write');
779 $params = DBA::getParam(func_get_args());
781 // In a case of a deadlock we are repeating the query 20 times
785 $stmt = $this->p($sql, $params);
787 if (is_bool($stmt)) {
789 } elseif (is_object($stmt)) {
797 } while (($this->errorno == 1213) && (--$timeout > 0));
799 if ($this->errorno != 0) {
800 // We have to preserve the error code, somewhere in the logging it get lost
801 $error = $this->error;
802 $errorno = $this->errorno;
804 if ($this->testmode) {
805 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
808 $this->logger->error('DB Error', [
811 'callstack' => System::callstack(8),
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($stmt->table) && is_array($columns)) {
977 $columns = $this->castFields($stmt->table, $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), ['callstack' => System::callstack(6)]);
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 successfull?
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);
1361 $table_string = DBA::buildTableString([$table]);
1363 $condition_string = DBA::buildCondition($condition);
1365 if (!empty($params['ignore'])) {
1366 $ignore = 'IGNORE ';
1371 $sql = "UPDATE " . $ignore . $table_string . " SET "
1372 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1373 . $condition_string;
1375 // Combines the updated fields parameter values with the condition parameter values
1376 $params = array_merge(array_values($fields), $condition);
1378 return $this->e($sql, $params);
1382 * Retrieve a single record from a table and returns it in an associative array
1384 * @param string $table Table name in format [schema.]table
1385 * @param array $fields Array of selected fields, empty for all
1386 * @param array $condition Array of fields for condition
1387 * @param array $params Array of several parameters
1389 * @return bool|array
1390 * @throws \Exception
1391 * @see $this->select
1393 public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1395 $params['limit'] = 1;
1396 $result = $this->select($table, $fields, $condition, $params);
1398 if (is_bool($result)) {
1401 $row = $this->fetch($result);
1402 $this->close($result);
1408 * Select rows from a table and fills an array with the data
1410 * @param string $table Table name in format [schema.]table
1411 * @param array $fields Array of selected fields, empty for all
1412 * @param array $condition Array of fields for condition
1413 * @param array $params Array of several parameters
1414 * @return array Data array
1415 * @throws \Exception
1418 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1420 return $this->toArray($this->select($table, $fields, $condition, $params));
1424 * Escape fields, adding special treatment for "group by" handling
1426 * @param array $fields
1427 * @param array $options
1428 * @return array Escaped fields
1430 private function escapeFields(array $fields, array $options): array
1432 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1433 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1434 // Otherwise MySQL would report errors.
1435 if (!empty($options['group_by']) && !empty($options['order'])) {
1436 foreach ($options['order'] as $key => $field) {
1437 if (!is_int($key)) {
1438 if (!in_array($key, $fields)) {
1442 if (!in_array($field, $fields)) {
1449 array_walk($fields, function (&$value, $key) use ($options) {
1451 $value = DBA::quoteIdentifier($field);
1453 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1454 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1462 * Select rows from a table
1468 * $table = ['schema' => 'table'];
1469 * @see DBA::buildTableString()
1471 * $fields = ['id', 'uri', 'uid', 'network'];
1473 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1475 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1476 * @see DBA::buildCondition()
1478 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1479 * @see DBA::buildParameter()
1481 * $data = DBA::select($table, $fields, $condition, $params);
1483 * @param string $table Table name in format [schema.]table
1484 * @param array $fields Array of selected fields, empty for all
1485 * @param array $condition Array of fields for condition
1486 * @param array $params Array of several parameters
1487 * @return boolean|object
1488 * @throws \Exception
1490 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1492 if (empty($table)) {
1496 if (count($fields) > 0) {
1497 $fields = $this->escapeFields($fields, $params);
1498 $select_string = implode(', ', $fields);
1500 $select_string = '*';
1503 $table_string = DBA::buildTableString([$table]);
1505 $condition_string = DBA::buildCondition($condition);
1507 $param_string = DBA::buildParameter($params);
1509 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1511 $result = $this->p($sql, $condition);
1513 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1514 $result->table = $table;
1521 * Counts the rows from a table satisfying the provided condition
1523 * @param string $table Table name in format [schema.]table
1524 * @param array $condition Array of fields for condition
1525 * @param array $params Array of several parameters
1527 * @return int Count of rows
1532 * $condition = ["uid" => 1, "network" => 'dspr'];
1534 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1536 * $count = DBA::count($table, $condition);
1537 * @throws \Exception
1539 public function count(string $table, array $condition = [], array $params = []): int
1541 if (empty($table)) {
1542 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1545 $table_string = DBA::buildTableString([$table]);
1547 $condition_string = DBA::buildCondition($condition);
1549 if (empty($params['expression'])) {
1551 } elseif (!empty($params['distinct'])) {
1552 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1554 $expression = DBA::quoteIdentifier($params['expression']);
1557 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1559 $row = $this->fetchFirst($sql, $condition);
1561 if (!isset($row['count'])) {
1562 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1565 return (int)$row['count'];
1570 * Fills an array with data from a query
1572 * @param object $stmt statement object
1573 * @param bool $do_close Close database connection after last row
1574 * @param int $count maximum number of rows to be fetched
1576 * @return array Data array
1578 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1580 if (is_bool($stmt)) {
1585 while ($row = $this->fetch($stmt)) {
1587 if (($count != 0) && (count($data) == $count)) {
1593 $this->close($stmt);
1600 * Cast field types according to the table definition
1602 * @param string $table
1603 * @param array $fields
1604 * @return array casted fields
1606 public function castFields(string $table, array $fields): array
1608 // When there is no data, we don't need to do something
1609 if (empty($fields)) {
1613 // We only need to cast fields with PDO
1614 if ($this->driver != self::PDO) {
1618 // We only need to cast when emulating the prepares
1619 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1625 $tables = $this->dbaDefinition->getAll();
1626 if (empty($tables[$table])) {
1627 // When a matching table wasn't found we check if it is a view
1628 $views = $this->viewDefinition->getAll();
1629 if (empty($views[$table])) {
1633 foreach (array_keys($fields) as $field) {
1634 if (!empty($views[$table]['fields'][$field])) {
1635 $viewdef = $views[$table]['fields'][$field];
1636 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1637 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1642 foreach ($tables[$table]['fields'] as $field => $definition) {
1643 $types[$field] = $definition['type'];
1647 foreach ($fields as $field => $content) {
1648 if (is_null($content) || empty($types[$field])) {
1652 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1653 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1654 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1655 $fields[$field] = (int)$content;
1657 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1658 $fields[$field] = (float)$content;
1666 * Returns the error number of the last query
1668 * @return string Error number (0 if no error)
1670 public function errorNo(): int
1672 return $this->errorno;
1676 * Returns the error message of the last query
1678 * @return string Error message ('' if no error)
1680 public function errorMessage(): string
1682 return $this->error;
1686 * Closes the current statement
1688 * @param object $stmt statement object
1690 * @return boolean was the close successful?
1692 public function close($stmt): bool
1695 $this->profiler->startRecording('database');
1697 if (!is_object($stmt)) {
1701 switch ($this->driver) {
1703 $ret = $stmt->closeCursor();
1706 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1707 // We should be careful not to assume the object type of $stmt
1708 // because DBA::p() has been able to return both types.
1709 if ($stmt instanceof mysqli_stmt) {
1710 $stmt->free_result();
1711 $ret = $stmt->close();
1712 } elseif ($stmt instanceof mysqli_result) {
1721 $this->profiler->stopRecording();
1727 * Return a list of database processes
1730 * 'list' => List of processes, separated in their different states
1731 * 'amount' => Number of concurrent database processes
1732 * @throws \Exception
1734 public function processlist(): array
1736 $ret = $this->p('SHOW PROCESSLIST');
1737 $data = $this->toArray($ret);
1741 foreach ($data as $process) {
1742 $state = trim($process['State']);
1744 // Filter out all non blocking processes
1745 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1752 foreach ($states as $state => $usage) {
1753 if ($statelist != '') {
1756 $statelist .= $state . ': ' . $usage;
1758 return (['list' => $statelist, 'amount' => $processes]);
1762 * Fetch a database variable
1764 * @param string $name
1765 * @return string|null content or null if inexistent
1766 * @throws \Exception
1768 public function getVariable(string $name)
1770 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1771 return $result['Value'] ?? null;
1775 * Checks if $array is a filled array with at least one entry.
1777 * @param mixed $array A filled array with at least one entry
1778 * @return boolean Whether $array is a filled array or an object with rows
1780 public function isResult($array): bool
1782 // It could be a return value from an update statement
1783 if (is_bool($array)) {
1787 if (is_object($array)) {
1788 return $this->numRows($array) > 0;
1791 return (is_array($array) && (count($array) > 0));
1795 * Callback function for "esc_array"
1797 * @param mixed $value Array value
1798 * @param string $key Array key
1799 * @param boolean $add_quotation add quotation marks for string values
1802 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1804 if (!$add_quotation) {
1805 if (is_bool($value)) {
1806 $value = ($value ? '1' : '0');
1808 $value = $this->escape($value);
1813 if (is_bool($value)) {
1814 $value = ($value ? 'true' : 'false');
1815 } elseif (is_float($value) || is_integer($value)) {
1816 $value = (string)$value;
1818 $value = "'" . $this->escape($value) . "'";
1823 * Escapes a whole array
1825 * @param mixed $arr Array with values to be escaped
1826 * @param boolean $add_quotation add quotation marks for string values
1829 public function escapeArray(&$arr, bool $add_quotation = false)
1831 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1835 * Replaces a string in the provided fields of the provided table
1837 * @param string $table Table name
1838 * @param array $fields List of field names in the provided table
1839 * @param string $search String to search for
1840 * @param string $replace String to replace with
1842 * @throws \Exception
1844 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1846 $search = $this->escape($search);
1847 $replace = $this->escape($replace);
1850 foreach ($fields as $field) {
1851 $field = DBA::quoteIdentifier($field);
1852 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1855 $upds = implode(', ', $upd);
1857 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1859 if (!$this->isResult($r)) {
1860 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());