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 and fills an array with the data
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 array Data array
423 public static function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
425 return self::$database->selectToArray($table, $fields, $condition, $params);
429 * @brief Select rows from a table
431 * @param string $table Table name
432 * @param array $fields Array of selected fields, empty for all
433 * @param array $condition Array of fields for condition
434 * @param array $params Array of several parameters
436 * @return boolean|object
440 * $fields = array("id", "uri", "uid", "network");
442 * $condition = array("uid" => 1, "network" => 'dspr');
444 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
446 * $params = array("order" => array("id", "received" => true), "limit" => 10);
448 * $data = DBA::select($table, $fields, $condition, $params);
451 public static function select($table, array $fields = [], array $condition = [], array $params = [])
453 return self::$database->select($table, $fields, $condition, $params);
457 * @brief Counts the rows from a table satisfying the provided condition
459 * @param string $table Table name
460 * @param array $condition array of fields for condition
467 * $condition = ["uid" => 1, "network" => 'dspr'];
469 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
471 * $count = DBA::count($table, $condition);
474 public static function count($table, array $condition = [])
476 return self::$database->count($table, $condition);
480 * @brief Returns the SQL condition string built from the provided condition array
482 * This function operates with two modes.
483 * - Supplied with a filed/value associative array, it builds simple strict
484 * equality conditions linked by AND.
485 * - Supplied with a flat list, the first element is the condition string and
486 * the following arguments are the values to be interpolated
488 * $condition = ["uid" => 1, "network" => 'dspr'];
490 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
492 * In either case, the provided array is left with the parameters only
494 * @param array $condition
497 public static function buildCondition(array &$condition = [])
499 $condition_string = '';
500 if (count($condition) > 0) {
502 $first_key = key($condition);
503 if (is_int($first_key)) {
504 $condition_string = " WHERE (" . array_shift($condition) . ")";
507 $condition_string = "";
508 foreach ($condition as $field => $value) {
509 if ($condition_string != "") {
510 $condition_string .= " AND ";
512 if (is_array($value)) {
513 /* Workaround for MySQL Bug #64791.
514 * Never mix data types inside any IN() condition.
515 * In case of mixed types, cast all as string.
516 * Logic needs to be consistent with DBA::p() data types.
520 foreach ($value as $single_value) {
521 if (is_int($single_value)) {
528 if ($is_int && $is_alpha) {
529 foreach ($value as &$ref) {
534 unset($ref); //Prevent accidental re-use.
537 $new_values = array_merge($new_values, array_values($value));
538 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
539 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
540 } elseif (is_null($value)) {
541 $condition_string .= "`" . $field . "` IS NULL";
543 $new_values[$field] = $value;
544 $condition_string .= "`" . $field . "` = ?";
547 $condition_string = " WHERE (" . $condition_string . ")";
548 $condition = $new_values;
552 return $condition_string;
556 * @brief Returns the SQL parameter string built from the provided parameter array
558 * @param array $params
561 public static function buildParameter(array $params = [])
563 $groupby_string = '';
564 if (isset($params['group_by'])) {
565 $groupby_string = " GROUP BY ";
566 foreach ($params['group_by'] as $fields) {
567 $groupby_string .= "`" . $fields . "`, ";
569 $groupby_string = substr($groupby_string, 0, -2);
573 if (isset($params['order'])) {
574 $order_string = " ORDER BY ";
575 foreach ($params['order'] AS $fields => $order) {
576 if ($order === 'RAND()') {
577 $order_string .= "RAND(), ";
578 } elseif (!is_int($fields)) {
579 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
581 $order_string .= "`" . $order . "`, ";
584 $order_string = substr($order_string, 0, -2);
588 if (isset($params['limit']) && is_numeric($params['limit'])) {
589 $limit_string = " LIMIT " . intval($params['limit']);
592 if (isset($params['limit']) && is_array($params['limit'])) {
593 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
596 return $groupby_string . $order_string . $limit_string;
600 * @brief Fills an array with data from a query
602 * @param object $stmt statement object
603 * @param bool $do_close
604 * @return array Data array
606 public static function toArray($stmt, $do_close = true)
608 return self::$database->toArray($stmt, $do_close);
612 * @brief Returns the error number of the last query
614 * @return string Error number (0 if no error)
616 public static function errorNo()
618 return self::$database->errorNo();
622 * @brief Returns the error message of the last query
624 * @return string Error message ('' if no error)
626 public static function errorMessage()
628 return self::$database->errorMessage();
632 * @brief Closes the current statement
634 * @param object $stmt statement object
635 * @return boolean was the close successful?
637 public static function close($stmt)
639 return self::$database->close($stmt);
643 * @brief Return a list of database processes
646 * 'list' => List of processes, separated in their different states
647 * 'amount' => Number of concurrent database processes
650 public static function processlist()
652 return self::$database->processlist();
656 * Checks if $array is a filled array with at least one entry.
658 * @param mixed $array A filled array with at least one entry
660 * @return boolean Whether $array is a filled array or an object with rows
662 public static function isResult($array)
664 return self::$database->isResult($array);
668 * @brief Escapes a whole array
670 * @param mixed $arr Array with values to be escaped
671 * @param boolean $add_quotation add quotation marks for string values
674 public static function escapeArray(&$arr, $add_quotation = false)
676 return self::$database->escapeArray($arr, $add_quotation);