3 namespace Friendica\Database;
12 * @class MySQL database class
14 * This class is for the low level database stuff that does driver specific things.
19 * Lowest possible date value
21 const NULL_DATE = '0001-01-01';
23 * Lowest possible datetime value
25 const NULL_DATETIME = '0001-01-01 00:00:00';
30 private static $database;
32 public static function init(Database $database)
34 self::$database = $database;
37 public static function connect()
39 return self::$database->connect();
43 * Disconnects the current database connection
45 public static function disconnect()
47 self::$database->disconnect();
51 * Perform a reconnect of an existing database connection
53 public static function reconnect()
55 return self::$database->reconnect();
59 * Return the database object.
62 public static function getConnection()
64 return self::$database->getConnection();
68 * @brief Returns the MySQL server version string
70 * This function discriminate between the deprecated mysql API and the current
71 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
75 public static function serverInfo()
77 return self::$database->serverInfo();
81 * @brief Returns the selected database name
86 public static function databaseName()
88 return self::$database->databaseName();
91 public static function escape($str)
93 return self::$database->escape($str);
96 public static function connected()
98 return self::$database->connected();
102 * @brief Replaces ANY_VALUE() function by MIN() function,
103 * if the database server does not support ANY_VALUE().
105 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
106 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
107 * A standard fall-back is to use MIN().
109 * @param string $sql An SQL string without the values
110 * @return string The input SQL string modified if necessary.
112 public static function anyValueFallback($sql)
114 return self::$database->anyValueFallback($sql);
118 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
120 * This is safe when we bind the parameters later.
121 * The parameter values aren't part of the SQL.
123 * @param string $sql An SQL string without the values
124 * @return string The input SQL string modified if necessary.
126 public static function cleanQuery($sql)
128 $search = ["\t", "\n", "\r", " "];
129 $replace = [' ', ' ', ' ', ' '];
132 $sql = str_replace($search, $replace, $sql);
133 } while ($oldsql != $sql);
139 * @brief Convert parameter array to an universal form
140 * @param array $args Parameter array
141 * @return array universalized parameter array
143 public static function getParam($args)
147 // When the second function parameter is an array then use this as the parameter array
148 if ((count($args) > 0) && (is_array($args[1]))) {
156 * @brief Executes a prepared statement that returns data
157 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
159 * Please only use it with complicated queries.
160 * For all regular queries please use DBA::select or DBA::exists
162 * @param string $sql SQL statement
163 * @return bool|object statement object or result object
166 public static function p($sql)
168 $params = self::getParam(func_get_args());
170 return self::$database->p($sql, $params);
174 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
176 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
178 * @param string $sql SQL statement
179 * @return boolean Was the query successfull? False is returned only if an error occurred
182 public static function e($sql) {
184 $params = self::getParam(func_get_args());
186 return self::$database->e($sql, $params);
190 * @brief Check if data exists
192 * @param string $table Table name
193 * @param array $condition array of fields for condition
195 * @return boolean Are there rows for that condition?
198 public static function exists($table, $condition)
200 return self::$database->exists($table, $condition);
204 * Fetches the first row
206 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
208 * @brief Fetches the first row
209 * @param string $sql SQL statement
210 * @return array first row of query
213 public static function fetchFirst($sql)
215 $params = self::getParam(func_get_args());
217 return self::$database->fetchFirst($sql, $params);
221 * @brief Returns the number of affected rows of the last statement
223 * @return int Number of rows
225 public static function affectedRows()
227 return self::$database->affectedRows();
231 * @brief Returns the number of columns of a statement
233 * @param object Statement object
234 * @return int Number of columns
236 public static function columnCount($stmt)
238 return self::$database->columnCount($stmt);
241 * @brief Returns the number of rows of a statement
243 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
244 * @return int Number of rows
246 public static function numRows($stmt)
248 return self::$database->numRows($stmt);
252 * @brief Fetch a single row
254 * @param mixed $stmt statement object
255 * @return array current row
257 public static function fetch($stmt)
259 return self::$database->fetch($stmt);
263 * @brief Insert a row into a table
265 * @param string $table Table name
266 * @param array $param parameter array
267 * @param bool $on_duplicate_update Do an update on a duplicate entry
269 * @return boolean was the insert successful?
272 public static function insert($table, $param, $on_duplicate_update = false)
274 return self::$database->insert($table, $param, $on_duplicate_update);
278 * @brief Fetch the id of the last insert command
280 * @return integer Last inserted id
282 public static function lastInsertId()
284 return self::$database->lastInsertId();
288 * @brief Locks a table for exclusive write access
290 * This function can be extended in the future to accept a table array as well.
292 * @param string $table Table name
294 * @return boolean was the lock successful?
297 public static function lock($table)
299 return self::$database->lock($table);
303 * @brief Unlocks all locked tables
305 * @return boolean was the unlock successful?
308 public static function unlock()
310 return self::$database->unlock();
314 * @brief Starts a transaction
316 * @return boolean Was the command executed successfully?
318 public static function transaction()
320 return self::$database->transaction();
324 * @brief Does a commit
326 * @return boolean Was the command executed successfully?
328 public static function commit()
330 return self::$database->commit();
334 * @brief Does a rollback
336 * @return boolean Was the command executed successfully?
338 public static function rollback()
340 return self::$database->rollback();
344 * @brief Delete a row from a table
346 * @param string $table Table name
347 * @param array $conditions Field condition(s)
348 * @param array $options
349 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
350 * relations (default: true)
352 * @return boolean was the delete successful?
355 public static function delete($table, array $conditions, array $options = [])
357 return self::$database->delete($table, $conditions, $options);
361 * @brief Updates rows
363 * Updates rows in the database. When $old_fields is set to an array,
364 * the system will only do an update if the fields in that array changed.
367 * Only the values in $old_fields are compared.
368 * This is an intentional behaviour.
371 * We include the timestamp field in $fields but not in $old_fields.
372 * Then the row will only get the new timestamp when the other fields had changed.
374 * When $old_fields is set to a boolean value the system will do this compare itself.
375 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
378 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
379 * When you set $old_fields to "true" then $fields must contain all relevant fields!
381 * @param string $table Table name
382 * @param array $fields contains the fields that are updated
383 * @param array $condition condition array with the key values
384 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
386 * @return boolean was the update successfull?
389 public static function update($table, $fields, $condition, $old_fields = [])
391 return self::$database->update($table, $fields, $condition, $old_fields);
395 * Retrieve a single record from a table and returns it in an associative array
397 * @brief Retrieve a single record from a table
398 * @param string $table
399 * @param array $fields
400 * @param array $condition
401 * @param array $params
406 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
408 return self::$database->selectFirst($table, $fields, $condition, $params);
412 * @brief Select rows from a table
414 * @param string $table Table name
415 * @param array $fields Array of selected fields, empty for all
416 * @param array $condition Array of fields for condition
417 * @param array $params Array of several parameters
419 * @return boolean|object
423 * $fields = array("id", "uri", "uid", "network");
425 * $condition = array("uid" => 1, "network" => 'dspr');
427 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
429 * $params = array("order" => array("id", "received" => true), "limit" => 10);
431 * $data = DBA::select($table, $fields, $condition, $params);
434 public static function select($table, array $fields = [], array $condition = [], array $params = [])
436 return self::$database->select($table, $fields, $condition, $params);
440 * @brief Counts the rows from a table satisfying the provided condition
442 * @param string $table Table name
443 * @param array $condition array of fields for condition
450 * $condition = ["uid" => 1, "network" => 'dspr'];
452 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
454 * $count = DBA::count($table, $condition);
457 public static function count($table, array $condition = [])
459 return self::$database->count($table, $condition);
463 * @brief Returns the SQL condition string built from the provided condition array
465 * This function operates with two modes.
466 * - Supplied with a filed/value associative array, it builds simple strict
467 * equality conditions linked by AND.
468 * - Supplied with a flat list, the first element is the condition string and
469 * the following arguments are the values to be interpolated
471 * $condition = ["uid" => 1, "network" => 'dspr'];
473 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
475 * In either case, the provided array is left with the parameters only
477 * @param array $condition
480 public static function buildCondition(array &$condition = [])
482 $condition_string = '';
483 if (count($condition) > 0) {
485 $first_key = key($condition);
486 if (is_int($first_key)) {
487 $condition_string = " WHERE (" . array_shift($condition) . ")";
490 $condition_string = "";
491 foreach ($condition as $field => $value) {
492 if ($condition_string != "") {
493 $condition_string .= " AND ";
495 if (is_array($value)) {
496 /* Workaround for MySQL Bug #64791.
497 * Never mix data types inside any IN() condition.
498 * In case of mixed types, cast all as string.
499 * Logic needs to be consistent with DBA::p() data types.
503 foreach ($value as $single_value) {
504 if (is_int($single_value)) {
511 if ($is_int && $is_alpha) {
512 foreach ($value as &$ref) {
517 unset($ref); //Prevent accidental re-use.
520 $new_values = array_merge($new_values, array_values($value));
521 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
522 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
523 } elseif (is_null($value)) {
524 $condition_string .= "`" . $field . "` IS NULL";
526 $new_values[$field] = $value;
527 $condition_string .= "`" . $field . "` = ?";
530 $condition_string = " WHERE (" . $condition_string . ")";
531 $condition = $new_values;
535 return $condition_string;
539 * @brief Returns the SQL parameter string built from the provided parameter array
541 * @param array $params
544 public static function buildParameter(array $params = [])
546 $groupby_string = '';
547 if (isset($params['group_by'])) {
548 $groupby_string = " GROUP BY ";
549 foreach ($params['group_by'] as $fields) {
550 $groupby_string .= "`" . $fields . "`, ";
552 $groupby_string = substr($groupby_string, 0, -2);
556 if (isset($params['order'])) {
557 $order_string = " ORDER BY ";
558 foreach ($params['order'] AS $fields => $order) {
559 if ($order === 'RAND()') {
560 $order_string .= "RAND(), ";
561 } elseif (!is_int($fields)) {
562 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
564 $order_string .= "`" . $order . "`, ";
567 $order_string = substr($order_string, 0, -2);
571 if (isset($params['limit']) && is_numeric($params['limit'])) {
572 $limit_string = " LIMIT " . intval($params['limit']);
575 if (isset($params['limit']) && is_array($params['limit'])) {
576 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
579 return $groupby_string . $order_string . $limit_string;
583 * @brief Fills an array with data from a query
585 * @param object $stmt statement object
586 * @param bool $do_close
587 * @return array Data array
589 public static function toArray($stmt, $do_close = true)
591 return self::$database->toArray($stmt, $do_close);
595 * @brief Returns the error number of the last query
597 * @return string Error number (0 if no error)
599 public static function errorNo()
601 return self::$database->errorNo();
605 * @brief Returns the error message of the last query
607 * @return string Error message ('' if no error)
609 public static function errorMessage()
611 return self::$database->errorMessage();
615 * @brief Closes the current statement
617 * @param object $stmt statement object
618 * @return boolean was the close successful?
620 public static function close($stmt)
622 return self::$database->close($stmt);
626 * @brief Return a list of database processes
629 * 'list' => List of processes, separated in their different states
630 * 'amount' => Number of concurrent database processes
633 public static function processlist()
635 return self::$database->processlist();
639 * Checks if $array is a filled array with at least one entry.
641 * @param mixed $array A filled array with at least one entry
643 * @return boolean Whether $array is a filled array or an object with rows
645 public static function isResult($array)
647 return self::$database->isResult($array);
651 * @brief Escapes a whole array
653 * @param mixed $arr Array with values to be escaped
654 * @param boolean $add_quotation add quotation marks for string values
657 public static function escapeArray(&$arr, $add_quotation = false)
659 return self::$database->escapeArray($arr, $add_quotation);