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) {
160 // Cast string and set it
161 $this->lastFile = (string) $fqfn;
165 * Reset the last error and exception instance. This should be done after
166 * a successfull "query"
170 private final function resetLastError () {
171 $this->lastError = "";
172 $this->lastException = null;
176 * Getter for last read file
178 * @return $lastFile The last read file's name with full path
180 public final function getLastFile () {
181 return $this->lastFile;
185 * Setter for contents of the last read file
187 * @param $contents An array with header and data elements
190 private final function setLastFileContents (array $contents) {
192 $this->lastContents = $contents;
196 * Getter for last read file's content as an array
198 * @return $lastContent The array with elements 'header' and 'data'.
200 public final function getLastContents () {
201 return $this->lastContents;
205 * Getter for file extension
207 * @return $fileExtension The array with elements 'header' and 'data'.
209 public final function getFileExtension () {
210 return $this->fileExtension;
214 * Reads a local data file and returns it's contents in an array
216 * @param $fqfn The FQFN for the requested file
219 private function getDataArrayFromFile ($fqfn) {
220 // Get a file pointer
221 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
223 // Get the raw data and BASE64-decode it
224 $compressedData = base64_decode($fileInstance->readLinesFromFile());
226 // Close the file and throw the instance away
227 $fileInstance->closeFile();
228 unset($fileInstance);
231 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
234 $dataArray = unserialize($serializedData);
241 * Writes data array to local file
243 * @param $fqfn The FQFN of the local file
244 * @param $dataArray An array with all the data we shall write
247 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
248 // Get a file pointer instance
249 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
251 // Serialize and compress it
252 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
254 // Write this data BASE64 encoded to the file
255 $fileInstance->writeToFile(base64_encode($compressedData));
257 // Close the file pointer
258 $fileInstance->closeFile();
262 * Getter for table information file contents or an empty if the info file was not created
264 * @param $dataSetInstance An instance of a database set class
265 * @return $infoArray An array with all table informations
267 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
268 // Default content is no data
269 $infoArray = array();
271 // Create FQFN for getting the table information file
272 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
274 // Get the file contents
276 $infoArray = $this->getDataArrayFromFile($fqfn);
277 } catch (FileNotFoundException $e) {
278 // Not found, so ignore it here
286 * Creates the table info file from given dataset instance
288 * @param $dataSetInstance An instance of a database set class
291 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
292 // Create FQFN for creating the table information file
293 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
295 // Get the data out from dataset in a local array
296 $this->tableInfo[$dataSetInstance->getTableName()] = array(
297 'primary' => $dataSetInstance->getPrimaryKey(),
299 'last_updated' => time()
302 // Write the data to the file
303 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
307 * Updates the primary key information or creates the table info file if not found
309 * @param $dataSetInstance An instance of a database set class
312 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
313 // Get the information array from lower method
314 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
316 // Is the primary key there?
317 if (!isset($this->tableInfo['primary'])) {
318 // Then create the info file
319 $this->createTableInfoFile($dataSetInstance);
320 } elseif (($this->getConfigInstance()->readConfig('db_update_primary_forced') === "Y") && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
321 // Set the array element
322 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
325 $this->updateTableInfoFile($dataSetInstance);
330 * Makes sure that the database connection is alive
333 * @todo Do some checks on the database directory and files here
335 public function connectToDatabase () {
339 * Starts a SELECT query on the database by given return type, table name
340 * and search criteria
342 * @param $resultType Result type ("array", "object" and "indexed" are valid)
343 * @param $tableName Name of the database table
344 * @param $criteria Local search criteria class
345 * @return $resultData Result data of the query
346 * @throws UnsupportedCriteriaException If the criteria is unsupported
347 * @throws SqlException If an "SQL error" occurs
349 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
350 // The result is null by any errors
353 // Create full path name
354 $pathName = $this->getSavePath() . $tableName . '/';
356 // A "select" query is not that easy on local files, so first try to
357 // find the "table" which is in fact a directory on the server
359 // Get a directory pointer instance
360 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
362 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
368 // Initialize limit/skip
373 // Read the directory with some exceptions
374 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
375 // Does the extension match?
376 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
382 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
385 if (is_array($dataArray)) {
386 // Search in the criteria with FMFW (First Matches, First Wins)
387 foreach ($dataArray as $key => $value) {
388 // Get criteria element
389 $criteria = $criteriaInstance->getCriteriaElemnent($key);
391 // Is the criteria met?
392 if ((!is_null($criteria)) && ($criteria == $value)) {
394 // Shall we skip this entry?
395 if ($criteriaInstance->getSkip() > 0) {
396 // We shall skip some entries
397 if ($skipFound < $criteriaInstance->getSkip()) {
405 $dataArray['__idx'] = $idx;
408 $resultData['rows'][] = $dataArray;
410 // Count found entries up
416 // Throw an exception here
417 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
424 // Close directory and throw the instance away
425 $directoryInstance->closeDirectory();
426 unset($directoryInstance);
428 // Reset last error message and exception
429 $this->resetLastError();
430 } catch (PathIsNoDirectoryException $e) {
431 // Path not found means "table not found" for real databases...
432 $this->lastException = $e;
433 $this->lastError = $e->getMessage();
435 // So throw an SqlException here with faked error message
436 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
437 } catch (FrameworkException $e) {
438 // Catch all exceptions and store them in last error
439 $this->lastException = $e;
440 $this->lastError = $e->getMessage();
443 // Return the gathered result
448 * "Inserts" a data set instance into a local file database folder
450 * @param $dataSetInstance A storeable data set
452 * @throws SqlException If an SQL error occurs
454 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
455 // Create full path name
456 $fqfn = sprintf("%s%s/%s.%s",
457 $this->getSavePath(),
458 $dataSetInstance->getTableName(),
459 md5($dataSetInstance->getUniqueValue()),
460 $this->getFileExtension()
463 // Try to save the request away
465 // Write the data away
466 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
468 // Update the primary key
469 $this->updatePrimaryKey($dataSetInstance);
471 // Reset last error message and exception
472 $this->resetLastError();
473 } catch (FrameworkException $e) {
474 // Catch all exceptions and store them in last error
475 $this->lastException = $e;
476 $this->lastError = $e->getMessage();
478 // Throw an SQL exception
479 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
484 * "Updates" a data set instance with a database layer
486 * @param $dataSetInstance A storeable data set
488 * @throws SqlException If an SQL error occurs
490 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
491 // Create full path name
492 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
494 // Try all the requests
496 // Get a file pointer instance
497 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
499 // Initialize limit/skip
503 // Get the criteria array from the dataset
504 $criteriaArray = $dataSetInstance->getCriteriaArray();
506 // Get search criteria
507 $searchInstance = $dataSetInstance->getSearchInstance();
509 // Read the directory with some exceptions
510 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
511 // Does the extension match?
512 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
517 // Open this file for reading
518 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
521 if (is_array($dataArray)) {
522 // Search in the criteria with FMFW (First Matches, First Wins)
523 foreach ($dataArray as $key => $value) {
524 // Get criteria element
525 $criteria = $searchInstance->getCriteriaElemnent($key);
527 // Is the criteria met?
528 if ((!is_null($criteria)) && ($criteria == $value)) {
530 // Shall we skip this entry?
531 if ($searchInstance->getSkip() > 0) {
532 // We shall skip some entries
533 if ($skipFound < $searchInstance->getSkip()) {
540 // Entry found, so update it
541 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
542 $dataArray[$criteriaKey] = $criteriaValue;
545 // Write the data to a local file
546 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
556 // Close the file pointer
557 $directoryInstance->closeDirectory();
559 // Update the primary key
560 $this->updatePrimaryKey($dataSetInstance);
562 // Reset last error message and exception
563 $this->resetLastError();
564 } catch (FrameworkException $e) {
565 // Catch all exceptions and store them in last error
566 $this->lastException = $e;
567 $this->lastError = $e->getMessage();
569 // Throw an SQL exception
570 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
575 * Getter for primary key of specified table or if not found null will be
576 * returned. This must be database-specific.
578 * @param $tableName Name of the table we need the primary key from
579 * @return $primaryKey Primary key column of the given table
581 public function getPrimaryKeyOfTable ($tableName) {
582 // Default key is null
585 // Does the table information exist?
586 if (isset($this->tableInfo[$tableName])) {
587 // Then return the primary key
588 $primaryKey = $this->tableInfo[$tableName]['primary'];