InvalidDataTest.php in Zircon Profile 8
File
core/modules/system/src/Tests/Database/InvalidDataTest.php
View source
<?php
namespace Drupal\system\Tests\Database;
use Drupal\Core\Database\IntegrityConstraintViolationException;
class InvalidDataTest extends DatabaseTestBase {
function testInsertDuplicateData() {
try {
db_insert('test')
->fields(array(
'name',
'age',
'job',
))
->values(array(
'name' => 'Elvis',
'age' => 63,
'job' => 'Singer',
))
->values(array(
'name' => 'John',
'age' => 17,
'job' => 'Consultant',
))
->values(array(
'name' => 'Frank',
'age' => 75,
'job' => 'Singer',
))
->execute();
$this
->fail('Insert succeeded when it should not have.');
} catch (IntegrityConstraintViolationException $e) {
$name = db_query('SELECT name FROM {test} WHERE age = :age', array(
':age' => 63,
))
->fetchField();
if ($name == 'Elvis') {
if (!Database::getConnection()
->supportsTransactions()) {
$this
->pass("The whole transaction has not been rolled-back when a duplicate key insert occurs, this is expected because the database doesn't support transactions");
}
else {
$this
->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
}
}
else {
$this
->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
}
$record = db_select('test')
->fields('test', array(
'name',
'age',
))
->condition('age', array(
17,
75,
), 'IN')
->execute()
->fetchObject();
$this
->assertFalse($record, 'The rest of the insert aborted as expected.');
}
}
}