tripal_entities.field_storage.inc 11 KB

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