You are here

private function DatabaseSchema_sqlsrv::createPrimaryKey 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::createPrimaryKey()

Create a Primary Key for the table, does not drop any prior primary keys neither it takes care of cleaning technical primary column. Only call this if you are sure the table does not currently hold a primary key.

Parameters

string $table:

mixed $fields:

int $limit:

4 calls to DatabaseSchema_sqlsrv::createPrimaryKey()
DatabaseSchema_sqlsrv::addPrimaryKey in sqlsrv/schema.inc
Override DatabaseSchema::addPrimaryKey().
DatabaseSchema_sqlsrv::compressPrimaryKeyIndex in sqlsrv/schema.inc
Sometimes the size of a table's primary key index needs to be reduced to allow for Primary XML Indexes.
DatabaseSchema_sqlsrv::createTable in sqlsrv/schema.inc
{@Inheritdoc}
DatabaseSchema_sqlsrv::recreatePrimaryKey in sqlsrv/schema.inc
Drops the current primary key and creates a new one. If the previous primary key was an internal primary key, it tries to cleant it up.

File

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

Class

DatabaseSchema_sqlsrv

Code

private function createPrimaryKey($table, $fields, $limit = 900) {

  // To be on the safe side, on the most restrictive use case the limit
  // for a primary key clustered index is of 128 bytes (usually 900).
  // @see http://blogs.msdn.com/b/jgalla/archive/2005/08/18/453189.aspx
  // If that is going to be exceeded, use a computed column.
  $csv_fields = $this
    ->createKeySql($fields);
  $size = $this
    ->calculateClusteredIndexRowSizeBytes($table, $this
    ->createKeySql($fields, TRUE));
  $result = array();
  $index = FALSE;

  // Add support for nullable columns in a primary key.
  $nullable = FALSE;
  $field_specs = $this
    ->loadFieldsSpec($fields, $table);
  foreach ($field_specs as $field) {
    if ($field['is_nullable'] == TRUE) {
      $nullable = TRUE;
      break;
    }
  }
  if ($nullable || $size >= $limit) {

    // Use a computed column instead, and create a custom index.
    $result[] = "{$this->COMPUTED_PK_COLUMN_NAME} AS (CONVERT(VARCHAR(32), HASHBYTES('MD5', CONCAT('',{$csv_fields})), 2)) PERSISTED NOT NULL";
    $result[] = "CONSTRAINT {{$table}}_pkey PRIMARY KEY CLUSTERED ({$this->COMPUTED_PK_COLUMN_NAME})";
    $index = TRUE;
  }
  else {
    $result[] = "CONSTRAINT {{$table}}_pkey PRIMARY KEY CLUSTERED ({$csv_fields})";
  }
  $this->connection
    ->query_direct('ALTER TABLE [{' . $table . '}] ADD ' . implode(' ', $result));

  // If we relied on a computed column for the Primary Key,
  // at least index the fields with a regular index.
  if ($index) {
    $this
      ->addIndex($table, $this->COMPUTED_PK_COLUMN_INDEX, $fields);
  }

  // Invalidate current introspection.
  $this
    ->queryColumnInformationInvalidate($table);
}