tripal_chado.cv.api.inc 39 KB

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