3 namespace Org\Mxchange\CoreFramework\Database\Backend\Lfdb;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Criteria\Criteria;
8 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
9 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
10 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
11 use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
12 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
13 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
14 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
15 use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
16 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
22 * Database backend class for storing objects in locally created files.
24 * This class serializes arrays stored in the dataset instance and saves them
25 * to local files. Every file (except 'info') represents a single line. Every
26 * directory within the 'db' (base) directory represents a table.
28 * A configurable 'file_io_class' is being used as "storage backend".
30 * @author Roland Haeder <webmaster@shipsimu.org>
32 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
33 * @license GNU GPL 3.0 or any newer version
34 * @link http://www.shipsimu.org
36 * This program is free software: you can redistribute it and/or modify
37 * it under the terms of the GNU General Public License as published by
38 * the Free Software Foundation, either version 3 of the License, or
39 * (at your option) any later version.
41 * This program is distributed in the hope that it will be useful,
42 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 * GNU General Public License for more details.
46 * You should have received a copy of the GNU General Public License
47 * along with this program. If not, see <http://www.gnu.org/licenses/>.
49 class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
51 * The file's extension
53 private $fileExtension = 'serialized';
56 * The last read file's name
58 private $lastFile = '';
61 * The last read file's content including header information
63 private $lastContents = array();
66 * Whether the "connection is already up
68 private $alreadyConnected = false;
71 * Table information array
73 private $tableInfo = array();
78 private $indexKey = '__idx';
81 * The file I/O instance for the template loader
83 private $fileIoInstance = NULL;
86 * A Compressor instance
88 private $compressorChannelInstance = NULL;
91 * The protected constructor. Do never instance from outside! You need to
92 * set a local file path. The class will then validate it.
96 protected function __construct () {
97 // Call parent constructor
98 parent::__construct(__CLASS__);
102 * Create an object of CachedLocalFileDatabase and set the save path from
103 * configuration for local files.
105 * @return $databaseInstance An instance of CachedLocalFileDatabase
107 public static final function createCachedLocalFileDatabase () {
109 $databaseInstance = new CachedLocalFileDatabase();
111 // Get a new compressor channel instance
112 $compressorChannelInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
114 // Set the compressor channel
115 $databaseInstance->setCompressorChannelInstance($compressorChannelInstance);
117 // Get a file IO handler
118 $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
121 $databaseInstance->setFileIoInstance($fileIoInstance);
123 // "Connect" to the database
124 $databaseInstance->connectToDatabase();
126 // Return database instance
127 return $databaseInstance;
131 * Setter for the last read file
133 * @param $infoInstance The FQFN of the last read file
136 private final function setLastFile (SplFileInfo $infoInstance) {
137 // Cast string and set it
138 $this->lastFile = $infoInstance;
142 * Getter for last read file
144 * @return $lastFile The last read file's name with full path
146 public final function getLastFile () {
147 return $this->lastFile;
151 * Setter for contents of the last read file
153 * @param $contents An array with header and data elements
156 private final function setLastFileContents (array $contents) {
158 $this->lastContents = $contents;
162 * Getter for last read file's content as an array
164 * @return $lastContent The array with elements 'header' and 'data'.
166 public final function getLastContents () {
167 return $this->lastContents;
171 * Getter for file extension
173 * @return $fileExtension The array with elements 'header' and 'data'.
175 public final function getFileExtension () {
176 return $this->fileExtension;
180 * Getter for index key
182 * @return $indexKey Index key
184 public final function getIndexKey () {
185 return $this->indexKey;
188 * Private getter for file IO instance
190 * @return $fileIoInstance An instance to the file I/O sub-system
192 protected final function getFileIoInstance () {
193 return $this->fileIoInstance;
197 * Setter for file I/O instance
199 * @param $fileIoInstance An instance to the file I/O sub-system
202 public final function setFileIoInstance (IoHandler $fileIoInstance) {
203 $this->fileIoInstance = $fileIoInstance;
207 * Setter for compressor channel
209 * @param $compressorChannelInstance An instance of a CompressorChannel class
212 protected final function setCompressorChannelInstance (CompressorChannel $compressorChannelInstance) {
213 $this->compressorChannelInstance = $compressorChannelInstance;
217 * Getter for compressor channel
219 * @return $compressorChannelInstance An instance of a CompressorChannel class
221 protected final function getCompressorChannelInstance () {
222 return $this->compressorChannelInstance;
226 * Reads a local data file and returns it's contents in an array
228 * @param $infoInstance An instance of a SplFileInfo class
231 private function getDataArrayFromFile (SplFileInfo $infoInstance) {
232 // Init compressed data
233 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Reading elements from database file ' . $infoInstance . ' ...');
234 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
235 $compressedData = $compressedData['data'];
238 $serializedData = $this->getCompressorChannelInstance()->getCompressor()->decompressStream($compressedData);
241 $dataArray = json_decode($serializedData, true);
244 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
245 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
250 * Writes data array to local file
252 * @param $infoInstance An instance of a SplFileInfo class
253 * @param $dataArray An array with all the data we shall write
256 private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
257 // Serialize and compress it
258 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
259 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
260 $compressedData = $this->getCompressorChannelInstance()->getCompressor()->compressStream(json_encode($dataArray));
262 // Write this data BASE64 encoded to the file
263 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing ' . strlen($compressedData) . ' bytes ...');
264 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
267 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file completed.');
271 * Getter for table information file contents or an empty if info file was not created
273 * @param $dataSetInstance An instance of a database set class
274 * @return $infoArray An array with all table informations
276 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
277 // Default content is no data
278 $infoArray = array();
280 // Create FQFN for getting the table information file
281 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
283 // Get the file contents
285 $infoArray = $this->getDataArrayFromFile($infoInstance);
286 } catch (FileNotFoundException $e) {
287 // Not found, so ignore it here
295 * Generates a file info class from given dataset instance and string
297 * @param $dataSetInstance An instance of a database set class
298 * @param $rowName Name of the row
299 * @return $infoInstance An instance of a SplFileInfo class
301 private function generateFileFromDataSet (Criteria $dataSetInstance, string $rowName) {
302 // Instanciate new file object
303 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
306 return $infoInstance;
310 * Creates the table info file from given dataset instance
312 * @param $dataSetInstance An instance of a database set class
315 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
316 // Create FQFN for creating the table information file
317 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
319 // Get the data out from dataset in a local array
320 $this->tableInfo[$dataSetInstance->getTableName()] = array(
321 'primary' => $dataSetInstance->getPrimaryKey(),
323 'last_updated' => time()
326 // Write the data to the file
327 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
331 * Updates the table info file from given dataset instance
333 * @param $dataSetInstance An instance of a database set class
336 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
337 // Get table name from criteria
338 $tableName = $dataSetInstance->getTableName();
340 // Create FQFN for creating the table information file
341 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
343 // Get the data out from dataset in a local array
344 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
345 $this->tableInfo[$tableName]['last_updated'] = time();
347 // Write the data to the file
348 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
352 * Updates the primary key information or creates the table info file if not found
354 * @param $dataSetInstance An instance of a database set class
357 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
358 // Get table name from criteria
359 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
360 $tableName = $dataSetInstance->getTableName();
362 // Get the information array from lower method
363 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s', $tableName));
364 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
366 // Is the primary key there?
367 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableInfo=' . print_r($this->tableInfo, true));
368 if (!isset($this->tableInfo[$tableName]['primary'])) {
369 // Then create the info file
370 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Creating info table for tableName=%s ...', $tableName));
371 $this->createTableInfoFile($dataSetInstance);
372 } elseif ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
373 // Set the array element
374 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
375 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
378 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Updating info table for tableName=%s ...', $tableName));
379 $this->updateTableInfoFile($dataSetInstance);
383 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
387 * Makes sure that the database connection is alive
390 * @todo Do some checks on the database directory and files here
392 public function connectToDatabase () {
396 * Starts a SELECT query on the database by given return type, table name
397 * and search criteria
399 * @param $tableName Name of the database table
400 * @param $searchInstance Local search criteria class
401 * @return $resultData Result data of the query
402 * @throws UnsupportedCriteriaException If the criteria is unsupported
403 * @throws SqlException If an 'SQL error' occurs
405 public function querySelect (string $tableName, LocalSearchCriteria $searchInstance) {
406 // The result is null by any errors
407 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
410 // Create full path name
411 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
414 * A 'select' query is not that easy on local files, so first try to
415 * find the 'table' which is in fact a directory on the server
418 // Get a directory pointer instance
419 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for pathName=%s ...', $pathName));
420 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
422 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
424 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
425 BaseDatabaseBackend::RESULT_INDEX_ROWS => array()
428 // Initialize limit/skip
433 // Read the directory with some exceptions
434 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
435 // Does the extension match?
436 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
437 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
439 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
440 $directoryInstance->getDirectoryIteratorInstance()->next();
445 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
448 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
449 if (is_array($dataArray)) {
450 // Default is nothing found
453 // Search in the criteria with FMFW (First Matches, First Wins)
454 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataArray()=%d', count($dataArray)));
455 foreach ($dataArray as $key => $value) {
456 // Make sure value is not bool
457 assert(!is_bool($value));
460 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
461 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
465 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
466 if ($isFound === true) {
467 // Shall we skip this entry?
468 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d', $searchInstance->getSkip()));
469 if ($searchInstance->getSkip() > 0) {
470 // We shall skip some entries
471 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: skipFound=%s', $skipFound));
472 if ($skipFound < $searchInstance->getSkip()) {
480 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
481 $dataArray[$this->getIndexKey()] = $idx;
484 array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
486 // Count found entries up
487 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: resultData[%s]()=%d', BaseDatabaseBackend::RESULT_INDEX_ROWS, count($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS])));
491 // Throw an exception here
492 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
498 // Advance to next entry
499 $directoryInstance->getDirectoryIteratorInstance()->next();
502 // Close directory and throw the instance away
503 $directoryInstance->closeDirectory();
504 unset($directoryInstance);
506 // Reset last exception
507 $this->resetLastException();
508 } catch (PathIsNoDirectoryException $e) {
509 // Path not found means "table not found" for real databases...
510 $this->setLastException($e);
512 // So throw an SqlException here with faked error message
513 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
514 } catch (FrameworkException $e) {
515 // Catch all exceptions and store them in last error
516 $this->setLastException($e);
519 // Return the gathered result
524 * "Inserts" a data set instance into a local file database folder
526 * @param $dataSetInstance A storeable data set
528 * @throws SqlException If an SQL error occurs
530 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
531 // Try to save the request away
532 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
534 // Create full path name
535 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
537 // Write the data away
538 $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
540 // Update the primary key
541 $this->updatePrimaryKey($dataSetInstance);
543 // Reset last exception
544 $this->resetLastException();
545 } catch (FrameworkException $e) {
546 // Catch all exceptions and store them in last error
547 $this->setLastException($e);
549 // Throw an SQL exception
550 throw new SqlException(array(
552 sprintf('Cannot write data to table '%s', is the table created?', $dataSetInstance->getTableName()),
553 self::DB_CODE_TABLE_UNWRITEABLE
555 self::EXCEPTION_SQL_QUERY
560 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
564 * "Updates" a data set instance with a database layer
566 * @param $dataSetInstance An instance of a StorableCriteria class
568 * @throws SqlException If an SQL error occurs
570 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
571 // Create full path name
572 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
574 // Try all the requests
576 // Get a file pointer instance
577 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
579 // Initialize limit/skip
583 // Get the criteria array from the dataset
584 $searchArray = $dataSetInstance->getCriteriaArray();
586 // Get search criteria
587 $searchInstance = $dataSetInstance->getSearchInstance();
589 // Read the directory with some exceptions
590 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
591 // Does the extension match?
592 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
593 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
595 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
596 $directoryInstance->getDirectoryIteratorInstance()->next();
600 // Open this file for reading
601 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
602 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
605 if (is_array($dataArray)) {
606 // Default is nothing found
609 // Search in the criteria with FMFW (First Matches, First Wins)
610 foreach ($dataArray as $key => $value) {
611 // Make sure value is not bool
612 assert(!is_bool($value));
615 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
619 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: isFound=' . intval($isFound));
620 if ($isFound === true) {
621 // Shall we skip this entry?
622 if ($searchInstance->getSkip() > 0) {
623 // We shall skip some entries
624 if ($skipFound < $searchInstance->getSkip()) {
626 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Found entry, but skipping ...');
632 // Entry found, so update it
633 foreach ($searchArray as $searchKey => $searchValue) {
634 // Make sure the value is not bool again
635 assert(!is_bool($searchValue));
636 assert($searchKey != $this->indexKey);
638 // Debug message + add/update it
639 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
640 $dataArray[$searchKey] = $searchValue;
643 // Write the data to a local file
644 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing dataArray()=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
645 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
647 // Count found entries up
652 // Advance to next entry
653 $directoryInstance->getDirectoryIteratorInstance()->next();
656 // Close the file pointer
657 $directoryInstance->closeDirectory();
659 // Update the primary key
660 $this->updatePrimaryKey($dataSetInstance);
662 // Reset last exception
663 $this->resetLastException();
664 } catch (FrameworkException $e) {
665 // Catch all exceptions and store them in last error
666 $this->setLastException($e);
668 // Throw an SQL exception
669 throw new SqlException(array($this, sprintf('Cannot write data to table '%s', is the table created? Exception: %s, message:%s', $dataSetInstance->getTableName(), $e->__toString(), $e->getMessage()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
674 * Getter for primary key of specified table or if not found null will be
675 * returned. This must be database-specific.
677 * @param $tableName Name of the table we need the primary key from
678 * @return $primaryKey Primary key column of the given table
679 * @todo Rename method to getPrimaryKeyFromTableInfo()
681 public function getPrimaryKeyOfTable (string $tableName) {
682 // Default key is null
685 // Does the table information exist?
686 if (isset($this->tableInfo[$tableName])) {
687 // Then return the primary key
688 $primaryKey = $this->tableInfo[$tableName]['primary'];
696 * Removes non-public data from given array.
698 * @param $data An array with possible non-public data that needs to be removed.
699 * @return $data A cleaned up array with only public data.
700 * @todo Add more generic non-public data for removal
702 public function removeNonPublicDataFromArray (array $data) {
704 unset($data[$this->indexKey]);
707 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: data[' . gettype($data) . ']='.print_r($data, true));
712 * Counts total rows of given table
714 * @param $tableName Table name
715 * @return $count Total rows of given table
717 public function countTotalRows (string $tableName) {
718 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ' - CALLED!');
720 // Create full path name
721 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
723 // Try all the requests
725 // Get a file pointer instance
726 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
728 // Initialize counter
731 // Read the directory with some exceptions
732 while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
733 // Does the extension match?
734 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
735 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
737 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
743 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
746 } catch (FrameworkException $e) {
747 // Catch all exceptions and store them in last error
748 $this->setLastException($e);
750 // Throw an SQL exception
751 throw new SqlException(array($this, sprintf('Cannot count on table '%s', is the table created?', $dataSetInstance->getTableName()), self::DB_CODE_TABLE_NOT_FOUND), self::EXCEPTION_SQL_QUERY);
755 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');