3 use Friendica\Core\L10n;
4 use Friendica\Core\System;
5 use Friendica\Database\DBM;
6 use Friendica\Database\DBStructure;
7 use Friendica\Util\DateTimeFormat;
10 * @class MySQL database class
12 * This class is for the low level database stuff that does driver specific things.
16 public static $connected = false;
18 private static $_server_info = '';
20 private static $driver;
21 private static $error = false;
22 private static $errorno = 0;
23 private static $affected_rows = 0;
24 private static $in_transaction = false;
25 private static $relation = [];
27 public static function connect($serveraddr, $user, $pass, $db, $install = false) {
28 if (!is_null(self::$db)) {
34 $stamp1 = microtime(true);
36 $serveraddr = trim($serveraddr);
38 $serverdata = explode(':', $serveraddr);
39 $server = $serverdata[0];
41 if (count($serverdata) > 1) {
42 $port = trim($serverdata[1]);
45 $server = trim($server);
50 if (!(strlen($server) && strlen($user))) {
55 // server has to be a non-empty string that is not 'localhost' and not an IP
56 if (strlen($server) && ($server !== 'localhost') && filter_var($server, FILTER_VALIDATE_IP) === false) {
57 if (! dns_get_record($server, DNS_A + DNS_CNAME)) {
58 self::$error = L10n::t('Cannot locate DNS info for database server \'%s\'', $server);
64 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
65 self::$driver = 'pdo';
66 $connect = "mysql:host=".$server.";dbname=".$db;
69 $connect .= ";port=".$port;
72 if (isset($a->config["system"]["db_charset"])) {
73 $connect .= ";charset=".$a->config["system"]["db_charset"];
76 self::$db = @new PDO($connect, $user, $pass);
77 self::$connected = true;
78 } catch (PDOException $e) {
82 if (!self::$connected && class_exists('mysqli')) {
83 self::$driver = 'mysqli';
84 self::$db = @new mysqli($server, $user, $pass, $db, $port);
85 if (!mysqli_connect_errno()) {
86 self::$connected = true;
88 if (isset($a->config["system"]["db_charset"])) {
89 self::$db->set_charset($a->config["system"]["db_charset"]);
94 // No suitable SQL driver was found.
95 if (!self::$connected) {
98 $a->save_timestamp($stamp1, "network");
100 return self::$connected;
104 * @brief Returns the MySQL server version string
106 * This function discriminate between the deprecated mysql API and the current
107 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
111 public static function server_info() {
112 if (self::$_server_info == '') {
113 switch (self::$driver) {
115 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
118 self::$_server_info = self::$db->server_info;
122 return self::$_server_info;
126 * @brief Returns the selected database name
130 public static function database_name() {
131 $ret = self::p("SELECT DATABASE() AS `db`");
132 $data = self::inArray($ret);
133 return $data[0]['db'];
137 * @brief Analyze a database query and log this if some conditions are met.
139 * @param string $query The database query that will be analyzed
141 private static function logIndex($query) {
144 if (empty($a->config["system"]["db_log_index"])) {
148 // Don't explain an explain statement
149 if (strtolower(substr($query, 0, 7)) == "explain") {
153 // Only do the explain on "select", "update" and "delete"
154 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
158 $r = self::p("EXPLAIN ".$query);
159 if (!DBM::is_result($r)) {
163 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
164 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
166 while ($row = dba::fetch($r)) {
167 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
168 $log = (in_array($row['key'], $watchlist) &&
169 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
174 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
178 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
183 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
184 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
185 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
186 basename($backtrace[1]["file"])."\t".
187 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
188 substr($query, 0, 2000)."\n", FILE_APPEND);
193 public static function escape($str) {
194 switch (self::$driver) {
196 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
198 return @self::$db->real_escape_string($str);
202 public static function connected() {
205 switch (self::$driver) {
207 $r = dba::p("SELECT 1");
208 if (DBM::is_result($r)) {
209 $row = dba::inArray($r);
210 $connected = ($row[0]['1'] == '1');
214 $connected = self::$db->ping();
221 * @brief Replaces ANY_VALUE() function by MIN() function,
222 * if the database server does not support ANY_VALUE().
224 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
225 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
226 * A standard fall-back is to use MIN().
228 * @param string $sql An SQL string without the values
229 * @return string The input SQL string modified if necessary.
231 public static function any_value_fallback($sql) {
232 $server_info = self::server_info();
233 if (version_compare($server_info, '5.7.5', '<') ||
234 (stripos($server_info, 'MariaDB') !== false)) {
235 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
241 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
243 * This is safe when we bind the parameters later.
244 * The parameter values aren't part of the SQL.
246 * @param string $sql An SQL string without the values
247 * @return string The input SQL string modified if necessary.
249 public static function clean_query($sql) {
250 $search = ["\t", "\n", "\r", " "];
251 $replace = [' ', ' ', ' ', ' '];
254 $sql = str_replace($search, $replace, $sql);
255 } while ($oldsql != $sql);
262 * @brief Replaces the ? placeholders with the parameters in the $args array
264 * @param string $sql SQL query
265 * @param array $args The parameters that are to replace the ? placeholders
266 * @return string The replaced SQL query
268 private static function replaceParameters($sql, $args) {
270 foreach ($args AS $param => $value) {
271 if (is_int($args[$param]) || is_float($args[$param])) {
272 $replace = intval($args[$param]);
274 $replace = "'".self::escape($args[$param])."'";
277 $pos = strpos($sql, '?', $offset);
278 if ($pos !== false) {
279 $sql = substr_replace($sql, $replace, $pos, 1);
281 $offset = $pos + strlen($replace);
287 * @brief Convert parameter array to an universal form
288 * @param array $args Parameter array
289 * @return array universalized parameter array
291 private static function getParam($args) {
294 // When the second function parameter is an array then use this as the parameter array
295 if ((count($args) > 0) && (is_array($args[1]))) {
303 * @brief Executes a prepared statement that returns data
304 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
306 * Please only use it with complicated queries.
307 * For all regular queries please use dba::select or dba::exists
309 * @param string $sql SQL statement
310 * @return bool|object statement object
312 public static function p($sql) {
315 $stamp1 = microtime(true);
317 $params = self::getParam(func_get_args());
319 // Renumber the array keys to be sure that they fit
322 foreach ($params AS $param) {
323 // Avoid problems with some MySQL servers and boolean values. See issue #3645
324 if (is_bool($param)) {
325 $param = (int)$param;
327 $args[++$i] = $param;
330 if (!self::$connected) {
334 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
335 // Question: Should we continue or stop the query here?
336 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
339 $sql = self::clean_query($sql);
340 $sql = self::any_value_fallback($sql);
344 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
345 $sql = "/*".System::callstack()." */ ".$sql;
350 self::$affected_rows = 0;
352 // We have to make some things different if this function is called from "e"
353 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
355 if (isset($trace[1])) {
356 $called_from = $trace[1];
358 // We use just something that is defined to avoid warnings
359 $called_from = $trace[0];
361 // We are having an own error logging in the function "e"
362 $called_from_e = ($called_from['function'] == 'e');
364 switch (self::$driver) {
366 // If there are no arguments we use "query"
367 if (count($args) == 0) {
368 if (!$retval = self::$db->query($sql)) {
369 $errorInfo = self::$db->errorInfo();
370 self::$error = $errorInfo[2];
371 self::$errorno = $errorInfo[1];
375 self::$affected_rows = $retval->rowCount();
379 if (!$stmt = self::$db->prepare($sql)) {
380 $errorInfo = self::$db->errorInfo();
381 self::$error = $errorInfo[2];
382 self::$errorno = $errorInfo[1];
387 foreach ($args AS $param => $value) {
388 $stmt->bindParam($param, $args[$param]);
391 if (!$stmt->execute()) {
392 $errorInfo = $stmt->errorInfo();
393 self::$error = $errorInfo[2];
394 self::$errorno = $errorInfo[1];
398 self::$affected_rows = $retval->rowCount();
402 // There are SQL statements that cannot be executed with a prepared statement
403 $parts = explode(' ', $orig_sql);
404 $command = strtolower($parts[0]);
405 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
407 // The fallback routine is called as well when there are no arguments
408 if (!$can_be_prepared || (count($args) == 0)) {
409 $retval = self::$db->query(self::replaceParameters($sql, $args));
410 if (self::$db->errno) {
411 self::$error = self::$db->error;
412 self::$errorno = self::$db->errno;
415 if (isset($retval->num_rows)) {
416 self::$affected_rows = $retval->num_rows;
418 self::$affected_rows = self::$db->affected_rows;
424 $stmt = self::$db->stmt_init();
426 if (!$stmt->prepare($sql)) {
427 self::$error = $stmt->error;
428 self::$errorno = $stmt->errno;
435 foreach ($args AS $param => $value) {
436 if (is_int($args[$param])) {
438 } elseif (is_float($args[$param])) {
440 } elseif (is_string($args[$param])) {
445 $values[] = &$args[$param];
448 if (count($values) > 0) {
449 array_unshift($values, $params);
450 call_user_func_array([$stmt, 'bind_param'], $values);
453 if (!$stmt->execute()) {
454 self::$error = self::$db->error;
455 self::$errorno = self::$db->errno;
458 $stmt->store_result();
460 self::$affected_rows = $retval->affected_rows;
465 // We are having an own error logging in the function "e"
466 if ((self::$errorno != 0) && !$called_from_e) {
467 // We have to preserve the error code, somewhere in the logging it get lost
468 $error = self::$error;
469 $errorno = self::$errorno;
471 logger('DB Error '.self::$errorno.': '.self::$error."\n".
472 System::callstack(8)."\n".self::replaceParameters($sql, $params));
474 self::$error = $error;
475 self::$errorno = $errorno;
478 $a->save_timestamp($stamp1, 'database');
480 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
482 $stamp2 = microtime(true);
483 $duration = (float)($stamp2 - $stamp1);
485 if (($duration > $a->config["system"]["db_loglimit"])) {
486 $duration = round($duration, 3);
487 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
489 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
490 basename($backtrace[1]["file"])."\t".
491 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
492 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
499 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
501 * Please use dba::delete, dba::insert, dba::update, ... instead
503 * @param string $sql SQL statement
504 * @return boolean Was the query successfull? False is returned only if an error occurred
506 public static function e($sql) {
509 $stamp = microtime(true);
511 $params = self::getParam(func_get_args());
513 // In a case of a deadlock we are repeating the query 20 times
517 $stmt = self::p($sql, $params);
519 if (is_bool($stmt)) {
521 } elseif (is_object($stmt)) {
529 } while ((self::$errorno == 1213) && (--$timeout > 0));
531 if (self::$errorno != 0) {
532 // We have to preserve the error code, somewhere in the logging it get lost
533 $error = self::$error;
534 $errorno = self::$errorno;
536 logger('DB Error '.self::$errorno.': '.self::$error."\n".
537 System::callstack(8)."\n".self::replaceParameters($sql, $params));
539 self::$error = $error;
540 self::$errorno = $errorno;
543 $a->save_timestamp($stamp, "database_write");
549 * @brief Check if data exists
551 * @param string $table Table name
552 * @param array $condition array of fields for condition
554 * @return boolean Are there rows for that condition?
556 public static function exists($table, $condition) {
564 $first_key = key($condition);
565 if (!is_int($first_key)) {
566 $fields = [$first_key];
569 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
571 if (is_bool($stmt)) {
574 $retval = (self::num_rows($stmt) > 0);
583 * Fetches the first row
585 * Please use dba::selectFirst or dba::exists whenever this is possible.
587 * @brief Fetches the first row
588 * @param string $sql SQL statement
589 * @return array first row of query
591 public static function fetch_first($sql) {
592 $params = self::getParam(func_get_args());
594 $stmt = self::p($sql, $params);
596 if (is_bool($stmt)) {
599 $retval = self::fetch($stmt);
608 * @brief Returns the number of affected rows of the last statement
610 * @return int Number of rows
612 public static function affected_rows() {
613 return self::$affected_rows;
617 * @brief Returns the number of columns of a statement
619 * @param object Statement object
620 * @return int Number of columns
622 public static function columnCount($stmt) {
623 if (!is_object($stmt)) {
626 switch (self::$driver) {
628 return $stmt->columnCount();
630 return $stmt->field_count;
635 * @brief Returns the number of rows of a statement
637 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
638 * @return int Number of rows
640 public static function num_rows($stmt) {
641 if (!is_object($stmt)) {
644 switch (self::$driver) {
646 return $stmt->rowCount();
648 return $stmt->num_rows;
654 * @brief Fetch a single row
656 * @param mixed $stmt statement object
657 * @return array current row
659 public static function fetch($stmt) {
662 $stamp1 = microtime(true);
666 if (!is_object($stmt)) {
670 switch (self::$driver) {
672 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
675 if (get_class($stmt) == 'mysqli_result') {
676 $columns = $stmt->fetch_assoc();
680 // This code works, but is slow
682 // Bind the result to a result array
686 for ($x = 0; $x < $stmt->field_count; $x++) {
687 $cols[] = &$cols_num[$x];
690 call_user_func_array([$stmt, 'bind_result'], $cols);
692 if (!$stmt->fetch()) {
697 // We need to get the field names for the array keys
698 // It seems that there is no better way to do this.
699 $result = $stmt->result_metadata();
700 $fields = $result->fetch_fields();
702 foreach ($cols_num AS $param => $col) {
703 $columns[$fields[$param]->name] = $col;
707 $a->save_timestamp($stamp1, 'database');
713 * @brief Insert a row into a table
715 * @param string $table Table name
716 * @param array $param parameter array
717 * @param bool $on_duplicate_update Do an update on a duplicate entry
719 * @return boolean was the insert successfull?
721 public static function insert($table, $param, $on_duplicate_update = false) {
723 if (empty($table) || empty($param)) {
724 logger('Table and fields have to be set');
728 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
729 substr(str_repeat("?, ", count($param)), 0, -2).")";
731 if ($on_duplicate_update) {
732 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
734 $values = array_values($param);
735 $param = array_merge_recursive($values, $values);
738 return self::e($sql, $param);
742 * @brief Fetch the id of the last insert command
744 * @return integer Last inserted id
746 public static function lastInsertId() {
747 switch (self::$driver) {
749 $id = self::$db->lastInsertId();
752 $id = self::$db->insert_id;
759 * @brief Locks a table for exclusive write access
761 * This function can be extended in the future to accept a table array as well.
763 * @param string $table Table name
765 * @return boolean was the lock successful?
767 public static function lock($table) {
768 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
769 self::e("SET autocommit=0");
770 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
772 self::e("SET autocommit=1");
774 self::$in_transaction = true;
780 * @brief Unlocks all locked tables
782 * @return boolean was the unlock successful?
784 public static function unlock() {
785 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
787 $success = self::e("UNLOCK TABLES");
788 self::e("SET autocommit=1");
789 self::$in_transaction = false;
794 * @brief Starts a transaction
796 * @return boolean Was the command executed successfully?
798 public static function transaction() {
799 if (!self::e('COMMIT')) {
802 if (!self::e('START TRANSACTION')) {
805 self::$in_transaction = true;
810 * @brief Does a commit
812 * @return boolean Was the command executed successfully?
814 public static function commit() {
815 if (!self::e('COMMIT')) {
818 self::$in_transaction = false;
823 * @brief Does a rollback
825 * @return boolean Was the command executed successfully?
827 public static function rollback() {
828 if (!self::e('ROLLBACK')) {
831 self::$in_transaction = false;
836 * @brief Build the array with the table relations
838 * The array is build from the database definitions in DBStructure.php
840 * This process must only be started once, since the value is cached.
842 private static function buildRelationData() {
843 $definition = DBStructure::definition();
845 foreach ($definition AS $table => $structure) {
846 foreach ($structure['fields'] AS $field => $field_struct) {
847 if (isset($field_struct['relation'])) {
848 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
849 self::$relation[$rel_table][$rel_field][$table][] = $field;
857 * @brief Delete a row from a table
859 * @param string $table Table name
860 * @param array $conditions Field condition(s)
861 * @param boolean $in_process Internal use: Only do a commit after the last delete
862 * @param array $callstack Internal use: prevent endless loops
864 * @return boolean|array was the delete successful? When $in_process is set: deletion data
866 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
868 if (empty($table) || empty($conditions)) {
869 logger('Table and conditions have to be set');
875 // Create a key for the loop prevention
876 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
878 // We quit when this key already exists in the callstack.
879 if (isset($callstack[$key])) {
883 $callstack[$key] = true;
885 $table = self::escape($table);
887 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
889 $cascade = defaults($options, 'cascade', true);
891 // To speed up the whole process we cache the table relations
892 if ($cascade && count(self::$relation) == 0) {
893 self::buildRelationData();
896 // Is there a relation entry for the table?
897 if (isset(self::$relation[$table])) {
898 // We only allow a simple "one field" relation.
899 $field = array_keys(self::$relation[$table])[0];
900 $rel_def = array_values(self::$relation[$table])[0];
902 // Create a key for preventing double queries
903 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
905 // When the search field is the relation field, we don't need to fetch the rows
906 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
907 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
908 foreach ($rel_def AS $rel_table => $rel_fields) {
909 foreach ($rel_fields AS $rel_field) {
910 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
911 $commands = array_merge($commands, $retval);
914 // We quit when this key already exists in the callstack.
915 } elseif (!isset($callstack[$qkey])) {
917 $callstack[$qkey] = true;
919 // Fetch all rows that are to be deleted
920 $data = self::select($table, [$field], $conditions);
922 while ($row = self::fetch($data)) {
923 // Now we accumulate the delete commands
924 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
925 $commands = array_merge($commands, $retval);
930 // Since we had split the delete command we don't need the original command anymore
931 unset($commands[$key]);
936 // Now we finalize the process
937 $do_transaction = !self::$in_transaction;
939 if ($do_transaction) {
946 foreach ($commands AS $command) {
947 $conditions = $command['conditions'];
949 $first_key = key($conditions);
951 $condition_string = self::buildCondition($conditions);
953 if ((count($command['conditions']) > 1) || is_int($first_key)) {
954 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
955 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
957 if (!self::e($sql, $conditions)) {
958 if ($do_transaction) {
964 $key_table = $command['table'];
965 $key_condition = array_keys($command['conditions'])[0];
966 $value = array_values($command['conditions'])[0];
968 // Split the SQL queries in chunks of 100 values
969 // We do the $i stuff here to make the code better readable
970 $i = $counter[$key_table][$key_condition];
971 if (count($compacted[$key_table][$key_condition][$i]) > 100) {
975 $compacted[$key_table][$key_condition][$i][$value] = $value;
976 $counter[$key_table][$key_condition] = $i;
979 foreach ($compacted AS $table => $values) {
980 foreach ($values AS $field => $field_value_list) {
981 foreach ($field_value_list AS $field_values) {
982 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
983 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
985 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
987 if (!self::e($sql, $field_values)) {
988 if ($do_transaction) {
996 if ($do_transaction) {
1006 * @brief Updates rows
1008 * Updates rows in the database. When $old_fields is set to an array,
1009 * the system will only do an update if the fields in that array changed.
1012 * Only the values in $old_fields are compared.
1013 * This is an intentional behaviour.
1016 * We include the timestamp field in $fields but not in $old_fields.
1017 * Then the row will only get the new timestamp when the other fields had changed.
1019 * When $old_fields is set to a boolean value the system will do this compare itself.
1020 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1023 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1024 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1026 * @param string $table Table name
1027 * @param array $fields contains the fields that are updated
1028 * @param array $condition condition array with the key values
1029 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1031 * @return boolean was the update successfull?
1033 public static function update($table, $fields, $condition, $old_fields = []) {
1035 if (empty($table) || empty($fields) || empty($condition)) {
1036 logger('Table, fields and condition have to be set');
1040 $table = self::escape($table);
1042 $condition_string = self::buildCondition($condition);
1044 if (is_bool($old_fields)) {
1045 $do_insert = $old_fields;
1047 $old_fields = self::selectFirst($table, [], $condition);
1049 if (is_bool($old_fields)) {
1051 $values = array_merge($condition, $fields);
1052 return self::insert($table, $values, $do_insert);
1058 $do_update = (count($old_fields) == 0);
1060 foreach ($old_fields AS $fieldname => $content) {
1061 if (isset($fields[$fieldname])) {
1062 if ($fields[$fieldname] == $content) {
1063 unset($fields[$fieldname]);
1070 if (!$do_update || (count($fields) == 0)) {
1074 $sql = "UPDATE `".$table."` SET `".
1075 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1077 $params1 = array_values($fields);
1078 $params2 = array_values($condition);
1079 $params = array_merge_recursive($params1, $params2);
1081 return self::e($sql, $params);
1085 * Retrieve a single record from a table and returns it in an associative array
1087 * @brief Retrieve a single record from a table
1088 * @param string $table
1089 * @param array $fields
1090 * @param array $condition
1091 * @param array $params
1092 * @return bool|array
1095 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1097 $params['limit'] = 1;
1098 $result = self::select($table, $fields, $condition, $params);
1100 if (is_bool($result)) {
1103 $row = self::fetch($result);
1104 self::close($result);
1110 * @brief Select rows from a table
1112 * @param string $table Table name
1113 * @param array $fields Array of selected fields, empty for all
1114 * @param array $condition Array of fields for condition
1115 * @param array $params Array of several parameters
1117 * @return boolean|object
1121 * $fields = array("id", "uri", "uid", "network");
1123 * $condition = array("uid" => 1, "network" => 'dspr');
1125 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1127 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1129 * $data = dba::select($table, $fields, $condition, $params);
1131 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1137 $table = self::escape($table);
1139 if (count($fields) > 0) {
1140 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1142 $select_fields = "*";
1145 $condition_string = self::buildCondition($condition);
1148 if (isset($params['order'])) {
1149 $order_string = " ORDER BY ";
1150 foreach ($params['order'] AS $fields => $order) {
1151 if (!is_int($fields)) {
1152 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1154 $order_string .= "`" . $order . "`, ";
1157 $order_string = substr($order_string, 0, -2);
1161 if (isset($params['limit']) && is_int($params['limit'])) {
1162 $limit_string = " LIMIT " . $params['limit'];
1165 if (isset($params['limit']) && is_array($params['limit'])) {
1166 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1169 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1171 $result = self::p($sql, $condition);
1177 * @brief Counts the rows from a table satisfying the provided condition
1179 * @param string $table Table name
1180 * @param array $condition array of fields for condition
1187 * $condition = ["uid" => 1, "network" => 'dspr'];
1189 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1191 * $count = dba::count($table, $condition);
1193 public static function count($table, array $condition = [])
1199 $condition_string = self::buildCondition($condition);
1201 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1203 $row = self::fetch_first($sql, $condition);
1205 return $row['count'];
1209 * @brief Returns the SQL condition string built from the provided condition array
1211 * This function operates with two modes.
1212 * - Supplied with a filed/value associative array, it builds simple strict
1213 * equality conditions linked by AND.
1214 * - Supplied with a flat list, the first element is the condition string and
1215 * the following arguments are the values to be interpolated
1217 * $condition = ["uid" => 1, "network" => 'dspr'];
1219 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1221 * In either case, the provided array is left with the parameters only
1223 * @param array $condition
1226 private static function buildCondition(array &$condition = [])
1228 $condition_string = '';
1229 if (count($condition) > 0) {
1231 $first_key = key($condition);
1232 if (is_int($first_key)) {
1233 $condition_string = " WHERE ".array_shift($condition);
1236 $condition_string = "";
1237 foreach ($condition as $field => $value) {
1238 if ($condition_string != "") {
1239 $condition_string .= " AND ";
1241 if (is_array($value)) {
1242 $new_values = array_merge($new_values, array_values($value));
1243 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1244 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1246 $new_values[$field] = $value;
1247 $condition_string .= "`" . $field . "` = ?";
1250 $condition_string = " WHERE " . $condition_string;
1251 $condition = $new_values;
1255 return $condition_string;
1259 * @brief Fills an array with data from a query
1261 * @param object $stmt statement object
1262 * @return array Data array
1264 public static function inArray($stmt, $do_close = true) {
1265 if (is_bool($stmt)) {
1270 while ($row = self::fetch($stmt)) {
1280 * @brief Returns the error number of the last query
1282 * @return string Error number (0 if no error)
1284 public static function errorNo() {
1285 return self::$errorno;
1289 * @brief Returns the error message of the last query
1291 * @return string Error message ('' if no error)
1293 public static function errorMessage() {
1294 return self::$error;
1298 * @brief Closes the current statement
1300 * @param object $stmt statement object
1301 * @return boolean was the close successful?
1303 public static function close($stmt) {
1306 $stamp1 = microtime(true);
1308 if (!is_object($stmt)) {
1312 switch (self::$driver) {
1314 $ret = $stmt->closeCursor();
1317 $stmt->free_result();
1318 $ret = $stmt->close();
1322 $a->save_timestamp($stamp1, 'database');
1328 function dbesc($str) {
1329 if (dba::$connected) {
1330 return(dba::escape($str));
1332 return(str_replace("'","\\'",$str));
1337 * @brief execute SQL query with printf style args - deprecated
1339 * Please use the dba:: functions instead:
1340 * dba::select, dba::exists, dba::insert
1341 * dba::delete, dba::update, dba::p, dba::e
1343 * @param $args Query parameters (1 to N parameters of different types)
1344 * @return array|bool Query array
1347 $args = func_get_args();
1350 if (!dba::$connected) {
1354 $sql = dba::clean_query($sql);
1355 $sql = dba::any_value_fallback($sql);
1357 $stmt = @vsprintf($sql, $args);
1359 $ret = dba::p($stmt);
1361 if (is_bool($ret)) {
1365 $columns = dba::columnCount($ret);
1367 $data = dba::inArray($ret);
1369 if ((count($data) == 0) && ($columns == 0)) {
1376 function dba_timer() {
1377 return microtime(true);