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 `post` 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)
392 * @return boolean was the delete successful?
395 public static function delete($table, array $conditions, array $options = [])
397 return DI::dba()->delete($table, $conditions, $options);
401 * Updates rows in the database.
403 * When $old_fields is set to an array,
404 * the system will only do an update if the fields in that array changed.
407 * Only the values in $old_fields are compared.
408 * This is an intentional behaviour.
411 * We include the timestamp field in $fields but not in $old_fields.
412 * Then the row will only get the new timestamp when the other fields had changed.
414 * When $old_fields is set to a boolean value the system will do this compare itself.
415 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
418 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
419 * When you set $old_fields to "true" then $fields must contain all relevant fields!
421 * @param string|array $table Table name or array [schema => table]
422 * @param array $fields contains the fields that are updated
423 * @param array $condition condition array with the key values
424 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
426 * @return boolean was the update successfull?
429 public static function update($table, $fields, $condition, $old_fields = [])
431 return DI::dba()->update($table, $fields, $condition, $old_fields);
435 * Retrieve a single record from a table and returns it in an associative array
437 * @param string|array $table Table name or array [schema => table]
438 * @param array $fields
439 * @param array $condition
440 * @param array $params
445 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
447 return DI::dba()->selectFirst($table, $fields, $condition, $params);
451 * Select rows from a table and fills an array with the data
453 * @param string|array $table Table name or array [schema => table]
454 * @param array $fields Array of selected fields, empty for all
455 * @param array $condition Array of fields for condition
456 * @param array $params Array of several parameters
458 * @return array Data array
462 public static function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
464 return DI::dba()->selectToArray($table, $fields, $condition, $params);
468 * Select rows from a table
470 * @param string|array $table Table name or array [schema => table]
471 * @param array $fields Array of selected fields, empty for all
472 * @param array $condition Array of fields for condition
473 * @param array $params Array of several parameters
475 * @return boolean|object
479 * $fields = array("id", "uri", "uid", "network");
481 * $condition = array("uid" => 1, "network" => 'dspr');
483 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
485 * $params = array("order" => array("id", "received" => true), "limit" => 10);
487 * $data = DBA::select($table, $fields, $condition, $params);
490 public static function select($table, array $fields = [], array $condition = [], array $params = [])
492 return DI::dba()->select($table, $fields, $condition, $params);
496 * Counts the rows from a table satisfying the provided condition
498 * @param string|array $table Table name or array [schema => table]
499 * @param array $condition array of fields for condition
500 * @param array $params Array of several parameters
507 * $condition = ["uid" => 1, "network" => 'dspr'];
509 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
511 * $count = DBA::count($table, $condition);
514 public static function count($table, array $condition = [], array $params = [])
516 return DI::dba()->count($table, $condition, $params);
520 * Build the table query substring from one or more tables, with or without a schema.
524 * - [table1, table2, ...]
525 * - [schema1 => table1, schema2 => table2, table3, ...]
527 * @param string|array $tables
530 public static function buildTableString($tables)
532 if (is_string($tables)) {
538 foreach ($tables as $schema => $table) {
539 if (is_numeric($schema)) {
540 $quotedTables[] = self::quoteIdentifier($table);
542 $quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
546 return implode(', ', $quotedTables);
550 * Escape an identifier (table or field name)
555 public static function quoteIdentifier($identifier)
557 return '`' . str_replace('`', '``', $identifier) . '`';
561 * Returns the SQL condition string built from the provided condition array
563 * This function operates with two modes.
564 * - Supplied with a field/value associative array, it builds simple strict
565 * equality conditions linked by AND.
566 * - Supplied with a flat list, the first element is the condition string and
567 * the following arguments are the values to be interpolated
569 * $condition = ["uid" => 1, "network" => 'dspr'];
571 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
573 * In either case, the provided array is left with the parameters only
575 * @param array $condition
578 public static function buildCondition(array &$condition = [])
580 $condition = self::collapseCondition($condition);
582 $condition_string = '';
583 if (count($condition) > 0) {
584 $condition_string = " WHERE (" . array_shift($condition) . ")";
587 return $condition_string;
591 * Collapse an associative array condition into a SQL string + parameters condition array.
593 * ['uid' => 1, 'network' => ['dspr', 'apub']]
595 * gets transformed into
597 * ["`uid` = ? AND `network` IN (?, ?)", 1, 'dspr', 'apub']
599 * @param array $condition
602 public static function collapseCondition(array $condition)
604 // Ensures an always true condition is returned
605 if (count($condition) < 1) {
610 $first_key = key($condition);
612 if (is_int($first_key)) {
618 $condition_string = "";
619 foreach ($condition as $field => $value) {
620 if ($condition_string != "") {
621 $condition_string .= " AND ";
624 if (is_array($value)) {
626 /* Workaround for MySQL Bug #64791.
627 * Never mix data types inside any IN() condition.
628 * In case of mixed types, cast all as string.
629 * Logic needs to be consistent with DBA::p() data types.
633 foreach ($value as $single_value) {
634 if (is_int($single_value)) {
641 if ($is_int && $is_alpha) {
642 foreach ($value as &$ref) {
647 unset($ref); //Prevent accidental re-use.
650 $values = array_merge($values, array_values($value));
651 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
652 $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
654 // Empty value array isn't supported by IN and is logically equivalent to no match
655 $condition_string .= "FALSE";
657 } elseif (is_null($value)) {
658 $condition_string .= self::quoteIdentifier($field) . " IS NULL";
660 $values[$field] = $value;
661 $condition_string .= self::quoteIdentifier($field) . " = ?";
665 $condition = array_merge([$condition_string], array_values($values));
671 * Merges the provided conditions into a single collapsed one
673 * @param array ...$conditions One or more condition arrays
674 * @return array A collapsed condition
675 * @see DBA::collapseCondition() for the condition array formats
677 public static function mergeConditions(array ...$conditions)
679 if (count($conditions) == 1) {
680 return current($conditions);
683 $conditionStrings = [];
686 foreach ($conditions as $key => $condition) {
691 $condition = self::collapseCondition($condition);
693 $conditionStrings[] = array_shift($condition);
694 // The result array holds the eventual parameter values
695 $result = array_merge($result, $condition);
698 if (count($conditionStrings)) {
699 // We prepend the condition string at the end to form a collapsed condition array again
700 array_unshift($result, implode(' AND ', $conditionStrings));
707 * Returns the SQL parameter string built from the provided parameter array
709 * Expected format for each key:
712 * - list of column names
715 * - numeric keyed column name => ASC
716 * - associative element with boolean value => DESC (true), ASC (false)
717 * - associative element with string value => 'ASC' or 'DESC' literally
720 * - single numeric value => count
721 * - list with two numeric values => offset, count
723 * @param array $params
726 public static function buildParameter(array $params = [])
728 $groupby_string = '';
729 if (!empty($params['group_by'])) {
730 $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
734 if (isset($params['order'])) {
735 $order_string = " ORDER BY ";
736 foreach ($params['order'] AS $fields => $order) {
737 if ($order === 'RAND()') {
738 $order_string .= "RAND(), ";
739 } elseif (!is_int($fields)) {
740 if ($order !== 'DESC' && $order !== 'ASC') {
741 $order = $order ? 'DESC' : 'ASC';
744 $order_string .= self::quoteIdentifier($fields) . " " . $order . ", ";
746 $order_string .= self::quoteIdentifier($order) . ", ";
749 $order_string = substr($order_string, 0, -2);
753 if (isset($params['limit']) && is_numeric($params['limit'])) {
754 $limit_string = " LIMIT " . intval($params['limit']);
757 if (isset($params['limit']) && is_array($params['limit'])) {
758 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
761 return $groupby_string . $order_string . $limit_string;
765 * Fills an array with data from a query
767 * @param object $stmt statement object
768 * @param bool $do_close Close database connection after last row
769 * @param int $count maximum number of rows to be fetched
771 * @return array Data array
773 public static function toArray($stmt, $do_close = true, int $count = 0)
775 return DI::dba()->toArray($stmt, $do_close, $count);
779 * Cast field types according to the table definition
781 * @param string $table
782 * @param array $fields
783 * @return array casted fields
785 public static function castFields(string $table, array $fields)
787 return DI::dba()->castFields($table, $fields);
791 * Returns the error number of the last query
793 * @return string Error number (0 if no error)
795 public static function errorNo()
797 return DI::dba()->errorNo();
801 * Returns the error message of the last query
803 * @return string Error message ('' if no error)
805 public static function errorMessage()
807 return DI::dba()->errorMessage();
811 * Closes the current statement
813 * @param object $stmt statement object
814 * @return boolean was the close successful?
816 public static function close($stmt)
818 return DI::dba()->close($stmt);
822 * Return a list of database processes
825 * 'list' => List of processes, separated in their different states
826 * 'amount' => Number of concurrent database processes
829 public static function processlist()
831 return DI::dba()->processlist();
835 * Fetch a database variable
837 * @param string $name
838 * @return string content
840 public static function getVariable(string $name)
842 return DI::dba()->getVariable($name);
846 * Checks if $array is a filled array with at least one entry.
848 * @param mixed $array A filled array with at least one entry
850 * @return boolean Whether $array is a filled array or an object with rows
852 public static function isResult($array)
854 return DI::dba()->isResult($array);
858 * Escapes a whole array
860 * @param mixed $arr Array with values to be escaped
861 * @param boolean $add_quotation add quotation marks for string values
864 public static function escapeArray(&$arr, $add_quotation = false)
866 DI::dba()->escapeArray($arr, $add_quotation);