tripal_chado.field_storage.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <?php
  2. /**
  3. * Implements hook_field_storage_info().
  4. */
  5. function tripal_chado_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_chado_field_storage_write($entity_type, $entity, $op, $fields) {
  18. // Get the bundle and the term for this entity.
  19. $bundle = tripal_load_bundle_entity($entity->bundle);
  20. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  21. $term = reset($term);
  22. // Get the base table, type field and record_id from the entity.
  23. $base_table = tripal_get_bundle_variable('chado_table', $bundle->id);
  24. $type_field = tripal_get_bundle_variable('chado_column', $bundle->id);
  25. // Look for an record in the chado_entity table for this entity.
  26. $chado_entity = db_select('chado_entity', 'ct')
  27. ->fields('ct')
  28. ->condition('ct.entity_id', $entity->id)
  29. ->execute()
  30. ->fetchObject();
  31. $record_id = NULL;
  32. if ($chado_entity) {
  33. $record_id = $chado_entity->record_id;
  34. }
  35. // Convert the fields into a key/value list of fields and their values.
  36. $field_vals = tripal_chado_field_storage_unnest_fields($fields, $entity_type, $entity);
  37. // Recursively write fields for the base table.
  38. $record_id = tripal_chado_field_storage_write_recursive($entity_type, $entity, $term,
  39. $op, $field_vals, $base_table, $base_table, $type_field, $record_id);
  40. // If this is an insert then add the chado_entity record.
  41. if ($op == FIELD_STORAGE_INSERT) {
  42. // Add a record to the chado_entity table so that the data for the
  43. // fields can be pulled from Chado when loaded the next time.
  44. $record = array(
  45. 'entity_id' => $entity->id,
  46. 'record_id' => $record_id,
  47. 'data_table' => $base_table,
  48. 'type_table' => $base_table,
  49. 'field' => $type_field,
  50. );
  51. $success = drupal_write_record('chado_entity', $record);
  52. if (!$success) {
  53. drupal_set_message('Unable to insert new Chado entity.', 'error');
  54. }
  55. }
  56. // Now that we have handled the base table, we need to handle fields that
  57. // are not part of the base table.
  58. foreach ($fields as $field_id) {
  59. // Get the field using the id.
  60. $field = field_info_field_by_id($field_id);
  61. $field_name = $field['field_name'];
  62. // If the field has a chado_table setting then we can try to write.
  63. if (array_key_exists('settings', $field) and array_key_exists('chado_table', $field['settings'])) {
  64. // Skip fields that use the base table, as we've already handled those.
  65. if ($field['settings']['chado_table'] != $base_table){
  66. $field_table = $field['settings']['chado_table'];
  67. // Iterate through each record.
  68. foreach ($field_vals[$field_name] as $delta => $fvals) {
  69. tripal_chado_field_storage_write_recursive($entity_type, $entity, $term,
  70. $op, $fvals, $base_table, $field_table);
  71. }
  72. }
  73. }
  74. }
  75. }
  76. /**
  77. *
  78. * @param $entity_type
  79. * @param $entity
  80. * @param $op
  81. * @param $field_vals
  82. * @param $tablename
  83. * @param $type_field
  84. * @param $record_id
  85. * @param $depth
  86. * @throws Exception
  87. * @return
  88. * The record_id of the table if a matching record exists.
  89. */
  90. function tripal_chado_field_storage_write_recursive($entity_type, $entity, $term,
  91. $op, $field_vals, $base_table, $tablename, $type_field = NULL,
  92. $record_id = NULL, $depth = 0) {
  93. // Intialize the values array.
  94. $values = array();
  95. // Get the schema for this table so that we can identify the primary key
  96. // and foreign keys.
  97. $schema = chado_get_schema($tablename);
  98. $pkey_field = $schema['primary key'][0];
  99. $fkey_fields = $schema['foreign keys'];
  100. $fkey_fields_list = array();
  101. $fkey_base_linker = NULL;
  102. // STEP 1: Recurse on the FK fields.
  103. // Loop through the foreign keys so that we can recurse on those first.
  104. foreach ($fkey_fields as $fk_table => $details) {
  105. foreach ($details['columns'] as $local_id => $remote_id) {
  106. // If this is the base table then do not recurse on the type_id.
  107. if ($tablename == $base_table && $local_id == $type_field) {
  108. $values[$local_id] = $term->details['cvterm']->cvterm_id;
  109. continue;
  110. }
  111. // If this is not the base table then do not recurse on the FK field
  112. // that links this table to the base table.
  113. if ($tablename != $base_table && $details['table'] == $base_table) {
  114. $fkey_base_linker = $local_id;
  115. continue;
  116. }
  117. // Get the value of the FK field as provided by the user.
  118. $fk_val = NULL;
  119. $fk_vals = array();
  120. $fk_field_name = $tablename . '__' . $local_id;
  121. if (array_key_exists($fk_field_name, $field_vals)) {
  122. $fk_val = $field_vals[$fk_field_name][0]['value'];
  123. $fk_vals = $field_vals[$fk_field_name][0];
  124. unset($fk_vals['value']);
  125. }
  126. // Don't recurse if the value of the FK field is set to NULL. The
  127. // Tripal Chado API value for NULL is '__NULL__'.
  128. if ($fk_val == "__NULL__") {
  129. $values[$local_id] = $fk_val;
  130. continue;
  131. }
  132. // Don't recuse if there are no fkvals.
  133. if (count(array_keys($fk_vals)) == 0) {
  134. continue;
  135. }
  136. // Keep track of the FK fields so that in STEP 2 we don't have to
  137. // loop through the $fk_fields again.
  138. $fkey_fields_list[] = $local_id;
  139. // Recurse on the FK field. Pass in the ID for the FK field if one
  140. // exists in the $field_vals;
  141. $fk_val = tripal_chado_field_storage_write_recursive($entity_type,
  142. $entity, $term, $op, $fk_vals, $base_table, $fk_table, NULL, $fk_val, $depth + 1);
  143. if (isset($fk_val) and $fk_val != '' and $fk_val != 0) {
  144. $values[$local_id] = $fk_val;
  145. }
  146. }
  147. }
  148. // STEP 2: Loop through the non FK fields.
  149. // Loop through the fields passed to the function and find any that
  150. // are for this table. Then add their values to the $values array.
  151. foreach ($field_vals as $field_name => $items) {
  152. if (preg_match('/^' . $tablename . '__(.*)/', $field_name, $matches)) {
  153. $chado_field = $matches[1];
  154. // Skip the PKey field. We won't ever insert a primary key and if
  155. // one is provided in the fields then we use it for matching on an
  156. // update. We don't add it to the $values array in either case.
  157. if ($chado_field == $pkey_field) {
  158. continue;
  159. }
  160. // Skip FK fields as those should already have been dealt with the
  161. // recursive code above.
  162. if (in_array($chado_field, $fkey_fields_list)) {
  163. continue;
  164. }
  165. // If the value is empty then exclude this field
  166. if (!$items[0]['value']) {
  167. continue;
  168. }
  169. // Add the value of the field to the $values arr for later insert/update.
  170. $values[$chado_field] = $items[0]['value'];
  171. }
  172. }
  173. // STEP 3: Insert/Update the record.
  174. // If there are no values then return.
  175. if (count($values) == 0) {
  176. return $record_id;
  177. }
  178. // If we don't have an incoming record ID then this is an insert.
  179. if ($record_id == NULL) {
  180. // STEP 3a: Before inserting, we want to make sure the record does not
  181. // already exist. Using the unique constraint check for a matching record.
  182. $options = array('is_duplicate' => TRUE);
  183. $is_duplicate = chado_select_record($tablename, array('*'), $values, $options);
  184. if($is_duplicate) {
  185. $record = chado_select_record($tablename, array('*'), $values);
  186. return $record[0]->$pkey_field;
  187. }
  188. // STEP 3b: Insert the reocrd
  189. // Insert the values array as a new record in the table.
  190. $record = chado_insert_record($tablename, $values);
  191. if ($record === FALSE) {
  192. throw new Exception('Could not insert Chado record into table: "' . $tablename . '".');
  193. }
  194. $record_id = $record[$pkey_field];
  195. }
  196. // We have an incoming record_id so this is an update.
  197. else {
  198. $match[$pkey_field] = $record_id;
  199. if (!chado_update_record($tablename, $match, $values)) {
  200. drupal_set_message("Could not update Chado record in table: $tablename.", 'error');
  201. }
  202. }
  203. return $record_id;
  204. }
  205. /**
  206. * Implements hook_field_storage_load().
  207. *
  208. * Responsible for loading the fields from the Chado database and adding
  209. * their values to the entity.
  210. */
  211. function tripal_chado_field_storage_load($entity_type, $entities, $age,
  212. $fields, $options) {
  213. $load_current = $age == FIELD_LOAD_CURRENT;
  214. global $language;
  215. $langcode = $language->language;
  216. foreach ($entities as $id => $entity) {
  217. // Get the base table and record id for the fields of this entity.
  218. $details = db_select('chado_entity', 'ce')
  219. ->fields('ce')
  220. ->condition('entity_id', $entity->id)
  221. ->execute()
  222. ->fetchObject();
  223. if (!$details) {
  224. // TODO: what to do if record is missing!
  225. }
  226. // Get some values needed for loading the values from Chado.
  227. $base_table = $details->data_table;
  228. $type_field = $details->field;
  229. $record_id = $details->record_id;
  230. // Get this table's schema.
  231. $schema = chado_get_schema($base_table);
  232. $pkey_field = $schema['primary key'][0];
  233. // Get the base record if one exists
  234. $columns = array('*');
  235. $match = array($pkey_field => $record_id);
  236. $record = chado_select_record($base_table, $columns, $match);
  237. $record = $record[0];
  238. // Iterate through the entity's fields so we can get the column names
  239. // that need to be selected from each of the tables represented.
  240. $tables = array();
  241. foreach ($fields as $field_id => $ids) {
  242. // By the time this hook runs, the relevant field definitions have been
  243. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  244. // on each field individually is more efficient than loading all fields in
  245. // memory upfront with field_info_field_by_ids().
  246. $field = field_info_field_by_id($field_id);
  247. $field_name = $field['field_name'];
  248. $field_type = $field['type'];
  249. $field_module = $field['module'];
  250. // Skip fields that don't map to a Chado table (e.g. kvproperty_adder).
  251. if (!array_key_exists('settings', $field) or !array_key_exists('chado_table', $field['settings'])) {
  252. continue;
  253. }
  254. // Get the Chado table and column for this field.
  255. $field_table = $field['settings']['chado_table'];
  256. $field_column = $field['settings']['chado_column'];
  257. // There are only two types of fields: 1) fields that represent a single
  258. // column of the base table, or 2) fields that represent a linked record
  259. // in a many-to-one relationship with the base table.
  260. // Type 1: fields from base tables.
  261. if ($field_table == $base_table) {
  262. // Set an empty value by default, and if there is a record, then update.
  263. $entity->{$field_name}['und'][0]['value'] = '';
  264. if ($record and property_exists($record, $field_column)) {
  265. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  266. }
  267. // Allow the creating module to alter the value if desired. The
  268. // module should do this if the field has any other form elements
  269. // that need populationg besides the default value.
  270. $load_function = $field_module . '_' . $field_type . '_field_load';
  271. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  272. if (function_exists($load_function)) {
  273. $load_function($field, $entity, $base_table, $record);
  274. }
  275. }
  276. // Type 2: fields for linked records. These fields will have any number
  277. // of form elements that might need populating so we'll offload the
  278. // loading of these fields to the field itself.
  279. if ($field_table != $base_table) {
  280. // Set an empty value by default, and let the hook function update it.
  281. $entity->{$field_name}['und'][0]['value'] = '';
  282. $load_function = $field_module . '_' . $field_type . '_field_load';
  283. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  284. if (function_exists($load_function)) {
  285. $load_function($field, $entity, $base_table, $record);
  286. }
  287. }
  288. } // end: foreach ($fields as $field_id => $ids) {
  289. } // end: foreach ($entities as $id => $entity) {
  290. }
  291. /**
  292. * Iterates through all of the fields reformats to a key/value array.
  293. *
  294. * @param $fields
  295. */
  296. function tripal_chado_field_storage_unnest_fields($fields, $entity_type, $entity) {
  297. $new_fields = array();
  298. // Iterate through all of the fields.
  299. foreach ($fields as $field_id => $ids) {
  300. // Get the field name and all of it's items.
  301. $field = field_info_field_by_id($field_id);
  302. $field_name = $field['field_name'];
  303. $items = field_get_items($entity_type, $entity, $field_name);
  304. // Iterate through the field's items. Fields with cardinality ($delta) > 1
  305. // are multi-valued.
  306. foreach ($items as $delta => $item) {
  307. foreach ($item as $item_name => $value) {
  308. if ($item_name == 'value') {
  309. $new_fields[$field_name][$delta]['value'] = $value;
  310. continue;
  311. }
  312. $matches = array();
  313. if (preg_match('/^(.*?)__.*?$/', $item_name, $matches)) {
  314. $table_name = $matches[1];
  315. $new_fields[$field_name][$delta][$item_name][0]['value'] = $value;
  316. }
  317. }
  318. }
  319. }
  320. return $new_fields;
  321. }