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\Database\Sql\SqlException;
13 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
14 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
15 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
16 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
17 use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
18 use Org\Mxchange\CoreFramework\Traits\Compressor\Channel\CompressorChannelTrait;
19 use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
22 use \InvalidArgumentException;
26 * Database backend class for storing objects in locally created files.
28 * This class serializes arrays stored in the dataset instance and saves them
29 * to local files. Every file (except 'info') represents a single line. Every
30 * directory within the 'db' (base) directory represents a table.
32 * A configurable 'file_io_class' is being used as "storage backend".
34 * @author Roland Haeder <webmaster@shipsimu.org>
36 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
37 * @license GNU GPL 3.0 or any newer version
38 * @link http://www.shipsimu.org
40 * This program is free software: you can redistribute it and/or modify
41 * it under the terms of the GNU General Public License as published by
42 * the Free Software Foundation, either version 3 of the License, or
43 * (at your option) any later version.
45 * This program is distributed in the hope that it will be useful,
46 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48 * GNU General Public License for more details.
50 * You should have received a copy of the GNU General Public License
51 * along with this program. If not, see <http://www.gnu.org/licenses/>.
53 class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
55 use CompressorChannelTrait;
59 * The file's extension
61 private $fileExtension = 'serialized';
64 * The last read file's name
66 private $lastFile = '';
69 * The last read file's content including header information
71 private $lastContents = [];
74 * Whether the "connection is already up
76 private $alreadyConnected = false;
79 * Table information array
81 private $tableInfo = [];
86 private $indexKey = '__idx';
89 * Cached file names based on table name to avoid "expensive" invocations
90 * of FrameworkConfiguration->getConfigEntry().
92 private $pathNames = [];
95 * The protected constructor. Do never instance from outside! You need to
96 * set a local file path. The class will then validate it.
100 private function __construct () {
101 // Call parent constructor
102 parent::__construct(__CLASS__);
106 * Create an object of CachedLocalFileDatabase and set the save path from
107 * configuration for local files.
109 * @return $databaseInstance An instance of CachedLocalFileDatabase
111 public static final function createCachedLocalFileDatabase () {
113 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: CALLED!');
114 $databaseInstance = new CachedLocalFileDatabase();
116 // Set the compressor channel
117 $databaseInstance->setCompressorChannelInstance(ObjectFactory::createObjectByConfiguredName('compressor_channel_class'));
119 // Get a file IO handler and set it
120 $databaseInstance->setFileIoInstance(ObjectFactory::createObjectByConfiguredName('file_io_class'));
122 // "Connect" to the database
123 $databaseInstance->connectToDatabase();
125 // Return database instance
126 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: databaseInstance=%s - EXIT!', $databaseInstance->__toString()));
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;
189 * Reads a local data file and returns it's contents in an array
191 * @param $infoInstance An instance of a SplFileInfo class
194 private function getDataArrayFromFile (SplFileInfo $infoInstance) {
195 // Init compressed data
196 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: infoInstance=%s - CALLED!', $infoInstance->__toString()));
197 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
200 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: compressedData[]=%s', gettype($compressedData)));
201 $serializedData = $this->getCompressorChannelInstance()->getCompressor()->decompressStream($compressedData['data']);
204 $dataArray = json_decode($serializedData, true);
207 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: dataArray()=%d - EXIT!', count($dataArray)));
212 * Writes data array to local file
214 * @param $infoInstance An instance of a SplFileInfo class
215 * @param $dataArray An array with all the data we shall write
218 private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
219 // Serialize and compress it
220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
221 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: dataArray=' . print_r($dataArray, true));
222 $compressedData = $this->getCompressorChannelInstance()->getCompressor()->compressStream(json_encode($dataArray));
224 // Write this data BASE64 encoded to the file
225 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
226 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
229 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
233 * Getter for table information file contents or an empty if info file was not created
235 * @param $dataSetInstance An instance of a database set class
236 * @return $infoArray An array with all table informations
238 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
239 // Default content is no data
242 // Create FQFN for getting the table information file
243 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
245 // Get the file contents
247 $infoArray = $this->getDataArrayFromFile($infoInstance);
248 } catch (FileNotFoundException $e) {
249 // Not found, so ignore it here
257 * Generates a file info class from given dataset instance and string
259 * @param $dataSetInstance An instance of a database set class
260 * @param $rowName Name of the row
261 * @return $infoInstance An instance of a SplFileInfo class
263 private function generateFileFromDataSet (Criteria $dataSetInstance, string $rowName) {
264 // Instanciate new file object
265 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
268 return $infoInstance;
272 * Creates the table info file from given dataset instance
274 * @param $dataSetInstance An instance of a database set class
277 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
278 // Create FQFN for creating the table information file
279 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
281 // Get the data out from dataset in a local array
282 $this->tableInfo[$dataSetInstance->getTableName()] = [
283 'primary' => $dataSetInstance->getPrimaryKey(),
285 'last_updated' => time(),
288 // Write the data to the file
289 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
293 * Updates the table info file from given dataset instance
295 * @param $dataSetInstance An instance of a database set class
298 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
299 // Get table name from criteria
300 $tableName = $dataSetInstance->getTableName();
302 // Create FQFN for creating the table information file
303 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
305 // Get the data out from dataset in a local array
306 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
307 $this->tableInfo[$tableName]['last_updated'] = time();
309 // Write the data to the file
310 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
314 * Updates the primary key information or creates the table info file if not found
316 * @param $dataSetInstance An instance of a database set class
319 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
320 // Get table name from criteria
321 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
322 $tableName = $dataSetInstance->getTableName();
324 // Get the information array from lower method
325 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%s', $tableName));
326 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
328 // Is the primary key there?
329 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: tableInfo=' . print_r($this->tableInfo, true));
330 if (!isset($this->tableInfo[$tableName]['primary'])) {
331 // Then create the info file
332 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Creating info table for tableName=%s ...', $tableName));
333 $this->createTableInfoFile($dataSetInstance);
334 } elseif (FrameworkBootstrap::getConfigurationInstance()->isEnabled('db_update_primary_forced') && $dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary']) {
335 // Set the array element
336 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
337 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
340 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Updating info table for tableName=%s ...', $tableName));
341 $this->updateTableInfoFile($dataSetInstance);
345 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: EXIT!');
349 * Makes sure that the database connection is alive
352 * @todo Do some checks on the database directory and files here
354 public function connectToDatabase () {
358 * Starts a SELECT query on the database by given return type, table name
359 * and search criteria
361 * @param $tableName Name of the database table
362 * @param $searchInstance Local search criteria class
363 * @return $resultData Result data of the query
364 * @throws InvalidArgumentException If a parameter is not valid
365 * @throws UnsupportedCriteriaException If the criteria is unsupported
366 * @throws SqlException If an 'SQL error' occurs
368 public function querySelect (string $tableName, LocalSearchCriteria $searchInstance) {
369 // Validate parameter
370 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
371 if (empty($tableName)) {
373 throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
374 } elseif (!isset($this->pathNames[$tableName])) {
375 // "Cache" is not present, so create and assign it
376 $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
379 // The result is null by any errors
383 * A 'select' query is not that easy on local files, so first try to
384 * find the 'table' which is in fact a directory on the server
387 // Get a directory pointer instance
388 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Getting directory_class for this->pathNames[%s]=%s ...', $tableName, $this->pathNames[$tableName]));
389 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
391 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
393 BaseDatabaseResult::RESULT_NAME_STATUS => self::RESULT_OKAY,
394 BaseDatabaseResult::RESULT_NAME_ROWS => [],
395 BaseDatabaseResult::RESULT_NAME_EXCEPTION => NULL,
398 // Initialize limit/skip
403 // Read the directory with some exceptions
404 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
405 // Does the extension match?
406 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
407 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
409 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
410 $directoryInstance->getDirectoryIteratorInstance()->next();
415 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
418 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
419 if (is_array($dataArray)) {
420 // Default is nothing found
423 // Search in the criteria with FMFW (First Matches, First Wins)
424 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: data[]=%d', count($dataArray)));
425 foreach ($dataArray as $key => $value) {
427 $isFound = ($isFound && $searchInstance->isCriteriaMatching($key, $value));
428 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
432 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
433 if ($isFound === true) {
434 // Shall we skip this entry?
435 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: searchInstance->skip=%d,skipFound=%d', $searchInstance->getSkip(), $skipFound));
436 if ($searchInstance->getSkip() > 0 && $skipFound < $searchInstance->getSkip()) {
443 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
444 $dataArray[$this->getIndexKey()] = $idx;
447 array_push($resultData[BaseDatabaseResult::RESULT_NAME_ROWS], $dataArray);
449 // Count found entries up
450 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: resultData[%s]()=%d', BaseDatabaseResult::RESULT_NAME_ROWS, count($resultData[BaseDatabaseResult::RESULT_NAME_ROWS])));
454 // Throw an exception here
455 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
461 // Advance to next entry
462 $directoryInstance->getDirectoryIteratorInstance()->next();
465 // Close directory and throw the instance away
466 $directoryInstance->closeDirectory();
467 unset($directoryInstance);
469 // Reset last exception
470 $this->resetLastException();
471 } catch (PathIsNoDirectoryException $e) {
472 // Path not found means "table not found" for real databases...
473 $this->setLastException($e);
475 // So throw an SqlException here with faked error message
476 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
477 } catch (FrameworkException $e) {
478 // Catch all exceptions and store them in last error
479 $this->setLastException($e);
482 // Return the gathered result
487 * "Inserts" a data set instance into a local file database folder
489 * @param $dataSetInstance A storeable data set
491 * @throws SqlException If an SQL error occurs
493 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
494 // Try to save the request away
495 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
497 // Create full path name
498 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
500 // Write the data away
501 $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
503 // Update the primary key
504 $this->updatePrimaryKey($dataSetInstance);
506 // Reset last exception
507 $this->resetLastException();
508 } catch (FrameworkException $e) {
509 // Catch all exceptions and store them in last error
510 $this->setLastException($e);
512 // Throw an SQL exception
513 throw new SqlException([
515 sprintf('Cannot write data to table '%s', is the table created? e=%s,e->message=%s',
516 $dataSetInstance->getTableName(),
520 self::DB_CODE_TABLE_UNWRITEABLE
522 self::EXCEPTION_SQL_QUERY
527 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: EXIT!');
531 * "Updates" a data set instance with a database layer
533 * @param $dataSetInstance An instance of a StorableCriteria class
535 * @throws InvalidArgumentException If $tableName is empty
536 * @throws SqlException If an SQL error occurs
538 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
540 $tableName = $dataSetInstance->getTableName();
543 if (empty($tableName)) {
544 // Should never be an empty string
545 throw new InvalidArgumentException('Class field dataSetInstance->tableName is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
546 } elseif (!isset($this->pathNames[$tableName])) {
547 // "Cache" is not present, so create and assign it
548 $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
551 // Try all the requests
553 // Get a file pointer instance
554 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
556 // Initialize limit/skip
560 // Get the criteria array from the dataset
561 $searchArray = $dataSetInstance->getCriteriaArray();
563 // Get search criteria
564 $searchInstance = $dataSetInstance->getSearchInstance();
566 // Read the directory with some exceptions
567 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
568 // Does the extension match?
569 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
570 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
572 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
573 $directoryInstance->getDirectoryIteratorInstance()->next();
577 // Open this file for reading
578 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
579 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
582 if (is_array($dataArray)) {
583 // Default is nothing found
586 // Search in the criteria with FMFW (First Matches, First Wins)
587 foreach ($dataArray as $key => $value) {
589 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
593 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: isFound=' . intval($isFound));
594 if ($isFound === true) {
595 // Shall we skip this entry?
596 if ($searchInstance->getSkip() > 0) {
597 // We shall skip some entries
598 if ($skipFound < $searchInstance->getSkip()) {
600 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: Found entry, but skipping ...');
606 // Entry found, so update it
607 foreach ($searchArray as $searchKey => $searchValue) {
608 // Make sure the value is not bool again
609 assert(!is_bool($searchValue));
610 assert($searchKey != $this->indexKey);
612 // Debug message + add/update it
613 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
614 $dataArray[$searchKey] = $searchValue;
617 // Write the data to a local file
618 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: Writing data[]=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
619 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
621 // Count found entries up
626 // Advance to next entry
627 $directoryInstance->getDirectoryIteratorInstance()->next();
630 // Close the file pointer
631 $directoryInstance->closeDirectory();
633 // Update the primary key
634 $this->updatePrimaryKey($dataSetInstance);
636 // Reset last exception
637 $this->resetLastException();
638 } catch (FrameworkException $e) {
639 // Catch all exceptions and store them in last error
640 $this->setLastException($e);
642 // Throw an SQL exception
643 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);
648 * Getter for primary key of specified table or if not found null will be
649 * returned. This must be database-specific.
651 * @param $tableName Name of the table we need the primary key from
652 * @return $primaryKey Primary key column of the given table
653 * @throws InvalidArgumentException If a parameter is not valid
654 * @todo Rename method to getPrimaryKeyFromTableInfo()
656 public function getPrimaryKeyOfTable (string $tableName) {
657 // Validate parameter
658 if (empty($tableName)) {
660 throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
663 // Default key is null
666 // Does the table information exist?
667 if (isset($this->tableInfo[$tableName])) {
668 // Then return the primary key
669 $primaryKey = $this->tableInfo[$tableName]['primary'];
677 * Removes non-public data from given array.
679 * @param $data An array with possible non-public data that needs to be removed.
680 * @return $data A cleaned up array with only public data.
681 * @todo Add more generic non-public data for removal
683 public function removeNonPublicDataFromArray (array $data) {
685 unset($data[$this->indexKey]);
688 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: data[' . gettype($data) . ']='.print_r($data, true));
693 * Counts total rows of given table
695 * @param $tableName Table name
696 * @return $count Total rows of given table
697 * @throws InvalidArgumentException If a parameter is not valid
699 public function countTotalRows (string $tableName) {
700 // Validate parameter
701 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: tableName=' . $tableName . ' - CALLED!');
702 if (empty($tableName)) {
704 throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
705 } elseif (!isset($this->pathNames[$tableName])) {
706 // "Cache" is not present, so create and assign it
707 $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
710 // Try all the requests
711 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: this->pathNames[%s]=%s', $tableName, $this->pathNames[$tableName]));
713 // Get a file pointer instance
714 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
716 // Initialize counter
719 // Read the directory with some exceptions
720 while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) {
721 // Does the extension match?
722 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
723 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
725 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
731 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
734 } catch (FrameworkException $e) {
735 // Catch all exceptions and store them in last error
736 $this->setLastException($e);
738 // Throw an SQL exception
739 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);
743 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');