tripal_entities.field_storage.inc 11 KB

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