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;
20 * @class MySQL database class
22 * This class is for the low level database stuff that does driver specific things.
27 * Lowest possible date value
29 const NULL_DATE = '0001-01-01';
31 * Lowest possible datetime value
33 const NULL_DATETIME = '0001-01-01 00:00:00';
35 public static $connected = false;
37 private static $server_info = '';
38 private static $connection;
39 private static $driver;
40 private static $error = false;
41 private static $errorno = 0;
42 private static $affected_rows = 0;
43 private static $in_transaction = false;
44 private static $in_retrial = false;
45 private static $relation = [];
46 private static $db_serveraddr = '';
47 private static $db_user = '';
48 private static $db_pass = '';
49 private static $db_name = '';
50 private static $db_charset = '';
52 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
54 if (!is_null(self::$connection) && self::connected()) {
58 // We are storing these values for being able to perform a reconnect
59 self::$db_serveraddr = $serveraddr;
60 self::$db_user = $user;
61 self::$db_pass = $pass;
63 self::$db_charset = $charset;
66 $serveraddr = trim($serveraddr);
68 $serverdata = explode(':', $serveraddr);
69 $server = $serverdata[0];
71 if (count($serverdata) > 1) {
72 $port = trim($serverdata[1]);
75 $server = trim($server);
79 $charset = trim($charset);
81 if (!(strlen($server) && strlen($user))) {
85 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
86 self::$driver = 'pdo';
87 $connect = "mysql:host=".$server.";dbname=".$db;
90 $connect .= ";port=".$port;
94 $connect .= ";charset=".$charset;
98 self::$connection = @new PDO($connect, $user, $pass);
99 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
100 self::$connected = true;
101 } catch (PDOException $e) {
102 /// @TODO At least log exception, don't ignore it!
106 if (!self::$connected && class_exists('\mysqli')) {
107 self::$driver = 'mysqli';
110 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
112 self::$connection = @new mysqli($server, $user, $pass, $db);
115 if (!mysqli_connect_errno()) {
116 self::$connected = true;
119 self::$connection->set_charset($charset);
124 // No suitable SQL driver was found.
125 if (!self::$connected) {
126 self::$driver = null;
127 self::$connection = null;
130 return self::$connected;
134 * Disconnects the current database connection
136 public static function disconnect()
138 if (is_null(self::$connection)) {
142 switch (self::$driver) {
144 self::$connection = null;
147 self::$connection->close();
148 self::$connection = null;
154 * Perform a reconnect of an existing database connection
156 public static function reconnect() {
159 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
164 * Return the database object.
167 public static function getConnection()
169 return self::$connection;
173 * @brief Returns the MySQL server version string
175 * This function discriminate between the deprecated mysql API and the current
176 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
180 public static function serverInfo() {
181 if (self::$server_info == '') {
182 switch (self::$driver) {
184 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
187 self::$server_info = self::$connection->server_info;
191 return self::$server_info;
195 * @brief Returns the selected database name
200 public static function databaseName() {
201 $ret = self::p("SELECT DATABASE() AS `db`");
202 $data = self::toArray($ret);
203 return $data[0]['db'];
207 * @brief Analyze a database query and log this if some conditions are met.
209 * @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
393 public static function p($sql) {
396 $stamp1 = microtime(true);
398 $params = self::getParam(func_get_args());
400 // Renumber the array keys to be sure that they fit
403 foreach ($params AS $param) {
404 // Avoid problems with some MySQL servers and boolean values. See issue #3645
405 if (is_bool($param)) {
406 $param = (int)$param;
408 $args[++$i] = $param;
411 if (!self::$connected) {
415 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
416 // Question: Should we continue or stop the query here?
417 Logger::log('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), Logger::DEBUG);
420 $sql = self::cleanQuery($sql);
421 $sql = self::anyValueFallback($sql);
425 if ($a->getConfigValue('system', 'db_callstack')) {
426 $sql = "/*".System::callstack()." */ ".$sql;
431 self::$affected_rows = 0;
433 // We have to make some things different if this function is called from "e"
434 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
436 if (isset($trace[1])) {
437 $called_from = $trace[1];
439 // We use just something that is defined to avoid warnings
440 $called_from = $trace[0];
442 // We are having an own error logging in the function "e"
443 $called_from_e = ($called_from['function'] == 'e');
445 switch (self::$driver) {
447 // If there are no arguments we use "query"
448 if (count($args) == 0) {
449 if (!$retval = self::$connection->query($sql)) {
450 $errorInfo = self::$connection->errorInfo();
451 self::$error = $errorInfo[2];
452 self::$errorno = $errorInfo[1];
456 self::$affected_rows = $retval->rowCount();
460 if (!$stmt = self::$connection->prepare($sql)) {
461 $errorInfo = self::$connection->errorInfo();
462 self::$error = $errorInfo[2];
463 self::$errorno = $errorInfo[1];
468 foreach ($args AS $param => $value) {
469 if (is_int($args[$param])) {
470 $data_type = PDO::PARAM_INT;
472 $data_type = PDO::PARAM_STR;
474 $stmt->bindParam($param, $args[$param], $data_type);
477 if (!$stmt->execute()) {
478 $errorInfo = $stmt->errorInfo();
479 self::$error = $errorInfo[2];
480 self::$errorno = $errorInfo[1];
484 self::$affected_rows = $retval->rowCount();
488 // There are SQL statements that cannot be executed with a prepared statement
489 $parts = explode(' ', $orig_sql);
490 $command = strtolower($parts[0]);
491 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
493 // The fallback routine is called as well when there are no arguments
494 if (!$can_be_prepared || (count($args) == 0)) {
495 $retval = self::$connection->query(self::replaceParameters($sql, $args));
496 if (self::$connection->errno) {
497 self::$error = self::$connection->error;
498 self::$errorno = self::$connection->errno;
501 if (isset($retval->num_rows)) {
502 self::$affected_rows = $retval->num_rows;
504 self::$affected_rows = self::$connection->affected_rows;
510 $stmt = self::$connection->stmt_init();
512 if (!$stmt->prepare($sql)) {
513 self::$error = $stmt->error;
514 self::$errorno = $stmt->errno;
521 foreach ($args AS $param => $value) {
522 if (is_int($args[$param])) {
524 } elseif (is_float($args[$param])) {
526 } elseif (is_string($args[$param])) {
531 $values[] = &$args[$param];
534 if (count($values) > 0) {
535 array_unshift($values, $param_types);
536 call_user_func_array([$stmt, 'bind_param'], $values);
539 if (!$stmt->execute()) {
540 self::$error = self::$connection->error;
541 self::$errorno = self::$connection->errno;
544 $stmt->store_result();
546 self::$affected_rows = $retval->affected_rows;
551 // We are having an own error logging in the function "e"
552 if ((self::$errorno != 0) && !$called_from_e) {
553 // We have to preserve the error code, somewhere in the logging it get lost
554 $error = self::$error;
555 $errorno = self::$errorno;
557 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
558 System::callstack(8)."\n".self::replaceParameters($sql, $args));
560 // On a lost connection we try to reconnect - but only once.
561 if ($errorno == 2006) {
562 if (self::$in_retrial || !self::reconnect()) {
563 // It doesn't make sense to continue when the database connection was lost
564 if (self::$in_retrial) {
565 Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
567 Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
572 Logger::log('Reconnected after database error '.$errorno.': '.$error);
573 self::$in_retrial = true;
574 $ret = self::p($sql, $args);
575 self::$in_retrial = false;
580 self::$error = $error;
581 self::$errorno = $errorno;
584 $a->saveTimestamp($stamp1, 'database');
586 if ($a->getConfigValue('system', 'db_log')) {
587 $stamp2 = microtime(true);
588 $duration = (float)($stamp2 - $stamp1);
590 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
591 $duration = round($duration, 3);
592 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
594 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
595 basename($backtrace[1]["file"])."\t".
596 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
597 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
604 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
606 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
608 * @param string $sql SQL statement
609 * @return boolean Was the query successfull? False is returned only if an error occurred
612 public static function e($sql) {
615 $stamp = microtime(true);
617 $params = self::getParam(func_get_args());
619 // In a case of a deadlock we are repeating the query 20 times
623 $stmt = self::p($sql, $params);
625 if (is_bool($stmt)) {
627 } elseif (is_object($stmt)) {
635 } while ((self::$errorno == 1213) && (--$timeout > 0));
637 if (self::$errorno != 0) {
638 // We have to preserve the error code, somewhere in the logging it get lost
639 $error = self::$error;
640 $errorno = self::$errorno;
642 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
643 System::callstack(8)."\n".self::replaceParameters($sql, $params));
645 // On a lost connection we simply quit.
646 // A reconnect like in self::p could be dangerous with modifications
647 if ($errorno == 2006) {
648 Logger::log('Giving up because of database error '.$errorno.': '.$error);
652 self::$error = $error;
653 self::$errorno = $errorno;
656 $a->saveTimestamp($stamp, "database_write");
662 * @brief Check if data exists
664 * @param string $table Table name
665 * @param array $condition array of fields for condition
667 * @return boolean Are there rows for that condition?
670 public static function exists($table, $condition) {
677 if (empty($condition)) {
678 return DBStructure::existsTable($table);
682 $first_key = key($condition);
683 if (!is_int($first_key)) {
684 $fields = [$first_key];
687 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
689 if (is_bool($stmt)) {
692 $retval = (self::numRows($stmt) > 0);
701 * Fetches the first row
703 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
705 * @brief Fetches the first row
706 * @param string $sql SQL statement
707 * @return array first row of query
710 public static function fetchFirst($sql) {
711 $params = self::getParam(func_get_args());
713 $stmt = self::p($sql, $params);
715 if (is_bool($stmt)) {
718 $retval = self::fetch($stmt);
727 * @brief Returns the number of affected rows of the last statement
729 * @return int Number of rows
731 public static function affectedRows() {
732 return self::$affected_rows;
736 * @brief Returns the number of columns of a statement
738 * @param object Statement object
739 * @return int Number of columns
741 public static function columnCount($stmt) {
742 if (!is_object($stmt)) {
745 switch (self::$driver) {
747 return $stmt->columnCount();
749 return $stmt->field_count;
754 * @brief Returns the number of rows of a statement
756 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
757 * @return int Number of rows
759 public static function numRows($stmt) {
760 if (!is_object($stmt)) {
763 switch (self::$driver) {
765 return $stmt->rowCount();
767 return $stmt->num_rows;
773 * @brief Fetch a single row
775 * @param mixed $stmt statement object
776 * @return array current row
778 public static function fetch($stmt) {
781 $stamp1 = microtime(true);
785 if (!is_object($stmt)) {
789 switch (self::$driver) {
791 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
794 if (get_class($stmt) == 'mysqli_result') {
795 $columns = $stmt->fetch_assoc();
799 // This code works, but is slow
801 // Bind the result to a result array
805 for ($x = 0; $x < $stmt->field_count; $x++) {
806 $cols[] = &$cols_num[$x];
809 call_user_func_array([$stmt, 'bind_result'], $cols);
811 if (!$stmt->fetch()) {
816 // We need to get the field names for the array keys
817 // It seems that there is no better way to do this.
818 $result = $stmt->result_metadata();
819 $fields = $result->fetch_fields();
821 foreach ($cols_num AS $param => $col) {
822 $columns[$fields[$param]->name] = $col;
826 $a->saveTimestamp($stamp1, 'database');
832 * @brief Insert a row into a table
834 * @param string $table Table name
835 * @param array $param parameter array
836 * @param bool $on_duplicate_update Do an update on a duplicate entry
838 * @return boolean was the insert successful?
841 public static function insert($table, $param, $on_duplicate_update = false) {
843 if (empty($table) || empty($param)) {
844 Logger::log('Table and fields have to be set');
848 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
849 substr(str_repeat("?, ", count($param)), 0, -2).")";
851 if ($on_duplicate_update) {
852 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
854 $values = array_values($param);
855 $param = array_merge_recursive($values, $values);
858 return self::e($sql, $param);
862 * @brief Fetch the id of the last insert command
864 * @return integer Last inserted id
866 public static function lastInsertId() {
867 switch (self::$driver) {
869 $id = self::$connection->lastInsertId();
872 $id = self::$connection->insert_id;
879 * @brief Locks a table for exclusive write access
881 * This function can be extended in the future to accept a table array as well.
883 * @param string $table Table name
885 * @return boolean was the lock successful?
888 public static function lock($table) {
889 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
890 if (self::$driver == 'pdo') {
891 self::e("SET autocommit=0");
892 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
894 self::$connection->autocommit(false);
897 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
899 if (self::$driver == 'pdo') {
900 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
904 if (self::$driver == 'pdo') {
905 self::e("SET autocommit=1");
907 self::$connection->autocommit(true);
910 self::$in_transaction = true;
916 * @brief Unlocks all locked tables
918 * @return boolean was the unlock successful?
921 public static function unlock() {
922 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
923 self::performCommit();
925 if (self::$driver == 'pdo') {
926 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
929 $success = self::e("UNLOCK TABLES");
931 if (self::$driver == 'pdo') {
932 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
933 self::e("SET autocommit=1");
935 self::$connection->autocommit(true);
938 self::$in_transaction = false;
943 * @brief Starts a transaction
945 * @return boolean Was the command executed successfully?
947 public static function transaction() {
948 if (!self::performCommit()) {
952 switch (self::$driver) {
954 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
960 if (!self::$connection->begin_transaction()) {
966 self::$in_transaction = true;
970 private static function performCommit()
972 switch (self::$driver) {
974 if (!self::$connection->inTransaction()) {
978 return self::$connection->commit();
981 return self::$connection->commit();
988 * @brief Does a commit
990 * @return boolean Was the command executed successfully?
992 public static function commit() {
993 if (!self::performCommit()) {
996 self::$in_transaction = false;
1001 * @brief Does a rollback
1003 * @return boolean Was the command executed successfully?
1005 public static function rollback() {
1008 switch (self::$driver) {
1010 if (!self::$connection->inTransaction()) {
1014 $ret = self::$connection->rollBack();
1018 $ret = self::$connection->rollback();
1021 self::$in_transaction = false;
1026 * @brief Build the array with the table relations
1028 * The array is build from the database definitions in DBStructure.php
1030 * This process must only be started once, since the value is cached.
1032 private static function buildRelationData() {
1033 $definition = DBStructure::definition();
1035 foreach ($definition AS $table => $structure) {
1036 foreach ($structure['fields'] AS $field => $field_struct) {
1037 if (isset($field_struct['relation'])) {
1038 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1039 self::$relation[$rel_table][$rel_field][$table][] = $field;
1047 * @brief Delete a row from a table
1049 * @param string $table Table name
1050 * @param array $conditions Field condition(s)
1051 * @param array $options
1052 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1053 * relations (default: true)
1054 * @param array $callstack Internal use: prevent endless loops
1056 * @return boolean was the delete successful?
1057 * @throws \Exception
1059 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1061 if (empty($table) || empty($conditions)) {
1062 Logger::log('Table and conditions have to be set');
1068 // Create a key for the loop prevention
1069 $key = $table . ':' . json_encode($conditions);
1071 // We quit when this key already exists in the callstack.
1072 if (isset($callstack[$key])) {
1076 $callstack[$key] = true;
1078 $table = self::escape($table);
1080 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1082 // Don't use "defaults" here, since it would set "false" to "true"
1083 if (isset($options['cascade'])) {
1084 $cascade = $options['cascade'];
1089 // To speed up the whole process we cache the table relations
1090 if ($cascade && count(self::$relation) == 0) {
1091 self::buildRelationData();
1094 // Is there a relation entry for the table?
1095 if ($cascade && isset(self::$relation[$table])) {
1096 // We only allow a simple "one field" relation.
1097 $field = array_keys(self::$relation[$table])[0];
1098 $rel_def = array_values(self::$relation[$table])[0];
1100 // Create a key for preventing double queries
1101 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1103 // When the search field is the relation field, we don't need to fetch the rows
1104 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1105 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1106 foreach ($rel_def AS $rel_table => $rel_fields) {
1107 foreach ($rel_fields AS $rel_field) {
1108 self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1111 // We quit when this key already exists in the callstack.
1112 } elseif (!isset($callstack[$qkey])) {
1113 $callstack[$qkey] = true;
1115 // Fetch all rows that are to be deleted
1116 $data = self::select($table, [$field], $conditions);
1118 while ($row = self::fetch($data)) {
1119 self::delete($table, [$field => $row[$field]], $options, $callstack);
1124 // Since we had split the delete command we don't need the original command anymore
1125 unset($commands[$key]);
1129 // Now we finalize the process
1130 $do_transaction = !self::$in_transaction;
1132 if ($do_transaction) {
1133 self::transaction();
1139 foreach ($commands AS $command) {
1140 $conditions = $command['conditions'];
1142 $first_key = key($conditions);
1144 $condition_string = self::buildCondition($conditions);
1146 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1147 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1148 Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
1150 if (!self::e($sql, $conditions)) {
1151 if ($do_transaction) {
1157 $key_table = $command['table'];
1158 $key_condition = array_keys($command['conditions'])[0];
1159 $value = array_values($command['conditions'])[0];
1161 // Split the SQL queries in chunks of 100 values
1162 // We do the $i stuff here to make the code better readable
1163 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1164 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1168 $compacted[$key_table][$key_condition][$i][$value] = $value;
1169 $counter[$key_table][$key_condition] = $i;
1172 foreach ($compacted AS $table => $values) {
1173 foreach ($values AS $field => $field_value_list) {
1174 foreach ($field_value_list AS $field_values) {
1175 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1176 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1178 Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
1180 if (!self::e($sql, $field_values)) {
1181 if ($do_transaction) {
1189 if ($do_transaction) {
1196 * @brief Updates rows
1198 * Updates rows in the database. When $old_fields is set to an array,
1199 * the system will only do an update if the fields in that array changed.
1202 * Only the values in $old_fields are compared.
1203 * This is an intentional behaviour.
1206 * We include the timestamp field in $fields but not in $old_fields.
1207 * Then the row will only get the new timestamp when the other fields had changed.
1209 * When $old_fields is set to a boolean value the system will do this compare itself.
1210 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1213 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1214 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1216 * @param string $table Table name
1217 * @param array $fields contains the fields that are updated
1218 * @param array $condition condition array with the key values
1219 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1221 * @return boolean was the update successfull?
1222 * @throws \Exception
1224 public static function update($table, $fields, $condition, $old_fields = []) {
1226 if (empty($table) || empty($fields) || empty($condition)) {
1227 Logger::log('Table, fields and condition have to be set');
1231 $table = self::escape($table);
1233 $condition_string = self::buildCondition($condition);
1235 if (is_bool($old_fields)) {
1236 $do_insert = $old_fields;
1238 $old_fields = self::selectFirst($table, [], $condition);
1240 if (is_bool($old_fields)) {
1242 $values = array_merge($condition, $fields);
1243 return self::insert($table, $values, $do_insert);
1249 $do_update = (count($old_fields) == 0);
1251 foreach ($old_fields AS $fieldname => $content) {
1252 if (isset($fields[$fieldname])) {
1253 if (($fields[$fieldname] == $content) && !is_null($content)) {
1254 unset($fields[$fieldname]);
1261 if (!$do_update || (count($fields) == 0)) {
1265 $sql = "UPDATE `".$table."` SET `".
1266 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1268 $params1 = array_values($fields);
1269 $params2 = array_values($condition);
1270 $params = array_merge_recursive($params1, $params2);
1272 return self::e($sql, $params);
1276 * Retrieve a single record from a table and returns it in an associative array
1278 * @brief Retrieve a single record from a table
1279 * @param string $table
1280 * @param array $fields
1281 * @param array $condition
1282 * @param array $params
1283 * @return bool|array
1284 * @throws \Exception
1287 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1289 $params['limit'] = 1;
1290 $result = self::select($table, $fields, $condition, $params);
1292 if (is_bool($result)) {
1295 $row = self::fetch($result);
1296 self::close($result);
1302 * @brief Select rows from a table
1304 * @param string $table Table name
1305 * @param array $fields Array of selected fields, empty for all
1306 * @param array $condition Array of fields for condition
1307 * @param array $params Array of several parameters
1309 * @return boolean|object
1313 * $fields = array("id", "uri", "uid", "network");
1315 * $condition = array("uid" => 1, "network" => 'dspr');
1317 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1319 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1321 * $data = DBA::select($table, $fields, $condition, $params);
1322 * @throws \Exception
1324 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1330 $table = self::escape($table);
1332 if (count($fields) > 0) {
1333 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1335 $select_fields = "*";
1338 $condition_string = self::buildCondition($condition);
1340 $param_string = self::buildParameter($params);
1342 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1344 $result = self::p($sql, $condition);
1350 * @brief Counts the rows from a table satisfying the provided condition
1352 * @param string $table Table name
1353 * @param array $condition array of fields for condition
1360 * $condition = ["uid" => 1, "network" => 'dspr'];
1362 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1364 * $count = DBA::count($table, $condition);
1365 * @throws \Exception
1367 public static function count($table, array $condition = [])
1373 $condition_string = self::buildCondition($condition);
1375 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1377 $row = self::fetchFirst($sql, $condition);
1379 return $row['count'];
1383 * @brief Returns the SQL condition string built from the provided condition array
1385 * This function operates with two modes.
1386 * - Supplied with a filed/value associative array, it builds simple strict
1387 * equality conditions linked by AND.
1388 * - Supplied with a flat list, the first element is the condition string and
1389 * the following arguments are the values to be interpolated
1391 * $condition = ["uid" => 1, "network" => 'dspr'];
1393 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1395 * In either case, the provided array is left with the parameters only
1397 * @param array $condition
1400 public static function buildCondition(array &$condition = [])
1402 $condition_string = '';
1403 if (count($condition) > 0) {
1405 $first_key = key($condition);
1406 if (is_int($first_key)) {
1407 $condition_string = " WHERE (" . array_shift($condition) . ")";
1410 $condition_string = "";
1411 foreach ($condition as $field => $value) {
1412 if ($condition_string != "") {
1413 $condition_string .= " AND ";
1415 if (is_array($value)) {
1416 /* Workaround for MySQL Bug #64791.
1417 * Never mix data types inside any IN() condition.
1418 * In case of mixed types, cast all as string.
1419 * Logic needs to be consistent with DBA::p() data types.
1423 foreach ($value as $single_value) {
1424 if (is_int($single_value)) {
1431 if ($is_int && $is_alpha) {
1432 foreach ($value as &$ref) {
1434 $ref = (string)$ref;
1437 unset($ref); //Prevent accidental re-use.
1440 $new_values = array_merge($new_values, array_values($value));
1441 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1442 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1444 $new_values[$field] = $value;
1445 $condition_string .= "`" . $field . "` = ?";
1448 $condition_string = " WHERE (" . $condition_string . ")";
1449 $condition = $new_values;
1453 return $condition_string;
1457 * @brief Returns the SQL parameter string built from the provided parameter array
1459 * @param array $params
1462 public static function buildParameter(array $params = [])
1465 if (isset($params['order'])) {
1466 $order_string = " ORDER BY ";
1467 foreach ($params['order'] AS $fields => $order) {
1468 if (!is_int($fields)) {
1469 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1471 $order_string .= "`" . $order . "`, ";
1474 $order_string = substr($order_string, 0, -2);
1478 if (isset($params['limit']) && is_int($params['limit'])) {
1479 $limit_string = " LIMIT " . intval($params['limit']);
1482 if (isset($params['limit']) && is_array($params['limit'])) {
1483 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1486 return $order_string.$limit_string;
1490 * @brief Fills an array with data from a query
1492 * @param object $stmt statement object
1493 * @param bool $do_close
1494 * @return array Data array
1496 public static function toArray($stmt, $do_close = true) {
1497 if (is_bool($stmt)) {
1502 while ($row = self::fetch($stmt)) {
1512 * @brief Returns the error number of the last query
1514 * @return string Error number (0 if no error)
1516 public static function errorNo() {
1517 return self::$errorno;
1521 * @brief Returns the error message of the last query
1523 * @return string Error message ('' if no error)
1525 public static function errorMessage() {
1526 return self::$error;
1530 * @brief Closes the current statement
1532 * @param object $stmt statement object
1533 * @return boolean was the close successful?
1535 public static function close($stmt) {
1538 $stamp1 = microtime(true);
1540 if (!is_object($stmt)) {
1544 switch (self::$driver) {
1546 $ret = $stmt->closeCursor();
1549 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1550 // We should be careful not to assume the object type of $stmt
1551 // because DBA::p() has been able to return both types.
1552 if ($stmt instanceof mysqli_stmt) {
1553 $stmt->free_result();
1554 $ret = $stmt->close();
1555 } elseif ($stmt instanceof mysqli_result) {
1564 $a->saveTimestamp($stamp1, 'database');
1570 * @brief Return a list of database processes
1573 * 'list' => List of processes, separated in their different states
1574 * 'amount' => Number of concurrent database processes
1575 * @throws \Exception
1577 public static function processlist()
1579 $ret = self::p("SHOW PROCESSLIST");
1580 $data = self::toArray($ret);
1584 foreach ($data as $process) {
1585 $state = trim($process["State"]);
1587 // Filter out all non blocking processes
1588 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1595 foreach ($states as $state => $usage) {
1596 if ($statelist != "") {
1599 $statelist .= $state.": ".$usage;
1601 return(["list" => $statelist, "amount" => $processes]);
1605 * Checks if $array is a filled array with at least one entry.
1607 * @param mixed $array A filled array with at least one entry
1609 * @return boolean Whether $array is a filled array or an object with rows
1611 public static function isResult($array)
1613 // It could be a return value from an update statement
1614 if (is_bool($array)) {
1618 if (is_object($array)) {
1619 return self::numRows($array) > 0;
1622 return (is_array($array) && (count($array) > 0));
1626 * @brief Callback function for "esc_array"
1628 * @param mixed $value Array value
1629 * @param string $key Array key
1630 * @param boolean $add_quotation add quotation marks for string values
1633 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1635 if (!$add_quotation) {
1636 if (is_bool($value)) {
1637 $value = ($value ? '1' : '0');
1639 $value = self::escape($value);
1644 if (is_bool($value)) {
1645 $value = ($value ? 'true' : 'false');
1646 } elseif (is_float($value) || is_integer($value)) {
1647 $value = (string) $value;
1649 $value = "'" . self::escape($value) . "'";
1654 * @brief Escapes a whole array
1656 * @param mixed $arr Array with values to be escaped
1657 * @param boolean $add_quotation add quotation marks for string values
1660 public static function escapeArray(&$arr, $add_quotation = false)
1662 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);