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\Traits\Compressor\Channel\CompressorChannelTrait;
16 use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
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 use CompressorChannelTrait;
55 * The file's extension
57 private $fileExtension = 'serialized';
60 * The last read file's name
62 private $lastFile = '';
65 * The last read file's content including header information
67 private $lastContents = [];
70 * Whether the "connection is already up
72 private $alreadyConnected = false;
75 * Table information array
77 private $tableInfo = [];
82 private $indexKey = '__idx';
85 * The protected constructor. Do never instance from outside! You need to
86 * set a local file path. The class will then validate it.
90 protected function __construct () {
91 // Call parent constructor
92 parent::__construct(__CLASS__);
96 * Create an object of CachedLocalFileDatabase and set the save path from
97 * configuration for local files.
99 * @return $databaseInstance An instance of CachedLocalFileDatabase
101 public static final function createCachedLocalFileDatabase () {
103 $databaseInstance = new CachedLocalFileDatabase();
105 // Set the compressor channel
106 $databaseInstance->setCompressorChannelInstance(ObjectFactory::createObjectByConfiguredName('compressor_channel_class'));
108 // Get a file IO handler and set it
109 $databaseInstance->setFileIoInstance(ObjectFactory::createObjectByConfiguredName('file_io_class'));
111 // "Connect" to the database
112 $databaseInstance->connectToDatabase();
114 // Return database instance
115 return $databaseInstance;
119 * Setter for the last read file
121 * @param $infoInstance The FQFN of the last read file
124 private final function setLastFile (SplFileInfo $infoInstance) {
125 // Cast string and set it
126 $this->lastFile = $infoInstance;
130 * Getter for last read file
132 * @return $lastFile The last read file's name with full path
134 public final function getLastFile () {
135 return $this->lastFile;
139 * Setter for contents of the last read file
141 * @param $contents An array with header and data elements
144 private final function setLastFileContents (array $contents) {
146 $this->lastContents = $contents;
150 * Getter for last read file's content as an array
152 * @return $lastContent The array with elements 'header' and 'data'.
154 public final function getLastContents () {
155 return $this->lastContents;
159 * Getter for file extension
161 * @return $fileExtension The array with elements 'header' and 'data'.
163 public final function getFileExtension () {
164 return $this->fileExtension;
168 * Getter for index key
170 * @return $indexKey Index key
172 public final function getIndexKey () {
173 return $this->indexKey;
177 * Reads a local data file and returns it's contents in an array
179 * @param $infoInstance An instance of a SplFileInfo class
182 private function getDataArrayFromFile (SplFileInfo $infoInstance) {
183 // Init compressed data
184 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Reading elements from database file ' . $infoInstance . ' ...');
185 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
186 $compressedData = $compressedData['data'];
189 $serializedData = $this->getCompressorChannelInstance()->getCompressor()->decompressStream($compressedData);
192 $dataArray = json_decode($serializedData, true);
195 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
196 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
201 * Writes data array to local file
203 * @param $infoInstance An instance of a SplFileInfo class
204 * @param $dataArray An array with all the data we shall write
207 private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
208 // Serialize and compress it
209 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
210 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
211 $compressedData = $this->getCompressorChannelInstance()->getCompressor()->compressStream(json_encode($dataArray));
213 // Write this data BASE64 encoded to the file
214 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing ' . strlen($compressedData) . ' bytes ...');
215 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
218 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file completed.');
222 * Getter for table information file contents or an empty if info file was not created
224 * @param $dataSetInstance An instance of a database set class
225 * @return $infoArray An array with all table informations
227 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
228 // Default content is no data
231 // Create FQFN for getting the table information file
232 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
234 // Get the file contents
236 $infoArray = $this->getDataArrayFromFile($infoInstance);
237 } catch (FileNotFoundException $e) {
238 // Not found, so ignore it here
246 * Generates a file info class from given dataset instance and string
248 * @param $dataSetInstance An instance of a database set class
249 * @param $rowName Name of the row
250 * @return $infoInstance An instance of a SplFileInfo class
252 private function generateFileFromDataSet (Criteria $dataSetInstance, string $rowName) {
253 // Instanciate new file object
254 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
257 return $infoInstance;
261 * Creates the table info file from given dataset instance
263 * @param $dataSetInstance An instance of a database set class
266 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
267 // Create FQFN for creating the table information file
268 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
270 // Get the data out from dataset in a local array
271 $this->tableInfo[$dataSetInstance->getTableName()] = array(
272 'primary' => $dataSetInstance->getPrimaryKey(),
274 'last_updated' => time()
277 // Write the data to the file
278 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
282 * Updates the table info file from given dataset instance
284 * @param $dataSetInstance An instance of a database set class
287 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
288 // Get table name from criteria
289 $tableName = $dataSetInstance->getTableName();
291 // Create FQFN for creating the table information file
292 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
294 // Get the data out from dataset in a local array
295 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
296 $this->tableInfo[$tableName]['last_updated'] = time();
298 // Write the data to the file
299 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
303 * Updates the primary key information or creates the table info file if not found
305 * @param $dataSetInstance An instance of a database set class
308 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
309 // Get table name from criteria
310 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
311 $tableName = $dataSetInstance->getTableName();
313 // Get the information array from lower method
314 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s', $tableName));
315 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
317 // Is the primary key there?
318 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableInfo=' . print_r($this->tableInfo, true));
319 if (!isset($this->tableInfo[$tableName]['primary'])) {
320 // Then create the info file
321 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Creating info table for tableName=%s ...', $tableName));
322 $this->createTableInfoFile($dataSetInstance);
323 } elseif ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
324 // Set the array element
325 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
326 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
329 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Updating info table for tableName=%s ...', $tableName));
330 $this->updateTableInfoFile($dataSetInstance);
334 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
338 * Makes sure that the database connection is alive
341 * @todo Do some checks on the database directory and files here
343 public function connectToDatabase () {
347 * Starts a SELECT query on the database by given return type, table name
348 * and search criteria
350 * @param $tableName Name of the database table
351 * @param $searchInstance Local search criteria class
352 * @return $resultData Result data of the query
353 * @throws UnsupportedCriteriaException If the criteria is unsupported
354 * @throws SqlException If an 'SQL error' occurs
356 public function querySelect (string $tableName, LocalSearchCriteria $searchInstance) {
357 // The result is null by any errors
358 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
361 // Create full path name
362 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
365 * A 'select' query is not that easy on local files, so first try to
366 * find the 'table' which is in fact a directory on the server
369 // Get a directory pointer instance
370 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for pathName=%s ...', $pathName));
371 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
373 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
375 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
376 BaseDatabaseBackend::RESULT_INDEX_ROWS => []
379 // Initialize limit/skip
384 // Read the directory with some exceptions
385 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
386 // Does the extension match?
387 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
388 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
390 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
391 $directoryInstance->getDirectoryIteratorInstance()->next();
396 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
399 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
400 if (is_array($dataArray)) {
401 // Default is nothing found
404 // Search in the criteria with FMFW (First Matches, First Wins)
405 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: data[]=%d', count($dataArray)));
406 foreach ($dataArray as $key => $value) {
407 // Make sure value is not bool
408 assert(!is_bool($value));
411 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
412 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
416 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
417 if ($isFound === true) {
418 // Shall we skip this entry?
419 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d', $searchInstance->getSkip()));
420 if ($searchInstance->getSkip() > 0) {
421 // We shall skip some entries
422 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: skipFound=%s', $skipFound));
423 if ($skipFound < $searchInstance->getSkip()) {
431 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
432 $dataArray[$this->getIndexKey()] = $idx;
435 array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
437 // Count found entries up
438 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: resultData[%s]()=%d', BaseDatabaseBackend::RESULT_INDEX_ROWS, count($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS])));
442 // Throw an exception here
443 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
449 // Advance to next entry
450 $directoryInstance->getDirectoryIteratorInstance()->next();
453 // Close directory and throw the instance away
454 $directoryInstance->closeDirectory();
455 unset($directoryInstance);
457 // Reset last exception
458 $this->resetLastException();
459 } catch (PathIsNoDirectoryException $e) {
460 // Path not found means "table not found" for real databases...
461 $this->setLastException($e);
463 // So throw an SqlException here with faked error message
464 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
465 } catch (FrameworkException $e) {
466 // Catch all exceptions and store them in last error
467 $this->setLastException($e);
470 // Return the gathered result
475 * "Inserts" a data set instance into a local file database folder
477 * @param $dataSetInstance A storeable data set
479 * @throws SqlException If an SQL error occurs
481 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
482 // Try to save the request away
483 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
485 // Create full path name
486 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
488 // Write the data away
489 $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
491 // Update the primary key
492 $this->updatePrimaryKey($dataSetInstance);
494 // Reset last exception
495 $this->resetLastException();
496 } catch (FrameworkException $e) {
497 // Catch all exceptions and store them in last error
498 $this->setLastException($e);
500 // Throw an SQL exception
501 throw new SqlException(array(
503 sprintf('Cannot write data to table '%s', is the table created?', $dataSetInstance->getTableName()),
504 self::DB_CODE_TABLE_UNWRITEABLE
506 self::EXCEPTION_SQL_QUERY
511 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
515 * "Updates" a data set instance with a database layer
517 * @param $dataSetInstance An instance of a StorableCriteria class
519 * @throws SqlException If an SQL error occurs
521 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
522 // Create full path name
523 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
525 // Try all the requests
527 // Get a file pointer instance
528 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
530 // Initialize limit/skip
534 // Get the criteria array from the dataset
535 $searchArray = $dataSetInstance->getCriteriaArray();
537 // Get search criteria
538 $searchInstance = $dataSetInstance->getSearchInstance();
540 // Read the directory with some exceptions
541 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
542 // Does the extension match?
543 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
544 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
546 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
547 $directoryInstance->getDirectoryIteratorInstance()->next();
551 // Open this file for reading
552 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
553 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
556 if (is_array($dataArray)) {
557 // Default is nothing found
560 // Search in the criteria with FMFW (First Matches, First Wins)
561 foreach ($dataArray as $key => $value) {
562 // Make sure value is not bool
563 assert(!is_bool($value));
566 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
570 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: isFound=' . intval($isFound));
571 if ($isFound === true) {
572 // Shall we skip this entry?
573 if ($searchInstance->getSkip() > 0) {
574 // We shall skip some entries
575 if ($skipFound < $searchInstance->getSkip()) {
577 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Found entry, but skipping ...');
583 // Entry found, so update it
584 foreach ($searchArray as $searchKey => $searchValue) {
585 // Make sure the value is not bool again
586 assert(!is_bool($searchValue));
587 assert($searchKey != $this->indexKey);
589 // Debug message + add/update it
590 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
591 $dataArray[$searchKey] = $searchValue;
594 // Write the data to a local file
595 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing data[]=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
596 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
598 // Count found entries up
603 // Advance to next entry
604 $directoryInstance->getDirectoryIteratorInstance()->next();
607 // Close the file pointer
608 $directoryInstance->closeDirectory();
610 // Update the primary key
611 $this->updatePrimaryKey($dataSetInstance);
613 // Reset last exception
614 $this->resetLastException();
615 } catch (FrameworkException $e) {
616 // Catch all exceptions and store them in last error
617 $this->setLastException($e);
619 // Throw an SQL exception
620 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);
625 * Getter for primary key of specified table or if not found null will be
626 * returned. This must be database-specific.
628 * @param $tableName Name of the table we need the primary key from
629 * @return $primaryKey Primary key column of the given table
630 * @todo Rename method to getPrimaryKeyFromTableInfo()
632 public function getPrimaryKeyOfTable (string $tableName) {
633 // Default key is null
636 // Does the table information exist?
637 if (isset($this->tableInfo[$tableName])) {
638 // Then return the primary key
639 $primaryKey = $this->tableInfo[$tableName]['primary'];
647 * Removes non-public data from given array.
649 * @param $data An array with possible non-public data that needs to be removed.
650 * @return $data A cleaned up array with only public data.
651 * @todo Add more generic non-public data for removal
653 public function removeNonPublicDataFromArray (array $data) {
655 unset($data[$this->indexKey]);
658 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: data[' . gettype($data) . ']='.print_r($data, true));
663 * Counts total rows of given table
665 * @param $tableName Table name
666 * @return $count Total rows of given table
668 public function countTotalRows (string $tableName) {
669 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ' - CALLED!');
671 // Create full path name
672 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
674 // Try all the requests
676 // Get a file pointer instance
677 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
679 // Initialize counter
682 // Read the directory with some exceptions
683 while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
684 // Does the extension match?
685 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
686 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
688 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
694 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
697 } catch (FrameworkException $e) {
698 // Catch all exceptions and store them in last error
699 $this->setLastException($e);
701 // Throw an SQL exception
702 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);
706 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');