3 namespace Friendica\Database;
5 use Friendica\Core\Config\Cache\IConfigCache;
6 use Friendica\Core\Logger;
7 use Friendica\Core\System;
8 use Friendica\Util\DateTimeFormat;
9 use Friendica\Util\Profiler;
18 * @class MySQL database class
20 * This class is for the low level database stuff that does driver specific things.
25 * Lowest possible date value
27 const NULL_DATE = '0001-01-01';
29 * Lowest possible datetime value
31 const NULL_DATETIME = '0001-01-01 00:00:00';
33 public static $connected = false;
38 private static $configCache;
42 private static $profiler;
46 private static $basePath;
47 private static $server_info = '';
48 private static $connection;
49 private static $driver;
50 private static $error = false;
51 private static $errorno = 0;
52 private static $affected_rows = 0;
53 private static $in_transaction = false;
54 private static $in_retrial = false;
55 private static $relation = [];
56 private static $db_serveraddr = '';
57 private static $db_user = '';
58 private static $db_pass = '';
59 private static $db_name = '';
60 private static $db_charset = '';
62 public static function connect($basePath, IConfigCache $configCache, Profiler $profiler, $serveraddr, $user, $pass, $db, $charset = null)
64 if (!is_null(self::$connection) && self::connected()) {
68 // We are storing these values for being able to perform a reconnect
69 self::$basePath = $basePath;
70 self::$configCache = $configCache;
71 self::$profiler = $profiler;
72 self::$db_serveraddr = $serveraddr;
73 self::$db_user = $user;
74 self::$db_pass = $pass;
76 self::$db_charset = $charset;
79 $serveraddr = trim($serveraddr);
81 $serverdata = explode(':', $serveraddr);
82 $server = $serverdata[0];
84 if (count($serverdata) > 1) {
85 $port = trim($serverdata[1]);
88 $server = trim($server);
92 $charset = trim($charset);
94 if (!(strlen($server) && strlen($user))) {
98 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
99 self::$driver = 'pdo';
100 $connect = "mysql:host=".$server.";dbname=".$db;
103 $connect .= ";port=".$port;
107 $connect .= ";charset=".$charset;
111 self::$connection = @new PDO($connect, $user, $pass);
112 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
113 self::$connected = true;
114 } catch (PDOException $e) {
115 /// @TODO At least log exception, don't ignore it!
119 if (!self::$connected && class_exists('\mysqli')) {
120 self::$driver = 'mysqli';
123 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
125 self::$connection = @new mysqli($server, $user, $pass, $db);
128 if (!mysqli_connect_errno()) {
129 self::$connected = true;
132 self::$connection->set_charset($charset);
137 // No suitable SQL driver was found.
138 if (!self::$connected) {
139 self::$driver = null;
140 self::$connection = null;
143 return self::$connected;
147 * Disconnects the current database connection
149 public static function disconnect()
151 if (is_null(self::$connection)) {
155 switch (self::$driver) {
157 self::$connection = null;
160 self::$connection->close();
161 self::$connection = null;
167 * Perform a reconnect of an existing database connection
169 public static function reconnect() {
172 $ret = self::connect(self::$basePath, self::$configCache, self::$profiler, self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
177 * Return the database object.
180 public static function getConnection()
182 return self::$connection;
186 * @brief Returns the MySQL server version string
188 * This function discriminate between the deprecated mysql API and the current
189 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
193 public static function serverInfo() {
194 if (self::$server_info == '') {
195 switch (self::$driver) {
197 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
200 self::$server_info = self::$connection->server_info;
204 return self::$server_info;
208 * @brief Returns the selected database name
213 public static function databaseName() {
214 $ret = self::p("SELECT DATABASE() AS `db`");
215 $data = self::toArray($ret);
216 return $data[0]['db'];
220 * @brief Analyze a database query and log this if some conditions are met.
222 * @param string $query The database query that will be analyzed
225 private static function logIndex($query) {
227 if (!self::$configCache->get('system', 'db_log_index')) {
231 // Don't explain an explain statement
232 if (strtolower(substr($query, 0, 7)) == "explain") {
236 // Only do the explain on "select", "update" and "delete"
237 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
241 $r = self::p("EXPLAIN ".$query);
242 if (!self::isResult($r)) {
246 $watchlist = explode(',', self::$configCache->get('system', 'db_log_index_watch'));
247 $blacklist = explode(',', self::$configCache->get('system', 'db_log_index_blacklist'));
249 while ($row = self::fetch($r)) {
250 if ((intval(self::$configCache->get('system', 'db_loglimit_index')) > 0)) {
251 $log = (in_array($row['key'], $watchlist) &&
252 ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index'))));
257 if ((intval(self::$configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index_high')))) {
261 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
266 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
267 @file_put_contents(self::$configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
268 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
269 basename($backtrace[1]["file"])."\t".
270 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
271 substr($query, 0, 2000)."\n", FILE_APPEND);
276 public static function escape($str) {
277 if (self::$connected) {
278 switch (self::$driver) {
280 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
283 return @self::$connection->real_escape_string($str);
286 return str_replace("'", "\\'", $str);
290 public static function connected() {
293 if (is_null(self::$connection)) {
297 switch (self::$driver) {
299 $r = self::p("SELECT 1");
300 if (self::isResult($r)) {
301 $row = self::toArray($r);
302 $connected = ($row[0]['1'] == '1');
306 $connected = self::$connection->ping();
313 * @brief Replaces ANY_VALUE() function by MIN() function,
314 * if the database server does not support ANY_VALUE().
316 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
317 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
318 * A standard fall-back is to use MIN().
320 * @param string $sql An SQL string without the values
321 * @return string The input SQL string modified if necessary.
323 public static function anyValueFallback($sql) {
324 $server_info = self::serverInfo();
325 if (version_compare($server_info, '5.7.5', '<') ||
326 (stripos($server_info, 'MariaDB') !== false)) {
327 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
333 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
335 * This is safe when we bind the parameters later.
336 * The parameter values aren't part of the SQL.
338 * @param string $sql An SQL string without the values
339 * @return string The input SQL string modified if necessary.
341 public static function cleanQuery($sql) {
342 $search = ["\t", "\n", "\r", " "];
343 $replace = [' ', ' ', ' ', ' '];
346 $sql = str_replace($search, $replace, $sql);
347 } while ($oldsql != $sql);
354 * @brief Replaces the ? placeholders with the parameters in the $args array
356 * @param string $sql SQL query
357 * @param array $args The parameters that are to replace the ? placeholders
358 * @return string The replaced SQL query
360 private static function replaceParameters($sql, $args) {
362 foreach ($args AS $param => $value) {
363 if (is_int($args[$param]) || is_float($args[$param])) {
364 $replace = intval($args[$param]);
366 $replace = "'".self::escape($args[$param])."'";
369 $pos = strpos($sql, '?', $offset);
370 if ($pos !== false) {
371 $sql = substr_replace($sql, $replace, $pos, 1);
373 $offset = $pos + strlen($replace);
379 * @brief Convert parameter array to an universal form
380 * @param array $args Parameter array
381 * @return array universalized parameter array
383 private static function getParam($args) {
386 // When the second function parameter is an array then use this as the parameter array
387 if ((count($args) > 0) && (is_array($args[1]))) {
395 * @brief Executes a prepared statement that returns data
396 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
398 * Please only use it with complicated queries.
399 * For all regular queries please use DBA::select or DBA::exists
401 * @param string $sql SQL statement
402 * @return bool|object statement object or result object
405 public static function p($sql) {
407 $stamp1 = microtime(true);
409 $params = self::getParam(func_get_args());
411 // Renumber the array keys to be sure that they fit
414 foreach ($params AS $param) {
415 // Avoid problems with some MySQL servers and boolean values. See issue #3645
416 if (is_bool($param)) {
417 $param = (int)$param;
419 $args[++$i] = $param;
422 if (!self::$connected) {
426 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
427 // Question: Should we continue or stop the query here?
428 Logger::error('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true));
431 $sql = self::cleanQuery($sql);
432 $sql = self::anyValueFallback($sql);
436 if (self::$configCache->get('system', 'db_callstack') !== null) {
437 $sql = "/*".System::callstack()." */ ".$sql;
442 self::$affected_rows = 0;
444 // We have to make some things different if this function is called from "e"
445 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
447 if (isset($trace[1])) {
448 $called_from = $trace[1];
450 // We use just something that is defined to avoid warnings
451 $called_from = $trace[0];
453 // We are having an own error logging in the function "e"
454 $called_from_e = ($called_from['function'] == 'e');
456 switch (self::$driver) {
458 // If there are no arguments we use "query"
459 if (count($args) == 0) {
460 if (!$retval = self::$connection->query($sql)) {
461 $errorInfo = self::$connection->errorInfo();
462 self::$error = $errorInfo[2];
463 self::$errorno = $errorInfo[1];
467 self::$affected_rows = $retval->rowCount();
471 if (!$stmt = self::$connection->prepare($sql)) {
472 $errorInfo = self::$connection->errorInfo();
473 self::$error = $errorInfo[2];
474 self::$errorno = $errorInfo[1];
479 foreach ($args AS $param => $value) {
480 if (is_int($args[$param])) {
481 $data_type = PDO::PARAM_INT;
483 $data_type = PDO::PARAM_STR;
485 $stmt->bindParam($param, $args[$param], $data_type);
488 if (!$stmt->execute()) {
489 $errorInfo = $stmt->errorInfo();
490 self::$error = $errorInfo[2];
491 self::$errorno = $errorInfo[1];
495 self::$affected_rows = $retval->rowCount();
499 // There are SQL statements that cannot be executed with a prepared statement
500 $parts = explode(' ', $orig_sql);
501 $command = strtolower($parts[0]);
502 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
504 // The fallback routine is called as well when there are no arguments
505 if (!$can_be_prepared || (count($args) == 0)) {
506 $retval = self::$connection->query(self::replaceParameters($sql, $args));
507 if (self::$connection->errno) {
508 self::$error = self::$connection->error;
509 self::$errorno = self::$connection->errno;
512 if (isset($retval->num_rows)) {
513 self::$affected_rows = $retval->num_rows;
515 self::$affected_rows = self::$connection->affected_rows;
521 $stmt = self::$connection->stmt_init();
523 if (!$stmt->prepare($sql)) {
524 self::$error = $stmt->error;
525 self::$errorno = $stmt->errno;
532 foreach ($args AS $param => $value) {
533 if (is_int($args[$param])) {
535 } elseif (is_float($args[$param])) {
537 } elseif (is_string($args[$param])) {
542 $values[] = &$args[$param];
545 if (count($values) > 0) {
546 array_unshift($values, $param_types);
547 call_user_func_array([$stmt, 'bind_param'], $values);
550 if (!$stmt->execute()) {
551 self::$error = self::$connection->error;
552 self::$errorno = self::$connection->errno;
555 $stmt->store_result();
557 self::$affected_rows = $retval->affected_rows;
562 // We are having an own error logging in the function "e"
563 if ((self::$errorno != 0) && !$called_from_e) {
564 // We have to preserve the error code, somewhere in the logging it get lost
565 $error = self::$error;
566 $errorno = self::$errorno;
568 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
569 System::callstack(8)."\n".self::replaceParameters($sql, $args));
571 // On a lost connection we try to reconnect - but only once.
572 if ($errorno == 2006) {
573 if (self::$in_retrial || !self::reconnect()) {
574 // It doesn't make sense to continue when the database connection was lost
575 if (self::$in_retrial) {
576 Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
578 Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
583 Logger::log('Reconnected after database error '.$errorno.': '.$error);
584 self::$in_retrial = true;
585 $ret = self::p($sql, $args);
586 self::$in_retrial = false;
591 self::$error = $error;
592 self::$errorno = $errorno;
595 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
597 if (self::$configCache->get('system', 'db_log')) {
598 $stamp2 = microtime(true);
599 $duration = (float)($stamp2 - $stamp1);
601 if (($duration > self::$configCache->get('system', 'db_loglimit'))) {
602 $duration = round($duration, 3);
603 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
605 @file_put_contents(self::$configCache->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
606 basename($backtrace[1]["file"])."\t".
607 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
608 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
615 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
617 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
619 * @param string $sql SQL statement
620 * @return boolean Was the query successfull? False is returned only if an error occurred
623 public static function e($sql) {
625 $stamp = microtime(true);
627 $params = self::getParam(func_get_args());
629 // In a case of a deadlock we are repeating the query 20 times
633 $stmt = self::p($sql, $params);
635 if (is_bool($stmt)) {
637 } elseif (is_object($stmt)) {
645 } while ((self::$errorno == 1213) && (--$timeout > 0));
647 if (self::$errorno != 0) {
648 // We have to preserve the error code, somewhere in the logging it get lost
649 $error = self::$error;
650 $errorno = self::$errorno;
652 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
653 System::callstack(8)."\n".self::replaceParameters($sql, $params));
655 // On a lost connection we simply quit.
656 // A reconnect like in self::p could be dangerous with modifications
657 if ($errorno == 2006) {
658 Logger::log('Giving up because of database error '.$errorno.': '.$error);
662 self::$error = $error;
663 self::$errorno = $errorno;
666 self::$profiler->saveTimestamp($stamp, "database_write", System::callstack());
672 * @brief Check if data exists
674 * @param string $table Table name
675 * @param array $condition array of fields for condition
677 * @return boolean Are there rows for that condition?
680 public static function exists($table, $condition) {
687 if (empty($condition)) {
688 return DBStructure::existsTable($table);
692 $first_key = key($condition);
693 if (!is_int($first_key)) {
694 $fields = [$first_key];
697 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
699 if (is_bool($stmt)) {
702 $retval = (self::numRows($stmt) > 0);
711 * Fetches the first row
713 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
715 * @brief Fetches the first row
716 * @param string $sql SQL statement
717 * @return array first row of query
720 public static function fetchFirst($sql) {
721 $params = self::getParam(func_get_args());
723 $stmt = self::p($sql, $params);
725 if (is_bool($stmt)) {
728 $retval = self::fetch($stmt);
737 * @brief Returns the number of affected rows of the last statement
739 * @return int Number of rows
741 public static function affectedRows() {
742 return self::$affected_rows;
746 * @brief Returns the number of columns of a statement
748 * @param object Statement object
749 * @return int Number of columns
751 public static function columnCount($stmt) {
752 if (!is_object($stmt)) {
755 switch (self::$driver) {
757 return $stmt->columnCount();
759 return $stmt->field_count;
764 * @brief Returns the number of rows of a statement
766 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
767 * @return int Number of rows
769 public static function numRows($stmt) {
770 if (!is_object($stmt)) {
773 switch (self::$driver) {
775 return $stmt->rowCount();
777 return $stmt->num_rows;
783 * @brief Fetch a single row
785 * @param mixed $stmt statement object
786 * @return array current row
788 public static function fetch($stmt) {
790 $stamp1 = microtime(true);
794 if (!is_object($stmt)) {
798 switch (self::$driver) {
800 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
803 if (get_class($stmt) == 'mysqli_result') {
804 $columns = $stmt->fetch_assoc();
808 // This code works, but is slow
810 // Bind the result to a result array
814 for ($x = 0; $x < $stmt->field_count; $x++) {
815 $cols[] = &$cols_num[$x];
818 call_user_func_array([$stmt, 'bind_result'], $cols);
820 if (!$stmt->fetch()) {
825 // We need to get the field names for the array keys
826 // It seems that there is no better way to do this.
827 $result = $stmt->result_metadata();
828 $fields = $result->fetch_fields();
830 foreach ($cols_num AS $param => $col) {
831 $columns[$fields[$param]->name] = $col;
835 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
841 * @brief Insert a row into a table
843 * @param string $table Table name
844 * @param array $param parameter array
845 * @param bool $on_duplicate_update Do an update on a duplicate entry
847 * @return boolean was the insert successful?
850 public static function insert($table, $param, $on_duplicate_update = false) {
852 if (empty($table) || empty($param)) {
853 Logger::log('Table and fields have to be set');
857 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
858 substr(str_repeat("?, ", count($param)), 0, -2).")";
860 if ($on_duplicate_update) {
861 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
863 $values = array_values($param);
864 $param = array_merge_recursive($values, $values);
867 return self::e($sql, $param);
871 * @brief Fetch the id of the last insert command
873 * @return integer Last inserted id
875 public static function lastInsertId() {
876 switch (self::$driver) {
878 $id = self::$connection->lastInsertId();
881 $id = self::$connection->insert_id;
888 * @brief Locks a table for exclusive write access
890 * This function can be extended in the future to accept a table array as well.
892 * @param string $table Table name
894 * @return boolean was the lock successful?
897 public static function lock($table) {
898 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
899 if (self::$driver == 'pdo') {
900 self::e("SET autocommit=0");
901 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
903 self::$connection->autocommit(false);
906 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
908 if (self::$driver == 'pdo') {
909 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
913 if (self::$driver == 'pdo') {
914 self::e("SET autocommit=1");
916 self::$connection->autocommit(true);
919 self::$in_transaction = true;
925 * @brief Unlocks all locked tables
927 * @return boolean was the unlock successful?
930 public static function unlock() {
931 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
932 self::performCommit();
934 if (self::$driver == 'pdo') {
935 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
938 $success = self::e("UNLOCK TABLES");
940 if (self::$driver == 'pdo') {
941 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
942 self::e("SET autocommit=1");
944 self::$connection->autocommit(true);
947 self::$in_transaction = false;
952 * @brief Starts a transaction
954 * @return boolean Was the command executed successfully?
956 public static function transaction() {
957 if (!self::performCommit()) {
961 switch (self::$driver) {
963 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
969 if (!self::$connection->begin_transaction()) {
975 self::$in_transaction = true;
979 private static function performCommit()
981 switch (self::$driver) {
983 if (!self::$connection->inTransaction()) {
987 return self::$connection->commit();
990 return self::$connection->commit();
997 * @brief Does a commit
999 * @return boolean Was the command executed successfully?
1001 public static function commit() {
1002 if (!self::performCommit()) {
1005 self::$in_transaction = false;
1010 * @brief Does a rollback
1012 * @return boolean Was the command executed successfully?
1014 public static function rollback() {
1017 switch (self::$driver) {
1019 if (!self::$connection->inTransaction()) {
1023 $ret = self::$connection->rollBack();
1027 $ret = self::$connection->rollback();
1030 self::$in_transaction = false;
1035 * @brief Build the array with the table relations
1037 * The array is build from the database definitions in DBStructure.php
1039 * This process must only be started once, since the value is cached.
1041 private static function buildRelationData() {
1042 $definition = DBStructure::definition(self::$basePath);
1044 foreach ($definition AS $table => $structure) {
1045 foreach ($structure['fields'] AS $field => $field_struct) {
1046 if (isset($field_struct['relation'])) {
1047 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1048 self::$relation[$rel_table][$rel_field][$table][] = $field;
1056 * @brief Delete a row from a table
1058 * @param string $table Table name
1059 * @param array $conditions Field condition(s)
1060 * @param array $options
1061 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1062 * relations (default: true)
1063 * @param array $callstack Internal use: prevent endless loops
1065 * @return boolean was the delete successful?
1066 * @throws \Exception
1068 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1070 if (empty($table) || empty($conditions)) {
1071 Logger::log('Table and conditions have to be set');
1077 // Create a key for the loop prevention
1078 $key = $table . ':' . json_encode($conditions);
1080 // We quit when this key already exists in the callstack.
1081 if (isset($callstack[$key])) {
1085 $callstack[$key] = true;
1087 $table = self::escape($table);
1089 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1091 // Don't use "defaults" here, since it would set "false" to "true"
1092 if (isset($options['cascade'])) {
1093 $cascade = $options['cascade'];
1098 // To speed up the whole process we cache the table relations
1099 if ($cascade && count(self::$relation) == 0) {
1100 self::buildRelationData();
1103 // Is there a relation entry for the table?
1104 if ($cascade && isset(self::$relation[$table])) {
1105 // We only allow a simple "one field" relation.
1106 $field = array_keys(self::$relation[$table])[0];
1107 $rel_def = array_values(self::$relation[$table])[0];
1109 // Create a key for preventing double queries
1110 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1112 // When the search field is the relation field, we don't need to fetch the rows
1113 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1114 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1115 foreach ($rel_def AS $rel_table => $rel_fields) {
1116 foreach ($rel_fields AS $rel_field) {
1117 self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1120 // We quit when this key already exists in the callstack.
1121 } elseif (!isset($callstack[$qkey])) {
1122 $callstack[$qkey] = true;
1124 // Fetch all rows that are to be deleted
1125 $data = self::select($table, [$field], $conditions);
1127 while ($row = self::fetch($data)) {
1128 self::delete($table, [$field => $row[$field]], $options, $callstack);
1133 // Since we had split the delete command we don't need the original command anymore
1134 unset($commands[$key]);
1138 // Now we finalize the process
1139 $do_transaction = !self::$in_transaction;
1141 if ($do_transaction) {
1142 self::transaction();
1148 foreach ($commands AS $command) {
1149 $conditions = $command['conditions'];
1151 $first_key = key($conditions);
1153 $condition_string = self::buildCondition($conditions);
1155 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1156 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1157 Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
1159 if (!self::e($sql, $conditions)) {
1160 if ($do_transaction) {
1166 $key_table = $command['table'];
1167 $key_condition = array_keys($command['conditions'])[0];
1168 $value = array_values($command['conditions'])[0];
1170 // Split the SQL queries in chunks of 100 values
1171 // We do the $i stuff here to make the code better readable
1172 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1173 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1177 $compacted[$key_table][$key_condition][$i][$value] = $value;
1178 $counter[$key_table][$key_condition] = $i;
1181 foreach ($compacted AS $table => $values) {
1182 foreach ($values AS $field => $field_value_list) {
1183 foreach ($field_value_list AS $field_values) {
1184 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1185 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1187 Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
1189 if (!self::e($sql, $field_values)) {
1190 if ($do_transaction) {
1198 if ($do_transaction) {
1205 * @brief Updates rows
1207 * Updates rows in the database. When $old_fields is set to an array,
1208 * the system will only do an update if the fields in that array changed.
1211 * Only the values in $old_fields are compared.
1212 * This is an intentional behaviour.
1215 * We include the timestamp field in $fields but not in $old_fields.
1216 * Then the row will only get the new timestamp when the other fields had changed.
1218 * When $old_fields is set to a boolean value the system will do this compare itself.
1219 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1222 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1223 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1225 * @param string $table Table name
1226 * @param array $fields contains the fields that are updated
1227 * @param array $condition condition array with the key values
1228 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1230 * @return boolean was the update successfull?
1231 * @throws \Exception
1233 public static function update($table, $fields, $condition, $old_fields = []) {
1235 if (empty($table) || empty($fields) || empty($condition)) {
1236 Logger::log('Table, fields and condition have to be set');
1240 $table = self::escape($table);
1242 $condition_string = self::buildCondition($condition);
1244 if (is_bool($old_fields)) {
1245 $do_insert = $old_fields;
1247 $old_fields = self::selectFirst($table, [], $condition);
1249 if (is_bool($old_fields)) {
1251 $values = array_merge($condition, $fields);
1252 return self::insert($table, $values, $do_insert);
1258 $do_update = (count($old_fields) == 0);
1260 foreach ($old_fields AS $fieldname => $content) {
1261 if (isset($fields[$fieldname])) {
1262 if (($fields[$fieldname] == $content) && !is_null($content)) {
1263 unset($fields[$fieldname]);
1270 if (!$do_update || (count($fields) == 0)) {
1274 $sql = "UPDATE `".$table."` SET `".
1275 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1277 $params1 = array_values($fields);
1278 $params2 = array_values($condition);
1279 $params = array_merge_recursive($params1, $params2);
1281 return self::e($sql, $params);
1285 * Retrieve a single record from a table and returns it in an associative array
1287 * @brief Retrieve a single record from a table
1288 * @param string $table
1289 * @param array $fields
1290 * @param array $condition
1291 * @param array $params
1292 * @return bool|array
1293 * @throws \Exception
1296 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1298 $params['limit'] = 1;
1299 $result = self::select($table, $fields, $condition, $params);
1301 if (is_bool($result)) {
1304 $row = self::fetch($result);
1305 self::close($result);
1311 * @brief Select rows from a table
1313 * @param string $table Table name
1314 * @param array $fields Array of selected fields, empty for all
1315 * @param array $condition Array of fields for condition
1316 * @param array $params Array of several parameters
1318 * @return boolean|object
1322 * $fields = array("id", "uri", "uid", "network");
1324 * $condition = array("uid" => 1, "network" => 'dspr');
1326 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1328 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1330 * $data = DBA::select($table, $fields, $condition, $params);
1331 * @throws \Exception
1333 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1339 $table = self::escape($table);
1341 if (count($fields) > 0) {
1342 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1344 $select_fields = "*";
1347 $condition_string = self::buildCondition($condition);
1349 $param_string = self::buildParameter($params);
1351 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1353 $result = self::p($sql, $condition);
1359 * @brief Counts the rows from a table satisfying the provided condition
1361 * @param string $table Table name
1362 * @param array $condition array of fields for condition
1369 * $condition = ["uid" => 1, "network" => 'dspr'];
1371 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1373 * $count = DBA::count($table, $condition);
1374 * @throws \Exception
1376 public static function count($table, array $condition = [])
1382 $condition_string = self::buildCondition($condition);
1384 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1386 $row = self::fetchFirst($sql, $condition);
1388 return $row['count'];
1392 * @brief Returns the SQL condition string built from the provided condition array
1394 * This function operates with two modes.
1395 * - Supplied with a filed/value associative array, it builds simple strict
1396 * equality conditions linked by AND.
1397 * - Supplied with a flat list, the first element is the condition string and
1398 * the following arguments are the values to be interpolated
1400 * $condition = ["uid" => 1, "network" => 'dspr'];
1402 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1404 * In either case, the provided array is left with the parameters only
1406 * @param array $condition
1409 public static function buildCondition(array &$condition = [])
1411 $condition_string = '';
1412 if (count($condition) > 0) {
1414 $first_key = key($condition);
1415 if (is_int($first_key)) {
1416 $condition_string = " WHERE (" . array_shift($condition) . ")";
1419 $condition_string = "";
1420 foreach ($condition as $field => $value) {
1421 if ($condition_string != "") {
1422 $condition_string .= " AND ";
1424 if (is_array($value)) {
1425 /* Workaround for MySQL Bug #64791.
1426 * Never mix data types inside any IN() condition.
1427 * In case of mixed types, cast all as string.
1428 * Logic needs to be consistent with DBA::p() data types.
1432 foreach ($value as $single_value) {
1433 if (is_int($single_value)) {
1440 if ($is_int && $is_alpha) {
1441 foreach ($value as &$ref) {
1443 $ref = (string)$ref;
1446 unset($ref); //Prevent accidental re-use.
1449 $new_values = array_merge($new_values, array_values($value));
1450 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1451 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1453 $new_values[$field] = $value;
1454 $condition_string .= "`" . $field . "` = ?";
1457 $condition_string = " WHERE (" . $condition_string . ")";
1458 $condition = $new_values;
1462 return $condition_string;
1466 * @brief Returns the SQL parameter string built from the provided parameter array
1468 * @param array $params
1471 public static function buildParameter(array $params = [])
1474 if (isset($params['order'])) {
1475 $order_string = " ORDER BY ";
1476 foreach ($params['order'] AS $fields => $order) {
1477 if (!is_int($fields)) {
1478 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1480 $order_string .= "`" . $order . "`, ";
1483 $order_string = substr($order_string, 0, -2);
1487 if (isset($params['limit']) && is_int($params['limit'])) {
1488 $limit_string = " LIMIT " . intval($params['limit']);
1491 if (isset($params['limit']) && is_array($params['limit'])) {
1492 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1495 return $order_string.$limit_string;
1499 * @brief Fills an array with data from a query
1501 * @param object $stmt statement object
1502 * @param bool $do_close
1503 * @return array Data array
1505 public static function toArray($stmt, $do_close = true) {
1506 if (is_bool($stmt)) {
1511 while ($row = self::fetch($stmt)) {
1521 * @brief Returns the error number of the last query
1523 * @return string Error number (0 if no error)
1525 public static function errorNo() {
1526 return self::$errorno;
1530 * @brief Returns the error message of the last query
1532 * @return string Error message ('' if no error)
1534 public static function errorMessage() {
1535 return self::$error;
1539 * @brief Closes the current statement
1541 * @param object $stmt statement object
1542 * @return boolean was the close successful?
1544 public static function close($stmt) {
1546 $stamp1 = microtime(true);
1548 if (!is_object($stmt)) {
1552 switch (self::$driver) {
1554 $ret = $stmt->closeCursor();
1557 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1558 // We should be careful not to assume the object type of $stmt
1559 // because DBA::p() has been able to return both types.
1560 if ($stmt instanceof mysqli_stmt) {
1561 $stmt->free_result();
1562 $ret = $stmt->close();
1563 } elseif ($stmt instanceof mysqli_result) {
1572 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
1578 * @brief Return a list of database processes
1581 * 'list' => List of processes, separated in their different states
1582 * 'amount' => Number of concurrent database processes
1583 * @throws \Exception
1585 public static function processlist()
1587 $ret = self::p("SHOW PROCESSLIST");
1588 $data = self::toArray($ret);
1592 foreach ($data as $process) {
1593 $state = trim($process["State"]);
1595 // Filter out all non blocking processes
1596 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1603 foreach ($states as $state => $usage) {
1604 if ($statelist != "") {
1607 $statelist .= $state.": ".$usage;
1609 return(["list" => $statelist, "amount" => $processes]);
1613 * Checks if $array is a filled array with at least one entry.
1615 * @param mixed $array A filled array with at least one entry
1617 * @return boolean Whether $array is a filled array or an object with rows
1619 public static function isResult($array)
1621 // It could be a return value from an update statement
1622 if (is_bool($array)) {
1626 if (is_object($array)) {
1627 return self::numRows($array) > 0;
1630 return (is_array($array) && (count($array) > 0));
1634 * @brief Callback function for "esc_array"
1636 * @param mixed $value Array value
1637 * @param string $key Array key
1638 * @param boolean $add_quotation add quotation marks for string values
1641 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1643 if (!$add_quotation) {
1644 if (is_bool($value)) {
1645 $value = ($value ? '1' : '0');
1647 $value = self::escape($value);
1652 if (is_bool($value)) {
1653 $value = ($value ? 'true' : 'false');
1654 } elseif (is_float($value) || is_integer($value)) {
1655 $value = (string) $value;
1657 $value = "'" . self::escape($value) . "'";
1662 * @brief Escapes a whole array
1664 * @param mixed $arr Array with values to be escaped
1665 * @param boolean $add_quotation add quotation marks for string values
1668 public static function escapeArray(&$arr, $add_quotation = false)
1670 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);