public function SchemaTestExtended::testPrimaryKeyHandling in Drupal driver for SQL Server and SQL Azure 8.2
Test adding / removing / readding a primary key to a table.
File
- tests/
src/ Kernel/ SchemaTestExtended.php, line 85
Class
- SchemaTestExtended
- Tests table creation and modification via the schema API.
Namespace
Drupal\Tests\sqlsrv\KernelCode
public function testPrimaryKeyHandling() {
$table_spec = array(
'fields' => array(
'id' => array(
'type' => 'int',
'not null' => TRUE,
),
),
);
$database = \Drupal::database();
$database
->schema()
->createTable('test_table', $table_spec);
$this
->assertTrue($database
->schema()
->tableExists('test_table'), t('Creating a table without a primary key works.'));
$database
->schema()
->addPrimaryKey('test_table', array(
'id',
));
$this
->pass(t('Adding a primary key should work when the table has no data.'));
// Try adding a row.
$database
->insert('test_table')
->fields(array(
'id' => 1,
))
->execute();
// The second row with the same value should conflict.
try {
$database
->insert('test_table')
->fields(array(
'id' => 1,
))
->execute();
$this
->fail(t('Duplicate values in the table should not be allowed when the primary key is there.'));
} catch (IntegrityConstraintViolationException $e) {
}
// Drop the primary key and retry.
$database
->schema()
->dropPrimaryKey('test_table');
$this
->pass(t('Removing a primary key should work.'));
$database
->insert('test_table')
->fields(array(
'id' => 1,
))
->execute();
$this
->pass(t('Adding a duplicate row should work without the primary key.'));
try {
$database
->schema()
->addPrimaryKey('test_table', array(
'id',
));
$this
->fail(t('Trying to add a primary key should fail with duplicate rows in the table.'));
} catch (IntegrityConstraintViolationException $e) {
}
}