]> git.mxchange.org Git - core.git/blobdiff - framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php
Continued:
[core.git] / framework / main / classes / database / backend / lfdb_legacy / class_CachedLocalFileDatabase.php
index 7bdd9d4083f7b0c1615d2cacf6d61ea62c508062..a4ef4ffcc0f6b8807063f2e19d006ca2d081fcc2 100644 (file)
@@ -9,7 +9,8 @@ use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
 use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Database\Sql\SqlException;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
 use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
@@ -19,6 +20,7 @@ use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
 // Import SPL stuff
 use \InvalidArgumentException;
 use \SplFileInfo;
+use \UnexpectedValueException;
 
 /**
  * Database backend class for storing objects in locally created files.
@@ -31,7 +33,7 @@ use \SplFileInfo;
  *
  * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.shipsimu.org
  *
@@ -83,13 +85,19 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
         */
        private $indexKey = '__idx';
 
+       /**
+        * Cached file names based on table name to avoid "expensive" invocations
+        * of FrameworkConfiguration->getConfigEntry().
+        */
+       private $pathNames = [];
+
        /**
         * The protected constructor. Do never instance from outside! You need to
         * set a local file path. The class will then validate it.
         *
         * @return      void
         */
-       protected function __construct () {
+       private function __construct () {
                // Call parent constructor
                parent::__construct(__CLASS__);
        }
@@ -322,7 +330,7 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                        // Then create the info file
                        //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Creating info table for tableName=%s ...', $tableName));
                        $this->createTableInfoFile($dataSetInstance);
-               } elseif ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
+               } elseif (FrameworkBootstrap::getConfigurationInstance()->isEnabled('db_update_primary_forced') && $dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary']) {
                        // Set the array element
                        //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
                        $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
@@ -362,22 +370,22 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                if (empty($tableName)) {
                        // Throw IAE
                        throw new InvalidArgumentException('Parameter "tableName" is empty');
+               } elseif (!isset($this->pathNames[$tableName])) {
+                       // "Cache" is not present, so create and assign it
+                       $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
                }
 
                // The result is null by any errors
                $resultData = NULL;
 
-               // Create full path name
-               $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
-
                /*
                 * A 'select' query is not that easy on local files, so first try to
                 * find the 'table' which is in fact a directory on the server
                 */
                try {
                        // Get a directory pointer instance
-                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for pathName=%s ...', $pathName));
-                       $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for this->pathNames[%s]=%s ...', $tableName, $this->pathNames[$tableName]));
+                       $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
 
                        // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
                        $resultData = [
@@ -391,7 +399,7 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                        $idx = 1;
 
                        // Read the directory with some exceptions
-                       while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
+                       while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
                                // Does the extension match?
                                //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
                                if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
@@ -413,11 +421,8 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                                        // Search in the criteria with FMFW (First Matches, First Wins)
                                        //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: data[]=%d', count($dataArray)));
                                        foreach ($dataArray as $key => $value) {
-                                               // Make sure value is not bool
-                                               assert(!is_bool($value));
-
                                                // Found one entry?
-                                               $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
+                                               $isFound = ($isFound && $searchInstance->isCriteriaMatching($key, $value));
                                                //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
                                        }
 
@@ -425,15 +430,11 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                                        //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
                                        if ($isFound === true) {
                                                // Shall we skip this entry?
-                                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d', $searchInstance->getSkip()));
-                                               if ($searchInstance->getSkip() > 0) {
-                                                       // We shall skip some entries
-                                                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: skipFound=%s', $skipFound));
-                                                       if ($skipFound < $searchInstance->getSkip()) {
-                                                               // Skip this entry
-                                                               $skipFound++;
-                                                               break;
-                                                       }
+                                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d,skipFound=%d', $searchInstance->getSkip(), $skipFound));
+                                               if ($searchInstance->getSkip() > 0 && $skipFound < $searchInstance->getSkip()) {
+                                                       // Skip this entry
+                                                       $skipFound++;
+                                                       break;
                                                }
 
                                                // Set id number
@@ -507,11 +508,15 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                        $this->setLastException($e);
 
                        // Throw an SQL exception
-                       throw new SqlException(array(
+                       throw new SqlException([
                                        $this,
-                                       sprintf('Cannot write data to table &#39;%s&#39;, is the table created?', $dataSetInstance->getTableName()),
+                                       sprintf('Cannot write data to table &#39;%s&#39;, is the table created? e=%s,e->message=%s',
+                                               $dataSetInstance->getTableName(),
+                                               $e->__toString(),
+                                               $e->getMessage()
+                                       ),
                                        self::DB_CODE_TABLE_UNWRITEABLE
-                               ),
+                               ],
                                self::EXCEPTION_SQL_QUERY
                        );
                }
@@ -525,16 +530,26 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
         *
         * @param       $dataSetInstance        An instance of a StorableCriteria class
         * @return      void
+        * @throws      UnexpectedValueException        If $tableName is empty
         * @throws      SqlException    If an SQL error occurs
         */
        public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
-               // Create full path name
-               $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
+               // Get table name
+               $tableName = $dataSetInstance->getTableName();
+
+               // Is "cache" there?
+               if (empty($tableName)) {
+                       // Should never be an empty string
+                       throw new UnexpectedValueException('Class field dataSetInstance->tableName is empty');
+               } elseif (!isset($this->pathNames[$tableName])) {
+                       // "Cache" is not present, so create and assign it
+                       $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
+               }
 
                // Try all the requests
                try {
                        // Get a file pointer instance
-                       $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
+                       $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
 
                        // Initialize limit/skip
                        $limitFound = 0;
@@ -547,7 +562,7 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                        $searchInstance = $dataSetInstance->getSearchInstance();
 
                        // Read the directory with some exceptions
-                       while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
+                       while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
                                // Does the extension match?
                                //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
                                if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
@@ -568,9 +583,6 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
 
                                        // Search in the criteria with FMFW (First Matches, First Wins)
                                        foreach ($dataArray as $key => $value) {
-                                               // Make sure value is not bool
-                                               assert(!is_bool($value));
-
                                                // Found one entry?
                                                $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
                                        }
@@ -688,23 +700,22 @@ class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBac
                if (empty($tableName)) {
                        // Throw IAE
                        throw new InvalidArgumentException('Parameter "tableName" is empty');
+               } elseif (!isset($this->pathNames[$tableName])) {
+                       // "Cache" is not present, so create and assign it
+                       $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
                }
 
-
-               // Create full path name
-               $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
-
                // Try all the requests
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: pathName=' . $pathName);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: this->pathNames[%s]=%s', $tableName, $this->pathNames[$tableName]));
                try {
                        // Get a file pointer instance
-                       $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
+                       $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
 
                        // Initialize counter
                        $count = 0;
 
                        // Read the directory with some exceptions
-                       while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
+                       while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) {
                                // Does the extension match?
                                //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
                                if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {