tripal_chado.api.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. // Used for adding runtime to the progress report.
  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. $args = array();
  104. $select = "SELECT T.$pkey_field as record_id ";
  105. $from = "
  106. FROM {" . $table . "} T
  107. LEFT JOIN [" . $chado_entity_table . "] CE on CE.record_id = T.$pkey_field
  108. ";
  109. // For migration of Tripal v2 nodes to entities we want to include the
  110. // coresponding chado linker table.
  111. if ($sync_node && db_table_exists('chado_' . $table)) {
  112. $select = "SELECT T.$pkey_field as record_id, CT.nid ";
  113. $from .= " INNER JOIN [chado_" . $table . "] CT ON CT.$pkey_field = T.$pkey_field";
  114. }
  115. $where = " WHERE CE.record_id IS NULL ";
  116. // Handle records that are mapped to property tables.
  117. if ($type_linker_table and $type_column and $type_value) {
  118. $propschema = chado_get_schema($type_linker_table);
  119. $fkeys = $propschema['foreign keys'][$table]['columns'];
  120. foreach ($fkeys as $leftkey => $rightkey) {
  121. if ($rightkey == $pkey_field) {
  122. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  123. }
  124. }
  125. $where .= "AND LT.$type_column = :cvterm_id and LT.value = :prop_value";
  126. $args[':cvterm_id'] = $cvterm_id;
  127. $args[':prop_value'] = $type_value;
  128. }
  129. // Handle records that are mapped to cvterm linking tables.
  130. if ($type_linker_table and $type_column and !$type_value) {
  131. $cvtschema = chado_get_schema($type_linker_table);
  132. $fkeys = $cvtschema['foreign keys'][$table]['columns'];
  133. foreach ($fkeys as $leftkey => $rightkey) {
  134. if ($rightkey == $pkey_field) {
  135. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  136. }
  137. }
  138. $where .= "AND LT.$type_column = :cvterm_id";
  139. $args[':cvterm_id'] = $cvterm_id;
  140. }
  141. // Handle records that are mapped via a type_id column in the base table.
  142. if (!$type_linker_table and $type_column) {
  143. $where .= "AND T.$type_column = :cvterm_id";
  144. $args[':cvterm_id'] = $cvterm_id;
  145. }
  146. // Handle the case where records are in the cvterm table and mapped via a single
  147. // vocab. Here we use the type_value for the cv_id.
  148. if ($table == 'cvterm' and $type_value) {
  149. $where .= "AND T.cv_id = :cv_id";
  150. $args[':cv_id'] = $type_value;
  151. }
  152. // Handle the case where records are in the cvterm table but we want to
  153. // use all of the child terms.
  154. if ($table == 'cvterm' and !$type_value) {
  155. $where .= "AND T.cvterm_id IN (
  156. SELECT CVTP.subject_id
  157. FROM {cvtermpath} CVTP
  158. WHERE CVTP.object_id = :cvterm_id)
  159. ";
  160. $args[':cvterm_id'] = $cvterm_id;
  161. }
  162. // Now add in any additional filters
  163. $fields = field_info_field_map();
  164. foreach ($fields as $field_name => $details) {
  165. if (array_key_exists('TripalEntity', $details['bundles']) and
  166. in_array($bundle_name, $details['bundles']['TripalEntity']) and
  167. in_array($field_name, array_keys($filters))){
  168. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  169. $chado_table = $instance['settings']['chado_table'];
  170. $chado_column = $instance['settings']['chado_column'];
  171. if ($chado_table == $table) {
  172. $where .= " AND T.$chado_column = :$field_name";
  173. $args[":$field_name"] = $filters[$field_name];
  174. }
  175. }
  176. }
  177. // First get the count
  178. // @performance optimize, estimate or remove this. It's only used for reporting progress on the command-line.
  179. $sql = "SELECT count(*) as num_records " . $from . $where;
  180. $result = chado_query($sql, $args);
  181. $count = $result->fetchField();
  182. print "\nThere are $count records to publish.\n";
  183. print "\nNOTE: publishing records is performed using database transactions. If the job fails\n" .
  184. "or is terminated prematurely then the current set of $chunk_size is rolled back with\n" .
  185. "no changes to the database. Simply re-run the publishing job to publish any remaining\n".
  186. "content after fixing the issue that caused the job to fail.\n\n" .
  187. "Also, the following progress only updates every $chunk_size records.\n";
  188. // Perform the query.
  189. $sql = $select . $from . $where . ' LIMIT '.$chunk_size;
  190. $more_records_to_publish = TRUE;
  191. $total_published = 0;
  192. while ($more_records_to_publish) {
  193. $records = chado_query($sql, $args);
  194. // Update the job status every chunk start.
  195. // Because this is outside of hte transaction, we can update the admin through the jobs UI.
  196. $complete = ($total_published / $count) * 33.33333333;
  197. if ($report_progress) { $job->setProgress(intval($complete * 3)); }
  198. if ($total_published === 0) {
  199. printf("%d of %d records. (%0.2f%%) Memory: %s bytes.\r",
  200. $i, $count, 0, number_format(memory_get_usage()), 0);
  201. }
  202. else {
  203. printf("%d of %d records. (%0.2f%%) Memory: %s bytes; Current run time: %s minutes.\r",
  204. $total_published, $count, $complete * 3, number_format(memory_get_usage()), number_format((microtime(true) - $started_at)/60, 2));
  205. }
  206. // There is no need to cache transactions since Drupal handles nested transactions
  207. // "by performing no transactional operations (as far as the database sees) within
  208. // the inner nesting layers". Effectively, Drupal ensures nested trasactions work the
  209. // same as passing a transaction through to the deepest level and not starting a new
  210. // transaction if we are already in one.
  211. $transaction = db_transaction();
  212. try {
  213. $i = 0;
  214. while($record = $records->fetchObject()) {
  215. // First save the tripal_entity record.
  216. // @performace This is likely a bottleneck. Too bad we can't create
  217. // multiple entities at once... sort of like the copy method.
  218. $record_id = $record->record_id;
  219. $ec = entity_get_controller('TripalEntity');
  220. $entity = $ec->create(array(
  221. 'bundle' => $bundle_name,
  222. 'term_id' => $bundle->term_id,
  223. // Add in the Chado details for when the hook_entity_create()
  224. // is called and our tripal_chado_entity_create() implementation
  225. // can deal with it.
  226. 'chado_record' => chado_generate_var($table, array($pkey_field => $record_id), array('include_fk' => 0)),
  227. 'chado_record_id' => $record_id,
  228. 'publish' => TRUE,
  229. 'bundle_object' => $bundle,
  230. ));
  231. $entity = $entity->save($cache);
  232. if (!$entity) {
  233. throw new Exception('Could not create entity.');
  234. }
  235. // Next save the chado entity record.
  236. $entity_record = array(
  237. 'entity_id' => $entity->id,
  238. 'record_id' => $record_id,
  239. );
  240. // For the Tv2 to Tv3 migration we want to add the nid to the
  241. // entity so we can associate the node with the entity.
  242. if (property_exists($record, 'nid')) {
  243. $entity_record['nid'] = $record->nid;
  244. }
  245. $result = db_insert($chado_entity_table)
  246. ->fields($entity_record)
  247. ->execute();
  248. if(!$result){
  249. throw new Exception('Could not create mapping of entity to Chado record.');
  250. }
  251. $i++;
  252. $total_published++;
  253. }
  254. }
  255. catch (Exception $e) {
  256. $transaction->rollback();
  257. $error = $e->getMessage();
  258. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not publish record: @error", array('@error' => $error));
  259. drupal_set_message('Failed publishing record. See recent logs for more details.', 'error');
  260. return FALSE;
  261. }
  262. // If we get through the loop and haven't completed 100 records, then we're done!
  263. if ($i < $chunk_size) {
  264. $more_records_to_publish = FALSE;
  265. }
  266. // Commit our current chunk.
  267. unset($transaction);
  268. }
  269. drupal_set_message("Succesfully published $total_published " . $bundle->label . " record(s).");
  270. return TRUE;
  271. }
  272. /**
  273. * Returns an array of tokens based on Tripal Entity Fields.
  274. *
  275. * @param $base_table
  276. * The name of a base table in Chado.
  277. * @return
  278. * An array of tokens where the key is the machine_name of the token.
  279. *
  280. * @ingroup tripal_chado_api
  281. */
  282. function chado_get_tokens($base_table) {
  283. $tokens = array();
  284. $table_descrip = chado_get_schema($base_table);
  285. foreach ($table_descrip['fields'] as $field_name => $field_details) {
  286. $token = '[' . $base_table . '.' . $field_name . ']';
  287. $location = implode(' > ',array($base_table, $field_name));
  288. $tokens[$token] = array(
  289. 'name' => ucwords(str_replace('_',' ',$base_table)) . ': ' . ucwords(str_replace('_',' ',$field_name)),
  290. 'table' => $base_table,
  291. 'field' => $field_name,
  292. 'token' => $token,
  293. 'description' => array_key_exists('description', $field_details) ? $field_details['description'] : '',
  294. 'location' => $location
  295. );
  296. if (!array_key_exists('description', $field_details) or preg_match('/TODO/',$field_details['description'])) {
  297. $tokens[$token]['description'] = 'The '.$field_name.' field of the '.$base_table.' table.';
  298. }
  299. }
  300. // RECURSION:
  301. // Follow the foreign key relationships recursively
  302. if (array_key_exists('foreign keys', $table_descrip)) {
  303. foreach ($table_descrip['foreign keys'] as $table => $details) {
  304. foreach ($details['columns'] as $left_field => $right_field) {
  305. $sub_token_prefix = $base_table . '.' . $left_field;
  306. $sub_location_prefix = implode(' > ',array($base_table, $left_field));
  307. $sub_tokens = chado_get_tokens($table);
  308. if (is_array($sub_tokens)) {
  309. $tokens = array_merge($tokens, $sub_tokens);
  310. }
  311. }
  312. }
  313. }
  314. return $tokens;
  315. }
  316. /**
  317. * Replace all Chado Tokens in a given string.
  318. *
  319. * NOTE: If there is no value for a token then the token is removed.
  320. *
  321. * @param string $string
  322. * The string containing tokens.
  323. * @param $record
  324. * A Chado record as generated by chado_generate_var()
  325. *
  326. * @return
  327. * The string will all tokens replaced with values.
  328. *
  329. * @ingroup tripal_chado_api
  330. */
  331. function chado_replace_tokens($string, $record) {
  332. // Get the list of tokens
  333. $tokens = chado_get_tokens($record->tablename);
  334. // Determine which tokens were used in the format string
  335. if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
  336. // Get the value for each token used
  337. foreach ($used_tokens[0] as $token) {
  338. $token_info = $tokens[$token];
  339. if (!empty($token_info)) {
  340. $table = $token_info['table'];
  341. $var = $record;
  342. $value = '';
  343. // Iterate through each portion of the location string. An example string
  344. // might be: stock > type_id > name.
  345. $location = explode('>', $token_info['location']);
  346. foreach ($location as $index) {
  347. $index = trim($index);
  348. // if $var is an object then it is the $node object or a table
  349. // that has been expanded.
  350. if (is_object($var)) {
  351. // check to see if the index is a member of the object. If so,
  352. // then reset the $var to this value.
  353. if (property_exists($var, $index)) {
  354. $value = $var->$index;
  355. }
  356. }
  357. // if the $var is an array then there are multiple instances of the same
  358. // table in a FK relationship (e.g. relationship tables)
  359. elseif (is_array($var)) {
  360. $value = $var[$index];
  361. }
  362. else {
  363. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  364. 'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
  365. 'to access \'%index\' for the following: \'%var\'.',
  366. array('%token' => $token, '%index' => $index, '%var' => print_r($var,TRUE))
  367. );
  368. }
  369. }
  370. $string = str_replace($token, $value, $string);
  371. }
  372. }
  373. }
  374. return $string;
  375. }