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 $relation = [];
28 public static function connect($serveraddr, $user, $pass, $db) {
29 if (!is_null(self::$db)) {
35 $stamp1 = microtime(true);
37 $serveraddr = trim($serveraddr);
39 $serverdata = explode(':', $serveraddr);
40 $server = $serverdata[0];
42 if (count($serverdata) > 1) {
43 $port = trim($serverdata[1]);
46 $server = trim($server);
51 if (!(strlen($server) && strlen($user))) {
55 if ($a->mode == App::MODE_INSTALL) {
56 // server has to be a non-empty string that is not 'localhost' and not an IP
57 if (strlen($server) && ($server !== 'localhost') && filter_var($server, FILTER_VALIDATE_IP) === false) {
58 if (! dns_get_record($server, DNS_A + DNS_CNAME)) {
59 self::$error = L10n::t('Cannot locate DNS info for database server \'%s\'', $server);
65 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
66 self::$driver = 'pdo';
67 $connect = "mysql:host=".$server.";dbname=".$db;
70 $connect .= ";port=".$port;
73 if (isset($a->config["system"]["db_charset"])) {
74 $connect .= ";charset=".$a->config["system"]["db_charset"];
77 self::$db = @new PDO($connect, $user, $pass);
78 self::$connected = true;
79 } catch (PDOException $e) {
83 if (!self::$connected && class_exists('mysqli')) {
84 self::$driver = 'mysqli';
85 self::$db = @new mysqli($server, $user, $pass, $db, $port);
86 if (!mysqli_connect_errno()) {
87 self::$connected = true;
89 if (isset($a->config["system"]["db_charset"])) {
90 self::$db->set_charset($a->config["system"]["db_charset"]);
95 // No suitable SQL driver was found.
96 if (!self::$connected) {
100 $a->save_timestamp($stamp1, "network");
102 return self::$connected;
106 * Return the database object.
109 public static function get_db()
115 * @brief Returns the MySQL server version string
117 * This function discriminate between the deprecated mysql API and the current
118 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
122 public static function server_info() {
123 if (self::$_server_info == '') {
124 switch (self::$driver) {
126 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
129 self::$_server_info = self::$db->server_info;
133 return self::$_server_info;
137 * @brief Returns the selected database name
141 public static function database_name() {
142 $ret = self::p("SELECT DATABASE() AS `db`");
143 $data = self::inArray($ret);
144 return $data[0]['db'];
148 * @brief Analyze a database query and log this if some conditions are met.
150 * @param string $query The database query that will be analyzed
152 private static function logIndex($query) {
155 if (empty($a->config["system"]["db_log_index"])) {
159 // Don't explain an explain statement
160 if (strtolower(substr($query, 0, 7)) == "explain") {
164 // Only do the explain on "select", "update" and "delete"
165 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
169 $r = self::p("EXPLAIN ".$query);
170 if (!DBM::is_result($r)) {
174 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
175 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
177 while ($row = dba::fetch($r)) {
178 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
179 $log = (in_array($row['key'], $watchlist) &&
180 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
185 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
189 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
194 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
195 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
196 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
197 basename($backtrace[1]["file"])."\t".
198 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
199 substr($query, 0, 2000)."\n", FILE_APPEND);
204 public static function escape($str) {
205 switch (self::$driver) {
207 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
209 return @self::$db->real_escape_string($str);
213 public static function connected() {
216 switch (self::$driver) {
218 $r = dba::p("SELECT 1");
219 if (DBM::is_result($r)) {
220 $row = dba::inArray($r);
221 $connected = ($row[0]['1'] == '1');
225 $connected = self::$db->ping();
232 * @brief Replaces ANY_VALUE() function by MIN() function,
233 * if the database server does not support ANY_VALUE().
235 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
236 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
237 * A standard fall-back is to use MIN().
239 * @param string $sql An SQL string without the values
240 * @return string The input SQL string modified if necessary.
242 public static function any_value_fallback($sql) {
243 $server_info = self::server_info();
244 if (version_compare($server_info, '5.7.5', '<') ||
245 (stripos($server_info, 'MariaDB') !== false)) {
246 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
252 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
254 * This is safe when we bind the parameters later.
255 * The parameter values aren't part of the SQL.
257 * @param string $sql An SQL string without the values
258 * @return string The input SQL string modified if necessary.
260 public static function clean_query($sql) {
261 $search = ["\t", "\n", "\r", " "];
262 $replace = [' ', ' ', ' ', ' '];
265 $sql = str_replace($search, $replace, $sql);
266 } while ($oldsql != $sql);
273 * @brief Replaces the ? placeholders with the parameters in the $args array
275 * @param string $sql SQL query
276 * @param array $args The parameters that are to replace the ? placeholders
277 * @return string The replaced SQL query
279 private static function replaceParameters($sql, $args) {
281 foreach ($args AS $param => $value) {
282 if (is_int($args[$param]) || is_float($args[$param])) {
283 $replace = intval($args[$param]);
285 $replace = "'".self::escape($args[$param])."'";
288 $pos = strpos($sql, '?', $offset);
289 if ($pos !== false) {
290 $sql = substr_replace($sql, $replace, $pos, 1);
292 $offset = $pos + strlen($replace);
298 * @brief Convert parameter array to an universal form
299 * @param array $args Parameter array
300 * @return array universalized parameter array
302 private static function getParam($args) {
305 // When the second function parameter is an array then use this as the parameter array
306 if ((count($args) > 0) && (is_array($args[1]))) {
314 * @brief Executes a prepared statement that returns data
315 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
317 * Please only use it with complicated queries.
318 * For all regular queries please use dba::select or dba::exists
320 * @param string $sql SQL statement
321 * @return bool|object statement object
323 public static function p($sql) {
326 $stamp1 = microtime(true);
328 $params = self::getParam(func_get_args());
330 // Renumber the array keys to be sure that they fit
333 foreach ($params AS $param) {
334 // Avoid problems with some MySQL servers and boolean values. See issue #3645
335 if (is_bool($param)) {
336 $param = (int)$param;
338 $args[++$i] = $param;
341 if (!self::$connected) {
345 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
346 // Question: Should we continue or stop the query here?
347 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
350 $sql = self::clean_query($sql);
351 $sql = self::any_value_fallback($sql);
355 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
356 $sql = "/*".System::callstack()." */ ".$sql;
361 self::$affected_rows = 0;
363 // We have to make some things different if this function is called from "e"
364 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
366 if (isset($trace[1])) {
367 $called_from = $trace[1];
369 // We use just something that is defined to avoid warnings
370 $called_from = $trace[0];
372 // We are having an own error logging in the function "e"
373 $called_from_e = ($called_from['function'] == 'e');
375 switch (self::$driver) {
377 // If there are no arguments we use "query"
378 if (count($args) == 0) {
379 if (!$retval = self::$db->query($sql)) {
380 $errorInfo = self::$db->errorInfo();
381 self::$error = $errorInfo[2];
382 self::$errorno = $errorInfo[1];
386 self::$affected_rows = $retval->rowCount();
390 if (!$stmt = self::$db->prepare($sql)) {
391 $errorInfo = self::$db->errorInfo();
392 self::$error = $errorInfo[2];
393 self::$errorno = $errorInfo[1];
398 foreach ($args AS $param => $value) {
399 $stmt->bindParam($param, $args[$param]);
402 if (!$stmt->execute()) {
403 $errorInfo = $stmt->errorInfo();
404 self::$error = $errorInfo[2];
405 self::$errorno = $errorInfo[1];
409 self::$affected_rows = $retval->rowCount();
413 // There are SQL statements that cannot be executed with a prepared statement
414 $parts = explode(' ', $orig_sql);
415 $command = strtolower($parts[0]);
416 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
418 // The fallback routine is called as well when there are no arguments
419 if (!$can_be_prepared || (count($args) == 0)) {
420 $retval = self::$db->query(self::replaceParameters($sql, $args));
421 if (self::$db->errno) {
422 self::$error = self::$db->error;
423 self::$errorno = self::$db->errno;
426 if (isset($retval->num_rows)) {
427 self::$affected_rows = $retval->num_rows;
429 self::$affected_rows = self::$db->affected_rows;
435 $stmt = self::$db->stmt_init();
437 if (!$stmt->prepare($sql)) {
438 self::$error = $stmt->error;
439 self::$errorno = $stmt->errno;
446 foreach ($args AS $param => $value) {
447 if (is_int($args[$param])) {
449 } elseif (is_float($args[$param])) {
451 } elseif (is_string($args[$param])) {
456 $values[] = &$args[$param];
459 if (count($values) > 0) {
460 array_unshift($values, $params);
461 call_user_func_array([$stmt, 'bind_param'], $values);
464 if (!$stmt->execute()) {
465 self::$error = self::$db->error;
466 self::$errorno = self::$db->errno;
469 $stmt->store_result();
471 self::$affected_rows = $retval->affected_rows;
476 // We are having an own error logging in the function "e"
477 if ((self::$errorno != 0) && !$called_from_e) {
478 // We have to preserve the error code, somewhere in the logging it get lost
479 $error = self::$error;
480 $errorno = self::$errorno;
482 logger('DB Error '.self::$errorno.': '.self::$error."\n".
483 System::callstack(8)."\n".self::replaceParameters($sql, $params));
485 self::$error = $error;
486 self::$errorno = $errorno;
489 $a->save_timestamp($stamp1, 'database');
491 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
493 $stamp2 = microtime(true);
494 $duration = (float)($stamp2 - $stamp1);
496 if (($duration > $a->config["system"]["db_loglimit"])) {
497 $duration = round($duration, 3);
498 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
500 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
501 basename($backtrace[1]["file"])."\t".
502 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
503 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
510 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
512 * Please use dba::delete, dba::insert, dba::update, ... instead
514 * @param string $sql SQL statement
515 * @return boolean Was the query successfull? False is returned only if an error occurred
517 public static function e($sql) {
520 $stamp = microtime(true);
522 $params = self::getParam(func_get_args());
524 // In a case of a deadlock we are repeating the query 20 times
528 $stmt = self::p($sql, $params);
530 if (is_bool($stmt)) {
532 } elseif (is_object($stmt)) {
540 } while ((self::$errorno == 1213) && (--$timeout > 0));
542 if (self::$errorno != 0) {
543 // We have to preserve the error code, somewhere in the logging it get lost
544 $error = self::$error;
545 $errorno = self::$errorno;
547 logger('DB Error '.self::$errorno.': '.self::$error."\n".
548 System::callstack(8)."\n".self::replaceParameters($sql, $params));
550 self::$error = $error;
551 self::$errorno = $errorno;
554 $a->save_timestamp($stamp, "database_write");
560 * @brief Check if data exists
562 * @param string $table Table name
563 * @param array $condition array of fields for condition
565 * @return boolean Are there rows for that condition?
567 public static function exists($table, $condition) {
575 $first_key = key($condition);
576 if (!is_int($first_key)) {
577 $fields = [$first_key];
580 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
582 if (is_bool($stmt)) {
585 $retval = (self::num_rows($stmt) > 0);
594 * Fetches the first row
596 * Please use dba::selectFirst or dba::exists whenever this is possible.
598 * @brief Fetches the first row
599 * @param string $sql SQL statement
600 * @return array first row of query
602 public static function fetch_first($sql) {
603 $params = self::getParam(func_get_args());
605 $stmt = self::p($sql, $params);
607 if (is_bool($stmt)) {
610 $retval = self::fetch($stmt);
619 * @brief Returns the number of affected rows of the last statement
621 * @return int Number of rows
623 public static function affected_rows() {
624 return self::$affected_rows;
628 * @brief Returns the number of columns of a statement
630 * @param object Statement object
631 * @return int Number of columns
633 public static function columnCount($stmt) {
634 if (!is_object($stmt)) {
637 switch (self::$driver) {
639 return $stmt->columnCount();
641 return $stmt->field_count;
646 * @brief Returns the number of rows of a statement
648 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
649 * @return int Number of rows
651 public static function num_rows($stmt) {
652 if (!is_object($stmt)) {
655 switch (self::$driver) {
657 return $stmt->rowCount();
659 return $stmt->num_rows;
665 * @brief Fetch a single row
667 * @param mixed $stmt statement object
668 * @return array current row
670 public static function fetch($stmt) {
673 $stamp1 = microtime(true);
677 if (!is_object($stmt)) {
681 switch (self::$driver) {
683 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
686 if (get_class($stmt) == 'mysqli_result') {
687 $columns = $stmt->fetch_assoc();
691 // This code works, but is slow
693 // Bind the result to a result array
697 for ($x = 0; $x < $stmt->field_count; $x++) {
698 $cols[] = &$cols_num[$x];
701 call_user_func_array([$stmt, 'bind_result'], $cols);
703 if (!$stmt->fetch()) {
708 // We need to get the field names for the array keys
709 // It seems that there is no better way to do this.
710 $result = $stmt->result_metadata();
711 $fields = $result->fetch_fields();
713 foreach ($cols_num AS $param => $col) {
714 $columns[$fields[$param]->name] = $col;
718 $a->save_timestamp($stamp1, 'database');
724 * @brief Insert a row into a table
726 * @param string $table Table name
727 * @param array $param parameter array
728 * @param bool $on_duplicate_update Do an update on a duplicate entry
730 * @return boolean was the insert successfull?
732 public static function insert($table, $param, $on_duplicate_update = false) {
734 if (empty($table) || empty($param)) {
735 logger('Table and fields have to be set');
739 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
740 substr(str_repeat("?, ", count($param)), 0, -2).")";
742 if ($on_duplicate_update) {
743 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
745 $values = array_values($param);
746 $param = array_merge_recursive($values, $values);
749 return self::e($sql, $param);
753 * @brief Fetch the id of the last insert command
755 * @return integer Last inserted id
757 public static function lastInsertId() {
758 switch (self::$driver) {
760 $id = self::$db->lastInsertId();
763 $id = self::$db->insert_id;
770 * @brief Locks a table for exclusive write access
772 * This function can be extended in the future to accept a table array as well.
774 * @param string $table Table name
776 * @return boolean was the lock successful?
778 public static function lock($table) {
779 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
780 self::e("SET autocommit=0");
781 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
783 self::e("SET autocommit=1");
785 self::$in_transaction = true;
791 * @brief Unlocks all locked tables
793 * @return boolean was the unlock successful?
795 public static function unlock() {
796 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
798 $success = self::e("UNLOCK TABLES");
799 self::e("SET autocommit=1");
800 self::$in_transaction = false;
805 * @brief Starts a transaction
807 * @return boolean Was the command executed successfully?
809 public static function transaction() {
810 if (!self::e('COMMIT')) {
813 if (!self::e('START TRANSACTION')) {
816 self::$in_transaction = true;
821 * @brief Does a commit
823 * @return boolean Was the command executed successfully?
825 public static function commit() {
826 if (!self::e('COMMIT')) {
829 self::$in_transaction = false;
834 * @brief Does a rollback
836 * @return boolean Was the command executed successfully?
838 public static function rollback() {
839 if (!self::e('ROLLBACK')) {
842 self::$in_transaction = false;
847 * @brief Build the array with the table relations
849 * The array is build from the database definitions in DBStructure.php
851 * This process must only be started once, since the value is cached.
853 private static function buildRelationData() {
854 $definition = DBStructure::definition();
856 foreach ($definition AS $table => $structure) {
857 foreach ($structure['fields'] AS $field => $field_struct) {
858 if (isset($field_struct['relation'])) {
859 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
860 self::$relation[$rel_table][$rel_field][$table][] = $field;
868 * @brief Delete a row from a table
870 * @param string $table Table name
871 * @param array $conditions Field condition(s)
872 * @param array $options
873 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
874 * relations (default: true)
875 * @param boolean $in_process Internal use: Only do a commit after the last delete
876 * @param array $callstack Internal use: prevent endless loops
878 * @return boolean|array was the delete successful? When $in_process is set: deletion data
880 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
882 if (empty($table) || empty($conditions)) {
883 logger('Table and conditions have to be set');
889 // Create a key for the loop prevention
890 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
892 // We quit when this key already exists in the callstack.
893 if (isset($callstack[$key])) {
897 $callstack[$key] = true;
899 $table = self::escape($table);
901 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
903 $cascade = defaults($options, 'cascade', true);
905 // To speed up the whole process we cache the table relations
906 if ($cascade && count(self::$relation) == 0) {
907 self::buildRelationData();
910 // Is there a relation entry for the table?
911 if ($cascade && isset(self::$relation[$table])) {
912 // We only allow a simple "one field" relation.
913 $field = array_keys(self::$relation[$table])[0];
914 $rel_def = array_values(self::$relation[$table])[0];
916 // Create a key for preventing double queries
917 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
919 // When the search field is the relation field, we don't need to fetch the rows
920 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
921 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
922 foreach ($rel_def AS $rel_table => $rel_fields) {
923 foreach ($rel_fields AS $rel_field) {
924 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
925 $commands = array_merge($commands, $retval);
928 // We quit when this key already exists in the callstack.
929 } elseif (!isset($callstack[$qkey])) {
931 $callstack[$qkey] = true;
933 // Fetch all rows that are to be deleted
934 $data = self::select($table, [$field], $conditions);
936 while ($row = self::fetch($data)) {
937 // Now we accumulate the delete commands
938 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
939 $commands = array_merge($commands, $retval);
944 // Since we had split the delete command we don't need the original command anymore
945 unset($commands[$key]);
950 // Now we finalize the process
951 $do_transaction = !self::$in_transaction;
953 if ($do_transaction) {
960 foreach ($commands AS $command) {
961 $conditions = $command['conditions'];
963 $first_key = key($conditions);
965 $condition_string = self::buildCondition($conditions);
967 if ((count($command['conditions']) > 1) || is_int($first_key)) {
968 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
969 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
971 if (!self::e($sql, $conditions)) {
972 if ($do_transaction) {
978 $key_table = $command['table'];
979 $key_condition = array_keys($command['conditions'])[0];
980 $value = array_values($command['conditions'])[0];
982 // Split the SQL queries in chunks of 100 values
983 // We do the $i stuff here to make the code better readable
984 $i = $counter[$key_table][$key_condition];
985 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
989 $compacted[$key_table][$key_condition][$i][$value] = $value;
990 $counter[$key_table][$key_condition] = $i;
993 foreach ($compacted AS $table => $values) {
994 foreach ($values AS $field => $field_value_list) {
995 foreach ($field_value_list AS $field_values) {
996 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
997 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
999 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1001 if (!self::e($sql, $field_values)) {
1002 if ($do_transaction) {
1010 if ($do_transaction) {
1020 * @brief Updates rows
1022 * Updates rows in the database. When $old_fields is set to an array,
1023 * the system will only do an update if the fields in that array changed.
1026 * Only the values in $old_fields are compared.
1027 * This is an intentional behaviour.
1030 * We include the timestamp field in $fields but not in $old_fields.
1031 * Then the row will only get the new timestamp when the other fields had changed.
1033 * When $old_fields is set to a boolean value the system will do this compare itself.
1034 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1037 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1038 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1040 * @param string $table Table name
1041 * @param array $fields contains the fields that are updated
1042 * @param array $condition condition array with the key values
1043 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1045 * @return boolean was the update successfull?
1047 public static function update($table, $fields, $condition, $old_fields = []) {
1049 if (empty($table) || empty($fields) || empty($condition)) {
1050 logger('Table, fields and condition have to be set');
1054 $table = self::escape($table);
1056 $condition_string = self::buildCondition($condition);
1058 if (is_bool($old_fields)) {
1059 $do_insert = $old_fields;
1061 $old_fields = self::selectFirst($table, [], $condition);
1063 if (is_bool($old_fields)) {
1065 $values = array_merge($condition, $fields);
1066 return self::insert($table, $values, $do_insert);
1072 $do_update = (count($old_fields) == 0);
1074 foreach ($old_fields AS $fieldname => $content) {
1075 if (isset($fields[$fieldname])) {
1076 if ($fields[$fieldname] == $content) {
1077 unset($fields[$fieldname]);
1084 if (!$do_update || (count($fields) == 0)) {
1088 $sql = "UPDATE `".$table."` SET `".
1089 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1091 $params1 = array_values($fields);
1092 $params2 = array_values($condition);
1093 $params = array_merge_recursive($params1, $params2);
1095 return self::e($sql, $params);
1099 * Retrieve a single record from a table and returns it in an associative array
1101 * @brief Retrieve a single record from a table
1102 * @param string $table
1103 * @param array $fields
1104 * @param array $condition
1105 * @param array $params
1106 * @return bool|array
1109 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1111 $params['limit'] = 1;
1112 $result = self::select($table, $fields, $condition, $params);
1114 if (is_bool($result)) {
1117 $row = self::fetch($result);
1118 self::close($result);
1124 * @brief Select rows from a table
1126 * @param string $table Table name
1127 * @param array $fields Array of selected fields, empty for all
1128 * @param array $condition Array of fields for condition
1129 * @param array $params Array of several parameters
1131 * @return boolean|object
1135 * $fields = array("id", "uri", "uid", "network");
1137 * $condition = array("uid" => 1, "network" => 'dspr');
1139 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1141 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1143 * $data = dba::select($table, $fields, $condition, $params);
1145 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1151 $table = self::escape($table);
1153 if (count($fields) > 0) {
1154 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1156 $select_fields = "*";
1159 $condition_string = self::buildCondition($condition);
1162 if (isset($params['order'])) {
1163 $order_string = " ORDER BY ";
1164 foreach ($params['order'] AS $fields => $order) {
1165 if (!is_int($fields)) {
1166 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1168 $order_string .= "`" . $order . "`, ";
1171 $order_string = substr($order_string, 0, -2);
1175 if (isset($params['limit']) && is_int($params['limit'])) {
1176 $limit_string = " LIMIT " . $params['limit'];
1179 if (isset($params['limit']) && is_array($params['limit'])) {
1180 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1183 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1185 $result = self::p($sql, $condition);
1191 * @brief Counts the rows from a table satisfying the provided condition
1193 * @param string $table Table name
1194 * @param array $condition array of fields for condition
1201 * $condition = ["uid" => 1, "network" => 'dspr'];
1203 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1205 * $count = dba::count($table, $condition);
1207 public static function count($table, array $condition = [])
1213 $condition_string = self::buildCondition($condition);
1215 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1217 $row = self::fetch_first($sql, $condition);
1219 return $row['count'];
1223 * @brief Returns the SQL condition string built from the provided condition array
1225 * This function operates with two modes.
1226 * - Supplied with a filed/value associative array, it builds simple strict
1227 * equality conditions linked by AND.
1228 * - Supplied with a flat list, the first element is the condition string and
1229 * the following arguments are the values to be interpolated
1231 * $condition = ["uid" => 1, "network" => 'dspr'];
1233 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1235 * In either case, the provided array is left with the parameters only
1237 * @param array $condition
1240 private static function buildCondition(array &$condition = [])
1242 $condition_string = '';
1243 if (count($condition) > 0) {
1245 $first_key = key($condition);
1246 if (is_int($first_key)) {
1247 $condition_string = " WHERE ".array_shift($condition);
1250 $condition_string = "";
1251 foreach ($condition as $field => $value) {
1252 if ($condition_string != "") {
1253 $condition_string .= " AND ";
1255 if (is_array($value)) {
1256 $new_values = array_merge($new_values, array_values($value));
1257 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1258 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1260 $new_values[$field] = $value;
1261 $condition_string .= "`" . $field . "` = ?";
1264 $condition_string = " WHERE " . $condition_string;
1265 $condition = $new_values;
1269 return $condition_string;
1273 * @brief Fills an array with data from a query
1275 * @param object $stmt statement object
1276 * @return array Data array
1278 public static function inArray($stmt, $do_close = true) {
1279 if (is_bool($stmt)) {
1284 while ($row = self::fetch($stmt)) {
1294 * @brief Returns the error number of the last query
1296 * @return string Error number (0 if no error)
1298 public static function errorNo() {
1299 return self::$errorno;
1303 * @brief Returns the error message of the last query
1305 * @return string Error message ('' if no error)
1307 public static function errorMessage() {
1308 return self::$error;
1312 * @brief Closes the current statement
1314 * @param object $stmt statement object
1315 * @return boolean was the close successful?
1317 public static function close($stmt) {
1320 $stamp1 = microtime(true);
1322 if (!is_object($stmt)) {
1326 switch (self::$driver) {
1328 $ret = $stmt->closeCursor();
1331 $stmt->free_result();
1332 $ret = $stmt->close();
1336 $a->save_timestamp($stamp1, 'database');
1342 function dbesc($str) {
1343 if (dba::$connected) {
1344 return(dba::escape($str));
1346 return(str_replace("'","\\'",$str));
1351 * @brief execute SQL query with printf style args - deprecated
1353 * Please use the dba:: functions instead:
1354 * dba::select, dba::exists, dba::insert
1355 * dba::delete, dba::update, dba::p, dba::e
1357 * @param $args Query parameters (1 to N parameters of different types)
1358 * @return array|bool Query array
1361 $args = func_get_args();
1364 if (!dba::$connected) {
1368 $sql = dba::clean_query($sql);
1369 $sql = dba::any_value_fallback($sql);
1371 $stmt = @vsprintf($sql, $args);
1373 $ret = dba::p($stmt);
1375 if (is_bool($ret)) {
1379 $columns = dba::columnCount($ret);
1381 $data = dba::inArray($ret);
1383 if ((count($data) == 0) && ($columns == 0)) {
1390 function dba_timer() {
1391 return microtime(true);