]> git.mxchange.org Git - core.git/blob - framework/main/classes/database/frontend/class_BaseDatabaseFrontend.php
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 - 2020 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                 } // END - if
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          * 'Inserts' a data set instance into a local file database folder
94          *
95          * @param       $dataSetInstance        A storeable data set
96          * @param       $onlyKeys                       Only use these keys for a cache key
97          * @return      void
98          */
99         protected function queryInsertDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = []) {
100                 // Default cache key is NULL
101                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: dataSetInstance=%s,onlyKeys()=%d - CALLED!', $dataSetInstance->__toString(), count($onlyKeys)));
102                 $cacheKey = NULL;
103
104                 // Is cache enabled?
105                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
106                         // First get a key suitable for our cache and extend it with this class name
107                         $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
108                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: Using cache key ' . $cacheKey . ' for purging ...');
109                 } // END - if
110
111                 // Does this key exists in cache?
112                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: cacheKey[%s]=%s', gettype($cacheKey), $cacheKey));
113                 if ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->getCacheInstance()->offsetExists($cacheKey))) {
114                         // Purge the cache
115                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Calling this->cacheInstance->purgeOffset(%s) ...', $cacheKey));
116                         $this->getCacheInstance()->purgeOffset($cacheKey);
117                 } // END - if
118
119                 // Handle it over to the middleware
120                 FrameworkBootstrap::getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
121
122                 // Trace message
123                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: EXIT!');
124         }
125
126         /**
127          * 'Updates' a data set instance with a database layer
128          *
129          * @param       $dataSetInstance        A storeable data set
130          * @param       $onlyKeys                       Only use these keys for a cache key
131          * @return      void
132          */
133         protected function queryUpdateDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = []) {
134                 // Init cache key
135                 $cacheKey = NULL;
136
137                 // Is cache enabled?
138                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
139                         // First get a key suitable for our cache and extend it with this class name
140                         $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
141                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: Using cache key ' . $cacheKey . ' for purging ...');
142                 } // END - if
143
144                 // Does this key exists in cache?
145                 if ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->getCacheInstance()->offsetExists($cacheKey))) {
146                         // Purge the cache
147                         $this->getCacheInstance()->purgeOffset($cacheKey);
148                 } // END - if
149
150                 // Handle it over to the middleware
151                 FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
152         }
153
154         /**
155          * Getter for index key
156          *
157          * @return      $indexKey       Index key
158          */
159         public final function getIndexKey () {
160                 return FrameworkBootstrap::getDatabaseInstance()->getIndexKey();
161         }
162
163         /**
164          * Getter for last exception
165          *
166          * @return      $lastException  Last exception or NULL if none occured
167          */
168         public final function getLastException () {
169                 return FrameworkBootstrap::getDatabaseInstance()->getLastException();
170         }
171
172         /**
173          * Do a "select" query on the current table with the given search criteria and
174          * store it in cache for later usage
175          *
176          * @param       $criteriaInstance       An instance of a Criteria class
177          * @param       $onlyKeys                       Only use these keys for a cache key
178          * @return      $resultInstance         An instance of a database result class
179          */
180         public function doSelectByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
181                 // Default cache key if cache is not enabled
182                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: criteriaInstance=%s,onlyKeys()=%d - CALLED!', $criteriaInstance->__toString(), count($onlyKeys)));
183                 $cacheKey = NULL;
184                 $result = [];
185
186                 // Is the cache enabled?
187                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
188                         // First get a key suitable for our cache and extend it with this class name
189                         $cacheKey = $this->getCacheKeyByCriteria($criteriaInstance, $onlyKeys);
190                 } // END - if
191
192                 // Does this key exists in cache?
193                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: cacheKey[%s]=%s', gettype($cacheKey), $cacheKey));
194                 if ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->getCacheInstance()->offsetExists($cacheKey, BaseDatabaseResult::RESULT_NAME_ROWS, 1))) {
195                         // Then use this result
196                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Cache used for cacheKey=%s', $cacheKey));
197                         $result = $this->getCacheInstance()->offsetGet($cacheKey);
198                 } else {
199                         // Now it's time to ask the database layer for this select statement
200                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Quering database, cacheKey=%s ...', $cacheKey));
201                         $result = FrameworkBootstrap::getDatabaseInstance()->doSelectByTableCriteria($this->getTableName(), $criteriaInstance);
202
203                         // Cache the result if not null
204                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: result[]=%s', gettype($result)));
205                         if (!is_null($result)) {
206                                 // Is cache enabled?
207                                 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('database_cache_enabled') === true) {
208                                         // A valid result has returned from the database layer
209                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: Setting cacheKey=%s with result()=%d entries', $cacheKey, count($result)));
210                                         $this->getCacheInstance()->offsetSet($cacheKey, $result);
211                                 } // END - if
212                         } else {
213                                 // This invalid result must be wrapped
214                                 $result = array(
215                                         BaseDatabaseResult::RESULT_NAME_STATUS    => 'invalid',
216                                         BaseDatabaseResult::RESULT_NAME_EXCEPTION => FrameworkBootstrap::getDatabaseInstance()->getLastException()
217                                 );
218                         }
219                 }
220
221                 // Create an instance of a CachedDatabaseResult class with the given result
222                 // @TODO Minor: Update above comment to e.g. BaseDatabaseResult
223                 //* 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])));
224                 $resultInstance = ObjectFactory::createObjectByConfiguredName('database_result_class', array($result));
225
226                 // And return the instance
227                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FRONTEND: resultInstance=%s - EXIT!', $resultInstance->__toString()));
228                 return $resultInstance;
229         }
230
231         /**
232          * Count the numbers of rows we shall receive
233          *
234          * @param       $criteriaInstance       An instance of a Criteria class
235          * @param       $onlyKeys                       Only use these keys for a cache key
236          * @return      $numRows                        Numbers of rows of database entries
237          */
238         public function doSelectCountByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
239                 // Total numbers is -1 so we can distinglish between failed and valid queries
240                 $numRows = 0;
241
242                 // Get the result from above method
243                 $resultInstance = $this->doSelectByCriteria($criteriaInstance, $onlyKeys);
244
245                 // Was that query fine?
246                 if ($resultInstance->ifStatusIsOkay()) {
247                         // Then get the number of rows
248                         $numRows = $resultInstance->getAffectedRows();
249
250                         // Debug message
251                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRONTEND: numRows=' . $numRows);
252                 } // END - if
253
254                 // Return the result
255                 return $numRows;
256         }
257
258         /**
259          * Getter for primary key used in wrapped table
260          *
261          * @return      $primaryKey             Primary key used in wrapped table
262          */
263         public final function getPrimaryKeyValue () {
264                 // Get the table name and a database instance and ask for it
265                 $primaryKey = FrameworkBootstrap::getDatabaseInstance()->getPrimaryKeyOfTable($this->getTableName());
266
267                 // Return value
268                 return $primaryKey;
269         }
270
271         /**
272          * Count rows of this table
273          *
274          * @return      $count  Count of total rows in this table
275          */
276         public final function countTotalRows () {
277                 // Get the table name and a database instance and ask for it
278                 $count = FrameworkBootstrap::getDatabaseInstance()->countTotalRows($this->getTableName());
279
280                 // Return value
281                 return $count;
282         }
283
284         /**
285          * Removes non-public data from given array.
286          *
287          * @param       $data   An array with possible non-public data that needs to be removed.
288          * @return      $data   A cleaned up array with only public data.
289          */
290         public function removeNonPublicDataFromArray (array $data) {
291                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('WRAPPER[' . $this->__toString() . ']: Calling FrameworkBootstrap::getDatabaseInstance()->removeNonPublicDataFromArray(data) ...');
292                 $data = FrameworkBootstrap::getDatabaseInstance()->removeNonPublicDataFromArray($data);
293
294                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('WRAPPER[' . $this->__toString() . ']: data[]=' . gettype($data));
295                 return $data;
296         }
297
298 }