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\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 \Friendica\Core\Config\ValueObject\Cache
58 protected $configCache;
64 * @var LoggerInterface
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(Cache $configCache, Profiler $profiler, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition)
86 // We are storing these values for being able to perform a reconnect
87 $this->configCache = $configCache;
88 $this->profiler = $profiler;
89 $this->dbaDefinition = $dbaDefinition;
90 $this->viewDefinition = $viewDefinition;
92 // Temporary NullLogger until we can fetch the logger class from the config
93 $this->logger = new NullLogger();
99 * Tries to connect to database
101 * @return bool Success
103 public function connect(): bool
105 if (!is_null($this->connection) && $this->connected()) {
106 return $this->connected;
109 // Reset connected state
110 $this->connected = false;
113 $serveraddr = trim($this->configCache->get('database', 'hostname'));
114 $serverdata = explode(':', $serveraddr);
115 $server = $serverdata[0];
116 if (count($serverdata) > 1) {
117 $port = trim($serverdata[1]);
120 if (!empty(trim($this->configCache->get('database', 'port')))) {
121 $port = trim($this->configCache->get('database', 'port'));
124 $server = trim($server);
125 $user = trim($this->configCache->get('database', 'username'));
126 $pass = trim($this->configCache->get('database', 'password'));
127 $db = trim($this->configCache->get('database', 'database'));
128 $charset = trim($this->configCache->get('database', 'charset'));
129 $socket = trim($this->configCache->get('database', 'socket'));
131 if (!(strlen($server) && strlen($user))) {
135 $persistent = (bool)$this->configCache->get('database', 'persistent');
137 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
139 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
140 $this->driver = self::PDO;
141 $connect = "mysql:host=" . $server . ";dbname=" . $db;
144 $connect .= ";port=" . $port;
148 $connect .= ";charset=" . $charset;
152 $connect .= ";$unix_socket=" . $socket;
156 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
157 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
158 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
159 $this->connected = true;
160 } catch (PDOException $e) {
161 $this->connected = false;
165 if (!$this->connected && class_exists('\mysqli')) {
166 $this->driver = self::MYSQLI;
169 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
171 $this->connection = @new mysqli($server, $user, $pass, $db);
174 if (!mysqli_connect_errno()) {
175 $this->connected = true;
178 $this->connection->set_charset($charset);
182 $this->connection->set_socket($socket);
188 // No suitable SQL driver was found.
189 if (!$this->connected) {
191 $this->connection = null;
194 return $this->connected;
197 public function setTestmode(bool $test)
199 $this->testmode = $test;
202 * Sets the logger for DBA
204 * @note this is necessary because if we want to load the logger configuration
205 * from the DB, but there's an error, we would print out an exception.
206 * So the logger gets updated after the logger configuration can be retrieved
209 * @param LoggerInterface $logger
211 public function setLogger(LoggerInterface $logger)
213 $this->logger = $logger;
217 * Sets the profiler for DBA
219 * @param Profiler $profiler
221 public function setProfiler(Profiler $profiler)
223 $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->configCache->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->configCache->get('system', 'db_log_index_watch'));
341 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
343 while ($row = $this->fetch($r)) {
344 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
345 $log = (in_array($row['key'], $watchlist) &&
346 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
351 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
355 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
360 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
361 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
362 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
363 basename($backtrace[1]["file"]) . "\t" .
364 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
365 substr($query, 0, 4000) . "\n", FILE_APPEND);
371 * Removes every not allowlisted character from the identifier string
373 * @param string $identifier
374 * @return string sanitized identifier
377 private function sanitizeIdentifier(string $identifier): string
379 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
382 public function escape($str)
384 if ($this->connected) {
385 switch ($this->driver) {
387 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
390 return @$this->connection->real_escape_string($str);
393 return str_replace("'", "\\'", $str);
398 * Returns connected flag
400 * @return bool Whether connection to database was success
402 public function isConnected(): bool
404 return $this->connected;
408 * Checks connection status
410 * @return bool Whether connection to database was success
412 public function connected()
416 if (is_null($this->connection)) {
420 switch ($this->driver) {
422 $r = $this->p("SELECT 1");
423 if ($this->isResult($r)) {
424 $row = $this->toArray($r);
425 $connected = ($row[0]['1'] == '1');
429 $connected = $this->connection->ping();
437 * Replaces ANY_VALUE() function by MIN() function,
438 * if the database server does not support ANY_VALUE().
440 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
441 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
442 * A standard fall-back is to use MIN().
444 * @param string $sql An SQL string without the values
446 * @return string The input SQL string modified if necessary.
448 public function anyValueFallback(string $sql): string
450 $server_info = $this->serverInfo();
451 if (version_compare($server_info, '5.7.5', '<') ||
452 (stripos($server_info, 'MariaDB') !== false)) {
453 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
459 * Replaces the ? placeholders with the parameters in the $args array
461 * @param string $sql SQL query
462 * @param array $args The parameters that are to replace the ? placeholders
464 * @return string The replaced SQL query
466 private function replaceParameters(string $sql, array $args): string
469 foreach ($args as $param => $value) {
470 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
471 $replace = intval($args[$param]);
472 } elseif (is_null($args[$param])) {
475 $replace = "'" . $this->escape($args[$param]) . "'";
478 $pos = strpos($sql, '?', $offset);
479 if ($pos !== false) {
480 $sql = substr_replace($sql, $replace, $pos, 1);
482 $offset = $pos + strlen($replace);
488 * Executes a prepared statement that returns data
490 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
492 * Please only use it with complicated queries.
493 * For all regular queries please use DBA::select or DBA::exists
495 * @param string $sql SQL statement
497 * @return bool|object statement object or result object
500 public function p(string $sql)
503 $this->profiler->startRecording('database');
504 $stamp1 = microtime(true);
506 $params = DBA::getParam(func_get_args());
508 // Renumber the array keys to be sure that they fit
511 foreach ($params as $param) {
512 // Avoid problems with some MySQL servers and boolean values. See issue #3645
513 if (is_bool($param)) {
514 $param = (int)$param;
516 $args[++$i] = $param;
519 if (!$this->connected) {
523 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
524 // Question: Should we continue or stop the query here?
525 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
528 $sql = DBA::cleanQuery($sql);
529 $sql = $this->anyValueFallback($sql);
533 if ($this->configCache->get('system', 'db_callstack') !== null) {
534 $sql = "/*" . System::callstack() . " */ " . $sql;
540 $this->affected_rows = 0;
542 // We have to make some things different if this function is called from "e"
543 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
545 if (isset($trace[1])) {
546 $called_from = $trace[1];
548 // We use just something that is defined to avoid warnings
549 $called_from = $trace[0];
551 // We are having an own error logging in the function "e"
552 $called_from_e = ($called_from['function'] == 'e');
554 if (!isset($this->connection)) {
555 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
558 switch ($this->driver) {
560 // If there are no arguments we use "query"
561 if (count($args) == 0) {
562 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
563 $errorInfo = $this->connection->errorInfo();
564 $this->error = (string)$errorInfo[2];
565 $this->errorno = (int)$errorInfo[1];
570 $this->affected_rows = $retval->rowCount();
574 /** @var $stmt mysqli_stmt|PDOStatement */
575 if (!$stmt = $this->connection->prepare($sql)) {
576 $errorInfo = $this->connection->errorInfo();
577 $this->error = (string)$errorInfo[2];
578 $this->errorno = (int)$errorInfo[1];
584 foreach (array_keys($args) as $param) {
585 $data_type = PDO::PARAM_STR;
586 if (is_int($args[$param])) {
587 $data_type = PDO::PARAM_INT;
588 } elseif ($args[$param] !== null) {
589 $args[$param] = (string)$args[$param];
592 $stmt->bindParam($param, $args[$param], $data_type);
595 if (!$stmt->execute()) {
596 $errorInfo = $stmt->errorInfo();
597 $this->error = (string)$errorInfo[2];
598 $this->errorno = (int)$errorInfo[1];
603 $this->affected_rows = $retval->rowCount();
607 // There are SQL statements that cannot be executed with a prepared statement
608 $parts = explode(' ', $orig_sql);
609 $command = strtolower($parts[0]);
610 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
612 // The fallback routine is called as well when there are no arguments
613 if (!$can_be_prepared || (count($args) == 0)) {
614 $retval = $this->connection->query($this->replaceParameters($sql, $args));
615 if ($this->connection->errno) {
616 $this->error = (string)$this->connection->error;
617 $this->errorno = (int)$this->connection->errno;
621 if (isset($retval->num_rows)) {
622 $this->affected_rows = $retval->num_rows;
624 $this->affected_rows = $this->connection->affected_rows;
630 $stmt = $this->connection->stmt_init();
632 if (!$stmt->prepare($sql)) {
633 $this->error = (string)$stmt->error;
634 $this->errorno = (int)$stmt->errno;
642 foreach (array_keys($args) as $param) {
643 if (is_int($args[$param])) {
645 } elseif (is_float($args[$param])) {
647 } elseif (is_string($args[$param])) {
649 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
651 $args[$param] = (string)$args[$param];
655 $values[] = &$args[$param];
658 if (count($values) > 0) {
659 array_unshift($values, $param_types);
660 call_user_func_array([$stmt, 'bind_param'], $values);
663 if (!$stmt->execute()) {
664 $this->error = (string)$this->connection->error;
665 $this->errorno = (int)$this->connection->errno;
669 $stmt->store_result();
671 $this->affected_rows = $retval->affected_rows;
676 // See issue https://github.com/friendica/friendica/issues/8572
677 // Ensure that we always get an error message on an error.
678 if ($is_error && empty($this->errorno)) {
682 if ($is_error && empty($this->error)) {
683 $this->error = 'Unknown database error';
686 // We are having an own error logging in the function "e"
687 if (($this->errorno != 0) && !$called_from_e) {
688 // We have to preserve the error code, somewhere in the logging it get lost
689 $error = $this->error;
690 $errorno = $this->errorno;
692 if ($this->testmode) {
693 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
696 $this->logger->error('DB Error', [
699 'callstack' => System::callstack(8),
700 'params' => $this->replaceParameters($sql, $args),
703 // On a lost connection we try to reconnect - but only once.
704 if ($errorno == 2006) {
705 if ($this->in_retrial || !$this->reconnect()) {
706 // It doesn't make sense to continue when the database connection was lost
707 if ($this->in_retrial) {
708 $this->logger->notice('Giving up retrial because of database error', [
713 $this->logger->notice('Couldn\'t reconnect after database error', [
721 $this->logger->notice('Reconnected after database error', [
725 $this->in_retrial = true;
726 $ret = $this->p($sql, $args);
727 $this->in_retrial = false;
732 $this->error = (string)$error;
733 $this->errorno = (int)$errorno;
736 $this->profiler->stopRecording();
738 if ($this->configCache->get('system', 'db_log')) {
739 $stamp2 = microtime(true);
740 $duration = (float)($stamp2 - $stamp1);
742 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
743 $duration = round($duration, 3);
744 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
746 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
747 basename($backtrace[1]["file"]) . "\t" .
748 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
749 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
756 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
758 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
760 * @param string $sql SQL statement
762 * @return boolean Was the query successfull? False is returned only if an error occurred
765 public function e(string $sql): bool
769 $this->profiler->startRecording('database_write');
771 $params = DBA::getParam(func_get_args());
773 // In a case of a deadlock we are repeating the query 20 times
777 $stmt = $this->p($sql, $params);
779 if (is_bool($stmt)) {
781 } elseif (is_object($stmt)) {
789 } while (($this->errorno == 1213) && (--$timeout > 0));
791 if ($this->errorno != 0) {
792 // We have to preserve the error code, somewhere in the logging it get lost
793 $error = $this->error;
794 $errorno = $this->errorno;
796 if ($this->testmode) {
797 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
800 $this->logger->error('DB Error', [
803 'callstack' => System::callstack(8),
804 'params' => $this->replaceParameters($sql, $params),
807 // On a lost connection we simply quit.
808 // A reconnect like in $this->p could be dangerous with modifications
809 if ($errorno == 2006) {
810 $this->logger->notice('Giving up because of database error', [
817 $this->error = $error;
818 $this->errorno = $errorno;
821 $this->profiler->stopRecording();
827 * Check if data exists
829 * @param string $table Table name in format schema.table (while scheme is optiona)
830 * @param array $condition Array of fields for condition
832 * @return boolean Are there rows for that condition?
834 * @todo Please unwrap the DBStructure::existsTable() call so this method has one behavior only: checking existence on records
836 public function exists(string $table, array $condition): bool
844 if (empty($condition)) {
845 return DBStructure::existsTable($table);
849 $first_key = key($condition);
850 if (!is_int($first_key)) {
851 $fields = [$first_key];
854 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
856 if (is_bool($stmt)) {
859 $retval = ($this->numRows($stmt) > 0);
868 * Fetches the first row
870 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
872 * Fetches the first row
874 * @param string $sql SQL statement
876 * @return array|bool first row of query or false on failure
879 public function fetchFirst(string $sql)
881 $params = DBA::getParam(func_get_args());
883 $stmt = $this->p($sql, $params);
885 if (is_bool($stmt)) {
888 $retval = $this->fetch($stmt);
897 * Returns the number of affected rows of the last statement
899 * @return int Number of rows
901 public function affectedRows(): int
903 return $this->affected_rows;
907 * Returns the number of columns of a statement
909 * @param object Statement object
911 * @return int Number of columns
913 public function columnCount($stmt): int
915 if (!is_object($stmt)) {
918 switch ($this->driver) {
920 return $stmt->columnCount();
922 return $stmt->field_count;
928 * Returns the number of rows of a statement
930 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
932 * @return int Number of rows
934 public function numRows($stmt): int
936 if (!is_object($stmt)) {
939 switch ($this->driver) {
941 return $stmt->rowCount();
943 return $stmt->num_rows;
951 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
953 * @return array|bool Current row or false on failure
955 public function fetch($stmt)
957 $this->profiler->startRecording('database');
961 if (!is_object($stmt)) {
965 switch ($this->driver) {
967 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
968 if (!empty($stmt->table) && is_array($columns)) {
969 $columns = $this->castFields($stmt->table, $columns);
973 if (get_class($stmt) == 'mysqli_result') {
974 $columns = $stmt->fetch_assoc() ?? false;
978 // This code works, but is slow
980 // Bind the result to a result array
984 for ($x = 0; $x < $stmt->field_count; $x++) {
985 $cols[] = &$cols_num[$x];
988 call_user_func_array([$stmt, 'bind_result'], $cols);
990 if (!$stmt->fetch()) {
995 // We need to get the field names for the array keys
996 // It seems that there is no better way to do this.
997 $result = $stmt->result_metadata();
998 $fields = $result->fetch_fields();
1000 foreach ($cols_num as $param => $col) {
1001 $columns[$fields[$param]->name] = $col;
1005 $this->profiler->stopRecording();
1011 * Insert a row into a table. Field value objects will be cast as string.
1013 * @param string $table Table name in format schema.table (while scheme is optiona)
1014 * @param array $param parameter array
1015 * @param int $duplicate_mode What to do on a duplicated entry
1017 * @return boolean was the insert successful?
1018 * @throws \Exception
1020 public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1022 if (empty($table) || empty($param)) {
1023 $this->logger->info('Table and fields have to be set');
1027 $param = $this->castFields($table, $param);
1029 $table_string = DBA::buildTableString([$table]);
1031 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1033 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1037 if ($duplicate_mode == self::INSERT_IGNORE) {
1041 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1043 if ($duplicate_mode == self::INSERT_UPDATE) {
1044 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1046 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1048 $values = array_values($param);
1049 $param = array_merge_recursive($values, $values);
1052 $result = $this->e($sql, $param);
1053 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1057 return $this->affectedRows() != 0;
1061 * Inserts a row with the provided data in the provided table.
1062 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1064 * @param string $table Table name in format schema.table (while scheme is optiona)
1065 * @param array $param parameter array
1066 * @return boolean was the insert successful?
1067 * @throws \Exception
1069 public function replace(string $table, array $param): bool
1071 if (empty($table) || empty($param)) {
1072 $this->logger->info('Table and fields have to be set');
1076 $param = $this->castFields($table, $param);
1078 $table_string = DBA::buildTableString([$table]);
1080 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1082 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1084 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1086 return $this->e($sql, $param);
1090 * Fetch the id of the last insert command
1092 * @return integer Last inserted id
1094 public function lastInsertId(): int
1096 switch ($this->driver) {
1098 $id = $this->connection->lastInsertId();
1101 $id = $this->connection->insert_id;
1108 * Locks a table for exclusive write access
1110 * This function can be extended in the future to accept a table array as well.
1112 * @param string $table Table name in format schema.table (while scheme is optiona)
1113 * @return boolean was the lock successful?
1114 * @throws \Exception
1116 public function lock(string $table): bool
1118 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1119 if ($this->driver == self::PDO) {
1120 $this->e("SET autocommit=0");
1121 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1123 $this->connection->autocommit(false);
1126 $success = $this->e("LOCK TABLES " . DBA::buildTableString([$table]) . " WRITE");
1128 if ($this->driver == self::PDO) {
1129 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1133 if ($this->driver == self::PDO) {
1134 $this->e("SET autocommit=1");
1136 $this->connection->autocommit(true);
1139 $this->in_transaction = true;
1145 * Unlocks all locked tables
1147 * @return boolean was the unlock successful?
1148 * @throws \Exception
1150 public function unlock(): bool
1152 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1153 $this->performCommit();
1155 if ($this->driver == self::PDO) {
1156 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1159 $success = $this->e("UNLOCK TABLES");
1161 if ($this->driver == self::PDO) {
1162 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1163 $this->e("SET autocommit=1");
1165 $this->connection->autocommit(true);
1168 $this->in_transaction = false;
1173 * Starts a transaction
1175 * @return boolean Was the command executed successfully?
1177 public function transaction(): bool
1179 if (!$this->performCommit()) {
1183 switch ($this->driver) {
1185 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1191 if (!$this->connection->begin_transaction()) {
1197 $this->in_transaction = true;
1202 * Performs the commit
1204 * @return boolean Was the command executed successfully?
1206 protected function performCommit(): bool
1208 switch ($this->driver) {
1210 if (!$this->connection->inTransaction()) {
1214 return $this->connection->commit();
1217 return $this->connection->commit();
1226 * @return boolean Was the command executed successfully?
1228 public function commit(): bool
1230 if (!$this->performCommit()) {
1233 $this->in_transaction = false;
1240 * @return boolean Was the command executed successfully?
1242 public function rollback(): bool
1246 switch ($this->driver) {
1248 if (!$this->connection->inTransaction()) {
1252 $ret = $this->connection->rollBack();
1256 $ret = $this->connection->rollback();
1260 $this->in_transaction = false;
1265 * Delete a row from a table
1267 * @param string $table Table name
1268 * @param array $conditions Field condition(s)
1270 * @return boolean was the delete successful?
1271 * @throws \Exception
1273 public function delete(string $table, array $conditions): bool
1275 if (empty($table) || empty($conditions)) {
1276 $this->logger->info('Table and conditions have to be set');
1280 $table_string = DBA::buildTableString([$table]);
1282 $condition_string = DBA::buildCondition($conditions);
1284 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1285 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1286 return $this->e($sql, $conditions);
1290 * Updates rows in the database. Field value objects will be cast as string.
1292 * When $old_fields is set to an array,
1293 * the system will only do an update if the fields in that array changed.
1296 * Only the values in $old_fields are compared.
1297 * This is an intentional behaviour.
1300 * We include the timestamp field in $fields but not in $old_fields.
1301 * Then the row will only get the new timestamp when the other fields had changed.
1303 * When $old_fields is set to a boolean value the system will do this compare itself.
1304 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1307 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1308 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1310 * @param string $table Table name in format schema.table (while scheme is optiona)
1311 * @param array $fields contains the fields that are updated
1312 * @param array $condition condition array with the key values
1313 * @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)
1314 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1316 * @return boolean was the update successfull?
1317 * @throws \Exception
1318 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1320 public function update(string $table, array $fields, array $condition, $old_fields = [], array $params = [])
1322 if (empty($table) || empty($fields) || empty($condition)) {
1323 $this->logger->info('Table, fields and condition have to be set');
1327 if (is_bool($old_fields)) {
1328 $do_insert = $old_fields;
1330 $old_fields = $this->selectFirst($table, [], $condition);
1332 if (is_bool($old_fields)) {
1334 $values = array_merge($condition, $fields);
1335 return $this->replace($table, $values);
1341 foreach ($old_fields as $fieldname => $content) {
1342 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1343 unset($fields[$fieldname]);
1347 if (count($fields) == 0) {
1351 $fields = $this->castFields($table, $fields);
1353 $table_string = DBA::buildTableString([$table]);
1355 $condition_string = DBA::buildCondition($condition);
1357 if (!empty($params['ignore'])) {
1358 $ignore = 'IGNORE ';
1363 $sql = "UPDATE " . $ignore . $table_string . " SET "
1364 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1365 . $condition_string;
1367 // Combines the updated fields parameter values with the condition parameter values
1368 $params = array_merge(array_values($fields), $condition);
1370 return $this->e($sql, $params);
1374 * Retrieve a single record from a table and returns it in an associative array
1376 * @param string $table Table name in format schema.table (while scheme is optiona)
1377 * @param array $fields Array of selected fields, empty for all
1378 * @param array $condition Array of fields for condition
1379 * @param array $params Array of several parameters
1381 * @return bool|array
1382 * @throws \Exception
1383 * @see $this->select
1385 public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1387 $params['limit'] = 1;
1388 $result = $this->select($table, $fields, $condition, $params);
1390 if (is_bool($result)) {
1393 $row = $this->fetch($result);
1394 $this->close($result);
1400 * Select rows from a table and fills an array with the data
1402 * @param string $table Table name in format schema.table (while scheme is optiona)
1403 * @param array $fields Array of selected fields, empty for all
1404 * @param array $condition Array of fields for condition
1405 * @param array $params Array of several parameters
1406 * @return array Data array
1407 * @throws \Exception
1410 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1412 return $this->toArray($this->select($table, $fields, $condition, $params));
1416 * Escape fields, adding special treatment for "group by" handling
1418 * @param array $fields
1419 * @param array $options
1420 * @return array Escaped fields
1422 private function escapeFields(array $fields, array $options): array
1424 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1425 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1426 // Otherwise MySQL would report errors.
1427 if (!empty($options['group_by']) && !empty($options['order'])) {
1428 foreach ($options['order'] as $key => $field) {
1429 if (!is_int($key)) {
1430 if (!in_array($key, $fields)) {
1434 if (!in_array($field, $fields)) {
1441 array_walk($fields, function(&$value, $key) use ($options)
1444 $value = DBA::quoteIdentifier($field);
1446 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1447 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1455 * Select rows from a table
1461 * $table = ['schema' => 'table'];
1462 * @see DBA::buildTableString()
1464 * $fields = ['id', 'uri', 'uid', 'network'];
1466 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1468 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1469 * @see DBA::buildCondition()
1471 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1472 * @see DBA::buildParameter()
1474 * $data = DBA::select($table, $fields, $condition, $params);
1476 * @param string $table Table name in format schema.table (while scheme is optiona)
1477 * @param array $fields Array of selected fields, empty for all
1478 * @param array $condition Array of fields for condition
1479 * @param array $params Array of several parameters
1480 * @return boolean|object
1481 * @throws \Exception
1483 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1485 if (empty($table)) {
1489 if (count($fields) > 0) {
1490 $fields = $this->escapeFields($fields, $params);
1491 $select_string = implode(', ', $fields);
1493 $select_string = '*';
1496 $table_string = DBA::buildTableString([$table]);
1498 $condition_string = DBA::buildCondition($condition);
1500 $param_string = DBA::buildParameter($params);
1502 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1504 $result = $this->p($sql, $condition);
1506 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1507 $result->table = $table;
1514 * Counts the rows from a table satisfying the provided condition
1516 * @param string $table Table name in format schema.table (while scheme is optiona)
1517 * @param array $condition Array of fields for condition
1518 * @param array $params Array of several parameters
1520 * @return int Count of rows
1525 * $condition = ["uid" => 1, "network" => 'dspr'];
1527 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1529 * $count = DBA::count($table, $condition);
1530 * @throws \Exception
1532 public function count(string $table, array $condition = [], array $params = []): int
1534 if (empty($table)) {
1535 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1538 $table_string = DBA::buildTableString([$table]);
1540 $condition_string = DBA::buildCondition($condition);
1542 if (empty($params['expression'])) {
1544 } elseif (!empty($params['distinct'])) {
1545 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1547 $expression = DBA::quoteIdentifier($params['expression']);
1550 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1552 $row = $this->fetchFirst($sql, $condition);
1554 if (!isset($row['count'])) {
1555 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1558 return (int)$row['count'];
1563 * Fills an array with data from a query
1565 * @param object $stmt statement object
1566 * @param bool $do_close Close database connection after last row
1567 * @param int $count maximum number of rows to be fetched
1569 * @return array Data array
1571 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1573 if (is_bool($stmt)) {
1578 while ($row = $this->fetch($stmt)) {
1580 if (($count != 0) && (count($data) == $count)) {
1586 $this->close($stmt);
1593 * Cast field types according to the table definition
1595 * @param string $table
1596 * @param array $fields
1597 * @return array casted fields
1599 public function castFields(string $table, array $fields): array
1601 // When there is no data, we don't need to do something
1602 if (empty($fields)) {
1606 // We only need to cast fields with PDO
1607 if ($this->driver != self::PDO) {
1611 // We only need to cast when emulating the prepares
1612 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1618 $tables = $this->dbaDefinition->getAll();
1619 if (empty($tables[$table])) {
1620 // When a matching table wasn't found we check if it is a view
1621 $views = $this->viewDefinition->getAll();
1622 if (empty($views[$table])) {
1626 foreach (array_keys($fields) as $field) {
1627 if (!empty($views[$table]['fields'][$field])) {
1628 $viewdef = $views[$table]['fields'][$field];
1629 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1630 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1635 foreach ($tables[$table]['fields'] as $field => $definition) {
1636 $types[$field] = $definition['type'];
1640 foreach ($fields as $field => $content) {
1641 if (is_null($content) || empty($types[$field])) {
1645 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1646 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1647 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1648 $fields[$field] = (int)$content;
1650 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1651 $fields[$field] = (float)$content;
1659 * Returns the error number of the last query
1661 * @return string Error number (0 if no error)
1663 public function errorNo(): int
1665 return $this->errorno;
1669 * Returns the error message of the last query
1671 * @return string Error message ('' if no error)
1673 public function errorMessage(): string
1675 return $this->error;
1679 * Closes the current statement
1681 * @param object $stmt statement object
1683 * @return boolean was the close successful?
1685 public function close($stmt): bool
1688 $this->profiler->startRecording('database');
1690 if (!is_object($stmt)) {
1694 switch ($this->driver) {
1696 $ret = $stmt->closeCursor();
1699 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1700 // We should be careful not to assume the object type of $stmt
1701 // because DBA::p() has been able to return both types.
1702 if ($stmt instanceof mysqli_stmt) {
1703 $stmt->free_result();
1704 $ret = $stmt->close();
1705 } elseif ($stmt instanceof mysqli_result) {
1714 $this->profiler->stopRecording();
1720 * Return a list of database processes
1723 * 'list' => List of processes, separated in their different states
1724 * 'amount' => Number of concurrent database processes
1725 * @throws \Exception
1727 public function processlist(): array
1729 $ret = $this->p('SHOW PROCESSLIST');
1730 $data = $this->toArray($ret);
1734 foreach ($data as $process) {
1735 $state = trim($process['State']);
1737 // Filter out all non blocking processes
1738 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1745 foreach ($states as $state => $usage) {
1746 if ($statelist != '') {
1749 $statelist .= $state . ': ' . $usage;
1751 return (['list' => $statelist, 'amount' => $processes]);
1755 * Fetch a database variable
1757 * @param string $name
1758 * @return string|null content or null if inexistent
1759 * @throws \Exception
1761 public function getVariable(string $name)
1763 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1764 return $result['Value'] ?? null;
1768 * Checks if $array is a filled array with at least one entry.
1770 * @param mixed $array A filled array with at least one entry
1771 * @return boolean Whether $array is a filled array or an object with rows
1773 public function isResult($array): bool
1775 // It could be a return value from an update statement
1776 if (is_bool($array)) {
1780 if (is_object($array)) {
1781 return $this->numRows($array) > 0;
1784 return (is_array($array) && (count($array) > 0));
1788 * Callback function for "esc_array"
1790 * @param mixed $value Array value
1791 * @param string $key Array key
1792 * @param boolean $add_quotation add quotation marks for string values
1795 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1797 if (!$add_quotation) {
1798 if (is_bool($value)) {
1799 $value = ($value ? '1' : '0');
1801 $value = $this->escape($value);
1806 if (is_bool($value)) {
1807 $value = ($value ? 'true' : 'false');
1808 } elseif (is_float($value) || is_integer($value)) {
1809 $value = (string)$value;
1811 $value = "'" . $this->escape($value) . "'";
1816 * Escapes a whole array
1818 * @param mixed $arr Array with values to be escaped
1819 * @param boolean $add_quotation add quotation marks for string values
1822 public function escapeArray(&$arr, bool $add_quotation = false)
1824 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1828 * Replaces a string in the provided fields of the provided table
1830 * @param string $table Table name
1831 * @param array $fields List of field names in the provided table
1832 * @param string $search String to search for
1833 * @param string $replace String to replace with
1835 * @throws \Exception
1837 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1839 $search = $this->escape($search);
1840 $replace = $this->escape($replace);
1843 foreach ($fields as $field) {
1844 $field = DBA::quoteIdentifier($field);
1845 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1848 $upds = implode(', ', $upd);
1850 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1852 if (!$this->isResult($r)) {
1853 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());