tripal_chado.api.inc 15 KB

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