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 * @brief Returns the MySQL server version string
108 * This function discriminate between the deprecated mysql API and the current
109 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
113 public static function server_info() {
114 if (self::$_server_info == '') {
115 switch (self::$driver) {
117 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
120 self::$_server_info = self::$db->server_info;
124 return self::$_server_info;
128 * @brief Returns the selected database name
132 public static function database_name() {
133 $ret = self::p("SELECT DATABASE() AS `db`");
134 $data = self::inArray($ret);
135 return $data[0]['db'];
139 * @brief Analyze a database query and log this if some conditions are met.
141 * @param string $query The database query that will be analyzed
143 private static function logIndex($query) {
146 if (empty($a->config["system"]["db_log_index"])) {
150 // Don't explain an explain statement
151 if (strtolower(substr($query, 0, 7)) == "explain") {
155 // Only do the explain on "select", "update" and "delete"
156 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
160 $r = self::p("EXPLAIN ".$query);
161 if (!DBM::is_result($r)) {
165 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
166 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
168 while ($row = dba::fetch($r)) {
169 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
170 $log = (in_array($row['key'], $watchlist) &&
171 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
176 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
180 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
185 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
186 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
187 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
188 basename($backtrace[1]["file"])."\t".
189 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
190 substr($query, 0, 2000)."\n", FILE_APPEND);
195 public static function escape($str) {
196 switch (self::$driver) {
198 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
200 return @self::$db->real_escape_string($str);
204 public static function connected() {
207 switch (self::$driver) {
209 $r = dba::p("SELECT 1");
210 if (DBM::is_result($r)) {
211 $row = dba::inArray($r);
212 $connected = ($row[0]['1'] == '1');
216 $connected = self::$db->ping();
223 * @brief Replaces ANY_VALUE() function by MIN() function,
224 * if the database server does not support ANY_VALUE().
226 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
227 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
228 * A standard fall-back is to use MIN().
230 * @param string $sql An SQL string without the values
231 * @return string The input SQL string modified if necessary.
233 public static function any_value_fallback($sql) {
234 $server_info = self::server_info();
235 if (version_compare($server_info, '5.7.5', '<') ||
236 (stripos($server_info, 'MariaDB') !== false)) {
237 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
243 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
245 * This is safe when we bind the parameters later.
246 * The parameter values aren't part of the SQL.
248 * @param string $sql An SQL string without the values
249 * @return string The input SQL string modified if necessary.
251 public static function clean_query($sql) {
252 $search = ["\t", "\n", "\r", " "];
253 $replace = [' ', ' ', ' ', ' '];
256 $sql = str_replace($search, $replace, $sql);
257 } while ($oldsql != $sql);
264 * @brief Replaces the ? placeholders with the parameters in the $args array
266 * @param string $sql SQL query
267 * @param array $args The parameters that are to replace the ? placeholders
268 * @return string The replaced SQL query
270 private static function replaceParameters($sql, $args) {
272 foreach ($args AS $param => $value) {
273 if (is_int($args[$param]) || is_float($args[$param])) {
274 $replace = intval($args[$param]);
276 $replace = "'".self::escape($args[$param])."'";
279 $pos = strpos($sql, '?', $offset);
280 if ($pos !== false) {
281 $sql = substr_replace($sql, $replace, $pos, 1);
283 $offset = $pos + strlen($replace);
289 * @brief Convert parameter array to an universal form
290 * @param array $args Parameter array
291 * @return array universalized parameter array
293 private static function getParam($args) {
296 // When the second function parameter is an array then use this as the parameter array
297 if ((count($args) > 0) && (is_array($args[1]))) {
305 * @brief Executes a prepared statement that returns data
306 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
308 * Please only use it with complicated queries.
309 * For all regular queries please use dba::select or dba::exists
311 * @param string $sql SQL statement
312 * @return bool|object statement object
314 public static function p($sql) {
317 $stamp1 = microtime(true);
319 $params = self::getParam(func_get_args());
321 // Renumber the array keys to be sure that they fit
324 foreach ($params AS $param) {
325 // Avoid problems with some MySQL servers and boolean values. See issue #3645
326 if (is_bool($param)) {
327 $param = (int)$param;
329 $args[++$i] = $param;
332 if (!self::$connected) {
336 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
337 // Question: Should we continue or stop the query here?
338 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
341 $sql = self::clean_query($sql);
342 $sql = self::any_value_fallback($sql);
346 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
347 $sql = "/*".System::callstack()." */ ".$sql;
352 self::$affected_rows = 0;
354 // We have to make some things different if this function is called from "e"
355 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
357 if (isset($trace[1])) {
358 $called_from = $trace[1];
360 // We use just something that is defined to avoid warnings
361 $called_from = $trace[0];
363 // We are having an own error logging in the function "e"
364 $called_from_e = ($called_from['function'] == 'e');
366 switch (self::$driver) {
368 // If there are no arguments we use "query"
369 if (count($args) == 0) {
370 if (!$retval = self::$db->query($sql)) {
371 $errorInfo = self::$db->errorInfo();
372 self::$error = $errorInfo[2];
373 self::$errorno = $errorInfo[1];
377 self::$affected_rows = $retval->rowCount();
381 if (!$stmt = self::$db->prepare($sql)) {
382 $errorInfo = self::$db->errorInfo();
383 self::$error = $errorInfo[2];
384 self::$errorno = $errorInfo[1];
389 foreach ($args AS $param => $value) {
390 $stmt->bindParam($param, $args[$param]);
393 if (!$stmt->execute()) {
394 $errorInfo = $stmt->errorInfo();
395 self::$error = $errorInfo[2];
396 self::$errorno = $errorInfo[1];
400 self::$affected_rows = $retval->rowCount();
404 // There are SQL statements that cannot be executed with a prepared statement
405 $parts = explode(' ', $orig_sql);
406 $command = strtolower($parts[0]);
407 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
409 // The fallback routine is called as well when there are no arguments
410 if (!$can_be_prepared || (count($args) == 0)) {
411 $retval = self::$db->query(self::replaceParameters($sql, $args));
412 if (self::$db->errno) {
413 self::$error = self::$db->error;
414 self::$errorno = self::$db->errno;
417 if (isset($retval->num_rows)) {
418 self::$affected_rows = $retval->num_rows;
420 self::$affected_rows = self::$db->affected_rows;
426 $stmt = self::$db->stmt_init();
428 if (!$stmt->prepare($sql)) {
429 self::$error = $stmt->error;
430 self::$errorno = $stmt->errno;
437 foreach ($args AS $param => $value) {
438 if (is_int($args[$param])) {
440 } elseif (is_float($args[$param])) {
442 } elseif (is_string($args[$param])) {
447 $values[] = &$args[$param];
450 if (count($values) > 0) {
451 array_unshift($values, $params);
452 call_user_func_array([$stmt, 'bind_param'], $values);
455 if (!$stmt->execute()) {
456 self::$error = self::$db->error;
457 self::$errorno = self::$db->errno;
460 $stmt->store_result();
462 self::$affected_rows = $retval->affected_rows;
467 // We are having an own error logging in the function "e"
468 if ((self::$errorno != 0) && !$called_from_e) {
469 // We have to preserve the error code, somewhere in the logging it get lost
470 $error = self::$error;
471 $errorno = self::$errorno;
473 logger('DB Error '.self::$errorno.': '.self::$error."\n".
474 System::callstack(8)."\n".self::replaceParameters($sql, $params));
476 self::$error = $error;
477 self::$errorno = $errorno;
480 $a->save_timestamp($stamp1, 'database');
482 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
484 $stamp2 = microtime(true);
485 $duration = (float)($stamp2 - $stamp1);
487 if (($duration > $a->config["system"]["db_loglimit"])) {
488 $duration = round($duration, 3);
489 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
491 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
492 basename($backtrace[1]["file"])."\t".
493 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
494 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
501 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
503 * Please use dba::delete, dba::insert, dba::update, ... instead
505 * @param string $sql SQL statement
506 * @return boolean Was the query successfull? False is returned only if an error occurred
508 public static function e($sql) {
511 $stamp = microtime(true);
513 $params = self::getParam(func_get_args());
515 // In a case of a deadlock we are repeating the query 20 times
519 $stmt = self::p($sql, $params);
521 if (is_bool($stmt)) {
523 } elseif (is_object($stmt)) {
531 } while ((self::$errorno == 1213) && (--$timeout > 0));
533 if (self::$errorno != 0) {
534 // We have to preserve the error code, somewhere in the logging it get lost
535 $error = self::$error;
536 $errorno = self::$errorno;
538 logger('DB Error '.self::$errorno.': '.self::$error."\n".
539 System::callstack(8)."\n".self::replaceParameters($sql, $params));
541 self::$error = $error;
542 self::$errorno = $errorno;
545 $a->save_timestamp($stamp, "database_write");
551 * @brief Check if data exists
553 * @param string $table Table name
554 * @param array $condition array of fields for condition
556 * @return boolean Are there rows for that condition?
558 public static function exists($table, $condition) {
566 $first_key = key($condition);
567 if (!is_int($first_key)) {
568 $fields = [$first_key];
571 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
573 if (is_bool($stmt)) {
576 $retval = (self::num_rows($stmt) > 0);
585 * Fetches the first row
587 * Please use dba::selectFirst or dba::exists whenever this is possible.
589 * @brief Fetches the first row
590 * @param string $sql SQL statement
591 * @return array first row of query
593 public static function fetch_first($sql) {
594 $params = self::getParam(func_get_args());
596 $stmt = self::p($sql, $params);
598 if (is_bool($stmt)) {
601 $retval = self::fetch($stmt);
610 * @brief Returns the number of affected rows of the last statement
612 * @return int Number of rows
614 public static function affected_rows() {
615 return self::$affected_rows;
619 * @brief Returns the number of columns of a statement
621 * @param object Statement object
622 * @return int Number of columns
624 public static function columnCount($stmt) {
625 if (!is_object($stmt)) {
628 switch (self::$driver) {
630 return $stmt->columnCount();
632 return $stmt->field_count;
637 * @brief Returns the number of rows of a statement
639 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
640 * @return int Number of rows
642 public static function num_rows($stmt) {
643 if (!is_object($stmt)) {
646 switch (self::$driver) {
648 return $stmt->rowCount();
650 return $stmt->num_rows;
656 * @brief Fetch a single row
658 * @param mixed $stmt statement object
659 * @return array current row
661 public static function fetch($stmt) {
664 $stamp1 = microtime(true);
668 if (!is_object($stmt)) {
672 switch (self::$driver) {
674 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
677 if (get_class($stmt) == 'mysqli_result') {
678 $columns = $stmt->fetch_assoc();
682 // This code works, but is slow
684 // Bind the result to a result array
688 for ($x = 0; $x < $stmt->field_count; $x++) {
689 $cols[] = &$cols_num[$x];
692 call_user_func_array([$stmt, 'bind_result'], $cols);
694 if (!$stmt->fetch()) {
699 // We need to get the field names for the array keys
700 // It seems that there is no better way to do this.
701 $result = $stmt->result_metadata();
702 $fields = $result->fetch_fields();
704 foreach ($cols_num AS $param => $col) {
705 $columns[$fields[$param]->name] = $col;
709 $a->save_timestamp($stamp1, 'database');
715 * @brief Insert a row into a table
717 * @param string $table Table name
718 * @param array $param parameter array
719 * @param bool $on_duplicate_update Do an update on a duplicate entry
721 * @return boolean was the insert successfull?
723 public static function insert($table, $param, $on_duplicate_update = false) {
725 if (empty($table) || empty($param)) {
726 logger('Table and fields have to be set');
730 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
731 substr(str_repeat("?, ", count($param)), 0, -2).")";
733 if ($on_duplicate_update) {
734 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
736 $values = array_values($param);
737 $param = array_merge_recursive($values, $values);
740 return self::e($sql, $param);
744 * @brief Fetch the id of the last insert command
746 * @return integer Last inserted id
748 public static function lastInsertId() {
749 switch (self::$driver) {
751 $id = self::$db->lastInsertId();
754 $id = self::$db->insert_id;
761 * @brief Locks a table for exclusive write access
763 * This function can be extended in the future to accept a table array as well.
765 * @param string $table Table name
767 * @return boolean was the lock successful?
769 public static function lock($table) {
770 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
771 self::e("SET autocommit=0");
772 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
774 self::e("SET autocommit=1");
776 self::$in_transaction = true;
782 * @brief Unlocks all locked tables
784 * @return boolean was the unlock successful?
786 public static function unlock() {
787 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
789 $success = self::e("UNLOCK TABLES");
790 self::e("SET autocommit=1");
791 self::$in_transaction = false;
796 * @brief Starts a transaction
798 * @return boolean Was the command executed successfully?
800 public static function transaction() {
801 if (!self::e('COMMIT')) {
804 if (!self::e('START TRANSACTION')) {
807 self::$in_transaction = true;
812 * @brief Does a commit
814 * @return boolean Was the command executed successfully?
816 public static function commit() {
817 if (!self::e('COMMIT')) {
820 self::$in_transaction = false;
825 * @brief Does a rollback
827 * @return boolean Was the command executed successfully?
829 public static function rollback() {
830 if (!self::e('ROLLBACK')) {
833 self::$in_transaction = false;
838 * @brief Build the array with the table relations
840 * The array is build from the database definitions in DBStructure.php
842 * This process must only be started once, since the value is cached.
844 private static function buildRelationData() {
845 $definition = DBStructure::definition();
847 foreach ($definition AS $table => $structure) {
848 foreach ($structure['fields'] AS $field => $field_struct) {
849 if (isset($field_struct['relation'])) {
850 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
851 self::$relation[$rel_table][$rel_field][$table][] = $field;
859 * @brief Delete a row from a table
861 * @param string $table Table name
862 * @param array $conditions Field condition(s)
863 * @param array $options
864 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
865 * relations (default: true)
866 * @param boolean $in_process Internal use: Only do a commit after the last delete
867 * @param array $callstack Internal use: prevent endless loops
869 * @return boolean|array was the delete successful? When $in_process is set: deletion data
871 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
873 if (empty($table) || empty($conditions)) {
874 logger('Table and conditions have to be set');
880 // Create a key for the loop prevention
881 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
883 // We quit when this key already exists in the callstack.
884 if (isset($callstack[$key])) {
888 $callstack[$key] = true;
890 $table = self::escape($table);
892 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
894 $cascade = defaults($options, 'cascade', true);
896 // To speed up the whole process we cache the table relations
897 if ($cascade && count(self::$relation) == 0) {
898 self::buildRelationData();
901 // Is there a relation entry for the table?
902 if ($cascade && isset(self::$relation[$table])) {
903 // We only allow a simple "one field" relation.
904 $field = array_keys(self::$relation[$table])[0];
905 $rel_def = array_values(self::$relation[$table])[0];
907 // Create a key for preventing double queries
908 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
910 // When the search field is the relation field, we don't need to fetch the rows
911 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
912 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
913 foreach ($rel_def AS $rel_table => $rel_fields) {
914 foreach ($rel_fields AS $rel_field) {
915 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
916 $commands = array_merge($commands, $retval);
919 // We quit when this key already exists in the callstack.
920 } elseif (!isset($callstack[$qkey])) {
922 $callstack[$qkey] = true;
924 // Fetch all rows that are to be deleted
925 $data = self::select($table, [$field], $conditions);
927 while ($row = self::fetch($data)) {
928 // Now we accumulate the delete commands
929 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
930 $commands = array_merge($commands, $retval);
935 // Since we had split the delete command we don't need the original command anymore
936 unset($commands[$key]);
941 // Now we finalize the process
942 $do_transaction = !self::$in_transaction;
944 if ($do_transaction) {
951 foreach ($commands AS $command) {
952 $conditions = $command['conditions'];
954 $first_key = key($conditions);
956 $condition_string = self::buildCondition($conditions);
958 if ((count($command['conditions']) > 1) || is_int($first_key)) {
959 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
960 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
962 if (!self::e($sql, $conditions)) {
963 if ($do_transaction) {
969 $key_table = $command['table'];
970 $key_condition = array_keys($command['conditions'])[0];
971 $value = array_values($command['conditions'])[0];
973 // Split the SQL queries in chunks of 100 values
974 // We do the $i stuff here to make the code better readable
975 $i = $counter[$key_table][$key_condition];
976 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
980 $compacted[$key_table][$key_condition][$i][$value] = $value;
981 $counter[$key_table][$key_condition] = $i;
984 foreach ($compacted AS $table => $values) {
985 foreach ($values AS $field => $field_value_list) {
986 foreach ($field_value_list AS $field_values) {
987 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
988 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
990 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
992 if (!self::e($sql, $field_values)) {
993 if ($do_transaction) {
1001 if ($do_transaction) {
1011 * @brief Updates rows
1013 * Updates rows in the database. When $old_fields is set to an array,
1014 * the system will only do an update if the fields in that array changed.
1017 * Only the values in $old_fields are compared.
1018 * This is an intentional behaviour.
1021 * We include the timestamp field in $fields but not in $old_fields.
1022 * Then the row will only get the new timestamp when the other fields had changed.
1024 * When $old_fields is set to a boolean value the system will do this compare itself.
1025 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1028 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1029 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1031 * @param string $table Table name
1032 * @param array $fields contains the fields that are updated
1033 * @param array $condition condition array with the key values
1034 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1036 * @return boolean was the update successfull?
1038 public static function update($table, $fields, $condition, $old_fields = []) {
1040 if (empty($table) || empty($fields) || empty($condition)) {
1041 logger('Table, fields and condition have to be set');
1045 $table = self::escape($table);
1047 $condition_string = self::buildCondition($condition);
1049 if (is_bool($old_fields)) {
1050 $do_insert = $old_fields;
1052 $old_fields = self::selectFirst($table, [], $condition);
1054 if (is_bool($old_fields)) {
1056 $values = array_merge($condition, $fields);
1057 return self::insert($table, $values, $do_insert);
1063 $do_update = (count($old_fields) == 0);
1065 foreach ($old_fields AS $fieldname => $content) {
1066 if (isset($fields[$fieldname])) {
1067 if ($fields[$fieldname] == $content) {
1068 unset($fields[$fieldname]);
1075 if (!$do_update || (count($fields) == 0)) {
1079 $sql = "UPDATE `".$table."` SET `".
1080 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1082 $params1 = array_values($fields);
1083 $params2 = array_values($condition);
1084 $params = array_merge_recursive($params1, $params2);
1086 return self::e($sql, $params);
1090 * Retrieve a single record from a table and returns it in an associative array
1092 * @brief Retrieve a single record from a table
1093 * @param string $table
1094 * @param array $fields
1095 * @param array $condition
1096 * @param array $params
1097 * @return bool|array
1100 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1102 $params['limit'] = 1;
1103 $result = self::select($table, $fields, $condition, $params);
1105 if (is_bool($result)) {
1108 $row = self::fetch($result);
1109 self::close($result);
1115 * @brief Select rows from a table
1117 * @param string $table Table name
1118 * @param array $fields Array of selected fields, empty for all
1119 * @param array $condition Array of fields for condition
1120 * @param array $params Array of several parameters
1122 * @return boolean|object
1126 * $fields = array("id", "uri", "uid", "network");
1128 * $condition = array("uid" => 1, "network" => 'dspr');
1130 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1132 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1134 * $data = dba::select($table, $fields, $condition, $params);
1136 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1142 $table = self::escape($table);
1144 if (count($fields) > 0) {
1145 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1147 $select_fields = "*";
1150 $condition_string = self::buildCondition($condition);
1153 if (isset($params['order'])) {
1154 $order_string = " ORDER BY ";
1155 foreach ($params['order'] AS $fields => $order) {
1156 if (!is_int($fields)) {
1157 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1159 $order_string .= "`" . $order . "`, ";
1162 $order_string = substr($order_string, 0, -2);
1166 if (isset($params['limit']) && is_int($params['limit'])) {
1167 $limit_string = " LIMIT " . $params['limit'];
1170 if (isset($params['limit']) && is_array($params['limit'])) {
1171 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1174 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1176 $result = self::p($sql, $condition);
1182 * @brief Counts the rows from a table satisfying the provided condition
1184 * @param string $table Table name
1185 * @param array $condition array of fields for condition
1192 * $condition = ["uid" => 1, "network" => 'dspr'];
1194 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1196 * $count = dba::count($table, $condition);
1198 public static function count($table, array $condition = [])
1204 $condition_string = self::buildCondition($condition);
1206 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1208 $row = self::fetch_first($sql, $condition);
1210 return $row['count'];
1214 * @brief Returns the SQL condition string built from the provided condition array
1216 * This function operates with two modes.
1217 * - Supplied with a filed/value associative array, it builds simple strict
1218 * equality conditions linked by AND.
1219 * - Supplied with a flat list, the first element is the condition string and
1220 * the following arguments are the values to be interpolated
1222 * $condition = ["uid" => 1, "network" => 'dspr'];
1224 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1226 * In either case, the provided array is left with the parameters only
1228 * @param array $condition
1231 private static function buildCondition(array &$condition = [])
1233 $condition_string = '';
1234 if (count($condition) > 0) {
1236 $first_key = key($condition);
1237 if (is_int($first_key)) {
1238 $condition_string = " WHERE ".array_shift($condition);
1241 $condition_string = "";
1242 foreach ($condition as $field => $value) {
1243 if ($condition_string != "") {
1244 $condition_string .= " AND ";
1246 if (is_array($value)) {
1247 $new_values = array_merge($new_values, array_values($value));
1248 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1249 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1251 $new_values[$field] = $value;
1252 $condition_string .= "`" . $field . "` = ?";
1255 $condition_string = " WHERE " . $condition_string;
1256 $condition = $new_values;
1260 return $condition_string;
1264 * @brief Fills an array with data from a query
1266 * @param object $stmt statement object
1267 * @return array Data array
1269 public static function inArray($stmt, $do_close = true) {
1270 if (is_bool($stmt)) {
1275 while ($row = self::fetch($stmt)) {
1285 * @brief Returns the error number of the last query
1287 * @return string Error number (0 if no error)
1289 public static function errorNo() {
1290 return self::$errorno;
1294 * @brief Returns the error message of the last query
1296 * @return string Error message ('' if no error)
1298 public static function errorMessage() {
1299 return self::$error;
1303 * @brief Closes the current statement
1305 * @param object $stmt statement object
1306 * @return boolean was the close successful?
1308 public static function close($stmt) {
1311 $stamp1 = microtime(true);
1313 if (!is_object($stmt)) {
1317 switch (self::$driver) {
1319 $ret = $stmt->closeCursor();
1322 $stmt->free_result();
1323 $ret = $stmt->close();
1327 $a->save_timestamp($stamp1, 'database');
1333 function dbesc($str) {
1334 if (dba::$connected) {
1335 return(dba::escape($str));
1337 return(str_replace("'","\\'",$str));
1342 * @brief execute SQL query with printf style args - deprecated
1344 * Please use the dba:: functions instead:
1345 * dba::select, dba::exists, dba::insert
1346 * dba::delete, dba::update, dba::p, dba::e
1348 * @param $args Query parameters (1 to N parameters of different types)
1349 * @return array|bool Query array
1352 $args = func_get_args();
1355 if (!dba::$connected) {
1359 $sql = dba::clean_query($sql);
1360 $sql = dba::any_value_fallback($sql);
1362 $stmt = @vsprintf($sql, $args);
1364 $ret = dba::p($stmt);
1366 if (is_bool($ret)) {
1370 $columns = dba::columnCount($ret);
1372 $data = dba::inArray($ret);
1374 if ((count($data) == 0) && ($columns == 0)) {
1381 function dba_timer() {
1382 return microtime(true);