tripal_chado.cv.api.inc 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  1. <?php
  2. /**
  3. * @file
  4. * Provides API functions specificially for managing controlled vocabulary
  5. * records in Chado.
  6. *
  7. * @ingroup tripal_chado
  8. */
  9. /**
  10. * @defgroup tripal_chado_cv_api Chado CV
  11. * @ingroup tripal_chado_api
  12. * @{
  13. * Provides API functions specificially for managing controlled vocabulary
  14. * records in Chado. Please note that Tripal v3 provides a generic set of
  15. * API functions for working with controlled vocabularies (CVs). This allows for
  16. * CVs to be stored using any back-end. By default CV's continue to be housed
  17. * in Chado. Therefore, if you are working directly with controlled vocabulary
  18. * records inside of a Chado-aware module then these functions can be used.
  19. * @}
  20. */
  21. /**
  22. * Retrieves a chado controlled vocabulary variable
  23. *
  24. * @param $identifier
  25. * An array with the key stating what the identifier is. Supported keys (only
  26. * on of the following unique keys is required):
  27. * - cv_id: the chado cv.cv_id primary key.
  28. * - name: the chado cv.name field (assume unique).
  29. * @param $options
  30. * An array of options. Supported keys include:
  31. * - Any keys supported by chado_generate_var(). See that function
  32. * definition fot additional details.
  33. *
  34. * NOTE: the $identifier parameter can really be any array similar to $values
  35. * passed into chado_select_record(). It should fully specify the cv record to
  36. * be returned.
  37. *
  38. * @return
  39. * If unique values were passed in as an identifier then an object describing
  40. * the cv will be returned (will be a chado variable from
  41. * chado_generate_var()). Otherwise, FALSE will be returned.
  42. *
  43. * @ingroup tripal_chado_cv_api
  44. */
  45. function chado_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. "chado_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. "chado_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. "chado_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. "chado_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_cv_api
  118. */
  119. function chado_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_chado_cv_api
  161. */
  162. function chado_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. "chado_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. "chado_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
  185. // chado_generate_var().
  186. if (isset($identifiers['synonym'])) {
  187. $synonym = $identifiers['synonym']['name'];
  188. $values = array('synonym' => $synonym);
  189. if (isset($identifiers['synonym']['cv_id'])) {
  190. $values['cvterm_id'] = array('cv_id' => $identifiers['synonym']['cv_id']);
  191. }
  192. if (isset($identifiers['synonym']['cv_name'])) {
  193. $values['cvterm_id'] = array('cv_id' => array('name' => $identifiers['synonym']['cv_name']));
  194. }
  195. $options = array(
  196. 'case_insensitive_columns' => array('name')
  197. );
  198. $result = chado_select_record('cvtermsynonym', array('cvterm_id'), $values, $options);
  199. // if the synonym doens't exist or more than one record is returned then
  200. // return false.
  201. if (count($result) == 0) {
  202. return FALSE;
  203. }
  204. if (count($result) > 1) {
  205. return FALSE;
  206. }
  207. $identifiers = array('cvterm_id' => $result[0]->cvterm_id);
  208. }
  209. // If one of the identifiers is property then use chado_get_record_with_property().
  210. if (isset($identifiers['property'])) {
  211. $property = $identifiers['property'];
  212. unset($identifiers['property']);
  213. $cvterm = chado_get_record_with_property(
  214. array('table' => 'cvterm', 'base_records' => $identifiers),
  215. array('type_name' => $property),
  216. $options
  217. );
  218. }
  219. if (isset($identifiers['id'])) {
  220. list($db_name, $accession) = preg_split('/:/', $identifiers['id']);
  221. $cvterm = chado_generate_var('cvterm',array(
  222. 'dbxref_id' => array(
  223. 'db_id' => array(
  224. 'name' => $db_name,
  225. ),
  226. 'accession' => $accession,
  227. )
  228. ));
  229. }
  230. // Else we have a simple case and we can just use chado_generate_var to get
  231. // the cvterm.
  232. else {
  233. // Try to get the cvterm.
  234. $cvterm = chado_generate_var('cvterm', $identifiers, $options);
  235. }
  236. // Ensure the cvterm is singular. If it's an array then it is not singular.
  237. if (is_array($cvterm)) {
  238. tripal_report_error(
  239. 'tripal_cv_api',
  240. TRIPAL_ERROR,
  241. "chado_get_cvterm: The identifiers you passed in were not unique. You passed in %identifier.",
  242. array(
  243. '%identifier'=> print_r($identifiers, TRUE)
  244. )
  245. );
  246. }
  247. // Report an error if $cvterm is FALSE since then chado_generate_var has
  248. // failed.
  249. elseif ($cvterm === FALSE) {
  250. tripal_report_error(
  251. 'tripal_cv_api',
  252. TRIPAL_ERROR,
  253. "chado_get_cvterm: chado_generate_var() failed to return a cvterm based on the identifiers
  254. you passed in. You should check that your identifiers are correct, as well as, look
  255. for a chado_generate_var error for additional clues. You passed in %identifier.",
  256. array(
  257. '%identifier'=> print_r($identifiers, TRUE)
  258. )
  259. );
  260. }
  261. // Else, as far we know, everything is fine so give them their cvterm :)
  262. else {
  263. return $cvterm;
  264. }
  265. }
  266. /**
  267. * Create an options array to be used in a form element
  268. * which provides a list of all chado cvterms.
  269. *
  270. * @param $cv_id
  271. * The chado cv_id; only cvterms with the supplied cv_id will be returnedl.
  272. * @param $rel_type
  273. * Set to TRUE if the terms returned should only be relationship types in
  274. * the vocabulary. This is useful for creating drop-downs of terms
  275. * used for relationship linker tables.
  276. *
  277. * @return
  278. * An associative array with the cvterm_id's as keys. The first
  279. * element in the array has a key of '0' and a value of 'Select a Type'.
  280. *
  281. * @ingroup tripal_chado_cv_api
  282. */
  283. function chado_get_cvterm_select_options($cv_id, $rel_type = FALSE) {
  284. $columns = array('cvterm_id', 'name');
  285. $values = array('cv_id' => $cv_id);
  286. if ($rel_type) {
  287. $values['is_relationshiptype'] = 1;
  288. }
  289. $s_options = array('order_by' => array('name' => 'ASC'));
  290. $cvterms = chado_select_record('cvterm', $columns, $values, $s_options);
  291. $options = array();
  292. $options[0] = 'Select a Type';
  293. foreach ($cvterms as $cvterm) {
  294. $options[$cvterm->cvterm_id] = $cvterm->name;
  295. }
  296. return $options;
  297. }
  298. /**
  299. * Updates the cvtermpath table of Chado for the specified CV.
  300. *
  301. * @param $cv_id
  302. * The chado cv_id.
  303. * @param $job_id
  304. * This function is intended to be used with the Tripal Jobs API.
  305. * When this function is called as a job the $job_id is automatically
  306. * passed to this function.
  307. * @return
  308. * TRUE on success FALSE on failure.
  309. *
  310. * @ingroup tripal_chado_cv_api
  311. */
  312. function tripal_update_cvtermpath_old($cv_id, $job_id = NULL) {
  313. // TODO: need better error checking in this function
  314. // First get the controlled vocabulary name:
  315. $sql = "SELECT * FROM {cv} WHERE cv_id = :cv_id";
  316. $cv = chado_query($sql, array(':cv_id' => $cv_id))->fetchObject();
  317. print "\nUpdating cvtermpath for $cv->name...\n";
  318. // We need to set the chado schema as active because some of the
  319. // functions call other functions which would not be in scope.
  320. $previous = chado_set_active('chado');
  321. try {
  322. $sql = "SELECT * FROM fill_cvtermpath(:name)";
  323. db_query($sql, array(':name' => $cv->name));
  324. chado_set_active($previous);
  325. }
  326. catch (Exception $e) {
  327. chado_set_active($previous);
  328. $error = $e->getMessage();
  329. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath table: @error", array('@error' => $error));
  330. return FALSE;
  331. }
  332. return TRUE;
  333. }
  334. /**
  335. * Duplicate of fill_cvtermpath() stored procedure in Chado.
  336. *
  337. * Identifies all of the root terms of the controlled vocabulary. These
  338. * root terms are then processed by calling the
  339. * _chado_update_cvtermpath_root_loop() function on each one.
  340. *
  341. * @param $cvid
  342. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  343. * @param $job_id
  344. *
  345. * @ingroup tripal_chado_cv_api
  346. */
  347. function chado_update_cvtermpath($cv_id, $job_id = NULL){
  348. // TODO: there's a function to determine the current Chado instance.
  349. // we should use that.
  350. $prev_db = chado_set_active('chado');
  351. print "\nNOTE: Updating CV Term Path is performed using a database transaction. \n" .
  352. "If the update fails or is terminated prematurely then any new changes \n" .
  353. "made will be rolled back.\n\n";
  354. $transaction = db_transaction();
  355. try {
  356. $result = db_query('
  357. SELECT DISTINCT t.*
  358. FROM cvterm t
  359. LEFT JOIN cvterm_relationship r ON (t.cvterm_id = r.subject_id)
  360. INNER JOIN cvterm_relationship r2 ON (t.cvterm_id = r2.object_id)
  361. WHERE t.cv_id = :cvid AND r.subject_id is null',
  362. array(':cvid' => $cv_id)
  363. );
  364. // Iterate through each root level term.
  365. $record = $result->fetchAll();
  366. $roots = [];
  367. foreach ($record as $item){
  368. _chado_update_cvtermpath_root_loop($item->cvterm_id, $item->cv_id, $roots);
  369. }
  370. }
  371. catch (Exception $e) {
  372. // Rollback any database changes
  373. $transaction->rollback();
  374. throw $e;
  375. }
  376. finally {
  377. // Set the database back
  378. chado_set_active($prev_db);
  379. }
  380. }
  381. /**
  382. * Duplicate of _fill_cvtermpath4root() stored procedure in Chado.
  383. *
  384. * This function process a "branch" of the ontology. Initially, the
  385. * "root" starts at the top of the tree. But, as the cvtermpath is populated
  386. * the "root" becomes terms deeper in the tree.
  387. *
  388. * @param $rootid
  389. * The term ID from the cvterm table of Chado (i.e. cvterm.cvterm_id).
  390. * @param $cvid
  391. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  392. *
  393. * @ingroup tripal_chado_cv_api
  394. */
  395. function _chado_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
  396. $ttype = db_query(
  397. 'SELECT cv.cvterm_id
  398. FROM cvterm cv
  399. WHERE cv.name = :isa
  400. OR cv.name = :is_a
  401. '
  402. ,
  403. array(':isa' => "isa", ':is_a' => "is_a")
  404. );
  405. $result = $ttype->fetchObject();
  406. $term_id = $rootid . '|' . $rootid . '|' . $cvid . '|' . $result->cvterm_id;
  407. // If the child_id matches any other id in the array then we've hit a loop.
  408. foreach ($roots as $element_id) {
  409. if ($element_id == $term_id) {
  410. return;
  411. }
  412. }
  413. // Then add that new entry to the $tree_path.
  414. $roots[] = $term_id;
  415. // Descends through the branch starting at this "root" term.
  416. $tree_path = [];
  417. $matched_rows = [];
  418. $possible_start_of_loop = [];
  419. $depth = 0;
  420. _chado_update_cvtermpath_loop($rootid, $rootid, $cvid, $result->cvterm_id, $depth,
  421. 0, $tree_path, FALSE, $matched_rows, $possible_start_of_loop, FALSE);
  422. // Get's the children terms of this "root" term and then recursively calls
  423. // this function making each child root.
  424. $cterm = db_query(
  425. 'SELECT *
  426. FROM cvterm_relationship
  427. WHERE object_id = :rootid
  428. ',
  429. [':rootid' => $rootid]
  430. );
  431. while ($cterm_result = $cterm->fetchAssoc()) {
  432. _chado_update_cvtermpath_root_loop($cterm_result['subject_id'], $cvid, $roots);
  433. }
  434. }
  435. /**
  436. *
  437. * @param $origin
  438. * The root terms cvterm_id.
  439. * @param $child_id
  440. * The cvterm_id of the current child term. The child term is a descendent
  441. * of the origin.
  442. * @param $cv_id
  443. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  444. * @param $type_id
  445. * The relationship type between the origin term and the child.
  446. * @param $depth
  447. * The depth of the recursion.
  448. * @param $increment_of_depth.
  449. * An integer tailing the number of children that have been walked down.
  450. * @param $tree_path.
  451. * The array of every term between the current child and the origin. Each
  452. * element in the array is an associative array with the keys:
  453. * -build_id: an string identifier for the child that combines the origin,
  454. * child cvterm_id,cv_id, and the type_id.
  455. * -depth: the depth that a child was inserted into the cvtermpath table.
  456. * @param $possible_loop
  457. * A boolean flag.
  458. * @param $matched_row
  459. * An array of rows that are currently in the cvtermpath table that match the
  460. * build_id of the current term trying to be written to the table
  461. * @param $possible_start_of_ loop
  462. * The array of the possible loop item between the current child and the
  463. * origin. Each element in the array is an associative array with the keys:
  464. * - cvid : $cv_id
  465. * - subject_id:
  466. * - child_id : $child_id,
  467. * - type_id : $type_id,
  468. * - depth : $depth,
  469. * @param $no_loop_skip_test
  470. * A boolean used when the possible loop has been ruled out as a loop.
  471. *
  472. *
  473. * @ingroup tripal_chado_cv_api
  474. */
  475. function _chado_update_cvtermpath_loop(
  476. $origin,
  477. $child_id,
  478. $cv_id,
  479. $type_id,
  480. $depth,
  481. $increment_of_depth,
  482. $tree_path,
  483. $possible_loop,
  484. $matched_rows,
  485. $possible_start_of_loop,
  486. $no_loop_skip_test) {
  487. // We have not detected a loop, so it's safe to insert the term.
  488. $new_match_rows = [];
  489. if (!empty($possible_start_of_loop)) {
  490. // Go through each matched_row.
  491. if (count($matched_rows) === 1) {
  492. // Get the cvtermpath_id and then increment down one row.
  493. $cvtermpath_id = (int) $matched_rows[0]->cvtermpath_id;
  494. $cvtermpath_id = $cvtermpath_id + 1;
  495. chado_set_active('chado');
  496. $next_row = db_query(
  497. 'SELECT *
  498. FROM cvtermpath
  499. WHERE cvtermpath_id = :cvtermpath_id
  500. ',
  501. [':cvtermpath_id' => $cvtermpath_id]
  502. );
  503. $next_row = $next_row->fetchObject();
  504. // If the next row matches the values passed we can't rule out a loop.
  505. if (($next_row->type_id === $type_id) &&
  506. ($next_row->subject_id === $child_id) &&
  507. ($next_row->object_id === $origin) &&
  508. ($next_row->cv_id === $cv_id)) {
  509. $new_match_rows[] = $next_row;
  510. }
  511. elseif (($next_row->type_id === $possible_start_of_loop['type_id']) &&
  512. ($next_row->subject_id === $possible_start_of_loop['subject_id']) &&
  513. ($next_row->object_id === $possible_start_of_loop['object_id']) &&
  514. ($next_row->cv_id === $possible_start_of_loop['cv_id'])) {
  515. // The next_row is equal to start of loop, so we've reached the end
  516. // and confirmed that this is a loop.
  517. $possible_loop == FALSE;
  518. $matched_rows = [];
  519. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  520. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  521. $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
  522. }
  523. }
  524. else {
  525. foreach ($matched_rows as $matched_row) {
  526. // Get the cvtermpath_id and then increment down one row.
  527. $cvtermpath_id = (int) $match_row->cvtermpath_id;
  528. // Get the cvtermpath_id and then increment down one row.
  529. $cvtermpath_id = $cvtermpath_id + 1;
  530. chado_set_active('chado');
  531. $next_row = db_query(
  532. 'SELECT *
  533. FROM cvtermpath
  534. WHERE cvtermpath_id = :cvtermpath_id
  535. ',
  536. [':cvtermpath_id' => $cvtermpath_id]
  537. );
  538. $next_row = $next_row->fetchObject();
  539. // If the next row matches the values passed we can't rule out a loop.
  540. if (($next_row->type_id === $type_id) &&
  541. ($next_row->subject_id === $child_id) &&
  542. ($next_row->object_id === $origin) &&
  543. ($next_row->cv_id === $cv_id)) {
  544. $new_match_rows[] = $next_row;
  545. }
  546. elseif (($next_row->type_id === $possible_start_of_loop['type_id']) &&
  547. ($next_row->subject_id === $possible_start_of_loop['subject_id']) &&
  548. ($next_row->object_id === $possible_start_of_loop['object_id']) &&
  549. ($next_row->cv_id === $possible_start_of_loop['cv_id'])) {
  550. // The next_row is equal to start of loop, so we've reached the end
  551. // and confirmed that this is a loop.
  552. $possible_loop == FALSE;
  553. $matched_rows = [];
  554. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  555. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  556. $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
  557. }
  558. }
  559. }
  560. // If $match_rows is empty there is no loop.
  561. if (empty($new_match_rows)) {
  562. $possible_loop == FALSE;
  563. $matched_rows = [];
  564. unset($new_match_rows);
  565. $no_loop_skip_test = TRUE;
  566. // There is not loop so pass it back the possible_start_of_loop info
  567. // and a flag telling it to skip the loop check.
  568. _chado_update_cvtermpath_loop_increment($possible_start_of_loop->subject_id,
  569. $possible_start_of_loop->child_id, $possible_start_of_loop->cvid,
  570. $possible_start_of_loop->type_id, $possible_start_of_loop->depth,
  571. $increment_of_depth, $tree_path, $possible_loop, $matched_rows,
  572. $possible_start_of_loop, $no_loop_skip_test);
  573. }
  574. // If $match_rows is not empty we need to keep trying rows.
  575. else {
  576. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  577. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  578. $match_rows, $possible_start_of_loop, $no_loop_skip_test);
  579. }
  580. }
  581. elseif ($possible_loop === FALSE) {
  582. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  583. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  584. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  585. }
  586. }
  587. /**
  588. *
  589. * @param $origin
  590. * The root terms cvterm_id.
  591. * @param $child_id
  592. * The cvterm_id of the current child term. The child term is a descendent
  593. * of the origin.
  594. * @param $cv_id
  595. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  596. * @param $type_id
  597. * The relationship type between the origin term and the child.
  598. * @param $depth
  599. * The depth of the recursion.
  600. * @param $increment_of_depth.
  601. * An integer.
  602. * @param $tree_path.
  603. * The array of every term between the current child and the origin. Each
  604. * element in the array is an associative array with the keys:
  605. * -build_id: an string identifier for the child that combines the origin,
  606. * child cvterm_id,cv_id, and the type_id.
  607. * -depth: the depth that a child was inserted into the cvtermpath table.
  608. * @param $possible_loop
  609. * A boolean flag.
  610. * @param $matched_row
  611. * An array of rows that are currently in the cvtermpath table that match the
  612. * build_id of the current term trying to be written to the table
  613. * @param $possible_start_of_ loop
  614. * The array of the possible loop item between the current child and the origin.
  615. * Each element in the array is an associative array with the keys:
  616. * - cvid : $cv_id
  617. * - subject_id:
  618. * - child_id : $child_id,
  619. * - type_id : $type_id,
  620. * - depth : $depth,
  621. * @param $no_loop_skip_test
  622. * A boolean used when the possible loop has been ruled out as a loop.
  623. * @return multitype: Either a number that represents the row count of existing
  624. * rows that already match these specification or a Boolean false.
  625. *
  626. * @ingroup tripal_chado_cv_api
  627. */
  628. function _chado_update_cvtermpath_loop_increment(
  629. $origin,
  630. $child_id,
  631. $cv_id,
  632. $type_id,
  633. $depth,
  634. $increment_of_depth,
  635. $tree_path,
  636. $possible_loop,
  637. $matched_rows,
  638. &$possible_start_of_loop,
  639. $no_loop_skip_test) {
  640. // Check to see if a row with these values already exists.
  641. if ($possible_loop === FALSE && empty($possible_start_of_loop)) {
  642. chado_set_active('chado');
  643. $count = db_query(
  644. ' SELECT *
  645. FROM cvtermpath
  646. WHERE object_id = :origin
  647. AND subject_id = :child_id
  648. AND pathdistance = :depth
  649. AND type_id = :type_id
  650. ',
  651. [
  652. ':origin' => $origin,
  653. ':child_id' => $child_id,
  654. ':depth' => $depth,
  655. ':type_id' => $type_id
  656. ]
  657. );
  658. $count->fetchAll();
  659. $count_total = $count->rowCount();
  660. if ($count_total > 0) {
  661. return $count;
  662. }
  663. // Build the ID.
  664. $term_id = $origin . '|' . $child_id . '|' . $cv_id . '|' . $type_id;
  665. if ($no_loop_skip_test === FALSE) {
  666. // If the increment of depth is 0 then it's the first time and we need to
  667. // skip the test so we can build the tree_path which will be tested against.
  668. if ($increment_of_depth != 0) {
  669. // Search the $tree_path for the new $child_id in the build_id column.
  670. foreach ($tree_path as $parent) {
  671. // If this child is the same as a parent term that has already been
  672. // processed then we have a potential loop.
  673. if ($parent['build_id'] == $term_id) {
  674. // Tell the function this is a possible loop and to stop writing to
  675. // the table.
  676. $possible_loop = TRUE;
  677. // Find all the results in the table that might be the start of the
  678. // loop.
  679. $matching_rows = db_query(
  680. ' SELECT *
  681. FROM cvtermpath
  682. WHERE cv_id = :cvid
  683. AND object_id = :origin
  684. AND subject_id = :child_id
  685. AND type_id = :type_id
  686. ',
  687. [
  688. ':cvid' => $cv_id,
  689. ':origin' => $origin,
  690. ':child_id' => $child_id,
  691. ':type_id' => $type_id
  692. ]
  693. );
  694. $matched_rows = $matching_rows->fetchAll();
  695. $possible_start_of_loop = array(
  696. 'cvid' => $cv_id,
  697. 'subject_id' => $origin,
  698. 'child_id' => $child_id,
  699. 'type_id' => $type_id,
  700. 'depth' => $depth,
  701. );
  702. }
  703. }
  704. }
  705. $find_query = db_select('chado.cvtermpath', 'CVTP');
  706. $find_query->fields('CVTP', ['subject_id']);
  707. $find_query->condition('object_id', $origin);
  708. $find_query->condition('subject_id', $child_id);
  709. $find_query->condition('type_id', $type_id);
  710. $find_query->condition('pathdistance', $depth);
  711. $exists = $find_query->execute()->fetchObject();
  712. if(!$exists){
  713. $query = db_insert('cvtermpath')
  714. ->fields([
  715. 'object_id' => $origin,
  716. 'subject_id' => $child_id,
  717. 'cv_id' => $cv_id,
  718. 'type_id' => $type_id,
  719. 'pathdistance' => $depth,
  720. ]);
  721. try {
  722. $rows = $query->execute();
  723. } catch (Exception $e) {
  724. $error = $e->getMessage();
  725. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath term: @error", array('@error' => $error));
  726. return false;
  727. }
  728. }
  729. // Then add that new entry to the $tree_path.
  730. $tree_path[$increment_of_depth] = [
  731. 'build_id' => $term_id,
  732. 'depth' => $depth
  733. ];
  734. }
  735. // Reset to FALSE and empty variable if passed in as TRUE.
  736. $no_loop_skip_test == FALSE;
  737. $possible_start_of_loop = [];
  738. // Get all of the relationships of this child term, and recursively
  739. // call the _chado_update_cvtermpath_loop_increment() function to continue
  740. // descending down the tree.
  741. $query = db_select('cvterm_relationship', 'cvtr')
  742. ->fields('cvtr')
  743. ->condition('cvtr.object_id', $child_id, '=')
  744. ->execute();
  745. $cterm_relationships = $query->fetchAll();
  746. foreach ($cterm_relationships as $item) {
  747. $increment_of_depth++;
  748. _chado_update_cvtermpath_loop_increment($origin, $item->subject_id, $cv_id,
  749. $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  750. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  751. }
  752. }
  753. elseif ($possible_loop === FALSE && !empty($possible_start_of_loop)) {
  754. // This means a loop has been identified and the recursive call can move
  755. // on to the next item and skip the rest of this run.
  756. return $possible_start_of_loop;
  757. }
  758. elseif ($possible_loop === TRUE) {
  759. // Get all of the relationships of this child term, and recursively
  760. // call the _chado_update_cvtermpath_loop() function to continue
  761. // descending down the tree.
  762. $query = db_select('cvterm_relationship', 'cvtr')
  763. ->fields('cvtr')
  764. ->condition('cvtr.object_id', $child_id, '=')
  765. ->execute();
  766. $cterm_relationships = $query->fetchAll();
  767. foreach ($cterm_relationships as $item) {
  768. $increment_of_depth++;
  769. _chado_update_cvtermpath_loop($origin, $item->subject_id, $cv_id,
  770. $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  771. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  772. }
  773. }
  774. }
  775. /**
  776. * Adds a controlled vocabulary to the CV table of Chado.
  777. *
  778. * @param $name
  779. * The name of the controlled vocabulary. These are typically all lower case
  780. * with no special characters other than an undrescore (for spaces).
  781. * @param $comment
  782. * A description or definition of the vocabulary.
  783. *
  784. * @return
  785. * An object populated with fields from the newly added database.
  786. *
  787. * @ingroup tripal_chado_cv_api
  788. */
  789. function chado_insert_cv($name, $definition) {
  790. // Insert/update values.
  791. $ins_values = array(
  792. 'name' => $name,
  793. 'definition' => $definition
  794. );
  795. // See if the CV default exists already in the database.
  796. $sel_values = array('name' => $name);
  797. $results = chado_select_record('cv', array('*'), $sel_values);
  798. // If it does not exists then add it.
  799. if (count($results) == 0) {
  800. $success = chado_insert_record('cv', $ins_values);
  801. if (!$success) {
  802. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to create the CV record", NULL);
  803. return FALSE;
  804. }
  805. $results = chado_select_record('cv', array('*'), $sel_values);
  806. }
  807. // If it already exists then do an update.
  808. else {
  809. $success = chado_update_record('cv', $sel_values, $ins_values);
  810. if (!$success) {
  811. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the CV record", NULL);
  812. return FALSE;
  813. }
  814. $results = chado_select_record('cv', array('*'), $sel_values);
  815. }
  816. // Return the cv object.
  817. return $results[0];
  818. }
  819. /**
  820. * Add's a controlled vocabulary term to Chado.
  821. *
  822. * This function will add a cvterm record (and a dbxref record if appropriate
  823. * values are provided). If the parent vocabulary does not exist then
  824. * that also is added to the cv table. If the cvterm is a relationship term
  825. * then the 'is_relationship' value should be set. All
  826. * terms must also have a corresponding database. This is specified in the
  827. * term's ID just before the colon (e.g. GO:003824). If the database does not
  828. * exist in the DB table then it will be added automatically. The accession
  829. * (the value just after the colon in the term's ID) will be added to the
  830. * dbxref table. If the CVterm already exists and $update is set (default)
  831. * then the cvterm is updated. If the CVTerm already exists and $update is
  832. * not set, then no changes are made and the CVTerm object is returned.
  833. *
  834. * @param $term
  835. * An associative array with the following keys:
  836. * - id: the term accession. must be of the form <DB>:<ACCESSION>, where
  837. * <DB> is the name of the database to which the cvterm belongs and the
  838. * <ACCESSION> is the term's accession number in the database.
  839. * - name: the name of the term. usually meant to be human-readable.
  840. * - is_obsolete: is present and set to 1 if the term is defunct.
  841. * - definition: the definition of the term.
  842. * - cv_name: The CV name to which the term belongs. If this arugment is
  843. * null or not provided then the function tries to find a record in the
  844. * CV table with the same name provided in the $term[namespace]. If
  845. * this field is provided then it overrides what the value in
  846. * $term[namespace].
  847. * - is_relationship: If this term is a relationship term then this value
  848. * should be 1.
  849. * - db_name: In some cases the database name will not be part of the
  850. * $term['id'] and it needs to be explicitly set. Use this argument
  851. * only if the database name cannot be specififed in the term ID
  852. * (e.g. <DB>:<ACCESSION>).
  853. * @param $options
  854. * An associative array with the following keys:
  855. * - update_existing: By default this is TRUE. If the term exists it is
  856. * automatically updated.
  857. *
  858. * @return
  859. * A cvterm object
  860. *
  861. * @ingroup tripal_chado_cv_api
  862. */
  863. function chado_insert_cvterm($term, $options = array()) {
  864. // Get the term properties.
  865. $id = (isset($term['id'])) ? $term['id'] : '';
  866. $name = '';
  867. $cvname = '';
  868. $definition = '';
  869. $is_obsolete = 0;
  870. $accession = '';
  871. // Set Defaults.
  872. if (isset($term['cv_name'])) {
  873. $cvname = $term['cv_name'];
  874. }
  875. else {
  876. $cvname = 'local';
  877. }
  878. // Namespace is deprecated but must be supported for backwards
  879. // compatability.
  880. if (array_key_exists('namespace', $term)) {
  881. $cvname = $term['namespace'];
  882. }
  883. if (isset($term['is_relationship'])) {
  884. $is_relationship = $term['is_relationship'];
  885. }
  886. else {
  887. $is_relationship = 0;
  888. }
  889. if (isset($term['db_name'])) {
  890. $dbname = $term['db_name'];
  891. }
  892. else {
  893. $dbname = 'internal';
  894. }
  895. if (isset($options['update_existing'])) {
  896. $update = $options['update_existing'];
  897. }
  898. else {
  899. $update = 1;
  900. }
  901. if (array_key_exists('name', $term)) {
  902. $name = $term['name'];
  903. }
  904. else {
  905. $name = $id;
  906. }
  907. if (array_key_exists('definition', $term)) {
  908. $definition = preg_replace('/^\"(.*)\"/', '\1', $term['definition']);
  909. }
  910. else {
  911. $definition = '';
  912. }
  913. if (array_key_exists('is_obsolete', $term)) {
  914. $is_obsolete = $term['is_obsolete'];
  915. if (strcmp($is_obsolete, 'true') == 0) {
  916. $is_obsolete = 1;
  917. }
  918. }
  919. if (!$name and !$id) {
  920. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
  921. return 0;
  922. }
  923. if (!$id) {
  924. $id = $name;
  925. }
  926. // Get the accession and the database from the cvterm id.
  927. if ($dbname) {
  928. $accession = $id;
  929. }
  930. if (preg_match('/^.+?:.*$/', $id)) {
  931. $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
  932. $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
  933. }
  934. // Check that we have a database name, give a different message if it's a
  935. // relationship.
  936. if ($is_relationship and !$dbname) {
  937. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database name is not provided for this relationship term: $id", NULL);
  938. return 0;
  939. }
  940. if (!$is_relationship and !$dbname) {
  941. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database identifier is missing from the term: $id", NULL);
  942. return 0;
  943. }
  944. // Make sure the CV name exists.
  945. $cv = chado_get_cv(array('name' => $cvname));
  946. if (!$cv) {
  947. $cv = chado_insert_cv($cvname, '');
  948. }
  949. if (!$cv) {
  950. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find namespace '$cvname' when adding/updating $id", NULL);
  951. return 0;
  952. }
  953. // This SQL statement will be used a lot to find a cvterm so just set it
  954. // here for easy reference below. Because CV terms can change their names
  955. // but accessions don't change, the following SQL finds cvterms based on
  956. // their accession rather than the name.
  957. $cvtermsql = "
  958. SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
  959. DB.name as dbname, DB.db_id, DBX.accession
  960. FROM {cvterm} CVT
  961. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  962. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  963. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  964. WHERE DBX.accession = :accession and DB.name = :name
  965. ";
  966. // Add the database. The function will just return the DB object if the
  967. // database already exists.
  968. $db = chado_get_db(array('name' => $dbname));
  969. if (!$db) {
  970. $db = chado_insert_db(array('name' => $dbname));
  971. }
  972. if (!$db) {
  973. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
  974. return 0;
  975. }
  976. // The cvterm table has two unique dependencies. We need to check both.
  977. // first check the (name, cv_id, is_obsolete) constraint.
  978. $values = array(
  979. 'name' => $name,
  980. 'is_obsolete' => $is_obsolete,
  981. 'cv_id' => array(
  982. 'name' => $cvname,
  983. ),
  984. );
  985. $result = chado_select_record('cvterm', array('*'), $values);
  986. if (count($result) == 1) {
  987. $cvterm = $result[0];
  988. // Get the dbxref record.
  989. $values = array('dbxref_id' => $cvterm->dbxref_id);
  990. $result = chado_select_record('dbxref', array('*'), $values);
  991. $dbxref = $result[0];
  992. if (!$dbxref) {
  993. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  994. 'Unable to access the dbxref record for the :term cvterm. Term Record: !record',
  995. array(':term' => $name, '!record' => print_r($cvterm, TRUE))
  996. );
  997. return FALSE;
  998. }
  999. // Get the db.
  1000. $values = array('db_id' => $dbxref->db_id);
  1001. $result = chado_select_record('db', array('*'), $values);
  1002. $db_check = $result[0];
  1003. // // The database name for this existing term does not match that of the
  1004. // // one provided to this function. The CV name matches otherwise we
  1005. // // wouldn't have made it this far. So, let's swap the database for
  1006. // // this term.
  1007. // if ($db_check->name != $db->name) {
  1008. // // Look to see if the correct dbxref record already exists for this
  1009. // // database.
  1010. // $values = array(
  1011. // 'db_id' => $db->db_id,
  1012. // 'accession' => $accession,
  1013. // );
  1014. // $result = chado_select_record('dbxref', array('*'), $values);
  1015. // // If we already have a good dbxref then we want to update our cvterm
  1016. // // to use this dbxref.
  1017. // if (count($result) > 0) {
  1018. // $dbxref = $result[0];
  1019. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  1020. // $values = array('dbxref_id' => $dbxref->dbxref_id);
  1021. // $success = chado_update_record('cvterm', $match, $values);
  1022. // if (!$success) {
  1023. // tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
  1024. // "'$name' (id: $accession), for database $dbname", NULL);
  1025. // return 0;
  1026. // }
  1027. // }
  1028. // // If we don't have the dbxref then we want to delete our cvterm and let
  1029. // // the code below recreate it with the correct info.
  1030. // else {
  1031. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  1032. // chado_delete_record('cvterm', $match);
  1033. // }
  1034. // }
  1035. // Check that the accession matches. Sometimes an OBO can define a term
  1036. // multiple times but with different accessions. If this is the case we
  1037. // can't do an insert or it will violate the constraint in the cvterm table.
  1038. // So we'll need to add the record to the cvterm_dbxref table instead.
  1039. if ($dbxref->accession != $accession) {
  1040. // Get/add the dbxref for his term.
  1041. $dbxref_new = chado_insert_dbxref(array(
  1042. 'db_id' => $db->db_id,
  1043. 'accession' => $accession
  1044. ));
  1045. if (!$dbxref_new) {
  1046. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1047. "$name (id: $accession), for database $dbname", NULL);
  1048. return 0;
  1049. }
  1050. // Check to see if the cvterm_dbxref record already exists.
  1051. $values = array(
  1052. 'cvterm_id' => $cvterm->cvterm_id,
  1053. 'dbxref_id' => $dbxref_new->dbxref_id,
  1054. 'is_for_definition' => 1,
  1055. );
  1056. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  1057. // if the cvterm_dbxref record does not exists then add it
  1058. if (count($result)==0) {
  1059. $options = array(
  1060. 'return_record' => FALSE,
  1061. );
  1062. $success = chado_insert_record('cvterm_dbxref', $values, $options);
  1063. if (!$success) {
  1064. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
  1065. "duplicated cvterm: $name (id: $accession), for database $dbname", NULL);
  1066. return 0;
  1067. }
  1068. }
  1069. // Get the original cvterm with the same name and return that.
  1070. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  1071. $cvterm = $result->fetchObject();
  1072. return $cvterm;
  1073. }
  1074. // Continue on, we've fixed the record if the db_id did not match.
  1075. // We can now perform and updated if we need to.
  1076. }
  1077. // Get the CVterm record.
  1078. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1079. $cvterm = $result->fetchObject();
  1080. if (!$cvterm) {
  1081. // Check to see if the dbxref exists if not, add it.
  1082. $dbxref = chado_insert_dbxref(array(
  1083. 'db_id' => $db->db_id,
  1084. 'accession' => $accession
  1085. ));
  1086. if (!$dbxref) {
  1087. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1088. "$name (id: $accession), for database $dbname", NULL);
  1089. return 0;
  1090. }
  1091. // Check to see if the dbxref already has an entry in the cvterm table.
  1092. $values = array('dbxref_id' => $dbxref->dbxref_id);
  1093. $check = chado_select_record('cvterm', array('cvterm_id'), $values);
  1094. if (count($check) == 0) {
  1095. // now add the cvterm
  1096. $ins_values = array(
  1097. 'cv_id' => $cv->cv_id,
  1098. 'name' => $name,
  1099. 'definition' => $definition,
  1100. 'dbxref_id' => $dbxref->dbxref_id,
  1101. 'is_obsolete' => $is_obsolete,
  1102. 'is_relationshiptype' => $is_relationship,
  1103. );
  1104. $success = chado_insert_record('cvterm', $ins_values);
  1105. if (!$success) {
  1106. if (!$is_relationship) {
  1107. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
  1108. return 0;
  1109. }
  1110. else {
  1111. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
  1112. return 0;
  1113. }
  1114. }
  1115. }
  1116. // This dbxref already exists in the cvterm table.
  1117. else {
  1118. tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
  1119. return 0;
  1120. }
  1121. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1122. $cvterm = $result->fetchObject();
  1123. }
  1124. // Update the cvterm.
  1125. elseif ($update) {
  1126. // First, basic update of the term.
  1127. $match = array('cvterm_id' => $cvterm->cvterm_id);
  1128. $upd_values = array(
  1129. 'name' => $name,
  1130. 'definition' => $definition,
  1131. 'is_obsolete' => $is_obsolete,
  1132. 'is_relationshiptype' => $is_relationship,
  1133. );
  1134. $success = chado_update_record('cvterm', $match, $upd_values);
  1135. if (!$success) {
  1136. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
  1137. return 0;
  1138. }
  1139. // Second, check that the dbxref has not changed and if it has then update
  1140. // it.
  1141. $checksql = "
  1142. SELECT cvterm_id
  1143. FROM {cvterm} CVT
  1144. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  1145. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  1146. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  1147. WHERE DBX.accession = :accession and DB.name = :dbname and CVT.name = :term and CV.name = :cvname
  1148. ";
  1149. $check = chado_query($checksql, array(':accession' => $accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
  1150. if (!$check) {
  1151. // Check to see if the dbxref exists if not, add it.
  1152. $dbxref = chado_insert_dbxref(array(
  1153. 'db_id' => $db->db_id,
  1154. 'accession' => $accession
  1155. ));
  1156. if (!$dbxref) {
  1157. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1158. "$name (id: $accession), for database $dbname", NULL);
  1159. return 0;
  1160. }
  1161. $match = array('cvterm_id' => $cvterm->cvterm_id);
  1162. $upd_values = array(
  1163. 'dbxref_id' => $dbxref->dbxref_id,
  1164. );
  1165. $success = chado_update_record('cvterm', $match, $upd_values);
  1166. if (!$success) {
  1167. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term $name with new accession $db:$accession", NULL);
  1168. return 0;
  1169. }
  1170. }
  1171. // Finally grab the updated details.
  1172. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1173. $cvterm = $result->fetchObject();
  1174. }
  1175. else {
  1176. // Do nothing, we have the cvterm but we don't want to update.
  1177. }
  1178. // Return the cvterm.
  1179. return $cvterm;
  1180. }
  1181. /**
  1182. * TODO: deprecate this function
  1183. *
  1184. * Avoid using this function as it will be deprecated in future releases.
  1185. *
  1186. * This function allows other modules to programatically
  1187. * submit an ontology for loading into Chado.
  1188. *
  1189. * This function will add a job to the Jobs subsystem for parsing the ontology.
  1190. * You can either pass a known OBO ID to the function or the URL
  1191. * or full path the the ontology file. If a URL or file name is
  1192. * passed then the $obo_name argument must also be provided. If
  1193. * this is the first time the ontology has been provided to Tripal
  1194. * then it will be added to the database and will be assigned a
  1195. * unique OBO ID.
  1196. *
  1197. * @param $obo_id
  1198. * If the ontology is already loaded into the Tripal tables then
  1199. * use this argument to specify the unique ID for the ontology
  1200. * that will be loaded.
  1201. * @param $obo_name
  1202. * If the OBO has not been added before then use this argument
  1203. * to specify the human readable name of the ontology.
  1204. * @param $obo_url
  1205. * If the OBO to be loaded is located on a remote server then
  1206. * use this argument to provide the URL.
  1207. * @param $obo_file
  1208. * If the OBO is housed on the local file system of the server then
  1209. * use this argument to specify the full path.
  1210. *
  1211. * @return
  1212. * returns the job_id of the submitted job or FALSE if the job was not added
  1213. *
  1214. * @ingroup tripal_chado_cv_api
  1215. */
  1216. function chado_submit_obo_job($obo) {
  1217. global $user;
  1218. // Set Defaults
  1219. $obo['obo_id'] = (isset($obo['obo_id'])) ? $obo['obo_id'] : NULL;
  1220. $obo['name'] = (isset($obo['name'])) ? $obo['name'] : NULL;
  1221. $obo['url'] = (isset($obo['url'])) ? $obo['url'] : NULL;
  1222. $obo['file'] = (isset($obo['file'])) ? $obo['file'] : NULL;
  1223. $includes = array(
  1224. drupal_get_path('module', 'tripal_chado') . '/includes/tripal_chado.cv.inc',
  1225. );
  1226. if ($obo['obo_id']) {
  1227. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  1228. $result = db_query($sql, array(':obo_id' => $obo['obo_id']))->fetchObject();
  1229. $args = array($result->obo_id);
  1230. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1231. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1232. }
  1233. else {
  1234. if ($obo['url']) {
  1235. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :url";
  1236. $result = db_query($sql, array(':url' => $obo['url']))->fetchObject();
  1237. $args = array($result->obo_id);
  1238. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1239. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1240. }
  1241. elseif ($obo['file']) {
  1242. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :file";
  1243. $result = db_query($sql, array(':url' => $obo['file']))->fetchObject();
  1244. $args = array($result->obo_id);
  1245. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1246. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1247. }
  1248. }
  1249. return FALSE;
  1250. }
  1251. /**
  1252. * Add the OBO to the tripal_cv_obo table in the Drupal database.
  1253. *
  1254. * If the OBO name already exists in the table then the path is updated.
  1255. *
  1256. * @param $name
  1257. * The human readable name of this ontology.
  1258. * @param $path
  1259. * The file path or URL of the ontology.
  1260. *
  1261. * @return
  1262. * Returns the ontology ID.
  1263. *
  1264. * @ingroup tripal_chado_cv_api
  1265. */
  1266. function chado_insert_obo($name, $path) {
  1267. // Make sure an OBO with the same name doesn't already exist.
  1268. $obo_id = db_select('tripal_cv_obo', 'tco')
  1269. ->fields('tco', array('obo_id'))
  1270. ->condition('name', $name)
  1271. ->execute()
  1272. ->fetchField();
  1273. if ($obo_id) {
  1274. db_update('tripal_cv_obo')
  1275. ->fields(array(
  1276. 'path' => $path,
  1277. ))
  1278. ->condition('name', $name)
  1279. ->execute();
  1280. return $obo_id;
  1281. }
  1282. else {
  1283. $obo_id = db_insert('tripal_cv_obo')
  1284. ->fields(array(
  1285. 'name' => $name,
  1286. 'path' => $path,
  1287. ))
  1288. ->execute();
  1289. return $obo_id;
  1290. }
  1291. }
  1292. /**
  1293. * Retrieves an OBO record.
  1294. *
  1295. * @param $values
  1296. * An associate array with the following allowed keys: obo_id, name.
  1297. *
  1298. * @return
  1299. * An instance of an OBO record object.
  1300. *
  1301. * @ingroup tripal_chado_cv_api
  1302. */
  1303. function chado_get_obo($values) {
  1304. $query = db_select('tripal_cv_obo', 'tco')
  1305. ->fields('tco');
  1306. if (array_key_exists('name', $values)) {
  1307. $query->condition('tco.name', $values['name']);
  1308. }
  1309. if (array_key_exists('obo_id', $values)) {
  1310. $query->condition('tco.obo_id', $values['obo_id']);
  1311. }
  1312. return $query->execute()->fetchObject();
  1313. }
  1314. /**
  1315. * This function is intended to be used in autocomplete forms.
  1316. *
  1317. * This function searches for a matching controlled vobulary name.
  1318. *
  1319. * @param $string
  1320. * The string to search for.
  1321. *
  1322. * @return
  1323. * A json array of terms that begin with the provided string.
  1324. *
  1325. * @ingroup tripal_chado_cv_api
  1326. */
  1327. function chado_autocomplete_cv($string = '') {
  1328. $sql = "
  1329. SELECT CV.cv_id, CV.name
  1330. FROM {cv} CV
  1331. WHERE lower(CV.name) like lower(:name)
  1332. ORDER by CV.name
  1333. LIMIT 25 OFFSET 0
  1334. ";
  1335. $results = chado_query($sql, array(':name' => $string . '%'));
  1336. $items = array();
  1337. foreach ($results as $cv) {
  1338. $items[$cv->name] = $cv->name;
  1339. }
  1340. drupal_json_output($items);
  1341. }
  1342. /**
  1343. * This function is intended to be used in autocomplete forms
  1344. * for searching for CV terms that begin with the provided string.
  1345. *
  1346. * @param $cv_id
  1347. * The CV ID in which to search for the term.
  1348. * @param $string
  1349. * The string to search for.
  1350. *
  1351. * @return
  1352. * A json array of terms that begin with the provided string.
  1353. *
  1354. * @ingroup tripal_chado_cv_api
  1355. */
  1356. function chado_autocomplete_cvterm($cv_id, $string = '') {
  1357. if ($cv_id) {
  1358. $sql = "
  1359. SELECT CVT.cvterm_id, CVT.name
  1360. FROM {cvterm} CVT
  1361. WHERE CVT.cv_id = :cv_id and lower(CVT.name) like lower(:name)
  1362. UNION
  1363. SELECT CVT2.cvterm_id, CVTS.synonym as name
  1364. FROM {cvterm} CVT2
  1365. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1366. WHERE CVT2.cv_id = :cv_id and lower(CVTS.synonym) like lower(:name)
  1367. ORDER by name
  1368. LIMIT 25 OFFSET 0
  1369. ";
  1370. $results = chado_query($sql, array(':cv_id' => $cv_id, ':name' => $string . '%'));
  1371. $items = array();
  1372. foreach ($results as $term) {
  1373. $items[$term->name] = $term->name;
  1374. }
  1375. }
  1376. // If a CV wasn't provided then search all of them, and include the cv
  1377. // in the results.
  1378. else {
  1379. $sql = "
  1380. SELECT CVT.cvterm_id, CVT.name, CV.name as cvname, CVT.cv_id
  1381. FROM {cvterm} CVT
  1382. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  1383. WHERE lower(CVT.name) like lower(:name)
  1384. UNION
  1385. SELECT CVT2.cvterm_id, CVTS.synonym as name, CV2.name as cvname, CVT2.cv_id
  1386. FROM {cvterm} CVT2
  1387. INNER JOIN {cv} CV2 on CVT2.cv_id = CV2.cv_id
  1388. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1389. WHERE lower(CVTS.synonym) like lower(:name)
  1390. ORDER by name
  1391. LIMIT 25 OFFSET 0
  1392. ";
  1393. $results = chado_query($sql, array(':name' => $string . '%'));
  1394. $items = array();
  1395. foreach ($results as $term) {
  1396. $items[$term->name] = $term->name;
  1397. }
  1398. }
  1399. drupal_json_output($items);
  1400. }
  1401. /**
  1402. * Add a record to a cvterm linking table (ie: feature_cvterm).
  1403. *
  1404. * @param $basetable
  1405. * The base table to which the cvterm should be linked/associated. Thus to
  1406. * associate a cvterm to a feature the basetable=feature and cvterm_id is
  1407. * added to the feature_cvterm table.
  1408. * @param $record_id
  1409. * The primary key of the basetable to associate the cvterm with. This should
  1410. * be in integer.
  1411. * @param $cvterm
  1412. * An associative array describing the cvterm. Valid keys include:
  1413. * - name: the name for the cvterm,
  1414. * - cv_name: the name of the cv the cvterm belongs to.
  1415. * - cv_id: the primary key of the cv the cvterm belongs to.
  1416. * @param $options
  1417. * An associative array of options. Valid keys include:
  1418. * - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is
  1419. * the default.
  1420. *
  1421. * @ingroup tripal_chado_cv_api
  1422. */
  1423. function chado_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
  1424. $linking_table = $basetable . '_cvterm';
  1425. $foreignkey_name = $basetable . '_id';
  1426. // Default Values
  1427. $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
  1428. // If the cvterm_id is not set then find the cvterm record using the name and
  1429. // cv_id.
  1430. if (!isset($cvterm['cvterm_id'])) {
  1431. $values = array(
  1432. 'name' => $cvterm['name'],
  1433. );
  1434. if (isset($cvterm['cv_id'])) {
  1435. $values['cv_id'] = $cvterm['cv_id'];
  1436. }
  1437. elseif (isset($cvterm['cv_name'])) {
  1438. $values['cv_id'] = array(
  1439. 'name' => $cvterm['cv_name']
  1440. );
  1441. }
  1442. else {
  1443. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1444. "chado_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
  1445. supplied. You were trying to associate a cvterm with the %base %record_id
  1446. and supplied the cvterm values: %cvterm.",
  1447. array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
  1448. );
  1449. return FALSE;
  1450. }
  1451. // Get the cvterm. If it doesn't exist then add it if the option
  1452. // 'insert_cvterm' is set.
  1453. $select = chado_select_record('cvterm', array('*'), $values);
  1454. if ($select) {
  1455. $cvterm['cvterm_id'] = $select[0]->cvterm_id;
  1456. }
  1457. elseif ($options['insert_cvterm']) {
  1458. // Insert the cvterm
  1459. $insert = chado_insert_cvterm($values);
  1460. if (isset($insert->cvterm_id)) {
  1461. $cvterm['cvterm_id'] = $insert->cvterm_id;
  1462. }
  1463. else {
  1464. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1465. "chado_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
  1466. array('%cvterm' => print_r($cvterm,TRUE))
  1467. );
  1468. return FALSE;
  1469. }
  1470. }
  1471. else {
  1472. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1473. "chado_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
  1474. array('%cvterm' => print_r($cvterm,TRUE))
  1475. );
  1476. return FALSE;
  1477. }
  1478. }
  1479. // Now add the link between the record & cvterm.
  1480. if ($cvterm['cvterm_id'] > 0) {
  1481. $values = array(
  1482. 'cvterm_id' => $cvterm['cvterm_id'],
  1483. $foreignkey_name => $record_id,
  1484. 'pub_id' => 1,
  1485. );
  1486. // Check if the cvterm is already associated. If so, don't re-add it.
  1487. $result = chado_select_record($linking_table, array('*'), $values);
  1488. if (!$result) {
  1489. $success = chado_insert_record($linking_table, $values);
  1490. if (!$success) {
  1491. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1492. "Failed to insert the %base record %term",
  1493. array('%base' => $linking_table, '%term' => $cvterm['name'])
  1494. );
  1495. return FALSE;
  1496. }
  1497. $result = chado_select_record($linking_table, array('*'), $values);
  1498. }
  1499. if (isset($result[0])) {
  1500. return $result[0];
  1501. }
  1502. else {
  1503. return FALSE;
  1504. }
  1505. }
  1506. return FALSE;
  1507. }