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();
76 private $indexKey = "__idx";
79 * The protected constructor. Do never instance from outside! You need to
80 * set a local file path. The class will then validate it.
84 protected function __construct() {
85 // Call parent constructor
86 parent::__construct(__CLASS__);
89 $this->removeNumberFormaters();
90 $this->removeSystemArray();
94 * Create an object of LocalFileDatabase and set the save path for local files.
95 * This method also validates the given file path.
97 * @param $savePath The local file path string
98 * @param $ioInstance The input/output handler. This
99 * should be FileIoHandler
100 * @return $dbInstance An instance of LocalFileDatabase
102 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
104 $dbInstance = new LocalFileDatabase();
106 // Set save path and IO instance
107 $dbInstance->setSavePath($savePath);
108 $dbInstance->setFileIoInstance($ioInstance);
110 // "Connect" to the database
111 $dbInstance->connectToDatabase();
113 // Return database instance
118 * Setter for save path
120 * @param $savePath The local save path where we shall put our serialized classes
123 public final function setSavePath ($savePath) {
125 $savePath = (string) $savePath;
128 $this->savePath = $savePath;
132 * Getter for save path
134 * @return $savePath The local save path where we shall put our serialized classes
136 public final function getSavePath () {
137 return $this->savePath;
141 * Getter for last error message
143 * @return $lastError Last error message
145 public final function getLastError () {
146 return $this->lastError;
150 * Getter for last exception
152 * @return $lastException Last thrown exception
154 public final function getLastException () {
155 return $this->lastException;
159 * Setter for the last read file
161 * @param $fqfn The FQFN of the last read file
164 private final function setLastFile ($fqfn) {
165 // Cast string and set it
166 $this->lastFile = (string) $fqfn;
170 * Reset the last error and exception instance. This should be done after
171 * a successfull "query"
175 private final function resetLastError () {
176 $this->lastError = "";
177 $this->lastException = null;
181 * Getter for last read file
183 * @return $lastFile The last read file's name with full path
185 public final function getLastFile () {
186 return $this->lastFile;
190 * Setter for contents of the last read file
192 * @param $contents An array with header and data elements
195 private final function setLastFileContents (array $contents) {
197 $this->lastContents = $contents;
201 * Getter for last read file's content as an array
203 * @return $lastContent The array with elements 'header' and 'data'.
205 public final function getLastContents () {
206 return $this->lastContents;
210 * Getter for file extension
212 * @return $fileExtension The array with elements 'header' and 'data'.
214 public final function getFileExtension () {
215 return $this->fileExtension;
219 * Getter for index key
221 * @return $indexKey Index key
223 public final function getIndexKey () {
224 return $this->indexKey;
228 * Reads a local data file and returns it's contents in an array
230 * @param $fqfn The FQFN for the requested file
233 private function getDataArrayFromFile ($fqfn) {
234 // Get a file pointer
235 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
237 // Get the raw data and BASE64-decode it
238 $compressedData = base64_decode($fileInstance->readLinesFromFile());
240 // Close the file and throw the instance away
241 $fileInstance->closeFile();
242 unset($fileInstance);
245 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
248 $dataArray = unserialize($serializedData);
255 * Writes data array to local file
257 * @param $fqfn The FQFN of the local file
258 * @param $dataArray An array with all the data we shall write
261 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
262 // Get a file pointer instance
263 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
265 // Serialize and compress it
266 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
268 // Write this data BASE64 encoded to the file
269 $fileInstance->writeToFile(base64_encode($compressedData));
271 // Close the file pointer
272 $fileInstance->closeFile();
276 * Getter for table information file contents or an empty if the info file was not created
278 * @param $dataSetInstance An instance of a database set class
279 * @return $infoArray An array with all table informations
281 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
282 // Default content is no data
283 $infoArray = array();
285 // Create FQFN for getting the table information file
286 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
288 // Get the file contents
290 $infoArray = $this->getDataArrayFromFile($fqfn);
291 } catch (FileNotFoundException $e) {
292 // Not found, so ignore it here
300 * Creates the table info file from given dataset instance
302 * @param $dataSetInstance An instance of a database set class
305 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
306 // Create FQFN for creating the table information file
307 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
309 // Get the data out from dataset in a local array
310 $this->tableInfo[$dataSetInstance->getTableName()] = array(
311 'primary' => $dataSetInstance->getPrimaryKey(),
313 'last_updated' => time()
316 // Write the data to the file
317 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
321 * Updates the primary key information or creates the table info file if not found
323 * @param $dataSetInstance An instance of a database set class
326 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
327 // Get the information array from lower method
328 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
330 // Is the primary key there?
331 if (!isset($this->tableInfo['primary'])) {
332 // Then create the info file
333 $this->createTableInfoFile($dataSetInstance);
334 } elseif (($this->getConfigInstance()->readConfig('db_update_primary_forced') === "Y") && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
335 // Set the array element
336 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
339 $this->updateTableInfoFile($dataSetInstance);
344 * Makes sure that the database connection is alive
347 * @todo Do some checks on the database directory and files here
349 public function connectToDatabase () {
353 * Starts a SELECT query on the database by given return type, table name
354 * and search criteria
356 * @param $resultType Result type ("array", "object" and "indexed" are valid)
357 * @param $tableName Name of the database table
358 * @param $criteria Local search criteria class
359 * @return $resultData Result data of the query
360 * @throws UnsupportedCriteriaException If the criteria is unsupported
361 * @throws SqlException If an "SQL error" occurs
363 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
364 // The result is null by any errors
367 // Create full path name
368 $pathName = $this->getSavePath() . $tableName . '/';
370 // A "select" query is not that easy on local files, so first try to
371 // find the "table" which is in fact a directory on the server
373 // Get a directory pointer instance
374 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
376 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
382 // Initialize limit/skip
387 // Read the directory with some exceptions
388 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
389 // Does the extension match?
390 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
396 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
399 if (is_array($dataArray)) {
400 // Search in the criteria with FMFW (First Matches, First Wins)
401 foreach ($dataArray as $key => $value) {
402 // Get criteria element
403 $criteria = $criteriaInstance->getCriteriaElemnent($key);
405 // Is the criteria met?
406 if ((!is_null($criteria)) && ($criteria == $value)) {
408 // Shall we skip this entry?
409 if ($criteriaInstance->getSkip() > 0) {
410 // We shall skip some entries
411 if ($skipFound < $criteriaInstance->getSkip()) {
419 $dataArray[$this->getIndexKey()] = $idx;
422 $resultData['rows'][] = $dataArray;
424 // Count found entries up
430 // Throw an exception here
431 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
438 // Close directory and throw the instance away
439 $directoryInstance->closeDirectory();
440 unset($directoryInstance);
442 // Reset last error message and exception
443 $this->resetLastError();
444 } catch (PathIsNoDirectoryException $e) {
445 // Path not found means "table not found" for real databases...
446 $this->lastException = $e;
447 $this->lastError = $e->getMessage();
449 // So throw an SqlException here with faked error message
450 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
451 } catch (FrameworkException $e) {
452 // Catch all exceptions and store them in last error
453 $this->lastException = $e;
454 $this->lastError = $e->getMessage();
457 // Return the gathered result
462 * "Inserts" a data set instance into a local file database folder
464 * @param $dataSetInstance A storeable data set
466 * @throws SqlException If an SQL error occurs
468 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
469 // Create full path name
470 $fqfn = sprintf("%s%s/%s.%s",
471 $this->getSavePath(),
472 $dataSetInstance->getTableName(),
473 md5($dataSetInstance->getUniqueValue()),
474 $this->getFileExtension()
477 // Try to save the request away
479 // Write the data away
480 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
482 // Update the primary key
483 $this->updatePrimaryKey($dataSetInstance);
485 // Reset last error message and exception
486 $this->resetLastError();
487 } catch (FrameworkException $e) {
488 // Catch all exceptions and store them in last error
489 $this->lastException = $e;
490 $this->lastError = $e->getMessage();
492 // Throw an SQL exception
493 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
498 * "Updates" a data set instance with a database layer
500 * @param $dataSetInstance A storeable data set
502 * @throws SqlException If an SQL error occurs
504 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
505 // Create full path name
506 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
508 // Try all the requests
510 // Get a file pointer instance
511 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
513 // Initialize limit/skip
517 // Get the criteria array from the dataset
518 $criteriaArray = $dataSetInstance->getCriteriaArray();
520 // Get search criteria
521 $searchInstance = $dataSetInstance->getSearchInstance();
523 // Read the directory with some exceptions
524 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
525 // Does the extension match?
526 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
531 // Open this file for reading
532 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
535 if (is_array($dataArray)) {
536 // Search in the criteria with FMFW (First Matches, First Wins)
537 foreach ($dataArray as $key => $value) {
538 // Get criteria element
539 $criteria = $searchInstance->getCriteriaElemnent($key);
541 // Is the criteria met?
542 if ((!is_null($criteria)) && ($criteria == $value)) {
544 // Shall we skip this entry?
545 if ($searchInstance->getSkip() > 0) {
546 // We shall skip some entries
547 if ($skipFound < $searchInstance->getSkip()) {
554 // Entry found, so update it
555 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
556 $dataArray[$criteriaKey] = $criteriaValue;
559 // Write the data to a local file
560 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
570 // Close the file pointer
571 $directoryInstance->closeDirectory();
573 // Update the primary key
574 $this->updatePrimaryKey($dataSetInstance);
576 // Reset last error message and exception
577 $this->resetLastError();
578 } catch (FrameworkException $e) {
579 // Catch all exceptions and store them in last error
580 $this->lastException = $e;
581 $this->lastError = $e->getMessage();
583 // Throw an SQL exception
584 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
589 * Getter for primary key of specified table or if not found null will be
590 * returned. This must be database-specific.
592 * @param $tableName Name of the table we need the primary key from
593 * @return $primaryKey Primary key column of the given table
595 public function getPrimaryKeyOfTable ($tableName) {
596 // Default key is null
599 // Does the table information exist?
600 if (isset($this->tableInfo[$tableName])) {
601 // Then return the primary key
602 $primaryKey = $this->tableInfo[$tableName]['primary'];