3 * @copyright Copyright (C) 2010-2022, the Friendica project
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(): bool
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(): bool
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(): string
95 return DI::dba()->serverInfo();
99 * Returns the selected database name
104 public static function databaseName(): string
106 return DI::dba()->databaseName();
110 * Escape all SQL unsafe data
113 * @return string escaped string
115 public static function escape(string $str): string
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(): bool
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(string $sql): string
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(string $sql): string
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(array $args): array
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(string $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(string $sql): bool
213 $params = self::getParam(func_get_args());
215 return DI::dba()->e($sql, $params);
219 * Check if data exists
221 * @param string $table Table name or array [schema => table]
222 * @param array $condition Array of fields for condition
223 * @return boolean Are there rows for that condition?
226 public static function exists(string $table, array $condition): bool
228 return DI::dba()->exists($table, $condition);
232 * Fetches the first row
234 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
236 * @param string $sql SQL statement
237 * @return array first row of query
240 public static function fetchFirst(string $sql)
242 $params = self::getParam(func_get_args());
244 return DI::dba()->fetchFirst($sql, $params);
248 * Returns the number of affected rows of the last statement
250 * @return int Number of rows
252 public static function affectedRows(): int
254 return DI::dba()->affectedRows();
258 * Returns the number of columns of a statement
260 * @param object Statement object
261 * @return int Number of columns
263 public static function columnCount($stmt): int
265 return DI::dba()->columnCount($stmt);
268 * Returns the number of rows of a statement
270 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
271 * @return int Number of rows
273 public static function numRows($stmt): int
275 return DI::dba()->numRows($stmt);
281 * @param mixed $stmt statement object
282 * @return array current row
284 public static function fetch($stmt)
286 return DI::dba()->fetch($stmt);
290 * Insert a row into a table
292 * @param string $table Table name or array [schema => table]
293 * @param array $param parameter array
294 * @param int $duplicate_mode What to do on a duplicated entry
295 * @return boolean was the insert successful?
298 public static function insert(string $table, array $param, int $duplicate_mode = Database::INSERT_DEFAULT): bool
300 return DI::dba()->insert($table, $param, $duplicate_mode);
304 * Inserts a row with the provided data in the provided table.
305 * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
307 * @param string $table Table name or array [schema => table]
308 * @param array $param parameter array
309 * @return boolean was the insert successful?
312 public static function replace(string $table, array $param): bool
314 return DI::dba()->replace($table, $param);
318 * Fetch the id of the last insert command
320 * @return integer Last inserted id
322 public static function lastInsertId(): int
324 return DI::dba()->lastInsertId();
328 * Locks a table for exclusive write access
330 * This function can be extended in the future to accept a table array as well.
332 * @param string $table Table name or array [schema => table]
333 * @return boolean was the lock successful?
336 public static function lock(string $table): bool
338 return DI::dba()->lock($table);
342 * Unlocks all locked tables
344 * @return boolean was the unlock successful?
347 public static function unlock(): bool
349 return DI::dba()->unlock();
353 * Starts a transaction
355 * @return boolean Was the command executed successfully?
357 public static function transaction(): bool
359 return DI::dba()->transaction();
365 * @return boolean Was the command executed successfully?
367 public static function commit(): bool
369 return DI::dba()->commit();
375 * @return boolean Was the command executed successfully?
377 public static function rollback(): bool
379 return DI::dba()->rollback();
383 * Delete a row from a table
385 * @param string $table Table name
386 * @param array $conditions Field condition(s)
388 * @return boolean was the delete successful?
391 public static function delete(string $table, array $conditions, array $options = []): bool
393 return DI::dba()->delete($table, $conditions, $options);
397 * Updates rows in the database.
399 * When $old_fields is set to an array,
400 * the system will only do an update if the fields in that array changed.
403 * Only the values in $old_fields are compared.
404 * This is an intentional behaviour.
407 * We include the timestamp field in $fields but not in $old_fields.
408 * Then the row will only get the new timestamp when the other fields had changed.
410 * When $old_fields is set to a boolean value the system will do this compare itself.
411 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
414 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
415 * When you set $old_fields to "true" then $fields must contain all relevant fields!
417 * @param string $table Table name or array [schema => table]
418 * @param array $fields contains the fields that are updated
419 * @param array $condition condition array with the key values
420 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
421 * @param array $params Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
423 * @return boolean was the update successfull?
426 public static function update(string $table, array $fields, array $condition, $old_fields = [], array $params = []): bool
428 return DI::dba()->update($table, $fields, $condition, $old_fields, $params);
432 * Retrieve a single record from a table and returns it in an associative array
434 * @param string|array $table Table name or array [schema => table]
435 * @param array $fields
436 * @param array $condition
437 * @param array $params
442 public static function selectFirst($table, array $fields = [], array $condition = [], array $params = [])
444 return DI::dba()->selectFirst($table, $fields, $condition, $params);
448 * Select rows from a table and fills an array with the data
450 * @param string $table Table name or array [schema => table]
451 * @param array $fields Array of selected fields, empty for all
452 * @param array $condition Array of fields for condition
453 * @param array $params Array of several parameters
455 * @return array Data array
459 public static function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
461 return DI::dba()->selectToArray($table, $fields, $condition, $params);
465 * Select rows from a table
467 * @param string $table Table name or array [schema => table]
468 * @param array $fields Array of selected fields, empty for all
469 * @param array $condition Array of fields for condition
470 * @param array $params Array of several parameters
472 * @return boolean|object
476 * $fields = array("id", "uri", "uid", "network");
478 * $condition = array("uid" => 1, "network" => 'dspr');
480 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
482 * $params = array("order" => array("id", "received" => true), "limit" => 10);
484 * $data = DBA::select($table, $fields, $condition, $params);
487 public static function select(string $table, array $fields = [], array $condition = [], array $params = [])
489 return DI::dba()->select($table, $fields, $condition, $params);
493 * Counts the rows from a table satisfying the provided condition
495 * @param string $table Table name or array [schema => table]
496 * @param array $condition array of fields for condition
497 * @param array $params Array of several parameters
504 * $condition = ["uid" => 1, "network" => 'dspr'];
506 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
508 * $count = DBA::count($table, $condition);
511 public static function count(string $table, array $condition = [], array $params = []): int
513 return DI::dba()->count($table, $condition, $params);
517 * Build the table query substring from one or more tables, with or without a schema.
521 * - [table1, table2, ...]
522 * - [schema1 => table1, schema2 => table2, table3, ...]
524 * @param array $tables Table names
527 public static function buildTableString(array $tables): string
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(string $identifier): string
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 = []): string
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): array
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): array
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 = []): string
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 Close database connection after last row
762 * @param int $count maximum number of rows to be fetched
764 * @return array Data array
766 public static function toArray($stmt, bool $do_close = true, int $count = 0): array
768 return DI::dba()->toArray($stmt, $do_close, $count);
772 * Cast field types according to the table definition
774 * @param string $table
775 * @param array $fields
776 * @return array casted fields
778 public static function castFields(string $table, array $fields): array
780 return DI::dba()->castFields($table, $fields);
784 * Returns the error number of the last query
786 * @return string Error number (0 if no error)
788 public static function errorNo(): int
790 return DI::dba()->errorNo();
794 * Returns the error message of the last query
796 * @return string Error message ('' if no error)
798 public static function errorMessage(): string
800 return DI::dba()->errorMessage();
804 * Closes the current statement
806 * @param object $stmt statement object
807 * @return boolean was the close successful?
809 public static function close($stmt): bool
811 return DI::dba()->close($stmt);
815 * Return a list of database processes
818 * 'list' => List of processes, separated in their different states
819 * 'amount' => Number of concurrent database processes
822 public static function processlist(): array
824 return DI::dba()->processlist();
828 * Fetch a database variable
830 * @param string $name
831 * @return string content
833 public static function getVariable(string $name)
835 return DI::dba()->getVariable($name);
839 * Checks if $array is a filled array with at least one entry.
841 * @param mixed $array A filled array with at least one entry
842 * @return boolean Whether $array is a filled array or an object with rows
844 public static function isResult($array): bool
846 return DI::dba()->isResult($array);
850 * Escapes a whole array
852 * @param mixed $arr Array with values to be escaped
853 * @param boolean $add_quotation add quotation marks for string values
856 public static function escapeArray(&$arr, bool $add_quotation = false)
858 DI::dba()->escapeArray($arr, $add_quotation);