3 use Friendica\Core\L10n;
4 use Friendica\Core\System;
5 use Friendica\Database\DBM;
6 use Friendica\Database\DBStructure;
7 use Friendica\Util\Temporal;
9 require_once('include/datetime.php');
12 * @class MySQL database class
14 * This class is for the low level database stuff that does driver specific things.
18 public static $connected = true;
20 private static $_server_info = '';
22 private static $driver;
23 private static $error = false;
24 private static $errorno = 0;
25 private static $affected_rows = 0;
26 private static $in_transaction = false;
27 private static $relation = [];
29 public static function connect($serveraddr, $user, $pass, $db, $install = false) {
30 if (!is_null(self::$db)) {
36 $stamp1 = microtime(true);
38 $serveraddr = trim($serveraddr);
40 $serverdata = explode(':', $serveraddr);
41 $server = $serverdata[0];
43 if (count($serverdata) > 1) {
44 $port = trim($serverdata[1]);
47 $server = trim($server);
52 if (!(strlen($server) && strlen($user))) {
53 self::$connected = false;
59 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
60 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
61 self::$error = L10n::t('Cannot locate DNS info for database server \'%s\'', $server);
62 self::$connected = false;
69 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
70 self::$driver = 'pdo';
71 $connect = "mysql:host=".$server.";dbname=".$db;
74 $connect .= ";port=".$port;
77 if (isset($a->config["system"]["db_charset"])) {
78 $connect .= ";charset=".$a->config["system"]["db_charset"];
81 self::$db = @new PDO($connect, $user, $pass);
82 self::$connected = true;
83 } catch (PDOException $e) {
84 self::$connected = false;
88 if (!self::$connected && class_exists('mysqli')) {
89 self::$driver = 'mysqli';
90 self::$db = @new mysqli($server, $user, $pass, $db, $port);
91 if (!mysqli_connect_errno()) {
92 self::$connected = true;
94 if (isset($a->config["system"]["db_charset"])) {
95 self::$db->set_charset($a->config["system"]["db_charset"]);
100 // No suitable SQL driver was found.
101 if (!self::$connected) {
104 System::unavailable();
107 $a->save_timestamp($stamp1, "network");
113 * @brief Returns the MySQL server version string
115 * This function discriminate between the deprecated mysql API and the current
116 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
120 public static function server_info() {
121 if (self::$_server_info == '') {
122 switch (self::$driver) {
124 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
127 self::$_server_info = self::$db->server_info;
131 return self::$_server_info;
135 * @brief Returns the selected database name
139 public static function database_name() {
140 $ret = self::p("SELECT DATABASE() AS `db`");
141 $data = self::inArray($ret);
142 return $data[0]['db'];
146 * @brief Analyze a database query and log this if some conditions are met.
148 * @param string $query The database query that will be analyzed
150 private static function log_index($query) {
153 if (empty($a->config["system"]["db_log_index"])) {
157 // Don't explain an explain statement
158 if (strtolower(substr($query, 0, 7)) == "explain") {
162 // Only do the explain on "select", "update" and "delete"
163 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
167 $r = self::p("EXPLAIN ".$query);
168 if (!DBM::is_result($r)) {
172 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
173 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
175 while ($row = dba::fetch($r)) {
176 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
177 $log = (in_array($row['key'], $watchlist) &&
178 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
183 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
187 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
192 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
193 @file_put_contents($a->config["system"]["db_log_index"], Temporal::utcNow()."\t".
194 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
195 basename($backtrace[1]["file"])."\t".
196 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
197 substr($query, 0, 2000)."\n", FILE_APPEND);
202 public static function escape($str) {
203 switch (self::$driver) {
205 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
207 return @self::$db->real_escape_string($str);
211 public static function connected() {
214 switch (self::$driver) {
216 $r = dba::p("SELECT 1");
217 if (DBM::is_result($r)) {
218 $row = dba::inArray($r);
219 $connected = ($row[0]['1'] == '1');
223 $connected = self::$db->ping();
230 * @brief Replaces ANY_VALUE() function by MIN() function,
231 * if the database server does not support ANY_VALUE().
233 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
234 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
235 * A standard fall-back is to use MIN().
237 * @param string $sql An SQL string without the values
238 * @return string The input SQL string modified if necessary.
240 public static function any_value_fallback($sql) {
241 $server_info = self::server_info();
242 if (version_compare($server_info, '5.7.5', '<') ||
243 (stripos($server_info, 'MariaDB') !== false)) {
244 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
250 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
252 * This is safe when we bind the parameters later.
253 * The parameter values aren't part of the SQL.
255 * @param string $sql An SQL string without the values
256 * @return string The input SQL string modified if necessary.
258 public static function clean_query($sql) {
259 $search = ["\t", "\n", "\r", " "];
260 $replace = [' ', ' ', ' ', ' '];
263 $sql = str_replace($search, $replace, $sql);
264 } while ($oldsql != $sql);
271 * @brief Replaces the ? placeholders with the parameters in the $args array
273 * @param string $sql SQL query
274 * @param array $args The parameters that are to replace the ? placeholders
275 * @return string The replaced SQL query
277 private static function replace_parameters($sql, $args) {
279 foreach ($args AS $param => $value) {
280 if (is_int($args[$param]) || is_float($args[$param])) {
281 $replace = intval($args[$param]);
283 $replace = "'".self::escape($args[$param])."'";
286 $pos = strpos($sql, '?', $offset);
287 if ($pos !== false) {
288 $sql = substr_replace($sql, $replace, $pos, 1);
290 $offset = $pos + strlen($replace);
296 * @brief Convert parameter array to an universal form
297 * @param array $args Parameter array
298 * @return array universalized parameter array
300 private static function getParam($args) {
303 // When the second function parameter is an array then use this as the parameter array
304 if ((count($args) > 0) && (is_array($args[1]))) {
312 * @brief Executes a prepared statement that returns data
313 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
315 * Please only use it with complicated queries.
316 * For all regular queries please use dba::select or dba::exists
318 * @param string $sql SQL statement
319 * @return bool|object statement object
321 public static function p($sql) {
324 $stamp1 = microtime(true);
326 $params = self::getParam(func_get_args());
328 // Renumber the array keys to be sure that they fit
331 foreach ($params AS $param) {
332 // Avoid problems with some MySQL servers and boolean values. See issue #3645
333 if (is_bool($param)) {
334 $param = (int)$param;
336 $args[++$i] = $param;
339 if (!self::$connected) {
343 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
344 // Question: Should we continue or stop the query here?
345 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
348 $sql = self::clean_query($sql);
349 $sql = self::any_value_fallback($sql);
353 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
354 $sql = "/*".System::callstack()." */ ".$sql;
359 self::$affected_rows = 0;
361 // We have to make some things different if this function is called from "e"
362 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
364 if (isset($trace[1])) {
365 $called_from = $trace[1];
367 // We use just something that is defined to avoid warnings
368 $called_from = $trace[0];
370 // We are having an own error logging in the function "e"
371 $called_from_e = ($called_from['function'] == 'e');
373 switch (self::$driver) {
375 // If there are no arguments we use "query"
376 if (count($args) == 0) {
377 if (!$retval = self::$db->query($sql)) {
378 $errorInfo = self::$db->errorInfo();
379 self::$error = $errorInfo[2];
380 self::$errorno = $errorInfo[1];
384 self::$affected_rows = $retval->rowCount();
388 if (!$stmt = self::$db->prepare($sql)) {
389 $errorInfo = self::$db->errorInfo();
390 self::$error = $errorInfo[2];
391 self::$errorno = $errorInfo[1];
396 foreach ($args AS $param => $value) {
397 $stmt->bindParam($param, $args[$param]);
400 if (!$stmt->execute()) {
401 $errorInfo = $stmt->errorInfo();
402 self::$error = $errorInfo[2];
403 self::$errorno = $errorInfo[1];
407 self::$affected_rows = $retval->rowCount();
411 // There are SQL statements that cannot be executed with a prepared statement
412 $parts = explode(' ', $orig_sql);
413 $command = strtolower($parts[0]);
414 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
416 // The fallback routine is called as well when there are no arguments
417 if (!$can_be_prepared || (count($args) == 0)) {
418 $retval = self::$db->query(self::replace_parameters($sql, $args));
419 if (self::$db->errno) {
420 self::$error = self::$db->error;
421 self::$errorno = self::$db->errno;
424 if (isset($retval->num_rows)) {
425 self::$affected_rows = $retval->num_rows;
427 self::$affected_rows = self::$db->affected_rows;
433 $stmt = self::$db->stmt_init();
435 if (!$stmt->prepare($sql)) {
436 self::$error = $stmt->error;
437 self::$errorno = $stmt->errno;
444 foreach ($args AS $param => $value) {
445 if (is_int($args[$param])) {
447 } elseif (is_float($args[$param])) {
449 } elseif (is_string($args[$param])) {
454 $values[] = &$args[$param];
457 if (count($values) > 0) {
458 array_unshift($values, $params);
459 call_user_func_array([$stmt, 'bind_param'], $values);
462 if (!$stmt->execute()) {
463 self::$error = self::$db->error;
464 self::$errorno = self::$db->errno;
467 $stmt->store_result();
469 self::$affected_rows = $retval->affected_rows;
474 // We are having an own error logging in the function "e"
475 if ((self::$errorno != 0) && !$called_from_e) {
476 // We have to preserve the error code, somewhere in the logging it get lost
477 $error = self::$error;
478 $errorno = self::$errorno;
480 logger('DB Error '.self::$errorno.': '.self::$error."\n".
481 System::callstack(8)."\n".self::replace_parameters($sql, $params));
483 self::$error = $error;
484 self::$errorno = $errorno;
487 $a->save_timestamp($stamp1, 'database');
489 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
491 $stamp2 = microtime(true);
492 $duration = (float)($stamp2 - $stamp1);
494 if (($duration > $a->config["system"]["db_loglimit"])) {
495 $duration = round($duration, 3);
496 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
498 @file_put_contents($a->config["system"]["db_log"], Temporal::utcNow()."\t".$duration."\t".
499 basename($backtrace[1]["file"])."\t".
500 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
501 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
508 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
510 * Please use dba::delete, dba::insert, dba::update, ... instead
512 * @param string $sql SQL statement
513 * @return boolean Was the query successfull? False is returned only if an error occurred
515 public static function e($sql) {
518 $stamp = microtime(true);
520 $params = self::getParam(func_get_args());
522 // In a case of a deadlock we are repeating the query 20 times
526 $stmt = self::p($sql, $params);
528 if (is_bool($stmt)) {
530 } elseif (is_object($stmt)) {
538 } while ((self::$errorno == 1213) && (--$timeout > 0));
540 if (self::$errorno != 0) {
541 // We have to preserve the error code, somewhere in the logging it get lost
542 $error = self::$error;
543 $errorno = self::$errorno;
545 logger('DB Error '.self::$errorno.': '.self::$error."\n".
546 System::callstack(8)."\n".self::replace_parameters($sql, $params));
548 self::$error = $error;
549 self::$errorno = $errorno;
552 $a->save_timestamp($stamp, "database_write");
558 * @brief Check if data exists
560 * @param string $table Table name
561 * @param array $condition array of fields for condition
563 * @return boolean Are there rows for that condition?
565 public static function exists($table, $condition) {
572 $array_element = each($condition);
573 $array_key = $array_element['key'];
574 if (!is_int($array_key)) {
575 $fields = [$array_key];
578 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
580 if (is_bool($stmt)) {
583 $retval = (self::num_rows($stmt) > 0);
592 * Fetches the first row
594 * Please use dba::selectFirst or dba::exists whenever this is possible.
596 * @brief Fetches the first row
597 * @param string $sql SQL statement
598 * @return array first row of query
600 public static function fetch_first($sql) {
601 $params = self::getParam(func_get_args());
603 $stmt = self::p($sql, $params);
605 if (is_bool($stmt)) {
608 $retval = self::fetch($stmt);
617 * @brief Returns the number of affected rows of the last statement
619 * @return int Number of rows
621 public static function affected_rows() {
622 return self::$affected_rows;
626 * @brief Returns the number of columns of a statement
628 * @param object Statement object
629 * @return int Number of columns
631 public static function columnCount($stmt) {
632 if (!is_object($stmt)) {
635 switch (self::$driver) {
637 return $stmt->columnCount();
639 return $stmt->field_count;
644 * @brief Returns the number of rows of a statement
646 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
647 * @return int Number of rows
649 public static function num_rows($stmt) {
650 if (!is_object($stmt)) {
653 switch (self::$driver) {
655 return $stmt->rowCount();
657 return $stmt->num_rows;
663 * @brief Fetch a single row
665 * @param mixed $stmt statement object
666 * @return array current row
668 public static function fetch($stmt) {
669 if (!is_object($stmt)) {
673 switch (self::$driver) {
675 return $stmt->fetch(PDO::FETCH_ASSOC);
677 if (get_class($stmt) == 'mysqli_result') {
678 return $stmt->fetch_assoc();
681 // This code works, but is slow
683 // Bind the result to a result array
687 for ($x = 0; $x < $stmt->field_count; $x++) {
688 $cols[] = &$cols_num[$x];
691 call_user_func_array([$stmt, 'bind_result'], $cols);
693 if (!$stmt->fetch()) {
698 // We need to get the field names for the array keys
699 // It seems that there is no better way to do this.
700 $result = $stmt->result_metadata();
701 $fields = $result->fetch_fields();
704 foreach ($cols_num AS $param => $col) {
705 $columns[$fields[$param]->name] = $col;
712 * @brief Insert a row into a table
714 * @param string $table Table name
715 * @param array $param parameter array
716 * @param bool $on_duplicate_update Do an update on a duplicate entry
718 * @return boolean was the insert successfull?
720 public static function insert($table, $param, $on_duplicate_update = false) {
722 if (empty($table) || empty($param)) {
723 logger('Table and fields have to be set');
727 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
728 substr(str_repeat("?, ", count($param)), 0, -2).")";
730 if ($on_duplicate_update) {
731 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
733 $values = array_values($param);
734 $param = array_merge_recursive($values, $values);
737 return self::e($sql, $param);
741 * @brief Fetch the id of the last insert command
743 * @return integer Last inserted id
745 public static function lastInsertId() {
746 switch (self::$driver) {
748 $id = self::$db->lastInsertId();
751 $id = self::$db->insert_id;
758 * @brief Locks a table for exclusive write access
760 * This function can be extended in the future to accept a table array as well.
762 * @param string $table Table name
764 * @return boolean was the lock successful?
766 public static function lock($table) {
767 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
768 self::e("SET autocommit=0");
769 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
771 self::e("SET autocommit=1");
773 self::$in_transaction = true;
779 * @brief Unlocks all locked tables
781 * @return boolean was the unlock successful?
783 public static function unlock() {
784 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
786 $success = self::e("UNLOCK TABLES");
787 self::e("SET autocommit=1");
788 self::$in_transaction = false;
793 * @brief Starts a transaction
795 * @return boolean Was the command executed successfully?
797 public static function transaction() {
798 if (!self::e('COMMIT')) {
801 if (!self::e('START TRANSACTION')) {
804 self::$in_transaction = true;
809 * @brief Does a commit
811 * @return boolean Was the command executed successfully?
813 public static function commit() {
814 if (!self::e('COMMIT')) {
817 self::$in_transaction = false;
822 * @brief Does a rollback
824 * @return boolean Was the command executed successfully?
826 public static function rollback() {
827 if (!self::e('ROLLBACK')) {
830 self::$in_transaction = false;
835 * @brief Build the array with the table relations
837 * The array is build from the database definitions in DBStructure.php
839 * This process must only be started once, since the value is cached.
841 private static function build_relation_data() {
842 $definition = DBStructure::definition();
844 foreach ($definition AS $table => $structure) {
845 foreach ($structure['fields'] AS $field => $field_struct) {
846 if (isset($field_struct['relation'])) {
847 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
848 self::$relation[$rel_table][$rel_field][$table][] = $field;
856 * @brief Delete a row from a table
858 * @param string $table Table name
859 * @param array $conditions Field condition(s)
860 * @param boolean $in_process Internal use: Only do a commit after the last delete
861 * @param array $callstack Internal use: prevent endless loops
863 * @return boolean|array was the delete successful? When $in_process is set: deletion data
865 public static function delete($table, array $conditions, $in_process = false, array &$callstack = [])
867 if (empty($table) || empty($conditions)) {
868 logger('Table and conditions have to be set');
874 // Create a key for the loop prevention
875 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
877 // We quit when this key already exists in the callstack.
878 if (isset($callstack[$key])) {
882 $callstack[$key] = true;
884 $table = self::escape($table);
886 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
888 // To speed up the whole process we cache the table relations
889 if (count(self::$relation) == 0) {
890 self::build_relation_data();
893 // Is there a relation entry for the table?
894 if (isset(self::$relation[$table])) {
895 // We only allow a simple "one field" relation.
896 $field = array_keys(self::$relation[$table])[0];
897 $rel_def = array_values(self::$relation[$table])[0];
899 // Create a key for preventing double queries
900 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
902 // When the search field is the relation field, we don't need to fetch the rows
903 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
904 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
905 foreach ($rel_def AS $rel_table => $rel_fields) {
906 foreach ($rel_fields AS $rel_field) {
907 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], true, $callstack);
908 $commands = array_merge($commands, $retval);
911 // We quit when this key already exists in the callstack.
912 } elseif (!isset($callstack[$qkey])) {
914 $callstack[$qkey] = true;
916 // Fetch all rows that are to be deleted
917 $data = self::select($table, [$field], $conditions);
919 while ($row = self::fetch($data)) {
920 // Now we accumulate the delete commands
921 $retval = self::delete($table, [$field => $row[$field]], true, $callstack);
922 $commands = array_merge($commands, $retval);
927 // Since we had split the delete command we don't need the original command anymore
928 unset($commands[$key]);
933 // Now we finalize the process
934 $do_transaction = !self::$in_transaction;
936 if ($do_transaction) {
943 foreach ($commands AS $command) {
944 $conditions = $command['conditions'];
945 $array_element = each($conditions);
946 $array_key = $array_element['key'];
947 if (is_int($array_key)) {
948 $condition_string = " WHERE " . array_shift($conditions);
950 $condition_string = " WHERE `" . implode("` = ? AND `", array_keys($conditions)) . "` = ?";
953 if ((count($command['conditions']) > 1) || is_int($array_key)) {
954 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
955 logger(self::replace_parameters($sql, $conditions), LOGGER_DATA);
957 if (!self::e($sql, $conditions)) {
958 if ($do_transaction) {
964 $key_table = $command['table'];
965 $key_condition = array_keys($command['conditions'])[0];
966 $value = array_values($command['conditions'])[0];
968 // Split the SQL queries in chunks of 100 values
969 // We do the $i stuff here to make the code better readable
970 $i = $counter[$key_table][$key_condition];
971 if (count($compacted[$key_table][$key_condition][$i]) > 100) {
975 $compacted[$key_table][$key_condition][$i][$value] = $value;
976 $counter[$key_table][$key_condition] = $i;
979 foreach ($compacted AS $table => $values) {
980 foreach ($values AS $field => $field_value_list) {
981 foreach ($field_value_list AS $field_values) {
982 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
983 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
985 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
987 if (!self::e($sql, $field_values)) {
988 if ($do_transaction) {
996 if ($do_transaction) {
1006 * @brief Updates rows
1008 * Updates rows in the database. When $old_fields is set to an array,
1009 * the system will only do an update if the fields in that array changed.
1012 * Only the values in $old_fields are compared.
1013 * This is an intentional behaviour.
1016 * We include the timestamp field in $fields but not in $old_fields.
1017 * Then the row will only get the new timestamp when the other fields had changed.
1019 * When $old_fields is set to a boolean value the system will do this compare itself.
1020 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1023 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1024 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1026 * @param string $table Table name
1027 * @param array $fields contains the fields that are updated
1028 * @param array $condition condition array with the key values
1029 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1031 * @return boolean was the update successfull?
1033 public static function update($table, $fields, $condition, $old_fields = []) {
1035 if (empty($table) || empty($fields) || empty($condition)) {
1036 logger('Table, fields and condition have to be set');
1040 $table = self::escape($table);
1042 $array_element = each($condition);
1043 $array_key = $array_element['key'];
1044 if (is_int($array_key)) {
1045 $condition_string = " WHERE ".array_shift($condition);
1047 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1050 if (is_bool($old_fields)) {
1051 $do_insert = $old_fields;
1053 $old_fields = self::selectFirst($table, [], $condition);
1055 if (is_bool($old_fields)) {
1057 $values = array_merge($condition, $fields);
1058 return self::insert($table, $values, $do_insert);
1064 $do_update = (count($old_fields) == 0);
1066 foreach ($old_fields AS $fieldname => $content) {
1067 if (isset($fields[$fieldname])) {
1068 if ($fields[$fieldname] == $content) {
1069 unset($fields[$fieldname]);
1076 if (!$do_update || (count($fields) == 0)) {
1080 $sql = "UPDATE `".$table."` SET `".
1081 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1083 $params1 = array_values($fields);
1084 $params2 = array_values($condition);
1085 $params = array_merge_recursive($params1, $params2);
1087 return self::e($sql, $params);
1091 * Retrieve a single record from a table and returns it in an associative array
1093 * @brief Retrieve a single record from a table
1094 * @param string $table
1095 * @param array $fields
1096 * @param array $condition
1097 * @param array $params
1098 * @return bool|array
1101 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1103 $params['limit'] = 1;
1104 $result = self::select($table, $fields, $condition, $params);
1106 if (is_bool($result)) {
1109 $row = self::fetch($result);
1110 self::close($result);
1116 * @brief Select rows from a table
1118 * @param string $table Table name
1119 * @param array $fields Array of selected fields, empty for all
1120 * @param array $condition Array of fields for condition
1121 * @param array $params Array of several parameters
1123 * @return boolean|object
1127 * $fields = array("id", "uri", "uid", "network");
1129 * $condition = array("uid" => 1, "network" => 'dspr');
1131 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1133 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1135 * $data = dba::select($table, $fields, $condition, $params);
1137 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1143 if (count($fields) > 0) {
1144 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1146 $select_fields = "*";
1149 $condition_string = self::buildCondition($condition);
1152 if (isset($params['order'])) {
1153 $order_string = " ORDER BY ";
1154 foreach ($params['order'] AS $fields => $order) {
1155 if (!is_int($fields)) {
1156 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1158 $order_string .= "`" . $order . "`, ";
1161 $order_string = substr($order_string, 0, -2);
1165 if (isset($params['limit']) && is_int($params['limit'])) {
1166 $limit_string = " LIMIT " . $params['limit'];
1169 if (isset($params['limit']) && is_array($params['limit'])) {
1170 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1173 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1175 $result = self::p($sql, $condition);
1181 * @brief Counts the rows from a table satisfying the provided condition
1183 * @param string $table Table name
1184 * @param array $condition array of fields for condition
1191 * $condition = ["uid" => 1, "network" => 'dspr'];
1193 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1195 * $count = dba::count($table, $condition);
1197 public static function count($table, array $condition = [])
1203 $condition_string = self::buildCondition($condition);
1205 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1207 $row = self::fetch_first($sql, $condition);
1209 return $row['count'];
1213 * @brief Returns the SQL condition string built from the provided condition array
1215 * This function operates with two modes.
1216 * - Supplied with a filed/value associative array, it builds simple strict
1217 * equality conditions linked by AND.
1218 * - Supplied with a flat list, the first element is the condition string and
1219 * the following arguments are the values to be interpolated
1221 * $condition = ["uid" => 1, "network" => 'dspr'];
1223 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1225 * In either case, the provided array is left with the parameters only
1227 * @param array $condition
1230 private static function buildCondition(array &$condition = [])
1232 $condition_string = '';
1233 if (count($condition) > 0) {
1234 $array_element = each($condition);
1235 $array_key = $array_element['key'];
1236 if (is_int($array_key)) {
1237 $condition_string = " WHERE ".array_shift($condition);
1239 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1243 return $condition_string;
1247 * @brief Fills an array with data from a query
1249 * @param object $stmt statement object
1250 * @return array Data array
1252 public static function inArray($stmt, $do_close = true) {
1253 if (is_bool($stmt)) {
1258 while ($row = self::fetch($stmt)) {
1268 * @brief Returns the error number of the last query
1270 * @return string Error number (0 if no error)
1272 public static function errorNo() {
1273 return self::$errorno;
1277 * @brief Returns the error message of the last query
1279 * @return string Error message ('' if no error)
1281 public static function errorMessage() {
1282 return self::$error;
1286 * @brief Closes the current statement
1288 * @param object $stmt statement object
1289 * @return boolean was the close successful?
1291 public static function close($stmt) {
1292 if (!is_object($stmt)) {
1296 switch (self::$driver) {
1298 return $stmt->closeCursor();
1300 $stmt->free_result();
1301 return $stmt->close();
1306 function dbesc($str) {
1307 if (dba::$connected) {
1308 return(dba::escape($str));
1310 return(str_replace("'","\\'",$str));
1315 * @brief execute SQL query with printf style args - deprecated
1317 * Please use the dba:: functions instead:
1318 * dba::select, dba::exists, dba::insert
1319 * dba::delete, dba::update, dba::p, dba::e
1321 * @param $args Query parameters (1 to N parameters of different types)
1322 * @return array|bool Query array
1325 $args = func_get_args();
1328 if (!dba::$connected) {
1332 $sql = dba::clean_query($sql);
1333 $sql = dba::any_value_fallback($sql);
1335 $stmt = @vsprintf($sql, $args);
1337 $ret = dba::p($stmt);
1339 if (is_bool($ret)) {
1343 $columns = dba::columnCount($ret);
1345 $data = dba::inArray($ret);
1347 if ((count($data) == 0) && ($columns == 0)) {
1354 function dba_timer() {
1355 return microtime(true);