You are here

public function Scheme::getSizeInfo in Drupal driver for SQL Server and SQL Azure 8.2

Return size information

Parameters

string $database: Name of the database.

Return value

mixed

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Scheme.php, line 743

Class

Scheme

Namespace

Drupal\Driver\Database\sqlsrv

Code

public function getSizeInfo($database) {
  $sql = <<<EOF
      SELECT
    DB_NAME(db.database_id) DatabaseName,
    (CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB,
    (CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB,
    (CAST(mfstream.StreamSize AS FLOAT)*8)/1024 StreamSizeMB,
    (CAST(mftext.TextIndexSize AS FLOAT)*8)/1024 TextIndexSizeMB
FROM sys.databases db
    LEFT JOIN (SELECT database_id, SUM(size) RowSize FROM sys.master_files WHERE type = 0 GROUP BY database_id, type) mfrows ON mfrows.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) LogSize FROM sys.master_files WHERE type = 1 GROUP BY database_id, type) mflog ON mflog.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) StreamSize FROM sys.master_files WHERE type = 2 GROUP BY database_id, type) mfstream ON mfstream.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) TextIndexSize FROM sys.master_files WHERE type = 4 GROUP BY database_id, type) mftext ON mftext.database_id = db.database_id
    WHERE DB_NAME(db.database_id) = :database
EOF;

  // Database is defaulted from active connection.
  $result = null;
  try {
    $result = $this->cnn
      ->query_execute($sql, array(
      ':database' => $database,
    ))
      ->fetchObject();
  } catch (\Exception $e) {

    // This might not work on azure...
  }

  // There is a chance that this might not return the database size, so
  // try another strategy.
  if (empty($result->RowSizeMB)) {
    $sql = <<<EOF
      SELECT (SUM(reserved_page_count) * 8192) / 1024 / 1024 AS DbSizeInMB
      FROM    sys.dm_db_partition_stats
EOF;
    $result->RowSizeMB = $this->cnn
      ->query_execute($sql)
      ->fetchField();
  }

  // Try and get the number of tables
  $sql = <<<EOF
      SELECT COUNT(*) from information_schema.tables
      WHERE table_type = 'base table'
EOF;
  $result->TableCount = $this->cnn
    ->query_execute($sql)
    ->fetchField();
  return $result;
}