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, this is free software
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 {
28 // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
29 const DB_CODE_TABLE_MISSING = 0x100;
30 const DB_CODE_TABLE_UNWRITEABLE = 0x101;
31 const DB_CODE_DATA_FILE_CORRUPT = 0x102;
34 * Save path for "file database"
36 private $savePath = "";
39 * The file's extension
41 private $fileExtension = "serialized";
44 * The last read file's name
46 private $lastFile = "";
49 * The last read file's content including header information
51 private $lastContents = array();
54 * Wether the "connection is already up
56 private $alreadyConnected = false;
61 private $lastError = "";
66 private $lastException = null;
69 * Table information array
71 private $tableInfo = array();
74 * The protected constructor. Do never instance from outside! You need to
75 * set a local file path. The class will then validate it.
79 protected function __construct() {
80 // Call parent constructor
81 parent::__construct(__CLASS__);
84 $this->removeNumberFormaters();
85 $this->removeSystemArray();
89 * Create an object of LocalFileDatabase and set the save path for local files.
90 * This method also validates the given file path.
92 * @param $savePath The local file path string
93 * @param $ioInstance The input/output handler. This
94 * should be FileIoHandler
95 * @return $dbInstance An instance of LocalFileDatabase
97 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
99 $dbInstance = new LocalFileDatabase();
101 // Set save path and IO instance
102 $dbInstance->setSavePath($savePath);
103 $dbInstance->setFileIoInstance($ioInstance);
105 // "Connect" to the database
106 $dbInstance->connectToDatabase();
108 // Return database instance
113 * Setter for save path
115 * @param $savePath The local save path where we shall put our serialized classes
118 public final function setSavePath ($savePath) {
120 $savePath = (string) $savePath;
123 $this->savePath = $savePath;
127 * Getter for save path
129 * @return $savePath The local save path where we shall put our serialized classes
131 public final function getSavePath () {
132 return $this->savePath;
136 * Getter for last error message
138 * @return $lastError Last error message
140 public final function getLastError () {
141 return $this->lastError;
145 * Getter for last exception
147 * @return $lastException Last thrown exception
149 public final function getLastException () {
150 return $this->lastException;
154 * Setter for the last read file
156 * @param $fqfn The FQFN of the last read file
159 private final function setLastFile ($fqfn) {
161 $fqfn = (string) $fqfn;
162 $this->lastFile = $fqfn;
166 * Reset the last error and exception instance. This should be done after
167 * a successfull "query"
171 private final function resetLastError () {
172 $this->lastError = "";
173 $this->lastException = null;
177 * Getter for last read file
179 * @return $lastFile The last read file's name with full path
181 public final function getLastFile () {
182 return $this->lastFile;
186 * Setter for contents of the last read file
188 * @param $contents An array with header and data elements
191 private final function setLastFileContents ($contents) {
193 $contents = (array) $contents;
194 $this->lastContents = $contents;
198 * Getter for last read file's content as an array
200 * @return $lastContent The array with elements 'header' and 'data'.
202 public final function getLastContents () {
203 return $this->lastContents;
207 * Getter for file extension
209 * @return $fileExtension The array with elements 'header' and 'data'.
211 public final function getFileExtension () {
212 return $this->fileExtension;
216 * Reads a local data file and returns it's contents in an array
218 * @param $fqfn The FQFN for the requested file
221 private function getDataArrayFromFile ($fqfn) {
222 // Get a file pointer
223 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
225 // Get the raw data and BASE64-decode it
226 $compressedData = base64_decode($fileInstance->readLinesFromFile());
228 // Close the file and throw the instance away
229 $fileInstance->closeFile();
230 unset($fileInstance);
233 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
236 $dataArray = unserialize($serializedData);
243 * Writes data array to local file
245 * @param $fqfn The FQFN of the local file
246 * @param $dataArray An array with all the data we shall write
249 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
250 // Get a file pointer instance
251 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
253 // Serialize and compress it
254 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
256 // Write this data BASE64 encoded to the file
257 $fileInstance->writeToFile(base64_encode($compressedData));
259 // Close the file pointer
260 $fileInstance->closeFile();
264 * Getter for table information file contents or an empty if the info file was not created
266 * @param $dataSetInstance An instance of a database set class
267 * @return $infoArray An array with all table informations
269 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
270 // Default content is no data
271 $infoArray = array();
273 // Create FQFN for getting the table information file
274 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
276 // Get the file contents
278 $infoArray = $this->getDataArrayFromFile($fqfn);
279 } catch (FileNotFoundException $e) {
280 // Not found, so ignore it here
288 * Creates the table info file from given dataset instance
290 * @param $dataSetInstance An instance of a database set class
293 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
294 // Create FQFN for creating the table information file
295 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
297 // Get the data out from dataset in a local array
298 $this->tableInfo[$dataSetInstance->getTableName()] = array(
299 'primary' => $dataSetInstance->getPrimaryKey(),
301 'last_updated' => time()
304 // Write the data to the file
305 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
309 * Updates the primary key information or creates the table info file if not found
311 * @param $dataSetInstance An instance of a database set class
314 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
315 // Get the information array from lower method
316 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
318 // Is the primary key there?
319 if (!isset($this->tableInfo['primary'])) {
320 // Then create the info file
321 $this->createTableInfoFile($dataSetInstance);
322 } elseif (($this->getConfigInstance()->readConfig('db_update_primary_forced') === "Y") && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
323 // Set the array element
324 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
327 $this->updateTableInfoFile($dataSetInstance);
332 * Makes sure that the database connection is alive
335 * @todo Do some checks on the database directory and files here
337 public function connectToDatabase () {
341 * Starts a SELECT query on the database by given return type, table name
342 * and search criteria
344 * @param $resultType Result type ("array", "object" and "indexed" are valid)
345 * @param $tableName Name of the database table
346 * @param $criteria Local search criteria class
347 * @return $resultData Result data of the query
348 * @throws UnsupportedCriteriaException If the criteria is unsupported
349 * @throws SqlException If an "SQL error" occurs
351 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
352 // The result is null by any errors
355 // Create full path name
356 $pathName = $this->getSavePath() . $tableName . '/';
358 // A "select" query is not that easy on local files, so first try to
359 // find the "table" which is in fact a directory on the server
361 // Get a directory pointer instance
362 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
364 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
370 // Initialize limit/skip
374 // Read the directory with some exceptions
375 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
376 // Does the extension match?
377 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
383 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
386 if (is_array($dataArray)) {
387 // Search in the criteria with FMFW (First Matches, First Wins)
388 foreach ($dataArray as $key => $value) {
389 // Get criteria element
390 $criteria = $criteriaInstance->getCriteriaElemnent($key);
392 // Is the criteria met?
393 if ((!is_null($criteria)) && ($criteria == $value)) {
395 // Shall we skip this entry?
396 if ($criteriaInstance->getSkip() > 0) {
397 // We shall skip some entries
398 if ($skipFound < $criteriaInstance->getSkip()) {
406 $resultData['rows'][] = $dataArray;
412 // Throw an exception here
413 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
417 // Close directory and throw the instance away
418 $directoryInstance->closeDirectory();
419 unset($directoryInstance);
421 // Reset last error message and exception
422 $this->resetLastError();
423 } catch (PathIsNoDirectoryException $e) {
424 // Path not found means "table not found" for real databases...
425 $this->lastException = $e;
426 $this->lastError = $e->getMessage();
428 // So throw an SqlException here with faked error message
429 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
430 } catch (FrameworkException $e) {
431 // Catch all exceptions and store them in last error
432 $this->lastException = $e;
433 $this->lastError = $e->getMessage();
436 // Return the gathered result
441 * "Inserts" a data set instance into a local file database folder
443 * @param $dataSetInstance A storeable data set
445 * @throws SqlException If an SQL error occurs
447 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
448 // Create full path name
449 $fqfn = sprintf("%s%s/%s.%s",
450 $this->getSavePath(),
451 $dataSetInstance->getTableName(),
452 md5($dataSetInstance->getUniqueValue()),
453 $this->getFileExtension()
456 // Try to save the request away
458 // Write the data away
459 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
461 // Update the primary key
462 $this->updatePrimaryKey($dataSetInstance);
464 // Reset last error message and exception
465 $this->resetLastError();
466 } catch (FrameworkException $e) {
467 // Catch all exceptions and store them in last error
468 $this->lastException = $e;
469 $this->lastError = $e->getMessage();
471 // Throw an SQL exception
472 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
477 * "Updates" a data set instance with a database layer
479 * @param $dataSetInstance A storeable data set
481 * @throws SqlException If an SQL error occurs
483 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
484 // Create full path name
485 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
487 // Try all the requests
489 // Get a file pointer instance
490 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
492 // Initialize limit/skip
496 // Get the criteria array from the dataset
497 $criteriaArray = $dataSetInstance->getCriteriaArray();
499 // Get search criteria
500 $searchInstance = $dataSetInstance->getSearchInstance();
502 // Read the directory with some exceptions
503 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
504 // Does the extension match?
505 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
510 // Open this file for reading
511 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
514 if (is_array($dataArray)) {
515 // Search in the criteria with FMFW (First Matches, First Wins)
516 foreach ($dataArray as $key => $value) {
517 // Get criteria element
518 $criteria = $searchInstance->getCriteriaElemnent($key);
520 // Is the criteria met?
521 if ((!is_null($criteria)) && ($criteria == $value)) {
523 // Shall we skip this entry?
524 if ($searchInstance->getSkip() > 0) {
525 // We shall skip some entries
526 if ($skipFound < $searchInstance->getSkip()) {
533 // Entry found, so update it
534 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
535 $dataArray[$criteriaKey] = $criteriaValue;
538 // Write the data to a local file
539 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
549 // Close the file pointer
550 $directoryInstance->closeDirectory();
552 // Update the primary key
553 $this->updatePrimaryKey($dataSetInstance);
555 // Reset last error message and exception
556 $this->resetLastError();
557 } catch (FrameworkException $e) {
558 // Catch all exceptions and store them in last error
559 $this->lastException = $e;
560 $this->lastError = $e->getMessage();
562 // Throw an SQL exception
563 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
568 * Getter for primary key of specified table or if not found null will be
569 * returned. This must be database-specific.
571 * @param $tableName Name of the table we need the primary key from
572 * @return $primaryKey Primary key column of the given table
574 public function getPrimaryKeyOfTable ($tableName) {
575 // Default key is null
578 // Does the table information exist?
579 if (isset($this->tableInfo[$tableName])) {
580 // Then return the primary key
581 $primaryKey = $this->tableInfo[$tableName]['primary'];