You are here

public function DatabaseSchema_sqlsrv::renameTable in Drupal driver for SQL Server and SQL Azure 7

Same name and namespace in other branches
  1. 7.3 sqlsrv/schema.inc \DatabaseSchema_sqlsrv::renameTable()
  2. 7.2 sqlsrv/schema.inc \DatabaseSchema_sqlsrv::renameTable()

Override DatabaseSchema::renameTable().

@status complete

Overrides DatabaseSchema::renameTable

File

sqlsrv/schema.inc, line 390
Database schema code for Microsoft SQL Server database servers.

Class

DatabaseSchema_sqlsrv

Code

public function renameTable($table, $new_name) {
  if (!$this
    ->tableExists($table)) {
    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)) {
    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('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('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('EXEC sp_rename :old, :new, :type', array(
        ':old' => $old_table_info['schema'] . '.' . $object->name,
        ':new' => $new_table_info['table'] . '_' . $matches[1],
        ':type' => 'OBJECT',
      ));
    }
  }
}