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 - 2011 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 * The file's extension
38 private $fileExtension = 'serialized';
41 * The last read file's name
43 private $lastFile = '';
46 * The last read file's content including header information
48 private $lastContents = array();
51 * Wether the "connection is already up
53 private $alreadyConnected = false;
58 private $lastError = '';
63 private $lastException = NULL;
66 * Table information array
68 private $tableInfo = array();
73 private $indexKey = '__idx';
76 * The protected constructor. Do never instance from outside! You need to
77 * set a local file path. The class will then validate it.
81 protected function __construct () {
82 // Call parent constructor
83 parent::__construct(__CLASS__);
87 * Create an object of LocalFileDatabase and set the save path from
88 * configuration for local files.
90 * @return $databaseInstance An instance of LocalFileDatabase
92 public static final function createLocalFileDatabase () {
94 $databaseInstance = new LocalFileDatabase();
96 // Get a new compressor channel instance
97 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
99 // Set the compressor channel
100 $databaseInstance->setCompressorChannel($compressorInstance);
102 // "Connect" to the database
103 $databaseInstance->connectToDatabase();
105 // Return database instance
106 return $databaseInstance;
110 * Getter for last error message
112 * @return $lastError Last error message
114 public final function getLastError () {
115 return $this->lastError;
119 * Getter for last exception
121 * @return $lastException Last thrown exception
123 public final function getLastException () {
124 return $this->lastException;
128 * Setter for the last read file
130 * @param $fqfn The FQFN of the last read file
133 private final function setLastFile ($fqfn) {
134 // Cast string and set it
135 $this->lastFile = (string) $fqfn;
139 * Reset the last error and exception instance. This should be done after
140 * a successfull "query"
144 private final function resetLastError () {
145 $this->lastError = '';
146 $this->lastException = NULL;
150 * Getter for last read file
152 * @return $lastFile The last read file's name with full path
154 public final function getLastFile () {
155 return $this->lastFile;
159 * Setter for contents of the last read file
161 * @param $contents An array with header and data elements
164 private final function setLastFileContents (array $contents) {
166 $this->lastContents = $contents;
170 * Getter for last read file's content as an array
172 * @return $lastContent The array with elements 'header' and 'data'.
174 public final function getLastContents () {
175 return $this->lastContents;
179 * Getter for file extension
181 * @return $fileExtension The array with elements 'header' and 'data'.
183 public final function getFileExtension () {
184 return $this->fileExtension;
188 * Getter for index key
190 * @return $indexKey Index key
192 public final function getIndexKey () {
193 return $this->indexKey;
197 * Reads a local data file and returns it's contents in an array
199 * @param $fqfn The FQFN for the requested file
202 private function getDataArrayFromFile ($fqfn) {
203 // Get a file pointer
204 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
206 // Get the raw data and BASE64-decode it
207 $compressedData = base64_decode($fileInstance->readLinesFromFile());
209 // Close the file and throw the instance away
210 $fileInstance->closeFile();
211 unset($fileInstance);
214 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
217 $dataArray = unserialize($serializedData);
224 * Writes data array to local file
226 * @param $fqfn The FQFN of the local file
227 * @param $dataArray An array with all the data we shall write
230 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
231 // Get a file pointer instance
232 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
234 // Serialize and compress it
235 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
237 // Write this data BASE64 encoded to the file
238 $fileInstance->writeToFile(base64_encode($compressedData));
240 // Close the file pointer
241 $fileInstance->closeFile();
245 * Getter for table information file contents or an empty if info file was not created
247 * @param $dataSetInstance An instance of a database set class
248 * @return $infoArray An array with all table informations
250 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
251 // Default content is no data
252 $infoArray = array();
254 // Create FQFN for getting the table information file
255 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
257 // Get the file contents
259 $infoArray = $this->getDataArrayFromFile($fqfn);
260 } catch (FileIoException $e) {
261 // Not found, so ignore it here
269 * Generates an FQFN from given dataset instance and string
271 * @param $dataSetInstance An instance of a database set class
272 * @param $rowName Name of the row
273 * @return $fqfn The FQFN for this row
275 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
277 $fqfn = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
284 * Creates the table info file from given dataset instance
286 * @param $dataSetInstance An instance of a database set class
289 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
290 // Create FQFN for creating the table information file
291 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
293 // Get the data out from dataset in a local array
294 $this->tableInfo[$dataSetInstance->getTableName()] = array(
295 'primary' => $dataSetInstance->getPrimaryKey(),
297 'last_updated' => time()
300 // Write the data to the file
301 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
305 * Updates the primary key information or creates the table info file if not found
307 * @param $dataSetInstance An instance of a database set class
310 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
311 // Get the information array from lower method
312 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
314 // Is the primary key there?
315 if (!isset($this->tableInfo['primary'])) {
316 // Then create the info file
317 $this->createTableInfoFile($dataSetInstance);
318 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
319 // Set the array element
320 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
323 $this->updateTableInfoFile($dataSetInstance);
328 * Makes sure that the database connection is alive
331 * @todo Do some checks on the database directory and files here
333 public function connectToDatabase () {
337 * Starts a SELECT query on the database by given return type, table name
338 * and search criteria
340 * @param $resultType Result type ('array', 'object' and 'indexed' are valid)
341 * @param $tableName Name of the database table
342 * @param $criteria Local search criteria class
343 * @return $resultData Result data of the query
344 * @throws UnsupportedCriteriaException If the criteria is unsupported
345 * @throws SqlException If an 'SQL error' occurs
347 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
348 // The result is null by any errors
351 // Create full path name
352 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
354 // A 'select' query is not that easy on local files, so first try to
355 // find the 'table' which is in fact a directory on the server
357 // Get a directory pointer instance
358 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
360 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
362 'status' => LocalfileDatabase::RESULT_OKAY,
366 // Initialize limit/skip
371 // Read the directory with some exceptions
372 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
373 // Does the extension match?
374 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
380 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
383 if (is_array($dataArray)) {
384 // Search in the criteria with FMFW (First Matches, First Wins)
385 foreach ($dataArray as $key => $value) {
386 // Get criteria element
387 $criteria = $criteriaInstance->getCriteriaElemnent($key);
389 // Is the criteria met?
390 if ((!is_null($criteria)) && ($criteria == $value)) {
392 // Shall we skip this entry?
393 if ($criteriaInstance->getSkip() > 0) {
394 // We shall skip some entries
395 if ($skipFound < $criteriaInstance->getSkip()) {
403 $dataArray[$this->getIndexKey()] = $idx;
406 $resultData['rows'][] = $dataArray;
408 // Count found entries up
414 // Throw an exception here
415 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
422 // Close directory and throw the instance away
423 $directoryInstance->closeDirectory();
424 unset($directoryInstance);
426 // Reset last error message and exception
427 $this->resetLastError();
428 } catch (PathIsNoDirectoryException $e) {
429 // Path not found means "table not found" for real databases...
430 $this->lastException = $e;
431 $this->lastError = $e->getMessage();
433 // So throw an SqlException here with faked error message
434 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
435 } catch (FrameworkException $e) {
436 // Catch all exceptions and store them in last error
437 $this->lastException = $e;
438 $this->lastError = $e->getMessage();
441 // Return the gathered result
446 * "Inserts" a data set instance into a local file database folder
448 * @param $dataSetInstance A storeable data set
450 * @throws SqlException If an SQL error occurs
452 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
453 // Create full path name
454 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
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', is the table created?", $dataSetInstance->getTableName()), 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->getConfigInstance()->getConfigEntry('local_db_path') . $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', is the table created?", $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'];