tripal_core.api.inc 65 KB

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