tripal_chado.cv.api.inc 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. <?php
  2. /**
  3. * @file
  4. * This module provides a set of functions to simplify working with
  5. * controlled vocabularies.
  6. */
  7. /**
  8. * @defgroup tripal_chado_api Controlled Vocabulary API
  9. * @ingroup tripal_api
  10. * This module provides a set of functions to simplify working with
  11. * controlled vocabularies. Most of the API functions deal with retrieving
  12. * terms or their parent vocabularies.
  13. *
  14. * However, the API also supports
  15. * generation of trees for browsing a vocabulary as well as generation of
  16. * pie graphs for display of hierarchical counts of terms. Version 0.3b of
  17. * Tripal provides a feature browser and a feature summary chart uses
  18. * the API functions provided here. But in general charts and trees can be
  19. * created for any controlled vocabulary.
  20. *
  21. */
  22. /**
  23. * Retrieves a chado controlled vocabulary variable
  24. *
  25. * @param $identifier
  26. * An array with the key stating what the identifier is. Supported keys (only on of the
  27. * following unique keys is required):
  28. * - cv_id: the chado cv.cv_id primary key
  29. * - name: the chado cv.name field (assume unique)
  30. * @param $options
  31. * An array of options. Supported keys include:
  32. * - Any keys supported by chado_generate_var(). See that function definition for
  33. * additional details.
  34. *
  35. * NOTE: the $identifier parameter can really be any array similar to $values passed into
  36. * chado_select_record(). It should fully specify the cv record to be returned.
  37. *
  38. * @return
  39. * If unique values were passed in as an identifier then an object describing the cv
  40. * will be returned (will be a chado variable from chado_generate_var()). Otherwise,
  41. * FALSE will be returned.
  42. *
  43. * @ingroup tripal_chado_api
  44. */
  45. function tripal_get_cv($identifiers, $options = array()) {
  46. // Set Defaults
  47. if (!isset($options['include_fk'])) {
  48. // Tells chado_generate_var not to follow any foreign keys
  49. $options['include_fk'] = array();
  50. }
  51. // Error Checking of parameters
  52. if (!is_array($identifiers)) {
  53. tripal_report_error(
  54. 'tripal_chado_api',
  55. TRIPAL_ERROR,
  56. "tripal_get_cv: The identifier passed in is expected to be an array with the key
  57. matching a column name in the cv table (ie: cv_id or name). You passed in %identifier.",
  58. array(
  59. '%identifier'=> print_r($identifiers, TRUE)
  60. )
  61. );
  62. }
  63. elseif (empty($identifiers)) {
  64. tripal_report_error(
  65. 'tripal_chado_api',
  66. TRIPAL_ERROR,
  67. "tripal_get_cv: You did not pass in anything to identify the cv you want. The identifier
  68. is expected to be an array with the key matching a column name in the cv table
  69. (ie: cv_id or name). You passed in %identifier.",
  70. array(
  71. '%identifier'=> print_r($identifiers, TRUE)
  72. )
  73. );
  74. }
  75. // Try to get the cv
  76. $cv = chado_generate_var(
  77. 'cv',
  78. $identifiers,
  79. $options
  80. );
  81. // Ensure the cv is singular. If it's an array then it is not singular
  82. if (is_array($cv)) {
  83. tripal_report_error(
  84. 'tripal_chado_api',
  85. TRIPAL_ERROR,
  86. "tripal_get_cv: The identifiers you passed in were not unique. You passed in %identifier.",
  87. array(
  88. '%identifier'=> print_r($identifiers, TRUE)
  89. )
  90. );
  91. }
  92. // Report an error if $cv is FALSE since then chado_generate_var has failed
  93. elseif ($cv === FALSE) {
  94. tripal_report_error(
  95. 'tripal_chado_api',
  96. TRIPAL_ERROR,
  97. "tripal_get_cv: chado_generate_var() failed to return a cv based on the identifiers
  98. you passed in. You should check that your identifiers are correct, as well as, look
  99. for a chado_generate_var error for additional clues. You passed in %identifier.",
  100. array(
  101. '%identifier'=> print_r($identifiers, TRUE)
  102. )
  103. );
  104. }
  105. // Else, as far we know, everything is fine so give them their cv :)
  106. else {
  107. return $cv;
  108. }
  109. }
  110. /**
  111. * Create an options array to be used in a form element which provides a
  112. * list of all chado cvs
  113. *
  114. * @return
  115. * An array(cv_id => name) for each cv in the chado cv table
  116. *
  117. * @ingroup tripal_chado_api
  118. */
  119. function tripal_get_cv_select_options() {
  120. $results = chado_select_record('cv', array('cv_id', 'name'), array(), array('order_by' => array('name' => 'ASC')));
  121. $options = array();
  122. $options[] = 'Select a Vocabulary';
  123. foreach ($results as $r) {
  124. $options[$r->cv_id] = $r->name;
  125. }
  126. return $options;
  127. }
  128. /**
  129. * Retrieves a chado controlled vocabulary term variable
  130. *
  131. * @param $identifier
  132. * An array apropriate for use with the chado_generate_var for uniquely
  133. * identifying a cvterm record. Alternativley, there are also some specially
  134. * handled keys. They are:
  135. * - id: an ID for the term of the for [dbname]:[accession], where [dbname]
  136. * is the short name of the vocabulary and accession is the unique ID.
  137. * - cv_id: an integer indicating the cv_id or an array with 'name' => the
  138. * name of the cv.
  139. * - synonym: an array with 'name' => the name of the synonym of the cvterm
  140. * you want returned; 'cv_id' => the cv_id of the synonym; 'cv_name' =>
  141. * the name of the cv of the synonym
  142. * - property: An array/object describing the property to select records
  143. * for. It should at least have either a type_name (if unique across cvs)
  144. * or type_id. Other supported keys include: cv_id/cv_name (of the type),
  145. * value and rank
  146. * @param $options
  147. * An array of options. Supported keys include:
  148. * - Any keys supported by chado_generate_var(). See that function
  149. * definition for additional details.
  150. *
  151. * NOTE: the $identifier parameter can really be any array similar to $values
  152. * passed into chado_select_record(). It should fully specify the cvterm
  153. * record to be returned.
  154. *
  155. * @return
  156. * If unique values were passed in as an identifier then an object describing
  157. * the cvterm will be returned (will be a chado variable from
  158. * chado_generate_var()). Otherwise, FALSE will be returned.
  159. *
  160. * @ingroup tripal_cv_api
  161. */
  162. function tripal_get_cvterm($identifiers, $options = array()) {
  163. // Set Defaults
  164. if (!isset($options['include_fk'])) {
  165. // Tells chado_generate_var to only get the cv
  166. $options['include_fk'] = array('cv_id' => TRUE);
  167. }
  168. // Error Checking of parameters
  169. if (!is_array($identifiers)) {
  170. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  171. "tripal_get_cvterm: The identifier passed in is expected to be an array with the key
  172. matching a column name in the cvterm table (ie: cvterm_id or name). You passed in %identifier.",
  173. array('%identifier'=> print_r($identifiers, TRUE))
  174. );
  175. }
  176. elseif (empty($identifiers)) {
  177. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  178. "tripal_get_cvterm: You did not pass in anything to identify the cvterm you want. The identifier
  179. is expected to be an array with the key matching a column name in the cvterm table
  180. (ie: cvterm_id or name). You passed in %identifier.",
  181. array('%identifier'=> print_r($identifiers, TRUE))
  182. );
  183. }
  184. // If synonym was passed in, then process this first before calling chado_generate_var()
  185. if (isset($identifiers['synonym'])) {
  186. $synonym = $identifiers['synonym']['name'];
  187. $values = array('synonym' => $synonym);
  188. if (isset($identifiers['synonym']['cv_id'])) {
  189. $values['cvterm_id'] = array('cv_id' => $identifiers['synonym']['cv_id']);
  190. }
  191. if (isset($identifiers['synonym']['cv_name'])) {
  192. $values['cvterm_id'] = array('cv_id' => array('name' => $identifiers['synonym']['cv_name']));
  193. }
  194. $options = array(
  195. 'case_insensitive_columns' => array('name')
  196. );
  197. $result = chado_select_record('cvtermsynonym', array('cvterm_id'), $values, $options);
  198. // if the synonym doens't exist or more than one record is returned then return false
  199. if (count($result) == 0) {
  200. return FALSE;
  201. }
  202. if (count($result) > 1) {
  203. return FALSE;
  204. }
  205. $identifiers = array('cvterm_id' => $result[0]->cvterm_id);
  206. }
  207. // If one of the identifiers is property then use chado_get_record_with_property()
  208. if (isset($identifiers['property'])) {
  209. $property = $identifiers['property'];
  210. unset($identifiers['property']);
  211. $cvterm = chado_get_record_with_property(
  212. array('table' => 'cvterm', 'base_records' => $identifiers),
  213. array('type_name' => $property),
  214. $options
  215. );
  216. }
  217. if (isset($identifiers['id'])) {
  218. list($db_name, $accession) = preg_split('/:/', $identifiers['id']);
  219. $cvterm = chado_generate_var('cvterm',array(
  220. 'dbxref_id' => array(
  221. 'db_id' => array(
  222. 'name' => $db_name,
  223. ),
  224. 'accession' => $accession,
  225. )
  226. ));
  227. }
  228. // Else we have a simple case and we can just use chado_generate_var to get the cvterm
  229. else {
  230. // Try to get the cvterm
  231. $cvterm = chado_generate_var('cvterm', $identifiers, $options);
  232. }
  233. // Ensure the cvterm is singular. If it's an array then it is not singular
  234. if (is_array($cvterm)) {
  235. tripal_report_error(
  236. 'tripal_cv_api',
  237. TRIPAL_ERROR,
  238. "tripal_get_cvterm: The identifiers you passed in were not unique. You passed in %identifier.",
  239. array(
  240. '%identifier'=> print_r($identifiers, TRUE)
  241. )
  242. );
  243. }
  244. // Report an error if $cvterm is FALSE since then chado_generate_var has failed
  245. elseif ($cvterm === FALSE) {
  246. tripal_report_error(
  247. 'tripal_cv_api',
  248. TRIPAL_ERROR,
  249. "tripal_get_cvterm: chado_generate_var() failed to return a cvterm based on the identifiers
  250. you passed in. You should check that your identifiers are correct, as well as, look
  251. for a chado_generate_var error for additional clues. You passed in %identifier.",
  252. array(
  253. '%identifier'=> print_r($identifiers, TRUE)
  254. )
  255. );
  256. }
  257. // Else, as far we know, everything is fine so give them their cvterm :)
  258. else {
  259. return $cvterm;
  260. }
  261. }
  262. /**
  263. * Create an options array to be used in a form element
  264. * which provides a list of all chado cvterms
  265. *
  266. * @param $cv_id
  267. * The chado cv_id; only cvterms with the supplied cv_id will be returned
  268. * @param $rel_type
  269. * Set to TRUE if the terms returned should only be relationship types in
  270. * the vocabulary. This is useful for creating drop-downs of terms
  271. * used for relationship linker tables.
  272. *
  273. * @return
  274. * An associative array with the cvterm_id's as keys. The first
  275. * element in the array has a key of '0' and a value of 'Select a Type'
  276. *
  277. * @ingroup tripal_chado_api
  278. */
  279. function tripal_get_cvterm_select_options($cv_id, $rel_type = FALSE) {
  280. $columns = array('cvterm_id', 'name');
  281. $values = array('cv_id' => $cv_id);
  282. if ($rel_type) {
  283. $values['is_relationshiptype'] = 1;
  284. }
  285. $s_options = array('order_by' => array('name' => 'ASC'));
  286. $cvterms = chado_select_record('cvterm', $columns, $values, $s_options);
  287. $options = array();
  288. $options[0] = 'Select a Type';
  289. foreach ($cvterms as $cvterm) {
  290. $options[$cvterm->cvterm_id] = $cvterm->name;
  291. }
  292. return $options;
  293. }
  294. /**
  295. * Updates the cvtermpath table of Chado for the specified CV.
  296. *
  297. * @param $cv_id
  298. * The chado cv_id;
  299. * @param $job_id
  300. * This function is intended to be used with the Tripal Jobs API.
  301. * When this function is called as a job the $job_id is automatically
  302. * passed to this function.
  303. * @return
  304. * TRUE on success FALSE on failure
  305. *
  306. * @ingroup tripal_chado_api
  307. */
  308. function tripal_update_cvtermpath($cv_id, $job_id = NULL) {
  309. // TODO: need better error checking in this function
  310. // first get the controlled vocabulary name:
  311. $sql = "SELECT * FROM {cv} WHERE cv_id = :cv_id";
  312. $cv = chado_query($sql, array(':cv_id' => $cv_id))->fetchObject();
  313. print "\nUpdating cvtermpath for $cv->name...\n";
  314. // We need to set the chado schema as active because some of the
  315. // functions call other functions which would not be in scope.
  316. $previous = chado_set_active('chado');
  317. try {
  318. $sql = "SELECT * FROM fill_cvtermpath(:name)";
  319. db_query($sql, array(':name' => $cv->name));
  320. chado_set_active($previous);
  321. }
  322. catch (Exception $e) {
  323. chado_set_active($previous);
  324. $error = $e->getMessage();
  325. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath table: @error", array('@error' => $error));
  326. return FALSE;
  327. }
  328. return TRUE;
  329. }
  330. /**
  331. * Adds a controlled vocabular to the CV table of Chado.
  332. *
  333. * @param $name
  334. * The name of the controlled vocabulary. These are typically all lower case
  335. * with no special characters other than an undrescore (for spaces).
  336. * @param $comment
  337. * A description or definition of the vocabulary.
  338. *
  339. * @return
  340. * An object populated with fields from the newly added database.
  341. *
  342. * @ingroup tripal_chado_api
  343. */
  344. function tripal_insert_cv($name, $definition) {
  345. // insert/update values
  346. $ins_values = array(
  347. 'name' => $name,
  348. 'definition' => $definition
  349. );
  350. // see if the CV default exists already in the database
  351. $sel_values = array('name' => $name);
  352. $results = chado_select_record('cv', array('*'), $sel_values);
  353. // if it does not exists then add it
  354. if (count($results) == 0) {
  355. $success = chado_insert_record('cv', $ins_values);
  356. if (!$success) {
  357. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to create the CV record", NULL);
  358. return FALSE;
  359. }
  360. $results = chado_select_record('cv', array('*'), $sel_values);
  361. }
  362. // if it already exists then do an update
  363. else {
  364. $success = chado_update_record('cv', $sel_values, $ins_values);
  365. if (!$success) {
  366. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the CV record", NULL);
  367. return FALSE;
  368. }
  369. $results = chado_select_record('cv', array('*'), $sel_values);
  370. }
  371. // return the cv object
  372. return $results[0];
  373. }
  374. /**
  375. * Add's a controlled vocabulary term to Chado.
  376. *
  377. * This function will add a cvterm record (and a dbxref record if appropriate
  378. * values are provided). If the parent vocabulary does not exist then
  379. * that also is added to the cv table. If the cvterm is a relationship term
  380. * then the 'is_relationship' value should be set. All
  381. * terms must also have a corresponding database. This is specified in the
  382. * term's ID just before the colon (e.g. GO:003824). If the database does not
  383. * exist in the DB table then it will be added automatically. The accession
  384. * (the value just after the colon in the term's ID) will be added to the
  385. * dbxref table. If the CVterm already exists and $update is set (default)
  386. * then the cvterm is updated. If the CVTerm already exists and $update is
  387. * not set, then no changes are made and the CVTerm object is returned.
  388. *
  389. * @param $term
  390. * An associative array with the following keys:
  391. * - id: the term accession. must be of the form <DB>:<ACCESSION>, where
  392. * <DB> is the name of the database to which the cvterm belongs and the
  393. * <ACCESSION> is the term's accession number in the database.
  394. * - name: the name of the term. usually meant to be human-readable.
  395. * - is_obsolete: is present and set to 1 if the term is defunct
  396. * - definition: the definition of the term
  397. * - cv_name: The CV name to which the term belongs. If this arugment is
  398. * null or not provided then the function tries to find a record in the
  399. * CV table with the same name provided in the $term[namespace]. If
  400. * this field is provided then it overrides what the value in
  401. * $term[namespace]
  402. * - is_relationship: If this term is a relationship term then this value
  403. * should be 1.
  404. * - db_name: In some cases the database name will not be part of the
  405. * $term['id'] and it needs to be explicitly set. Use this argument
  406. * only if the database name cannot be specififed in the term ID
  407. * (e.g. <DB>:<ACCESSION>).
  408. * @param $options
  409. * An associative array with the following keys:
  410. * - update_existing: By default this is TRUE. If the term exists it is
  411. * automatically updated.
  412. * - force_db_change: Sometimes a term may need to switch from one
  413. * database to another. If the term already exists, but associated
  414. * with another term the insert (or update, rather) will fail. Set
  415. * this variable to TRUE to force the change to occur.
  416. *
  417. * @return
  418. * A cvterm object
  419. *
  420. * @ingroup tripal_chado_api
  421. */
  422. function tripal_insert_cvterm($term, $options = array()) {
  423. // get the term properties
  424. $id = (isset($term['id'])) ? $term['id'] : '';
  425. $name = '';
  426. $cvname = '';
  427. $definition = '';
  428. $is_obsolete = 0;
  429. $accession = '';
  430. // Set Defaults
  431. if (isset($term['cv_name'])) {
  432. $cvname = $term['cv_name'];
  433. }
  434. else {
  435. $cvname = 'local';
  436. }
  437. // Namespace is deprecated but must be supported for backwards
  438. // compatability
  439. if (array_key_exists('namespace', $term)) {
  440. $cvname = $term['namespace'];
  441. }
  442. if (isset($term['is_relationship'])) {
  443. $is_relationship = $term['is_relationship'];
  444. }
  445. else {
  446. $is_relationship = 0;
  447. }
  448. if (isset($term['db_name'])) {
  449. $dbname = $term['db_name'];
  450. }
  451. else {
  452. $dbname = 'local';
  453. }
  454. if (isset($options['update_existing'])) {
  455. $update = $options['update_existing'];
  456. }
  457. else {
  458. $update = 1;
  459. }
  460. if (array_key_exists('name', $term)) {
  461. $name = $term['name'];
  462. }
  463. else {
  464. $name = $id;
  465. }
  466. if (array_key_exists('definition', $term)) {
  467. $definition = preg_replace('/^\"(.*)\"/', '\1', $term['definition']);
  468. }
  469. else {
  470. $definition = '';
  471. }
  472. if (array_key_exists('is_obsolete', $term)) {
  473. $is_obsolete = $term['is_obsolete'];
  474. if (strcmp($is_obsolete, 'true') == 0) {
  475. $is_obsolete = 1;
  476. }
  477. }
  478. if (!$name and !$id) {
  479. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
  480. return 0;
  481. }
  482. if (!$id) {
  483. $id = $name;
  484. }
  485. // Get the accession and the database from the cvterm id.
  486. if ($dbname) {
  487. $accession = $id;
  488. }
  489. if (preg_match('/^.+?:.*$/', $id)) {
  490. $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
  491. $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
  492. }
  493. // Check that we have a database name, give a different message if it's a
  494. // relationship.
  495. if ($is_relationship and !$dbname) {
  496. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  497. "A database name is not provided for this relationship term: $id", NULL);
  498. return 0;
  499. }
  500. if (!$is_relationship and !$dbname) {
  501. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  502. "A database identifier is missing from the term: $id", NULL);
  503. return 0;
  504. }
  505. // Make sure the CV name exists
  506. $cv = tripal_get_cv(array('name' => $cvname));
  507. if (!$cv) {
  508. $cv = tripal_insert_cv($cvname, '');
  509. }
  510. if (!$cv) {
  511. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  512. "Cannot find namespace '$cvname' when adding/updating $id", NULL);
  513. return 0;
  514. }
  515. // This SQL statement will be used a lot to find a cvterm so just set it
  516. // here for easy reference below. Because CV terms can change their names
  517. // but accessions don't change, the following SQL finds cvterms based on
  518. // their accession rather than the name.
  519. $cvtermsql = "
  520. SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
  521. DB.name as dbname, DB.db_id, DBX.accession
  522. FROM {cvterm} CVT
  523. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  524. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  525. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  526. WHERE DBX.accession = :accession and DB.name = :name
  527. ";
  528. // Add the database. The function will just return the DB object if the
  529. // database already exists.
  530. $db = tripal_get_db(array('name' => $dbname));
  531. if (!$db) {
  532. $db = tripal_insert_db(array('name' => $dbname));
  533. }
  534. if (!$db) {
  535. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
  536. return 0;
  537. }
  538. // The cvterm table has two unique dependencies. We need to check both.
  539. // first check the (name, cv_id, is_obsolete) constraint.
  540. $values = array(
  541. 'name' => $name,
  542. 'is_obsolete' => $is_obsolete,
  543. 'cv_id' => array(
  544. 'name' => $cvname,
  545. ),
  546. );
  547. $result = chado_select_record('cvterm', array('*'), $values);
  548. if (count($result) == 1) {
  549. $cvterm = $result[0];
  550. // Get the dbxref record.
  551. $values = array('dbxref_id' => $cvterm->dbxref_id);
  552. $result = chado_select_record('dbxref', array('*'), $values);
  553. $dbxref = $result[0];
  554. if (!$dbxref) {
  555. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  556. 'Unable to access the dbxref record for the :term cvterm. Term Record: !record',
  557. array(':term' => $name, '!record' => print_r($cvterm, TRUE))
  558. );
  559. return FALSE;
  560. }
  561. // Get the db.
  562. $values = array('db_id' => $dbxref->db_id);
  563. $result = chado_select_record('db', array('*'), $values);
  564. $db_check = $result[0];
  565. // If the database from the existing record doesn't match the one that
  566. // has been provided then we have a problem. The term already exists
  567. // but we don't want to just switch the term, the callee must force it.
  568. if ($db_check->name != $db->name) {
  569. if (array_key_exists('force_db_change', $options) and
  570. $options['force_db_change'] != TRUE) {
  571. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  572. 'The term already exists, but associated with a different database record: \'!db\'. It cannot be added: !record',
  573. array(':term' => $name, '!db' => $db_check->name, '!record' => print_r($cvterm, TRUE))
  574. );
  575. return FALSE;
  576. }
  577. // Look to see if the correct dbxref record already exists for this
  578. // database.
  579. $values = array(
  580. 'db_id' => $db->db_id,
  581. 'accession' => $accession,
  582. );
  583. $result = chado_select_record('dbxref', array('*'), $values);
  584. // If we already have a good dbxref then we want to update our cvterm
  585. // to use this dbxref.
  586. if (count($result) > 0) {
  587. $dbxref = $result[0];
  588. $match = array('cvterm_id' => $cvterm->cvterm_id);
  589. $values = array('dbxref_id' => $dbxref->dbxref_id);
  590. $success = chado_update_record('cvterm', $match, $values);
  591. if (!$success) {
  592. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
  593. "'$name' (id: $accession), for database $dbname", NULL);
  594. return 0;
  595. }
  596. }
  597. // If we don't have the dbxref then we want to delete our cvterm and let
  598. // the code below recreate it with the correct info.
  599. else {
  600. $match = array('cvterm_id' => $cvterm->cvterm_id);
  601. chado_delete_record('cvterm', $match);
  602. }
  603. }
  604. // Check that the accession matches. Sometimes an OBO can define a term
  605. // multiple times but with different accessions. If this is the case we
  606. // can't do an insert or it will violate the constraint in the cvterm table.
  607. // So we'll need to add the record to the cvterm_dbxref table instead.
  608. if ($dbxref->accession != $accession) {
  609. // Get/add the dbxref for his term.
  610. $dbxref_new = tripal_insert_dbxref(array(
  611. 'db_id' => $db->db_id,
  612. 'accession' => $accession
  613. ));
  614. if (!$dbxref_new) {
  615. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  616. "$name (id: $accession), for database $dbname", NULL);
  617. return 0;
  618. }
  619. // Check to see if the cvterm_dbxref record already exists.
  620. $values = array(
  621. 'cvterm_id' => $cvterm->cvterm_id,
  622. 'dbxref_id' => $dbxref_new->dbxref_id,
  623. 'is_for_definition' => 1,
  624. );
  625. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  626. // if the cvterm_dbxref record does not exists then add it
  627. if (count($result)==0) {
  628. $options = array(
  629. 'return_record' => FALSE,
  630. );
  631. $success = chado_insert_record('cvterm_dbxref', $values, $options);
  632. if (!$success) {
  633. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
  634. "duplicated cvterm: $name (id: $accession), for database $dbname", NULL);
  635. return 0;
  636. }
  637. }
  638. // get the original cvterm with the same name and return that.
  639. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  640. $cvterm = $result->fetchObject();
  641. return $cvterm;
  642. }
  643. // Continue on, we've fixed the record if the db_id did not match.
  644. // We can now perform and updated if we need to.
  645. }
  646. // get the CVterm record
  647. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  648. $cvterm = $result->fetchObject();
  649. if (!$cvterm) {
  650. // Check to see if the dbxref exists if not, add it.
  651. $dbxref = tripal_insert_dbxref(array(
  652. 'db_id' => $db->db_id,
  653. 'accession' => $accession
  654. ));
  655. if (!$dbxref) {
  656. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  657. "$name (id: $accession), for database $dbname", NULL);
  658. return 0;
  659. }
  660. // Check to see if the dbxref already has an entry in the cvterm table.
  661. $values = array('dbxref_id' => $dbxref->dbxref_id);
  662. $check = chado_select_record('cvterm', array('cvterm_id'), $values);
  663. if (count($check) == 0) {
  664. // now add the cvterm
  665. $ins_values = array(
  666. 'cv_id' => $cv->cv_id,
  667. 'name' => $name,
  668. 'definition' => $definition,
  669. 'dbxref_id' => $dbxref->dbxref_id,
  670. 'is_obsolete' => $is_obsolete,
  671. 'is_relationshiptype' => $is_relationship,
  672. );
  673. $success = chado_insert_record('cvterm', $ins_values);
  674. if (!$success) {
  675. if (!$is_relationship) {
  676. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
  677. return 0;
  678. }
  679. else {
  680. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
  681. return 0;
  682. }
  683. }
  684. }
  685. // This dbxref already exists in the cvterm table.
  686. else {
  687. tripal_report_error('tripal_chado', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
  688. return 0;
  689. }
  690. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  691. $cvterm = $result->fetchObject();
  692. }
  693. // Update the cvterm.
  694. elseif ($update) {
  695. // First, basic update of the term.
  696. $match = array('cvterm_id' => $cvterm->cvterm_id);
  697. $upd_values = array(
  698. 'name' => $name,
  699. 'definition' => $definition,
  700. 'is_obsolete' => $is_obsolete,
  701. 'is_relationshiptype' => $is_relationship,
  702. );
  703. $success = chado_update_record('cvterm', $match, $upd_values);
  704. if (!$success) {
  705. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
  706. return 0;
  707. }
  708. // Second, check that the dbxref has not changed and if it has then update it.
  709. $checksql = "
  710. SELECT cvterm_id
  711. FROM {cvterm} CVT
  712. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  713. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  714. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  715. WHERE DBX.accession = :accession and DB.name = :dbname and CVT.name = :term and CV.name = :cvname
  716. ";
  717. $check = chado_query($checksql, array(':accession' => $dbxref->accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
  718. if (!$check) {
  719. // check to see if the dbxref exists if not, add it.
  720. $dbxref = tripal_insert_dbxref(array(
  721. 'db_id' => $db->db_id,
  722. 'accession' => $accession
  723. ));
  724. if (!$dbxref) {
  725. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  726. "$name (id: $accession), for database $dbname", NULL);
  727. return 0;
  728. }
  729. $match = array('cvterm_id' => $cvterm->cvterm_id);
  730. $upd_values = array(
  731. 'dbxref_id' => $dbxref->dbxref_id,
  732. );
  733. $success = chado_update_record('cvterm', $match, $upd_values);
  734. if (!$success) {
  735. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term $name with new accession $db:$accession", NULL);
  736. return 0;
  737. }
  738. }
  739. // Finally grab the updated details.
  740. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  741. $cvterm = $result->fetchObject();
  742. }
  743. else {
  744. // do nothing, we have the cvterm but we don't want to update
  745. }
  746. // return the cvterm
  747. return $cvterm;
  748. }
  749. /**
  750. * This function allows other modules to programatically
  751. * submit an ontology for loading into Chado.
  752. *
  753. * This function will add a job to the Jobs subsystem for parsing the ontology.
  754. * You can either pass a known OBO ID to the function or the URL
  755. * or full path the the ontology file. If a URL or file name is
  756. * passed then the $obo_name argument must also be provided. If
  757. * this is the first time the ontology has been provided to Tripal
  758. * then it will be added to the database and will be assigned a
  759. * unique OBO ID.
  760. *
  761. * @param $obo_id
  762. * If the ontology is already loaded into the Tripal tables then
  763. * use this argument to specify the unique ID for the ontology
  764. * that will be loaded
  765. * @param $obo_name
  766. * If the OBO has not been added before then use this argument
  767. * to specify the human readable name of the ontology.
  768. * @param $obo_url
  769. * If the OBO to be loaded is located on a remote server then
  770. * use this argument to provide the URL.
  771. * @param $obo_file
  772. * If the OBO is housed on the local file system of the server then
  773. * use this argument to specify the full path.
  774. *
  775. * @return
  776. * returns the job_id of the submitted job or FALSE if the job was not added
  777. *
  778. * @ingroup tripal_chado_api
  779. */
  780. function tripal_submit_obo_job($obo) {
  781. global $user;
  782. // Set Defaults
  783. $obo['obo_id'] = (isset($obo['obo_id'])) ? $obo['obo_id'] : NULL;
  784. $obo['name'] = (isset($obo['name'])) ? $obo['name'] : NULL;
  785. $obo['url'] = (isset($obo['url'])) ? $obo['url'] : NULL;
  786. $obo['file'] = (isset($obo['file'])) ? $obo['file'] : NULL;
  787. $includes = array(
  788. module_load_include('inc', 'tripal_chado', 'includes/loaders/tripal_chado.obo_loader'),
  789. );
  790. if ($obo['obo_id']) {
  791. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  792. $result = db_query($sql, array(':obo_id' => $obo['obo_id']))->fetchObject();
  793. $args = array($result->obo_id);
  794. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  795. "tripal_chado_load_obo_v1_2_id", $args, $user->uid, 10, $includes);
  796. }
  797. else {
  798. if ($obo['url']) {
  799. $args = array($obo['name'], $obo['url']);
  800. return tripal_add_job("Load OBO " . $obo['name'], 'tripal_chado',
  801. "tripal_chado_load_obo_v1_2_url", $args, $user->uid, 10, $includes);
  802. }
  803. elseif ($obo['file']) {
  804. $args = array($obo['name'], $obo['file']);
  805. return tripal_add_job("Load OBO " . $obo['name'], 'tripal_chado',
  806. "tripal_chado_load_obo_v1_2_file", $args, $user->uid, 10, $includes);
  807. }
  808. }
  809. return FALSE;
  810. }
  811. /**
  812. * Add the OBO to the tripal_cv_obo table in the Drupal database.
  813. *
  814. * If the OBO name already exists in the table then the path is updated.
  815. *
  816. * @param $name
  817. * The human readable name of this ontology
  818. * @param $path
  819. * The file path or URL of the ontology
  820. *
  821. * @return
  822. * Returns the ontology ID
  823. *
  824. * @ingroup tripal_chado_api
  825. */
  826. function tripal_insert_obo($name, $path) {
  827. // make sure an OBO with the same name doesn't already exist
  828. $obo_id = db_select('tripal_cv_obo', 'tco')
  829. ->fields('tco', array('obo_id'))
  830. ->condition('name', $name)
  831. ->execute()
  832. ->fetchField();
  833. if ($obo_id) {
  834. db_update('tripal_cv_obo')
  835. ->fields(array(
  836. 'path' => $path,
  837. ))
  838. ->condition('name', $name)
  839. ->execute();
  840. return $obo_id;
  841. }
  842. else {
  843. $obo_id = db_insert('tripal_cv_obo')
  844. ->fields(array(
  845. 'name' => $name,
  846. 'path' => $path,
  847. ))
  848. ->execute();
  849. return $obo_id;
  850. }
  851. }
  852. /**
  853. * Retrieves an OBO record.
  854. *
  855. * @param $values
  856. * An associate array with the following allowed keys: obo_id, name
  857. *
  858. * @return
  859. * An instance of an OBO record object.
  860. */
  861. function tripal_get_obo($values) {
  862. $query = db_select('tripal_cv_obo', 'tco')
  863. ->fields('tco');
  864. if (array_key_exists('name', $values)) {
  865. $query->condition('tco.name', $values['name']);
  866. }
  867. if (array_key_exists('obo_id', $values)) {
  868. $query->condition('tco.obo_id', $values['obo_id']);
  869. }
  870. return $query->execute()->fetchObject();
  871. }
  872. /**
  873. * This function is intended to be used in autocomplete forms
  874. * for searching for CV terms that begin with the provided string
  875. *
  876. * @param $cv_id
  877. * The CV ID in which to search for the term
  878. * @param $string
  879. * The string to search for
  880. *
  881. * @return
  882. * A json array of terms that begin with the provided string
  883. *
  884. * @ingroup tripal_chado_api
  885. */
  886. function tripal_autocomplete_cvterm($cv_id, $string = '') {
  887. if ($cv_id) {
  888. $sql = "
  889. SELECT CVT.cvterm_id, CVT.name
  890. FROM {cvterm} CVT
  891. WHERE CVT.cv_id = :cv_id and lower(CVT.name) like lower(:name)
  892. UNION
  893. SELECT CVT2.cvterm_id, CVTS.synonym as name
  894. FROM {cvterm} CVT2
  895. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  896. WHERE CVT2.cv_id = :cv_id and lower(CVTS.synonym) like lower(:name)
  897. ORDER by name
  898. LIMIT 25 OFFSET 0
  899. ";
  900. $results = chado_query($sql, array(':cv_id' => $cv_id, ':name' => $string . '%'));
  901. $items = array();
  902. foreach ($results as $term) {
  903. $items[$term->name] = $term->name;
  904. }
  905. }
  906. // If a CV wasn't provided then search all of them, and include the cv
  907. // in the results.
  908. else {
  909. $sql = "
  910. SELECT CVT.cvterm_id, CVT.name, CV.name as cvname, CVT.cv_id
  911. FROM {cvterm} CVT
  912. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  913. WHERE lower(CVT.name) like lower(:name)
  914. UNION
  915. SELECT CVT2.cvterm_id, CVTS.synonym as name, CV2.name as cvname, CVT2.cv_id
  916. FROM {cvterm} CVT2
  917. INNER JOIN {cv} CV2 on CVT2.cv_id = CV2.cv_id
  918. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  919. WHERE lower(CVTS.synonym) like lower(:name)
  920. ORDER by name
  921. LIMIT 25 OFFSET 0
  922. ";
  923. $results = chado_query($sql, array(':name' => $string . '%'));
  924. $items = array();
  925. foreach ($results as $term) {
  926. $items[$term->name] = $term->name;
  927. }
  928. }
  929. drupal_json_output($items);
  930. }
  931. /**
  932. * Add a record to a cvterm linking table (ie: feature_cvterm)
  933. *
  934. * @param $basetable
  935. * The base table to which the cvterm should be linked/associated. Thus to associate a
  936. * cvterm to a feature the basetable=feature and cvterm_id is added to the feature_cvterm table.
  937. * @param $record_id
  938. * The primary key of the basetable to associate the cvterm with. This should be in integer.
  939. * @param $cvterm
  940. * An associative array describing the cvterm. Valid keys include:
  941. * - name: the name for the cvterm,
  942. * - cv_name: the name of the cv the cvterm belongs to.
  943. * - cv_id: the primary key of the cv the cvterm belongs to.
  944. * @param $options
  945. * An associative array of options. Valid keys include:
  946. * - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is the default
  947. *
  948. * @ingroup tripal_chado_api
  949. */
  950. function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
  951. $linking_table = $basetable . '_cvterm';
  952. $foreignkey_name = $basetable . '_id';
  953. // Default Values
  954. $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
  955. // If the cvterm_id is not set then find the cvterm record using the name and cv_id
  956. if (!isset($cvterm['cvterm_id'])) {
  957. $values = array(
  958. 'name' => $cvterm['name'],
  959. );
  960. if (isset($cvterm['cv_id'])) {
  961. $values['cv_id'] = $cvterm['cv_id'];
  962. }
  963. elseif (isset($cvterm['cv_name'])) {
  964. $values['cv_id'] = array(
  965. 'name' => $cvterm['cv_name']
  966. );
  967. }
  968. else {
  969. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  970. "tripal_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
  971. supplied. You were trying to associate a cvterm with the %base %record_id
  972. and supplied the cvterm values: %cvterm.",
  973. array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
  974. );
  975. return FALSE;
  976. }
  977. // Get the cvterm. If it doesn't exist then add it if the option
  978. // 'insert_cvterm' is set.
  979. $select = chado_select_record('cvterm', array('*'), $values);
  980. if ($select) {
  981. $cvterm['cvterm_id'] = $select[0]->cvterm_id;
  982. }
  983. elseif ($options['insert_cvterm']) {
  984. // Insert the cvterm
  985. $insert = tripal_insert_cvterm($values);
  986. if (isset($insert->cvterm_id)) {
  987. $cvterm['cvterm_id'] = $insert->cvterm_id;
  988. }
  989. else {
  990. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  991. "tripal_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
  992. array('%cvterm' => print_r($cvterm,TRUE))
  993. );
  994. return FALSE;
  995. }
  996. }
  997. else {
  998. tripal_report_error('tripal_api', TRIPAL_WARNING,
  999. "tripal_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
  1000. array('%cvterm' => print_r($cvterm,TRUE))
  1001. );
  1002. return FALSE;
  1003. }
  1004. }
  1005. // Now add the link between the record & cvterm
  1006. if ($cvterm['cvterm_id'] > 0) {
  1007. $values = array(
  1008. 'cvterm_id' => $cvterm['cvterm_id'],
  1009. $foreignkey_name => $record_id,
  1010. 'pub_id' => 1,
  1011. );
  1012. // Check if the cvterm is already associated. If so, don't re-add it.
  1013. $result = chado_select_record($linking_table, array('*'), $values);
  1014. if (!$result) {
  1015. $success = chado_insert_record($linking_table, $values);
  1016. if (!$success) {
  1017. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1018. "Failed to insert the %base record %term",
  1019. array('%base' => $linking_table, '%term' => $cvterm['name'])
  1020. );
  1021. return FALSE;
  1022. }
  1023. $result = chado_select_record($linking_table, array('*'), $values);
  1024. }
  1025. if (isset($result[0])) {
  1026. return $result[0];
  1027. }
  1028. else {
  1029. return FALSE;
  1030. }
  1031. }
  1032. return FALSE;
  1033. }
  1034. /**
  1035. * This function sets the default vocabulary for a given table and field.
  1036. *
  1037. * @param $table
  1038. * The name of the table that contains a field with a foreign key
  1039. * relationship to the cvterm table
  1040. * @param $field
  1041. * The table field name that has the foreign key relationship to the
  1042. * cvterm table for which the default vocabulary will be set
  1043. * @param $cv_name
  1044. * The name of the vocabulary
  1045. *
  1046. * @return
  1047. * TRUE if set, FALSE if an error occured
  1048. */
  1049. function tripal_set_default_cv($table, $field, $cv_name, $cv_id = FALSE) {
  1050. // Get the CV object
  1051. if ($cv_id) {
  1052. $cv = tripal_get_cv(array('cv_id' => $cv_id));
  1053. }
  1054. else {
  1055. $cv = tripal_get_cv(array('name' => $cv_name));
  1056. }
  1057. if ($cv) {
  1058. // first delete any entries for this table and field
  1059. $num_deleted = db_delete('tripal_cv_defaults')
  1060. ->condition('table_name', $table)
  1061. ->condition('field_name', $field)
  1062. ->execute();
  1063. // now add the default value
  1064. $cv_default_id = db_insert('tripal_cv_defaults')
  1065. ->fields(array(
  1066. 'table_name' => $table,
  1067. 'field_name' => $field,
  1068. 'cv_id' => $cv->cv_id,
  1069. ))
  1070. ->execute();
  1071. if (!$cv_default_id) {
  1072. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  1073. "Cannot set default vocabulary for %table.%field. Check the error logs.",
  1074. array('%table' => $table, '%field' => $field));
  1075. return FALSE;
  1076. }
  1077. }
  1078. else {
  1079. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  1080. "Cannot set default vocabulary for %table.%field. The vocabulary name, '%cvname', doesn't exist.",
  1081. array('%table' => $table, '%field' => $field, '%cvname' => $cv_name));
  1082. return FALSE;
  1083. }
  1084. }