tripal_core.api.inc 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. <?php
  2. /**
  3. * @file
  4. * The Tripal Core API
  5. *
  6. * This file provides the API needed for all other Tripal and Tripal dependent
  7. * modules.
  8. */
  9. /**
  10. * @defgroup tripal_api Tripal API
  11. * @{
  12. * Provides an application programming interface (API) for the tripal package
  13. *
  14. * The Tripal API currently provides generic insert/update/select functions for all chado content as
  15. * well as some module specific functions that insert/update/delete/select specific chado content.
  16. *
  17. * This API is currently in it's infancy so some necessary functions might be missing. If you come
  18. * across a missing function that you think should be included go to the sourceforge feature request * page and request it's inclusion in the API. Such feature requests with a working function * definition will be given priority.
  19. * @}
  20. */
  21. /**
  22. * @defgroup tripal_schema_api Tripal Schema API
  23. * @{
  24. * Provides an application programming interface (API) used to describe chado tables to
  25. * drupal/tripal
  26. * @}
  27. * @ingroup tripal_api
  28. */
  29. require_once "tripal_core.schema.api.inc";
  30. /**
  31. * @defgroup tripal_chado_api Tripal Chado DB API
  32. * @{
  33. * Provides an application programming interface (API) to interact with the Chado database.
  34. * @}
  35. * @ingroup tripal_api
  36. */
  37. // just a temporary function for debugging
  38. function tripal_core_chado_insert_test(){
  39. $ivalues = array(
  40. 'organism_id' => array(
  41. 'genus' => 'Lens',
  42. 'species' => 'culinaris',
  43. ),
  44. 'name' => 'orange1.1g000034m.g',
  45. 'uniquename' => 'orange1.1g000034m.g9',
  46. 'type_id' => array (
  47. 'cv_id' => array (
  48. 'name' => 'sequence',
  49. ),
  50. 'name' => 'gene',
  51. 'is_obsolete' => 0
  52. ),
  53. );
  54. $umatch = array(
  55. 'organism_id' => array(
  56. 'genus' => 'Lens',
  57. 'species' => 'culinaris',
  58. ),
  59. 'uniquename' => 'orange1.1g000034m.g9',
  60. 'type_id' => array (
  61. 'cv_id' => array (
  62. 'name' => 'sequence',
  63. ),
  64. 'name' => 'gene',
  65. 'is_obsolete' => 0
  66. ),
  67. );
  68. $uvalues = array(
  69. 'name' => 'orange1.1g000034m.g',
  70. 'type_id' => array (
  71. 'cv_id' => array (
  72. 'name' => 'sequence',
  73. ),
  74. 'name' => 'mRNA',
  75. 'is_obsolete' => 0
  76. ),
  77. );
  78. $select_multiple = array(
  79. 'dbxref_id' => array(
  80. 'db_id' => 2,
  81. )
  82. );
  83. //$result = tripal_core_chado_insert('feature',$ivalues);
  84. //return "$result->feature_id";
  85. $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  86. //$result = tripal_core_chado_select('feature',array('type_id', 'uniquename'),$select_multiple);
  87. return $result;
  88. }
  89. /**
  90. * Provides a generic routine for inserting into any Chado table
  91. *
  92. * Use this function to insert a record into any Chado table. The first
  93. * argument specifies the table for inserting and the second is an array
  94. * of values to be inserted. The array is mutli-dimensional such that
  95. * foreign key lookup values can be specified.
  96. *
  97. * @param $table
  98. * The name of the chado table for inserting
  99. * @param $values
  100. * An associative array containing the values for inserting.
  101. *
  102. * @return
  103. * On success this function returns TRUE. On failure, it returns FALSE.
  104. *
  105. * Example usage:
  106. * @code
  107. * $values = array(
  108. * 'organism_id' => array(
  109. * 'genus' => 'Citrus',
  110. * 'species' => 'sinensis',
  111. * ),
  112. * 'name' => 'orange1.1g000034m.g',
  113. * 'uniquename' => 'orange1.1g000034m.g',
  114. * 'type_id' => array (
  115. * 'cv_id' => array (
  116. * 'name' => 'sequence',
  117. * ),
  118. * 'name' => 'gene',
  119. * 'is_obsolete' => 0
  120. * ),
  121. * );
  122. * $result = tripal_core_chado_insert('feature',$values);
  123. * @endcode
  124. * The above code inserts a record into the feature table. The $values array is
  125. * nested such that the organism is selected by way of the organism_id foreign
  126. * key constraint by specifying the genus and species. The cvterm is also
  127. * specified using its foreign key and the cv_id for the cvterm is nested as
  128. * well.
  129. *
  130. * @ingroup tripal_chado_api
  131. */
  132. function tripal_core_chado_insert($table,$values){
  133. $insert_values = array();
  134. // get the table description
  135. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  136. // iterate through the values array and create a new 'insert_values' array
  137. // that has all the values needed for insert with all foreign relationsihps
  138. // resolved.
  139. foreach($values as $field => $value){
  140. if(is_array($value)){
  141. // select the value from the foreign key relationship for this value
  142. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  143. if (sizeof($results) > 1) {
  144. watchdog('tripal_core', 'tripal_core_chado_insert: Too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  145. } elseif (sizeof($results) < 1) {
  146. watchdog('tripal_core', 'tripal_core_chado_insert: no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  147. } else {
  148. $insert_values[$field] = $results[0];
  149. }
  150. }
  151. else {
  152. $insert_values[$field] = $value;
  153. }
  154. }
  155. // check for violation of any unique constraints
  156. $ukeys = $table_desc['unique keys'];
  157. $ukselect_cols = array();
  158. $ukselect_vals = array();
  159. if ($ukeys) {
  160. foreach($ukeys as $name => $fields){
  161. foreach($fields as $index => $field){
  162. // build the arrays for performing a select that will check the contraint
  163. array_push($ukselect_cols,$field);
  164. $ukselect_vals[$field] = $insert_values[$field];
  165. }
  166. // now check the constraint
  167. if(tripal_core_chado_select($table,$ukselect_cols,$ukselect_vals)){
  168. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  169. return false;
  170. }
  171. }
  172. }
  173. // if trying to insert a field that is the primary key, make sure it also is unique
  174. $pkey = $table_desc['primary key'][0];
  175. if($insert_values[$pkey]){
  176. if(tripal_core_chado_select($table,array($pkey),array($pkey => $insert_values[$pkey]))){
  177. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  178. return false;
  179. }
  180. }
  181. // make sure required fields have a value
  182. $fields = $table_desc['fields'];
  183. foreach($fields as $field => $def){
  184. // a field is considered missing if it cannot be null and there is no default
  185. // value for it or it is of type 'serial'
  186. if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !isset($def['default']) and strcmp($def['type'],serial)!=0){
  187. watchdog('tripal_core',"tripal_core_chado_insert: Field $table.$field cannot be null: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  188. return false;
  189. }
  190. }
  191. // Now build the insert SQL statement
  192. $ifields = array();
  193. $ivalues = array();
  194. $itypes = array();
  195. foreach ($insert_values as $field => $value){
  196. array_push($ifields,$field);
  197. array_push($ivalues,$value);
  198. if(strcmp($fields[$field]['type'],'serial')==0 or
  199. strcmp($fields[$field]['type'],'int')==0){
  200. array_push($itypes,"%d");
  201. } else {
  202. array_push($itypes,"'%s'");
  203. }
  204. }
  205. $sql = "INSERT INTO {$table} (" . implode(", ",$ifields) . ") VALUES (". implode(", ",$itypes) .")";
  206. // finally perform the insert.
  207. $previous_db = tripal_db_set_active('chado'); // use chado database
  208. $result = db_query($sql,$ivalues);
  209. tripal_db_set_active($previous_db); // now use drupal database
  210. if($result){
  211. // add primary keys to values before return
  212. $primary_key = array();
  213. foreach ($table_desc['primary key'] as $field) {
  214. $value = db_last_insert_id($table, $field);
  215. $values[$field] = $value;
  216. }
  217. return $values;
  218. }
  219. else {
  220. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  221. return false;
  222. }
  223. return false;
  224. }
  225. /**
  226. * Provides a generic function for deleting a record(s) from any chado table
  227. *
  228. * Use this function to delete a record(s) in any Chado table. The first
  229. * argument specifies the table to delete from and the second is an array
  230. * of values to match for locating the record(s) to be deleted. The arrays
  231. * are mutli-dimensional such that foreign key lookup values can be specified.
  232. *
  233. * @param $table
  234. * The name of the chado table for inserting
  235. * @param $match
  236. * An associative array containing the values for locating a record to update.
  237. *
  238. * @return
  239. * On success this function returns TRUE. On failure, it returns FALSE.
  240. *
  241. * Example usage:
  242. * @code
  243. $umatch = array(
  244. 'organism_id' => array(
  245. 'genus' => 'Citrus',
  246. 'species' => 'sinensis',
  247. ),
  248. 'uniquename' => 'orange1.1g000034m.g7',
  249. 'type_id' => array (
  250. 'cv_id' => array (
  251. 'name' => 'sequence',
  252. ),
  253. 'name' => 'gene',
  254. 'is_obsolete' => 0
  255. ),
  256. );
  257. $uvalues = array(
  258. 'name' => 'orange1.1g000034m.g',
  259. 'type_id' => array (
  260. 'cv_id' => array (
  261. 'name' => 'sequence',
  262. ),
  263. 'name' => 'mRNA',
  264. 'is_obsolete' => 0
  265. ),
  266. );
  267. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  268. * @endcode
  269. * The above code species that a feature with a given uniquename, organism_id,
  270. * and type_id (the unique constraint for the feature table) will be deleted.
  271. * The organism_id is specified as a nested array that uses the organism_id
  272. * foreign key constraint to lookup the specified values to find the exact
  273. * organism_id. The same nested struture is also used for specifying the
  274. * values to update. The function will find all records that match the
  275. * columns specified and delete them.
  276. *
  277. * @ingroup tripal_chado_api
  278. */
  279. function tripal_core_chado_delete($table,$match){
  280. $delete_matches = array(); // contains the values for the where clause
  281. // get the table description
  282. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  283. // get the values needed for matching in the SQL statement
  284. foreach ($match as $field => $value){
  285. if(is_array($value)){
  286. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  287. if (sizeof($results) > 1) {
  288. watchdog('tripal_core', 'tripal_core_chado_delete: When trying to find record to delete, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  289. } elseif (sizeof($results) < 1) {
  290. watchdog('tripal_core', 'tripal_core_chado_delete: When trying to find record to delete, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  291. } else {
  292. $delete_matches[$field] = $results[0];
  293. }
  294. }
  295. else {
  296. $delete_matches[$field] = $value;
  297. }
  298. }
  299. // now build the SQL statement
  300. $sql = "DELETE FROM {$table} WHERE ";
  301. $dargs = array();
  302. foreach($delete_matches as $field => $value){
  303. if(strcmp($fields[$field]['type'],'serial')==0 or
  304. strcmp($fields[$field]['type'],'int')==0){
  305. $sql .= " $field = %d AND ";
  306. } else {
  307. $sql .= " $field = '%s' AND ";
  308. }
  309. array_push($dargs,$value);
  310. }
  311. $sql = substr($sql,0,-4); // get rid of the trailing 'AND'
  312. // finally perform the delete. If successful, return the updated record
  313. $previous_db = tripal_db_set_active('chado'); // use chado database
  314. $result = db_query($sql,$dargs);
  315. tripal_db_set_active($previous_db); // now use drupal database
  316. if($result){
  317. return true;
  318. }
  319. else {
  320. watchdog('tripal_core',"Cannot delete record in $table table. Match:" . print_r($match,1) . ". Values: ". print_r($values,1),array(),'WATCHDOG_ERROR');
  321. return false;
  322. }
  323. return false;
  324. }
  325. /**
  326. * Provides a generic routine for updating into any Chado table
  327. *
  328. * Use this function to update a record in any Chado table. The first
  329. * argument specifies the table for inserting, the second is an array
  330. * of values to matched for locating the record for updating, and the third
  331. * argument give the values to update. The arrays are mutli-dimensional such
  332. * that foreign key lookup values can be specified.
  333. *
  334. * @param $table
  335. * The name of the chado table for inserting
  336. * @param $match
  337. * An associative array containing the values for locating a record to update.
  338. * @param $values
  339. * An associative array containing the values for updating.
  340. *
  341. * @return
  342. * On success this function returns TRUE. On failure, it returns FALSE.
  343. *
  344. * Example usage:
  345. * @code
  346. $umatch = array(
  347. 'organism_id' => array(
  348. 'genus' => 'Citrus',
  349. 'species' => 'sinensis',
  350. ),
  351. 'uniquename' => 'orange1.1g000034m.g7',
  352. 'type_id' => array (
  353. 'cv_id' => array (
  354. 'name' => 'sequence',
  355. ),
  356. 'name' => 'gene',
  357. 'is_obsolete' => 0
  358. ),
  359. );
  360. $uvalues = array(
  361. 'name' => 'orange1.1g000034m.g',
  362. 'type_id' => array (
  363. 'cv_id' => array (
  364. 'name' => 'sequence',
  365. ),
  366. 'name' => 'mRNA',
  367. 'is_obsolete' => 0
  368. ),
  369. );
  370. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  371. * @endcode
  372. * The above code species that a feature with a given uniquename, organism_id,
  373. * and type_id (the unique constraint for the feature table) will be updated.
  374. * The organism_id is specified as a nested array that uses the organism_id
  375. * foreign key constraint to lookup the specified values to find the exact
  376. * organism_id. The same nested struture is also used for specifying the
  377. * values to update. The function will find the record that matches the
  378. * columns specified and update the record with the avlues in the $uvalues array.
  379. *
  380. * @ingroup tripal_chado_api
  381. */
  382. function tripal_core_chado_update($table,$match,$values){
  383. $update_values = array(); // contains the values to be updated
  384. $update_matches = array(); // contains the values for the where clause
  385. // get the table description
  386. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  387. // get the values needed for matching in the SQL statement
  388. foreach ($match as $field => $value){
  389. if(is_array($value)){
  390. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  391. if (sizeof($results) > 1) {
  392. watchdog('tripal_core', 'tripal_core_chado_update: When trying to find record to update, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  393. } elseif (sizeof($results) < 1) {
  394. watchdog('tripal_core', 'tripal_core_chado_update: When trying to find record to update, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  395. } else {
  396. $update_matches[$field] = $results[0];
  397. }
  398. }
  399. else {
  400. $update_matches[$field] = $value;
  401. }
  402. }
  403. // get the values used for updating
  404. foreach ($values as $field => $value){
  405. if(is_array($value)){
  406. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  407. if (sizeof($results) > 1) {
  408. watchdog('tripal_core', 'tripal_core_chado_update: When trying to find update values, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  409. } elseif (sizeof($results) < 1) {
  410. watchdog('tripal_core', 'tripal_core_chado_update: When trying to find update values, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
  411. } else {
  412. $update_values[$field] = $results[0];
  413. }
  414. }
  415. else {
  416. $update_values[$field] = $value;
  417. }
  418. }
  419. // now build the SQL statement
  420. $sql = "UPDATE {$table} SET ";
  421. $fields = $table_desc['fields'];
  422. $uargs = array();
  423. foreach($update_values as $field => $value){
  424. if(strcmp($fields[$field]['type'],'serial')==0 or
  425. strcmp($fields[$field]['type'],'int')==0){
  426. $sql .= " $field = %d, ";
  427. } else {
  428. $sql .= " $field = '%s', ";
  429. }
  430. array_push($uargs,$value);
  431. }
  432. $sql = substr($sql,0,-2); // get rid of the trailing comma & space
  433. $sql .= " WHERE ";
  434. foreach($update_matches as $field => $value){
  435. if(strcmp($fields[$field]['type'],'serial')==0 or
  436. strcmp($fields[$field]['type'],'int')==0){
  437. $sql .= " $field = %d AND ";
  438. } else {
  439. $sql .= " $field = '%s' AND ";
  440. }
  441. array_push($uargs,$value);
  442. }
  443. $sql = substr($sql,0,-4); // get rid of the trailing 'AND'
  444. // finally perform the update. If successful, return the updated record
  445. $previous_db = tripal_db_set_active('chado'); // use chado database
  446. $result = db_query($sql,$uargs);
  447. tripal_db_set_active($previous_db); // now use drupal database
  448. if($result){
  449. return true;
  450. }
  451. else {
  452. watchdog('tripal_core',"Cannot update record in $table table. Match:" . print_r($match,1) . ". Values: ". print_r($values,1),array(),'WATCHDOG_ERROR');
  453. return false;
  454. }
  455. return false;
  456. }
  457. /**
  458. * Provides a generic routine for selecting data from a Chado table
  459. *
  460. * Use this function to perform a simple select from any Chado table.
  461. *
  462. * @param $table
  463. * The name of the chado table for inserting
  464. * @param $columns
  465. * An array of column names
  466. * @param $values
  467. * An associative array containing the values for filtering the results. In the
  468. * case where multiple values for the same time are to be selected an additional
  469. * entry for the field should appear for each value
  470. * @param $options
  471. * An associative array of additional options where the key is the option
  472. * and the value is the value of that option.
  473. *
  474. * Additional Options Include:
  475. * - has_record
  476. * Set this argument to 'true' to have this function return a numeric
  477. * value for the number of recrods rather than the array of records. this
  478. * can be useful in 'if' statements to check the presence of particula records.
  479. * - return_sql
  480. * Set this to 'true' to have this function return an array where the first
  481. * element is the sql that would have been run and the second is an array of
  482. * arguments.
  483. * - case_insensitive_columns
  484. * An array of columns to do a case insensitive search on.
  485. * - regex_columns
  486. * An array of columns where the value passed in should be treated as a regular expression
  487. * - order_by
  488. * An associative array containing the column names of the table as keys
  489. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  490. * query will be sorted by the key values in the direction listed by the value
  491. *
  492. * @return
  493. * A database query result resource, FALSE if the query was not executed
  494. * correctly, or the number of records in the dataset if $has_record is set.
  495. *
  496. * Example usage:
  497. * @code
  498. * $columns = array('feature_id','name');
  499. * $values = array(
  500. * 'organism_id' => array(
  501. * 'genus' => 'Citrus',
  502. * 'species' => array('sinensis','clementina'),
  503. * ),
  504. * 'uniquename' => 'orange1.1g000034m.g',
  505. * 'type_id' => array (
  506. * 'cv_id' => array (
  507. * 'name' => 'sequence',
  508. * ),
  509. * 'name' => 'gene',
  510. * 'is_obsolete' => 0
  511. * ),
  512. * );
  513. * $result = tripal_core_chado_select('feature',$columns,$values);
  514. * @endcode
  515. * The above code selects a record from the feature table using the three fields
  516. * that uniquely identify a feature. The $columns array simply lists the columns
  517. * to select. The $values array is nested such that the organism is identified by
  518. * way of the organism_id foreign key constraint by specifying the genus and
  519. * species. The cvterm is also specified using its foreign key and the cv_id
  520. * for the cvterm is nested as well. In the example above, two different species
  521. * are allowed to match
  522. *
  523. * @ingroup tripal_chado_api
  524. */
  525. function tripal_core_chado_select($table,$columns,$values,$options = null){
  526. if (!is_array($options)) { $options = array(); }
  527. if (!$options['case_insensitive_columns']) { $options['case_insensitive_columns'] = array(); }
  528. if (!$options['regex_columns']) { $options['regex_columns'] = array(); }
  529. if (!$options['order_by']) { $options['order_by'] = array(); }
  530. if (!is_array($columns)){
  531. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  532. return false;
  533. }
  534. if (!is_array($values)){
  535. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  536. return false;
  537. }
  538. // get the table description
  539. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  540. $select = '';
  541. $from = '';
  542. $where = '';
  543. $args = array();
  544. foreach($values as $field => $value){
  545. $select[] = $field;
  546. if(is_array($value)){
  547. // if the user has specified multiple values for matching then this we
  548. // want to catch that and save them in our $where array, otherwise
  549. // we'll descend for a foreign key relationship
  550. if(array_values($value) === $value){
  551. $where[$field] = $value;
  552. } else {
  553. // select the value from the foreign key relationship for this value
  554. $foreign_options = array(
  555. 'regex_columns' => $options['regex_columns'],
  556. 'case_insensitive_columns' => $options['case_insensitive_columns']
  557. );
  558. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value, $foreign_options);
  559. if (sizeof($results) < 1) {
  560. // foreign key records are required
  561. // thus if none matched then return false and alert the admin through watchdog
  562. watchdog('tripal_core',
  563. 'tripal_core_chado_select: no record in the table referenced by the foreign key (!field) exists. tripal_core_chado_select table=!table, columns=!columns, values=!values',
  564. array('!table' => $table,
  565. '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  566. '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  567. '!field' => $field,
  568. ),
  569. WATCHDOG_WARNING);
  570. return false;
  571. } else {
  572. $where[$field] = $results;
  573. }
  574. }
  575. }
  576. else {
  577. //need to catch a 0 and make int if integer field
  578. if ($table_desc['fields'][$field]['type'] == 'int') {
  579. $where[$field][] = (int) $value;
  580. } else {
  581. $where[$field][] = $value;
  582. }
  583. }
  584. }
  585. // now build the SQL select statement
  586. if (empty($where)) {
  587. // sometimes want to select everything
  588. $sql = "SELECT " . implode(',',$columns) . " ";
  589. $sql .= "FROM {$table} ";
  590. } else {
  591. $sql = "SELECT " . implode(',',$columns) . " ";
  592. $sql .= "FROM {$table} ";
  593. $sql .= "WHERE ";
  594. foreach($where as $field => $value){
  595. if (count($value) > 1) {
  596. $sql .= "$field IN (".db_placeholders($value,'varchar').") AND ";
  597. foreach ($value as $v) { $args[] = $v; }
  598. } else {
  599. $operator = '=';
  600. if (in_array($field, $options['regex_columns'])) {
  601. $operator = '~*';
  602. }
  603. if (in_array($field, $options['case_insensitive_columns'])) {
  604. $sql .= "lower($field) $operator lower('%s') AND ";
  605. $args[] = $value[0];
  606. } else {
  607. $sql .= "$field $operator '%s' AND ";
  608. $args[] = $value[0];
  609. }
  610. }
  611. }
  612. $sql = substr($sql,0,-4); // get rid of the trailing 'AND '
  613. }
  614. // finally add any ordering of the results to the SQL statement
  615. if(count($options['order_by']) > 0){
  616. $sql .= " ORDER BY ";
  617. foreach($options['order_by'] as $field => $dir){
  618. $sql .= "$field $dir, ";
  619. }
  620. $sql = substr($sql,0,-2); // get rid of the trailing ', '
  621. }
  622. // if the caller has requested the SQL rather than the results...
  623. // which happens in the case of wanting to use the Drupal pager, then do so
  624. if($options['return_sql']){
  625. return array('sql'=> $sql, 'args' => $args);
  626. }
  627. $previous_db = tripal_db_set_active('chado'); // use chado database
  628. $resource = db_query($sql,$args);
  629. tripal_db_set_active($previous_db); // now use drupal database
  630. $results = array();
  631. while ($r = db_fetch_object($resource)) {
  632. $results[] = $r;
  633. }
  634. if(!$options['has_record']){
  635. return $results;
  636. } else{
  637. return count($results);
  638. }
  639. }
  640. /**
  641. * Gets the value of a foreign key relationship
  642. *
  643. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  644. * and tripal_core_chado_update to iterate through the associate array of
  645. * values that gets passed to each of those routines. The values array
  646. * is nested where foreign key contraints are used to specify a value that. See
  647. * documentation for any of those functions for further information.
  648. *
  649. * @param $table_desc
  650. * A table description for the table with the foreign key relationship to be identified generated by
  651. * hook_chado_<table name>_schema()
  652. * @param $field
  653. * The field in the table that is the foreign key.
  654. * @param $values
  655. * An associative array containing the values
  656. * @param $options
  657. * An associative array of additional options where the key is the option
  658. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  659. *
  660. * Additional Options Include:
  661. * - case_insensitive_columns
  662. * An array of columns to do a case insensitive search on.
  663. * - regex_columns
  664. * An array of columns where the value passed in should be treated as a regular expression
  665. *
  666. * @return
  667. * A string containg the results of the foreign key lookup, or FALSE if failed.
  668. *
  669. * Example usage:
  670. * @code
  671. *
  672. * $values = array(
  673. * 'genus' => 'Citrus',
  674. * 'species' => 'sinensis',
  675. * );
  676. * $value = tripal_core_chado_get_foreign_key('feature','organism_id',$values);
  677. *
  678. * @endcode
  679. * The above code selects a record from the feature table using the three fields
  680. * that uniquely identify a feature. The $columns array simply lists the columns
  681. * to select. The $values array is nested such that the organism is identified by
  682. * way of the organism_id foreign key constraint by specifying the genus and
  683. * species. The cvterm is also specified using its foreign key and the cv_id
  684. * for the cvterm is nested as well.
  685. *
  686. * @ingroup tripal_chado_api
  687. */
  688. function tripal_core_chado_get_foreign_key($table_desc,$field,$values, $options = null){
  689. if (!is_array($options)) { $options = array(); }
  690. if (!$options['case_insensitive_columns']) { $options['case_insensitive_columns'] = array(); }
  691. if (!$options['regex_columns']) { $options['regex_columns'] = array(); }
  692. // get the list of foreign keys for this table description and
  693. // iterate through those until we find the one we're looking for
  694. $fkeys = $table_desc['foreign keys'];
  695. if($fkeys){
  696. foreach($fkeys as $name => $def){
  697. if (is_array($def['table'])) {
  698. //foreign key was described 2X
  699. $message = "The foreign key ".$name." was defined twice. Please check modules to determine if hook_chado_".$table_desc['table']."_schema() was implemented and defined this foreign key when it wasn't supposed to. Modules this hook was implemented in: ".implode(', ', module_implements("chado_".$table_desc['table']."_schema")).".";
  700. watchdog('tripal_core', $message);
  701. drupal_set_message($message,'error');
  702. continue;
  703. }
  704. $table = $def['table'];
  705. $columns = $def['columns'];
  706. // iterate through the columns of the foreign key relationship
  707. foreach($columns as $left => $right){
  708. // does the left column in the relationship match our field?
  709. if(strcmp($field,$left)==0){
  710. // the column name of the foreign key matches the field we want
  711. // so this is the right relationship. Now we want to select
  712. $select_cols = array($right);
  713. $result = tripal_core_chado_select($table,$select_cols,$values, $options);
  714. $fields = array();
  715. foreach ($result as $obj) {
  716. $fields[] = $obj->$right;
  717. }
  718. return $fields;
  719. }
  720. }
  721. }
  722. }
  723. else {
  724. // TODO: what do we do if we get to this point and we have a fk
  725. // relationship expected but we don't have any definition for one in the
  726. // table schema??
  727. $message = "There is no foreign key relationship defined for ".$field.".
  728. To define a foreign key relationship, determine the table this foreign
  729. key referrs to (<foreign table>) and then implement
  730. hook_chado_<foreign table>_schema(). See
  731. tripal_feature_chado_feature_schema for an example.";
  732. watchdog('tripal_core', $message);
  733. drupal_set_message($message,'error');
  734. }
  735. return false;
  736. }
  737. /**
  738. * Generates an object containing the full details of a record(s) in chado.
  739. *
  740. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  741. * relationships have been followed meaning you have more complete details. Thus this function
  742. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  743. * you only case about a few columns.
  744. *
  745. * @param $table
  746. * The name of the base table to generate a variable for
  747. * @param $values
  748. * A select values array that selects the records you want from the base table
  749. * (this has the same form as tripal_core_chado_select)
  750. * @param $base_options
  751. * An array containing options for the base table. For example, an
  752. * option of 'order_by' may be used to sort results in the base table
  753. * if more than one are returned. The options must be compatible with
  754. * the options accepted by the tripal_core_chado_select() function.
  755. * @return
  756. * Either an object (if only one record was selected from the base table)
  757. * or an array of objects (if more than one record was selected from the base table).
  758. *
  759. * Example Usage:
  760. * @code
  761. $values = array(
  762. 'name' => 'Medtr4g030710'
  763. );
  764. $features = tripal_core_generate_chado_var('feature', $values);
  765. * @endcode
  766. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  767. * return an array of feature objects if more than one feature has that name.
  768. *
  769. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  770. * one of the following hooks:
  771. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  772. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  773. * this hook to return an array of fields to be excluded. For example:
  774. * @code
  775. mymodule_exclude_field_from_feature_by_default() {
  776. return array('residues' => TRUE);
  777. }
  778. * @endcode
  779. * will ensure that feature.residues is ecluded from a feature object by default.
  780. * - hook_exclude_type_by_default:
  781. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  782. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  783. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  784. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  785. * @code
  786. mymodule_exclude_type_by_default() {
  787. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  788. }
  789. * @endcode
  790. * will exclude all text fields with a length > 50. Thus if $feature.residues is longer than 50 * it will be excluded, otherwise it will be added.
  791. *
  792. * @ingroup tripal_chado_api
  793. */
  794. function tripal_core_generate_chado_var($table, $values, $base_options=array()) {
  795. // get description for the current table----------------------------------------------------------
  796. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  797. $table_primary_key = $table_desc['primary key'][0];
  798. $table_columns = array_keys($table_desc['fields']);
  799. // Expandable fields without value needed for criteria--------------------------------------------
  800. $all->expandable_fields = array();
  801. if ($table_desc['referring_tables']) {
  802. $all->expandable_tables = $table_desc['referring_tables'];
  803. } else {
  804. $all->expandable_tables = array();
  805. }
  806. $all->expandable_nodes = array();
  807. // Get fields to be removed by name.................................
  808. $fields_to_remove = module_invoke_all('exclude_field_from_'.$table.'_by_default');
  809. foreach ($fields_to_remove as $field_name => $criteria) {
  810. //replace &gt;field_name&lt; with the current field name &
  811. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  812. // if field_value needed we can't deal with this field yet
  813. if (preg_match('/&gt;field_value&lt; /', $criteria)) { break; }
  814. //if criteria then remove from query
  815. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  816. // watchdog('tripal_core',
  817. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  818. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  819. // WATCHDOG_NOTICE
  820. // );
  821. if ($success) {
  822. unset($table_columns[array_search($field_name, $table_columns)]);
  823. unset($fields_to_remove[$field_name]);
  824. $all->expandable_fields[] = $table . '.' . $field_name;
  825. }
  826. }
  827. //Get fields to be removed by type................................
  828. $types_to_remove = module_invoke_all('exclude_type_by_default');
  829. $field_types = array();
  830. foreach ($table_desc['fields'] as $field_name => $field_array) {
  831. $field_types[$field_array['type']][] = $field_name;
  832. }
  833. foreach ($types_to_remove as $field_type => $criteria) {
  834. // if there are fields of that type to remove
  835. if (is_array($field_types[$field_type])) {
  836. //replace &gt;field_name&lt; with the current field name &
  837. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  838. foreach ($field_types[$field_type] as $field_name) {
  839. // if field_value needed we can't deal with this field yet
  840. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  841. $fields_to_remove[$field_name] = $criteria;
  842. continue;
  843. }
  844. // if field_value needed we can't deal with this field yet
  845. if (preg_match('/&gt;field_value&lt; /', $criteria)) { break; }
  846. //if criteria then remove from query
  847. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  848. // watchdog('tripal_core',
  849. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  850. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  851. // WATCHDOG_NOTICE
  852. // );
  853. if ($success) {
  854. unset($table_columns[array_search($field_name, $table_columns)]);
  855. $all->expandable_fields[] = $table . '.' . $field_name;
  856. }
  857. } //end of foreach field of that type
  858. }
  859. } //end of foreach type to be removed
  860. // get the values for the record in the current table---------------------------------------------
  861. $results = tripal_core_chado_select($table, $table_columns, $values,$base_options);
  862. if($results){
  863. foreach ($results as $key => $object) {
  864. // Add empty expandable_x arrays
  865. $object->expandable_fields = $all->expandable_fields;
  866. $object->expandable_tables = $all->expandable_tables;
  867. $object->expandable_nodes = $all->expandable_nodes;
  868. // add curent table
  869. $object->tablename = $table;
  870. // check if the current table maps to a node type-----------------------------------------------
  871. // if this table is connected to a node there will be a chado_tablename table in drupal
  872. if (db_table_exists('chado_'.$table)) {
  873. // that has a foreign key to this one ($table_desc['primary key'][0]
  874. // and to the node table (nid)
  875. $sql = "SELECT %s, nid FROM chado_%s WHERE %s=%d";
  876. $mapping = db_fetch_object(db_query(
  877. $sql,
  878. $table_primary_key,
  879. $table,
  880. $table_primary_key,
  881. $object->{$table_primary_key}
  882. ));
  883. if ($mapping->{$table_primary_key}) {
  884. $object->nid = $mapping->nid;
  885. $object->expandable_nodes[] = $table;
  886. }
  887. }
  888. // remove any fields where criteria need to be evalulated---------------------------------------
  889. foreach ($fields_to_remove as $field_name => $criteria) {
  890. if (!isset($object->{$field_name})) { break; }
  891. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  892. //if criteria then remove from query
  893. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  894. // watchdog('tripal_core',
  895. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  896. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  897. // WATCHDOG_NOTICE
  898. // );
  899. if ($success) {
  900. unset($object->{$field_name});
  901. $object->expandable_fields[] = $table . '.' . $field_name;
  902. }
  903. }
  904. // recursively follow foreign key relationships nesting objects as we go------------------------
  905. if ($table_desc['foreign keys']) {
  906. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  907. $foreign_table = $foreign_key_array['table'];
  908. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  909. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  910. // the table referenced by the foreign key
  911. //Dont do anything if the foreign key is empty
  912. if (empty($object->{$foreign_key})) {
  913. break;
  914. }
  915. // get the record from the foreign table
  916. $foreign_values = array($primary_key => $object->{$foreign_key});
  917. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  918. // add the foreign record to the current object in a nested manner
  919. $object->{$foreign_key} = $foreign_object;
  920. // Flatten expandable_x arrays so only in the bottom object
  921. if (is_array($object->{$foreign_key}->expandable_fields)) {
  922. $object->expandable_fields = array_merge(
  923. $object->expandable_fields,
  924. $object->{$foreign_key}->expandable_fields
  925. );
  926. unset($object->{$foreign_key}->expandable_fields);
  927. }
  928. if (is_array($object->{$foreign_key}->expandable_tables)) {
  929. $object->expandable_tables = array_merge(
  930. $object->expandable_tables,
  931. $object->{$foreign_key}->expandable_tables
  932. );
  933. unset($object->{$foreign_key}->expandable_tables);
  934. }
  935. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  936. $object->expandable_nodes = array_merge(
  937. $object->expandable_nodes,
  938. $object->{$foreign_key}->expandable_nodes
  939. );
  940. unset($object->{$foreign_key}->expandable_nodes);
  941. }
  942. }
  943. }
  944. $results[$key] = $object;
  945. }
  946. }
  947. }
  948. // check only one result returned
  949. if (sizeof($results) == 1) {
  950. // add results to object
  951. return $results[0];
  952. } elseif (!empty($results)) {
  953. return $results;
  954. } else {
  955. // no results returned
  956. }
  957. }
  958. /**
  959. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  960. *
  961. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  962. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  963. * the tripal admin to get at these variables if he/she wants them.
  964. *
  965. * @param $object
  966. * This must be an object generated using tripal_core_generate_chado_var()
  967. * @param $type
  968. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  969. * @param $to_expand
  970. * The name of the field/table/node to be expanded
  971. * @param $table_options
  972. * An array containing options for the base table. For example, an
  973. * option of 'order_by' may be used to sort results in the base table
  974. * if more than one are returned. The options must be compatible with
  975. * the options accepted by the tripal_core_chado_select() function.
  976. * @return
  977. * A chado object supplemented with the field/table/node requested to be expanded
  978. *
  979. * Example Usage:
  980. * @code
  981. // Get a chado object to be expanded
  982. $values = array(
  983. 'name' => 'Medtr4g030710'
  984. );
  985. $features = tripal_core_generate_chado_var('feature', $values);
  986. // Expand the organism node
  987. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  988. // Expand the feature.residues field
  989. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  990. // Expand the feature properties (featureprop table)
  991. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  992. * @endcode
  993. *
  994. * @ingroup tripal_chado_api
  995. */
  996. function tripal_core_expand_chado_vars ($object, $type, $to_expand,$table_options = array()) {
  997. $base_table = $object->tablename;
  998. // check to see if they are expanding an array of objects
  999. if (is_array($object)) {
  1000. foreach ($object as $index => $o) {
  1001. $object[$index] = tripal_core_expand_chado_vars($o,$type,$to_expand);
  1002. }
  1003. return $object;
  1004. }
  1005. switch ($type) {
  1006. case "field": //--------------------------------------------------------------------------------
  1007. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1008. $tablename = $matches[1];
  1009. $fieldname = $matches[2];
  1010. $table_desc = module_invoke_all('chado_'.$tablename.'_schema');
  1011. $values = array();
  1012. foreach($table_desc['primary key'] as $key) {
  1013. $values[$key] = $object->{$key};
  1014. }
  1015. if ($base_table == $tablename) {
  1016. //get the field
  1017. $results = tripal_core_chado_select(
  1018. $tablename,
  1019. array($fieldname),
  1020. $values
  1021. );
  1022. $object->{$fieldname} = $results[0]->{$fieldname};
  1023. $object->expanded = $to_expand;
  1024. } else {
  1025. //We need to recurse -the field is in a nested object
  1026. foreach ((array) $object as $field_name => $field_value) {
  1027. if (is_object($field_value)) {
  1028. $object->{$field_name} = tripal_core_expand_chado_vars(
  1029. $field_value,
  1030. 'field',
  1031. $to_expand
  1032. );
  1033. }
  1034. } //end of for each field in the current object
  1035. }
  1036. } else {
  1037. watchdog(
  1038. 'tripal_core',
  1039. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  1040. WATCHDOG_ERROR
  1041. );
  1042. }
  1043. break;
  1044. case "table": //--------------------------------------------------------------------------------
  1045. $foreign_table = $to_expand;
  1046. $foreign_table_desc = module_invoke_all('chado_'.$foreign_table.'_schema');
  1047. // If it's connected to the base table
  1048. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1049. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1050. if (!$object->{$right}) { break; }
  1051. if (is_array($values)) {
  1052. $values = array_merge($values, array($left => $object->{$right}) );
  1053. } else {
  1054. $values = array($left => $object->{$right});
  1055. }
  1056. $foreign_object = tripal_core_generate_chado_var(
  1057. $foreign_table,
  1058. array($left => $object->{$right}),
  1059. $table_options
  1060. );
  1061. if ($foreign_object) {
  1062. // in the case where the a foreign key relationships exists more
  1063. // than once with the same table we want to alter the
  1064. // array structure
  1065. if(count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1){
  1066. $object->{$foreign_table}->{$left} = $foreign_object;
  1067. $object->expanded = $to_expand;
  1068. } else {
  1069. $object->{$foreign_table} = $foreign_object;
  1070. $object->expanded = $to_expand;
  1071. }
  1072. }
  1073. }
  1074. } else {
  1075. //We need to recurse -the table has a relationship to one of the nested objects
  1076. foreach ((array) $object as $field_name => $field_value) {
  1077. // if we have a nested object ->expand the table in it
  1078. if (is_object($field_value)) {
  1079. $object->{$field_name} = tripal_core_expand_chado_vars(
  1080. $field_value,
  1081. 'table',
  1082. $foreign_table
  1083. );
  1084. }
  1085. }
  1086. }
  1087. break;
  1088. case "node": //---------------------------------------------------------------------------------
  1089. //if the node to be expanded is for our base table, then just expand it
  1090. if ($object->tablename == $to_expand) {
  1091. $node = node_load($object->nid);
  1092. if ($node) {
  1093. $object->expanded = $to_expand;
  1094. $node->expandable_fields = $object->expandable_fields;
  1095. unset($object->expandable_fields);
  1096. $node->expandable_tables = $object->expandable_tables;
  1097. unset($object->expandable_tables);
  1098. $node->expandable_nodes = $object->expandable_nodes;
  1099. unset($object->expandable_nodes);
  1100. $node->{$base_table} = $object;
  1101. $object = $node;
  1102. } else {
  1103. watchdog(
  1104. 'tripal_core',
  1105. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1106. array('%nid'=>$object->nid),
  1107. WATCHDOG_ERROR
  1108. );
  1109. } //end of if node
  1110. } else {
  1111. //We need to recurse -the node to expand is one of the nested objects
  1112. foreach ((array) $object as $field_name => $field_value) {
  1113. if (is_object($field_value)) {
  1114. $object->{$field_name} = tripal_core_expand_chado_vars(
  1115. $field_value,
  1116. 'node',
  1117. $to_expand
  1118. );
  1119. }
  1120. } //end of for each field in the current object
  1121. }
  1122. break;
  1123. default:
  1124. watchdog('tripal_core',
  1125. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1126. array('%type'=>$type),
  1127. WATCHDOG_ERROR
  1128. );
  1129. return FALSE;
  1130. }
  1131. //move extended array downwards-------------------------------------------------------------------
  1132. if (!$object->expanded) {
  1133. //if there's no extended field then go hunting for it
  1134. foreach ( (array)$object as $field_name => $field_value) {
  1135. if (is_object($field_value)) {
  1136. if (isset($field_value->expanded)) {
  1137. $object->expanded = $field_value->expanded;
  1138. unset($field_value->expanded);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. //try again becasue now we might have moved it down
  1144. if ($object->expanded) {
  1145. $expandable_name = 'expandable_'.$type.'s';
  1146. if ($object->{$expandable_name}) {
  1147. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1148. unset($object->{$expandable_name}[$key_to_remove]);
  1149. unset($object->expanded);
  1150. } else {
  1151. // if there is an expandable array then we've reached the base object
  1152. // if we get here and don't have anything expanded then something went wrong
  1153. // watchdog(
  1154. // 'tripal_core',
  1155. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1156. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1157. // WATCHDOG_ERROR
  1158. // );
  1159. } //end of it we've reached the base object
  1160. }
  1161. return $object;
  1162. }
  1163. /**
  1164. * Implements hook_exclude_type_by_default()
  1165. *
  1166. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1167. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1168. * fields are excluded by default they can always be expanded at a later date using
  1169. * tripal_core_expand_chado_vars().
  1170. *
  1171. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1172. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1173. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1174. * contain the following tokens:
  1175. * - &gt;field_name&lt;
  1176. * Replaced by the name of the field to be excluded
  1177. * - &gt;field_value&lt;
  1178. * Replaced by the value of the field in the current record
  1179. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1180. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1181. * query.
  1182. *
  1183. * @return
  1184. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1185. *
  1186. * @ingroup tripal_chado_api
  1187. */
  1188. function tripal_core_exclude_type_by_default() {
  1189. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1190. }
  1191. /**
  1192. * Implements hook_exclude_field_from_<tablename>_by_default()
  1193. *
  1194. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1195. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1196. * fields are excluded by default they can always be expanded at a later date using
  1197. * tripal_core_expand_chado_vars().
  1198. *
  1199. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1200. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1201. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1202. * contain the following tokens:
  1203. * - &gt;field_name&lt;
  1204. * Replaced by the name of the field to be excluded
  1205. * - &gt;field_value&lt;
  1206. * Replaced by the value of the field in the current record
  1207. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1208. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1209. * query.
  1210. *
  1211. * @return
  1212. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1213. *
  1214. * @ingroup tripal_chado_api
  1215. */
  1216. function tripal_core_exclude_field_from_feature_by_default() {
  1217. return array();
  1218. }
  1219. /************************************************************************
  1220. * Use this function instead of db_query() to avoid switching databases
  1221. * when making query to the chado database
  1222. */
  1223. function chado_query($sql) {
  1224. $args = func_get_args();
  1225. array_shift($args);
  1226. $sql = db_prefix_tables($sql);
  1227. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1228. $args = $args[0];
  1229. }
  1230. _db_query_callback($args, TRUE);
  1231. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1232. $previous_db = db_set_active('chado');
  1233. $results = _db_query($sql);
  1234. db_set_active($previous_db);
  1235. return $results;
  1236. }
  1237. /************************************************************************
  1238. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1239. * 'analysis' table for a synced 'chado_analysis' node, use:
  1240. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1241. * Likewise,
  1242. * $organism_id = chado_get_id_for_node ('organism', $node)
  1243. * $feature_id = chado_get_id_for_node ('feature', $node)
  1244. */
  1245. function chado_get_id_for_node ($table, $node) {
  1246. return db_result(db_query("SELECT $table"."_id FROM {chado_".$table."} WHERE nid = $node->nid"));
  1247. }
  1248. /************************************************************************
  1249. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1250. * get the node id for an analysis, use:
  1251. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1252. * Likewise,
  1253. * $nid = chado_get_node_id ('organism', $organism_id)
  1254. * $nid = chado_get_node_id ('feature', $feature_id)
  1255. */
  1256. function chado_get_node_id ($table, $id) {
  1257. return db_result(db_query("SELECT nid FROM {chado_".$table."} WHERE $table"."_id = $id"));
  1258. }
  1259. /**
  1260. * Retrieve a property for a given base table record
  1261. *
  1262. * @param $basetable
  1263. * The base table for which the property should be retrieved. Thus to retrieve a property
  1264. * for a feature the basetable=feature and property is retrieved from featureprop
  1265. * @param $record_id
  1266. * The primary key of the basetable to retrieve properties for. This should be in integer.
  1267. * @param $property
  1268. * The cvterm name describing the type of properties to be retrieved
  1269. * @param $cv_name
  1270. * The name of the cv that the above cvterm is part of
  1271. *
  1272. * @return
  1273. * A chado variable with the specified properties expanded
  1274. *
  1275. * @ingroup tripal_chado_api
  1276. */
  1277. function tripal_core_get_property($basetable, $record_id, $property, $cv_name){
  1278. // get the foreign key for this property table
  1279. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1280. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1281. // construct the array of values to be inserted
  1282. $values = array (
  1283. $fkcol => $record_id,
  1284. 'type_id' => array (
  1285. 'cv_id' => array (
  1286. 'name' => $cv_name,
  1287. ),
  1288. 'name' => $property,
  1289. 'is_obsolete' => 0
  1290. ),
  1291. );
  1292. $results = tripal_core_generate_chado_var($basetable.'prop',$values);
  1293. $results = tripal_core_expand_chado_vars($results,'field',$basetable.'prop.value');
  1294. return $results;
  1295. }
  1296. /**
  1297. * Insert a property for a given basetable record
  1298. *
  1299. * @param $basetable
  1300. * The base table for which the property should be inserted. Thus to insert a property
  1301. * for a feature the basetable=feature and property is inserted into featureprop
  1302. * @param $record_id
  1303. * The primary key of the basetable to insert a property for. This should be in integer.
  1304. * @param $property
  1305. * The cvterm name describing the type of properties to be inserted
  1306. * @param $cv_name
  1307. * The name of the cv that the above cvterm is part of
  1308. * @param $value
  1309. * The value of the property to be inserted (can be empty)
  1310. * @param $update_if_present
  1311. * A boolean indicating whether an existing record should be updated or an error thrown
  1312. *
  1313. * @return
  1314. * Return True on Insert/Update and False otherwise
  1315. *
  1316. * @ingroup tripal_chado_api
  1317. */
  1318. function tripal_core_insert_property($basetable, $record_id, $property,
  1319. $cv_name, $value, $update_if_present = 0)
  1320. {
  1321. // first see if the property already exists, if so we can't insert
  1322. $prop = tripal_core_get_property($basetable,$record_id,$property,$cv_name);
  1323. if(count($prop)>0){
  1324. if($update_if_present){
  1325. return tripal_core_update_property($basetable,$record_id,$property,$cv_name,$value) ;
  1326. } else {
  1327. return FALSE;
  1328. }
  1329. }
  1330. // get the foreign key for this property table
  1331. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1332. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1333. // construct the array of values to be inserted
  1334. $values = array (
  1335. $fkcol => $record_id,
  1336. 'type_id' => array (
  1337. 'cv_id' => array (
  1338. 'name' => $cv_name,
  1339. ),
  1340. 'name' => $property,
  1341. 'is_obsolete' => 0
  1342. ),
  1343. 'value' => $value,
  1344. 'rank' => 0,
  1345. );
  1346. return tripal_core_chado_insert($basetable.'prop',$values);
  1347. }
  1348. /**
  1349. * Update a property for a given basetable record
  1350. *
  1351. * @param $basetable
  1352. * The base table for which the property should be updated. Thus to update a property
  1353. * for a feature the basetable=feature and property is updated in featureprop
  1354. * @param $record_id
  1355. * The primary key of the basetable to update a property for. This should be in integer.
  1356. * @param $property
  1357. * The cvterm name describing the type of property to be updated
  1358. * @param $cv_name
  1359. * The name of the cv that the above cvterm is part of
  1360. * @param $value
  1361. * The value of the property to be inserted (can be empty)
  1362. * @param $insert_if_missing
  1363. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  1364. *
  1365. * Note: The property to be updated is select via theu nique combination of $record_id and
  1366. * $property and then it is updated with the supplied value
  1367. *
  1368. * @return
  1369. * Return True on Update/Insert and False otherwise
  1370. *
  1371. * @ingroup tripal_chado_api
  1372. */
  1373. function tripal_core_update_property($basetable, $record_id,$property,$cv_name,
  1374. $value,$insert_if_missing = 0)
  1375. {
  1376. // first see if the property is missing (we can't update a missing property
  1377. $prop = tripal_core_get_property($basetable,$record_id,$property,$cv_name);
  1378. if(count($prop)==0){
  1379. if($insert_if_missing){
  1380. return tripal_core_insert_property($basetable,$record_id,$property,$cv_name,$value);
  1381. } else {
  1382. return FALSE;
  1383. }
  1384. }
  1385. // get the foreign key for this property table
  1386. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1387. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1388. // construct the array that will match the exact record to update
  1389. $match = array (
  1390. $fkcol => $record_id,
  1391. 'type_id' => array (
  1392. 'cv_id' => array (
  1393. 'name' => $cv_name,
  1394. ),
  1395. 'name' => $property,
  1396. ),
  1397. );
  1398. // construct the array of values to be updated
  1399. $values = array (
  1400. 'value' => $value,
  1401. );
  1402. return tripal_core_chado_update($basetable.'prop',$match,$values);
  1403. }
  1404. /**
  1405. * Deletes a property for a given basetable record
  1406. *
  1407. * @param $basetable
  1408. * The base table for which the property should be deleted. Thus to deleted a property
  1409. * for a feature the basetable=feature and property is deleted from featureprop
  1410. * @param $record_id
  1411. * The primary key of the basetable to delete a property for. This should be in integer.
  1412. * @param $property
  1413. * The cvterm name describing the type of property to be deleted
  1414. * @param $cv_name
  1415. * The name of the cv that the above cvterm is part of
  1416. *
  1417. * Note: The property to be deleted is select via theu nique combination of $record_id and $property
  1418. *
  1419. * @return
  1420. * Return True on Delete and False otherwise
  1421. *
  1422. * @ingroup tripal_chado_api
  1423. */
  1424. function tripal_core_delete_property($basetable, $record_id,$property,$cv_name){
  1425. // get the foreign key for this property table
  1426. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1427. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1428. // construct the array that will match the exact record to update
  1429. $match = array (
  1430. $fkcol => $record_id,
  1431. 'type_id' => array (
  1432. 'cv_id' => array (
  1433. 'name' => $cv_name,
  1434. ),
  1435. 'name' => $property,
  1436. ),
  1437. );
  1438. return tripal_core_chado_delete($basetable.'prop',$match);
  1439. }