tripal_chado.field_storage.inc 13 KB

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