tripal_chado.cv.api.inc 55 KB

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