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\Object\ObjectFactory;
13 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
14 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
15 use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
16 use Org\Mxchange\CoreFramework\Traits\Compressor\Channel\CompressorChannelTrait;
17 use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
20 use \InvalidArgumentException;
24 * Database backend class for storing objects in locally created files.
26 * This class serializes arrays stored in the dataset instance and saves them
27 * to local files. Every file (except 'info') represents a single line. Every
28 * directory within the 'db' (base) directory represents a table.
30 * A configurable 'file_io_class' is being used as "storage backend".
32 * @author Roland Haeder <webmaster@shipsimu.org>
34 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
35 * @license GNU GPL 3.0 or any newer version
36 * @link http://www.shipsimu.org
38 * This program is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or
41 * (at your option) any later version.
43 * This program is distributed in the hope that it will be useful,
44 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 * GNU General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see <http://www.gnu.org/licenses/>.
51 class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
53 use CompressorChannelTrait;
57 * The file's extension
59 private $fileExtension = 'serialized';
62 * The last read file's name
64 private $lastFile = '';
67 * The last read file's content including header information
69 private $lastContents = [];
72 * Whether the "connection is already up
74 private $alreadyConnected = false;
77 * Table information array
79 private $tableInfo = [];
84 private $indexKey = '__idx';
87 * The protected constructor. Do never instance from outside! You need to
88 * set a local file path. The class will then validate it.
92 private function __construct () {
93 // Call parent constructor
94 parent::__construct(__CLASS__);
98 * Create an object of CachedLocalFileDatabase and set the save path from
99 * configuration for local files.
101 * @return $databaseInstance An instance of CachedLocalFileDatabase
103 public static final function createCachedLocalFileDatabase () {
105 $databaseInstance = new CachedLocalFileDatabase();
107 // Set the compressor channel
108 $databaseInstance->setCompressorChannelInstance(ObjectFactory::createObjectByConfiguredName('compressor_channel_class'));
110 // Get a file IO handler and set it
111 $databaseInstance->setFileIoInstance(ObjectFactory::createObjectByConfiguredName('file_io_class'));
113 // "Connect" to the database
114 $databaseInstance->connectToDatabase();
116 // Return database instance
117 return $databaseInstance;
121 * Setter for the last read file
123 * @param $infoInstance The FQFN of the last read file
126 private final function setLastFile (SplFileInfo $infoInstance) {
127 // Cast string and set it
128 $this->lastFile = $infoInstance;
132 * Getter for last read file
134 * @return $lastFile The last read file's name with full path
136 public final function getLastFile () {
137 return $this->lastFile;
141 * Setter for contents of the last read file
143 * @param $contents An array with header and data elements
146 private final function setLastFileContents (array $contents) {
148 $this->lastContents = $contents;
152 * Getter for last read file's content as an array
154 * @return $lastContent The array with elements 'header' and 'data'.
156 public final function getLastContents () {
157 return $this->lastContents;
161 * Getter for file extension
163 * @return $fileExtension The array with elements 'header' and 'data'.
165 public final function getFileExtension () {
166 return $this->fileExtension;
170 * Getter for index key
172 * @return $indexKey Index key
174 public final function getIndexKey () {
175 return $this->indexKey;
179 * Reads a local data file and returns it's contents in an array
181 * @param $infoInstance An instance of a SplFileInfo class
184 private function getDataArrayFromFile (SplFileInfo $infoInstance) {
185 // Init compressed data
186 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Reading elements from database file ' . $infoInstance . ' ...');
187 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
188 $compressedData = $compressedData['data'];
191 $serializedData = $this->getCompressorChannelInstance()->getCompressor()->decompressStream($compressedData);
194 $dataArray = json_decode($serializedData, true);
197 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
198 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
203 * Writes data array to local file
205 * @param $infoInstance An instance of a SplFileInfo class
206 * @param $dataArray An array with all the data we shall write
209 private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
210 // Serialize and compress it
211 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
213 $compressedData = $this->getCompressorChannelInstance()->getCompressor()->compressStream(json_encode($dataArray));
215 // Write this data BASE64 encoded to the file
216 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing ' . strlen($compressedData) . ' bytes ...');
217 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file completed.');
224 * Getter for table information file contents or an empty if info file was not created
226 * @param $dataSetInstance An instance of a database set class
227 * @return $infoArray An array with all table informations
229 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
230 // Default content is no data
233 // Create FQFN for getting the table information file
234 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
236 // Get the file contents
238 $infoArray = $this->getDataArrayFromFile($infoInstance);
239 } catch (FileNotFoundException $e) {
240 // Not found, so ignore it here
248 * Generates a file info class from given dataset instance and string
250 * @param $dataSetInstance An instance of a database set class
251 * @param $rowName Name of the row
252 * @return $infoInstance An instance of a SplFileInfo class
254 private function generateFileFromDataSet (Criteria $dataSetInstance, string $rowName) {
255 // Instanciate new file object
256 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
259 return $infoInstance;
263 * Creates the table info file from given dataset instance
265 * @param $dataSetInstance An instance of a database set class
268 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
269 // Create FQFN for creating the table information file
270 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
272 // Get the data out from dataset in a local array
273 $this->tableInfo[$dataSetInstance->getTableName()] = array(
274 'primary' => $dataSetInstance->getPrimaryKey(),
276 'last_updated' => time()
279 // Write the data to the file
280 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
284 * Updates the table info file from given dataset instance
286 * @param $dataSetInstance An instance of a database set class
289 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
290 // Get table name from criteria
291 $tableName = $dataSetInstance->getTableName();
293 // Create FQFN for creating the table information file
294 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
296 // Get the data out from dataset in a local array
297 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
298 $this->tableInfo[$tableName]['last_updated'] = time();
300 // Write the data to the file
301 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
305 * Updates the primary key information or creates the table info file if not found
307 * @param $dataSetInstance An instance of a database set class
310 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
311 // Get table name from criteria
312 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
313 $tableName = $dataSetInstance->getTableName();
315 // Get the information array from lower method
316 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s', $tableName));
317 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
319 // Is the primary key there?
320 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableInfo=' . print_r($this->tableInfo, true));
321 if (!isset($this->tableInfo[$tableName]['primary'])) {
322 // Then create the info file
323 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Creating info table for tableName=%s ...', $tableName));
324 $this->createTableInfoFile($dataSetInstance);
325 } elseif ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
326 // Set the array element
327 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
328 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
331 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Updating info table for tableName=%s ...', $tableName));
332 $this->updateTableInfoFile($dataSetInstance);
336 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
340 * Makes sure that the database connection is alive
343 * @todo Do some checks on the database directory and files here
345 public function connectToDatabase () {
349 * Starts a SELECT query on the database by given return type, table name
350 * and search criteria
352 * @param $tableName Name of the database table
353 * @param $searchInstance Local search criteria class
354 * @return $resultData Result data of the query
355 * @throws InvalidArgumentException If a parameter is not valid
356 * @throws UnsupportedCriteriaException If the criteria is unsupported
357 * @throws SqlException If an 'SQL error' occurs
359 public function querySelect (string $tableName, LocalSearchCriteria $searchInstance) {
360 // Validate parameter
361 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
362 if (empty($tableName)) {
364 throw new InvalidArgumentException('Parameter "tableName" is empty');
367 // The result is null by any errors
370 // Create full path name
371 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
374 * A 'select' query is not that easy on local files, so first try to
375 * find the 'table' which is in fact a directory on the server
378 // Get a directory pointer instance
379 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for pathName=%s ...', $pathName));
380 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
382 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
384 BaseDatabaseResult::RESULT_NAME_STATUS => self::RESULT_OKAY,
385 BaseDatabaseResult::RESULT_NAME_ROWS => []
388 // Initialize limit/skip
393 // Read the directory with some exceptions
394 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
395 // Does the extension match?
396 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
397 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
399 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
400 $directoryInstance->getDirectoryIteratorInstance()->next();
405 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
408 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
409 if (is_array($dataArray)) {
410 // Default is nothing found
413 // Search in the criteria with FMFW (First Matches, First Wins)
414 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: data[]=%d', count($dataArray)));
415 foreach ($dataArray as $key => $value) {
417 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
418 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
422 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
423 if ($isFound === true) {
424 // Shall we skip this entry?
425 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d', $searchInstance->getSkip()));
426 if ($searchInstance->getSkip() > 0) {
427 // We shall skip some entries
428 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: skipFound=%s', $skipFound));
429 if ($skipFound < $searchInstance->getSkip()) {
437 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
438 $dataArray[$this->getIndexKey()] = $idx;
441 array_push($resultData[BaseDatabaseResult::RESULT_NAME_ROWS], $dataArray);
443 // Count found entries up
444 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: resultData[%s]()=%d', BaseDatabaseResult::RESULT_NAME_ROWS, count($resultData[BaseDatabaseResult::RESULT_NAME_ROWS])));
448 // Throw an exception here
449 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
455 // Advance to next entry
456 $directoryInstance->getDirectoryIteratorInstance()->next();
459 // Close directory and throw the instance away
460 $directoryInstance->closeDirectory();
461 unset($directoryInstance);
463 // Reset last exception
464 $this->resetLastException();
465 } catch (PathIsNoDirectoryException $e) {
466 // Path not found means "table not found" for real databases...
467 $this->setLastException($e);
469 // So throw an SqlException here with faked error message
470 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
471 } catch (FrameworkException $e) {
472 // Catch all exceptions and store them in last error
473 $this->setLastException($e);
476 // Return the gathered result
481 * "Inserts" a data set instance into a local file database folder
483 * @param $dataSetInstance A storeable data set
485 * @throws SqlException If an SQL error occurs
487 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
488 // Try to save the request away
489 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
491 // Create full path name
492 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
494 // Write the data away
495 $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
497 // Update the primary key
498 $this->updatePrimaryKey($dataSetInstance);
500 // Reset last exception
501 $this->resetLastException();
502 } catch (FrameworkException $e) {
503 // Catch all exceptions and store them in last error
504 $this->setLastException($e);
506 // Throw an SQL exception
507 throw new SqlException(array(
509 sprintf('Cannot write data to table '%s', is the table created?', $dataSetInstance->getTableName()),
510 self::DB_CODE_TABLE_UNWRITEABLE
512 self::EXCEPTION_SQL_QUERY
517 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
521 * "Updates" a data set instance with a database layer
523 * @param $dataSetInstance An instance of a StorableCriteria class
525 * @throws SqlException If an SQL error occurs
527 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
528 // Create full path name
529 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
531 // Try all the requests
533 // Get a file pointer instance
534 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
536 // Initialize limit/skip
540 // Get the criteria array from the dataset
541 $searchArray = $dataSetInstance->getCriteriaArray();
543 // Get search criteria
544 $searchInstance = $dataSetInstance->getSearchInstance();
546 // Read the directory with some exceptions
547 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
548 // Does the extension match?
549 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
550 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
552 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
553 $directoryInstance->getDirectoryIteratorInstance()->next();
557 // Open this file for reading
558 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
559 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
562 if (is_array($dataArray)) {
563 // Default is nothing found
566 // Search in the criteria with FMFW (First Matches, First Wins)
567 foreach ($dataArray as $key => $value) {
569 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
573 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: isFound=' . intval($isFound));
574 if ($isFound === true) {
575 // Shall we skip this entry?
576 if ($searchInstance->getSkip() > 0) {
577 // We shall skip some entries
578 if ($skipFound < $searchInstance->getSkip()) {
580 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Found entry, but skipping ...');
586 // Entry found, so update it
587 foreach ($searchArray as $searchKey => $searchValue) {
588 // Make sure the value is not bool again
589 assert(!is_bool($searchValue));
590 assert($searchKey != $this->indexKey);
592 // Debug message + add/update it
593 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
594 $dataArray[$searchKey] = $searchValue;
597 // Write the data to a local file
598 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing data[]=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
599 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
601 // Count found entries up
606 // Advance to next entry
607 $directoryInstance->getDirectoryIteratorInstance()->next();
610 // Close the file pointer
611 $directoryInstance->closeDirectory();
613 // Update the primary key
614 $this->updatePrimaryKey($dataSetInstance);
616 // Reset last exception
617 $this->resetLastException();
618 } catch (FrameworkException $e) {
619 // Catch all exceptions and store them in last error
620 $this->setLastException($e);
622 // Throw an SQL exception
623 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);
628 * Getter for primary key of specified table or if not found null will be
629 * returned. This must be database-specific.
631 * @param $tableName Name of the table we need the primary key from
632 * @return $primaryKey Primary key column of the given table
633 * @throws InvalidArgumentException If a parameter is not valid
634 * @todo Rename method to getPrimaryKeyFromTableInfo()
636 public function getPrimaryKeyOfTable (string $tableName) {
637 // Validate parameter
638 if (empty($tableName)) {
640 throw new InvalidArgumentException('Parameter "tableName" is empty');
643 // Default key is null
646 // Does the table information exist?
647 if (isset($this->tableInfo[$tableName])) {
648 // Then return the primary key
649 $primaryKey = $this->tableInfo[$tableName]['primary'];
657 * Removes non-public data from given array.
659 * @param $data An array with possible non-public data that needs to be removed.
660 * @return $data A cleaned up array with only public data.
661 * @todo Add more generic non-public data for removal
663 public function removeNonPublicDataFromArray (array $data) {
665 unset($data[$this->indexKey]);
668 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: data[' . gettype($data) . ']='.print_r($data, true));
673 * Counts total rows of given table
675 * @param $tableName Table name
676 * @return $count Total rows of given table
677 * @throws InvalidArgumentException If a parameter is not valid
679 public function countTotalRows (string $tableName) {
680 // Validate parameter
681 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ' - CALLED!');
682 if (empty($tableName)) {
684 throw new InvalidArgumentException('Parameter "tableName" is empty');
688 // Create full path name
689 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
691 // Try all the requests
692 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: pathName=' . $pathName);
694 // Get a file pointer instance
695 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
697 // Initialize counter
700 // Read the directory with some exceptions
701 while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) {
702 // Does the extension match?
703 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
704 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
706 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
712 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
715 } catch (FrameworkException $e) {
716 // Catch all exceptions and store them in last error
717 $this->setLastException($e);
719 // Throw an SQL exception
720 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);
724 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');