tripal_chado.cv.api.inc 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  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. *
  336. * @param unknown $cv_id
  337. */
  338. function chado_clear_cvtermpath($cv_id) {
  339. $sql = "DELETE FROM {cvtermpath} WHERE cv_id = :cv_id";
  340. chado_query($sql, [':cv_id' => $cv_id]);
  341. }
  342. function _chado_update_cvtermpath_remove_constraints() {
  343. $sql = "ALTER TABLE {cvtermpath} DROP CONSTRAINT IF EXISTS cvtermpath_c1";
  344. db_query($sql);
  345. $sql = "ALTER TABLE {cvtermpath} DROP CONSTRAINT IF EXISTS cvtermpath_cv_id_fkey";
  346. db_query($sql);
  347. $sql = "ALTER TABLE {cvtermpath} DROP CONSTRAINT IF EXISTS cvtermpath_object_id_fkey";
  348. db_query($sql);
  349. $sql = "ALTER TABLE {cvtermpath} DROP CONSTRAINT IF EXISTS cvtermpath_pkey";
  350. db_query($sql);
  351. $sql = "ALTER TABLE {cvtermpath} DROP CONSTRAINT IF EXISTS cvtermpath_subject_id_fkey";
  352. db_query($sql);
  353. $sql = "ALTER TABLE {cvtermpath} DROP CONSTRAINT IF EXISTS cvtermpath_type_id_fkey";
  354. db_query($sql);
  355. }
  356. function _chado_update_cvtermpath_add_constraints() {
  357. $sql = "ALTER TABLE {cvtermpath} ADD CONSTRAINT cvtermpath_c1 " .
  358. "UNIQUE (subject_id, object_id, type_id, pathdistance)";
  359. db_query($sql);
  360. $sql = "ALTER TABLE {cvtermpath} ADD CONSTRAINT cvtermpath_cv_id_fkey " .
  361. "FOREIGN KEY (cv_id) REFERENCES cv(cv_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED";
  362. db_query($sql);
  363. $sql = "ALTER TABLE {cvtermpath} ADD CONSTRAINT cvtermpath_object_id_fkey " .
  364. "FOREIGN KEY (object_id) REFERENCES cvterm(cvterm_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED";
  365. db_query($sql);
  366. $sql = "ALTER TABLE {cvtermpath} ADD CONSTRAINT cvtermpath_pkey " .
  367. "PRIMARY KEY (cvtermpath_id)";
  368. db_query($sql);
  369. $sql = "ALTER TABLE {cvtermpath} ADD CONSTRAINT cvtermpath_subject_id_fkey " .
  370. "FOREIGN KEY (subject_id) REFERENCES cvterm(cvterm_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED";
  371. db_query($sql);
  372. $sql = "ALTER TABLE {cvtermpath} ADD CONSTRAINT cvtermpath_type_id_fkey " .
  373. "FOREIGN KEY (type_id) REFERENCES cvterm(cvterm_id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED";
  374. db_query($sql);
  375. }
  376. /**
  377. * Replacement for the fill_cvtermpath() stored procedure in Chado.
  378. *
  379. * Fills the cvtermpath table of Chado with relationships between every
  380. * node in the ontology graph and all of it's descendents. This was
  381. * previously performed using the fill_cvtermpath() stored procedure of Chado
  382. * but that function cannot handle loops in the ontology graphs and results
  383. * in stack depth errors in PostgreSQL.
  384. *
  385. * @param $cv_id
  386. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  387. * @param $job
  388. * An instance of a TripalJob.
  389. *
  390. * @ingroup tripal_chado_cv_api
  391. */
  392. function chado_update_cvtermpath($cv_id, $clear = FALSE, $job = NULL) {
  393. $cv = new ChadoRecord('cv', $cv_id);
  394. print "Building cvterm paths for vocabulary: " . $cv->getValue('name') ."\n";
  395. if ($clear) {
  396. print "Clearing the cvtermpath table for this vocabulary...\n";
  397. chado_clear_cvtermpath($cv_id);
  398. print "Clearing completed.\n";
  399. }
  400. // The cache is used to limit repetitive queries by storing known data.
  401. $cache = [
  402. 'rels' => [],
  403. 'processed' => [],
  404. 'is_a' => NULL,
  405. ];
  406. // TODO: there's a function to determine the current Chado instance.
  407. // we should use that.
  408. $prev_db = chado_set_active('chado');
  409. $transaction = db_transaction();
  410. try {
  411. // Remove constraints for faster loading.
  412. _chado_update_cvtermpath_remove_constraints();
  413. // Get the is_a term. The OBO importer adds this for evey vocabulary.
  414. $sql = "SELECT * FROM cvterm WHERE name = :is_a and cv_id = :cv_id";
  415. $args = [':is_a' => 'is_a', ':cv_id' => $cv_id];
  416. $cache['$is_a'] = chado_query($sql, $args)->fetchObject();
  417. // First cache all the relationships for this vocaublary so that we
  418. // don't have to do repetitive queries to Chado.
  419. print "Retrieving relationships...\n";
  420. $sql = "
  421. SELECT CVTR.subject_id, CVTR.type_id, CVTR.object_id, CVTS.name
  422. FROM {cvterm_relationship} CVTR
  423. INNER JOIN {cvterm} CVTO on CVTO.cvterm_id = CVTR.object_id
  424. INNER JOIN {cvterm} CVTS on CVTS.cvterm_id = CVTR.subject_id
  425. WHERE CVTO.cv_id = :cv_id
  426. ";
  427. $rels = chado_query($sql, [':cv_id' => $cv_id]);
  428. $total_items;
  429. while ($rel = $rels->fetchObject()) {
  430. $cache['rels'][$rel->object_id][] = [$rel->subject_id, $rel->type_id, $rel->name];
  431. }
  432. $total_items = count(array_keys($cache['rels']));
  433. if ($job) {
  434. $job->setTotalItems($total_items);
  435. $job->logMessage('Note: Progress updates occur as each term is processed and ' .
  436. 'some terms take longer than others.');
  437. $job->setProgress(0);
  438. }
  439. // Next get the tree roots. These are terms that are in relationships as
  440. // an object but never as a subject.
  441. $sql = "
  442. SELECT DISTINCT CVT.cvterm_id, CVT.name
  443. FROM {cvterm} CVT
  444. LEFT JOIN {cvterm_relationship} CVTR ON CVT.cvterm_id = CVTR.subject_id
  445. INNER JOIN {cvterm_relationship} CVTR2 ON CVT.cvterm_id = CVTR2.object_id
  446. WHERE CVT.cv_id = :cvid AND CVTR.subject_id is NULL and
  447. CVT.is_relationshiptype = 0 and CVT.is_obsolete = 0
  448. ";
  449. $roots = chado_query($sql, [':cvid' => $cv_id]);
  450. // Iterate through the tree roots.
  451. print "Processing terms...\n";
  452. while ($root = $roots->fetchObject()) {
  453. $root_id = $root->cvterm_id;
  454. $root_name = $root->name;
  455. if ($job) {
  456. $job->logMessage('Processing tree root: ' . $root_name . '...');
  457. }
  458. // _chado_update_cvtermpath_traverse_tree($root_id, $cache, 0);
  459. // return;
  460. // Now start descending through the tree and add the relationships
  461. // to the cvtermpath table.
  462. $num_handled = 0;
  463. $depth = 0;
  464. _chado_update_cvtermpath_root($cv_id, $root_id, $root_name, $cache, $job,
  465. $num_handled, $clear, $depth);
  466. }
  467. // Restore the table constraints and indexes.
  468. _chado_update_cvtermpath_add_constraints();
  469. }
  470. catch (Exception $e) {
  471. $transaction->rollback();
  472. chado_set_active($prev_db);
  473. throw $e;
  474. }
  475. }
  476. /**
  477. *
  478. */
  479. function _chado_update_cvtermpath_traverse_tree($root_id, &$cache, $depth) {
  480. $mem = memory_get_usage();
  481. $memory = number_format($mem);
  482. print $memory . " $depth\n";
  483. // Mark this node as having been processed as a root node.
  484. $cache['processed'][$root_id] = TRUE;
  485. // Get this term's children and recurse.
  486. $children = $cache['rels'][$root_id];
  487. // If there are no children do nothing.
  488. if (!$children) {
  489. return;
  490. }
  491. $next_depth = $depth +1;
  492. foreach ($children as $child) {
  493. $child_id = $child[0];
  494. $type_id = $child[1];
  495. $name = $child[2];
  496. // Don't use a node as a root if we've already used it once before.
  497. if (array_key_exists($child_id, $cache['processed'])) {
  498. continue;
  499. }
  500. // recurse.
  501. _chado_update_cvtermpath_traverse_tree($child_id, $cache, $next_depth);
  502. }
  503. }
  504. /**
  505. * Treats a term within the ontology as a root.
  506. *
  507. * In order to add all relationships between a term and it's descendents each
  508. * term gets it's turn as a "root". The first time this function is called
  509. * it should be called with the actual root's of the ontology. This function
  510. * will then recursively treat each child term within the tree as a root in
  511. * order to find all relationships.
  512. *
  513. * @param $cv_id
  514. * The vocaulary Id
  515. * @param $root_id
  516. * This root term's cvterm Id.
  517. * @param $root_name
  518. * The name of this root term.
  519. * @param $cache
  520. * The cache used for lookups.
  521. * @param $job
  522. * The TripalJob instance.
  523. * @param $num_handled
  524. * Used to keep track of the number of nodes that have been handled for
  525. * progress reporting.
  526. * @param $clear
  527. * A flag indicating if the cvtermpath was cleared for this vocabulary
  528. * prior to processing the tree.
  529. * @param $root_depth
  530. * The current depth in the tree of this term.
  531. */
  532. function _chado_update_cvtermpath_root($cv_id, $root_id, $root_name, &$cache,
  533. $job, &$num_handled, $clear, $root_depth = 0) {
  534. $mem = memory_get_usage();
  535. $memory = number_format($mem);
  536. print $memory . " $root_depth\n";
  537. // Mark this node as having been processed as a root node.
  538. $cache['processed'][$root_id] = TRUE;
  539. // For the actual tree roots we need to add a relatioship to themselves.
  540. if ($root_depth == 0) {
  541. $is_a = $cache['$is_a'];
  542. $type_id = $is_a->cvterm_id;
  543. $depth = 1;
  544. _chado_update_cvtermpath_add_relationship($type_id, $root_id, $root_id, $cv_id, $depth, $clear);
  545. }
  546. // The $path variable contains only the current path on the descent. This
  547. // is used for detecting loops in the graph. If we encounter a node a
  548. // second time while traversing a single path of the tree then we've hit
  549. // a loop.
  550. $path = [];
  551. $path[] = $root_id;
  552. // Get this term's children and recurse.
  553. $children = $cache['rels'][$root_id];
  554. // If there are no children do nothing.
  555. if (!$children) {
  556. return;
  557. }
  558. // Set the job progress.
  559. $num_handled++;
  560. if ($job) {
  561. //print "$root_name\n";
  562. //$job->setItemsHandled($num_handled);
  563. }
  564. // Iterate through the children and descend the tree.
  565. foreach ($children as $child) {
  566. $child_id = $child[0];
  567. $type_id = $child[1];
  568. $name = $child[2];
  569. $path[$child_id];
  570. $next_depth = 1;
  571. _chado_update_cvtermpath_item($cv_id, $root_id, $child_id, $type_id,
  572. $path, $cache, $clear, $next_depth);
  573. }
  574. // Next make each child of this node a root and recurse again.
  575. foreach ($children as $child) {
  576. $child_id = $child[0];
  577. $type_id = $child[1];
  578. $name = $child[2];
  579. // Don't use a node as a root if we've already used it once before.
  580. if (array_key_exists($child_id, $cache['processed'])) {
  581. continue;
  582. }
  583. // Process this child as a root. The path is used to catch for loops
  584. // in the tree. If we encounter a node on the same path then we've
  585. // found a loop and we should stop.
  586. $path[] = $name;
  587. $next_depth = $root_depth + 1;
  588. _chado_update_cvtermpath_root($cv_id, $child_id, $name, $cache,
  589. $job, $num_handled, $clear, $next_depth);
  590. }
  591. }
  592. /**
  593. * Handles a single node in the tree.
  594. *
  595. * This is a recursive function which calls itself as the tree is descended. It
  596. * performs a depth-first search of the tree.
  597. *
  598. * @param $cv_id
  599. * The vocaulary Id
  600. * @param $root_id
  601. * This root term's cvterm Id.
  602. * @param $cvterm_id
  603. * This term's cvterm Id.
  604. * @param $type_id
  605. * The type relationship cvterm Id.
  606. * @param $path
  607. * An array used for storing the current path down the tree. This is the
  608. * sequence of nodes visited to this point down a single branch.
  609. * @param $cache
  610. * The cache used for lookups.
  611. * @param $depth
  612. * The current depth in the tree.
  613. */
  614. function _chado_update_cvtermpath_item($cv_id, $root_id, $cvterm_id, $type_id,
  615. $path, &$cache, $clear, $depth = 1) {
  616. //print implode('-', $path) . "\n";
  617. // Have we visited this node before while on this path then we won't
  618. // descend further as this means we've hit a loop.
  619. if (in_array($cvterm_id, $path)) {
  620. foreach ($path as $id) {
  621. $t = new ChadoRecord('cvterm', $id);
  622. print $t->getValue('name') . '-';
  623. }
  624. $t = new ChadoRecord('cvterm', $cvterm_id);
  625. print $t->getValue('name') . "\n";
  626. print "LOOP!!!!!!!!!!!!!!!!!!!!!!\n";
  627. return;
  628. }
  629. // Add this term to the path.
  630. $path[] = $cvterm_id;
  631. // Indicate we have visited this node in the tree and store the cvterm
  632. // path details that we need for inserting into the cvtermpath table.
  633. $next_depth = $depth + 1;
  634. // _chado_update_cvtermpath_add_relationship($type_id, $cvterm_id, $root_id,
  635. // $cv_id, $next_depth, $clear);
  636. // Get this term's children and recurse.
  637. $children = $cache['rels'][$cvterm_id];
  638. // If this term does not have children then return.
  639. if (!$children) {
  640. return;
  641. }
  642. // If the term has children then recurse on those.
  643. foreach ($children as $child) {
  644. $child_id = $child[0];
  645. $type_id = $child[1];
  646. _chado_update_cvtermpath_item($cv_id, $root_id, $child_id, $type_id,
  647. $path, $cache, $clear, $next_depth);
  648. }
  649. }
  650. /**
  651. * Inserts values into the cvtermpath table.
  652. *
  653. * After the entire tree below the current root term is traversed, this
  654. * function is called and inserts all of the relationships that were found
  655. * into the cvtermpath table.
  656. *
  657. * @param $visited
  658. * The array contaiing relationships for all visited nodes in the tree. These
  659. * elements will become the entries in the cvtermpath table.
  660. * @param $job
  661. * The TripalJob instance.
  662. * @param $clear
  663. * A flag indicating if the cvtermpath was cleared for this vocabulary
  664. * prior to processing the tree.
  665. */
  666. function _chado_update_cvtermpath_add_relationship($type_id, $cvterm_id,
  667. $root_id, $cv_id, $depth, $clear) {
  668. $cvtermpath = new ChadoRecord('cvtermpath');
  669. $cvtermpath->setValues([
  670. 'type_id' => $type_id,
  671. 'subject_id' => $cvterm_id,
  672. 'object_id' => $root_id,
  673. 'cv_id' => $cv_id,
  674. 'pathdistance' => $depth,
  675. ]);
  676. // if ($clear) {
  677. // $cvtermpath->insert();
  678. // }
  679. // else
  680. // if (!$cvtermpath->find()) {
  681. //$cvtermpath->insert();
  682. // }
  683. }
  684. /**
  685. * Duplicate of fill_cvtermpath() stored procedure in Chado.
  686. *
  687. * Identifies all of the root terms of the controlled vocabulary. These
  688. * root terms are then processed by calling the
  689. * _chado_update_cvtermpath_root_loop() function on each one.
  690. *
  691. * @param $cvid
  692. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  693. * @param $job_id
  694. *
  695. * @ingroup tripal_chado_cv_api
  696. */
  697. function chado_update_cvtermpath_old($cv_id, $job_id = NULL){
  698. // TODO: there's a function to determine the current Chado instance.
  699. // we should use that.
  700. $prev_db = chado_set_active('chado');
  701. print "\nNOTE: Updating CV Term Path is performed using a database transaction. \n" .
  702. "If the update fails or is terminated prematurely then any new changes \n" .
  703. "made will be rolled back.\n\n";
  704. $transaction = db_transaction();
  705. try {
  706. $result = db_query('
  707. SELECT DISTINCT t.*
  708. FROM cvterm t
  709. LEFT JOIN cvterm_relationship r ON (t.cvterm_id = r.subject_id)
  710. INNER JOIN cvterm_relationship r2 ON (t.cvterm_id = r2.object_id)
  711. WHERE t.cv_id = :cvid AND r.subject_id is null',
  712. array(':cvid' => $cv_id)
  713. );
  714. // Iterate through each root level term.
  715. $record = $result->fetchAll();
  716. $roots = [];
  717. foreach ($record as $item){
  718. _chado_update_cvtermpath_root_loop($item->cvterm_id, $item->cv_id, $roots);
  719. }
  720. }
  721. catch (Exception $e) {
  722. // Rollback any database changes
  723. $transaction->rollback();
  724. throw $e;
  725. }
  726. finally {
  727. // Set the database back
  728. chado_set_active($prev_db);
  729. }
  730. }
  731. /**
  732. * Duplicate of _fill_cvtermpath4root() stored procedure in Chado.
  733. *
  734. * This function process a "branch" of the ontology. Initially, the
  735. * "root" starts at the top of the tree. But, as the cvtermpath is populated
  736. * the "root" becomes terms deeper in the tree.
  737. *
  738. * @param $rootid
  739. * The term ID from the cvterm table of Chado (i.e. cvterm.cvterm_id).
  740. * @param $cvid
  741. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  742. *
  743. * @ingroup tripal_chado_cv_api
  744. */
  745. function _chado_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
  746. $ttype = db_query('
  747. SELECT cv.cvterm_id
  748. FROM cvterm cv
  749. WHERE cv.name = :isa
  750. OR cv.name = :is_a
  751. '
  752. ,
  753. array(':isa' => "isa", ':is_a' => "is_a")
  754. );
  755. $result = $ttype->fetchObject();
  756. $term_id = $rootid . '|' . $rootid . '|' . $cvid . '|' . $result->cvterm_id;
  757. // If the child_id matches any other id in the array then we've hit a loop.
  758. foreach ($roots as $element_id) {
  759. if ($element_id == $term_id) {
  760. return;
  761. }
  762. }
  763. // Then add that new entry to the $tree_path.
  764. $roots[] = $term_id;
  765. // Descends through the branch starting at this "root" term.
  766. $tree_path = [];
  767. $matched_rows = [];
  768. $possible_start_of_loop = [];
  769. $depth = 0;
  770. _chado_update_cvtermpath_loop($rootid, $rootid, $cvid, $result->cvterm_id, $depth,
  771. 0, $tree_path, FALSE, $matched_rows, $possible_start_of_loop, FALSE);
  772. // Get's the children terms of this "root" term and then recursively calls
  773. // this function making each child root.
  774. $cterm = db_query(
  775. 'SELECT *
  776. FROM cvterm_relationship
  777. WHERE object_id = :rootid
  778. ',
  779. [':rootid' => $rootid]
  780. );
  781. while ($cterm_result = $cterm->fetchAssoc()) {
  782. _chado_update_cvtermpath_root_loop($cterm_result['subject_id'], $cvid, $roots);
  783. }
  784. }
  785. /**
  786. *
  787. * @param $origin
  788. * The root terms cvterm_id.
  789. * @param $child_id
  790. * The cvterm_id of the current child term. The child term is a descendent
  791. * of the origin.
  792. * @param $cv_id
  793. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  794. * @param $type_id
  795. * The relationship type between the origin term and the child.
  796. * @param $depth
  797. * The depth of the recursion.
  798. * @param $increment_of_depth.
  799. * An integer tailing the number of children that have been walked down.
  800. * @param $tree_path.
  801. * The array of every term between the current child and the origin. Each
  802. * element in the array is an associative array with the keys:
  803. * -build_id: an string identifier for the child that combines the origin,
  804. * child cvterm_id,cv_id, and the type_id.
  805. * -depth: the depth that a child was inserted into the cvtermpath table.
  806. * @param $possible_loop
  807. * A boolean flag.
  808. * @param $matched_row
  809. * An array of rows that are currently in the cvtermpath table that match the
  810. * build_id of the current term trying to be written to the table
  811. * @param $possible_start_of_ loop
  812. * The array of the possible loop item between the current child and the
  813. * origin. Each element in the array is an associative array with the keys:
  814. * - cvid : $cv_id
  815. * - subject_id:
  816. * - child_id : $child_id,
  817. * - type_id : $type_id,
  818. * - depth : $depth,
  819. * @param $no_loop_skip_test
  820. * A boolean used when the possible loop has been ruled out as a loop.
  821. *
  822. *
  823. * @ingroup tripal_chado_cv_api
  824. */
  825. function _chado_update_cvtermpath_loop(
  826. $origin,
  827. $child_id,
  828. $cv_id,
  829. $type_id,
  830. $depth,
  831. $increment_of_depth,
  832. $tree_path,
  833. $possible_loop,
  834. $matched_rows,
  835. $possible_start_of_loop,
  836. $no_loop_skip_test) {
  837. // We have not detected a loop, so it's safe to insert the term.
  838. $new_match_rows = [];
  839. if (!empty($possible_start_of_loop)) {
  840. // Go through each matched_row.
  841. if (count($matched_rows) === 1) {
  842. // Get the cvtermpath_id and then increment down one row.
  843. $cvtermpath_id = (int) $matched_rows[0]->cvtermpath_id;
  844. $cvtermpath_id = $cvtermpath_id + 1;
  845. chado_set_active('chado');
  846. $next_row = db_query(
  847. 'SELECT *
  848. FROM cvtermpath
  849. WHERE cvtermpath_id = :cvtermpath_id
  850. ',
  851. [':cvtermpath_id' => $cvtermpath_id]
  852. );
  853. $next_row = $next_row->fetchObject();
  854. // If the next row matches the values passed we can't rule out a loop.
  855. if (($next_row->type_id === $type_id) &&
  856. ($next_row->subject_id === $child_id) &&
  857. ($next_row->object_id === $origin) &&
  858. ($next_row->cv_id === $cv_id)) {
  859. $new_match_rows[] = $next_row;
  860. }
  861. elseif (($next_row->type_id === $possible_start_of_loop['type_id']) &&
  862. ($next_row->subject_id === $possible_start_of_loop['subject_id']) &&
  863. ($next_row->object_id === $possible_start_of_loop['object_id']) &&
  864. ($next_row->cv_id === $possible_start_of_loop['cv_id'])) {
  865. // The next_row is equal to start of loop, so we've reached the end
  866. // and confirmed that this is a loop.
  867. $possible_loop == FALSE;
  868. $matched_rows = [];
  869. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  870. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  871. $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
  872. }
  873. }
  874. else {
  875. foreach ($matched_rows as $matched_row) {
  876. // Get the cvtermpath_id and then increment down one row.
  877. $cvtermpath_id = (int) $match_row->cvtermpath_id;
  878. // Get the cvtermpath_id and then increment down one row.
  879. $cvtermpath_id = $cvtermpath_id + 1;
  880. chado_set_active('chado');
  881. $next_row = db_query(
  882. 'SELECT *
  883. FROM cvtermpath
  884. WHERE cvtermpath_id = :cvtermpath_id
  885. ',
  886. [':cvtermpath_id' => $cvtermpath_id]
  887. );
  888. $next_row = $next_row->fetchObject();
  889. // If the next row matches the values passed we can't rule out a loop.
  890. if (($next_row->type_id === $type_id) &&
  891. ($next_row->subject_id === $child_id) &&
  892. ($next_row->object_id === $origin) &&
  893. ($next_row->cv_id === $cv_id)) {
  894. $new_match_rows[] = $next_row;
  895. }
  896. elseif (($next_row->type_id === $possible_start_of_loop['type_id']) &&
  897. ($next_row->subject_id === $possible_start_of_loop['subject_id']) &&
  898. ($next_row->object_id === $possible_start_of_loop['object_id']) &&
  899. ($next_row->cv_id === $possible_start_of_loop['cv_id'])) {
  900. // The next_row is equal to start of loop, so we've reached the end
  901. // and confirmed that this is a loop.
  902. $possible_loop == FALSE;
  903. $matched_rows = [];
  904. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  905. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  906. $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
  907. }
  908. }
  909. }
  910. // If $match_rows is empty there is no loop.
  911. if (empty($new_match_rows)) {
  912. $possible_loop == FALSE;
  913. $matched_rows = [];
  914. unset($new_match_rows);
  915. $no_loop_skip_test = TRUE;
  916. // There is not loop so pass it back the possible_start_of_loop info
  917. // and a flag telling it to skip the loop check.
  918. _chado_update_cvtermpath_loop_increment($possible_start_of_loop->subject_id,
  919. $possible_start_of_loop->child_id, $possible_start_of_loop->cvid,
  920. $possible_start_of_loop->type_id, $possible_start_of_loop->depth,
  921. $increment_of_depth, $tree_path, $possible_loop, $matched_rows,
  922. $possible_start_of_loop, $no_loop_skip_test);
  923. }
  924. // If $match_rows is not empty we need to keep trying rows.
  925. else {
  926. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  927. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  928. $match_rows, $possible_start_of_loop, $no_loop_skip_test);
  929. }
  930. }
  931. elseif ($possible_loop === FALSE) {
  932. _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  933. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  934. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  935. }
  936. }
  937. /**
  938. *
  939. * @param $origin
  940. * The root terms cvterm_id.
  941. * @param $child_id
  942. * The cvterm_id of the current child term. The child term is a descendent
  943. * of the origin.
  944. * @param $cv_id
  945. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  946. * @param $type_id
  947. * The relationship type between the origin term and the child.
  948. * @param $depth
  949. * The depth of the recursion.
  950. * @param $increment_of_depth.
  951. * An integer.
  952. * @param $tree_path.
  953. * The array of every term between the current child and the origin. Each
  954. * element in the array is an associative array with the keys:
  955. * -build_id: an string identifier for the child that combines the origin,
  956. * child cvterm_id,cv_id, and the type_id.
  957. * -depth: the depth that a child was inserted into the cvtermpath table.
  958. * @param $possible_loop
  959. * A boolean flag.
  960. * @param $matched_row
  961. * An array of rows that are currently in the cvtermpath table that match the
  962. * build_id of the current term trying to be written to the table
  963. * @param $possible_start_of_ loop
  964. * The array of the possible loop item between the current child and the origin.
  965. * Each element in the array is an associative array with the keys:
  966. * - cvid : $cv_id
  967. * - subject_id:
  968. * - child_id : $child_id,
  969. * - type_id : $type_id,
  970. * - depth : $depth,
  971. * @param $no_loop_skip_test
  972. * A boolean used when the possible loop has been ruled out as a loop.
  973. * @return multitype: Either a number that represents the row count of existing
  974. * rows that already match these specification or a Boolean false.
  975. *
  976. * @ingroup tripal_chado_cv_api
  977. */
  978. function _chado_update_cvtermpath_loop_increment(
  979. $origin,
  980. $child_id,
  981. $cv_id,
  982. $type_id,
  983. $depth,
  984. $increment_of_depth,
  985. $tree_path,
  986. $possible_loop,
  987. $matched_rows,
  988. &$possible_start_of_loop,
  989. $no_loop_skip_test) {
  990. // Check to see if a row with these values already exists.
  991. if ($possible_loop === FALSE && empty($possible_start_of_loop)) {
  992. chado_set_active('chado');
  993. $count = db_query(
  994. ' SELECT *
  995. FROM cvtermpath
  996. WHERE object_id = :origin
  997. AND subject_id = :child_id
  998. AND pathdistance = :depth
  999. AND type_id = :type_id
  1000. ',
  1001. [
  1002. ':origin' => $origin,
  1003. ':child_id' => $child_id,
  1004. ':depth' => $depth,
  1005. ':type_id' => $type_id
  1006. ]
  1007. );
  1008. $count->fetchAll();
  1009. $count_total = $count->rowCount();
  1010. if ($count_total > 0) {
  1011. return $count;
  1012. }
  1013. // Build the ID.
  1014. $term_id = $origin . '|' . $child_id . '|' . $cv_id . '|' . $type_id;
  1015. if ($no_loop_skip_test === FALSE) {
  1016. // If the increment of depth is 0 then it's the first time and we need to
  1017. // skip the test so we can build the tree_path which will be tested against.
  1018. if ($increment_of_depth != 0) {
  1019. // Search the $tree_path for the new $child_id in the build_id column.
  1020. foreach ($tree_path as $parent) {
  1021. // If this child is the same as a parent term that has already been
  1022. // processed then we have a potential loop.
  1023. if ($parent['build_id'] == $term_id) {
  1024. // Tell the function this is a possible loop and to stop writing to
  1025. // the table.
  1026. $possible_loop = TRUE;
  1027. // Find all the results in the table that might be the start of the
  1028. // loop.
  1029. $matching_rows = db_query(
  1030. ' SELECT *
  1031. FROM cvtermpath
  1032. WHERE cv_id = :cvid
  1033. AND object_id = :origin
  1034. AND subject_id = :child_id
  1035. AND type_id = :type_id
  1036. ',
  1037. [
  1038. ':cvid' => $cv_id,
  1039. ':origin' => $origin,
  1040. ':child_id' => $child_id,
  1041. ':type_id' => $type_id
  1042. ]
  1043. );
  1044. $matched_rows = $matching_rows->fetchAll();
  1045. $possible_start_of_loop = array(
  1046. 'cvid' => $cv_id,
  1047. 'subject_id' => $origin,
  1048. 'child_id' => $child_id,
  1049. 'type_id' => $type_id,
  1050. 'depth' => $depth,
  1051. );
  1052. }
  1053. }
  1054. }
  1055. $find_query = db_select('chado.cvtermpath', 'CVTP');
  1056. $find_query->fields('CVTP', ['subject_id']);
  1057. $find_query->condition('object_id', $origin);
  1058. $find_query->condition('subject_id', $child_id);
  1059. $find_query->condition('type_id', $type_id);
  1060. $find_query->condition('pathdistance', $depth);
  1061. $exists = $find_query->execute()->fetchObject();
  1062. if(!$exists){
  1063. $query = db_insert('cvtermpath')
  1064. ->fields([
  1065. 'object_id' => $origin,
  1066. 'subject_id' => $child_id,
  1067. 'cv_id' => $cv_id,
  1068. 'type_id' => $type_id,
  1069. 'pathdistance' => $depth,
  1070. ]);
  1071. try {
  1072. $rows = $query->execute();
  1073. } catch (Exception $e) {
  1074. $error = $e->getMessage();
  1075. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath term: @error", array('@error' => $error));
  1076. return false;
  1077. }
  1078. }
  1079. // Then add that new entry to the $tree_path.
  1080. $tree_path[$increment_of_depth] = [
  1081. 'build_id' => $term_id,
  1082. 'depth' => $depth
  1083. ];
  1084. }
  1085. // Reset to FALSE and empty variable if passed in as TRUE.
  1086. $no_loop_skip_test == FALSE;
  1087. $possible_start_of_loop = [];
  1088. // Get all of the relationships of this child term, and recursively
  1089. // call the _chado_update_cvtermpath_loop_increment() function to continue
  1090. // descending down the tree.
  1091. $query = db_select('cvterm_relationship', 'cvtr')
  1092. ->fields('cvtr')
  1093. ->condition('cvtr.object_id', $child_id, '=')
  1094. ->execute();
  1095. $cterm_relationships = $query->fetchAll();
  1096. foreach ($cterm_relationships as $item) {
  1097. $increment_of_depth++;
  1098. _chado_update_cvtermpath_loop_increment($origin, $item->subject_id, $cv_id,
  1099. $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  1100. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  1101. }
  1102. }
  1103. elseif ($possible_loop === FALSE && !empty($possible_start_of_loop)) {
  1104. // This means a loop has been identified and the recursive call can move
  1105. // on to the next item and skip the rest of this run.
  1106. return $possible_start_of_loop;
  1107. }
  1108. elseif ($possible_loop === TRUE) {
  1109. // Get all of the relationships of this child term, and recursively
  1110. // call the _chado_update_cvtermpath_loop() function to continue
  1111. // descending down the tree.
  1112. $query = db_select('cvterm_relationship', 'cvtr')
  1113. ->fields('cvtr')
  1114. ->condition('cvtr.object_id', $child_id, '=')
  1115. ->execute();
  1116. $cterm_relationships = $query->fetchAll();
  1117. foreach ($cterm_relationships as $item) {
  1118. $increment_of_depth++;
  1119. _chado_update_cvtermpath_loop($origin, $item->subject_id, $cv_id,
  1120. $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  1121. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  1122. }
  1123. }
  1124. }
  1125. /**
  1126. * Adds a controlled vocabulary to the CV table of Chado.
  1127. *
  1128. * @param $name
  1129. * The name of the controlled vocabulary. These are typically all lower case
  1130. * with no special characters other than an undrescore (for spaces).
  1131. * @param $comment
  1132. * A description or definition of the vocabulary.
  1133. *
  1134. * @return
  1135. * An object populated with fields from the newly added database.
  1136. *
  1137. * @ingroup tripal_chado_cv_api
  1138. */
  1139. function chado_insert_cv($name, $definition) {
  1140. // Insert/update values.
  1141. $ins_values = array(
  1142. 'name' => $name,
  1143. 'definition' => $definition
  1144. );
  1145. // See if the CV default exists already in the database.
  1146. $sel_values = array('name' => $name);
  1147. $results = chado_select_record('cv', array('*'), $sel_values);
  1148. // If it does not exists then add it.
  1149. if (count($results) == 0) {
  1150. $success = chado_insert_record('cv', $ins_values);
  1151. if (!$success) {
  1152. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to create the CV record", NULL);
  1153. return FALSE;
  1154. }
  1155. $results = chado_select_record('cv', array('*'), $sel_values);
  1156. }
  1157. // If it already exists then do an update.
  1158. else {
  1159. $success = chado_update_record('cv', $sel_values, $ins_values);
  1160. if (!$success) {
  1161. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the CV record", NULL);
  1162. return FALSE;
  1163. }
  1164. $results = chado_select_record('cv', array('*'), $sel_values);
  1165. }
  1166. // Return the cv object.
  1167. return $results[0];
  1168. }
  1169. /**
  1170. * Add's a controlled vocabulary term to Chado.
  1171. *
  1172. * This function will add a cvterm record (and a dbxref record if appropriate
  1173. * values are provided). If the parent vocabulary does not exist then
  1174. * that also is added to the cv table. If the cvterm is a relationship term
  1175. * then the 'is_relationship' value should be set. All
  1176. * terms must also have a corresponding database. This is specified in the
  1177. * term's ID just before the colon (e.g. GO:003824). If the database does not
  1178. * exist in the DB table then it will be added automatically. The accession
  1179. * (the value just after the colon in the term's ID) will be added to the
  1180. * dbxref table. If the CVterm already exists and $update is set (default)
  1181. * then the cvterm is updated. If the CVTerm already exists and $update is
  1182. * not set, then no changes are made and the CVTerm object is returned.
  1183. *
  1184. * @param $term
  1185. * An associative array with the following keys:
  1186. * - id: the term accession. must be of the form <DB>:<ACCESSION>, where
  1187. * <DB> is the name of the database to which the cvterm belongs and the
  1188. * <ACCESSION> is the term's accession number in the database.
  1189. * - name: the name of the term. usually meant to be human-readable.
  1190. * - is_obsolete: is present and set to 1 if the term is defunct.
  1191. * - definition: the definition of the term.
  1192. * - cv_name: The CV name to which the term belongs. If this arugment is
  1193. * null or not provided then the function tries to find a record in the
  1194. * CV table with the same name provided in the $term[namespace]. If
  1195. * this field is provided then it overrides what the value in
  1196. * $term[namespace].
  1197. * - is_relationship: If this term is a relationship term then this value
  1198. * should be 1.
  1199. * - db_name: In some cases the database name will not be part of the
  1200. * $term['id'] and it needs to be explicitly set. Use this argument
  1201. * only if the database name cannot be specififed in the term ID
  1202. * (e.g. <DB>:<ACCESSION>).
  1203. * @param $options
  1204. * An associative array with the following keys:
  1205. * - update_existing: By default this is TRUE. If the term exists it is
  1206. * automatically updated.
  1207. *
  1208. * @return
  1209. * A cvterm object
  1210. *
  1211. * @ingroup tripal_chado_cv_api
  1212. */
  1213. function chado_insert_cvterm($term, $options = array()) {
  1214. // Get the term properties.
  1215. $id = (isset($term['id'])) ? $term['id'] : '';
  1216. $name = '';
  1217. $cvname = '';
  1218. $definition = '';
  1219. $is_obsolete = 0;
  1220. $accession = '';
  1221. // Set Defaults.
  1222. if (isset($term['cv_name'])) {
  1223. $cvname = $term['cv_name'];
  1224. }
  1225. else {
  1226. $cvname = 'local';
  1227. }
  1228. // Namespace is deprecated but must be supported for backwards
  1229. // compatability.
  1230. if (array_key_exists('namespace', $term)) {
  1231. $cvname = $term['namespace'];
  1232. }
  1233. if (isset($term['is_relationship'])) {
  1234. $is_relationship = $term['is_relationship'];
  1235. }
  1236. else {
  1237. $is_relationship = 0;
  1238. }
  1239. if (isset($term['db_name'])) {
  1240. $dbname = $term['db_name'];
  1241. }
  1242. else {
  1243. $dbname = 'internal';
  1244. }
  1245. if (isset($options['update_existing'])) {
  1246. $update = $options['update_existing'];
  1247. }
  1248. else {
  1249. $update = 1;
  1250. }
  1251. if (array_key_exists('name', $term)) {
  1252. $name = $term['name'];
  1253. }
  1254. else {
  1255. $name = $id;
  1256. }
  1257. if (array_key_exists('definition', $term)) {
  1258. $definition = preg_replace('/^\"(.*)\"/', '\1', $term['definition']);
  1259. }
  1260. else {
  1261. $definition = '';
  1262. }
  1263. if (array_key_exists('is_obsolete', $term)) {
  1264. $is_obsolete = $term['is_obsolete'];
  1265. if (strcmp($is_obsolete, 'true') == 0) {
  1266. $is_obsolete = 1;
  1267. }
  1268. }
  1269. if (!$name and !$id) {
  1270. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
  1271. return 0;
  1272. }
  1273. if (!$id) {
  1274. $id = $name;
  1275. }
  1276. // Get the accession and the database from the cvterm id.
  1277. if ($dbname) {
  1278. $accession = $id;
  1279. }
  1280. if (preg_match('/^.+?:.*$/', $id)) {
  1281. $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
  1282. $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
  1283. }
  1284. // Check that we have a database name, give a different message if it's a
  1285. // relationship.
  1286. if ($is_relationship and !$dbname) {
  1287. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database name is not provided for this relationship term: $id", NULL);
  1288. return 0;
  1289. }
  1290. if (!$is_relationship and !$dbname) {
  1291. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database identifier is missing from the term: $id", NULL);
  1292. return 0;
  1293. }
  1294. // Make sure the CV name exists.
  1295. $cv = chado_get_cv(array('name' => $cvname));
  1296. if (!$cv) {
  1297. $cv = chado_insert_cv($cvname, '');
  1298. }
  1299. if (!$cv) {
  1300. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find namespace '$cvname' when adding/updating $id", NULL);
  1301. return 0;
  1302. }
  1303. // This SQL statement will be used a lot to find a cvterm so just set it
  1304. // here for easy reference below. Because CV terms can change their names
  1305. // but accessions don't change, the following SQL finds cvterms based on
  1306. // their accession rather than the name.
  1307. $cvtermsql = "
  1308. SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
  1309. DB.name as dbname, DB.db_id, DBX.accession
  1310. FROM {cvterm} CVT
  1311. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  1312. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  1313. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  1314. WHERE DBX.accession = :accession and DB.name = :name
  1315. ";
  1316. // Add the database. The function will just return the DB object if the
  1317. // database already exists.
  1318. $db = chado_get_db(array('name' => $dbname));
  1319. if (!$db) {
  1320. $db = chado_insert_db(array('name' => $dbname));
  1321. }
  1322. if (!$db) {
  1323. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
  1324. return 0;
  1325. }
  1326. // The cvterm table has two unique dependencies. We need to check both.
  1327. // first check the (name, cv_id, is_obsolete) constraint.
  1328. $values = array(
  1329. 'name' => $name,
  1330. 'is_obsolete' => $is_obsolete,
  1331. 'cv_id' => array(
  1332. 'name' => $cvname,
  1333. ),
  1334. );
  1335. $result = chado_select_record('cvterm', array('*'), $values);
  1336. if (count($result) == 1) {
  1337. $cvterm = $result[0];
  1338. // Get the dbxref record.
  1339. $values = array('dbxref_id' => $cvterm->dbxref_id);
  1340. $result = chado_select_record('dbxref', array('*'), $values);
  1341. $dbxref = $result[0];
  1342. if (!$dbxref) {
  1343. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  1344. 'Unable to access the dbxref record for the :term cvterm. Term Record: !record',
  1345. array(':term' => $name, '!record' => print_r($cvterm, TRUE))
  1346. );
  1347. return FALSE;
  1348. }
  1349. // Get the db.
  1350. $values = array('db_id' => $dbxref->db_id);
  1351. $result = chado_select_record('db', array('*'), $values);
  1352. $db_check = $result[0];
  1353. // // The database name for this existing term does not match that of the
  1354. // // one provided to this function. The CV name matches otherwise we
  1355. // // wouldn't have made it this far. So, let's swap the database for
  1356. // // this term.
  1357. // if ($db_check->name != $db->name) {
  1358. // // Look to see if the correct dbxref record already exists for this
  1359. // // database.
  1360. // $values = array(
  1361. // 'db_id' => $db->db_id,
  1362. // 'accession' => $accession,
  1363. // );
  1364. // $result = chado_select_record('dbxref', array('*'), $values);
  1365. // // If we already have a good dbxref then we want to update our cvterm
  1366. // // to use this dbxref.
  1367. // if (count($result) > 0) {
  1368. // $dbxref = $result[0];
  1369. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  1370. // $values = array('dbxref_id' => $dbxref->dbxref_id);
  1371. // $success = chado_update_record('cvterm', $match, $values);
  1372. // if (!$success) {
  1373. // tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
  1374. // "'$name' (id: $accession), for database $dbname", NULL);
  1375. // return 0;
  1376. // }
  1377. // }
  1378. // // If we don't have the dbxref then we want to delete our cvterm and let
  1379. // // the code below recreate it with the correct info.
  1380. // else {
  1381. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  1382. // chado_delete_record('cvterm', $match);
  1383. // }
  1384. // }
  1385. // Check that the accession matches. Sometimes an OBO can define a term
  1386. // multiple times but with different accessions. If this is the case we
  1387. // can't do an insert or it will violate the constraint in the cvterm table.
  1388. // So we'll need to add the record to the cvterm_dbxref table instead.
  1389. if ($dbxref->accession != $accession) {
  1390. // Get/add the dbxref for his term.
  1391. $dbxref_new = chado_insert_dbxref(array(
  1392. 'db_id' => $db->db_id,
  1393. 'accession' => $accession
  1394. ));
  1395. if (!$dbxref_new) {
  1396. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1397. "$name (id: $accession), for database $dbname", NULL);
  1398. return 0;
  1399. }
  1400. // Check to see if the cvterm_dbxref record already exists.
  1401. $values = array(
  1402. 'cvterm_id' => $cvterm->cvterm_id,
  1403. 'dbxref_id' => $dbxref_new->dbxref_id,
  1404. 'is_for_definition' => 1,
  1405. );
  1406. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  1407. // if the cvterm_dbxref record does not exists then add it
  1408. if (count($result)==0) {
  1409. $options = array(
  1410. 'return_record' => FALSE,
  1411. );
  1412. $success = chado_insert_record('cvterm_dbxref', $values, $options);
  1413. if (!$success) {
  1414. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
  1415. "duplicated cvterm: $name (id: $accession), for database $dbname", NULL);
  1416. return 0;
  1417. }
  1418. }
  1419. // Get the original cvterm with the same name and return that.
  1420. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  1421. $cvterm = $result->fetchObject();
  1422. return $cvterm;
  1423. }
  1424. // Continue on, we've fixed the record if the db_id did not match.
  1425. // We can now perform and updated if we need to.
  1426. }
  1427. // Get the CVterm record.
  1428. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1429. $cvterm = $result->fetchObject();
  1430. if (!$cvterm) {
  1431. // Check to see if the dbxref exists if not, add it.
  1432. $dbxref = chado_insert_dbxref(array(
  1433. 'db_id' => $db->db_id,
  1434. 'accession' => $accession
  1435. ));
  1436. if (!$dbxref) {
  1437. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1438. "$name (id: $accession), for database $dbname", NULL);
  1439. return 0;
  1440. }
  1441. // Check to see if the dbxref already has an entry in the cvterm table.
  1442. $values = array('dbxref_id' => $dbxref->dbxref_id);
  1443. $check = chado_select_record('cvterm', array('cvterm_id'), $values);
  1444. if (count($check) == 0) {
  1445. // now add the cvterm
  1446. $ins_values = array(
  1447. 'cv_id' => $cv->cv_id,
  1448. 'name' => $name,
  1449. 'definition' => $definition,
  1450. 'dbxref_id' => $dbxref->dbxref_id,
  1451. 'is_obsolete' => $is_obsolete,
  1452. 'is_relationshiptype' => $is_relationship,
  1453. );
  1454. $success = chado_insert_record('cvterm', $ins_values);
  1455. if (!$success) {
  1456. if (!$is_relationship) {
  1457. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
  1458. return 0;
  1459. }
  1460. else {
  1461. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
  1462. return 0;
  1463. }
  1464. }
  1465. }
  1466. // This dbxref already exists in the cvterm table.
  1467. else {
  1468. tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
  1469. return 0;
  1470. }
  1471. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1472. $cvterm = $result->fetchObject();
  1473. }
  1474. // Update the cvterm.
  1475. elseif ($update) {
  1476. // First, basic update of the term.
  1477. $match = array('cvterm_id' => $cvterm->cvterm_id);
  1478. $upd_values = array(
  1479. 'name' => $name,
  1480. 'definition' => $definition,
  1481. 'is_obsolete' => $is_obsolete,
  1482. 'is_relationshiptype' => $is_relationship,
  1483. );
  1484. $success = chado_update_record('cvterm', $match, $upd_values);
  1485. if (!$success) {
  1486. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
  1487. return 0;
  1488. }
  1489. // Second, check that the dbxref has not changed and if it has then update
  1490. // it.
  1491. $checksql = "
  1492. SELECT cvterm_id
  1493. FROM {cvterm} CVT
  1494. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  1495. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  1496. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  1497. WHERE DBX.accession = :accession and DB.name = :dbname and CVT.name = :term and CV.name = :cvname
  1498. ";
  1499. $check = chado_query($checksql, array(':accession' => $accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
  1500. if (!$check) {
  1501. // Check to see if the dbxref exists if not, add it.
  1502. $dbxref = chado_insert_dbxref(array(
  1503. 'db_id' => $db->db_id,
  1504. 'accession' => $accession
  1505. ));
  1506. if (!$dbxref) {
  1507. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1508. "$name (id: $accession), for database $dbname", NULL);
  1509. return 0;
  1510. }
  1511. $match = array('cvterm_id' => $cvterm->cvterm_id);
  1512. $upd_values = array(
  1513. 'dbxref_id' => $dbxref->dbxref_id,
  1514. );
  1515. $success = chado_update_record('cvterm', $match, $upd_values);
  1516. if (!$success) {
  1517. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term $name with new accession $db:$accession", NULL);
  1518. return 0;
  1519. }
  1520. }
  1521. // Finally grab the updated details.
  1522. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1523. $cvterm = $result->fetchObject();
  1524. }
  1525. else {
  1526. // Do nothing, we have the cvterm but we don't want to update.
  1527. }
  1528. // Return the cvterm.
  1529. return $cvterm;
  1530. }
  1531. /**
  1532. * TODO: deprecate this function
  1533. *
  1534. * Avoid using this function as it will be deprecated in future releases.
  1535. *
  1536. * This function allows other modules to programatically
  1537. * submit an ontology for loading into Chado.
  1538. *
  1539. * This function will add a job to the Jobs subsystem for parsing the ontology.
  1540. * You can either pass a known OBO ID to the function or the URL
  1541. * or full path the the ontology file. If a URL or file name is
  1542. * passed then the $obo_name argument must also be provided. If
  1543. * this is the first time the ontology has been provided to Tripal
  1544. * then it will be added to the database and will be assigned a
  1545. * unique OBO ID.
  1546. *
  1547. * @param $obo_id
  1548. * If the ontology is already loaded into the Tripal tables then
  1549. * use this argument to specify the unique ID for the ontology
  1550. * that will be loaded.
  1551. * @param $obo_name
  1552. * If the OBO has not been added before then use this argument
  1553. * to specify the human readable name of the ontology.
  1554. * @param $obo_url
  1555. * If the OBO to be loaded is located on a remote server then
  1556. * use this argument to provide the URL.
  1557. * @param $obo_file
  1558. * If the OBO is housed on the local file system of the server then
  1559. * use this argument to specify the full path.
  1560. *
  1561. * @return
  1562. * returns the job_id of the submitted job or FALSE if the job was not added
  1563. *
  1564. * @ingroup tripal_chado_cv_api
  1565. */
  1566. function chado_submit_obo_job($obo) {
  1567. global $user;
  1568. // Set Defaults
  1569. $obo['obo_id'] = (isset($obo['obo_id'])) ? $obo['obo_id'] : NULL;
  1570. $obo['name'] = (isset($obo['name'])) ? $obo['name'] : NULL;
  1571. $obo['url'] = (isset($obo['url'])) ? $obo['url'] : NULL;
  1572. $obo['file'] = (isset($obo['file'])) ? $obo['file'] : NULL;
  1573. $includes = array(
  1574. drupal_get_path('module', 'tripal_chado') . '/includes/tripal_chado.cv.inc',
  1575. );
  1576. if ($obo['obo_id']) {
  1577. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  1578. $result = db_query($sql, array(':obo_id' => $obo['obo_id']))->fetchObject();
  1579. $args = array($result->obo_id);
  1580. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1581. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1582. }
  1583. else {
  1584. if ($obo['url']) {
  1585. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :url";
  1586. $result = db_query($sql, array(':url' => $obo['url']))->fetchObject();
  1587. $args = array($result->obo_id);
  1588. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1589. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1590. }
  1591. elseif ($obo['file']) {
  1592. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :file";
  1593. $result = db_query($sql, array(':url' => $obo['file']))->fetchObject();
  1594. $args = array($result->obo_id);
  1595. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1596. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1597. }
  1598. }
  1599. return FALSE;
  1600. }
  1601. /**
  1602. * Add the OBO to the tripal_cv_obo table in the Drupal database.
  1603. *
  1604. * If the OBO name already exists in the table then the path is updated.
  1605. *
  1606. * @param $name
  1607. * The human readable name of this ontology.
  1608. * @param $path
  1609. * The file path or URL of the ontology.
  1610. *
  1611. * @return
  1612. * Returns the ontology ID.
  1613. *
  1614. * @ingroup tripal_chado_cv_api
  1615. */
  1616. function chado_insert_obo($name, $path) {
  1617. // Make sure an OBO with the same name doesn't already exist.
  1618. $obo_id = db_select('tripal_cv_obo', 'tco')
  1619. ->fields('tco', array('obo_id'))
  1620. ->condition('name', $name)
  1621. ->execute()
  1622. ->fetchField();
  1623. if ($obo_id) {
  1624. db_update('tripal_cv_obo')
  1625. ->fields(array(
  1626. 'path' => $path,
  1627. ))
  1628. ->condition('name', $name)
  1629. ->execute();
  1630. return $obo_id;
  1631. }
  1632. else {
  1633. $obo_id = db_insert('tripal_cv_obo')
  1634. ->fields(array(
  1635. 'name' => $name,
  1636. 'path' => $path,
  1637. ))
  1638. ->execute();
  1639. return $obo_id;
  1640. }
  1641. }
  1642. /**
  1643. * Retrieves an OBO record.
  1644. *
  1645. * @param $values
  1646. * An associate array with the following allowed keys: obo_id, name.
  1647. *
  1648. * @return
  1649. * An instance of an OBO record object.
  1650. *
  1651. * @ingroup tripal_chado_cv_api
  1652. */
  1653. function chado_get_obo($values) {
  1654. $query = db_select('tripal_cv_obo', 'tco')
  1655. ->fields('tco');
  1656. if (array_key_exists('name', $values)) {
  1657. $query->condition('tco.name', $values['name']);
  1658. }
  1659. if (array_key_exists('obo_id', $values)) {
  1660. $query->condition('tco.obo_id', $values['obo_id']);
  1661. }
  1662. return $query->execute()->fetchObject();
  1663. }
  1664. /**
  1665. * This function is intended to be used in autocomplete forms.
  1666. *
  1667. * This function searches for a matching controlled vobulary name.
  1668. *
  1669. * @param $string
  1670. * The string to search for.
  1671. *
  1672. * @return
  1673. * A json array of terms that begin with the provided string.
  1674. *
  1675. * @ingroup tripal_chado_cv_api
  1676. */
  1677. function chado_autocomplete_cv($string = '') {
  1678. $sql = "
  1679. SELECT CV.cv_id, CV.name
  1680. FROM {cv} CV
  1681. WHERE lower(CV.name) like lower(:name)
  1682. ORDER by CV.name
  1683. LIMIT 25 OFFSET 0
  1684. ";
  1685. $results = chado_query($sql, array(':name' => $string . '%'));
  1686. $items = array();
  1687. foreach ($results as $cv) {
  1688. $items[$cv->name] = $cv->name;
  1689. }
  1690. drupal_json_output($items);
  1691. }
  1692. /**
  1693. * This function is intended to be used in autocomplete forms
  1694. * for searching for CV terms that begin with the provided string.
  1695. *
  1696. * @param $cv_id
  1697. * The CV ID in which to search for the term.
  1698. * @param $string
  1699. * The string to search for.
  1700. *
  1701. * @return
  1702. * A json array of terms that begin with the provided string.
  1703. *
  1704. * @ingroup tripal_chado_cv_api
  1705. */
  1706. function chado_autocomplete_cvterm($cv_id, $string = '') {
  1707. if ($cv_id) {
  1708. $sql = "
  1709. SELECT CVT.cvterm_id, CVT.name
  1710. FROM {cvterm} CVT
  1711. WHERE CVT.cv_id = :cv_id and lower(CVT.name) like lower(:name)
  1712. UNION
  1713. SELECT CVT2.cvterm_id, CVTS.synonym as name
  1714. FROM {cvterm} CVT2
  1715. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1716. WHERE CVT2.cv_id = :cv_id and lower(CVTS.synonym) like lower(:name)
  1717. ORDER by name
  1718. LIMIT 25 OFFSET 0
  1719. ";
  1720. $results = chado_query($sql, array(':cv_id' => $cv_id, ':name' => $string . '%'));
  1721. $items = array();
  1722. foreach ($results as $term) {
  1723. $items[$term->name] = $term->name;
  1724. }
  1725. }
  1726. // If a CV wasn't provided then search all of them, and include the cv
  1727. // in the results.
  1728. else {
  1729. $sql = "
  1730. SELECT CVT.cvterm_id, CVT.name, CV.name as cvname, CVT.cv_id
  1731. FROM {cvterm} CVT
  1732. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  1733. WHERE lower(CVT.name) like lower(:name)
  1734. UNION
  1735. SELECT CVT2.cvterm_id, CVTS.synonym as name, CV2.name as cvname, CVT2.cv_id
  1736. FROM {cvterm} CVT2
  1737. INNER JOIN {cv} CV2 on CVT2.cv_id = CV2.cv_id
  1738. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1739. WHERE lower(CVTS.synonym) like lower(:name)
  1740. ORDER by name
  1741. LIMIT 25 OFFSET 0
  1742. ";
  1743. $results = chado_query($sql, array(':name' => $string . '%'));
  1744. $items = array();
  1745. foreach ($results as $term) {
  1746. $items[$term->name] = $term->name;
  1747. }
  1748. }
  1749. drupal_json_output($items);
  1750. }
  1751. /**
  1752. * Add a record to a cvterm linking table (ie: feature_cvterm).
  1753. *
  1754. * @param $basetable
  1755. * The base table to which the cvterm should be linked/associated. Thus to
  1756. * associate a cvterm to a feature the basetable=feature and cvterm_id is
  1757. * added to the feature_cvterm table.
  1758. * @param $record_id
  1759. * The primary key of the basetable to associate the cvterm with. This should
  1760. * be in integer.
  1761. * @param $cvterm
  1762. * An associative array describing the cvterm. Valid keys include:
  1763. * - name: the name for the cvterm,
  1764. * - cv_name: the name of the cv the cvterm belongs to.
  1765. * - cv_id: the primary key of the cv the cvterm belongs to.
  1766. * @param $options
  1767. * An associative array of options. Valid keys include:
  1768. * - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is
  1769. * the default.
  1770. *
  1771. * @ingroup tripal_chado_cv_api
  1772. */
  1773. function chado_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
  1774. $linking_table = $basetable . '_cvterm';
  1775. $foreignkey_name = $basetable . '_id';
  1776. // Default Values
  1777. $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
  1778. // If the cvterm_id is not set then find the cvterm record using the name and
  1779. // cv_id.
  1780. if (!isset($cvterm['cvterm_id'])) {
  1781. $values = array(
  1782. 'name' => $cvterm['name'],
  1783. );
  1784. if (isset($cvterm['cv_id'])) {
  1785. $values['cv_id'] = $cvterm['cv_id'];
  1786. }
  1787. elseif (isset($cvterm['cv_name'])) {
  1788. $values['cv_id'] = array(
  1789. 'name' => $cvterm['cv_name']
  1790. );
  1791. }
  1792. else {
  1793. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1794. "chado_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
  1795. supplied. You were trying to associate a cvterm with the %base %record_id
  1796. and supplied the cvterm values: %cvterm.",
  1797. array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
  1798. );
  1799. return FALSE;
  1800. }
  1801. // Get the cvterm. If it doesn't exist then add it if the option
  1802. // 'insert_cvterm' is set.
  1803. $select = chado_select_record('cvterm', array('*'), $values);
  1804. if ($select) {
  1805. $cvterm['cvterm_id'] = $select[0]->cvterm_id;
  1806. }
  1807. elseif ($options['insert_cvterm']) {
  1808. // Insert the cvterm
  1809. $insert = chado_insert_cvterm($values);
  1810. if (isset($insert->cvterm_id)) {
  1811. $cvterm['cvterm_id'] = $insert->cvterm_id;
  1812. }
  1813. else {
  1814. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1815. "chado_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
  1816. array('%cvterm' => print_r($cvterm,TRUE))
  1817. );
  1818. return FALSE;
  1819. }
  1820. }
  1821. else {
  1822. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1823. "chado_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
  1824. array('%cvterm' => print_r($cvterm,TRUE))
  1825. );
  1826. return FALSE;
  1827. }
  1828. }
  1829. // Now add the link between the record & cvterm.
  1830. if ($cvterm['cvterm_id'] > 0) {
  1831. $values = array(
  1832. 'cvterm_id' => $cvterm['cvterm_id'],
  1833. $foreignkey_name => $record_id,
  1834. 'pub_id' => 1,
  1835. );
  1836. // Check if the cvterm is already associated. If so, don't re-add it.
  1837. $result = chado_select_record($linking_table, array('*'), $values);
  1838. if (!$result) {
  1839. $success = chado_insert_record($linking_table, $values);
  1840. if (!$success) {
  1841. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1842. "Failed to insert the %base record %term",
  1843. array('%base' => $linking_table, '%term' => $cvterm['name'])
  1844. );
  1845. return FALSE;
  1846. }
  1847. $result = chado_select_record($linking_table, array('*'), $values);
  1848. }
  1849. if (isset($result[0])) {
  1850. return $result[0];
  1851. }
  1852. else {
  1853. return FALSE;
  1854. }
  1855. }
  1856. return FALSE;
  1857. }