3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
32 * This class is for the low level database stuff that does driver specific things.
37 * Lowest possible date value
39 const NULL_DATE = '0001-01-01';
41 * Lowest possible datetime value
43 const NULL_DATETIME = '0001-01-01 00:00:00';
45 public static function connect()
47 return DI::dba()->connect();
51 * Disconnects the current database connection
53 public static function disconnect()
55 DI::dba()->disconnect();
59 * Perform a reconnect of an existing database connection
61 public static function reconnect()
63 return DI::dba()->reconnect();
67 * Return the database object.
70 public static function getConnection()
72 return DI::dba()->getConnection();
76 * Return the database driver string
78 * @return string with either "pdo" or "mysqli"
80 public static function getDriver()
82 return DI::dba()->getDriver();
86 * Returns the MySQL server version string
88 * This function discriminate between the deprecated mysql API and the current
89 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
93 public static function serverInfo()
95 return DI::dba()->serverInfo();
99 * Returns the selected database name
104 public static function databaseName()
106 return DI::dba()->databaseName();
110 * Escape all SQL unsafe data
113 * @return string escaped string
115 public static function escape($str)
117 return DI::dba()->escape($str);
121 * Checks if the database is connected
123 * @return boolean is the database connected?
125 public static function connected()
127 return DI::dba()->connected();
131 * Replaces ANY_VALUE() function by MIN() function,
132 * if the database server does not support ANY_VALUE().
134 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
135 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
136 * A standard fall-back is to use MIN().
138 * @param string $sql An SQL string without the values
139 * @return string The input SQL string modified if necessary.
141 public static function anyValueFallback($sql)
143 return DI::dba()->anyValueFallback($sql);
147 * beautifies the query - useful for "SHOW PROCESSLIST"
149 * This is safe when we bind the parameters later.
150 * The parameter values aren't part of the SQL.
152 * @param string $sql An SQL string without the values
153 * @return string The input SQL string modified if necessary.
155 public static function cleanQuery($sql)
157 $search = ["\t", "\n", "\r", " "];
158 $replace = [' ', ' ', ' ', ' '];
161 $sql = str_replace($search, $replace, $sql);
162 } while ($oldsql != $sql);
168 * Convert parameter array to an universal form
169 * @param array $args Parameter array
170 * @return array universalized parameter array
172 public static function getParam($args)
176 // When the second function parameter is an array then use this as the parameter array
177 if ((count($args) > 0) && (is_array($args[1]))) {
185 * Executes a prepared statement that returns data
186 * Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
188 * Please only use it with complicated queries.
189 * For all regular queries please use DBA::select or DBA::exists
191 * @param string $sql SQL statement
192 * @return bool|object statement object or result object
195 public static function p($sql)
197 $params = self::getParam(func_get_args());
199 return DI::dba()->p($sql, $params);
203 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
205 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
207 * @param string $sql SQL statement
208 * @return boolean Was the query successfull? False is returned only if an error occurred
211 public static function e($sql) {
213 $params = self::getParam(func_get_args());
215 return DI::dba()->e($sql, $params);
219 * Check if data exists
221 * @param string|array $table Table name or array [schema => table]
222 * @param array $condition array of fields for condition
224 * @return boolean Are there rows for that condition?
227 public static function exists($table, $condition)
229 return DI::dba()->exists($table, $condition);
233 * Fetches the first row
235 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
237 * @param string $sql SQL statement
238 * @return array first row of query
241 public static function fetchFirst($sql)
243 $params = self::getParam(func_get_args());
245 return DI::dba()->fetchFirst($sql, $params);
249 * Returns the number of affected rows of the last statement
251 * @return int Number of rows
253 public static function affectedRows()
255 return DI::dba()->affectedRows();
259 * Returns the number of columns of a statement
261 * @param object Statement object
262 * @return int Number of columns
264 public static function columnCount($stmt)
266 return DI::dba()->columnCount($stmt);
269 * Returns the number of rows of a statement
271 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
272 * @return int Number of rows
274 public static function numRows($stmt)
276 return DI::dba()->numRows($stmt);
282 * @param mixed $stmt statement object
283 * @return array current row
285 public static function fetch($stmt)
287 return DI::dba()->fetch($stmt);
291 * Insert a row into a table
293 * @param string|array $table Table name or array [schema => table]
294 * @param array $param parameter array
295 * @param int $duplicate_mode What to do on a duplicated entry
297 * @return boolean was the insert successful?
300 public static function insert($table, array $param, int $duplicate_mode = Database::INSERT_DEFAULT)
302 return DI::dba()->insert($table, $param, $duplicate_mode);
306 * Inserts a row with the provided data in the provided table.
307 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
309 * @param string|array $table Table name or array [schema => table]
310 * @param array $param parameter array
312 * @return boolean was the insert successful?
315 public static function replace($table, $param)
317 return DI::dba()->replace($table, $param);
321 * Fetch the id of the last insert command
323 * @return integer Last inserted id
325 public static function lastInsertId()
327 return DI::dba()->lastInsertId();
331 * Locks a table for exclusive write access
333 * This function can be extended in the future to accept a table array as well.
335 * @param string|array $table Table name or array [schema => table]
337 * @return boolean was the lock successful?
340 public static function lock($table)
342 return DI::dba()->lock($table);
346 * Unlocks all locked tables
348 * @return boolean was the unlock successful?
351 public static function unlock()
353 return DI::dba()->unlock();
357 * Starts a transaction
359 * @return boolean Was the command executed successfully?
361 public static function transaction()
363 return DI::dba()->transaction();
369 * @return boolean Was the command executed successfully?
371 public static function commit()
373 return DI::dba()->commit();
379 * @return boolean Was the command executed successfully?
381 public static function rollback()
383 return DI::dba()->rollback();
387 * Delete a row from a table
389 * @param string|array $table Table name
390 * @param array $conditions Field condition(s)
391 * @param array $options
392 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
393 * relations (default: true)
395 * @return boolean was the delete successful?
398 public static function delete($table, array $conditions, array $options = [])
400 return DI::dba()->delete($table, $conditions, $options);
404 * Updates rows in the database.
406 * When $old_fields is set to an array,
407 * the system will only do an update if the fields in that array changed.
410 * Only the values in $old_fields are compared.
411 * This is an intentional behaviour.
414 * We include the timestamp field in $fields but not in $old_fields.
415 * Then the row will only get the new timestamp when the other fields had changed.
417 * When $old_fields is set to a boolean value the system will do this compare itself.
418 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
421 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
422 * When you set $old_fields to "true" then $fields must contain all relevant fields!
424 * @param string|array $table Table name or array [schema => table]
425 * @param array $fields contains the fields that are updated
426 * @param array $condition condition array with the key values
427 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
429 * @return boolean was the update successfull?
432 public static function update($table, $fields, $condition, $old_fields = [])
434 return DI::dba()->update($table, $fields, $condition, $old_fields);
438 * Retrieve a single record from a table and returns it in an associative array
440 * @param string|array $table Table name or array [schema => table]
441 * @param array $fields
442 * @param array $condition
443 * @param array $params
448 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
450 return DI::dba()->selectFirst($table, $fields, $condition, $params);
454 * Select rows from a table and fills an array with the data
456 * @param string|array $table Table name or array [schema => table]
457 * @param array $fields Array of selected fields, empty for all
458 * @param array $condition Array of fields for condition
459 * @param array $params Array of several parameters
461 * @return array Data array
465 public static function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
467 return DI::dba()->selectToArray($table, $fields, $condition, $params);
471 * Select rows from a table
473 * @param string|array $table Table name or array [schema => table]
474 * @param array $fields Array of selected fields, empty for all
475 * @param array $condition Array of fields for condition
476 * @param array $params Array of several parameters
478 * @return boolean|object
482 * $fields = array("id", "uri", "uid", "network");
484 * $condition = array("uid" => 1, "network" => 'dspr');
486 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
488 * $params = array("order" => array("id", "received" => true), "limit" => 10);
490 * $data = DBA::select($table, $fields, $condition, $params);
493 public static function select($table, array $fields = [], array $condition = [], array $params = [])
495 return DI::dba()->select($table, $fields, $condition, $params);
499 * Counts the rows from a table satisfying the provided condition
501 * @param string|array $table Table name or array [schema => table]
502 * @param array $condition array of fields for condition
503 * @param array $params Array of several parameters
510 * $condition = ["uid" => 1, "network" => 'dspr'];
512 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
514 * $count = DBA::count($table, $condition);
517 public static function count($table, array $condition = [], array $params = [])
519 return DI::dba()->count($table, $condition, $params);
523 * Build the table query substring from one or more tables, with or without a schema.
527 * - [table1, table2, ...]
528 * - [schema1 => table1, schema2 => table2, table3, ...]
530 * @param string|array $tables
533 public static function buildTableString($tables)
535 if (is_string($tables)) {
541 foreach ($tables as $schema => $table) {
542 if (is_numeric($schema)) {
543 $quotedTables[] = self::quoteIdentifier($table);
545 $quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
549 return implode(', ', $quotedTables);
553 * Escape an identifier (table or field name)
558 public static function quoteIdentifier($identifier)
560 return '`' . str_replace('`', '``', $identifier) . '`';
564 * Returns the SQL condition string built from the provided condition array
566 * This function operates with two modes.
567 * - Supplied with a field/value associative array, it builds simple strict
568 * equality conditions linked by AND.
569 * - Supplied with a flat list, the first element is the condition string and
570 * the following arguments are the values to be interpolated
572 * $condition = ["uid" => 1, "network" => 'dspr'];
574 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
576 * In either case, the provided array is left with the parameters only
578 * @param array $condition
581 public static function buildCondition(array &$condition = [])
583 $condition = self::collapseCondition($condition);
585 $condition_string = '';
586 if (count($condition) > 0) {
587 $condition_string = " WHERE (" . array_shift($condition) . ")";
590 return $condition_string;
594 * Collapse an associative array condition into a SQL string + parameters condition array.
596 * ['uid' => 1, 'network' => ['dspr', 'apub']]
598 * gets transformed into
600 * ["`uid` = ? AND `network` IN (?, ?)", 1, 'dspr', 'apub']
602 * @param array $condition
605 public static function collapseCondition(array $condition)
607 // Ensures an always true condition is returned
608 if (count($condition) < 1) {
613 $first_key = key($condition);
615 if (is_int($first_key)) {
621 $condition_string = "";
622 foreach ($condition as $field => $value) {
623 if ($condition_string != "") {
624 $condition_string .= " AND ";
627 if (is_array($value)) {
629 /* Workaround for MySQL Bug #64791.
630 * Never mix data types inside any IN() condition.
631 * In case of mixed types, cast all as string.
632 * Logic needs to be consistent with DBA::p() data types.
636 foreach ($value as $single_value) {
637 if (is_int($single_value)) {
644 if ($is_int && $is_alpha) {
645 foreach ($value as &$ref) {
650 unset($ref); //Prevent accidental re-use.
653 $values = array_merge($values, array_values($value));
654 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
655 $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
657 // Empty value array isn't supported by IN and is logically equivalent to no match
658 $condition_string .= "FALSE";
660 } elseif (is_null($value)) {
661 $condition_string .= self::quoteIdentifier($field) . " IS NULL";
663 $values[$field] = $value;
664 $condition_string .= self::quoteIdentifier($field) . " = ?";
668 $condition = array_merge([$condition_string], array_values($values));
674 * Merges the provided conditions into a single collapsed one
676 * @param array ...$conditions One or more condition arrays
677 * @return array A collapsed condition
678 * @see DBA::collapseCondition() for the condition array formats
680 public static function mergeConditions(array ...$conditions)
682 if (count($conditions) == 1) {
683 return current($conditions);
686 $conditionStrings = [];
689 foreach ($conditions as $key => $condition) {
694 $condition = self::collapseCondition($condition);
696 $conditionStrings[] = array_shift($condition);
697 // The result array holds the eventual parameter values
698 $result = array_merge($result, $condition);
701 if (count($conditionStrings)) {
702 // We prepend the condition string at the end to form a collapsed condition array again
703 array_unshift($result, implode(' AND ', $conditionStrings));
710 * Returns the SQL parameter string built from the provided parameter array
712 * Expected format for each key:
715 * - list of column names
718 * - numeric keyed column name => ASC
719 * - associative element with boolean value => DESC (true), ASC (false)
720 * - associative element with string value => 'ASC' or 'DESC' literally
723 * - single numeric value => count
724 * - list with two numeric values => offset, count
726 * @param array $params
729 public static function buildParameter(array $params = [])
731 $groupby_string = '';
732 if (!empty($params['group_by'])) {
733 $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
737 if (isset($params['order'])) {
738 $order_string = " ORDER BY ";
739 foreach ($params['order'] AS $fields => $order) {
740 if ($order === 'RAND()') {
741 $order_string .= "RAND(), ";
742 } elseif (!is_int($fields)) {
743 if ($order !== 'DESC' && $order !== 'ASC') {
744 $order = $order ? 'DESC' : 'ASC';
747 $order_string .= self::quoteIdentifier($fields) . " " . $order . ", ";
749 $order_string .= self::quoteIdentifier($order) . ", ";
752 $order_string = substr($order_string, 0, -2);
756 if (isset($params['limit']) && is_numeric($params['limit'])) {
757 $limit_string = " LIMIT " . intval($params['limit']);
760 if (isset($params['limit']) && is_array($params['limit'])) {
761 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
764 return $groupby_string . $order_string . $limit_string;
768 * Fills an array with data from a query
770 * @param object $stmt statement object
771 * @param bool $do_close
772 * @return array Data array
774 public static function toArray($stmt, $do_close = true)
776 return DI::dba()->toArray($stmt, $do_close);
780 * Returns the error number of the last query
782 * @return string Error number (0 if no error)
784 public static function errorNo()
786 return DI::dba()->errorNo();
790 * Returns the error message of the last query
792 * @return string Error message ('' if no error)
794 public static function errorMessage()
796 return DI::dba()->errorMessage();
800 * Closes the current statement
802 * @param object $stmt statement object
803 * @return boolean was the close successful?
805 public static function close($stmt)
807 return DI::dba()->close($stmt);
811 * Return a list of database processes
814 * 'list' => List of processes, separated in their different states
815 * 'amount' => Number of concurrent database processes
818 public static function processlist()
820 return DI::dba()->processlist();
824 * Fetch a database variable
826 * @param string $name
827 * @return string content
829 public static function getVariable(string $name)
831 return DI::dba()->getVariable($name);
835 * Checks if $array is a filled array with at least one entry.
837 * @param mixed $array A filled array with at least one entry
839 * @return boolean Whether $array is a filled array or an object with rows
841 public static function isResult($array)
843 return DI::dba()->isResult($array);
847 * Escapes a whole array
849 * @param mixed $arr Array with values to be escaped
850 * @param boolean $add_quotation add quotation marks for string values
853 public static function escapeArray(&$arr, $add_quotation = false)
855 DI::dba()->escapeArray($arr, $add_quotation);