Continued:
[core.git] / framework / main / classes / database / frontend / class_BaseDatabaseFrontend.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Database\Frontend;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Criteria\Criteria;
8 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
9 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
10 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
11 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
12 use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
13 use Org\Mxchange\CoreFramework\Traits\Cache\CacheableTrait;
14
15 /**
16  * A generic database frontend
17  *
18  * @author              Roland Haeder <webmaster@shipsimu.org>
19  * @version             0.0.0
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
21  * @license             GNU GPL 3.0 or any newer version
22  * @link                http://www.shipsimu.org
23  *
24  * This program is free software: you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License as published by
26  * the Free Software Foundation, either version 3 of the License, or
27  * (at your option) any later version.
28  *
29  * This program is distributed in the hope that it will be useful,
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32  * GNU General Public License for more details.
33  *
34  * You should have received a copy of the GNU General Public License
35  * along with this program. If not, see <http://www.gnu.org/licenses/>.
36  */
37 abstract class BaseDatabaseFrontend extends BaseFrameworkSystem {
38         // Load traits
39         use CacheableTrait;
40
41         /**
42          * Current table name to use
43          */
44         private $tableName = 'unknown';
45
46         /**
47          * Protected constructor
48          *
49          * @param       $className      Name of the class
50          * @return      void
51          */
52         protected function __construct (string $className) {
53                 // Call parent constructor
54                 parent::__construct($className);
55
56                 // Initialize the cache instance
57                 $this->initCacheInstance();
58         }
59
60         /**
61          * Initializes the cache instance with a new object
62          *
63          * @return      void
64          */
65         private final function initCacheInstance () {
66                 // Is the cache enabled?
67                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
68                         // Set the new instance
69                         $this->setCacheInstance(ObjectFactory::createObjectByConfiguredName('cache_class'));
70                 }
71         }
72
73         /**
74          * Setter for table name
75          *
76          * @param       $tableName      Name of table name to set
77          * @return      void
78          */
79         protected final function setTableName (string $tableName) {
80                 $this->tableName = $tableName;
81         }
82
83         /**
84          * Getter for table name
85          *
86          * @return      $tableName      Name of table name to set
87          */
88         protected final function getTableName () {
89                 return $this->tableName;
90         }
91
92         /**
93          * Gets a cache key from Criteria instance
94          *
95          * @param       $criteriaInstance       An instance of a Criteria class
96          * @param       $onlyKeys                       Only use these keys for a cache key
97          * @return      $cacheKey                       A cache key suitable for lookup/storage purposes
98          */
99         protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
100                 // Generate it
101                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
102                 $cacheKey = sprintf('%s@%s',
103                         $this->__toString(),
104                         $criteriaInstance->getCacheKey($onlyKeys)
105                 );
106
107                 // And return it
108                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
109                 return $cacheKey;
110         }
111
112         /**
113          * 'Inserts' a data set instance into a local file database folder
114          *
115          * @param       $dataSetInstance        A storeable data set
116          * @param       $onlyKeys                       Only use these keys for a cache key
117          * @return      void
118          */
119         protected function queryInsertDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = []) {
120                 // Default cache key is NULL
121                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: dataSetInstance=%s,onlyKeys()=%d - CALLED!', $dataSetInstance->__toString(), count($onlyKeys)));
122                 $cacheKey = NULL;
123
124                 // Is cache enabled?
125                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
126                         // First get a key suitable for our cache and extend it with this class name
127                         $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
128                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: Using cache key ' . $cacheKey . ' for purging ...');
129                 }
130
131                 // Does this key exists in cache?
132                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: cacheKey[%s]=%s', gettype($cacheKey), $cacheKey));
133                 if ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->getCacheInstance()->offsetExists($cacheKey))) {
134                         // Purge the cache
135                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Calling this->cacheInstance->purgeOffset(%s) ...', $cacheKey));
136                         $this->getCacheInstance()->purgeOffset($cacheKey);
137                 }
138
139                 // Handle it over to the middleware
140                 FrameworkBootstrap::getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
141
142                 // Trace message
143                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: EXIT!');
144         }
145
146         /**
147          * 'Updates' a data set instance with a database layer
148          *
149          * @param       $dataSetInstance        A storeable data set
150          * @param       $onlyKeys                       Only use these keys for a cache key
151          * @return      void
152          */
153         protected function queryUpdateDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = []) {
154                 // Init cache key
155                 $cacheKey = NULL;
156
157                 // Is cache enabled?
158                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
159                         // First get a key suitable for our cache and extend it with this class name
160                         $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
161                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: Using cache key ' . $cacheKey . ' for purging ...');
162                 }
163
164                 // Does this key exists in cache?
165                 if ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->getCacheInstance()->offsetExists($cacheKey))) {
166                         // Purge the cache
167                         $this->getCacheInstance()->purgeOffset($cacheKey);
168                 }
169
170                 // Handle it over to the middleware
171                 FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
172         }
173
174         /**
175          * Getter for index key
176          *
177          * @return      $indexKey       Index key
178          */
179         public final function getIndexKey () {
180                 return FrameworkBootstrap::getDatabaseInstance()->getIndexKey();
181         }
182
183         /**
184          * Getter for last exception
185          *
186          * @return      $lastException  Last exception or NULL if none occured
187          */
188         public final function getLastException () {
189                 return FrameworkBootstrap::getDatabaseInstance()->getLastException();
190         }
191
192         /**
193          * Do a "select" query on the current table with the given search criteria and
194          * store it in cache for later usage
195          *
196          * @param       $criteriaInstance       An instance of a Criteria class
197          * @param       $onlyKeys                       Only use these keys for a cache key
198          * @return      $resultInstance         An instance of a database result class
199          */
200         public function doSelectByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
201                 // Default cache key if cache is not enabled
202                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: criteriaInstance=%s,onlyKeys()=%d - CALLED!', $criteriaInstance->__toString(), count($onlyKeys)));
203                 $cacheKey = NULL;
204                 $result = [];
205
206                 // Is the cache enabled?
207                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
208                         // First get a key suitable for our cache and extend it with this class name
209                         $cacheKey = $this->getCacheKeyByCriteria($criteriaInstance, $onlyKeys);
210                 }
211
212                 // Does this key exists in cache?
213                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: cacheKey[%s]=%s', gettype($cacheKey), $cacheKey));
214                 if ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->getCacheInstance()->offsetExists($cacheKey, BaseDatabaseResult::RESULT_NAME_ROWS, 1))) {
215                         // Then use this result
216                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Cache used for cacheKey=%s', $cacheKey));
217                         $result = $this->getCacheInstance()->offsetGet($cacheKey);
218                 } else {
219                         // Now it's time to ask the database layer for this select statement
220                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Quering database, cacheKey=%s ...', $cacheKey));
221                         $result = FrameworkBootstrap::getDatabaseInstance()->doSelectByTableCriteria($this->getTableName(), $criteriaInstance);
222
223                         // Cache the result if not null
224                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: result[]=%s', gettype($result)));
225                         if (!is_null($result)) {
226                                 // Is cache enabled?
227                                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
228                                         // A valid result has returned from the database layer
229                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Setting cacheKey=%s with result()=%d entries', $cacheKey, count($result)));
230                                         $this->getCacheInstance()->offsetSet($cacheKey, $result);
231                                 }
232                         } else {
233                                 // This invalid result must be wrapped
234                                 $result = array(
235                                         BaseDatabaseResult::RESULT_NAME_STATUS    => 'invalid',
236                                         BaseDatabaseResult::RESULT_NAME_EXCEPTION => FrameworkBootstrap::getDatabaseInstance()->getLastException()
237                                 );
238                         }
239                 }
240
241                 // Create an instance of a CachedDatabaseResult class with the given result
242                 // @TODO Minor: Update above comment to e.g. BaseDatabaseResult
243                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: result[%s]=%s,result[%s]?=%d,result[%s]?=%d', BaseDatabaseResult::RESULT_NAME_STATUS, $result[BaseDatabaseResult::RESULT_NAME_STATUS], BaseDatabaseResult::RESULT_NAME_ROWS, isset($result[BaseDatabaseResult::RESULT_NAME_ROWS]), BaseDatabaseResult::RESULT_NAME_EXCEPTION, isset($result[BaseDatabaseResult::RESULT_NAME_EXCEPTION])));
244                 $resultInstance = ObjectFactory::createObjectByConfiguredName('database_result_class', array($result));
245
246                 // And return the instance
247                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: resultInstance=%s - EXIT!', $resultInstance->__toString()));
248                 return $resultInstance;
249         }
250
251         /**
252          * Count the numbers of rows we shall receive
253          *
254          * @param       $criteriaInstance       An instance of a Criteria class
255          * @param       $onlyKeys                       Only use these keys for a cache key
256          * @return      $numRows                        Numbers of rows of database entries
257          */
258         public function doSelectCountByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
259                 // Total numbers is -1 so we can distinglish between failed and valid queries
260                 $numRows = 0;
261
262                 // Get the result from above method
263                 $resultInstance = $this->doSelectByCriteria($criteriaInstance, $onlyKeys);
264
265                 // Was that query fine?
266                 if ($resultInstance->ifStatusIsOkay()) {
267                         // Then get the number of rows
268                         $numRows = $resultInstance->getAffectedRows();
269
270                         // Debug message
271                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: numRows=' . $numRows);
272                 }
273
274                 // Return the result
275                 return $numRows;
276         }
277
278         /**
279          * Getter for primary key used in wrapped table
280          *
281          * @return      $primaryKey             Primary key used in wrapped table
282          */
283         public final function getPrimaryKeyValue () {
284                 // Get the table name and a database instance and ask for it
285                 $primaryKey = FrameworkBootstrap::getDatabaseInstance()->getPrimaryKeyOfTable($this->getTableName());
286
287                 // Return value
288                 return $primaryKey;
289         }
290
291         /**
292          * Count rows of this table
293          *
294          * @return      $count  Count of total rows in this table
295          */
296         public final function countTotalRows () {
297                 // Get the table name and a database instance and ask for it
298                 $count = FrameworkBootstrap::getDatabaseInstance()->countTotalRows($this->getTableName());
299
300                 // Return value
301                 return $count;
302         }
303
304         /**
305          * Removes non-public data from given array.
306          *
307          * @param       $data   An array with possible non-public data that needs to be removed.
308          * @return      $data   A cleaned up array with only public data.
309          */
310         public function removeNonPublicDataFromArray (array $data) {
311                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('WRAPPER[' . $this->__toString() . ']: Calling FrameworkBootstrap::getDatabaseInstance()->removeNonPublicDataFromArray(data) ...');
312                 $data = FrameworkBootstrap::getDatabaseInstance()->removeNonPublicDataFromArray($data);
313
314                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('WRAPPER[' . $this->__toString() . ']: data[]=' . gettype($data));
315                 return $data;
316         }
317
318 }