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 $host = trim($serverdata[0]);
116 if (count($serverdata) > 1) {
117 $port = trim($serverdata[1]);
120 if (trim($this->configCache->get('database', 'port') ?? 0)) {
121 $port = trim($this->configCache->get('database', 'port') ?? 0);
124 $user = trim($this->configCache->get('database', 'username'));
125 $pass = trim($this->configCache->get('database', 'password'));
126 $database = trim($this->configCache->get('database', 'database'));
127 $charset = trim($this->configCache->get('database', 'charset'));
128 $socket = trim($this->configCache->get('database', 'socket'));
130 if (!$host && !$socket || !$user) {
134 $persistent = (bool)$this->configCache->get('database', 'persistent');
136 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
138 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
139 $this->driver = self::PDO;
141 $connect = 'mysql:unix_socket=' . $socket;
143 $connect = 'mysql:host=' . $host;
145 $connect .= ';port=' . $port;
150 $connect .= ';charset=' . $charset;
153 $connect .= ';dbname=' . $database;
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(null, $user, $pass, $database, null, $socket);
170 } elseif ($port > 0) {
171 $this->connection = @new mysqli($host, $user, $pass, $database, $port);
173 $this->connection = @new mysqli($host, $user, $pass, $database);
176 if (!mysqli_connect_errno()) {
177 $this->connected = true;
180 $this->connection->set_charset($charset);
185 // No suitable SQL driver was found.
186 if (!$this->connected) {
188 $this->connection = null;
191 return $this->connected;
194 public function setTestmode(bool $test)
196 $this->testmode = $test;
200 * Sets the logger for DBA
202 * @note this is necessary because if we want to load the logger configuration
203 * from the DB, but there's an error, we would print out an exception.
204 * So the logger gets updated after the logger configuration can be retrieved
207 * @param LoggerInterface $logger
209 public function setLogger(LoggerInterface $logger)
211 $this->logger = $logger;
215 * Sets the profiler for DBA
217 * @param Profiler $profiler
219 public function setProfiler(Profiler $profiler)
221 $this->profiler = $profiler;
225 * Disconnects the current database connection
227 public function disconnect()
229 if (!is_null($this->connection)) {
230 switch ($this->driver) {
232 $this->connection = null;
235 $this->connection->close();
236 $this->connection = null;
242 $this->connected = false;
246 * Perform a reconnect of an existing database connection
248 public function reconnect()
251 return $this->connect();
255 * Return the database object.
259 public function getConnection()
261 return $this->connection;
265 * Return the database driver string
267 * @return string with either "pdo" or "mysqli"
269 public function getDriver(): string
271 return $this->driver;
275 * Returns the MySQL server version string
277 * This function discriminate between the deprecated mysql API and the current
278 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
280 * @return string Database server information
282 public function serverInfo(): string
284 if ($this->server_info == '') {
285 switch ($this->driver) {
287 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
290 $this->server_info = $this->connection->server_info;
294 return $this->server_info;
298 * Returns the selected database name
300 * @return string Database name
303 public function databaseName(): string
305 $ret = $this->p("SELECT DATABASE() AS `db`");
306 $data = $this->toArray($ret);
307 return $data[0]['db'];
311 * Analyze a database query and log this if some conditions are met.
313 * @param string $query The database query that will be analyzed
317 private function logIndex(string $query)
320 if (!$this->configCache->get('system', 'db_log_index')) {
324 // Don't explain an explain statement
325 if (strtolower(substr($query, 0, 7)) == "explain") {
329 // Only do the explain on "select", "update" and "delete"
330 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
334 $r = $this->p("EXPLAIN " . $query);
335 if (!$this->isResult($r)) {
339 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
340 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
342 while ($row = $this->fetch($r)) {
343 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
344 $log = (in_array($row['key'], $watchlist) &&
345 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
350 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
354 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
359 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
361 $this->configCache->get('system', 'db_log_index'),
362 DateTimeFormat::utcNow() . "\t" .
363 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
364 basename($backtrace[1]["file"]) . "\t" .
365 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
366 substr($query, 0, 4000) . "\n",
374 * Removes every not allowlisted character from the identifier string
376 * @param string $identifier
377 * @return string sanitized identifier
380 private function sanitizeIdentifier(string $identifier): string
382 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
385 public function escape($str)
387 if ($this->connected) {
388 switch ($this->driver) {
390 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
393 return @$this->connection->real_escape_string($str);
396 return str_replace("'", "\\'", $str);
401 * Returns connected flag
403 * @return bool Whether connection to database was success
405 public function isConnected(): bool
407 return $this->connected;
411 * Checks connection status
413 * @return bool Whether connection to database was success
415 public function connected()
419 if (is_null($this->connection)) {
423 switch ($this->driver) {
425 $r = $this->p("SELECT 1");
426 if ($this->isResult($r)) {
427 $row = $this->toArray($r);
428 $connected = ($row[0]['1'] == '1');
432 $connected = $this->connection->ping();
440 * Replaces ANY_VALUE() function by MIN() function,
441 * if the database server does not support ANY_VALUE().
443 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
444 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
445 * A standard fall-back is to use MIN().
447 * @param string $sql An SQL string without the values
449 * @return string The input SQL string modified if necessary.
451 public function anyValueFallback(string $sql): string
453 $server_info = $this->serverInfo();
454 if (version_compare($server_info, '5.7.5', '<') ||
455 (stripos($server_info, 'MariaDB') !== false)) {
456 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
462 * Replaces the ? placeholders with the parameters in the $args array
464 * @param string $sql SQL query
465 * @param array $args The parameters that are to replace the ? placeholders
467 * @return string The replaced SQL query
469 private function replaceParameters(string $sql, array $args): string
472 foreach ($args as $param => $value) {
473 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
474 $replace = intval($args[$param]);
475 } elseif (is_null($args[$param])) {
478 $replace = "'" . $this->escape($args[$param]) . "'";
481 $pos = strpos($sql, '?', $offset);
482 if ($pos !== false) {
483 $sql = substr_replace($sql, $replace, $pos, 1);
485 $offset = $pos + strlen($replace);
491 * Executes a prepared statement that returns data
493 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
495 * Please only use it with complicated queries.
496 * For all regular queries please use DBA::select or DBA::exists
498 * @param string $sql SQL statement
500 * @return bool|object statement object or result object
503 public function p(string $sql)
506 $this->profiler->startRecording('database');
507 $stamp1 = microtime(true);
509 $params = DBA::getParam(func_get_args());
511 // Renumber the array keys to be sure that they fit
514 foreach ($params as $param) {
515 // Avoid problems with some MySQL servers and boolean values. See issue #3645
516 if (is_bool($param)) {
517 $param = (int)$param;
519 $args[++$i] = $param;
522 if (!$this->connected) {
526 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
527 // Question: Should we continue or stop the query here?
528 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
531 $sql = DBA::cleanQuery($sql);
532 $sql = $this->anyValueFallback($sql);
536 if ($this->configCache->get('system', 'db_callstack') !== null) {
537 $sql = "/*" . System::callstack() . " */ " . $sql;
543 $this->affected_rows = 0;
545 // We have to make some things different if this function is called from "e"
546 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
548 if (isset($trace[1])) {
549 $called_from = $trace[1];
551 // We use just something that is defined to avoid warnings
552 $called_from = $trace[0];
554 // We are having an own error logging in the function "e"
555 $called_from_e = ($called_from['function'] == 'e');
557 if (!isset($this->connection)) {
558 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
561 switch ($this->driver) {
563 // If there are no arguments we use "query"
564 if (count($args) == 0) {
565 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
566 $errorInfo = $this->connection->errorInfo();
567 $this->error = (string)$errorInfo[2];
568 $this->errorno = (int)$errorInfo[1];
573 $this->affected_rows = $retval->rowCount();
577 /** @var $stmt mysqli_stmt|PDOStatement */
578 if (!$stmt = $this->connection->prepare($sql)) {
579 $errorInfo = $this->connection->errorInfo();
580 $this->error = (string)$errorInfo[2];
581 $this->errorno = (int)$errorInfo[1];
587 foreach (array_keys($args) as $param) {
588 $data_type = PDO::PARAM_STR;
589 if (is_int($args[$param])) {
590 $data_type = PDO::PARAM_INT;
591 } elseif ($args[$param] !== null) {
592 $args[$param] = (string)$args[$param];
595 $stmt->bindParam($param, $args[$param], $data_type);
598 if (!$stmt->execute()) {
599 $errorInfo = $stmt->errorInfo();
600 $this->error = (string)$errorInfo[2];
601 $this->errorno = (int)$errorInfo[1];
606 $this->affected_rows = $retval->rowCount();
610 // There are SQL statements that cannot be executed with a prepared statement
611 $parts = explode(' ', $orig_sql);
612 $command = strtolower($parts[0]);
613 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
615 // The fallback routine is called as well when there are no arguments
616 if (!$can_be_prepared || (count($args) == 0)) {
617 $retval = $this->connection->query($this->replaceParameters($sql, $args));
618 if ($this->connection->errno) {
619 $this->error = (string)$this->connection->error;
620 $this->errorno = (int)$this->connection->errno;
624 if (isset($retval->num_rows)) {
625 $this->affected_rows = $retval->num_rows;
627 $this->affected_rows = $this->connection->affected_rows;
633 $stmt = $this->connection->stmt_init();
635 if (!$stmt->prepare($sql)) {
636 $this->error = (string)$stmt->error;
637 $this->errorno = (int)$stmt->errno;
645 foreach (array_keys($args) as $param) {
646 if (is_int($args[$param])) {
648 } elseif (is_float($args[$param])) {
650 } elseif (is_string($args[$param])) {
652 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
654 $args[$param] = (string)$args[$param];
658 $values[] = &$args[$param];
661 if (count($values) > 0) {
662 array_unshift($values, $param_types);
663 call_user_func_array([$stmt, 'bind_param'], $values);
666 if (!$stmt->execute()) {
667 $this->error = (string)$this->connection->error;
668 $this->errorno = (int)$this->connection->errno;
672 $stmt->store_result();
674 $this->affected_rows = $retval->affected_rows;
679 // See issue https://github.com/friendica/friendica/issues/8572
680 // Ensure that we always get an error message on an error.
681 if ($is_error && empty($this->errorno)) {
685 if ($is_error && empty($this->error)) {
686 $this->error = 'Unknown database error';
689 // We are having an own error logging in the function "e"
690 if (($this->errorno != 0) && !$called_from_e) {
691 // We have to preserve the error code, somewhere in the logging it get lost
692 $error = $this->error;
693 $errorno = $this->errorno;
695 if ($this->testmode) {
696 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
699 $this->logger->error('DB Error', [
702 'callstack' => System::callstack(8),
703 'params' => $this->replaceParameters($sql, $args),
706 // On a lost connection we try to reconnect - but only once.
707 if ($errorno == 2006) {
708 if ($this->in_retrial || !$this->reconnect()) {
709 // It doesn't make sense to continue when the database connection was lost
710 if ($this->in_retrial) {
711 $this->logger->notice('Giving up retrial because of database error', [
716 $this->logger->notice('Couldn\'t reconnect after database error', [
724 $this->logger->notice('Reconnected after database error', [
728 $this->in_retrial = true;
729 $ret = $this->p($sql, $args);
730 $this->in_retrial = false;
735 $this->error = (string)$error;
736 $this->errorno = (int)$errorno;
739 $this->profiler->stopRecording();
741 if ($this->configCache->get('system', 'db_log')) {
742 $stamp2 = microtime(true);
743 $duration = (float)($stamp2 - $stamp1);
745 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
746 $duration = round($duration, 3);
747 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
750 $this->configCache->get('system', 'db_log'),
751 DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
752 basename($backtrace[1]["file"]) . "\t" .
753 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
754 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n",
763 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
765 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
767 * @param string $sql SQL statement
769 * @return boolean Was the query successfull? False is returned only if an error occurred
772 public function e(string $sql): bool
776 $this->profiler->startRecording('database_write');
778 $params = DBA::getParam(func_get_args());
780 // In a case of a deadlock we are repeating the query 20 times
784 $stmt = $this->p($sql, $params);
786 if (is_bool($stmt)) {
788 } elseif (is_object($stmt)) {
796 } while (($this->errorno == 1213) && (--$timeout > 0));
798 if ($this->errorno != 0) {
799 // We have to preserve the error code, somewhere in the logging it get lost
800 $error = $this->error;
801 $errorno = $this->errorno;
803 if ($this->testmode) {
804 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
807 $this->logger->error('DB Error', [
810 'callstack' => System::callstack(8),
811 'params' => $this->replaceParameters($sql, $params),
814 // On a lost connection we simply quit.
815 // A reconnect like in $this->p could be dangerous with modifications
816 if ($errorno == 2006) {
817 $this->logger->notice('Giving up because of database error', [
824 $this->error = $error;
825 $this->errorno = $errorno;
828 $this->profiler->stopRecording();
834 * Check if data exists
836 * @param string $table Table name in format schema.table (while scheme is optiona)
837 * @param array $condition Array of fields for condition
839 * @return boolean Are there rows for that condition?
841 * @todo Please unwrap the DBStructure::existsTable() call so this method has one behavior only: checking existence on records
843 public function exists(string $table, array $condition): bool
851 if (empty($condition)) {
852 return DBStructure::existsTable($table);
856 $first_key = key($condition);
857 if (!is_int($first_key)) {
858 $fields = [$first_key];
861 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
863 if (is_bool($stmt)) {
866 $retval = ($this->numRows($stmt) > 0);
875 * Fetches the first row
877 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
879 * Fetches the first row
881 * @param string $sql SQL statement
883 * @return array|bool first row of query or false on failure
886 public function fetchFirst(string $sql)
888 $params = DBA::getParam(func_get_args());
890 $stmt = $this->p($sql, $params);
892 if (is_bool($stmt)) {
895 $retval = $this->fetch($stmt);
904 * Returns the number of affected rows of the last statement
906 * @return int Number of rows
908 public function affectedRows(): int
910 return $this->affected_rows;
914 * Returns the number of columns of a statement
916 * @param object Statement object
918 * @return int Number of columns
920 public function columnCount($stmt): int
922 if (!is_object($stmt)) {
925 switch ($this->driver) {
927 return $stmt->columnCount();
929 return $stmt->field_count;
935 * Returns the number of rows of a statement
937 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
939 * @return int Number of rows
941 public function numRows($stmt): int
943 if (!is_object($stmt)) {
946 switch ($this->driver) {
948 return $stmt->rowCount();
950 return $stmt->num_rows;
958 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
960 * @return array|bool Current row or false on failure
962 public function fetch($stmt)
964 $this->profiler->startRecording('database');
968 if (!is_object($stmt)) {
972 switch ($this->driver) {
974 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
975 if (!empty($stmt->table) && is_array($columns)) {
976 $columns = $this->castFields($stmt->table, $columns);
980 if (get_class($stmt) == 'mysqli_result') {
981 $columns = $stmt->fetch_assoc() ?? false;
985 // This code works, but is slow
987 // Bind the result to a result array
991 for ($x = 0; $x < $stmt->field_count; $x++) {
992 $cols[] = &$cols_num[$x];
995 call_user_func_array([$stmt, 'bind_result'], $cols);
997 if (!$stmt->fetch()) {
1002 // We need to get the field names for the array keys
1003 // It seems that there is no better way to do this.
1004 $result = $stmt->result_metadata();
1005 $fields = $result->fetch_fields();
1007 foreach ($cols_num as $param => $col) {
1008 $columns[$fields[$param]->name] = $col;
1012 $this->profiler->stopRecording();
1018 * Insert a row into a table. Field value objects will be cast as string.
1020 * @param string $table Table name in format schema.table (while scheme is optiona)
1021 * @param array $param parameter array
1022 * @param int $duplicate_mode What to do on a duplicated entry
1024 * @return boolean was the insert successful?
1025 * @throws \Exception
1027 public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1029 if (empty($table) || empty($param)) {
1030 $this->logger->info('Table and fields have to be set');
1034 $param = $this->castFields($table, $param);
1036 $table_string = DBA::buildTableString([$table]);
1038 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1040 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1044 if ($duplicate_mode == self::INSERT_IGNORE) {
1048 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1050 if ($duplicate_mode == self::INSERT_UPDATE) {
1051 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1053 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1055 $values = array_values($param);
1056 $param = array_merge_recursive($values, $values);
1059 $result = $this->e($sql, $param);
1060 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1064 return $this->affectedRows() != 0;
1068 * Inserts a row with the provided data in the provided table.
1069 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1071 * @param string $table Table name in format schema.table (while scheme is optiona)
1072 * @param array $param parameter array
1073 * @return boolean was the insert successful?
1074 * @throws \Exception
1076 public function replace(string $table, array $param): bool
1078 if (empty($table) || empty($param)) {
1079 $this->logger->info('Table and fields have to be set');
1083 $param = $this->castFields($table, $param);
1085 $table_string = DBA::buildTableString([$table]);
1087 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1089 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1091 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1093 return $this->e($sql, $param);
1097 * Fetch the id of the last insert command
1099 * @return integer Last inserted id
1101 public function lastInsertId(): int
1103 switch ($this->driver) {
1105 $id = $this->connection->lastInsertId();
1108 $id = $this->connection->insert_id;
1115 * Locks a table for exclusive write access
1117 * This function can be extended in the future to accept a table array as well.
1119 * @param string $table Table name in format schema.table (while scheme is optiona)
1120 * @return boolean was the lock successful?
1121 * @throws \Exception
1123 public function lock(string $table): bool
1125 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1126 if ($this->driver == self::PDO) {
1127 $this->e("SET autocommit=0");
1128 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1130 $this->connection->autocommit(false);
1133 $success = $this->e("LOCK TABLES " . DBA::buildTableString([$table]) . " WRITE");
1135 if ($this->driver == self::PDO) {
1136 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1140 if ($this->driver == self::PDO) {
1141 $this->e("SET autocommit=1");
1143 $this->connection->autocommit(true);
1146 $this->in_transaction = true;
1152 * Unlocks all locked tables
1154 * @return boolean was the unlock successful?
1155 * @throws \Exception
1157 public function unlock(): bool
1159 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1160 $this->performCommit();
1162 if ($this->driver == self::PDO) {
1163 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1166 $success = $this->e("UNLOCK TABLES");
1168 if ($this->driver == self::PDO) {
1169 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1170 $this->e("SET autocommit=1");
1172 $this->connection->autocommit(true);
1175 $this->in_transaction = false;
1180 * Starts a transaction
1182 * @return boolean Was the command executed successfully?
1184 public function transaction(): bool
1186 if (!$this->performCommit()) {
1190 switch ($this->driver) {
1192 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1198 if (!$this->connection->begin_transaction()) {
1204 $this->in_transaction = true;
1209 * Performs the commit
1211 * @return boolean Was the command executed successfully?
1213 protected function performCommit(): bool
1215 switch ($this->driver) {
1217 if (!$this->connection->inTransaction()) {
1221 return $this->connection->commit();
1224 return $this->connection->commit();
1233 * @return boolean Was the command executed successfully?
1235 public function commit(): bool
1237 if (!$this->performCommit()) {
1240 $this->in_transaction = false;
1247 * @return boolean Was the command executed successfully?
1249 public function rollback(): bool
1253 switch ($this->driver) {
1255 if (!$this->connection->inTransaction()) {
1259 $ret = $this->connection->rollBack();
1263 $ret = $this->connection->rollback();
1267 $this->in_transaction = false;
1272 * Delete a row from a table
1274 * @param string $table Table name
1275 * @param array $conditions Field condition(s)
1277 * @return boolean was the delete successful?
1278 * @throws \Exception
1280 public function delete(string $table, array $conditions): bool
1282 if (empty($table) || empty($conditions)) {
1283 $this->logger->info('Table and conditions have to be set');
1287 $table_string = DBA::buildTableString([$table]);
1289 $condition_string = DBA::buildCondition($conditions);
1291 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1292 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1293 return $this->e($sql, $conditions);
1297 * Updates rows in the database. Field value objects will be cast as string.
1299 * When $old_fields is set to an array,
1300 * the system will only do an update if the fields in that array changed.
1303 * Only the values in $old_fields are compared.
1304 * This is an intentional behaviour.
1307 * We include the timestamp field in $fields but not in $old_fields.
1308 * Then the row will only get the new timestamp when the other fields had changed.
1310 * When $old_fields is set to a boolean value the system will do this compare itself.
1311 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1314 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1315 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1317 * @param string $table Table name in format schema.table (while scheme is optiona)
1318 * @param array $fields contains the fields that are updated
1319 * @param array $condition condition array with the key values
1320 * @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)
1321 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1323 * @return boolean was the update successfull?
1324 * @throws \Exception
1325 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1327 public function update(string $table, array $fields, array $condition, $old_fields = [], array $params = [])
1329 if (empty($table) || empty($fields) || empty($condition)) {
1330 $this->logger->info('Table, fields and condition have to be set');
1334 if (is_bool($old_fields)) {
1335 $do_insert = $old_fields;
1337 $old_fields = $this->selectFirst($table, [], $condition);
1339 if (is_bool($old_fields)) {
1341 $values = array_merge($condition, $fields);
1342 return $this->replace($table, $values);
1348 foreach ($old_fields as $fieldname => $content) {
1349 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1350 unset($fields[$fieldname]);
1354 if (count($fields) == 0) {
1358 $fields = $this->castFields($table, $fields);
1360 $table_string = DBA::buildTableString([$table]);
1362 $condition_string = DBA::buildCondition($condition);
1364 if (!empty($params['ignore'])) {
1365 $ignore = 'IGNORE ';
1370 $sql = "UPDATE " . $ignore . $table_string . " SET "
1371 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1372 . $condition_string;
1374 // Combines the updated fields parameter values with the condition parameter values
1375 $params = array_merge(array_values($fields), $condition);
1377 return $this->e($sql, $params);
1381 * Retrieve a single record from a table and returns it in an associative array
1383 * @param string $table Table name in format schema.table (while scheme is optiona)
1384 * @param array $fields Array of selected fields, empty for all
1385 * @param array $condition Array of fields for condition
1386 * @param array $params Array of several parameters
1388 * @return bool|array
1389 * @throws \Exception
1390 * @see $this->select
1392 public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1394 $params['limit'] = 1;
1395 $result = $this->select($table, $fields, $condition, $params);
1397 if (is_bool($result)) {
1400 $row = $this->fetch($result);
1401 $this->close($result);
1407 * Select rows from a table and fills an array with the data
1409 * @param string $table Table name in format schema.table (while scheme is optiona)
1410 * @param array $fields Array of selected fields, empty for all
1411 * @param array $condition Array of fields for condition
1412 * @param array $params Array of several parameters
1413 * @return array Data array
1414 * @throws \Exception
1417 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1419 return $this->toArray($this->select($table, $fields, $condition, $params));
1423 * Escape fields, adding special treatment for "group by" handling
1425 * @param array $fields
1426 * @param array $options
1427 * @return array Escaped fields
1429 private function escapeFields(array $fields, array $options): array
1431 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1432 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1433 // Otherwise MySQL would report errors.
1434 if (!empty($options['group_by']) && !empty($options['order'])) {
1435 foreach ($options['order'] as $key => $field) {
1436 if (!is_int($key)) {
1437 if (!in_array($key, $fields)) {
1441 if (!in_array($field, $fields)) {
1448 array_walk($fields, function (&$value, $key) use ($options) {
1450 $value = DBA::quoteIdentifier($field);
1452 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1453 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1461 * Select rows from a table
1467 * $table = ['schema' => 'table'];
1468 * @see DBA::buildTableString()
1470 * $fields = ['id', 'uri', 'uid', 'network'];
1472 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1474 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1475 * @see DBA::buildCondition()
1477 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1478 * @see DBA::buildParameter()
1480 * $data = DBA::select($table, $fields, $condition, $params);
1482 * @param string $table Table name in format schema.table (while scheme is optiona)
1483 * @param array $fields Array of selected fields, empty for all
1484 * @param array $condition Array of fields for condition
1485 * @param array $params Array of several parameters
1486 * @return boolean|object
1487 * @throws \Exception
1489 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1491 if (empty($table)) {
1495 if (count($fields) > 0) {
1496 $fields = $this->escapeFields($fields, $params);
1497 $select_string = implode(', ', $fields);
1499 $select_string = '*';
1502 $table_string = DBA::buildTableString([$table]);
1504 $condition_string = DBA::buildCondition($condition);
1506 $param_string = DBA::buildParameter($params);
1508 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1510 $result = $this->p($sql, $condition);
1512 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1513 $result->table = $table;
1520 * Counts the rows from a table satisfying the provided condition
1522 * @param string $table Table name in format schema.table (while scheme is optiona)
1523 * @param array $condition Array of fields for condition
1524 * @param array $params Array of several parameters
1526 * @return int Count of rows
1531 * $condition = ["uid" => 1, "network" => 'dspr'];
1533 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1535 * $count = DBA::count($table, $condition);
1536 * @throws \Exception
1538 public function count(string $table, array $condition = [], array $params = []): int
1540 if (empty($table)) {
1541 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1544 $table_string = DBA::buildTableString([$table]);
1546 $condition_string = DBA::buildCondition($condition);
1548 if (empty($params['expression'])) {
1550 } elseif (!empty($params['distinct'])) {
1551 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1553 $expression = DBA::quoteIdentifier($params['expression']);
1556 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1558 $row = $this->fetchFirst($sql, $condition);
1560 if (!isset($row['count'])) {
1561 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1564 return (int)$row['count'];
1569 * Fills an array with data from a query
1571 * @param object $stmt statement object
1572 * @param bool $do_close Close database connection after last row
1573 * @param int $count maximum number of rows to be fetched
1575 * @return array Data array
1577 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1579 if (is_bool($stmt)) {
1584 while ($row = $this->fetch($stmt)) {
1586 if (($count != 0) && (count($data) == $count)) {
1592 $this->close($stmt);
1599 * Cast field types according to the table definition
1601 * @param string $table
1602 * @param array $fields
1603 * @return array casted fields
1605 public function castFields(string $table, array $fields): array
1607 // When there is no data, we don't need to do something
1608 if (empty($fields)) {
1612 // We only need to cast fields with PDO
1613 if ($this->driver != self::PDO) {
1617 // We only need to cast when emulating the prepares
1618 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1624 $tables = $this->dbaDefinition->getAll();
1625 if (empty($tables[$table])) {
1626 // When a matching table wasn't found we check if it is a view
1627 $views = $this->viewDefinition->getAll();
1628 if (empty($views[$table])) {
1632 foreach (array_keys($fields) as $field) {
1633 if (!empty($views[$table]['fields'][$field])) {
1634 $viewdef = $views[$table]['fields'][$field];
1635 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1636 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1641 foreach ($tables[$table]['fields'] as $field => $definition) {
1642 $types[$field] = $definition['type'];
1646 foreach ($fields as $field => $content) {
1647 if (is_null($content) || empty($types[$field])) {
1651 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1652 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1653 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1654 $fields[$field] = (int)$content;
1656 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1657 $fields[$field] = (float)$content;
1665 * Returns the error number of the last query
1667 * @return string Error number (0 if no error)
1669 public function errorNo(): int
1671 return $this->errorno;
1675 * Returns the error message of the last query
1677 * @return string Error message ('' if no error)
1679 public function errorMessage(): string
1681 return $this->error;
1685 * Closes the current statement
1687 * @param object $stmt statement object
1689 * @return boolean was the close successful?
1691 public function close($stmt): bool
1694 $this->profiler->startRecording('database');
1696 if (!is_object($stmt)) {
1700 switch ($this->driver) {
1702 $ret = $stmt->closeCursor();
1705 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1706 // We should be careful not to assume the object type of $stmt
1707 // because DBA::p() has been able to return both types.
1708 if ($stmt instanceof mysqli_stmt) {
1709 $stmt->free_result();
1710 $ret = $stmt->close();
1711 } elseif ($stmt instanceof mysqli_result) {
1720 $this->profiler->stopRecording();
1726 * Return a list of database processes
1729 * 'list' => List of processes, separated in their different states
1730 * 'amount' => Number of concurrent database processes
1731 * @throws \Exception
1733 public function processlist(): array
1735 $ret = $this->p('SHOW PROCESSLIST');
1736 $data = $this->toArray($ret);
1740 foreach ($data as $process) {
1741 $state = trim($process['State']);
1743 // Filter out all non blocking processes
1744 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1751 foreach ($states as $state => $usage) {
1752 if ($statelist != '') {
1755 $statelist .= $state . ': ' . $usage;
1757 return (['list' => $statelist, 'amount' => $processes]);
1761 * Fetch a database variable
1763 * @param string $name
1764 * @return string|null content or null if inexistent
1765 * @throws \Exception
1767 public function getVariable(string $name)
1769 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1770 return $result['Value'] ?? null;
1774 * Checks if $array is a filled array with at least one entry.
1776 * @param mixed $array A filled array with at least one entry
1777 * @return boolean Whether $array is a filled array or an object with rows
1779 public function isResult($array): bool
1781 // It could be a return value from an update statement
1782 if (is_bool($array)) {
1786 if (is_object($array)) {
1787 return $this->numRows($array) > 0;
1790 return (is_array($array) && (count($array) > 0));
1794 * Callback function for "esc_array"
1796 * @param mixed $value Array value
1797 * @param string $key Array key
1798 * @param boolean $add_quotation add quotation marks for string values
1801 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1803 if (!$add_quotation) {
1804 if (is_bool($value)) {
1805 $value = ($value ? '1' : '0');
1807 $value = $this->escape($value);
1812 if (is_bool($value)) {
1813 $value = ($value ? 'true' : 'false');
1814 } elseif (is_float($value) || is_integer($value)) {
1815 $value = (string)$value;
1817 $value = "'" . $this->escape($value) . "'";
1822 * Escapes a whole array
1824 * @param mixed $arr Array with values to be escaped
1825 * @param boolean $add_quotation add quotation marks for string values
1828 public function escapeArray(&$arr, bool $add_quotation = false)
1830 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1834 * Replaces a string in the provided fields of the provided table
1836 * @param string $table Table name
1837 * @param array $fields List of field names in the provided table
1838 * @param string $search String to search for
1839 * @param string $replace String to replace with
1841 * @throws \Exception
1843 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1845 $search = $this->escape($search);
1846 $replace = $this->escape($replace);
1849 foreach ($fields as $field) {
1850 $field = DBA::quoteIdentifier($field);
1851 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1854 $upds = implode(', ', $upd);
1856 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1858 if (!$this->isResult($r)) {
1859 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());