tripal_chado.api.inc 15 KB

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