SchemaTest.php 44 KB

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