]> git.mxchange.org Git - core.git/blob - framework/main/middleware/database/class_DatabaseConnection.php
29e8c7c25714906d6ec6bc6d97e9099546ace7bd
[core.git] / framework / main / middleware / database / class_DatabaseConnection.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Connection\Database;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Connector\Database\DatabaseConnector;
7 use Org\Mxchange\CoreFramework\Criteria\Criteria;
8 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
9 use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
10 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
11 use Org\Mxchange\CoreFramework\Registry\Registerable;
12 use Org\Mxchange\CoreFramework\Middleware\BaseMiddleware;
13 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
14
15 // Import SPL stuff
16 use \InvalidArgumentException;
17
18 /**
19  * Database selector class
20  *
21  * @author              Roland Haeder <webmaster@shipsimu.org>
22  * @version             0.0.0
23  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
24  * @license             GNU GPL 3.0 or any newer version
25  * @link                http://www.shipsimu.org
26  *
27  * This program is free software: you can redistribute it and/or modify
28  * it under the terms of the GNU General Public License as published by
29  * the Free Software Foundation, either version 3 of the License, or
30  * (at your option) any later version.
31  *
32  * This program is distributed in the hope that it will be useful,
33  * but WITHOUT ANY WARRANTY; without even the implied warranty of
34  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35  * GNU General Public License for more details.
36  *
37  * You should have received a copy of the GNU General Public License
38  * along with this program. If not, see <http://www.gnu.org/licenses/>.
39  */
40 class DatabaseConnection extends BaseMiddleware implements DatabaseConnector, Registerable {
41         /**
42          * Array for connection data
43          */
44         private $connectData = array(
45                 'login' => '',
46                 'pass'  => '',
47                 'dbase' => '',
48                 'host'  => ''
49         );
50
51         /**
52          * The real database layer
53          */
54         private $backendInstance = NULL;
55
56         /**
57          * An instance of this class
58          */
59         private static $selfInstance = NULL;
60
61         /**
62          * Protected constructor
63          */
64         private function __construct () {
65                 // Call parent constructor
66                 parent::__construct(__CLASS__);
67         }
68
69         /**
70          * Creates a new database connection layer
71          *
72          * @param       $debugInstance          An instance of a DebugMiddleware class
73          * @param       $backendInstance        An instance of a DatabaseBackend class
74          * @todo        $debugInstance is currently not used
75          */
76         public static final function createDatabaseConnection (DebugMiddleware $debugInstance, DatabaseBackend $backendInstance) {
77                 // Get instance
78                 $databaseInstance = new DatabaseConnection();
79
80                 // Set database layer
81                 $databaseInstance->setDatabaseLayer($backendInstance);
82
83                 // Set db instance
84                 self::$selfInstance = $databaseInstance;
85
86                 // Return instance
87                 return $databaseInstance;
88         }
89
90         /**
91          * Getter for this class
92          *
93          * @return      $selfInstance   An instance of this class
94          */
95         public static final function getSelfInstance () {
96                 return self::$selfInstance;
97         }
98
99         /**
100          * Setter for all database connection data. All these parameters may be
101          * supported by the underlaying backend.
102          *
103          * @param       $login  Login name to database
104          * @param       $pass   Passwort for above login
105          * @param       $dbase  Name of used database
106          * @param       $host   Host to connect to (default: 127.0.0.1)
107          * @return      void
108          */
109         public final function setConnectionData (string $login, string $pass, string $dbase, string $host = '127.0.0.1') {
110                 // Transfer connection data
111                 $this->connectData['login'] = $login;
112                 $this->connectData['pass']  = $pass;
113                 $this->connectData['dbase'] = $dbase;
114                 $this->connectData['host']  = $host;
115         }
116
117         /**
118          * Getter for connection data
119          *
120          * @return      $connectData    Connection data stored with this clas
121          */
122         public final function getConnectionData () {
123                 return $this->connectData;
124         }
125
126         /**
127          * Setter for the real database layer
128          * @param       $backendInstance        An instance of a DatabaseBackend class
129          * @return      void
130          */
131         public final function setDatabaseLayer (DatabaseBackend $backendInstance) {
132                 $this->backendInstance = $backendInstance;
133         }
134
135         /**
136          * Getter for index key
137          *
138          * @return      $indexKey       Index key
139          */
140         public final function getIndexKey () {
141                 return $this->backendInstance->getIndexKey();
142         }
143
144         /**
145          * Runs a 'select' statement on the database layer with given table name
146          * and criteria. If this doesn't fail the result will be returned
147          *
148          * @param       $tableName                      Name of the 'table' we shall query
149          * @param       $criteriaInstance       An instance of a Criteria class
150          * @return      $result                         The result as an array
151          * @throws      InvalidArgumentException        If a parameter is empty
152          */
153         public function doSelectByTableCriteria (string $tableName, Criteria $criteriaInstance) {
154                 // Validate parameter
155                 if (empty($tableName)) {
156                         // Throw IAE
157                         throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
158                 }
159
160                 // Connect to the database
161                 $this->backendInstance->connectToDatabase();
162
163                 // Get result from query
164                 $result = $this->backendInstance->querySelect($tableName, $criteriaInstance);
165
166                 // Return the result
167                 return $result;
168         }
169
170         /**
171          * Getter for last exception
172          *
173          * @return      $exceptionInstance      Last thrown exception
174          */
175         public final function getLastException () {
176                 $exceptionInstance = $this->backendInstance->getLastException();
177                 return $exceptionInstance;
178         }
179
180         /**
181          * 'Inserts' a data set instance into a local file database folder
182          *
183          * @param       $dataSetInstance        A storeable data set
184          * @return      void
185          */
186         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
187                 // Connect to the database
188                 $this->backendInstance->connectToDatabase();
189
190                 // Ask the database layer
191                 $this->backendInstance->queryInsertDataSet($dataSetInstance);
192         }
193
194         /**
195          * 'Updates' a data set instance with a database layer
196          *
197          * @param       $dataSetInstance        A storeable data set
198          * @return      void
199          */
200         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
201                 // Connect to the database
202                 $this->backendInstance->connectToDatabase();
203
204                 // Ask the database layer
205                 $this->backendInstance->queryUpdateDataSet($dataSetInstance);
206         }
207
208         /**
209          * Getter for primary key column of specified table name
210          *
211          * @param       $tableName              Name of table we need the primary key column from
212          * @return      $primaryKey             Primary key column of requested table
213          * @throws      InvalidArgumentException        If a parameter is empty
214          */
215         public function getPrimaryKeyOfTable (string $tableName) {
216                 // Validate parameter
217                 if (empty($tableName)) {
218                         // Throw IAE
219                         throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
220                 }
221
222                 // Connect to the database
223                 $this->backendInstance->connectToDatabase();
224
225                 // Ask the database layer
226                 $primaryKey = $this->backendInstance->getPrimaryKeyOfTable($tableName);
227
228                 // Return the value
229                 return $primaryKey;
230         }
231
232         /**
233          * Removes non-public data from given array.
234          *
235          * @param       $data   An array with possible non-public data that needs to be removed.
236          * @return      $data   A cleaned up array with only public data.
237          */
238         public function removeNonPublicDataFromArray (array $data) {
239                 // Connect to the database
240                 $this->backendInstance->connectToDatabase();
241
242                 // Call database backend
243                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DB-CONNECTION[' . $this->__toString() . ']: Invoking this->backendInstance->removeNonPublicDataFromArray(data) ...');
244                 $data = $this->backendInstance->removeNonPublicDataFromArray($data);
245
246                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DB-CONNECTION[' . $this->__toString() . ']: data[]=' . gettype($data));
247                 return $data;
248         }
249
250         /**
251          * Count total table rows
252          *
253          * @param       $tableName      Table name
254          * @return      $count          Total row count
255          * @throws      InvalidArgumentException        If a parameter is empty
256          */
257         public function countTotalRows (string $tableName) {
258                 // Validate parameter
259                 if (empty($tableName)) {
260                         // Throw IAE
261                         throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
262                 }
263
264                 // Connect to the database
265                 $this->backendInstance->connectToDatabase();
266
267                 // Ask the database layer
268                 $count = $this->backendInstance->countTotalRows($tableName);
269
270                 // Return the value
271                 return $count;
272         }
273
274 }