tripal_chado.api.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <?php
  2. /**
  3. * Publishes content in Chado as a new TripalEntity entity.
  4. *
  5. * @param $values
  6. * A key/value associative array that supports the following keys:
  7. * - bundle_name: The name of the the TripalBundle (e.g. bio_data-12345).
  8. * @param $job_id
  9. * (Optional) The numeric job ID as provided by the Tripal jobs system. There
  10. * is no need to specify this argument if this function is being called
  11. * outside of the jobs systems.
  12. *
  13. * @return boolean
  14. * TRUE if all of the records of the given bundle type were published, and
  15. * FALSE if a failure occured.
  16. */
  17. function tripal_chado_publish_records($values, $job_id = NULL) {
  18. // Make sure we have the required options: bundle_name.
  19. if (!array_key_exists('bundle_name', $values) or !$values['bundle_name']) {
  20. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  21. "Could not publish record: @error",
  22. array('@error' => 'The bundle name must be provided'));
  23. return FALSE;
  24. }
  25. // Get the incoming arguments from the $values array.
  26. $bundle_name = $values['bundle_name'];
  27. $filters = array_key_exists('filters', $values) ? $values['filters'] : array();
  28. $sync_node = array_key_exists('sync_node', $values) ? $values['sync_node'] : '';
  29. // Load the bundle entity so we can get information about which Chado
  30. // table/field this entity belongs to.
  31. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  32. if (!$bundle) {
  33. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  34. "Unknown bundle. Could not publish record: @error",
  35. array('@error' => 'The bundle name must be provided'));
  36. return FALSE;
  37. }
  38. $chado_entity_table = tripal_chado_get_bundle_entity_table($bundle);
  39. $table = $bundle->data_table;
  40. $type_column = $bundle->type_column;
  41. $type_linker_table = $bundle->type_linker_table;
  42. $cvterm_id = $bundle->type_id;
  43. // Get the table information for the Chado table.
  44. $table_schema = chado_get_schema($table);
  45. $pkey_field = $table_schema['primary key'][0];
  46. // Construct the SQL for identifying which records should be published.
  47. $args = array();
  48. $select = "SELECT $pkey_field as record_id ";
  49. $from = "
  50. FROM {" . $table . "} T
  51. LEFT JOIN public.$chado_entity_table CE on CE.record_id = T.$pkey_field
  52. ";
  53. // For migration of Tripal v2 nodes to entities we want to include the
  54. // coresponding chado linker table.
  55. if ($sync_node && db_table_exists('chado_' . $table)) {
  56. $select = "SELECT T.$pkey_field as record_id, CT.nid ";
  57. $from .= " INNER JOIN public.chado_$table CT ON CT.$pkey_field = T.$pkey_field";
  58. }
  59. $where = " WHERE CE.record_id IS NULL ";
  60. $args[':table'] = $table;
  61. // Handle bundles that use a linker property table for identifying the type
  62. // of record to publish.
  63. if ($type_linker_table and $type_column) {
  64. $propschema = chado_get_schema($type_linker_table);
  65. $fkeys = $propschema['foreign keys'][$table]['columns'];
  66. foreach ($fkeys as $leftkey => $rightkey) {
  67. if ($rightkey == $pkey_field) {
  68. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  69. }
  70. }
  71. $where .= "AND LT.$type_column = :cvterm_id";
  72. $args[':cvterm_id'] = $cvterm_id;
  73. }
  74. // If the type column is in the base table then add in the SQL for that.
  75. if (!$type_linker_table and $type_column) {
  76. $where .= "AND T.$type_column = :cvterm_id";
  77. $args[':cvterm_id'] = $cvterm_id;
  78. }
  79. // If no type column is specified then we have a problem.
  80. if ($type_linker_table and !$type_column) {
  81. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  82. "Could not publish record: @error",
  83. array('@error' => 'The bundle does not properly map to Chado.'));
  84. return FALSE;
  85. }
  86. // Now add in any additional filters
  87. $fields = field_info_field_map();
  88. foreach ($fields as $field_name => $details) {
  89. if (array_key_exists('TripalEntity', $details['bundles']) and
  90. in_array($bundle_name, $details['bundles']['TripalEntity']) and
  91. in_array($field_name, array_keys($filters))){
  92. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  93. $chado_table = $instance['settings']['chado_table'];
  94. $chado_column = $instance['settings']['chado_column'];
  95. if ($chado_table == $table) {
  96. $where .= " AND T.$chado_column = :$field_name";
  97. $args[":$field_name"] = $filters[$field_name];
  98. }
  99. }
  100. }
  101. // First get the count
  102. $sql = "SELECT count(*) as num_records " . $from . $where;
  103. $result = chado_query($sql, $args);
  104. $count = $result->fetchField();
  105. // calculate the interval for updates
  106. $interval = intval($count / 1000);
  107. if ($interval < 1) {
  108. $interval = 1;
  109. }
  110. // Perform the query.
  111. $sql = $select . $from . $where;
  112. $records = chado_query($sql, $args);
  113. //$transaction = db_transaction();
  114. print "\nNOTE: publishing records is performed using a database transaction. \n" .
  115. "If the load fails or is terminated prematurely then the entire set of \n" .
  116. "is rolled back with no changes to the database\n\n";
  117. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, 0, number_format(memory_get_usage()));
  118. try {
  119. $i = 0;
  120. while($record = $records->fetchObject()) {
  121. // update the job status every interval
  122. //if ($jobid and $i % $interval == 0) {
  123. $complete = ($i / $count) * 33.33333333;
  124. //tripal_set_job_progress($jobid, intval($complete + 33.33333333));
  125. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  126. //}
  127. // First save the tripal_entity record.
  128. $record_id = $record->record_id;
  129. $ec = entity_get_controller('TripalEntity');
  130. $entity = $ec->create(array(
  131. 'bundle' => $bundle_name,
  132. 'term_id' => $bundle->term_id,
  133. 'chado_record' => chado_generate_var($table, array($pkey_field => $record_id)),
  134. 'chado_record_id' => $record_id,
  135. ));
  136. $entity = $entity->save();
  137. if (!$entity) {
  138. throw new Exception('Could not create entity.');
  139. }
  140. // Next save the chado entity record.
  141. $entity_record = array(
  142. 'entity_id' => $entity->id,
  143. 'record_id' => $record_id,
  144. );
  145. // For the Tv2 to Tv3 migration we want to add the nid to the
  146. // entity so we can associate the node with the entity.
  147. if (property_exists($record, 'nid')) {
  148. $entity_record['nid'] = $record->nid;
  149. }
  150. $success = drupal_write_record($chado_entity_table, $entity_record);
  151. $i++;
  152. }
  153. }
  154. catch (Exception $e) {
  155. $transaction->rollback();
  156. $error = $e->getMessage();
  157. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not publish record: @error", array('@error' => $error));
  158. drupal_set_message('Failed publishing record. See recent logs for more details.', 'error');
  159. return FALSE;
  160. }
  161. drupal_set_message("Succesfully published $i " . $bundle->label . " record(s).");
  162. return TRUE;
  163. }
  164. /**
  165. * Returns an array of tokens based on Tripal Entity Fields.
  166. *
  167. * @param $base_table
  168. * The name of a base table in Chado.
  169. * @return
  170. * An array of tokens where the key is the machine_name of the token.
  171. */
  172. function tripal_get_chado_tokens($base_table) {
  173. $tokens = array();
  174. $table_descrip = chado_get_schema($base_table);
  175. foreach ($table_descrip['fields'] as $field_name => $field_details) {
  176. $token = '[' . $base_table . '.' . $field_name . ']';
  177. $location = implode(' > ',array($base_table, $field_name));
  178. $tokens[$token] = array(
  179. 'name' => ucwords(str_replace('_',' ',$base_table)) . ': ' . ucwords(str_replace('_',' ',$field_name)),
  180. 'table' => $base_table,
  181. 'field' => $field_name,
  182. 'token' => $token,
  183. 'description' => array_key_exists('description', $field_details) ? $field_details['description'] : '',
  184. 'location' => $location
  185. );
  186. if (!array_key_exists('description', $field_details) or preg_match('/TODO/',$field_details['description'])) {
  187. $tokens[$token]['description'] = 'The '.$field_name.' field of the '.$base_table.' table.';
  188. }
  189. }
  190. // RECURSION:
  191. // Follow the foreign key relationships recursively
  192. if (array_key_exists('foreign keys', $table_descrip)) {
  193. foreach ($table_descrip['foreign keys'] as $table => $details) {
  194. foreach ($details['columns'] as $left_field => $right_field) {
  195. $sub_token_prefix = $base_table . '.' . $left_field;
  196. $sub_location_prefix = implode(' > ',array($base_table, $left_field));
  197. $sub_tokens = tripal_get_chado_tokens($table);
  198. if (is_array($sub_tokens)) {
  199. $tokens = array_merge($tokens, $sub_tokens);
  200. }
  201. }
  202. }
  203. }
  204. return $tokens;
  205. }
  206. /**
  207. * Replace all Chado Tokens in a given string.
  208. *
  209. * NOTE: If there is no value for a token then the token is removed.
  210. *
  211. * @param string $string
  212. * The string containing tokens.
  213. * @param $record
  214. * A Chado record as generated by chado_generate_var()
  215. *
  216. * @return
  217. * The string will all tokens replaced with values.
  218. */
  219. function tripal_replace_chado_tokens($string, $record) {
  220. // Get the list of tokens
  221. $tokens = tripal_get_chado_tokens($record->tablename);
  222. // Determine which tokens were used in the format string
  223. if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
  224. // Get the value for each token used
  225. foreach ($used_tokens[0] as $token) {
  226. $token_info = $tokens[$token];
  227. if (!empty($token_info)) {
  228. $table = $token_info['table'];
  229. $var = $record;
  230. $value = '';
  231. // Iterate through each portion of the location string. An example string
  232. // might be: stock > type_id > name.
  233. $location = explode('>', $token_info['location']);
  234. foreach ($location as $index) {
  235. $index = trim($index);
  236. // if $var is an object then it is the $node object or a table
  237. // that has been expanded.
  238. if (is_object($var)) {
  239. // check to see if the index is a member of the object. If so,
  240. // then reset the $var to this value.
  241. if (property_exists($var, $index)) {
  242. $value = $var->$index;
  243. }
  244. }
  245. // if the $var is an array then there are multiple instances of the same
  246. // table in a FK relationship (e.g. relationship tables)
  247. elseif (is_array($var)) {
  248. $value = $var[$index];
  249. }
  250. else {
  251. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  252. 'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
  253. 'to access \'%index\' for the following: \'%var\'.',
  254. array('%token' => $token, '%index' => $index, '%var' => print_r($var,TRUE))
  255. );
  256. }
  257. }
  258. $string = str_replace($token, $value, $string);
  259. }
  260. }
  261. }
  262. return $string;
  263. }