3 namespace Friendica\Database;
5 // Do not use Core\Config in this class at risk of infinite loop.
6 // Please use App->getConfigVariable() instead.
7 //use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Util\DateTimeFormat;
16 * @class MySQL database class
18 * This class is for the low level database stuff that does driver specific things.
22 public static $connected = false;
24 private static $server_info = '';
26 private static $driver;
27 private static $error = false;
28 private static $errorno = 0;
29 private static $affected_rows = 0;
30 private static $in_transaction = false;
31 private static $in_retrial = false;
32 private static $relation = [];
33 private static $db_serveraddr = '';
34 private static $db_user = '';
35 private static $db_pass = '';
36 private static $db_name = '';
37 private static $db_charset = '';
39 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
41 if (!is_null(self::$db) && self::connected()) {
45 // We are storing these values for being able to perform a reconnect
46 self::$db_serveraddr = $serveraddr;
47 self::$db_user = $user;
48 self::$db_pass = $pass;
50 self::$db_charset = $charset;
52 $serveraddr = trim($serveraddr);
54 $serverdata = explode(':', $serveraddr);
55 $server = $serverdata[0];
57 if (count($serverdata) > 1) {
58 $port = trim($serverdata[1]);
61 $server = trim($server);
65 $charset = trim($charset);
67 if (!(strlen($server) && strlen($user))) {
71 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
72 self::$driver = 'pdo';
73 $connect = "mysql:host=".$server.";dbname=".$db;
76 $connect .= ";port=".$port;
80 $connect .= ";charset=".$charset;
84 self::$db = @new PDO($connect, $user, $pass);
85 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
86 self::$connected = true;
87 } catch (PDOException $e) {
91 if (!self::$connected && class_exists('mysqli')) {
92 self::$driver = 'mysqli';
93 self::$db = @new mysqli($server, $user, $pass, $db, $port);
94 if (!mysqli_connect_errno()) {
95 self::$connected = true;
98 self::$db->set_charset($charset);
103 // No suitable SQL driver was found.
104 if (!self::$connected) {
105 self::$driver = null;
109 return self::$connected;
113 * Disconnects the current database connection
115 public static function disconnect()
117 if (is_null(self::$db)) {
121 switch (self::$driver) {
133 * Perform a reconnect of an existing database connection
135 public static function reconnect() {
138 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
143 * Return the database object.
146 public static function get_db()
152 * @brief Returns the MySQL server version string
154 * This function discriminate between the deprecated mysql API and the current
155 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
159 public static function server_info() {
160 if (self::$server_info == '') {
161 switch (self::$driver) {
163 self::$server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
166 self::$server_info = self::$db->server_info;
170 return self::$server_info;
174 * @brief Returns the selected database name
178 public static function database_name() {
179 $ret = self::p("SELECT DATABASE() AS `db`");
180 $data = self::inArray($ret);
181 return $data[0]['db'];
185 * @brief Analyze a database query and log this if some conditions are met.
187 * @param string $query The database query that will be analyzed
189 private static function logIndex($query) {
192 if (!$a->getConfigVariable('system', 'db_log_index')) {
196 // Don't explain an explain statement
197 if (strtolower(substr($query, 0, 7)) == "explain") {
201 // Only do the explain on "select", "update" and "delete"
202 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
206 $r = self::p("EXPLAIN ".$query);
207 if (!DBM::is_result($r)) {
211 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
212 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
214 while ($row = self::fetch($r)) {
215 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
216 $log = (in_array($row['key'], $watchlist) &&
217 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
222 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
226 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
231 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
232 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
233 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
234 basename($backtrace[1]["file"])."\t".
235 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
236 substr($query, 0, 2000)."\n", FILE_APPEND);
241 public static function escape($str) {
242 switch (self::$driver) {
244 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
246 return @self::$db->real_escape_string($str);
250 public static function connected() {
253 if (is_null(self::$db)) {
257 switch (self::$driver) {
259 $r = self::p("SELECT 1");
260 if (DBM::is_result($r)) {
261 $row = self::inArray($r);
262 $connected = ($row[0]['1'] == '1');
266 $connected = self::$db->ping();
273 * @brief Replaces ANY_VALUE() function by MIN() function,
274 * if the database server does not support ANY_VALUE().
276 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
277 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
278 * A standard fall-back is to use MIN().
280 * @param string $sql An SQL string without the values
281 * @return string The input SQL string modified if necessary.
283 public static function any_value_fallback($sql) {
284 $server_info = self::server_info();
285 if (version_compare($server_info, '5.7.5', '<') ||
286 (stripos($server_info, 'MariaDB') !== false)) {
287 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
293 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
295 * This is safe when we bind the parameters later.
296 * The parameter values aren't part of the SQL.
298 * @param string $sql An SQL string without the values
299 * @return string The input SQL string modified if necessary.
301 public static function clean_query($sql) {
302 $search = ["\t", "\n", "\r", " "];
303 $replace = [' ', ' ', ' ', ' '];
306 $sql = str_replace($search, $replace, $sql);
307 } while ($oldsql != $sql);
314 * @brief Replaces the ? placeholders with the parameters in the $args array
316 * @param string $sql SQL query
317 * @param array $args The parameters that are to replace the ? placeholders
318 * @return string The replaced SQL query
320 private static function replaceParameters($sql, $args) {
322 foreach ($args AS $param => $value) {
323 if (is_int($args[$param]) || is_float($args[$param])) {
324 $replace = intval($args[$param]);
326 $replace = "'".self::escape($args[$param])."'";
329 $pos = strpos($sql, '?', $offset);
330 if ($pos !== false) {
331 $sql = substr_replace($sql, $replace, $pos, 1);
333 $offset = $pos + strlen($replace);
339 * @brief Convert parameter array to an universal form
340 * @param array $args Parameter array
341 * @return array universalized parameter array
343 private static function getParam($args) {
346 // When the second function parameter is an array then use this as the parameter array
347 if ((count($args) > 0) && (is_array($args[1]))) {
355 * @brief Executes a prepared statement that returns data
356 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
358 * Please only use it with complicated queries.
359 * For all regular queries please use dba::select or dba::exists
361 * @param string $sql SQL statement
362 * @return bool|object statement object or result object
364 public static function p($sql) {
367 $stamp1 = microtime(true);
369 $params = self::getParam(func_get_args());
371 // Renumber the array keys to be sure that they fit
374 foreach ($params AS $param) {
375 // Avoid problems with some MySQL servers and boolean values. See issue #3645
376 if (is_bool($param)) {
377 $param = (int)$param;
379 $args[++$i] = $param;
382 if (!self::$connected) {
386 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
387 // Question: Should we continue or stop the query here?
388 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
391 $sql = self::clean_query($sql);
392 $sql = self::any_value_fallback($sql);
396 if ($a->getConfigValue('system', 'db_callstack')) {
397 $sql = "/*".System::callstack()." */ ".$sql;
402 self::$affected_rows = 0;
404 // We have to make some things different if this function is called from "e"
405 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
407 if (isset($trace[1])) {
408 $called_from = $trace[1];
410 // We use just something that is defined to avoid warnings
411 $called_from = $trace[0];
413 // We are having an own error logging in the function "e"
414 $called_from_e = ($called_from['function'] == 'e');
416 switch (self::$driver) {
418 // If there are no arguments we use "query"
419 if (count($args) == 0) {
420 if (!$retval = self::$db->query($sql)) {
421 $errorInfo = self::$db->errorInfo();
422 self::$error = $errorInfo[2];
423 self::$errorno = $errorInfo[1];
427 self::$affected_rows = $retval->rowCount();
431 if (!$stmt = self::$db->prepare($sql)) {
432 $errorInfo = self::$db->errorInfo();
433 self::$error = $errorInfo[2];
434 self::$errorno = $errorInfo[1];
439 foreach ($args AS $param => $value) {
440 if (is_int($args[$param])) {
441 $data_type = PDO::PARAM_INT;
443 $data_type = PDO::PARAM_STR;
445 $stmt->bindParam($param, $args[$param], $data_type);
448 if (!$stmt->execute()) {
449 $errorInfo = $stmt->errorInfo();
450 self::$error = $errorInfo[2];
451 self::$errorno = $errorInfo[1];
455 self::$affected_rows = $retval->rowCount();
459 // There are SQL statements that cannot be executed with a prepared statement
460 $parts = explode(' ', $orig_sql);
461 $command = strtolower($parts[0]);
462 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
464 // The fallback routine is called as well when there are no arguments
465 if (!$can_be_prepared || (count($args) == 0)) {
466 $retval = self::$db->query(self::replaceParameters($sql, $args));
467 if (self::$db->errno) {
468 self::$error = self::$db->error;
469 self::$errorno = self::$db->errno;
472 if (isset($retval->num_rows)) {
473 self::$affected_rows = $retval->num_rows;
475 self::$affected_rows = self::$db->affected_rows;
481 $stmt = self::$db->stmt_init();
483 if (!$stmt->prepare($sql)) {
484 self::$error = $stmt->error;
485 self::$errorno = $stmt->errno;
492 foreach ($args AS $param => $value) {
493 if (is_int($args[$param])) {
495 } elseif (is_float($args[$param])) {
497 } elseif (is_string($args[$param])) {
502 $values[] = &$args[$param];
505 if (count($values) > 0) {
506 array_unshift($values, $param_types);
507 call_user_func_array([$stmt, 'bind_param'], $values);
510 if (!$stmt->execute()) {
511 self::$error = self::$db->error;
512 self::$errorno = self::$db->errno;
515 $stmt->store_result();
517 self::$affected_rows = $retval->affected_rows;
522 // We are having an own error logging in the function "e"
523 if ((self::$errorno != 0) && !$called_from_e) {
524 // We have to preserve the error code, somewhere in the logging it get lost
525 $error = self::$error;
526 $errorno = self::$errorno;
528 logger('DB Error '.self::$errorno.': '.self::$error."\n".
529 System::callstack(8)."\n".self::replaceParameters($sql, $args));
531 // On a lost connection we try to reconnect - but only once.
532 if ($errorno == 2006) {
533 if (self::$in_retrial || !self::reconnect()) {
534 // It doesn't make sense to continue when the database connection was lost
535 if (self::$in_retrial) {
536 logger('Giving up retrial because of database error '.$errorno.': '.$error);
538 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
543 logger('Reconnected after database error '.$errorno.': '.$error);
544 self::$in_retrial = true;
545 $ret = self::p($sql, $args);
546 self::$in_retrial = false;
551 self::$error = $error;
552 self::$errorno = $errorno;
555 $a->save_timestamp($stamp1, 'database');
557 if ($a->getConfigValue('system', 'db_log')) {
558 $stamp2 = microtime(true);
559 $duration = (float)($stamp2 - $stamp1);
561 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
562 $duration = round($duration, 3);
563 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
565 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
566 basename($backtrace[1]["file"])."\t".
567 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
568 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
575 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
577 * Please use dba::delete, dba::insert, dba::update, ... instead
579 * @param string $sql SQL statement
580 * @return boolean Was the query successfull? False is returned only if an error occurred
582 public static function e($sql) {
585 $stamp = microtime(true);
587 $params = self::getParam(func_get_args());
589 // In a case of a deadlock we are repeating the query 20 times
593 $stmt = self::p($sql, $params);
595 if (is_bool($stmt)) {
597 } elseif (is_object($stmt)) {
605 } while ((self::$errorno == 1213) && (--$timeout > 0));
607 if (self::$errorno != 0) {
608 // We have to preserve the error code, somewhere in the logging it get lost
609 $error = self::$error;
610 $errorno = self::$errorno;
612 logger('DB Error '.self::$errorno.': '.self::$error."\n".
613 System::callstack(8)."\n".self::replaceParameters($sql, $params));
615 // On a lost connection we simply quit.
616 // A reconnect like in self::p could be dangerous with modifications
617 if ($errorno == 2006) {
618 logger('Giving up because of database error '.$errorno.': '.$error);
622 self::$error = $error;
623 self::$errorno = $errorno;
626 $a->save_timestamp($stamp, "database_write");
632 * @brief Check if data exists
634 * @param string $table Table name
635 * @param array $condition array of fields for condition
637 * @return boolean Are there rows for that condition?
639 public static function exists($table, $condition) {
647 $first_key = key($condition);
648 if (!is_int($first_key)) {
649 $fields = [$first_key];
652 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
654 if (is_bool($stmt)) {
657 $retval = (self::num_rows($stmt) > 0);
666 * Fetches the first row
668 * Please use dba::selectFirst or dba::exists whenever this is possible.
670 * @brief Fetches the first row
671 * @param string $sql SQL statement
672 * @return array first row of query
674 public static function fetch_first($sql) {
675 $params = self::getParam(func_get_args());
677 $stmt = self::p($sql, $params);
679 if (is_bool($stmt)) {
682 $retval = self::fetch($stmt);
691 * @brief Returns the number of affected rows of the last statement
693 * @return int Number of rows
695 public static function affected_rows() {
696 return self::$affected_rows;
700 * @brief Returns the number of columns of a statement
702 * @param object Statement object
703 * @return int Number of columns
705 public static function columnCount($stmt) {
706 if (!is_object($stmt)) {
709 switch (self::$driver) {
711 return $stmt->columnCount();
713 return $stmt->field_count;
718 * @brief Returns the number of rows of a statement
720 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
721 * @return int Number of rows
723 public static function num_rows($stmt) {
724 if (!is_object($stmt)) {
727 switch (self::$driver) {
729 return $stmt->rowCount();
731 return $stmt->num_rows;
737 * @brief Fetch a single row
739 * @param mixed $stmt statement object
740 * @return array current row
742 public static function fetch($stmt) {
745 $stamp1 = microtime(true);
749 if (!is_object($stmt)) {
753 switch (self::$driver) {
755 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
758 if (get_class($stmt) == 'mysqli_result') {
759 $columns = $stmt->fetch_assoc();
763 // This code works, but is slow
765 // Bind the result to a result array
769 for ($x = 0; $x < $stmt->field_count; $x++) {
770 $cols[] = &$cols_num[$x];
773 call_user_func_array([$stmt, 'bind_result'], $cols);
775 if (!$stmt->fetch()) {
780 // We need to get the field names for the array keys
781 // It seems that there is no better way to do this.
782 $result = $stmt->result_metadata();
783 $fields = $result->fetch_fields();
785 foreach ($cols_num AS $param => $col) {
786 $columns[$fields[$param]->name] = $col;
790 $a->save_timestamp($stamp1, 'database');
796 * @brief Insert a row into a table
798 * @param string $table Table name
799 * @param array $param parameter array
800 * @param bool $on_duplicate_update Do an update on a duplicate entry
802 * @return boolean was the insert successfull?
804 public static function insert($table, $param, $on_duplicate_update = false) {
806 if (empty($table) || empty($param)) {
807 logger('Table and fields have to be set');
811 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
812 substr(str_repeat("?, ", count($param)), 0, -2).")";
814 if ($on_duplicate_update) {
815 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
817 $values = array_values($param);
818 $param = array_merge_recursive($values, $values);
821 return self::e($sql, $param);
825 * @brief Fetch the id of the last insert command
827 * @return integer Last inserted id
829 public static function lastInsertId() {
830 switch (self::$driver) {
832 $id = self::$db->lastInsertId();
835 $id = self::$db->insert_id;
842 * @brief Locks a table for exclusive write access
844 * This function can be extended in the future to accept a table array as well.
846 * @param string $table Table name
848 * @return boolean was the lock successful?
850 public static function lock($table) {
851 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
852 if (self::$driver == 'pdo') {
853 self::e("SET autocommit=0");
854 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
856 self::$db->autocommit(false);
859 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
861 if (self::$driver == 'pdo') {
862 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
866 if (self::$driver == 'pdo') {
867 self::e("SET autocommit=1");
869 self::$db->autocommit(true);
872 self::$in_transaction = true;
878 * @brief Unlocks all locked tables
880 * @return boolean was the unlock successful?
882 public static function unlock() {
883 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
884 self::performCommit();
886 if (self::$driver == 'pdo') {
887 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
890 $success = self::e("UNLOCK TABLES");
892 if (self::$driver == 'pdo') {
893 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
894 self::e("SET autocommit=1");
896 self::$db->autocommit(true);
899 self::$in_transaction = false;
904 * @brief Starts a transaction
906 * @return boolean Was the command executed successfully?
908 public static function transaction() {
909 if (!self::performCommit()) {
913 switch (self::$driver) {
915 if (self::$db->inTransaction()) {
918 if (!self::$db->beginTransaction()) {
923 if (!self::$db->begin_transaction()) {
929 self::$in_transaction = true;
933 private static function performCommit()
935 switch (self::$driver) {
937 if (!self::$db->inTransaction()) {
940 return self::$db->commit();
942 return self::$db->commit();
948 * @brief Does a commit
950 * @return boolean Was the command executed successfully?
952 public static function commit() {
953 if (!self::performCommit()) {
956 self::$in_transaction = false;
961 * @brief Does a rollback
963 * @return boolean Was the command executed successfully?
965 public static function rollback() {
968 switch (self::$driver) {
970 if (!self::$db->inTransaction()) {
974 $ret = self::$db->rollBack();
977 $ret = self::$db->rollback();
980 self::$in_transaction = false;
985 * @brief Build the array with the table relations
987 * The array is build from the database definitions in DBStructure.php
989 * This process must only be started once, since the value is cached.
991 private static function buildRelationData() {
992 $definition = DBStructure::definition();
994 foreach ($definition AS $table => $structure) {
995 foreach ($structure['fields'] AS $field => $field_struct) {
996 if (isset($field_struct['relation'])) {
997 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
998 self::$relation[$rel_table][$rel_field][$table][] = $field;
1006 * @brief Delete a row from a table
1008 * @param string $table Table name
1009 * @param array $conditions Field condition(s)
1010 * @param array $options
1011 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1012 * relations (default: true)
1013 * @param boolean $in_process Internal use: Only do a commit after the last delete
1014 * @param array $callstack Internal use: prevent endless loops
1016 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1018 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1020 if (empty($table) || empty($conditions)) {
1021 logger('Table and conditions have to be set');
1027 // Create a key for the loop prevention
1028 $key = $table . ':' . json_encode($conditions);
1030 // We quit when this key already exists in the callstack.
1031 if (isset($callstack[$key])) {
1035 $callstack[$key] = true;
1037 $table = self::escape($table);
1039 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1041 $cascade = defaults($options, 'cascade', true);
1043 // To speed up the whole process we cache the table relations
1044 if ($cascade && count(self::$relation) == 0) {
1045 self::buildRelationData();
1048 // Is there a relation entry for the table?
1049 if ($cascade && isset(self::$relation[$table])) {
1050 // We only allow a simple "one field" relation.
1051 $field = array_keys(self::$relation[$table])[0];
1052 $rel_def = array_values(self::$relation[$table])[0];
1054 // Create a key for preventing double queries
1055 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1057 // When the search field is the relation field, we don't need to fetch the rows
1058 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1059 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1060 foreach ($rel_def AS $rel_table => $rel_fields) {
1061 foreach ($rel_fields AS $rel_field) {
1062 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1063 $commands = array_merge($commands, $retval);
1066 // We quit when this key already exists in the callstack.
1067 } elseif (!isset($callstack[$qkey])) {
1069 $callstack[$qkey] = true;
1071 // Fetch all rows that are to be deleted
1072 $data = self::select($table, [$field], $conditions);
1074 while ($row = self::fetch($data)) {
1075 // Now we accumulate the delete commands
1076 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1077 $commands = array_merge($commands, $retval);
1082 // Since we had split the delete command we don't need the original command anymore
1083 unset($commands[$key]);
1088 // Now we finalize the process
1089 $do_transaction = !self::$in_transaction;
1091 if ($do_transaction) {
1092 self::transaction();
1098 foreach ($commands AS $command) {
1099 $conditions = $command['conditions'];
1101 $first_key = key($conditions);
1103 $condition_string = self::buildCondition($conditions);
1105 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1106 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1107 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1109 if (!self::e($sql, $conditions)) {
1110 if ($do_transaction) {
1116 $key_table = $command['table'];
1117 $key_condition = array_keys($command['conditions'])[0];
1118 $value = array_values($command['conditions'])[0];
1120 // Split the SQL queries in chunks of 100 values
1121 // We do the $i stuff here to make the code better readable
1122 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1123 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1127 $compacted[$key_table][$key_condition][$i][$value] = $value;
1128 $counter[$key_table][$key_condition] = $i;
1131 foreach ($compacted AS $table => $values) {
1132 foreach ($values AS $field => $field_value_list) {
1133 foreach ($field_value_list AS $field_values) {
1134 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1135 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1137 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1139 if (!self::e($sql, $field_values)) {
1140 if ($do_transaction) {
1148 if ($do_transaction) {
1158 * @brief Updates rows
1160 * Updates rows in the database. When $old_fields is set to an array,
1161 * the system will only do an update if the fields in that array changed.
1164 * Only the values in $old_fields are compared.
1165 * This is an intentional behaviour.
1168 * We include the timestamp field in $fields but not in $old_fields.
1169 * Then the row will only get the new timestamp when the other fields had changed.
1171 * When $old_fields is set to a boolean value the system will do this compare itself.
1172 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1175 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1176 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1178 * @param string $table Table name
1179 * @param array $fields contains the fields that are updated
1180 * @param array $condition condition array with the key values
1181 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1183 * @return boolean was the update successfull?
1185 public static function update($table, $fields, $condition, $old_fields = []) {
1187 if (empty($table) || empty($fields) || empty($condition)) {
1188 logger('Table, fields and condition have to be set');
1192 $table = self::escape($table);
1194 $condition_string = self::buildCondition($condition);
1196 if (is_bool($old_fields)) {
1197 $do_insert = $old_fields;
1199 $old_fields = self::selectFirst($table, [], $condition);
1201 if (is_bool($old_fields)) {
1203 $values = array_merge($condition, $fields);
1204 return self::insert($table, $values, $do_insert);
1210 $do_update = (count($old_fields) == 0);
1212 foreach ($old_fields AS $fieldname => $content) {
1213 if (isset($fields[$fieldname])) {
1214 if ($fields[$fieldname] == $content) {
1215 unset($fields[$fieldname]);
1222 if (!$do_update || (count($fields) == 0)) {
1226 $sql = "UPDATE `".$table."` SET `".
1227 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1229 $params1 = array_values($fields);
1230 $params2 = array_values($condition);
1231 $params = array_merge_recursive($params1, $params2);
1233 return self::e($sql, $params);
1237 * Retrieve a single record from a table and returns it in an associative array
1239 * @brief Retrieve a single record from a table
1240 * @param string $table
1241 * @param array $fields
1242 * @param array $condition
1243 * @param array $params
1244 * @return bool|array
1247 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1249 $params['limit'] = 1;
1250 $result = self::select($table, $fields, $condition, $params);
1252 if (is_bool($result)) {
1255 $row = self::fetch($result);
1256 self::close($result);
1262 * @brief Select rows from a table
1264 * @param string $table Table name
1265 * @param array $fields Array of selected fields, empty for all
1266 * @param array $condition Array of fields for condition
1267 * @param array $params Array of several parameters
1269 * @return boolean|object
1273 * $fields = array("id", "uri", "uid", "network");
1275 * $condition = array("uid" => 1, "network" => 'dspr');
1277 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1279 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1281 * $data = dba::select($table, $fields, $condition, $params);
1283 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1289 $table = self::escape($table);
1291 if (count($fields) > 0) {
1292 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1294 $select_fields = "*";
1297 $condition_string = self::buildCondition($condition);
1299 $param_string = self::buildParameter($params);
1301 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1303 $result = self::p($sql, $condition);
1309 * @brief Counts the rows from a table satisfying the provided condition
1311 * @param string $table Table name
1312 * @param array $condition array of fields for condition
1319 * $condition = ["uid" => 1, "network" => 'dspr'];
1321 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1323 * $count = dba::count($table, $condition);
1325 public static function count($table, array $condition = [])
1331 $condition_string = self::buildCondition($condition);
1333 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1335 $row = self::fetch_first($sql, $condition);
1337 return $row['count'];
1341 * @brief Returns the SQL condition string built from the provided condition array
1343 * This function operates with two modes.
1344 * - Supplied with a filed/value associative array, it builds simple strict
1345 * equality conditions linked by AND.
1346 * - Supplied with a flat list, the first element is the condition string and
1347 * the following arguments are the values to be interpolated
1349 * $condition = ["uid" => 1, "network" => 'dspr'];
1351 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1353 * In either case, the provided array is left with the parameters only
1355 * @param array $condition
1358 public static function buildCondition(array &$condition = [])
1360 $condition_string = '';
1361 if (count($condition) > 0) {
1363 $first_key = key($condition);
1364 if (is_int($first_key)) {
1365 $condition_string = " WHERE (" . array_shift($condition) . ")";
1368 $condition_string = "";
1369 foreach ($condition as $field => $value) {
1370 if ($condition_string != "") {
1371 $condition_string .= " AND ";
1373 if (is_array($value)) {
1374 /* Workaround for MySQL Bug #64791.
1375 * Never mix data types inside any IN() condition.
1376 * In case of mixed types, cast all as string.
1377 * Logic needs to be consistent with dba::p() data types.
1381 foreach ($value as $single_value) {
1382 if (is_int($single_value)) {
1389 if ($is_int && $is_alpha) {
1390 foreach ($value as &$ref) {
1392 $ref = (string)$ref;
1395 unset($ref); //Prevent accidental re-use.
1398 $new_values = array_merge($new_values, array_values($value));
1399 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1400 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1402 $new_values[$field] = $value;
1403 $condition_string .= "`" . $field . "` = ?";
1406 $condition_string = " WHERE (" . $condition_string . ")";
1407 $condition = $new_values;
1411 return $condition_string;
1415 * @brief Returns the SQL parameter string built from the provided parameter array
1417 * @param array $params
1420 public static function buildParameter(array $params = [])
1423 if (isset($params['order'])) {
1424 $order_string = " ORDER BY ";
1425 foreach ($params['order'] AS $fields => $order) {
1426 if (!is_int($fields)) {
1427 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1429 $order_string .= "`" . $order . "`, ";
1432 $order_string = substr($order_string, 0, -2);
1436 if (isset($params['limit']) && is_int($params['limit'])) {
1437 $limit_string = " LIMIT " . $params['limit'];
1440 if (isset($params['limit']) && is_array($params['limit'])) {
1441 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1444 return $order_string.$limit_string;
1448 * @brief Fills an array with data from a query
1450 * @param object $stmt statement object
1451 * @return array Data array
1453 public static function inArray($stmt, $do_close = true) {
1454 if (is_bool($stmt)) {
1459 while ($row = self::fetch($stmt)) {
1469 * @brief Returns the error number of the last query
1471 * @return string Error number (0 if no error)
1473 public static function errorNo() {
1474 return self::$errorno;
1478 * @brief Returns the error message of the last query
1480 * @return string Error message ('' if no error)
1482 public static function errorMessage() {
1483 return self::$error;
1487 * @brief Closes the current statement
1489 * @param object $stmt statement object
1490 * @return boolean was the close successful?
1492 public static function close($stmt) {
1495 $stamp1 = microtime(true);
1497 if (!is_object($stmt)) {
1501 switch (self::$driver) {
1503 $ret = $stmt->closeCursor();
1506 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1507 // We should be careful not to assume the object type of $stmt
1508 // because dba::p() has been able to return both types.
1509 if ($stmt instanceof mysqli_stmt) {
1510 $stmt->free_result();
1511 $ret = $stmt->close();
1512 } elseif ($stmt instanceof mysqli_result) {
1521 $a->save_timestamp($stamp1, 'database');