3 namespace Friendica\Database;
5 // Do not use native get/set/load of Core\Config in this class at risk of infinite loop.
6 // Please use Core\Config::getConfigVariable() instead.
7 use Friendica\Core\Config;
8 use Friendica\Core\Logger;
9 use Friendica\Core\System;
10 use Friendica\Util\DateTimeFormat;
19 * @class MySQL database class
21 * This class is for the low level database stuff that does driver specific things.
26 * Lowest possible date value
28 const NULL_DATE = '0001-01-01';
30 * Lowest possible datetime value
32 const NULL_DATETIME = '0001-01-01 00:00:00';
34 public static $connected = false;
36 private static $server_info = '';
37 private static $connection;
38 private static $driver;
39 private static $error = false;
40 private static $errorno = 0;
41 private static $affected_rows = 0;
42 private static $in_transaction = false;
43 private static $in_retrial = false;
44 private static $relation = [];
45 private static $db_serveraddr = '';
46 private static $db_user = '';
47 private static $db_pass = '';
48 private static $db_name = '';
49 private static $db_charset = '';
51 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
53 if (!is_null(self::$connection) && self::connected()) {
57 // We are storing these values for being able to perform a reconnect
58 self::$db_serveraddr = $serveraddr;
59 self::$db_user = $user;
60 self::$db_pass = $pass;
62 self::$db_charset = $charset;
65 $serveraddr = trim($serveraddr);
67 $serverdata = explode(':', $serveraddr);
68 $server = $serverdata[0];
70 if (count($serverdata) > 1) {
71 $port = trim($serverdata[1]);
74 $server = trim($server);
78 $charset = trim($charset);
80 if (!(strlen($server) && strlen($user))) {
84 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
85 self::$driver = 'pdo';
86 $connect = "mysql:host=".$server.";dbname=".$db;
89 $connect .= ";port=".$port;
93 $connect .= ";charset=".$charset;
97 self::$connection = @new PDO($connect, $user, $pass);
98 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
99 self::$connected = true;
100 } catch (PDOException $e) {
101 /// @TODO At least log exception, don't ignore it!
105 if (!self::$connected && class_exists('\mysqli')) {
106 self::$driver = 'mysqli';
109 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
111 self::$connection = @new mysqli($server, $user, $pass, $db);
114 if (!mysqli_connect_errno()) {
115 self::$connected = true;
118 self::$connection->set_charset($charset);
123 // No suitable SQL driver was found.
124 if (!self::$connected) {
125 self::$driver = null;
126 self::$connection = null;
129 return self::$connected;
133 * Disconnects the current database connection
135 public static function disconnect()
137 if (is_null(self::$connection)) {
141 switch (self::$driver) {
143 self::$connection = null;
146 self::$connection->close();
147 self::$connection = null;
153 * Perform a reconnect of an existing database connection
155 public static function reconnect() {
158 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
163 * Return the database object.
166 public static function getConnection()
168 return self::$connection;
172 * @brief Returns the MySQL server version string
174 * This function discriminate between the deprecated mysql API and the current
175 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
179 public static function serverInfo() {
180 if (self::$server_info == '') {
181 switch (self::$driver) {
183 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
186 self::$server_info = self::$connection->server_info;
190 return self::$server_info;
194 * @brief Returns the selected database name
199 public static function databaseName() {
200 $ret = self::p("SELECT DATABASE() AS `db`");
201 $data = self::toArray($ret);
202 return $data[0]['db'];
206 * @brief Analyze a database query and log this if some conditions are met.
208 * @param string $query The database query that will be analyzed
211 private static function logIndex($query) {
214 if (!Config::getConfigValue('system', 'db_log_index')) {
218 // Don't explain an explain statement
219 if (strtolower(substr($query, 0, 7)) == "explain") {
223 // Only do the explain on "select", "update" and "delete"
224 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
228 $r = self::p("EXPLAIN ".$query);
229 if (!self::isResult($r)) {
233 $watchlist = explode(',', Config::getConfigValue('system', 'db_log_index_watch'));
234 $blacklist = explode(',', Config::getConfigValue('system', 'db_log_index_blacklist'));
236 while ($row = self::fetch($r)) {
237 if ((intval(Config::getConfigValue('system', 'db_loglimit_index')) > 0)) {
238 $log = (in_array($row['key'], $watchlist) &&
239 ($row['rows'] >= intval(Config::getConfigValue('system', 'db_loglimit_index'))));
244 if ((intval(Config::getConfigValue('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($Config::getConfigValue('system', 'db_loglimit_index_high')))) {
248 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
253 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
254 @file_put_contents(Config::getConfigValue('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
255 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
256 basename($backtrace[1]["file"])."\t".
257 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
258 substr($query, 0, 2000)."\n", FILE_APPEND);
263 public static function escape($str) {
264 if (self::$connected) {
265 switch (self::$driver) {
267 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
270 return @self::$connection->real_escape_string($str);
273 return str_replace("'", "\\'", $str);
277 public static function connected() {
280 if (is_null(self::$connection)) {
284 switch (self::$driver) {
286 $r = self::p("SELECT 1");
287 if (self::isResult($r)) {
288 $row = self::toArray($r);
289 $connected = ($row[0]['1'] == '1');
293 $connected = self::$connection->ping();
300 * @brief Replaces ANY_VALUE() function by MIN() function,
301 * if the database server does not support ANY_VALUE().
303 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
304 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
305 * A standard fall-back is to use MIN().
307 * @param string $sql An SQL string without the values
308 * @return string The input SQL string modified if necessary.
310 public static function anyValueFallback($sql) {
311 $server_info = self::serverInfo();
312 if (version_compare($server_info, '5.7.5', '<') ||
313 (stripos($server_info, 'MariaDB') !== false)) {
314 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
320 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
322 * This is safe when we bind the parameters later.
323 * The parameter values aren't part of the SQL.
325 * @param string $sql An SQL string without the values
326 * @return string The input SQL string modified if necessary.
328 public static function cleanQuery($sql) {
329 $search = ["\t", "\n", "\r", " "];
330 $replace = [' ', ' ', ' ', ' '];
333 $sql = str_replace($search, $replace, $sql);
334 } while ($oldsql != $sql);
341 * @brief Replaces the ? placeholders with the parameters in the $args array
343 * @param string $sql SQL query
344 * @param array $args The parameters that are to replace the ? placeholders
345 * @return string The replaced SQL query
347 private static function replaceParameters($sql, $args) {
349 foreach ($args AS $param => $value) {
350 if (is_int($args[$param]) || is_float($args[$param])) {
351 $replace = intval($args[$param]);
353 $replace = "'".self::escape($args[$param])."'";
356 $pos = strpos($sql, '?', $offset);
357 if ($pos !== false) {
358 $sql = substr_replace($sql, $replace, $pos, 1);
360 $offset = $pos + strlen($replace);
366 * @brief Convert parameter array to an universal form
367 * @param array $args Parameter array
368 * @return array universalized parameter array
370 private static function getParam($args) {
373 // When the second function parameter is an array then use this as the parameter array
374 if ((count($args) > 0) && (is_array($args[1]))) {
382 * @brief Executes a prepared statement that returns data
383 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
385 * Please only use it with complicated queries.
386 * For all regular queries please use DBA::select or DBA::exists
388 * @param string $sql SQL statement
389 * @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 (Config::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 (Config::getConfigValue('system', 'db_log')) {
586 $stamp2 = microtime(true);
587 $duration = (float)($stamp2 - $stamp1);
589 if (($duration > Config::getConfigValue('system', 'db_loglimit'))) {
590 $duration = round($duration, 3);
591 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
593 @file_put_contents(Config::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
611 public static function e($sql) {
614 $stamp = microtime(true);
616 $params = self::getParam(func_get_args());
618 // In a case of a deadlock we are repeating the query 20 times
622 $stmt = self::p($sql, $params);
624 if (is_bool($stmt)) {
626 } elseif (is_object($stmt)) {
634 } while ((self::$errorno == 1213) && (--$timeout > 0));
636 if (self::$errorno != 0) {
637 // We have to preserve the error code, somewhere in the logging it get lost
638 $error = self::$error;
639 $errorno = self::$errorno;
641 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
642 System::callstack(8)."\n".self::replaceParameters($sql, $params));
644 // On a lost connection we simply quit.
645 // A reconnect like in self::p could be dangerous with modifications
646 if ($errorno == 2006) {
647 Logger::log('Giving up because of database error '.$errorno.': '.$error);
651 self::$error = $error;
652 self::$errorno = $errorno;
655 $a->saveTimestamp($stamp, "database_write");
661 * @brief Check if data exists
663 * @param string $table Table name
664 * @param array $condition array of fields for condition
666 * @return boolean Are there rows for that condition?
669 public static function exists($table, $condition) {
676 if (empty($condition)) {
677 return DBStructure::existsTable($table);
681 $first_key = key($condition);
682 if (!is_int($first_key)) {
683 $fields = [$first_key];
686 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
688 if (is_bool($stmt)) {
691 $retval = (self::numRows($stmt) > 0);
700 * Fetches the first row
702 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
704 * @brief Fetches the first row
705 * @param string $sql SQL statement
706 * @return array first row of query
709 public static function fetchFirst($sql) {
710 $params = self::getParam(func_get_args());
712 $stmt = self::p($sql, $params);
714 if (is_bool($stmt)) {
717 $retval = self::fetch($stmt);
726 * @brief Returns the number of affected rows of the last statement
728 * @return int Number of rows
730 public static function affectedRows() {
731 return self::$affected_rows;
735 * @brief Returns the number of columns of a statement
737 * @param object Statement object
738 * @return int Number of columns
740 public static function columnCount($stmt) {
741 if (!is_object($stmt)) {
744 switch (self::$driver) {
746 return $stmt->columnCount();
748 return $stmt->field_count;
753 * @brief Returns the number of rows of a statement
755 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
756 * @return int Number of rows
758 public static function numRows($stmt) {
759 if (!is_object($stmt)) {
762 switch (self::$driver) {
764 return $stmt->rowCount();
766 return $stmt->num_rows;
772 * @brief Fetch a single row
774 * @param mixed $stmt statement object
775 * @return array current row
777 public static function fetch($stmt) {
780 $stamp1 = microtime(true);
784 if (!is_object($stmt)) {
788 switch (self::$driver) {
790 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
793 if (get_class($stmt) == 'mysqli_result') {
794 $columns = $stmt->fetch_assoc();
798 // This code works, but is slow
800 // Bind the result to a result array
804 for ($x = 0; $x < $stmt->field_count; $x++) {
805 $cols[] = &$cols_num[$x];
808 call_user_func_array([$stmt, 'bind_result'], $cols);
810 if (!$stmt->fetch()) {
815 // We need to get the field names for the array keys
816 // It seems that there is no better way to do this.
817 $result = $stmt->result_metadata();
818 $fields = $result->fetch_fields();
820 foreach ($cols_num AS $param => $col) {
821 $columns[$fields[$param]->name] = $col;
825 $a->saveTimestamp($stamp1, 'database');
831 * @brief Insert a row into a table
833 * @param string $table Table name
834 * @param array $param parameter array
835 * @param bool $on_duplicate_update Do an update on a duplicate entry
837 * @return boolean was the insert successful?
840 public static function insert($table, $param, $on_duplicate_update = false) {
842 if (empty($table) || empty($param)) {
843 Logger::log('Table and fields have to be set');
847 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
848 substr(str_repeat("?, ", count($param)), 0, -2).")";
850 if ($on_duplicate_update) {
851 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
853 $values = array_values($param);
854 $param = array_merge_recursive($values, $values);
857 return self::e($sql, $param);
861 * @brief Fetch the id of the last insert command
863 * @return integer Last inserted id
865 public static function lastInsertId() {
866 switch (self::$driver) {
868 $id = self::$connection->lastInsertId();
871 $id = self::$connection->insert_id;
878 * @brief Locks a table for exclusive write access
880 * This function can be extended in the future to accept a table array as well.
882 * @param string $table Table name
884 * @return boolean was the lock successful?
887 public static function lock($table) {
888 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
889 if (self::$driver == 'pdo') {
890 self::e("SET autocommit=0");
891 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
893 self::$connection->autocommit(false);
896 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
898 if (self::$driver == 'pdo') {
899 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
903 if (self::$driver == 'pdo') {
904 self::e("SET autocommit=1");
906 self::$connection->autocommit(true);
909 self::$in_transaction = true;
915 * @brief Unlocks all locked tables
917 * @return boolean was the unlock successful?
920 public static function unlock() {
921 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
922 self::performCommit();
924 if (self::$driver == 'pdo') {
925 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
928 $success = self::e("UNLOCK TABLES");
930 if (self::$driver == 'pdo') {
931 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
932 self::e("SET autocommit=1");
934 self::$connection->autocommit(true);
937 self::$in_transaction = false;
942 * @brief Starts a transaction
944 * @return boolean Was the command executed successfully?
946 public static function transaction() {
947 if (!self::performCommit()) {
951 switch (self::$driver) {
953 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
959 if (!self::$connection->begin_transaction()) {
965 self::$in_transaction = true;
969 private static function performCommit()
971 switch (self::$driver) {
973 if (!self::$connection->inTransaction()) {
977 return self::$connection->commit();
980 return self::$connection->commit();
987 * @brief Does a commit
989 * @return boolean Was the command executed successfully?
991 public static function commit() {
992 if (!self::performCommit()) {
995 self::$in_transaction = false;
1000 * @brief Does a rollback
1002 * @return boolean Was the command executed successfully?
1004 public static function rollback() {
1007 switch (self::$driver) {
1009 if (!self::$connection->inTransaction()) {
1013 $ret = self::$connection->rollBack();
1017 $ret = self::$connection->rollback();
1020 self::$in_transaction = false;
1025 * @brief Build the array with the table relations
1027 * The array is build from the database definitions in DBStructure.php
1029 * This process must only be started once, since the value is cached.
1031 private static function buildRelationData() {
1032 $definition = DBStructure::definition();
1034 foreach ($definition AS $table => $structure) {
1035 foreach ($structure['fields'] AS $field => $field_struct) {
1036 if (isset($field_struct['relation'])) {
1037 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1038 self::$relation[$rel_table][$rel_field][$table][] = $field;
1046 * @brief Delete a row from a table
1048 * @param string $table Table name
1049 * @param array $conditions Field condition(s)
1050 * @param array $options
1051 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1052 * relations (default: true)
1053 * @param array $callstack Internal use: prevent endless loops
1055 * @return boolean was the delete successful?
1056 * @throws \Exception
1058 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1060 if (empty($table) || empty($conditions)) {
1061 Logger::log('Table and conditions have to be set');
1067 // Create a key for the loop prevention
1068 $key = $table . ':' . json_encode($conditions);
1070 // We quit when this key already exists in the callstack.
1071 if (isset($callstack[$key])) {
1075 $callstack[$key] = true;
1077 $table = self::escape($table);
1079 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1081 // Don't use "defaults" here, since it would set "false" to "true"
1082 if (isset($options['cascade'])) {
1083 $cascade = $options['cascade'];
1088 // To speed up the whole process we cache the table relations
1089 if ($cascade && count(self::$relation) == 0) {
1090 self::buildRelationData();
1093 // Is there a relation entry for the table?
1094 if ($cascade && isset(self::$relation[$table])) {
1095 // We only allow a simple "one field" relation.
1096 $field = array_keys(self::$relation[$table])[0];
1097 $rel_def = array_values(self::$relation[$table])[0];
1099 // Create a key for preventing double queries
1100 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1102 // When the search field is the relation field, we don't need to fetch the rows
1103 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1104 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1105 foreach ($rel_def AS $rel_table => $rel_fields) {
1106 foreach ($rel_fields AS $rel_field) {
1107 self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1110 // We quit when this key already exists in the callstack.
1111 } elseif (!isset($callstack[$qkey])) {
1112 $callstack[$qkey] = true;
1114 // Fetch all rows that are to be deleted
1115 $data = self::select($table, [$field], $conditions);
1117 while ($row = self::fetch($data)) {
1118 self::delete($table, [$field => $row[$field]], $options, $callstack);
1123 // Since we had split the delete command we don't need the original command anymore
1124 unset($commands[$key]);
1128 // Now we finalize the process
1129 $do_transaction = !self::$in_transaction;
1131 if ($do_transaction) {
1132 self::transaction();
1138 foreach ($commands AS $command) {
1139 $conditions = $command['conditions'];
1141 $first_key = key($conditions);
1143 $condition_string = self::buildCondition($conditions);
1145 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1146 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1147 Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
1149 if (!self::e($sql, $conditions)) {
1150 if ($do_transaction) {
1156 $key_table = $command['table'];
1157 $key_condition = array_keys($command['conditions'])[0];
1158 $value = array_values($command['conditions'])[0];
1160 // Split the SQL queries in chunks of 100 values
1161 // We do the $i stuff here to make the code better readable
1162 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1163 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1167 $compacted[$key_table][$key_condition][$i][$value] = $value;
1168 $counter[$key_table][$key_condition] = $i;
1171 foreach ($compacted AS $table => $values) {
1172 foreach ($values AS $field => $field_value_list) {
1173 foreach ($field_value_list AS $field_values) {
1174 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1175 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1177 Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
1179 if (!self::e($sql, $field_values)) {
1180 if ($do_transaction) {
1188 if ($do_transaction) {
1195 * @brief Updates rows
1197 * Updates rows in the database. When $old_fields is set to an array,
1198 * the system will only do an update if the fields in that array changed.
1201 * Only the values in $old_fields are compared.
1202 * This is an intentional behaviour.
1205 * We include the timestamp field in $fields but not in $old_fields.
1206 * Then the row will only get the new timestamp when the other fields had changed.
1208 * When $old_fields is set to a boolean value the system will do this compare itself.
1209 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1212 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1213 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1215 * @param string $table Table name
1216 * @param array $fields contains the fields that are updated
1217 * @param array $condition condition array with the key values
1218 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1220 * @return boolean was the update successfull?
1221 * @throws \Exception
1223 public static function update($table, $fields, $condition, $old_fields = []) {
1225 if (empty($table) || empty($fields) || empty($condition)) {
1226 Logger::log('Table, fields and condition have to be set');
1230 $table = self::escape($table);
1232 $condition_string = self::buildCondition($condition);
1234 if (is_bool($old_fields)) {
1235 $do_insert = $old_fields;
1237 $old_fields = self::selectFirst($table, [], $condition);
1239 if (is_bool($old_fields)) {
1241 $values = array_merge($condition, $fields);
1242 return self::insert($table, $values, $do_insert);
1248 $do_update = (count($old_fields) == 0);
1250 foreach ($old_fields AS $fieldname => $content) {
1251 if (isset($fields[$fieldname])) {
1252 if (($fields[$fieldname] == $content) && !is_null($content)) {
1253 unset($fields[$fieldname]);
1260 if (!$do_update || (count($fields) == 0)) {
1264 $sql = "UPDATE `".$table."` SET `".
1265 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1267 $params1 = array_values($fields);
1268 $params2 = array_values($condition);
1269 $params = array_merge_recursive($params1, $params2);
1271 return self::e($sql, $params);
1275 * Retrieve a single record from a table and returns it in an associative array
1277 * @brief Retrieve a single record from a table
1278 * @param string $table
1279 * @param array $fields
1280 * @param array $condition
1281 * @param array $params
1282 * @return bool|array
1283 * @throws \Exception
1286 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1288 $params['limit'] = 1;
1289 $result = self::select($table, $fields, $condition, $params);
1291 if (is_bool($result)) {
1294 $row = self::fetch($result);
1295 self::close($result);
1301 * @brief Select rows from a table
1303 * @param string $table Table name
1304 * @param array $fields Array of selected fields, empty for all
1305 * @param array $condition Array of fields for condition
1306 * @param array $params Array of several parameters
1308 * @return boolean|object
1312 * $fields = array("id", "uri", "uid", "network");
1314 * $condition = array("uid" => 1, "network" => 'dspr');
1316 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1318 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1320 * $data = DBA::select($table, $fields, $condition, $params);
1321 * @throws \Exception
1323 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1329 $table = self::escape($table);
1331 if (count($fields) > 0) {
1332 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1334 $select_fields = "*";
1337 $condition_string = self::buildCondition($condition);
1339 $param_string = self::buildParameter($params);
1341 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1343 $result = self::p($sql, $condition);
1349 * @brief Counts the rows from a table satisfying the provided condition
1351 * @param string $table Table name
1352 * @param array $condition array of fields for condition
1359 * $condition = ["uid" => 1, "network" => 'dspr'];
1361 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1363 * $count = DBA::count($table, $condition);
1364 * @throws \Exception
1366 public static function count($table, array $condition = [])
1372 $condition_string = self::buildCondition($condition);
1374 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1376 $row = self::fetchFirst($sql, $condition);
1378 return $row['count'];
1382 * @brief Returns the SQL condition string built from the provided condition array
1384 * This function operates with two modes.
1385 * - Supplied with a filed/value associative array, it builds simple strict
1386 * equality conditions linked by AND.
1387 * - Supplied with a flat list, the first element is the condition string and
1388 * the following arguments are the values to be interpolated
1390 * $condition = ["uid" => 1, "network" => 'dspr'];
1392 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1394 * In either case, the provided array is left with the parameters only
1396 * @param array $condition
1399 public static function buildCondition(array &$condition = [])
1401 $condition_string = '';
1402 if (count($condition) > 0) {
1404 $first_key = key($condition);
1405 if (is_int($first_key)) {
1406 $condition_string = " WHERE (" . array_shift($condition) . ")";
1409 $condition_string = "";
1410 foreach ($condition as $field => $value) {
1411 if ($condition_string != "") {
1412 $condition_string .= " AND ";
1414 if (is_array($value)) {
1415 /* Workaround for MySQL Bug #64791.
1416 * Never mix data types inside any IN() condition.
1417 * In case of mixed types, cast all as string.
1418 * Logic needs to be consistent with DBA::p() data types.
1422 foreach ($value as $single_value) {
1423 if (is_int($single_value)) {
1430 if ($is_int && $is_alpha) {
1431 foreach ($value as &$ref) {
1433 $ref = (string)$ref;
1436 unset($ref); //Prevent accidental re-use.
1439 $new_values = array_merge($new_values, array_values($value));
1440 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1441 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1443 $new_values[$field] = $value;
1444 $condition_string .= "`" . $field . "` = ?";
1447 $condition_string = " WHERE (" . $condition_string . ")";
1448 $condition = $new_values;
1452 return $condition_string;
1456 * @brief Returns the SQL parameter string built from the provided parameter array
1458 * @param array $params
1461 public static function buildParameter(array $params = [])
1464 if (isset($params['order'])) {
1465 $order_string = " ORDER BY ";
1466 foreach ($params['order'] AS $fields => $order) {
1467 if (!is_int($fields)) {
1468 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1470 $order_string .= "`" . $order . "`, ";
1473 $order_string = substr($order_string, 0, -2);
1477 if (isset($params['limit']) && is_int($params['limit'])) {
1478 $limit_string = " LIMIT " . intval($params['limit']);
1481 if (isset($params['limit']) && is_array($params['limit'])) {
1482 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1485 return $order_string.$limit_string;
1489 * @brief Fills an array with data from a query
1491 * @param object $stmt statement object
1492 * @param bool $do_close
1493 * @return array Data array
1495 public static function toArray($stmt, $do_close = true) {
1496 if (is_bool($stmt)) {
1501 while ($row = self::fetch($stmt)) {
1511 * @brief Returns the error number of the last query
1513 * @return string Error number (0 if no error)
1515 public static function errorNo() {
1516 return self::$errorno;
1520 * @brief Returns the error message of the last query
1522 * @return string Error message ('' if no error)
1524 public static function errorMessage() {
1525 return self::$error;
1529 * @brief Closes the current statement
1531 * @param object $stmt statement object
1532 * @return boolean was the close successful?
1534 public static function close($stmt) {
1537 $stamp1 = microtime(true);
1539 if (!is_object($stmt)) {
1543 switch (self::$driver) {
1545 $ret = $stmt->closeCursor();
1548 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1549 // We should be careful not to assume the object type of $stmt
1550 // because DBA::p() has been able to return both types.
1551 if ($stmt instanceof mysqli_stmt) {
1552 $stmt->free_result();
1553 $ret = $stmt->close();
1554 } elseif ($stmt instanceof mysqli_result) {
1563 $a->saveTimestamp($stamp1, 'database');
1569 * @brief Return a list of database processes
1572 * 'list' => List of processes, separated in their different states
1573 * 'amount' => Number of concurrent database processes
1574 * @throws \Exception
1576 public static function processlist()
1578 $ret = self::p("SHOW PROCESSLIST");
1579 $data = self::toArray($ret);
1583 foreach ($data as $process) {
1584 $state = trim($process["State"]);
1586 // Filter out all non blocking processes
1587 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1594 foreach ($states as $state => $usage) {
1595 if ($statelist != "") {
1598 $statelist .= $state.": ".$usage;
1600 return(["list" => $statelist, "amount" => $processes]);
1604 * Checks if $array is a filled array with at least one entry.
1606 * @param mixed $array A filled array with at least one entry
1608 * @return boolean Whether $array is a filled array or an object with rows
1610 public static function isResult($array)
1612 // It could be a return value from an update statement
1613 if (is_bool($array)) {
1617 if (is_object($array)) {
1618 return self::numRows($array) > 0;
1621 return (is_array($array) && (count($array) > 0));
1625 * @brief Callback function for "esc_array"
1627 * @param mixed $value Array value
1628 * @param string $key Array key
1629 * @param boolean $add_quotation add quotation marks for string values
1632 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1634 if (!$add_quotation) {
1635 if (is_bool($value)) {
1636 $value = ($value ? '1' : '0');
1638 $value = self::escape($value);
1643 if (is_bool($value)) {
1644 $value = ($value ? 'true' : 'false');
1645 } elseif (is_float($value) || is_integer($value)) {
1646 $value = (string) $value;
1648 $value = "'" . self::escape($value) . "'";
1653 * @brief Escapes a whole array
1655 * @param mixed $arr Array with values to be escaped
1656 * @param boolean $add_quotation add quotation marks for string values
1659 public static function escapeArray(&$arr, $add_quotation = false)
1661 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);