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 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 * Whether the "connection is already up
53 private $alreadyConnected = false;
56 * Table information array
58 private $tableInfo = array();
63 private $indexKey = '__idx';
66 * The protected constructor. Do never instance from outside! You need to
67 * set a local file path. The class will then validate it.
71 protected function __construct () {
72 // Call parent constructor
73 parent::__construct(__CLASS__);
77 * Create an object of LocalFileDatabase and set the save path from
78 * configuration for local files.
80 * @return $databaseInstance An instance of LocalFileDatabase
82 public static final function createLocalFileDatabase () {
84 $databaseInstance = new LocalFileDatabase();
86 // Get a new compressor channel instance
87 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
89 // Set the compressor channel
90 $databaseInstance->setCompressorChannel($compressorInstance);
92 // "Connect" to the database
93 $databaseInstance->connectToDatabase();
95 // Return database instance
96 return $databaseInstance;
100 * Setter for the last read file
102 * @param $fqfn The FQFN of the last read file
105 private final function setLastFile ($fqfn) {
106 // Cast string and set it
107 $this->lastFile = (string) $fqfn;
111 * Getter for last read file
113 * @return $lastFile The last read file's name with full path
115 public final function getLastFile () {
116 return $this->lastFile;
120 * Setter for contents of the last read file
122 * @param $contents An array with header and data elements
125 private final function setLastFileContents (array $contents) {
127 $this->lastContents = $contents;
131 * Getter for last read file's content as an array
133 * @return $lastContent The array with elements 'header' and 'data'.
135 public final function getLastContents () {
136 return $this->lastContents;
140 * Getter for file extension
142 * @return $fileExtension The array with elements 'header' and 'data'.
144 public final function getFileExtension () {
145 return $this->fileExtension;
149 * Getter for index key
151 * @return $indexKey Index key
153 public final function getIndexKey () {
154 return $this->indexKey;
158 * Reads a local data file and returns it's contents in an array
160 * @param $fqfn The FQFN for the requested file
163 private function getDataArrayFromFile ($fqfn) {
164 // Get a file pointer
165 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
167 // Get the raw data and BASE64-decode it
168 $compressedData = base64_decode($fileInstance->readLinesFromFile());
170 // Close the file and throw the instance away
171 $fileInstance->closeFile();
172 unset($fileInstance);
175 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
178 $dataArray = unserialize($serializedData);
185 * Writes data array to local file
187 * @param $fqfn The FQFN of the local file
188 * @param $dataArray An array with all the data we shall write
191 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
192 // Get a file pointer instance
193 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
195 // Serialize and compress it
196 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
198 // Write this data BASE64 encoded to the file
199 $fileInstance->writeToFile(base64_encode($compressedData));
201 // Close the file pointer
202 $fileInstance->closeFile();
206 * Getter for table information file contents or an empty if info file was not created
208 * @param $dataSetInstance An instance of a database set class
209 * @return $infoArray An array with all table informations
211 private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
212 // Default content is no data
213 $infoArray = array();
215 // Create FQFN for getting the table information file
216 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
218 // Get the file contents
220 $infoArray = $this->getDataArrayFromFile($fqfn);
221 } catch (FileIoException $e) {
222 // Not found, so ignore it here
230 * Generates an FQFN from given dataset instance and string
232 * @param $dataSetInstance An instance of a database set class
233 * @param $rowName Name of the row
234 * @return $fqfn The FQFN for this row
236 private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
238 $fqfn = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
245 * Creates the table info file from given dataset instance
247 * @param $dataSetInstance An instance of a database set class
250 private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
251 // Create FQFN for creating the table information file
252 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
254 // Get the data out from dataset in a local array
255 $this->tableInfo[$dataSetInstance->getTableName()] = array(
256 'primary' => $dataSetInstance->getPrimaryKey(),
258 'last_updated' => time()
261 // Write the data to the file
262 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
266 * Updates the primary key information or creates the table info file if not found
268 * @param $dataSetInstance An instance of a database set class
271 private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
272 // Get the information array from lower method
273 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
275 // Is the primary key there?
276 if (!isset($this->tableInfo['primary'])) {
277 // Then create the info file
278 $this->createTableInfoFile($dataSetInstance);
279 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
280 // Set the array element
281 $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
284 $this->updateTableInfoFile($dataSetInstance);
289 * Makes sure that the database connection is alive
292 * @todo Do some checks on the database directory and files here
294 public function connectToDatabase () {
298 * Starts a SELECT query on the database by given return type, table name
299 * and search criteria
301 * @param $tableName Name of the database table
302 * @param $criteria Local search criteria class
303 * @return $resultData Result data of the query
304 * @throws UnsupportedCriteriaException If the criteria is unsupported
305 * @throws SqlException If an 'SQL error' occurs
307 public function querySelect ($tableName, LocalSearchCriteria $criteriaInstance) {
308 // The result is null by any errors
311 // Create full path name
312 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
314 // A 'select' query is not that easy on local files, so first try to
315 // find the 'table' which is in fact a directory on the server
317 // Get a directory pointer instance
318 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
320 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
322 BaseDatabaseFrontend::RESULT_INDEX_STATUS => LocalfileDatabase::RESULT_OKAY,
323 BaseDatabaseFrontend::RESULT_INDEX_ROWS => array()
326 // Initialize limit/skip
331 // Read the directory with some exceptions
332 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && (($limitFound < $criteriaInstance->getLimit()) || ($criteriaInstance->getLimit() == 0))) {
333 // Does the extension match?
334 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
340 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
343 if (is_array($dataArray)) {
344 // Search in the criteria with FMFW (First Matches, First Wins)
345 foreach ($dataArray as $key => $value) {
346 // Get criteria element
347 $criteria = $criteriaInstance->getCriteriaElemnent($key);
349 // Is the criteria met?
350 //* NOISY-DEBUG: */ $this->debugOutput('DATABASE: criteria[' . gettype($criteria) . ']=' . $criteria . ',()=' . strlen($criteria) . ',value=' . $value . ',()=' . strlen($value));
351 if ((!is_null($criteria)) && ($criteria == $value)) {
352 // Shall we skip this entry?
353 if ($criteriaInstance->getSkip() > 0) {
354 // We shall skip some entries
355 if ($skipFound < $criteriaInstance->getSkip()) {
363 $dataArray[$this->getIndexKey()] = $idx;
366 //* NOISY-DEBUG: */ $this->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, true));
367 $resultData[BaseDatabaseFrontend::RESULT_INDEX_ROWS][] = $dataArray;
369 // Count found entries up
375 // Throw an exception here
376 throw new SqlException(array($this, sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
383 // Close directory and throw the instance away
384 $directoryInstance->closeDirectory();
385 unset($directoryInstance);
387 // Reset last exception
388 $this->resetLastException();
389 } catch (PathIsNoDirectoryException $e) {
390 // Path not found means "table not found" for real databases...
391 $this->setLastException($e);
393 // So throw an SqlException here with faked error message
394 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
395 } catch (FrameworkException $e) {
396 // Catch all exceptions and store them in last error
397 $this->setLastException($e);
400 // Return the gathered result
405 * "Inserts" a data set instance into a local file database folder
407 * @param $dataSetInstance A storeable data set
409 * @throws SqlException If an SQL error occurs
411 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
412 // Create full path name
413 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
415 // Try to save the request away
417 // Write the data away
418 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
420 // Update the primary key
421 $this->updatePrimaryKey($dataSetInstance);
423 // Reset last exception
424 $this->resetLastException();
425 } catch (FrameworkException $e) {
426 // Catch all exceptions and store them in last error
427 $this->setLastException($e);
429 // Throw an SQL exception
430 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);
435 * "Updates" a data set instance with a database layer
437 * @param $dataSetInstance A storeable data set
439 * @throws SqlException If an SQL error occurs
441 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
442 // Create full path name
443 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/';
445 // Try all the requests
447 // Get a file pointer instance
448 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
450 // Initialize limit/skip
454 // Get the criteria array from the dataset
455 $criteriaArray = $dataSetInstance->getCriteriaArray();
457 // Get search criteria
458 $searchInstance = $dataSetInstance->getSearchInstance();
460 // Read the directory with some exceptions
461 while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
462 // Does the extension match?
463 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
468 // Open this file for reading
469 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
472 if (is_array($dataArray)) {
473 // Search in the criteria with FMFW (First Matches, First Wins)
474 foreach ($dataArray as $key => $value) {
475 // Get criteria element
476 $criteria = $searchInstance->getCriteriaElemnent($key);
478 // Is the criteria met?
479 if ((!is_null($criteria)) && ($criteria == $value)) {
481 // Shall we skip this entry?
482 if ($searchInstance->getSkip() > 0) {
483 // We shall skip some entries
484 if ($skipFound < $searchInstance->getSkip()) {
491 // Entry found, so update it
492 foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
493 $dataArray[$criteriaKey] = $criteriaValue;
496 // Write the data to a local file
497 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
507 // Close the file pointer
508 $directoryInstance->closeDirectory();
510 // Update the primary key
511 $this->updatePrimaryKey($dataSetInstance);
513 // Reset last exception
514 $this->resetLastException();
515 } catch (FrameworkException $e) {
516 // Catch all exceptions and store them in last error
517 $this->setLastException($e);
519 // Throw an SQL exception
520 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);
525 * Getter for primary key of specified table or if not found null will be
526 * returned. This must be database-specific.
528 * @param $tableName Name of the table we need the primary key from
529 * @return $primaryKey Primary key column of the given table
531 public function getPrimaryKeyOfTable ($tableName) {
532 // Default key is null
535 // Does the table information exist?
536 if (isset($this->tableInfo[$tableName])) {
537 // Then return the primary key
538 $primaryKey = $this->tableInfo[$tableName]['primary'];