tripal_chado.api.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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
  27. * The jobs management object for the job if this function is run as a job.
  28. * This argument is added by Tripal during a job run and is not needed if
  29. * this function is run directly.
  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 = 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 with the job.
  41. if (is_numeric($job)) {
  42. $job_id = $job;
  43. $job = new TripalJob();
  44. $job->load($job_id);
  45. }
  46. // These are options for the tripal_report_error function. We do not
  47. // want to log messages to the watchdog but we do for the job and to
  48. // the terminal
  49. $message_type = 'publish_records';
  50. $message_opts = [
  51. 'watchdog' == FALSE,
  52. 'job' => $job,
  53. 'print' => TRUE,
  54. ];
  55. // Start an array for caching objects to save performance.
  56. $cache = array();
  57. // Make sure we have the required options: bundle_name.
  58. if (!array_key_exists('bundle_name', $values) or !$values['bundle_name']) {
  59. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  60. "Could not publish record: @error",
  61. ['@error' => 'The bundle name must be provided'], $message_opts);
  62. return FALSE;
  63. }
  64. // Get the incoming arguments from the $values array.
  65. $bundle_name = $values['bundle_name'];
  66. $filters = array_key_exists('filters', $values) ? $values['filters'] : array();
  67. $sync_node = array_key_exists('sync_node', $values) ? $values['sync_node'] : '';
  68. // We want to break the number of records to publish into chunks in order to ensure
  69. // transactions do not run for too long (performance issue). The number of records
  70. // to be processed per chunk is set here:
  71. $chunk_size = 500;
  72. // Load the bundle entity so we can get information about which Chado
  73. // table/field this entity belongs to.
  74. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  75. $cache['bundle'] = $bundle;
  76. if (!$bundle) {
  77. tripal_report_error($message_type, TRIPAL_ERROR,
  78. "Unknown bundle. Could not publish record: @error",
  79. ['@error' => 'The bundle name must be provided'], $message_opts);
  80. return FALSE;
  81. }
  82. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  83. // Get the mapping of the bio data type to the Chado table.
  84. $chado_bundle = db_select('chado_bundle', 'cb')
  85. ->fields('cb')
  86. ->condition('bundle_id', $bundle->id)
  87. ->execute()
  88. ->fetchObject();
  89. if(!$chado_bundle) {
  90. tripal_report_error($message_type, TRIPAL_ERROR,
  91. "Cannot find mapping of bundle to Chado tables. Could not publish record.",
  92. [], $message_opts);
  93. return FALSE;
  94. }
  95. // Load the term for use in setting the alias for each entity created.
  96. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  97. $cache['term'] = $term;
  98. $table = $chado_bundle->data_table;
  99. $type_column = $chado_bundle->type_column;
  100. $type_linker_table = $chado_bundle->type_linker_table;
  101. $cvterm_id = $chado_bundle->type_id;
  102. $type_value = $chado_bundle->type_value;
  103. // Get the table information for the Chado table.
  104. $table_schema = chado_get_schema($table);
  105. $pkey_field = $table_schema['primary key'][0];
  106. // Construct the SQL for identifying which records should be published.
  107. $args = array();
  108. $select = "SELECT T.$pkey_field as record_id ";
  109. $from = "
  110. FROM {" . $table . "} T
  111. LEFT JOIN [" . $chado_entity_table . "] CE on CE.record_id = T.$pkey_field
  112. ";
  113. // For migration of Tripal v2 nodes to entities we want to include the
  114. // coresponding chado linker table.
  115. if ($sync_node && db_table_exists('chado_' . $table)) {
  116. $select = "SELECT T.$pkey_field as record_id, CT.nid ";
  117. $from .= " INNER JOIN [chado_" . $table . "] CT ON CT.$pkey_field = T.$pkey_field";
  118. }
  119. $where = " WHERE CE.record_id IS NULL ";
  120. // Handle records that are mapped to property tables.
  121. if ($type_linker_table and $type_column and $type_value) {
  122. $propschema = chado_get_schema($type_linker_table);
  123. $fkeys = $propschema['foreign keys'][$table]['columns'];
  124. foreach ($fkeys as $leftkey => $rightkey) {
  125. if ($rightkey == $pkey_field) {
  126. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  127. }
  128. }
  129. $where .= "AND LT.$type_column = :cvterm_id and LT.value = :prop_value";
  130. $args[':cvterm_id'] = $cvterm_id;
  131. $args[':prop_value'] = $type_value;
  132. }
  133. // Handle records that are mapped to cvterm linking tables.
  134. if ($type_linker_table and $type_column and !$type_value) {
  135. $cvtschema = chado_get_schema($type_linker_table);
  136. $fkeys = $cvtschema['foreign keys'][$table]['columns'];
  137. foreach ($fkeys as $leftkey => $rightkey) {
  138. if ($rightkey == $pkey_field) {
  139. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  140. }
  141. }
  142. $where .= "AND LT.$type_column = :cvterm_id";
  143. $args[':cvterm_id'] = $cvterm_id;
  144. }
  145. // Handle records that are mapped via a type_id column in the base table.
  146. if (!$type_linker_table and $type_column) {
  147. $where .= "AND T.$type_column = :cvterm_id";
  148. $args[':cvterm_id'] = $cvterm_id;
  149. }
  150. // Handle the case where records are in the cvterm table and mapped via a single
  151. // vocab. Here we use the type_value for the cv_id.
  152. if ($table == 'cvterm' and $type_value) {
  153. $where .= "AND T.cv_id = :cv_id";
  154. $args[':cv_id'] = $type_value;
  155. }
  156. // Handle the case where records are in the cvterm table but we want to
  157. // use all of the child terms.
  158. if ($table == 'cvterm' and !$type_value) {
  159. $where .= "AND T.cvterm_id IN (
  160. SELECT CVTP.subject_id
  161. FROM {cvtermpath} CVTP
  162. WHERE CVTP.object_id = :cvterm_id)
  163. ";
  164. $args[':cvterm_id'] = $cvterm_id;
  165. }
  166. // Now add in any additional filters
  167. $fields = field_info_field_map();
  168. foreach ($fields as $field_name => $details) {
  169. if (array_key_exists('TripalEntity', $details['bundles']) and
  170. in_array($bundle_name, $details['bundles']['TripalEntity']) and
  171. in_array($field_name, array_keys($filters))){
  172. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  173. $chado_table = $instance['settings']['chado_table'];
  174. $chado_column = $instance['settings']['chado_column'];
  175. if ($chado_table == $table) {
  176. $where .= " AND T.$chado_column = :$field_name";
  177. $args[":$field_name"] = $filters[$field_name];
  178. }
  179. }
  180. }
  181. // First get the count
  182. // @performance optimize, estimate or remove this. It's only used for reporting progress on the command-line.
  183. $sql = "SELECT count(*) as num_records " . $from . $where;
  184. $result = chado_query($sql, $args);
  185. $count = $result->fetchField();
  186. tripal_report_error($message_type, TRIPAL_INFO,
  187. "There are !count records to publish.",
  188. ['!count' => $count], $message_opts);
  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. $records = chado_query($sql, $args);
  195. // Update the job status every chunk start.
  196. // Because this is outside of hte transaction, we can update the admin through the jobs UI.
  197. $complete = 0;
  198. if ($count > 0) {
  199. $complete = ($total_published / $count) * 33.33333333;
  200. }
  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. // There is no need to cache transactions since Drupal handles nested transactions
  211. // "by performing no transactional operations (as far as the database sees) within
  212. // the inner nesting layers". Effectively, Drupal ensures nested trasactions work the
  213. // same as passing a transaction through to the deepest level and not starting a new
  214. // transaction if we are already in one.
  215. $transaction = db_transaction();
  216. try {
  217. $i = 0;
  218. while($record = $records->fetchObject()) {
  219. // First save the tripal_entity record.
  220. // @performace This is likely a bottleneck. Too bad we can't create
  221. // multiple entities at once... sort of like the copy method.
  222. $record_id = $record->record_id;
  223. $ec = entity_get_controller('TripalEntity');
  224. $entity = $ec->create(array(
  225. 'bundle' => $bundle_name,
  226. 'term_id' => $bundle->term_id,
  227. // Add in the Chado details for when the hook_entity_create()
  228. // is called and our tripal_chado_entity_create() implementation
  229. // can deal with it.
  230. 'chado_record' => chado_generate_var($table, array($pkey_field => $record_id), array('include_fk' => 0)),
  231. 'chado_record_id' => $record_id,
  232. 'publish' => TRUE,
  233. 'bundle_object' => $bundle,
  234. ));
  235. $entity = $entity->save($cache);
  236. if (!$entity) {
  237. throw new Exception('Could not create entity.');
  238. }
  239. // Next save the chado entity record.
  240. $entity_record = array(
  241. 'entity_id' => $entity->id,
  242. 'record_id' => $record_id,
  243. );
  244. // For the Tv2 to Tv3 migration we want to add the nid to the
  245. // entity so we can associate the node with the entity.
  246. if (property_exists($record, 'nid')) {
  247. $entity_record['nid'] = $record->nid;
  248. }
  249. $result = db_insert($chado_entity_table)
  250. ->fields($entity_record)
  251. ->execute();
  252. if(!$result){
  253. throw new Exception('Could not create mapping of entity to Chado record.');
  254. }
  255. $i++;
  256. $total_published++;
  257. }
  258. }
  259. catch (Exception $e) {
  260. $transaction->rollback();
  261. $error = $e->getMessage();
  262. tripal_report_error($message_type, TRIPAL_ERROR, "Could not publish record: @error", array('@error' => $error));
  263. drupal_set_message('Failed publishing record. See recent logs for more details.', 'error');
  264. return FALSE;
  265. }
  266. // If we get through the loop and haven't completed 100 records, then we're done!
  267. if ($i < $chunk_size) {
  268. $more_records_to_publish = FALSE;
  269. }
  270. // Commit our current chunk.
  271. unset($transaction);
  272. }
  273. tripal_report_error($message_type, TRIPAL_INFO,
  274. "Succesfully published %count %type record(s).",
  275. ['%count' => $total_published, '%type' => $bundle->label], $message_opts);
  276. return TRUE;
  277. }
  278. /**
  279. * Returns an array of tokens based on Tripal Entity Fields.
  280. *
  281. * @param $base_table
  282. * The name of a base table in Chado.
  283. * @return
  284. * An array of tokens where the key is the machine_name of the token.
  285. *
  286. * @ingroup tripal_chado_api
  287. */
  288. function chado_get_tokens($base_table) {
  289. $tokens = array();
  290. $table_descrip = chado_get_schema($base_table);
  291. foreach ($table_descrip['fields'] as $field_name => $field_details) {
  292. $token = '[' . $base_table . '.' . $field_name . ']';
  293. $location = implode(' > ',array($base_table, $field_name));
  294. $tokens[$token] = array(
  295. 'name' => ucwords(str_replace('_',' ',$base_table)) . ': ' . ucwords(str_replace('_',' ',$field_name)),
  296. 'table' => $base_table,
  297. 'field' => $field_name,
  298. 'token' => $token,
  299. 'description' => array_key_exists('description', $field_details) ? $field_details['description'] : '',
  300. 'location' => $location
  301. );
  302. if (!array_key_exists('description', $field_details) or preg_match('/TODO/',$field_details['description'])) {
  303. $tokens[$token]['description'] = 'The '.$field_name.' field of the '.$base_table.' table.';
  304. }
  305. }
  306. // RECURSION:
  307. // Follow the foreign key relationships recursively
  308. if (array_key_exists('foreign keys', $table_descrip)) {
  309. foreach ($table_descrip['foreign keys'] as $table => $details) {
  310. foreach ($details['columns'] as $left_field => $right_field) {
  311. $sub_token_prefix = $base_table . '.' . $left_field;
  312. $sub_location_prefix = implode(' > ',array($base_table, $left_field));
  313. $sub_tokens = chado_get_tokens($table);
  314. if (is_array($sub_tokens)) {
  315. $tokens = array_merge($tokens, $sub_tokens);
  316. }
  317. }
  318. }
  319. }
  320. return $tokens;
  321. }
  322. /**
  323. * Replace all Chado Tokens in a given string.
  324. *
  325. * NOTE: If there is no value for a token then the token is removed.
  326. *
  327. * @param string $string
  328. * The string containing tokens.
  329. * @param $record
  330. * A Chado record as generated by chado_generate_var()
  331. *
  332. * @return
  333. * The string will all tokens replaced with values.
  334. *
  335. * @ingroup tripal_chado_api
  336. */
  337. function chado_replace_tokens($string, $record) {
  338. // Get the list of tokens
  339. $tokens = chado_get_tokens($record->tablename);
  340. // Determine which tokens were used in the format string
  341. if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
  342. // Get the value for each token used
  343. foreach ($used_tokens[0] as $token) {
  344. $token_info = $tokens[$token];
  345. if (!empty($token_info)) {
  346. $table = $token_info['table'];
  347. $var = $record;
  348. $value = '';
  349. // Iterate through each portion of the location string. An example string
  350. // might be: stock > type_id > name.
  351. $location = explode('>', $token_info['location']);
  352. foreach ($location as $index) {
  353. $index = trim($index);
  354. // if $var is an object then it is the $node object or a table
  355. // that has been expanded.
  356. if (is_object($var)) {
  357. // check to see if the index is a member of the object. If so,
  358. // then reset the $var to this value.
  359. if (property_exists($var, $index)) {
  360. $value = $var->$index;
  361. }
  362. }
  363. // if the $var is an array then there are multiple instances of the same
  364. // table in a FK relationship (e.g. relationship tables)
  365. elseif (is_array($var)) {
  366. $value = $var[$index];
  367. }
  368. else {
  369. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  370. 'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
  371. 'to access \'%index\' for the following: \'%var\'.',
  372. array('%token' => $token, '%index' => $index, '%var' => print_r($var,TRUE))
  373. );
  374. }
  375. }
  376. $string = str_replace($token, $value, $string);
  377. }
  378. }
  379. }
  380. return $string;
  381. }