3 namespace Friendica\Database;
13 * @class MySQL database class
15 * This class is for the low level database stuff that does driver specific things.
20 * Lowest possible date value
22 const NULL_DATE = '0001-01-01';
24 * Lowest possible datetime value
26 const NULL_DATETIME = '0001-01-01 00:00:00';
28 public static function connect()
30 return DI::dba()->connect();
34 * Disconnects the current database connection
36 public static function disconnect()
38 DI::dba()->disconnect();
42 * Perform a reconnect of an existing database connection
44 public static function reconnect()
46 return DI::dba()->reconnect();
50 * Return the database object.
53 public static function getConnection()
55 return DI::dba()->getConnection();
59 * @brief Returns the MySQL server version string
61 * This function discriminate between the deprecated mysql API and the current
62 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
66 public static function serverInfo()
68 return DI::dba()->serverInfo();
72 * @brief Returns the selected database name
77 public static function databaseName()
79 return DI::dba()->databaseName();
82 public static function escape($str)
84 return DI::dba()->escape($str);
87 public static function connected()
89 return DI::dba()->connected();
93 * @brief Replaces ANY_VALUE() function by MIN() function,
94 * if the database server does not support ANY_VALUE().
96 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
97 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
98 * A standard fall-back is to use MIN().
100 * @param string $sql An SQL string without the values
101 * @return string The input SQL string modified if necessary.
103 public static function anyValueFallback($sql)
105 return DI::dba()->anyValueFallback($sql);
109 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
111 * This is safe when we bind the parameters later.
112 * The parameter values aren't part of the SQL.
114 * @param string $sql An SQL string without the values
115 * @return string The input SQL string modified if necessary.
117 public static function cleanQuery($sql)
119 $search = ["\t", "\n", "\r", " "];
120 $replace = [' ', ' ', ' ', ' '];
123 $sql = str_replace($search, $replace, $sql);
124 } while ($oldsql != $sql);
130 * @brief Convert parameter array to an universal form
131 * @param array $args Parameter array
132 * @return array universalized parameter array
134 public static function getParam($args)
138 // When the second function parameter is an array then use this as the parameter array
139 if ((count($args) > 0) && (is_array($args[1]))) {
147 * @brief Executes a prepared statement that returns data
148 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
150 * Please only use it with complicated queries.
151 * For all regular queries please use DBA::select or DBA::exists
153 * @param string $sql SQL statement
154 * @return bool|object statement object or result object
157 public static function p($sql)
159 $params = self::getParam(func_get_args());
161 return DI::dba()->p($sql, $params);
165 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
167 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
169 * @param string $sql SQL statement
170 * @return boolean Was the query successfull? False is returned only if an error occurred
173 public static function e($sql) {
175 $params = self::getParam(func_get_args());
177 return DI::dba()->e($sql, $params);
181 * @brief Check if data exists
183 * @param string|array $table Table name or array [schema => table]
184 * @param array $condition array of fields for condition
186 * @return boolean Are there rows for that condition?
189 public static function exists($table, $condition)
191 return DI::dba()->exists($table, $condition);
195 * Fetches the first row
197 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
199 * @brief Fetches the first row
200 * @param string $sql SQL statement
201 * @return array first row of query
204 public static function fetchFirst($sql)
206 $params = self::getParam(func_get_args());
208 return DI::dba()->fetchFirst($sql, $params);
212 * @brief Returns the number of affected rows of the last statement
214 * @return int Number of rows
216 public static function affectedRows()
218 return DI::dba()->affectedRows();
222 * @brief Returns the number of columns of a statement
224 * @param object Statement object
225 * @return int Number of columns
227 public static function columnCount($stmt)
229 return DI::dba()->columnCount($stmt);
232 * @brief Returns the number of rows of a statement
234 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
235 * @return int Number of rows
237 public static function numRows($stmt)
239 return DI::dba()->numRows($stmt);
243 * @brief Fetch a single row
245 * @param mixed $stmt statement object
246 * @return array current row
248 public static function fetch($stmt)
250 return DI::dba()->fetch($stmt);
254 * @brief Insert a row into a table
256 * @param string|array $table Table name or array [schema => table]
257 * @param array $param parameter array
258 * @param bool $on_duplicate_update Do an update on a duplicate entry
260 * @return boolean was the insert successful?
263 public static function insert($table, $param, $on_duplicate_update = false)
265 return DI::dba()->insert($table, $param, $on_duplicate_update);
269 * @brief Fetch the id of the last insert command
271 * @return integer Last inserted id
273 public static function lastInsertId()
275 return DI::dba()->lastInsertId();
279 * @brief Locks a table for exclusive write access
281 * This function can be extended in the future to accept a table array as well.
283 * @param string|array $table Table name or array [schema => table]
285 * @return boolean was the lock successful?
288 public static function lock($table)
290 return DI::dba()->lock($table);
294 * @brief Unlocks all locked tables
296 * @return boolean was the unlock successful?
299 public static function unlock()
301 return DI::dba()->unlock();
305 * @brief Starts a transaction
307 * @return boolean Was the command executed successfully?
309 public static function transaction()
311 return DI::dba()->transaction();
315 * @brief Does a commit
317 * @return boolean Was the command executed successfully?
319 public static function commit()
321 return DI::dba()->commit();
325 * @brief Does a rollback
327 * @return boolean Was the command executed successfully?
329 public static function rollback()
331 return DI::dba()->rollback();
335 * @brief Delete a row from a table
337 * @param string|array $table Table name
338 * @param array $conditions Field condition(s)
339 * @param array $options
340 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
341 * relations (default: true)
343 * @return boolean was the delete successful?
346 public static function delete($table, array $conditions, array $options = [])
348 return DI::dba()->delete($table, $conditions, $options);
352 * @brief Updates rows
354 * Updates rows in the database. When $old_fields is set to an array,
355 * the system will only do an update if the fields in that array changed.
358 * Only the values in $old_fields are compared.
359 * This is an intentional behaviour.
362 * We include the timestamp field in $fields but not in $old_fields.
363 * Then the row will only get the new timestamp when the other fields had changed.
365 * When $old_fields is set to a boolean value the system will do this compare itself.
366 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
369 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
370 * When you set $old_fields to "true" then $fields must contain all relevant fields!
372 * @param string|array $table Table name or array [schema => table]
373 * @param array $fields contains the fields that are updated
374 * @param array $condition condition array with the key values
375 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
377 * @return boolean was the update successfull?
380 public static function update($table, $fields, $condition, $old_fields = [])
382 return DI::dba()->update($table, $fields, $condition, $old_fields);
386 * Retrieve a single record from a table and returns it in an associative array
388 * @brief Retrieve a single record from a table
389 * @param string|array $table Table name or array [schema => table]
390 * @param array $fields
391 * @param array $condition
392 * @param array $params
397 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
399 return DI::dba()->selectFirst($table, $fields, $condition, $params);
403 * @brief Select rows from a table and fills an array with the data
405 * @param string|array $table Table name or array [schema => table]
406 * @param array $fields Array of selected fields, empty for all
407 * @param array $condition Array of fields for condition
408 * @param array $params Array of several parameters
410 * @return array Data array
414 public static function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
416 return DI::dba()->selectToArray($table, $fields, $condition, $params);
420 * @brief Select rows from a table
422 * @param string|array $table Table name or array [schema => table]
423 * @param array $fields Array of selected fields, empty for all
424 * @param array $condition Array of fields for condition
425 * @param array $params Array of several parameters
427 * @return boolean|object
431 * $fields = array("id", "uri", "uid", "network");
433 * $condition = array("uid" => 1, "network" => 'dspr');
435 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
437 * $params = array("order" => array("id", "received" => true), "limit" => 10);
439 * $data = DBA::select($table, $fields, $condition, $params);
442 public static function select($table, array $fields = [], array $condition = [], array $params = [])
444 return DI::dba()->select($table, $fields, $condition, $params);
448 * @brief Counts the rows from a table satisfying the provided condition
450 * @param string|array $table Table name or array [schema => table]
451 * @param array $condition array of fields for condition
452 * @param array $params Array of several parameters
459 * $condition = ["uid" => 1, "network" => 'dspr'];
461 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
463 * $count = DBA::count($table, $condition);
466 public static function count($table, array $condition = [], array $params = [])
468 return DI::dba()->count($table, $condition, $params);
472 * Build the table query substring from one or more tables, with or without a schema.
476 * - [table1, table2, ...]
477 * - [schema1 => table1, schema2 => table2, table3, ...]
479 * @param string|array $tables
482 public static function buildTableString($tables)
484 if (is_string($tables)) {
490 foreach ($tables as $schema => $table) {
491 if (is_numeric($schema)) {
492 $quotedTables[] = self::quoteIdentifier($table);
494 $quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
498 return implode(', ', $quotedTables);
502 * Escape an identifier (table or field name)
507 public static function quoteIdentifier($identifier)
509 return '`' . str_replace('`', '``', $identifier) . '`';
513 * @brief Returns the SQL condition string built from the provided condition array
515 * This function operates with two modes.
516 * - Supplied with a filed/value associative array, it builds simple strict
517 * equality conditions linked by AND.
518 * - Supplied with a flat list, the first element is the condition string and
519 * the following arguments are the values to be interpolated
521 * $condition = ["uid" => 1, "network" => 'dspr'];
523 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
525 * In either case, the provided array is left with the parameters only
527 * @param array $condition
530 public static function buildCondition(array &$condition = [])
532 $condition = self::collapseCondition($condition);
534 $condition_string = '';
535 if (count($condition) > 0) {
536 $condition_string = " WHERE (" . array_shift($condition) . ")";
539 return $condition_string;
543 * Collapse an associative array condition into a SQL string + parameters condition array.
545 * ['uid' => 1, 'network' => ['dspr', 'apub']]
547 * gets transformed into
549 * ["`uid` = ? AND `network` IN (?, ?)", 1, 'dspr', 'apub']
551 * @param array $condition
554 public static function collapseCondition(array $condition)
556 // Ensures an always true condition is returned
557 if (count($condition) < 1) {
562 $first_key = key($condition);
564 if (is_int($first_key)) {
570 $condition_string = "";
571 foreach ($condition as $field => $value) {
572 if ($condition_string != "") {
573 $condition_string .= " AND ";
576 if (is_array($value)) {
578 /* Workaround for MySQL Bug #64791.
579 * Never mix data types inside any IN() condition.
580 * In case of mixed types, cast all as string.
581 * Logic needs to be consistent with DBA::p() data types.
585 foreach ($value as $single_value) {
586 if (is_int($single_value)) {
593 if ($is_int && $is_alpha) {
594 foreach ($value as &$ref) {
599 unset($ref); //Prevent accidental re-use.
602 $values = array_merge($values, array_values($value));
603 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
604 $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
606 // Empty value array isn't supported by IN and is logically equivalent to no match
607 $condition_string .= "FALSE";
609 } elseif (is_null($value)) {
610 $condition_string .= self::quoteIdentifier($field) . " IS NULL";
612 $values[$field] = $value;
613 $condition_string .= self::quoteIdentifier($field) . " = ?";
617 $condition = array_merge([$condition_string], array_values($values));
623 * @brief Returns the SQL parameter string built from the provided parameter array
625 * @param array $params
628 public static function buildParameter(array $params = [])
630 $groupby_string = '';
631 if (!empty($params['group_by'])) {
632 $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
636 if (isset($params['order'])) {
637 $order_string = " ORDER BY ";
638 foreach ($params['order'] AS $fields => $order) {
639 if ($order === 'RAND()') {
640 $order_string .= "RAND(), ";
641 } elseif (!is_int($fields)) {
642 $order_string .= self::quoteIdentifier($fields) . " " . ($order ? "DESC" : "ASC") . ", ";
644 $order_string .= self::quoteIdentifier($order) . ", ";
647 $order_string = substr($order_string, 0, -2);
651 if (isset($params['limit']) && is_numeric($params['limit'])) {
652 $limit_string = " LIMIT " . intval($params['limit']);
655 if (isset($params['limit']) && is_array($params['limit'])) {
656 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
659 return $groupby_string . $order_string . $limit_string;
663 * @brief Fills an array with data from a query
665 * @param object $stmt statement object
666 * @param bool $do_close
667 * @return array Data array
669 public static function toArray($stmt, $do_close = true)
671 return DI::dba()->toArray($stmt, $do_close);
675 * @brief Returns the error number of the last query
677 * @return string Error number (0 if no error)
679 public static function errorNo()
681 return DI::dba()->errorNo();
685 * @brief Returns the error message of the last query
687 * @return string Error message ('' if no error)
689 public static function errorMessage()
691 return DI::dba()->errorMessage();
695 * @brief Closes the current statement
697 * @param object $stmt statement object
698 * @return boolean was the close successful?
700 public static function close($stmt)
702 return DI::dba()->close($stmt);
706 * @brief Return a list of database processes
709 * 'list' => List of processes, separated in their different states
710 * 'amount' => Number of concurrent database processes
713 public static function processlist()
715 return DI::dba()->processlist();
719 * Checks if $array is a filled array with at least one entry.
721 * @param mixed $array A filled array with at least one entry
723 * @return boolean Whether $array is a filled array or an object with rows
725 public static function isResult($array)
727 return DI::dba()->isResult($array);
731 * @brief Escapes a whole array
733 * @param mixed $arr Array with values to be escaped
734 * @param boolean $add_quotation add quotation marks for string values
737 public static function escapeArray(&$arr, $add_quotation = false)
739 DI::dba()->escapeArray($arr, $add_quotation);