3 namespace Friendica\Database;
5 // Do not use Core\Config in this class at risk of infinite loop.
6 // Please use App->getConfigVariable() instead.
7 //use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Util\DateTimeFormat;
13 * @class MySQL database class
15 * This class is for the low level database stuff that does driver specific things.
19 public static $connected = false;
21 private static $server_info = '';
23 private static $driver;
24 private static $error = false;
25 private static $errorno = 0;
26 private static $affected_rows = 0;
27 private static $in_transaction = false;
28 private static $in_retrial = false;
29 private static $relation = [];
30 private static $db_serveraddr = '';
31 private static $db_user = '';
32 private static $db_pass = '';
33 private static $db_name = '';
34 private static $db_charset = '';
36 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
38 if (!is_null(self::$db) && self::connected()) {
42 // We are storing these values for being able to perform a reconnect
43 self::$db_serveraddr = $serveraddr;
44 self::$db_user = $user;
45 self::$db_pass = $pass;
47 self::$db_charset = $charset;
49 $serveraddr = trim($serveraddr);
51 $serverdata = explode(':', $serveraddr);
52 $server = $serverdata[0];
54 if (count($serverdata) > 1) {
55 $port = trim($serverdata[1]);
58 $server = trim($server);
62 $charset = trim($charset);
64 if (!(strlen($server) && strlen($user))) {
68 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
69 self::$driver = 'pdo';
70 $connect = "mysql:host=".$server.";dbname=".$db;
73 $connect .= ";port=".$port;
77 $connect .= ";charset=".$charset;
81 self::$db = @new PDO($connect, $user, $pass);
82 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
83 self::$connected = true;
84 } catch (PDOException $e) {
88 if (!self::$connected && class_exists('mysqli')) {
89 self::$driver = 'mysqli';
90 self::$db = @new mysqli($server, $user, $pass, $db, $port);
91 if (!mysqli_connect_errno()) {
92 self::$connected = true;
95 self::$db->set_charset($charset);
100 // No suitable SQL driver was found.
101 if (!self::$connected) {
102 self::$driver = null;
106 return self::$connected;
110 * Disconnects the current database connection
112 public static function disconnect()
114 if (is_null(self::$db)) {
118 switch (self::$driver) {
130 * Perform a reconnect of an existing database connection
132 public static function reconnect() {
135 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
140 * Return the database object.
143 public static function get_db()
149 * @brief Returns the MySQL server version string
151 * This function discriminate between the deprecated mysql API and the current
152 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
156 public static function server_info() {
157 if (self::$server_info == '') {
158 switch (self::$driver) {
160 self::$server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
163 self::$server_info = self::$db->server_info;
167 return self::$server_info;
171 * @brief Returns the selected database name
175 public static function database_name() {
176 $ret = self::p("SELECT DATABASE() AS `db`");
177 $data = self::inArray($ret);
178 return $data[0]['db'];
182 * @brief Analyze a database query and log this if some conditions are met.
184 * @param string $query The database query that will be analyzed
186 private static function logIndex($query) {
189 if (!$a->getConfigVariable('system', 'db_log_index')) {
193 // Don't explain an explain statement
194 if (strtolower(substr($query, 0, 7)) == "explain") {
198 // Only do the explain on "select", "update" and "delete"
199 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
203 $r = self::p("EXPLAIN ".$query);
204 if (!DBM::is_result($r)) {
208 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
209 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
211 while ($row = self::fetch($r)) {
212 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
213 $log = (in_array($row['key'], $watchlist) &&
214 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
219 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
223 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
228 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
229 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
230 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
231 basename($backtrace[1]["file"])."\t".
232 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
233 substr($query, 0, 2000)."\n", FILE_APPEND);
238 public static function escape($str) {
239 switch (self::$driver) {
241 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
243 return @self::$db->real_escape_string($str);
247 public static function connected() {
250 if (is_null(self::$db)) {
254 switch (self::$driver) {
256 $r = self::p("SELECT 1");
257 if (DBM::is_result($r)) {
258 $row = self::inArray($r);
259 $connected = ($row[0]['1'] == '1');
263 $connected = self::$db->ping();
270 * @brief Replaces ANY_VALUE() function by MIN() function,
271 * if the database server does not support ANY_VALUE().
273 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
274 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
275 * A standard fall-back is to use MIN().
277 * @param string $sql An SQL string without the values
278 * @return string The input SQL string modified if necessary.
280 public static function any_value_fallback($sql) {
281 $server_info = self::server_info();
282 if (version_compare($server_info, '5.7.5', '<') ||
283 (stripos($server_info, 'MariaDB') !== false)) {
284 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
290 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
292 * This is safe when we bind the parameters later.
293 * The parameter values aren't part of the SQL.
295 * @param string $sql An SQL string without the values
296 * @return string The input SQL string modified if necessary.
298 public static function clean_query($sql) {
299 $search = ["\t", "\n", "\r", " "];
300 $replace = [' ', ' ', ' ', ' '];
303 $sql = str_replace($search, $replace, $sql);
304 } while ($oldsql != $sql);
311 * @brief Replaces the ? placeholders with the parameters in the $args array
313 * @param string $sql SQL query
314 * @param array $args The parameters that are to replace the ? placeholders
315 * @return string The replaced SQL query
317 private static function replaceParameters($sql, $args) {
319 foreach ($args AS $param => $value) {
320 if (is_int($args[$param]) || is_float($args[$param])) {
321 $replace = intval($args[$param]);
323 $replace = "'".self::escape($args[$param])."'";
326 $pos = strpos($sql, '?', $offset);
327 if ($pos !== false) {
328 $sql = substr_replace($sql, $replace, $pos, 1);
330 $offset = $pos + strlen($replace);
336 * @brief Convert parameter array to an universal form
337 * @param array $args Parameter array
338 * @return array universalized parameter array
340 private static function getParam($args) {
343 // When the second function parameter is an array then use this as the parameter array
344 if ((count($args) > 0) && (is_array($args[1]))) {
352 * @brief Executes a prepared statement that returns data
353 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
355 * Please only use it with complicated queries.
356 * For all regular queries please use dba::select or dba::exists
358 * @param string $sql SQL statement
359 * @return bool|object statement object or result object
361 public static function p($sql) {
364 $stamp1 = microtime(true);
366 $params = self::getParam(func_get_args());
368 // Renumber the array keys to be sure that they fit
371 foreach ($params AS $param) {
372 // Avoid problems with some MySQL servers and boolean values. See issue #3645
373 if (is_bool($param)) {
374 $param = (int)$param;
376 $args[++$i] = $param;
379 if (!self::$connected) {
383 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
384 // Question: Should we continue or stop the query here?
385 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
388 $sql = self::clean_query($sql);
389 $sql = self::any_value_fallback($sql);
393 if ($a->getConfigValue('system', 'db_callstack')) {
394 $sql = "/*".System::callstack()." */ ".$sql;
399 self::$affected_rows = 0;
401 // We have to make some things different if this function is called from "e"
402 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
404 if (isset($trace[1])) {
405 $called_from = $trace[1];
407 // We use just something that is defined to avoid warnings
408 $called_from = $trace[0];
410 // We are having an own error logging in the function "e"
411 $called_from_e = ($called_from['function'] == 'e');
413 switch (self::$driver) {
415 // If there are no arguments we use "query"
416 if (count($args) == 0) {
417 if (!$retval = self::$db->query($sql)) {
418 $errorInfo = self::$db->errorInfo();
419 self::$error = $errorInfo[2];
420 self::$errorno = $errorInfo[1];
424 self::$affected_rows = $retval->rowCount();
428 if (!$stmt = self::$db->prepare($sql)) {
429 $errorInfo = self::$db->errorInfo();
430 self::$error = $errorInfo[2];
431 self::$errorno = $errorInfo[1];
436 foreach ($args AS $param => $value) {
437 if (is_int($args[$param])) {
438 $data_type = PDO::PARAM_INT;
440 $data_type = PDO::PARAM_STR;
442 $stmt->bindParam($param, $args[$param], $data_type);
445 if (!$stmt->execute()) {
446 $errorInfo = $stmt->errorInfo();
447 self::$error = $errorInfo[2];
448 self::$errorno = $errorInfo[1];
452 self::$affected_rows = $retval->rowCount();
456 // There are SQL statements that cannot be executed with a prepared statement
457 $parts = explode(' ', $orig_sql);
458 $command = strtolower($parts[0]);
459 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
461 // The fallback routine is called as well when there are no arguments
462 if (!$can_be_prepared || (count($args) == 0)) {
463 $retval = self::$db->query(self::replaceParameters($sql, $args));
464 if (self::$db->errno) {
465 self::$error = self::$db->error;
466 self::$errorno = self::$db->errno;
469 if (isset($retval->num_rows)) {
470 self::$affected_rows = $retval->num_rows;
472 self::$affected_rows = self::$db->affected_rows;
478 $stmt = self::$db->stmt_init();
480 if (!$stmt->prepare($sql)) {
481 self::$error = $stmt->error;
482 self::$errorno = $stmt->errno;
489 foreach ($args AS $param => $value) {
490 if (is_int($args[$param])) {
492 } elseif (is_float($args[$param])) {
494 } elseif (is_string($args[$param])) {
499 $values[] = &$args[$param];
502 if (count($values) > 0) {
503 array_unshift($values, $param_types);
504 call_user_func_array([$stmt, 'bind_param'], $values);
507 if (!$stmt->execute()) {
508 self::$error = self::$db->error;
509 self::$errorno = self::$db->errno;
512 $stmt->store_result();
514 self::$affected_rows = $retval->affected_rows;
519 // We are having an own error logging in the function "e"
520 if ((self::$errorno != 0) && !$called_from_e) {
521 // We have to preserve the error code, somewhere in the logging it get lost
522 $error = self::$error;
523 $errorno = self::$errorno;
525 logger('DB Error '.self::$errorno.': '.self::$error."\n".
526 System::callstack(8)."\n".self::replaceParameters($sql, $args));
528 // On a lost connection we try to reconnect - but only once.
529 if ($errorno == 2006) {
530 if (self::$in_retrial || !self::reconnect()) {
531 // It doesn't make sense to continue when the database connection was lost
532 if (self::$in_retrial) {
533 logger('Giving up retrial because of database error '.$errorno.': '.$error);
535 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
540 logger('Reconnected after database error '.$errorno.': '.$error);
541 self::$in_retrial = true;
542 $ret = self::p($sql, $args);
543 self::$in_retrial = false;
548 self::$error = $error;
549 self::$errorno = $errorno;
552 $a->save_timestamp($stamp1, 'database');
554 if ($a->getConfigValue('system', 'db_log')) {
555 $stamp2 = microtime(true);
556 $duration = (float)($stamp2 - $stamp1);
558 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
559 $duration = round($duration, 3);
560 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
562 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
563 basename($backtrace[1]["file"])."\t".
564 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
565 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
572 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
574 * Please use dba::delete, dba::insert, dba::update, ... instead
576 * @param string $sql SQL statement
577 * @return boolean Was the query successfull? False is returned only if an error occurred
579 public static function e($sql) {
582 $stamp = microtime(true);
584 $params = self::getParam(func_get_args());
586 // In a case of a deadlock we are repeating the query 20 times
590 $stmt = self::p($sql, $params);
592 if (is_bool($stmt)) {
594 } elseif (is_object($stmt)) {
602 } while ((self::$errorno == 1213) && (--$timeout > 0));
604 if (self::$errorno != 0) {
605 // We have to preserve the error code, somewhere in the logging it get lost
606 $error = self::$error;
607 $errorno = self::$errorno;
609 logger('DB Error '.self::$errorno.': '.self::$error."\n".
610 System::callstack(8)."\n".self::replaceParameters($sql, $params));
612 // On a lost connection we simply quit.
613 // A reconnect like in self::p could be dangerous with modifications
614 if ($errorno == 2006) {
615 logger('Giving up because of database error '.$errorno.': '.$error);
619 self::$error = $error;
620 self::$errorno = $errorno;
623 $a->save_timestamp($stamp, "database_write");
629 * @brief Check if data exists
631 * @param string $table Table name
632 * @param array $condition array of fields for condition
634 * @return boolean Are there rows for that condition?
636 public static function exists($table, $condition) {
644 $first_key = key($condition);
645 if (!is_int($first_key)) {
646 $fields = [$first_key];
649 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
651 if (is_bool($stmt)) {
654 $retval = (self::num_rows($stmt) > 0);
663 * Fetches the first row
665 * Please use dba::selectFirst or dba::exists whenever this is possible.
667 * @brief Fetches the first row
668 * @param string $sql SQL statement
669 * @return array first row of query
671 public static function fetch_first($sql) {
672 $params = self::getParam(func_get_args());
674 $stmt = self::p($sql, $params);
676 if (is_bool($stmt)) {
679 $retval = self::fetch($stmt);
688 * @brief Returns the number of affected rows of the last statement
690 * @return int Number of rows
692 public static function affected_rows() {
693 return self::$affected_rows;
697 * @brief Returns the number of columns of a statement
699 * @param object Statement object
700 * @return int Number of columns
702 public static function columnCount($stmt) {
703 if (!is_object($stmt)) {
706 switch (self::$driver) {
708 return $stmt->columnCount();
710 return $stmt->field_count;
715 * @brief Returns the number of rows of a statement
717 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
718 * @return int Number of rows
720 public static function num_rows($stmt) {
721 if (!is_object($stmt)) {
724 switch (self::$driver) {
726 return $stmt->rowCount();
728 return $stmt->num_rows;
734 * @brief Fetch a single row
736 * @param mixed $stmt statement object
737 * @return array current row
739 public static function fetch($stmt) {
742 $stamp1 = microtime(true);
746 if (!is_object($stmt)) {
750 switch (self::$driver) {
752 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
755 if (get_class($stmt) == 'mysqli_result') {
756 $columns = $stmt->fetch_assoc();
760 // This code works, but is slow
762 // Bind the result to a result array
766 for ($x = 0; $x < $stmt->field_count; $x++) {
767 $cols[] = &$cols_num[$x];
770 call_user_func_array([$stmt, 'bind_result'], $cols);
772 if (!$stmt->fetch()) {
777 // We need to get the field names for the array keys
778 // It seems that there is no better way to do this.
779 $result = $stmt->result_metadata();
780 $fields = $result->fetch_fields();
782 foreach ($cols_num AS $param => $col) {
783 $columns[$fields[$param]->name] = $col;
787 $a->save_timestamp($stamp1, 'database');
793 * @brief Insert a row into a table
795 * @param string $table Table name
796 * @param array $param parameter array
797 * @param bool $on_duplicate_update Do an update on a duplicate entry
799 * @return boolean was the insert successfull?
801 public static function insert($table, $param, $on_duplicate_update = false) {
803 if (empty($table) || empty($param)) {
804 logger('Table and fields have to be set');
808 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
809 substr(str_repeat("?, ", count($param)), 0, -2).")";
811 if ($on_duplicate_update) {
812 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
814 $values = array_values($param);
815 $param = array_merge_recursive($values, $values);
818 return self::e($sql, $param);
822 * @brief Fetch the id of the last insert command
824 * @return integer Last inserted id
826 public static function lastInsertId() {
827 switch (self::$driver) {
829 $id = self::$db->lastInsertId();
832 $id = self::$db->insert_id;
839 * @brief Locks a table for exclusive write access
841 * This function can be extended in the future to accept a table array as well.
843 * @param string $table Table name
845 * @return boolean was the lock successful?
847 public static function lock($table) {
848 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
849 if (self::$driver == 'pdo') {
850 self::e("SET autocommit=0");
851 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
853 self::$db->autocommit(false);
856 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
858 if (self::$driver == 'pdo') {
859 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
863 if (self::$driver == 'pdo') {
864 self::e("SET autocommit=1");
866 self::$db->autocommit(true);
869 self::$in_transaction = true;
875 * @brief Unlocks all locked tables
877 * @return boolean was the unlock successful?
879 public static function unlock() {
880 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
881 self::performCommit();
883 if (self::$driver == 'pdo') {
884 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
887 $success = self::e("UNLOCK TABLES");
889 if (self::$driver == 'pdo') {
890 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
891 self::e("SET autocommit=1");
893 self::$db->autocommit(true);
896 self::$in_transaction = false;
901 * @brief Starts a transaction
903 * @return boolean Was the command executed successfully?
905 public static function transaction() {
906 if (!self::performCommit()) {
910 switch (self::$driver) {
912 if (self::$db->inTransaction()) {
915 if (!self::$db->beginTransaction()) {
920 if (!self::$db->begin_transaction()) {
926 self::$in_transaction = true;
930 private static function performCommit()
932 switch (self::$driver) {
934 if (!self::$db->inTransaction()) {
937 return self::$db->commit();
939 return self::$db->commit();
945 * @brief Does a commit
947 * @return boolean Was the command executed successfully?
949 public static function commit() {
950 if (!self::performCommit()) {
953 self::$in_transaction = false;
958 * @brief Does a rollback
960 * @return boolean Was the command executed successfully?
962 public static function rollback() {
965 switch (self::$driver) {
967 if (!self::$db->inTransaction()) {
971 $ret = self::$db->rollBack();
974 $ret = self::$db->rollback();
977 self::$in_transaction = false;
982 * @brief Build the array with the table relations
984 * The array is build from the database definitions in DBStructure.php
986 * This process must only be started once, since the value is cached.
988 private static function buildRelationData() {
989 $definition = DBStructure::definition();
991 foreach ($definition AS $table => $structure) {
992 foreach ($structure['fields'] AS $field => $field_struct) {
993 if (isset($field_struct['relation'])) {
994 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
995 self::$relation[$rel_table][$rel_field][$table][] = $field;
1003 * @brief Delete a row from a table
1005 * @param string $table Table name
1006 * @param array $conditions Field condition(s)
1007 * @param array $options
1008 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1009 * relations (default: true)
1010 * @param boolean $in_process Internal use: Only do a commit after the last delete
1011 * @param array $callstack Internal use: prevent endless loops
1013 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1015 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1017 if (empty($table) || empty($conditions)) {
1018 logger('Table and conditions have to be set');
1024 // Create a key for the loop prevention
1025 $key = $table . ':' . json_encode($conditions);
1027 // We quit when this key already exists in the callstack.
1028 if (isset($callstack[$key])) {
1032 $callstack[$key] = true;
1034 $table = self::escape($table);
1036 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1038 $cascade = defaults($options, 'cascade', true);
1040 // To speed up the whole process we cache the table relations
1041 if ($cascade && count(self::$relation) == 0) {
1042 self::buildRelationData();
1045 // Is there a relation entry for the table?
1046 if ($cascade && isset(self::$relation[$table])) {
1047 // We only allow a simple "one field" relation.
1048 $field = array_keys(self::$relation[$table])[0];
1049 $rel_def = array_values(self::$relation[$table])[0];
1051 // Create a key for preventing double queries
1052 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1054 // When the search field is the relation field, we don't need to fetch the rows
1055 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1056 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1057 foreach ($rel_def AS $rel_table => $rel_fields) {
1058 foreach ($rel_fields AS $rel_field) {
1059 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1060 $commands = array_merge($commands, $retval);
1063 // We quit when this key already exists in the callstack.
1064 } elseif (!isset($callstack[$qkey])) {
1066 $callstack[$qkey] = true;
1068 // Fetch all rows that are to be deleted
1069 $data = self::select($table, [$field], $conditions);
1071 while ($row = self::fetch($data)) {
1072 // Now we accumulate the delete commands
1073 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1074 $commands = array_merge($commands, $retval);
1079 // Since we had split the delete command we don't need the original command anymore
1080 unset($commands[$key]);
1085 // Now we finalize the process
1086 $do_transaction = !self::$in_transaction;
1088 if ($do_transaction) {
1089 self::transaction();
1095 foreach ($commands AS $command) {
1096 $conditions = $command['conditions'];
1098 $first_key = key($conditions);
1100 $condition_string = self::buildCondition($conditions);
1102 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1103 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1104 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1106 if (!self::e($sql, $conditions)) {
1107 if ($do_transaction) {
1113 $key_table = $command['table'];
1114 $key_condition = array_keys($command['conditions'])[0];
1115 $value = array_values($command['conditions'])[0];
1117 // Split the SQL queries in chunks of 100 values
1118 // We do the $i stuff here to make the code better readable
1119 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1120 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1124 $compacted[$key_table][$key_condition][$i][$value] = $value;
1125 $counter[$key_table][$key_condition] = $i;
1128 foreach ($compacted AS $table => $values) {
1129 foreach ($values AS $field => $field_value_list) {
1130 foreach ($field_value_list AS $field_values) {
1131 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1132 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1134 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1136 if (!self::e($sql, $field_values)) {
1137 if ($do_transaction) {
1145 if ($do_transaction) {
1155 * @brief Updates rows
1157 * Updates rows in the database. When $old_fields is set to an array,
1158 * the system will only do an update if the fields in that array changed.
1161 * Only the values in $old_fields are compared.
1162 * This is an intentional behaviour.
1165 * We include the timestamp field in $fields but not in $old_fields.
1166 * Then the row will only get the new timestamp when the other fields had changed.
1168 * When $old_fields is set to a boolean value the system will do this compare itself.
1169 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1172 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1173 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1175 * @param string $table Table name
1176 * @param array $fields contains the fields that are updated
1177 * @param array $condition condition array with the key values
1178 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1180 * @return boolean was the update successfull?
1182 public static function update($table, $fields, $condition, $old_fields = []) {
1184 if (empty($table) || empty($fields) || empty($condition)) {
1185 logger('Table, fields and condition have to be set');
1189 $table = self::escape($table);
1191 $condition_string = self::buildCondition($condition);
1193 if (is_bool($old_fields)) {
1194 $do_insert = $old_fields;
1196 $old_fields = self::selectFirst($table, [], $condition);
1198 if (is_bool($old_fields)) {
1200 $values = array_merge($condition, $fields);
1201 return self::insert($table, $values, $do_insert);
1207 $do_update = (count($old_fields) == 0);
1209 foreach ($old_fields AS $fieldname => $content) {
1210 if (isset($fields[$fieldname])) {
1211 if ($fields[$fieldname] == $content) {
1212 unset($fields[$fieldname]);
1219 if (!$do_update || (count($fields) == 0)) {
1223 $sql = "UPDATE `".$table."` SET `".
1224 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1226 $params1 = array_values($fields);
1227 $params2 = array_values($condition);
1228 $params = array_merge_recursive($params1, $params2);
1230 return self::e($sql, $params);
1234 * Retrieve a single record from a table and returns it in an associative array
1236 * @brief Retrieve a single record from a table
1237 * @param string $table
1238 * @param array $fields
1239 * @param array $condition
1240 * @param array $params
1241 * @return bool|array
1244 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1246 $params['limit'] = 1;
1247 $result = self::select($table, $fields, $condition, $params);
1249 if (is_bool($result)) {
1252 $row = self::fetch($result);
1253 self::close($result);
1259 * @brief Select rows from a table
1261 * @param string $table Table name
1262 * @param array $fields Array of selected fields, empty for all
1263 * @param array $condition Array of fields for condition
1264 * @param array $params Array of several parameters
1266 * @return boolean|object
1270 * $fields = array("id", "uri", "uid", "network");
1272 * $condition = array("uid" => 1, "network" => 'dspr');
1274 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1276 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1278 * $data = dba::select($table, $fields, $condition, $params);
1280 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1286 $table = self::escape($table);
1288 if (count($fields) > 0) {
1289 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1291 $select_fields = "*";
1294 $condition_string = self::buildCondition($condition);
1296 $param_string = self::buildParameter($params);
1298 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1300 $result = self::p($sql, $condition);
1306 * @brief Counts the rows from a table satisfying the provided condition
1308 * @param string $table Table name
1309 * @param array $condition array of fields for condition
1316 * $condition = ["uid" => 1, "network" => 'dspr'];
1318 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1320 * $count = dba::count($table, $condition);
1322 public static function count($table, array $condition = [])
1328 $condition_string = self::buildCondition($condition);
1330 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1332 $row = self::fetch_first($sql, $condition);
1334 return $row['count'];
1338 * @brief Returns the SQL condition string built from the provided condition array
1340 * This function operates with two modes.
1341 * - Supplied with a filed/value associative array, it builds simple strict
1342 * equality conditions linked by AND.
1343 * - Supplied with a flat list, the first element is the condition string and
1344 * the following arguments are the values to be interpolated
1346 * $condition = ["uid" => 1, "network" => 'dspr'];
1348 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1350 * In either case, the provided array is left with the parameters only
1352 * @param array $condition
1355 public static function buildCondition(array &$condition = [])
1357 $condition_string = '';
1358 if (count($condition) > 0) {
1360 $first_key = key($condition);
1361 if (is_int($first_key)) {
1362 $condition_string = " WHERE (" . array_shift($condition) . ")";
1365 $condition_string = "";
1366 foreach ($condition as $field => $value) {
1367 if ($condition_string != "") {
1368 $condition_string .= " AND ";
1370 if (is_array($value)) {
1371 /* Workaround for MySQL Bug #64791.
1372 * Never mix data types inside any IN() condition.
1373 * In case of mixed types, cast all as string.
1374 * Logic needs to be consistent with dba::p() data types.
1378 foreach ($value as $single_value) {
1379 if (is_int($single_value)) {
1386 if ($is_int && $is_alpha) {
1387 foreach ($value as &$ref) {
1389 $ref = (string)$ref;
1392 unset($ref); //Prevent accidental re-use.
1395 $new_values = array_merge($new_values, array_values($value));
1396 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1397 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1399 $new_values[$field] = $value;
1400 $condition_string .= "`" . $field . "` = ?";
1403 $condition_string = " WHERE (" . $condition_string . ")";
1404 $condition = $new_values;
1408 return $condition_string;
1412 * @brief Returns the SQL parameter string built from the provided parameter array
1414 * @param array $params
1417 public static function buildParameter(array $params = [])
1420 if (isset($params['order'])) {
1421 $order_string = " ORDER BY ";
1422 foreach ($params['order'] AS $fields => $order) {
1423 if (!is_int($fields)) {
1424 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1426 $order_string .= "`" . $order . "`, ";
1429 $order_string = substr($order_string, 0, -2);
1433 if (isset($params['limit']) && is_int($params['limit'])) {
1434 $limit_string = " LIMIT " . $params['limit'];
1437 if (isset($params['limit']) && is_array($params['limit'])) {
1438 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1441 return $order_string.$limit_string;
1445 * @brief Fills an array with data from a query
1447 * @param object $stmt statement object
1448 * @return array Data array
1450 public static function inArray($stmt, $do_close = true) {
1451 if (is_bool($stmt)) {
1456 while ($row = self::fetch($stmt)) {
1466 * @brief Returns the error number of the last query
1468 * @return string Error number (0 if no error)
1470 public static function errorNo() {
1471 return self::$errorno;
1475 * @brief Returns the error message of the last query
1477 * @return string Error message ('' if no error)
1479 public static function errorMessage() {
1480 return self::$error;
1484 * @brief Closes the current statement
1486 * @param object $stmt statement object
1487 * @return boolean was the close successful?
1489 public static function close($stmt) {
1492 $stamp1 = microtime(true);
1494 if (!is_object($stmt)) {
1498 switch (self::$driver) {
1500 $ret = $stmt->closeCursor();
1503 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1504 // We should be careful not to assume the object type of $stmt
1505 // because dba::p() has been able to return both types.
1506 if ($stmt instanceof mysqli_stmt) {
1507 $stmt->free_result();
1508 $ret = $stmt->close();
1509 } elseif ($stmt instanceof mysqli_result) {
1518 $a->save_timestamp($stamp1, 'database');