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;
41 * This class is for the low level database stuff that does driver specific things.
46 const MYSQLI = 'mysqli';
48 const INSERT_DEFAULT = 0;
49 const INSERT_UPDATE = 1;
50 const INSERT_IGNORE = 2;
52 protected $connected = false;
55 * @var \Friendica\Core\Config\ValueObject\Cache
57 protected $configCache;
63 * @var LoggerInterface
66 protected $server_info = '';
67 /** @var PDO|mysqli */
68 protected $connection;
69 protected $driver = '';
70 protected $pdo_emulate_prepares = false;
71 private $error = false;
73 private $affected_rows = 0;
74 protected $in_transaction = false;
75 protected $in_retrial = false;
76 protected $testmode = false;
77 private $relation = [];
78 /** @var DbaDefinition */
79 protected $dbaDefinition;
80 /** @var ViewDefinition */
81 protected $viewDefinition;
83 public function __construct(Cache $configCache, Profiler $profiler, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition, LoggerInterface $logger)
85 // We are storing these values for being able to perform a reconnect
86 $this->configCache = $configCache;
87 $this->profiler = $profiler;
88 $this->logger = $logger;
89 $this->dbaDefinition = $dbaDefinition;
90 $this->viewDefinition = $viewDefinition;
96 * Tries to connect to database
98 * @return bool Success
100 public function connect(): bool
102 if (!is_null($this->connection) && $this->connected()) {
103 return $this->connected;
106 // Reset connected state
107 $this->connected = false;
110 $serveraddr = trim($this->configCache->get('database', 'hostname'));
111 $serverdata = explode(':', $serveraddr);
112 $server = $serverdata[0];
113 if (count($serverdata) > 1) {
114 $port = trim($serverdata[1]);
117 if (!empty(trim($this->configCache->get('database', 'port')))) {
118 $port = trim($this->configCache->get('database', 'port'));
121 $server = trim($server);
122 $user = trim($this->configCache->get('database', 'username'));
123 $pass = trim($this->configCache->get('database', 'password'));
124 $db = trim($this->configCache->get('database', 'database'));
125 $charset = trim($this->configCache->get('database', 'charset'));
126 $socket = trim($this->configCache->get('database', 'socket'));
128 if (!(strlen($server) && strlen($user))) {
132 $persistent = (bool)$this->configCache->get('database', 'persistent');
134 $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
136 if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
137 $this->driver = self::PDO;
138 $connect = "mysql:host=" . $server . ";dbname=" . $db;
141 $connect .= ";port=" . $port;
145 $connect .= ";charset=" . $charset;
149 $connect .= ";$unix_socket=" . $socket;
153 $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
154 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
155 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
156 $this->connected = true;
157 } catch (PDOException $e) {
158 $this->connected = false;
162 if (!$this->connected && class_exists('\mysqli')) {
163 $this->driver = self::MYSQLI;
166 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
168 $this->connection = @new mysqli($server, $user, $pass, $db);
171 if (!mysqli_connect_errno()) {
172 $this->connected = true;
175 $this->connection->set_charset($charset);
179 $this->connection->set_socket($socket);
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;
199 * Sets the logger for DBA
201 * @note this is necessary because if we want to load the logger configuration
202 * from the DB, but there's an error, we would print out an exception.
203 * So the logger gets updated after the logger configuration can be retrieved
206 * @param LoggerInterface $logger
208 public function setLogger(LoggerInterface $logger)
210 $this->logger = $logger;
214 * Sets the profiler for DBA
216 * @param Profiler $profiler
218 public function setProfiler(Profiler $profiler)
220 $this->profiler = $profiler;
223 * Disconnects the current database connection
225 public function disconnect()
227 if (!is_null($this->connection)) {
228 switch ($this->driver) {
230 $this->connection = null;
233 $this->connection->close();
234 $this->connection = null;
240 $this->connected = false;
244 * Perform a reconnect of an existing database connection
246 public function reconnect()
249 return $this->connect();
253 * Return the database object.
257 public function getConnection()
259 return $this->connection;
263 * Return the database driver string
265 * @return string with either "pdo" or "mysqli"
267 public function getDriver(): string
269 return $this->driver;
273 * Returns the MySQL server version string
275 * This function discriminate between the deprecated mysql API and the current
276 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
278 * @return string Database server information
280 public function serverInfo(): string
282 if ($this->server_info == '') {
283 switch ($this->driver) {
285 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
288 $this->server_info = $this->connection->server_info;
292 return $this->server_info;
296 * Returns the selected database name
298 * @return string Database name
301 public function databaseName(): string
303 $ret = $this->p("SELECT DATABASE() AS `db`");
304 $data = $this->toArray($ret);
305 return $data[0]['db'];
309 * Analyze a database query and log this if some conditions are met.
311 * @param string $query The database query that will be analyzed
315 private function logIndex(string $query)
318 if (!$this->configCache->get('system', 'db_log_index')) {
322 // Don't explain an explain statement
323 if (strtolower(substr($query, 0, 7)) == "explain") {
327 // Only do the explain on "select", "update" and "delete"
328 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
332 $r = $this->p("EXPLAIN " . $query);
333 if (!$this->isResult($r)) {
337 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
338 $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
340 while ($row = $this->fetch($r)) {
341 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
342 $log = (in_array($row['key'], $watchlist) &&
343 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
348 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
352 if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
357 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
358 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
359 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
360 basename($backtrace[1]["file"]) . "\t" .
361 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
362 substr($query, 0, 4000) . "\n", FILE_APPEND);
368 * Removes every not allowlisted character from the identifier string
370 * @param string $identifier
371 * @return string sanitized identifier
374 private function sanitizeIdentifier(string $identifier): string
376 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
379 public function escape($str)
381 if ($this->connected) {
382 switch ($this->driver) {
384 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
387 return @$this->connection->real_escape_string($str);
390 return str_replace("'", "\\'", $str);
395 * Returns connected flag
397 * @return bool Whether connection to database was success
399 public function isConnected(): bool
401 return $this->connected;
405 * Checks connection status
407 * @return bool Whether connection to database was success
409 public function connected()
413 if (is_null($this->connection)) {
417 switch ($this->driver) {
419 $r = $this->p("SELECT 1");
420 if ($this->isResult($r)) {
421 $row = $this->toArray($r);
422 $connected = ($row[0]['1'] == '1');
426 $connected = $this->connection->ping();
434 * Replaces ANY_VALUE() function by MIN() function,
435 * if the database server does not support ANY_VALUE().
437 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
438 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
439 * A standard fall-back is to use MIN().
441 * @param string $sql An SQL string without the values
443 * @return string The input SQL string modified if necessary.
445 public function anyValueFallback(string $sql): string
447 $server_info = $this->serverInfo();
448 if (version_compare($server_info, '5.7.5', '<') ||
449 (stripos($server_info, 'MariaDB') !== false)) {
450 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
456 * Replaces the ? placeholders with the parameters in the $args array
458 * @param string $sql SQL query
459 * @param array $args The parameters that are to replace the ? placeholders
461 * @return string The replaced SQL query
463 private function replaceParameters(string $sql, array $args): string
466 foreach ($args as $param => $value) {
467 if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
468 $replace = intval($args[$param]);
469 } elseif (is_null($args[$param])) {
472 $replace = "'" . $this->escape($args[$param]) . "'";
475 $pos = strpos($sql, '?', $offset);
476 if ($pos !== false) {
477 $sql = substr_replace($sql, $replace, $pos, 1);
479 $offset = $pos + strlen($replace);
485 * Executes a prepared statement that returns data
487 * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
489 * Please only use it with complicated queries.
490 * For all regular queries please use DBA::select or DBA::exists
492 * @param string $sql SQL statement
494 * @return bool|object statement object or result object
497 public function p(string $sql)
500 $this->profiler->startRecording('database');
501 $stamp1 = microtime(true);
503 $params = DBA::getParam(func_get_args());
505 // Renumber the array keys to be sure that they fit
508 foreach ($params as $param) {
509 // Avoid problems with some MySQL servers and boolean values. See issue #3645
510 if (is_bool($param)) {
511 $param = (int)$param;
513 $args[++$i] = $param;
516 if (!$this->connected) {
520 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
521 // Question: Should we continue or stop the query here?
522 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
525 $sql = DBA::cleanQuery($sql);
526 $sql = $this->anyValueFallback($sql);
530 if ($this->configCache->get('system', 'db_callstack') !== null) {
531 $sql = "/*" . System::callstack() . " */ " . $sql;
537 $this->affected_rows = 0;
539 // We have to make some things different if this function is called from "e"
540 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
542 if (isset($trace[1])) {
543 $called_from = $trace[1];
545 // We use just something that is defined to avoid warnings
546 $called_from = $trace[0];
548 // We are having an own error logging in the function "e"
549 $called_from_e = ($called_from['function'] == 'e');
551 if (!isset($this->connection)) {
552 throw new ServiceUnavailableException('The Connection is empty, although connected is set true.');
555 switch ($this->driver) {
557 // If there are no arguments we use "query"
558 if (count($args) == 0) {
559 if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
560 $errorInfo = $this->connection->errorInfo();
561 $this->error = $errorInfo[2];
562 $this->errorno = (int) $errorInfo[1];
567 $this->affected_rows = $retval->rowCount();
571 /** @var $stmt mysqli_stmt|PDOStatement */
572 if (!$stmt = $this->connection->prepare($sql)) {
573 $errorInfo = $this->connection->errorInfo();
574 $this->error = $errorInfo[2];
575 $this->errorno = (int) $errorInfo[1];
581 foreach (array_keys($args) as $param) {
582 $data_type = PDO::PARAM_STR;
583 if (is_int($args[$param])) {
584 $data_type = PDO::PARAM_INT;
585 } elseif ($args[$param] !== null) {
586 $args[$param] = (string)$args[$param];
589 $stmt->bindParam($param, $args[$param], $data_type);
592 if (!$stmt->execute()) {
593 $errorInfo = $stmt->errorInfo();
594 $this->error = $errorInfo[2];
595 $this->errorno = (int) $errorInfo[1];
600 $this->affected_rows = $retval->rowCount();
604 // There are SQL statements that cannot be executed with a prepared statement
605 $parts = explode(' ', $orig_sql);
606 $command = strtolower($parts[0]);
607 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
609 // The fallback routine is called as well when there are no arguments
610 if (!$can_be_prepared || (count($args) == 0)) {
611 $retval = $this->connection->query($this->replaceParameters($sql, $args));
612 if ($this->connection->errno) {
613 $this->error = $this->connection->error;
614 $this->errorno = $this->connection->errno;
618 if (isset($retval->num_rows)) {
619 $this->affected_rows = $retval->num_rows;
621 $this->affected_rows = $this->connection->affected_rows;
627 $stmt = $this->connection->stmt_init();
629 if (!$stmt->prepare($sql)) {
630 $this->error = $stmt->error;
631 $this->errorno = $stmt->errno;
639 foreach (array_keys($args) as $param) {
640 if (is_int($args[$param])) {
642 } elseif (is_float($args[$param])) {
644 } elseif (is_string($args[$param])) {
646 } elseif (is_object($args[$param]) && method_exists($args[$param], '__toString')) {
648 $args[$param] = (string)$args[$param];
652 $values[] = &$args[$param];
655 if (count($values) > 0) {
656 array_unshift($values, $param_types);
657 call_user_func_array([$stmt, 'bind_param'], $values);
660 if (!$stmt->execute()) {
661 $this->error = $this->connection->error;
662 $this->errorno = $this->connection->errno;
666 $stmt->store_result();
668 $this->affected_rows = $retval->affected_rows;
673 // See issue https://github.com/friendica/friendica/issues/8572
674 // Ensure that we always get an error message on an error.
675 if ($is_error && empty($this->errorno)) {
679 if ($is_error && empty($this->error)) {
680 $this->error = 'Unknown database error';
683 // We are having an own error logging in the function "e"
684 if (($this->errorno != 0) && !$called_from_e) {
685 // We have to preserve the error code, somewhere in the logging it get lost
686 $error = $this->error;
687 $errorno = $this->errorno;
689 if ($this->testmode) {
690 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
693 $this->logger->error('DB Error', [
696 'callstack' => System::callstack(8),
697 'params' => $this->replaceParameters($sql, $args),
700 // On a lost connection we try to reconnect - but only once.
701 if ($errorno == 2006) {
702 if ($this->in_retrial || !$this->reconnect()) {
703 // It doesn't make sense to continue when the database connection was lost
704 if ($this->in_retrial) {
705 $this->logger->notice('Giving up retrial because of database error', [
710 $this->logger->notice('Couldn\'t reconnect after database error', [
718 $this->logger->notice('Reconnected after database error', [
722 $this->in_retrial = true;
723 $ret = $this->p($sql, $args);
724 $this->in_retrial = false;
729 $this->error = $error;
730 $this->errorno = (int) $errorno;
733 $this->profiler->stopRecording();
735 if ($this->configCache->get('system', 'db_log')) {
736 $stamp2 = microtime(true);
737 $duration = (float)($stamp2 - $stamp1);
739 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
740 $duration = round($duration, 3);
741 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
743 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
744 basename($backtrace[1]["file"]) . "\t" .
745 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
746 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
753 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
755 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
757 * @param string $sql SQL statement
759 * @return boolean Was the query successfull? False is returned only if an error occurred
762 public function e(string $sql): bool
766 $this->profiler->startRecording('database_write');
768 $params = DBA::getParam(func_get_args());
770 // In a case of a deadlock we are repeating the query 20 times
774 $stmt = $this->p($sql, $params);
776 if (is_bool($stmt)) {
778 } elseif (is_object($stmt)) {
786 } while (($this->errorno == 1213) && (--$timeout > 0));
788 if ($this->errorno != 0) {
789 // We have to preserve the error code, somewhere in the logging it get lost
790 $error = $this->error;
791 $errorno = $this->errorno;
793 if ($this->testmode) {
794 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
797 $this->logger->error('DB Error', [
800 'callstack' => System::callstack(8),
801 'params' => $this->replaceParameters($sql, $params),
804 // On a lost connection we simply quit.
805 // A reconnect like in $this->p could be dangerous with modifications
806 if ($errorno == 2006) {
807 $this->logger->notice('Giving up because of database error', [
814 $this->error = $error;
815 $this->errorno = $errorno;
818 $this->profiler->stopRecording();
824 * Check if data exists
826 * @param string $table Table name in format schema.table (while scheme is optiona)
827 * @param array $condition Array of fields for condition
829 * @return boolean Are there rows for that condition?
831 * @todo Please unwrap the DBStructure::existsTable() call so this method has one behavior only: checking existence on records
833 public function exists(string $table, array $condition): bool
841 if (empty($condition)) {
842 return DBStructure::existsTable($table);
846 $first_key = key($condition);
847 if (!is_int($first_key)) {
848 $fields = [$first_key];
851 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
853 if (is_bool($stmt)) {
856 $retval = ($this->numRows($stmt) > 0);
865 * Fetches the first row
867 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
869 * Fetches the first row
871 * @param string $sql SQL statement
873 * @return array|bool first row of query or false on failure
876 public function fetchFirst(string $sql)
878 $params = DBA::getParam(func_get_args());
880 $stmt = $this->p($sql, $params);
882 if (is_bool($stmt)) {
885 $retval = $this->fetch($stmt);
894 * Returns the number of affected rows of the last statement
896 * @return int Number of rows
898 public function affectedRows(): int
900 return $this->affected_rows;
904 * Returns the number of columns of a statement
906 * @param object Statement object
908 * @return int Number of columns
910 public function columnCount($stmt): int
912 if (!is_object($stmt)) {
915 switch ($this->driver) {
917 return $stmt->columnCount();
919 return $stmt->field_count;
925 * Returns the number of rows of a statement
927 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
929 * @return int Number of rows
931 public function numRows($stmt): int
933 if (!is_object($stmt)) {
936 switch ($this->driver) {
938 return $stmt->rowCount();
940 return $stmt->num_rows;
948 * @param bool|PDOStatement|mysqli_stmt $stmt statement object
950 * @return array|bool Current row or false on failure
952 public function fetch($stmt)
954 $this->profiler->startRecording('database');
958 if (!is_object($stmt)) {
962 switch ($this->driver) {
964 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
965 if (!empty($stmt->table) && is_array($columns)) {
966 $columns = $this->castFields($stmt->table, $columns);
970 if (get_class($stmt) == 'mysqli_result') {
971 $columns = $stmt->fetch_assoc() ?? false;
975 // This code works, but is slow
977 // Bind the result to a result array
981 for ($x = 0; $x < $stmt->field_count; $x++) {
982 $cols[] = &$cols_num[$x];
985 call_user_func_array([$stmt, 'bind_result'], $cols);
987 if (!$stmt->fetch()) {
992 // We need to get the field names for the array keys
993 // It seems that there is no better way to do this.
994 $result = $stmt->result_metadata();
995 $fields = $result->fetch_fields();
997 foreach ($cols_num as $param => $col) {
998 $columns[$fields[$param]->name] = $col;
1002 $this->profiler->stopRecording();
1008 * Insert a row into a table. Field value objects will be cast as string.
1010 * @param string $table Table name in format schema.table (while scheme is optiona)
1011 * @param array $param parameter array
1012 * @param int $duplicate_mode What to do on a duplicated entry
1014 * @return boolean was the insert successful?
1015 * @throws \Exception
1017 public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1019 if (empty($table) || empty($param)) {
1020 $this->logger->info('Table and fields have to be set');
1024 $param = $this->castFields($table, $param);
1026 $table_string = DBA::buildTableString([$table]);
1028 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1030 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1034 if ($duplicate_mode == self::INSERT_IGNORE) {
1038 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1040 if ($duplicate_mode == self::INSERT_UPDATE) {
1041 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1043 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1045 $values = array_values($param);
1046 $param = array_merge_recursive($values, $values);
1049 $result = $this->e($sql, $param);
1050 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1054 return $this->affectedRows() != 0;
1058 * Inserts a row with the provided data in the provided table.
1059 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1061 * @param string $table Table name in format schema.table (while scheme is optiona)
1062 * @param array $param parameter array
1063 * @return boolean was the insert successful?
1064 * @throws \Exception
1066 public function replace(string $table, array $param): bool
1068 if (empty($table) || empty($param)) {
1069 $this->logger->info('Table and fields have to be set');
1073 $param = $this->castFields($table, $param);
1075 $table_string = DBA::buildTableString([$table]);
1077 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1079 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1081 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1083 return $this->e($sql, $param);
1087 * Fetch the id of the last insert command
1089 * @return integer Last inserted id
1091 public function lastInsertId(): int
1093 switch ($this->driver) {
1095 $id = $this->connection->lastInsertId();
1098 $id = $this->connection->insert_id;
1105 * Locks a table for exclusive write access
1107 * This function can be extended in the future to accept a table array as well.
1109 * @param string $table Table name in format schema.table (while scheme is optiona)
1110 * @return boolean was the lock successful?
1111 * @throws \Exception
1113 public function lock(string $table): bool
1115 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1116 if ($this->driver == self::PDO) {
1117 $this->e("SET autocommit=0");
1118 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1120 $this->connection->autocommit(false);
1123 $success = $this->e("LOCK TABLES " . DBA::buildTableString([$table]) . " WRITE");
1125 if ($this->driver == self::PDO) {
1126 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1130 if ($this->driver == self::PDO) {
1131 $this->e("SET autocommit=1");
1133 $this->connection->autocommit(true);
1136 $this->in_transaction = true;
1142 * Unlocks all locked tables
1144 * @return boolean was the unlock successful?
1145 * @throws \Exception
1147 public function unlock(): bool
1149 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1150 $this->performCommit();
1152 if ($this->driver == self::PDO) {
1153 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1156 $success = $this->e("UNLOCK TABLES");
1158 if ($this->driver == self::PDO) {
1159 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1160 $this->e("SET autocommit=1");
1162 $this->connection->autocommit(true);
1165 $this->in_transaction = false;
1170 * Starts a transaction
1172 * @return boolean Was the command executed successfully?
1174 public function transaction(): bool
1176 if (!$this->performCommit()) {
1180 switch ($this->driver) {
1182 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1188 if (!$this->connection->begin_transaction()) {
1194 $this->in_transaction = true;
1199 * Performs the commit
1201 * @return boolean Was the command executed successfully?
1203 protected function performCommit(): bool
1205 switch ($this->driver) {
1207 if (!$this->connection->inTransaction()) {
1211 return $this->connection->commit();
1214 return $this->connection->commit();
1223 * @return boolean Was the command executed successfully?
1225 public function commit(): bool
1227 if (!$this->performCommit()) {
1230 $this->in_transaction = false;
1237 * @return boolean Was the command executed successfully?
1239 public function rollback(): bool
1243 switch ($this->driver) {
1245 if (!$this->connection->inTransaction()) {
1249 $ret = $this->connection->rollBack();
1253 $ret = $this->connection->rollback();
1257 $this->in_transaction = false;
1262 * Delete a row from a table
1264 * @param string $table Table name
1265 * @param array $conditions Field condition(s)
1267 * @return boolean was the delete successful?
1268 * @throws \Exception
1270 public function delete(string $table, array $conditions): bool
1272 if (empty($table) || empty($conditions)) {
1273 $this->logger->info('Table and conditions have to be set');
1277 $table_string = DBA::buildTableString([$table]);
1279 $condition_string = DBA::buildCondition($conditions);
1281 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1282 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1283 return $this->e($sql, $conditions);
1287 * Updates rows in the database. Field value objects will be cast as string.
1289 * When $old_fields is set to an array,
1290 * the system will only do an update if the fields in that array changed.
1293 * Only the values in $old_fields are compared.
1294 * This is an intentional behaviour.
1297 * We include the timestamp field in $fields but not in $old_fields.
1298 * Then the row will only get the new timestamp when the other fields had changed.
1300 * When $old_fields is set to a boolean value the system will do this compare itself.
1301 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1304 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1305 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1307 * @param string $table Table name in format schema.table (while scheme is optiona)
1308 * @param array $fields contains the fields that are updated
1309 * @param array $condition condition array with the key values
1310 * @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)
1311 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1313 * @return boolean was the update successfull?
1314 * @throws \Exception
1315 * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1317 public function update(string $table, array $fields, array $condition, $old_fields = [], array $params = [])
1319 if (empty($table) || empty($fields) || empty($condition)) {
1320 $this->logger->info('Table, fields and condition have to be set');
1324 if (is_bool($old_fields)) {
1325 $do_insert = $old_fields;
1327 $old_fields = $this->selectFirst($table, [], $condition);
1329 if (is_bool($old_fields)) {
1331 $values = array_merge($condition, $fields);
1332 return $this->replace($table, $values);
1338 foreach ($old_fields as $fieldname => $content) {
1339 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1340 unset($fields[$fieldname]);
1344 if (count($fields) == 0) {
1348 $fields = $this->castFields($table, $fields);
1350 $table_string = DBA::buildTableString([$table]);
1352 $condition_string = DBA::buildCondition($condition);
1354 if (!empty($params['ignore'])) {
1355 $ignore = 'IGNORE ';
1360 $sql = "UPDATE " . $ignore . $table_string . " SET "
1361 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1362 . $condition_string;
1364 // Combines the updated fields parameter values with the condition parameter values
1365 $params = array_merge(array_values($fields), $condition);
1367 return $this->e($sql, $params);
1371 * Retrieve a single record from a table and returns it in an associative array
1373 * @param string $table Table name in format schema.table (while scheme is optiona)
1374 * @param array $fields Array of selected fields, empty for all
1375 * @param array $condition Array of fields for condition
1376 * @param array $params Array of several parameters
1378 * @return bool|array
1379 * @throws \Exception
1380 * @see $this->select
1382 public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1384 $params['limit'] = 1;
1385 $result = $this->select($table, $fields, $condition, $params);
1387 if (is_bool($result)) {
1390 $row = $this->fetch($result);
1391 $this->close($result);
1397 * Select rows from a table and fills an array with the data
1399 * @param string $table Table name in format schema.table (while scheme is optiona)
1400 * @param array $fields Array of selected fields, empty for all
1401 * @param array $condition Array of fields for condition
1402 * @param array $params Array of several parameters
1403 * @return array Data array
1404 * @throws \Exception
1407 public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1409 return $this->toArray($this->select($table, $fields, $condition, $params));
1413 * Escape fields, adding special treatment for "group by" handling
1415 * @param array $fields
1416 * @param array $options
1417 * @return array Escaped fields
1419 private function escapeFields(array $fields, array $options): array
1421 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1422 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1423 // Otherwise MySQL would report errors.
1424 if (!empty($options['group_by']) && !empty($options['order'])) {
1425 foreach ($options['order'] as $key => $field) {
1426 if (!is_int($key)) {
1427 if (!in_array($key, $fields)) {
1431 if (!in_array($field, $fields)) {
1438 array_walk($fields, function(&$value, $key) use ($options)
1441 $value = '`' . str_replace('`', '``', $value) . '`';
1443 if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1444 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1452 * Select rows from a table
1458 * $table = ['schema' => 'table'];
1459 * @see DBA::buildTableString()
1461 * $fields = ['id', 'uri', 'uid', 'network'];
1463 * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1465 * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1466 * @see DBA::buildCondition()
1468 * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1469 * @see DBA::buildParameter()
1471 * $data = DBA::select($table, $fields, $condition, $params);
1473 * @param string $table Table name in format schema.table (while scheme is optiona)
1474 * @param array $fields Array of selected fields, empty for all
1475 * @param array $condition Array of fields for condition
1476 * @param array $params Array of several parameters
1477 * @return boolean|object
1478 * @throws \Exception
1480 public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1482 if (empty($table)) {
1486 if (count($fields) > 0) {
1487 $fields = $this->escapeFields($fields, $params);
1488 $select_string = implode(', ', $fields);
1490 $select_string = '*';
1493 $table_string = DBA::buildTableString([$table]);
1495 $condition_string = DBA::buildCondition($condition);
1497 $param_string = DBA::buildParameter($params);
1499 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1501 $result = $this->p($sql, $condition);
1503 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1504 $result->table = $table;
1511 * Counts the rows from a table satisfying the provided condition
1513 * @param string $table Table name in format schema.table (while scheme is optiona)
1514 * @param array $condition Array of fields for condition
1515 * @param array $params Array of several parameters
1517 * @return int Count of rows
1522 * $condition = ["uid" => 1, "network" => 'dspr'];
1524 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1526 * $count = DBA::count($table, $condition);
1527 * @throws \Exception
1529 public function count(string $table, array $condition = [], array $params = []): int
1531 if (empty($table)) {
1532 throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1535 $table_string = DBA::buildTableString([$table]);
1537 $condition_string = DBA::buildCondition($condition);
1539 if (empty($params['expression'])) {
1541 } elseif (!empty($params['distinct'])) {
1542 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1544 $expression = DBA::quoteIdentifier($params['expression']);
1547 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1549 $row = $this->fetchFirst($sql, $condition);
1551 if (!isset($row['count'])) {
1552 $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1555 return (int)$row['count'];
1560 * Fills an array with data from a query
1562 * @param object $stmt statement object
1563 * @param bool $do_close Close database connection after last row
1564 * @param int $count maximum number of rows to be fetched
1566 * @return array Data array
1568 public function toArray($stmt, bool $do_close = true, int $count = 0): array
1570 if (is_bool($stmt)) {
1575 while ($row = $this->fetch($stmt)) {
1577 if (($count != 0) && (count($data) == $count)) {
1583 $this->close($stmt);
1590 * Cast field types according to the table definition
1592 * @param string $table
1593 * @param array $fields
1594 * @return array casted fields
1596 public function castFields(string $table, array $fields): array
1598 // When there is no data, we don't need to do something
1599 if (empty($fields)) {
1603 // We only need to cast fields with PDO
1604 if ($this->driver != self::PDO) {
1608 // We only need to cast when emulating the prepares
1609 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1615 $tables = $this->dbaDefinition->getAll();
1616 if (empty($tables[$table])) {
1617 // When a matching table wasn't found we check if it is a view
1618 $views = $this->viewDefinition->getAll();
1619 if (empty($views[$table])) {
1623 foreach (array_keys($fields) as $field) {
1624 if (!empty($views[$table]['fields'][$field])) {
1625 $viewdef = $views[$table]['fields'][$field];
1626 if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1627 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1632 foreach ($tables[$table]['fields'] as $field => $definition) {
1633 $types[$field] = $definition['type'];
1637 foreach ($fields as $field => $content) {
1638 if (is_null($content) || empty($types[$field])) {
1642 if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1643 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1644 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1645 $fields[$field] = (int)$content;
1647 if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1648 $fields[$field] = (float)$content;
1656 * Returns the error number of the last query
1658 * @return string Error number (0 if no error)
1660 public function errorNo(): int
1662 return $this->errorno;
1666 * Returns the error message of the last query
1668 * @return string Error message ('' if no error)
1670 public function errorMessage(): string
1672 return $this->error;
1676 * Closes the current statement
1678 * @param object $stmt statement object
1680 * @return boolean was the close successful?
1682 public function close($stmt): bool
1685 $this->profiler->startRecording('database');
1687 if (!is_object($stmt)) {
1691 switch ($this->driver) {
1693 $ret = $stmt->closeCursor();
1696 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1697 // We should be careful not to assume the object type of $stmt
1698 // because DBA::p() has been able to return both types.
1699 if ($stmt instanceof mysqli_stmt) {
1700 $stmt->free_result();
1701 $ret = $stmt->close();
1702 } elseif ($stmt instanceof mysqli_result) {
1711 $this->profiler->stopRecording();
1717 * Return a list of database processes
1720 * 'list' => List of processes, separated in their different states
1721 * 'amount' => Number of concurrent database processes
1722 * @throws \Exception
1724 public function processlist(): array
1726 $ret = $this->p('SHOW PROCESSLIST');
1727 $data = $this->toArray($ret);
1731 foreach ($data as $process) {
1732 $state = trim($process['State']);
1734 // Filter out all non blocking processes
1735 if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1742 foreach ($states as $state => $usage) {
1743 if ($statelist != '') {
1746 $statelist .= $state . ': ' . $usage;
1748 return (['list' => $statelist, 'amount' => $processes]);
1752 * Fetch a database variable
1754 * @param string $name
1755 * @return string|null content or null if inexistent
1756 * @throws \Exception
1758 public function getVariable(string $name)
1760 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1761 return $result['Value'] ?? null;
1765 * Checks if $array is a filled array with at least one entry.
1767 * @param mixed $array A filled array with at least one entry
1768 * @return boolean Whether $array is a filled array or an object with rows
1770 public function isResult($array): bool
1772 // It could be a return value from an update statement
1773 if (is_bool($array)) {
1777 if (is_object($array)) {
1778 return $this->numRows($array) > 0;
1781 return (is_array($array) && (count($array) > 0));
1785 * Callback function for "esc_array"
1787 * @param mixed $value Array value
1788 * @param string $key Array key
1789 * @param boolean $add_quotation add quotation marks for string values
1792 private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1794 if (!$add_quotation) {
1795 if (is_bool($value)) {
1796 $value = ($value ? '1' : '0');
1798 $value = $this->escape($value);
1803 if (is_bool($value)) {
1804 $value = ($value ? 'true' : 'false');
1805 } elseif (is_float($value) || is_integer($value)) {
1806 $value = (string)$value;
1808 $value = "'" . $this->escape($value) . "'";
1813 * Escapes a whole array
1815 * @param mixed $arr Array with values to be escaped
1816 * @param boolean $add_quotation add quotation marks for string values
1819 public function escapeArray(&$arr, bool $add_quotation = false)
1821 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1825 * Replaces a string in the provided fields of the provided table
1827 * @param string $table Table name
1828 * @param array $fields List of field names in the provided table
1829 * @param string $search String to search for
1830 * @param string $replace String to replace with
1832 * @throws \Exception
1834 public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1836 $search = $this->escape($search);
1837 $replace = $this->escape($replace);
1840 foreach ($fields as $field) {
1841 $field = DBA::quoteIdentifier($field);
1842 $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1845 $upds = implode(', ', $upd);
1847 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1849 if (!$this->isResult($r)) {
1850 throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());