tripal_entities.field_storage.inc 10 KB

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