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;
17 * @class MySQL database class
19 * This class is for the low level database stuff that does driver specific things.
23 public static $connected = false;
25 private static $server_info = '';
27 private static $driver;
28 private static $error = false;
29 private static $errorno = 0;
30 private static $affected_rows = 0;
31 private static $in_transaction = false;
32 private static $in_retrial = false;
33 private static $relation = [];
34 private static $db_serveraddr = '';
35 private static $db_user = '';
36 private static $db_pass = '';
37 private static $db_name = '';
38 private static $db_charset = '';
40 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
42 if (!is_null(self::$db) && self::connected()) {
46 // We are storing these values for being able to perform a reconnect
47 self::$db_serveraddr = $serveraddr;
48 self::$db_user = $user;
49 self::$db_pass = $pass;
51 self::$db_charset = $charset;
53 $serveraddr = trim($serveraddr);
55 $serverdata = explode(':', $serveraddr);
56 $server = $serverdata[0];
58 if (count($serverdata) > 1) {
59 $port = trim($serverdata[1]);
62 $server = trim($server);
66 $charset = trim($charset);
68 if (!(strlen($server) && strlen($user))) {
72 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
73 self::$driver = 'pdo';
74 $connect = "mysql:host=".$server.";dbname=".$db;
77 $connect .= ";port=".$port;
81 $connect .= ";charset=".$charset;
85 self::$db = @new PDO($connect, $user, $pass);
86 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
87 self::$connected = true;
88 } catch (PDOException $e) {
92 if (!self::$connected && class_exists('mysqli')) {
93 self::$driver = 'mysqli';
94 self::$db = @new mysqli($server, $user, $pass, $db, $port);
95 if (!mysqli_connect_errno()) {
96 self::$connected = true;
99 self::$db->set_charset($charset);
104 // No suitable SQL driver was found.
105 if (!self::$connected) {
106 self::$driver = null;
110 return self::$connected;
114 * Disconnects the current database connection
116 public static function disconnect()
118 if (is_null(self::$db)) {
122 switch (self::$driver) {
134 * Perform a reconnect of an existing database connection
136 public static function reconnect() {
139 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
144 * Return the database object.
147 public static function get_db()
153 * @brief Returns the MySQL server version string
155 * This function discriminate between the deprecated mysql API and the current
156 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
160 public static function server_info() {
161 if (self::$server_info == '') {
162 switch (self::$driver) {
164 self::$server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
167 self::$server_info = self::$db->server_info;
171 return self::$server_info;
175 * @brief Returns the selected database name
179 public static function database_name() {
180 $ret = self::p("SELECT DATABASE() AS `db`");
181 $data = self::inArray($ret);
182 return $data[0]['db'];
186 * @brief Analyze a database query and log this if some conditions are met.
188 * @param string $query The database query that will be analyzed
190 private static function logIndex($query) {
193 if (!$a->getConfigVariable('system', 'db_log_index')) {
197 // Don't explain an explain statement
198 if (strtolower(substr($query, 0, 7)) == "explain") {
202 // Only do the explain on "select", "update" and "delete"
203 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
207 $r = self::p("EXPLAIN ".$query);
208 if (!DBM::is_result($r)) {
212 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
213 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
215 while ($row = self::fetch($r)) {
216 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
217 $log = (in_array($row['key'], $watchlist) &&
218 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
223 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
227 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
232 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
233 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
234 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
235 basename($backtrace[1]["file"])."\t".
236 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
237 substr($query, 0, 2000)."\n", FILE_APPEND);
242 public static function escape($str) {
243 switch (self::$driver) {
245 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
247 return @self::$db->real_escape_string($str);
251 public static function connected() {
254 if (is_null(self::$db)) {
258 switch (self::$driver) {
260 $r = self::p("SELECT 1");
261 if (DBM::is_result($r)) {
262 $row = self::inArray($r);
263 $connected = ($row[0]['1'] == '1');
267 $connected = self::$db->ping();
274 * @brief Replaces ANY_VALUE() function by MIN() function,
275 * if the database server does not support ANY_VALUE().
277 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
278 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
279 * A standard fall-back is to use MIN().
281 * @param string $sql An SQL string without the values
282 * @return string The input SQL string modified if necessary.
284 public static function any_value_fallback($sql) {
285 $server_info = self::server_info();
286 if (version_compare($server_info, '5.7.5', '<') ||
287 (stripos($server_info, 'MariaDB') !== false)) {
288 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
294 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
296 * This is safe when we bind the parameters later.
297 * The parameter values aren't part of the SQL.
299 * @param string $sql An SQL string without the values
300 * @return string The input SQL string modified if necessary.
302 public static function clean_query($sql) {
303 $search = ["\t", "\n", "\r", " "];
304 $replace = [' ', ' ', ' ', ' '];
307 $sql = str_replace($search, $replace, $sql);
308 } while ($oldsql != $sql);
315 * @brief Replaces the ? placeholders with the parameters in the $args array
317 * @param string $sql SQL query
318 * @param array $args The parameters that are to replace the ? placeholders
319 * @return string The replaced SQL query
321 private static function replaceParameters($sql, $args) {
323 foreach ($args AS $param => $value) {
324 if (is_int($args[$param]) || is_float($args[$param])) {
325 $replace = intval($args[$param]);
327 $replace = "'".self::escape($args[$param])."'";
330 $pos = strpos($sql, '?', $offset);
331 if ($pos !== false) {
332 $sql = substr_replace($sql, $replace, $pos, 1);
334 $offset = $pos + strlen($replace);
340 * @brief Convert parameter array to an universal form
341 * @param array $args Parameter array
342 * @return array universalized parameter array
344 private static function getParam($args) {
347 // When the second function parameter is an array then use this as the parameter array
348 if ((count($args) > 0) && (is_array($args[1]))) {
356 * @brief Executes a prepared statement that returns data
357 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
359 * Please only use it with complicated queries.
360 * For all regular queries please use dba::select or dba::exists
362 * @param string $sql SQL statement
363 * @return bool|object statement object or result object
365 public static function p($sql) {
368 $stamp1 = microtime(true);
370 $params = self::getParam(func_get_args());
372 // Renumber the array keys to be sure that they fit
375 foreach ($params AS $param) {
376 // Avoid problems with some MySQL servers and boolean values. See issue #3645
377 if (is_bool($param)) {
378 $param = (int)$param;
380 $args[++$i] = $param;
383 if (!self::$connected) {
387 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
388 // Question: Should we continue or stop the query here?
389 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
392 $sql = self::clean_query($sql);
393 $sql = self::any_value_fallback($sql);
397 if ($a->getConfigValue('system', 'db_callstack')) {
398 $sql = "/*".System::callstack()." */ ".$sql;
403 self::$affected_rows = 0;
405 // We have to make some things different if this function is called from "e"
406 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
408 if (isset($trace[1])) {
409 $called_from = $trace[1];
411 // We use just something that is defined to avoid warnings
412 $called_from = $trace[0];
414 // We are having an own error logging in the function "e"
415 $called_from_e = ($called_from['function'] == 'e');
417 switch (self::$driver) {
419 // If there are no arguments we use "query"
420 if (count($args) == 0) {
421 if (!$retval = self::$db->query($sql)) {
422 $errorInfo = self::$db->errorInfo();
423 self::$error = $errorInfo[2];
424 self::$errorno = $errorInfo[1];
428 self::$affected_rows = $retval->rowCount();
432 if (!$stmt = self::$db->prepare($sql)) {
433 $errorInfo = self::$db->errorInfo();
434 self::$error = $errorInfo[2];
435 self::$errorno = $errorInfo[1];
440 foreach ($args AS $param => $value) {
441 if (is_int($args[$param])) {
442 $data_type = PDO::PARAM_INT;
444 $data_type = PDO::PARAM_STR;
446 $stmt->bindParam($param, $args[$param], $data_type);
449 if (!$stmt->execute()) {
450 $errorInfo = $stmt->errorInfo();
451 self::$error = $errorInfo[2];
452 self::$errorno = $errorInfo[1];
456 self::$affected_rows = $retval->rowCount();
460 // There are SQL statements that cannot be executed with a prepared statement
461 $parts = explode(' ', $orig_sql);
462 $command = strtolower($parts[0]);
463 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
465 // The fallback routine is called as well when there are no arguments
466 if (!$can_be_prepared || (count($args) == 0)) {
467 $retval = self::$db->query(self::replaceParameters($sql, $args));
468 if (self::$db->errno) {
469 self::$error = self::$db->error;
470 self::$errorno = self::$db->errno;
473 if (isset($retval->num_rows)) {
474 self::$affected_rows = $retval->num_rows;
476 self::$affected_rows = self::$db->affected_rows;
482 $stmt = self::$db->stmt_init();
484 if (!$stmt->prepare($sql)) {
485 self::$error = $stmt->error;
486 self::$errorno = $stmt->errno;
493 foreach ($args AS $param => $value) {
494 if (is_int($args[$param])) {
496 } elseif (is_float($args[$param])) {
498 } elseif (is_string($args[$param])) {
503 $values[] = &$args[$param];
506 if (count($values) > 0) {
507 array_unshift($values, $param_types);
508 call_user_func_array([$stmt, 'bind_param'], $values);
511 if (!$stmt->execute()) {
512 self::$error = self::$db->error;
513 self::$errorno = self::$db->errno;
516 $stmt->store_result();
518 self::$affected_rows = $retval->affected_rows;
523 // We are having an own error logging in the function "e"
524 if ((self::$errorno != 0) && !$called_from_e) {
525 // We have to preserve the error code, somewhere in the logging it get lost
526 $error = self::$error;
527 $errorno = self::$errorno;
529 logger('DB Error '.self::$errorno.': '.self::$error."\n".
530 System::callstack(8)."\n".self::replaceParameters($sql, $args));
532 // On a lost connection we try to reconnect - but only once.
533 if ($errorno == 2006) {
534 if (self::$in_retrial || !self::reconnect()) {
535 // It doesn't make sense to continue when the database connection was lost
536 if (self::$in_retrial) {
537 logger('Giving up retrial because of database error '.$errorno.': '.$error);
539 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
544 logger('Reconnected after database error '.$errorno.': '.$error);
545 self::$in_retrial = true;
546 $ret = self::p($sql, $args);
547 self::$in_retrial = false;
552 self::$error = $error;
553 self::$errorno = $errorno;
556 $a->save_timestamp($stamp1, 'database');
558 if ($a->getConfigValue('system', 'db_log')) {
559 $stamp2 = microtime(true);
560 $duration = (float)($stamp2 - $stamp1);
562 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
563 $duration = round($duration, 3);
564 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
566 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
567 basename($backtrace[1]["file"])."\t".
568 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
569 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
576 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
578 * Please use dba::delete, dba::insert, dba::update, ... instead
580 * @param string $sql SQL statement
581 * @return boolean Was the query successfull? False is returned only if an error occurred
583 public static function e($sql) {
586 $stamp = microtime(true);
588 $params = self::getParam(func_get_args());
590 // In a case of a deadlock we are repeating the query 20 times
594 $stmt = self::p($sql, $params);
596 if (is_bool($stmt)) {
598 } elseif (is_object($stmt)) {
606 } while ((self::$errorno == 1213) && (--$timeout > 0));
608 if (self::$errorno != 0) {
609 // We have to preserve the error code, somewhere in the logging it get lost
610 $error = self::$error;
611 $errorno = self::$errorno;
613 logger('DB Error '.self::$errorno.': '.self::$error."\n".
614 System::callstack(8)."\n".self::replaceParameters($sql, $params));
616 // On a lost connection we simply quit.
617 // A reconnect like in self::p could be dangerous with modifications
618 if ($errorno == 2006) {
619 logger('Giving up because of database error '.$errorno.': '.$error);
623 self::$error = $error;
624 self::$errorno = $errorno;
627 $a->save_timestamp($stamp, "database_write");
633 * @brief Check if data exists
635 * @param string $table Table name
636 * @param array $condition array of fields for condition
638 * @return boolean Are there rows for that condition?
640 public static function exists($table, $condition) {
648 $first_key = key($condition);
649 if (!is_int($first_key)) {
650 $fields = [$first_key];
653 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
655 if (is_bool($stmt)) {
658 $retval = (self::num_rows($stmt) > 0);
667 * Fetches the first row
669 * Please use dba::selectFirst or dba::exists whenever this is possible.
671 * @brief Fetches the first row
672 * @param string $sql SQL statement
673 * @return array first row of query
675 public static function fetch_first($sql) {
676 $params = self::getParam(func_get_args());
678 $stmt = self::p($sql, $params);
680 if (is_bool($stmt)) {
683 $retval = self::fetch($stmt);
692 * @brief Returns the number of affected rows of the last statement
694 * @return int Number of rows
696 public static function affected_rows() {
697 return self::$affected_rows;
701 * @brief Returns the number of columns of a statement
703 * @param object Statement object
704 * @return int Number of columns
706 public static function columnCount($stmt) {
707 if (!is_object($stmt)) {
710 switch (self::$driver) {
712 return $stmt->columnCount();
714 return $stmt->field_count;
719 * @brief Returns the number of rows of a statement
721 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
722 * @return int Number of rows
724 public static function num_rows($stmt) {
725 if (!is_object($stmt)) {
728 switch (self::$driver) {
730 return $stmt->rowCount();
732 return $stmt->num_rows;
738 * @brief Fetch a single row
740 * @param mixed $stmt statement object
741 * @return array current row
743 public static function fetch($stmt) {
746 $stamp1 = microtime(true);
750 if (!is_object($stmt)) {
754 switch (self::$driver) {
756 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
759 if (get_class($stmt) == 'mysqli_result') {
760 $columns = $stmt->fetch_assoc();
764 // This code works, but is slow
766 // Bind the result to a result array
770 for ($x = 0; $x < $stmt->field_count; $x++) {
771 $cols[] = &$cols_num[$x];
774 call_user_func_array([$stmt, 'bind_result'], $cols);
776 if (!$stmt->fetch()) {
781 // We need to get the field names for the array keys
782 // It seems that there is no better way to do this.
783 $result = $stmt->result_metadata();
784 $fields = $result->fetch_fields();
786 foreach ($cols_num AS $param => $col) {
787 $columns[$fields[$param]->name] = $col;
791 $a->save_timestamp($stamp1, 'database');
797 * @brief Insert a row into a table
799 * @param string $table Table name
800 * @param array $param parameter array
801 * @param bool $on_duplicate_update Do an update on a duplicate entry
803 * @return boolean was the insert successfull?
805 public static function insert($table, $param, $on_duplicate_update = false) {
807 if (empty($table) || empty($param)) {
808 logger('Table and fields have to be set');
812 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
813 substr(str_repeat("?, ", count($param)), 0, -2).")";
815 if ($on_duplicate_update) {
816 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
818 $values = array_values($param);
819 $param = array_merge_recursive($values, $values);
822 return self::e($sql, $param);
826 * @brief Fetch the id of the last insert command
828 * @return integer Last inserted id
830 public static function lastInsertId() {
831 switch (self::$driver) {
833 $id = self::$db->lastInsertId();
836 $id = self::$db->insert_id;
843 * @brief Locks a table for exclusive write access
845 * This function can be extended in the future to accept a table array as well.
847 * @param string $table Table name
849 * @return boolean was the lock successful?
851 public static function lock($table) {
852 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
853 if (self::$driver == 'pdo') {
854 self::e("SET autocommit=0");
855 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
857 self::$db->autocommit(false);
860 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
862 if (self::$driver == 'pdo') {
863 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
867 if (self::$driver == 'pdo') {
868 self::e("SET autocommit=1");
870 self::$db->autocommit(true);
873 self::$in_transaction = true;
879 * @brief Unlocks all locked tables
881 * @return boolean was the unlock successful?
883 public static function unlock() {
884 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
885 self::performCommit();
887 if (self::$driver == 'pdo') {
888 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
891 $success = self::e("UNLOCK TABLES");
893 if (self::$driver == 'pdo') {
894 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
895 self::e("SET autocommit=1");
897 self::$db->autocommit(true);
900 self::$in_transaction = false;
905 * @brief Starts a transaction
907 * @return boolean Was the command executed successfully?
909 public static function transaction() {
910 if (!self::performCommit()) {
914 switch (self::$driver) {
916 if (self::$db->inTransaction()) {
919 if (!self::$db->beginTransaction()) {
924 if (!self::$db->begin_transaction()) {
930 self::$in_transaction = true;
934 private static function performCommit()
936 switch (self::$driver) {
938 if (!self::$db->inTransaction()) {
941 return self::$db->commit();
943 return self::$db->commit();
949 * @brief Does a commit
951 * @return boolean Was the command executed successfully?
953 public static function commit() {
954 if (!self::performCommit()) {
957 self::$in_transaction = false;
962 * @brief Does a rollback
964 * @return boolean Was the command executed successfully?
966 public static function rollback() {
969 switch (self::$driver) {
971 if (!self::$db->inTransaction()) {
975 $ret = self::$db->rollBack();
978 $ret = self::$db->rollback();
981 self::$in_transaction = false;
986 * @brief Build the array with the table relations
988 * The array is build from the database definitions in DBStructure.php
990 * This process must only be started once, since the value is cached.
992 private static function buildRelationData() {
993 $definition = DBStructure::definition();
995 foreach ($definition AS $table => $structure) {
996 foreach ($structure['fields'] AS $field => $field_struct) {
997 if (isset($field_struct['relation'])) {
998 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
999 self::$relation[$rel_table][$rel_field][$table][] = $field;
1007 * @brief Delete a row from a table
1009 * @param string $table Table name
1010 * @param array $conditions Field condition(s)
1011 * @param array $options
1012 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1013 * relations (default: true)
1014 * @param boolean $in_process Internal use: Only do a commit after the last delete
1015 * @param array $callstack Internal use: prevent endless loops
1017 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1019 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1021 if (empty($table) || empty($conditions)) {
1022 logger('Table and conditions have to be set');
1028 // Create a key for the loop prevention
1029 $key = $table . ':' . json_encode($conditions);
1031 // We quit when this key already exists in the callstack.
1032 if (isset($callstack[$key])) {
1036 $callstack[$key] = true;
1038 $table = self::escape($table);
1040 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1042 $cascade = defaults($options, 'cascade', true);
1044 // To speed up the whole process we cache the table relations
1045 if ($cascade && count(self::$relation) == 0) {
1046 self::buildRelationData();
1049 // Is there a relation entry for the table?
1050 if ($cascade && isset(self::$relation[$table])) {
1051 // We only allow a simple "one field" relation.
1052 $field = array_keys(self::$relation[$table])[0];
1053 $rel_def = array_values(self::$relation[$table])[0];
1055 // Create a key for preventing double queries
1056 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1058 // When the search field is the relation field, we don't need to fetch the rows
1059 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1060 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1061 foreach ($rel_def AS $rel_table => $rel_fields) {
1062 foreach ($rel_fields AS $rel_field) {
1063 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1064 $commands = array_merge($commands, $retval);
1067 // We quit when this key already exists in the callstack.
1068 } elseif (!isset($callstack[$qkey])) {
1070 $callstack[$qkey] = true;
1072 // Fetch all rows that are to be deleted
1073 $data = self::select($table, [$field], $conditions);
1075 while ($row = self::fetch($data)) {
1076 // Now we accumulate the delete commands
1077 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1078 $commands = array_merge($commands, $retval);
1083 // Since we had split the delete command we don't need the original command anymore
1084 unset($commands[$key]);
1089 // Now we finalize the process
1090 $do_transaction = !self::$in_transaction;
1092 if ($do_transaction) {
1093 self::transaction();
1099 foreach ($commands AS $command) {
1100 $conditions = $command['conditions'];
1102 $first_key = key($conditions);
1104 $condition_string = self::buildCondition($conditions);
1106 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1107 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1108 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1110 if (!self::e($sql, $conditions)) {
1111 if ($do_transaction) {
1117 $key_table = $command['table'];
1118 $key_condition = array_keys($command['conditions'])[0];
1119 $value = array_values($command['conditions'])[0];
1121 // Split the SQL queries in chunks of 100 values
1122 // We do the $i stuff here to make the code better readable
1123 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1124 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1128 $compacted[$key_table][$key_condition][$i][$value] = $value;
1129 $counter[$key_table][$key_condition] = $i;
1132 foreach ($compacted AS $table => $values) {
1133 foreach ($values AS $field => $field_value_list) {
1134 foreach ($field_value_list AS $field_values) {
1135 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1136 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1138 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1140 if (!self::e($sql, $field_values)) {
1141 if ($do_transaction) {
1149 if ($do_transaction) {
1159 * @brief Updates rows
1161 * Updates rows in the database. When $old_fields is set to an array,
1162 * the system will only do an update if the fields in that array changed.
1165 * Only the values in $old_fields are compared.
1166 * This is an intentional behaviour.
1169 * We include the timestamp field in $fields but not in $old_fields.
1170 * Then the row will only get the new timestamp when the other fields had changed.
1172 * When $old_fields is set to a boolean value the system will do this compare itself.
1173 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1176 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1177 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1179 * @param string $table Table name
1180 * @param array $fields contains the fields that are updated
1181 * @param array $condition condition array with the key values
1182 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1184 * @return boolean was the update successfull?
1186 public static function update($table, $fields, $condition, $old_fields = []) {
1188 if (empty($table) || empty($fields) || empty($condition)) {
1189 logger('Table, fields and condition have to be set');
1193 $table = self::escape($table);
1195 $condition_string = self::buildCondition($condition);
1197 if (is_bool($old_fields)) {
1198 $do_insert = $old_fields;
1200 $old_fields = self::selectFirst($table, [], $condition);
1202 if (is_bool($old_fields)) {
1204 $values = array_merge($condition, $fields);
1205 return self::insert($table, $values, $do_insert);
1211 $do_update = (count($old_fields) == 0);
1213 foreach ($old_fields AS $fieldname => $content) {
1214 if (isset($fields[$fieldname])) {
1215 if ($fields[$fieldname] == $content) {
1216 unset($fields[$fieldname]);
1223 if (!$do_update || (count($fields) == 0)) {
1227 $sql = "UPDATE `".$table."` SET `".
1228 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1230 $params1 = array_values($fields);
1231 $params2 = array_values($condition);
1232 $params = array_merge_recursive($params1, $params2);
1234 return self::e($sql, $params);
1238 * Retrieve a single record from a table and returns it in an associative array
1240 * @brief Retrieve a single record from a table
1241 * @param string $table
1242 * @param array $fields
1243 * @param array $condition
1244 * @param array $params
1245 * @return bool|array
1248 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1250 $params['limit'] = 1;
1251 $result = self::select($table, $fields, $condition, $params);
1253 if (is_bool($result)) {
1256 $row = self::fetch($result);
1257 self::close($result);
1263 * @brief Select rows from a table
1265 * @param string $table Table name
1266 * @param array $fields Array of selected fields, empty for all
1267 * @param array $condition Array of fields for condition
1268 * @param array $params Array of several parameters
1270 * @return boolean|object
1274 * $fields = array("id", "uri", "uid", "network");
1276 * $condition = array("uid" => 1, "network" => 'dspr');
1278 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1280 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1282 * $data = dba::select($table, $fields, $condition, $params);
1284 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1290 $table = self::escape($table);
1292 if (count($fields) > 0) {
1293 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1295 $select_fields = "*";
1298 $condition_string = self::buildCondition($condition);
1300 $param_string = self::buildParameter($params);
1302 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1304 $result = self::p($sql, $condition);
1310 * @brief Counts the rows from a table satisfying the provided condition
1312 * @param string $table Table name
1313 * @param array $condition array of fields for condition
1320 * $condition = ["uid" => 1, "network" => 'dspr'];
1322 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1324 * $count = dba::count($table, $condition);
1326 public static function count($table, array $condition = [])
1332 $condition_string = self::buildCondition($condition);
1334 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1336 $row = self::fetch_first($sql, $condition);
1338 return $row['count'];
1342 * @brief Returns the SQL condition string built from the provided condition array
1344 * This function operates with two modes.
1345 * - Supplied with a filed/value associative array, it builds simple strict
1346 * equality conditions linked by AND.
1347 * - Supplied with a flat list, the first element is the condition string and
1348 * the following arguments are the values to be interpolated
1350 * $condition = ["uid" => 1, "network" => 'dspr'];
1352 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1354 * In either case, the provided array is left with the parameters only
1356 * @param array $condition
1359 public static function buildCondition(array &$condition = [])
1361 $condition_string = '';
1362 if (count($condition) > 0) {
1364 $first_key = key($condition);
1365 if (is_int($first_key)) {
1366 $condition_string = " WHERE (" . array_shift($condition) . ")";
1369 $condition_string = "";
1370 foreach ($condition as $field => $value) {
1371 if ($condition_string != "") {
1372 $condition_string .= " AND ";
1374 if (is_array($value)) {
1375 /* Workaround for MySQL Bug #64791.
1376 * Never mix data types inside any IN() condition.
1377 * In case of mixed types, cast all as string.
1378 * Logic needs to be consistent with dba::p() data types.
1382 foreach ($value as $single_value) {
1383 if (is_int($single_value)) {
1390 if ($is_int && $is_alpha) {
1391 foreach ($value as &$ref) {
1393 $ref = (string)$ref;
1396 unset($ref); //Prevent accidental re-use.
1399 $new_values = array_merge($new_values, array_values($value));
1400 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1401 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1403 $new_values[$field] = $value;
1404 $condition_string .= "`" . $field . "` = ?";
1407 $condition_string = " WHERE (" . $condition_string . ")";
1408 $condition = $new_values;
1412 return $condition_string;
1416 * @brief Returns the SQL parameter string built from the provided parameter array
1418 * @param array $params
1421 public static function buildParameter(array $params = [])
1424 if (isset($params['order'])) {
1425 $order_string = " ORDER BY ";
1426 foreach ($params['order'] AS $fields => $order) {
1427 if (!is_int($fields)) {
1428 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1430 $order_string .= "`" . $order . "`, ";
1433 $order_string = substr($order_string, 0, -2);
1437 if (isset($params['limit']) && is_int($params['limit'])) {
1438 $limit_string = " LIMIT " . $params['limit'];
1441 if (isset($params['limit']) && is_array($params['limit'])) {
1442 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1445 return $order_string.$limit_string;
1449 * @brief Fills an array with data from a query
1451 * @param object $stmt statement object
1452 * @return array Data array
1454 public static function inArray($stmt, $do_close = true) {
1455 if (is_bool($stmt)) {
1460 while ($row = self::fetch($stmt)) {
1470 * @brief Returns the error number of the last query
1472 * @return string Error number (0 if no error)
1474 public static function errorNo() {
1475 return self::$errorno;
1479 * @brief Returns the error message of the last query
1481 * @return string Error message ('' if no error)
1483 public static function errorMessage() {
1484 return self::$error;
1488 * @brief Closes the current statement
1490 * @param object $stmt statement object
1491 * @return boolean was the close successful?
1493 public static function close($stmt) {
1496 $stamp1 = microtime(true);
1498 if (!is_object($stmt)) {
1502 switch (self::$driver) {
1504 $ret = $stmt->closeCursor();
1507 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1508 // We should be careful not to assume the object type of $stmt
1509 // because dba::p() has been able to return both types.
1510 if ($stmt instanceof mysqli_stmt) {
1511 $stmt->free_result();
1512 $ret = $stmt->close();
1513 } elseif ($stmt instanceof mysqli_result) {
1522 $a->save_timestamp($stamp1, 'database');