tripal_core.api.inc 69 KB

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