tripal_core.api.inc 65 KB

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