tripal_chado.mapping.inc 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * This function populates the Tripal entity tables using existing
  4. * data in the database.
  5. */
  6. function tripal_chado_map_cvterms() {
  7. // Get chado base tables
  8. $base_tables = chado_get_base_tables();
  9. // Perform this action in a transaction
  10. $transaction = db_transaction();
  11. print "\nNOTE: Populating of tripal_cvterm_mapping table is performed using a database transaction. \n" .
  12. "If the load fails or is terminated prematurely then the entire set of \n" .
  13. "insertions/updates is rolled back and will not be found in the database\n\n";
  14. try {
  15. // Iterate through the referring tables to see what records are there.
  16. foreach ($base_tables as $tablename) {
  17. print "Examining $tablename...\n";
  18. $ref_schema = chado_get_schema($tablename);
  19. $fkeys = $ref_schema['foreign keys'];
  20. if (!isset($fkeys['cvterm']['columns'])) {
  21. continue;
  22. }
  23. foreach ($fkeys['cvterm']['columns'] as $local_id => $remote_id) {
  24. // Get the list of cvterm_ids from existing records in the table.
  25. $sql = "
  26. SELECT $local_id
  27. FROM { " . $tablename . "}
  28. GROUP BY $local_id
  29. ";
  30. $results = chado_query($sql);
  31. while ($cvterm_id = $results->fetchField()) {
  32. tripal_chado_add_cvterm_mapping($cvterm_id, $tablename, $local_id);
  33. }
  34. }
  35. }
  36. }
  37. catch (Exception $e) {
  38. print "\n"; // make sure we start errors on new line
  39. $transaction->rollback();
  40. watchdog_exception('tripal_chado', $e);
  41. print "FAILED: Rolling back database changes...\n";
  42. }
  43. print "\nDone.\n";
  44. }
  45. /*
  46. * Add a cvterm mapping record
  47. *
  48. * Check if the cvterm mapping record exists. If not, add it to the tripal_cvterm_mapping
  49. * table
  50. */
  51. function tripal_chado_add_cvterm_mapping($cvterm_id, $tablename, $chado_field) {
  52. // check if the record exists
  53. $record = db_select('tripal_cvterm_mapping', 'tcm')
  54. ->fields('tcm', array('mapping_id'))
  55. ->condition('cvterm_id', $cvterm_id)
  56. ->execute()
  57. ->fetchField();
  58. // insert records into the tripal_cvterm_mapping table.
  59. if (!$record) {
  60. db_insert('tripal_cvterm_mapping')
  61. ->fields(
  62. array(
  63. 'cvterm_id' => $cvterm_id,
  64. 'chado_table' => $tablename,
  65. 'chado_field' => $chado_field
  66. )
  67. )
  68. ->execute();
  69. }
  70. // if the record exists, update the term mapping
  71. else {
  72. db_update('tripal_cvterm_mapping')
  73. ->fields(
  74. array(
  75. 'chado_table' => $tablename,
  76. 'chado_field' => $chado_field
  77. )
  78. )
  79. ->condition('cvterm_id', $cvterm_id)
  80. ->execute()
  81. ;
  82. }
  83. }