4 use Friendica\Core\L10n;
5 use Friendica\Core\System;
6 use Friendica\Database\DBM;
7 use Friendica\Database\DBStructure;
8 use Friendica\Util\DateTimeFormat;
11 * @class MySQL database class
13 * This class is for the low level database stuff that does driver specific things.
17 public static $connected = false;
19 private static $_server_info = '';
21 private static $driver;
22 private static $error = false;
23 private static $errorno = 0;
24 private static $affected_rows = 0;
25 private static $in_transaction = false;
26 private static $in_retrial = false;
27 private static $relation = [];
28 private static $db_serveraddr = '';
29 private static $db_user = '';
30 private static $db_pass = '';
31 private static $db_name = '';
33 public static function connect($serveraddr, $user, $pass, $db) {
34 if (!is_null(self::$db) && self::connected()) {
40 $stamp1 = microtime(true);
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;
48 $serveraddr = trim($serveraddr);
50 $serverdata = explode(':', $serveraddr);
51 $server = $serverdata[0];
53 if (count($serverdata) > 1) {
54 $port = trim($serverdata[1]);
57 $server = trim($server);
62 if (!(strlen($server) && strlen($user))) {
66 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
67 self::$driver = 'pdo';
68 $connect = "mysql:host=".$server.";dbname=".$db;
71 $connect .= ";port=".$port;
74 if (isset($a->config["system"]["db_charset"])) {
75 $connect .= ";charset=".$a->config["system"]["db_charset"];
78 self::$db = @new PDO($connect, $user, $pass);
79 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
80 self::$connected = true;
81 } catch (PDOException $e) {
85 if (!self::$connected && class_exists('mysqli')) {
86 self::$driver = 'mysqli';
87 self::$db = @new mysqli($server, $user, $pass, $db, $port);
88 if (!mysqli_connect_errno()) {
89 self::$connected = true;
91 if (isset($a->config["system"]["db_charset"])) {
92 self::$db->set_charset($a->config["system"]["db_charset"]);
97 // No suitable SQL driver was found.
98 if (!self::$connected) {
102 $a->save_timestamp($stamp1, "network");
104 return self::$connected;
108 * Disconnects the current database connection
110 public static function disconnect()
112 if (is_null(self::$db)) {
116 switch (self::$driver) {
128 * Perform a reconnect of an existing database connection
130 public static function reconnect() {
133 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name);
138 * Return the database object.
141 public static function get_db()
147 * @brief Returns the MySQL server version string
149 * This function discriminate between the deprecated mysql API and the current
150 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
154 public static function server_info() {
155 if (self::$_server_info == '') {
156 switch (self::$driver) {
158 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
161 self::$_server_info = self::$db->server_info;
165 return self::$_server_info;
169 * @brief Returns the selected database name
173 public static function database_name() {
174 $ret = self::p("SELECT DATABASE() AS `db`");
175 $data = self::inArray($ret);
176 return $data[0]['db'];
180 * @brief Analyze a database query and log this if some conditions are met.
182 * @param string $query The database query that will be analyzed
184 private static function logIndex($query) {
187 if (empty($a->config["system"]["db_log_index"])) {
191 // Don't explain an explain statement
192 if (strtolower(substr($query, 0, 7)) == "explain") {
196 // Only do the explain on "select", "update" and "delete"
197 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
201 $r = self::p("EXPLAIN ".$query);
202 if (!DBM::is_result($r)) {
206 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
207 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
209 while ($row = dba::fetch($r)) {
210 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
211 $log = (in_array($row['key'], $watchlist) &&
212 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
217 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
221 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
226 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
227 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
228 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
229 basename($backtrace[1]["file"])."\t".
230 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
231 substr($query, 0, 2000)."\n", FILE_APPEND);
236 public static function escape($str) {
237 switch (self::$driver) {
239 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
241 return @self::$db->real_escape_string($str);
245 public static function connected() {
248 switch (self::$driver) {
250 $r = dba::p("SELECT 1");
251 if (DBM::is_result($r)) {
252 $row = dba::inArray($r);
253 $connected = ($row[0]['1'] == '1');
257 $connected = self::$db->ping();
264 * @brief Replaces ANY_VALUE() function by MIN() function,
265 * if the database server does not support ANY_VALUE().
267 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
268 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
269 * A standard fall-back is to use MIN().
271 * @param string $sql An SQL string without the values
272 * @return string The input SQL string modified if necessary.
274 public static function any_value_fallback($sql) {
275 $server_info = self::server_info();
276 if (version_compare($server_info, '5.7.5', '<') ||
277 (stripos($server_info, 'MariaDB') !== false)) {
278 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
284 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
286 * This is safe when we bind the parameters later.
287 * The parameter values aren't part of the SQL.
289 * @param string $sql An SQL string without the values
290 * @return string The input SQL string modified if necessary.
292 public static function clean_query($sql) {
293 $search = ["\t", "\n", "\r", " "];
294 $replace = [' ', ' ', ' ', ' '];
297 $sql = str_replace($search, $replace, $sql);
298 } while ($oldsql != $sql);
305 * @brief Replaces the ? placeholders with the parameters in the $args array
307 * @param string $sql SQL query
308 * @param array $args The parameters that are to replace the ? placeholders
309 * @return string The replaced SQL query
311 private static function replaceParameters($sql, $args) {
313 foreach ($args AS $param => $value) {
314 if (is_int($args[$param]) || is_float($args[$param])) {
315 $replace = intval($args[$param]);
317 $replace = "'".self::escape($args[$param])."'";
320 $pos = strpos($sql, '?', $offset);
321 if ($pos !== false) {
322 $sql = substr_replace($sql, $replace, $pos, 1);
324 $offset = $pos + strlen($replace);
330 * @brief Convert parameter array to an universal form
331 * @param array $args Parameter array
332 * @return array universalized parameter array
334 private static function getParam($args) {
337 // When the second function parameter is an array then use this as the parameter array
338 if ((count($args) > 0) && (is_array($args[1]))) {
346 * @brief Executes a prepared statement that returns data
347 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
349 * Please only use it with complicated queries.
350 * For all regular queries please use dba::select or dba::exists
352 * @param string $sql SQL statement
353 * @return bool|object statement object or result object
355 public static function p($sql) {
358 $stamp1 = microtime(true);
360 $params = self::getParam(func_get_args());
362 // Renumber the array keys to be sure that they fit
365 foreach ($params AS $param) {
366 // Avoid problems with some MySQL servers and boolean values. See issue #3645
367 if (is_bool($param)) {
368 $param = (int)$param;
370 $args[++$i] = $param;
373 if (!self::$connected) {
377 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
378 // Question: Should we continue or stop the query here?
379 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
382 $sql = self::clean_query($sql);
383 $sql = self::any_value_fallback($sql);
387 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
388 $sql = "/*".System::callstack()." */ ".$sql;
393 self::$affected_rows = 0;
395 // We have to make some things different if this function is called from "e"
396 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
398 if (isset($trace[1])) {
399 $called_from = $trace[1];
401 // We use just something that is defined to avoid warnings
402 $called_from = $trace[0];
404 // We are having an own error logging in the function "e"
405 $called_from_e = ($called_from['function'] == 'e');
407 switch (self::$driver) {
409 // If there are no arguments we use "query"
410 if (count($args) == 0) {
411 if (!$retval = self::$db->query($sql)) {
412 $errorInfo = self::$db->errorInfo();
413 self::$error = $errorInfo[2];
414 self::$errorno = $errorInfo[1];
418 self::$affected_rows = $retval->rowCount();
422 if (!$stmt = self::$db->prepare($sql)) {
423 $errorInfo = self::$db->errorInfo();
424 self::$error = $errorInfo[2];
425 self::$errorno = $errorInfo[1];
430 foreach ($args AS $param => $value) {
431 if (is_int($args[$param])) {
432 $data_type = PDO::PARAM_INT;
434 $data_type = PDO::PARAM_STR;
436 $stmt->bindParam($param, $args[$param], $data_type);
439 if (!$stmt->execute()) {
440 $errorInfo = $stmt->errorInfo();
441 self::$error = $errorInfo[2];
442 self::$errorno = $errorInfo[1];
446 self::$affected_rows = $retval->rowCount();
450 // There are SQL statements that cannot be executed with a prepared statement
451 $parts = explode(' ', $orig_sql);
452 $command = strtolower($parts[0]);
453 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
455 // The fallback routine is called as well when there are no arguments
456 if (!$can_be_prepared || (count($args) == 0)) {
457 $retval = self::$db->query(self::replaceParameters($sql, $args));
458 if (self::$db->errno) {
459 self::$error = self::$db->error;
460 self::$errorno = self::$db->errno;
463 if (isset($retval->num_rows)) {
464 self::$affected_rows = $retval->num_rows;
466 self::$affected_rows = self::$db->affected_rows;
472 $stmt = self::$db->stmt_init();
474 if (!$stmt->prepare($sql)) {
475 self::$error = $stmt->error;
476 self::$errorno = $stmt->errno;
483 foreach ($args AS $param => $value) {
484 if (is_int($args[$param])) {
486 } elseif (is_float($args[$param])) {
488 } elseif (is_string($args[$param])) {
493 $values[] = &$args[$param];
496 if (count($values) > 0) {
497 array_unshift($values, $param_types);
498 call_user_func_array([$stmt, 'bind_param'], $values);
501 if (!$stmt->execute()) {
502 self::$error = self::$db->error;
503 self::$errorno = self::$db->errno;
506 $stmt->store_result();
508 self::$affected_rows = $retval->affected_rows;
513 // We are having an own error logging in the function "e"
514 if ((self::$errorno != 0) && !$called_from_e) {
515 // We have to preserve the error code, somewhere in the logging it get lost
516 $error = self::$error;
517 $errorno = self::$errorno;
519 logger('DB Error '.self::$errorno.': '.self::$error."\n".
520 System::callstack(8)."\n".self::replaceParameters($sql, $args));
522 // On a lost connection we try to reconnect - but only once.
523 if ($errorno == 2006) {
524 if (self::$in_retrial || !self::reconnect()) {
525 // It doesn't make sense to continue when the database connection was lost
526 if (self::$in_retrial) {
527 logger('Giving up retrial because of database error '.$errorno.': '.$error);
529 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
534 logger('Reconnected after database error '.$errorno.': '.$error);
535 self::$in_retrial = true;
536 $ret = self::p($sql, $args);
537 self::$in_retrial = false;
542 self::$error = $error;
543 self::$errorno = $errorno;
546 $a->save_timestamp($stamp1, 'database');
548 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
550 $stamp2 = microtime(true);
551 $duration = (float)($stamp2 - $stamp1);
553 if (($duration > $a->config["system"]["db_loglimit"])) {
554 $duration = round($duration, 3);
555 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
557 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
558 basename($backtrace[1]["file"])."\t".
559 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
560 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
567 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
569 * Please use dba::delete, dba::insert, dba::update, ... instead
571 * @param string $sql SQL statement
572 * @return boolean Was the query successfull? False is returned only if an error occurred
574 public static function e($sql) {
577 $stamp = microtime(true);
579 $params = self::getParam(func_get_args());
581 // In a case of a deadlock we are repeating the query 20 times
585 $stmt = self::p($sql, $params);
587 if (is_bool($stmt)) {
589 } elseif (is_object($stmt)) {
597 } while ((self::$errorno == 1213) && (--$timeout > 0));
599 if (self::$errorno != 0) {
600 // We have to preserve the error code, somewhere in the logging it get lost
601 $error = self::$error;
602 $errorno = self::$errorno;
604 logger('DB Error '.self::$errorno.': '.self::$error."\n".
605 System::callstack(8)."\n".self::replaceParameters($sql, $params));
607 // On a lost connection we simply quit.
608 // A reconnect like in self::p could be dangerous with modifications
609 if ($errorno == 2006) {
610 logger('Giving up because of database error '.$errorno.': '.$error);
614 self::$error = $error;
615 self::$errorno = $errorno;
618 $a->save_timestamp($stamp, "database_write");
624 * @brief Check if data exists
626 * @param string $table Table name
627 * @param array $condition array of fields for condition
629 * @return boolean Are there rows for that condition?
631 public static function exists($table, $condition) {
639 $first_key = key($condition);
640 if (!is_int($first_key)) {
641 $fields = [$first_key];
644 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
646 if (is_bool($stmt)) {
649 $retval = (self::num_rows($stmt) > 0);
658 * Fetches the first row
660 * Please use dba::selectFirst or dba::exists whenever this is possible.
662 * @brief Fetches the first row
663 * @param string $sql SQL statement
664 * @return array first row of query
666 public static function fetch_first($sql) {
667 $params = self::getParam(func_get_args());
669 $stmt = self::p($sql, $params);
671 if (is_bool($stmt)) {
674 $retval = self::fetch($stmt);
683 * @brief Returns the number of affected rows of the last statement
685 * @return int Number of rows
687 public static function affected_rows() {
688 return self::$affected_rows;
692 * @brief Returns the number of columns of a statement
694 * @param object Statement object
695 * @return int Number of columns
697 public static function columnCount($stmt) {
698 if (!is_object($stmt)) {
701 switch (self::$driver) {
703 return $stmt->columnCount();
705 return $stmt->field_count;
710 * @brief Returns the number of rows of a statement
712 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
713 * @return int Number of rows
715 public static function num_rows($stmt) {
716 if (!is_object($stmt)) {
719 switch (self::$driver) {
721 return $stmt->rowCount();
723 return $stmt->num_rows;
729 * @brief Fetch a single row
731 * @param mixed $stmt statement object
732 * @return array current row
734 public static function fetch($stmt) {
737 $stamp1 = microtime(true);
741 if (!is_object($stmt)) {
745 switch (self::$driver) {
747 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
750 if (get_class($stmt) == 'mysqli_result') {
751 $columns = $stmt->fetch_assoc();
755 // This code works, but is slow
757 // Bind the result to a result array
761 for ($x = 0; $x < $stmt->field_count; $x++) {
762 $cols[] = &$cols_num[$x];
765 call_user_func_array([$stmt, 'bind_result'], $cols);
767 if (!$stmt->fetch()) {
772 // We need to get the field names for the array keys
773 // It seems that there is no better way to do this.
774 $result = $stmt->result_metadata();
775 $fields = $result->fetch_fields();
777 foreach ($cols_num AS $param => $col) {
778 $columns[$fields[$param]->name] = $col;
782 $a->save_timestamp($stamp1, 'database');
788 * @brief Insert a row into a table
790 * @param string $table Table name
791 * @param array $param parameter array
792 * @param bool $on_duplicate_update Do an update on a duplicate entry
794 * @return boolean was the insert successfull?
796 public static function insert($table, $param, $on_duplicate_update = false) {
798 if (empty($table) || empty($param)) {
799 logger('Table and fields have to be set');
803 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
804 substr(str_repeat("?, ", count($param)), 0, -2).")";
806 if ($on_duplicate_update) {
807 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
809 $values = array_values($param);
810 $param = array_merge_recursive($values, $values);
813 return self::e($sql, $param);
817 * @brief Fetch the id of the last insert command
819 * @return integer Last inserted id
821 public static function lastInsertId() {
822 switch (self::$driver) {
824 $id = self::$db->lastInsertId();
827 $id = self::$db->insert_id;
834 * @brief Locks a table for exclusive write access
836 * This function can be extended in the future to accept a table array as well.
838 * @param string $table Table name
840 * @return boolean was the lock successful?
842 public static function lock($table) {
843 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
844 if (self::$driver == 'pdo') {
845 self::e("SET autocommit=0");
846 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
848 self::$db->autocommit(false);
851 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
853 if (self::$driver == 'pdo') {
854 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
858 if (self::$driver == 'pdo') {
859 self::e("SET autocommit=1");
861 self::$db->autocommit(true);
864 self::$in_transaction = true;
870 * @brief Unlocks all locked tables
872 * @return boolean was the unlock successful?
874 public static function unlock() {
875 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
876 self::performCommit();
878 if (self::$driver == 'pdo') {
879 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
882 $success = self::e("UNLOCK TABLES");
884 if (self::$driver == 'pdo') {
885 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
886 self::e("SET autocommit=1");
888 self::$db->autocommit(true);
891 self::$in_transaction = false;
896 * @brief Starts a transaction
898 * @return boolean Was the command executed successfully?
900 public static function transaction() {
901 if (!self::performCommit()) {
905 switch (self::$driver) {
907 if (self::$db->inTransaction()) {
910 if (!self::$db->beginTransaction()) {
915 if (!self::$db->begin_transaction()) {
921 self::$in_transaction = true;
925 private static function performCommit()
927 switch (self::$driver) {
929 if (!self::$db->inTransaction()) {
932 return self::$db->commit();
934 return self::$db->commit();
940 * @brief Does a commit
942 * @return boolean Was the command executed successfully?
944 public static function commit() {
945 if (!self::performCommit()) {
948 self::$in_transaction = false;
953 * @brief Does a rollback
955 * @return boolean Was the command executed successfully?
957 public static function rollback() {
960 switch (self::$driver) {
962 if (!self::$db->inTransaction()) {
966 $ret = self::$db->rollBack();
969 $ret = self::$db->rollback();
972 self::$in_transaction = false;
977 * @brief Build the array with the table relations
979 * The array is build from the database definitions in DBStructure.php
981 * This process must only be started once, since the value is cached.
983 private static function buildRelationData() {
984 $definition = DBStructure::definition();
986 foreach ($definition AS $table => $structure) {
987 foreach ($structure['fields'] AS $field => $field_struct) {
988 if (isset($field_struct['relation'])) {
989 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
990 self::$relation[$rel_table][$rel_field][$table][] = $field;
998 * @brief Delete a row from a table
1000 * @param string $table Table name
1001 * @param array $conditions Field condition(s)
1002 * @param array $options
1003 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1004 * relations (default: true)
1005 * @param boolean $in_process Internal use: Only do a commit after the last delete
1006 * @param array $callstack Internal use: prevent endless loops
1008 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1010 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1012 if (empty($table) || empty($conditions)) {
1013 logger('Table and conditions have to be set');
1019 // Create a key for the loop prevention
1020 $key = $table . ':' . json_encode($conditions);
1022 // We quit when this key already exists in the callstack.
1023 if (isset($callstack[$key])) {
1027 $callstack[$key] = true;
1029 $table = self::escape($table);
1031 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1033 $cascade = defaults($options, 'cascade', true);
1035 // To speed up the whole process we cache the table relations
1036 if ($cascade && count(self::$relation) == 0) {
1037 self::buildRelationData();
1040 // Is there a relation entry for the table?
1041 if ($cascade && isset(self::$relation[$table])) {
1042 // We only allow a simple "one field" relation.
1043 $field = array_keys(self::$relation[$table])[0];
1044 $rel_def = array_values(self::$relation[$table])[0];
1046 // Create a key for preventing double queries
1047 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1049 // When the search field is the relation field, we don't need to fetch the rows
1050 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1051 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1052 foreach ($rel_def AS $rel_table => $rel_fields) {
1053 foreach ($rel_fields AS $rel_field) {
1054 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1055 $commands = array_merge($commands, $retval);
1058 // We quit when this key already exists in the callstack.
1059 } elseif (!isset($callstack[$qkey])) {
1061 $callstack[$qkey] = true;
1063 // Fetch all rows that are to be deleted
1064 $data = self::select($table, [$field], $conditions);
1066 while ($row = self::fetch($data)) {
1067 // Now we accumulate the delete commands
1068 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1069 $commands = array_merge($commands, $retval);
1074 // Since we had split the delete command we don't need the original command anymore
1075 unset($commands[$key]);
1080 // Now we finalize the process
1081 $do_transaction = !self::$in_transaction;
1083 if ($do_transaction) {
1084 self::transaction();
1090 foreach ($commands AS $command) {
1091 $conditions = $command['conditions'];
1093 $first_key = key($conditions);
1095 $condition_string = self::buildCondition($conditions);
1097 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1098 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1099 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1101 if (!self::e($sql, $conditions)) {
1102 if ($do_transaction) {
1108 $key_table = $command['table'];
1109 $key_condition = array_keys($command['conditions'])[0];
1110 $value = array_values($command['conditions'])[0];
1112 // Split the SQL queries in chunks of 100 values
1113 // We do the $i stuff here to make the code better readable
1114 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1115 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1119 $compacted[$key_table][$key_condition][$i][$value] = $value;
1120 $counter[$key_table][$key_condition] = $i;
1123 foreach ($compacted AS $table => $values) {
1124 foreach ($values AS $field => $field_value_list) {
1125 foreach ($field_value_list AS $field_values) {
1126 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1127 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1129 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1131 if (!self::e($sql, $field_values)) {
1132 if ($do_transaction) {
1140 if ($do_transaction) {
1150 * @brief Updates rows
1152 * Updates rows in the database. When $old_fields is set to an array,
1153 * the system will only do an update if the fields in that array changed.
1156 * Only the values in $old_fields are compared.
1157 * This is an intentional behaviour.
1160 * We include the timestamp field in $fields but not in $old_fields.
1161 * Then the row will only get the new timestamp when the other fields had changed.
1163 * When $old_fields is set to a boolean value the system will do this compare itself.
1164 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1167 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1168 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1170 * @param string $table Table name
1171 * @param array $fields contains the fields that are updated
1172 * @param array $condition condition array with the key values
1173 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1175 * @return boolean was the update successfull?
1177 public static function update($table, $fields, $condition, $old_fields = []) {
1179 if (empty($table) || empty($fields) || empty($condition)) {
1180 logger('Table, fields and condition have to be set');
1184 $table = self::escape($table);
1186 $condition_string = self::buildCondition($condition);
1188 if (is_bool($old_fields)) {
1189 $do_insert = $old_fields;
1191 $old_fields = self::selectFirst($table, [], $condition);
1193 if (is_bool($old_fields)) {
1195 $values = array_merge($condition, $fields);
1196 return self::insert($table, $values, $do_insert);
1202 $do_update = (count($old_fields) == 0);
1204 foreach ($old_fields AS $fieldname => $content) {
1205 if (isset($fields[$fieldname])) {
1206 if ($fields[$fieldname] == $content) {
1207 unset($fields[$fieldname]);
1214 if (!$do_update || (count($fields) == 0)) {
1218 $sql = "UPDATE `".$table."` SET `".
1219 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1221 $params1 = array_values($fields);
1222 $params2 = array_values($condition);
1223 $params = array_merge_recursive($params1, $params2);
1225 return self::e($sql, $params);
1229 * Retrieve a single record from a table and returns it in an associative array
1231 * @brief Retrieve a single record from a table
1232 * @param string $table
1233 * @param array $fields
1234 * @param array $condition
1235 * @param array $params
1236 * @return bool|array
1239 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1241 $params['limit'] = 1;
1242 $result = self::select($table, $fields, $condition, $params);
1244 if (is_bool($result)) {
1247 $row = self::fetch($result);
1248 self::close($result);
1254 * @brief Select rows from a table
1256 * @param string $table Table name
1257 * @param array $fields Array of selected fields, empty for all
1258 * @param array $condition Array of fields for condition
1259 * @param array $params Array of several parameters
1261 * @return boolean|object
1265 * $fields = array("id", "uri", "uid", "network");
1267 * $condition = array("uid" => 1, "network" => 'dspr');
1269 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1271 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1273 * $data = dba::select($table, $fields, $condition, $params);
1275 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1281 $table = self::escape($table);
1283 if (count($fields) > 0) {
1284 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1286 $select_fields = "*";
1289 $condition_string = self::buildCondition($condition);
1291 $param_string = self::buildParameter($params);
1293 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1295 $result = self::p($sql, $condition);
1301 * @brief Counts the rows from a table satisfying the provided condition
1303 * @param string $table Table name
1304 * @param array $condition array of fields for condition
1311 * $condition = ["uid" => 1, "network" => 'dspr'];
1313 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1315 * $count = dba::count($table, $condition);
1317 public static function count($table, array $condition = [])
1323 $condition_string = self::buildCondition($condition);
1325 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1327 $row = self::fetch_first($sql, $condition);
1329 return $row['count'];
1333 * @brief Returns the SQL condition string built from the provided condition array
1335 * This function operates with two modes.
1336 * - Supplied with a filed/value associative array, it builds simple strict
1337 * equality conditions linked by AND.
1338 * - Supplied with a flat list, the first element is the condition string and
1339 * the following arguments are the values to be interpolated
1341 * $condition = ["uid" => 1, "network" => 'dspr'];
1343 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1345 * In either case, the provided array is left with the parameters only
1347 * @param array $condition
1350 public static function buildCondition(array &$condition = [])
1352 $condition_string = '';
1353 if (count($condition) > 0) {
1355 $first_key = key($condition);
1356 if (is_int($first_key)) {
1357 $condition_string = " WHERE (" . array_shift($condition) . ")";
1360 $condition_string = "";
1361 foreach ($condition as $field => $value) {
1362 if ($condition_string != "") {
1363 $condition_string .= " AND ";
1365 if (is_array($value)) {
1366 /* Workaround for MySQL Bug #64791.
1367 * Never mix data types inside any IN() condition.
1368 * In case of mixed types, cast all as string.
1369 * Logic needs to be consistent with dba::p() data types.
1373 foreach ($value as $single_value) {
1374 if (is_int($single_value)) {
1381 if ($is_int && $is_alpha) {
1382 foreach ($value as &$ref) {
1384 $ref = (string)$ref;
1387 unset($ref); //Prevent accidental re-use.
1390 $new_values = array_merge($new_values, array_values($value));
1391 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1392 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1394 $new_values[$field] = $value;
1395 $condition_string .= "`" . $field . "` = ?";
1398 $condition_string = " WHERE (" . $condition_string . ")";
1399 $condition = $new_values;
1403 return $condition_string;
1407 * @brief Returns the SQL parameter string built from the provided parameter array
1409 * @param array $params
1412 public static function buildParameter(array $params = [])
1415 if (isset($params['order'])) {
1416 $order_string = " ORDER BY ";
1417 foreach ($params['order'] AS $fields => $order) {
1418 if (!is_int($fields)) {
1419 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1421 $order_string .= "`" . $order . "`, ";
1424 $order_string = substr($order_string, 0, -2);
1428 if (isset($params['limit']) && is_int($params['limit'])) {
1429 $limit_string = " LIMIT " . $params['limit'];
1432 if (isset($params['limit']) && is_array($params['limit'])) {
1433 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1436 return $order_string.$limit_string;
1440 * @brief Fills an array with data from a query
1442 * @param object $stmt statement object
1443 * @return array Data array
1445 public static function inArray($stmt, $do_close = true) {
1446 if (is_bool($stmt)) {
1451 while ($row = self::fetch($stmt)) {
1461 * @brief Returns the error number of the last query
1463 * @return string Error number (0 if no error)
1465 public static function errorNo() {
1466 return self::$errorno;
1470 * @brief Returns the error message of the last query
1472 * @return string Error message ('' if no error)
1474 public static function errorMessage() {
1475 return self::$error;
1479 * @brief Closes the current statement
1481 * @param object $stmt statement object
1482 * @return boolean was the close successful?
1484 public static function close($stmt) {
1487 $stamp1 = microtime(true);
1489 if (!is_object($stmt)) {
1493 switch (self::$driver) {
1495 $ret = $stmt->closeCursor();
1498 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1499 // We should be careful not to assume the object type of $stmt
1500 // because dba::p() has been able to return both types.
1501 if ($stmt instanceof mysqli_stmt) {
1502 $stmt->free_result();
1503 $ret = $stmt->close();
1504 } elseif ($stmt instanceof mysqli_result) {
1513 $a->save_timestamp($stamp1, 'database');
1519 function dbesc($str) {
1520 if (dba::$connected) {
1521 return(dba::escape($str));
1523 return(str_replace("'","\\'",$str));
1528 * @brief execute SQL query with printf style args - deprecated
1530 * Please use the dba:: functions instead:
1531 * dba::select, dba::exists, dba::insert
1532 * dba::delete, dba::update, dba::p, dba::e
1534 * @param $args Query parameters (1 to N parameters of different types)
1535 * @return array|bool Query array
1538 $args = func_get_args();
1541 if (!dba::$connected) {
1545 $sql = dba::clean_query($sql);
1546 $sql = dba::any_value_fallback($sql);
1548 $stmt = @vsprintf($sql, $args);
1550 $ret = dba::p($stmt);
1552 if (is_bool($ret)) {
1556 $columns = dba::columnCount($ret);
1558 $data = dba::inArray($ret);
1560 if ((count($data) == 0) && ($columns == 0)) {
1567 function dba_timer() {
1568 return microtime(true);