tripal_chado.api.inc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <?php
  2. /**
  3. * Retrieves an entity that matches the given table and record id.
  4. *
  5. * @param $table
  6. * The name of the Chado table.
  7. * @param $record_id
  8. * The record's primary key in the table specified by $table.
  9. *
  10. * @return
  11. * A chado_entity object.
  12. */
  13. function tripal_load_chado_entity($table, $record_id) {
  14. $entity_id = db_select('chado_entity', 'ce')
  15. ->fields('ce', array('entity_id'))
  16. ->condition('ce.record_id', $record_id)
  17. ->condition('ce.data_table', $table)
  18. ->execute()
  19. ->fetchField();
  20. if ($entity_id) {
  21. $entity = entity_load('TripalEntity', array($entity_id));
  22. return reset($entity);
  23. }
  24. return NULL;
  25. }
  26. /**
  27. * Retrieves the entity ID using a record ID.
  28. *
  29. * @param unknown $data_table
  30. * @param unknown $record_id
  31. */
  32. function tripal_get_chado_entity_id($data_table, $record_id) {
  33. return db_select('chado_entity', 'ce')
  34. ->fields('ce', array('entity_id'))
  35. ->condition('data_table', $data_table)
  36. ->condition('record_id', $record_id)
  37. ->execute()
  38. ->fetchField();
  39. }
  40. /**
  41. * Publishes content in Chado as a new TripalEntity entity.
  42. *
  43. * @param $values
  44. * A key/value associative array that supports the following keys:
  45. * - bundle_name: The name of the the TripalBundle (e.g. bio_data-12345).
  46. * @param $job_id
  47. * (Optional) The numeric job ID as provided by the Tripal jobs system. There
  48. * is no need to specify this argument if this function is being called
  49. * outside of the jobs systems.
  50. *
  51. * @return boolean
  52. * TRUE if all of the records of the given bundle type were published, and
  53. * FALSE if a failure occured.
  54. */
  55. function tripal_chado_publish_records($values, $job_id = NULL) {
  56. $bundle_name = $values['bundle_name'];
  57. $sync_node = array_key_exists('sync_node', $values) ? $values['sync_node'] : '';
  58. if (!array_key_exists('bundle_name', $values) or !$values['bundle_name']) {
  59. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not publish record: @error", array('@error' => 'The bundle name was not provided'));
  60. return FALSE;
  61. }
  62. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  63. $bundle_id = $bundle->id;
  64. $table = tripal_get_bundle_variable('chado_table', $bundle_id);
  65. $column = tripal_get_bundle_variable('chado_column', $bundle_id);
  66. $cvterm_id = tripal_get_bundle_variable('chado_cvterm_id', $bundle_id);
  67. // Get the table information
  68. $table_schema = chado_get_schema($table);
  69. $pkey_field = $table_schema['primary key'][0];
  70. $select = "SELECT $pkey_field as record_id ";
  71. $from = "FROM {" . $table . "} T
  72. LEFT JOIN public.chado_entity CE on CE.record_id = T.$pkey_field
  73. AND CE.data_table = '$table'
  74. ";
  75. if ($sync_node && db_table_exists('chado_' . $table)) {
  76. $select = "SELECT T.$pkey_field as record_id, CT.nid ";
  77. $from .= "INNER JOIN public.chado_$table CT ON CT.$pkey_field = T.$pkey_field";
  78. }
  79. $where = " WHERE CE.record_id IS NULL ";
  80. if ($table != 'analysis' and $table != 'organism') {
  81. $where .= "AND $column = $cvterm_id";
  82. }
  83. $sql = $select . $from . $where;
  84. $records = chado_query($sql);
  85. $num_published = 0;
  86. $transaction = db_transaction();
  87. try {
  88. while($record = $records->fetchObject()) {
  89. // First save the tripal_entity record.
  90. $record_id = $record->record_id;
  91. $ec = entity_get_controller('TripalEntity');
  92. $entity = $ec->create(array(
  93. 'bundle' => $bundle_name,
  94. 'term_id' => $bundle->term_id,
  95. ));
  96. if (!$entity->save()) {
  97. throw new Exception('Could not create entity.');
  98. }
  99. // Next save the chado_entity record.
  100. $entity_record = array(
  101. 'entity_id' => $entity->id,
  102. 'record_id' => $record_id,
  103. 'data_table' => $table,
  104. 'type_table' => $table,
  105. 'field' => $column,
  106. );
  107. // For the Tv2 to Tv3 migration we want to add the nid to the
  108. // entity so we can associate the node with the entity.
  109. if (property_exists($record, 'nid')) {
  110. $entity_record['nid'] = $record->nid;
  111. }
  112. $success = drupal_write_record('chado_entity', $entity_record);
  113. $entity = entity_load('TripalEntity', array($entity->id));
  114. $entity = reset($entity);
  115. $title_format = tripal_get_title_format($bundle);
  116. $title = tripal_replace_entity_tokens($title_format, $entity, $bundle);
  117. $ec->setTitle($entity, $title);
  118. $num_published++;
  119. }
  120. }
  121. catch (Exception $e) {
  122. $transaction->rollback();
  123. $error = $e->getMessage();
  124. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not publish record: @error", array('@error' => $error));
  125. drupal_set_message('Failed publishing record. See recent logs for more details.', 'error');
  126. return FALSE;
  127. }
  128. drupal_set_message("Succesfully published $num_published " . $bundle->label . " record(s).");
  129. return TRUE;
  130. }
  131. /**
  132. * Returns an array of tokens based on Tripal Entity Fields.
  133. *
  134. * @param $base_table
  135. * The name of a base table in Chado.
  136. * @return
  137. * An array of tokens where the key is the machine_name of the token.
  138. */
  139. function tripal_get_chado_tokens($base_table) {
  140. $tokens = array();
  141. $table_descrip = chado_get_schema($base_table);
  142. foreach ($table_descrip['fields'] as $field_name => $field_details) {
  143. $token = '[' . $base_table . '.' . $field_name . ']';
  144. $location = implode(' > ',array($base_table, $field_name));
  145. $tokens[$token] = array(
  146. 'name' => ucwords(str_replace('_',' ',$base_table)) . ': ' . ucwords(str_replace('_',' ',$field_name)),
  147. 'table' => $base_table,
  148. 'field' => $field_name,
  149. 'token' => $token,
  150. 'description' => array_key_exists('description', $field_details) ? $field_details['description'] : '',
  151. 'location' => $location
  152. );
  153. if (!array_key_exists('description', $field_details) or preg_match('/TODO/',$field_details['description'])) {
  154. $tokens[$token]['description'] = 'The '.$field_name.' field of the '.$base_table.' table.';
  155. }
  156. }
  157. // RECURSION:
  158. // Follow the foreign key relationships recursively
  159. if (array_key_exists('foreign keys', $table_descrip)) {
  160. foreach ($table_descrip['foreign keys'] as $table => $details) {
  161. foreach ($details['columns'] as $left_field => $right_field) {
  162. $sub_token_prefix = $base_table . '.' . $left_field;
  163. $sub_location_prefix = implode(' > ',array($base_table, $left_field));
  164. $sub_tokens = tripal_get_chado_tokens($table);
  165. if (is_array($sub_tokens)) {
  166. $tokens = array_merge($tokens, $sub_tokens);
  167. }
  168. }
  169. }
  170. }
  171. return $tokens;
  172. }
  173. /**
  174. * Replace all Chado Tokens in a given string.
  175. *
  176. * NOTE: If there is no value for a token then the token is removed.
  177. *
  178. * @param string $string
  179. * The string containing tokens.
  180. * @param $record
  181. * A Chado record as generated by chado_generate_var()
  182. *
  183. * @return
  184. * The string will all tokens replaced with values.
  185. */
  186. function tripal_replace_chado_tokens($string, $record) {
  187. // Get the list of tokens
  188. $tokens = tripal_get_chado_tokens($record->tablename);
  189. // Determine which tokens were used in the format string
  190. if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
  191. // Get the value for each token used
  192. foreach ($used_tokens[0] as $token) {
  193. $token_info = $tokens[$token];
  194. if (!empty($token_info)) {
  195. $table = $token_info['table'];
  196. $var = $record;
  197. $value = '';
  198. // Iterate through each portion of the location string. An example string
  199. // might be: stock > type_id > name.
  200. $location = explode('>', $token_info['location']);
  201. foreach ($location as $index) {
  202. $index = trim($index);
  203. // if $var is an object then it is the $node object or a table
  204. // that has been expanded.
  205. if (is_object($var)) {
  206. // check to see if the index is a member of the object. If so,
  207. // then reset the $var to this value.
  208. if (property_exists($var, $index)) {
  209. $value = $var->$index;
  210. }
  211. }
  212. // if the $var is an array then there are multiple instances of the same
  213. // table in a FK relationship (e.g. relationship tables)
  214. elseif (is_array($var)) {
  215. $value = $var[$index];
  216. }
  217. else {
  218. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  219. 'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
  220. 'to access \'%index\' for the following: \'%var\'.',
  221. array('%token' => $token, '%index' => $index, '%var' => print_r($var,TRUE))
  222. );
  223. }
  224. }
  225. $string = str_replace($token, $value, $string);
  226. }
  227. }
  228. }
  229. return $string;
  230. }