3 namespace Friendica\Database;
5 use Friendica\Core\Config\Cache;
6 use Friendica\Core\System;
7 use Friendica\Network\HTTPException\InternalServerErrorException;
8 use Friendica\Util\DateTimeFormat;
9 use Friendica\Util\Profiler;
16 use Psr\Log\LoggerInterface;
19 * @class MySQL database class
21 * This class is for the low level database stuff that does driver specific things.
25 protected $connected = false;
30 protected $configCache;
36 * @var LoggerInterface
39 protected $server_info = '';
40 /** @var PDO|mysqli */
41 protected $connection;
43 private $error = false;
45 private $affected_rows = 0;
46 protected $in_transaction = false;
47 protected $in_retrial = false;
48 private $relation = [];
50 public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
52 // We are storing these values for being able to perform a reconnect
53 $this->configCache = $configCache;
54 $this->profiler = $profiler;
55 $this->logger = $logger;
57 $this->readServerVariables($server);
60 if ($this->isConnected()) {
61 // Loads DB_UPDATE_VERSION constant
62 DBStructure::definition($configCache->get('system', 'basepath'), false);
66 private function readServerVariables(array $server)
68 // Use environment variables for mysql if they are set beforehand
69 if (!empty($server['MYSQL_HOST'])
70 && (!empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER'])))
71 && $server['MYSQL_PASSWORD'] !== false
72 && !empty($server['MYSQL_DATABASE']))
74 $db_host = $server['MYSQL_HOST'];
75 if (!empty($server['MYSQL_PORT'])) {
76 $db_host .= ':' . $server['MYSQL_PORT'];
78 $this->configCache->set('database', 'hostname', $db_host);
80 if (!empty($server['MYSQL_USERNAME'])) {
81 $this->configCache->set('database', 'username', $server['MYSQL_USERNAME']);
83 $this->configCache->set('database', 'username', $server['MYSQL_USER']);
85 $this->configCache->set('database', 'password', (string) $server['MYSQL_PASSWORD']);
86 $this->configCache->set('database', 'database', $server['MYSQL_DATABASE']);
90 public function connect()
92 if (!is_null($this->connection) && $this->connected()) {
93 return $this->connected;
96 // Reset connected state
97 $this->connected = false;
100 $serveraddr = trim($this->configCache->get('database', 'hostname'));
101 $serverdata = explode(':', $serveraddr);
102 $server = $serverdata[0];
103 if (count($serverdata) > 1) {
104 $port = trim($serverdata[1]);
106 $server = trim($server);
107 $user = trim($this->configCache->get('database', 'username'));
108 $pass = trim($this->configCache->get('database', 'password'));
109 $db = trim($this->configCache->get('database', 'database'));
110 $charset = trim($this->configCache->get('database', 'charset'));
112 if (!(strlen($server) && strlen($user))) {
116 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
117 $this->driver = 'pdo';
118 $connect = "mysql:host=" . $server . ";dbname=" . $db;
121 $connect .= ";port=" . $port;
125 $connect .= ";charset=" . $charset;
129 $this->connection = @new PDO($connect, $user, $pass);
130 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
131 $this->connected = true;
132 } catch (PDOException $e) {
133 $this->connected = false;
137 if (!$this->connected && class_exists('\mysqli')) {
138 $this->driver = 'mysqli';
141 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
143 $this->connection = @new mysqli($server, $user, $pass, $db);
146 if (!mysqli_connect_errno()) {
147 $this->connected = true;
150 $this->connection->set_charset($charset);
155 // No suitable SQL driver was found.
156 if (!$this->connected) {
157 $this->driver = null;
158 $this->connection = null;
161 return $this->connected;
165 * Sets the logger for DBA
167 * @note this is necessary because if we want to load the logger configuration
168 * from the DB, but there's an error, we would print out an exception.
169 * So the logger gets updated after the logger configuration can be retrieved
172 * @param LoggerInterface $logger
174 public function setLogger(LoggerInterface $logger)
176 $this->logger = $logger;
180 * Sets the profiler for DBA
182 * @param Profiler $profiler
184 public function setProfiler(Profiler $profiler)
186 $this->profiler = $profiler;
189 * Disconnects the current database connection
191 public function disconnect()
193 if (!is_null($this->connection)) {
194 switch ($this->driver) {
196 $this->connection = null;
199 $this->connection->close();
200 $this->connection = null;
205 $this->driver = null;
206 $this->connected = false;
210 * Perform a reconnect of an existing database connection
212 public function reconnect()
215 return $this->connect();
219 * Return the database object.
223 public function getConnection()
225 return $this->connection;
229 * Returns the MySQL server version string
231 * This function discriminate between the deprecated mysql API and the current
232 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
236 public function serverInfo()
238 if ($this->server_info == '') {
239 switch ($this->driver) {
241 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
244 $this->server_info = $this->connection->server_info;
248 return $this->server_info;
252 * Returns the selected database name
257 public function databaseName()
259 $ret = $this->p("SELECT DATABASE() AS `db`");
260 $data = $this->toArray($ret);
261 return $data[0]['db'];
265 * Analyze a database query and log this if some conditions are met.
267 * @param string $query The database query that will be analyzed
271 private function logIndex($query)
274 if (!$this->configCache->get('system', 'db_log_index')) {
278 // Don't explain an explain statement
279 if (strtolower(substr($query, 0, 7)) == "explain") {
283 // Only do the explain on "select", "update" and "delete"
284 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
288 $r = $this->p("EXPLAIN " . $query);
289 if (!$this->isResult($r)) {
293 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
294 $blacklist = explode(',', $this->configCache->get('system', 'db_log_index_blacklist'));
296 while ($row = $this->fetch($r)) {
297 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
298 $log = (in_array($row['key'], $watchlist) &&
299 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
304 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
308 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
313 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
314 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
315 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
316 basename($backtrace[1]["file"]) . "\t" .
317 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
318 substr($query, 0, 2000) . "\n", FILE_APPEND);
324 * Removes every not whitelisted character from the identifier string
326 * @param string $identifier
328 * @return string sanitized identifier
331 private function sanitizeIdentifier($identifier)
333 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
336 public function escape($str)
338 if ($this->connected) {
339 switch ($this->driver) {
341 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
344 return @$this->connection->real_escape_string($str);
347 return str_replace("'", "\\'", $str);
351 public function isConnected()
353 return $this->connected;
356 public function connected()
360 if (is_null($this->connection)) {
364 switch ($this->driver) {
366 $r = $this->p("SELECT 1");
367 if ($this->isResult($r)) {
368 $row = $this->toArray($r);
369 $connected = ($row[0]['1'] == '1');
373 $connected = $this->connection->ping();
381 * Replaces ANY_VALUE() function by MIN() function,
382 * if the database server does not support ANY_VALUE().
384 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
385 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
386 * A standard fall-back is to use MIN().
388 * @param string $sql An SQL string without the values
390 * @return string The input SQL string modified if necessary.
392 public function anyValueFallback($sql)
394 $server_info = $this->serverInfo();
395 if (version_compare($server_info, '5.7.5', '<') ||
396 (stripos($server_info, 'MariaDB') !== false)) {
397 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
403 * Replaces the ? placeholders with the parameters in the $args array
405 * @param string $sql SQL query
406 * @param array $args The parameters that are to replace the ? placeholders
408 * @return string The replaced SQL query
410 private function replaceParameters($sql, $args)
413 foreach ($args AS $param => $value) {
414 if (is_int($args[$param]) || is_float($args[$param])) {
415 $replace = intval($args[$param]);
417 $replace = "'" . $this->escape($args[$param]) . "'";
420 $pos = strpos($sql, '?', $offset);
421 if ($pos !== false) {
422 $sql = substr_replace($sql, $replace, $pos, 1);
424 $offset = $pos + strlen($replace);
430 * Executes a prepared statement that returns data
432 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
434 * Please only use it with complicated queries.
435 * For all regular queries please use DBA::select or DBA::exists
437 * @param string $sql SQL statement
439 * @return bool|object statement object or result object
442 public function p($sql)
445 $stamp1 = microtime(true);
447 $params = DBA::getParam(func_get_args());
449 // Renumber the array keys to be sure that they fit
452 foreach ($params AS $param) {
453 // Avoid problems with some MySQL servers and boolean values. See issue #3645
454 if (is_bool($param)) {
455 $param = (int)$param;
457 $args[++$i] = $param;
460 if (!$this->connected) {
464 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
465 // Question: Should we continue or stop the query here?
466 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
469 $sql = DBA::cleanQuery($sql);
470 $sql = $this->anyValueFallback($sql);
474 if ($this->configCache->get('system', 'db_callstack') !== null) {
475 $sql = "/*" . System::callstack() . " */ " . $sql;
480 $this->affected_rows = 0;
482 // We have to make some things different if this function is called from "e"
483 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
485 if (isset($trace[1])) {
486 $called_from = $trace[1];
488 // We use just something that is defined to avoid warnings
489 $called_from = $trace[0];
491 // We are having an own error logging in the function "e"
492 $called_from_e = ($called_from['function'] == 'e');
494 if (!isset($this->connection)) {
495 throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
498 switch ($this->driver) {
500 // If there are no arguments we use "query"
501 if (count($args) == 0) {
502 if (!$retval = $this->connection->query($sql)) {
503 $errorInfo = $this->connection->errorInfo();
504 $this->error = $errorInfo[2];
505 $this->errorno = $errorInfo[1];
509 $this->affected_rows = $retval->rowCount();
513 /** @var $stmt mysqli_stmt|PDOStatement */
514 if (!$stmt = $this->connection->prepare($sql)) {
515 $errorInfo = $this->connection->errorInfo();
516 $this->error = $errorInfo[2];
517 $this->errorno = $errorInfo[1];
522 foreach ($args AS $param => $value) {
523 if (is_int($args[$param])) {
524 $data_type = PDO::PARAM_INT;
526 $data_type = PDO::PARAM_STR;
528 $stmt->bindParam($param, $args[$param], $data_type);
531 if (!$stmt->execute()) {
532 $errorInfo = $stmt->errorInfo();
533 $this->error = $errorInfo[2];
534 $this->errorno = $errorInfo[1];
538 $this->affected_rows = $retval->rowCount();
542 // There are SQL statements that cannot be executed with a prepared statement
543 $parts = explode(' ', $orig_sql);
544 $command = strtolower($parts[0]);
545 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
547 // The fallback routine is called as well when there are no arguments
548 if (!$can_be_prepared || (count($args) == 0)) {
549 $retval = $this->connection->query($this->replaceParameters($sql, $args));
550 if ($this->connection->errno) {
551 $this->error = $this->connection->error;
552 $this->errorno = $this->connection->errno;
555 if (isset($retval->num_rows)) {
556 $this->affected_rows = $retval->num_rows;
558 $this->affected_rows = $this->connection->affected_rows;
564 $stmt = $this->connection->stmt_init();
566 if (!$stmt->prepare($sql)) {
567 $this->error = $stmt->error;
568 $this->errorno = $stmt->errno;
575 foreach ($args AS $param => $value) {
576 if (is_int($args[$param])) {
578 } elseif (is_float($args[$param])) {
580 } elseif (is_string($args[$param])) {
585 $values[] = &$args[$param];
588 if (count($values) > 0) {
589 array_unshift($values, $param_types);
590 call_user_func_array([$stmt, 'bind_param'], $values);
593 if (!$stmt->execute()) {
594 $this->error = $this->connection->error;
595 $this->errorno = $this->connection->errno;
598 $stmt->store_result();
600 $this->affected_rows = $retval->affected_rows;
605 // We are having an own error logging in the function "e"
606 if (($this->errorno != 0) && !$called_from_e) {
607 // We have to preserve the error code, somewhere in the logging it get lost
608 $error = $this->error;
609 $errorno = $this->errorno;
611 $this->logger->error('DB Error', [
612 'code' => $this->errorno,
613 'error' => $this->error,
614 'callstack' => System::callstack(8),
615 'params' => $this->replaceParameters($sql, $args),
618 // On a lost connection we try to reconnect - but only once.
619 if ($errorno == 2006) {
620 if ($this->in_retrial || !$this->reconnect()) {
621 // It doesn't make sense to continue when the database connection was lost
622 if ($this->in_retrial) {
623 $this->logger->notice('Giving up retrial because of database error', [
624 'code' => $this->errorno,
625 'error' => $this->error,
628 $this->logger->notice('Couldn\'t reconnect after database error', [
629 'code' => $this->errorno,
630 'error' => $this->error,
636 $this->logger->notice('Reconnected after database error', [
637 'code' => $this->errorno,
638 'error' => $this->error,
640 $this->in_retrial = true;
641 $ret = $this->p($sql, $args);
642 $this->in_retrial = false;
647 $this->error = $error;
648 $this->errorno = $errorno;
651 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
653 if ($this->configCache->get('system', 'db_log')) {
654 $stamp2 = microtime(true);
655 $duration = (float)($stamp2 - $stamp1);
657 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
658 $duration = round($duration, 3);
659 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
661 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
662 basename($backtrace[1]["file"]) . "\t" .
663 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
664 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
671 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
673 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
675 * @param string $sql SQL statement
677 * @return boolean Was the query successfull? False is returned only if an error occurred
680 public function e($sql)
683 $stamp = microtime(true);
685 $params = DBA::getParam(func_get_args());
687 // In a case of a deadlock we are repeating the query 20 times
691 $stmt = $this->p($sql, $params);
693 if (is_bool($stmt)) {
695 } elseif (is_object($stmt)) {
703 } while (($this->errorno == 1213) && (--$timeout > 0));
705 if ($this->errorno != 0) {
706 // We have to preserve the error code, somewhere in the logging it get lost
707 $error = $this->error;
708 $errorno = $this->errorno;
710 $this->logger->error('DB Error', [
711 'code' => $this->errorno,
712 'error' => $this->error,
713 'callstack' => System::callstack(8),
714 'params' => $this->replaceParameters($sql, $params),
717 // On a lost connection we simply quit.
718 // A reconnect like in $this->p could be dangerous with modifications
719 if ($errorno == 2006) {
720 $this->logger->notice('Giving up because of database error', [
721 'code' => $this->errorno,
722 'error' => $this->error,
727 $this->error = $error;
728 $this->errorno = $errorno;
731 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
737 * Check if data exists
739 * @param string|array $table Table name or array [schema => table]
740 * @param array $condition array of fields for condition
742 * @return boolean Are there rows for that condition?
745 public function exists($table, $condition)
753 if (empty($condition)) {
754 return DBStructure::existsTable($table);
758 $first_key = key($condition);
759 if (!is_int($first_key)) {
760 $fields = [$first_key];
763 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
765 if (is_bool($stmt)) {
768 $retval = ($this->numRows($stmt) > 0);
777 * Fetches the first row
779 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
781 * Fetches the first row
783 * @param string $sql SQL statement
785 * @return array first row of query
788 public function fetchFirst($sql)
790 $params = DBA::getParam(func_get_args());
792 $stmt = $this->p($sql, $params);
794 if (is_bool($stmt)) {
797 $retval = $this->fetch($stmt);
806 * Returns the number of affected rows of the last statement
808 * @return int Number of rows
810 public function affectedRows()
812 return $this->affected_rows;
816 * Returns the number of columns of a statement
818 * @param object Statement object
820 * @return int Number of columns
822 public function columnCount($stmt)
824 if (!is_object($stmt)) {
827 switch ($this->driver) {
829 return $stmt->columnCount();
831 return $stmt->field_count;
837 * Returns the number of rows of a statement
839 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
841 * @return int Number of rows
843 public function numRows($stmt)
845 if (!is_object($stmt)) {
848 switch ($this->driver) {
850 return $stmt->rowCount();
852 return $stmt->num_rows;
860 * @param mixed $stmt statement object
862 * @return array current row
864 public function fetch($stmt)
867 $stamp1 = microtime(true);
871 if (!is_object($stmt)) {
875 switch ($this->driver) {
877 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
880 if (get_class($stmt) == 'mysqli_result') {
881 $columns = $stmt->fetch_assoc();
885 // This code works, but is slow
887 // Bind the result to a result array
891 for ($x = 0; $x < $stmt->field_count; $x++) {
892 $cols[] = &$cols_num[$x];
895 call_user_func_array([$stmt, 'bind_result'], $cols);
897 if (!$stmt->fetch()) {
902 // We need to get the field names for the array keys
903 // It seems that there is no better way to do this.
904 $result = $stmt->result_metadata();
905 $fields = $result->fetch_fields();
907 foreach ($cols_num AS $param => $col) {
908 $columns[$fields[$param]->name] = $col;
912 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
918 * Insert a row into a table
920 * @param string|array $table Table name or array [schema => table]
921 * @param array $param parameter array
922 * @param bool $on_duplicate_update Do an update on a duplicate entry
924 * @return boolean was the insert successful?
927 public function insert($table, $param, $on_duplicate_update = false)
929 if (empty($table) || empty($param)) {
930 $this->logger->info('Table and fields have to be set');
934 $table_string = DBA::buildTableString($table);
936 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
938 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
940 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
942 if ($on_duplicate_update) {
943 $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
945 $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
947 $values = array_values($param);
948 $param = array_merge_recursive($values, $values);
951 return $this->e($sql, $param);
955 * Fetch the id of the last insert command
957 * @return integer Last inserted id
959 public function lastInsertId()
961 switch ($this->driver) {
963 $id = $this->connection->lastInsertId();
966 $id = $this->connection->insert_id;
973 * Locks a table for exclusive write access
975 * This function can be extended in the future to accept a table array as well.
977 * @param string|array $table Table name or array [schema => table]
979 * @return boolean was the lock successful?
982 public function lock($table)
984 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
985 if ($this->driver == 'pdo') {
986 $this->e("SET autocommit=0");
987 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
989 $this->connection->autocommit(false);
992 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
994 if ($this->driver == 'pdo') {
995 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
999 if ($this->driver == 'pdo') {
1000 $this->e("SET autocommit=1");
1002 $this->connection->autocommit(true);
1005 $this->in_transaction = true;
1011 * Unlocks all locked tables
1013 * @return boolean was the unlock successful?
1014 * @throws \Exception
1016 public function unlock()
1018 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1019 $this->performCommit();
1021 if ($this->driver == 'pdo') {
1022 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1025 $success = $this->e("UNLOCK TABLES");
1027 if ($this->driver == 'pdo') {
1028 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1029 $this->e("SET autocommit=1");
1031 $this->connection->autocommit(true);
1034 $this->in_transaction = false;
1039 * Starts a transaction
1041 * @return boolean Was the command executed successfully?
1043 public function transaction()
1045 if (!$this->performCommit()) {
1049 switch ($this->driver) {
1051 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1057 if (!$this->connection->begin_transaction()) {
1063 $this->in_transaction = true;
1067 protected function performCommit()
1069 switch ($this->driver) {
1071 if (!$this->connection->inTransaction()) {
1075 return $this->connection->commit();
1078 return $this->connection->commit();
1087 * @return boolean Was the command executed successfully?
1089 public function commit()
1091 if (!$this->performCommit()) {
1094 $this->in_transaction = false;
1101 * @return boolean Was the command executed successfully?
1103 public function rollback()
1107 switch ($this->driver) {
1109 if (!$this->connection->inTransaction()) {
1113 $ret = $this->connection->rollBack();
1117 $ret = $this->connection->rollback();
1120 $this->in_transaction = false;
1125 * Build the array with the table relations
1127 * The array is build from the database definitions in DBStructure.php
1129 * This process must only be started once, since the value is cached.
1131 private function buildRelationData()
1133 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1135 foreach ($definition AS $table => $structure) {
1136 foreach ($structure['fields'] AS $field => $field_struct) {
1137 if (isset($field_struct['relation'])) {
1138 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1139 $this->relation[$rel_table][$rel_field][$table][] = $field;
1147 * Delete a row from a table
1149 * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1151 * @param string $table Table name
1152 * @param array $conditions Field condition(s)
1153 * @param array $options
1154 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1155 * relations (default: true)
1156 * @param array $callstack Internal use: prevent endless loops
1158 * @return boolean was the delete successful?
1159 * @throws \Exception
1161 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1163 if (empty($table) || empty($conditions)) {
1164 $this->logger->info('Table and conditions have to be set');
1170 // Create a key for the loop prevention
1171 $key = $table . ':' . json_encode($conditions);
1173 // We quit when this key already exists in the callstack.
1174 if (isset($callstack[$key])) {
1178 $callstack[$key] = true;
1180 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1182 // Don't use "defaults" here, since it would set "false" to "true"
1183 if (isset($options['cascade'])) {
1184 $cascade = $options['cascade'];
1189 // To speed up the whole process we cache the table relations
1190 if ($cascade && count($this->relation) == 0) {
1191 $this->buildRelationData();
1194 // Is there a relation entry for the table?
1195 if ($cascade && isset($this->relation[$table])) {
1196 // We only allow a simple "one field" relation.
1197 $field = array_keys($this->relation[$table])[0];
1198 $rel_def = array_values($this->relation[$table])[0];
1200 // Create a key for preventing double queries
1201 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1203 // When the search field is the relation field, we don't need to fetch the rows
1204 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1205 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1206 foreach ($rel_def AS $rel_table => $rel_fields) {
1207 foreach ($rel_fields AS $rel_field) {
1208 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1211 // We quit when this key already exists in the callstack.
1212 } elseif (!isset($callstack[$qkey])) {
1213 $callstack[$qkey] = true;
1215 // Fetch all rows that are to be deleted
1216 $data = $this->select($table, [$field], $conditions);
1218 while ($row = $this->fetch($data)) {
1219 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1222 $this->close($data);
1224 // Since we had split the delete command we don't need the original command anymore
1225 unset($commands[$key]);
1229 // Now we finalize the process
1230 $do_transaction = !$this->in_transaction;
1232 if ($do_transaction) {
1233 $this->transaction();
1239 foreach ($commands AS $command) {
1240 $conditions = $command['conditions'];
1242 $first_key = key($conditions);
1244 $condition_string = DBA::buildCondition($conditions);
1246 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1247 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1248 $this->logger->debug($this->replaceParameters($sql, $conditions));
1250 if (!$this->e($sql, $conditions)) {
1251 if ($do_transaction) {
1257 $key_table = $command['table'];
1258 $key_condition = array_keys($command['conditions'])[0];
1259 $value = array_values($command['conditions'])[0];
1261 // Split the SQL queries in chunks of 100 values
1262 // We do the $i stuff here to make the code better readable
1263 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1264 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1268 $compacted[$key_table][$key_condition][$i][$value] = $value;
1269 $counter[$key_table][$key_condition] = $i;
1272 foreach ($compacted AS $table => $values) {
1273 foreach ($values AS $field => $field_value_list) {
1274 foreach ($field_value_list AS $field_values) {
1275 $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1276 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1278 $this->logger->debug($this->replaceParameters($sql, $field_values));
1280 if (!$this->e($sql, $field_values)) {
1281 if ($do_transaction) {
1289 if ($do_transaction) {
1298 * Updates rows in the database. When $old_fields is set to an array,
1299 * the system will only do an update if the fields in that array changed.
1302 * Only the values in $old_fields are compared.
1303 * This is an intentional behaviour.
1306 * We include the timestamp field in $fields but not in $old_fields.
1307 * Then the row will only get the new timestamp when the other fields had changed.
1309 * When $old_fields is set to a boolean value the system will do this compare itself.
1310 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1313 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1314 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1316 * @param string|array $table Table name or array [schema => table]
1317 * @param array $fields contains the fields that are updated
1318 * @param array $condition condition array with the key values
1319 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1321 * @return boolean was the update successfull?
1322 * @throws \Exception
1324 public function update($table, $fields, $condition, $old_fields = [])
1326 if (empty($table) || empty($fields) || empty($condition)) {
1327 $this->logger->info('Table, fields and condition have to be set');
1331 if (is_bool($old_fields)) {
1332 $do_insert = $old_fields;
1334 $old_fields = $this->selectFirst($table, [], $condition);
1336 if (is_bool($old_fields)) {
1338 $values = array_merge($condition, $fields);
1339 return $this->insert($table, $values, $do_insert);
1345 foreach ($old_fields AS $fieldname => $content) {
1346 if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1347 unset($fields[$fieldname]);
1351 if (count($fields) == 0) {
1355 $table_string = DBA::buildTableString($table);
1357 $condition_string = DBA::buildCondition($condition);
1359 $sql = "UPDATE " . $table_string . " SET "
1360 . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1361 . $condition_string;
1363 // Combines the updated fields parameter values with the condition parameter values
1364 $params = array_merge(array_values($fields), $condition);
1366 return $this->e($sql, $params);
1370 * Retrieve a single record from a table and returns it in an associative array
1372 * @param string|array $table
1373 * @param array $fields
1374 * @param array $condition
1375 * @param array $params
1377 * @return bool|array
1378 * @throws \Exception
1379 * @see $this->select
1381 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1383 $params['limit'] = 1;
1384 $result = $this->select($table, $fields, $condition, $params);
1386 if (is_bool($result)) {
1389 $row = $this->fetch($result);
1390 $this->close($result);
1396 * Select rows from a table and fills an array with the data
1398 * @param string|array $table Table name or array [schema => table]
1399 * @param array $fields Array of selected fields, empty for all
1400 * @param array $condition Array of fields for condition
1401 * @param array $params Array of several parameters
1403 * @return array Data array
1404 * @throws \Exception
1407 public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1409 return $this->toArray($this->select($table, $fields, $condition, $params));
1413 * Select rows from a table
1415 * @param string|array $table Table name or array [schema => table]
1416 * @param array $fields Array of selected fields, empty for all
1417 * @param array $condition Array of fields for condition
1418 * @param array $params Array of several parameters
1420 * @return boolean|object
1424 * $fields = array("id", "uri", "uid", "network");
1426 * $condition = array("uid" => 1, "network" => 'dspr');
1428 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1430 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1432 * $data = DBA::select($table, $fields, $condition, $params);
1433 * @throws \Exception
1435 public function select($table, array $fields = [], array $condition = [], array $params = [])
1437 if (empty($table)) {
1441 if (count($fields) > 0) {
1442 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1444 $select_string = '*';
1447 $table_string = DBA::buildTableString($table);
1449 $condition_string = DBA::buildCondition($condition);
1451 $param_string = DBA::buildParameter($params);
1453 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1455 $result = $this->p($sql, $condition);
1461 * Counts the rows from a table satisfying the provided condition
1463 * @param string|array $table Table name or array [schema => table]
1464 * @param array $condition Array of fields for condition
1465 * @param array $params Array of several parameters
1472 * $condition = ["uid" => 1, "network" => 'dspr'];
1474 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1476 * $count = DBA::count($table, $condition);
1477 * @throws \Exception
1479 public function count($table, array $condition = [], array $params = [])
1481 if (empty($table)) {
1485 $table_string = DBA::buildTableString($table);
1487 $condition_string = DBA::buildCondition($condition);
1489 if (empty($params['expression'])) {
1491 } elseif (!empty($params['distinct'])) {
1492 $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1494 $expression = DBA::quoteIdentifier($params['expression']);
1497 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1499 $row = $this->fetchFirst($sql, $condition);
1501 return $row['count'];
1505 * Fills an array with data from a query
1507 * @param object $stmt statement object
1508 * @param bool $do_close
1510 * @return array Data array
1512 public function toArray($stmt, $do_close = true)
1514 if (is_bool($stmt)) {
1519 while ($row = $this->fetch($stmt)) {
1524 $this->close($stmt);
1531 * Returns the error number of the last query
1533 * @return string Error number (0 if no error)
1535 public function errorNo()
1537 return $this->errorno;
1541 * Returns the error message of the last query
1543 * @return string Error message ('' if no error)
1545 public function errorMessage()
1547 return $this->error;
1551 * Closes the current statement
1553 * @param object $stmt statement object
1555 * @return boolean was the close successful?
1557 public function close($stmt)
1560 $stamp1 = microtime(true);
1562 if (!is_object($stmt)) {
1566 switch ($this->driver) {
1568 $ret = $stmt->closeCursor();
1571 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1572 // We should be careful not to assume the object type of $stmt
1573 // because DBA::p() has been able to return both types.
1574 if ($stmt instanceof mysqli_stmt) {
1575 $stmt->free_result();
1576 $ret = $stmt->close();
1577 } elseif ($stmt instanceof mysqli_result) {
1586 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1592 * Return a list of database processes
1595 * 'list' => List of processes, separated in their different states
1596 * 'amount' => Number of concurrent database processes
1597 * @throws \Exception
1599 public function processlist()
1601 $ret = $this->p("SHOW PROCESSLIST");
1602 $data = $this->toArray($ret);
1606 foreach ($data as $process) {
1607 $state = trim($process["State"]);
1609 // Filter out all non blocking processes
1610 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1617 foreach ($states as $state => $usage) {
1618 if ($statelist != "") {
1621 $statelist .= $state . ": " . $usage;
1623 return (["list" => $statelist, "amount" => $processes]);
1627 * Checks if $array is a filled array with at least one entry.
1629 * @param mixed $array A filled array with at least one entry
1631 * @return boolean Whether $array is a filled array or an object with rows
1633 public function isResult($array)
1635 // It could be a return value from an update statement
1636 if (is_bool($array)) {
1640 if (is_object($array)) {
1641 return $this->numRows($array) > 0;
1644 return (is_array($array) && (count($array) > 0));
1648 * Callback function for "esc_array"
1650 * @param mixed $value Array value
1651 * @param string $key Array key
1652 * @param boolean $add_quotation add quotation marks for string values
1656 private function escapeArrayCallback(&$value, $key, $add_quotation)
1658 if (!$add_quotation) {
1659 if (is_bool($value)) {
1660 $value = ($value ? '1' : '0');
1662 $value = $this->escape($value);
1667 if (is_bool($value)) {
1668 $value = ($value ? 'true' : 'false');
1669 } elseif (is_float($value) || is_integer($value)) {
1670 $value = (string)$value;
1672 $value = "'" . $this->escape($value) . "'";
1677 * Escapes a whole array
1679 * @param mixed $arr Array with values to be escaped
1680 * @param boolean $add_quotation add quotation marks for string values
1684 public function escapeArray(&$arr, $add_quotation = false)
1686 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);