]> git.mxchange.org Git - friendica.git/blobdiff - src/Database/Database.php
Replace BaseObject class with DI::* calls
[friendica.git] / src / Database / Database.php
index 1533b7674abc98819c31b382eb77a131665285d2..1dd3524ed61c694d2bc2f26303c475ca684325c2 100644 (file)
@@ -4,6 +4,7 @@ namespace Friendica\Database;
 
 use Friendica\Core\Config\Cache\ConfigCache;
 use Friendica\Core\System;
+use Friendica\Network\HTTPException\InternalServerErrorException;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Profiler;
 use mysqli;
@@ -21,29 +22,29 @@ use Psr\Log\LoggerInterface;
  */
 class Database
 {
-       private $connected = false;
+       protected $connected = false;
 
        /**
         * @var ConfigCache
         */
-       private $configCache;
+       protected $configCache;
        /**
         * @var Profiler
         */
-       private $profiler;
+       protected $profiler;
        /**
         * @var LoggerInterface
         */
-       private $logger;
-       private $server_info    = '';
+       protected $logger;
+       protected $server_info    = '';
        /** @var PDO|mysqli */
-       private $connection;
-       private $driver;
+       protected $connection;
+       protected $driver;
        private $error          = false;
        private $errorno        = 0;
        private $affected_rows  = 0;
-       private $in_transaction = false;
-       private $in_retrial     = false;
+       protected $in_transaction = false;
+       protected $in_retrial     = false;
        private $relation       = [];
 
        public function __construct(ConfigCache $configCache, Profiler $profiler, LoggerInterface $logger, array $server = [])
@@ -66,7 +67,7 @@ class Database
        {
                // Use environment variables for mysql if they are set beforehand
                if (!empty($server['MYSQL_HOST'])
-                   && !empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER']))
+                   && (!empty($server['MYSQL_USERNAME'] || !empty($server['MYSQL_USER'])))
                    && $server['MYSQL_PASSWORD'] !== false
                    && !empty($server['MYSQL_DATABASE']))
                {
@@ -89,9 +90,12 @@ class Database
        public function connect()
        {
                if (!is_null($this->connection) && $this->connected()) {
-                       return true;
+                       return $this->connected;
                }
 
+               // Reset connected state
+               $this->connected = false;
+
                $port       = 0;
                $serveraddr = trim($this->configCache->get('database', 'hostname'));
                $serverdata = explode(':', $serveraddr);
@@ -126,7 +130,7 @@ class Database
                                $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
                                $this->connected = true;
                        } catch (PDOException $e) {
-                               /// @TODO At least log exception, don't ignore it!
+                               $this->connected = false;
                        }
                }
 
@@ -186,19 +190,20 @@ class Database
         */
        public function disconnect()
        {
-               if (is_null($this->connection)) {
-                       return;
+               if (!is_null($this->connection)) {
+                       switch ($this->driver) {
+                               case 'pdo':
+                                       $this->connection = null;
+                                       break;
+                               case 'mysqli':
+                                       $this->connection->close();
+                                       $this->connection = null;
+                                       break;
+                       }
                }
 
-               switch ($this->driver) {
-                       case 'pdo':
-                               $this->connection = null;
-                               break;
-                       case 'mysqli':
-                               $this->connection->close();
-                               $this->connection = null;
-                               break;
-               }
+               $this->driver    = null;
+               $this->connected = false;
        }
 
        /**
@@ -368,6 +373,7 @@ class Database
                                $connected = $this->connection->ping();
                                break;
                }
+
                return $connected;
        }
 
@@ -484,6 +490,10 @@ class Database
                // We are having an own error logging in the function "e"
                $called_from_e = ($called_from['function'] == 'e');
 
+               if (!isset($this->connection)) {
+                       throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
+               }
+
                switch ($this->driver) {
                        case 'pdo':
                                // If there are no arguments we use "query"
@@ -725,8 +735,8 @@ class Database
        /**
         * @brief Check if data exists
         *
-        * @param string $table     Table name
-        * @param array  $condition array of fields for condition
+        * @param string|array $table     Table name or array [schema => table]
+        * @param array        $condition array of fields for condition
         *
         * @return boolean Are there rows for that condition?
         * @throws \Exception
@@ -906,49 +916,32 @@ class Database
        /**
         * @brief Insert a row into a table
         *
-        * @param string/array $table Table name
-        *
-        * @return string formatted and sanitzed table name
-        * @throws \Exception
-        */
-       public function formatTableName($table)
-       {
-               if (is_string($table)) {
-                       return "`" . $this->sanitizeIdentifier($table) . "`";
-               }
-
-               if (!is_array($table)) {
-                       return '';
-               }
-
-               $scheme = key($table);
-
-               return "`" . $this->sanitizeIdentifier($scheme) . "`.`" . $this->sanitizeIdentifier($table[$scheme]) . "`";
-       }
-
-       /**
-        * @brief Insert a row into a table
-        *
-        * @param string $table               Table name
-        * @param array  $param               parameter array
-        * @param bool   $on_duplicate_update Do an update on a duplicate entry
+        * @param string|array $table               Table name or array [schema => table]
+        * @param array        $param               parameter array
+        * @param bool         $on_duplicate_update Do an update on a duplicate entry
         *
         * @return boolean was the insert successful?
         * @throws \Exception
         */
        public function insert($table, $param, $on_duplicate_update = false)
        {
-
                if (empty($table) || empty($param)) {
                        $this->logger->info('Table and fields have to be set');
                        return false;
                }
 
-               $sql = "INSERT INTO " . $this->formatTableName($table) . " (`" . implode("`, `", array_keys($param)) . "`) VALUES (" .
-                      substr(str_repeat("?, ", count($param)), 0, -2) . ")";
+               $table_string = DBA::buildTableString($table);
+
+               $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
+
+               $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
+
+               $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
 
                if ($on_duplicate_update) {
-                       $sql .= " ON DUPLICATE KEY UPDATE `" . implode("` = ?, `", array_keys($param)) . "` = ?";
+                       $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
+
+                       $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
 
                        $values = array_values($param);
                        $param  = array_merge_recursive($values, $values);
@@ -980,7 +973,7 @@ class Database
         *
         * This function can be extended in the future to accept a table array as well.
         *
-        * @param string $table Table name
+        * @param string|array $table Table name or array [schema => table]
         *
         * @return boolean was the lock successful?
         * @throws \Exception
@@ -995,7 +988,7 @@ class Database
                        $this->connection->autocommit(false);
                }
 
-               $success = $this->e("LOCK TABLES " . $this->formatTableName($table) . " WRITE");
+               $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
 
                if ($this->driver == 'pdo') {
                        $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
@@ -1070,7 +1063,7 @@ class Database
                return true;
        }
 
-       private function performCommit()
+       protected function performCommit()
        {
                switch ($this->driver) {
                        case 'pdo':
@@ -1152,6 +1145,8 @@ class Database
        /**
         * @brief Delete a row from a table
         *
+        * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
+        *
         * @param string $table      Table name
         * @param array  $conditions Field condition(s)
         * @param array  $options
@@ -1176,13 +1171,11 @@ class Database
 
                // We quit when this key already exists in the callstack.
                if (isset($callstack[$key])) {
-                       return $commands;
+                       return true;
                }
 
                $callstack[$key] = true;
 
-               $table = $this->sanitizeIdentifier($table);
-
                $commands[$key] = ['table' => $table, 'conditions' => $conditions];
 
                // Don't use "defaults" here, since it would set "false" to "true"
@@ -1250,7 +1243,7 @@ class Database
                        $condition_string = DBA::buildCondition($conditions);
 
                        if ((count($command['conditions']) > 1) || is_int($first_key)) {
-                               $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
+                               $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
                                $this->logger->debug($this->replaceParameters($sql, $conditions));
 
                                if (!$this->e($sql, $conditions)) {
@@ -1278,7 +1271,7 @@ class Database
                foreach ($compacted AS $table => $values) {
                        foreach ($values AS $field => $field_value_list) {
                                foreach ($field_value_list AS $field_values) {
-                                       $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
+                                       $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
                                               substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
 
                                        $this->logger->debug($this->replaceParameters($sql, $field_values));
@@ -1319,7 +1312,7 @@ class Database
         * Only set $old_fields to a boolean value when you are sure that you will update a single row.
         * When you set $old_fields to "true" then $fields must contain all relevant fields!
         *
-        * @param string        $table      Table name
+        * @param string|array  $table      Table name or array [schema => table]
         * @param array         $fields     contains the fields that are updated
         * @param array         $condition  condition array with the key values
         * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
@@ -1329,12 +1322,13 @@ class Database
         */
        public function update($table, $fields, $condition, $old_fields = [])
        {
-
                if (empty($table) || empty($fields) || empty($condition)) {
                        $this->logger->info('Table, fields and condition have to be set');
                        return false;
                }
 
+               $table_string = DBA::buildTableString($table);
+
                $condition_string = DBA::buildCondition($condition);
 
                if (is_bool($old_fields)) {
@@ -1367,8 +1361,9 @@ class Database
                        return true;
                }
 
-               $sql = "UPDATE " . $this->formatTableName($table) . " SET `" .
-                      implode("` = ?, `", array_keys($fields)) . "` = ?" . $condition_string;
+               $sql = "UPDATE " . $table_string . " SET "
+                       . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
+                       . $condition_string;
 
                $params1 = array_values($fields);
                $params2 = array_values($condition);
@@ -1382,10 +1377,10 @@ class Database
         *
         * @brief Retrieve a single record from a table
         *
-        * @param string $table
-        * @param array  $fields
-        * @param array  $condition
-        * @param array  $params
+        * @param string|array $table
+        * @param array        $fields
+        * @param array        $condition
+        * @param array        $params
         *
         * @return bool|array
         * @throws \Exception
@@ -1408,16 +1403,16 @@ class Database
        /**
         * @brief Select rows from a table and fills an array with the data
         *
-        * @param string $table     Table name
-        * @param array  $fields    Array of selected fields, empty for all
-        * @param array  $condition Array of fields for condition
-        * @param array  $params    Array of several parameters
+        * @param string|array $table     Table name or array [schema => table]
+        * @param array        $fields    Array of selected fields, empty for all
+        * @param array        $condition Array of fields for condition
+        * @param array        $params    Array of several parameters
         *
         * @return array Data array
         * @throws \Exception
         * @see   self::select
         */
-       public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
+       public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
        {
                return $this->toArray($this->select($table, $fields, $condition, $params));
        }
@@ -1425,10 +1420,10 @@ class Database
        /**
         * @brief Select rows from a table
         *
-        * @param string $table     Table name
-        * @param array  $fields    Array of selected fields, empty for all
-        * @param array  $condition Array of fields for condition
-        * @param array  $params    Array of several parameters
+        * @param string|array $table     Table name or array [schema => table]
+        * @param array        $fields    Array of selected fields, empty for all
+        * @param array        $condition Array of fields for condition
+        * @param array        $params    Array of several parameters
         *
         * @return boolean|object
         *
@@ -1452,16 +1447,18 @@ class Database
                }
 
                if (count($fields) > 0) {
-                       $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
+                       $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
                } else {
-                       $select_fields = "*";
+                       $select_string = '*';
                }
 
+               $table_string = DBA::buildTableString($table);
+
                $condition_string = DBA::buildCondition($condition);
 
                $param_string = DBA::buildParameter($params);
 
-               $sql = "SELECT " . $select_fields . " FROM " . $this->formatTableName($table) . $condition_string . $param_string;
+               $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
 
                $result = $this->p($sql, $condition);
 
@@ -1471,8 +1468,9 @@ class Database
        /**
         * @brief Counts the rows from a table satisfying the provided condition
         *
-        * @param string $table     Table name
-        * @param array  $condition array of fields for condition
+        * @param string|array $table     Table name or array [schema => table]
+        * @param array        $condition Array of fields for condition
+        * @param array        $params    Array of several parameters
         *
         * @return int
         *
@@ -1486,15 +1484,25 @@ class Database
         * $count = DBA::count($table, $condition);
         * @throws \Exception
         */
-       public function count($table, array $condition = [])
+       public function count($table, array $condition = [], array $params = [])
        {
                if (empty($table)) {
                        return false;
                }
 
+               $table_string = DBA::buildTableString($table);
+
                $condition_string = DBA::buildCondition($condition);
 
-               $sql = "SELECT COUNT(*) AS `count` FROM " . $this->formatTableName($table) . $condition_string;
+               if (empty($params['expression'])) {
+                       $expression = '*';
+               } elseif (!empty($params['distinct'])) {
+                       $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
+               } else {
+                       $expression = DBA::quoteIdentifier($params['expression']);
+               }
+
+               $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
 
                $row = $this->fetchFirst($sql, $condition);
 
@@ -1512,16 +1520,18 @@ class Database
        public function toArray($stmt, $do_close = true)
        {
                if (is_bool($stmt)) {
-                       return $stmt;
+                       return [];
                }
 
                $data = [];
                while ($row = $this->fetch($stmt)) {
                        $data[] = $row;
                }
+
                if ($do_close) {
                        $this->close($stmt);
                }
+
                return $data;
        }