3 namespace Friendica\Database;
5 use Friendica\Core\Config\Cache\IConfigCache;
6 use Friendica\Core\System;
7 use Friendica\Util\DateTimeFormat;
8 use Friendica\Util\Profiler;
15 use Psr\Log\LoggerInterface;
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;
44 * @var LoggerInterface
46 private static $logger;
50 private static $basePath;
51 private static $server_info = '';
52 private static $connection;
53 private static $driver;
54 private static $error = false;
55 private static $errorno = 0;
56 private static $affected_rows = 0;
57 private static $in_transaction = false;
58 private static $in_retrial = false;
59 private static $relation = [];
60 private static $db_serveraddr = '';
61 private static $db_user = '';
62 private static $db_pass = '';
63 private static $db_name = '';
64 private static $db_charset = '';
66 public static function connect($basePath, IConfigCache $configCache, Profiler $profiler, LoggerInterface $logger, $serveraddr, $user, $pass, $db, $charset = null)
68 if (!is_null(self::$connection) && self::connected()) {
72 // We are storing these values for being able to perform a reconnect
73 self::$basePath = $basePath;
74 self::$configCache = $configCache;
75 self::$profiler = $profiler;
76 self::$logger = $logger;
77 self::$db_serveraddr = $serveraddr;
78 self::$db_user = $user;
79 self::$db_pass = $pass;
81 self::$db_charset = $charset;
84 $serveraddr = trim($serveraddr);
86 $serverdata = explode(':', $serveraddr);
87 $server = $serverdata[0];
89 if (count($serverdata) > 1) {
90 $port = trim($serverdata[1]);
93 $server = trim($server);
97 $charset = trim($charset);
99 if (!(strlen($server) && strlen($user))) {
103 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
104 self::$driver = 'pdo';
105 $connect = "mysql:host=".$server.";dbname=".$db;
108 $connect .= ";port=".$port;
112 $connect .= ";charset=".$charset;
116 self::$connection = @new PDO($connect, $user, $pass);
117 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
118 self::$connected = true;
119 } catch (PDOException $e) {
120 /// @TODO At least log exception, don't ignore it!
124 if (!self::$connected && class_exists('\mysqli')) {
125 self::$driver = 'mysqli';
128 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
130 self::$connection = @new mysqli($server, $user, $pass, $db);
133 if (!mysqli_connect_errno()) {
134 self::$connected = true;
137 self::$connection->set_charset($charset);
142 // No suitable SQL driver was found.
143 if (!self::$connected) {
144 self::$driver = null;
145 self::$connection = null;
148 return self::$connected;
152 * Sets the logger for DBA
154 * @note this is necessary because if we want to load the logger configuration
155 * from the DB, but there's an error, we would print out an exception.
156 * So the logger gets updated after the logger configuration can be retrieved
159 * @param LoggerInterface $logger
161 public static function setLogger(LoggerInterface $logger)
163 self::$logger = $logger;
167 * Disconnects the current database connection
169 public static function disconnect()
171 if (is_null(self::$connection)) {
175 switch (self::$driver) {
177 self::$connection = null;
180 self::$connection->close();
181 self::$connection = null;
187 * Perform a reconnect of an existing database connection
189 public static function reconnect() {
192 $ret = self::connect(self::$basePath, self::$configCache, self::$profiler, self::$logger, self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
197 * Return the database object.
200 public static function getConnection()
202 return self::$connection;
206 * @brief Returns the MySQL server version string
208 * This function discriminate between the deprecated mysql API and the current
209 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
213 public static function serverInfo() {
214 if (self::$server_info == '') {
215 switch (self::$driver) {
217 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
220 self::$server_info = self::$connection->server_info;
224 return self::$server_info;
228 * @brief Returns the selected database name
233 public static function databaseName() {
234 $ret = self::p("SELECT DATABASE() AS `db`");
235 $data = self::toArray($ret);
236 return $data[0]['db'];
240 * @brief Analyze a database query and log this if some conditions are met.
242 * @param string $query The database query that will be analyzed
245 private static function logIndex($query) {
247 if (!self::$configCache->get('system', 'db_log_index')) {
251 // Don't explain an explain statement
252 if (strtolower(substr($query, 0, 7)) == "explain") {
256 // Only do the explain on "select", "update" and "delete"
257 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
261 $r = self::p("EXPLAIN ".$query);
262 if (!self::isResult($r)) {
266 $watchlist = explode(',', self::$configCache->get('system', 'db_log_index_watch'));
267 $blacklist = explode(',', self::$configCache->get('system', 'db_log_index_blacklist'));
269 while ($row = self::fetch($r)) {
270 if ((intval(self::$configCache->get('system', 'db_loglimit_index')) > 0)) {
271 $log = (in_array($row['key'], $watchlist) &&
272 ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index'))));
277 if ((intval(self::$configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index_high')))) {
281 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
286 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
287 @file_put_contents(self::$configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
288 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
289 basename($backtrace[1]["file"])."\t".
290 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
291 substr($query, 0, 2000)."\n", FILE_APPEND);
296 public static function escape($str) {
297 if (self::$connected) {
298 switch (self::$driver) {
300 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
303 return @self::$connection->real_escape_string($str);
306 return str_replace("'", "\\'", $str);
310 public static function connected() {
313 if (is_null(self::$connection)) {
317 switch (self::$driver) {
319 $r = self::p("SELECT 1");
320 if (self::isResult($r)) {
321 $row = self::toArray($r);
322 $connected = ($row[0]['1'] == '1');
326 $connected = self::$connection->ping();
333 * @brief Replaces ANY_VALUE() function by MIN() function,
334 * if the database server does not support ANY_VALUE().
336 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
337 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
338 * A standard fall-back is to use MIN().
340 * @param string $sql An SQL string without the values
341 * @return string The input SQL string modified if necessary.
343 public static function anyValueFallback($sql) {
344 $server_info = self::serverInfo();
345 if (version_compare($server_info, '5.7.5', '<') ||
346 (stripos($server_info, 'MariaDB') !== false)) {
347 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
353 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
355 * This is safe when we bind the parameters later.
356 * The parameter values aren't part of the SQL.
358 * @param string $sql An SQL string without the values
359 * @return string The input SQL string modified if necessary.
361 public static function cleanQuery($sql) {
362 $search = ["\t", "\n", "\r", " "];
363 $replace = [' ', ' ', ' ', ' '];
366 $sql = str_replace($search, $replace, $sql);
367 } while ($oldsql != $sql);
374 * @brief Replaces the ? placeholders with the parameters in the $args array
376 * @param string $sql SQL query
377 * @param array $args The parameters that are to replace the ? placeholders
378 * @return string The replaced SQL query
380 private static function replaceParameters($sql, $args) {
382 foreach ($args AS $param => $value) {
383 if (is_int($args[$param]) || is_float($args[$param])) {
384 $replace = intval($args[$param]);
386 $replace = "'".self::escape($args[$param])."'";
389 $pos = strpos($sql, '?', $offset);
390 if ($pos !== false) {
391 $sql = substr_replace($sql, $replace, $pos, 1);
393 $offset = $pos + strlen($replace);
399 * @brief Convert parameter array to an universal form
400 * @param array $args Parameter array
401 * @return array universalized parameter array
403 private static function getParam($args) {
406 // When the second function parameter is an array then use this as the parameter array
407 if ((count($args) > 0) && (is_array($args[1]))) {
415 * @brief Executes a prepared statement that returns data
416 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
418 * Please only use it with complicated queries.
419 * For all regular queries please use DBA::select or DBA::exists
421 * @param string $sql SQL statement
422 * @return bool|object statement object or result object
425 public static function p($sql) {
427 $stamp1 = microtime(true);
429 $params = self::getParam(func_get_args());
431 // Renumber the array keys to be sure that they fit
434 foreach ($params AS $param) {
435 // Avoid problems with some MySQL servers and boolean values. See issue #3645
436 if (is_bool($param)) {
437 $param = (int)$param;
439 $args[++$i] = $param;
442 if (!self::$connected) {
446 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
447 // Question: Should we continue or stop the query here?
448 self::$logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
451 $sql = self::cleanQuery($sql);
452 $sql = self::anyValueFallback($sql);
456 if (self::$configCache->get('system', 'db_callstack') !== null) {
457 $sql = "/*".System::callstack()." */ ".$sql;
462 self::$affected_rows = 0;
464 // We have to make some things different if this function is called from "e"
465 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
467 if (isset($trace[1])) {
468 $called_from = $trace[1];
470 // We use just something that is defined to avoid warnings
471 $called_from = $trace[0];
473 // We are having an own error logging in the function "e"
474 $called_from_e = ($called_from['function'] == 'e');
476 switch (self::$driver) {
478 // If there are no arguments we use "query"
479 if (count($args) == 0) {
480 if (!$retval = self::$connection->query($sql)) {
481 $errorInfo = self::$connection->errorInfo();
482 self::$error = $errorInfo[2];
483 self::$errorno = $errorInfo[1];
487 self::$affected_rows = $retval->rowCount();
491 if (!$stmt = self::$connection->prepare($sql)) {
492 $errorInfo = self::$connection->errorInfo();
493 self::$error = $errorInfo[2];
494 self::$errorno = $errorInfo[1];
499 foreach ($args AS $param => $value) {
500 if (is_int($args[$param])) {
501 $data_type = PDO::PARAM_INT;
503 $data_type = PDO::PARAM_STR;
505 $stmt->bindParam($param, $args[$param], $data_type);
508 if (!$stmt->execute()) {
509 $errorInfo = $stmt->errorInfo();
510 self::$error = $errorInfo[2];
511 self::$errorno = $errorInfo[1];
515 self::$affected_rows = $retval->rowCount();
519 // There are SQL statements that cannot be executed with a prepared statement
520 $parts = explode(' ', $orig_sql);
521 $command = strtolower($parts[0]);
522 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
524 // The fallback routine is called as well when there are no arguments
525 if (!$can_be_prepared || (count($args) == 0)) {
526 $retval = self::$connection->query(self::replaceParameters($sql, $args));
527 if (self::$connection->errno) {
528 self::$error = self::$connection->error;
529 self::$errorno = self::$connection->errno;
532 if (isset($retval->num_rows)) {
533 self::$affected_rows = $retval->num_rows;
535 self::$affected_rows = self::$connection->affected_rows;
541 $stmt = self::$connection->stmt_init();
543 if (!$stmt->prepare($sql)) {
544 self::$error = $stmt->error;
545 self::$errorno = $stmt->errno;
552 foreach ($args AS $param => $value) {
553 if (is_int($args[$param])) {
555 } elseif (is_float($args[$param])) {
557 } elseif (is_string($args[$param])) {
562 $values[] = &$args[$param];
565 if (count($values) > 0) {
566 array_unshift($values, $param_types);
567 call_user_func_array([$stmt, 'bind_param'], $values);
570 if (!$stmt->execute()) {
571 self::$error = self::$connection->error;
572 self::$errorno = self::$connection->errno;
575 $stmt->store_result();
577 self::$affected_rows = $retval->affected_rows;
582 // We are having an own error logging in the function "e"
583 if ((self::$errorno != 0) && !$called_from_e) {
584 // We have to preserve the error code, somewhere in the logging it get lost
585 $error = self::$error;
586 $errorno = self::$errorno;
588 self::$logger->error('DB Error', [
589 'code' => self::$errorno,
590 'error' => self::$error,
591 'callstack' => System::callstack(8),
592 'params' => self::replaceParameters($sql, $args),
595 // On a lost connection we try to reconnect - but only once.
596 if ($errorno == 2006) {
597 if (self::$in_retrial || !self::reconnect()) {
598 // It doesn't make sense to continue when the database connection was lost
599 if (self::$in_retrial) {
600 self::$logger->notice('Giving up retrial because of database error', [
601 'code' => self::$errorno,
602 'error' => self::$error,
605 self::$logger->notice('Couldn\'t reconnect after database error', [
606 'code' => self::$errorno,
607 'error' => self::$error,
613 self::$logger->notice('Reconnected after database error', [
614 'code' => self::$errorno,
615 'error' => self::$error,
617 self::$in_retrial = true;
618 $ret = self::p($sql, $args);
619 self::$in_retrial = false;
624 self::$error = $error;
625 self::$errorno = $errorno;
628 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
630 if (self::$configCache->get('system', 'db_log')) {
631 $stamp2 = microtime(true);
632 $duration = (float)($stamp2 - $stamp1);
634 if (($duration > self::$configCache->get('system', 'db_loglimit'))) {
635 $duration = round($duration, 3);
636 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
638 @file_put_contents(self::$configCache->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
639 basename($backtrace[1]["file"])."\t".
640 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
641 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
648 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
650 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
652 * @param string $sql SQL statement
653 * @return boolean Was the query successfull? False is returned only if an error occurred
656 public static function e($sql) {
658 $stamp = microtime(true);
660 $params = self::getParam(func_get_args());
662 // In a case of a deadlock we are repeating the query 20 times
666 $stmt = self::p($sql, $params);
668 if (is_bool($stmt)) {
670 } elseif (is_object($stmt)) {
678 } while ((self::$errorno == 1213) && (--$timeout > 0));
680 if (self::$errorno != 0) {
681 // We have to preserve the error code, somewhere in the logging it get lost
682 $error = self::$error;
683 $errorno = self::$errorno;
685 self::$logger->error('DB Error', [
686 'code' => self::$errorno,
687 'error' => self::$error,
688 'callstack' => System::callstack(8),
689 'params' => self::replaceParameters($sql, $params),
692 // On a lost connection we simply quit.
693 // A reconnect like in self::p could be dangerous with modifications
694 if ($errorno == 2006) {
695 self::$logger->error('Giving up because of database error', [
696 'code' => self::$errorno,
697 'error' => self::$error,
702 self::$error = $error;
703 self::$errorno = $errorno;
706 self::$profiler->saveTimestamp($stamp, "database_write", System::callstack());
712 * @brief Check if data exists
714 * @param string $table Table name
715 * @param array $condition array of fields for condition
717 * @return boolean Are there rows for that condition?
720 public static function exists($table, $condition) {
727 if (empty($condition)) {
728 return DBStructure::existsTable($table);
732 $first_key = key($condition);
733 if (!is_int($first_key)) {
734 $fields = [$first_key];
737 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
739 if (is_bool($stmt)) {
742 $retval = (self::numRows($stmt) > 0);
751 * Fetches the first row
753 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
755 * @brief Fetches the first row
756 * @param string $sql SQL statement
757 * @return array first row of query
760 public static function fetchFirst($sql) {
761 $params = self::getParam(func_get_args());
763 $stmt = self::p($sql, $params);
765 if (is_bool($stmt)) {
768 $retval = self::fetch($stmt);
777 * @brief Returns the number of affected rows of the last statement
779 * @return int Number of rows
781 public static function affectedRows() {
782 return self::$affected_rows;
786 * @brief Returns the number of columns of a statement
788 * @param object Statement object
789 * @return int Number of columns
791 public static function columnCount($stmt) {
792 if (!is_object($stmt)) {
795 switch (self::$driver) {
797 return $stmt->columnCount();
799 return $stmt->field_count;
804 * @brief Returns the number of rows of a statement
806 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
807 * @return int Number of rows
809 public static function numRows($stmt) {
810 if (!is_object($stmt)) {
813 switch (self::$driver) {
815 return $stmt->rowCount();
817 return $stmt->num_rows;
823 * @brief Fetch a single row
825 * @param mixed $stmt statement object
826 * @return array current row
828 public static function fetch($stmt) {
830 $stamp1 = microtime(true);
834 if (!is_object($stmt)) {
838 switch (self::$driver) {
840 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
843 if (get_class($stmt) == 'mysqli_result') {
844 $columns = $stmt->fetch_assoc();
848 // This code works, but is slow
850 // Bind the result to a result array
854 for ($x = 0; $x < $stmt->field_count; $x++) {
855 $cols[] = &$cols_num[$x];
858 call_user_func_array([$stmt, 'bind_result'], $cols);
860 if (!$stmt->fetch()) {
865 // We need to get the field names for the array keys
866 // It seems that there is no better way to do this.
867 $result = $stmt->result_metadata();
868 $fields = $result->fetch_fields();
870 foreach ($cols_num AS $param => $col) {
871 $columns[$fields[$param]->name] = $col;
875 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
881 * @brief Insert a row into a table
883 * @param string $table Table name
884 * @param array $param parameter array
885 * @param bool $on_duplicate_update Do an update on a duplicate entry
887 * @return boolean was the insert successful?
890 public static function insert($table, $param, $on_duplicate_update = false) {
892 if (empty($table) || empty($param)) {
893 self::$logger->info('Table and fields have to be set');
897 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
898 substr(str_repeat("?, ", count($param)), 0, -2).")";
900 if ($on_duplicate_update) {
901 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
903 $values = array_values($param);
904 $param = array_merge_recursive($values, $values);
907 return self::e($sql, $param);
911 * @brief Fetch the id of the last insert command
913 * @return integer Last inserted id
915 public static function lastInsertId() {
916 switch (self::$driver) {
918 $id = self::$connection->lastInsertId();
921 $id = self::$connection->insert_id;
928 * @brief Locks a table for exclusive write access
930 * This function can be extended in the future to accept a table array as well.
932 * @param string $table Table name
934 * @return boolean was the lock successful?
937 public static function lock($table) {
938 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
939 if (self::$driver == 'pdo') {
940 self::e("SET autocommit=0");
941 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
943 self::$connection->autocommit(false);
946 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
948 if (self::$driver == 'pdo') {
949 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
953 if (self::$driver == 'pdo') {
954 self::e("SET autocommit=1");
956 self::$connection->autocommit(true);
959 self::$in_transaction = true;
965 * @brief Unlocks all locked tables
967 * @return boolean was the unlock successful?
970 public static function unlock() {
971 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
972 self::performCommit();
974 if (self::$driver == 'pdo') {
975 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
978 $success = self::e("UNLOCK TABLES");
980 if (self::$driver == 'pdo') {
981 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
982 self::e("SET autocommit=1");
984 self::$connection->autocommit(true);
987 self::$in_transaction = false;
992 * @brief Starts a transaction
994 * @return boolean Was the command executed successfully?
996 public static function transaction() {
997 if (!self::performCommit()) {
1001 switch (self::$driver) {
1003 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
1009 if (!self::$connection->begin_transaction()) {
1015 self::$in_transaction = true;
1019 private static function performCommit()
1021 switch (self::$driver) {
1023 if (!self::$connection->inTransaction()) {
1027 return self::$connection->commit();
1030 return self::$connection->commit();
1037 * @brief Does a commit
1039 * @return boolean Was the command executed successfully?
1041 public static function commit() {
1042 if (!self::performCommit()) {
1045 self::$in_transaction = false;
1050 * @brief Does a rollback
1052 * @return boolean Was the command executed successfully?
1054 public static function rollback() {
1057 switch (self::$driver) {
1059 if (!self::$connection->inTransaction()) {
1063 $ret = self::$connection->rollBack();
1067 $ret = self::$connection->rollback();
1070 self::$in_transaction = false;
1075 * @brief Build the array with the table relations
1077 * The array is build from the database definitions in DBStructure.php
1079 * This process must only be started once, since the value is cached.
1081 private static function buildRelationData() {
1082 $definition = DBStructure::definition(self::$basePath);
1084 foreach ($definition AS $table => $structure) {
1085 foreach ($structure['fields'] AS $field => $field_struct) {
1086 if (isset($field_struct['relation'])) {
1087 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1088 self::$relation[$rel_table][$rel_field][$table][] = $field;
1096 * @brief Delete a row from a table
1098 * @param string $table Table name
1099 * @param array $conditions Field condition(s)
1100 * @param array $options
1101 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1102 * relations (default: true)
1103 * @param array $callstack Internal use: prevent endless loops
1105 * @return boolean was the delete successful?
1106 * @throws \Exception
1108 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1110 if (empty($table) || empty($conditions)) {
1111 self::$logger->info('Table and conditions have to be set');
1117 // Create a key for the loop prevention
1118 $key = $table . ':' . json_encode($conditions);
1120 // We quit when this key already exists in the callstack.
1121 if (isset($callstack[$key])) {
1125 $callstack[$key] = true;
1127 $table = self::escape($table);
1129 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1131 // Don't use "defaults" here, since it would set "false" to "true"
1132 if (isset($options['cascade'])) {
1133 $cascade = $options['cascade'];
1138 // To speed up the whole process we cache the table relations
1139 if ($cascade && count(self::$relation) == 0) {
1140 self::buildRelationData();
1143 // Is there a relation entry for the table?
1144 if ($cascade && isset(self::$relation[$table])) {
1145 // We only allow a simple "one field" relation.
1146 $field = array_keys(self::$relation[$table])[0];
1147 $rel_def = array_values(self::$relation[$table])[0];
1149 // Create a key for preventing double queries
1150 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1152 // When the search field is the relation field, we don't need to fetch the rows
1153 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1154 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1155 foreach ($rel_def AS $rel_table => $rel_fields) {
1156 foreach ($rel_fields AS $rel_field) {
1157 self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1160 // We quit when this key already exists in the callstack.
1161 } elseif (!isset($callstack[$qkey])) {
1162 $callstack[$qkey] = true;
1164 // Fetch all rows that are to be deleted
1165 $data = self::select($table, [$field], $conditions);
1167 while ($row = self::fetch($data)) {
1168 self::delete($table, [$field => $row[$field]], $options, $callstack);
1173 // Since we had split the delete command we don't need the original command anymore
1174 unset($commands[$key]);
1178 // Now we finalize the process
1179 $do_transaction = !self::$in_transaction;
1181 if ($do_transaction) {
1182 self::transaction();
1188 foreach ($commands AS $command) {
1189 $conditions = $command['conditions'];
1191 $first_key = key($conditions);
1193 $condition_string = self::buildCondition($conditions);
1195 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1196 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1197 self::$logger->debug(self::replaceParameters($sql, $conditions));
1199 if (!self::e($sql, $conditions)) {
1200 if ($do_transaction) {
1206 $key_table = $command['table'];
1207 $key_condition = array_keys($command['conditions'])[0];
1208 $value = array_values($command['conditions'])[0];
1210 // Split the SQL queries in chunks of 100 values
1211 // We do the $i stuff here to make the code better readable
1212 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1213 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1217 $compacted[$key_table][$key_condition][$i][$value] = $value;
1218 $counter[$key_table][$key_condition] = $i;
1221 foreach ($compacted AS $table => $values) {
1222 foreach ($values AS $field => $field_value_list) {
1223 foreach ($field_value_list AS $field_values) {
1224 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1225 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1227 self::$logger->debug(self::replaceParameters($sql, $field_values));
1229 if (!self::e($sql, $field_values)) {
1230 if ($do_transaction) {
1238 if ($do_transaction) {
1245 * @brief Updates rows
1247 * Updates rows in the database. When $old_fields is set to an array,
1248 * the system will only do an update if the fields in that array changed.
1251 * Only the values in $old_fields are compared.
1252 * This is an intentional behaviour.
1255 * We include the timestamp field in $fields but not in $old_fields.
1256 * Then the row will only get the new timestamp when the other fields had changed.
1258 * When $old_fields is set to a boolean value the system will do this compare itself.
1259 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1262 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1263 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1265 * @param string $table Table name
1266 * @param array $fields contains the fields that are updated
1267 * @param array $condition condition array with the key values
1268 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1270 * @return boolean was the update successfull?
1271 * @throws \Exception
1273 public static function update($table, $fields, $condition, $old_fields = []) {
1275 if (empty($table) || empty($fields) || empty($condition)) {
1276 self::$logger->info('Table, fields and condition have to be set');
1280 $table = self::escape($table);
1282 $condition_string = self::buildCondition($condition);
1284 if (is_bool($old_fields)) {
1285 $do_insert = $old_fields;
1287 $old_fields = self::selectFirst($table, [], $condition);
1289 if (is_bool($old_fields)) {
1291 $values = array_merge($condition, $fields);
1292 return self::insert($table, $values, $do_insert);
1298 $do_update = (count($old_fields) == 0);
1300 foreach ($old_fields AS $fieldname => $content) {
1301 if (isset($fields[$fieldname])) {
1302 if (($fields[$fieldname] == $content) && !is_null($content)) {
1303 unset($fields[$fieldname]);
1310 if (!$do_update || (count($fields) == 0)) {
1314 $sql = "UPDATE `".$table."` SET `".
1315 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1317 $params1 = array_values($fields);
1318 $params2 = array_values($condition);
1319 $params = array_merge_recursive($params1, $params2);
1321 return self::e($sql, $params);
1325 * Retrieve a single record from a table and returns it in an associative array
1327 * @brief Retrieve a single record from a table
1328 * @param string $table
1329 * @param array $fields
1330 * @param array $condition
1331 * @param array $params
1332 * @return bool|array
1333 * @throws \Exception
1336 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1338 $params['limit'] = 1;
1339 $result = self::select($table, $fields, $condition, $params);
1341 if (is_bool($result)) {
1344 $row = self::fetch($result);
1345 self::close($result);
1351 * @brief Select rows from a table
1353 * @param string $table Table name
1354 * @param array $fields Array of selected fields, empty for all
1355 * @param array $condition Array of fields for condition
1356 * @param array $params Array of several parameters
1358 * @return boolean|object
1362 * $fields = array("id", "uri", "uid", "network");
1364 * $condition = array("uid" => 1, "network" => 'dspr');
1366 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1368 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1370 * $data = DBA::select($table, $fields, $condition, $params);
1371 * @throws \Exception
1373 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1379 $table = self::escape($table);
1381 if (count($fields) > 0) {
1382 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1384 $select_fields = "*";
1387 $condition_string = self::buildCondition($condition);
1389 $param_string = self::buildParameter($params);
1391 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1393 $result = self::p($sql, $condition);
1399 * @brief Counts the rows from a table satisfying the provided condition
1401 * @param string $table Table name
1402 * @param array $condition array of fields for condition
1409 * $condition = ["uid" => 1, "network" => 'dspr'];
1411 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1413 * $count = DBA::count($table, $condition);
1414 * @throws \Exception
1416 public static function count($table, array $condition = [])
1422 $condition_string = self::buildCondition($condition);
1424 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1426 $row = self::fetchFirst($sql, $condition);
1428 return $row['count'];
1432 * @brief Returns the SQL condition string built from the provided condition array
1434 * This function operates with two modes.
1435 * - Supplied with a filed/value associative array, it builds simple strict
1436 * equality conditions linked by AND.
1437 * - Supplied with a flat list, the first element is the condition string and
1438 * the following arguments are the values to be interpolated
1440 * $condition = ["uid" => 1, "network" => 'dspr'];
1442 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1444 * In either case, the provided array is left with the parameters only
1446 * @param array $condition
1449 public static function buildCondition(array &$condition = [])
1451 $condition_string = '';
1452 if (count($condition) > 0) {
1454 $first_key = key($condition);
1455 if (is_int($first_key)) {
1456 $condition_string = " WHERE (" . array_shift($condition) . ")";
1459 $condition_string = "";
1460 foreach ($condition as $field => $value) {
1461 if ($condition_string != "") {
1462 $condition_string .= " AND ";
1464 if (is_array($value)) {
1465 /* Workaround for MySQL Bug #64791.
1466 * Never mix data types inside any IN() condition.
1467 * In case of mixed types, cast all as string.
1468 * Logic needs to be consistent with DBA::p() data types.
1472 foreach ($value as $single_value) {
1473 if (is_int($single_value)) {
1480 if ($is_int && $is_alpha) {
1481 foreach ($value as &$ref) {
1483 $ref = (string)$ref;
1486 unset($ref); //Prevent accidental re-use.
1489 $new_values = array_merge($new_values, array_values($value));
1490 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1491 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1493 $new_values[$field] = $value;
1494 $condition_string .= "`" . $field . "` = ?";
1497 $condition_string = " WHERE (" . $condition_string . ")";
1498 $condition = $new_values;
1502 return $condition_string;
1506 * @brief Returns the SQL parameter string built from the provided parameter array
1508 * @param array $params
1511 public static function buildParameter(array $params = [])
1514 if (isset($params['order'])) {
1515 $order_string = " ORDER BY ";
1516 foreach ($params['order'] AS $fields => $order) {
1517 if (!is_int($fields)) {
1518 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1520 $order_string .= "`" . $order . "`, ";
1523 $order_string = substr($order_string, 0, -2);
1527 if (isset($params['limit']) && is_numeric($params['limit'])) {
1528 $limit_string = " LIMIT " . intval($params['limit']);
1531 if (isset($params['limit']) && is_array($params['limit'])) {
1532 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1535 return $order_string.$limit_string;
1539 * @brief Fills an array with data from a query
1541 * @param object $stmt statement object
1542 * @param bool $do_close
1543 * @return array Data array
1545 public static function toArray($stmt, $do_close = true) {
1546 if (is_bool($stmt)) {
1551 while ($row = self::fetch($stmt)) {
1561 * @brief Returns the error number of the last query
1563 * @return string Error number (0 if no error)
1565 public static function errorNo() {
1566 return self::$errorno;
1570 * @brief Returns the error message of the last query
1572 * @return string Error message ('' if no error)
1574 public static function errorMessage() {
1575 return self::$error;
1579 * @brief Closes the current statement
1581 * @param object $stmt statement object
1582 * @return boolean was the close successful?
1584 public static function close($stmt) {
1586 $stamp1 = microtime(true);
1588 if (!is_object($stmt)) {
1592 switch (self::$driver) {
1594 $ret = $stmt->closeCursor();
1597 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1598 // We should be careful not to assume the object type of $stmt
1599 // because DBA::p() has been able to return both types.
1600 if ($stmt instanceof mysqli_stmt) {
1601 $stmt->free_result();
1602 $ret = $stmt->close();
1603 } elseif ($stmt instanceof mysqli_result) {
1612 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
1618 * @brief Return a list of database processes
1621 * 'list' => List of processes, separated in their different states
1622 * 'amount' => Number of concurrent database processes
1623 * @throws \Exception
1625 public static function processlist()
1627 $ret = self::p("SHOW PROCESSLIST");
1628 $data = self::toArray($ret);
1632 foreach ($data as $process) {
1633 $state = trim($process["State"]);
1635 // Filter out all non blocking processes
1636 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1643 foreach ($states as $state => $usage) {
1644 if ($statelist != "") {
1647 $statelist .= $state.": ".$usage;
1649 return(["list" => $statelist, "amount" => $processes]);
1653 * Checks if $array is a filled array with at least one entry.
1655 * @param mixed $array A filled array with at least one entry
1657 * @return boolean Whether $array is a filled array or an object with rows
1659 public static function isResult($array)
1661 // It could be a return value from an update statement
1662 if (is_bool($array)) {
1666 if (is_object($array)) {
1667 return self::numRows($array) > 0;
1670 return (is_array($array) && (count($array) > 0));
1674 * @brief Callback function for "esc_array"
1676 * @param mixed $value Array value
1677 * @param string $key Array key
1678 * @param boolean $add_quotation add quotation marks for string values
1681 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1683 if (!$add_quotation) {
1684 if (is_bool($value)) {
1685 $value = ($value ? '1' : '0');
1687 $value = self::escape($value);
1692 if (is_bool($value)) {
1693 $value = ($value ? 'true' : 'false');
1694 } elseif (is_float($value) || is_integer($value)) {
1695 $value = (string) $value;
1697 $value = "'" . self::escape($value) . "'";
1702 * @brief Escapes a whole array
1704 * @param mixed $arr Array with values to be escaped
1705 * @param boolean $add_quotation add quotation marks for string values
1708 public static function escapeArray(&$arr, $add_quotation = false)
1710 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);