3 namespace CoreFramework\Database\Backend\Lfdb;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Generic\FrameworkException;
10 * Database backend class for storing objects in locally created files.
12 * This class serializes arrays stored in the dataset instance and saves them
13 * to local files. Every file (except 'info') represents a single line. Every
14 * directory within the 'db' (base) directory represents a table.
16 * A configurable 'file_io_class' is being used as "storage backend".
18 * @author Roland Haeder <webmaster@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.shipsimu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
39 * The file's extension
41 private $fileExtension = 'serialized';
44 * The last read file's name
46 private $lastFile = '';
49 * The last read file's content including header information
51 private $lastContents = array();
54 * Whether the "connection is already up
56 private $alreadyConnected = FALSE;
59 * Table information array
61 private $tableInfo = array();
66 private $indexKey = '__idx';
69 * The protected constructor. Do never instance from outside! You need to
70 * set a local file path. The class will then validate it.
74 protected function __construct () {
75 // Call parent constructor
76 parent::__construct(__CLASS__);
80 * Create an object of CachedLocalFileDatabase and set the save path from
81 * configuration for local files.
83 * @return $databaseInstance An instance of CachedLocalFileDatabase
85 public static final function createCachedLocalFileDatabase () {
87 $databaseInstance = new CachedLocalFileDatabase();
89 // Get a new compressor channel instance
90 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
92 // Set the compressor channel
93 $databaseInstance->setCompressorChannel($compressorInstance);
95 // Get a file IO handler
96 $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
99 $databaseInstance->setFileIoInstance($fileIoInstance);
101 // "Connect" to the database
102 $databaseInstance->connectToDatabase();
104 // Return database instance
105 return $databaseInstance;
109 * Setter for the last read file
111 * @param $fqfn The FQFN of the last read file
114 private final function setLastFile ($fqfn) {
115 // Cast string and set it
116 $this->lastFile = (string) $fqfn;
120 * Getter for last read file
122 * @return $lastFile The last read file's name with full path
124 public final function getLastFile () {
125 return $this->lastFile;
129 * Setter for contents of the last read file
131 * @param $contents An array with header and data elements
134 private final function setLastFileContents (array $contents) {
136 $this->lastContents = $contents;
140 * Getter for last read file's content as an array
142 * @return $lastContent The array with elements 'header' and 'data'.
144 public final function getLastContents () {
145 return $this->lastContents;
149 * Getter for file extension
151 * @return $fileExtension The array with elements 'header' and 'data'.
153 public final function getFileExtension () {
154 return $this->fileExtension;
158 * Getter for index key
160 * @return $indexKey Index key
162 public final function getIndexKey () {
163 return $this->indexKey;
167 * Reads a local data file and returns it's contents in an array
169 * @param $fqfn The FQFN for the requested file
172 private function getDataArrayFromFile ($fqfn) {
174 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Reading elements from database file ' . $fqfn . ' ...');
176 // Init compressed data
177 $compressedData = $this->getFileIoInstance()->loadFileContents($fqfn);
178 $compressedData = $compressedData['data'];
180 // Close the file and throw the instance away
181 unset($fileInstance);
184 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
187 $dataArray = json_decode($serializedData, TRUE);
190 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Read ' . count($dataArray) . ' elements from database file ' . $fqfn . '.');
191 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, TRUE));
198 * Writes data array to local file
200 * @param $fqfn The FQFN of the local file
201 * @param $dataArray An array with all the data we shall write
204 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $fqfn . ' ...');
207 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, TRUE));
209 // Serialize and compress it
210 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(json_encode($dataArray));
213 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
215 // Write this data BASE64 encoded to the file
216 $this->getFileIoInstance()->saveStreamToFile($fqfn, $compressedData, $this);
219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
223 * Getter for table information file contents or an empty if info file was not created
225 * @param $dataSetInstance An instance of a database set class
226 * @return $infoArray An array with all table informations
228 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
229 // Default content is no data
230 $infoArray = array();
232 // Create FQFN for getting the table information file
233 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
235 // Get the file contents
237 $infoArray = $this->getDataArrayFromFile($fqfn);
238 } catch (FileNotFoundException $e) {
239 // Not found, so ignore it here
247 * Generates an FQFN from given dataset instance and string
249 * @param $dataSetInstance An instance of a database set class
250 * @param $rowName Name of the row
251 * @return $fqfn The FQFN for this row
253 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
255 $fqfn = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
262 * Creates the table info file from given dataset instance
264 * @param $dataSetInstance An instance of a database set class
267 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
268 // Create FQFN for creating the table information file
269 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
271 // Get the data out from dataset in a local array
272 $this->tableInfo[$dataSetInstance->getTableName()] = array(
273 'primary' => $dataSetInstance->getPrimaryKey(),
275 'last_updated' => time()
278 // Write the data to the file
279 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
283 * Updates the table info file from given dataset instance
285 * @param $dataSetInstance An instance of a database set class
288 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
289 // Get table name from criteria
290 $tableName = $dataSetInstance->getTableName();
292 // Create FQFN for creating the table information file
293 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
295 // Get the data out from dataset in a local array
296 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
297 $this->tableInfo[$tableName]['last_updated'] = time();
299 // Write the data to the file
300 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$tableName]);
304 * Updates the primary key information or creates the table info file if not found
306 * @param $dataSetInstance An instance of a database set class
309 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
310 // Get table name from criteria
311 $tableName = $dataSetInstance->getTableName();
313 // Get the information array from lower method
314 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
316 // Is the primary key there?
317 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableInfo=' . print_r($this->tableInfo, TRUE));
318 if (!isset($this->tableInfo[$tableName]['primary'])) {
319 // Then create the info file
320 $this->createTableInfoFile($dataSetInstance);
321 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
322 // Set the array element
323 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
326 $this->updateTableInfoFile($dataSetInstance);
331 * Makes sure that the database connection is alive
334 * @todo Do some checks on the database directory and files here
336 public function connectToDatabase () {
340 * Starts a SELECT query on the database by given return type, table name
341 * and search criteria
343 * @param $tableName Name of the database table
344 * @param $searchInstance Local search criteria class
345 * @return $resultData Result data of the query
346 * @throws UnsupportedCriteriaException If the criteria is unsupported
347 * @throws SqlException If an 'SQL error' occurs
349 public function querySelect ($tableName, LocalSearchCriteria $searchInstance) {
351 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ' - CALLED!');
353 // The result is null by any errors
356 // Create full path name
357 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
360 * A 'select' query is not that easy on local files, so first try to
361 * find the 'table' which is in fact a directory on the server
364 // Get a directory pointer instance
365 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
367 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
369 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
370 BaseDatabaseBackend::RESULT_INDEX_ROWS => array()
373 // Initialize limit/skip
378 // Read the directory with some exceptions
379 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
381 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',this->getFileExtension()=' . $this->getFileExtension());
383 // Does the extension match?
384 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
390 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
391 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray, TRUE));
394 if (is_array($dataArray)) {
395 // Default is nothing found
398 // Search in the criteria with FMFW (First Matches, First Wins)
399 foreach ($dataArray as $key => $value) {
400 // Make sure value is not bool
401 assert(!is_bool($value));
404 $isFound = (($isFound === TRUE) && ($searchInstance->isCriteriaMatching($key, $value)));
405 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: key=' . $key . ',value=' . $value . ',isFound=' . intval($isFound));
409 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: isFound=' . intval($isFound) . ',limitFound=' . $limitFound . ',limit=' . $searchInstance->getLimit());
410 if ($isFound === TRUE) {
411 // Shall we skip this entry?
412 if ($searchInstance->getSkip() > 0) {
413 // We shall skip some entries
414 if ($skipFound < $searchInstance->getSkip()) {
422 $dataArray[$this->getIndexKey()] = $idx;
425 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, TRUE));
426 array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
428 // Count found entries up
432 // Throw an exception here
433 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
440 // Close directory and throw the instance away
441 $directoryInstance->closeDirectory();
442 unset($directoryInstance);
444 // Reset last exception
445 $this->resetLastException();
446 } catch (PathIsNoDirectoryException $e) {
447 // Path not found means "table not found" for real databases...
448 $this->setLastException($e);
450 // So throw an SqlException here with faked error message
451 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
452 } catch (FrameworkException $e) {
453 // Catch all exceptions and store them in last error
454 $this->setLastException($e);
457 // Return the gathered result
462 * "Inserts" a data set instance into a local file database folder
464 * @param $dataSetInstance A storeable data set
466 * @throws SqlException If an SQL error occurs
468 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
469 // Try to save the request away
471 // Create full path name
472 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
474 // Write the data away
475 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
477 // Update the primary key
478 $this->updatePrimaryKey($dataSetInstance);
480 // Reset last exception
481 $this->resetLastException();
482 } catch (FrameworkException $e) {
483 // Catch all exceptions and store them in last error
484 $this->setLastException($e);
486 // Throw an SQL exception
487 throw new SqlException(array($this, sprintf('Cannot write data to table '%s', is the table created?', $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
492 * "Updates" a data set instance with a database layer
494 * @param $dataSetInstance A storeable data set
496 * @throws SqlException If an SQL error occurs
498 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
499 // Create full path name
500 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/';
502 // Try all the requests
504 // Get a file pointer instance
505 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
507 // Initialize limit/skip
511 // Get the criteria array from the dataset
512 $searchArray = $dataSetInstance->getCriteriaArray();
514 // Get search criteria
515 $searchInstance = $dataSetInstance->getSearchInstance();
517 // Read the directory with some exceptions
518 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
519 // Does the extension match?
520 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
522 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
527 // Open this file for reading
528 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
529 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray, TRUE));
532 if (is_array($dataArray)) {
533 // Default is nothing found
536 // Search in the criteria with FMFW (First Matches, First Wins)
537 foreach ($dataArray as $key => $value) {
538 // Make sure value is not bool
539 assert(!is_bool($value));
542 $isFound = (($isFound === TRUE) && ($searchInstance->isCriteriaMatching($key, $value)));
546 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: isFound=' . intval($isFound));
547 if ($isFound === TRUE) {
548 // Shall we skip this entry?
549 if ($searchInstance->getSkip() > 0) {
550 // We shall skip some entries
551 if ($skipFound < $searchInstance->getSkip()) {
553 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Found entry, but skipping ...');
559 // Entry found, so update it
560 foreach ($searchArray as $searchKey => $searchValue) {
561 // Make sure the value is not bool again
562 assert(!is_bool($searchValue));
563 assert($searchKey != $this->indexKey);
565 // Debug message + add/update it
566 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
567 $dataArray[$searchKey] = $searchValue;
570 // Write the data to a local file
571 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Writing dataArray()=' . count($dataArray) . ' to ' . $dataFile . ' ...');
572 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
574 // Count found entries up
580 // Close the file pointer
581 $directoryInstance->closeDirectory();
583 // Update the primary key
584 $this->updatePrimaryKey($dataSetInstance);
586 // Reset last exception
587 $this->resetLastException();
588 } catch (FrameworkException $e) {
589 // Catch all exceptions and store them in last error
590 $this->setLastException($e);
592 // Throw an SQL exception
593 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);
598 * Getter for primary key of specified table or if not found null will be
599 * returned. This must be database-specific.
601 * @param $tableName Name of the table we need the primary key from
602 * @return $primaryKey Primary key column of the given table
604 public function getPrimaryKeyOfTable ($tableName) {
605 // Default key is null
608 // Does the table information exist?
609 if (isset($this->tableInfo[$tableName])) {
610 // Then return the primary key
611 $primaryKey = $this->tableInfo[$tableName]['primary'];
619 * Removes non-public data from given array.
621 * @param $data An array with possible non-public data that needs to be removed.
622 * @return $data A cleaned up array with only public data.
623 * @todo Add more generic non-public data for removal
625 public function removeNonPublicDataFromArray (array $data) {
627 unset($data[$this->indexKey]);
630 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: data[' . gettype($data) . ']='.print_r($data, TRUE));
635 * Counts total rows of given table
637 * @param $tableName Table name
638 * @return $count Total rows of given table
640 public function countTotalRows($tableName) {
641 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ' - CALLED!');
643 // Create full path name
644 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
646 // Try all the requests
648 // Get a file pointer instance
649 $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
651 // Initialize counter
654 // Read the directory with some exceptions
655 while ($dataFile = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
656 // Does the extension match?
657 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
659 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
665 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
668 } catch (FrameworkException $e) {
669 // Catch all exceptions and store them in last error
670 $this->setLastException($e);
672 // Throw an SQL exception
673 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);
677 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');