3 namespace Org\Mxchange\CoreFramework\Database\Backend\Lfdb;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Criteria\Criteria;
7 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
8 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
9 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
10 use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
11 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
12 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
13 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
19 * Database backend class for storing objects in locally created files.
21 * This class serializes arrays stored in the dataset instance and saves them
22 * to local files. Every file (except 'info') represents a single line. Every
23 * directory within the 'db' (base) directory represents a table.
25 * A configurable 'file_io_class' is being used as "storage backend".
27 * @author Roland Haeder <webmaster@shipsimu.org>
29 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
30 * @license GNU GPL 3.0 or any newer version
31 * @link http://www.shipsimu.org
33 * This program is free software: you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation, either version 3 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License
44 * along with this program. If not, see <http://www.gnu.org/licenses/>.
46 class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
48 * The file's extension
50 private $fileExtension = 'serialized';
53 * The last read file's name
55 private $lastFile = '';
58 * The last read file's content including header information
60 private $lastContents = array();
63 * Whether the "connection is already up
65 private $alreadyConnected = false;
68 * Table information array
70 private $tableInfo = array();
75 private $indexKey = '__idx';
78 * The protected constructor. Do never instance from outside! You need to
79 * set a local file path. The class will then validate it.
83 protected function __construct () {
84 // Call parent constructor
85 parent::__construct(__CLASS__);
89 * Create an object of CachedLocalFileDatabase and set the save path from
90 * configuration for local files.
92 * @return $databaseInstance An instance of CachedLocalFileDatabase
94 public static final function createCachedLocalFileDatabase () {
96 $databaseInstance = new CachedLocalFileDatabase();
98 // Get a new compressor channel instance
99 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
101 // Set the compressor channel
102 $databaseInstance->setCompressorChannel($compressorInstance);
104 // Get a file IO handler
105 $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
108 $databaseInstance->setFileIoInstance($fileIoInstance);
110 // "Connect" to the database
111 $databaseInstance->connectToDatabase();
113 // Return database instance
114 return $databaseInstance;
118 * Setter for the last read file
120 * @param $infoInstance The FQFN of the last read file
123 private final function setLastFile (SplFileInfo $infoInstance) {
124 // Cast string and set it
125 $this->lastFile = $infoInstance;
129 * Getter for last read file
131 * @return $lastFile The last read file's name with full path
133 public final function getLastFile () {
134 return $this->lastFile;
138 * Setter for contents of the last read file
140 * @param $contents An array with header and data elements
143 private final function setLastFileContents (array $contents) {
145 $this->lastContents = $contents;
149 * Getter for last read file's content as an array
151 * @return $lastContent The array with elements 'header' and 'data'.
153 public final function getLastContents () {
154 return $this->lastContents;
158 * Getter for file extension
160 * @return $fileExtension The array with elements 'header' and 'data'.
162 public final function getFileExtension () {
163 return $this->fileExtension;
167 * Getter for index key
169 * @return $indexKey Index key
171 public final function getIndexKey () {
172 return $this->indexKey;
176 * Reads a local data file and returns it's contents in an array
178 * @param $infoInstance An instance of a SplFileInfo class
181 private function getDataArrayFromFile (SplFileInfo $infoInstance) {
183 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Reading elements from database file ' . $infoInstance . ' ...');
185 // Init compressed data
186 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
187 $compressedData = $compressedData['data'];
190 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
193 $dataArray = json_decode($serializedData, true);
196 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
197 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, true));
204 * Writes data array to local file
206 * @param $infoInstance An instance of a SplFileInfo class
207 * @param $dataArray An array with all the data we shall write
210 private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
213 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, true));
215 // Serialize and compress it
216 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(json_encode($dataArray));
219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
221 // Write this data BASE64 encoded to the file
222 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
225 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
229 * Getter for table information file contents or an empty if info file was not created
231 * @param $dataSetInstance An instance of a database set class
232 * @return $infoArray An array with all table informations
234 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
235 // Default content is no data
236 $infoArray = array();
238 // Create FQFN for getting the table information file
239 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
241 // Get the file contents
243 $infoArray = $this->getDataArrayFromFile($infoInstance);
244 } catch (FileNotFoundException $e) {
245 // Not found, so ignore it here
253 * Generates a file info class from given dataset instance and string
255 * @param $dataSetInstance An instance of a database set class
256 * @param $rowName Name of the row
257 * @return $infoInstance An instance of a SplFileInfo class
259 private function generateFileFromDataSet (Criteria $dataSetInstance, $rowName) {
260 // Instanciate new file object
261 $infoInstance = new SplFileInfo($this->getConfigInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
264 return $infoInstance;
268 * Creates the table info file from given dataset instance
270 * @param $dataSetInstance An instance of a database set class
273 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
274 // Create FQFN for creating the table information file
275 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
277 // Get the data out from dataset in a local array
278 $this->tableInfo[$dataSetInstance->getTableName()] = array(
279 'primary' => $dataSetInstance->getPrimaryKey(),
281 'last_updated' => time()
284 // Write the data to the file
285 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
289 * Updates the table info file from given dataset instance
291 * @param $dataSetInstance An instance of a database set class
294 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
295 // Get table name from criteria
296 $tableName = $dataSetInstance->getTableName();
298 // Create FQFN for creating the table information file
299 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
301 // Get the data out from dataset in a local array
302 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
303 $this->tableInfo[$tableName]['last_updated'] = time();
305 // Write the data to the file
306 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
310 * Updates the primary key information or creates the table info file if not found
312 * @param $dataSetInstance An instance of a database set class
315 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
316 // Get table name from criteria
317 $tableName = $dataSetInstance->getTableName();
319 // Get the information array from lower method
320 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
322 // Is the primary key there?
323 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableInfo=' . print_r($this->tableInfo, true));
324 if (!isset($this->tableInfo[$tableName]['primary'])) {
325 // Then create the info file
326 $this->createTableInfoFile($dataSetInstance);
327 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
328 // Set the array element
329 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
332 $this->updateTableInfoFile($dataSetInstance);
337 * Makes sure that the database connection is alive
340 * @todo Do some checks on the database directory and files here
342 public function connectToDatabase () {
346 * Starts a SELECT query on the database by given return type, table name
347 * and search criteria
349 * @param $tableName Name of the database table
350 * @param $searchInstance Local search criteria class
351 * @return $resultData Result data of the query
352 * @throws UnsupportedCriteriaException If the criteria is unsupported
353 * @throws SqlException If an 'SQL error' occurs
355 public function querySelect ($tableName, LocalSearchCriteria $searchInstance) {
357 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ' - CALLED!');
359 // The result is null by any errors
362 // Create full path name
363 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
366 * A 'select' query is not that easy on local files, so first try to
367 * find the 'table' which is in fact a directory on the server
370 // Get a directory pointer instance
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 => array()
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))) {
387 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
389 // Does the extension match?
390 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
396 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
397 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: 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 foreach ($dataArray as $key => $value) {
406 // Make sure value is not bool
407 assert(!is_bool($value));
410 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
411 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: key=' . $key . ',value=' . $value . ',isFound=' . intval($isFound));
415 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: isFound=' . intval($isFound) . ',limitFound=' . $limitFound . ',limit=' . $searchInstance->getLimit());
416 if ($isFound === true) {
417 // Shall we skip this entry?
418 if ($searchInstance->getSkip() > 0) {
419 // We shall skip some entries
420 if ($skipFound < $searchInstance->getSkip()) {
428 $dataArray[$this->getIndexKey()] = $idx;
431 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, true));
432 array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
434 // Count found entries up
438 // Throw an exception here
439 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
446 // Close directory and throw the instance away
447 $directoryInstance->closeDirectory();
448 unset($directoryInstance);
450 // Reset last exception
451 $this->resetLastException();
452 } catch (PathIsNoDirectoryException $e) {
453 // Path not found means "table not found" for real databases...
454 $this->setLastException($e);
456 // So throw an SqlException here with faked error message
457 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
458 } catch (FrameworkException $e) {
459 // Catch all exceptions and store them in last error
460 $this->setLastException($e);
463 // Return the gathered result
468 * "Inserts" a data set instance into a local file database folder
470 * @param $dataSetInstance A storeable data set
472 * @throws SqlException If an SQL error occurs
474 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
475 // Try to save the request away
477 // Create full path name
478 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
480 // Write the data away
481 $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
483 // Update the primary key
484 $this->updatePrimaryKey($dataSetInstance);
486 // Reset last exception
487 $this->resetLastException();
488 } catch (FrameworkException $e) {
489 // Catch all exceptions and store them in last error
490 $this->setLastException($e);
492 // Throw an SQL exception
493 throw new SqlException(array(
495 sprintf('Cannot write data to table '%s', is the table created?', $dataSetInstance->getTableName()),
496 self::DB_CODE_TABLE_UNWRITEABLE
498 self::EXCEPTION_SQL_QUERY
504 * "Updates" a data set instance with a database layer
506 * @param $dataSetInstance A storeable data set
508 * @throws SqlException If an SQL error occurs
510 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
511 // Create full path name
512 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
514 // Try all the requests
516 // Get a file pointer instance
517 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
519 // Initialize limit/skip
523 // Get the criteria array from the dataset
524 $searchArray = $dataSetInstance->getCriteriaArray();
526 // Get search criteria
527 $searchInstance = $dataSetInstance->getSearchInstance();
529 // Read the directory with some exceptions
530 while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
532 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
534 // Does the extension match?
535 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
537 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
542 // Open this file for reading
543 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
544 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
547 if (is_array($dataArray)) {
548 // Default is nothing found
551 // Search in the criteria with FMFW (First Matches, First Wins)
552 foreach ($dataArray as $key => $value) {
553 // Make sure value is not bool
554 assert(!is_bool($value));
557 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
561 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: isFound=' . intval($isFound));
562 if ($isFound === true) {
563 // Shall we skip this entry?
564 if ($searchInstance->getSkip() > 0) {
565 // We shall skip some entries
566 if ($skipFound < $searchInstance->getSkip()) {
568 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Found entry, but skipping ...');
574 // Entry found, so update it
575 foreach ($searchArray as $searchKey => $searchValue) {
576 // Make sure the value is not bool again
577 assert(!is_bool($searchValue));
578 assert($searchKey != $this->indexKey);
580 // Debug message + add/update it
581 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
582 $dataArray[$searchKey] = $searchValue;
585 // Write the data to a local file
586 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Writing dataArray()=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
587 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
589 // Count found entries up
595 // Close the file pointer
596 $directoryInstance->closeDirectory();
598 // Update the primary key
599 $this->updatePrimaryKey($dataSetInstance);
601 // Reset last exception
602 $this->resetLastException();
603 } catch (FrameworkException $e) {
604 // Catch all exceptions and store them in last error
605 $this->setLastException($e);
607 // Throw an SQL exception
608 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);
613 * Getter for primary key of specified table or if not found null will be
614 * returned. This must be database-specific.
616 * @param $tableName Name of the table we need the primary key from
617 * @return $primaryKey Primary key column of the given table
618 * @todo Rename method to getPrimaryKeyFromTableInfo()
620 public function getPrimaryKeyOfTable ($tableName) {
621 // Default key is null
624 // Does the table information exist?
625 if (isset($this->tableInfo[$tableName])) {
626 // Then return the primary key
627 $primaryKey = $this->tableInfo[$tableName]['primary'];
635 * Removes non-public data from given array.
637 * @param $data An array with possible non-public data that needs to be removed.
638 * @return $data A cleaned up array with only public data.
639 * @todo Add more generic non-public data for removal
641 public function removeNonPublicDataFromArray (array $data) {
643 unset($data[$this->indexKey]);
646 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: data[' . gettype($data) . ']='.print_r($data, true));
651 * Counts total rows of given table
653 * @param $tableName Table name
654 * @return $count Total rows of given table
656 public function countTotalRows($tableName) {
657 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ' - CALLED!');
659 // Create full path name
660 $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
662 // Try all the requests
664 // Get a file pointer instance
665 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
667 // Initialize counter
670 // Read the directory with some exceptions
671 while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
673 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
675 // Does the extension match?
676 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
678 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
684 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
687 } catch (FrameworkException $e) {
688 // Catch all exceptions and store them in last error
689 $this->setLastException($e);
691 // Throw an SQL exception
692 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);
696 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');