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;
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(IConfigCache $configCache, Profiler $profiler, LoggerInterface $logger, $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::$configCache = $configCache;
70 self::$profiler = $profiler;
71 self::$logger = $logger;
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 * Sets the logger for DBA
149 * @note this is necessary because if we want to load the logger configuration
150 * from the DB, but there's an error, we would print out an exception.
151 * So the logger gets updated after the logger configuration can be retrieved
154 * @param LoggerInterface $logger
156 public static function setLogger(LoggerInterface $logger)
158 self::$logger = $logger;
162 * Disconnects the current database connection
164 public static function disconnect()
166 if (is_null(self::$connection)) {
170 switch (self::$driver) {
172 self::$connection = null;
175 self::$connection->close();
176 self::$connection = null;
182 * Perform a reconnect of an existing database connection
184 public static function reconnect() {
187 $ret = self::connect(self::$configCache, self::$profiler, self::$logger, self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
192 * Return the database object.
195 public static function getConnection()
197 return self::$connection;
201 * @brief Returns the MySQL server version string
203 * This function discriminate between the deprecated mysql API and the current
204 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
208 public static function serverInfo() {
209 if (self::$server_info == '') {
210 switch (self::$driver) {
212 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
215 self::$server_info = self::$connection->server_info;
219 return self::$server_info;
223 * @brief Returns the selected database name
228 public static function databaseName() {
229 $ret = self::p("SELECT DATABASE() AS `db`");
230 $data = self::toArray($ret);
231 return $data[0]['db'];
235 * @brief Analyze a database query and log this if some conditions are met.
237 * @param string $query The database query that will be analyzed
240 private static function logIndex($query) {
242 if (!self::$configCache->get('system', 'db_log_index')) {
246 // Don't explain an explain statement
247 if (strtolower(substr($query, 0, 7)) == "explain") {
251 // Only do the explain on "select", "update" and "delete"
252 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
256 $r = self::p("EXPLAIN ".$query);
257 if (!self::isResult($r)) {
261 $watchlist = explode(',', self::$configCache->get('system', 'db_log_index_watch'));
262 $blacklist = explode(',', self::$configCache->get('system', 'db_log_index_blacklist'));
264 while ($row = self::fetch($r)) {
265 if ((intval(self::$configCache->get('system', 'db_loglimit_index')) > 0)) {
266 $log = (in_array($row['key'], $watchlist) &&
267 ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index'))));
272 if ((intval(self::$configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index_high')))) {
276 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
281 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
282 @file_put_contents(self::$configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
283 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
284 basename($backtrace[1]["file"])."\t".
285 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
286 substr($query, 0, 2000)."\n", FILE_APPEND);
291 public static function escape($str) {
292 if (self::$connected) {
293 switch (self::$driver) {
295 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
298 return @self::$connection->real_escape_string($str);
301 return str_replace("'", "\\'", $str);
305 public static function connected() {
308 if (is_null(self::$connection)) {
312 switch (self::$driver) {
314 $r = self::p("SELECT 1");
315 if (self::isResult($r)) {
316 $row = self::toArray($r);
317 $connected = ($row[0]['1'] == '1');
321 $connected = self::$connection->ping();
328 * @brief Replaces ANY_VALUE() function by MIN() function,
329 * if the database server does not support ANY_VALUE().
331 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
332 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
333 * A standard fall-back is to use MIN().
335 * @param string $sql An SQL string without the values
336 * @return string The input SQL string modified if necessary.
338 public static function anyValueFallback($sql) {
339 $server_info = self::serverInfo();
340 if (version_compare($server_info, '5.7.5', '<') ||
341 (stripos($server_info, 'MariaDB') !== false)) {
342 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
348 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
350 * This is safe when we bind the parameters later.
351 * The parameter values aren't part of the SQL.
353 * @param string $sql An SQL string without the values
354 * @return string The input SQL string modified if necessary.
356 public static function cleanQuery($sql) {
357 $search = ["\t", "\n", "\r", " "];
358 $replace = [' ', ' ', ' ', ' '];
361 $sql = str_replace($search, $replace, $sql);
362 } while ($oldsql != $sql);
369 * @brief Replaces the ? placeholders with the parameters in the $args array
371 * @param string $sql SQL query
372 * @param array $args The parameters that are to replace the ? placeholders
373 * @return string The replaced SQL query
375 private static function replaceParameters($sql, $args) {
377 foreach ($args AS $param => $value) {
378 if (is_int($args[$param]) || is_float($args[$param])) {
379 $replace = intval($args[$param]);
381 $replace = "'".self::escape($args[$param])."'";
384 $pos = strpos($sql, '?', $offset);
385 if ($pos !== false) {
386 $sql = substr_replace($sql, $replace, $pos, 1);
388 $offset = $pos + strlen($replace);
394 * @brief Convert parameter array to an universal form
395 * @param array $args Parameter array
396 * @return array universalized parameter array
398 private static function getParam($args) {
401 // When the second function parameter is an array then use this as the parameter array
402 if ((count($args) > 0) && (is_array($args[1]))) {
410 * @brief Executes a prepared statement that returns data
411 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
413 * Please only use it with complicated queries.
414 * For all regular queries please use DBA::select or DBA::exists
416 * @param string $sql SQL statement
417 * @return bool|object statement object or result object
420 public static function p($sql) {
422 $stamp1 = microtime(true);
424 $params = self::getParam(func_get_args());
426 // Renumber the array keys to be sure that they fit
429 foreach ($params AS $param) {
430 // Avoid problems with some MySQL servers and boolean values. See issue #3645
431 if (is_bool($param)) {
432 $param = (int)$param;
434 $args[++$i] = $param;
437 if (!self::$connected) {
441 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
442 // Question: Should we continue or stop the query here?
443 self::$logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
446 $sql = self::cleanQuery($sql);
447 $sql = self::anyValueFallback($sql);
451 if (self::$configCache->get('system', 'db_callstack') !== null) {
452 $sql = "/*".System::callstack()." */ ".$sql;
457 self::$affected_rows = 0;
459 // We have to make some things different if this function is called from "e"
460 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
462 if (isset($trace[1])) {
463 $called_from = $trace[1];
465 // We use just something that is defined to avoid warnings
466 $called_from = $trace[0];
468 // We are having an own error logging in the function "e"
469 $called_from_e = ($called_from['function'] == 'e');
471 switch (self::$driver) {
473 // If there are no arguments we use "query"
474 if (count($args) == 0) {
475 if (!$retval = self::$connection->query($sql)) {
476 $errorInfo = self::$connection->errorInfo();
477 self::$error = $errorInfo[2];
478 self::$errorno = $errorInfo[1];
482 self::$affected_rows = $retval->rowCount();
486 if (!$stmt = self::$connection->prepare($sql)) {
487 $errorInfo = self::$connection->errorInfo();
488 self::$error = $errorInfo[2];
489 self::$errorno = $errorInfo[1];
494 foreach ($args AS $param => $value) {
495 if (is_int($args[$param])) {
496 $data_type = PDO::PARAM_INT;
498 $data_type = PDO::PARAM_STR;
500 $stmt->bindParam($param, $args[$param], $data_type);
503 if (!$stmt->execute()) {
504 $errorInfo = $stmt->errorInfo();
505 self::$error = $errorInfo[2];
506 self::$errorno = $errorInfo[1];
510 self::$affected_rows = $retval->rowCount();
514 // There are SQL statements that cannot be executed with a prepared statement
515 $parts = explode(' ', $orig_sql);
516 $command = strtolower($parts[0]);
517 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
519 // The fallback routine is called as well when there are no arguments
520 if (!$can_be_prepared || (count($args) == 0)) {
521 $retval = self::$connection->query(self::replaceParameters($sql, $args));
522 if (self::$connection->errno) {
523 self::$error = self::$connection->error;
524 self::$errorno = self::$connection->errno;
527 if (isset($retval->num_rows)) {
528 self::$affected_rows = $retval->num_rows;
530 self::$affected_rows = self::$connection->affected_rows;
536 $stmt = self::$connection->stmt_init();
538 if (!$stmt->prepare($sql)) {
539 self::$error = $stmt->error;
540 self::$errorno = $stmt->errno;
547 foreach ($args AS $param => $value) {
548 if (is_int($args[$param])) {
550 } elseif (is_float($args[$param])) {
552 } elseif (is_string($args[$param])) {
557 $values[] = &$args[$param];
560 if (count($values) > 0) {
561 array_unshift($values, $param_types);
562 call_user_func_array([$stmt, 'bind_param'], $values);
565 if (!$stmt->execute()) {
566 self::$error = self::$connection->error;
567 self::$errorno = self::$connection->errno;
570 $stmt->store_result();
572 self::$affected_rows = $retval->affected_rows;
577 // We are having an own error logging in the function "e"
578 if ((self::$errorno != 0) && !$called_from_e) {
579 // We have to preserve the error code, somewhere in the logging it get lost
580 $error = self::$error;
581 $errorno = self::$errorno;
583 self::$logger->error('DB Error', [
584 'code' => self::$errorno,
585 'error' => self::$error,
586 'callstack' => System::callstack(8),
587 'params' => self::replaceParameters($sql, $args),
590 // On a lost connection we try to reconnect - but only once.
591 if ($errorno == 2006) {
592 if (self::$in_retrial || !self::reconnect()) {
593 // It doesn't make sense to continue when the database connection was lost
594 if (self::$in_retrial) {
595 self::$logger->notice('Giving up retrial because of database error', [
596 'code' => self::$errorno,
597 'error' => self::$error,
600 self::$logger->notice('Couldn\'t reconnect after database error', [
601 'code' => self::$errorno,
602 'error' => self::$error,
608 self::$logger->notice('Reconnected after database error', [
609 'code' => self::$errorno,
610 'error' => self::$error,
612 self::$in_retrial = true;
613 $ret = self::p($sql, $args);
614 self::$in_retrial = false;
619 self::$error = $error;
620 self::$errorno = $errorno;
623 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
625 if (self::$configCache->get('system', 'db_log')) {
626 $stamp2 = microtime(true);
627 $duration = (float)($stamp2 - $stamp1);
629 if (($duration > self::$configCache->get('system', 'db_loglimit'))) {
630 $duration = round($duration, 3);
631 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
633 @file_put_contents(self::$configCache->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
634 basename($backtrace[1]["file"])."\t".
635 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
636 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
643 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
645 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
647 * @param string $sql SQL statement
648 * @return boolean Was the query successfull? False is returned only if an error occurred
651 public static function e($sql) {
653 $stamp = microtime(true);
655 $params = self::getParam(func_get_args());
657 // In a case of a deadlock we are repeating the query 20 times
661 $stmt = self::p($sql, $params);
663 if (is_bool($stmt)) {
665 } elseif (is_object($stmt)) {
673 } while ((self::$errorno == 1213) && (--$timeout > 0));
675 if (self::$errorno != 0) {
676 // We have to preserve the error code, somewhere in the logging it get lost
677 $error = self::$error;
678 $errorno = self::$errorno;
680 self::$logger->error('DB Error', [
681 'code' => self::$errorno,
682 'error' => self::$error,
683 'callstack' => System::callstack(8),
684 'params' => self::replaceParameters($sql, $params),
687 // On a lost connection we simply quit.
688 // A reconnect like in self::p could be dangerous with modifications
689 if ($errorno == 2006) {
690 self::$logger->notice('Giving up because of database error', [
691 'code' => self::$errorno,
692 'error' => self::$error,
697 self::$error = $error;
698 self::$errorno = $errorno;
701 self::$profiler->saveTimestamp($stamp, "database_write", System::callstack());
707 * @brief Check if data exists
709 * @param string $table Table name
710 * @param array $condition array of fields for condition
712 * @return boolean Are there rows for that condition?
715 public static function exists($table, $condition) {
722 if (empty($condition)) {
723 return DBStructure::existsTable($table);
727 $first_key = key($condition);
728 if (!is_int($first_key)) {
729 $fields = [$first_key];
732 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
734 if (is_bool($stmt)) {
737 $retval = (self::numRows($stmt) > 0);
746 * Fetches the first row
748 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
750 * @brief Fetches the first row
751 * @param string $sql SQL statement
752 * @return array first row of query
755 public static function fetchFirst($sql) {
756 $params = self::getParam(func_get_args());
758 $stmt = self::p($sql, $params);
760 if (is_bool($stmt)) {
763 $retval = self::fetch($stmt);
772 * @brief Returns the number of affected rows of the last statement
774 * @return int Number of rows
776 public static function affectedRows() {
777 return self::$affected_rows;
781 * @brief Returns the number of columns of a statement
783 * @param object Statement object
784 * @return int Number of columns
786 public static function columnCount($stmt) {
787 if (!is_object($stmt)) {
790 switch (self::$driver) {
792 return $stmt->columnCount();
794 return $stmt->field_count;
799 * @brief Returns the number of rows of a statement
801 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
802 * @return int Number of rows
804 public static function numRows($stmt) {
805 if (!is_object($stmt)) {
808 switch (self::$driver) {
810 return $stmt->rowCount();
812 return $stmt->num_rows;
818 * @brief Fetch a single row
820 * @param mixed $stmt statement object
821 * @return array current row
823 public static function fetch($stmt) {
825 $stamp1 = microtime(true);
829 if (!is_object($stmt)) {
833 switch (self::$driver) {
835 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
838 if (get_class($stmt) == 'mysqli_result') {
839 $columns = $stmt->fetch_assoc();
843 // This code works, but is slow
845 // Bind the result to a result array
849 for ($x = 0; $x < $stmt->field_count; $x++) {
850 $cols[] = &$cols_num[$x];
853 call_user_func_array([$stmt, 'bind_result'], $cols);
855 if (!$stmt->fetch()) {
860 // We need to get the field names for the array keys
861 // It seems that there is no better way to do this.
862 $result = $stmt->result_metadata();
863 $fields = $result->fetch_fields();
865 foreach ($cols_num AS $param => $col) {
866 $columns[$fields[$param]->name] = $col;
870 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
876 * @brief Insert a row into a table
878 * @param string $table Table name
879 * @param array $param parameter array
880 * @param bool $on_duplicate_update Do an update on a duplicate entry
882 * @return boolean was the insert successful?
885 public static function insert($table, $param, $on_duplicate_update = false) {
887 if (empty($table) || empty($param)) {
888 self::$logger->info('Table and fields have to be set');
892 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
893 substr(str_repeat("?, ", count($param)), 0, -2).")";
895 if ($on_duplicate_update) {
896 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
898 $values = array_values($param);
899 $param = array_merge_recursive($values, $values);
902 return self::e($sql, $param);
906 * @brief Fetch the id of the last insert command
908 * @return integer Last inserted id
910 public static function lastInsertId() {
911 switch (self::$driver) {
913 $id = self::$connection->lastInsertId();
916 $id = self::$connection->insert_id;
923 * @brief Locks a table for exclusive write access
925 * This function can be extended in the future to accept a table array as well.
927 * @param string $table Table name
929 * @return boolean was the lock successful?
932 public static function lock($table) {
933 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
934 if (self::$driver == 'pdo') {
935 self::e("SET autocommit=0");
936 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
938 self::$connection->autocommit(false);
941 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
943 if (self::$driver == 'pdo') {
944 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
948 if (self::$driver == 'pdo') {
949 self::e("SET autocommit=1");
951 self::$connection->autocommit(true);
954 self::$in_transaction = true;
960 * @brief Unlocks all locked tables
962 * @return boolean was the unlock successful?
965 public static function unlock() {
966 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
967 self::performCommit();
969 if (self::$driver == 'pdo') {
970 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
973 $success = self::e("UNLOCK TABLES");
975 if (self::$driver == 'pdo') {
976 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
977 self::e("SET autocommit=1");
979 self::$connection->autocommit(true);
982 self::$in_transaction = false;
987 * @brief Starts a transaction
989 * @return boolean Was the command executed successfully?
991 public static function transaction() {
992 if (!self::performCommit()) {
996 switch (self::$driver) {
998 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
1004 if (!self::$connection->begin_transaction()) {
1010 self::$in_transaction = true;
1014 private static function performCommit()
1016 switch (self::$driver) {
1018 if (!self::$connection->inTransaction()) {
1022 return self::$connection->commit();
1025 return self::$connection->commit();
1032 * @brief Does a commit
1034 * @return boolean Was the command executed successfully?
1036 public static function commit() {
1037 if (!self::performCommit()) {
1040 self::$in_transaction = false;
1045 * @brief Does a rollback
1047 * @return boolean Was the command executed successfully?
1049 public static function rollback() {
1052 switch (self::$driver) {
1054 if (!self::$connection->inTransaction()) {
1058 $ret = self::$connection->rollBack();
1062 $ret = self::$connection->rollback();
1065 self::$in_transaction = false;
1070 * @brief Build the array with the table relations
1072 * The array is build from the database definitions in DBStructure.php
1074 * This process must only be started once, since the value is cached.
1076 private static function buildRelationData() {
1077 $definition = DBStructure::definition(self::$configCache->get('system', 'basepath'));
1079 foreach ($definition AS $table => $structure) {
1080 foreach ($structure['fields'] AS $field => $field_struct) {
1081 if (isset($field_struct['relation'])) {
1082 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1083 self::$relation[$rel_table][$rel_field][$table][] = $field;
1091 * @brief Delete a row from a table
1093 * @param string $table Table name
1094 * @param array $conditions Field condition(s)
1095 * @param array $options
1096 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1097 * relations (default: true)
1098 * @param array $callstack Internal use: prevent endless loops
1100 * @return boolean was the delete successful?
1101 * @throws \Exception
1103 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1105 if (empty($table) || empty($conditions)) {
1106 self::$logger->info('Table and conditions have to be set');
1112 // Create a key for the loop prevention
1113 $key = $table . ':' . json_encode($conditions);
1115 // We quit when this key already exists in the callstack.
1116 if (isset($callstack[$key])) {
1120 $callstack[$key] = true;
1122 $table = self::escape($table);
1124 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1126 // Don't use "defaults" here, since it would set "false" to "true"
1127 if (isset($options['cascade'])) {
1128 $cascade = $options['cascade'];
1133 // To speed up the whole process we cache the table relations
1134 if ($cascade && count(self::$relation) == 0) {
1135 self::buildRelationData();
1138 // Is there a relation entry for the table?
1139 if ($cascade && isset(self::$relation[$table])) {
1140 // We only allow a simple "one field" relation.
1141 $field = array_keys(self::$relation[$table])[0];
1142 $rel_def = array_values(self::$relation[$table])[0];
1144 // Create a key for preventing double queries
1145 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1147 // When the search field is the relation field, we don't need to fetch the rows
1148 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1149 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1150 foreach ($rel_def AS $rel_table => $rel_fields) {
1151 foreach ($rel_fields AS $rel_field) {
1152 self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1155 // We quit when this key already exists in the callstack.
1156 } elseif (!isset($callstack[$qkey])) {
1157 $callstack[$qkey] = true;
1159 // Fetch all rows that are to be deleted
1160 $data = self::select($table, [$field], $conditions);
1162 while ($row = self::fetch($data)) {
1163 self::delete($table, [$field => $row[$field]], $options, $callstack);
1168 // Since we had split the delete command we don't need the original command anymore
1169 unset($commands[$key]);
1173 // Now we finalize the process
1174 $do_transaction = !self::$in_transaction;
1176 if ($do_transaction) {
1177 self::transaction();
1183 foreach ($commands AS $command) {
1184 $conditions = $command['conditions'];
1186 $first_key = key($conditions);
1188 $condition_string = self::buildCondition($conditions);
1190 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1191 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1192 self::$logger->debug(self::replaceParameters($sql, $conditions));
1194 if (!self::e($sql, $conditions)) {
1195 if ($do_transaction) {
1201 $key_table = $command['table'];
1202 $key_condition = array_keys($command['conditions'])[0];
1203 $value = array_values($command['conditions'])[0];
1205 // Split the SQL queries in chunks of 100 values
1206 // We do the $i stuff here to make the code better readable
1207 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1208 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1212 $compacted[$key_table][$key_condition][$i][$value] = $value;
1213 $counter[$key_table][$key_condition] = $i;
1216 foreach ($compacted AS $table => $values) {
1217 foreach ($values AS $field => $field_value_list) {
1218 foreach ($field_value_list AS $field_values) {
1219 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1220 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1222 self::$logger->debug(self::replaceParameters($sql, $field_values));
1224 if (!self::e($sql, $field_values)) {
1225 if ($do_transaction) {
1233 if ($do_transaction) {
1240 * @brief Updates rows
1242 * Updates rows in the database. When $old_fields is set to an array,
1243 * the system will only do an update if the fields in that array changed.
1246 * Only the values in $old_fields are compared.
1247 * This is an intentional behaviour.
1250 * We include the timestamp field in $fields but not in $old_fields.
1251 * Then the row will only get the new timestamp when the other fields had changed.
1253 * When $old_fields is set to a boolean value the system will do this compare itself.
1254 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1257 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1258 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1260 * @param string $table Table name
1261 * @param array $fields contains the fields that are updated
1262 * @param array $condition condition array with the key values
1263 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1265 * @return boolean was the update successfull?
1266 * @throws \Exception
1268 public static function update($table, $fields, $condition, $old_fields = []) {
1270 if (empty($table) || empty($fields) || empty($condition)) {
1271 self::$logger->info('Table, fields and condition have to be set');
1275 $table = self::escape($table);
1277 $condition_string = self::buildCondition($condition);
1279 if (is_bool($old_fields)) {
1280 $do_insert = $old_fields;
1282 $old_fields = self::selectFirst($table, [], $condition);
1284 if (is_bool($old_fields)) {
1286 $values = array_merge($condition, $fields);
1287 return self::insert($table, $values, $do_insert);
1293 $do_update = (count($old_fields) == 0);
1295 foreach ($old_fields AS $fieldname => $content) {
1296 if (isset($fields[$fieldname])) {
1297 if (($fields[$fieldname] == $content) && !is_null($content)) {
1298 unset($fields[$fieldname]);
1305 if (!$do_update || (count($fields) == 0)) {
1309 $sql = "UPDATE `".$table."` SET `".
1310 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1312 $params1 = array_values($fields);
1313 $params2 = array_values($condition);
1314 $params = array_merge_recursive($params1, $params2);
1316 return self::e($sql, $params);
1320 * Retrieve a single record from a table and returns it in an associative array
1322 * @brief Retrieve a single record from a table
1323 * @param string $table
1324 * @param array $fields
1325 * @param array $condition
1326 * @param array $params
1327 * @return bool|array
1328 * @throws \Exception
1331 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1333 $params['limit'] = 1;
1334 $result = self::select($table, $fields, $condition, $params);
1336 if (is_bool($result)) {
1339 $row = self::fetch($result);
1340 self::close($result);
1346 * @brief Select rows from a table
1348 * @param string $table Table name
1349 * @param array $fields Array of selected fields, empty for all
1350 * @param array $condition Array of fields for condition
1351 * @param array $params Array of several parameters
1353 * @return boolean|object
1357 * $fields = array("id", "uri", "uid", "network");
1359 * $condition = array("uid" => 1, "network" => 'dspr');
1361 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1363 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1365 * $data = DBA::select($table, $fields, $condition, $params);
1366 * @throws \Exception
1368 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1374 $table = self::escape($table);
1376 if (count($fields) > 0) {
1377 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1379 $select_fields = "*";
1382 $condition_string = self::buildCondition($condition);
1384 $param_string = self::buildParameter($params);
1386 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1388 $result = self::p($sql, $condition);
1394 * @brief Counts the rows from a table satisfying the provided condition
1396 * @param string $table Table name
1397 * @param array $condition array of fields for condition
1404 * $condition = ["uid" => 1, "network" => 'dspr'];
1406 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1408 * $count = DBA::count($table, $condition);
1409 * @throws \Exception
1411 public static function count($table, array $condition = [])
1417 $condition_string = self::buildCondition($condition);
1419 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1421 $row = self::fetchFirst($sql, $condition);
1423 return $row['count'];
1427 * @brief Returns the SQL condition string built from the provided condition array
1429 * This function operates with two modes.
1430 * - Supplied with a filed/value associative array, it builds simple strict
1431 * equality conditions linked by AND.
1432 * - Supplied with a flat list, the first element is the condition string and
1433 * the following arguments are the values to be interpolated
1435 * $condition = ["uid" => 1, "network" => 'dspr'];
1437 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1439 * In either case, the provided array is left with the parameters only
1441 * @param array $condition
1444 public static function buildCondition(array &$condition = [])
1446 $condition_string = '';
1447 if (count($condition) > 0) {
1449 $first_key = key($condition);
1450 if (is_int($first_key)) {
1451 $condition_string = " WHERE (" . array_shift($condition) . ")";
1454 $condition_string = "";
1455 foreach ($condition as $field => $value) {
1456 if ($condition_string != "") {
1457 $condition_string .= " AND ";
1459 if (is_array($value)) {
1460 /* Workaround for MySQL Bug #64791.
1461 * Never mix data types inside any IN() condition.
1462 * In case of mixed types, cast all as string.
1463 * Logic needs to be consistent with DBA::p() data types.
1467 foreach ($value as $single_value) {
1468 if (is_int($single_value)) {
1475 if ($is_int && $is_alpha) {
1476 foreach ($value as &$ref) {
1478 $ref = (string)$ref;
1481 unset($ref); //Prevent accidental re-use.
1484 $new_values = array_merge($new_values, array_values($value));
1485 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1486 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1488 $new_values[$field] = $value;
1489 $condition_string .= "`" . $field . "` = ?";
1492 $condition_string = " WHERE (" . $condition_string . ")";
1493 $condition = $new_values;
1497 return $condition_string;
1501 * @brief Returns the SQL parameter string built from the provided parameter array
1503 * @param array $params
1506 public static function buildParameter(array $params = [])
1509 if (isset($params['order'])) {
1510 $order_string = " ORDER BY ";
1511 foreach ($params['order'] AS $fields => $order) {
1512 if (!is_int($fields)) {
1513 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1515 $order_string .= "`" . $order . "`, ";
1518 $order_string = substr($order_string, 0, -2);
1522 if (isset($params['limit']) && is_numeric($params['limit'])) {
1523 $limit_string = " LIMIT " . intval($params['limit']);
1526 if (isset($params['limit']) && is_array($params['limit'])) {
1527 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1530 return $order_string.$limit_string;
1534 * @brief Fills an array with data from a query
1536 * @param object $stmt statement object
1537 * @param bool $do_close
1538 * @return array Data array
1540 public static function toArray($stmt, $do_close = true) {
1541 if (is_bool($stmt)) {
1546 while ($row = self::fetch($stmt)) {
1556 * @brief Returns the error number of the last query
1558 * @return string Error number (0 if no error)
1560 public static function errorNo() {
1561 return self::$errorno;
1565 * @brief Returns the error message of the last query
1567 * @return string Error message ('' if no error)
1569 public static function errorMessage() {
1570 return self::$error;
1574 * @brief Closes the current statement
1576 * @param object $stmt statement object
1577 * @return boolean was the close successful?
1579 public static function close($stmt) {
1581 $stamp1 = microtime(true);
1583 if (!is_object($stmt)) {
1587 switch (self::$driver) {
1589 $ret = $stmt->closeCursor();
1592 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1593 // We should be careful not to assume the object type of $stmt
1594 // because DBA::p() has been able to return both types.
1595 if ($stmt instanceof mysqli_stmt) {
1596 $stmt->free_result();
1597 $ret = $stmt->close();
1598 } elseif ($stmt instanceof mysqli_result) {
1607 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
1613 * @brief Return a list of database processes
1616 * 'list' => List of processes, separated in their different states
1617 * 'amount' => Number of concurrent database processes
1618 * @throws \Exception
1620 public static function processlist()
1622 $ret = self::p("SHOW PROCESSLIST");
1623 $data = self::toArray($ret);
1627 foreach ($data as $process) {
1628 $state = trim($process["State"]);
1630 // Filter out all non blocking processes
1631 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1638 foreach ($states as $state => $usage) {
1639 if ($statelist != "") {
1642 $statelist .= $state.": ".$usage;
1644 return(["list" => $statelist, "amount" => $processes]);
1648 * Checks if $array is a filled array with at least one entry.
1650 * @param mixed $array A filled array with at least one entry
1652 * @return boolean Whether $array is a filled array or an object with rows
1654 public static function isResult($array)
1656 // It could be a return value from an update statement
1657 if (is_bool($array)) {
1661 if (is_object($array)) {
1662 return self::numRows($array) > 0;
1665 return (is_array($array) && (count($array) > 0));
1669 * @brief Callback function for "esc_array"
1671 * @param mixed $value Array value
1672 * @param string $key Array key
1673 * @param boolean $add_quotation add quotation marks for string values
1676 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1678 if (!$add_quotation) {
1679 if (is_bool($value)) {
1680 $value = ($value ? '1' : '0');
1682 $value = self::escape($value);
1687 if (is_bool($value)) {
1688 $value = ($value ? 'true' : 'false');
1689 } elseif (is_float($value) || is_integer($value)) {
1690 $value = (string) $value;
1692 $value = "'" . self::escape($value) . "'";
1697 * @brief Escapes a whole array
1699 * @param mixed $arr Array with values to be escaped
1700 * @param boolean $add_quotation add quotation marks for string values
1703 public static function escapeArray(&$arr, $add_quotation = false)
1705 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);