PageRenderTime 63ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/core/tests/Drupal/KernelTests/Core/Database/SchemaTest.php

http://github.com/drupal/drupal
PHP | 1255 lines | 1217 code | 9 blank | 29 comment | 0 complexity | c28a25394601bbfaa13207715f4811b9 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. namespace Drupal\KernelTests\Core\Database;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Core\Database\Database;
  5. use Drupal\Core\Database\SchemaException;
  6. use Drupal\Core\Database\SchemaObjectDoesNotExistException;
  7. use Drupal\Core\Database\SchemaObjectExistsException;
  8. use Drupal\KernelTests\KernelTestBase;
  9. use Drupal\Component\Utility\Unicode;
  10. use Drupal\Tests\Core\Database\SchemaIntrospectionTestTrait;
  11. /**
  12. * Tests table creation and modification via the schema API.
  13. *
  14. * @coversDefaultClass \Drupal\Core\Database\Schema
  15. *
  16. * @group Database
  17. */
  18. class SchemaTest extends KernelTestBase {
  19. use SchemaIntrospectionTestTrait;
  20. /**
  21. * A global counter for table and field creation.
  22. *
  23. * @var int
  24. */
  25. protected $counter;
  26. /**
  27. * Connection to the database.
  28. *
  29. * @var \Drupal\Core\Database\Connection
  30. */
  31. protected $connection;
  32. /**
  33. * Database schema instance.
  34. *
  35. * @var \Drupal\Core\Database\Schema
  36. */
  37. protected $schema;
  38. /**
  39. * {@inheritdoc}
  40. */
  41. protected function setUp() {
  42. parent::setUp();
  43. $this->connection = Database::getConnection();
  44. $this->schema = $this->connection->schema();
  45. }
  46. /**
  47. * Tests database interactions.
  48. */
  49. public function testSchema() {
  50. // Try creating a table.
  51. $table_specification = [
  52. 'description' => 'Schema table description may contain "quotes" and could be long—very long indeed.',
  53. 'fields' => [
  54. 'id' => [
  55. 'type' => 'int',
  56. 'default' => NULL,
  57. ],
  58. 'test_field' => [
  59. 'type' => 'int',
  60. 'not null' => TRUE,
  61. 'description' => 'Schema table description may contain "quotes" and could be long—very long indeed. There could be "multiple quoted regions".',
  62. ],
  63. 'test_field_string' => [
  64. 'type' => 'varchar',
  65. 'length' => 20,
  66. 'not null' => TRUE,
  67. 'default' => "'\"funky default'\"",
  68. 'description' => 'Schema column description for string.',
  69. ],
  70. 'test_field_string_ascii' => [
  71. 'type' => 'varchar_ascii',
  72. 'length' => 255,
  73. 'description' => 'Schema column description for ASCII string.',
  74. ],
  75. ],
  76. ];
  77. $this->schema->createTable('test_table', $table_specification);
  78. // Assert that the table exists.
  79. $this->assertTrue($this->schema->tableExists('test_table'), 'The table exists.');
  80. // Assert that the table comment has been set.
  81. $this->checkSchemaComment($table_specification['description'], 'test_table');
  82. // Assert that the column comment has been set.
  83. $this->checkSchemaComment($table_specification['fields']['test_field']['description'], 'test_table', 'test_field');
  84. if ($this->connection->databaseType() === 'mysql') {
  85. // Make sure that varchar fields have the correct collation.
  86. $columns = $this->connection->query('SHOW FULL COLUMNS FROM {test_table}');
  87. foreach ($columns as $column) {
  88. if ($column->Field == 'test_field_string') {
  89. $string_check = ($column->Collation == 'utf8mb4_general_ci' || $column->Collation == 'utf8mb4_0900_ai_ci');
  90. }
  91. if ($column->Field == 'test_field_string_ascii') {
  92. $string_ascii_check = ($column->Collation == 'ascii_general_ci');
  93. }
  94. }
  95. $this->assertTrue(!empty($string_check), 'string field has the right collation.');
  96. $this->assertTrue(!empty($string_ascii_check), 'ASCII string field has the right collation.');
  97. }
  98. // An insert without a value for the column 'test_table' should fail.
  99. $this->assertFalse($this->tryInsert(), 'Insert without a default failed.');
  100. // Add a default value to the column.
  101. $this->schema->changeField('test_table', 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE, 'default' => 0]);
  102. // The insert should now succeed.
  103. $this->assertTrue($this->tryInsert(), 'Insert with a default succeeded.');
  104. // Remove the default.
  105. $this->schema->changeField('test_table', 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE]);
  106. // The insert should fail again.
  107. $this->assertFalse($this->tryInsert(), 'Insert without a default failed.');
  108. // Test for fake index and test for the boolean result of indexExists().
  109. $index_exists = $this->schema->indexExists('test_table', 'test_field');
  110. $this->assertIdentical($index_exists, FALSE, 'Fake index does not exist');
  111. // Add index.
  112. $this->schema->addIndex('test_table', 'test_field', ['test_field'], $table_specification);
  113. // Test for created index and test for the boolean result of indexExists().
  114. $index_exists = $this->schema->indexExists('test_table', 'test_field');
  115. $this->assertIdentical($index_exists, TRUE, 'Index created.');
  116. // Rename the table.
  117. $this->assertNull($this->schema->renameTable('test_table', 'test_table2'));
  118. // Index should be renamed.
  119. $index_exists = $this->schema->indexExists('test_table2', 'test_field');
  120. $this->assertTrue($index_exists, 'Index was renamed.');
  121. // We need the default so that we can insert after the rename.
  122. $this->schema->changeField('test_table2', 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE, 'default' => 0]);
  123. $this->assertFalse($this->tryInsert(), 'Insert into the old table failed.');
  124. $this->assertTrue($this->tryInsert('test_table2'), 'Insert into the new table succeeded.');
  125. // We should have successfully inserted exactly two rows.
  126. $count = $this->connection->query('SELECT COUNT(*) FROM {test_table2}')->fetchField();
  127. $this->assertEqual($count, 2, 'Two fields were successfully inserted.');
  128. // Try to drop the table.
  129. $this->schema->dropTable('test_table2');
  130. $this->assertFalse($this->schema->tableExists('test_table2'), 'The dropped table does not exist.');
  131. // Recreate the table.
  132. $this->schema->createTable('test_table', $table_specification);
  133. $this->schema->changeField('test_table', 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE, 'default' => 0]);
  134. $this->schema->addField('test_table', 'test_serial', ['type' => 'int', 'not null' => TRUE, 'default' => 0, 'description' => 'Added column description.']);
  135. // Assert that the column comment has been set.
  136. $this->checkSchemaComment('Added column description.', 'test_table', 'test_serial');
  137. // Change the new field to a serial column.
  138. $this->schema->changeField('test_table', 'test_serial', 'test_serial', ['type' => 'serial', 'not null' => TRUE, 'description' => 'Changed column description.'], ['primary key' => ['test_serial']]);
  139. // Assert that the column comment has been set.
  140. $this->checkSchemaComment('Changed column description.', 'test_table', 'test_serial');
  141. $this->assertTrue($this->tryInsert(), 'Insert with a serial succeeded.');
  142. $max1 = $this->connection->query('SELECT MAX(test_serial) FROM {test_table}')->fetchField();
  143. $this->assertTrue($this->tryInsert(), 'Insert with a serial succeeded.');
  144. $max2 = $this->connection->query('SELECT MAX(test_serial) FROM {test_table}')->fetchField();
  145. $this->assertTrue($max2 > $max1, 'The serial is monotone.');
  146. $count = $this->connection->query('SELECT COUNT(*) FROM {test_table}')->fetchField();
  147. $this->assertEqual($count, 2, 'There were two rows.');
  148. // Test adding a serial field to an existing table.
  149. $this->schema->dropTable('test_table');
  150. $this->schema->createTable('test_table', $table_specification);
  151. $this->schema->changeField('test_table', 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE, 'default' => 0]);
  152. $this->schema->addField('test_table', 'test_serial', ['type' => 'serial', 'not null' => TRUE], ['primary key' => ['test_serial']]);
  153. // Test the primary key columns.
  154. $method = new \ReflectionMethod(get_class($this->schema), 'findPrimaryKeyColumns');
  155. $method->setAccessible(TRUE);
  156. $this->assertSame(['test_serial'], $method->invoke($this->schema, 'test_table'));
  157. $this->assertTrue($this->tryInsert(), 'Insert with a serial succeeded.');
  158. $max1 = $this->connection->query('SELECT MAX(test_serial) FROM {test_table}')->fetchField();
  159. $this->assertTrue($this->tryInsert(), 'Insert with a serial succeeded.');
  160. $max2 = $this->connection->query('SELECT MAX(test_serial) FROM {test_table}')->fetchField();
  161. $this->assertTrue($max2 > $max1, 'The serial is monotone.');
  162. $count = $this->connection->query('SELECT COUNT(*) FROM {test_table}')->fetchField();
  163. $this->assertEqual($count, 2, 'There were two rows.');
  164. // Test adding a new column and form a composite primary key with it.
  165. $this->schema->addField('test_table', 'test_composite_primary_key', ['type' => 'int', 'not null' => TRUE, 'default' => 0], ['primary key' => ['test_serial', 'test_composite_primary_key']]);
  166. // Test the primary key columns.
  167. $this->assertSame(['test_serial', 'test_composite_primary_key'], $method->invoke($this->schema, 'test_table'));
  168. // Test renaming of keys and constraints.
  169. $this->schema->dropTable('test_table');
  170. $table_specification = [
  171. 'fields' => [
  172. 'id' => [
  173. 'type' => 'serial',
  174. 'not null' => TRUE,
  175. ],
  176. 'test_field' => [
  177. 'type' => 'int',
  178. 'default' => 0,
  179. ],
  180. ],
  181. 'primary key' => ['id'],
  182. 'unique keys' => [
  183. 'test_field' => ['test_field'],
  184. ],
  185. ];
  186. // PostgreSQL has a max identifier length of 63 characters, MySQL has 64 and
  187. // SQLite does not have any limit. Use the lowest common value and create a
  188. // table name as long as possible in order to cover edge cases around
  189. // identifier names for the table's primary or unique key constraints.
  190. $table_name = strtolower($this->getRandomGenerator()->name(63 - strlen($this->getDatabasePrefix())));
  191. $this->schema->createTable($table_name, $table_specification);
  192. $this->assertIndexOnColumns($table_name, ['id'], 'primary');
  193. $this->assertIndexOnColumns($table_name, ['test_field'], 'unique');
  194. $new_table_name = strtolower($this->getRandomGenerator()->name(63 - strlen($this->getDatabasePrefix())));
  195. $this->assertNull($this->schema->renameTable($table_name, $new_table_name));
  196. // Test for renamed primary and unique keys.
  197. $this->assertIndexOnColumns($new_table_name, ['id'], 'primary');
  198. $this->assertIndexOnColumns($new_table_name, ['test_field'], 'unique');
  199. // For PostgreSQL, we also need to check that the sequence has been renamed.
  200. // The initial name of the sequence has been generated automatically by
  201. // PostgreSQL when the table was created, however, on subsequent table
  202. // renames the name is generated by Drupal and can not be easily
  203. // re-constructed. Hence we can only check that we still have a sequence on
  204. // the new table name.
  205. if ($this->connection->databaseType() == 'pgsql') {
  206. $sequence_exists = (bool) $this->connection->query("SELECT pg_get_serial_sequence('{" . $new_table_name . "}', 'id')")->fetchField();
  207. $this->assertTrue($sequence_exists, 'Sequence was renamed.');
  208. // Rename the table again and repeat the check.
  209. $another_table_name = strtolower($this->getRandomGenerator()->name(63 - strlen($this->getDatabasePrefix())));
  210. $this->schema->renameTable($new_table_name, $another_table_name);
  211. $sequence_exists = (bool) $this->connection->query("SELECT pg_get_serial_sequence('{" . $another_table_name . "}', 'id')")->fetchField();
  212. $this->assertTrue($sequence_exists, 'Sequence was renamed.');
  213. }
  214. // Use database specific data type and ensure that table is created.
  215. $table_specification = [
  216. 'description' => 'Schema table description.',
  217. 'fields' => [
  218. 'timestamp' => [
  219. 'mysql_type' => 'timestamp',
  220. 'pgsql_type' => 'timestamp',
  221. 'sqlite_type' => 'datetime',
  222. 'not null' => FALSE,
  223. 'default' => NULL,
  224. ],
  225. ],
  226. ];
  227. try {
  228. $this->schema->createTable('test_timestamp', $table_specification);
  229. }
  230. catch (\Exception $e) {
  231. }
  232. $this->assertTrue($this->schema->tableExists('test_timestamp'), 'Table with database specific datatype was created.');
  233. }
  234. /**
  235. * @covers \Drupal\Core\Database\Driver\mysql\Schema::introspectIndexSchema
  236. * @covers \Drupal\Core\Database\Driver\pgsql\Schema::introspectIndexSchema
  237. * @covers \Drupal\Core\Database\Driver\sqlite\Schema::introspectIndexSchema
  238. */
  239. public function testIntrospectIndexSchema() {
  240. $table_specification = [
  241. 'fields' => [
  242. 'id' => [
  243. 'type' => 'int',
  244. 'not null' => TRUE,
  245. 'default' => 0,
  246. ],
  247. 'test_field_1' => [
  248. 'type' => 'int',
  249. 'not null' => TRUE,
  250. 'default' => 0,
  251. ],
  252. 'test_field_2' => [
  253. 'type' => 'int',
  254. 'default' => 0,
  255. ],
  256. 'test_field_3' => [
  257. 'type' => 'int',
  258. 'default' => 0,
  259. ],
  260. 'test_field_4' => [
  261. 'type' => 'int',
  262. 'default' => 0,
  263. ],
  264. 'test_field_5' => [
  265. 'type' => 'int',
  266. 'default' => 0,
  267. ],
  268. ],
  269. 'primary key' => ['id', 'test_field_1'],
  270. 'unique keys' => [
  271. 'test_field_2' => ['test_field_2'],
  272. 'test_field_3_test_field_4' => ['test_field_3', 'test_field_4'],
  273. ],
  274. 'indexes' => [
  275. 'test_field_4' => ['test_field_4'],
  276. 'test_field_4_test_field_5' => ['test_field_4', 'test_field_5'],
  277. ],
  278. ];
  279. $table_name = strtolower($this->getRandomGenerator()->name());
  280. $this->schema->createTable($table_name, $table_specification);
  281. unset($table_specification['fields']);
  282. $introspect_index_schema = new \ReflectionMethod(get_class($this->schema), 'introspectIndexSchema');
  283. $introspect_index_schema->setAccessible(TRUE);
  284. $index_schema = $introspect_index_schema->invoke($this->schema, $table_name);
  285. // The PostgreSQL driver is using a custom naming scheme for its indexes, so
  286. // we need to adjust the initial table specification.
  287. if ($this->connection->databaseType() === 'pgsql') {
  288. $ensure_identifier_length = new \ReflectionMethod(get_class($this->schema), 'ensureIdentifiersLength');
  289. $ensure_identifier_length->setAccessible(TRUE);
  290. foreach ($table_specification['unique keys'] as $original_index_name => $columns) {
  291. unset($table_specification['unique keys'][$original_index_name]);
  292. $new_index_name = $ensure_identifier_length->invoke($this->schema, $table_name, $original_index_name, 'key');
  293. $table_specification['unique keys'][$new_index_name] = $columns;
  294. }
  295. foreach ($table_specification['indexes'] as $original_index_name => $columns) {
  296. unset($table_specification['indexes'][$original_index_name]);
  297. $new_index_name = $ensure_identifier_length->invoke($this->schema, $table_name, $original_index_name, 'idx');
  298. $table_specification['indexes'][$new_index_name] = $columns;
  299. }
  300. }
  301. $this->assertEquals($table_specification, $index_schema);
  302. }
  303. /**
  304. * Tests that indexes on string fields are limited to 191 characters on MySQL.
  305. *
  306. * @see \Drupal\Core\Database\Driver\mysql\Schema::getNormalizedIndexes()
  307. */
  308. public function testIndexLength() {
  309. if ($this->connection->databaseType() !== 'mysql') {
  310. $this->markTestSkipped("The '{$this->connection->databaseType()}' database type does not support setting column length for indexes.");
  311. }
  312. $table_specification = [
  313. 'fields' => [
  314. 'id' => [
  315. 'type' => 'int',
  316. 'default' => NULL,
  317. ],
  318. 'test_field_text' => [
  319. 'type' => 'text',
  320. 'not null' => TRUE,
  321. ],
  322. 'test_field_string_long' => [
  323. 'type' => 'varchar',
  324. 'length' => 255,
  325. 'not null' => TRUE,
  326. ],
  327. 'test_field_string_ascii_long' => [
  328. 'type' => 'varchar_ascii',
  329. 'length' => 255,
  330. ],
  331. 'test_field_string_short' => [
  332. 'type' => 'varchar',
  333. 'length' => 128,
  334. 'not null' => TRUE,
  335. ],
  336. ],
  337. 'indexes' => [
  338. 'test_regular' => [
  339. 'test_field_text',
  340. 'test_field_string_long',
  341. 'test_field_string_ascii_long',
  342. 'test_field_string_short',
  343. ],
  344. 'test_length' => [
  345. ['test_field_text', 128],
  346. ['test_field_string_long', 128],
  347. ['test_field_string_ascii_long', 128],
  348. ['test_field_string_short', 128],
  349. ],
  350. 'test_mixed' => [
  351. ['test_field_text', 200],
  352. 'test_field_string_long',
  353. ['test_field_string_ascii_long', 200],
  354. 'test_field_string_short',
  355. ],
  356. ],
  357. ];
  358. $this->schema->createTable('test_table_index_length', $table_specification);
  359. // Ensure expected exception thrown when adding index with missing info.
  360. $expected_exception_message = "MySQL needs the 'test_field_text' field specification in order to normalize the 'test_regular' index";
  361. $missing_field_spec = $table_specification;
  362. unset($missing_field_spec['fields']['test_field_text']);
  363. try {
  364. $this->schema->addIndex('test_table_index_length', 'test_separate', [['test_field_text', 200]], $missing_field_spec);
  365. $this->fail('SchemaException not thrown when adding index with missing information.');
  366. }
  367. catch (SchemaException $e) {
  368. $this->assertEqual($expected_exception_message, $e->getMessage());
  369. }
  370. // Add a separate index.
  371. $this->schema->addIndex('test_table_index_length', 'test_separate', [['test_field_text', 200]], $table_specification);
  372. $table_specification_with_new_index = $table_specification;
  373. $table_specification_with_new_index['indexes']['test_separate'] = [['test_field_text', 200]];
  374. // Ensure that the exceptions of addIndex are thrown as expected.
  375. try {
  376. $this->schema->addIndex('test_table_index_length', 'test_separate', [['test_field_text', 200]], $table_specification);
  377. $this->fail('\Drupal\Core\Database\SchemaObjectExistsException exception missed.');
  378. }
  379. catch (SchemaObjectExistsException $e) {
  380. $this->pass('\Drupal\Core\Database\SchemaObjectExistsException thrown when index already exists.');
  381. }
  382. try {
  383. $this->schema->addIndex('test_table_non_existing', 'test_separate', [['test_field_text', 200]], $table_specification);
  384. $this->fail('\Drupal\Core\Database\SchemaObjectDoesNotExistException exception missed.');
  385. }
  386. catch (SchemaObjectDoesNotExistException $e) {
  387. $this->pass('\Drupal\Core\Database\SchemaObjectDoesNotExistException thrown when index already exists.');
  388. }
  389. // Get index information.
  390. $results = $this->connection->query('SHOW INDEX FROM {test_table_index_length}');
  391. $expected_lengths = [
  392. 'test_regular' => [
  393. 'test_field_text' => 191,
  394. 'test_field_string_long' => 191,
  395. 'test_field_string_ascii_long' => NULL,
  396. 'test_field_string_short' => NULL,
  397. ],
  398. 'test_length' => [
  399. 'test_field_text' => 128,
  400. 'test_field_string_long' => 128,
  401. 'test_field_string_ascii_long' => 128,
  402. 'test_field_string_short' => NULL,
  403. ],
  404. 'test_mixed' => [
  405. 'test_field_text' => 191,
  406. 'test_field_string_long' => 191,
  407. 'test_field_string_ascii_long' => 200,
  408. 'test_field_string_short' => NULL,
  409. ],
  410. 'test_separate' => [
  411. 'test_field_text' => 191,
  412. ],
  413. ];
  414. // Count the number of columns defined in the indexes.
  415. $column_count = 0;
  416. foreach ($table_specification_with_new_index['indexes'] as $index) {
  417. foreach ($index as $field) {
  418. $column_count++;
  419. }
  420. }
  421. $test_count = 0;
  422. foreach ($results as $result) {
  423. $this->assertEqual($result->Sub_part, $expected_lengths[$result->Key_name][$result->Column_name], 'Index length matches expected value.');
  424. $test_count++;
  425. }
  426. $this->assertEqual($test_count, $column_count, 'Number of tests matches expected value.');
  427. }
  428. /**
  429. * Tests inserting data into an existing table.
  430. *
  431. * @param string $table
  432. * The database table to insert data into.
  433. *
  434. * @return bool
  435. * TRUE if the insert succeeded, FALSE otherwise.
  436. */
  437. public function tryInsert($table = 'test_table') {
  438. try {
  439. $this->connection
  440. ->insert($table)
  441. ->fields(['id' => mt_rand(10, 20)])
  442. ->execute();
  443. return TRUE;
  444. }
  445. catch (\Exception $e) {
  446. return FALSE;
  447. }
  448. }
  449. /**
  450. * Checks that a table or column comment matches a given description.
  451. *
  452. * @param $description
  453. * The asserted description.
  454. * @param $table
  455. * The table to test.
  456. * @param $column
  457. * Optional column to test.
  458. */
  459. public function checkSchemaComment($description, $table, $column = NULL) {
  460. if (method_exists($this->schema, 'getComment')) {
  461. $comment = $this->schema->getComment($table, $column);
  462. // The schema comment truncation for mysql is different.
  463. if ($this->connection->databaseType() === 'mysql') {
  464. $max_length = $column ? 255 : 60;
  465. $description = Unicode::truncate($description, $max_length, TRUE, TRUE);
  466. }
  467. $this->assertEqual($comment, $description, 'The comment matches the schema description.');
  468. }
  469. }
  470. /**
  471. * Tests creating unsigned columns and data integrity thereof.
  472. */
  473. public function testUnsignedColumns() {
  474. // First create the table with just a serial column.
  475. $table_name = 'unsigned_table';
  476. $table_spec = [
  477. 'fields' => ['serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE]],
  478. 'primary key' => ['serial_column'],
  479. ];
  480. $this->schema->createTable($table_name, $table_spec);
  481. // Now set up columns for the other types.
  482. $types = ['int', 'float', 'numeric'];
  483. foreach ($types as $type) {
  484. $column_spec = ['type' => $type, 'unsigned' => TRUE];
  485. if ($type == 'numeric') {
  486. $column_spec += ['precision' => 10, 'scale' => 0];
  487. }
  488. $column_name = $type . '_column';
  489. $table_spec['fields'][$column_name] = $column_spec;
  490. $this->schema->addField($table_name, $column_name, $column_spec);
  491. }
  492. // Finally, check each column and try to insert invalid values into them.
  493. foreach ($table_spec['fields'] as $column_name => $column_spec) {
  494. $this->assertTrue($this->schema->fieldExists($table_name, $column_name), new FormattableMarkup('Unsigned @type column was created.', ['@type' => $column_spec['type']]));
  495. $this->assertFalse($this->tryUnsignedInsert($table_name, $column_name), new FormattableMarkup('Unsigned @type column rejected a negative value.', ['@type' => $column_spec['type']]));
  496. }
  497. }
  498. /**
  499. * Tries to insert a negative value into columns defined as unsigned.
  500. *
  501. * @param string $table_name
  502. * The table to insert.
  503. * @param string $column_name
  504. * The column to insert.
  505. *
  506. * @return bool
  507. * TRUE if the insert succeeded, FALSE otherwise.
  508. */
  509. public function tryUnsignedInsert($table_name, $column_name) {
  510. try {
  511. $this->connection
  512. ->insert($table_name)
  513. ->fields([$column_name => -1])
  514. ->execute();
  515. return TRUE;
  516. }
  517. catch (\Exception $e) {
  518. return FALSE;
  519. }
  520. }
  521. /**
  522. * Tests adding columns to an existing table with default and initial value.
  523. */
  524. public function testSchemaAddFieldDefaultInitial() {
  525. // Test varchar types.
  526. foreach ([1, 32, 128, 256, 512] as $length) {
  527. $base_field_spec = [
  528. 'type' => 'varchar',
  529. 'length' => $length,
  530. ];
  531. $variations = [
  532. ['not null' => FALSE],
  533. ['not null' => FALSE, 'default' => '7'],
  534. ['not null' => FALSE, 'default' => substr('"thing"', 0, $length)],
  535. ['not null' => FALSE, 'default' => substr("\"'hing", 0, $length)],
  536. ['not null' => TRUE, 'initial' => 'd'],
  537. ['not null' => FALSE, 'default' => NULL],
  538. ['not null' => TRUE, 'initial' => 'd', 'default' => '7'],
  539. ];
  540. foreach ($variations as $variation) {
  541. $field_spec = $variation + $base_field_spec;
  542. $this->assertFieldAdditionRemoval($field_spec);
  543. }
  544. }
  545. // Test int and float types.
  546. foreach (['int', 'float'] as $type) {
  547. foreach (['tiny', 'small', 'medium', 'normal', 'big'] as $size) {
  548. $base_field_spec = [
  549. 'type' => $type,
  550. 'size' => $size,
  551. ];
  552. $variations = [
  553. ['not null' => FALSE],
  554. ['not null' => FALSE, 'default' => 7],
  555. ['not null' => TRUE, 'initial' => 1],
  556. ['not null' => TRUE, 'initial' => 1, 'default' => 7],
  557. ['not null' => TRUE, 'initial_from_field' => 'serial_column'],
  558. [
  559. 'not null' => TRUE,
  560. 'initial_from_field' => 'test_nullable_field',
  561. 'initial' => 100,
  562. ],
  563. ];
  564. foreach ($variations as $variation) {
  565. $field_spec = $variation + $base_field_spec;
  566. $this->assertFieldAdditionRemoval($field_spec);
  567. }
  568. }
  569. }
  570. // Test numeric types.
  571. foreach ([1, 5, 10, 40, 65] as $precision) {
  572. foreach ([0, 2, 10, 30] as $scale) {
  573. // Skip combinations where precision is smaller than scale.
  574. if ($precision <= $scale) {
  575. continue;
  576. }
  577. $base_field_spec = [
  578. 'type' => 'numeric',
  579. 'scale' => $scale,
  580. 'precision' => $precision,
  581. ];
  582. $variations = [
  583. ['not null' => FALSE],
  584. ['not null' => FALSE, 'default' => 7],
  585. ['not null' => TRUE, 'initial' => 1],
  586. ['not null' => TRUE, 'initial' => 1, 'default' => 7],
  587. ['not null' => TRUE, 'initial_from_field' => 'serial_column'],
  588. ];
  589. foreach ($variations as $variation) {
  590. $field_spec = $variation + $base_field_spec;
  591. $this->assertFieldAdditionRemoval($field_spec);
  592. }
  593. }
  594. }
  595. }
  596. /**
  597. * Asserts that a given field can be added and removed from a table.
  598. *
  599. * The addition test covers both defining a field of a given specification
  600. * when initially creating at table and extending an existing table.
  601. *
  602. * @param $field_spec
  603. * The schema specification of the field.
  604. */
  605. protected function assertFieldAdditionRemoval($field_spec) {
  606. // Try creating the field on a new table.
  607. $table_name = 'test_table_' . ($this->counter++);
  608. $table_spec = [
  609. 'fields' => [
  610. 'serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
  611. 'test_nullable_field' => ['type' => 'int', 'not null' => FALSE],
  612. 'test_field' => $field_spec,
  613. ],
  614. 'primary key' => ['serial_column'],
  615. ];
  616. $this->schema->createTable($table_name, $table_spec);
  617. $this->pass(new FormattableMarkup('Table %table created.', ['%table' => $table_name]));
  618. // Check the characteristics of the field.
  619. $this->assertFieldCharacteristics($table_name, 'test_field', $field_spec);
  620. // Clean-up.
  621. $this->schema->dropTable($table_name);
  622. // Try adding a field to an existing table.
  623. $table_name = 'test_table_' . ($this->counter++);
  624. $table_spec = [
  625. 'fields' => [
  626. 'serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
  627. 'test_nullable_field' => ['type' => 'int', 'not null' => FALSE],
  628. ],
  629. 'primary key' => ['serial_column'],
  630. ];
  631. $this->schema->createTable($table_name, $table_spec);
  632. $this->pass(new FormattableMarkup('Table %table created.', ['%table' => $table_name]));
  633. // Insert some rows to the table to test the handling of initial values.
  634. for ($i = 0; $i < 3; $i++) {
  635. $this->connection
  636. ->insert($table_name)
  637. ->useDefaults(['serial_column'])
  638. ->fields(['test_nullable_field' => 100])
  639. ->execute();
  640. }
  641. // Add another row with no value for the 'test_nullable_field' column.
  642. $this->connection
  643. ->insert($table_name)
  644. ->useDefaults(['serial_column'])
  645. ->execute();
  646. $this->schema->addField($table_name, 'test_field', $field_spec);
  647. $this->pass(new FormattableMarkup('Column %column created.', ['%column' => 'test_field']));
  648. // Check the characteristics of the field.
  649. $this->assertFieldCharacteristics($table_name, 'test_field', $field_spec);
  650. // Clean-up.
  651. $this->schema->dropField($table_name, 'test_field');
  652. // Add back the field and then try to delete a field which is also a primary
  653. // key.
  654. $this->schema->addField($table_name, 'test_field', $field_spec);
  655. $this->schema->dropField($table_name, 'serial_column');
  656. $this->schema->dropTable($table_name);
  657. }
  658. /**
  659. * Asserts that a newly added field has the correct characteristics.
  660. */
  661. protected function assertFieldCharacteristics($table_name, $field_name, $field_spec) {
  662. // Check that the initial value has been registered.
  663. if (isset($field_spec['initial'])) {
  664. // There should be no row with a value different then $field_spec['initial'].
  665. $count = $this->connection
  666. ->select($table_name)
  667. ->fields($table_name, ['serial_column'])
  668. ->condition($field_name, $field_spec['initial'], '<>')
  669. ->countQuery()
  670. ->execute()
  671. ->fetchField();
  672. $this->assertEqual($count, 0, 'Initial values filled out.');
  673. }
  674. // Check that the initial value from another field has been registered.
  675. if (isset($field_spec['initial_from_field']) && !isset($field_spec['initial'])) {
  676. // There should be no row with a value different than
  677. // $field_spec['initial_from_field'].
  678. $count = $this->connection
  679. ->select($table_name)
  680. ->fields($table_name, ['serial_column'])
  681. ->where($table_name . '.' . $field_spec['initial_from_field'] . ' <> ' . $table_name . '.' . $field_name)
  682. ->countQuery()
  683. ->execute()
  684. ->fetchField();
  685. $this->assertEqual($count, 0, 'Initial values from another field filled out.');
  686. }
  687. elseif (isset($field_spec['initial_from_field']) && isset($field_spec['initial'])) {
  688. // There should be no row with a value different than '100'.
  689. $count = $this->connection
  690. ->select($table_name)
  691. ->fields($table_name, ['serial_column'])
  692. ->condition($field_name, 100, '<>')
  693. ->countQuery()
  694. ->execute()
  695. ->fetchField();
  696. $this->assertEqual($count, 0, 'Initial values from another field or a default value filled out.');
  697. }
  698. // Check that the default value has been registered.
  699. if (isset($field_spec['default'])) {
  700. // Try inserting a row, and check the resulting value of the new column.
  701. $id = $this->connection
  702. ->insert($table_name)
  703. ->useDefaults(['serial_column'])
  704. ->execute();
  705. $field_value = $this->connection
  706. ->select($table_name)
  707. ->fields($table_name, [$field_name])
  708. ->condition('serial_column', $id)
  709. ->execute()
  710. ->fetchField();
  711. $this->assertEqual($field_value, $field_spec['default'], 'Default value registered.');
  712. }
  713. }
  714. /**
  715. * Tests various schema changes' effect on the table's primary key.
  716. *
  717. * @param array $initial_primary_key
  718. * The initial primary key of the test table.
  719. * @param array $renamed_primary_key
  720. * The primary key of the test table after renaming the test field.
  721. *
  722. * @dataProvider providerTestSchemaCreateTablePrimaryKey
  723. *
  724. * @covers ::addField
  725. * @covers ::changeField
  726. * @covers ::dropField
  727. * @covers ::findPrimaryKeyColumns
  728. */
  729. public function testSchemaChangePrimaryKey(array $initial_primary_key, array $renamed_primary_key) {
  730. $find_primary_key_columns = new \ReflectionMethod(get_class($this->schema), 'findPrimaryKeyColumns');
  731. $find_primary_key_columns->setAccessible(TRUE);
  732. // Test making the field the primary key of the table upon creation.
  733. $table_name = 'test_table';
  734. $table_spec = [
  735. 'fields' => [
  736. 'test_field' => ['type' => 'int', 'not null' => TRUE],
  737. 'other_test_field' => ['type' => 'int', 'not null' => TRUE],
  738. ],
  739. 'primary key' => $initial_primary_key,
  740. ];
  741. $this->schema->createTable($table_name, $table_spec);
  742. $this->assertTrue($this->schema->fieldExists($table_name, 'test_field'));
  743. $this->assertEquals($initial_primary_key, $find_primary_key_columns->invoke($this->schema, $table_name));
  744. // Change the field type and make sure the primary key stays in place.
  745. $this->schema->changeField($table_name, 'test_field', 'test_field', ['type' => 'varchar', 'length' => 32, 'not null' => TRUE]);
  746. $this->assertTrue($this->schema->fieldExists($table_name, 'test_field'));
  747. $this->assertEquals($initial_primary_key, $find_primary_key_columns->invoke($this->schema, $table_name));
  748. // Add some data and change the field type back, to make sure that changing
  749. // the type leaves the primary key in place even with existing data.
  750. $this->connection
  751. ->insert($table_name)
  752. ->fields(['test_field' => 1, 'other_test_field' => 2])
  753. ->execute();
  754. $this->schema->changeField($table_name, 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE]);
  755. $this->assertTrue($this->schema->fieldExists($table_name, 'test_field'));
  756. $this->assertEquals($initial_primary_key, $find_primary_key_columns->invoke($this->schema, $table_name));
  757. // Make sure that adding the primary key can be done as part of changing
  758. // a field, as well.
  759. $this->schema->dropPrimaryKey($table_name);
  760. $this->assertEquals([], $find_primary_key_columns->invoke($this->schema, $table_name));
  761. $this->schema->changeField($table_name, 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE], ['primary key' => $initial_primary_key]);
  762. $this->assertTrue($this->schema->fieldExists($table_name, 'test_field'));
  763. $this->assertEquals($initial_primary_key, $find_primary_key_columns->invoke($this->schema, $table_name));
  764. // Rename the field and make sure the primary key was updated.
  765. $this->schema->changeField($table_name, 'test_field', 'test_field_renamed', ['type' => 'int', 'not null' => TRUE]);
  766. $this->assertTrue($this->schema->fieldExists($table_name, 'test_field_renamed'));
  767. $this->assertEquals($renamed_primary_key, $find_primary_key_columns->invoke($this->schema, $table_name));
  768. // Drop the field and make sure the primary key was dropped, as well.
  769. $this->schema->dropField($table_name, 'test_field_renamed');
  770. $this->assertFalse($this->schema->fieldExists($table_name, 'test_field_renamed'));
  771. $this->assertEquals([], $find_primary_key_columns->invoke($this->schema, $table_name));
  772. // Add the field again and make sure adding the primary key can be done at
  773. // the same time.
  774. $this->schema->addField($table_name, 'test_field', ['type' => 'int', 'default' => 0, 'not null' => TRUE], ['primary key' => $initial_primary_key]);
  775. $this->assertTrue($this->schema->fieldExists($table_name, 'test_field'));
  776. $this->assertEquals($initial_primary_key, $find_primary_key_columns->invoke($this->schema, $table_name));
  777. // Drop the field again and explicitly add a primary key.
  778. $this->schema->dropField($table_name, 'test_field');
  779. $this->schema->addPrimaryKey($table_name, ['other_test_field']);
  780. $this->assertFalse($this->schema->fieldExists($table_name, 'test_field'));
  781. $this->assertEquals(['other_test_field'], $find_primary_key_columns->invoke($this->schema, $table_name));
  782. // Test that adding a field with a primary key will work even with a
  783. // pre-existing primary key.
  784. $this->schema->addField($table_name, 'test_field', ['type' => 'int', 'default' => 0, 'not null' => TRUE], ['primary key' => $initial_primary_key]);
  785. $this->assertTrue($this->schema->fieldExists($table_name, 'test_field'));
  786. $this->assertEquals($initial_primary_key, $find_primary_key_columns->invoke($this->schema, $table_name));
  787. }
  788. /**
  789. * Provides test cases for SchemaTest::testSchemaCreateTablePrimaryKey().
  790. *
  791. * @return array
  792. * An array of test cases for SchemaTest::testSchemaCreateTablePrimaryKey().
  793. */
  794. public function providerTestSchemaCreateTablePrimaryKey() {
  795. $tests = [];
  796. $tests['simple_primary_key'] = [
  797. 'initial_primary_key' => ['test_field'],
  798. 'renamed_primary_key' => ['test_field_renamed'],
  799. ];
  800. $tests['composite_primary_key'] = [
  801. 'initial_primary_key' => ['test_field', 'other_test_field'],
  802. 'renamed_primary_key' => ['test_field_renamed', 'other_test_field'],
  803. ];
  804. $tests['composite_primary_key_different_order'] = [
  805. 'initial_primary_key' => ['other_test_field', 'test_field'],
  806. 'renamed_primary_key' => ['other_test_field', 'test_field_renamed'],
  807. ];
  808. return $tests;
  809. }
  810. /**
  811. * Tests an invalid field specification as a primary key on table creation.
  812. */
  813. public function testInvalidPrimaryKeyOnTableCreation() {
  814. // Test making an invalid field the primary key of the table upon creation.
  815. $table_name = 'test_table';
  816. $table_spec = [
  817. 'fields' => [
  818. 'test_field' => ['type' => 'int'],
  819. ],
  820. 'primary key' => ['test_field'],
  821. ];
  822. $this->expectException(SchemaException::class);
  823. $this->expectExceptionMessage("The 'test_field' field specification does not define 'not null' as TRUE.");
  824. $this->schema->createTable($table_name, $table_spec);
  825. }
  826. /**
  827. * Tests adding an invalid field specification as a primary key.
  828. */
  829. public function testInvalidPrimaryKeyAddition() {
  830. // Test adding a new invalid field to the primary key.
  831. $table_name = 'test_table';
  832. $table_spec = [
  833. 'fields' => [
  834. 'test_field' => ['type' => 'int', 'not null' => TRUE],
  835. ],
  836. 'primary key' => ['test_field'],
  837. ];
  838. $this->schema->createTable($table_name, $table_spec);
  839. $this->expectException(SchemaException::class);
  840. $this->expectExceptionMessage("The 'new_test_field' field specification does not define 'not null' as TRUE.");
  841. $this->schema->addField($table_name, 'new_test_field', ['type' => 'int'], ['primary key' => ['test_field', 'new_test_field']]);
  842. }
  843. /**
  844. * Tests changing the primary key with an invalid field specification.
  845. */
  846. public function testInvalidPrimaryKeyChange() {
  847. // Test adding a new invalid field to the primary key.
  848. $table_name = 'test_table';
  849. $table_spec = [
  850. 'fields' => [
  851. 'test_field' => ['type' => 'int', 'not null' => TRUE],
  852. ],
  853. 'primary key' => ['test_field'],
  854. ];
  855. $this->schema->createTable($table_name, $table_spec);
  856. $this->expectException(SchemaException::class);
  857. $this->expectExceptionMessage("The 'changed_test_field' field specification does not define 'not null' as TRUE.");
  858. $this->schema->dropPrimaryKey($table_name);
  859. $this->schema->changeField($table_name, 'test_field', 'changed_test_field', ['type' => 'int'], ['primary key' => ['changed_test_field']]);
  860. }
  861. /**
  862. * Tests changing columns between types with default and initial values.
  863. */
  864. public function testSchemaChangeFieldDefaultInitial() {
  865. $field_specs = [
  866. ['type' => 'int', 'size' => 'normal', 'not null' => FALSE],
  867. ['type' => 'int', 'size' => 'normal', 'not null' => TRUE, 'initial' => 1, 'default' => 17],
  868. ['type' => 'float', 'size' => 'normal', 'not null' => FALSE],
  869. ['type' => 'float', 'size' => 'normal', 'not null' => TRUE, 'initial' => 1, 'default' => 7.3],
  870. ['type' => 'numeric', 'scale' => 2, 'precision' => 10, 'not null' => FALSE],
  871. ['type' => 'numeric', 'scale' => 2, 'precision' => 10, 'not null' => TRUE, 'initial' => 1, 'default' => 7],
  872. ];
  873. foreach ($field_specs as $i => $old_spec) {
  874. foreach ($field_specs as $j => $new_spec) {
  875. if ($i === $j) {
  876. // Do not change a field into itself.
  877. continue;
  878. }
  879. $this->assertFieldChange($old_spec, $new_spec);
  880. }
  881. }
  882. $field_specs = [
  883. ['type' => 'varchar_ascii', 'length' => '255'],
  884. ['type' => 'varchar', 'length' => '255'],
  885. ['type' => 'text'],
  886. ['type' => 'blob', 'size' => 'big'],
  887. ];
  888. foreach ($field_specs as $i => $old_spec) {
  889. foreach ($field_specs as $j => $new_spec) {
  890. if ($i === $j) {
  891. // Do not change a field into itself.
  892. continue;
  893. }
  894. // Note if the serialized data contained an object this would fail on
  895. // Postgres.
  896. // @see https://www.drupal.org/node/1031122
  897. $this->assertFieldChange($old_spec, $new_spec, serialize(['string' => "This \n has \\\\ some backslash \"*string action.\\n"]));
  898. }
  899. }
  900. }
  901. /**
  902. * Asserts that a field can be changed from one spec to another.
  903. *
  904. * @param $old_spec
  905. * The beginning field specification.
  906. * @param $new_spec
  907. * The ending field specification.
  908. */
  909. protected function assertFieldChange($old_spec, $new_spec, $test_data = NULL) {
  910. $table_name = 'test_table_' . ($this->counter++);
  911. $table_spec = [
  912. 'fields' => [
  913. 'serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
  914. 'test_field' => $old_spec,
  915. ],
  916. 'primary key' => ['serial_column'],
  917. ];
  918. $this->schema->createTable($table_name, $table_spec);
  919. $this->pass(new FormattableMarkup('Table %table created.', ['%table' => $table_name]));
  920. // Check the characteristics of the field.
  921. $this->assertFieldCharacteristics($table_name, 'test_field', $old_spec);
  922. // Remove inserted rows.
  923. $this->connection->truncate($table_name)->execute();
  924. if ($test_data) {
  925. $id = $this->connection
  926. ->insert($table_name)
  927. ->fields(['test_field'], [$test_data])
  928. ->execute();
  929. }
  930. // Change the field.
  931. $this->schema->changeField($table_name, 'test_field', 'test_field', $new_spec);
  932. if ($test_data) {
  933. $field_value = $this->connection
  934. ->select($table_name)
  935. ->fields($table_name, ['test_field'])
  936. ->condition('serial_column', $id)
  937. ->execute()
  938. ->fetchField();
  939. $this->assertIdentical($field_value, $test_data);
  940. }
  941. // Check the field was changed.
  942. $this->assertFieldCharacteristics($table_name, 'test_field', $new_spec);
  943. // Clean-up.
  944. $this->schema->dropTable($table_name);
  945. }
  946. /**
  947. * @covers ::findPrimaryKeyColumns
  948. */
  949. public function testFindPrimaryKeyColumns() {
  950. $method = new \ReflectionMethod(get_class($this->schema), 'findPrimaryKeyColumns');
  951. $method->setAccessible(TRUE);
  952. // Test with single column primary key.
  953. $this->schema->createTable('table_with_pk_0', [
  954. 'description' => 'Table with primary key.',
  955. 'fields' => [
  956. 'id' => [
  957. 'type' => 'int',
  958. 'not null' => TRUE,
  959. ],
  960. 'test_field' => [
  961. 'type' => 'int',
  962. 'not null' => TRUE,
  963. ],
  964. ],
  965. 'primary key' => ['id'],
  966. ]);
  967. $this->assertSame(['id'], $method->invoke($this->schema, 'table_with_pk_0'));
  968. // Test with multiple column primary key.
  969. $this->schema->createTable('table_with_pk_1', [
  970. 'description' => 'Table with primary key with multiple columns.',
  971. 'fields' => [
  972. 'id0' => [
  973. 'type' => 'int',
  974. 'not null' => TRUE,
  975. ],
  976. 'id1' => [
  977. 'type' => 'int',
  978. 'not null' => TRUE,
  979. ],
  980. 'test_field' => [
  981. 'type' => 'int',
  982. 'not null' => TRUE,
  983. ],
  984. ],
  985. 'primary key' => ['id0', 'id1'],
  986. ]);
  987. $this->assertSame(['id0', 'id1'], $method->invoke($this->schema, 'table_with_pk_1'));
  988. // Test with multiple column primary key and not being the first column of
  989. // the table definition.
  990. $this->schema->createTable('table_with_pk_2', [
  991. 'description' => 'Table with primary key with multiple columns at the end and in reverted sequence.',
  992. 'fields' => [
  993. 'test_field_1' => [
  994. 'type' => 'int',
  995. 'not null' => TRUE,
  996. ],
  997. 'test_field_2' => [
  998. 'type' => 'int',
  999. 'not null' => TRUE,
  1000. ],
  1001. 'id3' => [
  1002. 'type' => 'int',
  1003. 'not null' => TRUE,
  1004. ],
  1005. 'id4' => [
  1006. 'type' => 'int',
  1007. 'not null' => TRUE,
  1008. ],
  1009. ],
  1010. 'primary key' => ['id4', 'id3'],
  1011. ]);
  1012. $this->assertSame(['id4', 'id3'], $method->invoke($this->schema, 'table_with_pk_2'));
  1013. // Test with multiple column primary key in a different order. For the
  1014. // PostgreSQL and the SQLite drivers is sorting used to get the primary key
  1015. // columns in the right order.
  1016. $this->schema->createTable('table_with_pk_3', [
  1017. 'description' => 'Table with primary key with multiple columns at the end and in reverted sequence.',
  1018. 'fields' => [
  1019. 'test_field_1' => [
  1020. 'type' => 'int',
  1021. 'not null' => TRUE,
  1022. ],
  1023. 'test_field_2' => [
  1024. 'type' => 'int',
  1025. 'not null' => TRUE,
  1026. ],
  1027. 'id3' => [
  1028. 'type' => 'int',
  1029. 'not null' => TRUE,
  1030. ],
  1031. 'id4' => [
  1032. 'type' => 'int',
  1033. 'not null' => TRUE,
  1034. ],
  1035. ],
  1036. 'primary key' => ['id3', 'test_field_2', 'id4'],
  1037. ]);
  1038. $this->assertSame(['id3', 'test_field_2', 'id4'], $method->invoke($this->schema, 'table_with_pk_3'));
  1039. // Test with table without a primary key.
  1040. $this->schema->createTable('table_without_pk_1', [
  1041. 'description' => 'Table without primary key.',
  1042. 'fields' => [
  1043. 'id' => [
  1044. 'type' => 'int',
  1045. 'not null' => TRUE,
  1046. ],
  1047. 'test_field' => [
  1048. 'type' => 'int',
  1049. 'not null' => TRUE,
  1050. ],
  1051. ],
  1052. ]);
  1053. $this->assertSame([], $method->invoke($this->schema, 'table_without_pk_1'));
  1054. // Test with table with an empty primary key.
  1055. $this->schema->createTable('table_without_pk_2', [
  1056. 'description' => 'Table without primary key.',
  1057. 'fields' => [
  1058. 'id' => [
  1059. 'type' => 'int',
  1060. 'not null' => TRUE,
  1061. ],
  1062. 'test_field' => [
  1063. 'type' => 'int',
  1064. 'not null' => TRUE,
  1065. ],
  1066. ],
  1067. 'primary key' => [],
  1068. ]);
  1069. $this->assertSame([], $method->invoke($this->schema, 'table_without_pk_2'));
  1070. // Test with non existing table.
  1071. $this->assertFalse($method->invoke($this->schema, 'non_existing_table'));
  1072. }
  1073. /**
  1074. * Tests the findTables() method.
  1075. */
  1076. public function testFindTables() {
  1077. // We will be testing with three tables, two of them using the default
  1078. // prefix and the third one with an individually specified prefix.
  1079. // Set up a new connection with different connection info.
  1080. $connection_info = Database::getConnectionInfo();
  1081. // Add per-table prefix to the second table.
  1082. $new_connection_info = $connection_info['default'];
  1083. $new_connection_info['prefix']['test_2_table'] = $new_connection_info['prefix']['default'] . '_shared_';
  1084. Database::addConnectionInfo('test', 'default', $new_connection_info);
  1085. Database::setActiveConnection('test');
  1086. $test_schema = Database::getConnection()->schema();
  1087. // Create the tables.
  1088. $table_specification = [
  1089. 'description' => 'Test table.',
  1090. 'fields' => [
  1091. 'id' => [
  1092. 'type' => 'int',
  1093. 'default' => NULL,
  1094. ],
  1095. ],
  1096. ];
  1097. $test_schema->createTable('test_1_table', $table_specification);
  1098. $test_schema->createTable('test_2_table', $table_specification);
  1099. $test_schema->createTable('the_third_table', $table_specification);
  1100. // Check the "all tables" syntax.
  1101. $tables = $test_schema->findTables('%');
  1102. sort($tables);
  1103. $expected = [
  1104. // The 'config' table is added by
  1105. // \Drupal\KernelTests\KernelTestBase::containerBuild().
  1106. 'config',
  1107. 'test_1_table',
  1108. // This table uses a per-table prefix, yet it is returned as un-prefixed.
  1109. 'test_2_table',
  1110. 'the_third_table',
  1111. ];
  1112. $this->assertEqual($tables, $expected, 'All tables were found.');
  1113. // Check the restrictive syntax.
  1114. $tables = $test_schema->findTables('test_%');
  1115. sort($tables);
  1116. $expected = [
  1117. 'test_1_table',
  1118. 'test_2_table',
  1119. ];
  1120. $this->assertEqual($tables, $expected, 'Two tables were found.');
  1121. // Go back to the initial connection.
  1122. Database::setActiveConnection('default');
  1123. }
  1124. }