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::$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
81 self::$connected = true;
82 } catch (PDOException $e) {
86 if (!self::$connected && class_exists('mysqli')) {
87 self::$driver = 'mysqli';
88 self::$db = @new mysqli($server, $user, $pass, $db, $port);
89 if (!mysqli_connect_errno()) {
90 self::$connected = true;
92 if (isset($a->config["system"]["db_charset"])) {
93 self::$db->set_charset($a->config["system"]["db_charset"]);
98 // No suitable SQL driver was found.
99 if (!self::$connected) {
100 self::$driver = null;
103 $a->save_timestamp($stamp1, "network");
105 return self::$connected;
109 * Disconnects the current database connection
111 public static function disconnect()
113 if (is_null(self::$db)) {
117 switch (self::$driver) {
129 * Perform a reconnect of an existing database connection
131 public static function reconnect() {
134 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name);
139 * Return the database object.
142 public static function get_db()
148 * @brief Returns the MySQL server version string
150 * This function discriminate between the deprecated mysql API and the current
151 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
155 public static function server_info() {
156 if (self::$_server_info == '') {
157 switch (self::$driver) {
159 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
162 self::$_server_info = self::$db->server_info;
166 return self::$_server_info;
170 * @brief Returns the selected database name
174 public static function database_name() {
175 $ret = self::p("SELECT DATABASE() AS `db`");
176 $data = self::inArray($ret);
177 return $data[0]['db'];
181 * @brief Analyze a database query and log this if some conditions are met.
183 * @param string $query The database query that will be analyzed
185 private static function logIndex($query) {
188 if (empty($a->config["system"]["db_log_index"])) {
192 // Don't explain an explain statement
193 if (strtolower(substr($query, 0, 7)) == "explain") {
197 // Only do the explain on "select", "update" and "delete"
198 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
202 $r = self::p("EXPLAIN ".$query);
203 if (!DBM::is_result($r)) {
207 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
208 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
210 while ($row = dba::fetch($r)) {
211 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
212 $log = (in_array($row['key'], $watchlist) &&
213 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
218 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
222 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
227 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
228 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
229 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
230 basename($backtrace[1]["file"])."\t".
231 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
232 substr($query, 0, 2000)."\n", FILE_APPEND);
237 public static function escape($str) {
238 switch (self::$driver) {
240 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
242 return @self::$db->real_escape_string($str);
246 public static function connected() {
249 switch (self::$driver) {
251 $r = dba::p("SELECT 1");
252 if (DBM::is_result($r)) {
253 $row = dba::inArray($r);
254 $connected = ($row[0]['1'] == '1');
258 $connected = self::$db->ping();
265 * @brief Replaces ANY_VALUE() function by MIN() function,
266 * if the database server does not support ANY_VALUE().
268 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
269 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
270 * A standard fall-back is to use MIN().
272 * @param string $sql An SQL string without the values
273 * @return string The input SQL string modified if necessary.
275 public static function any_value_fallback($sql) {
276 $server_info = self::server_info();
277 if (version_compare($server_info, '5.7.5', '<') ||
278 (stripos($server_info, 'MariaDB') !== false)) {
279 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
285 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
287 * This is safe when we bind the parameters later.
288 * The parameter values aren't part of the SQL.
290 * @param string $sql An SQL string without the values
291 * @return string The input SQL string modified if necessary.
293 public static function clean_query($sql) {
294 $search = ["\t", "\n", "\r", " "];
295 $replace = [' ', ' ', ' ', ' '];
298 $sql = str_replace($search, $replace, $sql);
299 } while ($oldsql != $sql);
306 * @brief Replaces the ? placeholders with the parameters in the $args array
308 * @param string $sql SQL query
309 * @param array $args The parameters that are to replace the ? placeholders
310 * @return string The replaced SQL query
312 private static function replaceParameters($sql, $args) {
314 foreach ($args AS $param => $value) {
315 if (is_int($args[$param]) || is_float($args[$param])) {
316 $replace = intval($args[$param]);
318 $replace = "'".self::escape($args[$param])."'";
321 $pos = strpos($sql, '?', $offset);
322 if ($pos !== false) {
323 $sql = substr_replace($sql, $replace, $pos, 1);
325 $offset = $pos + strlen($replace);
331 * @brief Convert parameter array to an universal form
332 * @param array $args Parameter array
333 * @return array universalized parameter array
335 private static function getParam($args) {
338 // When the second function parameter is an array then use this as the parameter array
339 if ((count($args) > 0) && (is_array($args[1]))) {
347 * @brief Executes a prepared statement that returns data
348 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
350 * Please only use it with complicated queries.
351 * For all regular queries please use dba::select or dba::exists
353 * @param string $sql SQL statement
354 * @return bool|object statement object
356 public static function p($sql) {
359 $stamp1 = microtime(true);
361 $params = self::getParam(func_get_args());
363 // Renumber the array keys to be sure that they fit
366 foreach ($params AS $param) {
367 // Avoid problems with some MySQL servers and boolean values. See issue #3645
368 if (is_bool($param)) {
369 $param = (int)$param;
371 $args[++$i] = $param;
374 if (!self::$connected) {
378 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
379 // Question: Should we continue or stop the query here?
380 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
383 $sql = self::clean_query($sql);
384 $sql = self::any_value_fallback($sql);
388 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
389 $sql = "/*".System::callstack()." */ ".$sql;
394 self::$affected_rows = 0;
396 // We have to make some things different if this function is called from "e"
397 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
399 if (isset($trace[1])) {
400 $called_from = $trace[1];
402 // We use just something that is defined to avoid warnings
403 $called_from = $trace[0];
405 // We are having an own error logging in the function "e"
406 $called_from_e = ($called_from['function'] == 'e');
408 switch (self::$driver) {
410 // If there are no arguments we use "query"
411 if (count($args) == 0) {
412 if (!$retval = self::$db->query($sql)) {
413 $errorInfo = self::$db->errorInfo();
414 self::$error = $errorInfo[2];
415 self::$errorno = $errorInfo[1];
419 self::$affected_rows = $retval->rowCount();
423 if (!$stmt = self::$db->prepare($sql)) {
424 $errorInfo = self::$db->errorInfo();
425 self::$error = $errorInfo[2];
426 self::$errorno = $errorInfo[1];
431 foreach ($args AS $param => $value) {
432 if (is_int($args[$param])) {
433 $data_type = PDO::PARAM_INT;
435 $data_type = PDO::PARAM_STR;
437 $stmt->bindParam($param, $args[$param], $data_type);
440 if (!$stmt->execute()) {
441 $errorInfo = $stmt->errorInfo();
442 self::$error = $errorInfo[2];
443 self::$errorno = $errorInfo[1];
447 self::$affected_rows = $retval->rowCount();
451 // There are SQL statements that cannot be executed with a prepared statement
452 $parts = explode(' ', $orig_sql);
453 $command = strtolower($parts[0]);
454 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
456 // The fallback routine is called as well when there are no arguments
457 if (!$can_be_prepared || (count($args) == 0)) {
458 $retval = self::$db->query(self::replaceParameters($sql, $args));
459 if (self::$db->errno) {
460 self::$error = self::$db->error;
461 self::$errorno = self::$db->errno;
464 if (isset($retval->num_rows)) {
465 self::$affected_rows = $retval->num_rows;
467 self::$affected_rows = self::$db->affected_rows;
473 $stmt = self::$db->stmt_init();
475 if (!$stmt->prepare($sql)) {
476 self::$error = $stmt->error;
477 self::$errorno = $stmt->errno;
484 foreach ($args AS $param => $value) {
485 if (is_int($args[$param])) {
487 } elseif (is_float($args[$param])) {
489 } elseif (is_string($args[$param])) {
494 $values[] = &$args[$param];
497 if (count($values) > 0) {
498 array_unshift($values, $param_types);
499 call_user_func_array([$stmt, 'bind_param'], $values);
502 if (!$stmt->execute()) {
503 self::$error = self::$db->error;
504 self::$errorno = self::$db->errno;
507 $stmt->store_result();
509 self::$affected_rows = $retval->affected_rows;
514 // We are having an own error logging in the function "e"
515 if ((self::$errorno != 0) && !$called_from_e) {
516 // We have to preserve the error code, somewhere in the logging it get lost
517 $error = self::$error;
518 $errorno = self::$errorno;
520 logger('DB Error '.self::$errorno.': '.self::$error."\n".
521 System::callstack(8)."\n".self::replaceParameters($sql, $args));
523 // On a lost connection we try to reconnect - but only once.
524 if ($errorno == 2006) {
525 if (self::$in_retrial || !self::reconnect()) {
526 // It doesn't make sense to continue when the database connection was lost
527 if (self::$in_retrial) {
528 logger('Giving up retrial because of database error '.$errorno.': '.$error);
530 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
535 logger('Reconnected after database error '.$errorno.': '.$error);
536 self::$in_retrial = true;
537 $ret = self::p($sql, $args);
538 self::$in_retrial = false;
543 self::$error = $error;
544 self::$errorno = $errorno;
547 $a->save_timestamp($stamp1, 'database');
549 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
551 $stamp2 = microtime(true);
552 $duration = (float)($stamp2 - $stamp1);
554 if (($duration > $a->config["system"]["db_loglimit"])) {
555 $duration = round($duration, 3);
556 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
558 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
559 basename($backtrace[1]["file"])."\t".
560 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
561 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
568 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
570 * Please use dba::delete, dba::insert, dba::update, ... instead
572 * @param string $sql SQL statement
573 * @return boolean Was the query successfull? False is returned only if an error occurred
575 public static function e($sql) {
578 $stamp = microtime(true);
580 $params = self::getParam(func_get_args());
582 // In a case of a deadlock we are repeating the query 20 times
586 $stmt = self::p($sql, $params);
588 if (is_bool($stmt)) {
590 } elseif (is_object($stmt)) {
598 } while ((self::$errorno == 1213) && (--$timeout > 0));
600 if (self::$errorno != 0) {
601 // We have to preserve the error code, somewhere in the logging it get lost
602 $error = self::$error;
603 $errorno = self::$errorno;
605 logger('DB Error '.self::$errorno.': '.self::$error."\n".
606 System::callstack(8)."\n".self::replaceParameters($sql, $params));
608 // On a lost connection we simply quit.
609 // A reconnect like in self::p could be dangerous with modifications
610 if ($errorno == 2006) {
611 logger('Giving up because of database error '.$errorno.': '.$error);
615 self::$error = $error;
616 self::$errorno = $errorno;
619 $a->save_timestamp($stamp, "database_write");
625 * @brief Check if data exists
627 * @param string $table Table name
628 * @param array $condition array of fields for condition
630 * @return boolean Are there rows for that condition?
632 public static function exists($table, $condition) {
640 $first_key = key($condition);
641 if (!is_int($first_key)) {
642 $fields = [$first_key];
645 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
647 if (is_bool($stmt)) {
650 $retval = (self::num_rows($stmt) > 0);
659 * Fetches the first row
661 * Please use dba::selectFirst or dba::exists whenever this is possible.
663 * @brief Fetches the first row
664 * @param string $sql SQL statement
665 * @return array first row of query
667 public static function fetch_first($sql) {
668 $params = self::getParam(func_get_args());
670 $stmt = self::p($sql, $params);
672 if (is_bool($stmt)) {
675 $retval = self::fetch($stmt);
684 * @brief Returns the number of affected rows of the last statement
686 * @return int Number of rows
688 public static function affected_rows() {
689 return self::$affected_rows;
693 * @brief Returns the number of columns of a statement
695 * @param object Statement object
696 * @return int Number of columns
698 public static function columnCount($stmt) {
699 if (!is_object($stmt)) {
702 switch (self::$driver) {
704 return $stmt->columnCount();
706 return $stmt->field_count;
711 * @brief Returns the number of rows of a statement
713 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
714 * @return int Number of rows
716 public static function num_rows($stmt) {
717 if (!is_object($stmt)) {
720 switch (self::$driver) {
722 return $stmt->rowCount();
724 return $stmt->num_rows;
730 * @brief Fetch a single row
732 * @param mixed $stmt statement object
733 * @return array current row
735 public static function fetch($stmt) {
738 $stamp1 = microtime(true);
742 if (!is_object($stmt)) {
746 switch (self::$driver) {
748 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
751 if (get_class($stmt) == 'mysqli_result') {
752 $columns = $stmt->fetch_assoc();
756 // This code works, but is slow
758 // Bind the result to a result array
762 for ($x = 0; $x < $stmt->field_count; $x++) {
763 $cols[] = &$cols_num[$x];
766 call_user_func_array([$stmt, 'bind_result'], $cols);
768 if (!$stmt->fetch()) {
773 // We need to get the field names for the array keys
774 // It seems that there is no better way to do this.
775 $result = $stmt->result_metadata();
776 $fields = $result->fetch_fields();
778 foreach ($cols_num AS $param => $col) {
779 $columns[$fields[$param]->name] = $col;
783 $a->save_timestamp($stamp1, 'database');
789 * @brief Insert a row into a table
791 * @param string $table Table name
792 * @param array $param parameter array
793 * @param bool $on_duplicate_update Do an update on a duplicate entry
795 * @return boolean was the insert successfull?
797 public static function insert($table, $param, $on_duplicate_update = false) {
799 if (empty($table) || empty($param)) {
800 logger('Table and fields have to be set');
804 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
805 substr(str_repeat("?, ", count($param)), 0, -2).")";
807 if ($on_duplicate_update) {
808 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
810 $values = array_values($param);
811 $param = array_merge_recursive($values, $values);
814 return self::e($sql, $param);
818 * @brief Fetch the id of the last insert command
820 * @return integer Last inserted id
822 public static function lastInsertId() {
823 switch (self::$driver) {
825 $id = self::$db->lastInsertId();
828 $id = self::$db->insert_id;
835 * @brief Locks a table for exclusive write access
837 * This function can be extended in the future to accept a table array as well.
839 * @param string $table Table name
841 * @return boolean was the lock successful?
843 public static function lock($table) {
844 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
845 self::e("SET autocommit=0");
846 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
848 self::e("SET autocommit=1");
850 self::$in_transaction = true;
856 * @brief Unlocks all locked tables
858 * @return boolean was the unlock successful?
860 public static function unlock() {
861 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
863 $success = self::e("UNLOCK TABLES");
864 self::e("SET autocommit=1");
865 self::$in_transaction = false;
870 * @brief Starts a transaction
872 * @return boolean Was the command executed successfully?
874 public static function transaction() {
875 if (!self::e('COMMIT')) {
878 if (!self::e('START TRANSACTION')) {
881 self::$in_transaction = true;
886 * @brief Does a commit
888 * @return boolean Was the command executed successfully?
890 public static function commit() {
891 if (!self::e('COMMIT')) {
894 self::$in_transaction = false;
899 * @brief Does a rollback
901 * @return boolean Was the command executed successfully?
903 public static function rollback() {
904 if (!self::e('ROLLBACK')) {
907 self::$in_transaction = false;
912 * @brief Build the array with the table relations
914 * The array is build from the database definitions in DBStructure.php
916 * This process must only be started once, since the value is cached.
918 private static function buildRelationData() {
919 $definition = DBStructure::definition();
921 foreach ($definition AS $table => $structure) {
922 foreach ($structure['fields'] AS $field => $field_struct) {
923 if (isset($field_struct['relation'])) {
924 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
925 self::$relation[$rel_table][$rel_field][$table][] = $field;
933 * @brief Delete a row from a table
935 * @param string $table Table name
936 * @param array $conditions Field condition(s)
937 * @param array $options
938 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
939 * relations (default: true)
940 * @param boolean $in_process Internal use: Only do a commit after the last delete
941 * @param array $callstack Internal use: prevent endless loops
943 * @return boolean|array was the delete successful? When $in_process is set: deletion data
945 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
947 if (empty($table) || empty($conditions)) {
948 logger('Table and conditions have to be set');
954 // Create a key for the loop prevention
955 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
957 // We quit when this key already exists in the callstack.
958 if (isset($callstack[$key])) {
962 $callstack[$key] = true;
964 $table = self::escape($table);
966 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
968 $cascade = defaults($options, 'cascade', true);
970 // To speed up the whole process we cache the table relations
971 if ($cascade && count(self::$relation) == 0) {
972 self::buildRelationData();
975 // Is there a relation entry for the table?
976 if ($cascade && isset(self::$relation[$table])) {
977 // We only allow a simple "one field" relation.
978 $field = array_keys(self::$relation[$table])[0];
979 $rel_def = array_values(self::$relation[$table])[0];
981 // Create a key for preventing double queries
982 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
984 // When the search field is the relation field, we don't need to fetch the rows
985 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
986 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
987 foreach ($rel_def AS $rel_table => $rel_fields) {
988 foreach ($rel_fields AS $rel_field) {
989 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
990 $commands = array_merge($commands, $retval);
993 // We quit when this key already exists in the callstack.
994 } elseif (!isset($callstack[$qkey])) {
996 $callstack[$qkey] = true;
998 // Fetch all rows that are to be deleted
999 $data = self::select($table, [$field], $conditions);
1001 while ($row = self::fetch($data)) {
1002 // Now we accumulate the delete commands
1003 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1004 $commands = array_merge($commands, $retval);
1009 // Since we had split the delete command we don't need the original command anymore
1010 unset($commands[$key]);
1015 // Now we finalize the process
1016 $do_transaction = !self::$in_transaction;
1018 if ($do_transaction) {
1019 self::transaction();
1025 foreach ($commands AS $command) {
1026 $conditions = $command['conditions'];
1028 $first_key = key($conditions);
1030 $condition_string = self::buildCondition($conditions);
1032 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1033 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1034 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1036 if (!self::e($sql, $conditions)) {
1037 if ($do_transaction) {
1043 $key_table = $command['table'];
1044 $key_condition = array_keys($command['conditions'])[0];
1045 $value = array_values($command['conditions'])[0];
1047 // Split the SQL queries in chunks of 100 values
1048 // We do the $i stuff here to make the code better readable
1049 $i = $counter[$key_table][$key_condition];
1050 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1054 $compacted[$key_table][$key_condition][$i][$value] = $value;
1055 $counter[$key_table][$key_condition] = $i;
1058 foreach ($compacted AS $table => $values) {
1059 foreach ($values AS $field => $field_value_list) {
1060 foreach ($field_value_list AS $field_values) {
1061 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1062 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1064 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1066 if (!self::e($sql, $field_values)) {
1067 if ($do_transaction) {
1075 if ($do_transaction) {
1085 * @brief Updates rows
1087 * Updates rows in the database. When $old_fields is set to an array,
1088 * the system will only do an update if the fields in that array changed.
1091 * Only the values in $old_fields are compared.
1092 * This is an intentional behaviour.
1095 * We include the timestamp field in $fields but not in $old_fields.
1096 * Then the row will only get the new timestamp when the other fields had changed.
1098 * When $old_fields is set to a boolean value the system will do this compare itself.
1099 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1102 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1103 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1105 * @param string $table Table name
1106 * @param array $fields contains the fields that are updated
1107 * @param array $condition condition array with the key values
1108 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1110 * @return boolean was the update successfull?
1112 public static function update($table, $fields, $condition, $old_fields = []) {
1114 if (empty($table) || empty($fields) || empty($condition)) {
1115 logger('Table, fields and condition have to be set');
1119 $table = self::escape($table);
1121 $condition_string = self::buildCondition($condition);
1123 if (is_bool($old_fields)) {
1124 $do_insert = $old_fields;
1126 $old_fields = self::selectFirst($table, [], $condition);
1128 if (is_bool($old_fields)) {
1130 $values = array_merge($condition, $fields);
1131 return self::insert($table, $values, $do_insert);
1137 $do_update = (count($old_fields) == 0);
1139 foreach ($old_fields AS $fieldname => $content) {
1140 if (isset($fields[$fieldname])) {
1141 if ($fields[$fieldname] == $content) {
1142 unset($fields[$fieldname]);
1149 if (!$do_update || (count($fields) == 0)) {
1153 $sql = "UPDATE `".$table."` SET `".
1154 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1156 $params1 = array_values($fields);
1157 $params2 = array_values($condition);
1158 $params = array_merge_recursive($params1, $params2);
1160 return self::e($sql, $params);
1164 * Retrieve a single record from a table and returns it in an associative array
1166 * @brief Retrieve a single record from a table
1167 * @param string $table
1168 * @param array $fields
1169 * @param array $condition
1170 * @param array $params
1171 * @return bool|array
1174 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1176 $params['limit'] = 1;
1177 $result = self::select($table, $fields, $condition, $params);
1179 if (is_bool($result)) {
1182 $row = self::fetch($result);
1183 self::close($result);
1189 * @brief Select rows from a table
1191 * @param string $table Table name
1192 * @param array $fields Array of selected fields, empty for all
1193 * @param array $condition Array of fields for condition
1194 * @param array $params Array of several parameters
1196 * @return boolean|object
1200 * $fields = array("id", "uri", "uid", "network");
1202 * $condition = array("uid" => 1, "network" => 'dspr');
1204 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1206 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1208 * $data = dba::select($table, $fields, $condition, $params);
1210 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1216 $table = self::escape($table);
1218 if (count($fields) > 0) {
1219 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1221 $select_fields = "*";
1224 $condition_string = self::buildCondition($condition);
1226 $param_string = self::buildParameter($params);
1228 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1230 $result = self::p($sql, $condition);
1236 * @brief Counts the rows from a table satisfying the provided condition
1238 * @param string $table Table name
1239 * @param array $condition array of fields for condition
1246 * $condition = ["uid" => 1, "network" => 'dspr'];
1248 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1250 * $count = dba::count($table, $condition);
1252 public static function count($table, array $condition = [])
1258 $condition_string = self::buildCondition($condition);
1260 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1262 $row = self::fetch_first($sql, $condition);
1264 return $row['count'];
1268 * @brief Returns the SQL condition string built from the provided condition array
1270 * This function operates with two modes.
1271 * - Supplied with a filed/value associative array, it builds simple strict
1272 * equality conditions linked by AND.
1273 * - Supplied with a flat list, the first element is the condition string and
1274 * the following arguments are the values to be interpolated
1276 * $condition = ["uid" => 1, "network" => 'dspr'];
1278 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1280 * In either case, the provided array is left with the parameters only
1282 * @param array $condition
1285 public static function buildCondition(array &$condition = [])
1287 $condition_string = '';
1288 if (count($condition) > 0) {
1290 $first_key = key($condition);
1291 if (is_int($first_key)) {
1292 $condition_string = " WHERE (" . array_shift($condition) . ")";
1295 $condition_string = "";
1296 foreach ($condition as $field => $value) {
1297 if ($condition_string != "") {
1298 $condition_string .= " AND ";
1300 if (is_array($value)) {
1301 // Check if there are integer values in the parameters
1305 foreach ($value as $single_value) {
1306 if (is_int($single_value)) {
1310 // To prevent to round floats we look for them
1311 if (is_float($single_value)) {
1315 // Is any non numeric value present?
1316 if (!is_numeric($single_value)) {
1321 // Cast them all in an unique method
1324 foreach ($value as $single_value) {
1325 if (!$is_alpha && !$is_float) {
1326 $casted[] = (int)$single_value;
1328 $casted[] = (string)$single_value;
1334 $new_values = array_merge($new_values, array_values($value));
1335 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1336 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1338 $new_values[$field] = $value;
1339 $condition_string .= "`" . $field . "` = ?";
1342 $condition_string = " WHERE (" . $condition_string . ")";
1343 $condition = $new_values;
1347 return $condition_string;
1351 * @brief Returns the SQL parameter string built from the provided parameter array
1353 * @param array $params
1356 public static function buildParameter(array $params = [])
1359 if (isset($params['order'])) {
1360 $order_string = " ORDER BY ";
1361 foreach ($params['order'] AS $fields => $order) {
1362 if (!is_int($fields)) {
1363 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1365 $order_string .= "`" . $order . "`, ";
1368 $order_string = substr($order_string, 0, -2);
1372 if (isset($params['limit']) && is_int($params['limit'])) {
1373 $limit_string = " LIMIT " . $params['limit'];
1376 if (isset($params['limit']) && is_array($params['limit'])) {
1377 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1380 return $order_string.$limit_string;
1384 * @brief Fills an array with data from a query
1386 * @param object $stmt statement object
1387 * @return array Data array
1389 public static function inArray($stmt, $do_close = true) {
1390 if (is_bool($stmt)) {
1395 while ($row = self::fetch($stmt)) {
1405 * @brief Returns the error number of the last query
1407 * @return string Error number (0 if no error)
1409 public static function errorNo() {
1410 return self::$errorno;
1414 * @brief Returns the error message of the last query
1416 * @return string Error message ('' if no error)
1418 public static function errorMessage() {
1419 return self::$error;
1423 * @brief Closes the current statement
1425 * @param object $stmt statement object
1426 * @return boolean was the close successful?
1428 public static function close($stmt) {
1431 $stamp1 = microtime(true);
1433 if (!is_object($stmt)) {
1437 switch (self::$driver) {
1439 $ret = $stmt->closeCursor();
1442 $stmt->free_result();
1443 $ret = $stmt->close();
1447 $a->save_timestamp($stamp1, 'database');
1453 function dbesc($str) {
1454 if (dba::$connected) {
1455 return(dba::escape($str));
1457 return(str_replace("'","\\'",$str));
1462 * @brief execute SQL query with printf style args - deprecated
1464 * Please use the dba:: functions instead:
1465 * dba::select, dba::exists, dba::insert
1466 * dba::delete, dba::update, dba::p, dba::e
1468 * @param $args Query parameters (1 to N parameters of different types)
1469 * @return array|bool Query array
1472 $args = func_get_args();
1475 if (!dba::$connected) {
1479 $sql = dba::clean_query($sql);
1480 $sql = dba::any_value_fallback($sql);
1482 $stmt = @vsprintf($sql, $args);
1484 $ret = dba::p($stmt);
1486 if (is_bool($ret)) {
1490 $columns = dba::columnCount($ret);
1492 $data = dba::inArray($ret);
1494 if ((count($data) == 0) && ($columns == 0)) {
1501 function dba_timer() {
1502 return microtime(true);