tripal_chado.api.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. // Make sure we have the required options: bundle_name.
  53. if (!array_key_exists('bundle_name', $values) or !$values['bundle_name']) {
  54. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  55. "Could not publish record: @error",
  56. array('@error' => 'The bundle name must be provided'));
  57. return FALSE;
  58. }
  59. // Get the incoming arguments from the $values array.
  60. $bundle_name = $values['bundle_name'];
  61. $filters = array_key_exists('filters', $values) ? $values['filters'] : array();
  62. $sync_node = array_key_exists('sync_node', $values) ? $values['sync_node'] : '';
  63. // @performance remove after development: 0.00059294700622559s
  64. // Load the bundle entity so we can get information about which Chado
  65. // table/field this entity belongs to.
  66. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  67. if (!$bundle) {
  68. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  69. "Unknown bundle. Could not publish record: @error",
  70. array('@error' => 'The bundle name must be provided'));
  71. return FALSE;
  72. }
  73. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  74. // @performance remove after development: 0.05065393447876s
  75. // Get the mapping of the bio data type to the Chado table.
  76. $chado_bundle = db_select('chado_bundle', 'cb')
  77. ->fields('cb')
  78. ->condition('bundle_id', $bundle->id)
  79. ->execute()
  80. ->fetchObject();
  81. if(!$chado_bundle) {
  82. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  83. "Cannot find mapping of bundle to Chado tables. Could not publish record.");
  84. return FALSE;
  85. }
  86. $table = $chado_bundle->data_table;
  87. $type_column = $chado_bundle->type_column;
  88. $type_linker_table = $chado_bundle->type_linker_table;
  89. $cvterm_id = $chado_bundle->type_id;
  90. $type_value = $chado_bundle->type_value;
  91. // @performance remove after development:0.051163911819458s
  92. // Get the table information for the Chado table.
  93. $table_schema = chado_get_schema($table);
  94. $pkey_field = $table_schema['primary key'][0];
  95. // @performance remove after development:0.05134105682373s
  96. // Construct the SQL for identifying which records should be published.
  97. // @performance find a way to optimize this?
  98. $args = array();
  99. $select = "SELECT T.$pkey_field as record_id ";
  100. $from = "
  101. FROM {" . $table . "} T
  102. LEFT JOIN [" . $chado_entity_table . "] CE on CE.record_id = T.$pkey_field
  103. ";
  104. // For migration of Tripal v2 nodes to entities we want to include the
  105. // coresponding chado linker table.
  106. if ($sync_node && db_table_exists('chado_' . $table)) {
  107. $select = "SELECT T.$pkey_field as record_id, CT.nid ";
  108. $from .= " INNER JOIN [chado_" . $table . "] CT ON CT.$pkey_field = T.$pkey_field";
  109. }
  110. $where = " WHERE CE.record_id IS NULL ";
  111. // Handle records that are mapped to property tables.
  112. if ($type_linker_table and $type_column and $type_value) {
  113. $propschema = chado_get_schema($type_linker_table);
  114. $fkeys = $propschema['foreign keys'][$table]['columns'];
  115. foreach ($fkeys as $leftkey => $rightkey) {
  116. if ($rightkey == $pkey_field) {
  117. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  118. }
  119. }
  120. $where .= "AND LT.$type_column = :cvterm_id and LT.value = :prop_value";
  121. $args[':cvterm_id'] = $cvterm_id;
  122. $args[':prop_value'] = $type_value;
  123. }
  124. // Handle records that are mapped to cvterm linking tables.
  125. if ($type_linker_table and $type_column and !$type_value) {
  126. $cvtschema = chado_get_schema($type_linker_table);
  127. $fkeys = $cvtschema['foreign keys'][$table]['columns'];
  128. foreach ($fkeys as $leftkey => $rightkey) {
  129. if ($rightkey == $pkey_field) {
  130. $from .= " INNER JOIN {" . $type_linker_table . "} LT ON T.$pkey_field = LT.$leftkey ";
  131. }
  132. }
  133. $where .= "AND LT.$type_column = :cvterm_id";
  134. $args[':cvterm_id'] = $cvterm_id;
  135. }
  136. // Handle records that are mapped via a type_id column in the base table.
  137. if (!$type_linker_table and $type_column) {
  138. $where .= "AND T.$type_column = :cvterm_id";
  139. $args[':cvterm_id'] = $cvterm_id;
  140. }
  141. // Handle the case where records are in the cvterm table and mapped via a single
  142. // vocab. Here we use the type_value for the cv_id.
  143. if ($table == 'cvterm' and $type_value) {
  144. $where .= "AND T.cv_id = :cv_id";
  145. $args[':cv_id'] = $type_value;
  146. }
  147. // Handle the case where records are in the cvterm table but we want to
  148. // use all of the child terms.
  149. if ($table == 'cvterm' and !$type_value) {
  150. $where .= "AND T.cvterm_id IN (
  151. SELECT CVTP.subject_id
  152. FROM {cvtermpath} CVTP
  153. WHERE CVTP.object_id = :cvterm_id)
  154. ";
  155. $args[':cvterm_id'] = $cvterm_id;
  156. }
  157. // Now add in any additional filters
  158. $fields = field_info_field_map();
  159. foreach ($fields as $field_name => $details) {
  160. if (array_key_exists('TripalEntity', $details['bundles']) and
  161. in_array($bundle_name, $details['bundles']['TripalEntity']) and
  162. in_array($field_name, array_keys($filters))){
  163. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  164. $chado_table = $instance['settings']['chado_table'];
  165. $chado_column = $instance['settings']['chado_column'];
  166. if ($chado_table == $table) {
  167. $where .= " AND T.$chado_column = :$field_name";
  168. $args[":$field_name"] = $filters[$field_name];
  169. }
  170. }
  171. }
  172. // @performance remove after development:0.060441970825195s
  173. // First get the count
  174. // @performance optimize, estimate or remove this. It's only used for reporting progress on the command-line.
  175. $sql = "SELECT count(*) as num_records " . $from . $where;
  176. $result = chado_query($sql, $args);
  177. $count = $result->fetchField();
  178. // calculate the interval for updates
  179. $interval = intval($count / 50);
  180. if ($interval < 1) {
  181. $interval = 1;
  182. }
  183. // @performance remove after development:0.25212502479553s
  184. print 'Count amount to do :' . (microtime(true) - $started_at) . "s.\n";
  185. // Perform the query.
  186. $sql = $select . $from . $where;
  187. $records = chado_query($sql, $args);
  188. // @performance remove after development:0.43729090690613s
  189. print 'Perform Query :' . (microtime(true) - $started_at) . "s.\n";
  190. // @performance evaluate this transaction. Long running transactions can have serious
  191. // performance issues in PostgreSQL. One option is to move the transaction within the
  192. // loop so that each one is not very long but then we end up with more overhead creating
  193. // transactions. A better albeit more complicated approach might be to break the job into
  194. // chunks where each one is a single transaction.
  195. $transaction = db_transaction();
  196. print "\nNOTE: publishing records is performed using a database transaction. \n" .
  197. "If the load fails or is terminated prematurely then the entire set of \n" .
  198. "is rolled back with no changes to the database\n\n";
  199. $i = 0;
  200. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, 0, number_format(memory_get_usage()));
  201. try {
  202. while($record = $records->fetchObject()) {
  203. // @performance remove after development
  204. print 'Start current entity :' . (microtime(true) - $started_at) . "s.\n";
  205. // update the job status every interval
  206. if ($i % $interval == 0) {
  207. $complete = ($i / $count) * 33.33333333;
  208. // Currently don't support setting job progress within a transaction.
  209. // if ($report_progress) { $job->setProgress(intval($complete * 3)); }
  210. printf("%d of %d records. (%0.2f%%) Memory: %s bytes\r", $i, $count, $complete * 3, number_format(memory_get_usage()));
  211. }
  212. // First save the tripal_entity record.
  213. // @performace This is likely a bottleneck. Too bad we can't create
  214. // multiple entities at once... sort of like the copy method.
  215. $record_id = $record->record_id;
  216. $ec = entity_get_controller('TripalEntity');
  217. $entity = $ec->create(array(
  218. 'bundle' => $bundle_name,
  219. 'term_id' => $bundle->term_id,
  220. // Add in the Chado details for when the hook_entity_create()
  221. // is called and our tripal_chado_entity_create() implementation
  222. // can deal with it.
  223. // @performance maybe there is something we can easily do here?
  224. 'chado_record' => chado_generate_var($table, array($pkey_field => $record_id)),
  225. 'chado_record_id' => $record_id,
  226. 'publish' => TRUE,
  227. ));
  228. $entity = $entity->save();
  229. if (!$entity) {
  230. throw new Exception('Could not create entity.');
  231. }
  232. // @performance remove after development: this takes 0.2-0.3s.
  233. //print 'Create entity itself :' . (microtime(true) - $started_at) . "s.\n";
  234. // Next save the chado entity record.
  235. $entity_record = array(
  236. 'entity_id' => $entity->id,
  237. 'record_id' => $record_id,
  238. );
  239. // For the Tv2 to Tv3 migration we want to add the nid to the
  240. // entity so we can associate the node with the entity.
  241. if (property_exists($record, 'nid')) {
  242. $entity_record['nid'] = $record->nid;
  243. }
  244. $result = db_insert($chado_entity_table)
  245. ->fields($entity_record)
  246. ->execute();
  247. if(!$result){
  248. throw new Exception('Could not create mapping of entity to Chado record.');
  249. }
  250. // @performance remove after development: this takes <0.001s.
  251. // print 'Relate back to chado :' . (microtime(true) - $started_at) . "s.\n";
  252. $i++;
  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. drupal_set_message("Succesfully published $i " . $bundle->label . " record(s).");
  263. // @performance remove after development
  264. print 'Complete :' . (microtime(true) - $started_at) . "s.\n";
  265. return TRUE;
  266. }
  267. /**
  268. * Returns an array of tokens based on Tripal Entity Fields.
  269. *
  270. * @param $base_table
  271. * The name of a base table in Chado.
  272. * @return
  273. * An array of tokens where the key is the machine_name of the token.
  274. *
  275. * @ingroup tripal_chado_api
  276. */
  277. function chado_get_tokens($base_table) {
  278. $tokens = array();
  279. $table_descrip = chado_get_schema($base_table);
  280. foreach ($table_descrip['fields'] as $field_name => $field_details) {
  281. $token = '[' . $base_table . '.' . $field_name . ']';
  282. $location = implode(' > ',array($base_table, $field_name));
  283. $tokens[$token] = array(
  284. 'name' => ucwords(str_replace('_',' ',$base_table)) . ': ' . ucwords(str_replace('_',' ',$field_name)),
  285. 'table' => $base_table,
  286. 'field' => $field_name,
  287. 'token' => $token,
  288. 'description' => array_key_exists('description', $field_details) ? $field_details['description'] : '',
  289. 'location' => $location
  290. );
  291. if (!array_key_exists('description', $field_details) or preg_match('/TODO/',$field_details['description'])) {
  292. $tokens[$token]['description'] = 'The '.$field_name.' field of the '.$base_table.' table.';
  293. }
  294. }
  295. // RECURSION:
  296. // Follow the foreign key relationships recursively
  297. if (array_key_exists('foreign keys', $table_descrip)) {
  298. foreach ($table_descrip['foreign keys'] as $table => $details) {
  299. foreach ($details['columns'] as $left_field => $right_field) {
  300. $sub_token_prefix = $base_table . '.' . $left_field;
  301. $sub_location_prefix = implode(' > ',array($base_table, $left_field));
  302. $sub_tokens = chado_get_tokens($table);
  303. if (is_array($sub_tokens)) {
  304. $tokens = array_merge($tokens, $sub_tokens);
  305. }
  306. }
  307. }
  308. }
  309. return $tokens;
  310. }
  311. /**
  312. * Replace all Chado Tokens in a given string.
  313. *
  314. * NOTE: If there is no value for a token then the token is removed.
  315. *
  316. * @param string $string
  317. * The string containing tokens.
  318. * @param $record
  319. * A Chado record as generated by chado_generate_var()
  320. *
  321. * @return
  322. * The string will all tokens replaced with values.
  323. *
  324. * @ingroup tripal_chado_api
  325. */
  326. function chado_replace_tokens($string, $record) {
  327. // Get the list of tokens
  328. $tokens = chado_get_tokens($record->tablename);
  329. // Determine which tokens were used in the format string
  330. if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
  331. // Get the value for each token used
  332. foreach ($used_tokens[0] as $token) {
  333. $token_info = $tokens[$token];
  334. if (!empty($token_info)) {
  335. $table = $token_info['table'];
  336. $var = $record;
  337. $value = '';
  338. // Iterate through each portion of the location string. An example string
  339. // might be: stock > type_id > name.
  340. $location = explode('>', $token_info['location']);
  341. foreach ($location as $index) {
  342. $index = trim($index);
  343. // if $var is an object then it is the $node object or a table
  344. // that has been expanded.
  345. if (is_object($var)) {
  346. // check to see if the index is a member of the object. If so,
  347. // then reset the $var to this value.
  348. if (property_exists($var, $index)) {
  349. $value = $var->$index;
  350. }
  351. }
  352. // if the $var is an array then there are multiple instances of the same
  353. // table in a FK relationship (e.g. relationship tables)
  354. elseif (is_array($var)) {
  355. $value = $var[$index];
  356. }
  357. else {
  358. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  359. 'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
  360. 'to access \'%index\' for the following: \'%var\'.',
  361. array('%token' => $token, '%index' => $index, '%var' => print_r($var,TRUE))
  362. );
  363. }
  364. }
  365. $string = str_replace($token, $value, $string);
  366. }
  367. }
  368. }
  369. return $string;
  370. }