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 = [];
29 public static function connect($serveraddr, $user, $pass, $db) {
30 if (!is_null(self::$db)) {
36 $stamp1 = microtime(true);
38 $serveraddr = trim($serveraddr);
40 $serverdata = explode(':', $serveraddr);
41 $server = $serverdata[0];
43 if (count($serverdata) > 1) {
44 $port = trim($serverdata[1]);
47 $server = trim($server);
52 if (!(strlen($server) && strlen($user))) {
57 if ($a->mode == App::MODE_INSTALL) {
58 // server has to be a non-empty string that is not 'localhost' and not an IP
59 if (strlen($server) && ($server !== 'localhost') && filter_var($server, FILTER_VALIDATE_IP) === false) {
60 if (! dns_get_record($server, DNS_A + DNS_CNAME)) {
61 self::$error = L10n::t('Cannot locate DNS info for database server \'%s\'', $server);
67 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
68 self::$driver = 'pdo';
69 $connect = "mysql:host=".$server.";dbname=".$db;
72 $connect .= ";port=".$port;
75 if (isset($a->config["system"]["db_charset"])) {
76 $connect .= ";charset=".$a->config["system"]["db_charset"];
79 self::$db = @new PDO($connect, $user, $pass);
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;
107 public static function reconnect() {
108 // This variable is only defined here again to prevent warning messages
109 // It is a local variable and should hopefully not interfere with the global one.
110 $a = new App(dirname(__DIR__));
112 // We have to the the variable to "null" to force a new connection
114 include '.htconfig.php';
116 $ret = self::connect($db_host, $db_user, $db_pass, $db_data);
117 unset($db_host, $db_user, $db_pass, $db_data);
123 * @brief Returns the MySQL server version string
125 * This function discriminate between the deprecated mysql API and the current
126 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
130 public static function server_info() {
131 if (self::$_server_info == '') {
132 switch (self::$driver) {
134 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
137 self::$_server_info = self::$db->server_info;
141 return self::$_server_info;
145 * @brief Returns the selected database name
149 public static function database_name() {
150 $ret = self::p("SELECT DATABASE() AS `db`");
151 $data = self::inArray($ret);
152 return $data[0]['db'];
156 * @brief Analyze a database query and log this if some conditions are met.
158 * @param string $query The database query that will be analyzed
160 private static function logIndex($query) {
163 if (empty($a->config["system"]["db_log_index"])) {
167 // Don't explain an explain statement
168 if (strtolower(substr($query, 0, 7)) == "explain") {
172 // Only do the explain on "select", "update" and "delete"
173 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
177 $r = self::p("EXPLAIN ".$query);
178 if (!DBM::is_result($r)) {
182 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
183 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
185 while ($row = dba::fetch($r)) {
186 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
187 $log = (in_array($row['key'], $watchlist) &&
188 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
193 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
197 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
202 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
203 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
204 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
205 basename($backtrace[1]["file"])."\t".
206 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
207 substr($query, 0, 2000)."\n", FILE_APPEND);
212 public static function escape($str) {
213 switch (self::$driver) {
215 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
217 return @self::$db->real_escape_string($str);
221 public static function connected() {
224 switch (self::$driver) {
226 $r = dba::p("SELECT 1");
227 if (DBM::is_result($r)) {
228 $row = dba::inArray($r);
229 $connected = ($row[0]['1'] == '1');
233 $connected = self::$db->ping();
240 * @brief Replaces ANY_VALUE() function by MIN() function,
241 * if the database server does not support ANY_VALUE().
243 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
244 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
245 * A standard fall-back is to use MIN().
247 * @param string $sql An SQL string without the values
248 * @return string The input SQL string modified if necessary.
250 public static function any_value_fallback($sql) {
251 $server_info = self::server_info();
252 if (version_compare($server_info, '5.7.5', '<') ||
253 (stripos($server_info, 'MariaDB') !== false)) {
254 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
260 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
262 * This is safe when we bind the parameters later.
263 * The parameter values aren't part of the SQL.
265 * @param string $sql An SQL string without the values
266 * @return string The input SQL string modified if necessary.
268 public static function clean_query($sql) {
269 $search = ["\t", "\n", "\r", " "];
270 $replace = [' ', ' ', ' ', ' '];
273 $sql = str_replace($search, $replace, $sql);
274 } while ($oldsql != $sql);
281 * @brief Replaces the ? placeholders with the parameters in the $args array
283 * @param string $sql SQL query
284 * @param array $args The parameters that are to replace the ? placeholders
285 * @return string The replaced SQL query
287 private static function replaceParameters($sql, $args) {
289 foreach ($args AS $param => $value) {
290 if (is_int($args[$param]) || is_float($args[$param])) {
291 $replace = intval($args[$param]);
293 $replace = "'".self::escape($args[$param])."'";
296 $pos = strpos($sql, '?', $offset);
297 if ($pos !== false) {
298 $sql = substr_replace($sql, $replace, $pos, 1);
300 $offset = $pos + strlen($replace);
306 * @brief Convert parameter array to an universal form
307 * @param array $args Parameter array
308 * @return array universalized parameter array
310 private static function getParam($args) {
313 // When the second function parameter is an array then use this as the parameter array
314 if ((count($args) > 0) && (is_array($args[1]))) {
322 * @brief Executes a prepared statement that returns data
323 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
325 * Please only use it with complicated queries.
326 * For all regular queries please use dba::select or dba::exists
328 * @param string $sql SQL statement
329 * @return bool|object statement object
331 public static function p($sql) {
334 $stamp1 = microtime(true);
336 $params = self::getParam(func_get_args());
338 // Renumber the array keys to be sure that they fit
341 foreach ($params AS $param) {
342 // Avoid problems with some MySQL servers and boolean values. See issue #3645
343 if (is_bool($param)) {
344 $param = (int)$param;
346 $args[++$i] = $param;
349 if (!self::$connected) {
353 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
354 // Question: Should we continue or stop the query here?
355 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
358 $sql = self::clean_query($sql);
359 $sql = self::any_value_fallback($sql);
363 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
364 $sql = "/*".System::callstack()." */ ".$sql;
369 self::$affected_rows = 0;
371 // We have to make some things different if this function is called from "e"
372 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
374 if (isset($trace[1])) {
375 $called_from = $trace[1];
377 // We use just something that is defined to avoid warnings
378 $called_from = $trace[0];
380 // We are having an own error logging in the function "e"
381 $called_from_e = ($called_from['function'] == 'e');
383 switch (self::$driver) {
385 // If there are no arguments we use "query"
386 if (count($args) == 0) {
387 if (!$retval = self::$db->query($sql)) {
388 $errorInfo = self::$db->errorInfo();
389 self::$error = $errorInfo[2];
390 self::$errorno = $errorInfo[1];
394 self::$affected_rows = $retval->rowCount();
398 if (!$stmt = self::$db->prepare($sql)) {
399 $errorInfo = self::$db->errorInfo();
400 self::$error = $errorInfo[2];
401 self::$errorno = $errorInfo[1];
406 foreach ($args AS $param => $value) {
407 $stmt->bindParam($param, $args[$param]);
410 if (!$stmt->execute()) {
411 $errorInfo = $stmt->errorInfo();
412 self::$error = $errorInfo[2];
413 self::$errorno = $errorInfo[1];
417 self::$affected_rows = $retval->rowCount();
421 // There are SQL statements that cannot be executed with a prepared statement
422 $parts = explode(' ', $orig_sql);
423 $command = strtolower($parts[0]);
424 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
426 // The fallback routine is called as well when there are no arguments
427 if (!$can_be_prepared || (count($args) == 0)) {
428 $retval = self::$db->query(self::replaceParameters($sql, $args));
429 if (self::$db->errno) {
430 self::$error = self::$db->error;
431 self::$errorno = self::$db->errno;
434 if (isset($retval->num_rows)) {
435 self::$affected_rows = $retval->num_rows;
437 self::$affected_rows = self::$db->affected_rows;
443 $stmt = self::$db->stmt_init();
445 if (!$stmt->prepare($sql)) {
446 self::$error = $stmt->error;
447 self::$errorno = $stmt->errno;
454 foreach ($args AS $param => $value) {
455 if (is_int($args[$param])) {
457 } elseif (is_float($args[$param])) {
459 } elseif (is_string($args[$param])) {
464 $values[] = &$args[$param];
467 if (count($values) > 0) {
468 array_unshift($values, $params);
469 call_user_func_array([$stmt, 'bind_param'], $values);
472 if (!$stmt->execute()) {
473 self::$error = self::$db->error;
474 self::$errorno = self::$db->errno;
477 $stmt->store_result();
479 self::$affected_rows = $retval->affected_rows;
484 // We are having an own error logging in the function "e"
485 if ((self::$errorno != 0) && !$called_from_e) {
486 // We have to preserve the error code, somewhere in the logging it get lost
487 $error = self::$error;
488 $errorno = self::$errorno;
490 logger('DB Error '.self::$errorno.': '.self::$error."\n".
491 System::callstack(8)."\n".self::replaceParameters($sql, $params));
493 // On a lost connection we try to reconnect - but only once.
494 if ($errorno == 2006) {
495 if (self::$in_retrial || !self::reconnect()) {
496 // It doesn't make sense to continue when the database connection was lost
497 logger('Giving up because of database error '.$errorno.': '.$error);
501 logger('Reconnected after database error '.$errorno.': '.$error);
502 self::$in_retrial = true;
503 return self::p($sql, $params);
507 self::$error = $error;
508 self::$errorno = $errorno;
511 $a->save_timestamp($stamp1, 'database');
513 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
515 $stamp2 = microtime(true);
516 $duration = (float)($stamp2 - $stamp1);
518 if (($duration > $a->config["system"]["db_loglimit"])) {
519 $duration = round($duration, 3);
520 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
522 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
523 basename($backtrace[1]["file"])."\t".
524 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
525 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
532 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
534 * Please use dba::delete, dba::insert, dba::update, ... instead
536 * @param string $sql SQL statement
537 * @return boolean Was the query successfull? False is returned only if an error occurred
539 public static function e($sql) {
542 $stamp = microtime(true);
544 $params = self::getParam(func_get_args());
546 // In a case of a deadlock we are repeating the query 20 times
550 $stmt = self::p($sql, $params);
552 if (is_bool($stmt)) {
554 } elseif (is_object($stmt)) {
562 } while ((self::$errorno == 1213) && (--$timeout > 0));
564 if (self::$errorno != 0) {
565 // We have to preserve the error code, somewhere in the logging it get lost
566 $error = self::$error;
567 $errorno = self::$errorno;
569 logger('DB Error '.self::$errorno.': '.self::$error."\n".
570 System::callstack(8)."\n".self::replaceParameters($sql, $params));
572 self::$error = $error;
573 self::$errorno = $errorno;
576 $a->save_timestamp($stamp, "database_write");
582 * @brief Check if data exists
584 * @param string $table Table name
585 * @param array $condition array of fields for condition
587 * @return boolean Are there rows for that condition?
589 public static function exists($table, $condition) {
597 $first_key = key($condition);
598 if (!is_int($first_key)) {
599 $fields = [$first_key];
602 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
604 if (is_bool($stmt)) {
607 $retval = (self::num_rows($stmt) > 0);
616 * Fetches the first row
618 * Please use dba::selectFirst or dba::exists whenever this is possible.
620 * @brief Fetches the first row
621 * @param string $sql SQL statement
622 * @return array first row of query
624 public static function fetch_first($sql) {
625 $params = self::getParam(func_get_args());
627 $stmt = self::p($sql, $params);
629 if (is_bool($stmt)) {
632 $retval = self::fetch($stmt);
641 * @brief Returns the number of affected rows of the last statement
643 * @return int Number of rows
645 public static function affected_rows() {
646 return self::$affected_rows;
650 * @brief Returns the number of columns of a statement
652 * @param object Statement object
653 * @return int Number of columns
655 public static function columnCount($stmt) {
656 if (!is_object($stmt)) {
659 switch (self::$driver) {
661 return $stmt->columnCount();
663 return $stmt->field_count;
668 * @brief Returns the number of rows of a statement
670 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
671 * @return int Number of rows
673 public static function num_rows($stmt) {
674 if (!is_object($stmt)) {
677 switch (self::$driver) {
679 return $stmt->rowCount();
681 return $stmt->num_rows;
687 * @brief Fetch a single row
689 * @param mixed $stmt statement object
690 * @return array current row
692 public static function fetch($stmt) {
695 $stamp1 = microtime(true);
699 if (!is_object($stmt)) {
703 switch (self::$driver) {
705 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
708 if (get_class($stmt) == 'mysqli_result') {
709 $columns = $stmt->fetch_assoc();
713 // This code works, but is slow
715 // Bind the result to a result array
719 for ($x = 0; $x < $stmt->field_count; $x++) {
720 $cols[] = &$cols_num[$x];
723 call_user_func_array([$stmt, 'bind_result'], $cols);
725 if (!$stmt->fetch()) {
730 // We need to get the field names for the array keys
731 // It seems that there is no better way to do this.
732 $result = $stmt->result_metadata();
733 $fields = $result->fetch_fields();
735 foreach ($cols_num AS $param => $col) {
736 $columns[$fields[$param]->name] = $col;
740 $a->save_timestamp($stamp1, 'database');
746 * @brief Insert a row into a table
748 * @param string $table Table name
749 * @param array $param parameter array
750 * @param bool $on_duplicate_update Do an update on a duplicate entry
752 * @return boolean was the insert successfull?
754 public static function insert($table, $param, $on_duplicate_update = false) {
756 if (empty($table) || empty($param)) {
757 logger('Table and fields have to be set');
761 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
762 substr(str_repeat("?, ", count($param)), 0, -2).")";
764 if ($on_duplicate_update) {
765 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
767 $values = array_values($param);
768 $param = array_merge_recursive($values, $values);
771 return self::e($sql, $param);
775 * @brief Fetch the id of the last insert command
777 * @return integer Last inserted id
779 public static function lastInsertId() {
780 switch (self::$driver) {
782 $id = self::$db->lastInsertId();
785 $id = self::$db->insert_id;
792 * @brief Locks a table for exclusive write access
794 * This function can be extended in the future to accept a table array as well.
796 * @param string $table Table name
798 * @return boolean was the lock successful?
800 public static function lock($table) {
801 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
802 self::e("SET autocommit=0");
803 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
805 self::e("SET autocommit=1");
807 self::$in_transaction = true;
813 * @brief Unlocks all locked tables
815 * @return boolean was the unlock successful?
817 public static function unlock() {
818 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
820 $success = self::e("UNLOCK TABLES");
821 self::e("SET autocommit=1");
822 self::$in_transaction = false;
827 * @brief Starts a transaction
829 * @return boolean Was the command executed successfully?
831 public static function transaction() {
832 if (!self::e('COMMIT')) {
835 if (!self::e('START TRANSACTION')) {
838 self::$in_transaction = true;
843 * @brief Does a commit
845 * @return boolean Was the command executed successfully?
847 public static function commit() {
848 if (!self::e('COMMIT')) {
851 self::$in_transaction = false;
856 * @brief Does a rollback
858 * @return boolean Was the command executed successfully?
860 public static function rollback() {
861 if (!self::e('ROLLBACK')) {
864 self::$in_transaction = false;
869 * @brief Build the array with the table relations
871 * The array is build from the database definitions in DBStructure.php
873 * This process must only be started once, since the value is cached.
875 private static function buildRelationData() {
876 $definition = DBStructure::definition();
878 foreach ($definition AS $table => $structure) {
879 foreach ($structure['fields'] AS $field => $field_struct) {
880 if (isset($field_struct['relation'])) {
881 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
882 self::$relation[$rel_table][$rel_field][$table][] = $field;
890 * @brief Delete a row from a table
892 * @param string $table Table name
893 * @param array $conditions Field condition(s)
894 * @param array $options
895 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
896 * relations (default: true)
897 * @param boolean $in_process Internal use: Only do a commit after the last delete
898 * @param array $callstack Internal use: prevent endless loops
900 * @return boolean|array was the delete successful? When $in_process is set: deletion data
902 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
904 if (empty($table) || empty($conditions)) {
905 logger('Table and conditions have to be set');
911 // Create a key for the loop prevention
912 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
914 // We quit when this key already exists in the callstack.
915 if (isset($callstack[$key])) {
919 $callstack[$key] = true;
921 $table = self::escape($table);
923 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
925 $cascade = defaults($options, 'cascade', true);
927 // To speed up the whole process we cache the table relations
928 if ($cascade && count(self::$relation) == 0) {
929 self::buildRelationData();
932 // Is there a relation entry for the table?
933 if ($cascade && isset(self::$relation[$table])) {
934 // We only allow a simple "one field" relation.
935 $field = array_keys(self::$relation[$table])[0];
936 $rel_def = array_values(self::$relation[$table])[0];
938 // Create a key for preventing double queries
939 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
941 // When the search field is the relation field, we don't need to fetch the rows
942 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
943 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
944 foreach ($rel_def AS $rel_table => $rel_fields) {
945 foreach ($rel_fields AS $rel_field) {
946 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
947 $commands = array_merge($commands, $retval);
950 // We quit when this key already exists in the callstack.
951 } elseif (!isset($callstack[$qkey])) {
953 $callstack[$qkey] = true;
955 // Fetch all rows that are to be deleted
956 $data = self::select($table, [$field], $conditions);
958 while ($row = self::fetch($data)) {
959 // Now we accumulate the delete commands
960 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
961 $commands = array_merge($commands, $retval);
966 // Since we had split the delete command we don't need the original command anymore
967 unset($commands[$key]);
972 // Now we finalize the process
973 $do_transaction = !self::$in_transaction;
975 if ($do_transaction) {
982 foreach ($commands AS $command) {
983 $conditions = $command['conditions'];
985 $first_key = key($conditions);
987 $condition_string = self::buildCondition($conditions);
989 if ((count($command['conditions']) > 1) || is_int($first_key)) {
990 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
991 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
993 if (!self::e($sql, $conditions)) {
994 if ($do_transaction) {
1000 $key_table = $command['table'];
1001 $key_condition = array_keys($command['conditions'])[0];
1002 $value = array_values($command['conditions'])[0];
1004 // Split the SQL queries in chunks of 100 values
1005 // We do the $i stuff here to make the code better readable
1006 $i = $counter[$key_table][$key_condition];
1007 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1011 $compacted[$key_table][$key_condition][$i][$value] = $value;
1012 $counter[$key_table][$key_condition] = $i;
1015 foreach ($compacted AS $table => $values) {
1016 foreach ($values AS $field => $field_value_list) {
1017 foreach ($field_value_list AS $field_values) {
1018 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1019 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1021 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1023 if (!self::e($sql, $field_values)) {
1024 if ($do_transaction) {
1032 if ($do_transaction) {
1042 * @brief Updates rows
1044 * Updates rows in the database. When $old_fields is set to an array,
1045 * the system will only do an update if the fields in that array changed.
1048 * Only the values in $old_fields are compared.
1049 * This is an intentional behaviour.
1052 * We include the timestamp field in $fields but not in $old_fields.
1053 * Then the row will only get the new timestamp when the other fields had changed.
1055 * When $old_fields is set to a boolean value the system will do this compare itself.
1056 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1059 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1060 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1062 * @param string $table Table name
1063 * @param array $fields contains the fields that are updated
1064 * @param array $condition condition array with the key values
1065 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1067 * @return boolean was the update successfull?
1069 public static function update($table, $fields, $condition, $old_fields = []) {
1071 if (empty($table) || empty($fields) || empty($condition)) {
1072 logger('Table, fields and condition have to be set');
1076 $table = self::escape($table);
1078 $condition_string = self::buildCondition($condition);
1080 if (is_bool($old_fields)) {
1081 $do_insert = $old_fields;
1083 $old_fields = self::selectFirst($table, [], $condition);
1085 if (is_bool($old_fields)) {
1087 $values = array_merge($condition, $fields);
1088 return self::insert($table, $values, $do_insert);
1094 $do_update = (count($old_fields) == 0);
1096 foreach ($old_fields AS $fieldname => $content) {
1097 if (isset($fields[$fieldname])) {
1098 if ($fields[$fieldname] == $content) {
1099 unset($fields[$fieldname]);
1106 if (!$do_update || (count($fields) == 0)) {
1110 $sql = "UPDATE `".$table."` SET `".
1111 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1113 $params1 = array_values($fields);
1114 $params2 = array_values($condition);
1115 $params = array_merge_recursive($params1, $params2);
1117 return self::e($sql, $params);
1121 * Retrieve a single record from a table and returns it in an associative array
1123 * @brief Retrieve a single record from a table
1124 * @param string $table
1125 * @param array $fields
1126 * @param array $condition
1127 * @param array $params
1128 * @return bool|array
1131 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1133 $params['limit'] = 1;
1134 $result = self::select($table, $fields, $condition, $params);
1136 if (is_bool($result)) {
1139 $row = self::fetch($result);
1140 self::close($result);
1146 * @brief Select rows from a table
1148 * @param string $table Table name
1149 * @param array $fields Array of selected fields, empty for all
1150 * @param array $condition Array of fields for condition
1151 * @param array $params Array of several parameters
1153 * @return boolean|object
1157 * $fields = array("id", "uri", "uid", "network");
1159 * $condition = array("uid" => 1, "network" => 'dspr');
1161 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1163 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1165 * $data = dba::select($table, $fields, $condition, $params);
1167 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1173 $table = self::escape($table);
1175 if (count($fields) > 0) {
1176 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1178 $select_fields = "*";
1181 $condition_string = self::buildCondition($condition);
1184 if (isset($params['order'])) {
1185 $order_string = " ORDER BY ";
1186 foreach ($params['order'] AS $fields => $order) {
1187 if (!is_int($fields)) {
1188 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1190 $order_string .= "`" . $order . "`, ";
1193 $order_string = substr($order_string, 0, -2);
1197 if (isset($params['limit']) && is_int($params['limit'])) {
1198 $limit_string = " LIMIT " . $params['limit'];
1201 if (isset($params['limit']) && is_array($params['limit'])) {
1202 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1205 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1207 $result = self::p($sql, $condition);
1213 * @brief Counts the rows from a table satisfying the provided condition
1215 * @param string $table Table name
1216 * @param array $condition array of fields for condition
1223 * $condition = ["uid" => 1, "network" => 'dspr'];
1225 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1227 * $count = dba::count($table, $condition);
1229 public static function count($table, array $condition = [])
1235 $condition_string = self::buildCondition($condition);
1237 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1239 $row = self::fetch_first($sql, $condition);
1241 return $row['count'];
1245 * @brief Returns the SQL condition string built from the provided condition array
1247 * This function operates with two modes.
1248 * - Supplied with a filed/value associative array, it builds simple strict
1249 * equality conditions linked by AND.
1250 * - Supplied with a flat list, the first element is the condition string and
1251 * the following arguments are the values to be interpolated
1253 * $condition = ["uid" => 1, "network" => 'dspr'];
1255 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1257 * In either case, the provided array is left with the parameters only
1259 * @param array $condition
1262 private static function buildCondition(array &$condition = [])
1264 $condition_string = '';
1265 if (count($condition) > 0) {
1267 $first_key = key($condition);
1268 if (is_int($first_key)) {
1269 $condition_string = " WHERE ".array_shift($condition);
1272 $condition_string = "";
1273 foreach ($condition as $field => $value) {
1274 if ($condition_string != "") {
1275 $condition_string .= " AND ";
1277 if (is_array($value)) {
1278 $new_values = array_merge($new_values, array_values($value));
1279 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1280 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1282 $new_values[$field] = $value;
1283 $condition_string .= "`" . $field . "` = ?";
1286 $condition_string = " WHERE " . $condition_string;
1287 $condition = $new_values;
1291 return $condition_string;
1295 * @brief Fills an array with data from a query
1297 * @param object $stmt statement object
1298 * @return array Data array
1300 public static function inArray($stmt, $do_close = true) {
1301 if (is_bool($stmt)) {
1306 while ($row = self::fetch($stmt)) {
1316 * @brief Returns the error number of the last query
1318 * @return string Error number (0 if no error)
1320 public static function errorNo() {
1321 return self::$errorno;
1325 * @brief Returns the error message of the last query
1327 * @return string Error message ('' if no error)
1329 public static function errorMessage() {
1330 return self::$error;
1334 * @brief Closes the current statement
1336 * @param object $stmt statement object
1337 * @return boolean was the close successful?
1339 public static function close($stmt) {
1342 $stamp1 = microtime(true);
1344 if (!is_object($stmt)) {
1348 switch (self::$driver) {
1350 $ret = $stmt->closeCursor();
1353 $stmt->free_result();
1354 $ret = $stmt->close();
1358 $a->save_timestamp($stamp1, 'database');
1364 function dbesc($str) {
1365 if (dba::$connected) {
1366 return(dba::escape($str));
1368 return(str_replace("'","\\'",$str));
1373 * @brief execute SQL query with printf style args - deprecated
1375 * Please use the dba:: functions instead:
1376 * dba::select, dba::exists, dba::insert
1377 * dba::delete, dba::update, dba::p, dba::e
1379 * @param $args Query parameters (1 to N parameters of different types)
1380 * @return array|bool Query array
1383 $args = func_get_args();
1386 if (!dba::$connected) {
1390 $sql = dba::clean_query($sql);
1391 $sql = dba::any_value_fallback($sql);
1393 $stmt = @vsprintf($sql, $args);
1395 $ret = dba::p($stmt);
1397 if (is_bool($ret)) {
1401 $columns = dba::columnCount($ret);
1403 $data = dba::inArray($ret);
1405 if ((count($data) == 0) && ($columns == 0)) {
1412 function dba_timer() {
1413 return microtime(true);