tripal_chado.cv.api.inc 55 KB

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