tripal_entities.field_storage.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. <?php
  2. /**
  3. * Implements hook_field_storage_info().
  4. */
  5. function tripal_entities_field_storage_info() {
  6. return array(
  7. 'field_chado_storage' => array(
  8. 'label' => t('Chado storage'),
  9. 'description' => t('Stores fields in the local Chado database.'),
  10. 'settings' => array(),
  11. ),
  12. );
  13. }
  14. /**
  15. * Implements hook_field_storage_write().
  16. */
  17. function tripal_entities_field_storage_write($entity_type, $entity, $op, $fields) {
  18. // Conver the fields into a key/value list of fields and their values.
  19. $field_vals = tripal_entities_field_storage_unnest_fields($fields, $entity_type, $entity);
  20. // Calculate the md5 checksum for the sequence per user's request
  21. if (key_exists('feature__md5checksum', $field_vals) && key_exists('feature__residues', $field_vals)) {
  22. $residues = $field_vals['feature__residues'];
  23. $field_vals['feature__md5checksum'] = $field_vals['feature__md5checksum'] ? md5($residues) : NULL;
  24. }
  25. $transaction = db_transaction();
  26. try {
  27. switch ($op) {
  28. case FIELD_STORAGE_INSERT:
  29. // Use the cvterm_id to look up tables where this term is used
  30. $sel_values = array(
  31. 'term_id' => array(
  32. 'cvterm_id' => $entity->cvterm_id,
  33. ),
  34. );
  35. $term_usage = chado_generate_var('tripal_term_usage', $sel_values, array('return_array' => 1));
  36. // For each table that uses this term, insert the field recursively
  37. foreach ($term_usage as $usage) {
  38. $data_table = $usage->data_table;
  39. //$type_table = $usage->type_table;
  40. $type_field = $usage->field;
  41. tripal_entities_field_storage_write_recursive($entity_type, $entity,
  42. $op, $field_vals, $data_table, $type_field);
  43. }
  44. break;
  45. case FIELD_STORAGE_UPDATE :
  46. // Get the base table and record id for the fields of this entity.
  47. $details = db_select('chado_entity', 'ce')
  48. ->fields('ce')
  49. ->condition('entity_id', $entity->id)
  50. ->execute()
  51. ->fetchObject();
  52. $tablename = $details->data_table;
  53. $type_field = $details->field;
  54. $record_id = $details->record_id;
  55. tripal_entities_field_storage_write_recursive($entity_type, $entity,
  56. $op, $field_vals, $tablename, $type_field, $record_id);
  57. if (!$details) {
  58. // TODO: what to do if record is missing!
  59. }
  60. break;
  61. }
  62. }
  63. catch (Exception $e) {
  64. $transaction->rollback();
  65. watchdog_exception('tripal_feature', $e);
  66. drupal_set_message('Could not write record to Chado. See recent logs', 'error');
  67. }
  68. }
  69. /**
  70. * Implements hook_field_storage_write_recursive().
  71. */
  72. function tripal_entities_field_storage_write_recursive($entity_type, $entity,
  73. $op, $field_vals, $tablename, $type_field = NULL, $record_id = NULL, $depth = 0) {
  74. // Intialize the values array and $record_id;
  75. $values = array();
  76. // Get the schema for this table so that we can identify the primary key
  77. // and foreign keys.
  78. $schema = chado_get_schema($tablename);
  79. $pkey_field = $schema['primary key'][0];
  80. $fkey_fields = $schema['foreign keys'];
  81. $fkey_fields_list = array();
  82. // STEP 1: Recurse on the FK fields.
  83. // Loop through the foreign keys os that we can recurse on those first.
  84. foreach ($fkey_fields as $fk_table => $details) {
  85. foreach ($details['columns'] as $local_id => $remote_id) {
  86. // If this is the base table then do not recurse on the type_id. The
  87. // type_id is set in the entity. We are at the base table when
  88. // the depth is 0.
  89. if ($depth == 0 && $local_id == $type_field) {
  90. $values[$local_id] = $entity->cvterm_id;
  91. continue;
  92. }
  93. // Keep track of the FK fields so that in STEP 2 we don't have to
  94. // loop through the $fk_fields again.
  95. $fkey_fields_list[] = $local_id;
  96. // Recurse on the FK field. Pass in the ID for the FK field if one
  97. // exists in the $field_vals;
  98. $fk_val = NULL;
  99. $fk_field_name = $tablename . '__' . $local_id;
  100. $fk_val = array_key_exists($fk_field_name, $field_vals) ? $field_vals[$fk_field_name] : NULL;
  101. $fk_val = tripal_entities_field_storage_write_recursive($entity_type,
  102. $entity, $op, $field_vals, $fk_table, NULL, $fk_val, $depth + 1);
  103. if ($fk_val) {
  104. $values[$local_id] = $fk_val;
  105. }
  106. }
  107. }
  108. // STEP 2: Loop through the incoming fields.
  109. // Loop through the fields passed to the function and find any that
  110. // are for this table. Then add their values to the $values array.
  111. foreach ($field_vals as $field_name => $field_val) {
  112. // If the field value is empty then continue.
  113. if (!isset($field_val) or $field_val === '' or $field_val === NULL) {
  114. continue;
  115. }
  116. if (preg_match('/^' . $tablename . '__(.*)/', $field_name, $matches)) {
  117. $chado_field = $matches[1];
  118. // Skip the Pkey field. We won't ever insert a primary key and if
  119. // one is provided in the fields then we use it for matching on an
  120. // update. We don't add it to the $values array in either case.
  121. if ($chado_field == $pkey_field) {
  122. continue;
  123. }
  124. // Skip FK fields as those should already have been dealt with the
  125. // recursive code above.
  126. if (in_array($chado_field, $fkey_fields_list)) {
  127. continue;
  128. }
  129. // Add the value of the field to the $values arr for later insert/update.
  130. $values[$chado_field] = $field_vals[$field_name];
  131. }
  132. }
  133. // STEP 3: Insert/Update the record.
  134. // If there are no values then return.
  135. if (count($values) == 0) {
  136. return $record_id;
  137. }
  138. // If we don't have an incoming record ID then this is an insert.
  139. if (!$record_id) {
  140. // Insert the values array as a new record in the table.
  141. $record = chado_insert_record($tablename, $values);
  142. if ($record === FALSE) {
  143. drupal_set_message('Could not insert Chado record into table, "$table".', 'error');
  144. }
  145. $record_id = $record[$pkey_field];
  146. // Add a record to the chado_entity table so that the data for the
  147. // fields can be pulled from Chado when loaded the next time. Only do
  148. // this for the base table record.
  149. if ($depth == 0) {
  150. $record = array(
  151. 'entity_id' => $entity->id,
  152. 'record_id' => $record_id,
  153. 'data_table' => $tablename,
  154. 'type_table' => $tablename, // TODO: this must be fixed.
  155. 'field' => $type_field,
  156. );
  157. $success = drupal_write_record('chado_entity', $record);
  158. if (!$success) {
  159. drupal_set_message('Unable to insert new Chado entity.', 'error');
  160. }
  161. }
  162. }
  163. // We have an incoming record_id so this is an update.
  164. else {
  165. $match[$pkey_field] = $record_id;
  166. if (!chado_update_record($tablename, $match, $values)) {
  167. drupal_set_message('Could not update Chado record for in table, "$table".', 'error');
  168. }
  169. }
  170. return $record_id;
  171. }
  172. /**
  173. * Implements hook_field_storage_load().
  174. *
  175. * Responsible for loading the fields from the Chado database and adding
  176. * their values to the entity.
  177. */
  178. function tripal_entities_field_storage_load($entity_type, $entities, $age, $fields, $options) {
  179. $load_current = $age == FIELD_LOAD_CURRENT;
  180. global $language;
  181. $langcode = $language->language;
  182. foreach ($entities as $id => $entity) {
  183. // Get the base table and record id for the fields of this entity.
  184. $details = db_select('chado_entity', 'ce')
  185. ->fields('ce')
  186. ->condition('entity_id', $entity->id)
  187. ->execute()
  188. ->fetchObject();
  189. if (!$details) {
  190. // TODO: what to do if record is missing!
  191. }
  192. // Find out which table should receive the insert.
  193. $tablename = $details->data_table;
  194. $type_field = $details->field;
  195. $schema = chado_get_schema($tablename);
  196. $pkey_field = $schema['primary key'][0];
  197. $record_id = $details->record_id;
  198. // Iterate through the field names to get the list of tables and fields
  199. // that should be queried.
  200. $columns = array();
  201. foreach ($fields as $field_id => $ids) {
  202. // By the time this hook runs, the relevant field definitions have been
  203. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  204. // on each field individually is more efficient than loading all fields in
  205. // memory upfront with field_info_field_by_ids().
  206. $field = field_info_field_by_id($field_id);
  207. $field_name = $field['field_name'];
  208. $matches = array();
  209. if (preg_match('/^(.*?)__(.*?)$/', $field_name, $matches)) {
  210. $table = $matches[1];
  211. $field = $matches[2];
  212. $columns[$table][] = $field;
  213. }
  214. }
  215. // Get the record
  216. $values = array($pkey_field => $record_id);
  217. $record = chado_select_record($tablename, $columns[$tablename], $values);
  218. // Now set the field values
  219. foreach ($fields as $field_id => $ids) {
  220. $field = field_info_field_by_id($field_id);
  221. $field_name = $field['field_name'];
  222. $matches = array();
  223. if (preg_match('/^(.*?)__(.*?)$/', $field_name, $matches)) {
  224. $table = $matches[1];
  225. $field = $matches[2];
  226. $entity->{$field_name}['und'][] = array('value' => $record[0]->$field);
  227. }
  228. }
  229. }
  230. }
  231. /**
  232. * Iterates through all of the fields reformats to a key/value array.
  233. *
  234. * @param $fields
  235. */
  236. function tripal_entities_field_storage_unnest_fields($fields, $entity_type, $entity) {
  237. $new_fields = array();
  238. foreach ($fields as $field_id => $ids) {
  239. $field = field_info_field_by_id($field_id);
  240. $field_name = $field['field_name'];
  241. // Currently, we only support one language, but for for the sake of
  242. // thoroughness we'll iterate through all possible languages.
  243. $all_languages = field_available_languages($entity_type, $field);
  244. $field_languages = array_intersect($all_languages, array_keys((array) $entity->$field_name));
  245. foreach ($field_languages as $langcode) {
  246. $items = (array) $entity->{$field_name}[$langcode];
  247. // The number of items is related to the cardinatily of the field.
  248. // We should always only have one item because this is a field in a
  249. // table. But we loop anyway.
  250. foreach ($items as $delta => $item) {
  251. // If the $value is an array then this field has nested fields. We
  252. // want to add those to our $new_fields list.
  253. if (is_array($item['value'])) {
  254. foreach ($item['value'] as $children) {
  255. foreach ($children as $child_field_name => $child_value) {
  256. if (preg_match('/^.*?__.*?$/', $child_field_name)) {
  257. $new_fields[$child_field_name] = $child_value;
  258. }
  259. }
  260. }
  261. }
  262. else {
  263. $new_fields[$field_name] = $item['value'];
  264. }
  265. }
  266. }
  267. }
  268. return $new_fields;
  269. }