tripal_core.api.inc 59 KB

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