public function Schema::addUniqueKey in Drupal driver for SQL Server and SQL Azure 3.1.x
Same name and namespace in other branches
- 4.2.x src/Driver/Database/sqlsrv/Schema.php \Drupal\sqlsrv\Driver\Database\sqlsrv\Schema::addUniqueKey()
- 4.0.x src/Driver/Database/sqlsrv/Schema.php \Drupal\sqlsrv\Driver\Database\sqlsrv\Schema::addUniqueKey()
- 4.1.x src/Driver/Database/sqlsrv/Schema.php \Drupal\sqlsrv\Driver\Database\sqlsrv\Schema::addUniqueKey()
Add a unique key.
Parameters
$table: The table to be altered.
$name: The name of the key.
$fields: An array of field names.
Throws
\Drupal\Core\Database\SchemaObjectDoesNotExistException If the specified table doesn't exist.
\Drupal\Core\Database\SchemaObjectExistsException If the specified table already has a key by that name.
Overrides Schema::addUniqueKey
2 calls to Schema::addUniqueKey()
- Schema::createTable in src/
Driver/ Database/ sqlsrv/ Schema.php - Create a new table from a Drupal table definition.
- Schema::recreateTableKeys in src/
Driver/ Database/ sqlsrv/ Schema.php - Re-create keys associated to a table.
File
- src/
Driver/ Database/ sqlsrv/ Schema.php, line 474
Class
Namespace
Drupal\sqlsrv\Driver\Database\sqlsrvCode
public function addUniqueKey($table, $name, $fields) {
if (!$this
->tableExists($table)) {
throw new SchemaObjectDoesNotExistException(t("Cannot add unique key %name to table %table: table doesn't exist.", [
'%table' => $table,
'%name' => $name,
]));
}
if ($this
->uniqueKeyExists($table, $name)) {
throw new SchemaObjectExistsException(t("Cannot add unique key %name to table %table: unique key already exists.", [
'%table' => $table,
'%name' => $name,
]));
}
$this
->createTechnicalPrimaryColumn($table);
// Then, build a expression based on the columns.
$column_expression = [];
foreach ($fields as $field) {
if (is_array($field)) {
$column_expression[] = 'SUBSTRING(CAST(' . $field[0] . ' AS varbinary(max)),1,' . $field[1] . ')';
}
else {
$column_expression[] = 'CAST(' . $field . ' AS varbinary(max))';
}
}
$column_expression = implode(' + ', $column_expression);
// Build a computed column based on the expression that replaces NULL
// values with the globally unique identifier generated previously.
// This is (very) unlikely to result in a collision with any actual value
// in the columns of the unique key.
$this->connection
->query("ALTER TABLE {{$table}} ADD __unique_{$name} AS CAST(HashBytes('MD4', COALESCE({$column_expression}, CAST(" . self::TECHNICAL_PK_COLUMN_NAME . " AS varbinary(max)))) AS varbinary(16))");
$this->connection
->query("CREATE UNIQUE INDEX {$name}_unique ON {{$table}} (__unique_{$name})");
$this
->resetColumnInformation($table);
}