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 - 2012 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 BaseDatabaseBackend implements DatabaseBackendInterface {
28 * The file's extension
30 private $fileExtension = 'serialized';
33 * The last read file's name
35 private $lastFile = '';
38 * The last read file's content including header information
40 private $lastContents = array();
43 * Whether the "connection is already up
45 private $alreadyConnected = false;
48 * Table information array
50 private $tableInfo = array();
55 private $indexKey = '__idx';
58 * The protected constructor. Do never instance from outside! You need to
59 * set a local file path. The class will then validate it.
63 protected function __construct () {
64 // Call parent constructor
65 parent::__construct(__CLASS__);
69 * Create an object of LocalFileDatabase and set the save path from
70 * configuration for local files.
72 * @return $databaseInstance An instance of LocalFileDatabase
74 public static final function createLocalFileDatabase () {
76 $databaseInstance = new LocalFileDatabase();
78 // Get a new compressor channel instance
79 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
81 // Set the compressor channel
82 $databaseInstance->setCompressorChannel($compressorInstance);
84 // Get a file IO handler
85 $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
88 $databaseInstance->setFileIoInstance($fileIoInstance);
90 // "Connect" to the database
91 $databaseInstance->connectToDatabase();
93 // Return database instance
94 return $databaseInstance;
98 * Setter for the last read file
100 * @param $fqfn The FQFN of the last read file
103 private final function setLastFile ($fqfn) {
104 // Cast string and set it
105 $this->lastFile = (string) $fqfn;
109 * Getter for last read file
111 * @return $lastFile The last read file's name with full path
113 public final function getLastFile () {
114 return $this->lastFile;
118 * Setter for contents of the last read file
120 * @param $contents An array with header and data elements
123 private final function setLastFileContents (array $contents) {
125 $this->lastContents = $contents;
129 * Getter for last read file's content as an array
131 * @return $lastContent The array with elements 'header' and 'data'.
133 public final function getLastContents () {
134 return $this->lastContents;
138 * Getter for file extension
140 * @return $fileExtension The array with elements 'header' and 'data'.
142 public final function getFileExtension () {
143 return $this->fileExtension;
147 * Getter for index key
149 * @return $indexKey Index key
151 public final function getIndexKey () {
152 return $this->indexKey;
156 * Reads a local data file and returns it's contents in an array
158 * @param $fqfn The FQFN for the requested file
161 private function getDataArrayFromFile ($fqfn) {
163 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Reading elements from database file ' . $fqfn . ' ...');
165 // Init compressed data
166 $compressedData = $this->getFileIoInstance()->loadFileContents($fqfn);
167 $compressedData = $compressedData['data'];
169 // Close the file and throw the instance away
170 unset($fileInstance);
173 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
176 $dataArray = unserialize($serializedData);
179 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Read ' . count($dataArray) . ' elements from database file ' . $fqfn . '.');
186 * Writes data array to local file
188 * @param $fqfn The FQFN of the local file
189 * @param $dataArray An array with all the data we shall write
192 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
194 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $fqfn . ' ...');
196 // Serialize and compress it
197 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
200 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
202 // Write this data BASE64 encoded to the file
203 $this->getFileIoInstance()->saveFile($fqfn, $compressedData);
206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
210 * Getter for table information file contents or an empty if info file was not created
212 * @param $dataSetInstance An instance of a database set class
213 * @return $infoArray An array with all table informations
215 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
216 // Default content is no data
217 $infoArray = array();
219 // Create FQFN for getting the table information file
220 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
222 // Get the file contents
224 $infoArray = $this->getDataArrayFromFile($fqfn);
225 } catch (FileIoException $e) {
226 // Not found, so ignore it here
234 * Generates an FQFN from given dataset instance and string
236 * @param $dataSetInstance An instance of a database set class
237 * @param $rowName Name of the row
238 * @return $fqfn The FQFN for this row
240 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
242 $fqfn = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
249 * Creates the table info file from given dataset instance
251 * @param $dataSetInstance An instance of a database set class
254 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
255 // Create FQFN for creating the table information file
256 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
258 // Get the data out from dataset in a local array
259 $this->tableInfo[$dataSetInstance->getTableName()] = array(
260 'primary' => $dataSetInstance->getPrimaryKey(),
262 'last_updated' => time()
265 // Write the data to the file
266 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
270 * Updates the primary key information or creates the table info file if not found
272 * @param $dataSetInstance An instance of a database set class
275 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
276 // Get the information array from lower method
277 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
279 // Is the primary key there?
280 if (!isset($this->tableInfo['primary'])) {
281 // Then create the info file
282 $this->createTableInfoFile($dataSetInstance);
283 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
284 // Set the array element
285 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
288 $this->updateTableInfoFile($dataSetInstance);
293 * Makes sure that the database connection is alive
296 * @todo Do some checks on the database directory and files here
298 public function connectToDatabase () {
302 * Starts a SELECT query on the database by given return type, table name
303 * and search criteria
305 * @param $tableName Name of the database table
306 * @param $criteria Local search criteria class
307 * @return $resultData Result data of the query
308 * @throws UnsupportedCriteriaException If the criteria is unsupported
309 * @throws SqlException If an 'SQL error' occurs
311 public function querySelect ($tableName, LocalSearchCriteria $criteriaInstance) {
312 // The result is null by any errors
315 // Create full path name
316 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
318 // A 'select' query is not that easy on local files, so first try to
319 // find the 'table' which is in fact a directory on the server
321 // Get a directory pointer instance
322 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
324 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
326 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
327 BaseDatabaseBackend::RESULT_INDEX_ROWS => array()
330 // Initialize limit/skip
335 // Read the directory with some exceptions
336 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && (($limitFound < $criteriaInstance->getLimit()) || ($criteriaInstance->getLimit() == 0))) {
337 // Does the extension match?
338 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
344 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
345 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray,true));
348 if (is_array($dataArray)) {
349 // Search in the criteria with FMFW (First Matches, First Wins)
350 foreach ($dataArray as $key => $value) {
351 // Get criteria element
352 $criteria = $criteriaInstance->getCriteriaElemnent($key);
354 // Is the criteria met or none set?
355 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: criteria[' . gettype($criteria) . ']=' . $criteria . ';()=' . strlen($criteria) . ',criteriaInstance()=' . $criteriaInstance->count() . ',value(' . strlen($value) . ')=' . $value);
356 if (((!is_null($criteria)) && ($criteria == $value)) || ($criteriaInstance->count() == 0)) {
357 // Shall we skip this entry?
358 if ($criteriaInstance->getSkip() > 0) {
359 // We shall skip some entries
360 if ($skipFound < $criteriaInstance->getSkip()) {
368 $dataArray[$this->getIndexKey()] = $idx;
371 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, true));
372 $resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS][] = $dataArray;
374 // Count found entries up
380 // Throw an exception here
381 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
388 // Close directory and throw the instance away
389 $directoryInstance->closeDirectory();
390 unset($directoryInstance);
392 // Reset last exception
393 $this->resetLastException();
394 } catch (PathIsNoDirectoryException $e) {
395 // Path not found means "table not found" for real databases...
396 $this->setLastException($e);
398 // So throw an SqlException here with faked error message
399 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
400 } catch (FrameworkException $e) {
401 // Catch all exceptions and store them in last error
402 $this->setLastException($e);
405 // Return the gathered result
410 * "Inserts" a data set instance into a local file database folder
412 * @param $dataSetInstance A storeable data set
414 * @throws SqlException If an SQL error occurs
416 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
417 // Create full path name
418 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
420 // Try to save the request away
422 // Write the data away
423 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
425 // Update the primary key
426 $this->updatePrimaryKey($dataSetInstance);
428 // Reset last exception
429 $this->resetLastException();
430 } catch (FrameworkException $e) {
431 // Catch all exceptions and store them in last error
432 $this->setLastException($e);
434 // Throw an SQL exception
435 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);
440 * "Updates" a data set instance with a database layer
442 * @param $dataSetInstance A storeable data set
444 * @throws SqlException If an SQL error occurs
446 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
447 // Create full path name
448 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/';
450 // Try all the requests
452 // Get a file pointer instance
453 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
455 // Initialize limit/skip
459 // Get the criteria array from the dataset
460 $criteriaArray = $dataSetInstance->getCriteriaArray();
462 // Get search criteria
463 $searchInstance = $dataSetInstance->getSearchInstance();
465 // Read the directory with some exceptions
466 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
467 // Does the extension match?
468 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
470 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
475 // Open this file for reading
476 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
477 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray,true));
480 if (is_array($dataArray)) {
481 // Search in the criteria with FMFW (First Matches, First Wins)
482 foreach ($dataArray as $key => $value) {
483 // Get criteria element
484 $criteria = $searchInstance->getCriteriaElemnent($key);
485 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',key=' . $key . ',criteria=' . $criteria);
487 // Is the criteria met?
488 if (((!is_null($criteria)) && ($criteria == $value)) || ($searchInstance->count() == 0)) {
489 // Shall we skip this entry?
490 if ($searchInstance->getSkip() > 0) {
491 // We shall skip some entries
492 if ($skipFound < $searchInstance->getSkip()) {
499 // Entry found, so update it
500 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
501 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: criteriaKey=' . $criteriaKey . ',criteriaValue=' . $criteriaValue);
502 $dataArray[$criteriaKey] = $criteriaValue;
505 // Write the data to a local file
506 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
516 // Close the file pointer
517 $directoryInstance->closeDirectory();
519 // Update the primary key
520 $this->updatePrimaryKey($dataSetInstance);
522 // Reset last exception
523 $this->resetLastException();
524 } catch (FrameworkException $e) {
525 // Catch all exceptions and store them in last error
526 $this->setLastException($e);
528 // Throw an SQL exception
529 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);
534 * Getter for primary key of specified table or if not found null will be
535 * returned. This must be database-specific.
537 * @param $tableName Name of the table we need the primary key from
538 * @return $primaryKey Primary key column of the given table
540 public function getPrimaryKeyOfTable ($tableName) {
541 // Default key is null
544 // Does the table information exist?
545 if (isset($this->tableInfo[$tableName])) {
546 // Then return the primary key
547 $primaryKey = $this->tableInfo[$tableName]['primary'];