3 * Database backend class for storing objects in locally created files.
5 * This class serializes objects and saves them to local files.
7 * @author Roland Haeder <webmaster@ship-simu.org>
9 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
10 * @license GNU GPL 3.0 or any newer version
11 * @link http://www.ship-simu.org
13 * This program is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation, either version 3 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontendInterface {
27 // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
28 const DB_CODE_TABLE_MISSING = 0x100;
29 const DB_CODE_TABLE_UNWRITEABLE = 0x101;
30 const DB_CODE_DATA_FILE_CORRUPT = 0x102;
33 const RESULT_OKAY = 'ok';
36 * The file's extension
38 private $fileExtension = 'serialized';
41 * The last read file's name
43 private $lastFile = '';
46 * The last read file's content including header information
48 private $lastContents = array();
51 * Whether the "connection is already up
53 private $alreadyConnected = false;
58 private $lastException = NULL;
61 * Table information array
63 private $tableInfo = array();
68 private $indexKey = '__idx';
71 * The protected constructor. Do never instance from outside! You need to
72 * set a local file path. The class will then validate it.
76 protected function __construct () {
77 // Call parent constructor
78 parent::__construct(__CLASS__);
82 * Create an object of LocalFileDatabase and set the save path from
83 * configuration for local files.
85 * @return $databaseInstance An instance of LocalFileDatabase
87 public static final function createLocalFileDatabase () {
89 $databaseInstance = new LocalFileDatabase();
91 // Get a new compressor channel instance
92 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
94 // Set the compressor channel
95 $databaseInstance->setCompressorChannel($compressorInstance);
97 // "Connect" to the database
98 $databaseInstance->connectToDatabase();
100 // Return database instance
101 return $databaseInstance;
105 * Getter for last exception
107 * @return $lastException Last thrown exception
109 public final function getLastException () {
110 return $this->lastException;
114 * Setter for the last read file
116 * @param $fqfn The FQFN of the last read file
119 private final function setLastFile ($fqfn) {
120 // Cast string and set it
121 $this->lastFile = (string) $fqfn;
125 * Reset the last exception instance. This should be done after a "query"
126 * was completed without any errors.
130 private final function resetLastException () {
131 $this->lastException = NULL;
135 * Getter for last read file
137 * @return $lastFile The last read file's name with full path
139 public final function getLastFile () {
140 return $this->lastFile;
144 * Setter for contents of the last read file
146 * @param $contents An array with header and data elements
149 private final function setLastFileContents (array $contents) {
151 $this->lastContents = $contents;
155 * Getter for last read file's content as an array
157 * @return $lastContent The array with elements 'header' and 'data'.
159 public final function getLastContents () {
160 return $this->lastContents;
164 * Getter for file extension
166 * @return $fileExtension The array with elements 'header' and 'data'.
168 public final function getFileExtension () {
169 return $this->fileExtension;
173 * Getter for index key
175 * @return $indexKey Index key
177 public final function getIndexKey () {
178 return $this->indexKey;
182 * Reads a local data file and returns it's contents in an array
184 * @param $fqfn The FQFN for the requested file
187 private function getDataArrayFromFile ($fqfn) {
188 // Get a file pointer
189 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
191 // Get the raw data and BASE64-decode it
192 $compressedData = base64_decode($fileInstance->readLinesFromFile());
194 // Close the file and throw the instance away
195 $fileInstance->closeFile();
196 unset($fileInstance);
199 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
202 $dataArray = unserialize($serializedData);
209 * Writes data array to local file
211 * @param $fqfn The FQFN of the local file
212 * @param $dataArray An array with all the data we shall write
215 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
216 // Get a file pointer instance
217 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
219 // Serialize and compress it
220 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
222 // Write this data BASE64 encoded to the file
223 $fileInstance->writeToFile(base64_encode($compressedData));
225 // Close the file pointer
226 $fileInstance->closeFile();
230 * Getter for table information file contents or an empty if info file was not created
232 * @param $dataSetInstance An instance of a database set class
233 * @return $infoArray An array with all table informations
235 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
236 // Default content is no data
237 $infoArray = array();
239 // Create FQFN for getting the table information file
240 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
242 // Get the file contents
244 $infoArray = $this->getDataArrayFromFile($fqfn);
245 } catch (FileIoException $e) {
246 // Not found, so ignore it here
254 * Generates an FQFN from given dataset instance and string
256 * @param $dataSetInstance An instance of a database set class
257 * @param $rowName Name of the row
258 * @return $fqfn The FQFN for this row
260 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
262 $fqfn = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
269 * Creates the table info file from given dataset instance
271 * @param $dataSetInstance An instance of a database set class
274 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
275 // Create FQFN for creating the table information file
276 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
278 // Get the data out from dataset in a local array
279 $this->tableInfo[$dataSetInstance->getTableName()] = array(
280 'primary' => $dataSetInstance->getPrimaryKey(),
282 'last_updated' => time()
285 // Write the data to the file
286 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
290 * Updates the primary key information or creates the table info file if not found
292 * @param $dataSetInstance An instance of a database set class
295 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
296 // Get the information array from lower method
297 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
299 // Is the primary key there?
300 if (!isset($this->tableInfo['primary'])) {
301 // Then create the info file
302 $this->createTableInfoFile($dataSetInstance);
303 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
304 // Set the array element
305 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
308 $this->updateTableInfoFile($dataSetInstance);
313 * Makes sure that the database connection is alive
316 * @todo Do some checks on the database directory and files here
318 public function connectToDatabase () {
322 * Starts a SELECT query on the database by given return type, table name
323 * and search criteria
325 * @param $tableName Name of the database table
326 * @param $criteria Local search criteria class
327 * @return $resultData Result data of the query
328 * @throws UnsupportedCriteriaException If the criteria is unsupported
329 * @throws SqlException If an 'SQL error' occurs
331 public function querySelect ($tableName, LocalSearchCriteria $criteriaInstance) {
332 // The result is null by any errors
335 // Create full path name
336 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
338 // A 'select' query is not that easy on local files, so first try to
339 // find the 'table' which is in fact a directory on the server
341 // Get a directory pointer instance
342 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
344 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
346 BaseDatabaseFrontend::RESULT_INDEX_STATUS => LocalfileDatabase::RESULT_OKAY,
347 BaseDatabaseFrontend::RESULT_INDEX_ROWS => array()
350 // Initialize limit/skip
355 // Read the directory with some exceptions
356 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && (($limitFound < $criteriaInstance->getLimit()) || ($criteriaInstance->getLimit() == 0))) {
357 // Does the extension match?
358 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
364 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
367 if (is_array($dataArray)) {
368 // Search in the criteria with FMFW (First Matches, First Wins)
369 foreach ($dataArray as $key => $value) {
370 // Get criteria element
371 $criteria = $criteriaInstance->getCriteriaElemnent($key);
373 // Is the criteria met?
374 //* NOISY-DEBUG: */ $this->debugOutput('DATABASE: criteria[' . gettype($criteria) . ']=' . $criteria . ',()=' . strlen($criteria) . ',value=' . $value . ',()=' . strlen($value));
375 if ((!is_null($criteria)) && ($criteria == $value)) {
376 // Shall we skip this entry?
377 if ($criteriaInstance->getSkip() > 0) {
378 // We shall skip some entries
379 if ($skipFound < $criteriaInstance->getSkip()) {
387 $dataArray[$this->getIndexKey()] = $idx;
390 //* NOISY-DEBUG: */ $this->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, true));
391 $resultData[BaseDatabaseFrontend::RESULT_INDEX_ROWS][] = $dataArray;
393 // Count found entries up
399 // Throw an exception here
400 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
407 // Close directory and throw the instance away
408 $directoryInstance->closeDirectory();
409 unset($directoryInstance);
411 // Reset last exception
412 $this->resetLastException();
413 } catch (PathIsNoDirectoryException $e) {
414 // Path not found means "table not found" for real databases...
415 $this->lastException = $e;
417 // So throw an SqlException here with faked error message
418 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
419 } catch (FrameworkException $e) {
420 // Catch all exceptions and store them in last error
421 $this->lastException = $e;
424 // Return the gathered result
429 * "Inserts" a data set instance into a local file database folder
431 * @param $dataSetInstance A storeable data set
433 * @throws SqlException If an SQL error occurs
435 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
436 // Create full path name
437 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
439 // Try to save the request away
441 // Write the data away
442 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
444 // Update the primary key
445 $this->updatePrimaryKey($dataSetInstance);
447 // Reset last exception
448 $this->resetLastException();
449 } catch (FrameworkException $e) {
450 // Catch all exceptions and store them in last error
451 $this->lastException = $e;
453 // Throw an SQL exception
454 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);
459 * "Updates" a data set instance with a database layer
461 * @param $dataSetInstance A storeable data set
463 * @throws SqlException If an SQL error occurs
465 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
466 // Create full path name
467 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/';
469 // Try all the requests
471 // Get a file pointer instance
472 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
474 // Initialize limit/skip
478 // Get the criteria array from the dataset
479 $criteriaArray = $dataSetInstance->getCriteriaArray();
481 // Get search criteria
482 $searchInstance = $dataSetInstance->getSearchInstance();
484 // Read the directory with some exceptions
485 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
486 // Does the extension match?
487 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
492 // Open this file for reading
493 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
496 if (is_array($dataArray)) {
497 // Search in the criteria with FMFW (First Matches, First Wins)
498 foreach ($dataArray as $key => $value) {
499 // Get criteria element
500 $criteria = $searchInstance->getCriteriaElemnent($key);
502 // Is the criteria met?
503 if ((!is_null($criteria)) && ($criteria == $value)) {
505 // Shall we skip this entry?
506 if ($searchInstance->getSkip() > 0) {
507 // We shall skip some entries
508 if ($skipFound < $searchInstance->getSkip()) {
515 // Entry found, so update it
516 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
517 $dataArray[$criteriaKey] = $criteriaValue;
520 // Write the data to a local file
521 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
531 // Close the file pointer
532 $directoryInstance->closeDirectory();
534 // Update the primary key
535 $this->updatePrimaryKey($dataSetInstance);
537 // Reset last exception
538 $this->resetLastException();
539 } catch (FrameworkException $e) {
540 // Catch all exceptions and store them in last error
541 $this->lastException = $e;
543 // Throw an SQL exception
544 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);
549 * Getter for primary key of specified table or if not found null will be
550 * returned. This must be database-specific.
552 * @param $tableName Name of the table we need the primary key from
553 * @return $primaryKey Primary key column of the given table
555 public function getPrimaryKeyOfTable ($tableName) {
556 // Default key is null
559 // Does the table information exist?
560 if (isset($this->tableInfo[$tableName])) {
561 // Then return the primary key
562 $primaryKey = $this->tableInfo[$tableName]['primary'];