You are here

public function Schema::renameTable in Drupal driver for SQL Server and SQL Azure 3.0.x

Same name and namespace in other branches
  1. 8.2 drivers/lib/Drupal/Driver/Database/sqlsrv/Schema.php \Drupal\Driver\Database\sqlsrv\Schema::renameTable()
  2. 8 drivers/lib/Drupal/Driver/Database/sqlsrv/Schema.php \Drupal\Driver\Database\sqlsrv\Schema::renameTable()

Rename a table.

Parameters

$table: The table to be renamed.

$new_name: The new name for the table.

Throws

\Drupal\Core\Database\SchemaObjectDoesNotExistException If the specified table doesn't exist.

\Drupal\Core\Database\SchemaObjectExistsException If a table with the specified new name already exists.

Overrides Schema::renameTable

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Schema.php, line 177

Class

Schema

Namespace

Drupal\Driver\Database\sqlsrv

Code

public function renameTable($table, $new_name) {
  if (!$this
    ->tableExists($table)) {
    throw new SchemaObjectDoesNotExistException(t("Cannot rename %table to %table_new: table %table doesn't exist.", [
      '%table' => $table,
      '%table_new' => $new_name,
    ]));
  }
  if ($this
    ->tableExists($new_name)) {
    throw new SchemaObjectExistsException(t("Cannot rename %table to %table_new: table %table_new already exists.", [
      '%table' => $table,
      '%table_new' => $new_name,
    ]));
  }
  $old_table_info = $this
    ->getPrefixInfo($table);
  $new_table_info = $this
    ->getPrefixInfo($new_name);

  // We don't support renaming tables across schemas (yet).
  if ($old_table_info['schema'] != $new_table_info['schema']) {
    throw new \PDOException(t('Cannot rename a table across schema.'));
  }
  $this->connection
    ->queryDirect('EXEC sp_rename :old, :new', [
    ':old' => $old_table_info['schema'] . '.' . $old_table_info['table'],
    ':new' => $new_table_info['table'],
  ]);

  // Constraint names are global in SQL Server, so we need to rename them
  // when renaming the table. For some strange reason, indexes are local to
  // a table.
  $objects = $this->connection
    ->queryDirect('SELECT name FROM sys.objects WHERE parent_object_id = OBJECT_ID(:table)', [
    ':table' => $new_table_info['schema'] . '.' . $new_table_info['table'],
  ]);
  foreach ($objects as $object) {
    if (preg_match('/^' . preg_quote($old_table_info['table']) . '_(.*)$/', $object->name, $matches)) {
      $this->connection
        ->queryDirect('EXEC sp_rename :old, :new, :type', [
        ':old' => $old_table_info['schema'] . '.' . $object->name,
        ':new' => $new_table_info['table'] . '_' . $matches[1],
        ':type' => 'OBJECT',
      ]);
    }
  }
  $this
    ->resetColumnInformation($table);
}