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 * Returns the MySQL server version string
78 * This function discriminate between the deprecated mysql API and the current
79 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
83 public static function serverInfo()
85 return DI::dba()->serverInfo();
89 * Returns the selected database name
94 public static function databaseName()
96 return DI::dba()->databaseName();
100 * Escape all SQL unsafe data
103 * @return string escaped string
105 public static function escape($str)
107 return DI::dba()->escape($str);
111 * Checks if the database is connected
113 * @return boolean is the database connected?
115 public static function connected()
117 return DI::dba()->connected();
121 * Replaces ANY_VALUE() function by MIN() function,
122 * if the database server does not support ANY_VALUE().
124 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
125 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
126 * A standard fall-back is to use MIN().
128 * @param string $sql An SQL string without the values
129 * @return string The input SQL string modified if necessary.
131 public static function anyValueFallback($sql)
133 return DI::dba()->anyValueFallback($sql);
137 * beautifies the query - useful for "SHOW PROCESSLIST"
139 * This is safe when we bind the parameters later.
140 * The parameter values aren't part of the SQL.
142 * @param string $sql An SQL string without the values
143 * @return string The input SQL string modified if necessary.
145 public static function cleanQuery($sql)
147 $search = ["\t", "\n", "\r", " "];
148 $replace = [' ', ' ', ' ', ' '];
151 $sql = str_replace($search, $replace, $sql);
152 } while ($oldsql != $sql);
158 * Convert parameter array to an universal form
159 * @param array $args Parameter array
160 * @return array universalized parameter array
162 public static function getParam($args)
166 // When the second function parameter is an array then use this as the parameter array
167 if ((count($args) > 0) && (is_array($args[1]))) {
175 * Executes a prepared statement that returns data
176 * Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
178 * Please only use it with complicated queries.
179 * For all regular queries please use DBA::select or DBA::exists
181 * @param string $sql SQL statement
182 * @return bool|object statement object or result object
185 public static function p($sql)
187 $params = self::getParam(func_get_args());
189 return DI::dba()->p($sql, $params);
193 * Executes a prepared statement like UPDATE or INSERT that doesn't return data
195 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
197 * @param string $sql SQL statement
198 * @return boolean Was the query successfull? False is returned only if an error occurred
201 public static function e($sql) {
203 $params = self::getParam(func_get_args());
205 return DI::dba()->e($sql, $params);
209 * Check if data exists
211 * @param string|array $table Table name or array [schema => table]
212 * @param array $condition array of fields for condition
214 * @return boolean Are there rows for that condition?
217 public static function exists($table, $condition)
219 return DI::dba()->exists($table, $condition);
223 * Fetches the first row
225 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
227 * @param string $sql SQL statement
228 * @return array first row of query
231 public static function fetchFirst($sql)
233 $params = self::getParam(func_get_args());
235 return DI::dba()->fetchFirst($sql, $params);
239 * Returns the number of affected rows of the last statement
241 * @return int Number of rows
243 public static function affectedRows()
245 return DI::dba()->affectedRows();
249 * Returns the number of columns of a statement
251 * @param object Statement object
252 * @return int Number of columns
254 public static function columnCount($stmt)
256 return DI::dba()->columnCount($stmt);
259 * Returns the number of rows of a statement
261 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
262 * @return int Number of rows
264 public static function numRows($stmt)
266 return DI::dba()->numRows($stmt);
272 * @param mixed $stmt statement object
273 * @return array current row
275 public static function fetch($stmt)
277 return DI::dba()->fetch($stmt);
281 * Insert a row into a table
283 * @param string|array $table Table name or array [schema => table]
284 * @param array $param parameter array
285 * @param bool $on_duplicate_update Do an update on a duplicate entry
287 * @return boolean was the insert successful?
290 public static function insert($table, $param, $on_duplicate_update = false)
292 return DI::dba()->insert($table, $param, $on_duplicate_update);
296 * Inserts a row with the provided data in the provided table.
297 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
299 * @param string|array $table Table name or array [schema => table]
300 * @param array $param parameter array
302 * @return boolean was the insert successful?
305 public static function replace($table, $param)
307 return DI::dba()->replace($table, $param);
311 * Fetch the id of the last insert command
313 * @return integer Last inserted id
315 public static function lastInsertId()
317 return DI::dba()->lastInsertId();
321 * Locks a table for exclusive write access
323 * This function can be extended in the future to accept a table array as well.
325 * @param string|array $table Table name or array [schema => table]
327 * @return boolean was the lock successful?
330 public static function lock($table)
332 return DI::dba()->lock($table);
336 * Unlocks all locked tables
338 * @return boolean was the unlock successful?
341 public static function unlock()
343 return DI::dba()->unlock();
347 * Starts a transaction
349 * @return boolean Was the command executed successfully?
351 public static function transaction()
353 return DI::dba()->transaction();
359 * @return boolean Was the command executed successfully?
361 public static function commit()
363 return DI::dba()->commit();
369 * @return boolean Was the command executed successfully?
371 public static function rollback()
373 return DI::dba()->rollback();
377 * Delete a row from a table
379 * @param string|array $table Table name
380 * @param array $conditions Field condition(s)
381 * @param array $options
382 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
383 * relations (default: true)
385 * @return boolean was the delete successful?
388 public static function delete($table, array $conditions, array $options = [])
390 return DI::dba()->delete($table, $conditions, $options);
394 * Updates rows in the database.
396 * When $old_fields is set to an array,
397 * the system will only do an update if the fields in that array changed.
400 * Only the values in $old_fields are compared.
401 * This is an intentional behaviour.
404 * We include the timestamp field in $fields but not in $old_fields.
405 * Then the row will only get the new timestamp when the other fields had changed.
407 * When $old_fields is set to a boolean value the system will do this compare itself.
408 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
411 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
412 * When you set $old_fields to "true" then $fields must contain all relevant fields!
414 * @param string|array $table Table name or array [schema => table]
415 * @param array $fields contains the fields that are updated
416 * @param array $condition condition array with the key values
417 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
419 * @return boolean was the update successfull?
422 public static function update($table, $fields, $condition, $old_fields = [])
424 return DI::dba()->update($table, $fields, $condition, $old_fields);
428 * Retrieve a single record from a table and returns it in an associative array
430 * @param string|array $table Table name or array [schema => table]
431 * @param array $fields
432 * @param array $condition
433 * @param array $params
438 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
440 return DI::dba()->selectFirst($table, $fields, $condition, $params);
444 * Select rows from a table and fills an array with the data
446 * @param string|array $table Table name or array [schema => table]
447 * @param array $fields Array of selected fields, empty for all
448 * @param array $condition Array of fields for condition
449 * @param array $params Array of several parameters
451 * @return array Data array
455 public static function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
457 return DI::dba()->selectToArray($table, $fields, $condition, $params);
461 * Select rows from a table
463 * @param string|array $table Table name or array [schema => table]
464 * @param array $fields Array of selected fields, empty for all
465 * @param array $condition Array of fields for condition
466 * @param array $params Array of several parameters
468 * @return boolean|object
472 * $fields = array("id", "uri", "uid", "network");
474 * $condition = array("uid" => 1, "network" => 'dspr');
476 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
478 * $params = array("order" => array("id", "received" => true), "limit" => 10);
480 * $data = DBA::select($table, $fields, $condition, $params);
483 public static function select($table, array $fields = [], array $condition = [], array $params = [])
485 return DI::dba()->select($table, $fields, $condition, $params);
489 * Counts the rows from a table satisfying the provided condition
491 * @param string|array $table Table name or array [schema => table]
492 * @param array $condition array of fields for condition
493 * @param array $params Array of several parameters
500 * $condition = ["uid" => 1, "network" => 'dspr'];
502 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
504 * $count = DBA::count($table, $condition);
507 public static function count($table, array $condition = [], array $params = [])
509 return DI::dba()->count($table, $condition, $params);
513 * Build the table query substring from one or more tables, with or without a schema.
517 * - [table1, table2, ...]
518 * - [schema1 => table1, schema2 => table2, table3, ...]
520 * @param string|array $tables
523 public static function buildTableString($tables)
525 if (is_string($tables)) {
531 foreach ($tables as $schema => $table) {
532 if (is_numeric($schema)) {
533 $quotedTables[] = self::quoteIdentifier($table);
535 $quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
539 return implode(', ', $quotedTables);
543 * Escape an identifier (table or field name)
548 public static function quoteIdentifier($identifier)
550 return '`' . str_replace('`', '``', $identifier) . '`';
554 * Returns the SQL condition string built from the provided condition array
556 * This function operates with two modes.
557 * - Supplied with a field/value associative array, it builds simple strict
558 * equality conditions linked by AND.
559 * - Supplied with a flat list, the first element is the condition string and
560 * the following arguments are the values to be interpolated
562 * $condition = ["uid" => 1, "network" => 'dspr'];
564 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
566 * In either case, the provided array is left with the parameters only
568 * @param array $condition
571 public static function buildCondition(array &$condition = [])
573 $condition = self::collapseCondition($condition);
575 $condition_string = '';
576 if (count($condition) > 0) {
577 $condition_string = " WHERE (" . array_shift($condition) . ")";
580 return $condition_string;
584 * Collapse an associative array condition into a SQL string + parameters condition array.
586 * ['uid' => 1, 'network' => ['dspr', 'apub']]
588 * gets transformed into
590 * ["`uid` = ? AND `network` IN (?, ?)", 1, 'dspr', 'apub']
592 * @param array $condition
595 public static function collapseCondition(array $condition)
597 // Ensures an always true condition is returned
598 if (count($condition) < 1) {
603 $first_key = key($condition);
605 if (is_int($first_key)) {
611 $condition_string = "";
612 foreach ($condition as $field => $value) {
613 if ($condition_string != "") {
614 $condition_string .= " AND ";
617 if (is_array($value)) {
619 /* Workaround for MySQL Bug #64791.
620 * Never mix data types inside any IN() condition.
621 * In case of mixed types, cast all as string.
622 * Logic needs to be consistent with DBA::p() data types.
626 foreach ($value as $single_value) {
627 if (is_int($single_value)) {
634 if ($is_int && $is_alpha) {
635 foreach ($value as &$ref) {
640 unset($ref); //Prevent accidental re-use.
643 $values = array_merge($values, array_values($value));
644 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
645 $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
647 // Empty value array isn't supported by IN and is logically equivalent to no match
648 $condition_string .= "FALSE";
650 } elseif (is_null($value)) {
651 $condition_string .= self::quoteIdentifier($field) . " IS NULL";
653 $values[$field] = $value;
654 $condition_string .= self::quoteIdentifier($field) . " = ?";
658 $condition = array_merge([$condition_string], array_values($values));
664 * Merges the provided conditions into a single collapsed one
666 * @param array ...$conditions One or more condition arrays
667 * @return array A collapsed condition
668 * @see DBA::collapseCondition() for the condition array formats
670 public static function mergeConditions(array ...$conditions)
672 if (count($conditions) == 1) {
673 return current($conditions);
676 $conditionStrings = [];
679 foreach ($conditions as $key => $condition) {
684 $condition = self::collapseCondition($condition);
686 $conditionStrings[] = array_shift($condition);
687 // The result array holds the eventual parameter values
688 $result = array_merge($result, $condition);
691 if (count($conditionStrings)) {
692 // We prepend the condition string at the end to form a collapsed condition array again
693 array_unshift($result, implode(' AND ', $conditionStrings));
700 * Returns the SQL parameter string built from the provided parameter array
702 * Expected format for each key:
705 * - list of column names
708 * - numeric keyed column name => ASC
709 * - associative element with boolean value => DESC (true), ASC (false)
710 * - associative element with string value => 'ASC' or 'DESC' literally
713 * - single numeric value => count
714 * - list with two numeric values => offset, count
716 * @param array $params
719 public static function buildParameter(array $params = [])
721 $groupby_string = '';
722 if (!empty($params['group_by'])) {
723 $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
727 if (isset($params['order'])) {
728 $order_string = " ORDER BY ";
729 foreach ($params['order'] AS $fields => $order) {
730 if ($order === 'RAND()') {
731 $order_string .= "RAND(), ";
732 } elseif (!is_int($fields)) {
733 if ($order !== 'DESC' && $order !== 'ASC') {
734 $order = $order ? 'DESC' : 'ASC';
737 $order_string .= self::quoteIdentifier($fields) . " " . $order . ", ";
739 $order_string .= self::quoteIdentifier($order) . ", ";
742 $order_string = substr($order_string, 0, -2);
746 if (isset($params['limit']) && is_numeric($params['limit'])) {
747 $limit_string = " LIMIT " . intval($params['limit']);
750 if (isset($params['limit']) && is_array($params['limit'])) {
751 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
754 return $groupby_string . $order_string . $limit_string;
758 * Fills an array with data from a query
760 * @param object $stmt statement object
761 * @param bool $do_close
762 * @return array Data array
764 public static function toArray($stmt, $do_close = true)
766 return DI::dba()->toArray($stmt, $do_close);
770 * Returns the error number of the last query
772 * @return string Error number (0 if no error)
774 public static function errorNo()
776 return DI::dba()->errorNo();
780 * Returns the error message of the last query
782 * @return string Error message ('' if no error)
784 public static function errorMessage()
786 return DI::dba()->errorMessage();
790 * Closes the current statement
792 * @param object $stmt statement object
793 * @return boolean was the close successful?
795 public static function close($stmt)
797 return DI::dba()->close($stmt);
801 * Return a list of database processes
804 * 'list' => List of processes, separated in their different states
805 * 'amount' => Number of concurrent database processes
808 public static function processlist()
810 return DI::dba()->processlist();
814 * Fetch a database variable
816 * @param string $name
817 * @return string content
819 public static function getVariable(string $name)
821 return DI::dba()->getVariable($name);
825 * Checks if $array is a filled array with at least one entry.
827 * @param mixed $array A filled array with at least one entry
829 * @return boolean Whether $array is a filled array or an object with rows
831 public static function isResult($array)
833 return DI::dba()->isResult($array);
837 * Escapes a whole array
839 * @param mixed $arr Array with values to be escaped
840 * @param boolean $add_quotation add quotation marks for string values
843 public static function escapeArray(&$arr, $add_quotation = false)
845 DI::dba()->escapeArray($arr, $add_quotation);