You are here

public function Connection::__destruct in Drupal 8

Same name in this branch
  1. 8 core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php \Drupal\Core\Database\Driver\sqlite\Connection::__destruct()
  2. 8 core/lib/Drupal/Core/Database/Driver/mysql/Connection.php \Drupal\Core\Database\Driver\mysql\Connection::__destruct()
Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php \Drupal\Core\Database\Driver\sqlite\Connection::__destruct()

Destructor for the SQLite connection.

We prune empty databases on destruct, but only if tables have been dropped. This is especially needed when running the test suite, which creates and destroy databases several times in a row.

File

core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php, line 175

Class

Connection
SQLite implementation of \Drupal\Core\Database\Connection.

Namespace

Drupal\Core\Database\Driver\sqlite

Code

public function __destruct() {
  if ($this->tableDropped && !empty($this->attachedDatabases)) {
    foreach ($this->attachedDatabases as $prefix) {

      // Check if the database is now empty, ignore the internal SQLite tables.
      try {
        $count = $this
          ->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', [
          ':type' => 'table',
          ':pattern' => 'sqlite_%',
        ])
          ->fetchField();

        // We can prune the database file if it doesn't have any tables.
        if ($count == 0 && $this->connectionOptions['database'] != ':memory:') {

          // Detaching the database fails at this point, but no other queries
          // are executed after the connection is destructed so we can simply
          // remove the database file.
          unlink($this->connectionOptions['database'] . '-' . $prefix);
        }
      } catch (\Exception $e) {

        // Ignore the exception and continue. There is nothing we can do here
        // to report the error or fail safe.
      }
    }
  }
}