tripal_core.api.inc 72 KB

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