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\Logger;
10 use Friendica\Core\System;
11 use Friendica\Util\DateTimeFormat;
19 require_once 'include/dba.php';
22 * @class MySQL database class
24 * This class is for the low level database stuff that does driver specific things.
29 * Lowest possible date value
31 const NULL_DATE = '0001-01-01';
33 * Lowest possible datetime value
35 const NULL_DATETIME = '0001-01-01 00:00:00';
37 public static $connected = false;
39 private static $server_info = '';
40 private static $connection;
41 private static $driver;
42 private static $error = false;
43 private static $errorno = 0;
44 private static $affected_rows = 0;
45 private static $in_transaction = false;
46 private static $in_retrial = false;
47 private static $relation = [];
48 private static $db_serveraddr = '';
49 private static $db_user = '';
50 private static $db_pass = '';
51 private static $db_name = '';
52 private static $db_charset = '';
54 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
56 if (!is_null(self::$connection) && self::connected()) {
60 // We are storing these values for being able to perform a reconnect
61 self::$db_serveraddr = $serveraddr;
62 self::$db_user = $user;
63 self::$db_pass = $pass;
65 self::$db_charset = $charset;
68 $serveraddr = trim($serveraddr);
70 $serverdata = explode(':', $serveraddr);
71 $server = $serverdata[0];
73 if (count($serverdata) > 1) {
74 $port = trim($serverdata[1]);
77 $server = trim($server);
81 $charset = trim($charset);
83 if (!(strlen($server) && strlen($user))) {
87 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
88 self::$driver = 'pdo';
89 $connect = "mysql:host=".$server.";dbname=".$db;
92 $connect .= ";port=".$port;
96 $connect .= ";charset=".$charset;
100 self::$connection = @new PDO($connect, $user, $pass);
101 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
102 self::$connected = true;
103 } catch (PDOException $e) {
104 /// @TODO At least log exception, don't ignore it!
108 if (!self::$connected && class_exists('\mysqli')) {
109 self::$driver = 'mysqli';
112 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
114 self::$connection = @new mysqli($server, $user, $pass, $db);
117 if (!mysqli_connect_errno()) {
118 self::$connected = true;
121 self::$connection->set_charset($charset);
126 // No suitable SQL driver was found.
127 if (!self::$connected) {
128 self::$driver = null;
129 self::$connection = null;
132 return self::$connected;
136 * Disconnects the current database connection
138 public static function disconnect()
140 if (is_null(self::$connection)) {
144 switch (self::$driver) {
146 self::$connection = null;
149 self::$connection->close();
150 self::$connection = null;
156 * Perform a reconnect of an existing database connection
158 public static function reconnect() {
161 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
166 * Return the database object.
169 public static function getConnection()
171 return self::$connection;
175 * @brief Returns the MySQL server version string
177 * This function discriminate between the deprecated mysql API and the current
178 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
182 public static function serverInfo() {
183 if (self::$server_info == '') {
184 switch (self::$driver) {
186 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
189 self::$server_info = self::$connection->server_info;
193 return self::$server_info;
197 * @brief Returns the selected database name
201 public static function databaseName() {
202 $ret = self::p("SELECT DATABASE() AS `db`");
203 $data = self::toArray($ret);
204 return $data[0]['db'];
208 * @brief Analyze a database query and log this if some conditions are met.
210 * @param string $query The database query that will be analyzed
212 private static function logIndex($query) {
215 if (!$a->getConfigVariable('system', 'db_log_index')) {
219 // Don't explain an explain statement
220 if (strtolower(substr($query, 0, 7)) == "explain") {
224 // Only do the explain on "select", "update" and "delete"
225 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
229 $r = self::p("EXPLAIN ".$query);
230 if (!self::isResult($r)) {
234 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
235 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
237 while ($row = self::fetch($r)) {
238 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
239 $log = (in_array($row['key'], $watchlist) &&
240 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
245 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
249 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
254 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
255 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
256 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
257 basename($backtrace[1]["file"])."\t".
258 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
259 substr($query, 0, 2000)."\n", FILE_APPEND);
264 public static function escape($str) {
265 if (self::$connected) {
266 switch (self::$driver) {
268 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
271 return @self::$connection->real_escape_string($str);
274 return str_replace("'", "\\'", $str);
278 public static function connected() {
281 if (is_null(self::$connection)) {
285 switch (self::$driver) {
287 $r = self::p("SELECT 1");
288 if (self::isResult($r)) {
289 $row = self::toArray($r);
290 $connected = ($row[0]['1'] == '1');
294 $connected = self::$connection->ping();
301 * @brief Replaces ANY_VALUE() function by MIN() function,
302 * if the database server does not support ANY_VALUE().
304 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
305 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
306 * A standard fall-back is to use MIN().
308 * @param string $sql An SQL string without the values
309 * @return string The input SQL string modified if necessary.
311 public static function anyValueFallback($sql) {
312 $server_info = self::serverInfo();
313 if (version_compare($server_info, '5.7.5', '<') ||
314 (stripos($server_info, 'MariaDB') !== false)) {
315 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
321 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
323 * This is safe when we bind the parameters later.
324 * The parameter values aren't part of the SQL.
326 * @param string $sql An SQL string without the values
327 * @return string The input SQL string modified if necessary.
329 public static function cleanQuery($sql) {
330 $search = ["\t", "\n", "\r", " "];
331 $replace = [' ', ' ', ' ', ' '];
334 $sql = str_replace($search, $replace, $sql);
335 } while ($oldsql != $sql);
342 * @brief Replaces the ? placeholders with the parameters in the $args array
344 * @param string $sql SQL query
345 * @param array $args The parameters that are to replace the ? placeholders
346 * @return string The replaced SQL query
348 private static function replaceParameters($sql, $args) {
350 foreach ($args AS $param => $value) {
351 if (is_int($args[$param]) || is_float($args[$param])) {
352 $replace = intval($args[$param]);
354 $replace = "'".self::escape($args[$param])."'";
357 $pos = strpos($sql, '?', $offset);
358 if ($pos !== false) {
359 $sql = substr_replace($sql, $replace, $pos, 1);
361 $offset = $pos + strlen($replace);
367 * @brief Convert parameter array to an universal form
368 * @param array $args Parameter array
369 * @return array universalized parameter array
371 private static function getParam($args) {
374 // When the second function parameter is an array then use this as the parameter array
375 if ((count($args) > 0) && (is_array($args[1]))) {
383 * @brief Executes a prepared statement that returns data
384 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
386 * Please only use it with complicated queries.
387 * For all regular queries please use DBA::select or DBA::exists
389 * @param string $sql SQL statement
390 * @return bool|object statement object or result object
392 public static function p($sql) {
395 $stamp1 = microtime(true);
397 $params = self::getParam(func_get_args());
399 // Renumber the array keys to be sure that they fit
402 foreach ($params AS $param) {
403 // Avoid problems with some MySQL servers and boolean values. See issue #3645
404 if (is_bool($param)) {
405 $param = (int)$param;
407 $args[++$i] = $param;
410 if (!self::$connected) {
414 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
415 // Question: Should we continue or stop the query here?
416 Logger::log('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), Logger::DEBUG);
419 $sql = self::cleanQuery($sql);
420 $sql = self::anyValueFallback($sql);
424 if ($a->getConfigValue('system', 'db_callstack')) {
425 $sql = "/*".System::callstack()." */ ".$sql;
430 self::$affected_rows = 0;
432 // We have to make some things different if this function is called from "e"
433 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
435 if (isset($trace[1])) {
436 $called_from = $trace[1];
438 // We use just something that is defined to avoid warnings
439 $called_from = $trace[0];
441 // We are having an own error logging in the function "e"
442 $called_from_e = ($called_from['function'] == 'e');
444 switch (self::$driver) {
446 // If there are no arguments we use "query"
447 if (count($args) == 0) {
448 if (!$retval = self::$connection->query($sql)) {
449 $errorInfo = self::$connection->errorInfo();
450 self::$error = $errorInfo[2];
451 self::$errorno = $errorInfo[1];
455 self::$affected_rows = $retval->rowCount();
459 if (!$stmt = self::$connection->prepare($sql)) {
460 $errorInfo = self::$connection->errorInfo();
461 self::$error = $errorInfo[2];
462 self::$errorno = $errorInfo[1];
467 foreach ($args AS $param => $value) {
468 if (is_int($args[$param])) {
469 $data_type = PDO::PARAM_INT;
471 $data_type = PDO::PARAM_STR;
473 $stmt->bindParam($param, $args[$param], $data_type);
476 if (!$stmt->execute()) {
477 $errorInfo = $stmt->errorInfo();
478 self::$error = $errorInfo[2];
479 self::$errorno = $errorInfo[1];
483 self::$affected_rows = $retval->rowCount();
487 // There are SQL statements that cannot be executed with a prepared statement
488 $parts = explode(' ', $orig_sql);
489 $command = strtolower($parts[0]);
490 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
492 // The fallback routine is called as well when there are no arguments
493 if (!$can_be_prepared || (count($args) == 0)) {
494 $retval = self::$connection->query(self::replaceParameters($sql, $args));
495 if (self::$connection->errno) {
496 self::$error = self::$connection->error;
497 self::$errorno = self::$connection->errno;
500 if (isset($retval->num_rows)) {
501 self::$affected_rows = $retval->num_rows;
503 self::$affected_rows = self::$connection->affected_rows;
509 $stmt = self::$connection->stmt_init();
511 if (!$stmt->prepare($sql)) {
512 self::$error = $stmt->error;
513 self::$errorno = $stmt->errno;
520 foreach ($args AS $param => $value) {
521 if (is_int($args[$param])) {
523 } elseif (is_float($args[$param])) {
525 } elseif (is_string($args[$param])) {
530 $values[] = &$args[$param];
533 if (count($values) > 0) {
534 array_unshift($values, $param_types);
535 call_user_func_array([$stmt, 'bind_param'], $values);
538 if (!$stmt->execute()) {
539 self::$error = self::$connection->error;
540 self::$errorno = self::$connection->errno;
543 $stmt->store_result();
545 self::$affected_rows = $retval->affected_rows;
550 // We are having an own error logging in the function "e"
551 if ((self::$errorno != 0) && !$called_from_e) {
552 // We have to preserve the error code, somewhere in the logging it get lost
553 $error = self::$error;
554 $errorno = self::$errorno;
556 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
557 System::callstack(8)."\n".self::replaceParameters($sql, $args));
559 // On a lost connection we try to reconnect - but only once.
560 if ($errorno == 2006) {
561 if (self::$in_retrial || !self::reconnect()) {
562 // It doesn't make sense to continue when the database connection was lost
563 if (self::$in_retrial) {
564 Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
566 Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
571 Logger::log('Reconnected after database error '.$errorno.': '.$error);
572 self::$in_retrial = true;
573 $ret = self::p($sql, $args);
574 self::$in_retrial = false;
579 self::$error = $error;
580 self::$errorno = $errorno;
583 $a->saveTimestamp($stamp1, 'database');
585 if ($a->getConfigValue('system', 'db_log')) {
586 $stamp2 = microtime(true);
587 $duration = (float)($stamp2 - $stamp1);
589 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
590 $duration = round($duration, 3);
591 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
593 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
594 basename($backtrace[1]["file"])."\t".
595 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
596 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
603 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
605 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
607 * @param string $sql SQL statement
608 * @return boolean Was the query successfull? False is returned only if an error occurred
610 public static function e($sql) {
613 $stamp = microtime(true);
615 $params = self::getParam(func_get_args());
617 // In a case of a deadlock we are repeating the query 20 times
621 $stmt = self::p($sql, $params);
623 if (is_bool($stmt)) {
625 } elseif (is_object($stmt)) {
633 } while ((self::$errorno == 1213) && (--$timeout > 0));
635 if (self::$errorno != 0) {
636 // We have to preserve the error code, somewhere in the logging it get lost
637 $error = self::$error;
638 $errorno = self::$errorno;
640 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
641 System::callstack(8)."\n".self::replaceParameters($sql, $params));
643 // On a lost connection we simply quit.
644 // A reconnect like in self::p could be dangerous with modifications
645 if ($errorno == 2006) {
646 Logger::log('Giving up because of database error '.$errorno.': '.$error);
650 self::$error = $error;
651 self::$errorno = $errorno;
654 $a->saveTimestamp($stamp, "database_write");
660 * @brief Check if data exists
662 * @param string $table Table name
663 * @param array $condition array of fields for condition
665 * @return boolean Are there rows for that condition?
667 public static function exists($table, $condition) {
674 if (empty($condition)) {
675 return DBStructure::existsTable($table);
679 $first_key = key($condition);
680 if (!is_int($first_key)) {
681 $fields = [$first_key];
684 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
686 if (is_bool($stmt)) {
689 $retval = (self::numRows($stmt) > 0);
698 * Fetches the first row
700 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
702 * @brief Fetches the first row
703 * @param string $sql SQL statement
704 * @return array first row of query
706 public static function fetchFirst($sql) {
707 $params = self::getParam(func_get_args());
709 $stmt = self::p($sql, $params);
711 if (is_bool($stmt)) {
714 $retval = self::fetch($stmt);
723 * @brief Returns the number of affected rows of the last statement
725 * @return int Number of rows
727 public static function affectedRows() {
728 return self::$affected_rows;
732 * @brief Returns the number of columns of a statement
734 * @param object Statement object
735 * @return int Number of columns
737 public static function columnCount($stmt) {
738 if (!is_object($stmt)) {
741 switch (self::$driver) {
743 return $stmt->columnCount();
745 return $stmt->field_count;
750 * @brief Returns the number of rows of a statement
752 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
753 * @return int Number of rows
755 public static function numRows($stmt) {
756 if (!is_object($stmt)) {
759 switch (self::$driver) {
761 return $stmt->rowCount();
763 return $stmt->num_rows;
769 * @brief Fetch a single row
771 * @param mixed $stmt statement object
772 * @return array current row
774 public static function fetch($stmt) {
777 $stamp1 = microtime(true);
781 if (!is_object($stmt)) {
785 switch (self::$driver) {
787 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
790 if (get_class($stmt) == 'mysqli_result') {
791 $columns = $stmt->fetch_assoc();
795 // This code works, but is slow
797 // Bind the result to a result array
801 for ($x = 0; $x < $stmt->field_count; $x++) {
802 $cols[] = &$cols_num[$x];
805 call_user_func_array([$stmt, 'bind_result'], $cols);
807 if (!$stmt->fetch()) {
812 // We need to get the field names for the array keys
813 // It seems that there is no better way to do this.
814 $result = $stmt->result_metadata();
815 $fields = $result->fetch_fields();
817 foreach ($cols_num AS $param => $col) {
818 $columns[$fields[$param]->name] = $col;
822 $a->saveTimestamp($stamp1, 'database');
828 * @brief Insert a row into a table
830 * @param string $table Table name
831 * @param array $param parameter array
832 * @param bool $on_duplicate_update Do an update on a duplicate entry
834 * @return boolean was the insert successful?
836 public static function insert($table, $param, $on_duplicate_update = false) {
838 if (empty($table) || empty($param)) {
839 Logger::log('Table and fields have to be set');
843 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
844 substr(str_repeat("?, ", count($param)), 0, -2).")";
846 if ($on_duplicate_update) {
847 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
849 $values = array_values($param);
850 $param = array_merge_recursive($values, $values);
853 return self::e($sql, $param);
857 * @brief Fetch the id of the last insert command
859 * @return integer Last inserted id
861 public static function lastInsertId() {
862 switch (self::$driver) {
864 $id = self::$connection->lastInsertId();
867 $id = self::$connection->insert_id;
874 * @brief Locks a table for exclusive write access
876 * This function can be extended in the future to accept a table array as well.
878 * @param string $table Table name
880 * @return boolean was the lock successful?
882 public static function lock($table) {
883 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
884 if (self::$driver == 'pdo') {
885 self::e("SET autocommit=0");
886 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
888 self::$connection->autocommit(false);
891 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
893 if (self::$driver == 'pdo') {
894 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
898 if (self::$driver == 'pdo') {
899 self::e("SET autocommit=1");
901 self::$connection->autocommit(true);
904 self::$in_transaction = true;
910 * @brief Unlocks all locked tables
912 * @return boolean was the unlock successful?
914 public static function unlock() {
915 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
916 self::performCommit();
918 if (self::$driver == 'pdo') {
919 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
922 $success = self::e("UNLOCK TABLES");
924 if (self::$driver == 'pdo') {
925 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
926 self::e("SET autocommit=1");
928 self::$connection->autocommit(true);
931 self::$in_transaction = false;
936 * @brief Starts a transaction
938 * @return boolean Was the command executed successfully?
940 public static function transaction() {
941 if (!self::performCommit()) {
945 switch (self::$driver) {
947 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
953 if (!self::$connection->begin_transaction()) {
959 self::$in_transaction = true;
963 private static function performCommit()
965 switch (self::$driver) {
967 if (!self::$connection->inTransaction()) {
971 return self::$connection->commit();
974 return self::$connection->commit();
981 * @brief Does a commit
983 * @return boolean Was the command executed successfully?
985 public static function commit() {
986 if (!self::performCommit()) {
989 self::$in_transaction = false;
994 * @brief Does a rollback
996 * @return boolean Was the command executed successfully?
998 public static function rollback() {
1001 switch (self::$driver) {
1003 if (!self::$connection->inTransaction()) {
1007 $ret = self::$connection->rollBack();
1011 $ret = self::$connection->rollback();
1014 self::$in_transaction = false;
1019 * @brief Build the array with the table relations
1021 * The array is build from the database definitions in DBStructure.php
1023 * This process must only be started once, since the value is cached.
1025 private static function buildRelationData() {
1026 $definition = DBStructure::definition();
1028 foreach ($definition AS $table => $structure) {
1029 foreach ($structure['fields'] AS $field => $field_struct) {
1030 if (isset($field_struct['relation'])) {
1031 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1032 self::$relation[$rel_table][$rel_field][$table][] = $field;
1040 * @brief Delete a row from a table
1042 * @param string $table Table name
1043 * @param array $conditions Field condition(s)
1044 * @param array $options
1045 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1046 * relations (default: true)
1047 * @param array $callstack Internal use: prevent endless loops
1049 * @return boolean was the delete successful?
1051 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1053 if (empty($table) || empty($conditions)) {
1054 Logger::log('Table and conditions have to be set');
1060 // Create a key for the loop prevention
1061 $key = $table . ':' . json_encode($conditions);
1063 // We quit when this key already exists in the callstack.
1064 if (isset($callstack[$key])) {
1068 $callstack[$key] = true;
1070 $table = self::escape($table);
1072 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1074 // Don't use "defaults" here, since it would set "false" to "true"
1075 if (isset($options['cascade'])) {
1076 $cascade = $options['cascade'];
1081 // To speed up the whole process we cache the table relations
1082 if ($cascade && count(self::$relation) == 0) {
1083 self::buildRelationData();
1086 // Is there a relation entry for the table?
1087 if ($cascade && isset(self::$relation[$table])) {
1088 // We only allow a simple "one field" relation.
1089 $field = array_keys(self::$relation[$table])[0];
1090 $rel_def = array_values(self::$relation[$table])[0];
1092 // Create a key for preventing double queries
1093 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1095 // When the search field is the relation field, we don't need to fetch the rows
1096 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1097 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1098 foreach ($rel_def AS $rel_table => $rel_fields) {
1099 foreach ($rel_fields AS $rel_field) {
1100 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1103 // We quit when this key already exists in the callstack.
1104 } elseif (!isset($callstack[$qkey])) {
1105 $callstack[$qkey] = true;
1107 // Fetch all rows that are to be deleted
1108 $data = self::select($table, [$field], $conditions);
1110 while ($row = self::fetch($data)) {
1111 self::delete($table, [$field => $row[$field]], $options, $callstack);
1116 // Since we had split the delete command we don't need the original command anymore
1117 unset($commands[$key]);
1121 // Now we finalize the process
1122 $do_transaction = !self::$in_transaction;
1124 if ($do_transaction) {
1125 self::transaction();
1131 foreach ($commands AS $command) {
1132 $conditions = $command['conditions'];
1134 $first_key = key($conditions);
1136 $condition_string = self::buildCondition($conditions);
1138 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1139 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1140 Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
1142 if (!self::e($sql, $conditions)) {
1143 if ($do_transaction) {
1149 $key_table = $command['table'];
1150 $key_condition = array_keys($command['conditions'])[0];
1151 $value = array_values($command['conditions'])[0];
1153 // Split the SQL queries in chunks of 100 values
1154 // We do the $i stuff here to make the code better readable
1155 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1156 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1160 $compacted[$key_table][$key_condition][$i][$value] = $value;
1161 $counter[$key_table][$key_condition] = $i;
1164 foreach ($compacted AS $table => $values) {
1165 foreach ($values AS $field => $field_value_list) {
1166 foreach ($field_value_list AS $field_values) {
1167 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1168 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1170 Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
1172 if (!self::e($sql, $field_values)) {
1173 if ($do_transaction) {
1181 if ($do_transaction) {
1188 * @brief Updates rows
1190 * Updates rows in the database. When $old_fields is set to an array,
1191 * the system will only do an update if the fields in that array changed.
1194 * Only the values in $old_fields are compared.
1195 * This is an intentional behaviour.
1198 * We include the timestamp field in $fields but not in $old_fields.
1199 * Then the row will only get the new timestamp when the other fields had changed.
1201 * When $old_fields is set to a boolean value the system will do this compare itself.
1202 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1205 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1206 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1208 * @param string $table Table name
1209 * @param array $fields contains the fields that are updated
1210 * @param array $condition condition array with the key values
1211 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1213 * @return boolean was the update successfull?
1215 public static function update($table, $fields, $condition, $old_fields = []) {
1217 if (empty($table) || empty($fields) || empty($condition)) {
1218 Logger::log('Table, fields and condition have to be set');
1222 $table = self::escape($table);
1224 $condition_string = self::buildCondition($condition);
1226 if (is_bool($old_fields)) {
1227 $do_insert = $old_fields;
1229 $old_fields = self::selectFirst($table, [], $condition);
1231 if (is_bool($old_fields)) {
1233 $values = array_merge($condition, $fields);
1234 return self::insert($table, $values, $do_insert);
1240 $do_update = (count($old_fields) == 0);
1242 foreach ($old_fields AS $fieldname => $content) {
1243 if (isset($fields[$fieldname])) {
1244 if ($fields[$fieldname] == $content) {
1245 unset($fields[$fieldname]);
1252 if (!$do_update || (count($fields) == 0)) {
1256 $sql = "UPDATE `".$table."` SET `".
1257 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1259 $params1 = array_values($fields);
1260 $params2 = array_values($condition);
1261 $params = array_merge_recursive($params1, $params2);
1263 return self::e($sql, $params);
1267 * Retrieve a single record from a table and returns it in an associative array
1269 * @brief Retrieve a single record from a table
1270 * @param string $table
1271 * @param array $fields
1272 * @param array $condition
1273 * @param array $params
1274 * @return bool|array
1277 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1279 $params['limit'] = 1;
1280 $result = self::select($table, $fields, $condition, $params);
1282 if (is_bool($result)) {
1285 $row = self::fetch($result);
1286 self::close($result);
1292 * @brief Select rows from a table
1294 * @param string $table Table name
1295 * @param array $fields Array of selected fields, empty for all
1296 * @param array $condition Array of fields for condition
1297 * @param array $params Array of several parameters
1299 * @return boolean|object
1303 * $fields = array("id", "uri", "uid", "network");
1305 * $condition = array("uid" => 1, "network" => 'dspr');
1307 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1309 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1311 * $data = DBA::select($table, $fields, $condition, $params);
1313 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1319 $table = self::escape($table);
1321 if (count($fields) > 0) {
1322 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1324 $select_fields = "*";
1327 $condition_string = self::buildCondition($condition);
1329 $param_string = self::buildParameter($params);
1331 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1333 $result = self::p($sql, $condition);
1339 * @brief Counts the rows from a table satisfying the provided condition
1341 * @param string $table Table name
1342 * @param array $condition array of fields for condition
1349 * $condition = ["uid" => 1, "network" => 'dspr'];
1351 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1353 * $count = DBA::count($table, $condition);
1355 public static function count($table, array $condition = [])
1361 $condition_string = self::buildCondition($condition);
1363 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1365 $row = self::fetchFirst($sql, $condition);
1367 return $row['count'];
1371 * @brief Returns the SQL condition string built from the provided condition array
1373 * This function operates with two modes.
1374 * - Supplied with a filed/value associative array, it builds simple strict
1375 * equality conditions linked by AND.
1376 * - Supplied with a flat list, the first element is the condition string and
1377 * the following arguments are the values to be interpolated
1379 * $condition = ["uid" => 1, "network" => 'dspr'];
1381 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1383 * In either case, the provided array is left with the parameters only
1385 * @param array $condition
1388 public static function buildCondition(array &$condition = [])
1390 $condition_string = '';
1391 if (count($condition) > 0) {
1393 $first_key = key($condition);
1394 if (is_int($first_key)) {
1395 $condition_string = " WHERE (" . array_shift($condition) . ")";
1398 $condition_string = "";
1399 foreach ($condition as $field => $value) {
1400 if ($condition_string != "") {
1401 $condition_string .= " AND ";
1403 if (is_array($value)) {
1404 /* Workaround for MySQL Bug #64791.
1405 * Never mix data types inside any IN() condition.
1406 * In case of mixed types, cast all as string.
1407 * Logic needs to be consistent with DBA::p() data types.
1411 foreach ($value as $single_value) {
1412 if (is_int($single_value)) {
1419 if ($is_int && $is_alpha) {
1420 foreach ($value as &$ref) {
1422 $ref = (string)$ref;
1425 unset($ref); //Prevent accidental re-use.
1428 $new_values = array_merge($new_values, array_values($value));
1429 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1430 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1432 $new_values[$field] = $value;
1433 $condition_string .= "`" . $field . "` = ?";
1436 $condition_string = " WHERE (" . $condition_string . ")";
1437 $condition = $new_values;
1441 return $condition_string;
1445 * @brief Returns the SQL parameter string built from the provided parameter array
1447 * @param array $params
1450 public static function buildParameter(array $params = [])
1453 if (isset($params['order'])) {
1454 $order_string = " ORDER BY ";
1455 foreach ($params['order'] AS $fields => $order) {
1456 if (!is_int($fields)) {
1457 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1459 $order_string .= "`" . $order . "`, ";
1462 $order_string = substr($order_string, 0, -2);
1466 if (isset($params['limit']) && is_int($params['limit'])) {
1467 $limit_string = " LIMIT " . intval($params['limit']);
1470 if (isset($params['limit']) && is_array($params['limit'])) {
1471 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1474 return $order_string.$limit_string;
1478 * @brief Fills an array with data from a query
1480 * @param object $stmt statement object
1481 * @return array Data array
1483 public static function toArray($stmt, $do_close = true) {
1484 if (is_bool($stmt)) {
1489 while ($row = self::fetch($stmt)) {
1499 * @brief Returns the error number of the last query
1501 * @return string Error number (0 if no error)
1503 public static function errorNo() {
1504 return self::$errorno;
1508 * @brief Returns the error message of the last query
1510 * @return string Error message ('' if no error)
1512 public static function errorMessage() {
1513 return self::$error;
1517 * @brief Closes the current statement
1519 * @param object $stmt statement object
1520 * @return boolean was the close successful?
1522 public static function close($stmt) {
1525 $stamp1 = microtime(true);
1527 if (!is_object($stmt)) {
1531 switch (self::$driver) {
1533 $ret = $stmt->closeCursor();
1536 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1537 // We should be careful not to assume the object type of $stmt
1538 // because DBA::p() has been able to return both types.
1539 if ($stmt instanceof mysqli_stmt) {
1540 $stmt->free_result();
1541 $ret = $stmt->close();
1542 } elseif ($stmt instanceof mysqli_result) {
1551 $a->saveTimestamp($stamp1, 'database');
1557 * @brief Return a list of database processes
1560 * 'list' => List of processes, separated in their different states
1561 * 'amount' => Number of concurrent database processes
1563 public static function processlist()
1565 $ret = self::p("SHOW PROCESSLIST");
1566 $data = self::toArray($ret);
1572 foreach ($data as $process) {
1573 $state = trim($process["State"]);
1575 // Filter out all non blocking processes
1576 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1583 foreach ($states as $state => $usage) {
1584 if ($statelist != "") {
1587 $statelist .= $state.": ".$usage;
1589 return(["list" => $statelist, "amount" => $processes]);
1593 * Checks if $array is a filled array with at least one entry.
1595 * @param mixed $array A filled array with at least one entry
1597 * @return boolean Whether $array is a filled array or an object with rows
1599 public static function isResult($array)
1601 // It could be a return value from an update statement
1602 if (is_bool($array)) {
1606 if (is_object($array)) {
1607 return self::numRows($array) > 0;
1610 return (is_array($array) && (count($array) > 0));
1614 * @brief Callback function for "esc_array"
1616 * @param mixed $value Array value
1617 * @param string $key Array key
1618 * @param boolean $add_quotation add quotation marks for string values
1621 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1623 if (!$add_quotation) {
1624 if (is_bool($value)) {
1625 $value = ($value ? '1' : '0');
1627 $value = self::escape($value);
1632 if (is_bool($value)) {
1633 $value = ($value ? 'true' : 'false');
1634 } elseif (is_float($value) || is_integer($value)) {
1635 $value = (string) $value;
1637 $value = "'" . self::escape($value) . "'";
1642 * @brief Escapes a whole array
1644 * @param mixed $arr Array with values to be escaped
1645 * @param boolean $add_quotation add quotation marks for string values
1648 public static function escapeArray(&$arr, $add_quotation = false)
1650 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);