tripal_core.api.inc 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  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. If the table already
  1696. * exists then it will be dropped and recreated using the schema provided.
  1697. * Howver, it will only drop a table if it exsits in the tripal_custom_tables
  1698. * table. This way the function cannot be used to accidentally alter existing
  1699. * non custom tables.
  1700. *
  1701. * @param $ret
  1702. * Array to which query results will be added.
  1703. * @param $table
  1704. * The name of the table to create.
  1705. * @param $schema
  1706. * A Drupal-style Schema API definition of the table
  1707. *
  1708. * @return
  1709. * A database query result resource for the new table, or FALSE if table was not constructed.
  1710. *
  1711. * @ingroup tripal_core_api
  1712. */
  1713. function tripal_create_chado_table (&$ret,$table,$schema) {
  1714. $ret = array();
  1715. // If the table exits in Chado but not in the tripal_custom_tables field
  1716. // then call an error. if the table exits in the tripal_custom_tables but
  1717. // not in Chado then create the table and replace the entry.
  1718. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1719. $centry = db_fetch_object(db_query($sql,$table));
  1720. $previous_db = tripal_db_set_active('chado'); // use chado database
  1721. $exists = db_table_exists($table);
  1722. tripal_db_set_active($previous_db); // now use drupal database
  1723. if(!$exists){
  1724. $previous_db = tripal_db_set_active('chado'); // use chado database
  1725. db_create_table($ret,$table,$schema);
  1726. tripal_db_set_active($previous_db); // now use drupal database
  1727. if(count($ret)==0){
  1728. watchdog('tripal_core', "Error adding custom table '!table_name'.",
  1729. array('!table_name' => $table), WATCHDOG_ERROR);
  1730. return FALSE;
  1731. }
  1732. }
  1733. if($exists and !$centry){
  1734. watchdog('tripal_core', "Could not add custom table '!table_name'. It ".
  1735. "already exists but is not known to Tripal as being a custom table.",
  1736. array('!table_name' => $table), WATCHDOG_WARNING);
  1737. return FALSE;
  1738. }
  1739. if($exists and $centry){
  1740. // drop the table we'll recreate it with the new schema
  1741. $previous_db = tripal_db_set_active('chado'); // use chado database
  1742. db_drop_table($ret,$table);
  1743. db_create_table($ret,$table,$schema);
  1744. tripal_db_set_active($previous_db); // now use drupal database
  1745. }
  1746. // if the table creation was succesful then add an entry
  1747. // in the tripal_custom_table
  1748. $record = new stdClass();
  1749. $record->table_name = $table;
  1750. $record->schema = serialize($schema);
  1751. // if an entry already exists then remove it
  1752. if($centry){
  1753. $sql = "DELETE FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1754. db_query($sql,$table);
  1755. }
  1756. $success = drupal_write_record('tripal_custom_tables',$record);
  1757. if(!$success){
  1758. watchdog('tripal_core', "Error adding custom table.",
  1759. array('!table_name' => $table), WATCHDOG_ERROR);
  1760. return FALSE;
  1761. }
  1762. return $ret;
  1763. }
  1764. /**
  1765. * Retrieves the schema in an array for the specified custom table.
  1766. *
  1767. * @param $table
  1768. * The name of the table to create.
  1769. *
  1770. * @return
  1771. * A Drupal-style Schema API array definition of the table. Returns
  1772. * FALSE on failure.
  1773. *
  1774. * @ingroup tripal_core_api
  1775. */
  1776. function tripal_get_chado_custom_schema ($table) {
  1777. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1778. $custom = db_fetch_object(db_query($sql,$table));
  1779. if(!$custom){
  1780. return FALSE;
  1781. }
  1782. else {
  1783. return unserialize($custom->schema);
  1784. }
  1785. }