tripal_core.api.inc 64 KB

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