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 - 2011 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 * Save path for "file database"
38 private $savePath = '';
41 * The file's extension
43 private $fileExtension = 'serialized';
46 * The last read file's name
48 private $lastFile = '';
51 * The last read file's content including header information
53 private $lastContents = array();
56 * Wether the "connection is already up
58 private $alreadyConnected = false;
63 private $lastError = '';
68 private $lastException = null;
71 * Table information array
73 private $tableInfo = array();
78 private $indexKey = '__idx';
81 * The protected constructor. Do never instance from outside! You need to
82 * set a local file path. The class will then validate it.
86 protected function __construct () {
87 // Call parent constructor
88 parent::__construct(__CLASS__);
92 * Create an object of LocalFileDatabase and set the save path for local files.
93 * This method also validates the given file path.
95 * @param $savePath The local file path string
96 * @return $dbInstance An instance of LocalFileDatabase
98 public static final function createLocalFileDatabase ($savePath) {
100 $databaseInstance = new LocalFileDatabase();
102 // Set save path and IO instance
103 $databaseInstance->setSavePath($savePath);
105 // Set the compressor channel
106 $databaseInstance->setCompressorChannel(CompressorChannel::createCompressorChannel(
107 $databaseInstance->getConfigInstance()->getConfigEntry('base_path').
108 $databaseInstance->getConfigInstance()->getConfigEntry('compressor_base_path')
111 // "Connect" to the database
112 $databaseInstance->connectToDatabase();
114 // Return database instance
115 return $databaseInstance;
119 * Setter for save path
121 * @param $savePath The local save path where we shall put our serialized classes
124 public final function setSavePath ($savePath) {
126 $this->savePath = (string) $savePath;
130 * Getter for save path
132 * @return $savePath The local save path where we shall put our serialized classes
134 public final function getSavePath () {
135 return $this->savePath;
139 * Getter for last error message
141 * @return $lastError Last error message
143 public final function getLastError () {
144 return $this->lastError;
148 * Getter for last exception
150 * @return $lastException Last thrown exception
152 public final function getLastException () {
153 return $this->lastException;
157 * Setter for the last read file
159 * @param $fqfn The FQFN of the last read file
162 private final function setLastFile ($fqfn) {
163 // Cast string and set it
164 $this->lastFile = (string) $fqfn;
168 * Reset the last error and exception instance. This should be done after
169 * a successfull "query"
173 private final function resetLastError () {
174 $this->lastError = '';
175 $this->lastException = null;
179 * Getter for last read file
181 * @return $lastFile The last read file's name with full path
183 public final function getLastFile () {
184 return $this->lastFile;
188 * Setter for contents of the last read file
190 * @param $contents An array with header and data elements
193 private final function setLastFileContents (array $contents) {
195 $this->lastContents = $contents;
199 * Getter for last read file's content as an array
201 * @return $lastContent The array with elements 'header' and 'data'.
203 public final function getLastContents () {
204 return $this->lastContents;
208 * Getter for file extension
210 * @return $fileExtension The array with elements 'header' and 'data'.
212 public final function getFileExtension () {
213 return $this->fileExtension;
217 * Getter for index key
219 * @return $indexKey Index key
221 public final function getIndexKey () {
222 return $this->indexKey;
226 * Reads a local data file and returns it's contents in an array
228 * @param $fqfn The FQFN for the requested file
231 private function getDataArrayFromFile ($fqfn) {
232 // Get a file pointer
233 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
235 // Get the raw data and BASE64-decode it
236 $compressedData = base64_decode($fileInstance->readLinesFromFile());
238 // Close the file and throw the instance away
239 $fileInstance->closeFile();
240 unset($fileInstance);
243 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
246 $dataArray = unserialize($serializedData);
253 * Writes data array to local file
255 * @param $fqfn The FQFN of the local file
256 * @param $dataArray An array with all the data we shall write
259 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
260 // Get a file pointer instance
261 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
263 // Serialize and compress it
264 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
266 // Write this data BASE64 encoded to the file
267 $fileInstance->writeToFile(base64_encode($compressedData));
269 // Close the file pointer
270 $fileInstance->closeFile();
274 * Getter for table information file contents or an empty if info file was not created
276 * @param $dataSetInstance An instance of a database set class
277 * @return $infoArray An array with all table informations
279 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
280 // Default content is no data
281 $infoArray = array();
283 // Create FQFN for getting the table information file
284 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
286 // Get the file contents
288 $infoArray = $this->getDataArrayFromFile($fqfn);
289 } catch (FileIoException $e) {
290 // Not found, so ignore it here
298 * Generates an FQFN from given dataset instance and string
300 * @param $dataSetInstance An instance of a database set class
301 * @param $rowName Name of the row
302 * @return $fqfn The FQFN for this row
304 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
306 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
313 * Creates the table info file from given dataset instance
315 * @param $dataSetInstance An instance of a database set class
318 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
319 // Create FQFN for creating the table information file
320 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
322 // Get the data out from dataset in a local array
323 $this->tableInfo[$dataSetInstance->getTableName()] = array(
324 'primary' => $dataSetInstance->getPrimaryKey(),
326 'last_updated' => time()
329 // Write the data to the file
330 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
334 * Updates the primary key information or creates the table info file if not found
336 * @param $dataSetInstance An instance of a database set class
339 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
340 // Get the information array from lower method
341 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
343 // Is the primary key there?
344 if (!isset($this->tableInfo['primary'])) {
345 // Then create the info file
346 $this->createTableInfoFile($dataSetInstance);
347 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
348 // Set the array element
349 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
352 $this->updateTableInfoFile($dataSetInstance);
357 * Makes sure that the database connection is alive
360 * @todo Do some checks on the database directory and files here
362 public function connectToDatabase () {
366 * Starts a SELECT query on the database by given return type, table name
367 * and search criteria
369 * @param $resultType Result type ('array', 'object' and 'indexed' are valid)
370 * @param $tableName Name of the database table
371 * @param $criteria Local search criteria class
372 * @return $resultData Result data of the query
373 * @throws UnsupportedCriteriaException If the criteria is unsupported
374 * @throws SqlException If an 'SQL error' occurs
376 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
377 // The result is null by any errors
380 // Create full path name
381 $pathName = $this->getSavePath() . $tableName . '/';
383 // A 'select' query is not that easy on local files, so first try to
384 // find the 'table' which is in fact a directory on the server
386 // Get a directory pointer instance
387 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
389 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
391 'status' => LocalfileDatabase::RESULT_OKAY,
395 // Initialize limit/skip
400 // Read the directory with some exceptions
401 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
402 // Does the extension match?
403 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
409 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
412 if (is_array($dataArray)) {
413 // Search in the criteria with FMFW (First Matches, First Wins)
414 foreach ($dataArray as $key => $value) {
415 // Get criteria element
416 $criteria = $criteriaInstance->getCriteriaElemnent($key);
418 // Is the criteria met?
419 if ((!is_null($criteria)) && ($criteria == $value)) {
421 // Shall we skip this entry?
422 if ($criteriaInstance->getSkip() > 0) {
423 // We shall skip some entries
424 if ($skipFound < $criteriaInstance->getSkip()) {
432 $dataArray[$this->getIndexKey()] = $idx;
435 $resultData['rows'][] = $dataArray;
437 // Count found entries up
443 // Throw an exception here
444 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
451 // Close directory and throw the instance away
452 $directoryInstance->closeDirectory();
453 unset($directoryInstance);
455 // Reset last error message and exception
456 $this->resetLastError();
457 } catch (PathIsNoDirectoryException $e) {
458 // Path not found means "table not found" for real databases...
459 $this->lastException = $e;
460 $this->lastError = $e->getMessage();
462 // So throw an SqlException here with faked error message
463 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
464 } catch (FrameworkException $e) {
465 // Catch all exceptions and store them in last error
466 $this->lastException = $e;
467 $this->lastError = $e->getMessage();
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 // Create full path name
483 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
485 // Try to save the request away
487 // Write the data away
488 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
490 // Update the primary key
491 $this->updatePrimaryKey($dataSetInstance);
493 // Reset last error message and exception
494 $this->resetLastError();
495 } catch (FrameworkException $e) {
496 // Catch all exceptions and store them in last error
497 $this->lastException = $e;
498 $this->lastError = $e->getMessage();
500 // Throw an SQL exception
501 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);
506 * "Updates" a data set instance with a database layer
508 * @param $dataSetInstance A storeable data set
510 * @throws SqlException If an SQL error occurs
512 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
513 // Create full path name
514 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
516 // Try all the requests
518 // Get a file pointer instance
519 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
521 // Initialize limit/skip
525 // Get the criteria array from the dataset
526 $criteriaArray = $dataSetInstance->getCriteriaArray();
528 // Get search criteria
529 $searchInstance = $dataSetInstance->getSearchInstance();
531 // Read the directory with some exceptions
532 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
533 // Does the extension match?
534 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
539 // Open this file for reading
540 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
543 if (is_array($dataArray)) {
544 // Search in the criteria with FMFW (First Matches, First Wins)
545 foreach ($dataArray as $key => $value) {
546 // Get criteria element
547 $criteria = $searchInstance->getCriteriaElemnent($key);
549 // Is the criteria met?
550 if ((!is_null($criteria)) && ($criteria == $value)) {
552 // Shall we skip this entry?
553 if ($searchInstance->getSkip() > 0) {
554 // We shall skip some entries
555 if ($skipFound < $searchInstance->getSkip()) {
562 // Entry found, so update it
563 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
564 $dataArray[$criteriaKey] = $criteriaValue;
567 // Write the data to a local file
568 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
578 // Close the file pointer
579 $directoryInstance->closeDirectory();
581 // Update the primary key
582 $this->updatePrimaryKey($dataSetInstance);
584 // Reset last error message and exception
585 $this->resetLastError();
586 } catch (FrameworkException $e) {
587 // Catch all exceptions and store them in last error
588 $this->lastException = $e;
589 $this->lastError = $e->getMessage();
591 // Throw an SQL exception
592 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);
597 * Getter for primary key of specified table or if not found null will be
598 * returned. This must be database-specific.
600 * @param $tableName Name of the table we need the primary key from
601 * @return $primaryKey Primary key column of the given table
603 public function getPrimaryKeyOfTable ($tableName) {
604 // Default key is null
607 // Does the table information exist?
608 if (isset($this->tableInfo[$tableName])) {
609 // Then return the primary key
610 $primaryKey = $this->tableInfo[$tableName]['primary'];