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 * 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 * Returns the selected database name
77 public static function databaseName()
79 return DI::dba()->databaseName();
83 * Escape all SQL unsafe data
86 * @return string escaped string
88 public static function escape($str)
90 return DI::dba()->escape($str);
94 * Checks if the database is connected
96 * @return boolean is the database connected?
98 public static function connected()
100 return DI::dba()->connected();
104 * Replaces ANY_VALUE() function by MIN() function,
105 * if the database server does not support ANY_VALUE().
107 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
108 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
109 * A standard fall-back is to use MIN().
111 * @param string $sql An SQL string without the values
112 * @return string The input SQL string modified if necessary.
114 public static function anyValueFallback($sql)
116 return DI::dba()->anyValueFallback($sql);
120 * beautifies the query - useful for "SHOW PROCESSLIST"
122 * This is safe when we bind the parameters later.
123 * The parameter values aren't part of the SQL.
125 * @param string $sql An SQL string without the values
126 * @return string The input SQL string modified if necessary.
128 public static function cleanQuery($sql)
130 $search = ["\t", "\n", "\r", " "];
131 $replace = [' ', ' ', ' ', ' '];
134 $sql = str_replace($search, $replace, $sql);
135 } while ($oldsql != $sql);
141 * Convert parameter array to an universal form
142 * @param array $args Parameter array
143 * @return array universalized parameter array
145 public static function getParam($args)
149 // When the second function parameter is an array then use this as the parameter array
150 if ((count($args) > 0) && (is_array($args[1]))) {
158 * Executes a prepared statement that returns data
159 * Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
161 * Please only use it with complicated queries.
162 * For all regular queries please use DBA::select or DBA::exists
164 * @param string $sql SQL statement
165 * @return bool|object statement object or result object
168 public static function p($sql)
170 $params = self::getParam(func_get_args());
172 return DI::dba()->p($sql, $params);
176 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
178 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
180 * @param string $sql SQL statement
181 * @return boolean Was the query successfull? False is returned only if an error occurred
184 public static function e($sql) {
186 $params = self::getParam(func_get_args());
188 return DI::dba()->e($sql, $params);
192 * Check if data exists
194 * @param string|array $table Table name or array [schema => table]
195 * @param array $condition array of fields for condition
197 * @return boolean Are there rows for that condition?
200 public static function exists($table, $condition)
202 return DI::dba()->exists($table, $condition);
206 * Fetches the first row
208 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
210 * @param string $sql SQL statement
211 * @return array first row of query
214 public static function fetchFirst($sql)
216 $params = self::getParam(func_get_args());
218 return DI::dba()->fetchFirst($sql, $params);
222 * Returns the number of affected rows of the last statement
224 * @return int Number of rows
226 public static function affectedRows()
228 return DI::dba()->affectedRows();
232 * Returns the number of columns of a statement
234 * @param object Statement object
235 * @return int Number of columns
237 public static function columnCount($stmt)
239 return DI::dba()->columnCount($stmt);
242 * Returns the number of rows of a statement
244 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
245 * @return int Number of rows
247 public static function numRows($stmt)
249 return DI::dba()->numRows($stmt);
255 * @param mixed $stmt statement object
256 * @return array current row
258 public static function fetch($stmt)
260 return DI::dba()->fetch($stmt);
264 * Insert a row into a table
266 * @param string|array $table Table name or array [schema => table]
267 * @param array $param parameter array
268 * @param bool $on_duplicate_update Do an update on a duplicate entry
270 * @return boolean was the insert successful?
273 public static function insert($table, $param, $on_duplicate_update = false)
275 return DI::dba()->insert($table, $param, $on_duplicate_update);
279 * Fetch the id of the last insert command
281 * @return integer Last inserted id
283 public static function lastInsertId()
285 return DI::dba()->lastInsertId();
289 * Locks a table for exclusive write access
291 * This function can be extended in the future to accept a table array as well.
293 * @param string|array $table Table name or array [schema => table]
295 * @return boolean was the lock successful?
298 public static function lock($table)
300 return DI::dba()->lock($table);
304 * Unlocks all locked tables
306 * @return boolean was the unlock successful?
309 public static function unlock()
311 return DI::dba()->unlock();
315 * Starts a transaction
317 * @return boolean Was the command executed successfully?
319 public static function transaction()
321 return DI::dba()->transaction();
327 * @return boolean Was the command executed successfully?
329 public static function commit()
331 return DI::dba()->commit();
337 * @return boolean Was the command executed successfully?
339 public static function rollback()
341 return DI::dba()->rollback();
345 * Delete a row from a table
347 * @param string|array $table Table name
348 * @param array $conditions Field condition(s)
349 * @param array $options
350 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
351 * relations (default: true)
353 * @return boolean was the delete successful?
356 public static function delete($table, array $conditions, array $options = [])
358 return DI::dba()->delete($table, $conditions, $options);
362 * Updates rows in the database.
364 * When $old_fields is set to an array,
365 * the system will only do an update if the fields in that array changed.
368 * Only the values in $old_fields are compared.
369 * This is an intentional behaviour.
372 * We include the timestamp field in $fields but not in $old_fields.
373 * Then the row will only get the new timestamp when the other fields had changed.
375 * When $old_fields is set to a boolean value the system will do this compare itself.
376 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
379 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
380 * When you set $old_fields to "true" then $fields must contain all relevant fields!
382 * @param string|array $table Table name or array [schema => table]
383 * @param array $fields contains the fields that are updated
384 * @param array $condition condition array with the key values
385 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
387 * @return boolean was the update successfull?
390 public static function update($table, $fields, $condition, $old_fields = [])
392 return DI::dba()->update($table, $fields, $condition, $old_fields);
396 * Retrieve a single record from a table and returns it in an associative array
398 * @param string|array $table Table name or array [schema => 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 DI::dba()->selectFirst($table, $fields, $condition, $params);
412 * Select rows from a table and fills an array with the data
414 * @param string|array $table Table name or array [schema => table]
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($table, array $fields = [], array $condition = [], array $params = [])
425 return DI::dba()->selectToArray($table, $fields, $condition, $params);
429 * Select rows from a table
431 * @param string|array $table Table name or array [schema => table]
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 DI::dba()->select($table, $fields, $condition, $params);
457 * Counts the rows from a table satisfying the provided condition
459 * @param string|array $table Table name or array [schema => table]
460 * @param array $condition array of fields for condition
461 * @param array $params Array of several parameters
468 * $condition = ["uid" => 1, "network" => 'dspr'];
470 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
472 * $count = DBA::count($table, $condition);
475 public static function count($table, array $condition = [], array $params = [])
477 return DI::dba()->count($table, $condition, $params);
481 * Build the table query substring from one or more tables, with or without a schema.
485 * - [table1, table2, ...]
486 * - [schema1 => table1, schema2 => table2, table3, ...]
488 * @param string|array $tables
491 public static function buildTableString($tables)
493 if (is_string($tables)) {
499 foreach ($tables as $schema => $table) {
500 if (is_numeric($schema)) {
501 $quotedTables[] = self::quoteIdentifier($table);
503 $quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
507 return implode(', ', $quotedTables);
511 * Escape an identifier (table or field name)
516 public static function quoteIdentifier($identifier)
518 return '`' . str_replace('`', '``', $identifier) . '`';
522 * Returns the SQL condition string built from the provided condition array
524 * This function operates with two modes.
525 * - Supplied with a filed/value associative array, it builds simple strict
526 * equality conditions linked by AND.
527 * - Supplied with a flat list, the first element is the condition string and
528 * the following arguments are the values to be interpolated
530 * $condition = ["uid" => 1, "network" => 'dspr'];
532 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
534 * In either case, the provided array is left with the parameters only
536 * @param array $condition
539 public static function buildCondition(array &$condition = [])
541 $condition = self::collapseCondition($condition);
543 $condition_string = '';
544 if (count($condition) > 0) {
545 $condition_string = " WHERE (" . array_shift($condition) . ")";
548 return $condition_string;
552 * Collapse an associative array condition into a SQL string + parameters condition array.
554 * ['uid' => 1, 'network' => ['dspr', 'apub']]
556 * gets transformed into
558 * ["`uid` = ? AND `network` IN (?, ?)", 1, 'dspr', 'apub']
560 * @param array $condition
563 public static function collapseCondition(array $condition)
565 // Ensures an always true condition is returned
566 if (count($condition) < 1) {
571 $first_key = key($condition);
573 if (is_int($first_key)) {
579 $condition_string = "";
580 foreach ($condition as $field => $value) {
581 if ($condition_string != "") {
582 $condition_string .= " AND ";
585 if (is_array($value)) {
587 /* Workaround for MySQL Bug #64791.
588 * Never mix data types inside any IN() condition.
589 * In case of mixed types, cast all as string.
590 * Logic needs to be consistent with DBA::p() data types.
594 foreach ($value as $single_value) {
595 if (is_int($single_value)) {
602 if ($is_int && $is_alpha) {
603 foreach ($value as &$ref) {
608 unset($ref); //Prevent accidental re-use.
611 $values = array_merge($values, array_values($value));
612 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
613 $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
615 // Empty value array isn't supported by IN and is logically equivalent to no match
616 $condition_string .= "FALSE";
618 } elseif (is_null($value)) {
619 $condition_string .= self::quoteIdentifier($field) . " IS NULL";
621 $values[$field] = $value;
622 $condition_string .= self::quoteIdentifier($field) . " = ?";
626 $condition = array_merge([$condition_string], array_values($values));
632 * Returns the SQL parameter string built from the provided parameter array
634 * @param array $params
637 public static function buildParameter(array $params = [])
639 $groupby_string = '';
640 if (!empty($params['group_by'])) {
641 $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
645 if (isset($params['order'])) {
646 $order_string = " ORDER BY ";
647 foreach ($params['order'] AS $fields => $order) {
648 if ($order === 'RAND()') {
649 $order_string .= "RAND(), ";
650 } elseif (!is_int($fields)) {
651 $order_string .= self::quoteIdentifier($fields) . " " . ($order ? "DESC" : "ASC") . ", ";
653 $order_string .= self::quoteIdentifier($order) . ", ";
656 $order_string = substr($order_string, 0, -2);
660 if (isset($params['limit']) && is_numeric($params['limit'])) {
661 $limit_string = " LIMIT " . intval($params['limit']);
664 if (isset($params['limit']) && is_array($params['limit'])) {
665 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
668 return $groupby_string . $order_string . $limit_string;
672 * Fills an array with data from a query
674 * @param object $stmt statement object
675 * @param bool $do_close
676 * @return array Data array
678 public static function toArray($stmt, $do_close = true)
680 return DI::dba()->toArray($stmt, $do_close);
684 * Returns the error number of the last query
686 * @return string Error number (0 if no error)
688 public static function errorNo()
690 return DI::dba()->errorNo();
694 * Returns the error message of the last query
696 * @return string Error message ('' if no error)
698 public static function errorMessage()
700 return DI::dba()->errorMessage();
704 * Closes the current statement
706 * @param object $stmt statement object
707 * @return boolean was the close successful?
709 public static function close($stmt)
711 return DI::dba()->close($stmt);
715 * Return a list of database processes
718 * 'list' => List of processes, separated in their different states
719 * 'amount' => Number of concurrent database processes
722 public static function processlist()
724 return DI::dba()->processlist();
728 * Checks if $array is a filled array with at least one entry.
730 * @param mixed $array A filled array with at least one entry
732 * @return boolean Whether $array is a filled array or an object with rows
734 public static function isResult($array)
736 return DI::dba()->isResult($array);
740 * Escapes a whole array
742 * @param mixed $arr Array with values to be escaped
743 * @param boolean $add_quotation add quotation marks for string values
746 public static function escapeArray(&$arr, $add_quotation = false)
748 DI::dba()->escapeArray($arr, $add_quotation);