You are here

public function Schema::renameTable in Drupal driver for SQL Server and SQL Azure 8

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. 3.0.x drivers/lib/Drupal/Driver/Database/sqlsrv/Schema.php \Drupal\Driver\Database\sqlsrv\Schema::renameTable()

Override DatabaseSchema::renameTable().

@status complete

Overrides Schema::renameTable

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Schema.php, line 896
Definition of Drupal\Driver\Database\sqlsrv\Schema

Class

Schema

Namespace

Drupal\Driver\Database\sqlsrv

Code

public function renameTable($table, $new_name) {
  if (!$this
    ->tableExists($table, TRUE)) {
    throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename %table to %table_new: table %table doesn't exist.", array(
      '%table' => $table,
      '%table_new' => $new_name,
    )));
  }
  if ($this
    ->tableExists($new_name, TRUE)) {
    throw new DatabaseSchemaObjectExistsException(t("Cannot rename %table to %table_new: table %table_new already exists.", array(
      '%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
    ->query_direct('EXEC sp_rename :old, :new', array(
    ':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
    ->query_direct('SELECT name FROM sys.objects WHERE parent_object_id = OBJECT_ID(:table)', array(
    ':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
        ->query_direct('EXEC sp_rename :old, :new, :type', array(
        ':old' => $old_table_info['schema'] . '.' . $object->name,
        ':new' => $new_table_info['table'] . '_' . $matches[1],
        ':type' => 'OBJECT',
      ));
    }
  }
}