tripal_chado.field_storage.inc 13 KB

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