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 = true;
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))) {
51 self::$connected = false;
57 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
58 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
59 self::$error = L10n::t('Cannot locate DNS info for database server \'%s\'', $server);
60 self::$connected = false;
67 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
68 self::$driver = 'pdo';
69 $connect = "mysql:host=".$server.";dbname=".$db;
72 $connect .= ";port=".$port;
75 if (isset($a->config["system"]["db_charset"])) {
76 $connect .= ";charset=".$a->config["system"]["db_charset"];
79 self::$db = @new PDO($connect, $user, $pass);
80 self::$connected = true;
81 } catch (PDOException $e) {
82 self::$connected = false;
86 if (!self::$connected && class_exists('mysqli')) {
87 self::$driver = 'mysqli';
88 self::$db = @new mysqli($server, $user, $pass, $db, $port);
89 if (!mysqli_connect_errno()) {
90 self::$connected = true;
92 if (isset($a->config["system"]["db_charset"])) {
93 self::$db->set_charset($a->config["system"]["db_charset"]);
98 // No suitable SQL driver was found.
99 if (!self::$connected) {
102 System::unavailable();
106 $a->save_timestamp($stamp1, "network");
112 * @brief Returns the MySQL server version string
114 * This function discriminate between the deprecated mysql API and the current
115 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
119 public static function server_info() {
120 if (self::$_server_info == '') {
121 switch (self::$driver) {
123 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
126 self::$_server_info = self::$db->server_info;
130 return self::$_server_info;
134 * @brief Returns the selected database name
138 public static function database_name() {
139 $ret = self::p("SELECT DATABASE() AS `db`");
140 $data = self::inArray($ret);
141 return $data[0]['db'];
145 * @brief Analyze a database query and log this if some conditions are met.
147 * @param string $query The database query that will be analyzed
149 private static function log_index($query) {
152 if (empty($a->config["system"]["db_log_index"])) {
156 // Don't explain an explain statement
157 if (strtolower(substr($query, 0, 7)) == "explain") {
161 // Only do the explain on "select", "update" and "delete"
162 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
166 $r = self::p("EXPLAIN ".$query);
167 if (!DBM::is_result($r)) {
171 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
172 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
174 while ($row = dba::fetch($r)) {
175 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
176 $log = (in_array($row['key'], $watchlist) &&
177 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
182 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
186 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
191 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
192 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
193 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
194 basename($backtrace[1]["file"])."\t".
195 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
196 substr($query, 0, 2000)."\n", FILE_APPEND);
201 public static function escape($str) {
202 switch (self::$driver) {
204 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
206 return @self::$db->real_escape_string($str);
210 public static function connected() {
213 switch (self::$driver) {
215 $r = dba::p("SELECT 1");
216 if (DBM::is_result($r)) {
217 $row = dba::inArray($r);
218 $connected = ($row[0]['1'] == '1');
222 $connected = self::$db->ping();
229 * @brief Replaces ANY_VALUE() function by MIN() function,
230 * if the database server does not support ANY_VALUE().
232 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
233 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
234 * A standard fall-back is to use MIN().
236 * @param string $sql An SQL string without the values
237 * @return string The input SQL string modified if necessary.
239 public static function any_value_fallback($sql) {
240 $server_info = self::server_info();
241 if (version_compare($server_info, '5.7.5', '<') ||
242 (stripos($server_info, 'MariaDB') !== false)) {
243 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
249 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
251 * This is safe when we bind the parameters later.
252 * The parameter values aren't part of the SQL.
254 * @param string $sql An SQL string without the values
255 * @return string The input SQL string modified if necessary.
257 public static function clean_query($sql) {
258 $search = ["\t", "\n", "\r", " "];
259 $replace = [' ', ' ', ' ', ' '];
262 $sql = str_replace($search, $replace, $sql);
263 } while ($oldsql != $sql);
270 * @brief Replaces the ? placeholders with the parameters in the $args array
272 * @param string $sql SQL query
273 * @param array $args The parameters that are to replace the ? placeholders
274 * @return string The replaced SQL query
276 private static function replace_parameters($sql, $args) {
278 foreach ($args AS $param => $value) {
279 if (is_int($args[$param]) || is_float($args[$param])) {
280 $replace = intval($args[$param]);
282 $replace = "'".self::escape($args[$param])."'";
285 $pos = strpos($sql, '?', $offset);
286 if ($pos !== false) {
287 $sql = substr_replace($sql, $replace, $pos, 1);
289 $offset = $pos + strlen($replace);
295 * @brief Convert parameter array to an universal form
296 * @param array $args Parameter array
297 * @return array universalized parameter array
299 private static function getParam($args) {
302 // When the second function parameter is an array then use this as the parameter array
303 if ((count($args) > 0) && (is_array($args[1]))) {
311 * @brief Executes a prepared statement that returns data
312 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
314 * Please only use it with complicated queries.
315 * For all regular queries please use dba::select or dba::exists
317 * @param string $sql SQL statement
318 * @return bool|object statement object
320 public static function p($sql) {
323 $stamp1 = microtime(true);
325 $params = self::getParam(func_get_args());
327 // Renumber the array keys to be sure that they fit
330 foreach ($params AS $param) {
331 // Avoid problems with some MySQL servers and boolean values. See issue #3645
332 if (is_bool($param)) {
333 $param = (int)$param;
335 $args[++$i] = $param;
338 if (!self::$connected) {
342 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
343 // Question: Should we continue or stop the query here?
344 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
347 $sql = self::clean_query($sql);
348 $sql = self::any_value_fallback($sql);
352 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
353 $sql = "/*".System::callstack()." */ ".$sql;
358 self::$affected_rows = 0;
360 // We have to make some things different if this function is called from "e"
361 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
363 if (isset($trace[1])) {
364 $called_from = $trace[1];
366 // We use just something that is defined to avoid warnings
367 $called_from = $trace[0];
369 // We are having an own error logging in the function "e"
370 $called_from_e = ($called_from['function'] == 'e');
372 switch (self::$driver) {
374 // If there are no arguments we use "query"
375 if (count($args) == 0) {
376 if (!$retval = self::$db->query($sql)) {
377 $errorInfo = self::$db->errorInfo();
378 self::$error = $errorInfo[2];
379 self::$errorno = $errorInfo[1];
383 self::$affected_rows = $retval->rowCount();
387 if (!$stmt = self::$db->prepare($sql)) {
388 $errorInfo = self::$db->errorInfo();
389 self::$error = $errorInfo[2];
390 self::$errorno = $errorInfo[1];
395 foreach ($args AS $param => $value) {
396 $stmt->bindParam($param, $args[$param]);
399 if (!$stmt->execute()) {
400 $errorInfo = $stmt->errorInfo();
401 self::$error = $errorInfo[2];
402 self::$errorno = $errorInfo[1];
406 self::$affected_rows = $retval->rowCount();
410 // There are SQL statements that cannot be executed with a prepared statement
411 $parts = explode(' ', $orig_sql);
412 $command = strtolower($parts[0]);
413 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
415 // The fallback routine is called as well when there are no arguments
416 if (!$can_be_prepared || (count($args) == 0)) {
417 $retval = self::$db->query(self::replace_parameters($sql, $args));
418 if (self::$db->errno) {
419 self::$error = self::$db->error;
420 self::$errorno = self::$db->errno;
423 if (isset($retval->num_rows)) {
424 self::$affected_rows = $retval->num_rows;
426 self::$affected_rows = self::$db->affected_rows;
432 $stmt = self::$db->stmt_init();
434 if (!$stmt->prepare($sql)) {
435 self::$error = $stmt->error;
436 self::$errorno = $stmt->errno;
443 foreach ($args AS $param => $value) {
444 if (is_int($args[$param])) {
446 } elseif (is_float($args[$param])) {
448 } elseif (is_string($args[$param])) {
453 $values[] = &$args[$param];
456 if (count($values) > 0) {
457 array_unshift($values, $params);
458 call_user_func_array([$stmt, 'bind_param'], $values);
461 if (!$stmt->execute()) {
462 self::$error = self::$db->error;
463 self::$errorno = self::$db->errno;
466 $stmt->store_result();
468 self::$affected_rows = $retval->affected_rows;
473 // We are having an own error logging in the function "e"
474 if ((self::$errorno != 0) && !$called_from_e) {
475 // We have to preserve the error code, somewhere in the logging it get lost
476 $error = self::$error;
477 $errorno = self::$errorno;
479 logger('DB Error '.self::$errorno.': '.self::$error."\n".
480 System::callstack(8)."\n".self::replace_parameters($sql, $params));
482 self::$error = $error;
483 self::$errorno = $errorno;
486 $a->save_timestamp($stamp1, 'database');
488 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
490 $stamp2 = microtime(true);
491 $duration = (float)($stamp2 - $stamp1);
493 if (($duration > $a->config["system"]["db_loglimit"])) {
494 $duration = round($duration, 3);
495 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
497 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
498 basename($backtrace[1]["file"])."\t".
499 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
500 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
507 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
509 * Please use dba::delete, dba::insert, dba::update, ... instead
511 * @param string $sql SQL statement
512 * @return boolean Was the query successfull? False is returned only if an error occurred
514 public static function e($sql) {
517 $stamp = microtime(true);
519 $params = self::getParam(func_get_args());
521 // In a case of a deadlock we are repeating the query 20 times
525 $stmt = self::p($sql, $params);
527 if (is_bool($stmt)) {
529 } elseif (is_object($stmt)) {
537 } while ((self::$errorno == 1213) && (--$timeout > 0));
539 if (self::$errorno != 0) {
540 // We have to preserve the error code, somewhere in the logging it get lost
541 $error = self::$error;
542 $errorno = self::$errorno;
544 logger('DB Error '.self::$errorno.': '.self::$error."\n".
545 System::callstack(8)."\n".self::replace_parameters($sql, $params));
547 self::$error = $error;
548 self::$errorno = $errorno;
551 $a->save_timestamp($stamp, "database_write");
557 * @brief Check if data exists
559 * @param string $table Table name
560 * @param array $condition array of fields for condition
562 * @return boolean Are there rows for that condition?
564 public static function exists($table, $condition) {
571 $array_element = each($condition);
572 $array_key = $array_element['key'];
573 if (!is_int($array_key)) {
574 $fields = [$array_key];
577 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
579 if (is_bool($stmt)) {
582 $retval = (self::num_rows($stmt) > 0);
591 * Fetches the first row
593 * Please use dba::selectFirst or dba::exists whenever this is possible.
595 * @brief Fetches the first row
596 * @param string $sql SQL statement
597 * @return array first row of query
599 public static function fetch_first($sql) {
600 $params = self::getParam(func_get_args());
602 $stmt = self::p($sql, $params);
604 if (is_bool($stmt)) {
607 $retval = self::fetch($stmt);
616 * @brief Returns the number of affected rows of the last statement
618 * @return int Number of rows
620 public static function affected_rows() {
621 return self::$affected_rows;
625 * @brief Returns the number of columns of a statement
627 * @param object Statement object
628 * @return int Number of columns
630 public static function columnCount($stmt) {
631 if (!is_object($stmt)) {
634 switch (self::$driver) {
636 return $stmt->columnCount();
638 return $stmt->field_count;
643 * @brief Returns the number of rows of a statement
645 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
646 * @return int Number of rows
648 public static function num_rows($stmt) {
649 if (!is_object($stmt)) {
652 switch (self::$driver) {
654 return $stmt->rowCount();
656 return $stmt->num_rows;
662 * @brief Fetch a single row
664 * @param mixed $stmt statement object
665 * @return array current row
667 public static function fetch($stmt) {
670 $stamp1 = microtime(true);
674 if (!is_object($stmt)) {
678 switch (self::$driver) {
680 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
683 if (get_class($stmt) == 'mysqli_result') {
684 $columns = $stmt->fetch_assoc();
688 // This code works, but is slow
690 // Bind the result to a result array
694 for ($x = 0; $x < $stmt->field_count; $x++) {
695 $cols[] = &$cols_num[$x];
698 call_user_func_array([$stmt, 'bind_result'], $cols);
700 if (!$stmt->fetch()) {
705 // We need to get the field names for the array keys
706 // It seems that there is no better way to do this.
707 $result = $stmt->result_metadata();
708 $fields = $result->fetch_fields();
710 foreach ($cols_num AS $param => $col) {
711 $columns[$fields[$param]->name] = $col;
715 $a->save_timestamp($stamp1, 'database');
721 * @brief Insert a row into a table
723 * @param string $table Table name
724 * @param array $param parameter array
725 * @param bool $on_duplicate_update Do an update on a duplicate entry
727 * @return boolean was the insert successfull?
729 public static function insert($table, $param, $on_duplicate_update = false) {
731 if (empty($table) || empty($param)) {
732 logger('Table and fields have to be set');
736 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
737 substr(str_repeat("?, ", count($param)), 0, -2).")";
739 if ($on_duplicate_update) {
740 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
742 $values = array_values($param);
743 $param = array_merge_recursive($values, $values);
746 return self::e($sql, $param);
750 * @brief Fetch the id of the last insert command
752 * @return integer Last inserted id
754 public static function lastInsertId() {
755 switch (self::$driver) {
757 $id = self::$db->lastInsertId();
760 $id = self::$db->insert_id;
767 * @brief Locks a table for exclusive write access
769 * This function can be extended in the future to accept a table array as well.
771 * @param string $table Table name
773 * @return boolean was the lock successful?
775 public static function lock($table) {
776 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
777 self::e("SET autocommit=0");
778 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
780 self::e("SET autocommit=1");
782 self::$in_transaction = true;
788 * @brief Unlocks all locked tables
790 * @return boolean was the unlock successful?
792 public static function unlock() {
793 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
795 $success = self::e("UNLOCK TABLES");
796 self::e("SET autocommit=1");
797 self::$in_transaction = false;
802 * @brief Starts a transaction
804 * @return boolean Was the command executed successfully?
806 public static function transaction() {
807 if (!self::e('COMMIT')) {
810 if (!self::e('START TRANSACTION')) {
813 self::$in_transaction = true;
818 * @brief Does a commit
820 * @return boolean Was the command executed successfully?
822 public static function commit() {
823 if (!self::e('COMMIT')) {
826 self::$in_transaction = false;
831 * @brief Does a rollback
833 * @return boolean Was the command executed successfully?
835 public static function rollback() {
836 if (!self::e('ROLLBACK')) {
839 self::$in_transaction = false;
844 * @brief Build the array with the table relations
846 * The array is build from the database definitions in DBStructure.php
848 * This process must only be started once, since the value is cached.
850 private static function build_relation_data() {
851 $definition = DBStructure::definition();
853 foreach ($definition AS $table => $structure) {
854 foreach ($structure['fields'] AS $field => $field_struct) {
855 if (isset($field_struct['relation'])) {
856 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
857 self::$relation[$rel_table][$rel_field][$table][] = $field;
865 * @brief Delete a row from a table
867 * @param string $table Table name
868 * @param array $conditions Field condition(s)
869 * @param boolean $in_process Internal use: Only do a commit after the last delete
870 * @param array $callstack Internal use: prevent endless loops
872 * @return boolean|array was the delete successful? When $in_process is set: deletion data
874 public static function delete($table, array $conditions, $in_process = false, array &$callstack = [])
876 if (empty($table) || empty($conditions)) {
877 logger('Table and conditions have to be set');
883 // Create a key for the loop prevention
884 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
886 // We quit when this key already exists in the callstack.
887 if (isset($callstack[$key])) {
891 $callstack[$key] = true;
893 $table = self::escape($table);
895 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
897 // To speed up the whole process we cache the table relations
898 if (count(self::$relation) == 0) {
899 self::build_relation_data();
902 // Is there a relation entry for the table?
903 if (isset(self::$relation[$table])) {
904 // We only allow a simple "one field" relation.
905 $field = array_keys(self::$relation[$table])[0];
906 $rel_def = array_values(self::$relation[$table])[0];
908 // Create a key for preventing double queries
909 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
911 // When the search field is the relation field, we don't need to fetch the rows
912 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
913 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
914 foreach ($rel_def AS $rel_table => $rel_fields) {
915 foreach ($rel_fields AS $rel_field) {
916 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], true, $callstack);
917 $commands = array_merge($commands, $retval);
920 // We quit when this key already exists in the callstack.
921 } elseif (!isset($callstack[$qkey])) {
923 $callstack[$qkey] = true;
925 // Fetch all rows that are to be deleted
926 $data = self::select($table, [$field], $conditions);
928 while ($row = self::fetch($data)) {
929 // Now we accumulate the delete commands
930 $retval = self::delete($table, [$field => $row[$field]], true, $callstack);
931 $commands = array_merge($commands, $retval);
936 // Since we had split the delete command we don't need the original command anymore
937 unset($commands[$key]);
942 // Now we finalize the process
943 $do_transaction = !self::$in_transaction;
945 if ($do_transaction) {
952 foreach ($commands AS $command) {
953 $conditions = $command['conditions'];
954 $array_element = each($conditions);
955 $array_key = $array_element['key'];
956 if (is_int($array_key)) {
957 $condition_string = " WHERE " . array_shift($conditions);
959 $condition_string = " WHERE `" . implode("` = ? AND `", array_keys($conditions)) . "` = ?";
962 if ((count($command['conditions']) > 1) || is_int($array_key)) {
963 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
964 logger(self::replace_parameters($sql, $conditions), LOGGER_DATA);
966 if (!self::e($sql, $conditions)) {
967 if ($do_transaction) {
973 $key_table = $command['table'];
974 $key_condition = array_keys($command['conditions'])[0];
975 $value = array_values($command['conditions'])[0];
977 // Split the SQL queries in chunks of 100 values
978 // We do the $i stuff here to make the code better readable
979 $i = $counter[$key_table][$key_condition];
980 if (count($compacted[$key_table][$key_condition][$i]) > 100) {
984 $compacted[$key_table][$key_condition][$i][$value] = $value;
985 $counter[$key_table][$key_condition] = $i;
988 foreach ($compacted AS $table => $values) {
989 foreach ($values AS $field => $field_value_list) {
990 foreach ($field_value_list AS $field_values) {
991 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
992 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
994 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
996 if (!self::e($sql, $field_values)) {
997 if ($do_transaction) {
1005 if ($do_transaction) {
1015 * @brief Updates rows
1017 * Updates rows in the database. When $old_fields is set to an array,
1018 * the system will only do an update if the fields in that array changed.
1021 * Only the values in $old_fields are compared.
1022 * This is an intentional behaviour.
1025 * We include the timestamp field in $fields but not in $old_fields.
1026 * Then the row will only get the new timestamp when the other fields had changed.
1028 * When $old_fields is set to a boolean value the system will do this compare itself.
1029 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1032 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1033 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1035 * @param string $table Table name
1036 * @param array $fields contains the fields that are updated
1037 * @param array $condition condition array with the key values
1038 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1040 * @return boolean was the update successfull?
1042 public static function update($table, $fields, $condition, $old_fields = []) {
1044 if (empty($table) || empty($fields) || empty($condition)) {
1045 logger('Table, fields and condition have to be set');
1049 $table = self::escape($table);
1051 $array_element = each($condition);
1052 $array_key = $array_element['key'];
1053 if (is_int($array_key)) {
1054 $condition_string = " WHERE ".array_shift($condition);
1056 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1059 if (is_bool($old_fields)) {
1060 $do_insert = $old_fields;
1062 $old_fields = self::selectFirst($table, [], $condition);
1064 if (is_bool($old_fields)) {
1066 $values = array_merge($condition, $fields);
1067 return self::insert($table, $values, $do_insert);
1073 $do_update = (count($old_fields) == 0);
1075 foreach ($old_fields AS $fieldname => $content) {
1076 if (isset($fields[$fieldname])) {
1077 if ($fields[$fieldname] == $content) {
1078 unset($fields[$fieldname]);
1085 if (!$do_update || (count($fields) == 0)) {
1089 $sql = "UPDATE `".$table."` SET `".
1090 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1092 $params1 = array_values($fields);
1093 $params2 = array_values($condition);
1094 $params = array_merge_recursive($params1, $params2);
1096 return self::e($sql, $params);
1100 * Retrieve a single record from a table and returns it in an associative array
1102 * @brief Retrieve a single record from a table
1103 * @param string $table
1104 * @param array $fields
1105 * @param array $condition
1106 * @param array $params
1107 * @return bool|array
1110 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1112 $params['limit'] = 1;
1113 $result = self::select($table, $fields, $condition, $params);
1115 if (is_bool($result)) {
1118 $row = self::fetch($result);
1119 self::close($result);
1125 * @brief Select rows from a table
1127 * @param string $table Table name
1128 * @param array $fields Array of selected fields, empty for all
1129 * @param array $condition Array of fields for condition
1130 * @param array $params Array of several parameters
1132 * @return boolean|object
1136 * $fields = array("id", "uri", "uid", "network");
1138 * $condition = array("uid" => 1, "network" => 'dspr');
1140 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1142 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1144 * $data = dba::select($table, $fields, $condition, $params);
1146 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1152 if (count($fields) > 0) {
1153 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1155 $select_fields = "*";
1158 $condition_string = self::buildCondition($condition);
1161 if (isset($params['order'])) {
1162 $order_string = " ORDER BY ";
1163 foreach ($params['order'] AS $fields => $order) {
1164 if (!is_int($fields)) {
1165 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1167 $order_string .= "`" . $order . "`, ";
1170 $order_string = substr($order_string, 0, -2);
1174 if (isset($params['limit']) && is_int($params['limit'])) {
1175 $limit_string = " LIMIT " . $params['limit'];
1178 if (isset($params['limit']) && is_array($params['limit'])) {
1179 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1182 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1184 $result = self::p($sql, $condition);
1190 * @brief Counts the rows from a table satisfying the provided condition
1192 * @param string $table Table name
1193 * @param array $condition array of fields for condition
1200 * $condition = ["uid" => 1, "network" => 'dspr'];
1202 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1204 * $count = dba::count($table, $condition);
1206 public static function count($table, array $condition = [])
1212 $condition_string = self::buildCondition($condition);
1214 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1216 $row = self::fetch_first($sql, $condition);
1218 return $row['count'];
1222 * @brief Returns the SQL condition string built from the provided condition array
1224 * This function operates with two modes.
1225 * - Supplied with a filed/value associative array, it builds simple strict
1226 * equality conditions linked by AND.
1227 * - Supplied with a flat list, the first element is the condition string and
1228 * the following arguments are the values to be interpolated
1230 * $condition = ["uid" => 1, "network" => 'dspr'];
1232 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1234 * In either case, the provided array is left with the parameters only
1236 * @param array $condition
1239 private static function buildCondition(array &$condition = [])
1241 $condition_string = '';
1242 if (count($condition) > 0) {
1243 $array_element = each($condition);
1244 $array_key = $array_element['key'];
1245 if (is_int($array_key)) {
1246 $condition_string = " WHERE ".array_shift($condition);
1248 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1252 return $condition_string;
1256 * @brief Fills an array with data from a query
1258 * @param object $stmt statement object
1259 * @return array Data array
1261 public static function inArray($stmt, $do_close = true) {
1262 if (is_bool($stmt)) {
1267 while ($row = self::fetch($stmt)) {
1277 * @brief Returns the error number of the last query
1279 * @return string Error number (0 if no error)
1281 public static function errorNo() {
1282 return self::$errorno;
1286 * @brief Returns the error message of the last query
1288 * @return string Error message ('' if no error)
1290 public static function errorMessage() {
1291 return self::$error;
1295 * @brief Closes the current statement
1297 * @param object $stmt statement object
1298 * @return boolean was the close successful?
1300 public static function close($stmt) {
1303 $stamp1 = microtime(true);
1305 if (!is_object($stmt)) {
1309 switch (self::$driver) {
1311 $ret = $stmt->closeCursor();
1314 $stmt->free_result();
1315 $ret = $stmt->close();
1319 $a->save_timestamp($stamp1, 'database');
1325 function dbesc($str) {
1326 if (dba::$connected) {
1327 return(dba::escape($str));
1329 return(str_replace("'","\\'",$str));
1334 * @brief execute SQL query with printf style args - deprecated
1336 * Please use the dba:: functions instead:
1337 * dba::select, dba::exists, dba::insert
1338 * dba::delete, dba::update, dba::p, dba::e
1340 * @param $args Query parameters (1 to N parameters of different types)
1341 * @return array|bool Query array
1344 $args = func_get_args();
1347 if (!dba::$connected) {
1351 $sql = dba::clean_query($sql);
1352 $sql = dba::any_value_fallback($sql);
1354 $stmt = @vsprintf($sql, $args);
1356 $ret = dba::p($stmt);
1358 if (is_bool($ret)) {
1362 $columns = dba::columnCount($ret);
1364 $data = dba::inArray($ret);
1366 if ((count($data) == 0) && ($columns == 0)) {
1373 function dba_timer() {
1374 return microtime(true);