]> 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                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for pathName=%s ...', $pathName));
368                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
369
370                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
371                         $resultData = array(
372                                 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
373                                 BaseDatabaseBackend::RESULT_INDEX_ROWS   => array()
374                         );
375
376                         // Initialize limit/skip
377                         $limitFound = 0;
378                         $skipFound = 0;
379                         $idx = 1;
380
381                         // Read the directory with some exceptions
382                         while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
383                                 // Does the extension match?
384                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
385                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
386                                         // Skip this file!
387                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
388                                         $directoryInstance->getDirectoryIteratorInstance()->next();
389                                         continue;
390                                 } // END - if
391
392                                 // Read the file
393                                 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
394
395                                 // Is this an array?
396                                 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
397                                 if (is_array($dataArray)) {
398                                         // Default is nothing found
399                                         $isFound = true;
400
401                                         // Search in the criteria with FMFW (First Matches, First Wins)
402                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataArray()=%d', count($dataArray)));
403                                         foreach ($dataArray as $key => $value) {
404                                                 // Make sure value is not bool
405                                                 assert(!is_bool($value));
406
407                                                 // Found one entry?
408                                                 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
409                                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
410                                         } // END - foreach
411
412                                         // Is all found?
413                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
414                                         if ($isFound === true) {
415                                                 // Shall we skip this entry?
416                                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d', $searchInstance->getSkip()));
417                                                 if ($searchInstance->getSkip() > 0) {
418                                                         // We shall skip some entries
419                                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: skipFound=%s', $skipFound));
420                                                         if ($skipFound < $searchInstance->getSkip()) {
421                                                                 // Skip this entry
422                                                                 $skipFound++;
423                                                                 break;
424                                                         } // END - if
425                                                 } // END - if
426
427                                                 // Set id number
428                                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
429                                                 $dataArray[$this->getIndexKey()] = $idx;
430
431                                                 // Entry found!
432                                                 array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
433
434                                                 // Count found entries up
435                                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: resultData[%s]()=%d', BaseDatabaseBackend::RESULT_INDEX_ROWS, count($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS])));
436                                                 $limitFound++;
437                                         } // END - if
438                                 } else {
439                                         // Throw an exception here
440                                         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);
441                                 }
442
443                                 // Count entry up
444                                 $idx++;
445
446                                 // Advance to next entry
447                                 $directoryInstance->getDirectoryIteratorInstance()->next();
448                         } // END - while
449
450                         // Close directory and throw the instance away
451                         $directoryInstance->closeDirectory();
452                         unset($directoryInstance);
453
454                         // Reset last exception
455                         $this->resetLastException();
456                 } catch (PathIsNoDirectoryException $e) {
457                         // Path not found means "table not found" for real databases...
458                         $this->setLastException($e);
459
460                         // So throw an SqlException here with faked error message
461                         throw new SqlException (array($this, sprintf('Table &#39;%s&#39; not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
462                 } catch (FrameworkException $e) {
463                         // Catch all exceptions and store them in last error
464                         $this->setLastException($e);
465                 }
466
467                 // Return the gathered result
468                 return $resultData;
469         }
470
471         /**
472          * "Inserts" a data set instance into a local file database folder
473          *
474          * @param       $dataSetInstance        A storeable data set
475          * @return      void
476          * @throws      SqlException    If an SQL error occurs
477          */
478         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
479                 // Try to save the request away
480                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
481                 try {
482                         // Create full path name
483                         $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
484
485                         // Write the data away
486                         $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
487
488                         // Update the primary key
489                         $this->updatePrimaryKey($dataSetInstance);
490
491                         // Reset last exception
492                         $this->resetLastException();
493                 } catch (FrameworkException $e) {
494                         // Catch all exceptions and store them in last error
495                         $this->setLastException($e);
496
497                         // Throw an SQL exception
498                         throw new SqlException(array(
499                                         $this,
500                                         sprintf('Cannot write data to table &#39;%s&#39;, is the table created?', $dataSetInstance->getTableName()),
501                                         self::DB_CODE_TABLE_UNWRITEABLE
502                                 ),
503                                 self::EXCEPTION_SQL_QUERY
504                         );
505                 }
506
507                 // Trace message
508                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
509         }
510
511         /**
512          * "Updates" a data set instance with a database layer
513          *
514          * @param       $dataSetInstance        A storeable data set
515          * @return      void
516          * @throws      SqlException    If an SQL error occurs
517          */
518         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
519                 // Create full path name
520                 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
521
522                 // Try all the requests
523                 try {
524                         // Get a file pointer instance
525                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
526
527                         // Initialize limit/skip
528                         $limitFound = 0;
529                         $skipFound = 0;
530
531                         // Get the criteria array from the dataset
532                         $searchArray = $dataSetInstance->getCriteriaArray();
533
534                         // Get search criteria
535                         $searchInstance = $dataSetInstance->getSearchInstance();
536
537                         // Read the directory with some exceptions
538                         while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
539                                 // Does the extension match?
540                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
541                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
542                                         // Skip this file!
543                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
544                                         $directoryInstance->getDirectoryIteratorInstance()->next();
545                                         continue;
546                                 } // END - if
547
548                                 // Open this file for reading
549                                 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
550                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
551
552                                 // Is this an array?
553                                 if (is_array($dataArray)) {
554                                         // Default is nothing found
555                                         $isFound = true;
556
557                                         // Search in the criteria with FMFW (First Matches, First Wins)
558                                         foreach ($dataArray as $key => $value) {
559                                                 // Make sure value is not bool
560                                                 assert(!is_bool($value));
561
562                                                 // Found one entry?
563                                                 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
564                                         } // END - foreach
565
566                                         // Is all found?
567                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: isFound=' . intval($isFound));
568                                         if ($isFound === true) {
569                                                 // Shall we skip this entry?
570                                                 if ($searchInstance->getSkip() > 0) {
571                                                         // We shall skip some entries
572                                                         if ($skipFound < $searchInstance->getSkip()) {
573                                                                 // Skip this entry
574                                                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Found entry, but skipping ...');
575                                                                 $skipFound++;
576                                                                 break;
577                                                         } // END - if
578                                                 } // END - if
579
580                                                 // Entry found, so update it
581                                                 foreach ($searchArray as $searchKey => $searchValue) {
582                                                         // Make sure the value is not bool again
583                                                         assert(!is_bool($searchValue));
584                                                         assert($searchKey != $this->indexKey);
585
586                                                         // Debug message + add/update it
587                                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
588                                                         $dataArray[$searchKey] = $searchValue;
589                                                 } // END - foreach
590
591                                                 // Write the data to a local file
592                                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing dataArray()=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
593                                                 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
594
595                                                 // Count found entries up
596                                                 $limitFound++;
597                                         } // END - if
598                                 } // END - if
599
600                                 // Advance to next entry
601                                 $directoryInstance->getDirectoryIteratorInstance()->next();
602                         } // END - while
603
604                         // Close the file pointer
605                         $directoryInstance->closeDirectory();
606
607                         // Update the primary key
608                         $this->updatePrimaryKey($dataSetInstance);
609
610                         // Reset last exception
611                         $this->resetLastException();
612                 } catch (FrameworkException $e) {
613                         // Catch all exceptions and store them in last error
614                         $this->setLastException($e);
615
616                         // Throw an SQL exception
617                         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);
618                 }
619         }
620
621         /**
622          * Getter for primary key of specified table or if not found null will be
623          * returned. This must be database-specific.
624          *
625          * @param       $tableName              Name of the table we need the primary key from
626          * @return      $primaryKey             Primary key column of the given table
627          * @todo        Rename method to getPrimaryKeyFromTableInfo()
628          */
629         public function getPrimaryKeyOfTable ($tableName) {
630                 // Default key is null
631                 $primaryKey = NULL;
632
633                 // Does the table information exist?
634                 if (isset($this->tableInfo[$tableName])) {
635                         // Then return the primary key
636                         $primaryKey = $this->tableInfo[$tableName]['primary'];
637                 } // END - if
638
639                 // Return the column
640                 return $primaryKey;
641         }
642
643         /**
644          * Removes non-public data from given array.
645          *
646          * @param       $data   An array with possible non-public data that needs to be removed.
647          * @return      $data   A cleaned up array with only public data.
648          * @todo        Add more generic non-public data for removal
649          */
650         public function removeNonPublicDataFromArray (array $data) {
651                 // Remove '__idx'
652                 unset($data[$this->indexKey]);
653
654                 // Return it
655                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: data[' . gettype($data) . ']='.print_r($data, true));
656                 return $data;
657         }
658
659         /**
660          * Counts total rows of given table
661          *
662          * @param       $tableName      Table name
663          * @return      $count          Total rows of given table
664          */
665         public function countTotalRows($tableName) {
666                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ' - CALLED!');
667
668                 // Create full path name
669                 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
670
671                 // Try all the requests
672                 try {
673                         // Get a file pointer instance
674                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
675
676                         // Initialize counter
677                         $count = 0;
678
679                         // Read the directory with some exceptions
680                         while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
681                                 // Does the extension match?
682                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
683                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
684                                         // Debug message
685                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
686                                         // Skip this file!
687                                         continue;
688                                 } // END - if
689
690                                 // Count this row up
691                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
692                                 $count++;
693                         } // END - while
694                 } catch (FrameworkException $e) {
695                         // Catch all exceptions and store them in last error
696                         $this->setLastException($e);
697
698                         // Throw an SQL exception
699                         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);
700                 }
701
702                 // Return count
703                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');
704                 return $count;
705         }
706
707 }