tripal_chado.api.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. * @ingroup tripal_chado_api
  18. */
  19. function tripal_chado_publish_records($values, $job_id = NULL) {
  20. // We want the job object in order to report progress.
  21. if (is_object($job_id)) {
  22. $job = $job_id;
  23. }
  24. if (is_numeric($job_id)) {
  25. $job = new TripalJob();
  26. $job->load($job_id);
  27. }
  28. $report_progress = FALSE;
  29. if (is_object($job)) {
  30. $report_progress = TRUE;
  31. }
  32. // Make sure we have the required options: bundle_name.
  33. if (!array_key_exists('bundle_name', $values) or !$values['bundle_name']) {
  34. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  35. "Could not publish record: @error",
  36. array('@error' => 'The bundle name must be provided'));
  37. return FALSE;
  38. }
  39. // Get the incoming arguments from the $values array.
  40. $bundle_name = $values['bundle_name'];
  41. $filters = array_key_exists('filters', $values) ? $values['filters'] : array();
  42. $sync_node = array_key_exists('sync_node', $values) ? $values['sync_node'] : '';
  43. // Load the bundle entity so we can get information about which Chado
  44. // table/field this entity belongs to.
  45. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  46. if (!$bundle) {
  47. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  48. "Unknown bundle. Could not publish record: @error",
  49. array('@error' => 'The bundle name must be provided'));
  50. return FALSE;
  51. }
  52. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  53. // Get the mapping of the bio data type to the Chado table.
  54. $chado_bundle = db_select('chado_bundle', 'cb')
  55. ->fields('cb')
  56. ->condition('bundle_id', $bundle->id)
  57. ->execute()
  58. ->fetchObject();
  59. if(!$chado_bundle) {
  60. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  61. "Cannot find mapping of bundle to Chado tables. Could not publish record.");
  62. return FALSE;
  63. }
  64. $table = $chado_bundle->data_table;
  65. $type_column = $chado_bundle->type_column;
  66. $type_linker_table = $chado_bundle->type_linker_table;
  67. $cvterm_id = $chado_bundle->type_id;
  68. $type_value = $chado_bundle->type_value;
  69. // Get the table information for the Chado table.
  70. $table_schema = chado_get_schema($table);
  71. $pkey_field = $table_schema['primary key'][0];
  72. // Construct the SQL for identifying which records should be published.
  73. $args = array();
  74. $select = "SELECT T.$pkey_field as record_id ";
  75. $from = "
  76. FROM {" . $table . "} T
  77. LEFT JOIN [" . $chado_entity_table . "] CE on CE.record_id = T.$pkey_field
  78. ";
  79. // For migration of Tripal v2 nodes to entities we want to include the
  80. // coresponding chado linker table.
  81. if ($sync_node && db_table_exists('chado_' . $table)) {
  82. $select = "SELECT T.$pkey_field as record_id, CT.nid ";
  83. $from .= " INNER JOIN [chado_" . $table . "] CT ON CT.$pkey_field = T.$pkey_field";
  84. }
  85. $where = " WHERE CE.record_id IS NULL ";
  86. // Handle records that are mapped to property tables.
  87. if ($type_linker_table and $type_column and $type_value) {
  88. $propschema = chado_get_schema($type_linker_table);
  89. $fkeys = $propschema['foreign keys'][$table]['columns'];
  90. foreach ($fkeys as $leftkey => $rightkey) {
  91. if ($rightkey == $pkey_field) {
  92. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  93. }
  94. }
  95. $where .= "AND LT.$type_column = :cvterm_id and LT.value = :prop_value";
  96. $args[':cvterm_id'] = $cvterm_id;
  97. $args[':prop_value'] = $type_value;
  98. }
  99. // Handle records that are mapped to cvterm linking tables.
  100. if ($type_linker_table and $type_column and !$type_value) {
  101. $cvtschema = chado_get_schema($type_linker_table);
  102. $fkeys = $cvtschema['foreign keys'][$table]['columns'];
  103. foreach ($fkeys as $leftkey => $rightkey) {
  104. if ($rightkey == $pkey_field) {
  105. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  106. }
  107. }
  108. $where .= "AND LT.$type_column = :cvterm_id";
  109. $args[':cvterm_id'] = $cvterm_id;
  110. }
  111. // Handle records that are mapped via a type_id column in the base table.
  112. if (!$type_linker_table and $type_column) {
  113. $where .= "AND T.$type_column = :cvterm_id";
  114. $args[':cvterm_id'] = $cvterm_id;
  115. }
  116. // Handle the case where records are in the cvterm table and mapped via a single
  117. // vocab. Here we use the type_value for the cv_id.
  118. if ($table == 'cvterm' and $type_value) {
  119. $where .= "AND T.cv_id = :cv_id";
  120. $args[':cv_id'] = $type_value;
  121. }
  122. // Handle the case where records are in the cvterm table but we want to
  123. // use all of the child terms.
  124. if ($table == 'cvterm' and !$type_value) {
  125. $where .= "AND T.cvterm_id IN (
  126. SELECT CVTP.subject_id
  127. FROM {cvtermpath} CVTP
  128. WHERE CVTP.object_id = :cvterm_id)
  129. ";
  130. $args[':cvterm_id'] = $cvterm_id;
  131. }
  132. // Now add in any additional filters
  133. $fields = field_info_field_map();
  134. foreach ($fields as $field_name => $details) {
  135. if (array_key_exists('TripalEntity', $details['bundles']) and
  136. in_array($bundle_name, $details['bundles']['TripalEntity']) and
  137. in_array($field_name, array_keys($filters))){
  138. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  139. $chado_table = $instance['settings']['chado_table'];
  140. $chado_column = $instance['settings']['chado_column'];
  141. if ($chado_table == $table) {
  142. $where .= " AND T.$chado_column = :$field_name";
  143. $args[":$field_name"] = $filters[$field_name];
  144. }
  145. }
  146. }
  147. // First get the count
  148. $sql = "SELECT count(*) as num_records " . $from . $where;
  149. $result = chado_query($sql, $args);
  150. $count = $result->fetchField();
  151. // calculate the interval for updates
  152. $interval = intval($count / 50);
  153. if ($interval < 1) {
  154. $interval = 1;
  155. }
  156. // Perform the query.
  157. $sql = $select . $from . $where;
  158. $records = chado_query($sql, $args);
  159. $transaction = db_transaction();
  160. print "\nNOTE: publishing records is performed using a database transaction. \n" .
  161. "If the load fails or is terminated prematurely then the entire set of \n" .
  162. "is rolled back with no changes to the database\n\n";
  163. $i = 0;
  164. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, 0, number_format(memory_get_usage()));
  165. try {
  166. while($record = $records->fetchObject()) {
  167. // update the job status every interval
  168. if ($i % $interval == 0) {
  169. $complete = ($i / $count) * 33.33333333;
  170. // Currently don't support setting job progress within a transaction.
  171. // if ($report_progress) { $job->setProgress(intval($complete * 3)); }
  172. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  173. }
  174. // First save the tripal_entity record.
  175. $record_id = $record->record_id;
  176. $ec = entity_get_controller('TripalEntity');
  177. $entity = $ec->create(array(
  178. 'bundle' => $bundle_name,
  179. 'term_id' => $bundle->term_id,
  180. // Add in the Chado details for when the hook_entity_create()
  181. // is called and our tripal_chado_entity_create() implementation
  182. // can deal with it.
  183. 'chado_record' => chado_generate_var($table, array($pkey_field => $record_id)),
  184. 'chado_record_id' => $record_id,
  185. ));
  186. $entity = $entity->save();
  187. if (!$entity) {
  188. throw new Exception('Could not create entity.');
  189. }
  190. // Next save the chado entity record.
  191. $entity_record = array(
  192. 'entity_id' => $entity->id,
  193. 'record_id' => $record_id,
  194. );
  195. // For the Tv2 to Tv3 migration we want to add the nid to the
  196. // entity so we can associate the node with the entity.
  197. if (property_exists($record, 'nid')) {
  198. $entity_record['nid'] = $record->nid;
  199. }
  200. $result = db_insert($chado_entity_table)
  201. ->fields($entity_record)
  202. ->execute();
  203. if(!$result){
  204. throw new Exception('Could not create mapping of entity to Chado record.');
  205. }
  206. $i++;
  207. }
  208. }
  209. catch (Exception $e) {
  210. $transaction->rollback();
  211. $error = $e->getMessage();
  212. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not publish record: @error", array('@error' => $error));
  213. drupal_set_message('Failed publishing record. See recent logs for more details.', 'error');
  214. return FALSE;
  215. }
  216. drupal_set_message("Succesfully published $i " . $bundle->label . " record(s).");
  217. return TRUE;
  218. }
  219. /**
  220. * Returns an array of tokens based on Tripal Entity Fields.
  221. *
  222. * @param $base_table
  223. * The name of a base table in Chado.
  224. * @return
  225. * An array of tokens where the key is the machine_name of the token.
  226. */
  227. function tripal_get_chado_tokens($base_table) {
  228. $tokens = array();
  229. $table_descrip = chado_get_schema($base_table);
  230. foreach ($table_descrip['fields'] as $field_name => $field_details) {
  231. $token = '[' . $base_table . '.' . $field_name . ']';
  232. $location = implode(' > ',array($base_table, $field_name));
  233. $tokens[$token] = array(
  234. 'name' => ucwords(str_replace('_',' ',$base_table)) . ': ' . ucwords(str_replace('_',' ',$field_name)),
  235. 'table' => $base_table,
  236. 'field' => $field_name,
  237. 'token' => $token,
  238. 'description' => array_key_exists('description', $field_details) ? $field_details['description'] : '',
  239. 'location' => $location
  240. );
  241. if (!array_key_exists('description', $field_details) or preg_match('/TODO/',$field_details['description'])) {
  242. $tokens[$token]['description'] = 'The '.$field_name.' field of the '.$base_table.' table.';
  243. }
  244. }
  245. // RECURSION:
  246. // Follow the foreign key relationships recursively
  247. if (array_key_exists('foreign keys', $table_descrip)) {
  248. foreach ($table_descrip['foreign keys'] as $table => $details) {
  249. foreach ($details['columns'] as $left_field => $right_field) {
  250. $sub_token_prefix = $base_table . '.' . $left_field;
  251. $sub_location_prefix = implode(' > ',array($base_table, $left_field));
  252. $sub_tokens = tripal_get_chado_tokens($table);
  253. if (is_array($sub_tokens)) {
  254. $tokens = array_merge($tokens, $sub_tokens);
  255. }
  256. }
  257. }
  258. }
  259. return $tokens;
  260. }
  261. /**
  262. * Replace all Chado Tokens in a given string.
  263. *
  264. * NOTE: If there is no value for a token then the token is removed.
  265. *
  266. * @param string $string
  267. * The string containing tokens.
  268. * @param $record
  269. * A Chado record as generated by chado_generate_var()
  270. *
  271. * @return
  272. * The string will all tokens replaced with values.
  273. */
  274. function tripal_replace_chado_tokens($string, $record) {
  275. // Get the list of tokens
  276. $tokens = tripal_get_chado_tokens($record->tablename);
  277. // Determine which tokens were used in the format string
  278. if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
  279. // Get the value for each token used
  280. foreach ($used_tokens[0] as $token) {
  281. $token_info = $tokens[$token];
  282. if (!empty($token_info)) {
  283. $table = $token_info['table'];
  284. $var = $record;
  285. $value = '';
  286. // Iterate through each portion of the location string. An example string
  287. // might be: stock > type_id > name.
  288. $location = explode('>', $token_info['location']);
  289. foreach ($location as $index) {
  290. $index = trim($index);
  291. // if $var is an object then it is the $node object or a table
  292. // that has been expanded.
  293. if (is_object($var)) {
  294. // check to see if the index is a member of the object. If so,
  295. // then reset the $var to this value.
  296. if (property_exists($var, $index)) {
  297. $value = $var->$index;
  298. }
  299. }
  300. // if the $var is an array then there are multiple instances of the same
  301. // table in a FK relationship (e.g. relationship tables)
  302. elseif (is_array($var)) {
  303. $value = $var[$index];
  304. }
  305. else {
  306. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  307. 'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
  308. 'to access \'%index\' for the following: \'%var\'.',
  309. array('%token' => $token, '%index' => $index, '%var' => print_r($var,TRUE))
  310. );
  311. }
  312. }
  313. $string = str_replace($token, $value, $string);
  314. }
  315. }
  316. }
  317. return $string;
  318. }