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->generateFqfnFromDataSet($dataSetInstance, 'info');
290 // Get the file contents
292 $infoArray = $this->getDataArrayFromFile($fqfn);
293 } catch (FileNotFoundException $e) {
294 // Not found, so ignore it here
302 * Generates an FQFN from given dataset instance and string
304 * @param $dataSetInstance An instance of a database set class
305 * @param $rowName Name of the row
306 * @return $fqfn The FQFN for this row
308 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
310 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
317 * Creates the table info file from given dataset instance
319 * @param $dataSetInstance An instance of a database set class
322 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
323 // Create FQFN for creating the table information file
324 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
326 // Get the data out from dataset in a local array
327 $this->tableInfo[$dataSetInstance->getTableName()] = array(
328 'primary' => $dataSetInstance->getPrimaryKey(),
330 'last_updated' => time()
333 // Write the data to the file
334 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
338 * Updates the primary key information or creates the table info file if not found
340 * @param $dataSetInstance An instance of a database set class
343 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
344 // Get the information array from lower method
345 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
347 // Is the primary key there?
348 if (!isset($this->tableInfo['primary'])) {
349 // Then create the info file
350 $this->createTableInfoFile($dataSetInstance);
351 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
352 // Set the array element
353 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
356 $this->updateTableInfoFile($dataSetInstance);
361 * Makes sure that the database connection is alive
364 * @todo Do some checks on the database directory and files here
366 public function connectToDatabase () {
370 * Starts a SELECT query on the database by given return type, table name
371 * and search criteria
373 * @param $resultType Result type ('array', 'object' and 'indexed' are valid)
374 * @param $tableName Name of the database table
375 * @param $criteria Local search criteria class
376 * @return $resultData Result data of the query
377 * @throws UnsupportedCriteriaException If the criteria is unsupported
378 * @throws SqlException If an 'SQL error' occurs
380 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
381 // The result is null by any errors
384 // Create full path name
385 $pathName = $this->getSavePath() . $tableName . '/';
387 // A 'select' query is not that easy on local files, so first try to
388 // find the 'table' which is in fact a directory on the server
390 // Get a directory pointer instance
391 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
393 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
395 'status' => LocalfileDatabase::RESULT_OKAY,
399 // Initialize limit/skip
404 // Read the directory with some exceptions
405 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
406 // Does the extension match?
407 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
413 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
416 if (is_array($dataArray)) {
417 // Search in the criteria with FMFW (First Matches, First Wins)
418 foreach ($dataArray as $key => $value) {
419 // Get criteria element
420 $criteria = $criteriaInstance->getCriteriaElemnent($key);
422 // Is the criteria met?
423 if ((!is_null($criteria)) && ($criteria == $value)) {
425 // Shall we skip this entry?
426 if ($criteriaInstance->getSkip() > 0) {
427 // We shall skip some entries
428 if ($skipFound < $criteriaInstance->getSkip()) {
436 $dataArray[$this->getIndexKey()] = $idx;
439 $resultData['rows'][] = $dataArray;
441 // Count found entries up
447 // Throw an exception here
448 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
455 // Close directory and throw the instance away
456 $directoryInstance->closeDirectory();
457 unset($directoryInstance);
459 // Reset last error message and exception
460 $this->resetLastError();
461 } catch (PathIsNoDirectoryException $e) {
462 // Path not found means "table not found" for real databases...
463 $this->lastException = $e;
464 $this->lastError = $e->getMessage();
466 // So throw an SqlException here with faked error message
467 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
468 } catch (FrameworkException $e) {
469 // Catch all exceptions and store them in last error
470 $this->lastException = $e;
471 $this->lastError = $e->getMessage();
474 // Return the gathered result
479 * "Inserts" a data set instance into a local file database folder
481 * @param $dataSetInstance A storeable data set
483 * @throws SqlException If an SQL error occurs
485 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
486 // Create full path name
487 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
489 // Try to save the request away
491 // Write the data away
492 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
494 // Update the primary key
495 $this->updatePrimaryKey($dataSetInstance);
497 // Reset last error message and exception
498 $this->resetLastError();
499 } catch (FrameworkException $e) {
500 // Catch all exceptions and store them in last error
501 $this->lastException = $e;
502 $this->lastError = $e->getMessage();
504 // Throw an SQL exception
505 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
510 * "Updates" a data set instance with a database layer
512 * @param $dataSetInstance A storeable data set
514 * @throws SqlException If an SQL error occurs
516 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
517 // Create full path name
518 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
520 // Try all the requests
522 // Get a file pointer instance
523 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
525 // Initialize limit/skip
529 // Get the criteria array from the dataset
530 $criteriaArray = $dataSetInstance->getCriteriaArray();
532 // Get search criteria
533 $searchInstance = $dataSetInstance->getSearchInstance();
535 // Read the directory with some exceptions
536 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
537 // Does the extension match?
538 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
543 // Open this file for reading
544 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
547 if (is_array($dataArray)) {
548 // Search in the criteria with FMFW (First Matches, First Wins)
549 foreach ($dataArray as $key => $value) {
550 // Get criteria element
551 $criteria = $searchInstance->getCriteriaElemnent($key);
553 // Is the criteria met?
554 if ((!is_null($criteria)) && ($criteria == $value)) {
556 // Shall we skip this entry?
557 if ($searchInstance->getSkip() > 0) {
558 // We shall skip some entries
559 if ($skipFound < $searchInstance->getSkip()) {
566 // Entry found, so update it
567 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
568 $dataArray[$criteriaKey] = $criteriaValue;
571 // Write the data to a local file
572 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
582 // Close the file pointer
583 $directoryInstance->closeDirectory();
585 // Update the primary key
586 $this->updatePrimaryKey($dataSetInstance);
588 // Reset last error message and exception
589 $this->resetLastError();
590 } catch (FrameworkException $e) {
591 // Catch all exceptions and store them in last error
592 $this->lastException = $e;
593 $this->lastError = $e->getMessage();
595 // Throw an SQL exception
596 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
601 * Getter for primary key of specified table or if not found null will be
602 * returned. This must be database-specific.
604 * @param $tableName Name of the table we need the primary key from
605 * @return $primaryKey Primary key column of the given table
607 public function getPrimaryKeyOfTable ($tableName) {
608 // Default key is null
611 // Does the table information exist?
612 if (isset($this->tableInfo[$tableName])) {
613 // Then return the primary key
614 $primaryKey = $this->tableInfo[$tableName]['primary'];