]> git.mxchange.org Git - core.git/blobdiff - inc/classes/main/database/class_BaseDatabaseWrapper.php
Used more DatabaseWrapperFactory as one instance of each is fine.
[core.git] / inc / classes / main / database / class_BaseDatabaseWrapper.php
index e406938b42fb4f025ec3a7b0d163888cbfef289a..c2a18b864e59f43df7d31fc98563e8469c75f1fc 100644 (file)
@@ -2,11 +2,11 @@
 /**
  * A generic database wrapper
  *
- * @author             Roland Haeder <webmaster@ship-simu.org>
+ * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, this is free software
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
- * @link               http://www.ship-simu.org
+ * @link               http://www.shipsimu.org
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -25,28 +25,24 @@ class BaseDatabaseWrapper extends BaseFrameworkSystem {
        /**
         * Cache instance
         */
-       private $cacheInstance = null;
+       private $cacheInstance = NULL;
 
        /**
         * Current table name to use
         */
-       private $tableName = "unknown";
+       private $tableName = 'unknown';
 
        /**
         * Protected constructor
         *
         * @return      void
         */
-       protected function __construct($class) {
+       protected function __construct ($class) {
                // Call parent constructor
                parent::__construct($class);
 
                // Initialize the cache instance
                $this->initCacheInstance();
-
-               // Clean up a little
-               $this->removeNumberFormaters();
-               $this->removeSystemArray();
        }
 
        /**
@@ -55,8 +51,104 @@ class BaseDatabaseWrapper extends BaseFrameworkSystem {
         * @return      void
         */
        private final function initCacheInstance () {
-               // Set the new instance
-               $this->cacheInstance = CacheFactory::getFactory()->createConfiguredCache();
+               // Is the cache enabled?
+               if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) {
+                       // Set the new instance
+                       $this->cacheInstance = CacheFactory::getFactory()->createConfiguredCache();
+               } // END - if
+       }
+
+       /**
+        * Setter for table name
+        *
+        * @param       $tableName      Name of table name to set
+        * @return      void
+        */
+       protected final function setTableName ($tableName) {
+               $this->tableName = (string) $tableName;
+       }
+
+       /**
+        * Getter for table name
+        *
+        * @return      $tableName      Name of table name to set
+        */
+       protected final function getTableName () {
+               return $this->tableName;
+       }
+
+       /**
+        * 'Inserts' a data set instance into a local file database folder
+        *
+        * @param       $dataSetInstance        A storeable data set
+        * @param       $onlyKeys                       Only use these keys for a cache key
+        * @return      void
+        */
+       protected function queryInsertDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = array()) {
+               // Default cache key is NULL
+               $cacheKey = NULL;
+
+               // Is cache enabled?
+               if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) {
+                       // First get a key suitable for our cache and extend it with this class name
+                       $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
+                       //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Using cache key ' . $cacheKey . ' for purging ...');
+               } // END - if
+
+               // Does this key exists in cache?
+               if (($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) && ($this->cacheInstance->offsetExists($cacheKey))) {
+                       // Purge the cache
+                       $this->cacheInstance->purgeOffset($cacheKey);
+               } // END - if
+
+               // Handle it over to the middleware
+               $this->getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
+       }
+
+       /**
+        * 'Updates' a data set instance with a database layer
+        *
+        * @param       $dataSetInstance        A storeable data set
+        * @param       $onlyKeys                       Only use these keys for a cache key
+        * @return      void
+        */
+       protected function queryUpdateDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = array()) {
+               // Init cache key
+               $cacheKey = NULL;
+
+               // Is cache enabled?
+               if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) {
+                       // First get a key suitable for our cache and extend it with this class name
+                       $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
+                       //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Using cache key ' . $cacheKey . ' for purging ...');
+               } // END - if
+
+               // Does this key exists in cache?
+               if (($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) && ($this->cacheInstance->offsetExists($cacheKey))) {
+                       // Purge the cache
+                       $this->cacheInstance->purgeOffset($cacheKey);
+               } // END - if
+
+               // Handle it over to the middleware
+               $this->getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
+       }
+
+       /**
+        * Getter for index key
+        *
+        * @return      $indexKey       Index key
+        */
+       public final function getIndexKey () {
+               return $this->getDatabaseInstance()->getIndexKey();
+       }
+
+       /**
+        * Getter for last exception
+        *
+        * @return      $lastException  Last exception or NULL if none occured
+        */
+       public final function getLastException () {
+               return $this->getDatabaseInstance()->getLastException();
        }
 
        /**
@@ -64,38 +156,53 @@ class BaseDatabaseWrapper extends BaseFrameworkSystem {
         * store it in cache for later usage
         *
         * @param       $criteriaInstance       An instance of a Criteria class
+        * @param       $onlyKeys                       Only use these keys for a cache key
         * @return      $resultInstance         An instance of a database result class
         */
-       public function doSelectByCriteria (Criteria $criteriaInstance) {
-               // First get a key suitable for our cache and extend it with this class name
-               $cacheKey = sprintf("%s@%s",
-                       $this->__toString(),
-                       $criteriaInstance->getCacheKey()
-               );
+       public function doSelectByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
+               // Default cache key if cache is not enabled
+               $cacheKey = NULL;
+
+               // Is the cache enabled?
+               if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) {
+                       // First get a key suitable for our cache and extend it with this class name
+                       $cacheKey = $this->getCacheKeyByCriteria($criteriaInstance, $onlyKeys);
+               } // END - if
 
                // Does this key exists in cache?
-               if ($this->cacheInstance->offsetExists($cacheKey)) {
+               if (($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) && ($this->cacheInstance->offsetExists($cacheKey, BaseDatabaseBackend::RESULT_INDEX_ROWS, 1))) {
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Cache used for cacheKey=' . $cacheKey . ':' . print_r($this->cacheInstance->offsetGet($cacheKey), TRUE));
+
                        // Then use this result
-                       $result = $cacheInstance->offsetGet($cacheKey);
+                       $result = $this->cacheInstance->offsetGet($cacheKey);
                } else {
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: Quering database, cacheKey=' . $cacheKey);
+
                        // Now it's time to ask the database layer for this select statement
                        $result = $this->getDatabaseInstance()->doSelectByTableCriteria($this->getTableName(), $criteriaInstance);
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: result[]=' . gettype($result));
 
                        // Cache the result if not null
                        if (!is_null($result)) {
-                               // A valid result has returned from the database layer
-                               $this->cacheInstance->offsetSet($cacheKey, $result);
+                               // Is cache enabled?
+                               if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === TRUE) {
+                                       // A valid result has returned from the database layer
+                                       $this->cacheInstance->offsetSet($cacheKey, $result);
+                               } // END - if
                        } else {
                                // This invalid result must be wrapped
                                $result = array(
-                                       'status'                => "invalid",
-                                       'exception'             => $this->getDatabaseInstance()->getLastException()
+                                       BaseDatabaseBackend::RESULT_INDEX_STATUS    => 'invalid',
+                                       BaseDatabaseBackend::RESULT_INDEX_EXCEPTION => $this->getDatabaseInstance()->getLastException()
                                );
                        }
                }
 
-               // Create an instance of a DatabaseResult class with the given result
-               $resultInstance = DatabaseResult::createDatabaseResult($result);
+               // Create an instance of a CachedDatabaseResult class with the given result
+               // @TODO Minor: Update above comment to e.g. BaseDatabaseResult
+               $resultInstance = ObjectFactory::createObjectByConfiguredName('database_result_class', array($result));
 
                // And return the instance
                return $resultInstance;
@@ -105,19 +212,23 @@ class BaseDatabaseWrapper extends BaseFrameworkSystem {
         * Count the numbers of rows we shall receive
         *
         * @param       $criteriaInstance       An instance of a Criteria class
+        * @param       $onlyKeys                       Only use these keys for a cache key
         * @return      $numRows                        Numbers of rows of database entries
         */
-       public function doSelectCountByCriteria (Criteria $criteriaInstance) {
-               // Total numbers is zero by default
+       public function doSelectCountByCriteria (Criteria $criteriaInstance, $onlyKeys = array()) {
+               // Total numbers is -1 so we can distinglish between failed and valid queries
                $numRows = 0;
 
                // Get the result from above method
-               $resultInstance = $this->doSelectByCriteria($criteriaInstance);
+               $resultInstance = $this->doSelectByCriteria($criteriaInstance, $onlyKeys);
 
                // Was that query fine?
                if ($resultInstance->ifStatusIsOkay()) {
                        // Then get the number of rows
                        $numRows = $resultInstance->getAffectedRows();
+
+                       // Debug message
+                       //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-WRAPPER: numRows=' . $numRows);
                } // END - if
 
                // Return the result
@@ -125,35 +236,43 @@ class BaseDatabaseWrapper extends BaseFrameworkSystem {
        }
 
        /**
-        * Setter for table name
+        * Getter for primary key used in wrapped table
         *
-        * @param       $tableName      Name of table name to set
-        * @return      void
+        * @return      $primaryKey             Primary key used in wrapped table
         */
-       protected final function setTableName ($tableName) {
-               $this->tableName = (string) $tableName;
+       public final function getPrimaryKeyValue () {
+               // Get the table name and a database instance and ask for it
+               $primaryKey = $this->getDatabaseInstance()->getPrimaryKeyOfTable($this->getTableName());
+
+               // Return value
+               return $primaryKey;
        }
 
        /**
-        * Getter for table name
+        * Count rows of this table
         *
-        * @return      $tableName      Name of table name to set
+        * @return      $count  Count of total rows in this table
         */
-       protected final function getTableName () {
-               return $this->tableName;
+       public final function countTotalRows () {
+               // Get the table name and a database instance and ask for it
+               $count = $this->getDatabaseInstance()->countTotalRows($this->getTableName());
+
+               // Return value
+               return $count;
        }
 
        /**
-        * Getter for primary key used in wrapped table
+        * Removes non-public data from given array.
         *
-        * @return      $primaryKey             Primary key used in wrapped table
+        * @param       $data   An array with possible non-public data that needs to be removed.
+        * @return      $data   A cleaned up array with only public data.
         */
-       public final function getPrimaryKeyValue () {
-               // Get the table name and a database instance and ask for it
-               $primaryKey = $this->getDatabaseInstance()->getPrimaryKeyOfTable($this->getTableName());
+       public function removeNonPublicDataFromArray (array $data) {
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('WRAPPER[' . $this->__toString() . ']: Calling this->getDatabaseInstance()->removeNonPublicDataFromArray(data) ...');
+               $data = $this->getDatabaseInstance()->removeNonPublicDataFromArray($data);
 
-               // Return value
-               return $primaryKey;
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('WRAPPER[' . $this->__toString() . ']: data[]=' . gettype($data));
+               return $data;
        }
 }