]> git.mxchange.org Git - core.git/blob - framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php
Continued:
[core.git] / framework / main / classes / database / backend / lfdb_legacy / class_CachedLocalFileDatabase.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Database\Backend\Lfdb;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Criteria\Criteria;
7 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
8 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
9 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
10 use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
11 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
12 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
13 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
14
15 // Import SPL stuff
16 use \SplFileInfo;
17
18 /**
19  * Database backend class for storing objects in locally created files.
20  *
21  * This class serializes arrays stored in the dataset instance and saves them
22  * to local files. Every file (except 'info') represents a single line. Every
23  * directory within the 'db' (base) directory represents a table.
24  *
25  * A configurable 'file_io_class' is being used as "storage backend".
26  *
27  * @author              Roland Haeder <webmaster@shipsimu.org>
28  * @version             0.0.0
29  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
30  * @license             GNU GPL 3.0 or any newer version
31  * @link                http://www.shipsimu.org
32  *
33  * This program is free software: you can redistribute it and/or modify
34  * it under the terms of the GNU General Public License as published by
35  * the Free Software Foundation, either version 3 of the License, or
36  * (at your option) any later version.
37  *
38  * This program is distributed in the hope that it will be useful,
39  * but WITHOUT ANY WARRANTY; without even the implied warranty of
40  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41  * GNU General Public License for more details.
42  *
43  * You should have received a copy of the GNU General Public License
44  * along with this program. If not, see <http://www.gnu.org/licenses/>.
45  */
46 class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
47         /**
48          * The file's extension
49          */
50         private $fileExtension = 'serialized';
51
52         /**
53          * The last read file's name
54          */
55         private $lastFile = '';
56
57         /**
58          * The last read file's content including header information
59          */
60         private $lastContents = array();
61
62         /**
63          * Whether the "connection is already up
64          */
65         private $alreadyConnected = false;
66
67         /**
68          * Table information array
69          */
70         private $tableInfo = array();
71
72         /**
73          * Element for index
74          */
75         private $indexKey = '__idx';
76
77         /**
78          * The protected constructor. Do never instance from outside! You need to
79          * set a local file path. The class will then validate it.
80          *
81          * @return      void
82          */
83         protected function __construct () {
84                 // Call parent constructor
85                 parent::__construct(__CLASS__);
86         }
87
88         /**
89          * Create an object of CachedLocalFileDatabase and set the save path from
90          * configuration for local files.
91          *
92          * @return      $databaseInstance       An instance of CachedLocalFileDatabase
93          */
94         public static final function createCachedLocalFileDatabase () {
95                 // Get an instance
96                 $databaseInstance = new CachedLocalFileDatabase();
97
98                 // Get a new compressor channel instance
99                 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
100
101                 // Set the compressor channel
102                 $databaseInstance->setCompressorChannel($compressorInstance);
103
104                 // Get a file IO handler
105                 $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
106
107                 // ... and set it
108                 $databaseInstance->setFileIoInstance($fileIoInstance);
109
110                 // "Connect" to the database
111                 $databaseInstance->connectToDatabase();
112
113                 // Return database instance
114                 return $databaseInstance;
115         }
116
117         /**
118          * Setter for the last read file
119          *
120          * @param       $infoInstance   The FQFN of the last read file
121          * @return      void
122          */
123         private final function setLastFile (SplFileInfo $infoInstance) {
124                 // Cast string and set it
125                 $this->lastFile = $infoInstance;
126         }
127
128         /**
129          * Getter for last read file
130          *
131          * @return      $lastFile       The last read file's name with full path
132          */
133         public final function getLastFile () {
134                 return $this->lastFile;
135         }
136
137         /**
138          * Setter for contents of the last read file
139          *
140          * @param               $contents       An array with header and data elements
141          * @return      void
142          */
143         private final function setLastFileContents (array $contents) {
144                 // Set array
145                 $this->lastContents = $contents;
146         }
147
148         /**
149          * Getter for last read file's content as an array
150          *
151          * @return      $lastContent    The array with elements 'header' and 'data'.
152          */
153         public final function getLastContents () {
154                 return $this->lastContents;
155         }
156
157         /**
158          * Getter for file extension
159          *
160          * @return      $fileExtension  The array with elements 'header' and 'data'.
161          */
162         public final function getFileExtension () {
163                 return $this->fileExtension;
164         }
165
166         /**
167          * Getter for index key
168          *
169          * @return      $indexKey       Index key
170          */
171         public final function getIndexKey () {
172                 return $this->indexKey;
173         }
174
175         /**
176          * Reads a local data file  and returns it's contents in an array
177          *
178          * @param       $infoInstance   An instance of a SplFileInfo class
179          * @return      $dataArray
180          */
181         private function getDataArrayFromFile (SplFileInfo $infoInstance) {
182                 // Debug message
183                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Reading elements from database file ' . $infoInstance . ' ...');
184
185                 // Init compressed data
186                 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
187                 $compressedData = $compressedData['data'];
188
189                 // Decompress it
190                 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
191
192                 // Unserialize it
193                 $dataArray = json_decode($serializedData, true);
194
195                 // Debug message
196                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
197                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
198
199                 // Finally return it
200                 return $dataArray;
201         }
202
203         /**
204          * Writes data array to local file
205          *
206          * @param       $infoInstance   An instance of a SplFileInfo class
207          * @param       $dataArray      An array with all the data we shall write
208          * @return      void
209          */
210         private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
211                 // Debug message
212                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
213                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
214
215                 // Serialize and compress it
216                 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(json_encode($dataArray));
217
218                 // Write this data BASE64 encoded to the file
219                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing ' . strlen($compressedData) . ' bytes ...');
220                 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
221
222                 // Debug message
223                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file completed.');
224         }
225
226         /**
227          * Getter for table information file contents or an empty if info file was not created
228          *
229          * @param       $dataSetInstance        An instance of a database set class
230          * @return      $infoArray                      An array with all table informations
231          */
232         private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
233                 // Default content is no data
234                 $infoArray = array();
235
236                 // Create FQFN for getting the table information file
237                 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
238
239                 // Get the file contents
240                 try {
241                         $infoArray = $this->getDataArrayFromFile($infoInstance);
242                 } catch (FileNotFoundException $e) {
243                         // Not found, so ignore it here
244                 }
245
246                 // ... and return it
247                 return $infoArray;
248         }
249
250         /**
251          * Generates a file info class from given dataset instance and string
252          *
253          * @param       $dataSetInstance        An instance of a database set class
254          * @param       $rowName                        Name of the row
255          * @return      $infoInstance           An instance of a SplFileInfo class
256          */
257         private function generateFileFromDataSet (Criteria $dataSetInstance, $rowName) {
258                 // Instanciate new file object
259                 $infoInstance = new SplFileInfo($this->getConfigInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
260
261                 // Return it
262                 return $infoInstance;
263         }
264
265         /**
266          * Creates the table info file from given dataset instance
267          *
268          * @param       $dataSetInstance        An instance of a database set class
269          * @return      void
270          */
271         private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
272                 // Create FQFN for creating the table information file
273                 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
274
275                 // Get the data out from dataset in a local array
276                 $this->tableInfo[$dataSetInstance->getTableName()] = array(
277                         'primary'      => $dataSetInstance->getPrimaryKey(),
278                         'created'      => time(),
279                         'last_updated' => time()
280                 );
281
282                 // Write the data to the file
283                 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
284         }
285
286         /**
287          * Updates the table info file from given dataset instance
288          *
289          * @param       $dataSetInstance        An instance of a database set class
290          * @return      void
291          */
292         private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
293                 // Get table name from criteria
294                 $tableName = $dataSetInstance->getTableName();
295
296                 // Create FQFN for creating the table information file
297                 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
298
299                 // Get the data out from dataset in a local array
300                 $this->tableInfo[$tableName]['primary']      = $dataSetInstance->getPrimaryKey();
301                 $this->tableInfo[$tableName]['last_updated'] = time();
302
303                 // Write the data to the file
304                 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
305         }
306
307         /**
308          * Updates the primary key information or creates the table info file if not found
309          *
310          * @param       $dataSetInstance        An instance of a database set class
311          * @return      void
312          */
313         private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
314                 // Get table name from criteria
315                 $tableName = $dataSetInstance->getTableName();
316
317                 // Get the information array from lower method
318                 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
319
320                 // Is the primary key there?
321                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableInfo=' . print_r($this->tableInfo, true));
322                 if (!isset($this->tableInfo[$tableName]['primary'])) {
323                         // Then create the info file
324                         $this->createTableInfoFile($dataSetInstance);
325                 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
326                         // Set the array element
327                         $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
328
329                         // Update the entry
330                         $this->updateTableInfoFile($dataSetInstance);
331                 }
332         }
333
334         /**
335          * Makes sure that the database connection is alive
336          *
337          * @return      void
338          * @todo        Do some checks on the database directory and files here
339          */
340         public function connectToDatabase () {
341         }
342
343         /**
344          * Starts a SELECT query on the database by given return type, table name
345          * and search criteria
346          *
347          * @param       $tableName                      Name of the database table
348          * @param       $searchInstance         Local search criteria class
349          * @return      $resultData                     Result data of the query
350          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
351          * @throws      SqlException                                    If an 'SQL error' occurs
352          */
353         public function querySelect ($tableName, LocalSearchCriteria $searchInstance) {
354                 // The result is null by any errors
355                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
356                 $resultData = NULL;
357
358                 // Create full path name
359                 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
360
361                 /*
362                  * A 'select' query is not that easy on local files, so first try to
363                  * find the 'table' which is in fact a directory on the server
364                  */
365                 try {
366                         // Get a directory pointer instance
367                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
368
369                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
370                         $resultData = array(
371                                 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
372                                 BaseDatabaseBackend::RESULT_INDEX_ROWS   => array()
373                         );
374
375                         // Initialize limit/skip
376                         $limitFound = 0;
377                         $skipFound = 0;
378                         $idx = 1;
379
380                         // Read the directory with some exceptions
381                         while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
382                                 // Does the extension match?
383                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInstance.extension=%s,this->getFileExtension()=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
384                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
385                                         // Skip this file!
386                                         continue;
387                                 } // END - if
388
389                                 // Read the file
390                                 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
391
392                                 // Is this an array?
393                                 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
394                                 if (is_array($dataArray)) {
395                                         // Default is nothing found
396                                         $isFound = true;
397
398                                         // Search in the criteria with FMFW (First Matches, First Wins)
399                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataArray()=%d', count($dataArray)));
400                                         foreach ($dataArray as $key => $value) {
401                                                 // Make sure value is not bool
402                                                 assert(!is_bool($value));
403
404                                                 // Found one entry?
405                                                 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
406                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
407                                         } // END - foreach
408
409                                         // Is all found?
410                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
411                                         if ($isFound === true) {
412                                                 // Shall we skip this entry?
413                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d', $searchInstance->getSkip()));
414                                                 if ($searchInstance->getSkip() > 0) {
415                                                         // We shall skip some entries
416                                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: skipFound=%s', $skipFound));
417                                                         if ($skipFound < $searchInstance->getSkip()) {
418                                                                 // Skip this entry
419                                                                 $skipFound++;
420                                                                 break;
421                                                         } // END - if
422                                                 } // END - if
423
424                                                 // Set id number
425                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
426                                                 $dataArray[$this->getIndexKey()] = $idx;
427
428                                                 // Entry found!
429                                                 array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
430
431                                                 // Count found entries up
432                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: resultData[%s]()=%d', BaseDatabaseBackend::RESULT_INDEX_ROWS, count($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS])));
433                                                 $limitFound++;
434                                         } // END - if
435                                 } else {
436                                         // Throw an exception here
437                                         throw new SqlException(array($this, sprintf('File &#39;%s&#39; contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
438                                 }
439
440                                 // Count entry up
441                                 $idx++;
442                         } // END - while
443
444                         // Close directory and throw the instance away
445                         $directoryInstance->closeDirectory();
446                         unset($directoryInstance);
447
448                         // Reset last exception
449                         $this->resetLastException();
450                 } catch (PathIsNoDirectoryException $e) {
451                         // Path not found means "table not found" for real databases...
452                         $this->setLastException($e);
453
454                         // So throw an SqlException here with faked error message
455                         throw new SqlException (array($this, sprintf('Table &#39;%s&#39; not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
456                 } catch (FrameworkException $e) {
457                         // Catch all exceptions and store them in last error
458                         $this->setLastException($e);
459                 }
460
461                 // Return the gathered result
462                 return $resultData;
463         }
464
465         /**
466          * "Inserts" a data set instance into a local file database folder
467          *
468          * @param       $dataSetInstance        A storeable data set
469          * @return      void
470          * @throws      SqlException    If an SQL error occurs
471          */
472         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
473                 // Try to save the request away
474                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
475                 try {
476                         // Create full path name
477                         $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
478
479                         // Write the data away
480                         $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
481
482                         // Update the primary key
483                         $this->updatePrimaryKey($dataSetInstance);
484
485                         // Reset last exception
486                         $this->resetLastException();
487                 } catch (FrameworkException $e) {
488                         // Catch all exceptions and store them in last error
489                         $this->setLastException($e);
490
491                         // Throw an SQL exception
492                         throw new SqlException(array(
493                                         $this,
494                                         sprintf('Cannot write data to table &#39;%s&#39;, is the table created?', $dataSetInstance->getTableName()),
495                                         self::DB_CODE_TABLE_UNWRITEABLE
496                                 ),
497                                 self::EXCEPTION_SQL_QUERY
498                         );
499                 }
500
501                 // Trace message
502                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
503         }
504
505         /**
506          * "Updates" a data set instance with a database layer
507          *
508          * @param       $dataSetInstance        A storeable data set
509          * @return      void
510          * @throws      SqlException    If an SQL error occurs
511          */
512         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
513                 // Create full path name
514                 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
515
516                 // Try all the requests
517                 try {
518                         // Get a file pointer instance
519                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
520
521                         // Initialize limit/skip
522                         $limitFound = 0;
523                         $skipFound = 0;
524
525                         // Get the criteria array from the dataset
526                         $searchArray = $dataSetInstance->getCriteriaArray();
527
528                         // Get search criteria
529                         $searchInstance = $dataSetInstance->getSearchInstance();
530
531                         // Read the directory with some exceptions
532                         while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
533                                 // Debug message
534                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
535
536                                 // Does the extension match?
537                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
538                                         // Debug message
539                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
540                                         // Skip this file!
541                                         continue;
542                                 } // END - if
543
544                                 // Open this file for reading
545                                 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
546                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
547
548                                 // Is this an array?
549                                 if (is_array($dataArray)) {
550                                         // Default is nothing found
551                                         $isFound = true;
552
553                                         // Search in the criteria with FMFW (First Matches, First Wins)
554                                         foreach ($dataArray as $key => $value) {
555                                                 // Make sure value is not bool
556                                                 assert(!is_bool($value));
557
558                                                 // Found one entry?
559                                                 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
560                                         } // END - foreach
561
562                                         // Is all found?
563                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: isFound=' . intval($isFound));
564                                         if ($isFound === true) {
565                                                 // Shall we skip this entry?
566                                                 if ($searchInstance->getSkip() > 0) {
567                                                         // We shall skip some entries
568                                                         if ($skipFound < $searchInstance->getSkip()) {
569                                                                 // Skip this entry
570                                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Found entry, but skipping ...');
571                                                                 $skipFound++;
572                                                                 break;
573                                                         } // END - if
574                                                 } // END - if
575
576                                                 // Entry found, so update it
577                                                 foreach ($searchArray as $searchKey => $searchValue) {
578                                                         // Make sure the value is not bool again
579                                                         assert(!is_bool($searchValue));
580                                                         assert($searchKey != $this->indexKey);
581
582                                                         // Debug message + add/update it
583                                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
584                                                         $dataArray[$searchKey] = $searchValue;
585                                                 } // END - foreach
586
587                                                 // Write the data to a local file
588                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing dataArray()=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
589                                                 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
590
591                                                 // Count found entries up
592                                                 $limitFound++;
593                                         } // END - if
594                                 } // END - if
595                         } // END - while
596
597                         // Close the file pointer
598                         $directoryInstance->closeDirectory();
599
600                         // Update the primary key
601                         $this->updatePrimaryKey($dataSetInstance);
602
603                         // Reset last exception
604                         $this->resetLastException();
605                 } catch (FrameworkException $e) {
606                         // Catch all exceptions and store them in last error
607                         $this->setLastException($e);
608
609                         // Throw an SQL exception
610                         throw new SqlException(array($this, sprintf('Cannot write data to table &#39;%s&#39;, is the table created? Exception: %s, message:%s', $dataSetInstance->getTableName(), $e->__toString(), $e->getMessage()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
611                 }
612         }
613
614         /**
615          * Getter for primary key of specified table or if not found null will be
616          * returned. This must be database-specific.
617          *
618          * @param       $tableName              Name of the table we need the primary key from
619          * @return      $primaryKey             Primary key column of the given table
620          * @todo        Rename method to getPrimaryKeyFromTableInfo()
621          */
622         public function getPrimaryKeyOfTable ($tableName) {
623                 // Default key is null
624                 $primaryKey = NULL;
625
626                 // Does the table information exist?
627                 if (isset($this->tableInfo[$tableName])) {
628                         // Then return the primary key
629                         $primaryKey = $this->tableInfo[$tableName]['primary'];
630                 } // END - if
631
632                 // Return the column
633                 return $primaryKey;
634         }
635
636         /**
637          * Removes non-public data from given array.
638          *
639          * @param       $data   An array with possible non-public data that needs to be removed.
640          * @return      $data   A cleaned up array with only public data.
641          * @todo        Add more generic non-public data for removal
642          */
643         public function removeNonPublicDataFromArray (array $data) {
644                 // Remove '__idx'
645                 unset($data[$this->indexKey]);
646
647                 // Return it
648                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: data[' . gettype($data) . ']='.print_r($data, true));
649                 return $data;
650         }
651
652         /**
653          * Counts total rows of given table
654          *
655          * @param       $tableName      Table name
656          * @return      $count          Total rows of given table
657          */
658         public function countTotalRows($tableName) {
659                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ' - CALLED!');
660
661                 // Create full path name
662                 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
663
664                 // Try all the requests
665                 try {
666                         // Get a file pointer instance
667                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
668
669                         // Initialize counter
670                         $count = 0;
671
672                         // Read the directory with some exceptions
673                         while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
674                                 // Debug message
675                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
676
677                                 // Does the extension match?
678                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
679                                         // Debug message
680                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
681                                         // Skip this file!
682                                         continue;
683                                 } // END - if
684
685                                 // Count this row up
686                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
687                                 $count++;
688                         } // END - while
689                 } catch (FrameworkException $e) {
690                         // Catch all exceptions and store them in last error
691                         $this->setLastException($e);
692
693                         // Throw an SQL exception
694                         throw new SqlException(array($this, sprintf('Cannot count on table &#39;%s&#39;, is the table created?', $dataSetInstance->getTableName()), self::DB_CODE_TABLE_NOT_FOUND), self::EXCEPTION_SQL_QUERY);
695                 }
696
697                 // Return count
698                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');
699                 return $count;
700         }
701
702 }