cd785bb7ca341fca74e297b9a712df52f902aaab
[core.git] / inc / classes / main / database / class_BaseDatabaseWrapper.php
1 <?php
2 /**
3  * A generic database wrapper
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class BaseDatabaseWrapper extends BaseFrameworkSystem {
25         /**
26          * Cache instance
27          */
28         private $cacheInstance = NULL;
29
30         /**
31          * Current table name to use
32          */
33         private $tableName = 'unknown';
34
35         /**
36          * Protected constructor
37          *
38          * @return      void
39          */
40         protected function __construct ($class) {
41                 // Call parent constructor
42                 parent::__construct($class);
43
44                 // Initialize the cache instance
45                 $this->initCacheInstance();
46         }
47
48         /**
49          * Initializes the cache instance with a new object
50          *
51          * @return      void
52          */
53         private final function initCacheInstance () {
54                 // Set the new instance
55                 $this->cacheInstance = CacheFactory::getFactory()->createConfiguredCache();
56         }
57
58         /**
59          * Setter for table name
60          *
61          * @param       $tableName      Name of table name to set
62          * @return      void
63          */
64         protected final function setTableName ($tableName) {
65                 $this->tableName = (string) $tableName;
66         }
67
68         /**
69          * Getter for table name
70          *
71          * @return      $tableName      Name of table name to set
72          */
73         protected final function getTableName () {
74                 return $this->tableName;
75         }
76
77         /**
78          * 'Inserts' a data set instance into a local file database folder
79          *
80          * @param       $dataSetInstance        A storeable data set
81          * @param       $onlyKeys                       Only use these keys for a cache key
82          * @return      void
83          */
84         protected function queryInsertDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = array()) {
85                 // First get a key suitable for our cache and extend it with this class name
86                 $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
87                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Using cache key ' . $cacheKey . ' for purging ...');
88
89                 // Does this key exists in cache?
90                 if ($this->cacheInstance->offsetExists($cacheKey)) {
91                         // Purge the cache
92                         $this->cacheInstance->purgeOffset($cacheKey);
93                 } // END - if
94
95                 // Handle it over to the middleware
96                 $this->getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
97         }
98
99         /**
100          * 'Updates' a data set instance with a database layer
101          *
102          * @param       $dataSetInstance        A storeable data set
103          * @param       $onlyKeys                       Only use these keys for a cache key
104          * @return      void
105          */
106         protected function queryUpdateDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = array()) {
107                 // First get a key suitable for our cache and extend it with this class name
108                 $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
109                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Using cache key ' . $cacheKey . ' for purging ...');
110
111                 // Does this key exists in cache?
112                 if ($this->cacheInstance->offsetExists($cacheKey)) {
113                         // Purge the cache
114                         $this->cacheInstance->purgeOffset($cacheKey);
115                 } // END - if
116
117                 // Handle it over to the middleware
118                 $this->getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
119         }
120
121         /**
122          * Getter for index key
123          *
124          * @return      $indexKey       Index key
125          */
126         public final function getIndexKey () {
127                 return $this->getDatabaseInstance()->getIndexKey();
128         }
129
130         /**
131          * Getter for last exception
132          *
133          * @return      $lastException  Last exception or NULL if none occured
134          */
135         public final function getLastException () {
136                 return $this->getDatabaseInstance()->getLastException();
137         }
138
139         /**
140          * Do a "select" query on the current table with the given search criteria and
141          * store it in cache for later usage
142          *
143          * @param       $criteriaInstance       An instance of a Criteria class
144          * @param       $onlyKeys                       Only use these keys for a cache key
145          * @return      $resultInstance         An instance of a database result class
146          */
147         public function doSelectByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
148                 // Default cache key if cache is not enabled
149                 $cacheKey = NULL;
150
151                 // Is the cache enabled?
152                 if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) {
153                         // First get a key suitable for our cache and extend it with this class name
154                         $cacheKey = $this->getCacheKeyByCriteria($criteriaInstance, $onlyKeys);
155                 } // END - if
156
157                 // Does this key exists in cache?
158                 if (($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) && ($this->cacheInstance->offsetExists($cacheKey, BaseDatabaseBackend::RESULT_INDEX_ROWS, 1))) {
159                         // Debug message
160                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Cache used for cacheKey=' . $cacheKey . ':' . print_r($this->cacheInstance->offsetGet($cacheKey), TRUE));
161
162                         // Then use this result
163                         $result = $this->cacheInstance->offsetGet($cacheKey);
164                 } else {
165                         // Debug message
166                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Quering database, cacheKey=' . $cacheKey);
167
168                         // Now it's time to ask the database layer for this select statement
169                         $result = $this->getDatabaseInstance()->doSelectByTableCriteria($this->getTableName(), $criteriaInstance);
170                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: result[]=' . gettype($result));
171
172                         // Cache the result if not null
173                         if (!is_null($result)) {
174                                 // A valid result has returned from the database layer
175                                 $this->cacheInstance->offsetSet($cacheKey, $result);
176                         } else {
177                                 // This invalid result must be wrapped
178                                 $result = array(
179                                         BaseDatabaseBackend::RESULT_INDEX_STATUS    => 'invalid',
180                                         BaseDatabaseBackend::RESULT_INDEX_EXCEPTION => $this->getDatabaseInstance()->getLastException()
181                                 );
182                         }
183                 }
184
185                 // Create an instance of a DatabaseResult class with the given result
186                 $resultInstance = ObjectFactory::createObjectByConfiguredName('database_result_class', array($result));
187
188                 // And return the instance
189                 return $resultInstance;
190         }
191
192         /**
193          * Count the numbers of rows we shall receive
194          *
195          * @param       $criteriaInstance       An instance of a Criteria class
196          * @param       $onlyKeys                       Only use these keys for a cache key
197          * @return      $numRows                        Numbers of rows of database entries
198          */
199         public function doSelectCountByCriteria (Criteria $criteriaInstance, $onlyKeys =  array()) {
200                 // Total numbers is -1 so we can distinglish between failed and valid queries
201                 $numRows = 0;
202
203                 // Get the result from above method
204                 $resultInstance = $this->doSelectByCriteria($criteriaInstance, $onlyKeys);
205
206                 // Was that query fine?
207                 if ($resultInstance->ifStatusIsOkay()) {
208                         // Then get the number of rows
209                         $numRows = $resultInstance->getAffectedRows();
210
211                         // Debug message
212                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: numRows=' . $numRows);
213                 } // END - if
214
215                 // Return the result
216                 return $numRows;
217         }
218
219         /**
220          * Getter for primary key used in wrapped table
221          *
222          * @return      $primaryKey             Primary key used in wrapped table
223          */
224         public final function getPrimaryKeyValue () {
225                 // Get the table name and a database instance and ask for it
226                 $primaryKey = $this->getDatabaseInstance()->getPrimaryKeyOfTable($this->getTableName());
227
228                 // Return 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                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('WRAPPER[' . $this->__toString() . ']: Calling this->getDatabaseInstance()->removeNonPublicDataFromArray(data) ...');
240                 $data = $this->getDatabaseInstance()->removeNonPublicDataFromArray($data);
241
242                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('WRAPPER[' . $this->__toString() . ']: data[]=' . gettype($data));
243                 return $data;
244         }
245 }
246
247 // [EOF]
248 ?>