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\Result\Database\BaseDatabaseResult;
17 use Org\Mxchange\CoreFramework\Traits\Compressor\Channel\CompressorChannelTrait;
18 use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
21 use \InvalidArgumentException;
23 use \UnexpectedValueException;
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 - 2021 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 $databaseInstance = new CachedLocalFileDatabase();
115 // Set the compressor channel
116 $databaseInstance->setCompressorChannelInstance(ObjectFactory::createObjectByConfiguredName('compressor_channel_class'));
118 // Get a file IO handler and set it
119 $databaseInstance->setFileIoInstance(ObjectFactory::createObjectByConfiguredName('file_io_class'));
121 // "Connect" to the database
122 $databaseInstance->connectToDatabase();
124 // Return database instance
125 return $databaseInstance;
129 * Setter for the last read file
131 * @param $infoInstance The FQFN of the last read file
134 private final function setLastFile (SplFileInfo $infoInstance) {
135 // Cast string and set it
136 $this->lastFile = $infoInstance;
140 * Getter for last read file
142 * @return $lastFile The last read file's name with full path
144 public final function getLastFile () {
145 return $this->lastFile;
149 * Setter for contents of the last read file
151 * @param $contents An array with header and data elements
154 private final function setLastFileContents (array $contents) {
156 $this->lastContents = $contents;
160 * Getter for last read file's content as an array
162 * @return $lastContent The array with elements 'header' and 'data'.
164 public final function getLastContents () {
165 return $this->lastContents;
169 * Getter for file extension
171 * @return $fileExtension The array with elements 'header' and 'data'.
173 public final function getFileExtension () {
174 return $this->fileExtension;
178 * Getter for index key
180 * @return $indexKey Index key
182 public final function getIndexKey () {
183 return $this->indexKey;
187 * Reads a local data file and returns it's contents in an array
189 * @param $infoInstance An instance of a SplFileInfo class
192 private function getDataArrayFromFile (SplFileInfo $infoInstance) {
193 // Init compressed data
194 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Reading elements from database file ' . $infoInstance . ' ...');
195 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
196 $compressedData = $compressedData['data'];
199 $serializedData = $this->getCompressorChannelInstance()->getCompressor()->decompressStream($compressedData);
202 $dataArray = json_decode($serializedData, true);
205 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
211 * Writes data array to local file
213 * @param $infoInstance An instance of a SplFileInfo class
214 * @param $dataArray An array with all the data we shall write
217 private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
218 // Serialize and compress it
219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
221 $compressedData = $this->getCompressorChannelInstance()->getCompressor()->compressStream(json_encode($dataArray));
223 // Write this data BASE64 encoded to the file
224 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing ' . strlen($compressedData) . ' bytes ...');
225 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
228 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file completed.');
232 * Getter for table information file contents or an empty if info file was not created
234 * @param $dataSetInstance An instance of a database set class
235 * @return $infoArray An array with all table informations
237 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
238 // Default content is no data
241 // Create FQFN for getting the table information file
242 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
244 // Get the file contents
246 $infoArray = $this->getDataArrayFromFile($infoInstance);
247 } catch (FileNotFoundException $e) {
248 // Not found, so ignore it here
256 * Generates a file info class from given dataset instance and string
258 * @param $dataSetInstance An instance of a database set class
259 * @param $rowName Name of the row
260 * @return $infoInstance An instance of a SplFileInfo class
262 private function generateFileFromDataSet (Criteria $dataSetInstance, string $rowName) {
263 // Instanciate new file object
264 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
267 return $infoInstance;
271 * Creates the table info file from given dataset instance
273 * @param $dataSetInstance An instance of a database set class
276 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
277 // Create FQFN for creating the table information file
278 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
280 // Get the data out from dataset in a local array
281 $this->tableInfo[$dataSetInstance->getTableName()] = array(
282 'primary' => $dataSetInstance->getPrimaryKey(),
284 'last_updated' => time()
287 // Write the data to the file
288 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
292 * Updates the table info file from given dataset instance
294 * @param $dataSetInstance An instance of a database set class
297 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
298 // Get table name from criteria
299 $tableName = $dataSetInstance->getTableName();
301 // Create FQFN for creating the table information file
302 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
304 // Get the data out from dataset in a local array
305 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
306 $this->tableInfo[$tableName]['last_updated'] = time();
308 // Write the data to the file
309 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
313 * Updates the primary key information or creates the table info file if not found
315 * @param $dataSetInstance An instance of a database set class
318 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
319 // Get table name from criteria
320 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
321 $tableName = $dataSetInstance->getTableName();
323 // Get the information array from lower method
324 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s', $tableName));
325 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
327 // Is the primary key there?
328 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableInfo=' . print_r($this->tableInfo, true));
329 if (!isset($this->tableInfo[$tableName]['primary'])) {
330 // Then create the info file
331 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Creating info table for tableName=%s ...', $tableName));
332 $this->createTableInfoFile($dataSetInstance);
333 } elseif ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
334 // Set the array element
335 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
336 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
339 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Updating info table for tableName=%s ...', $tableName));
340 $this->updateTableInfoFile($dataSetInstance);
344 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
348 * Makes sure that the database connection is alive
351 * @todo Do some checks on the database directory and files here
353 public function connectToDatabase () {
357 * Starts a SELECT query on the database by given return type, table name
358 * and search criteria
360 * @param $tableName Name of the database table
361 * @param $searchInstance Local search criteria class
362 * @return $resultData Result data of the query
363 * @throws InvalidArgumentException If a parameter is not valid
364 * @throws UnsupportedCriteriaException If the criteria is unsupported
365 * @throws SqlException If an 'SQL error' occurs
367 public function querySelect (string $tableName, LocalSearchCriteria $searchInstance) {
368 // Validate parameter
369 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
370 if (empty($tableName)) {
372 throw new InvalidArgumentException('Parameter "tableName" is empty');
373 } elseif (!isset($this->pathNames[$tableName])) {
374 // "Cache" is not present, so create and assign it
375 $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
378 // The result is null by any errors
382 * A 'select' query is not that easy on local files, so first try to
383 * find the 'table' which is in fact a directory on the server
386 // Get a directory pointer instance
387 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for this->pathNames[%s]=%s ...', $tableName, $this->pathNames[$tableName]));
388 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
390 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
392 BaseDatabaseResult::RESULT_NAME_STATUS => self::RESULT_OKAY,
393 BaseDatabaseResult::RESULT_NAME_ROWS => []
396 // Initialize limit/skip
401 // Read the directory with some exceptions
402 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
403 // Does the extension match?
404 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
405 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
407 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
408 $directoryInstance->getDirectoryIteratorInstance()->next();
413 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
416 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
417 if (is_array($dataArray)) {
418 // Default is nothing found
421 // Search in the criteria with FMFW (First Matches, First Wins)
422 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: data[]=%d', count($dataArray)));
423 foreach ($dataArray as $key => $value) {
425 $isFound = ($isFound && $searchInstance->isCriteriaMatching($key, $value));
426 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
430 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
431 if ($isFound === true) {
432 // Shall we skip this entry?
433 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d,skipFound=%d', $searchInstance->getSkip(), $skipFound));
434 if ($searchInstance->getSkip() > 0 && $skipFound < $searchInstance->getSkip()) {
441 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
442 $dataArray[$this->getIndexKey()] = $idx;
445 array_push($resultData[BaseDatabaseResult::RESULT_NAME_ROWS], $dataArray);
447 // Count found entries up
448 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: resultData[%s]()=%d', BaseDatabaseResult::RESULT_NAME_ROWS, count($resultData[BaseDatabaseResult::RESULT_NAME_ROWS])));
452 // Throw an exception here
453 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
459 // Advance to next entry
460 $directoryInstance->getDirectoryIteratorInstance()->next();
463 // Close directory and throw the instance away
464 $directoryInstance->closeDirectory();
465 unset($directoryInstance);
467 // Reset last exception
468 $this->resetLastException();
469 } catch (PathIsNoDirectoryException $e) {
470 // Path not found means "table not found" for real databases...
471 $this->setLastException($e);
473 // So throw an SqlException here with faked error message
474 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
475 } catch (FrameworkException $e) {
476 // Catch all exceptions and store them in last error
477 $this->setLastException($e);
480 // Return the gathered result
485 * "Inserts" a data set instance into a local file database folder
487 * @param $dataSetInstance A storeable data set
489 * @throws SqlException If an SQL error occurs
491 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
492 // Try to save the request away
493 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
495 // Create full path name
496 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
498 // Write the data away
499 $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
501 // Update the primary key
502 $this->updatePrimaryKey($dataSetInstance);
504 // Reset last exception
505 $this->resetLastException();
506 } catch (FrameworkException $e) {
507 // Catch all exceptions and store them in last error
508 $this->setLastException($e);
510 // Throw an SQL exception
511 throw new SqlException([
513 sprintf('Cannot write data to table '%s', is the table created? e=%s,e->message=%s',
514 $dataSetInstance->getTableName(),
518 self::DB_CODE_TABLE_UNWRITEABLE
520 self::EXCEPTION_SQL_QUERY
525 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
529 * "Updates" a data set instance with a database layer
531 * @param $dataSetInstance An instance of a StorableCriteria class
533 * @throws UnexpectedValueException If $tableName is empty
534 * @throws SqlException If an SQL error occurs
536 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
538 $tableName = $dataSetInstance->getTableName();
541 if (empty($tableName)) {
542 // Should never be an empty string
543 throw new UnexpectedValueException('Class field dataSetInstance->tableName is empty');
544 } elseif (!isset($this->pathNames[$tableName])) {
545 // "Cache" is not present, so create and assign it
546 $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
549 // Try all the requests
551 // Get a file pointer instance
552 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
554 // Initialize limit/skip
558 // Get the criteria array from the dataset
559 $searchArray = $dataSetInstance->getCriteriaArray();
561 // Get search criteria
562 $searchInstance = $dataSetInstance->getSearchInstance();
564 // Read the directory with some exceptions
565 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
566 // Does the extension match?
567 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
568 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
570 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
571 $directoryInstance->getDirectoryIteratorInstance()->next();
575 // Open this file for reading
576 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
577 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
580 if (is_array($dataArray)) {
581 // Default is nothing found
584 // Search in the criteria with FMFW (First Matches, First Wins)
585 foreach ($dataArray as $key => $value) {
587 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
591 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: isFound=' . intval($isFound));
592 if ($isFound === true) {
593 // Shall we skip this entry?
594 if ($searchInstance->getSkip() > 0) {
595 // We shall skip some entries
596 if ($skipFound < $searchInstance->getSkip()) {
598 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Found entry, but skipping ...');
604 // Entry found, so update it
605 foreach ($searchArray as $searchKey => $searchValue) {
606 // Make sure the value is not bool again
607 assert(!is_bool($searchValue));
608 assert($searchKey != $this->indexKey);
610 // Debug message + add/update it
611 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
612 $dataArray[$searchKey] = $searchValue;
615 // Write the data to a local file
616 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing data[]=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
617 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
619 // Count found entries up
624 // Advance to next entry
625 $directoryInstance->getDirectoryIteratorInstance()->next();
628 // Close the file pointer
629 $directoryInstance->closeDirectory();
631 // Update the primary key
632 $this->updatePrimaryKey($dataSetInstance);
634 // Reset last exception
635 $this->resetLastException();
636 } catch (FrameworkException $e) {
637 // Catch all exceptions and store them in last error
638 $this->setLastException($e);
640 // Throw an SQL exception
641 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);
646 * Getter for primary key of specified table or if not found null will be
647 * returned. This must be database-specific.
649 * @param $tableName Name of the table we need the primary key from
650 * @return $primaryKey Primary key column of the given table
651 * @throws InvalidArgumentException If a parameter is not valid
652 * @todo Rename method to getPrimaryKeyFromTableInfo()
654 public function getPrimaryKeyOfTable (string $tableName) {
655 // Validate parameter
656 if (empty($tableName)) {
658 throw new InvalidArgumentException('Parameter "tableName" is empty');
661 // Default key is null
664 // Does the table information exist?
665 if (isset($this->tableInfo[$tableName])) {
666 // Then return the primary key
667 $primaryKey = $this->tableInfo[$tableName]['primary'];
675 * Removes non-public data from given array.
677 * @param $data An array with possible non-public data that needs to be removed.
678 * @return $data A cleaned up array with only public data.
679 * @todo Add more generic non-public data for removal
681 public function removeNonPublicDataFromArray (array $data) {
683 unset($data[$this->indexKey]);
686 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: data[' . gettype($data) . ']='.print_r($data, true));
691 * Counts total rows of given table
693 * @param $tableName Table name
694 * @return $count Total rows of given table
695 * @throws InvalidArgumentException If a parameter is not valid
697 public function countTotalRows (string $tableName) {
698 // Validate parameter
699 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ' - CALLED!');
700 if (empty($tableName)) {
702 throw new InvalidArgumentException('Parameter "tableName" is empty');
703 } elseif (!isset($this->pathNames[$tableName])) {
704 // "Cache" is not present, so create and assign it
705 $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
708 // Try all the requests
709 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: this->pathNames[%s]=%s', $tableName, $this->pathNames[$tableName]));
711 // Get a file pointer instance
712 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
714 // Initialize counter
717 // Read the directory with some exceptions
718 while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) {
719 // Does the extension match?
720 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
721 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
723 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
729 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
732 } catch (FrameworkException $e) {
733 // Catch all exceptions and store them in last error
734 $this->setLastException($e);
736 // Throw an SQL exception
737 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);
741 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');