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