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::$connected = true;
80 } catch (PDOException $e) {
84 if (!self::$connected && class_exists('mysqli')) {
85 self::$driver = 'mysqli';
86 self::$db = @new mysqli($server, $user, $pass, $db, $port);
87 if (!mysqli_connect_errno()) {
88 self::$connected = true;
90 if (isset($a->config["system"]["db_charset"])) {
91 self::$db->set_charset($a->config["system"]["db_charset"]);
96 // No suitable SQL driver was found.
97 if (!self::$connected) {
101 $a->save_timestamp($stamp1, "network");
103 return self::$connected;
107 * Disconnects the current database connection
109 public static function disconnect()
111 if (is_null(self::$db)) {
115 switch (self::$driver) {
127 * Perform a reconnect of an existing database connection
129 public static function reconnect() {
132 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name);
137 * Return the database object.
140 public static function get_db()
146 * @brief Returns the MySQL server version string
148 * This function discriminate between the deprecated mysql API and the current
149 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
153 public static function server_info() {
154 if (self::$_server_info == '') {
155 switch (self::$driver) {
157 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
160 self::$_server_info = self::$db->server_info;
164 return self::$_server_info;
168 * @brief Returns the selected database name
172 public static function database_name() {
173 $ret = self::p("SELECT DATABASE() AS `db`");
174 $data = self::inArray($ret);
175 return $data[0]['db'];
179 * @brief Analyze a database query and log this if some conditions are met.
181 * @param string $query The database query that will be analyzed
183 private static function logIndex($query) {
186 if (empty($a->config["system"]["db_log_index"])) {
190 // Don't explain an explain statement
191 if (strtolower(substr($query, 0, 7)) == "explain") {
195 // Only do the explain on "select", "update" and "delete"
196 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
200 $r = self::p("EXPLAIN ".$query);
201 if (!DBM::is_result($r)) {
205 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
206 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
208 while ($row = dba::fetch($r)) {
209 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
210 $log = (in_array($row['key'], $watchlist) &&
211 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
216 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
220 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
225 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
226 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
227 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
228 basename($backtrace[1]["file"])."\t".
229 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
230 substr($query, 0, 2000)."\n", FILE_APPEND);
235 public static function escape($str) {
236 switch (self::$driver) {
238 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
240 return @self::$db->real_escape_string($str);
244 public static function connected() {
247 switch (self::$driver) {
249 $r = dba::p("SELECT 1");
250 if (DBM::is_result($r)) {
251 $row = dba::inArray($r);
252 $connected = ($row[0]['1'] == '1');
256 $connected = self::$db->ping();
263 * @brief Replaces ANY_VALUE() function by MIN() function,
264 * if the database server does not support ANY_VALUE().
266 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
267 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
268 * A standard fall-back is to use MIN().
270 * @param string $sql An SQL string without the values
271 * @return string The input SQL string modified if necessary.
273 public static function any_value_fallback($sql) {
274 $server_info = self::server_info();
275 if (version_compare($server_info, '5.7.5', '<') ||
276 (stripos($server_info, 'MariaDB') !== false)) {
277 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
283 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
285 * This is safe when we bind the parameters later.
286 * The parameter values aren't part of the SQL.
288 * @param string $sql An SQL string without the values
289 * @return string The input SQL string modified if necessary.
291 public static function clean_query($sql) {
292 $search = ["\t", "\n", "\r", " "];
293 $replace = [' ', ' ', ' ', ' '];
296 $sql = str_replace($search, $replace, $sql);
297 } while ($oldsql != $sql);
304 * @brief Replaces the ? placeholders with the parameters in the $args array
306 * @param string $sql SQL query
307 * @param array $args The parameters that are to replace the ? placeholders
308 * @return string The replaced SQL query
310 private static function replaceParameters($sql, $args) {
312 foreach ($args AS $param => $value) {
313 if (is_int($args[$param]) || is_float($args[$param])) {
314 $replace = intval($args[$param]);
316 $replace = "'".self::escape($args[$param])."'";
319 $pos = strpos($sql, '?', $offset);
320 if ($pos !== false) {
321 $sql = substr_replace($sql, $replace, $pos, 1);
323 $offset = $pos + strlen($replace);
329 * @brief Convert parameter array to an universal form
330 * @param array $args Parameter array
331 * @return array universalized parameter array
333 private static function getParam($args) {
336 // When the second function parameter is an array then use this as the parameter array
337 if ((count($args) > 0) && (is_array($args[1]))) {
345 * @brief Executes a prepared statement that returns data
346 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
348 * Please only use it with complicated queries.
349 * For all regular queries please use dba::select or dba::exists
351 * @param string $sql SQL statement
352 * @return bool|object statement object
354 public static function p($sql) {
357 $stamp1 = microtime(true);
359 $params = self::getParam(func_get_args());
361 // Renumber the array keys to be sure that they fit
364 foreach ($params AS $param) {
365 // Avoid problems with some MySQL servers and boolean values. See issue #3645
366 if (is_bool($param)) {
367 $param = (int)$param;
369 $args[++$i] = $param;
372 if (!self::$connected) {
376 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
377 // Question: Should we continue or stop the query here?
378 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
381 $sql = self::clean_query($sql);
382 $sql = self::any_value_fallback($sql);
386 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
387 $sql = "/*".System::callstack()." */ ".$sql;
392 self::$affected_rows = 0;
394 // We have to make some things different if this function is called from "e"
395 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
397 if (isset($trace[1])) {
398 $called_from = $trace[1];
400 // We use just something that is defined to avoid warnings
401 $called_from = $trace[0];
403 // We are having an own error logging in the function "e"
404 $called_from_e = ($called_from['function'] == 'e');
406 switch (self::$driver) {
408 // If there are no arguments we use "query"
409 if (count($args) == 0) {
410 if (!$retval = self::$db->query($sql)) {
411 $errorInfo = self::$db->errorInfo();
412 self::$error = $errorInfo[2];
413 self::$errorno = $errorInfo[1];
417 self::$affected_rows = $retval->rowCount();
421 if (!$stmt = self::$db->prepare($sql)) {
422 $errorInfo = self::$db->errorInfo();
423 self::$error = $errorInfo[2];
424 self::$errorno = $errorInfo[1];
429 foreach ($args AS $param => $value) {
430 $stmt->bindParam($param, $args[$param]);
433 if (!$stmt->execute()) {
434 $errorInfo = $stmt->errorInfo();
435 self::$error = $errorInfo[2];
436 self::$errorno = $errorInfo[1];
440 self::$affected_rows = $retval->rowCount();
444 // There are SQL statements that cannot be executed with a prepared statement
445 $parts = explode(' ', $orig_sql);
446 $command = strtolower($parts[0]);
447 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
449 // The fallback routine is called as well when there are no arguments
450 if (!$can_be_prepared || (count($args) == 0)) {
451 $retval = self::$db->query(self::replaceParameters($sql, $args));
452 if (self::$db->errno) {
453 self::$error = self::$db->error;
454 self::$errorno = self::$db->errno;
457 if (isset($retval->num_rows)) {
458 self::$affected_rows = $retval->num_rows;
460 self::$affected_rows = self::$db->affected_rows;
466 $stmt = self::$db->stmt_init();
468 if (!$stmt->prepare($sql)) {
469 self::$error = $stmt->error;
470 self::$errorno = $stmt->errno;
477 foreach ($args AS $param => $value) {
478 if (is_int($args[$param])) {
480 } elseif (is_float($args[$param])) {
482 } elseif (is_string($args[$param])) {
487 $values[] = &$args[$param];
490 if (count($values) > 0) {
491 array_unshift($values, $param_types);
492 call_user_func_array([$stmt, 'bind_param'], $values);
495 if (!$stmt->execute()) {
496 self::$error = self::$db->error;
497 self::$errorno = self::$db->errno;
500 $stmt->store_result();
502 self::$affected_rows = $retval->affected_rows;
507 // We are having an own error logging in the function "e"
508 if ((self::$errorno != 0) && !$called_from_e) {
509 // We have to preserve the error code, somewhere in the logging it get lost
510 $error = self::$error;
511 $errorno = self::$errorno;
513 logger('DB Error '.self::$errorno.': '.self::$error."\n".
514 System::callstack(8)."\n".self::replaceParameters($sql, $args));
516 // On a lost connection we try to reconnect - but only once.
517 if ($errorno == 2006) {
518 if (self::$in_retrial || !self::reconnect()) {
519 // It doesn't make sense to continue when the database connection was lost
520 if (self::$in_retrial) {
521 logger('Giving up retrial because of database error '.$errorno.': '.$error);
523 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
528 logger('Reconnected after database error '.$errorno.': '.$error);
529 self::$in_retrial = true;
530 $ret = self::p($sql, $args);
531 self::$in_retrial = false;
536 self::$error = $error;
537 self::$errorno = $errorno;
540 $a->save_timestamp($stamp1, 'database');
542 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
544 $stamp2 = microtime(true);
545 $duration = (float)($stamp2 - $stamp1);
547 if (($duration > $a->config["system"]["db_loglimit"])) {
548 $duration = round($duration, 3);
549 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
551 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
552 basename($backtrace[1]["file"])."\t".
553 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
554 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
561 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
563 * Please use dba::delete, dba::insert, dba::update, ... instead
565 * @param string $sql SQL statement
566 * @return boolean Was the query successfull? False is returned only if an error occurred
568 public static function e($sql) {
571 $stamp = microtime(true);
573 $params = self::getParam(func_get_args());
575 // In a case of a deadlock we are repeating the query 20 times
579 $stmt = self::p($sql, $params);
581 if (is_bool($stmt)) {
583 } elseif (is_object($stmt)) {
591 } while ((self::$errorno == 1213) && (--$timeout > 0));
593 if (self::$errorno != 0) {
594 // We have to preserve the error code, somewhere in the logging it get lost
595 $error = self::$error;
596 $errorno = self::$errorno;
598 logger('DB Error '.self::$errorno.': '.self::$error."\n".
599 System::callstack(8)."\n".self::replaceParameters($sql, $params));
601 self::$error = $error;
602 self::$errorno = $errorno;
605 $a->save_timestamp($stamp, "database_write");
611 * @brief Check if data exists
613 * @param string $table Table name
614 * @param array $condition array of fields for condition
616 * @return boolean Are there rows for that condition?
618 public static function exists($table, $condition) {
626 $first_key = key($condition);
627 if (!is_int($first_key)) {
628 $fields = [$first_key];
631 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
633 if (is_bool($stmt)) {
636 $retval = (self::num_rows($stmt) > 0);
645 * Fetches the first row
647 * Please use dba::selectFirst or dba::exists whenever this is possible.
649 * @brief Fetches the first row
650 * @param string $sql SQL statement
651 * @return array first row of query
653 public static function fetch_first($sql) {
654 $params = self::getParam(func_get_args());
656 $stmt = self::p($sql, $params);
658 if (is_bool($stmt)) {
661 $retval = self::fetch($stmt);
670 * @brief Returns the number of affected rows of the last statement
672 * @return int Number of rows
674 public static function affected_rows() {
675 return self::$affected_rows;
679 * @brief Returns the number of columns of a statement
681 * @param object Statement object
682 * @return int Number of columns
684 public static function columnCount($stmt) {
685 if (!is_object($stmt)) {
688 switch (self::$driver) {
690 return $stmt->columnCount();
692 return $stmt->field_count;
697 * @brief Returns the number of rows of a statement
699 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
700 * @return int Number of rows
702 public static function num_rows($stmt) {
703 if (!is_object($stmt)) {
706 switch (self::$driver) {
708 return $stmt->rowCount();
710 return $stmt->num_rows;
716 * @brief Fetch a single row
718 * @param mixed $stmt statement object
719 * @return array current row
721 public static function fetch($stmt) {
724 $stamp1 = microtime(true);
728 if (!is_object($stmt)) {
732 switch (self::$driver) {
734 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
737 if (get_class($stmt) == 'mysqli_result') {
738 $columns = $stmt->fetch_assoc();
742 // This code works, but is slow
744 // Bind the result to a result array
748 for ($x = 0; $x < $stmt->field_count; $x++) {
749 $cols[] = &$cols_num[$x];
752 call_user_func_array([$stmt, 'bind_result'], $cols);
754 if (!$stmt->fetch()) {
759 // We need to get the field names for the array keys
760 // It seems that there is no better way to do this.
761 $result = $stmt->result_metadata();
762 $fields = $result->fetch_fields();
764 foreach ($cols_num AS $param => $col) {
765 $columns[$fields[$param]->name] = $col;
769 $a->save_timestamp($stamp1, 'database');
775 * @brief Insert a row into a table
777 * @param string $table Table name
778 * @param array $param parameter array
779 * @param bool $on_duplicate_update Do an update on a duplicate entry
781 * @return boolean was the insert successfull?
783 public static function insert($table, $param, $on_duplicate_update = false) {
785 if (empty($table) || empty($param)) {
786 logger('Table and fields have to be set');
790 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
791 substr(str_repeat("?, ", count($param)), 0, -2).")";
793 if ($on_duplicate_update) {
794 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
796 $values = array_values($param);
797 $param = array_merge_recursive($values, $values);
800 return self::e($sql, $param);
804 * @brief Fetch the id of the last insert command
806 * @return integer Last inserted id
808 public static function lastInsertId() {
809 switch (self::$driver) {
811 $id = self::$db->lastInsertId();
814 $id = self::$db->insert_id;
821 * @brief Locks a table for exclusive write access
823 * This function can be extended in the future to accept a table array as well.
825 * @param string $table Table name
827 * @return boolean was the lock successful?
829 public static function lock($table) {
830 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
831 self::e("SET autocommit=0");
832 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
834 self::e("SET autocommit=1");
836 self::$in_transaction = true;
842 * @brief Unlocks all locked tables
844 * @return boolean was the unlock successful?
846 public static function unlock() {
847 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
849 $success = self::e("UNLOCK TABLES");
850 self::e("SET autocommit=1");
851 self::$in_transaction = false;
856 * @brief Starts a transaction
858 * @return boolean Was the command executed successfully?
860 public static function transaction() {
861 if (!self::e('COMMIT')) {
864 if (!self::e('START TRANSACTION')) {
867 self::$in_transaction = true;
872 * @brief Does a commit
874 * @return boolean Was the command executed successfully?
876 public static function commit() {
877 if (!self::e('COMMIT')) {
880 self::$in_transaction = false;
885 * @brief Does a rollback
887 * @return boolean Was the command executed successfully?
889 public static function rollback() {
890 if (!self::e('ROLLBACK')) {
893 self::$in_transaction = false;
898 * @brief Build the array with the table relations
900 * The array is build from the database definitions in DBStructure.php
902 * This process must only be started once, since the value is cached.
904 private static function buildRelationData() {
905 $definition = DBStructure::definition();
907 foreach ($definition AS $table => $structure) {
908 foreach ($structure['fields'] AS $field => $field_struct) {
909 if (isset($field_struct['relation'])) {
910 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
911 self::$relation[$rel_table][$rel_field][$table][] = $field;
919 * @brief Delete a row from a table
921 * @param string $table Table name
922 * @param array $conditions Field condition(s)
923 * @param array $options
924 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
925 * relations (default: true)
926 * @param boolean $in_process Internal use: Only do a commit after the last delete
927 * @param array $callstack Internal use: prevent endless loops
929 * @return boolean|array was the delete successful? When $in_process is set: deletion data
931 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
933 if (empty($table) || empty($conditions)) {
934 logger('Table and conditions have to be set');
940 // Create a key for the loop prevention
941 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
943 // We quit when this key already exists in the callstack.
944 if (isset($callstack[$key])) {
948 $callstack[$key] = true;
950 $table = self::escape($table);
952 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
954 $cascade = defaults($options, 'cascade', true);
956 // To speed up the whole process we cache the table relations
957 if ($cascade && count(self::$relation) == 0) {
958 self::buildRelationData();
961 // Is there a relation entry for the table?
962 if ($cascade && isset(self::$relation[$table])) {
963 // We only allow a simple "one field" relation.
964 $field = array_keys(self::$relation[$table])[0];
965 $rel_def = array_values(self::$relation[$table])[0];
967 // Create a key for preventing double queries
968 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
970 // When the search field is the relation field, we don't need to fetch the rows
971 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
972 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
973 foreach ($rel_def AS $rel_table => $rel_fields) {
974 foreach ($rel_fields AS $rel_field) {
975 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
976 $commands = array_merge($commands, $retval);
979 // We quit when this key already exists in the callstack.
980 } elseif (!isset($callstack[$qkey])) {
982 $callstack[$qkey] = true;
984 // Fetch all rows that are to be deleted
985 $data = self::select($table, [$field], $conditions);
987 while ($row = self::fetch($data)) {
988 // Now we accumulate the delete commands
989 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
990 $commands = array_merge($commands, $retval);
995 // Since we had split the delete command we don't need the original command anymore
996 unset($commands[$key]);
1001 // Now we finalize the process
1002 $do_transaction = !self::$in_transaction;
1004 if ($do_transaction) {
1005 self::transaction();
1011 foreach ($commands AS $command) {
1012 $conditions = $command['conditions'];
1014 $first_key = key($conditions);
1016 $condition_string = self::buildCondition($conditions);
1018 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1019 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1020 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1022 if (!self::e($sql, $conditions)) {
1023 if ($do_transaction) {
1029 $key_table = $command['table'];
1030 $key_condition = array_keys($command['conditions'])[0];
1031 $value = array_values($command['conditions'])[0];
1033 // Split the SQL queries in chunks of 100 values
1034 // We do the $i stuff here to make the code better readable
1035 $i = $counter[$key_table][$key_condition];
1036 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1040 $compacted[$key_table][$key_condition][$i][$value] = $value;
1041 $counter[$key_table][$key_condition] = $i;
1044 foreach ($compacted AS $table => $values) {
1045 foreach ($values AS $field => $field_value_list) {
1046 foreach ($field_value_list AS $field_values) {
1047 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1048 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1050 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1052 if (!self::e($sql, $field_values)) {
1053 if ($do_transaction) {
1061 if ($do_transaction) {
1071 * @brief Updates rows
1073 * Updates rows in the database. When $old_fields is set to an array,
1074 * the system will only do an update if the fields in that array changed.
1077 * Only the values in $old_fields are compared.
1078 * This is an intentional behaviour.
1081 * We include the timestamp field in $fields but not in $old_fields.
1082 * Then the row will only get the new timestamp when the other fields had changed.
1084 * When $old_fields is set to a boolean value the system will do this compare itself.
1085 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1088 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1089 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1091 * @param string $table Table name
1092 * @param array $fields contains the fields that are updated
1093 * @param array $condition condition array with the key values
1094 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1096 * @return boolean was the update successfull?
1098 public static function update($table, $fields, $condition, $old_fields = []) {
1100 if (empty($table) || empty($fields) || empty($condition)) {
1101 logger('Table, fields and condition have to be set');
1105 $table = self::escape($table);
1107 $condition_string = self::buildCondition($condition);
1109 if (is_bool($old_fields)) {
1110 $do_insert = $old_fields;
1112 $old_fields = self::selectFirst($table, [], $condition);
1114 if (is_bool($old_fields)) {
1116 $values = array_merge($condition, $fields);
1117 return self::insert($table, $values, $do_insert);
1123 $do_update = (count($old_fields) == 0);
1125 foreach ($old_fields AS $fieldname => $content) {
1126 if (isset($fields[$fieldname])) {
1127 if ($fields[$fieldname] == $content) {
1128 unset($fields[$fieldname]);
1135 if (!$do_update || (count($fields) == 0)) {
1139 $sql = "UPDATE `".$table."` SET `".
1140 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1142 $params1 = array_values($fields);
1143 $params2 = array_values($condition);
1144 $params = array_merge_recursive($params1, $params2);
1146 return self::e($sql, $params);
1150 * Retrieve a single record from a table and returns it in an associative array
1152 * @brief Retrieve a single record from a table
1153 * @param string $table
1154 * @param array $fields
1155 * @param array $condition
1156 * @param array $params
1157 * @return bool|array
1160 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1162 $params['limit'] = 1;
1163 $result = self::select($table, $fields, $condition, $params);
1165 if (is_bool($result)) {
1168 $row = self::fetch($result);
1169 self::close($result);
1175 * @brief Select rows from a table
1177 * @param string $table Table name
1178 * @param array $fields Array of selected fields, empty for all
1179 * @param array $condition Array of fields for condition
1180 * @param array $params Array of several parameters
1182 * @return boolean|object
1186 * $fields = array("id", "uri", "uid", "network");
1188 * $condition = array("uid" => 1, "network" => 'dspr');
1190 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1192 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1194 * $data = dba::select($table, $fields, $condition, $params);
1196 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1202 $table = self::escape($table);
1204 if (count($fields) > 0) {
1205 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1207 $select_fields = "*";
1210 $condition_string = self::buildCondition($condition);
1212 $param_string = self::buildParameter($params);
1214 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1216 $result = self::p($sql, $condition);
1222 * @brief Counts the rows from a table satisfying the provided condition
1224 * @param string $table Table name
1225 * @param array $condition array of fields for condition
1232 * $condition = ["uid" => 1, "network" => 'dspr'];
1234 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1236 * $count = dba::count($table, $condition);
1238 public static function count($table, array $condition = [])
1244 $condition_string = self::buildCondition($condition);
1246 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1248 $row = self::fetch_first($sql, $condition);
1250 return $row['count'];
1254 * @brief Returns the SQL condition string built from the provided condition array
1256 * This function operates with two modes.
1257 * - Supplied with a filed/value associative array, it builds simple strict
1258 * equality conditions linked by AND.
1259 * - Supplied with a flat list, the first element is the condition string and
1260 * the following arguments are the values to be interpolated
1262 * $condition = ["uid" => 1, "network" => 'dspr'];
1264 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1266 * In either case, the provided array is left with the parameters only
1268 * @param array $condition
1271 public static function buildCondition(array &$condition = [])
1273 $condition_string = '';
1274 if (count($condition) > 0) {
1276 $first_key = key($condition);
1277 if (is_int($first_key)) {
1278 $condition_string = " WHERE (" . array_shift($condition) . ")";
1281 $condition_string = "";
1282 foreach ($condition as $field => $value) {
1283 if ($condition_string != "") {
1284 $condition_string .= " AND ";
1286 if (is_array($value)) {
1287 $new_values = array_merge($new_values, array_values($value));
1288 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1289 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1291 $new_values[$field] = $value;
1292 $condition_string .= "`" . $field . "` = ?";
1295 $condition_string = " WHERE (" . $condition_string . ")";
1296 $condition = $new_values;
1300 return $condition_string;
1304 * @brief Returns the SQL parameter string built from the provided parameter array
1306 * @param array $params
1309 public static function buildParameter(array $params = [])
1312 if (isset($params['order'])) {
1313 $order_string = " ORDER BY ";
1314 foreach ($params['order'] AS $fields => $order) {
1315 if (!is_int($fields)) {
1316 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1318 $order_string .= "`" . $order . "`, ";
1321 $order_string = substr($order_string, 0, -2);
1325 if (isset($params['limit']) && is_int($params['limit'])) {
1326 $limit_string = " LIMIT " . $params['limit'];
1329 if (isset($params['limit']) && is_array($params['limit'])) {
1330 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1333 return $order_string.$limit_string;
1337 * @brief Fills an array with data from a query
1339 * @param object $stmt statement object
1340 * @return array Data array
1342 public static function inArray($stmt, $do_close = true) {
1343 if (is_bool($stmt)) {
1348 while ($row = self::fetch($stmt)) {
1358 * @brief Returns the error number of the last query
1360 * @return string Error number (0 if no error)
1362 public static function errorNo() {
1363 return self::$errorno;
1367 * @brief Returns the error message of the last query
1369 * @return string Error message ('' if no error)
1371 public static function errorMessage() {
1372 return self::$error;
1376 * @brief Closes the current statement
1378 * @param object $stmt statement object
1379 * @return boolean was the close successful?
1381 public static function close($stmt) {
1384 $stamp1 = microtime(true);
1386 if (!is_object($stmt)) {
1390 switch (self::$driver) {
1392 $ret = $stmt->closeCursor();
1395 $stmt->free_result();
1396 $ret = $stmt->close();
1400 $a->save_timestamp($stamp1, 'database');
1406 function dbesc($str) {
1407 if (dba::$connected) {
1408 return(dba::escape($str));
1410 return(str_replace("'","\\'",$str));
1415 * @brief execute SQL query with printf style args - deprecated
1417 * Please use the dba:: functions instead:
1418 * dba::select, dba::exists, dba::insert
1419 * dba::delete, dba::update, dba::p, dba::e
1421 * @param $args Query parameters (1 to N parameters of different types)
1422 * @return array|bool Query array
1425 $args = func_get_args();
1428 if (!dba::$connected) {
1432 $sql = dba::clean_query($sql);
1433 $sql = dba::any_value_fallback($sql);
1435 $stmt = @vsprintf($sql, $args);
1437 $ret = dba::p($stmt);
1439 if (is_bool($ret)) {
1443 $columns = dba::columnCount($ret);
1445 $data = dba::inArray($ret);
1447 if ((count($data) == 0) && ($columns == 0)) {
1454 function dba_timer() {
1455 return microtime(true);