You are here

public static function DbHandler::optimizeTables in DB Maintenance 8

Same name and namespace in other branches
  1. 7.2 src/Module/Db/DbHandler.php \Drupal\db_maintenance\Module\Db\DbHandler::optimizeTables()
  2. 2.0.x src/Module/Db/DbHandler.php \Drupal\db_maintenance\Module\Db\DbHandler::optimizeTables()

Performs the maintenance.

2 calls to DbHandler::optimizeTables()
CommonHookHandler::hookCron in src/Module/Hook/CommonHookHandler.php
Implements hook_cron().
DefaultController::optimizeTables in src/Controller/DefaultController.php

File

src/Module/Db/DbHandler.php, line 26
DbHandler class.

Class

DbHandler
DbHandler class.

Namespace

Drupal\db_maintenance\Module\Db

Code

public static function optimizeTables() {
  $dbs = self::getDatabases();
  foreach ($dbs as $db => $connection) {
    $db_name = $connection['default']['database'];
    $all_tables = ConfigHandler::getProcessAllTables();
    if ($all_tables) {
      $config_tables = self::listTables($db);
    }
    else {
      $config_tables = ConfigHandler::getTableList($db_name);
    }

    // Only proceed if tables are selected for this database.
    if (is_array($config_tables) && count($config_tables) > 0) {
      foreach ($config_tables as $key => $table_name) {

        // Set the database to query.
        $previous = Database::setActiveConnection($db);
        $table_clear = PrefixHandler::clearPrefix($table_name);
        if (Database::getConnection()
          ->schema()
          ->tableExists($table_clear)) {
          $handler = DbServerHandlerFactory::getDbServerHandler();
          $handler
            ->optimizeTable($table_name);
        }
        else {
          WatchdogAdapter::watchdog('db_maintenance', '@table table in @db database was configured to be optimized but does not exist.', array(
            '@db' => $db_name,
            '@table' => $table_name,
          ), LogLevel::NOTICE);
        }

        // Return to the previously set database.
        Database::setActiveConnection($previous);
        WatchdogAdapter::watchdog('db_maintenance', 'Optimized @table table in @db database.', array(
          '@db' => $db_name,
          '@table' => $table_name,
        ), LogLevel::DEBUG);
      }
      if (ConfigHandler::getWriteLog()) {
        $tables = implode(', ', $config_tables);
        WatchdogAdapter::watchdog('db_maintenance', 'Optimized tables in @db database: @tables', array(
          '@db' => $db_name,
          '@tables' => $tables,
        ), LogLevel::INFO);
      }
    }
  }
  ConfigHandler::setCronLastRun(\Drupal::time()
    ->getRequestTime());
}