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, 2010 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 * @param $ioInstance The input/output handler. This
97 * should be FileIoHandler
98 * @return $dbInstance An instance of LocalFileDatabase
100 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
102 $databaseInstance = new LocalFileDatabase();
104 // Set save path and IO instance
105 $databaseInstance->setSavePath($savePath);
106 $databaseInstance->setFileIoInstance($ioInstance);
108 // Set the compressor channel
109 $databaseInstance->setCompressorChannel(CompressorChannel::createCompressorChannel(
110 $databaseInstance->getConfigInstance()->getConfigEntry('base_path').
111 $databaseInstance->getConfigInstance()->getConfigEntry('compressor_base_path')
114 // "Connect" to the database
115 $databaseInstance->connectToDatabase();
117 // Return database instance
118 return $databaseInstance;
122 * Setter for save path
124 * @param $savePath The local save path where we shall put our serialized classes
127 public final function setSavePath ($savePath) {
129 $this->savePath = (string) $savePath;
133 * Getter for save path
135 * @return $savePath The local save path where we shall put our serialized classes
137 public final function getSavePath () {
138 return $this->savePath;
142 * Getter for last error message
144 * @return $lastError Last error message
146 public final function getLastError () {
147 return $this->lastError;
151 * Getter for last exception
153 * @return $lastException Last thrown exception
155 public final function getLastException () {
156 return $this->lastException;
160 * Setter for the last read file
162 * @param $fqfn The FQFN of the last read file
165 private final function setLastFile ($fqfn) {
166 // Cast string and set it
167 $this->lastFile = (string) $fqfn;
171 * Reset the last error and exception instance. This should be done after
172 * a successfull "query"
176 private final function resetLastError () {
177 $this->lastError = '';
178 $this->lastException = null;
182 * Getter for last read file
184 * @return $lastFile The last read file's name with full path
186 public final function getLastFile () {
187 return $this->lastFile;
191 * Setter for contents of the last read file
193 * @param $contents An array with header and data elements
196 private final function setLastFileContents (array $contents) {
198 $this->lastContents = $contents;
202 * Getter for last read file's content as an array
204 * @return $lastContent The array with elements 'header' and 'data'.
206 public final function getLastContents () {
207 return $this->lastContents;
211 * Getter for file extension
213 * @return $fileExtension The array with elements 'header' and 'data'.
215 public final function getFileExtension () {
216 return $this->fileExtension;
220 * Getter for index key
222 * @return $indexKey Index key
224 public final function getIndexKey () {
225 return $this->indexKey;
229 * Reads a local data file and returns it's contents in an array
231 * @param $fqfn The FQFN for the requested file
234 private function getDataArrayFromFile ($fqfn) {
235 // Get a file pointer
236 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
238 // Get the raw data and BASE64-decode it
239 $compressedData = base64_decode($fileInstance->readLinesFromFile());
241 // Close the file and throw the instance away
242 $fileInstance->closeFile();
243 unset($fileInstance);
246 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
249 $dataArray = unserialize($serializedData);
256 * Writes data array to local file
258 * @param $fqfn The FQFN of the local file
259 * @param $dataArray An array with all the data we shall write
262 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
263 // Get a file pointer instance
264 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
266 // Serialize and compress it
267 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
269 // Write this data BASE64 encoded to the file
270 $fileInstance->writeToFile(base64_encode($compressedData));
272 // Close the file pointer
273 $fileInstance->closeFile();
277 * Getter for table information file contents or an empty if info file was not created
279 * @param $dataSetInstance An instance of a database set class
280 * @return $infoArray An array with all table informations
282 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
283 // Default content is no data
284 $infoArray = array();
286 // Create FQFN for getting the table information file
287 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
289 // Get the file contents
291 $infoArray = $this->getDataArrayFromFile($fqfn);
292 } catch (FileIoException $e) {
293 // Not found, so ignore it here
301 * Generates an FQFN from given dataset instance and string
303 * @param $dataSetInstance An instance of a database set class
304 * @param $rowName Name of the row
305 * @return $fqfn The FQFN for this row
307 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
309 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
316 * Creates the table info file from given dataset instance
318 * @param $dataSetInstance An instance of a database set class
321 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
322 // Create FQFN for creating the table information file
323 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
325 // Get the data out from dataset in a local array
326 $this->tableInfo[$dataSetInstance->getTableName()] = array(
327 'primary' => $dataSetInstance->getPrimaryKey(),
329 'last_updated' => time()
332 // Write the data to the file
333 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
337 * Updates the primary key information or creates the table info file if not found
339 * @param $dataSetInstance An instance of a database set class
342 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
343 // Get the information array from lower method
344 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
346 // Is the primary key there?
347 if (!isset($this->tableInfo['primary'])) {
348 // Then create the info file
349 $this->createTableInfoFile($dataSetInstance);
350 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
351 // Set the array element
352 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
355 $this->updateTableInfoFile($dataSetInstance);
360 * Makes sure that the database connection is alive
363 * @todo Do some checks on the database directory and files here
365 public function connectToDatabase () {
369 * Starts a SELECT query on the database by given return type, table name
370 * and search criteria
372 * @param $resultType Result type ('array', 'object' and 'indexed' are valid)
373 * @param $tableName Name of the database table
374 * @param $criteria Local search criteria class
375 * @return $resultData Result data of the query
376 * @throws UnsupportedCriteriaException If the criteria is unsupported
377 * @throws SqlException If an 'SQL error' occurs
379 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
380 // The result is null by any errors
383 // Create full path name
384 $pathName = $this->getSavePath() . $tableName . '/';
386 // A 'select' query is not that easy on local files, so first try to
387 // find the 'table' which is in fact a directory on the server
389 // Get a directory pointer instance
390 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
392 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
394 'status' => LocalfileDatabase::RESULT_OKAY,
398 // Initialize limit/skip
403 // Read the directory with some exceptions
404 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
405 // Does the extension match?
406 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
412 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
415 if (is_array($dataArray)) {
416 // Search in the criteria with FMFW (First Matches, First Wins)
417 foreach ($dataArray as $key => $value) {
418 // Get criteria element
419 $criteria = $criteriaInstance->getCriteriaElemnent($key);
421 // Is the criteria met?
422 if ((!is_null($criteria)) && ($criteria == $value)) {
424 // Shall we skip this entry?
425 if ($criteriaInstance->getSkip() > 0) {
426 // We shall skip some entries
427 if ($skipFound < $criteriaInstance->getSkip()) {
435 $dataArray[$this->getIndexKey()] = $idx;
438 $resultData['rows'][] = $dataArray;
440 // Count found entries up
446 // Throw an exception here
447 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
454 // Close directory and throw the instance away
455 $directoryInstance->closeDirectory();
456 unset($directoryInstance);
458 // Reset last error message and exception
459 $this->resetLastError();
460 } catch (PathIsNoDirectoryException $e) {
461 // Path not found means "table not found" for real databases...
462 $this->lastException = $e;
463 $this->lastError = $e->getMessage();
465 // So throw an SqlException here with faked error message
466 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
467 } catch (FrameworkException $e) {
468 // Catch all exceptions and store them in last error
469 $this->lastException = $e;
470 $this->lastError = $e->getMessage();
473 // Return the gathered result
478 * "Inserts" a data set instance into a local file database folder
480 * @param $dataSetInstance A storeable data set
482 * @throws SqlException If an SQL error occurs
484 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
485 // Create full path name
486 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
488 // Try to save the request away
490 // Write the data away
491 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
493 // Update the primary key
494 $this->updatePrimaryKey($dataSetInstance);
496 // Reset last error message and exception
497 $this->resetLastError();
498 } catch (FrameworkException $e) {
499 // Catch all exceptions and store them in last error
500 $this->lastException = $e;
501 $this->lastError = $e->getMessage();
503 // Throw an SQL exception
504 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
509 * "Updates" a data set instance with a database layer
511 * @param $dataSetInstance A storeable data set
513 * @throws SqlException If an SQL error occurs
515 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
516 // Create full path name
517 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
519 // Try all the requests
521 // Get a file pointer instance
522 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
524 // Initialize limit/skip
528 // Get the criteria array from the dataset
529 $criteriaArray = $dataSetInstance->getCriteriaArray();
531 // Get search criteria
532 $searchInstance = $dataSetInstance->getSearchInstance();
534 // Read the directory with some exceptions
535 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
536 // Does the extension match?
537 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
542 // Open this file for reading
543 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
546 if (is_array($dataArray)) {
547 // Search in the criteria with FMFW (First Matches, First Wins)
548 foreach ($dataArray as $key => $value) {
549 // Get criteria element
550 $criteria = $searchInstance->getCriteriaElemnent($key);
552 // Is the criteria met?
553 if ((!is_null($criteria)) && ($criteria == $value)) {
555 // Shall we skip this entry?
556 if ($searchInstance->getSkip() > 0) {
557 // We shall skip some entries
558 if ($skipFound < $searchInstance->getSkip()) {
565 // Entry found, so update it
566 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
567 $dataArray[$criteriaKey] = $criteriaValue;
570 // Write the data to a local file
571 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
581 // Close the file pointer
582 $directoryInstance->closeDirectory();
584 // Update the primary key
585 $this->updatePrimaryKey($dataSetInstance);
587 // Reset last error message and exception
588 $this->resetLastError();
589 } catch (FrameworkException $e) {
590 // Catch all exceptions and store them in last error
591 $this->lastException = $e;
592 $this->lastError = $e->getMessage();
594 // Throw an SQL exception
595 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
600 * Getter for primary key of specified table or if not found null will be
601 * returned. This must be database-specific.
603 * @param $tableName Name of the table we need the primary key from
604 * @return $primaryKey Primary key column of the given table
606 public function getPrimaryKeyOfTable ($tableName) {
607 // Default key is null
610 // Does the table information exist?
611 if (isset($this->tableInfo[$tableName])) {
612 // Then return the primary key
613 $primaryKey = $this->tableInfo[$tableName]['primary'];