3 namespace Friendica\Database;
5 // Do not use Core\Config in this class at risk of infinite loop.
6 // Please use App->getConfigVariable() instead.
7 //use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Util\DateTimeFormat;
18 require_once 'include/dba.php';
21 * @class MySQL database class
23 * This class is for the low level database stuff that does driver specific things.
27 public static $connected = false;
29 private static $server_info = '';
30 private static $connection;
31 private static $driver;
32 private static $error = false;
33 private static $errorno = 0;
34 private static $affected_rows = 0;
35 private static $in_transaction = false;
36 private static $in_retrial = false;
37 private static $relation = [];
38 private static $db_serveraddr = '';
39 private static $db_user = '';
40 private static $db_pass = '';
41 private static $db_name = '';
42 private static $db_charset = '';
44 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
46 if (!is_null(self::$connection) && self::connected()) {
50 // We are storing these values for being able to perform a reconnect
51 self::$db_serveraddr = $serveraddr;
52 self::$db_user = $user;
53 self::$db_pass = $pass;
55 self::$db_charset = $charset;
58 $serveraddr = trim($serveraddr);
60 $serverdata = explode(':', $serveraddr);
61 $server = $serverdata[0];
63 if (count($serverdata) > 1) {
64 $port = trim($serverdata[1]);
67 $server = trim($server);
71 $charset = trim($charset);
73 if (!(strlen($server) && strlen($user))) {
77 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
78 self::$driver = 'pdo';
79 $connect = "mysql:host=".$server.";dbname=".$db;
82 $connect .= ";port=".$port;
86 $connect .= ";charset=".$charset;
90 self::$connection = @new PDO($connect, $user, $pass);
91 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
92 self::$connected = true;
93 } catch (PDOException $e) {
94 /// @TODO At least log exception, don't ignore it!
98 if (!self::$connected && class_exists('\mysqli')) {
99 self::$driver = 'mysqli';
102 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
104 self::$connection = @new mysqli($server, $user, $pass, $db);
107 if (!mysqli_connect_errno()) {
108 self::$connected = true;
111 self::$connection->set_charset($charset);
116 // No suitable SQL driver was found.
117 if (!self::$connected) {
118 self::$driver = null;
119 self::$connection = null;
122 return self::$connected;
126 * Disconnects the current database connection
128 public static function disconnect()
130 if (is_null(self::$connection)) {
134 switch (self::$driver) {
136 self::$connection = null;
139 self::$connection->close();
140 self::$connection = null;
146 * Perform a reconnect of an existing database connection
148 public static function reconnect() {
151 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
156 * Return the database object.
159 public static function getConnection()
161 return self::$connection;
165 * @brief Returns the MySQL server version string
167 * This function discriminate between the deprecated mysql API and the current
168 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
172 public static function serverInfo() {
173 if (self::$server_info == '') {
174 switch (self::$driver) {
176 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
179 self::$server_info = self::$connection->server_info;
183 return self::$server_info;
187 * @brief Returns the selected database name
191 public static function databaseName() {
192 $ret = self::p("SELECT DATABASE() AS `db`");
193 $data = self::toArray($ret);
194 return $data[0]['db'];
198 * @brief Analyze a database query and log this if some conditions are met.
200 * @param string $query The database query that will be analyzed
202 private static function logIndex($query) {
205 if (!$a->getConfigVariable('system', 'db_log_index')) {
209 // Don't explain an explain statement
210 if (strtolower(substr($query, 0, 7)) == "explain") {
214 // Only do the explain on "select", "update" and "delete"
215 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
219 $r = self::p("EXPLAIN ".$query);
220 if (!self::isResult($r)) {
224 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
225 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
227 while ($row = self::fetch($r)) {
228 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
229 $log = (in_array($row['key'], $watchlist) &&
230 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
235 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
239 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
244 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
245 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
246 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
247 basename($backtrace[1]["file"])."\t".
248 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
249 substr($query, 0, 2000)."\n", FILE_APPEND);
254 public static function escape($str) {
255 if (self::$connected) {
256 switch (self::$driver) {
258 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
261 return @self::$connection->real_escape_string($str);
264 return str_replace("'", "\\'", $str);
268 public static function connected() {
271 if (is_null(self::$connection)) {
275 switch (self::$driver) {
277 $r = self::p("SELECT 1");
278 if (self::isResult($r)) {
279 $row = self::toArray($r);
280 $connected = ($row[0]['1'] == '1');
284 $connected = self::$connection->ping();
291 * @brief Replaces ANY_VALUE() function by MIN() function,
292 * if the database server does not support ANY_VALUE().
294 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
295 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
296 * A standard fall-back is to use MIN().
298 * @param string $sql An SQL string without the values
299 * @return string The input SQL string modified if necessary.
301 public static function anyValueFallback($sql) {
302 $server_info = self::serverInfo();
303 if (version_compare($server_info, '5.7.5', '<') ||
304 (stripos($server_info, 'MariaDB') !== false)) {
305 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
311 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
313 * This is safe when we bind the parameters later.
314 * The parameter values aren't part of the SQL.
316 * @param string $sql An SQL string without the values
317 * @return string The input SQL string modified if necessary.
319 public static function cleanQuery($sql) {
320 $search = ["\t", "\n", "\r", " "];
321 $replace = [' ', ' ', ' ', ' '];
324 $sql = str_replace($search, $replace, $sql);
325 } while ($oldsql != $sql);
332 * @brief Replaces the ? placeholders with the parameters in the $args array
334 * @param string $sql SQL query
335 * @param array $args The parameters that are to replace the ? placeholders
336 * @return string The replaced SQL query
338 private static function replaceParameters($sql, $args) {
340 foreach ($args AS $param => $value) {
341 if (is_int($args[$param]) || is_float($args[$param])) {
342 $replace = intval($args[$param]);
344 $replace = "'".self::escape($args[$param])."'";
347 $pos = strpos($sql, '?', $offset);
348 if ($pos !== false) {
349 $sql = substr_replace($sql, $replace, $pos, 1);
351 $offset = $pos + strlen($replace);
357 * @brief Convert parameter array to an universal form
358 * @param array $args Parameter array
359 * @return array universalized parameter array
361 private static function getParam($args) {
364 // When the second function parameter is an array then use this as the parameter array
365 if ((count($args) > 0) && (is_array($args[1]))) {
373 * @brief Executes a prepared statement that returns data
374 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
376 * Please only use it with complicated queries.
377 * For all regular queries please use DBA::select or DBA::exists
379 * @param string $sql SQL statement
380 * @return bool|object statement object or result object
382 public static function p($sql) {
385 $stamp1 = microtime(true);
387 $params = self::getParam(func_get_args());
389 // Renumber the array keys to be sure that they fit
392 foreach ($params AS $param) {
393 // Avoid problems with some MySQL servers and boolean values. See issue #3645
394 if (is_bool($param)) {
395 $param = (int)$param;
397 $args[++$i] = $param;
400 if (!self::$connected) {
404 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
405 // Question: Should we continue or stop the query here?
406 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
409 $sql = self::cleanQuery($sql);
410 $sql = self::anyValueFallback($sql);
414 if ($a->getConfigValue('system', 'db_callstack')) {
415 $sql = "/*".System::callstack()." */ ".$sql;
420 self::$affected_rows = 0;
422 // We have to make some things different if this function is called from "e"
423 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
425 if (isset($trace[1])) {
426 $called_from = $trace[1];
428 // We use just something that is defined to avoid warnings
429 $called_from = $trace[0];
431 // We are having an own error logging in the function "e"
432 $called_from_e = ($called_from['function'] == 'e');
434 switch (self::$driver) {
436 // If there are no arguments we use "query"
437 if (count($args) == 0) {
438 if (!$retval = self::$connection->query($sql)) {
439 $errorInfo = self::$connection->errorInfo();
440 self::$error = $errorInfo[2];
441 self::$errorno = $errorInfo[1];
445 self::$affected_rows = $retval->rowCount();
449 if (!$stmt = self::$connection->prepare($sql)) {
450 $errorInfo = self::$connection->errorInfo();
451 self::$error = $errorInfo[2];
452 self::$errorno = $errorInfo[1];
457 foreach ($args AS $param => $value) {
458 if (is_int($args[$param])) {
459 $data_type = PDO::PARAM_INT;
461 $data_type = PDO::PARAM_STR;
463 $stmt->bindParam($param, $args[$param], $data_type);
466 if (!$stmt->execute()) {
467 $errorInfo = $stmt->errorInfo();
468 self::$error = $errorInfo[2];
469 self::$errorno = $errorInfo[1];
473 self::$affected_rows = $retval->rowCount();
477 // There are SQL statements that cannot be executed with a prepared statement
478 $parts = explode(' ', $orig_sql);
479 $command = strtolower($parts[0]);
480 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
482 // The fallback routine is called as well when there are no arguments
483 if (!$can_be_prepared || (count($args) == 0)) {
484 $retval = self::$connection->query(self::replaceParameters($sql, $args));
485 if (self::$connection->errno) {
486 self::$error = self::$connection->error;
487 self::$errorno = self::$connection->errno;
490 if (isset($retval->num_rows)) {
491 self::$affected_rows = $retval->num_rows;
493 self::$affected_rows = self::$connection->affected_rows;
499 $stmt = self::$connection->stmt_init();
501 if (!$stmt->prepare($sql)) {
502 self::$error = $stmt->error;
503 self::$errorno = $stmt->errno;
510 foreach ($args AS $param => $value) {
511 if (is_int($args[$param])) {
513 } elseif (is_float($args[$param])) {
515 } elseif (is_string($args[$param])) {
520 $values[] = &$args[$param];
523 if (count($values) > 0) {
524 array_unshift($values, $param_types);
525 call_user_func_array([$stmt, 'bind_param'], $values);
528 if (!$stmt->execute()) {
529 self::$error = self::$connection->error;
530 self::$errorno = self::$connection->errno;
533 $stmt->store_result();
535 self::$affected_rows = $retval->affected_rows;
540 // We are having an own error logging in the function "e"
541 if ((self::$errorno != 0) && !$called_from_e) {
542 // We have to preserve the error code, somewhere in the logging it get lost
543 $error = self::$error;
544 $errorno = self::$errorno;
546 logger('DB Error '.self::$errorno.': '.self::$error."\n".
547 System::callstack(8)."\n".self::replaceParameters($sql, $args));
549 // On a lost connection we try to reconnect - but only once.
550 if ($errorno == 2006) {
551 if (self::$in_retrial || !self::reconnect()) {
552 // It doesn't make sense to continue when the database connection was lost
553 if (self::$in_retrial) {
554 logger('Giving up retrial because of database error '.$errorno.': '.$error);
556 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
561 logger('Reconnected after database error '.$errorno.': '.$error);
562 self::$in_retrial = true;
563 $ret = self::p($sql, $args);
564 self::$in_retrial = false;
569 self::$error = $error;
570 self::$errorno = $errorno;
573 $a->saveTimestamp($stamp1, 'database');
575 if ($a->getConfigValue('system', 'db_log')) {
576 $stamp2 = microtime(true);
577 $duration = (float)($stamp2 - $stamp1);
579 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
580 $duration = round($duration, 3);
581 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
583 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
584 basename($backtrace[1]["file"])."\t".
585 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
586 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
593 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
595 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
597 * @param string $sql SQL statement
598 * @return boolean Was the query successfull? False is returned only if an error occurred
600 public static function e($sql) {
603 $stamp = microtime(true);
605 $params = self::getParam(func_get_args());
607 // In a case of a deadlock we are repeating the query 20 times
611 $stmt = self::p($sql, $params);
613 if (is_bool($stmt)) {
615 } elseif (is_object($stmt)) {
623 } while ((self::$errorno == 1213) && (--$timeout > 0));
625 if (self::$errorno != 0) {
626 // We have to preserve the error code, somewhere in the logging it get lost
627 $error = self::$error;
628 $errorno = self::$errorno;
630 logger('DB Error '.self::$errorno.': '.self::$error."\n".
631 System::callstack(8)."\n".self::replaceParameters($sql, $params));
633 // On a lost connection we simply quit.
634 // A reconnect like in self::p could be dangerous with modifications
635 if ($errorno == 2006) {
636 logger('Giving up because of database error '.$errorno.': '.$error);
640 self::$error = $error;
641 self::$errorno = $errorno;
644 $a->saveTimestamp($stamp, "database_write");
650 * @brief Check if data exists
652 * @param string $table Table name
653 * @param array $condition array of fields for condition
655 * @return boolean Are there rows for that condition?
657 public static function exists($table, $condition) {
664 if (empty($condition)) {
665 return DBStructure::existsTable($table);
669 $first_key = key($condition);
670 if (!is_int($first_key)) {
671 $fields = [$first_key];
674 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
676 if (is_bool($stmt)) {
679 $retval = (self::numRows($stmt) > 0);
688 * Fetches the first row
690 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
692 * @brief Fetches the first row
693 * @param string $sql SQL statement
694 * @return array first row of query
696 public static function fetchFirst($sql) {
697 $params = self::getParam(func_get_args());
699 $stmt = self::p($sql, $params);
701 if (is_bool($stmt)) {
704 $retval = self::fetch($stmt);
713 * @brief Returns the number of affected rows of the last statement
715 * @return int Number of rows
717 public static function affectedRows() {
718 return self::$affected_rows;
722 * @brief Returns the number of columns of a statement
724 * @param object Statement object
725 * @return int Number of columns
727 public static function columnCount($stmt) {
728 if (!is_object($stmt)) {
731 switch (self::$driver) {
733 return $stmt->columnCount();
735 return $stmt->field_count;
740 * @brief Returns the number of rows of a statement
742 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
743 * @return int Number of rows
745 public static function numRows($stmt) {
746 if (!is_object($stmt)) {
749 switch (self::$driver) {
751 return $stmt->rowCount();
753 return $stmt->num_rows;
759 * @brief Fetch a single row
761 * @param mixed $stmt statement object
762 * @return array current row
764 public static function fetch($stmt) {
767 $stamp1 = microtime(true);
771 if (!is_object($stmt)) {
775 switch (self::$driver) {
777 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
780 if (get_class($stmt) == 'mysqli_result') {
781 $columns = $stmt->fetch_assoc();
785 // This code works, but is slow
787 // Bind the result to a result array
791 for ($x = 0; $x < $stmt->field_count; $x++) {
792 $cols[] = &$cols_num[$x];
795 call_user_func_array([$stmt, 'bind_result'], $cols);
797 if (!$stmt->fetch()) {
802 // We need to get the field names for the array keys
803 // It seems that there is no better way to do this.
804 $result = $stmt->result_metadata();
805 $fields = $result->fetch_fields();
807 foreach ($cols_num AS $param => $col) {
808 $columns[$fields[$param]->name] = $col;
812 $a->saveTimestamp($stamp1, 'database');
818 * @brief Insert a row into a table
820 * @param string $table Table name
821 * @param array $param parameter array
822 * @param bool $on_duplicate_update Do an update on a duplicate entry
824 * @return boolean was the insert successfull?
826 public static function insert($table, $param, $on_duplicate_update = false) {
828 if (empty($table) || empty($param)) {
829 logger('Table and fields have to be set');
833 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
834 substr(str_repeat("?, ", count($param)), 0, -2).")";
836 if ($on_duplicate_update) {
837 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
839 $values = array_values($param);
840 $param = array_merge_recursive($values, $values);
843 return self::e($sql, $param);
847 * @brief Fetch the id of the last insert command
849 * @return integer Last inserted id
851 public static function lastInsertId() {
852 switch (self::$driver) {
854 $id = self::$connection->lastInsertId();
857 $id = self::$connection->insert_id;
864 * @brief Locks a table for exclusive write access
866 * This function can be extended in the future to accept a table array as well.
868 * @param string $table Table name
870 * @return boolean was the lock successful?
872 public static function lock($table) {
873 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
874 if (self::$driver == 'pdo') {
875 self::e("SET autocommit=0");
876 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
878 self::$connection->autocommit(false);
881 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
883 if (self::$driver == 'pdo') {
884 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
888 if (self::$driver == 'pdo') {
889 self::e("SET autocommit=1");
891 self::$connection->autocommit(true);
894 self::$in_transaction = true;
900 * @brief Unlocks all locked tables
902 * @return boolean was the unlock successful?
904 public static function unlock() {
905 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
906 self::performCommit();
908 if (self::$driver == 'pdo') {
909 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
912 $success = self::e("UNLOCK TABLES");
914 if (self::$driver == 'pdo') {
915 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
916 self::e("SET autocommit=1");
918 self::$connection->autocommit(true);
921 self::$in_transaction = false;
926 * @brief Starts a transaction
928 * @return boolean Was the command executed successfully?
930 public static function transaction() {
931 if (!self::performCommit()) {
935 switch (self::$driver) {
937 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
943 if (!self::$connection->begin_transaction()) {
949 self::$in_transaction = true;
953 private static function performCommit()
955 switch (self::$driver) {
957 if (!self::$connection->inTransaction()) {
961 return self::$connection->commit();
964 return self::$connection->commit();
971 * @brief Does a commit
973 * @return boolean Was the command executed successfully?
975 public static function commit() {
976 if (!self::performCommit()) {
979 self::$in_transaction = false;
984 * @brief Does a rollback
986 * @return boolean Was the command executed successfully?
988 public static function rollback() {
991 switch (self::$driver) {
993 if (!self::$connection->inTransaction()) {
997 $ret = self::$connection->rollBack();
1001 $ret = self::$connection->rollback();
1004 self::$in_transaction = false;
1009 * @brief Build the array with the table relations
1011 * The array is build from the database definitions in DBStructure.php
1013 * This process must only be started once, since the value is cached.
1015 private static function buildRelationData() {
1016 $definition = DBStructure::definition();
1018 foreach ($definition AS $table => $structure) {
1019 foreach ($structure['fields'] AS $field => $field_struct) {
1020 if (isset($field_struct['relation'])) {
1021 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1022 self::$relation[$rel_table][$rel_field][$table][] = $field;
1030 * @brief Delete a row from a table
1032 * @param string $table Table name
1033 * @param array $conditions Field condition(s)
1034 * @param array $options
1035 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1036 * relations (default: true)
1037 * @param boolean $in_process Internal use: Only do a commit after the last delete
1038 * @param array $callstack Internal use: prevent endless loops
1040 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1042 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1044 if (empty($table) || empty($conditions)) {
1045 logger('Table and conditions have to be set');
1051 // Create a key for the loop prevention
1052 $key = $table . ':' . json_encode($conditions);
1054 // We quit when this key already exists in the callstack.
1055 if (isset($callstack[$key])) {
1059 $callstack[$key] = true;
1061 $table = self::escape($table);
1063 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1065 // Don't use "defaults" here, since it would set "false" to "true"
1066 if (isset($options['cascade'])) {
1067 $cascade = $options['cascade'];
1072 // To speed up the whole process we cache the table relations
1073 if ($cascade && count(self::$relation) == 0) {
1074 self::buildRelationData();
1077 // Is there a relation entry for the table?
1078 if ($cascade && isset(self::$relation[$table])) {
1079 // We only allow a simple "one field" relation.
1080 $field = array_keys(self::$relation[$table])[0];
1081 $rel_def = array_values(self::$relation[$table])[0];
1083 // Create a key for preventing double queries
1084 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1086 // When the search field is the relation field, we don't need to fetch the rows
1087 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1088 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1089 foreach ($rel_def AS $rel_table => $rel_fields) {
1090 foreach ($rel_fields AS $rel_field) {
1091 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1092 $commands = array_merge($commands, $retval);
1095 // We quit when this key already exists in the callstack.
1096 } elseif (!isset($callstack[$qkey])) {
1098 $callstack[$qkey] = true;
1100 // Fetch all rows that are to be deleted
1101 $data = self::select($table, [$field], $conditions);
1103 while ($row = self::fetch($data)) {
1104 // Now we accumulate the delete commands
1105 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1106 $commands = array_merge($commands, $retval);
1111 // Since we had split the delete command we don't need the original command anymore
1112 unset($commands[$key]);
1117 // Now we finalize the process
1118 $do_transaction = !self::$in_transaction;
1120 if ($do_transaction) {
1121 self::transaction();
1127 foreach ($commands AS $command) {
1128 $conditions = $command['conditions'];
1130 $first_key = key($conditions);
1132 $condition_string = self::buildCondition($conditions);
1134 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1135 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1136 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1138 if (!self::e($sql, $conditions)) {
1139 if ($do_transaction) {
1145 $key_table = $command['table'];
1146 $key_condition = array_keys($command['conditions'])[0];
1147 $value = array_values($command['conditions'])[0];
1149 // Split the SQL queries in chunks of 100 values
1150 // We do the $i stuff here to make the code better readable
1151 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1152 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1156 $compacted[$key_table][$key_condition][$i][$value] = $value;
1157 $counter[$key_table][$key_condition] = $i;
1160 foreach ($compacted AS $table => $values) {
1161 foreach ($values AS $field => $field_value_list) {
1162 foreach ($field_value_list AS $field_values) {
1163 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1164 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1166 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1168 if (!self::e($sql, $field_values)) {
1169 if ($do_transaction) {
1177 if ($do_transaction) {
1187 * @brief Updates rows
1189 * Updates rows in the database. When $old_fields is set to an array,
1190 * the system will only do an update if the fields in that array changed.
1193 * Only the values in $old_fields are compared.
1194 * This is an intentional behaviour.
1197 * We include the timestamp field in $fields but not in $old_fields.
1198 * Then the row will only get the new timestamp when the other fields had changed.
1200 * When $old_fields is set to a boolean value the system will do this compare itself.
1201 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1204 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1205 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1207 * @param string $table Table name
1208 * @param array $fields contains the fields that are updated
1209 * @param array $condition condition array with the key values
1210 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1212 * @return boolean was the update successfull?
1214 public static function update($table, $fields, $condition, $old_fields = []) {
1216 if (empty($table) || empty($fields) || empty($condition)) {
1217 logger('Table, fields and condition have to be set');
1221 $table = self::escape($table);
1223 $condition_string = self::buildCondition($condition);
1225 if (is_bool($old_fields)) {
1226 $do_insert = $old_fields;
1228 $old_fields = self::selectFirst($table, [], $condition);
1230 if (is_bool($old_fields)) {
1232 $values = array_merge($condition, $fields);
1233 return self::insert($table, $values, $do_insert);
1239 $do_update = (count($old_fields) == 0);
1241 foreach ($old_fields AS $fieldname => $content) {
1242 if (isset($fields[$fieldname])) {
1243 if ($fields[$fieldname] == $content) {
1244 unset($fields[$fieldname]);
1251 if (!$do_update || (count($fields) == 0)) {
1255 $sql = "UPDATE `".$table."` SET `".
1256 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1258 $params1 = array_values($fields);
1259 $params2 = array_values($condition);
1260 $params = array_merge_recursive($params1, $params2);
1262 return self::e($sql, $params);
1266 * Retrieve a single record from a table and returns it in an associative array
1268 * @brief Retrieve a single record from a table
1269 * @param string $table
1270 * @param array $fields
1271 * @param array $condition
1272 * @param array $params
1273 * @return bool|array
1276 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1278 $params['limit'] = 1;
1279 $result = self::select($table, $fields, $condition, $params);
1281 if (is_bool($result)) {
1284 $row = self::fetch($result);
1285 self::close($result);
1291 * @brief Select rows from a table
1293 * @param string $table Table name
1294 * @param array $fields Array of selected fields, empty for all
1295 * @param array $condition Array of fields for condition
1296 * @param array $params Array of several parameters
1298 * @return boolean|object
1302 * $fields = array("id", "uri", "uid", "network");
1304 * $condition = array("uid" => 1, "network" => 'dspr');
1306 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1308 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1310 * $data = DBA::select($table, $fields, $condition, $params);
1312 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1318 $table = self::escape($table);
1320 if (count($fields) > 0) {
1321 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1323 $select_fields = "*";
1326 $condition_string = self::buildCondition($condition);
1328 $param_string = self::buildParameter($params);
1330 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1332 $result = self::p($sql, $condition);
1338 * @brief Counts the rows from a table satisfying the provided condition
1340 * @param string $table Table name
1341 * @param array $condition array of fields for condition
1348 * $condition = ["uid" => 1, "network" => 'dspr'];
1350 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1352 * $count = DBA::count($table, $condition);
1354 public static function count($table, array $condition = [])
1360 $condition_string = self::buildCondition($condition);
1362 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1364 $row = self::fetchFirst($sql, $condition);
1366 return $row['count'];
1370 * @brief Returns the SQL condition string built from the provided condition array
1372 * This function operates with two modes.
1373 * - Supplied with a filed/value associative array, it builds simple strict
1374 * equality conditions linked by AND.
1375 * - Supplied with a flat list, the first element is the condition string and
1376 * the following arguments are the values to be interpolated
1378 * $condition = ["uid" => 1, "network" => 'dspr'];
1380 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1382 * In either case, the provided array is left with the parameters only
1384 * @param array $condition
1387 public static function buildCondition(array &$condition = [])
1389 $condition_string = '';
1390 if (count($condition) > 0) {
1392 $first_key = key($condition);
1393 if (is_int($first_key)) {
1394 $condition_string = " WHERE (" . array_shift($condition) . ")";
1397 $condition_string = "";
1398 foreach ($condition as $field => $value) {
1399 if ($condition_string != "") {
1400 $condition_string .= " AND ";
1402 if (is_array($value)) {
1403 /* Workaround for MySQL Bug #64791.
1404 * Never mix data types inside any IN() condition.
1405 * In case of mixed types, cast all as string.
1406 * Logic needs to be consistent with DBA::p() data types.
1410 foreach ($value as $single_value) {
1411 if (is_int($single_value)) {
1418 if ($is_int && $is_alpha) {
1419 foreach ($value as &$ref) {
1421 $ref = (string)$ref;
1424 unset($ref); //Prevent accidental re-use.
1427 $new_values = array_merge($new_values, array_values($value));
1428 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1429 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1431 $new_values[$field] = $value;
1432 $condition_string .= "`" . $field . "` = ?";
1435 $condition_string = " WHERE (" . $condition_string . ")";
1436 $condition = $new_values;
1440 return $condition_string;
1444 * @brief Returns the SQL parameter string built from the provided parameter array
1446 * @param array $params
1449 public static function buildParameter(array $params = [])
1452 if (isset($params['order'])) {
1453 $order_string = " ORDER BY ";
1454 foreach ($params['order'] AS $fields => $order) {
1455 if (!is_int($fields)) {
1456 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1458 $order_string .= "`" . $order . "`, ";
1461 $order_string = substr($order_string, 0, -2);
1465 if (isset($params['limit']) && is_int($params['limit'])) {
1466 $limit_string = " LIMIT " . intval($params['limit']);
1469 if (isset($params['limit']) && is_array($params['limit'])) {
1470 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1473 return $order_string.$limit_string;
1477 * @brief Fills an array with data from a query
1479 * @param object $stmt statement object
1480 * @return array Data array
1482 public static function toArray($stmt, $do_close = true) {
1483 if (is_bool($stmt)) {
1488 while ($row = self::fetch($stmt)) {
1498 * @brief Returns the error number of the last query
1500 * @return string Error number (0 if no error)
1502 public static function errorNo() {
1503 return self::$errorno;
1507 * @brief Returns the error message of the last query
1509 * @return string Error message ('' if no error)
1511 public static function errorMessage() {
1512 return self::$error;
1516 * @brief Closes the current statement
1518 * @param object $stmt statement object
1519 * @return boolean was the close successful?
1521 public static function close($stmt) {
1524 $stamp1 = microtime(true);
1526 if (!is_object($stmt)) {
1530 switch (self::$driver) {
1532 $ret = $stmt->closeCursor();
1535 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1536 // We should be careful not to assume the object type of $stmt
1537 // because DBA::p() has been able to return both types.
1538 if ($stmt instanceof mysqli_stmt) {
1539 $stmt->free_result();
1540 $ret = $stmt->close();
1541 } elseif ($stmt instanceof mysqli_result) {
1550 $a->saveTimestamp($stamp1, 'database');
1556 * @brief Return a list of database processes
1559 * 'list' => List of processes, separated in their different states
1560 * 'amount' => Number of concurrent database processes
1562 public static function processlist()
1564 $ret = self::p("SHOW PROCESSLIST");
1565 $data = self::toArray($ret);
1571 foreach ($data as $process) {
1572 $state = trim($process["State"]);
1574 // Filter out all non blocking processes
1575 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1582 foreach ($states as $state => $usage) {
1583 if ($statelist != "") {
1586 $statelist .= $state.": ".$usage;
1588 return(["list" => $statelist, "amount" => $processes]);
1592 * Checks if $array is a filled array with at least one entry.
1594 * @param mixed $array A filled array with at least one entry
1596 * @return boolean Whether $array is a filled array or an object with rows
1598 public static function isResult($array)
1600 // It could be a return value from an update statement
1601 if (is_bool($array)) {
1605 if (is_object($array)) {
1606 return self::numRows($array) > 0;
1609 return (is_array($array) && (count($array) > 0));
1613 * @brief Callback function for "esc_array"
1615 * @param mixed $value Array value
1616 * @param string $key Array key
1617 * @param boolean $add_quotation add quotation marks for string values
1620 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1622 if (!$add_quotation) {
1623 if (is_bool($value)) {
1624 $value = ($value ? '1' : '0');
1626 $value = self::escape($value);
1631 if (is_bool($value)) {
1632 $value = ($value ? 'true' : 'false');
1633 } elseif (is_float($value) || is_integer($value)) {
1634 $value = (string) $value;
1636 $value = "'" . self::escape($value) . "'";
1641 * @brief Escapes a whole array
1643 * @param mixed $arr Array with values to be escaped
1644 * @param boolean $add_quotation add quotation marks for string values
1647 public static function escapeArray(&$arr, $add_quotation = false)
1649 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);