tripal_core.api.inc 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  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 (count($results) ==0) {
  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. if(count($result) > 0){
  727. foreach ($result as $obj) {
  728. $fields[] = $obj->$right;
  729. }
  730. return $fields;
  731. }
  732. }
  733. }
  734. }
  735. }
  736. else {
  737. // TODO: what do we do if we get to this point and we have a fk
  738. // relationship expected but we don't have any definition for one in the
  739. // table schema??
  740. $message = "There is no foreign key relationship defined for ".$field.".
  741. To define a foreign key relationship, determine the table this foreign
  742. key referrs to (<foreign table>) and then implement
  743. hook_chado_<foreign table>_schema(). See
  744. tripal_feature_chado_feature_schema for an example.";
  745. watchdog('tripal_core', $message);
  746. drupal_set_message($message,'error');
  747. }
  748. return false;
  749. }
  750. /**
  751. * Generates an object containing the full details of a record(s) in chado.
  752. *
  753. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  754. * relationships have been followed meaning you have more complete details. Thus this function
  755. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  756. * you only case about a few columns.
  757. *
  758. * @param $table
  759. * The name of the base table to generate a variable for
  760. * @param $values
  761. * A select values array that selects the records you want from the base table
  762. * (this has the same form as tripal_core_chado_select)
  763. * @param $base_options
  764. * An array containing options for the base table. For example, an
  765. * option of 'order_by' may be used to sort results in the base table
  766. * if more than one are returned. The options must be compatible with
  767. * the options accepted by the tripal_core_chado_select() function.
  768. * @return
  769. * Either an object (if only one record was selected from the base table)
  770. * or an array of objects (if more than one record was selected from the base table).
  771. *
  772. * Example Usage:
  773. * @code
  774. $values = array(
  775. 'name' => 'Medtr4g030710'
  776. );
  777. $features = tripal_core_generate_chado_var('feature', $values);
  778. * @endcode
  779. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  780. * return an array of feature objects if more than one feature has that name.
  781. *
  782. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  783. * one of the following hooks:
  784. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  785. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  786. * this hook to return an array of fields to be excluded. For example:
  787. * @code
  788. mymodule_exclude_field_from_feature_by_default() {
  789. return array('residues' => TRUE);
  790. }
  791. * @endcode
  792. * will ensure that feature.residues is ecluded from a feature object by default.
  793. * - hook_exclude_type_by_default:
  794. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  795. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  796. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  797. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  798. * @code
  799. mymodule_exclude_type_by_default() {
  800. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  801. }
  802. * @endcode
  803. * 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.
  804. *
  805. * @ingroup tripal_chado_api
  806. */
  807. function tripal_core_generate_chado_var($table, $values, $base_options=array()) {
  808. $all = new stdClass();
  809. // get description for the current table----------------------------------------------------------
  810. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  811. $table_primary_key = $table_desc['primary key'][0];
  812. $table_columns = array_keys($table_desc['fields']);
  813. // Expandable fields without value needed for criteria--------------------------------------------
  814. $all->expandable_fields = array();
  815. if ($table_desc['referring_tables']) {
  816. $all->expandable_tables = $table_desc['referring_tables'];
  817. } else {
  818. $all->expandable_tables = array();
  819. }
  820. $all->expandable_nodes = array();
  821. // Get fields to be removed by name.................................
  822. $fields_to_remove = module_invoke_all('exclude_field_from_'.$table.'_by_default');
  823. foreach ($fields_to_remove as $field_name => $criteria) {
  824. //replace &gt;field_name&lt; with the current field name &
  825. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  826. // if field_value needed we can't deal with this field yet
  827. if (preg_match('/&gt;field_value&lt; /', $criteria)) { break; }
  828. //if criteria then remove from query
  829. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  830. // watchdog('tripal_core',
  831. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  832. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  833. // WATCHDOG_NOTICE
  834. // );
  835. if ($success) {
  836. unset($table_columns[array_search($field_name, $table_columns)]);
  837. unset($fields_to_remove[$field_name]);
  838. $all->expandable_fields[] = $table . '.' . $field_name;
  839. }
  840. }
  841. //Get fields to be removed by type................................
  842. $types_to_remove = module_invoke_all('exclude_type_by_default');
  843. $field_types = array();
  844. foreach ($table_desc['fields'] as $field_name => $field_array) {
  845. $field_types[$field_array['type']][] = $field_name;
  846. }
  847. foreach ($types_to_remove as $field_type => $criteria) {
  848. // if there are fields of that type to remove
  849. if (is_array($field_types[$field_type])) {
  850. //replace &gt;field_name&lt; with the current field name &
  851. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  852. foreach ($field_types[$field_type] as $field_name) {
  853. // if field_value needed we can't deal with this field yet
  854. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  855. $fields_to_remove[$field_name] = $criteria;
  856. continue;
  857. }
  858. // if field_value needed we can't deal with this field yet
  859. if (preg_match('/&gt;field_value&lt; /', $criteria)) { break; }
  860. //if criteria then remove from query
  861. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  862. // watchdog('tripal_core',
  863. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  864. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  865. // WATCHDOG_NOTICE
  866. // );
  867. if ($success) {
  868. unset($table_columns[array_search($field_name, $table_columns)]);
  869. $all->expandable_fields[] = $table . '.' . $field_name;
  870. }
  871. } //end of foreach field of that type
  872. }
  873. } //end of foreach type to be removed
  874. // get the values for the record in the current table---------------------------------------------
  875. $results = tripal_core_chado_select($table, $table_columns, $values,$base_options);
  876. if($results){
  877. foreach ($results as $key => $object) {
  878. // Add empty expandable_x arrays
  879. $object->expandable_fields = $all->expandable_fields;
  880. $object->expandable_tables = $all->expandable_tables;
  881. $object->expandable_nodes = $all->expandable_nodes;
  882. // add curent table
  883. $object->tablename = $table;
  884. // check if the current table maps to a node type-----------------------------------------------
  885. // if this table is connected to a node there will be a chado_tablename table in drupal
  886. if (db_table_exists('chado_'.$table)) {
  887. // that has a foreign key to this one ($table_desc['primary key'][0]
  888. // and to the node table (nid)
  889. $sql = "SELECT %s, nid FROM chado_%s WHERE %s=%d";
  890. $mapping = db_fetch_object(db_query(
  891. $sql,
  892. $table_primary_key,
  893. $table,
  894. $table_primary_key,
  895. $object->{$table_primary_key}
  896. ));
  897. if ($mapping->{$table_primary_key}) {
  898. $object->nid = $mapping->nid;
  899. $object->expandable_nodes[] = $table;
  900. }
  901. }
  902. // remove any fields where criteria need to be evalulated---------------------------------------
  903. foreach ($fields_to_remove as $field_name => $criteria) {
  904. if (!isset($object->{$field_name})) { break; }
  905. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  906. //if criteria then remove from query
  907. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  908. // watchdog('tripal_core',
  909. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  910. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  911. // WATCHDOG_NOTICE
  912. // );
  913. if ($success) {
  914. unset($object->{$field_name});
  915. $object->expandable_fields[] = $table . '.' . $field_name;
  916. }
  917. }
  918. // recursively follow foreign key relationships nesting objects as we go------------------------
  919. if ($table_desc['foreign keys']) {
  920. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  921. $foreign_table = $foreign_key_array['table'];
  922. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  923. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  924. // the table referenced by the foreign key
  925. //Dont do anything if the foreign key is empty
  926. if (empty($object->{$foreign_key})) {
  927. break;
  928. }
  929. // get the record from the foreign table
  930. $foreign_values = array($primary_key => $object->{$foreign_key});
  931. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  932. // add the foreign record to the current object in a nested manner
  933. $object->{$foreign_key} = $foreign_object;
  934. // Flatten expandable_x arrays so only in the bottom object
  935. if (is_array($object->{$foreign_key}->expandable_fields)) {
  936. $object->expandable_fields = array_merge(
  937. $object->expandable_fields,
  938. $object->{$foreign_key}->expandable_fields
  939. );
  940. unset($object->{$foreign_key}->expandable_fields);
  941. }
  942. if (is_array($object->{$foreign_key}->expandable_tables)) {
  943. $object->expandable_tables = array_merge(
  944. $object->expandable_tables,
  945. $object->{$foreign_key}->expandable_tables
  946. );
  947. unset($object->{$foreign_key}->expandable_tables);
  948. }
  949. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  950. $object->expandable_nodes = array_merge(
  951. $object->expandable_nodes,
  952. $object->{$foreign_key}->expandable_nodes
  953. );
  954. unset($object->{$foreign_key}->expandable_nodes);
  955. }
  956. }
  957. }
  958. $results[$key] = $object;
  959. }
  960. }
  961. }
  962. // check only one result returned
  963. if (sizeof($results) == 1) {
  964. // add results to object
  965. return $results[0];
  966. } elseif (!empty($results)) {
  967. return $results;
  968. } else {
  969. // no results returned
  970. }
  971. }
  972. /**
  973. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  974. *
  975. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  976. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  977. * the tripal admin to get at these variables if he/she wants them.
  978. *
  979. * @param $object
  980. * This must be an object generated using tripal_core_generate_chado_var()
  981. * @param $type
  982. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  983. * @param $to_expand
  984. * The name of the field/table/node to be expanded
  985. * @param $table_options
  986. * An array containing options for the base table. For example, an
  987. * option of 'order_by' may be used to sort results in the base table
  988. * if more than one are returned. The options must be compatible with
  989. * the options accepted by the tripal_core_chado_select() function.
  990. * @return
  991. * A chado object supplemented with the field/table/node requested to be expanded
  992. *
  993. * Example Usage:
  994. * @code
  995. // Get a chado object to be expanded
  996. $values = array(
  997. 'name' => 'Medtr4g030710'
  998. );
  999. $features = tripal_core_generate_chado_var('feature', $values);
  1000. // Expand the organism node
  1001. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1002. // Expand the feature.residues field
  1003. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1004. // Expand the feature properties (featureprop table)
  1005. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1006. * @endcode
  1007. *
  1008. * @ingroup tripal_chado_api
  1009. */
  1010. function tripal_core_expand_chado_vars ($object, $type, $to_expand,$table_options = array()) {
  1011. $base_table = $object->tablename;
  1012. // check to see if they are expanding an array of objects
  1013. if (is_array($object)) {
  1014. foreach ($object as $index => $o) {
  1015. $object[$index] = tripal_core_expand_chado_vars($o,$type,$to_expand);
  1016. }
  1017. return $object;
  1018. }
  1019. switch ($type) {
  1020. case "field": //--------------------------------------------------------------------------------
  1021. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1022. $tablename = $matches[1];
  1023. $fieldname = $matches[2];
  1024. $table_desc = module_invoke_all('chado_'.$tablename.'_schema');
  1025. $values = array();
  1026. foreach($table_desc['primary key'] as $key) {
  1027. $values[$key] = $object->{$key};
  1028. }
  1029. if ($base_table == $tablename) {
  1030. //get the field
  1031. $results = tripal_core_chado_select(
  1032. $tablename,
  1033. array($fieldname),
  1034. $values
  1035. );
  1036. $object->{$fieldname} = $results[0]->{$fieldname};
  1037. $object->expanded = $to_expand;
  1038. } else {
  1039. //We need to recurse -the field is in a nested object
  1040. foreach ((array) $object as $field_name => $field_value) {
  1041. if (is_object($field_value)) {
  1042. $object->{$field_name} = tripal_core_expand_chado_vars(
  1043. $field_value,
  1044. 'field',
  1045. $to_expand
  1046. );
  1047. }
  1048. } //end of for each field in the current object
  1049. }
  1050. } else {
  1051. watchdog(
  1052. 'tripal_core',
  1053. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  1054. WATCHDOG_ERROR
  1055. );
  1056. }
  1057. break;
  1058. case "table": //--------------------------------------------------------------------------------
  1059. $foreign_table = $to_expand;
  1060. $foreign_table_desc = module_invoke_all('chado_'.$foreign_table.'_schema');
  1061. // If it's connected to the base table
  1062. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1063. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1064. if (!$object->{$right}) { break; }
  1065. if (is_array($values)) {
  1066. $values = array_merge($values, array($left => $object->{$right}) );
  1067. } else {
  1068. $values = array($left => $object->{$right});
  1069. }
  1070. $foreign_object = tripal_core_generate_chado_var(
  1071. $foreign_table,
  1072. array($left => $object->{$right}),
  1073. $table_options
  1074. );
  1075. if ($foreign_object) {
  1076. // in the case where the a foreign key relationships exists more
  1077. // than once with the same table we want to alter the
  1078. // array structure
  1079. if(count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1){
  1080. $object->{$foreign_table}->{$left} = $foreign_object;
  1081. $object->expanded = $to_expand;
  1082. } else {
  1083. $object->{$foreign_table} = $foreign_object;
  1084. $object->expanded = $to_expand;
  1085. }
  1086. }
  1087. }
  1088. } else {
  1089. //We need to recurse -the table has a relationship to one of the nested objects
  1090. foreach ((array) $object as $field_name => $field_value) {
  1091. // if we have a nested object ->expand the table in it
  1092. if (is_object($field_value)) {
  1093. $object->{$field_name} = tripal_core_expand_chado_vars(
  1094. $field_value,
  1095. 'table',
  1096. $foreign_table
  1097. );
  1098. }
  1099. }
  1100. }
  1101. break;
  1102. case "node": //---------------------------------------------------------------------------------
  1103. //if the node to be expanded is for our base table, then just expand it
  1104. if ($object->tablename == $to_expand) {
  1105. $node = node_load($object->nid);
  1106. if ($node) {
  1107. $object->expanded = $to_expand;
  1108. $node->expandable_fields = $object->expandable_fields;
  1109. unset($object->expandable_fields);
  1110. $node->expandable_tables = $object->expandable_tables;
  1111. unset($object->expandable_tables);
  1112. $node->expandable_nodes = $object->expandable_nodes;
  1113. unset($object->expandable_nodes);
  1114. $node->{$base_table} = $object;
  1115. $object = $node;
  1116. } else {
  1117. watchdog(
  1118. 'tripal_core',
  1119. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1120. array('%nid'=>$object->nid),
  1121. WATCHDOG_ERROR
  1122. );
  1123. } //end of if node
  1124. } else {
  1125. //We need to recurse -the node to expand is one of the nested objects
  1126. foreach ((array) $object as $field_name => $field_value) {
  1127. if (is_object($field_value)) {
  1128. $object->{$field_name} = tripal_core_expand_chado_vars(
  1129. $field_value,
  1130. 'node',
  1131. $to_expand
  1132. );
  1133. }
  1134. } //end of for each field in the current object
  1135. }
  1136. break;
  1137. default:
  1138. watchdog('tripal_core',
  1139. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1140. array('%type'=>$type),
  1141. WATCHDOG_ERROR
  1142. );
  1143. return FALSE;
  1144. }
  1145. //move extended array downwards-------------------------------------------------------------------
  1146. if (!$object->expanded) {
  1147. //if there's no extended field then go hunting for it
  1148. foreach ( (array)$object as $field_name => $field_value) {
  1149. if (is_object($field_value)) {
  1150. if (isset($field_value->expanded)) {
  1151. $object->expanded = $field_value->expanded;
  1152. unset($field_value->expanded);
  1153. }
  1154. }
  1155. }
  1156. }
  1157. //try again becasue now we might have moved it down
  1158. if ($object->expanded) {
  1159. $expandable_name = 'expandable_'.$type.'s';
  1160. if ($object->{$expandable_name}) {
  1161. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1162. unset($object->{$expandable_name}[$key_to_remove]);
  1163. unset($object->expanded);
  1164. } else {
  1165. // if there is an expandable array then we've reached the base object
  1166. // if we get here and don't have anything expanded then something went wrong
  1167. // watchdog(
  1168. // 'tripal_core',
  1169. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1170. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1171. // WATCHDOG_ERROR
  1172. // );
  1173. } //end of it we've reached the base object
  1174. }
  1175. return $object;
  1176. }
  1177. /**
  1178. * Implements hook_exclude_type_by_default()
  1179. *
  1180. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1181. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1182. * fields are excluded by default they can always be expanded at a later date using
  1183. * tripal_core_expand_chado_vars().
  1184. *
  1185. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1186. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1187. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1188. * contain the following tokens:
  1189. * - &gt;field_name&lt;
  1190. * Replaced by the name of the field to be excluded
  1191. * - &gt;field_value&lt;
  1192. * Replaced by the value of the field in the current record
  1193. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1194. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1195. * query.
  1196. *
  1197. * @return
  1198. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1199. *
  1200. * @ingroup tripal_chado_api
  1201. */
  1202. function tripal_core_exclude_type_by_default() {
  1203. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1204. }
  1205. /**
  1206. * Implements hook_exclude_field_from_<tablename>_by_default()
  1207. *
  1208. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1209. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1210. * fields are excluded by default they can always be expanded at a later date using
  1211. * tripal_core_expand_chado_vars().
  1212. *
  1213. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1214. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1215. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1216. * contain the following tokens:
  1217. * - &gt;field_name&lt;
  1218. * Replaced by the name of the field to be excluded
  1219. * - &gt;field_value&lt;
  1220. * Replaced by the value of the field in the current record
  1221. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1222. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1223. * query.
  1224. *
  1225. * @return
  1226. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1227. *
  1228. * @ingroup tripal_chado_api
  1229. */
  1230. function tripal_core_exclude_field_from_feature_by_default() {
  1231. return array();
  1232. }
  1233. /**
  1234. * Use this function instead of db_query() to avoid switching databases
  1235. * when making query to the chado database
  1236. */
  1237. function chado_query($sql) {
  1238. $args = func_get_args();
  1239. array_shift($args);
  1240. $sql = db_prefix_tables($sql);
  1241. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1242. $args = $args[0];
  1243. }
  1244. _db_query_callback($args, TRUE);
  1245. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1246. $previous_db = tripal_db_set_active('chado');
  1247. $results = _db_query($sql);
  1248. tripal_db_set_active($previous_db);
  1249. return $results;
  1250. }
  1251. /**
  1252. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1253. * 'analysis' table for a synced 'chado_analysis' node, use:
  1254. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1255. * Likewise,
  1256. * $organism_id = chado_get_id_for_node ('organism', $node)
  1257. * $feature_id = chado_get_id_for_node ('feature', $node)
  1258. */
  1259. function chado_get_id_for_node ($table, $node) {
  1260. return db_result(db_query("SELECT $table"."_id FROM {chado_".$table."} WHERE nid = $node->nid"));
  1261. }
  1262. /**
  1263. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1264. * get the node id for an analysis, use:
  1265. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1266. * Likewise,
  1267. * $nid = chado_get_node_id ('organism', $organism_id)
  1268. * $nid = chado_get_node_id ('feature', $feature_id)
  1269. */
  1270. function chado_get_node_id ($table, $id) {
  1271. return db_result(db_query("SELECT nid FROM {chado_".$table."} WHERE $table"."_id = $id"));
  1272. }
  1273. /**
  1274. * Retrieve a property for a given base table record
  1275. *
  1276. * @param $basetable
  1277. * The base table for which the property should be retrieved. Thus to retrieve a property
  1278. * for a feature the basetable=feature and property is retrieved from featureprop
  1279. * @param $record_id
  1280. * The foriegn key field of the base table. This should be in integer.
  1281. * @param $property
  1282. * The cvterm name describing the type of properties to be retrieved
  1283. * @param $cv_name
  1284. * The name of the cv that the above cvterm is part of
  1285. *
  1286. * @return
  1287. * An array in the same format as that generated by the function
  1288. * tripal_core_generate_chado_var(). If only one record is returned it
  1289. * is a single object. If more than one record is returned then it is an array
  1290. * of objects
  1291. *
  1292. * @ingroup tripal_chado_api
  1293. */
  1294. function tripal_core_get_property($basetable, $record_id, $property, $cv_name){
  1295. // get the foreign key for this property table
  1296. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1297. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1298. // construct the array of values to be selected
  1299. $values = array (
  1300. $fkcol => $record_id,
  1301. 'type_id' => array (
  1302. 'cv_id' => array (
  1303. 'name' => $cv_name,
  1304. ),
  1305. 'name' => $property,
  1306. 'is_obsolete' => 0
  1307. ),
  1308. );
  1309. $results = tripal_core_generate_chado_var($basetable.'prop',$values);
  1310. $results = tripal_core_expand_chado_vars($results,'field',$basetable.'prop.value');
  1311. return $results;
  1312. }
  1313. /**
  1314. * Insert a property for a given base table. By default if the property already
  1315. * exists a new property is added with the next available rank. If
  1316. * $update_if_present argument is specified then the record will be updated if it
  1317. * exists rather than adding a new property.
  1318. *
  1319. * @param $basetable
  1320. * The base table for which the property should be inserted. Thus to insert a property
  1321. * for a feature the basetable=feature and property is inserted into featureprop
  1322. * @param $record_id
  1323. * The foriegn key field of the base table. This should be in integer.
  1324. * @param $property
  1325. * The cvterm name describing the type of properties to be inserted
  1326. * @param $cv_name
  1327. * The name of the cv that the above cvterm is part of
  1328. * @param $value
  1329. * The value of the property to be inserted (can be empty)
  1330. * @param $update_if_present
  1331. * A boolean indicating whether an existing record should be updated. If the
  1332. * property already exists and this value is not specified or is zero then
  1333. * a new property will be added with the next largest rank.
  1334. *
  1335. * @return
  1336. * Return True on Insert/Update and False otherwise
  1337. *
  1338. * @ingroup tripal_chado_api
  1339. */
  1340. function tripal_core_insert_property($basetable, $record_id, $property,
  1341. $cv_name, $value, $update_if_present = 0)
  1342. {
  1343. // first see if the property already exists, if the user want's to update
  1344. // then we can do that, but otherwise we want to increment the rank and
  1345. // insert
  1346. $props = tripal_core_get_property($basetable,$record_id,$property,$cv_name);
  1347. if(!is_array($props)) {
  1348. $props = array($props);
  1349. }
  1350. $rank = 0;
  1351. if(count($props)>0){
  1352. if($update_if_present){
  1353. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value) ;
  1354. } else {
  1355. // iterate through the properties returned and check to see if the
  1356. // property with this value already exists if not, get the largest rank
  1357. // and insert the same property but with this new value
  1358. foreach($props as $p){
  1359. if($p->rank > $rank){
  1360. $rank = $p->rank;
  1361. }
  1362. if(strcmp($p->value,$value)==0){
  1363. return TRUE;
  1364. }
  1365. }
  1366. // now add 1 to the rank
  1367. $rank++;
  1368. }
  1369. }
  1370. // get the foreign key for this property table
  1371. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1372. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1373. // construct the array of values to be inserted
  1374. $values = array (
  1375. $fkcol => $record_id,
  1376. 'type_id' => array (
  1377. 'cv_id' => array (
  1378. 'name' => $cv_name,
  1379. ),
  1380. 'name' => $property,
  1381. 'is_obsolete' => 0
  1382. ),
  1383. 'value' => $value,
  1384. 'rank' => $rank,
  1385. );
  1386. return tripal_core_chado_insert($basetable.'prop',$values);
  1387. }
  1388. /**
  1389. * Update a property for a given base table record and property name. This
  1390. * function should be used only if one record of the property will be present.
  1391. * If the property name can have multiple entries (with increasing rank) then
  1392. * use the function named tripal_core_update_property_by_id
  1393. *
  1394. * @param $basetable
  1395. * The base table for which the property should be updated. The property table
  1396. * is constructed using a combination of the base table name and the suffix
  1397. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1398. * @param $record_id
  1399. * The foreign key of the basetable to update a property for. This should be in integer.
  1400. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  1401. * @param $property
  1402. * The cvterm name of property to be updated
  1403. * @param $cv_name
  1404. * The name of the cv that the above cvterm is part of
  1405. * @param $value
  1406. * The value of the property to be inserted (can be empty)
  1407. * @param $insert_if_missing
  1408. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  1409. *
  1410. * Note: The property to be updated is select via the unique combination of $record_id and
  1411. * $property and then it is updated with the supplied value
  1412. *
  1413. * @return
  1414. * Return True on Update/Insert and False otherwise
  1415. *
  1416. * @ingroup tripal_chado_api
  1417. */
  1418. function tripal_core_update_property($basetable, $record_id, $property,
  1419. $cv_name, $value, $insert_if_missing = 0)
  1420. {
  1421. // first see if the property is missing (we can't update a missing property
  1422. $prop = tripal_core_get_property($basetable,$record_id,$property,$cv_name);
  1423. if(count($prop)==0){
  1424. if($insert_if_missing){
  1425. return tripal_core_insert_property($basetable,$record_id,$property,$cv_name,$value);
  1426. } else {
  1427. return FALSE;
  1428. }
  1429. }
  1430. // get the foreign key for this property table
  1431. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1432. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1433. // construct the array that will match the exact record to update
  1434. $match = array (
  1435. $fkcol => $record_id,
  1436. 'type_id' => array (
  1437. 'cv_id' => array (
  1438. 'name' => $cv_name,
  1439. ),
  1440. 'name' => $property,
  1441. ),
  1442. );
  1443. // construct the array of values to be updated
  1444. $values = array (
  1445. 'value' => $value,
  1446. );
  1447. return tripal_core_chado_update($basetable.'prop',$match,$values);
  1448. }
  1449. /**
  1450. * Update a property for a given base table record. This function should be
  1451. * used if multiple records of the same property will be present. Also, use this
  1452. * function to change the property name of an existing property.
  1453. *
  1454. * @param $basetable
  1455. * The base table for which the property should be updated. The property table
  1456. * is constructed using a combination of the base table name and the suffix
  1457. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1458. * @param $record_id
  1459. * The primary key of the base table. This should be in integer.
  1460. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  1461. * @param $property
  1462. * The cvterm name of property to be updated
  1463. * @param $cv_name
  1464. * The name of the cv that the above cvterm is part of
  1465. * @param $value
  1466. * The value of the property to be inserted (can be empty)
  1467. *
  1468. * @return
  1469. * Return True on Update/Insert and False otherwise
  1470. *
  1471. * @ingroup tripal_chado_api
  1472. */
  1473. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  1474. $cv_name, $value)
  1475. {
  1476. // get the primary key for this property table
  1477. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1478. $pkcol = $table_desc['primary key'][0];
  1479. // construct the array that will match the exact record to update
  1480. $match = array (
  1481. $pkcol => $record_id,
  1482. );
  1483. // construct the array of values to be updated
  1484. $values = array (
  1485. 'type_id' => array (
  1486. 'cv_id' => array (
  1487. 'name' => $cv_name,
  1488. ),
  1489. 'name' => $property,
  1490. ),
  1491. 'value' => $value,
  1492. );
  1493. return tripal_core_chado_update($basetable.'prop',$match,$values);
  1494. }
  1495. /**
  1496. * Deletes a property for a given base table record using the property name
  1497. *
  1498. * @param $basetable
  1499. * The base table for which the property should be deleted. Thus to deleted a property
  1500. * for a feature the basetable=feature and property is deleted from featureprop
  1501. * @param $record_id
  1502. * The primary key of the basetable to delete a property for. This should be in integer.
  1503. * @param $property
  1504. * The cvterm name describing the type of property to be deleted
  1505. * @param $cv_name
  1506. * The name of the cv that the above cvterm is part of
  1507. *
  1508. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  1509. *
  1510. * @return
  1511. * Return True on Delete and False otherwise
  1512. *
  1513. * @ingroup tripal_chado_api
  1514. */
  1515. function tripal_core_delete_property($basetable, $record_id,$property,$cv_name){
  1516. // get the foreign key for this property table
  1517. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1518. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1519. // construct the array that will match the exact record to update
  1520. $match = array (
  1521. $fkcol => $record_id,
  1522. 'type_id' => array (
  1523. 'cv_id' => array (
  1524. 'name' => $cv_name,
  1525. ),
  1526. 'name' => $property,
  1527. ),
  1528. );
  1529. return tripal_core_chado_delete($basetable.'prop',$match);
  1530. }
  1531. /**
  1532. * Deletes a property using the property ID
  1533. *
  1534. * @param $basetable
  1535. * The base table for which the property should be deleted. Thus to deleted a property
  1536. * for a feature the basetable=feature and property is deleted from featureprop
  1537. * @param $record_id
  1538. * The primary key of the basetable to delete a property for. This should be in integer.
  1539. *
  1540. * @return
  1541. * Return True on Delete and False otherwise
  1542. *
  1543. * @ingroup tripal_chado_api
  1544. */
  1545. function tripal_core_delete_property_by_id($basetable, $record_id){
  1546. // get the foreign key for this property table
  1547. $table_desc = module_invoke_all('chado_'.$basetable.'prop_schema');
  1548. $pkcol = $table_desc['primary key'][0];
  1549. // construct the array that will match the exact record to update
  1550. $match = array (
  1551. $pkcol => $record_id,
  1552. );
  1553. return tripal_core_chado_delete($basetable.'prop',$match);
  1554. }
  1555. /**
  1556. * This function is typically used in the '.install' file for a Tripal module
  1557. * Each module should call this function during installation to create
  1558. * the module data directory which is sites/default/files/tripal/[module_name]
  1559. * for default Drupal settings. This directory can then be used by the module
  1560. * for storing files.
  1561. *
  1562. * @param $module_name
  1563. * the name of the module being installed.
  1564. *
  1565. * @returns
  1566. * nothing
  1567. *
  1568. * @ingroup tripal_files_api
  1569. */
  1570. function tripal_create_moddir($module_name){
  1571. // make the data directory for this module
  1572. $data_dir = file_directory_path() . "/tripal/$module_name";
  1573. if(!file_check_directory($data_dir,FILE_CREATE_DIRECTORY|FILE_MODIFY_PERMISSIONS)){
  1574. $message = "Cannot create directory $data_dir. This module may not ".
  1575. "behave correctly without this directory. Please create ".
  1576. "the directory manually or fix the problem and reinstall.";
  1577. drupal_set_message($message,'error');
  1578. watchdog('tripal_core',$message,array(),WATCHDOG_ERROR);
  1579. }
  1580. }
  1581. /**
  1582. * Each Tripal module has a unique data directory which was creatd using the
  1583. * tripal_create_moddir function during installation. This function
  1584. * retrieves the directory path.
  1585. *
  1586. * @param $module_name
  1587. * The name of the module
  1588. *
  1589. * @returns
  1590. * The path within the Drupal installation where the data directory resides
  1591. * @ingroup tripal_files_api
  1592. */
  1593. function tripal_get_moddir($module_name){
  1594. $data_dir = file_directory_path() . "/tripal/$module_name";
  1595. return $data_dir;
  1596. }
  1597. /**
  1598. * Set the Tripal Database
  1599. *
  1600. * The tripal_db_set_active function is used to prevent namespace collisions
  1601. * when chado and drupal are installed in the same database but in different
  1602. * schemas. It is also used for backwards compatibility with older versions
  1603. * of tripal or in cases where chado is located outside of the Drupal database.
  1604. *
  1605. * @ingroup tripal_chado_api
  1606. */
  1607. function tripal_db_set_active($dbname){
  1608. global $db_url, $db_type;
  1609. $chado_exists = 0;
  1610. // only postgres can support search paths. So if this is MysQL then
  1611. // just run the normal tripal_db_set_active function.
  1612. if(strcmp($db_type,'pgsql')==0){
  1613. // if the 'chado' database is in the $db_url variable then chado is
  1614. // not in the same Drupal database
  1615. if(is_array($db_url)){
  1616. if(isset($db_url[$dbname])){
  1617. return db_set_active($dbname);
  1618. }
  1619. }
  1620. // check to make sure the chado schema exists
  1621. $sql = "select nspname from pg_catalog.pg_namespace where nspname = 'chado'";
  1622. if(db_fetch_object(db_query($sql))){
  1623. $chado_exists = 1;
  1624. }
  1625. // here we make the assumption that the default database schema is
  1626. // 'public'. This will most likely always be the case but if not,
  1627. // then this code will break
  1628. if($chado_exists && strcmp($dbname,'chado')==0){
  1629. db_query("set search_path to %s",'chado,public');
  1630. return 'public,chado';
  1631. }
  1632. elseif($chado_exists) {
  1633. db_query("set search_path to %s",'public,chado');
  1634. return 'chado,public';
  1635. }
  1636. else {
  1637. return db_set_active($dbname);
  1638. }
  1639. }
  1640. else return db_set_active($dbname);
  1641. }
  1642. /**
  1643. * Purpose: Get max rank for a given set of criteria
  1644. * This function was developed with the many property tables in chado in mind
  1645. *
  1646. * @param $tablename
  1647. * The name of the chado table you want to select the max rank from this table must contain a
  1648. * rank column of type integer
  1649. * @param $where_options
  1650. * where options should include the id and type for that table to correctly
  1651. * group a set of records together where the only difference are the value and rank
  1652. * @code
  1653. * array(
  1654. * <column_name> => array(
  1655. * 'type' => <type of column: INT/STRING>,
  1656. * 'value' => <the value you want to filter on>,
  1657. * 'exact' => <if TRUE use =; if FALSE use ~>,
  1658. * )
  1659. * )
  1660. * @endcode
  1661. * @return the maximum rank
  1662. *
  1663. * @ingroup tripal_chado_api
  1664. */
  1665. function tripal_get_max_chado_rank ($tablename, $where_options) {
  1666. $where= array();
  1667. //generate the where clause from supplied options
  1668. // the key is the column name
  1669. foreach ($where_options as $key => $val_array) {
  1670. if (preg_match('/INT/', $val_array['type'])) {
  1671. $where[] = $key."=".$val_array['value'];
  1672. } else {
  1673. if ($val_array['exact']) { $operator='='; }
  1674. else { $operator='~'; }
  1675. $where[] = $key.$operator."'".$val_array['value']."'";
  1676. }
  1677. }
  1678. $previous_db = tripal_db_set_active('chado');
  1679. $result = db_fetch_object(db_query(
  1680. "SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
  1681. $tablename,
  1682. implode(' AND ',$where)
  1683. ));
  1684. tripal_db_set_active($previous_db);
  1685. //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
  1686. if ($result->count > 0) {
  1687. return $result->max_rank;
  1688. } else {
  1689. return -1;
  1690. }
  1691. }
  1692. /**
  1693. * Add a new table to the Chado schema. This function is simply a wrapper for
  1694. * the db_create_table() function of Drupal, but ensures the table is created
  1695. * inside the Chado schema rather than the Drupal schema.
  1696. *
  1697. * @param $ret
  1698. * Array to which query results will be added.
  1699. * @param $table
  1700. * The name of the table to create.
  1701. * @param $schema
  1702. * A Drupal-style Schema API definition of the table
  1703. *
  1704. * @return
  1705. * A database query result resource for the new table, or FALSE if table was not constructed.
  1706. *
  1707. * @ingroup tripal_core_api
  1708. */
  1709. function tripal_create_chado_table (&$ret,$table,$schema) {
  1710. $ret = array();
  1711. $previous_db = tripal_db_set_active('chado'); // use chado database
  1712. db_create_table($ret,$table,$schema);
  1713. tripal_db_set_active($previous_db); // now use drupal database
  1714. // if the table creation was succesful then add an entry
  1715. // in the tripal_custom_table
  1716. if($ret){
  1717. $record = new stdClass();
  1718. $record->table_name = $table;
  1719. $record->schema = serialize($schema);
  1720. $success = drupal_write_record('tripal_custom_tables',$record);
  1721. if(!$success){
  1722. drupal_set_message($message,"Error adding custom table: $table");
  1723. }
  1724. }
  1725. return $ret;
  1726. }