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 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__);
91 $this->removeNumberFormaters();
92 $this->removeSystemArray();
96 * Create an object of LocalFileDatabase and set the save path for local files.
97 * This method also validates the given file path.
99 * @param $savePath The local file path string
100 * @param $ioInstance The input/output handler. This
101 * should be FileIoHandler
102 * @return $dbInstance An instance of LocalFileDatabase
104 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
106 $dbInstance = new LocalFileDatabase();
108 // Set save path and IO instance
109 $dbInstance->setSavePath($savePath);
110 $dbInstance->setFileIoInstance($ioInstance);
112 // "Connect" to the database
113 $dbInstance->connectToDatabase();
115 // Return database instance
120 * Setter for save path
122 * @param $savePath The local save path where we shall put our serialized classes
125 public final function setSavePath ($savePath) {
127 $savePath = (string) $savePath;
130 $this->savePath = $savePath;
134 * Getter for save path
136 * @return $savePath The local save path where we shall put our serialized classes
138 public final function getSavePath () {
139 return $this->savePath;
143 * Getter for last error message
145 * @return $lastError Last error message
147 public final function getLastError () {
148 return $this->lastError;
152 * Getter for last exception
154 * @return $lastException Last thrown exception
156 public final function getLastException () {
157 return $this->lastException;
161 * Setter for the last read file
163 * @param $fqfn The FQFN of the last read file
166 private final function setLastFile ($fqfn) {
167 // Cast string and set it
168 $this->lastFile = (string) $fqfn;
172 * Reset the last error and exception instance. This should be done after
173 * a successfull "query"
177 private final function resetLastError () {
178 $this->lastError = '';
179 $this->lastException = null;
183 * Getter for last read file
185 * @return $lastFile The last read file's name with full path
187 public final function getLastFile () {
188 return $this->lastFile;
192 * Setter for contents of the last read file
194 * @param $contents An array with header and data elements
197 private final function setLastFileContents (array $contents) {
199 $this->lastContents = $contents;
203 * Getter for last read file's content as an array
205 * @return $lastContent The array with elements 'header' and 'data'.
207 public final function getLastContents () {
208 return $this->lastContents;
212 * Getter for file extension
214 * @return $fileExtension The array with elements 'header' and 'data'.
216 public final function getFileExtension () {
217 return $this->fileExtension;
221 * Getter for index key
223 * @return $indexKey Index key
225 public final function getIndexKey () {
226 return $this->indexKey;
230 * Reads a local data file and returns it's contents in an array
232 * @param $fqfn The FQFN for the requested file
235 private function getDataArrayFromFile ($fqfn) {
236 // Get a file pointer
237 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
239 // Get the raw data and BASE64-decode it
240 $compressedData = base64_decode($fileInstance->readLinesFromFile());
242 // Close the file and throw the instance away
243 $fileInstance->closeFile();
244 unset($fileInstance);
247 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
250 $dataArray = unserialize($serializedData);
257 * Writes data array to local file
259 * @param $fqfn The FQFN of the local file
260 * @param $dataArray An array with all the data we shall write
263 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
264 // Get a file pointer instance
265 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
267 // Serialize and compress it
268 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
270 // Write this data BASE64 encoded to the file
271 $fileInstance->writeToFile(base64_encode($compressedData));
273 // Close the file pointer
274 $fileInstance->closeFile();
278 * Getter for table information file contents or an empty if info file was not created
280 * @param $dataSetInstance An instance of a database set class
281 * @return $infoArray An array with all table informations
283 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
284 // Default content is no data
285 $infoArray = array();
287 // Create FQFN for getting the table information file
288 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
290 // Get the file contents
292 $infoArray = $this->getDataArrayFromFile($fqfn);
293 } catch (FileNotFoundException $e) {
294 // Not found, so ignore it here
302 * Creates the table info file from given dataset instance
304 * @param $dataSetInstance An instance of a database set class
307 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
308 // Create FQFN for creating the table information file
309 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
311 // Get the data out from dataset in a local array
312 $this->tableInfo[$dataSetInstance->getTableName()] = array(
313 'primary' => $dataSetInstance->getPrimaryKey(),
315 'last_updated' => time()
318 // Write the data to the file
319 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
323 * Updates the primary key information or creates the table info file if not found
325 * @param $dataSetInstance An instance of a database set class
328 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
329 // Get the information array from lower method
330 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
332 // Is the primary key there?
333 if (!isset($this->tableInfo['primary'])) {
334 // Then create the info file
335 $this->createTableInfoFile($dataSetInstance);
336 } elseif (($this->getConfigInstance()->readConfig('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
337 // Set the array element
338 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
341 $this->updateTableInfoFile($dataSetInstance);
346 * Makes sure that the database connection is alive
349 * @todo Do some checks on the database directory and files here
351 public function connectToDatabase () {
355 * Starts a SELECT query on the database by given return type, table name
356 * and search criteria
358 * @param $resultType Result type ('array', 'object' and 'indexed' are valid)
359 * @param $tableName Name of the database table
360 * @param $criteria Local search criteria class
361 * @return $resultData Result data of the query
362 * @throws UnsupportedCriteriaException If the criteria is unsupported
363 * @throws SqlException If an 'SQL error' occurs
365 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
366 // The result is null by any errors
369 // Create full path name
370 $pathName = $this->getSavePath() . $tableName . '/';
372 // A 'select' query is not that easy on local files, so first try to
373 // find the 'table' which is in fact a directory on the server
375 // Get a directory pointer instance
376 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
378 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
380 'status' => LocalfileDatabase::RESULT_OKAY,
384 // Initialize limit/skip
389 // Read the directory with some exceptions
390 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
391 // Does the extension match?
392 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
398 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
401 if (is_array($dataArray)) {
402 // Search in the criteria with FMFW (First Matches, First Wins)
403 foreach ($dataArray as $key => $value) {
404 // Get criteria element
405 $criteria = $criteriaInstance->getCriteriaElemnent($key);
407 // Is the criteria met?
408 if ((!is_null($criteria)) && ($criteria == $value)) {
410 // Shall we skip this entry?
411 if ($criteriaInstance->getSkip() > 0) {
412 // We shall skip some entries
413 if ($skipFound < $criteriaInstance->getSkip()) {
421 $dataArray[$this->getIndexKey()] = $idx;
424 $resultData['rows'][] = $dataArray;
426 // 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 error message and exception
445 $this->resetLastError();
446 } catch (PathIsNoDirectoryException $e) {
447 // Path not found means "table not found" for real databases...
448 $this->lastException = $e;
449 $this->lastError = $e->getMessage();
451 // So throw an SqlException here with faked error message
452 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
453 } catch (FrameworkException $e) {
454 // Catch all exceptions and store them in last error
455 $this->lastException = $e;
456 $this->lastError = $e->getMessage();
459 // Return the gathered result
464 * "Inserts" a data set instance into a local file database folder
466 * @param $dataSetInstance A storeable data set
468 * @throws SqlException If an SQL error occurs
470 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
471 // Create full path name
472 $fqfn = sprintf("%s%s/%s.%s",
473 $this->getSavePath(),
474 $dataSetInstance->getTableName(),
475 md5($dataSetInstance->getUniqueValue()),
476 $this->getFileExtension()
479 // Try to save the request away
481 // Write the data away
482 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
484 // Update the primary key
485 $this->updatePrimaryKey($dataSetInstance);
487 // Reset last error message and exception
488 $this->resetLastError();
489 } catch (FrameworkException $e) {
490 // Catch all exceptions and store them in last error
491 $this->lastException = $e;
492 $this->lastError = $e->getMessage();
494 // Throw an SQL exception
495 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
500 * "Updates" a data set instance with a database layer
502 * @param $dataSetInstance A storeable data set
504 * @throws SqlException If an SQL error occurs
506 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
507 // Create full path name
508 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
510 // Try all the requests
512 // Get a file pointer instance
513 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
515 // Initialize limit/skip
519 // Get the criteria array from the dataset
520 $criteriaArray = $dataSetInstance->getCriteriaArray();
522 // Get search criteria
523 $searchInstance = $dataSetInstance->getSearchInstance();
525 // Read the directory with some exceptions
526 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
527 // Does the extension match?
528 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
533 // Open this file for reading
534 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
537 if (is_array($dataArray)) {
538 // Search in the criteria with FMFW (First Matches, First Wins)
539 foreach ($dataArray as $key => $value) {
540 // Get criteria element
541 $criteria = $searchInstance->getCriteriaElemnent($key);
543 // Is the criteria met?
544 if ((!is_null($criteria)) && ($criteria == $value)) {
546 // Shall we skip this entry?
547 if ($searchInstance->getSkip() > 0) {
548 // We shall skip some entries
549 if ($skipFound < $searchInstance->getSkip()) {
556 // Entry found, so update it
557 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
558 $dataArray[$criteriaKey] = $criteriaValue;
561 // Write the data to a local file
562 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
572 // Close the file pointer
573 $directoryInstance->closeDirectory();
575 // Update the primary key
576 $this->updatePrimaryKey($dataSetInstance);
578 // Reset last error message and exception
579 $this->resetLastError();
580 } catch (FrameworkException $e) {
581 // Catch all exceptions and store them in last error
582 $this->lastException = $e;
583 $this->lastError = $e->getMessage();
585 // Throw an SQL exception
586 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
591 * Getter for primary key of specified table or if not found null will be
592 * returned. This must be database-specific.
594 * @param $tableName Name of the table we need the primary key from
595 * @return $primaryKey Primary key column of the given table
597 public function getPrimaryKeyOfTable ($tableName) {
598 // Default key is null
601 // Does the table information exist?
602 if (isset($this->tableInfo[$tableName])) {
603 // Then return the primary key
604 $primaryKey = $this->tableInfo[$tableName]['primary'];