tripal_chado.api.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /**
  3. * @file
  4. *
  5. * This file contains miscellaneous API functions specific to working with
  6. * records in Chado that do not have a home in any other sub category of
  7. * API functions.
  8. */
  9. /**
  10. * @defgroup tripal_chado_api Chado
  11. *
  12. * @ingroup tripal_api
  13. * The Tripal Chado API is a set of functions for interacting with data
  14. * inside of a Chado relational database. Entities (or pages) in Drupal
  15. * that are provided by Tripal can supply data from any supported database
  16. * back-end, and Chado is the default. This API contains a variety of sub
  17. * categories (or groups) where functions are organized. Any extension module
  18. * that desires to work with data in Chado will find these functions useful.
  19. */
  20. /**
  21. * Publishes content in Chado as a new TripalEntity entity.
  22. *
  23. * @param $values
  24. * A key/value associative array that supports the following keys:
  25. * - bundle_name: The name of the the TripalBundle (e.g. bio_data-12345).
  26. * @param $job_id
  27. * (Optional) The numeric job ID as provided by the Tripal jobs system. There
  28. * is no need to specify this argument if this function is being called
  29. * outside of the jobs systems.
  30. *
  31. * @return boolean
  32. * TRUE if all of the records of the given bundle type were published, and
  33. * FALSE if a failure occured.
  34. *
  35. * @ingroup tripal_chado_api
  36. */
  37. function chado_publish_records($values, $job_id = NULL) {
  38. // @performance remove after development
  39. $started_at = microtime(true);
  40. // We want the job object in order to report progress.
  41. if (is_object($job_id)) {
  42. $job = $job_id;
  43. }
  44. if (is_numeric($job_id)) {
  45. $job = new TripalJob();
  46. $job->load($job_id);
  47. }
  48. $report_progress = FALSE;
  49. if (is_object($job)) {
  50. $report_progress = TRUE;
  51. }
  52. // Start an array for caching objects to save performance.
  53. $cache = array();
  54. // Make sure we have the required options: bundle_name.
  55. if (!array_key_exists('bundle_name', $values) or !$values['bundle_name']) {
  56. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  57. "Could not publish record: @error",
  58. array('@error' => 'The bundle name must be provided'));
  59. return FALSE;
  60. }
  61. // Get the incoming arguments from the $values array.
  62. $bundle_name = $values['bundle_name'];
  63. $filters = array_key_exists('filters', $values) ? $values['filters'] : array();
  64. $sync_node = array_key_exists('sync_node', $values) ? $values['sync_node'] : '';
  65. // We want to break the number of records to publish into chunks in order to ensure
  66. // transactions do not run for too long (performance issue). The number of records
  67. // to be processed per chunk is set here:
  68. $chunk_size = 500;
  69. // Load the bundle entity so we can get information about which Chado
  70. // table/field this entity belongs to.
  71. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  72. $cache['bundle'] = $bundle;
  73. if (!$bundle) {
  74. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  75. "Unknown bundle. Could not publish record: @error",
  76. array('@error' => 'The bundle name must be provided'));
  77. return FALSE;
  78. }
  79. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  80. // Get the mapping of the bio data type to the Chado table.
  81. $chado_bundle = db_select('chado_bundle', 'cb')
  82. ->fields('cb')
  83. ->condition('bundle_id', $bundle->id)
  84. ->execute()
  85. ->fetchObject();
  86. if(!$chado_bundle) {
  87. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  88. "Cannot find mapping of bundle to Chado tables. Could not publish record.");
  89. return FALSE;
  90. }
  91. // Load the term for use in setting the alias for each entity created.
  92. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  93. $cache['term'] = $term;
  94. $table = $chado_bundle->data_table;
  95. $type_column = $chado_bundle->type_column;
  96. $type_linker_table = $chado_bundle->type_linker_table;
  97. $cvterm_id = $chado_bundle->type_id;
  98. $type_value = $chado_bundle->type_value;
  99. // Get the table information for the Chado table.
  100. $table_schema = chado_get_schema($table);
  101. $pkey_field = $table_schema['primary key'][0];
  102. // Construct the SQL for identifying which records should be published.
  103. // @performance find a way to optimize this?
  104. $args = array();
  105. $select = "SELECT T.$pkey_field as record_id ";
  106. $from = "
  107. FROM {" . $table . "} T
  108. LEFT JOIN [" . $chado_entity_table . "] CE on CE.record_id = T.$pkey_field
  109. ";
  110. // For migration of Tripal v2 nodes to entities we want to include the
  111. // coresponding chado linker table.
  112. if ($sync_node && db_table_exists('chado_' . $table)) {
  113. $select = "SELECT T.$pkey_field as record_id, CT.nid ";
  114. $from .= " INNER JOIN [chado_" . $table . "] CT ON CT.$pkey_field = T.$pkey_field";
  115. }
  116. $where = " WHERE CE.record_id IS NULL ";
  117. // Handle records that are mapped to property tables.
  118. if ($type_linker_table and $type_column and $type_value) {
  119. $propschema = chado_get_schema($type_linker_table);
  120. $fkeys = $propschema['foreign keys'][$table]['columns'];
  121. foreach ($fkeys as $leftkey => $rightkey) {
  122. if ($rightkey == $pkey_field) {
  123. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  124. }
  125. }
  126. $where .= "AND LT.$type_column = :cvterm_id and LT.value = :prop_value";
  127. $args[':cvterm_id'] = $cvterm_id;
  128. $args[':prop_value'] = $type_value;
  129. }
  130. // Handle records that are mapped to cvterm linking tables.
  131. if ($type_linker_table and $type_column and !$type_value) {
  132. $cvtschema = chado_get_schema($type_linker_table);
  133. $fkeys = $cvtschema['foreign keys'][$table]['columns'];
  134. foreach ($fkeys as $leftkey => $rightkey) {
  135. if ($rightkey == $pkey_field) {
  136. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  137. }
  138. }
  139. $where .= "AND LT.$type_column = :cvterm_id";
  140. $args[':cvterm_id'] = $cvterm_id;
  141. }
  142. // Handle records that are mapped via a type_id column in the base table.
  143. if (!$type_linker_table and $type_column) {
  144. $where .= "AND T.$type_column = :cvterm_id";
  145. $args[':cvterm_id'] = $cvterm_id;
  146. }
  147. // Handle the case where records are in the cvterm table and mapped via a single
  148. // vocab. Here we use the type_value for the cv_id.
  149. if ($table == 'cvterm' and $type_value) {
  150. $where .= "AND T.cv_id = :cv_id";
  151. $args[':cv_id'] = $type_value;
  152. }
  153. // Handle the case where records are in the cvterm table but we want to
  154. // use all of the child terms.
  155. if ($table == 'cvterm' and !$type_value) {
  156. $where .= "AND T.cvterm_id IN (
  157. SELECT CVTP.subject_id
  158. FROM {cvtermpath} CVTP
  159. WHERE CVTP.object_id = :cvterm_id)
  160. ";
  161. $args[':cvterm_id'] = $cvterm_id;
  162. }
  163. // Now add in any additional filters
  164. $fields = field_info_field_map();
  165. foreach ($fields as $field_name => $details) {
  166. if (array_key_exists('TripalEntity', $details['bundles']) and
  167. in_array($bundle_name, $details['bundles']['TripalEntity']) and
  168. in_array($field_name, array_keys($filters))){
  169. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  170. $chado_table = $instance['settings']['chado_table'];
  171. $chado_column = $instance['settings']['chado_column'];
  172. if ($chado_table == $table) {
  173. $where .= " AND T.$chado_column = :$field_name";
  174. $args[":$field_name"] = $filters[$field_name];
  175. }
  176. }
  177. }
  178. // First get the count
  179. // @performance optimize, estimate or remove this. It's only used for reporting progress on the command-line.
  180. $sql = "SELECT count(*) as num_records " . $from . $where;
  181. $result = chado_query($sql, $args);
  182. $count = $result->fetchField();
  183. print "\nThere are $count records to publish.\n";
  184. print "\nNOTE: publishing records is performed using database transactions. If the job fails\n" .
  185. "or is terminated prematurely then the current set of $chunk_size is rolled back with\n" .
  186. "no changes to the database. Simply re-run the publishing job to publish any remaining\n".
  187. "content after fixing the issue that caused the job to fail.\n\n" .
  188. "Also, the following progress only updates every $chunk_size records.\n";
  189. // Perform the query.
  190. $sql = $select . $from . $where . ' LIMIT '.$chunk_size;
  191. $more_records_to_publish = TRUE;
  192. $total_published = 0;
  193. while ($more_records_to_publish) {
  194. // @performance remove after development:0.43729090690613s
  195. // @performance limiting this query DRASTICALLY decreases query execution time: 0.26s
  196. // @performance print 'Perform Query :' . (microtime(true) - $started_at) . "s.\n\n";
  197. $records = chado_query($sql, $args);
  198. // Update the job status every chunk start.
  199. // Because this is outside of hte transaction, we can update the admin through the jobs UI.
  200. $complete = ($total_published / $count) * 33.33333333;
  201. if ($report_progress) { $job->setProgress(intval($complete * 3)); }
  202. if ($total_published === 0) {
  203. printf("%d of %d records. (%0.2f%%) Memory: %s bytes.\r",
  204. $i, $count, 0, number_format(memory_get_usage()), 0);
  205. }
  206. else {
  207. printf("%d of %d records. (%0.2f%%) Memory: %s bytes; Current run time: %s minutes.\r",
  208. $total_published, $count, $complete * 3, number_format(memory_get_usage()), number_format((microtime(true) - $started_at)/60, 2));
  209. }
  210. // @performance evaluate this transaction. Long running transactions can have serious
  211. // performance issues in PostgreSQL. One option is to move the transaction within the
  212. // loop so that each one is not very long but then we end up with more overhead creating
  213. // transactions. A better albeit more complicated approach might be to break the job into
  214. // chunks where each one is a single transaction.
  215. $transaction = db_transaction();
  216. $cache['transaction'] = $transaction;
  217. try {
  218. $i = 0;
  219. while($record = $records->fetchObject()) {
  220. // First save the tripal_entity record.
  221. // @performace This is likely a bottleneck. Too bad we can't create
  222. // multiple entities at once... sort of like the copy method.
  223. $record_id = $record->record_id;
  224. $ec = entity_get_controller('TripalEntity');
  225. $entity = $ec->create(array(
  226. 'bundle' => $bundle_name,
  227. 'term_id' => $bundle->term_id,
  228. // Add in the Chado details for when the hook_entity_create()
  229. // is called and our tripal_chado_entity_create() implementation
  230. // can deal with it.
  231. 'chado_record' => chado_generate_var($table, array($pkey_field => $record_id), array('include_fk' => 0)),
  232. 'chado_record_id' => $record_id,
  233. 'publish' => TRUE,
  234. 'bundle_object' => $bundle,
  235. ));
  236. // We pass in the transaction and tell save not to clear the field cache for
  237. // for performance reasons. We will clear the field cache in bulk below.
  238. // @todo clear the field cache in bulk below ;-p
  239. $cache['clear_cached_fields'] = FALSE;
  240. $entity = $entity->save($cache);
  241. if (!$entity) {
  242. throw new Exception('Could not create entity.');
  243. }
  244. // Next save the chado entity record.
  245. $entity_record = array(
  246. 'entity_id' => $entity->id,
  247. 'record_id' => $record_id,
  248. );
  249. // For the Tv2 to Tv3 migration we want to add the nid to the
  250. // entity so we can associate the node with the entity.
  251. if (property_exists($record, 'nid')) {
  252. $entity_record['nid'] = $record->nid;
  253. }
  254. $result = db_insert($chado_entity_table)
  255. ->fields($entity_record)
  256. ->execute();
  257. if(!$result){
  258. throw new Exception('Could not create mapping of entity to Chado record.');
  259. }
  260. $i++;
  261. $total_published++;
  262. }
  263. }
  264. catch (Exception $e) {
  265. $transaction->rollback();
  266. $error = $e->getMessage();
  267. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not publish record: @error", array('@error' => $error));
  268. drupal_set_message('Failed publishing record. See recent logs for more details.', 'error');
  269. return FALSE;
  270. }
  271. // If we get through the loop and haven't completed 100 records, then we're done!
  272. if ($i < $chunk_size) {
  273. $more_records_to_publish = FALSE;
  274. }
  275. // Commit our current chunk.
  276. unset($transaction);
  277. }
  278. drupal_set_message("Succesfully published $total_published " . $bundle->label . " record(s).");
  279. return TRUE;
  280. }
  281. /**
  282. * Returns an array of tokens based on Tripal Entity Fields.
  283. *
  284. * @param $base_table
  285. * The name of a base table in Chado.
  286. * @return
  287. * An array of tokens where the key is the machine_name of the token.
  288. *
  289. * @ingroup tripal_chado_api
  290. */
  291. function chado_get_tokens($base_table) {
  292. $tokens = array();
  293. $table_descrip = chado_get_schema($base_table);
  294. foreach ($table_descrip['fields'] as $field_name => $field_details) {
  295. $token = '[' . $base_table . '.' . $field_name . ']';
  296. $location = implode(' > ',array($base_table, $field_name));
  297. $tokens[$token] = array(
  298. 'name' => ucwords(str_replace('_',' ',$base_table)) . ': ' . ucwords(str_replace('_',' ',$field_name)),
  299. 'table' => $base_table,
  300. 'field' => $field_name,
  301. 'token' => $token,
  302. 'description' => array_key_exists('description', $field_details) ? $field_details['description'] : '',
  303. 'location' => $location
  304. );
  305. if (!array_key_exists('description', $field_details) or preg_match('/TODO/',$field_details['description'])) {
  306. $tokens[$token]['description'] = 'The '.$field_name.' field of the '.$base_table.' table.';
  307. }
  308. }
  309. // RECURSION:
  310. // Follow the foreign key relationships recursively
  311. if (array_key_exists('foreign keys', $table_descrip)) {
  312. foreach ($table_descrip['foreign keys'] as $table => $details) {
  313. foreach ($details['columns'] as $left_field => $right_field) {
  314. $sub_token_prefix = $base_table . '.' . $left_field;
  315. $sub_location_prefix = implode(' > ',array($base_table, $left_field));
  316. $sub_tokens = chado_get_tokens($table);
  317. if (is_array($sub_tokens)) {
  318. $tokens = array_merge($tokens, $sub_tokens);
  319. }
  320. }
  321. }
  322. }
  323. return $tokens;
  324. }
  325. /**
  326. * Replace all Chado Tokens in a given string.
  327. *
  328. * NOTE: If there is no value for a token then the token is removed.
  329. *
  330. * @param string $string
  331. * The string containing tokens.
  332. * @param $record
  333. * A Chado record as generated by chado_generate_var()
  334. *
  335. * @return
  336. * The string will all tokens replaced with values.
  337. *
  338. * @ingroup tripal_chado_api
  339. */
  340. function chado_replace_tokens($string, $record) {
  341. // Get the list of tokens
  342. $tokens = chado_get_tokens($record->tablename);
  343. // Determine which tokens were used in the format string
  344. if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
  345. // Get the value for each token used
  346. foreach ($used_tokens[0] as $token) {
  347. $token_info = $tokens[$token];
  348. if (!empty($token_info)) {
  349. $table = $token_info['table'];
  350. $var = $record;
  351. $value = '';
  352. // Iterate through each portion of the location string. An example string
  353. // might be: stock > type_id > name.
  354. $location = explode('>', $token_info['location']);
  355. foreach ($location as $index) {
  356. $index = trim($index);
  357. // if $var is an object then it is the $node object or a table
  358. // that has been expanded.
  359. if (is_object($var)) {
  360. // check to see if the index is a member of the object. If so,
  361. // then reset the $var to this value.
  362. if (property_exists($var, $index)) {
  363. $value = $var->$index;
  364. }
  365. }
  366. // if the $var is an array then there are multiple instances of the same
  367. // table in a FK relationship (e.g. relationship tables)
  368. elseif (is_array($var)) {
  369. $value = $var[$index];
  370. }
  371. else {
  372. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  373. 'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
  374. 'to access \'%index\' for the following: \'%var\'.',
  375. array('%token' => $token, '%index' => $index, '%var' => print_r($var,TRUE))
  376. );
  377. }
  378. }
  379. $string = str_replace($token, $value, $string);
  380. }
  381. }
  382. }
  383. return $string;
  384. }