You are here

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

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

Override DatabaseSchema::renameTable().

@status complete

Overrides DatabaseSchema::renameTable

File

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

Class

DatabaseSchema_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.'));
  }

  // Borrar la caché de table_exists
  fastcache::cache_clear_all('*', 'tableExists', TRUE);
  $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',
      ));
    }
  }
}