3 * Database backend class for storing objects in locally created files.
5 * This class serializes arrays stored in the dataset instance and saves them
6 * to local files. Every file (except 'info') represents a single line. Every
7 * directory within the 'db' (base) directory represents a table.
9 * A configurable 'file_io_class' is being used as "storage backend".
11 * @author Roland Haeder <webmaster@shipsimu.org>
13 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
14 * @license GNU GPL 3.0 or any newer version
15 * @link http://www.shipsimu.org
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 class LocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
32 * The file's extension
34 private $fileExtension = 'serialized';
37 * The last read file's name
39 private $lastFile = '';
42 * The last read file's content including header information
44 private $lastContents = array();
47 * Whether the "connection is already up
49 private $alreadyConnected = FALSE;
52 * Table information array
54 private $tableInfo = array();
59 private $indexKey = '__idx';
62 * The protected constructor. Do never instance from outside! You need to
63 * set a local file path. The class will then validate it.
67 protected function __construct () {
68 // Call parent constructor
69 parent::__construct(__CLASS__);
73 * Create an object of LocalFileDatabase and set the save path from
74 * configuration for local files.
76 * @return $databaseInstance An instance of LocalFileDatabase
78 public static final function createLocalFileDatabase () {
80 $databaseInstance = new LocalFileDatabase();
82 // Get a new compressor channel instance
83 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
85 // Set the compressor channel
86 $databaseInstance->setCompressorChannel($compressorInstance);
88 // Get a file IO handler
89 $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
92 $databaseInstance->setFileIoInstance($fileIoInstance);
94 // "Connect" to the database
95 $databaseInstance->connectToDatabase();
97 // Return database instance
98 return $databaseInstance;
102 * Setter for the last read file
104 * @param $fqfn The FQFN of the last read file
107 private final function setLastFile ($fqfn) {
108 // Cast string and set it
109 $this->lastFile = (string) $fqfn;
113 * Getter for last read file
115 * @return $lastFile The last read file's name with full path
117 public final function getLastFile () {
118 return $this->lastFile;
122 * Setter for contents of the last read file
124 * @param $contents An array with header and data elements
127 private final function setLastFileContents (array $contents) {
129 $this->lastContents = $contents;
133 * Getter for last read file's content as an array
135 * @return $lastContent The array with elements 'header' and 'data'.
137 public final function getLastContents () {
138 return $this->lastContents;
142 * Getter for file extension
144 * @return $fileExtension The array with elements 'header' and 'data'.
146 public final function getFileExtension () {
147 return $this->fileExtension;
151 * Getter for index key
153 * @return $indexKey Index key
155 public final function getIndexKey () {
156 return $this->indexKey;
160 * Reads a local data file and returns it's contents in an array
162 * @param $fqfn The FQFN for the requested file
165 private function getDataArrayFromFile ($fqfn) {
167 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Reading elements from database file ' . $fqfn . ' ...');
169 // Init compressed data
170 $compressedData = $this->getFileIoInstance()->loadFileContents($fqfn);
171 $compressedData = $compressedData['data'];
173 // Close the file and throw the instance away
174 unset($fileInstance);
177 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
180 $dataArray = unserialize($serializedData);
183 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Read ' . count($dataArray) . ' elements from database file ' . $fqfn . '.');
184 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, TRUE));
191 * Writes data array to local file
193 * @param $fqfn The FQFN of the local file
194 * @param $dataArray An array with all the data we shall write
197 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
199 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $fqfn . ' ...');
200 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, TRUE));
202 // Serialize and compress it
203 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
208 // Write this data BASE64 encoded to the file
209 $this->getFileIoInstance()->saveFile($fqfn, $compressedData, $this);
212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
216 * Getter for table information file contents or an empty if info file was not created
218 * @param $dataSetInstance An instance of a database set class
219 * @return $infoArray An array with all table informations
221 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
222 // Default content is no data
223 $infoArray = array();
225 // Create FQFN for getting the table information file
226 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
228 // Get the file contents
230 $infoArray = $this->getDataArrayFromFile($fqfn);
231 } catch (FileIoException $e) {
232 // Not found, so ignore it here
240 * Generates an FQFN from given dataset instance and string
242 * @param $dataSetInstance An instance of a database set class
243 * @param $rowName Name of the row
244 * @return $fqfn The FQFN for this row
246 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
248 $fqfn = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
255 * Creates the table info file from given dataset instance
257 * @param $dataSetInstance An instance of a database set class
260 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
261 // Create FQFN for creating the table information file
262 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
264 // Get the data out from dataset in a local array
265 $this->tableInfo[$dataSetInstance->getTableName()] = array(
266 'primary' => $dataSetInstance->getPrimaryKey(),
268 'last_updated' => time()
271 // Write the data to the file
272 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
276 * Updates the table info file from given dataset instance
278 * @param $dataSetInstance An instance of a database set class
281 private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
282 // "Cache" table name
283 $tableName = $dataSetInstance->getTableName();
285 // Create FQFN for creating the table information file
286 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
288 // Get the data out from dataset in a local array
289 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
290 $this->tableInfo[$tableName]['last_updated'] = time();
292 // Write the data to the file
293 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$tableName]);
297 * Updates the primary key information or creates the table info file if not found
299 * @param $dataSetInstance An instance of a database set class
302 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
303 // "Cache" table name
304 $tableName = $dataSetInstance->getTableName();
306 // Get the information array from lower method
307 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
309 // Is the primary key there?
310 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: tableInfo=' . print_r($this->tableInfo, TRUE));
311 if (!isset($this->tableInfo[$tableName]['primary'])) {
312 // Then create the info file
313 $this->createTableInfoFile($dataSetInstance);
314 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
315 // Set the array element
316 $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
319 $this->updateTableInfoFile($dataSetInstance);
324 * Makes sure that the database connection is alive
327 * @todo Do some checks on the database directory and files here
329 public function connectToDatabase () {
333 * Starts a SELECT query on the database by given return type, table name
334 * and search criteria
336 * @param $tableName Name of the database table
337 * @param $searchInstance Local search criteria class
338 * @return $resultData Result data of the query
339 * @throws UnsupportedCriteriaException If the criteria is unsupported
340 * @throws SqlException If an 'SQL error' occurs
342 public function querySelect ($tableName, LocalSearchCriteria $searchInstance) {
343 // The result is null by any errors
346 // Create full path name
347 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
349 // A 'select' query is not that easy on local files, so first try to
350 // find the 'table' which is in fact a directory on the server
352 // Get a directory pointer instance
353 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
355 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
357 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
358 BaseDatabaseBackend::RESULT_INDEX_ROWS => array()
361 // Initialize limit/skip
366 // Read the directory with some exceptions
367 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
368 // Does the extension match?
369 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
375 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
376 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray, TRUE));
379 if (is_array($dataArray)) {
380 // Default is nothing found
383 // Search in the criteria with FMFW (First Matches, First Wins)
384 foreach ($dataArray as $key => $value) {
385 // Make sure value is not bool
386 assert(!is_bool($value));
389 $isFound = (($isFound === TRUE) && ($searchInstance->isCriteriaMatching($key, $value)));
390 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: key=' . $key . ',value=' . $value . ',isFound=' . intval($isFound));
394 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: isFound=' . intval($isFound) . ',limitFound=' . $limitFound . ',limit=' . $searchInstance->getLimit());
395 if ($isFound === TRUE) {
396 // Shall we skip this entry?
397 if ($searchInstance->getSkip() > 0) {
398 // We shall skip some entries
399 if ($skipFound < $searchInstance->getSkip()) {
407 $dataArray[$this->getIndexKey()] = $idx;
410 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, TRUE));
411 array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
413 // Count found entries up
417 // Throw an exception here
418 throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
425 // Close directory and throw the instance away
426 $directoryInstance->closeDirectory();
427 unset($directoryInstance);
429 // Reset last exception
430 $this->resetLastException();
431 } catch (PathIsNoDirectoryException $e) {
432 // Path not found means "table not found" for real databases...
433 $this->setLastException($e);
435 // So throw an SqlException here with faked error message
436 throw new SqlException (array($this, sprintf('Table '%s' not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
437 } catch (FrameworkException $e) {
438 // Catch all exceptions and store them in last error
439 $this->setLastException($e);
442 // Return the gathered result
447 * "Inserts" a data set instance into a local file database folder
449 * @param $dataSetInstance A storeable data set
451 * @throws SqlException If an SQL error occurs
453 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
454 // Try to save the request away
456 // Create full path name
457 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
459 // Write the data away
460 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
462 // Update the primary key
463 $this->updatePrimaryKey($dataSetInstance);
465 // Reset last exception
466 $this->resetLastException();
467 } catch (FrameworkException $e) {
468 // Catch all exceptions and store them in last error
469 $this->setLastException($e);
471 // Throw an SQL exception
472 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);
477 * "Updates" a data set instance with a database layer
479 * @param $dataSetInstance A storeable data set
481 * @throws SqlException If an SQL error occurs
483 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
484 // Create full path name
485 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/';
487 // Try all the requests
489 // Get a file pointer instance
490 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
492 // Initialize limit/skip
496 // Get the criteria array from the dataset
497 $searchArray = $dataSetInstance->getCriteriaArray();
499 // Get search criteria
500 $searchInstance = $dataSetInstance->getSearchInstance();
502 // Read the directory with some exceptions
503 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
504 // Does the extension match?
505 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
507 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
512 // Open this file for reading
513 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
514 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray, TRUE));
517 if (is_array($dataArray)) {
518 // Default is nothing found
521 // Search in the criteria with FMFW (First Matches, First Wins)
522 foreach ($dataArray as $key => $value) {
523 // Make sure value is not bool
524 assert(!is_bool($value));
527 $isFound = (($isFound === TRUE) && ($searchInstance->isCriteriaMatching($key, $value)));
531 if ($isFound === TRUE) {
532 // Shall we skip this entry?
533 if ($searchInstance->getSkip() > 0) {
534 // We shall skip some entries
535 if ($skipFound < $searchInstance->getSkip()) {
542 // Entry found, so update it
543 foreach ($searchArray as $searchKey => $searchValue) {
544 // Make sure the value is not bool again
545 assert(!is_bool($searchValue));
546 assert($searchKey != $this->indexKey);
548 // Debug message + add/update it
549 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
550 $dataArray[$searchKey] = $searchValue;
553 // Write the data to a local file
554 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
556 // Count found entries up
562 // Close the file pointer
563 $directoryInstance->closeDirectory();
565 // Update the primary key
566 $this->updatePrimaryKey($dataSetInstance);
568 // Reset last exception
569 $this->resetLastException();
570 } catch (FrameworkException $e) {
571 // Catch all exceptions and store them in last error
572 $this->setLastException($e);
574 // Throw an SQL exception
575 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);
580 * Getter for primary key of specified table or if not found null will be
581 * returned. This must be database-specific.
583 * @param $tableName Name of the table we need the primary key from
584 * @return $primaryKey Primary key column of the given table
586 public function getPrimaryKeyOfTable ($tableName) {
587 // Default key is null
590 // Does the table information exist?
591 if (isset($this->tableInfo[$tableName])) {
592 // Then return the primary key
593 $primaryKey = $this->tableInfo[$tableName]['primary'];