tripal_chado.mapping.inc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. ->condition('chado_table', $tablename)
  57. ->condition('chado_field', $chado_field)
  58. ->execute()
  59. ->fetchField();
  60. // insert records into the tripal_cvterm_mapping table.
  61. if (!$record) {
  62. db_insert('tripal_cvterm_mapping')
  63. ->fields(
  64. array(
  65. 'cvterm_id' => $cvterm_id,
  66. 'chado_table' => $tablename,
  67. 'chado_field' => $chado_field
  68. )
  69. )
  70. ->execute();
  71. }
  72. }