field_sql_storage.test

Tests for field_sql_storage.module.

Field_sql_storage.module implements the default back-end storage plugin for the Field Strage API.

File

drupal-7.x/modules/field/modules/field_sql_storage/field_sql_storage.test
View source
  1. <?php
  2. /**
  3. * @file
  4. * Tests for field_sql_storage.module.
  5. *
  6. * Field_sql_storage.module implements the default back-end storage plugin
  7. * for the Field Strage API.
  8. */
  9. /**
  10. * Tests field storage.
  11. */
  12. class FieldSqlStorageTestCase extends DrupalWebTestCase {
  13. public static function getInfo() {
  14. return array(
  15. 'name' => 'Field SQL storage tests',
  16. 'description' => "Test field SQL storage module.",
  17. 'group' => 'Field API'
  18. );
  19. }
  20. function setUp() {
  21. parent::setUp('field_sql_storage', 'field', 'field_test', 'text');
  22. $this->field_name = strtolower($this->randomName());
  23. $this->field = array('field_name' => $this->field_name, 'type' => 'test_field', 'cardinality' => 4);
  24. $this->field = field_create_field($this->field);
  25. $this->instance = array(
  26. 'field_name' => $this->field_name,
  27. 'entity_type' => 'test_entity',
  28. 'bundle' => 'test_bundle'
  29. );
  30. $this->instance = field_create_instance($this->instance);
  31. $this->table = _field_sql_storage_tablename($this->field);
  32. $this->revision_table = _field_sql_storage_revision_tablename($this->field);
  33. }
  34. /**
  35. * Uses the mysql tables and records to verify
  36. * field_load_revision works correctly.
  37. */
  38. function testFieldAttachLoad() {
  39. $entity_type = 'test_entity';
  40. $eid = 0;
  41. $langcode = LANGUAGE_NONE;
  42. $columns = array('entity_type', 'entity_id', 'revision_id', 'delta', 'language', $this->field_name . '_value');
  43. // Insert data for four revisions to the field revisions table
  44. $query = db_insert($this->revision_table)->fields($columns);
  45. for ($evid = 0; $evid < 4; ++$evid) {
  46. $values[$evid] = array();
  47. // Note: we insert one extra value ('<=' instead of '<').
  48. for ($delta = 0; $delta <= $this->field['cardinality']; $delta++) {
  49. $value = mt_rand(1, 127);
  50. $values[$evid][] = $value;
  51. $query->values(array($entity_type, $eid, $evid, $delta, $langcode, $value));
  52. }
  53. }
  54. $query->execute();
  55. // Insert data for the "most current revision" into the field table
  56. $query = db_insert($this->table)->fields($columns);
  57. foreach ($values[0] as $delta => $value) {
  58. $query->values(array($entity_type, $eid, 0, $delta, $langcode, $value));
  59. }
  60. $query->execute();
  61. // Load the "most current revision"
  62. $entity = field_test_create_stub_entity($eid, 0, $this->instance['bundle']);
  63. field_attach_load($entity_type, array($eid => $entity));
  64. foreach ($values[0] as $delta => $value) {
  65. if ($delta < $this->field['cardinality']) {
  66. $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'], $value, "Value $delta is loaded correctly for current revision");
  67. }
  68. else {
  69. $this->assertFalse(array_key_exists($delta, $entity->{$this->field_name}[$langcode]), "No extraneous value gets loaded for current revision.");
  70. }
  71. }
  72. // Load every revision
  73. for ($evid = 0; $evid < 4; ++$evid) {
  74. $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
  75. field_attach_load_revision($entity_type, array($eid => $entity));
  76. foreach ($values[$evid] as $delta => $value) {
  77. if ($delta < $this->field['cardinality']) {
  78. $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'], $value, "Value $delta for revision $evid is loaded correctly");
  79. }
  80. else {
  81. $this->assertFalse(array_key_exists($delta, $entity->{$this->field_name}[$langcode]), "No extraneous value gets loaded for revision $evid.");
  82. }
  83. }
  84. }
  85. // Add a translation in an unavailable language and verify it is not loaded.
  86. $eid = $evid = 1;
  87. $unavailable_language = 'xx';
  88. $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
  89. $values = array($entity_type, $eid, $evid, 0, $unavailable_language, mt_rand(1, 127));
  90. db_insert($this->table)->fields($columns)->values($values)->execute();
  91. db_insert($this->revision_table)->fields($columns)->values($values)->execute();
  92. field_attach_load($entity_type, array($eid => $entity));
  93. $this->assertFalse(array_key_exists($unavailable_language, $entity->{$this->field_name}), 'Field translation in an unavailable language ignored');
  94. }
  95. /**
  96. * Reads mysql to verify correct data is
  97. * written when using insert and update.
  98. */
  99. function testFieldAttachInsertAndUpdate() {
  100. $entity_type = 'test_entity';
  101. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  102. $langcode = LANGUAGE_NONE;
  103. // Test insert.
  104. $values = array();
  105. // Note: we try to insert one extra value ('<=' instead of '<').
  106. // TODO : test empty values filtering and "compression" (store consecutive deltas).
  107. for ($delta = 0; $delta <= $this->field['cardinality']; $delta++) {
  108. $values[$delta]['value'] = mt_rand(1, 127);
  109. }
  110. $entity->{$this->field_name}[$langcode] = $rev_values[0] = $values;
  111. field_attach_insert($entity_type, $entity);
  112. $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
  113. foreach ($values as $delta => $value) {
  114. if ($delta < $this->field['cardinality']) {
  115. $this->assertEqual($rows[$delta][$this->field_name . '_value'], $value['value'], format_string("Value %delta is inserted correctly", array('%delta' => $delta)));
  116. }
  117. else {
  118. $this->assertFalse(array_key_exists($delta, $rows), "No extraneous value gets inserted.");
  119. }
  120. }
  121. // Test update.
  122. $entity = field_test_create_stub_entity(0, 1, $this->instance['bundle']);
  123. $values = array();
  124. // Note: we try to update one extra value ('<=' instead of '<').
  125. for ($delta = 0; $delta <= $this->field['cardinality']; $delta++) {
  126. $values[$delta]['value'] = mt_rand(1, 127);
  127. }
  128. $entity->{$this->field_name}[$langcode] = $rev_values[1] = $values;
  129. field_attach_update($entity_type, $entity);
  130. $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
  131. foreach ($values as $delta => $value) {
  132. if ($delta < $this->field['cardinality']) {
  133. $this->assertEqual($rows[$delta][$this->field_name . '_value'], $value['value'], format_string("Value %delta is updated correctly", array('%delta' => $delta)));
  134. }
  135. else {
  136. $this->assertFalse(array_key_exists($delta, $rows), "No extraneous value gets updated.");
  137. }
  138. }
  139. // Check that data for both revisions are in the revision table.
  140. // We make sure each value is stored correctly, then unset it.
  141. // When an entire revision's values are unset (remembering that we
  142. // put one extra value in $values per revision), unset the entire
  143. // revision. Then, if $rev_values is empty at the end, all
  144. // revision data was found.
  145. $results = db_select($this->revision_table, 't')->fields('t')->execute();
  146. foreach ($results as $row) {
  147. $this->assertEqual($row->{$this->field_name . '_value'}, $rev_values[$row->revision_id][$row->delta]['value'], "Value {$row->delta} for revision {$row->revision_id} stored correctly");
  148. unset($rev_values[$row->revision_id][$row->delta]);
  149. if (count($rev_values[$row->revision_id]) == 1) {
  150. unset($rev_values[$row->revision_id]);
  151. }
  152. }
  153. $this->assertTrue(empty($rev_values), "All values for all revisions are stored in revision table {$this->revision_table}");
  154. // Check that update leaves the field data untouched if
  155. // $entity->{$field_name} is absent.
  156. unset($entity->{$this->field_name});
  157. field_attach_update($entity_type, $entity);
  158. $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
  159. foreach ($values as $delta => $value) {
  160. if ($delta < $this->field['cardinality']) {
  161. $this->assertEqual($rows[$delta][$this->field_name . '_value'], $value['value'], format_string("Update with no field_name entry leaves value %delta untouched", array('%delta' => $delta)));
  162. }
  163. }
  164. // Check that update with an empty $entity->$field_name empties the field.
  165. $entity->{$this->field_name} = NULL;
  166. field_attach_update($entity_type, $entity);
  167. $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', PDO::FETCH_ASSOC);
  168. $this->assertEqual(count($rows), 0, "Update with an empty field_name entry empties the field.");
  169. }
  170. /**
  171. * Tests insert and update with missing or NULL fields.
  172. */
  173. function testFieldAttachSaveMissingData() {
  174. $entity_type = 'test_entity';
  175. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  176. $langcode = LANGUAGE_NONE;
  177. // Insert: Field is missing
  178. field_attach_insert($entity_type, $entity);
  179. $count = db_select($this->table)
  180. ->countQuery()
  181. ->execute()
  182. ->fetchField();
  183. $this->assertEqual($count, 0, 'Missing field results in no inserts');
  184. // Insert: Field is NULL
  185. $entity->{$this->field_name} = NULL;
  186. field_attach_insert($entity_type, $entity);
  187. $count = db_select($this->table)
  188. ->countQuery()
  189. ->execute()
  190. ->fetchField();
  191. $this->assertEqual($count, 0, 'NULL field results in no inserts');
  192. // Add some real data
  193. $entity->{$this->field_name}[$langcode] = array(0 => array('value' => 1));
  194. field_attach_insert($entity_type, $entity);
  195. $count = db_select($this->table)
  196. ->countQuery()
  197. ->execute()
  198. ->fetchField();
  199. $this->assertEqual($count, 1, 'Field data saved');
  200. // Update: Field is missing. Data should survive.
  201. unset($entity->{$this->field_name});
  202. field_attach_update($entity_type, $entity);
  203. $count = db_select($this->table)
  204. ->countQuery()
  205. ->execute()
  206. ->fetchField();
  207. $this->assertEqual($count, 1, 'Missing field leaves data in table');
  208. // Update: Field is NULL. Data should be wiped.
  209. $entity->{$this->field_name} = NULL;
  210. field_attach_update($entity_type, $entity);
  211. $count = db_select($this->table)
  212. ->countQuery()
  213. ->execute()
  214. ->fetchField();
  215. $this->assertEqual($count, 0, 'NULL field leaves no data in table');
  216. // Add a translation in an unavailable language.
  217. $unavailable_language = 'xx';
  218. db_insert($this->table)
  219. ->fields(array('entity_type', 'bundle', 'deleted', 'entity_id', 'revision_id', 'delta', 'language'))
  220. ->values(array($entity_type, $this->instance['bundle'], 0, 0, 0, 0, $unavailable_language))
  221. ->execute();
  222. $count = db_select($this->table)
  223. ->countQuery()
  224. ->execute()
  225. ->fetchField();
  226. $this->assertEqual($count, 1, 'Field translation in an unavailable language saved.');
  227. // Again add some real data.
  228. $entity->{$this->field_name}[$langcode] = array(0 => array('value' => 1));
  229. field_attach_insert($entity_type, $entity);
  230. $count = db_select($this->table)
  231. ->countQuery()
  232. ->execute()
  233. ->fetchField();
  234. $this->assertEqual($count, 2, 'Field data saved.');
  235. // Update: Field translation is missing but field is not empty. Translation
  236. // data should survive.
  237. $entity->{$this->field_name}[$unavailable_language] = array(mt_rand(1, 127));
  238. unset($entity->{$this->field_name}[$langcode]);
  239. field_attach_update($entity_type, $entity);
  240. $count = db_select($this->table)
  241. ->countQuery()
  242. ->execute()
  243. ->fetchField();
  244. $this->assertEqual($count, 2, 'Missing field translation leaves data in table.');
  245. // Update: Field translation is NULL but field is not empty. Translation
  246. // data should be wiped.
  247. $entity->{$this->field_name}[$langcode] = NULL;
  248. field_attach_update($entity_type, $entity);
  249. $count = db_select($this->table)
  250. ->countQuery()
  251. ->execute()
  252. ->fetchField();
  253. $this->assertEqual($count, 1, 'NULL field translation is wiped.');
  254. }
  255. /**
  256. * Test trying to update a field with data.
  257. */
  258. function testUpdateFieldSchemaWithData() {
  259. // Create a decimal 5.2 field and add some data.
  260. $field = array('field_name' => 'decimal52', 'type' => 'number_decimal', 'settings' => array('precision' => 5, 'scale' => 2));
  261. $field = field_create_field($field);
  262. $instance = array('field_name' => 'decimal52', 'entity_type' => 'test_entity', 'bundle' => 'test_bundle');
  263. $instance = field_create_instance($instance);
  264. $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
  265. $entity->decimal52[LANGUAGE_NONE][0]['value'] = '1.235';
  266. field_attach_insert('test_entity', $entity);
  267. // Attempt to update the field in a way that would work without data.
  268. $field['settings']['scale'] = 3;
  269. try {
  270. field_update_field($field);
  271. $this->fail(t('Cannot update field schema with data.'));
  272. }
  273. catch (FieldException $e) {
  274. $this->pass(t('Cannot update field schema with data.'));
  275. }
  276. }
  277. /**
  278. * Test that failure to create fields is handled gracefully.
  279. */
  280. function testFieldUpdateFailure() {
  281. // Create a text field.
  282. $field = array('field_name' => 'test_text', 'type' => 'text', 'settings' => array('max_length' => 255));
  283. $field = field_create_field($field);
  284. // Attempt to update the field in a way that would break the storage.
  285. $prior_field = $field;
  286. $field['settings']['max_length'] = -1;
  287. try {
  288. field_update_field($field);
  289. $this->fail(t('Update succeeded.'));
  290. }
  291. catch (Exception $e) {
  292. $this->pass(t('Update properly failed.'));
  293. }
  294. // Ensure that the field tables are still there.
  295. foreach (_field_sql_storage_schema($prior_field) as $table_name => $table_info) {
  296. $this->assertTrue(db_table_exists($table_name), format_string('Table %table exists.', array('%table' => $table_name)));
  297. }
  298. }
  299. /**
  300. * Test adding and removing indexes while data is present.
  301. */
  302. function testFieldUpdateIndexesWithData() {
  303. // Create a decimal field.
  304. $field_name = 'testfield';
  305. $field = array('field_name' => $field_name, 'type' => 'text');
  306. $field = field_create_field($field);
  307. $instance = array('field_name' => $field_name, 'entity_type' => 'test_entity', 'bundle' => 'test_bundle');
  308. $instance = field_create_instance($instance);
  309. $tables = array(_field_sql_storage_tablename($field), _field_sql_storage_revision_tablename($field));
  310. // Verify the indexes we will create do not exist yet.
  311. foreach ($tables as $table) {
  312. $this->assertFalse(Database::getConnection()->schema()->indexExists($table, 'value'), format_string("No index named value exists in %table", array('%table' => $table)));
  313. $this->assertFalse(Database::getConnection()->schema()->indexExists($table, 'value_format'), format_string("No index named value_format exists in %table", array('%table' => $table)));
  314. }
  315. // Add data so the table cannot be dropped.
  316. $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
  317. $entity->{$field_name}[LANGUAGE_NONE][0]['value'] = 'field data';
  318. field_attach_insert('test_entity', $entity);
  319. // Add an index
  320. $field = array('field_name' => $field_name, 'indexes' => array('value' => array('value')));
  321. field_update_field($field);
  322. foreach ($tables as $table) {
  323. $this->assertTrue(Database::getConnection()->schema()->indexExists($table, "{$field_name}_value"), format_string("Index on value created in %table", array('%table' => $table)));
  324. }
  325. // Add a different index, removing the existing custom one.
  326. $field = array('field_name' => $field_name, 'indexes' => array('value_format' => array('value', 'format')));
  327. field_update_field($field);
  328. foreach ($tables as $table) {
  329. $this->assertTrue(Database::getConnection()->schema()->indexExists($table, "{$field_name}_value_format"), format_string("Index on value_format created in %table", array('%table' => $table)));
  330. $this->assertFalse(Database::getConnection()->schema()->indexExists($table, "{$field_name}_value"), format_string("Index on value removed in %table", array('%table' => $table)));
  331. }
  332. // Verify that the tables were not dropped.
  333. $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
  334. field_attach_load('test_entity', array(0 => $entity));
  335. $this->assertEqual($entity->{$field_name}[LANGUAGE_NONE][0]['value'], 'field data', "Index changes performed without dropping the tables");
  336. }
  337. /**
  338. * Test the storage details.
  339. */
  340. function testFieldStorageDetails() {
  341. $current = _field_sql_storage_tablename($this->field);
  342. $revision = _field_sql_storage_revision_tablename($this->field);
  343. // Retrieve the field and instance with field_info so the storage details are attached.
  344. $field = field_info_field($this->field['field_name']);
  345. $instance = field_info_instance($this->instance['entity_type'], $this->instance['field_name'], $this->instance['bundle']);
  346. // The storage details are indexed by a storage engine type.
  347. $this->assertTrue(array_key_exists('sql', $field['storage']['details']), 'The storage type is SQL.');
  348. // The SQL details are indexed by table name.
  349. $details = $field['storage']['details']['sql'];
  350. $this->assertTrue(array_key_exists($current, $details[FIELD_LOAD_CURRENT]), 'Table name is available in the instance array.');
  351. $this->assertTrue(array_key_exists($revision, $details[FIELD_LOAD_REVISION]), 'Revision table name is available in the instance array.');
  352. // Test current and revision storage details together because the columns
  353. // are the same.
  354. foreach ((array) $this->field['columns'] as $column_name => $attributes) {
  355. $storage_column_name = _field_sql_storage_columnname($this->field['field_name'], $column_name);
  356. $this->assertEqual($details[FIELD_LOAD_CURRENT][$current][$column_name], $storage_column_name, format_string('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => $current)));
  357. $this->assertEqual($details[FIELD_LOAD_REVISION][$revision][$column_name], $storage_column_name, format_string('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => $revision)));
  358. }
  359. }
  360. /**
  361. * Test foreign key support.
  362. */
  363. function testFieldSqlStorageForeignKeys() {
  364. // Create a 'shape' field, with a configurable foreign key (see
  365. // field_test_field_schema()).
  366. $field_name = 'testfield';
  367. $foreign_key_name = 'shape';
  368. $field = array('field_name' => $field_name, 'type' => 'shape', 'settings' => array('foreign_key_name' => $foreign_key_name));
  369. field_create_field($field);
  370. // Retrieve the field definition and check that the foreign key is in place.
  371. $field = field_info_field($field_name);
  372. $this->assertEqual($field['foreign keys'][$foreign_key_name]['table'], $foreign_key_name, 'Foreign key table name preserved through CRUD');
  373. $this->assertEqual($field['foreign keys'][$foreign_key_name]['columns'][$foreign_key_name], 'id', 'Foreign key column name preserved through CRUD');
  374. // Update the field settings, it should update the foreign key definition
  375. // too.
  376. $foreign_key_name = 'color';
  377. $field['settings']['foreign_key_name'] = $foreign_key_name;
  378. field_update_field($field);
  379. // Retrieve the field definition and check that the foreign key is in place.
  380. $field = field_info_field($field_name);
  381. $this->assertEqual($field['foreign keys'][$foreign_key_name]['table'], $foreign_key_name, 'Foreign key table name modified after update');
  382. $this->assertEqual($field['foreign keys'][$foreign_key_name]['columns'][$foreign_key_name], 'id', 'Foreign key column name modified after update');
  383. // Now grab the SQL schema and verify that too.
  384. $schema = drupal_get_schema(_field_sql_storage_tablename($field), TRUE);
  385. $this->assertEqual(count($schema['foreign keys']), 1, 'There is 1 foreign key in the schema');
  386. $foreign_key = reset($schema['foreign keys']);
  387. $foreign_key_column = _field_sql_storage_columnname($field['field_name'], $foreign_key_name);
  388. $this->assertEqual($foreign_key['table'], $foreign_key_name, 'Foreign key table name preserved in the schema');
  389. $this->assertEqual($foreign_key['columns'][$foreign_key_column], 'id', 'Foreign key column name preserved in the schema');
  390. }
  391. }