3 namespace Friendica\Database;
5 use Friendica\Core\Config\IConfigCache;
6 use Friendica\Core\Logger;
7 use Friendica\Core\System;
8 use Friendica\Util\DateTimeFormat;
17 * @class MySQL database class
19 * This class is for the low level database stuff that does driver specific things.
24 * Lowest possible date value
26 const NULL_DATE = '0001-01-01';
28 * Lowest possible datetime value
30 const NULL_DATETIME = '0001-01-01 00:00:00';
32 public static $connected = false;
37 private static $configCache;
38 private static $server_info = '';
39 private static $connection;
40 private static $driver;
41 private static $error = false;
42 private static $errorno = 0;
43 private static $affected_rows = 0;
44 private static $in_transaction = false;
45 private static $in_retrial = false;
46 private static $relation = [];
47 private static $db_serveraddr = '';
48 private static $db_user = '';
49 private static $db_pass = '';
50 private static $db_name = '';
51 private static $db_charset = '';
53 public static function connect($configCache, $serveraddr, $user, $pass, $db, $charset = null)
55 if (!is_null(self::$connection) && self::connected()) {
59 // We are storing these values for being able to perform a reconnect
60 self::$configCache = $configCache;
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::$configCache, 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
202 public static function databaseName() {
203 $ret = self::p("SELECT DATABASE() AS `db`");
204 $data = self::toArray($ret);
205 return $data[0]['db'];
209 * @brief Analyze a database query and log this if some conditions are met.
211 * @param string $query The database query that will be analyzed
214 private static function logIndex($query) {
216 if (!self::$configCache->get('system', 'db_log_index')) {
220 // Don't explain an explain statement
221 if (strtolower(substr($query, 0, 7)) == "explain") {
225 // Only do the explain on "select", "update" and "delete"
226 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
230 $r = self::p("EXPLAIN ".$query);
231 if (!self::isResult($r)) {
235 $watchlist = explode(',', self::$configCache->get('system', 'db_log_index_watch'));
236 $blacklist = explode(',', self::$configCache->get('system', 'db_log_index_blacklist'));
238 while ($row = self::fetch($r)) {
239 if ((intval(self::$configCache->get('system', 'db_loglimit_index')) > 0)) {
240 $log = (in_array($row['key'], $watchlist) &&
241 ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index'))));
246 if ((intval(self::$configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index_high')))) {
250 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
255 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
256 @file_put_contents(self::$configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
257 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
258 basename($backtrace[1]["file"])."\t".
259 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
260 substr($query, 0, 2000)."\n", FILE_APPEND);
265 public static function escape($str) {
266 if (self::$connected) {
267 switch (self::$driver) {
269 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
272 return @self::$connection->real_escape_string($str);
275 return str_replace("'", "\\'", $str);
279 public static function connected() {
282 if (is_null(self::$connection)) {
286 switch (self::$driver) {
288 $r = self::p("SELECT 1");
289 if (self::isResult($r)) {
290 $row = self::toArray($r);
291 $connected = ($row[0]['1'] == '1');
295 $connected = self::$connection->ping();
302 * @brief Replaces ANY_VALUE() function by MIN() function,
303 * if the database server does not support ANY_VALUE().
305 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
306 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
307 * A standard fall-back is to use MIN().
309 * @param string $sql An SQL string without the values
310 * @return string The input SQL string modified if necessary.
312 public static function anyValueFallback($sql) {
313 $server_info = self::serverInfo();
314 if (version_compare($server_info, '5.7.5', '<') ||
315 (stripos($server_info, 'MariaDB') !== false)) {
316 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
322 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
324 * This is safe when we bind the parameters later.
325 * The parameter values aren't part of the SQL.
327 * @param string $sql An SQL string without the values
328 * @return string The input SQL string modified if necessary.
330 public static function cleanQuery($sql) {
331 $search = ["\t", "\n", "\r", " "];
332 $replace = [' ', ' ', ' ', ' '];
335 $sql = str_replace($search, $replace, $sql);
336 } while ($oldsql != $sql);
343 * @brief Replaces the ? placeholders with the parameters in the $args array
345 * @param string $sql SQL query
346 * @param array $args The parameters that are to replace the ? placeholders
347 * @return string The replaced SQL query
349 private static function replaceParameters($sql, $args) {
351 foreach ($args AS $param => $value) {
352 if (is_int($args[$param]) || is_float($args[$param])) {
353 $replace = intval($args[$param]);
355 $replace = "'".self::escape($args[$param])."'";
358 $pos = strpos($sql, '?', $offset);
359 if ($pos !== false) {
360 $sql = substr_replace($sql, $replace, $pos, 1);
362 $offset = $pos + strlen($replace);
368 * @brief Convert parameter array to an universal form
369 * @param array $args Parameter array
370 * @return array universalized parameter array
372 private static function getParam($args) {
375 // When the second function parameter is an array then use this as the parameter array
376 if ((count($args) > 0) && (is_array($args[1]))) {
384 * @brief Executes a prepared statement that returns data
385 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
387 * Please only use it with complicated queries.
388 * For all regular queries please use DBA::select or DBA::exists
390 * @param string $sql SQL statement
391 * @return bool|object statement object or result object
394 public static function p($sql) {
397 $stamp1 = microtime(true);
399 $params = self::getParam(func_get_args());
401 // Renumber the array keys to be sure that they fit
404 foreach ($params AS $param) {
405 // Avoid problems with some MySQL servers and boolean values. See issue #3645
406 if (is_bool($param)) {
407 $param = (int)$param;
409 $args[++$i] = $param;
412 if (!self::$connected) {
416 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
417 // Question: Should we continue or stop the query here?
418 Logger::log('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), Logger::DEBUG);
421 $sql = self::cleanQuery($sql);
422 $sql = self::anyValueFallback($sql);
426 if (self::$configCache->get('system', 'db_callstack') !== null) {
427 $sql = "/*".System::callstack()." */ ".$sql;
432 self::$affected_rows = 0;
434 // We have to make some things different if this function is called from "e"
435 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
437 if (isset($trace[1])) {
438 $called_from = $trace[1];
440 // We use just something that is defined to avoid warnings
441 $called_from = $trace[0];
443 // We are having an own error logging in the function "e"
444 $called_from_e = ($called_from['function'] == 'e');
446 switch (self::$driver) {
448 // If there are no arguments we use "query"
449 if (count($args) == 0) {
450 if (!$retval = self::$connection->query($sql)) {
451 $errorInfo = self::$connection->errorInfo();
452 self::$error = $errorInfo[2];
453 self::$errorno = $errorInfo[1];
457 self::$affected_rows = $retval->rowCount();
461 if (!$stmt = self::$connection->prepare($sql)) {
462 $errorInfo = self::$connection->errorInfo();
463 self::$error = $errorInfo[2];
464 self::$errorno = $errorInfo[1];
469 foreach ($args AS $param => $value) {
470 if (is_int($args[$param])) {
471 $data_type = PDO::PARAM_INT;
473 $data_type = PDO::PARAM_STR;
475 $stmt->bindParam($param, $args[$param], $data_type);
478 if (!$stmt->execute()) {
479 $errorInfo = $stmt->errorInfo();
480 self::$error = $errorInfo[2];
481 self::$errorno = $errorInfo[1];
485 self::$affected_rows = $retval->rowCount();
489 // There are SQL statements that cannot be executed with a prepared statement
490 $parts = explode(' ', $orig_sql);
491 $command = strtolower($parts[0]);
492 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
494 // The fallback routine is called as well when there are no arguments
495 if (!$can_be_prepared || (count($args) == 0)) {
496 $retval = self::$connection->query(self::replaceParameters($sql, $args));
497 if (self::$connection->errno) {
498 self::$error = self::$connection->error;
499 self::$errorno = self::$connection->errno;
502 if (isset($retval->num_rows)) {
503 self::$affected_rows = $retval->num_rows;
505 self::$affected_rows = self::$connection->affected_rows;
511 $stmt = self::$connection->stmt_init();
513 if (!$stmt->prepare($sql)) {
514 self::$error = $stmt->error;
515 self::$errorno = $stmt->errno;
522 foreach ($args AS $param => $value) {
523 if (is_int($args[$param])) {
525 } elseif (is_float($args[$param])) {
527 } elseif (is_string($args[$param])) {
532 $values[] = &$args[$param];
535 if (count($values) > 0) {
536 array_unshift($values, $param_types);
537 call_user_func_array([$stmt, 'bind_param'], $values);
540 if (!$stmt->execute()) {
541 self::$error = self::$connection->error;
542 self::$errorno = self::$connection->errno;
545 $stmt->store_result();
547 self::$affected_rows = $retval->affected_rows;
552 // We are having an own error logging in the function "e"
553 if ((self::$errorno != 0) && !$called_from_e) {
554 // We have to preserve the error code, somewhere in the logging it get lost
555 $error = self::$error;
556 $errorno = self::$errorno;
558 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
559 System::callstack(8)."\n".self::replaceParameters($sql, $args));
561 // On a lost connection we try to reconnect - but only once.
562 if ($errorno == 2006) {
563 if (self::$in_retrial || !self::reconnect()) {
564 // It doesn't make sense to continue when the database connection was lost
565 if (self::$in_retrial) {
566 Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
568 Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
573 Logger::log('Reconnected after database error '.$errorno.': '.$error);
574 self::$in_retrial = true;
575 $ret = self::p($sql, $args);
576 self::$in_retrial = false;
581 self::$error = $error;
582 self::$errorno = $errorno;
585 $a->saveTimestamp($stamp1, 'database');
587 if (self::$configCache->get('system', 'db_log')) {
588 $stamp2 = microtime(true);
589 $duration = (float)($stamp2 - $stamp1);
591 if (($duration > self::$configCache->get('system', 'db_loglimit'))) {
592 $duration = round($duration, 3);
593 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
595 @file_put_contents(self::$configCache->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
596 basename($backtrace[1]["file"])."\t".
597 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
598 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
605 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
607 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
609 * @param string $sql SQL statement
610 * @return boolean Was the query successfull? False is returned only if an error occurred
613 public static function e($sql) {
616 $stamp = microtime(true);
618 $params = self::getParam(func_get_args());
620 // In a case of a deadlock we are repeating the query 20 times
624 $stmt = self::p($sql, $params);
626 if (is_bool($stmt)) {
628 } elseif (is_object($stmt)) {
636 } while ((self::$errorno == 1213) && (--$timeout > 0));
638 if (self::$errorno != 0) {
639 // We have to preserve the error code, somewhere in the logging it get lost
640 $error = self::$error;
641 $errorno = self::$errorno;
643 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
644 System::callstack(8)."\n".self::replaceParameters($sql, $params));
646 // On a lost connection we simply quit.
647 // A reconnect like in self::p could be dangerous with modifications
648 if ($errorno == 2006) {
649 Logger::log('Giving up because of database error '.$errorno.': '.$error);
653 self::$error = $error;
654 self::$errorno = $errorno;
657 $a->saveTimestamp($stamp, "database_write");
663 * @brief Check if data exists
665 * @param string $table Table name
666 * @param array $condition array of fields for condition
668 * @return boolean Are there rows for that condition?
671 public static function exists($table, $condition) {
678 if (empty($condition)) {
679 return DBStructure::existsTable($table);
683 $first_key = key($condition);
684 if (!is_int($first_key)) {
685 $fields = [$first_key];
688 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
690 if (is_bool($stmt)) {
693 $retval = (self::numRows($stmt) > 0);
702 * Fetches the first row
704 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
706 * @brief Fetches the first row
707 * @param string $sql SQL statement
708 * @return array first row of query
711 public static function fetchFirst($sql) {
712 $params = self::getParam(func_get_args());
714 $stmt = self::p($sql, $params);
716 if (is_bool($stmt)) {
719 $retval = self::fetch($stmt);
728 * @brief Returns the number of affected rows of the last statement
730 * @return int Number of rows
732 public static function affectedRows() {
733 return self::$affected_rows;
737 * @brief Returns the number of columns of a statement
739 * @param object Statement object
740 * @return int Number of columns
742 public static function columnCount($stmt) {
743 if (!is_object($stmt)) {
746 switch (self::$driver) {
748 return $stmt->columnCount();
750 return $stmt->field_count;
755 * @brief Returns the number of rows of a statement
757 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
758 * @return int Number of rows
760 public static function numRows($stmt) {
761 if (!is_object($stmt)) {
764 switch (self::$driver) {
766 return $stmt->rowCount();
768 return $stmt->num_rows;
774 * @brief Fetch a single row
776 * @param mixed $stmt statement object
777 * @return array current row
779 public static function fetch($stmt) {
782 $stamp1 = microtime(true);
786 if (!is_object($stmt)) {
790 switch (self::$driver) {
792 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
795 if (get_class($stmt) == 'mysqli_result') {
796 $columns = $stmt->fetch_assoc();
800 // This code works, but is slow
802 // Bind the result to a result array
806 for ($x = 0; $x < $stmt->field_count; $x++) {
807 $cols[] = &$cols_num[$x];
810 call_user_func_array([$stmt, 'bind_result'], $cols);
812 if (!$stmt->fetch()) {
817 // We need to get the field names for the array keys
818 // It seems that there is no better way to do this.
819 $result = $stmt->result_metadata();
820 $fields = $result->fetch_fields();
822 foreach ($cols_num AS $param => $col) {
823 $columns[$fields[$param]->name] = $col;
827 $a->saveTimestamp($stamp1, 'database');
833 * @brief Insert a row into a table
835 * @param string $table Table name
836 * @param array $param parameter array
837 * @param bool $on_duplicate_update Do an update on a duplicate entry
839 * @return boolean was the insert successful?
842 public static function insert($table, $param, $on_duplicate_update = false) {
844 if (empty($table) || empty($param)) {
845 Logger::log('Table and fields have to be set');
849 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
850 substr(str_repeat("?, ", count($param)), 0, -2).")";
852 if ($on_duplicate_update) {
853 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
855 $values = array_values($param);
856 $param = array_merge_recursive($values, $values);
859 return self::e($sql, $param);
863 * @brief Fetch the id of the last insert command
865 * @return integer Last inserted id
867 public static function lastInsertId() {
868 switch (self::$driver) {
870 $id = self::$connection->lastInsertId();
873 $id = self::$connection->insert_id;
880 * @brief Locks a table for exclusive write access
882 * This function can be extended in the future to accept a table array as well.
884 * @param string $table Table name
886 * @return boolean was the lock successful?
889 public static function lock($table) {
890 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
891 if (self::$driver == 'pdo') {
892 self::e("SET autocommit=0");
893 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
895 self::$connection->autocommit(false);
898 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
900 if (self::$driver == 'pdo') {
901 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
905 if (self::$driver == 'pdo') {
906 self::e("SET autocommit=1");
908 self::$connection->autocommit(true);
911 self::$in_transaction = true;
917 * @brief Unlocks all locked tables
919 * @return boolean was the unlock successful?
922 public static function unlock() {
923 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
924 self::performCommit();
926 if (self::$driver == 'pdo') {
927 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
930 $success = self::e("UNLOCK TABLES");
932 if (self::$driver == 'pdo') {
933 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
934 self::e("SET autocommit=1");
936 self::$connection->autocommit(true);
939 self::$in_transaction = false;
944 * @brief Starts a transaction
946 * @return boolean Was the command executed successfully?
948 public static function transaction() {
949 if (!self::performCommit()) {
953 switch (self::$driver) {
955 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
961 if (!self::$connection->begin_transaction()) {
967 self::$in_transaction = true;
971 private static function performCommit()
973 switch (self::$driver) {
975 if (!self::$connection->inTransaction()) {
979 return self::$connection->commit();
982 return self::$connection->commit();
989 * @brief Does a commit
991 * @return boolean Was the command executed successfully?
993 public static function commit() {
994 if (!self::performCommit()) {
997 self::$in_transaction = false;
1002 * @brief Does a rollback
1004 * @return boolean Was the command executed successfully?
1006 public static function rollback() {
1009 switch (self::$driver) {
1011 if (!self::$connection->inTransaction()) {
1015 $ret = self::$connection->rollBack();
1019 $ret = self::$connection->rollback();
1022 self::$in_transaction = false;
1027 * @brief Build the array with the table relations
1029 * The array is build from the database definitions in DBStructure.php
1031 * This process must only be started once, since the value is cached.
1033 private static function buildRelationData() {
1034 $definition = DBStructure::definition(self::$configCache->get('system', 'basepath'));
1036 foreach ($definition AS $table => $structure) {
1037 foreach ($structure['fields'] AS $field => $field_struct) {
1038 if (isset($field_struct['relation'])) {
1039 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1040 self::$relation[$rel_table][$rel_field][$table][] = $field;
1048 * @brief Delete a row from a table
1050 * @param string $table Table name
1051 * @param array $conditions Field condition(s)
1052 * @param array $options
1053 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1054 * relations (default: true)
1055 * @param array $callstack Internal use: prevent endless loops
1057 * @return boolean was the delete successful?
1058 * @throws \Exception
1060 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1062 if (empty($table) || empty($conditions)) {
1063 Logger::log('Table and conditions have to be set');
1069 // Create a key for the loop prevention
1070 $key = $table . ':' . json_encode($conditions);
1072 // We quit when this key already exists in the callstack.
1073 if (isset($callstack[$key])) {
1077 $callstack[$key] = true;
1079 $table = self::escape($table);
1081 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1083 // Don't use "defaults" here, since it would set "false" to "true"
1084 if (isset($options['cascade'])) {
1085 $cascade = $options['cascade'];
1090 // To speed up the whole process we cache the table relations
1091 if ($cascade && count(self::$relation) == 0) {
1092 self::buildRelationData();
1095 // Is there a relation entry for the table?
1096 if ($cascade && isset(self::$relation[$table])) {
1097 // We only allow a simple "one field" relation.
1098 $field = array_keys(self::$relation[$table])[0];
1099 $rel_def = array_values(self::$relation[$table])[0];
1101 // Create a key for preventing double queries
1102 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1104 // When the search field is the relation field, we don't need to fetch the rows
1105 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1106 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1107 foreach ($rel_def AS $rel_table => $rel_fields) {
1108 foreach ($rel_fields AS $rel_field) {
1109 self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1112 // We quit when this key already exists in the callstack.
1113 } elseif (!isset($callstack[$qkey])) {
1114 $callstack[$qkey] = true;
1116 // Fetch all rows that are to be deleted
1117 $data = self::select($table, [$field], $conditions);
1119 while ($row = self::fetch($data)) {
1120 self::delete($table, [$field => $row[$field]], $options, $callstack);
1125 // Since we had split the delete command we don't need the original command anymore
1126 unset($commands[$key]);
1130 // Now we finalize the process
1131 $do_transaction = !self::$in_transaction;
1133 if ($do_transaction) {
1134 self::transaction();
1140 foreach ($commands AS $command) {
1141 $conditions = $command['conditions'];
1143 $first_key = key($conditions);
1145 $condition_string = self::buildCondition($conditions);
1147 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1148 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1149 Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
1151 if (!self::e($sql, $conditions)) {
1152 if ($do_transaction) {
1158 $key_table = $command['table'];
1159 $key_condition = array_keys($command['conditions'])[0];
1160 $value = array_values($command['conditions'])[0];
1162 // Split the SQL queries in chunks of 100 values
1163 // We do the $i stuff here to make the code better readable
1164 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1165 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1169 $compacted[$key_table][$key_condition][$i][$value] = $value;
1170 $counter[$key_table][$key_condition] = $i;
1173 foreach ($compacted AS $table => $values) {
1174 foreach ($values AS $field => $field_value_list) {
1175 foreach ($field_value_list AS $field_values) {
1176 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1177 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1179 Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
1181 if (!self::e($sql, $field_values)) {
1182 if ($do_transaction) {
1190 if ($do_transaction) {
1197 * @brief Updates rows
1199 * Updates rows in the database. When $old_fields is set to an array,
1200 * the system will only do an update if the fields in that array changed.
1203 * Only the values in $old_fields are compared.
1204 * This is an intentional behaviour.
1207 * We include the timestamp field in $fields but not in $old_fields.
1208 * Then the row will only get the new timestamp when the other fields had changed.
1210 * When $old_fields is set to a boolean value the system will do this compare itself.
1211 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1214 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1215 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1217 * @param string $table Table name
1218 * @param array $fields contains the fields that are updated
1219 * @param array $condition condition array with the key values
1220 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1222 * @return boolean was the update successfull?
1223 * @throws \Exception
1225 public static function update($table, $fields, $condition, $old_fields = []) {
1227 if (empty($table) || empty($fields) || empty($condition)) {
1228 Logger::log('Table, fields and condition have to be set');
1232 $table = self::escape($table);
1234 $condition_string = self::buildCondition($condition);
1236 if (is_bool($old_fields)) {
1237 $do_insert = $old_fields;
1239 $old_fields = self::selectFirst($table, [], $condition);
1241 if (is_bool($old_fields)) {
1243 $values = array_merge($condition, $fields);
1244 return self::insert($table, $values, $do_insert);
1250 $do_update = (count($old_fields) == 0);
1252 foreach ($old_fields AS $fieldname => $content) {
1253 if (isset($fields[$fieldname])) {
1254 if (($fields[$fieldname] == $content) && !is_null($content)) {
1255 unset($fields[$fieldname]);
1262 if (!$do_update || (count($fields) == 0)) {
1266 $sql = "UPDATE `".$table."` SET `".
1267 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1269 $params1 = array_values($fields);
1270 $params2 = array_values($condition);
1271 $params = array_merge_recursive($params1, $params2);
1273 return self::e($sql, $params);
1277 * Retrieve a single record from a table and returns it in an associative array
1279 * @brief Retrieve a single record from a table
1280 * @param string $table
1281 * @param array $fields
1282 * @param array $condition
1283 * @param array $params
1284 * @return bool|array
1285 * @throws \Exception
1288 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1290 $params['limit'] = 1;
1291 $result = self::select($table, $fields, $condition, $params);
1293 if (is_bool($result)) {
1296 $row = self::fetch($result);
1297 self::close($result);
1303 * @brief Select rows from a table
1305 * @param string $table Table name
1306 * @param array $fields Array of selected fields, empty for all
1307 * @param array $condition Array of fields for condition
1308 * @param array $params Array of several parameters
1310 * @return boolean|object
1314 * $fields = array("id", "uri", "uid", "network");
1316 * $condition = array("uid" => 1, "network" => 'dspr');
1318 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1320 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1322 * $data = DBA::select($table, $fields, $condition, $params);
1323 * @throws \Exception
1325 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1331 $table = self::escape($table);
1333 if (count($fields) > 0) {
1334 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1336 $select_fields = "*";
1339 $condition_string = self::buildCondition($condition);
1341 $param_string = self::buildParameter($params);
1343 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1345 $result = self::p($sql, $condition);
1351 * @brief Counts the rows from a table satisfying the provided condition
1353 * @param string $table Table name
1354 * @param array $condition array of fields for condition
1361 * $condition = ["uid" => 1, "network" => 'dspr'];
1363 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1365 * $count = DBA::count($table, $condition);
1366 * @throws \Exception
1368 public static function count($table, array $condition = [])
1374 $condition_string = self::buildCondition($condition);
1376 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1378 $row = self::fetchFirst($sql, $condition);
1380 return $row['count'];
1384 * @brief Returns the SQL condition string built from the provided condition array
1386 * This function operates with two modes.
1387 * - Supplied with a filed/value associative array, it builds simple strict
1388 * equality conditions linked by AND.
1389 * - Supplied with a flat list, the first element is the condition string and
1390 * the following arguments are the values to be interpolated
1392 * $condition = ["uid" => 1, "network" => 'dspr'];
1394 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1396 * In either case, the provided array is left with the parameters only
1398 * @param array $condition
1401 public static function buildCondition(array &$condition = [])
1403 $condition_string = '';
1404 if (count($condition) > 0) {
1406 $first_key = key($condition);
1407 if (is_int($first_key)) {
1408 $condition_string = " WHERE (" . array_shift($condition) . ")";
1411 $condition_string = "";
1412 foreach ($condition as $field => $value) {
1413 if ($condition_string != "") {
1414 $condition_string .= " AND ";
1416 if (is_array($value)) {
1417 /* Workaround for MySQL Bug #64791.
1418 * Never mix data types inside any IN() condition.
1419 * In case of mixed types, cast all as string.
1420 * Logic needs to be consistent with DBA::p() data types.
1424 foreach ($value as $single_value) {
1425 if (is_int($single_value)) {
1432 if ($is_int && $is_alpha) {
1433 foreach ($value as &$ref) {
1435 $ref = (string)$ref;
1438 unset($ref); //Prevent accidental re-use.
1441 $new_values = array_merge($new_values, array_values($value));
1442 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1443 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1445 $new_values[$field] = $value;
1446 $condition_string .= "`" . $field . "` = ?";
1449 $condition_string = " WHERE (" . $condition_string . ")";
1450 $condition = $new_values;
1454 return $condition_string;
1458 * @brief Returns the SQL parameter string built from the provided parameter array
1460 * @param array $params
1463 public static function buildParameter(array $params = [])
1466 if (isset($params['order'])) {
1467 $order_string = " ORDER BY ";
1468 foreach ($params['order'] AS $fields => $order) {
1469 if (!is_int($fields)) {
1470 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1472 $order_string .= "`" . $order . "`, ";
1475 $order_string = substr($order_string, 0, -2);
1479 if (isset($params['limit']) && is_int($params['limit'])) {
1480 $limit_string = " LIMIT " . intval($params['limit']);
1483 if (isset($params['limit']) && is_array($params['limit'])) {
1484 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1487 return $order_string.$limit_string;
1491 * @brief Fills an array with data from a query
1493 * @param object $stmt statement object
1494 * @param bool $do_close
1495 * @return array Data array
1497 public static function toArray($stmt, $do_close = true) {
1498 if (is_bool($stmt)) {
1503 while ($row = self::fetch($stmt)) {
1513 * @brief Returns the error number of the last query
1515 * @return string Error number (0 if no error)
1517 public static function errorNo() {
1518 return self::$errorno;
1522 * @brief Returns the error message of the last query
1524 * @return string Error message ('' if no error)
1526 public static function errorMessage() {
1527 return self::$error;
1531 * @brief Closes the current statement
1533 * @param object $stmt statement object
1534 * @return boolean was the close successful?
1536 public static function close($stmt) {
1539 $stamp1 = microtime(true);
1541 if (!is_object($stmt)) {
1545 switch (self::$driver) {
1547 $ret = $stmt->closeCursor();
1550 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1551 // We should be careful not to assume the object type of $stmt
1552 // because DBA::p() has been able to return both types.
1553 if ($stmt instanceof mysqli_stmt) {
1554 $stmt->free_result();
1555 $ret = $stmt->close();
1556 } elseif ($stmt instanceof mysqli_result) {
1565 $a->saveTimestamp($stamp1, 'database');
1571 * @brief Return a list of database processes
1574 * 'list' => List of processes, separated in their different states
1575 * 'amount' => Number of concurrent database processes
1576 * @throws \Exception
1578 public static function processlist()
1580 $ret = self::p("SHOW PROCESSLIST");
1581 $data = self::toArray($ret);
1585 foreach ($data as $process) {
1586 $state = trim($process["State"]);
1588 // Filter out all non blocking processes
1589 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1596 foreach ($states as $state => $usage) {
1597 if ($statelist != "") {
1600 $statelist .= $state.": ".$usage;
1602 return(["list" => $statelist, "amount" => $processes]);
1606 * Checks if $array is a filled array with at least one entry.
1608 * @param mixed $array A filled array with at least one entry
1610 * @return boolean Whether $array is a filled array or an object with rows
1612 public static function isResult($array)
1614 // It could be a return value from an update statement
1615 if (is_bool($array)) {
1619 if (is_object($array)) {
1620 return self::numRows($array) > 0;
1623 return (is_array($array) && (count($array) > 0));
1627 * @brief Callback function for "esc_array"
1629 * @param mixed $value Array value
1630 * @param string $key Array key
1631 * @param boolean $add_quotation add quotation marks for string values
1634 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1636 if (!$add_quotation) {
1637 if (is_bool($value)) {
1638 $value = ($value ? '1' : '0');
1640 $value = self::escape($value);
1645 if (is_bool($value)) {
1646 $value = ($value ? 'true' : 'false');
1647 } elseif (is_float($value) || is_integer($value)) {
1648 $value = (string) $value;
1650 $value = "'" . self::escape($value) . "'";
1655 * @brief Escapes a whole array
1657 * @param mixed $arr Array with values to be escaped
1658 * @param boolean $add_quotation add quotation marks for string values
1661 public static function escapeArray(&$arr, $add_quotation = false)
1663 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);