]> git.mxchange.org Git - friendica.git/blob - src/Database/DBA.php
Added support for the "replace" database command
[friendica.git] / src / Database / DBA.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Database;
23
24 use Friendica\DI;
25 use mysqli;
26 use mysqli_result;
27 use mysqli_stmt;
28 use PDO;
29 use PDOStatement;
30
31 /**
32  * This class is for the low level database stuff that does driver specific things.
33  */
34 class DBA
35 {
36         /**
37          * Lowest possible date value
38          */
39         const NULL_DATE     = '0001-01-01';
40         /**
41          * Lowest possible datetime value
42          */
43         const NULL_DATETIME = '0001-01-01 00:00:00';
44
45         public static function connect()
46         {
47                 return DI::dba()->connect();
48         }
49
50         /**
51          * Disconnects the current database connection
52          */
53         public static function disconnect()
54         {
55                 DI::dba()->disconnect();
56         }
57
58         /**
59          * Perform a reconnect of an existing database connection
60          */
61         public static function reconnect()
62         {
63                 return DI::dba()->reconnect();
64         }
65
66         /**
67          * Return the database object.
68          * @return PDO|mysqli
69          */
70         public static function getConnection()
71         {
72                 return DI::dba()->getConnection();
73         }
74
75         /**
76          * Returns the MySQL server version string
77          *
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
80          *
81          * @return string
82          */
83         public static function serverInfo()
84         {
85                 return DI::dba()->serverInfo();
86         }
87
88         /**
89          * Returns the selected database name
90          *
91          * @return string
92          * @throws \Exception
93          */
94         public static function databaseName()
95         {
96                 return DI::dba()->databaseName();
97         }
98
99         /**
100          * Escape all SQL unsafe data
101          *
102          * @param string $str
103          * @return string escaped string
104          */
105         public static function escape($str)
106         {
107                 return DI::dba()->escape($str);
108         }
109
110         /**
111          * Checks if the database is connected
112          *
113          * @return boolean is the database connected?
114          */
115         public static function connected()
116         {
117                 return DI::dba()->connected();
118         }
119
120         /**
121          * Replaces ANY_VALUE() function by MIN() function,
122          * if the database server does not support ANY_VALUE().
123          *
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().
127          *
128          * @param string $sql An SQL string without the values
129          * @return string The input SQL string modified if necessary.
130          */
131         public static function anyValueFallback($sql)
132         {
133                 return DI::dba()->anyValueFallback($sql);
134         }
135
136         /**
137          * beautifies the query - useful for "SHOW PROCESSLIST"
138          *
139          * This is safe when we bind the parameters later.
140          * The parameter values aren't part of the SQL.
141          *
142          * @param string $sql An SQL string without the values
143          * @return string The input SQL string modified if necessary.
144          */
145         public static function cleanQuery($sql)
146         {
147                 $search = ["\t", "\n", "\r", "  "];
148                 $replace = [' ', ' ', ' ', ' '];
149                 do {
150                         $oldsql = $sql;
151                         $sql = str_replace($search, $replace, $sql);
152                 } while ($oldsql != $sql);
153
154                 return $sql;
155         }
156
157         /**
158          * Convert parameter array to an universal form
159          * @param array $args Parameter array
160          * @return array universalized parameter array
161          */
162         public static function getParam($args)
163         {
164                 unset($args[0]);
165
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]))) {
168                         return $args[1];
169                 } else {
170                         return $args;
171                 }
172         }
173
174         /**
175          * Executes a prepared statement that returns data
176          * Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
177          *
178          * Please only use it with complicated queries.
179          * For all regular queries please use DBA::select or DBA::exists
180          *
181          * @param string $sql SQL statement
182          * @return bool|object statement object or result object
183          * @throws \Exception
184          */
185         public static function p($sql)
186         {
187                 $params = self::getParam(func_get_args());
188
189                 return DI::dba()->p($sql, $params);
190         }
191
192         /**
193          * Executes a prepared statement like UPDATE or INSERT that doesn't return data
194          *
195          * Please use DBA::delete, DBA::insert, DBA::update, ... instead
196          *
197          * @param string $sql SQL statement
198          * @return boolean Was the query successfull? False is returned only if an error occurred
199          * @throws \Exception
200          */
201         public static function e($sql) {
202
203                 $params = self::getParam(func_get_args());
204
205                 return DI::dba()->e($sql, $params);
206         }
207
208         /**
209          * Check if data exists
210          *
211          * @param string|array $table     Table name or array [schema => table]
212          * @param array        $condition array of fields for condition
213          *
214          * @return boolean Are there rows for that condition?
215          * @throws \Exception
216          */
217         public static function exists($table, $condition)
218         {
219                 return DI::dba()->exists($table, $condition);
220         }
221
222         /**
223          * Fetches the first row
224          *
225          * Please use DBA::selectFirst or DBA::exists whenever this is possible.
226          *
227          * @param string $sql SQL statement
228          * @return array first row of query
229          * @throws \Exception
230          */
231         public static function fetchFirst($sql)
232         {
233                 $params = self::getParam(func_get_args());
234
235                 return DI::dba()->fetchFirst($sql, $params);
236         }
237
238         /**
239          * Returns the number of affected rows of the last statement
240          *
241          * @return int Number of rows
242          */
243         public static function affectedRows()
244         {
245                 return DI::dba()->affectedRows();
246         }
247
248         /**
249          * Returns the number of columns of a statement
250          *
251          * @param object Statement object
252          * @return int Number of columns
253          */
254         public static function columnCount($stmt)
255         {
256                 return DI::dba()->columnCount($stmt);
257         }
258         /**
259          * Returns the number of rows of a statement
260          *
261          * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
262          * @return int Number of rows
263          */
264         public static function numRows($stmt)
265         {
266                 return DI::dba()->numRows($stmt);
267         }
268
269         /**
270          * Fetch a single row
271          *
272          * @param mixed $stmt statement object
273          * @return array current row
274          */
275         public static function fetch($stmt)
276         {
277                 return DI::dba()->fetch($stmt);
278         }
279
280         /**
281          * Insert a row into a table
282          *
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
286          *
287          * @return boolean was the insert successful?
288          * @throws \Exception
289          */
290         public static function insert($table, $param, $on_duplicate_update = false)
291         {
292                 return DI::dba()->insert($table, $param, $on_duplicate_update);
293         }
294
295         /**
296          * Replace a row of a table
297          *
298          * @param string|array $table Table name or array [schema => table]
299          * @param array        $param parameter array
300          *
301          * @return boolean was the insert successful?
302          * @throws \Exception
303          */
304         public static function replace($table, $param)
305         {
306                 return DI::dba()->replace($table, $param);
307         }
308
309         /**
310          * Fetch the id of the last insert command
311          *
312          * @return integer Last inserted id
313          */
314         public static function lastInsertId()
315         {
316                 return DI::dba()->lastInsertId();
317         }
318
319         /**
320          * Locks a table for exclusive write access
321          *
322          * This function can be extended in the future to accept a table array as well.
323          *
324          * @param string|array $table Table name or array [schema => table]
325          *
326          * @return boolean was the lock successful?
327          * @throws \Exception
328          */
329         public static function lock($table)
330         {
331                 return DI::dba()->lock($table);
332         }
333
334         /**
335          * Unlocks all locked tables
336          *
337          * @return boolean was the unlock successful?
338          * @throws \Exception
339          */
340         public static function unlock()
341         {
342                 return DI::dba()->unlock();
343         }
344
345         /**
346          * Starts a transaction
347          *
348          * @return boolean Was the command executed successfully?
349          */
350         public static function transaction()
351         {
352                 return DI::dba()->transaction();
353         }
354
355         /**
356          * Does a commit
357          *
358          * @return boolean Was the command executed successfully?
359          */
360         public static function commit()
361         {
362                 return DI::dba()->commit();
363         }
364
365         /**
366          * Does a rollback
367          *
368          * @return boolean Was the command executed successfully?
369          */
370         public static function rollback()
371         {
372                 return DI::dba()->rollback();
373         }
374
375         /**
376          * Delete a row from a table
377          *
378          * @param string|array $table      Table name
379          * @param array        $conditions Field condition(s)
380          * @param array        $options
381          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
382          *                           relations (default: true)
383          *
384          * @return boolean was the delete successful?
385          * @throws \Exception
386          */
387         public static function delete($table, array $conditions, array $options = [])
388         {
389                 return DI::dba()->delete($table, $conditions, $options);
390         }
391
392         /**
393          * Updates rows in the database.
394          *
395          * When $old_fields is set to an array,
396          * the system will only do an update if the fields in that array changed.
397          *
398          * Attention:
399          * Only the values in $old_fields are compared.
400          * This is an intentional behaviour.
401          *
402          * Example:
403          * We include the timestamp field in $fields but not in $old_fields.
404          * Then the row will only get the new timestamp when the other fields had changed.
405          *
406          * When $old_fields is set to a boolean value the system will do this compare itself.
407          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
408          *
409          * Attention:
410          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
411          * When you set $old_fields to "true" then $fields must contain all relevant fields!
412          *
413          * @param string|array  $table      Table name or array [schema => table]
414          * @param array         $fields     contains the fields that are updated
415          * @param array         $condition  condition array with the key values
416          * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
417          *
418          * @return boolean was the update successfull?
419          * @throws \Exception
420          */
421         public static function update($table, $fields, $condition, $old_fields = [])
422         {
423                 return DI::dba()->update($table, $fields, $condition, $old_fields);
424         }
425
426         /**
427          * Retrieve a single record from a table and returns it in an associative array
428          *
429          * @param string|array $table     Table name or array [schema => table]
430          * @param array        $fields
431          * @param array        $condition
432          * @param array        $params
433          * @return bool|array
434          * @throws \Exception
435          * @see   self::select
436          */
437         public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
438         {
439                 return DI::dba()->selectFirst($table, $fields, $condition, $params);
440         }
441
442         /**
443          * Select rows from a table and fills an array with the data
444          *
445          * @param string|array $table     Table name or array [schema => table]
446          * @param array        $fields    Array of selected fields, empty for all
447          * @param array        $condition Array of fields for condition
448          * @param array        $params    Array of several parameters
449          *
450          * @return array Data array
451          * @throws \Exception
452          * @see   self::select
453          */
454         public static function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
455         {
456                 return DI::dba()->selectToArray($table, $fields, $condition, $params);
457         }
458
459         /**
460          * Select rows from a table
461          *
462          * @param string|array $table     Table name or array [schema => table]
463          * @param array        $fields    Array of selected fields, empty for all
464          * @param array        $condition Array of fields for condition
465          * @param array        $params    Array of several parameters
466          *
467          * @return boolean|object
468          *
469          * Example:
470          * $table = "item";
471          * $fields = array("id", "uri", "uid", "network");
472          *
473          * $condition = array("uid" => 1, "network" => 'dspr');
474          * or:
475          * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
476          *
477          * $params = array("order" => array("id", "received" => true), "limit" => 10);
478          *
479          * $data = DBA::select($table, $fields, $condition, $params);
480          * @throws \Exception
481          */
482         public static function select($table, array $fields = [], array $condition = [], array $params = [])
483         {
484                 return DI::dba()->select($table, $fields, $condition, $params);
485         }
486
487         /**
488          * Counts the rows from a table satisfying the provided condition
489          *
490          * @param string|array $table     Table name or array [schema => table]
491          * @param array        $condition array of fields for condition
492          * @param array        $params    Array of several parameters
493          *
494          * @return int
495          *
496          * Example:
497          * $table = "item";
498          *
499          * $condition = ["uid" => 1, "network" => 'dspr'];
500          * or:
501          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
502          *
503          * $count = DBA::count($table, $condition);
504          * @throws \Exception
505          */
506         public static function count($table, array $condition = [], array $params = [])
507         {
508                 return DI::dba()->count($table, $condition, $params);
509         }
510
511         /**
512          * Build the table query substring from one or more tables, with or without a schema.
513          *
514          * Expected formats:
515          * - table
516          * - [table1, table2, ...]
517          * - [schema1 => table1, schema2 => table2, table3, ...]
518          *
519          * @param string|array $tables
520          * @return string
521          */
522         public static function buildTableString($tables)
523         {
524                 if (is_string($tables)) {
525                         $tables = [$tables];
526                 }
527
528                 $quotedTables = [];
529
530                 foreach ($tables as $schema => $table) {
531                         if (is_numeric($schema)) {
532                                 $quotedTables[] = self::quoteIdentifier($table);
533                         } else {
534                                 $quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
535                         }
536                 }
537
538                 return implode(', ', $quotedTables);
539         }
540
541         /**
542          * Escape an identifier (table or field name)
543          *
544          * @param $identifier
545          * @return string
546          */
547         public static function quoteIdentifier($identifier)
548         {
549                 return '`' . str_replace('`', '``', $identifier) . '`';
550         }
551
552         /**
553          * Returns the SQL condition string built from the provided condition array
554          *
555          * This function operates with two modes.
556          * - Supplied with a field/value associative array, it builds simple strict
557          *   equality conditions linked by AND.
558          * - Supplied with a flat list, the first element is the condition string and
559          *   the following arguments are the values to be interpolated
560          *
561          * $condition = ["uid" => 1, "network" => 'dspr'];
562          * or:
563          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
564          *
565          * In either case, the provided array is left with the parameters only
566          *
567          * @param array $condition
568          * @return string
569          */
570         public static function buildCondition(array &$condition = [])
571         {
572                 $condition = self::collapseCondition($condition);
573                 
574                 $condition_string = '';
575                 if (count($condition) > 0) {
576                         $condition_string = " WHERE (" . array_shift($condition) . ")";
577                 }
578
579                 return $condition_string;
580         }
581
582         /**
583          * Collapse an associative array condition into a SQL string + parameters condition array.
584          *
585          * ['uid' => 1, 'network' => ['dspr', 'apub']]
586          *
587          * gets transformed into
588          *
589          * ["`uid` = ? AND `network` IN (?, ?)", 1, 'dspr', 'apub']
590          *
591          * @param array $condition
592          * @return array
593          */
594         public static function collapseCondition(array $condition)
595         {
596                 // Ensures an always true condition is returned
597                 if (count($condition) < 1) {
598                         return ['1'];
599                 }
600
601                 reset($condition);
602                 $first_key = key($condition);
603
604                 if (is_int($first_key)) {
605                         // Already collapsed
606                         return $condition;
607                 }
608
609                 $values = [];
610                 $condition_string = "";
611                 foreach ($condition as $field => $value) {
612                         if ($condition_string != "") {
613                                 $condition_string .= " AND ";
614                         }
615
616                         if (is_array($value)) {
617                                 if (count($value)) {
618                                         /* Workaround for MySQL Bug #64791.
619                                          * Never mix data types inside any IN() condition.
620                                          * In case of mixed types, cast all as string.
621                                          * Logic needs to be consistent with DBA::p() data types.
622                                          */
623                                         $is_int = false;
624                                         $is_alpha = false;
625                                         foreach ($value as $single_value) {
626                                                 if (is_int($single_value)) {
627                                                         $is_int = true;
628                                                 } else {
629                                                         $is_alpha = true;
630                                                 }
631                                         }
632
633                                         if ($is_int && $is_alpha) {
634                                                 foreach ($value as &$ref) {
635                                                         if (is_int($ref)) {
636                                                                 $ref = (string)$ref;
637                                                         }
638                                                 }
639                                                 unset($ref); //Prevent accidental re-use.
640                                         }
641
642                                         $values = array_merge($values, array_values($value));
643                                         $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
644                                         $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
645                                 } else {
646                                         // Empty value array isn't supported by IN and is logically equivalent to no match
647                                         $condition_string .= "FALSE";
648                                 }
649                         } elseif (is_null($value)) {
650                                 $condition_string .= self::quoteIdentifier($field) . " IS NULL";
651                         } else {
652                                 $values[$field] = $value;
653                                 $condition_string .= self::quoteIdentifier($field) . " = ?";
654                         }
655                 }
656
657                 $condition = array_merge([$condition_string], array_values($values));
658
659                 return $condition;
660         }
661
662         /**
663          * Merges the provided conditions into a single collapsed one
664          *
665          * @param array ...$conditions One or more condition arrays
666          * @return array A collapsed condition
667          * @see DBA::collapseCondition() for the condition array formats
668          */
669         public static function mergeConditions(array ...$conditions)
670         {
671                 $conditionStrings = [];
672                 $result = [];
673
674                 foreach ($conditions as $key => $condition) {
675                         $condition = self::collapseCondition($condition);
676
677                         $conditionStrings[] = array_shift($condition);
678                         // The result array holds the eventual parameter values
679                         $result = array_merge($result, $condition);
680                 }
681
682                 if (count($conditionStrings)) {
683                         // We prepend the condition string at the end to form a collapsed condition array again
684                         array_unshift($result, implode(' AND ', $conditionStrings));
685                 }
686
687                 return $result;
688         }
689
690         /**
691          * Returns the SQL parameter string built from the provided parameter array
692          *
693          * Expected format for each key:
694          *
695          * group_by:
696          *  - list of column names
697          *
698          * order:
699          *  - numeric keyed column name => ASC
700          *  - associative element with boolean value => DESC (true), ASC (false)
701          *  - associative element with string value => 'ASC' or 'DESC' literally
702          *
703          * limit:
704          *  - single numeric value => count
705          *  - list with two numeric values => offset, count
706          *
707          * @param array $params
708          * @return string
709          */
710         public static function buildParameter(array $params = [])
711         {
712                 $groupby_string = '';
713                 if (!empty($params['group_by'])) {
714                         $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
715                 }
716
717                 $order_string = '';
718                 if (isset($params['order'])) {
719                         $order_string = " ORDER BY ";
720                         foreach ($params['order'] AS $fields => $order) {
721                                 if ($order === 'RAND()') {
722                                         $order_string .= "RAND(), ";
723                                 } elseif (!is_int($fields)) {
724                                         if ($order !== 'DESC' && $order !== 'ASC') {
725                                                 $order = $order ? 'DESC' : 'ASC';
726                                         }
727
728                                         $order_string .= self::quoteIdentifier($fields) . " " . $order . ", ";
729                                 } else {
730                                         $order_string .= self::quoteIdentifier($order) . ", ";
731                                 }
732                         }
733                         $order_string = substr($order_string, 0, -2);
734                 }
735
736                 $limit_string = '';
737                 if (isset($params['limit']) && is_numeric($params['limit'])) {
738                         $limit_string = " LIMIT " . intval($params['limit']);
739                 }
740
741                 if (isset($params['limit']) && is_array($params['limit'])) {
742                         $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
743                 }
744
745                 return $groupby_string . $order_string . $limit_string;
746         }
747
748         /**
749          * Fills an array with data from a query
750          *
751          * @param object $stmt statement object
752          * @param bool   $do_close
753          * @return array Data array
754          */
755         public static function toArray($stmt, $do_close = true)
756         {
757                 return DI::dba()->toArray($stmt, $do_close);
758         }
759
760         /**
761          * Returns the error number of the last query
762          *
763          * @return string Error number (0 if no error)
764          */
765         public static function errorNo()
766         {
767                 return DI::dba()->errorNo();
768         }
769
770         /**
771          * Returns the error message of the last query
772          *
773          * @return string Error message ('' if no error)
774          */
775         public static function errorMessage()
776         {
777                 return DI::dba()->errorMessage();
778         }
779
780         /**
781          * Closes the current statement
782          *
783          * @param object $stmt statement object
784          * @return boolean was the close successful?
785          */
786         public static function close($stmt)
787         {
788                 return DI::dba()->close($stmt);
789         }
790
791         /**
792          * Return a list of database processes
793          *
794          * @return array
795          *      'list' => List of processes, separated in their different states
796          *      'amount' => Number of concurrent database processes
797          * @throws \Exception
798          */
799         public static function processlist()
800         {
801                 return DI::dba()->processlist();
802         }
803
804         /**
805          * Fetch a database variable
806          *
807          * @param string $name
808          * @return string content
809          */
810         public static function getVariable(string $name)
811         {
812                 return DI::dba()->getVariable($name);
813         }
814
815         /**
816          * Checks if $array is a filled array with at least one entry.
817          *
818          * @param mixed $array A filled array with at least one entry
819          *
820          * @return boolean Whether $array is a filled array or an object with rows
821          */
822         public static function isResult($array)
823         {
824                 return DI::dba()->isResult($array);
825         }
826
827         /**
828          * Escapes a whole array
829          *
830          * @param mixed   $arr           Array with values to be escaped
831          * @param boolean $add_quotation add quotation marks for string values
832          * @return void
833          */
834         public static function escapeArray(&$arr, $add_quotation = false)
835         {
836                 DI::dba()->escapeArray($arr, $add_quotation);
837         }
838 }